github.com/containerd/nerdctl/v2@v2.0.0-beta.5.0.20240520001846-b5758f54fa28/pkg/portutil/iptable/iptables_test.go (about)

     1  /*
     2     Copyright The containerd Authors.
     3  
     4     Licensed under the Apache License, Version 2.0 (the "License");
     5     you may not use this file except in compliance with the License.
     6     You may obtain a copy of the License at
     7  
     8         http://www.apache.org/licenses/LICENSE-2.0
     9  
    10     Unless required by applicable law or agreed to in writing, software
    11     distributed under the License is distributed on an "AS IS" BASIS,
    12     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13     See the License for the specific language governing permissions and
    14     limitations under the License.
    15  */
    16  
    17  package iptable
    18  
    19  import (
    20  	"testing"
    21  )
    22  
    23  func TestParseIPTableRules(t *testing.T) {
    24  	testCases := []struct {
    25  		name  string
    26  		rules []string
    27  		want  []uint64
    28  	}{
    29  		{
    30  			name:  "Empty input",
    31  			rules: []string{},
    32  			want:  []uint64{},
    33  		},
    34  		{
    35  			name: "Single rule with single port",
    36  			rules: []string{
    37  				"-A CNI-HOSTPORT-DNAT -p tcp -m comment --comment \"dnat name: \"bridge\" id: \"some-id\"\" -m multiport --dports 8080 -j CNI-DN-some-hash",
    38  			},
    39  			want: []uint64{8080},
    40  		},
    41  		{
    42  			name: "Multiple rules with multiple ports",
    43  			rules: []string{
    44  				"-A CNI-HOSTPORT-DNAT -p tcp -m comment --comment \"dnat name: \"bridge\" id: \"some-id\"\" -m multiport --dports 8080 -j CNI-DN-some-hash",
    45  				"-A CNI-HOSTPORT-DNAT -p tcp -m comment --comment \"dnat name: \"bridge\" id: \"some-id\"\" -m multiport --dports 9090 -j CNI-DN-some-hash",
    46  			},
    47  			want: []uint64{8080, 9090},
    48  		},
    49  	}
    50  
    51  	for _, tc := range testCases {
    52  		t.Run(tc.name, func(t *testing.T) {
    53  			got := ParseIPTableRules(tc.rules)
    54  			if !equal(got, tc.want) {
    55  				t.Errorf("ParseIPTableRules(%v) = %v; want %v", tc.rules, got, tc.want)
    56  			}
    57  		})
    58  	}
    59  }
    60  
    61  func equal(a, b []uint64) bool {
    62  	if len(a) != len(b) {
    63  		return false
    64  	}
    65  	for i, v := range a {
    66  		if v != b[i] {
    67  			return false
    68  		}
    69  	}
    70  	return true
    71  }