bosun.org@v0.0.0-20210513094433-e25bc3e69a1f/host/host_test.go (about) 1 package host 2 3 import ( 4 "testing" 5 6 "bosun.org/name" 7 ) 8 9 type testCase struct { 10 providedName, expectedName string 11 } 12 13 func getNameProcessor(useFullName bool) name.Processor { 14 np, err := NewHostNameProcessor(useFullName) 15 if err != nil { 16 panic("Failed to create name.Processor") 17 } 18 19 return np 20 } 21 22 func initialiseHost(name string, useFullName bool) Host { 23 h, err := NewHost(name, getNameProcessor(useFullName)) 24 if err != nil { 25 panic(err) 26 } 27 28 return h 29 } 30 31 func validateTestCases(host Host, testCases []testCase, t *testing.T) { 32 if host.GetNameProcessor() == nil { 33 t.Error("Expected host to have a name processor") 34 return 35 } 36 37 for _, tc := range testCases { 38 if err := host.SetName(tc.providedName); err != nil { 39 t.Error(err) 40 continue 41 } 42 43 if got := host.GetName(); got != tc.expectedName { 44 t.Errorf("Expected '%s' but got '%s'", tc.expectedName, got) 45 } 46 } 47 } 48 49 func TestNew_ShortName(t *testing.T) { 50 testCases := []testCase{ 51 {"host", "host"}, 52 {"mach.acme.com", "mach"}, 53 {"abc-def.acme.co.uk", "abc-def"}, 54 } 55 56 n := "mach1" 57 host := initialiseHost(n+".domain.com", false) 58 if host.GetName() != n { 59 t.Errorf("Expected '%s' but got '%s'", n, host.GetName()) 60 } 61 62 validateTestCases(host, testCases, t) 63 } 64 65 func TestNew_FullName(t *testing.T) { 66 testCases := []testCase{ 67 {"host", "host"}, 68 {"mach.acme.com", "mach.acme.com"}, 69 {"abc-def.acme.co.uk", "abc-def.acme.co.uk"}, 70 } 71 72 host := initialiseHost("some.name", true) 73 validateTestCases(host, testCases, t) 74 } 75 76 func TestChangeNameProcessor(t *testing.T) { 77 testCases := []testCase{ 78 {"host", "host"}, 79 {"mach.acme.com", "mach"}, 80 {"abc-def.acme.co.uk", "abc-def"}, 81 } 82 83 host := initialiseHost("some.name", false) 84 validateTestCases(host, testCases, t) 85 86 if err := host.SetNameProcessor(getNameProcessor(true)); err != nil { 87 t.Error(err) 88 return 89 } 90 91 testCases = []testCase{ 92 {"host", "host"}, 93 {"mach.acme.com", "mach.acme.com"}, 94 {"abc-def.acme.co.uk", "abc-def.acme.co.uk"}, 95 } 96 97 validateTestCases(host, testCases, t) 98 }