38 lines
984 B
Go
38 lines
984 B
Go
package clip
|
|
|
|
import "testing"
|
|
|
|
func TestExtractJSONObject(t *testing.T) {
|
|
cases := []struct {
|
|
name string
|
|
in string
|
|
want string
|
|
}{
|
|
{"raw json", `{"a":1}`, `{"a":1}`},
|
|
{"with prose", "Sure, here you go:\n{\"a\":1}\nThanks", `{"a":1}`},
|
|
{"with fence", "```json\n{\"a\":1}\n```", `{"a":1}`},
|
|
{"nested", `prelude {"a":{"b":2},"c":3} trailing`, `{"a":{"b":2},"c":3}`},
|
|
{"brace in string", `{"text":"hello {world}"}`, `{"text":"hello {world}"}`},
|
|
}
|
|
for _, c := range cases {
|
|
t.Run(c.name, func(t *testing.T) {
|
|
got, err := extractJSONObject(c.in)
|
|
if err != nil {
|
|
t.Fatalf("err: %v", err)
|
|
}
|
|
if got != c.want {
|
|
t.Errorf("got %q want %q", got, c.want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestExtractJSONObjectMissing(t *testing.T) {
|
|
if _, err := extractJSONObject("no json here"); err == nil {
|
|
t.Error("expected error for missing JSON")
|
|
}
|
|
if _, err := extractJSONObject(`{"unterminated":`); err == nil {
|
|
t.Error("expected error for unbalanced braces")
|
|
}
|
|
}
|