github.com/outbrain/consul@v1.4.5/agent/structs/check_definition_test.go (about) 1 package structs 2 3 import ( 4 "reflect" 5 "testing" 6 "time" 7 8 "github.com/google/gofuzz" 9 "github.com/hashicorp/consul/api" 10 "github.com/mitchellh/reflectwalk" 11 "github.com/pascaldekloe/goe/verify" 12 ) 13 14 func TestCheckDefinition_Defaults(t *testing.T) { 15 t.Parallel() 16 def := CheckDefinition{} 17 check := def.HealthCheck("node1") 18 19 // Health checks default to critical state 20 if check.Status != api.HealthCritical { 21 t.Fatalf("bad: %v", check.Status) 22 } 23 } 24 25 type walker struct { 26 fields map[string]reflect.Value 27 } 28 29 func (w *walker) Struct(reflect.Value) error { 30 return nil 31 } 32 33 func (w *walker) StructField(f reflect.StructField, v reflect.Value) error { 34 w.fields[f.Name] = v 35 return nil 36 } 37 38 func mapFields(obj interface{}) map[string]reflect.Value { 39 w := &walker{make(map[string]reflect.Value)} 40 if err := reflectwalk.Walk(obj, w); err != nil { 41 panic(err) 42 } 43 return w.fields 44 } 45 46 func TestCheckDefinition_CheckType(t *testing.T) { 47 t.Parallel() 48 49 // Fuzz a definition to fill all its fields with data. 50 var def CheckDefinition 51 fuzz.New().Fuzz(&def) 52 orig := mapFields(def) 53 54 // Remap the ID field which changes name, and redact fields we don't 55 // expect in the copy. 56 orig["CheckID"] = orig["ID"] 57 delete(orig, "ID") 58 delete(orig, "ServiceID") 59 delete(orig, "Token") 60 61 // Now convert to a check type and ensure that all fields left match. 62 chk := def.CheckType() 63 copy := mapFields(chk) 64 for f, vo := range orig { 65 vc, ok := copy[f] 66 if !ok { 67 t.Fatalf("struct is missing field %q", f) 68 } 69 70 if !reflect.DeepEqual(vo.Interface(), vc.Interface()) { 71 t.Fatalf("copy skipped field %q", f) 72 } 73 } 74 } 75 76 func TestCheckDefinitionToCheckType(t *testing.T) { 77 t.Parallel() 78 got := &CheckDefinition{ 79 ID: "id", 80 Name: "name", 81 Status: "green", 82 Notes: "notes", 83 84 ServiceID: "svcid", 85 Token: "tok", 86 ScriptArgs: []string{"/bin/foo"}, 87 HTTP: "someurl", 88 TCP: "host:port", 89 Interval: 1 * time.Second, 90 DockerContainerID: "abc123", 91 Shell: "/bin/ksh", 92 TLSSkipVerify: true, 93 Timeout: 2 * time.Second, 94 TTL: 3 * time.Second, 95 DeregisterCriticalServiceAfter: 4 * time.Second, 96 } 97 want := &CheckType{ 98 CheckID: "id", 99 Name: "name", 100 Status: "green", 101 Notes: "notes", 102 103 ScriptArgs: []string{"/bin/foo"}, 104 HTTP: "someurl", 105 TCP: "host:port", 106 Interval: 1 * time.Second, 107 DockerContainerID: "abc123", 108 Shell: "/bin/ksh", 109 TLSSkipVerify: true, 110 Timeout: 2 * time.Second, 111 TTL: 3 * time.Second, 112 DeregisterCriticalServiceAfter: 4 * time.Second, 113 } 114 verify.Values(t, "", got.CheckType(), want) 115 }