package check import ( "context" "encoding/json" "errors" "net/http" "net/http/httptest" "strings" "testing" "time" ) func TestParsePath(t *testing.T) { doc := map[string]any{"a": map[string]any{"b": []any{"x", map[string]any{"c": 1.0}}}, "list": []any{[]any{"deep"}}} for _, tc := range []struct { path string want any found bool }{ {"a.b[1].c", 1.0, true}, {"$.a.b[0]", "x", true}, {"list[0][0]", "deep", true}, {"a.b[5]", nil, false}, {"a.missing", nil, false}, {"a.b.c", nil, false}, } { p, err := parsePath(tc.path) if err != nil { t.Fatalf("parsePath(%q) = %v", tc.path, err) } got, found := p.lookup(doc) if found != tc.found || (found && got != tc.want) { t.Errorf("lookup(%q) = %v, %t; want %v, %t", tc.path, got, found, tc.want, tc.found) } } for _, bad := range []string{"a..b", "a[x]", "a[-1]", "a[1]b", "[", "a[1"} { if _, err := parsePath(bad); err == nil { t.Errorf("parsePath(%q) accepted", bad) } } } func TestAssertions(t *testing.T) { var doc any _ = json.Unmarshal([]byte(`{"status":"ok","queue":{"depth":12},"healthy":true,"tags":["eu","db"],"version":"1.20"}`), &doc) for _, tc := range []struct { a Assertion ok bool want string }{ {Assertion{Path: "status", Op: "==", Value: "ok"}, true, ""}, {Assertion{Path: "status", Op: "!=", Value: "ok"}, false, `status is "ok", expected != ok`}, {Assertion{Path: "queue.depth", Op: "<", Value: "100"}, true, ""}, {Assertion{Path: "queue.depth", Op: ">=", Value: "20"}, false, "queue.depth is 12, expected >= 20"}, {Assertion{Path: "queue.depth", Op: "==", Value: "12.0"}, true, ""}, {Assertion{Path: "healthy", Op: "==", Value: "true"}, true, ""}, {Assertion{Path: "tags", Op: "contains", Value: "db"}, true, ""}, {Assertion{Path: "version", Op: "contains", Value: "1.2"}, true, ""}, {Assertion{Path: "version", Op: ">", Value: "1"}, false, `version is not a number: "1.20"`}, {Assertion{Path: "error", Op: "absent"}, true, ""}, {Assertion{Path: "queue", Op: "exists"}, true, ""}, {Assertion{Path: "queue.lag", Op: "==", Value: "0"}, false, "queue.lag is missing"}, } { got := tc.a.evaluate(doc) if (got == "") != tc.ok || (tc.want != "" && got != tc.want) { t.Errorf("%+v.evaluate() = %q, want ok=%t %q", tc.a, got, tc.ok, tc.want) } } } func TestJSONValidate(t *testing.T) { ok := `{"assertions":[{"path":"status","op":"==","value":"ok"},{"path":"","op":"==","value":""}]}` cfg, err := Validate(JSON, "https://api.example.com/health", json.RawMessage(ok)) if err != nil { t.Fatalf("Validate() = %v", err) } var c JSONConfig _ = json.Unmarshal(cfg, &c) if len(c.Assertions) != 1 || c.Method != http.MethodGet || c.ExpectStatus[0] != "2xx" { t.Errorf("normalized config = %+v", c) } for body, code := range map[string]string{ `{"assertions":[]}`: "invalid_assertions", `{"assertions":[{"path":"a[","op":"=="}]}`: "invalid_assertion_path", `{"assertions":[{"path":"a","op":"~"}]}`: "invalid_assertion_op", `{"assertions":[{"path":"a","op":">","value":"x"}]}`: "invalid_assertion_value", `{"method":"POST","body":"{","assertions":[{"path":"a","op":"exists"}]}`: "invalid_json_body", } { var inv ErrInvalid if _, err := Validate(JSON, "https://api.example.com", json.RawMessage(body)); !errors.As(err, &inv) || inv.Code != code { t.Errorf("Validate(%s) = %v, want %s", body, err, code) } } } func TestJSONRun(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodPost && r.Header.Get("Content-Type") != "application/json" { http.Error(w, "bad", http.StatusBadRequest) return } if r.Header.Get("Authorization") != "Bearer t" { http.Error(w, "no", http.StatusUnauthorized) return } _, _ = w.Write([]byte(`{"db":{"status":"degraded"}}`)) })) defer srv.Close() run := func(cfg string) Outcome { c, err := Validate(JSON, srv.URL, json.RawMessage(cfg)) if err != nil { t.Fatal(err) } return Run(context.Background(), Spec{Type: JSON, Target: srv.URL, Timeout: 2 * time.Second, Config: c, AllowPrivate: true}) } if o := run(`{"headers":{"Authorization":"Bearer t"},"assertions":[{"path":"db.status","op":"==","value":"degraded"}]}`); !o.OK { t.Errorf("matching assertion failed: %+v", o) } if o := run(`{"method":"POST","body":"{}","headers":{"Authorization":"Bearer t"},"assertions":[{"path":"db.status","op":"==","value":"ok"}]}`); o.OK || !strings.Contains(o.Error, `db.status is "degraded"`) { t.Errorf("failing assertion = %+v", o) } if o := run(`{"assertions":[{"path":"db","op":"exists"}]}`); o.OK || o.StatusCode != http.StatusUnauthorized { t.Errorf("unexpected status = %+v", o) } }