summaryrefslogtreecommitdiffhomepage
path: root/interfaces/interfaces_test.go
blob: 7633d5e70b1f9d0dc09000b208e3ace6e1316157 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package interfaces

import (
	"errors"
	"net"
	"testing"

	"github.com/stretchr/testify/require"
)

func fakeIface(idx int, name string, loopback bool) net.Interface {
	var flags net.Flags
	if loopback {
		flags |= net.FlagLoopback
	}
	return net.Interface{
		Index:        idx,
		MTU:          1500,
		Name:         name,
		HardwareAddr: []byte{0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff},
		Flags:        flags,
	}
}

func TestGetLoopbackInterfaces(t *testing.T) {
	interfaceGetter = func() ([]net.Interface, error) {
		return []net.Interface{
			fakeIface(0, "lo", true),
			fakeIface(1, "eth0", false),
			fakeIface(2, "eth1", false),
		}, nil
	}
	ifaces, err := GetLoopbackInterfaces()
	// this has to be reassigned before any require.* call
	interfaceGetter = net.Interfaces

	require.NoError(t, err)
	require.Equal(t, 1, len(ifaces))
}

func TestGetLoopbackInterfacesError(t *testing.T) {
	interfaceGetter = func() ([]net.Interface, error) {
		return nil, errors.New("expected error")

	}
	_, err := GetLoopbackInterfaces()
	// this has to be reassigned before any require.* call
	interfaceGetter = net.Interfaces

	require.Error(t, err)
}

func TestGetNonLoopbackInterfaces(t *testing.T) {
	interfaceGetter = func() ([]net.Interface, error) {
		return []net.Interface{
			fakeIface(0, "lo", true),
			fakeIface(1, "eth0", false),
			fakeIface(2, "eth1", false),
		}, nil
	}
	ifaces, err := GetNonLoopbackInterfaces()
	// this has to be reassigned before any require.* call
	interfaceGetter = net.Interfaces

	require.NoError(t, err)
	require.Equal(t, 2, len(ifaces))
}

func TestGetNonLoopbackInterfacesError(t *testing.T) {
	interfaceGetter = func() ([]net.Interface, error) {
		return nil, errors.New("expected error")

	}
	_, err := GetNonLoopbackInterfaces()
	// this has to be reassigned before any require.* call
	interfaceGetter = net.Interfaces

	require.Error(t, err)
}