iface_test.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Copyright 2017 flannel authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package ip
  15. import (
  16. "net"
  17. "testing"
  18. "github.com/coreos/flannel/pkg/ns"
  19. "github.com/vishvananda/netlink"
  20. )
  21. func TestEnsureV4AddressOnLink(t *testing.T) {
  22. teardown := ns.SetUpNetlinkTest(t)
  23. defer teardown()
  24. lo, err := netlink.LinkByName("lo")
  25. if err != nil {
  26. t.Fatal(err)
  27. }
  28. if err := netlink.LinkSetUp(lo); err != nil {
  29. t.Fatal(err)
  30. }
  31. // check changing address
  32. if err := EnsureV4AddressOnLink(IP4Net{IP: FromIP(net.ParseIP("127.0.0.2")), PrefixLen: 24}, lo); err != nil {
  33. t.Fatal(err)
  34. }
  35. addrs, err := netlink.AddrList(lo, netlink.FAMILY_V4)
  36. if err != nil {
  37. t.Fatal(err)
  38. }
  39. if len(addrs) != 1 || addrs[0].String() != "127.0.0.2/24 lo" {
  40. t.Fatalf("addrs %v is not expected", addrs)
  41. }
  42. // check changing address if there exist multiple addresses
  43. if err := netlink.AddrAdd(lo, &netlink.Addr{IPNet: &net.IPNet{IP: net.ParseIP("127.0.0.3"), Mask: net.CIDRMask(24, 32)}}); err != nil {
  44. t.Fatal(err)
  45. }
  46. if err := EnsureV4AddressOnLink(IP4Net{IP: FromIP(net.ParseIP("127.0.0.2")), PrefixLen: 24}, lo); err == nil {
  47. t.Fatal("EnsureV4AddressOnLink should return error if there exist multiple address on link")
  48. }
  49. }