1package toml
2
3import (
4	"testing"
5)
6
7func assertArrayContainsInAnyOrder(t *testing.T, array []interface{}, objects ...interface{}) {
8	if len(array) != len(objects) {
9		t.Fatalf("array contains %d objects but %d are expected", len(array), len(objects))
10	}
11
12	for _, o := range objects {
13		found := false
14		for _, a := range array {
15			if a == o {
16				found = true
17				break
18			}
19		}
20		if !found {
21			t.Fatal(o, "not found in array", array)
22		}
23	}
24}
25
26func TestQueryExample(t *testing.T) {
27	config, _ := Load(`
28      [[book]]
29      title = "The Stand"
30      author = "Stephen King"
31      [[book]]
32      title = "For Whom the Bell Tolls"
33      author = "Ernest Hemmingway"
34      [[book]]
35      title = "Neuromancer"
36      author = "William Gibson"
37    `)
38
39	authors, _ := config.Query("$.book.author")
40	names := authors.Values()
41	if len(names) != 3 {
42		t.Fatalf("query should return 3 names but returned %d", len(names))
43	}
44	assertArrayContainsInAnyOrder(t, names, "Stephen King", "Ernest Hemmingway", "William Gibson")
45}
46
47func TestQueryReadmeExample(t *testing.T) {
48	config, _ := Load(`
49[postgres]
50user = "pelletier"
51password = "mypassword"
52`)
53	results, _ := config.Query("$..[user,password]")
54	values := results.Values()
55	if len(values) != 2 {
56		t.Fatalf("query should return 2 values but returned %d", len(values))
57	}
58	assertArrayContainsInAnyOrder(t, values, "pelletier", "mypassword")
59}
60
61func TestQueryPathNotPresent(t *testing.T) {
62	config, _ := Load(`a = "hello"`)
63	results, err := config.Query("$.foo.bar")
64	if err != nil {
65		t.Fatalf("err should be nil. got %s instead", err)
66	}
67	if len(results.items) != 0 {
68		t.Fatalf("no items should be matched. %d matched instead", len(results.items))
69	}
70}
71