netns_test.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright (c) 2016 Arista Networks, Inc.
  2. // Use of this source code is governed by the Apache License 2.0
  3. // that can be found in the COPYING file.
  4. package netns
  5. import (
  6. "io/ioutil"
  7. "os"
  8. "path/filepath"
  9. "testing"
  10. )
  11. type mockHandle int
  12. func (mh mockHandle) close() error {
  13. return nil
  14. }
  15. func (mh mockHandle) fd() int {
  16. return 0
  17. }
  18. func TestNetNs(t *testing.T) {
  19. setNsCallCount := 0
  20. // Mock getNs
  21. oldGetNs := getNs
  22. getNs = func(nsName string) (handle, error) {
  23. return mockHandle(1), nil
  24. }
  25. defer func() {
  26. getNs = oldGetNs
  27. }()
  28. // Mock setNs
  29. oldSetNs := setNs
  30. setNs = func(fd handle) error {
  31. setNsCallCount++
  32. return nil
  33. }
  34. defer func() {
  35. setNs = oldSetNs
  36. }()
  37. // Create a tempfile so we can use its name for the network namespace
  38. tmpfile, err := ioutil.TempFile("", "")
  39. if err != nil {
  40. t.Fatalf("Failed to create a temp file: %s", err)
  41. }
  42. defer os.Remove(tmpfile.Name())
  43. nsName := filepath.Base(tmpfile.Name())
  44. // Map of network namespace name to the number of times it should call setNs
  45. cases := map[string]int{"": 0, "default": 2, nsName: 2}
  46. for name, callCount := range cases {
  47. var cbResult string
  48. err = Do(name, func() error {
  49. cbResult = "Hello" + name
  50. return nil
  51. })
  52. if err != nil {
  53. t.Fatalf("Error calling function in different network namespace: %s", err)
  54. }
  55. if cbResult != "Hello"+name {
  56. t.Fatalf("Failed to call the callback function")
  57. }
  58. if setNsCallCount != callCount {
  59. t.Fatalf("setNs should have been called %d times for %s, but was called %d times",
  60. callCount, name, setNsCallCount)
  61. }
  62. setNsCallCount = 0
  63. }
  64. }