github.com/Prakhar-Agarwal-byte/moby@v0.0.0-20231027092010-a14e3e8ab87e/libnetwork/drivers/bridge/setup_ip_forwarding_test.go (about) 1 //go:build linux 2 3 package bridge 4 5 import ( 6 "bytes" 7 "os" 8 "testing" 9 ) 10 11 func TestSetupIPForwarding(t *testing.T) { 12 // Read current setting and ensure the original value gets restored 13 procSetting := readCurrentIPForwardingSetting(t) 14 defer reconcileIPForwardingSetting(t, procSetting) 15 16 // Disable IP Forwarding if enabled 17 if bytes.Equal(procSetting, []byte("1\n")) { 18 writeIPForwardingSetting(t, []byte{'0', '\n'}) 19 } 20 21 // Set IP Forwarding 22 if err := setupIPForwarding(true, true); err != nil { 23 t.Fatalf("Failed to setup IP forwarding: %v", err) 24 } 25 26 // Read new setting 27 procSetting = readCurrentIPForwardingSetting(t) 28 if !bytes.Equal(procSetting, []byte("1\n")) { 29 t.Fatal("Failed to effectively setup IP forwarding") 30 } 31 } 32 33 func readCurrentIPForwardingSetting(t *testing.T) []byte { 34 procSetting, err := os.ReadFile(ipv4ForwardConf) 35 if err != nil { 36 t.Fatalf("Can't execute test: Failed to read current IP forwarding setting: %v", err) 37 } 38 return procSetting 39 } 40 41 func writeIPForwardingSetting(t *testing.T, chars []byte) { 42 err := os.WriteFile(ipv4ForwardConf, chars, ipv4ForwardConfPerm) 43 if err != nil { 44 t.Fatalf("Can't execute or cleanup after test: Failed to reset IP forwarding: %v", err) 45 } 46 } 47 48 func reconcileIPForwardingSetting(t *testing.T, original []byte) { 49 current := readCurrentIPForwardingSetting(t) 50 if !bytes.Equal(original, current) { 51 writeIPForwardingSetting(t, original) 52 } 53 }