github.com/qri-io/qri@v0.10.1-0.20220104210721-c771715036cb/automation/spec/hook.go (about) 1 package spec 2 3 import ( 4 "encoding/json" 5 "errors" 6 "testing" 7 8 "github.com/qri-io/qri/automation/hook" 9 ) 10 11 // AssertHook confirms the expected behavior of a hook.Hook Interface 12 // implementation 13 func AssertHook(t *testing.T, h hook.Hook) { 14 eventType, _ := h.Event() 15 if eventType == "" { 16 t.Errorf("Event method must return a non-empty event.Type") 17 } 18 if h.Type() == "" { 19 t.Error("Type method must return a non-empty hook.Type") 20 } 21 if err := h.SetEnabled(true); err != nil { 22 t.Fatalf("hook.SetEnabled unexpected error: %s", err) 23 } 24 if !h.Enabled() { 25 t.Error("expected hook.Enabled() to be true after hook.SetEnabled(true)") 26 } 27 if err := h.SetEnabled(false); err != nil { 28 t.Fatalf("hook.SetEnabled unexpected error: %s", err) 29 } 30 if h.Enabled() { 31 t.Error("expected hook.Enabled() to be false after hook.SetEnabled(false)") 32 } 33 hBytes, err := json.Marshal(h) 34 if err != nil { 35 t.Fatalf("json.Marshal unexpected error: %s", err) 36 } 37 hObj := map[string]interface{}{} 38 if err := json.Unmarshal(hBytes, &hObj); err != nil { 39 t.Fatalf("json.Unmarshal unexpected error: %s", err) 40 } 41 hType, ok := hObj["type"] 42 if !ok { 43 t.Fatal("json.Marshal error, expected Type field to exist") 44 } 45 if hType != h.Type() { 46 t.Fatalf("json.Marshal error, expected marshalled type %q to match hook.Type() %q", hType, h.Type()) 47 } 48 49 hObj["type"] = "bad hook type" 50 hBytes, err = json.Marshal(hObj) 51 if err != nil { 52 t.Fatalf("json.Marshal unexpected error: %s", err) 53 } 54 if err := json.Unmarshal(hBytes, h); !errors.Is(err, hook.ErrUnexpectedType) { 55 t.Fatalf("json.Unmarshal should emit a `hook.ErrUnexpectedType` error if the given type does not match the hook.Type of the Hook") 56 } 57 }