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

     1  package strmatcher_test
     2  
     3  import (
     4  	"reflect"
     5  	"testing"
     6  
     7  	. "github.com/v2fly/v2ray-core/v5/common/strmatcher"
     8  )
     9  
    10  func TestDomainMatcherGroup(t *testing.T) {
    11  	patterns := []struct {
    12  		Pattern string
    13  		Value   uint32
    14  	}{
    15  		{
    16  			Pattern: "v2fly.org",
    17  			Value:   1,
    18  		},
    19  		{
    20  			Pattern: "google.com",
    21  			Value:   2,
    22  		},
    23  		{
    24  			Pattern: "x.a.com",
    25  			Value:   3,
    26  		},
    27  		{
    28  			Pattern: "a.b.com",
    29  			Value:   4,
    30  		},
    31  		{
    32  			Pattern: "c.a.b.com",
    33  			Value:   5,
    34  		},
    35  		{
    36  			Pattern: "x.y.com",
    37  			Value:   4,
    38  		},
    39  		{
    40  			Pattern: "x.y.com",
    41  			Value:   6,
    42  		},
    43  	}
    44  	testCases := []struct {
    45  		Domain string
    46  		Result []uint32
    47  	}{
    48  		{
    49  			Domain: "x.v2fly.org",
    50  			Result: []uint32{1},
    51  		},
    52  		{
    53  			Domain: "y.com",
    54  			Result: nil,
    55  		},
    56  		{
    57  			Domain: "a.b.com",
    58  			Result: []uint32{4},
    59  		},
    60  		{ // Matches [c.a.b.com, a.b.com]
    61  			Domain: "c.a.b.com",
    62  			Result: []uint32{5, 4},
    63  		},
    64  		{
    65  			Domain: "c.a..b.com",
    66  			Result: nil,
    67  		},
    68  		{
    69  			Domain: ".com",
    70  			Result: nil,
    71  		},
    72  		{
    73  			Domain: "com",
    74  			Result: nil,
    75  		},
    76  		{
    77  			Domain: "",
    78  			Result: nil,
    79  		},
    80  		{
    81  			Domain: "x.y.com",
    82  			Result: []uint32{4, 6},
    83  		},
    84  	}
    85  	g := NewDomainMatcherGroup()
    86  	for _, pattern := range patterns {
    87  		AddMatcherToGroup(g, DomainMatcher(pattern.Pattern), pattern.Value)
    88  	}
    89  	for _, testCase := range testCases {
    90  		r := g.Match(testCase.Domain)
    91  		if !reflect.DeepEqual(r, testCase.Result) {
    92  			t.Error("Failed to match domain: ", testCase.Domain, ", expect ", testCase.Result, ", but got ", r)
    93  		}
    94  	}
    95  }
    96  
    97  func TestEmptyDomainMatcherGroup(t *testing.T) {
    98  	g := NewDomainMatcherGroup()
    99  	r := g.Match("v2fly.org")
   100  	if len(r) != 0 {
   101  		t.Error("Expect [], but ", r)
   102  	}
   103  }