github.com/sagernet/netlink@v0.0.0-20240612041022-b9a21c07ac6a/bridge_linux_test.go (about)

     1  package netlink
     2  
     3  import (
     4  	"fmt"
     5  	"io/ioutil"
     6  	"testing"
     7  )
     8  
     9  func TestBridgeVlan(t *testing.T) {
    10  	minKernelRequired(t, 3, 10)
    11  
    12  	tearDown := setUpNetlinkTest(t)
    13  	defer tearDown()
    14  	if err := remountSysfs(); err != nil {
    15  		t.Fatal(err)
    16  	}
    17  	bridgeName := "foo"
    18  	bridge := &Bridge{LinkAttrs: LinkAttrs{Name: bridgeName}}
    19  	if err := LinkAdd(bridge); err != nil {
    20  		t.Fatal(err)
    21  	}
    22  	if err := ioutil.WriteFile(fmt.Sprintf("/sys/devices/virtual/net/%s/bridge/vlan_filtering", bridgeName), []byte("1"), 0644); err != nil {
    23  		t.Fatal(err)
    24  	}
    25  	if vlanMap, err := BridgeVlanList(); err != nil {
    26  		t.Fatal(err)
    27  	} else {
    28  		if len(vlanMap) != 1 {
    29  			t.Fatal()
    30  		}
    31  		if vInfo, ok := vlanMap[int32(bridge.Index)]; !ok {
    32  			t.Fatal("vlanMap should include foo port vlan info")
    33  		} else {
    34  			if len(vInfo) != 1 {
    35  				t.Fatal()
    36  			} else {
    37  				if !vInfo[0].EngressUntag() || !vInfo[0].PortVID() || vInfo[0].Vid != 1 {
    38  					t.Fatalf("bridge vlan show get wrong return %s", vInfo[0].String())
    39  				}
    40  			}
    41  		}
    42  	}
    43  	dummy := &Dummy{LinkAttrs: LinkAttrs{Name: "dum1"}}
    44  	if err := LinkAdd(dummy); err != nil {
    45  		t.Fatal(err)
    46  	}
    47  	if err := LinkSetMaster(dummy, bridge); err != nil {
    48  		t.Fatal(err)
    49  	}
    50  	if err := BridgeVlanAdd(dummy, 2, false, false, false, false); err != nil {
    51  		t.Fatal(err)
    52  	}
    53  	if err := BridgeVlanAdd(dummy, 3, true, true, false, false); err != nil {
    54  		t.Fatal(err)
    55  	}
    56  	if vlanMap, err := BridgeVlanList(); err != nil {
    57  		t.Fatal(err)
    58  	} else {
    59  		if len(vlanMap) != 2 {
    60  			t.Fatal()
    61  		}
    62  		if vInfo, ok := vlanMap[int32(bridge.Index)]; !ok {
    63  			t.Fatal("vlanMap should include foo port vlan info")
    64  		} else {
    65  			if fmt.Sprintf("%v", vInfo) != "[{Flags:6 Vid:1}]" {
    66  				t.Fatalf("unexpected result %v", vInfo)
    67  			}
    68  		}
    69  		if vInfo, ok := vlanMap[int32(dummy.Index)]; !ok {
    70  			t.Fatal("vlanMap should include dum1 port vlan info")
    71  		} else {
    72  			if fmt.Sprintf("%v", vInfo) != "[{Flags:4 Vid:1} {Flags:0 Vid:2} {Flags:6 Vid:3}]" {
    73  				t.Fatalf("unexpected result %v", vInfo)
    74  			}
    75  		}
    76  	}
    77  }