link_test.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2019 Yunion
  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 iproute2
  15. import (
  16. "fmt"
  17. "testing"
  18. "github.com/vishvananda/netlink"
  19. )
  20. func genDummyName(t *testing.T) string {
  21. for i := 0; i < 100; i++ {
  22. name := fmt.Sprintf("dummy%d", i)
  23. if _, err := netlink.LinkByName(name); err != nil {
  24. return name
  25. }
  26. }
  27. t.Fatalf("can't even find a dummy name")
  28. return ""
  29. }
  30. func addDummy(t *testing.T, name string) *netlink.Dummy {
  31. attrs := netlink.NewLinkAttrs()
  32. attrs.Name = name
  33. dum := &netlink.Dummy{
  34. LinkAttrs: attrs,
  35. }
  36. if err := netlink.LinkAdd(dum); err != nil {
  37. t.Skipf("add %s: %v", name, err)
  38. }
  39. return dum
  40. }
  41. func delDummy(t *testing.T, dum *netlink.Dummy) {
  42. if err := netlink.LinkDel(dum); err != nil {
  43. t.Errorf("del %s: %v", dum.Name, err)
  44. }
  45. }
  46. func TestLink(t *testing.T) {
  47. ifname := genDummyName(t)
  48. dum := addDummy(t, ifname)
  49. defer delDummy(t, dum)
  50. l := NewLink(ifname)
  51. l.Up().MTU(100).Address("00:11:22:33:44:55")
  52. if err := l.Err(); err != nil {
  53. t.Fatalf("got error: %v", err)
  54. }
  55. l.Down().MTU(120).Address("00:11:22:33:44:88")
  56. if err := l.Err(); err != nil {
  57. t.Fatalf("got error: %v", err)
  58. }
  59. }