| 1 |
// Copyright (c) 2020, Maxime Soulé |
| 2 |
// All rights reserved. |
| 3 |
// |
| 4 |
// This source code is licensed under the BSD-style license found in the |
| 5 |
// LICENSE file in the root directory of this source tree. |
| 6 |
|
| 7 |
package util_test |
| 8 |
|
| 9 |
import ( |
| 10 |
"encoding/json" |
| 11 |
"reflect" |
| 12 |
"testing" |
| 13 |
|
| 14 |
"github.com/maxatome/go-testdeep/internal/util" |
| 15 |
) |
| 16 |
|
| 17 |
func TestJSONPointer(t *testing.T) { |
| 18 |
var ref any |
| 19 |
err := json.Unmarshal([]byte(` |
| 20 |
{ |
| 21 |
"foo": ["bar", "baz"], |
| 22 |
"": 0, |
| 23 |
"a/b": 1, |
| 24 |
"c%d": 2, |
| 25 |
"e^f": 3, |
| 26 |
"g|h": 4, |
| 27 |
"i\\j": 5, |
| 28 |
"k\"l": 6, |
| 29 |
" ": 7, |
| 30 |
"m~n": 8 |
| 31 |
}`), |
| 32 |
&ref) |
| 33 |
if err != nil { |
| 34 |
t.Fatalf("json.Unmarshal failed: %s", err) |
| 35 |
} |
| 36 |
|
| 37 |
checkOK := func(pointer string, expected any) { |
| 38 |
t.Helper() |
| 39 |
|
| 40 |
got, err := util.JSONPointer(ref, pointer) |
| 41 |
if !reflect.DeepEqual(got, expected) { |
| 42 |
t.Errorf("got: %v expected: %v", got, expected) |
| 43 |
} |
| 44 |
if err != nil { |
| 45 |
t.Errorf("error <%s> received instead of nil", err) |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
checkErr := func(pointer, errExpected string) { |
| 50 |
t.Helper() |
| 51 |
|
| 52 |
got, err := util.JSONPointer(ref, pointer) |
| 53 |
if got != nil { |
| 54 |
t.Errorf("got: %v expected: nil", got) |
| 55 |
} |
| 56 |
if err == nil { |
| 57 |
t.Errorf("error nil received instead of <%s>", errExpected) |
| 58 |
} else if err.Error() != errExpected { |
| 59 |
t.Errorf("error <%s> received instead of <%s>", err, errExpected) |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
checkOK(``, ref) |
| 64 |
checkOK(`/foo`, []any{"bar", "baz"}) |
| 65 |
checkOK(`/foo/0`, "bar") |
| 66 |
checkOK(`/`, float64(0)) |
| 67 |
checkOK(`/a~1b`, float64(1)) |
| 68 |
checkOK(`/c%d`, float64(2)) |
| 69 |
checkOK(`/e^f`, float64(3)) |
| 70 |
checkOK(`/g|h`, float64(4)) |
| 71 |
checkOK(`/i\j`, float64(5)) |
| 72 |
checkOK(`/k"l`, float64(6)) |
| 73 |
checkOK(`/ `, float64(7)) |
| 74 |
checkOK(`/m~0n`, float64(8)) |
| 75 |
|
| 76 |
checkErr("x", "invalid JSON pointer") |
| 77 |
checkErr("/8", "key not found @/8") |
| 78 |
checkErr("/foo/-1/pipo", "array but not an index in JSON pointer @/foo/-1") |
| 79 |
checkErr("/foo/bingo/pipo", "array but not an index in JSON pointer @/foo/bingo") |
| 80 |
checkErr("/foo/2/pipo", "out of array range @/foo/2") |
| 81 |
checkErr("/foo/1/pipo", "not a map nor an array @/foo/1/pipo") |
| 82 |
} |