-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
iter_test.go
115 lines (104 loc) · 2.56 KB
/
iter_test.go
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
106
107
108
109
110
111
112
113
114
115
// Copyright 2019 The Mellium Contributors.
// Use of this source code is governed by the BSD 2-clause
// license that can be found in the LICENSE file.
package xmlstream_test
import (
"encoding/xml"
"fmt"
"io"
"strconv"
"strings"
"testing"
"mellium.im/xmlstream"
)
var iterTests = [...]struct {
in string
out [][]xml.Token
err error
}{
0: {in: `<a></a>`},
1: {
in: `<nums><a>1</a><foo/></nums>`,
out: [][]xml.Token{
{aStart, xml.CharData("1"), aStart.End()},
{fooStart, fooStart.End()},
},
},
2: {
in: `<nums><a/>CHAR<a/></nums>`,
out: [][]xml.Token{
{aStart, aStart.End()},
{xml.CharData("CHAR")},
{aStart, aStart.End()},
},
},
}
func TestIter(t *testing.T) {
for i, tc := range iterTests {
t.Run(strconv.Itoa(i), func(t *testing.T) {
i := i
_ = i
d := xml.NewDecoder(strings.NewReader(tc.in))
// Discard the opening tag.
if _, err := d.Token(); err != nil {
t.Fatalf("Error popping initial token: %q", err)
}
iter := xmlstream.NewIter(d)
out := [][]xml.Token{}
for iter.Next() {
start, r := iter.Current()
toks, err := xmlstream.ReadAll(r)
if err != nil {
t.Fatalf("Error reading tokens: %q", err)
}
if start != nil {
toks = append([]xml.Token{start.Copy()}, toks...)
}
out = append(out, toks)
}
if err := iter.Err(); err != tc.err {
t.Errorf("Wrong error: want=%q, got=%q", tc.err, err)
}
if err := iter.Close(); err != nil {
t.Errorf("Error closing iter: %q", err)
}
// Check that the entire token stream was consumed and we didn't leave it
// in a partially consumed state.
if tok, err := d.Token(); err != io.EOF || tok != nil {
t.Errorf("Expected token stream to be consumed, got token %+v, with err %q", tok, err)
}
// Don't try to compare nil and empty slice with DeepEqual
if len(out) == 0 && len(tc.out) == 0 {
return
}
if fmt.Sprintf("%#v", out) != fmt.Sprintf("%#v", tc.out) {
t.Errorf("Wrong output:\nwant=\n%#v,\ngot=\n%#v", tc.out, out)
}
})
}
}
type recordCloser struct {
called bool
}
func (c *recordCloser) Close() error {
c.called = true
return nil
}
func TestIterClosesInner(t *testing.T) {
recorder := &recordCloser{}
rc := struct {
xml.TokenReader
io.Closer
}{
TokenReader: xml.NewDecoder(strings.NewReader(`<nums><int>1</int><foo/></nums>`)),
Closer: recorder,
}
iter := xmlstream.NewIter(rc)
err := iter.Close()
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if !recorder.called {
t.Errorf("Expected iter to close the inner reader if it is a TokenReadCloser")
}
}