package json import ( "bufio" "main/walk" "strings" "testing" ) func TestNavigateTo(t *testing.T) { type testCase struct { fromPath []walk.PathSegment fromState JSONWriterState toKeep int toPath []walk.PathSegment toState JSONWriterState expected string } tests := []testCase { { fromPath: []walk.PathSegment{}, fromState: JSONWriterStateBeforeValue, toKeep: 0, toPath: []walk.PathSegment{"a", "b", "c"}, toState: JSONWriterStateBeforeValue, expected: `{"a":{"b":{"c":`, }, { fromPath: []walk.PathSegment{}, fromState: JSONWriterStateBeforeValue, toKeep: 0, toPath: []walk.PathSegment{0, "a", "a", 0, 1}, toState: JSONWriterStateInMap, expected: `[{"a":{"a":[[{`, }, { fromPath: []walk.PathSegment{}, fromState: JSONWriterStateInMap, toKeep: 0, toPath: []walk.PathSegment{}, toState: JSONWriterStateInArray, expected: "}\n[", }, { fromPath: []walk.PathSegment{0, 0}, fromState: JSONWriterStateBeforeValue, toKeep: 2, toPath: []walk.PathSegment{"a"}, toState: JSONWriterStateInArray, expected: `{"a":[`, }, { fromPath: []walk.PathSegment{"a", "b"}, fromState: JSONWriterStateAfterValue, toKeep: 1, toPath: []walk.PathSegment{"c"}, toState: JSONWriterStateBeforeValue, expected: `,"c":`, }, { fromPath: []walk.PathSegment{0, "a"}, fromState: JSONWriterStateInArray, toKeep: 0, toPath: []walk.PathSegment{"b", 1}, toState: JSONWriterStateInMap, expected: `]}]` + "\n" + `{"b":[{`, }, { fromPath: []walk.PathSegment{"a", "b", "c", "d", "e"}, fromState: JSONWriterStateAfterValue, toKeep: 2, toPath: []walk.PathSegment{"f", "g", "h"}, toState: JSONWriterStateBeforeValue, expected: `}},"f":{"g":{"h":`, }, { fromPath: []walk.PathSegment{"a", 0, "b"}, fromState: JSONWriterStateAfterValue, toKeep: 2, toPath: []walk.PathSegment{0}, toState: JSONWriterStateBeforeValue, expected: `},[`, }, } for i, test := range tests { var writer strings.Builder jsonWriter := &JSONWriter { path: test.fromPath, writer: bufio.NewWriter(&writer), state: test.fromState, } jsonWriter.navigateTo( test.toKeep, test.toPath, test.toState, ) jsonWriter.writer.Flush() res := writer.String() if res != test.expected { t.Errorf(`Test %d: Expected '%s' found '%s'`, i, test.expected, res) } } }