setup_ip_forwarding_test.go 1.4 KB

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