setup_ip_forwarding_test.go 2.1 KB

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