File: dnscache_test.go

package info (click to toggle)
golang-github-viki-org-dnscache 0.0~git20130720.0.c70c1f2-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 60 kB
  • ctags: 19
  • sloc: makefile: 3
file content (79 lines) | stat: -rw-r--r-- 2,444 bytes parent folder | download | duplicates (2)
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 dnscache

import (
  "net"
  "sort"
  "time"
  "testing"
)

func TestFetchReturnsAndErrorOnInvalidLookup(t *testing.T) {
  ips, err := New(0).Lookup("invalid.viki.io")
  if ips != nil {
    t.Errorf("Expecting nil ips, got %v", ips)
  }
  expected := "lookup invalid.viki.io: no such host"
  if err.Error() != expected {
    t.Errorf("Expecting %q error, got %q", expected, err.Error())
  }
}

func TestFetchReturnsAListOfIps(t *testing.T) {
  ips, _ := New(0).Lookup("dnscache.go.test.viki.io")
  assertIps(t, ips, []string{"1.123.58.13", "31.85.32.110"})
}

func TestCallingLookupAddsTheItemToTheCache(t *testing.T) {
  r := New(0)
  r.Lookup("dnscache.go.test.viki.io")
  assertIps(t, r.cache["dnscache.go.test.viki.io"], []string{"1.123.58.13", "31.85.32.110"})
}

func TestFetchLoadsValueFromTheCache(t *testing.T) {
  r := New(0)
  r.cache["invalid.viki.io"] = []net.IP{net.ParseIP("1.1.2.3")}
  ips, _ := r.Fetch("invalid.viki.io")
  assertIps(t, ips, []string{"1.1.2.3"})
}

func TestFetchOneLoadsTheFirstValue(t *testing.T) {
  r := New(0)
  r.cache["something.viki.io"] = []net.IP{net.ParseIP("1.1.2.3"), net.ParseIP("100.100.102.103")}
  ip, _ := r.FetchOne("something.viki.io")
  assertIps(t, []net.IP{ip}, []string{"1.1.2.3"})
}

func TestFetchOneStringLoadsTheFirstValue(t *testing.T) {
  r := New(0)
  r.cache["something.viki.io"] = []net.IP{net.ParseIP("100.100.102.103"), net.ParseIP("100.100.102.104")}
  ip, _ := r.FetchOneString("something.viki.io")
  if ip != "100.100.102.103" {
    t.Errorf("expected 100.100.102.103 but got %v", ip)
  }
}

func TestFetchLoadsTheIpAndCachesIt(t *testing.T) {
  r := New(0)
  ips, _ := r.Fetch("dnscache.go.test.viki.io")
  assertIps(t, ips, []string{"1.123.58.13", "31.85.32.110"})
  assertIps(t, r.cache["dnscache.go.test.viki.io"], []string{"1.123.58.13", "31.85.32.110"})
}

func TestItReloadsTheIpsAtAGivenInterval(t *testing.T) {
  r := New(1)
  r.cache["dnscache.go.test.viki.io"] = nil
  time.Sleep(time.Second * 2)
  assertIps(t, r.cache["dnscache.go.test.viki.io"], []string{"1.123.58.13", "31.85.32.110"})
}

func assertIps(t *testing.T, actuals []net.IP, expected []string) {
  if len(actuals) != len(expected) {
    t.Errorf("Expecting %d ips, got %d", len(expected), len(actuals))
  }
  sort.Strings(expected)
  for _, ip := range actuals {
    if sort.SearchStrings(expected, ip.String()) == -1 {
      t.Errorf("Got an unexpected ip: %v:", actuals[0])
    }
  }
}