diff options
| author | Felix Hanley <felix@userspace.com.au> | 2018-11-20 00:54:42 +0000 |
|---|---|---|
| committer | Felix Hanley <felix@userspace.com.au> | 2018-11-20 04:43:29 +0000 |
| commit | 505c75b306322a22aef900aac636100eab556be9 (patch) | |
| tree | ca0af0d717a34efe10a890dced90898fc2a153e7 /jsonpath/parser_test.go | |
| parent | bbf5d9bb88ee4fe955d810e90aa90c302e1dc02d (diff) | |
| download | query-505c75b306322a22aef900aac636100eab556be9.tar.gz query-505c75b306322a22aef900aac636100eab556be9.tar.bz2 | |
Jsonpath WIP
Diffstat (limited to 'jsonpath/parser_test.go')
| -rw-r--r-- | jsonpath/parser_test.go | 92 |
1 files changed, 92 insertions, 0 deletions
diff --git a/jsonpath/parser_test.go b/jsonpath/parser_test.go new file mode 100644 index 0000000..2406651 --- /dev/null +++ b/jsonpath/parser_test.go @@ -0,0 +1,92 @@ +package jsonpath + +import ( + //"fmt" + "strings" + "testing" + + "src.userspace.com.au/query/json" +) + +func TestParse(t *testing.T) { + tests := []struct { + path, src, expect string + }{ + { + path: "$", + src: `{"test":"one"}`, + expect: "one", + }, + { + path: "$.test", + src: `{"test":"one"}`, + expect: "one", + }, + { + path: "$.a.b", + src: `{"a":{"b":"two"}}`, + expect: "two", + }, + { + path: "$.a.b.c", + src: `{"a":{"b":{"c":"two"}}}`, + expect: "two", + }, + { + path: "$.a.b", + src: `{"fail":{"a":"one"},"a":{"b":"three"}}`, + expect: "three", + }, + { + path: "$.test.test", + src: `{"fail":{"test1":"one"},"test1":{"test3":"two"}}`, + expect: "", + }, + { + path: "$..test", + src: `{"fail":{"test1":{"test":"two"}}}`, + expect: "two", + }, + { + path: "$.a.b.c.d", + src: `{"a":{"b":{"c":{"d":"blah"}}}}`, + expect: "blah", + }, + { + path: "$.test[2]", + src: `{"test":[1,"two","three"]}`, + expect: "three", + }, + { + path: "$.*", + src: `{"test":"one"}`, + expect: "one", + }, + } + + p := Parser{} + + for _, tt := range tests { + doc, err := json.Parse(strings.NewReader(tt.src)) + if err != nil { + t.Fatalf("json.Parse(%q) failed: %s", tt.src, err) + } + //doc.PrintTree(0) + + sel, err := p.Parse(tt.path) + if err != nil { + t.Fatalf("Parse(%q) failed: %s", tt.path, err) + } + actualText := "" + actual := sel.MatchFirst(doc) + if actual != nil { + actualText = actual.InnerText() + } + + if tt.expect == "" && actualText != "" { + t.Fatalf("MatchFirst(%s) => %s, expected nothing", tt.src, actualText) + } else if actualText != tt.expect { + t.Fatalf("MatchFirst(%s) => %s, expected %s", tt.src, actualText, tt.expect) + } + } +} |
