setup_ip_forwarding_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. // Create test interface with ip forwarding setting enabled
  16. config := &Configuration{
  17. EnableIPForwarding: true}
  18. // Set IP Forwarding
  19. if err := setupIPForwarding(config); err != nil {
  20. t.Fatalf("Failed to setup IP forwarding: %v", err)
  21. }
  22. // Read new setting
  23. procSetting = readCurrentIPForwardingSetting(t)
  24. if bytes.Compare(procSetting, []byte("1\n")) != 0 {
  25. t.Fatalf("Failed to effectively setup IP forwarding")
  26. }
  27. }
  28. func TestUnexpectedSetupIPForwarding(t *testing.T) {
  29. // Read current setting and ensure the original value gets restored
  30. procSetting := readCurrentIPForwardingSetting(t)
  31. defer reconcileIPForwardingSetting(t, procSetting)
  32. // Create test interface without ip forwarding setting enabled
  33. config := &Configuration{
  34. EnableIPForwarding: false}
  35. // Attempt Set IP Forwarding
  36. err := setupIPForwarding(config)
  37. if err == nil {
  38. t.Fatal("Setup IP forwarding was expected to fail")
  39. }
  40. if _, ok := err.(*ErrIPFwdCfg); !ok {
  41. t.Fatalf("Setup IP forwarding failed with unexpected error: %v", err)
  42. }
  43. }
  44. func readCurrentIPForwardingSetting(t *testing.T) []byte {
  45. procSetting, err := ioutil.ReadFile(ipv4ForwardConf)
  46. if err != nil {
  47. t.Fatalf("Can't execute test: Failed to read current IP forwarding setting: %v", err)
  48. }
  49. return procSetting
  50. }
  51. func writeIPForwardingSetting(t *testing.T, chars []byte) {
  52. err := ioutil.WriteFile(ipv4ForwardConf, chars, ipv4ForwardConfPerm)
  53. if err != nil {
  54. t.Fatalf("Can't execute or cleanup after test: Failed to reset IP forwarding: %v", err)
  55. }
  56. }
  57. func reconcileIPForwardingSetting(t *testing.T, original []byte) {
  58. current := readCurrentIPForwardingSetting(t)
  59. if bytes.Compare(original, current) != 0 {
  60. writeIPForwardingSetting(t, original)
  61. }
  62. }