github.com/newrelic/go-agent@v3.26.0+incompatible/internal/metric_rules_test.go (about)

     1  // Copyright 2020 New Relic Corporation. All rights reserved.
     2  // SPDX-License-Identifier: Apache-2.0
     3  
     4  package internal
     5  
     6  import (
     7  	"encoding/json"
     8  	"testing"
     9  
    10  	"github.com/newrelic/go-agent/internal/crossagent"
    11  )
    12  
    13  func TestMetricRules(t *testing.T) {
    14  	var tcs []struct {
    15  		Testname string      `json:"testname"`
    16  		Rules    metricRules `json:"rules"`
    17  		Tests    []struct {
    18  			Input    string `json:"input"`
    19  			Expected string `json:"expected"`
    20  		} `json:"tests"`
    21  	}
    22  
    23  	err := crossagent.ReadJSON("rules.json", &tcs)
    24  	if err != nil {
    25  		t.Fatal(err)
    26  	}
    27  
    28  	for _, tc := range tcs {
    29  		// This test relies upon Perl-specific regex syntax (negative
    30  		// lookahead assertions) which are not implemented in Go's
    31  		// regexp package. We believe these types of rules are
    32  		// exceedingly rare in practice, so we're skipping
    33  		// implementation of this exotic syntax for now.
    34  		if tc.Testname == "saxon's test" {
    35  			continue
    36  		}
    37  
    38  		for _, x := range tc.Tests {
    39  			out := tc.Rules.Apply(x.Input)
    40  			if out != x.Expected {
    41  				t.Fatal(tc.Testname, x.Input, out, x.Expected)
    42  			}
    43  		}
    44  	}
    45  }
    46  
    47  func TestMetricRuleWithNegativeLookaheadAssertion(t *testing.T) {
    48  	js := `[{
    49  		"match_expression":"^(?!account|application).*",
    50  		"replacement":"*",
    51  		"ignore":false,
    52  		"eval_order":0,
    53  		"each_segment":true
    54  	}]`
    55  	var rules metricRules
    56  	err := json.Unmarshal([]byte(js), &rules)
    57  	if nil != err {
    58  		t.Fatal(err)
    59  	}
    60  	if 0 != rules.Len() {
    61  		t.Fatal(rules)
    62  	}
    63  }
    64  
    65  func TestNilApplyRules(t *testing.T) {
    66  	var rules metricRules
    67  
    68  	input := "hello"
    69  	out := rules.Apply(input)
    70  	if input != out {
    71  		t.Fatal(input, out)
    72  	}
    73  }
    74  
    75  func TestAmbiguousReplacement(t *testing.T) {
    76  	js := `[{
    77  		"match_expression":"(.*)/[^/]*.(bmp|css|gif|ico|jpg|jpeg|js|png)",
    78  		"replacement":"\\\\1/*.\\2",
    79  		"ignore":false,
    80  		"eval_order":0
    81  	}]`
    82  	var rules metricRules
    83  	err := json.Unmarshal([]byte(js), &rules)
    84  	if nil != err {
    85  		t.Fatal(err)
    86  	}
    87  	if 0 != rules.Len() {
    88  		t.Fatal(rules)
    89  	}
    90  }
    91  
    92  func TestBadMetricRulesJSON(t *testing.T) {
    93  	js := `{}`
    94  	var rules metricRules
    95  	err := json.Unmarshal([]byte(js), &rules)
    96  	if nil == err {
    97  		t.Fatal("missing bad json error")
    98  	}
    99  }