github.com/v2fly/v2ray-core/v5@v5.16.2-0.20240507031116-8191faa6e095/common/strmatcher/indexmatcher_linear_test.go (about)

     1  package strmatcher_test
     2  
     3  import (
     4  	"reflect"
     5  	"testing"
     6  
     7  	"github.com/v2fly/v2ray-core/v5/common"
     8  	. "github.com/v2fly/v2ray-core/v5/common/strmatcher"
     9  )
    10  
    11  // See https://github.com/v2fly/v2ray-core/issues/92#issuecomment-673238489
    12  func TestLinearIndexMatcher(t *testing.T) {
    13  	rules := []struct {
    14  		Type   Type
    15  		Domain string
    16  	}{
    17  		{
    18  			Type:   Regex,
    19  			Domain: "apis\\.us$",
    20  		},
    21  		{
    22  			Type:   Substr,
    23  			Domain: "apis",
    24  		},
    25  		{
    26  			Type:   Domain,
    27  			Domain: "googleapis.com",
    28  		},
    29  		{
    30  			Type:   Domain,
    31  			Domain: "com",
    32  		},
    33  		{
    34  			Type:   Full,
    35  			Domain: "www.baidu.com",
    36  		},
    37  		{
    38  			Type:   Substr,
    39  			Domain: "apis",
    40  		},
    41  		{
    42  			Type:   Domain,
    43  			Domain: "googleapis.com",
    44  		},
    45  		{
    46  			Type:   Full,
    47  			Domain: "fonts.googleapis.com",
    48  		},
    49  		{
    50  			Type:   Full,
    51  			Domain: "www.baidu.com",
    52  		},
    53  		{
    54  			Type:   Domain,
    55  			Domain: "example.com",
    56  		},
    57  	}
    58  	cases := []struct {
    59  		Input  string
    60  		Output []uint32
    61  	}{
    62  		{
    63  			Input:  "www.baidu.com",
    64  			Output: []uint32{5, 9, 4},
    65  		},
    66  		{
    67  			Input:  "fonts.googleapis.com",
    68  			Output: []uint32{8, 3, 7, 4, 2, 6},
    69  		},
    70  		{
    71  			Input:  "example.googleapis.com",
    72  			Output: []uint32{3, 7, 4, 2, 6},
    73  		},
    74  		{
    75  			Input:  "testapis.us",
    76  			Output: []uint32{2, 6, 1},
    77  		},
    78  		{
    79  			Input:  "example.com",
    80  			Output: []uint32{10, 4},
    81  		},
    82  	}
    83  	matcherGroup := NewLinearIndexMatcher()
    84  	for _, rule := range rules {
    85  		matcher, err := rule.Type.New(rule.Domain)
    86  		common.Must(err)
    87  		matcherGroup.Add(matcher)
    88  	}
    89  	matcherGroup.Build()
    90  	for _, test := range cases {
    91  		if m := matcherGroup.Match(test.Input); !reflect.DeepEqual(m, test.Output) {
    92  			t.Error("unexpected output: ", m, " for test case ", test)
    93  		}
    94  	}
    95  }