<- Back to shtanton's homepage
aboutsummaryrefslogtreecommitdiff
path: root/json/write_test.go
blob: 508ccfa33da446e80b9e826dc06f068d4253787d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
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)
		}
	}
}