forked from tam7t/droplan
/
helper_test.go
82 lines (72 loc) · 2.05 KB
/
helper_test.go
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
80
81
82
package main
import (
"encoding/json"
"errors"
"net"
"strings"
"testing"
"github.com/digitalocean/go-metadata"
. "github.com/franela/goblin"
)
func TestHelper(t *testing.T) {
g := Goblin(t)
g.Describe(`PrivateInterface`, func() {
g.Describe(`with a valid interface`, func() {
g.It(`returns the correct interface`, func() {
ifaces, _ := net.Interfaces()
addrs, _ := ifaces[0].Addrs()
localAddr := addrs[0]
ip := localAddr.String()
switch v := localAddr.(type) {
case *net.IPAddr:
ip = v.IP.String()
case *net.IPNet:
ip = v.IP.String()
}
ifaceName, err := PrivateInterface(ifaces, ip)
g.Assert(ifaceName).Equal(ifaces[0].Name)
g.Assert(err).Equal(nil)
})
})
g.It(`with an invalid IP`, func() {
ifaces, _ := net.Interfaces()
ifaceName, err := PrivateInterface(ifaces, `somethingBad`)
g.Assert(ifaceName).Equal(``)
g.Assert(err).Equal(errors.New(`local interface could not be found`))
})
})
g.Describe(`LocalAddress`, func() {
g.Describe(`with a private interface`, func() {
g.Describe(`with an ipv4 address`, func() {
g.It(`returns the ip address`, func() {
data := decodeMetadata(`{"interfaces": {"private": [{"ipv4": {"ip_address": "privateIP"}}]}}`)
addr, _ := LocalAddress(data)
g.Assert(addr).Equal(`privateIP`)
})
})
g.Describe(`without an ipv4 address`, func() {
g.It(`returns an error`, func() {
data := decodeMetadata(`{"interfaces": {"public": [{"ipv4": {"ip_address": "publicIP"}}]}}`)
_, err := LocalAddress(data)
g.Assert(err).Equal(errors.New(`no private interfaces`))
})
})
})
g.Describe(`without a private interface`, func() {
g.It(`returns an error`, func() {
data := &metadata.Metadata{}
_, err := LocalAddress(data)
g.Assert(err).Equal(errors.New(`no private interfaces`))
})
})
})
}
func decodeMetadata(data string) *metadata.Metadata {
var output metadata.Metadata
var err error
err = json.NewDecoder(strings.NewReader(data)).Decode(&output)
if err != nil {
panic(err)
}
return &output
}