github.com/adityamillind98/moby@v23.0.0-rc.4+incompatible/libnetwork/drivers/bridge/setup_ip_forwarding_test.go (about)

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