setup_ip_forwarding_test.go 1.4 KB

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