github.com/metacubex/mihomo@v1.18.5/component/cidr/ipcidr_set_test.go (about)

     1  package cidr
     2  
     3  import (
     4  	"testing"
     5  )
     6  
     7  func TestIpv4(t *testing.T) {
     8  	tests := []struct {
     9  		name     string
    10  		ipCidr   string
    11  		ip       string
    12  		expected bool
    13  	}{
    14  		{
    15  			name:     "Test Case 1",
    16  			ipCidr:   "149.154.160.0/20",
    17  			ip:       "149.154.160.0",
    18  			expected: true,
    19  		},
    20  		{
    21  			name:     "Test Case 2",
    22  			ipCidr:   "192.168.0.0/16",
    23  			ip:       "10.0.0.1",
    24  			expected: false,
    25  		},
    26  	}
    27  
    28  	for _, test := range tests {
    29  		t.Run(test.name, func(t *testing.T) {
    30  			set := &IpCidrSet{}
    31  			set.AddIpCidrForString(test.ipCidr)
    32  
    33  			result := set.IsContainForString(test.ip)
    34  			if result != test.expected {
    35  				t.Errorf("Expected result: %v, got: %v", test.expected, result)
    36  			}
    37  		})
    38  	}
    39  }
    40  
    41  func TestIpv6(t *testing.T) {
    42  	tests := []struct {
    43  		name     string
    44  		ipCidr   string
    45  		ip       string
    46  		expected bool
    47  	}{
    48  		{
    49  			name:     "Test Case 1",
    50  			ipCidr:   "2409:8000::/20",
    51  			ip:       "2409:8087:1e03:21::27",
    52  			expected: true,
    53  		},
    54  		{
    55  			name:     "Test Case 2",
    56  			ipCidr:   "240e::/16",
    57  			ip:       "240e:964:ea02:100:1800::71",
    58  			expected: true,
    59  		},
    60  	}
    61  	// Add more test cases as needed
    62  
    63  	for _, test := range tests {
    64  		t.Run(test.name, func(t *testing.T) {
    65  			set := &IpCidrSet{}
    66  			set.AddIpCidrForString(test.ipCidr)
    67  
    68  			result := set.IsContainForString(test.ip)
    69  			if result != test.expected {
    70  				t.Errorf("Expected result: %v, got: %v", test.expected, result)
    71  			}
    72  		})
    73  	}
    74  }
    75  
    76  func TestMerge(t *testing.T) {
    77  	tests := []struct {
    78  		name        string
    79  		ipCidr1     string
    80  		ipCidr2     string
    81  		ipCidr3     string
    82  		expectedLen int
    83  	}{
    84  		{
    85  			name:        "Test Case 1",
    86  			ipCidr1:     "2409:8000::/20",
    87  			ipCidr2:     "2409:8000::/21",
    88  			ipCidr3:     "2409:8000::/48",
    89  			expectedLen: 1,
    90  		},
    91  	}
    92  
    93  	for _, test := range tests {
    94  		t.Run(test.name, func(t *testing.T) {
    95  			set := &IpCidrSet{}
    96  			set.AddIpCidrForString(test.ipCidr1)
    97  			set.AddIpCidrForString(test.ipCidr2)
    98  			set.Merge()
    99  
   100  			rangesLen := len(set.rr)
   101  
   102  			if rangesLen != test.expectedLen {
   103  				t.Errorf("Expected len: %v, got: %v", test.expectedLen, rangesLen)
   104  			}
   105  		})
   106  	}
   107  }