setup_ip_forwarding_test.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. BridgeName: DefaultBridgeName,
  18. EnableIPForwarding: true}
  19. br := &bridgeInterface{}
  20. // Set IP Forwarding
  21. if err := setupIPForwarding(config, br); err != nil {
  22. t.Fatalf("Failed to setup IP forwarding: %v", err)
  23. }
  24. // Read new setting
  25. procSetting = readCurrentIPForwardingSetting(t)
  26. if bytes.Compare(procSetting, []byte("1\n")) != 0 {
  27. t.Fatalf("Failed to effectively setup IP forwarding")
  28. }
  29. }
  30. func TestUnexpectedSetupIPForwarding(t *testing.T) {
  31. // Read current setting and ensure the original value gets restored
  32. procSetting := readCurrentIPForwardingSetting(t)
  33. defer reconcileIPForwardingSetting(t, procSetting)
  34. // Create test interface without ip forwarding setting enabled
  35. config := &Configuration{
  36. BridgeName: DefaultBridgeName,
  37. EnableIPForwarding: false}
  38. br := &bridgeInterface{}
  39. // Attempt Set IP Forwarding
  40. err := setupIPForwarding(config, br)
  41. if err == nil {
  42. t.Fatal("Setup IP forwarding was expected to fail")
  43. }
  44. if _, ok := err.(*ipForwardCfgError); !ok {
  45. t.Fatalf("Setup IP forwarding failed with unexpected error: %v", err)
  46. }
  47. }
  48. func readCurrentIPForwardingSetting(t *testing.T) []byte {
  49. procSetting, err := ioutil.ReadFile(ipv4ForwardConf)
  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(ipv4ForwardConf, chars, ipv4ForwardConfPerm)
  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. }