setup_ip_forwarding_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package bridge
  2. import (
  3. "bytes"
  4. "io/ioutil"
  5. "strings"
  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.Compare(procSetting, []byte("1\n")) == 0 {
  14. writeIPForwardingSetting(t, []byte{'0', '\n'})
  15. }
  16. // Create test interface with ip forwarding setting enabled
  17. br := &Interface{
  18. Config: &Configuration{
  19. BridgeName: DefaultBridgeName,
  20. EnableIPForwarding: true,
  21. },
  22. }
  23. // Set IP Forwarding
  24. if err := SetupIPForwarding(br); err != nil {
  25. t.Fatalf("Failed to setup IP forwarding: %v", err)
  26. }
  27. // Read new setting
  28. procSetting = readCurrentIPForwardingSetting(t)
  29. if bytes.Compare(procSetting, []byte("1\n")) != 0 {
  30. t.Fatalf("Failed to effectively setup IP forwarding")
  31. }
  32. }
  33. func TestUnexpectedSetupIPForwarding(t *testing.T) {
  34. // Read current setting and ensure the original value gets restored
  35. procSetting := readCurrentIPForwardingSetting(t)
  36. defer reconcileIPForwardingSetting(t, procSetting)
  37. // Create test interface without ip forwarding setting enabled
  38. br := &Interface{
  39. Config: &Configuration{
  40. BridgeName: DefaultBridgeName,
  41. EnableIPForwarding: false,
  42. },
  43. }
  44. // Attempt Set IP Forwarding
  45. if err := SetupIPForwarding(br); err == nil {
  46. t.Fatal("Setup IP forwarding was expected to fail")
  47. } else if !strings.Contains(err.Error(), "Unexpected request") {
  48. t.Fatalf("Setup IP forwarding failed with unexpected error: %v", err)
  49. }
  50. }
  51. func readCurrentIPForwardingSetting(t *testing.T) []byte {
  52. procSetting, err := ioutil.ReadFile(IPV4_FORW_CONF_FILE)
  53. if err != nil {
  54. t.Fatalf("Can't execute test: Failed to read current IP forwarding setting: %v", err)
  55. }
  56. return procSetting
  57. }
  58. func writeIPForwardingSetting(t *testing.T, chars []byte) {
  59. err := ioutil.WriteFile(IPV4_FORW_CONF_FILE, chars, PERM)
  60. if err != nil {
  61. t.Fatalf("Can't execute or cleanup after test: Failed to reset IP forwarding: %v", err)
  62. }
  63. }
  64. func reconcileIPForwardingSetting(t *testing.T, original []byte) {
  65. current := readCurrentIPForwardingSetting(t)
  66. if bytes.Compare(original, current) != 0 {
  67. writeIPForwardingSetting(t, original)
  68. }
  69. }