-
Notifications
You must be signed in to change notification settings - Fork 13
/
gosax_test.go
125 lines (111 loc) · 2.36 KB
/
gosax_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
116
117
118
119
120
121
122
123
124
125
// Tests.
//
// Eli Bendersky [https://eli.thegreenplace.net]
// This code is in the public domain.
package gosax
import (
"bytes"
"strings"
"testing"
)
func TestInit(*testing.T) {
// Test that nothing crashed in init()
}
func TestBasic(t *testing.T) {
var plantId string
var numOrigins int
var startDoc bool
var endDoc bool
scb := SaxCallbacks{
StartDocument: func() {
startDoc = true
},
EndDocument: func() {
endDoc = true
},
StartElement: func(name string, attrs []string) {
if name == "plant" {
if len(attrs) < 2 {
t.Errorf("want len(attrs) at least 2, got %v", len(attrs))
}
if attrs[0] != "id" {
t.Errorf("want 'id' attr, got %v", attrs[0])
}
plantId = attrs[1]
} else if name == "origin" {
numOrigins++
}
},
EndElement: func(name string) {
},
}
err := ParseFile("testfiles/fruit.xml", scb)
if err != nil {
panic(err)
}
if plantId != "27" {
t.Errorf("want plant id %v, got %v", 27, plantId)
}
if numOrigins != 2 {
t.Errorf("want num origins 2, got %v", numOrigins)
}
if !startDoc {
t.Errorf("want doc start, found none")
}
if !endDoc {
t.Errorf("want doc end, found none")
}
}
func TestCharacters(t *testing.T) {
m := make(map[string]bool)
scb := SaxCallbacks{
Characters: func(contents string) {
m[contents] = true
},
}
err := ParseFile("testfiles/fruit.xml", scb)
if err != nil {
panic(err)
}
chars := []string{"Coffee", "Ethiopia", "Brazil"}
for _, c := range chars {
if _, ok := m[c]; !ok {
t.Errorf("expected to find %v characters", c)
}
}
}
func TestError(t *testing.T) {
scb := SaxCallbacks{}
err := ParseFile("testfiles/badfile.xml", scb)
if err == nil {
t.Errorf("want non-nil error")
}
if !strings.Contains(err.Error(), "Start tag expected") {
t.Errorf("want start tag error, got '%v'", err)
}
}
func TestMemParse(t *testing.T) {
m := make(map[string]bool)
scb := SaxCallbacks{
Characters: func(contents string) {
m[contents] = true
},
}
buf := bytes.Buffer{}
buf.WriteString(`<?xml version="1.0" encoding="UTF-8"?>
<plant id="27">
<name>Coffee</name>
<origin>Ethiopia</origin>
<origin>Brazil</origin>
</plant>`)
err := ParseMem(buf, scb)
if err != nil {
panic(err)
}
chars := []string{"Coffee", "Ethiopia", "Brazil"}
for _, c := range chars {
if _, ok := m[c]; !ok {
t.Errorf("expected to find %v characters", c)
}
}
}