-
Notifications
You must be signed in to change notification settings - Fork 209
/
Copy pathSWXMLHashSpecs.swift
320 lines (262 loc) · 14.7 KB
/
SWXMLHashSpecs.swift
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
//
// SWXMLHashTests.swift
//
// Copyright (c) 2014 David Mohundro
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import SWXMLHash
import Quick
import Nimble
// swiftlint:disable force_unwrapping
// swiftlint:disable force_try
// swiftlint:disable line_length
// swiftlint:disable function_body_length
class SWXMLHashTests: QuickSpec {
override func spec() {
let xmlToParse = "<root><header>header mixed content<title>Test Title Header</title>more mixed content</header><catalog><book id=\"bk101\"><author>Gambardella, Matthew</author><title>XML Developer's Guide</title><genre>Computer</genre><price>44.95</price><publish_date>2000-10-01</publish_date><description>An in-depth look at creating applications with XML.</description></book><book id=\"bk102\"><author>Ralls, Kim</author><title>Midnight Rain</title><genre>Fantasy</genre><price>5.95</price><publish_date>2000-12-16</publish_date><description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description></book><book id=\"bk103\"><author>Corets, Eva</author><title>Maeve Ascendant</title><genre>Fantasy</genre><price>5.95</price><publish_date>2000-11-17</publish_date><description>After the collapse of a nanotechnology society in England, the young survivors lay the foundation for a new society.</description></book></catalog></root>"
var xml: XMLIndexer?
beforeEach {
xml = SWXMLHash.parse(xmlToParse)
}
describe("xml parsing") {
it("should be able to parse individual elements") {
expect(xml!["root"]["header"]["title"].element?.text).to(equal("Test Title Header"))
}
it("should be able to parse element groups") {
expect(xml!["root"]["catalog"]["book"][1]["author"].element?.text).to(equal("Ralls, Kim"))
}
it("should be able to parse attributes") {
expect(xml!["root"]["catalog"]["book"][1].element?.attributes["id"]).to(equal("bk102"))
}
it("should be able to look up elements by name and attribute") {
expect(try! xml!["root"]["catalog"]["book"].withAttr("id", "bk102")["author"].element?.text).to(equal("Ralls, Kim"))
}
it("should be able to iterate element groups") {
let result = xml!["root"]["catalog"]["book"].all.map({ $0["genre"].element!.text! }).joinWithSeparator(", ")
expect(result).to(equal("Computer, Fantasy, Fantasy"))
}
it("should be able to iterate element groups even if only one element is found") {
expect(xml!["root"]["header"]["title"].all.count).to(equal(1))
}
it("should be able to index element groups even if only one element is found") {
expect(xml!["root"]["header"]["title"][0].element?.text).to(equal("Test Title Header"))
}
it("should be able to iterate using for-in") {
var count = 0
for _ in xml!["root"]["catalog"]["book"] {
count++
}
expect(count).to(equal(3))
}
it("should be able to enumerate children") {
let result = xml!["root"]["catalog"]["book"][0].children.map({ $0.element!.name }).joinWithSeparator(", ")
expect(result).to(equal("author, title, genre, price, publish_date, description"))
}
it("should be able to handle mixed content") {
expect(xml!["root"]["header"].element?.text).to(equal("header mixed contentmore mixed content"))
}
it("should handle interleaving XML elements") {
let interleavedXml = "<html><body><p>one</p><div>two</div><p>three</p><div>four</div></body></html>"
let parsed = SWXMLHash.parse(interleavedXml)
let result = parsed["html"]["body"].children.map({ $0.element!.text! }).joinWithSeparator(", ")
expect(result).to(equal("one, two, three, four"))
}
it("should be able to provide a description for the document") {
let descriptionXml = "<root><foo><what id=\"myId\">puppies</what></foo></root>"
let parsed = SWXMLHash.parse(descriptionXml)
expect(parsed.description).to(equal("<root><foo><what id=\"myId\">puppies</what></foo></root>"))
}
}
describe("white space parsing") {
var xml: XMLIndexer?
beforeEach {
let bundle = NSBundle(forClass: SWXMLHashTests.self)
let path = bundle.pathForResource("test", ofType: "xml")
let data = NSData(contentsOfFile: path!)
xml = SWXMLHash.parse(data!)
}
it("should be able to pull text between elements without whitespace (issue #6)") {
expect(xml!["niotemplate"]["section"][0]["constraint"][1].element?.text).to(equal("H:|-15-[title]-15-|"))
}
it("should be able to correctly parse CDATA sections *with* whitespace") {
expect(xml!["niotemplate"]["other"].element?.text).to(equal("\n \n this\n has\n white\n space\n \n "))
}
}
describe("xml parsing error scenarios") {
it("should return nil when keys don't match") {
expect(xml!["root"]["what"]["header"]["foo"].element?.name).to(beNil())
}
it("should provide an error object when keys don't match") {
var err: XMLIndexer.Error?
defer {
expect(err).toNot(beNil())
}
do {
try xml!.byKey("root").byKey("what").byKey("header").byKey("foo")
} catch let error as XMLIndexer.Error {
err = error
} catch { err = nil }
}
it("should provide an error element when indexers don't match") {
var err: XMLIndexer.Error?
defer {
expect(err).toNot(beNil())
}
do {
try xml!.byKey("what").byKey("subelement").byIndex(5).byKey("nomatch")
} catch let error as XMLIndexer.Error {
err = error
} catch { err = nil }
}
it("should still return errors when accessing via subscripting") {
var err: XMLIndexer.Error? = nil
switch xml!["what"]["subelement"][5]["nomatch"] {
case .XMLError(let error):
err = error
default:
err = nil
}
expect(err).toNot(beNil())
}
}
describe("mixed text with XML elements") {
var xml: XMLIndexer?
beforeEach {
let xmlContent = "<everything><news><content>Here is a cool thing <a href=\"google.com\">A</a> and second cool thing <a href=\"fb.com\">B</a></content></news></everything>"
xml = SWXMLHash.parse(xmlContent)
}
it("should be able to get all contents inside of an element") {
expect(xml!["everything"]["news"]["content"].description).to(equal("<content>Here is a cool thing <a href=\"google.com\">A</a> and second cool thing <a href=\"fb.com\">B</a></content>"))
}
}
}
}
class SWXMLHashLazyTests: QuickSpec {
override func spec() {
let xmlToParse = "<root><header>header mixed content<title>Test Title Header</title>more mixed content</header><catalog><book id=\"bk101\"><author>Gambardella, Matthew</author><title>XML Developer's Guide</title><genre>Computer</genre><price>44.95</price><publish_date>2000-10-01</publish_date><description>An in-depth look at creating applications with XML.</description></book><book id=\"bk102\"><author>Ralls, Kim</author><title>Midnight Rain</title><genre>Fantasy</genre><price>5.95</price><publish_date>2000-12-16</publish_date><description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description></book><book id=\"bk103\"><author>Corets, Eva</author><title>Maeve Ascendant</title><genre>Fantasy</genre><price>5.95</price><publish_date>2000-11-17</publish_date><description>After the collapse of a nanotechnology society in England, the young survivors lay the foundation for a new society.</description></book></catalog></root>"
var xml: XMLIndexer?
beforeEach {
xml = SWXMLHash.config { config in config.shouldProcessLazily = true }.parse(xmlToParse)
}
describe("lazy xml parsing") {
it("should be able to parse individual elements") {
expect(xml!["root"]["header"]["title"].element?.text).to(equal("Test Title Header"))
}
it("should be able to parse element groups") {
expect(xml!["root"]["catalog"]["book"][1]["author"].element?.text).to(equal("Ralls, Kim"))
}
it("should be able to parse attributes") {
expect(xml!["root"]["catalog"]["book"][1].element?.attributes["id"]).to(equal("bk102"))
}
it("should be able to look up elements by name and attribute") {
expect(try! xml!["root"]["catalog"]["book"].withAttr("id", "bk102")["author"].element?.text).to(equal("Ralls, Kim"))
}
it("should be able to iterate element groups") {
let result = xml!["root"]["catalog"]["book"].all.map({ $0["genre"].element?.text ?? "" }).joinWithSeparator(", ")
expect(result).to(equal("Computer, Fantasy, Fantasy"))
}
it("should be able to iterate element groups even if only one element is found") {
expect(xml!["root"]["header"]["title"].all.count).to(equal(1))
}
it("should be able to index element groups even if only one element is found") {
expect(xml!["root"]["header"]["title"][0].element?.text).to(equal("Test Title Header"))
}
it("should be able to iterate using for-in") {
var count = 0
for _ in xml!["root"]["catalog"]["book"] {
count++
}
expect(count).to(equal(3))
}
it("should be able to enumerate children") {
let result = xml!["root"]["catalog"]["book"][0].children.map({ $0.element?.name ?? "" }).joinWithSeparator(", ")
expect(result).to(equal("author, title, genre, price, publish_date, description"))
}
it("should be able to handle mixed content") {
expect(xml!["root"]["header"].element?.text).to(equal("header mixed contentmore mixed content"))
}
it("should handle interleaving XML elements") {
let interleavedXml = "<html><body><p>one</p><div>two</div><p>three</p><div>four</div></body></html>"
let parsed = SWXMLHash.lazy(interleavedXml)
let result = parsed["html"]["body"].children.map({ $0.element?.text ?? "" }).joinWithSeparator(", ")
expect(result).to(equal("one, two, three, four"))
}
}
describe("white space parsing") {
var xml: XMLIndexer?
beforeEach {
let bundle = NSBundle(forClass: SWXMLHashTests.self)
let path = bundle.pathForResource("test", ofType: "xml")
let data = NSData(contentsOfFile: path!)
xml = SWXMLHash.lazy(data!)
}
it("should be able to pull text between elements without whitespace (issue #6)") {
expect(xml!["niotemplate"]["section"][0]["constraint"][1].element?.text).to(equal("H:|-15-[title]-15-|"))
}
it("should be able to correctly parse CDATA sections *with* whitespace") {
expect(xml!["niotemplate"]["other"].element?.text).to(equal("\n \n this\n has\n white\n space\n \n "))
}
}
describe("xml parsing error scenarios") {
it("should return nil when keys don't match") {
expect(xml!["root"]["what"]["header"]["foo"].element?.name).to(beNil())
}
}
}
}
class SWXMLHashConfigSpecs: QuickSpec {
override func spec() {
describe("optional configuration options for NSXMLParser") {
var parser: XMLIndexer?
let xmlWithNamespace = "<root xmlns:h=\"http://www.w3.org/TR/html4/\"" +
" xmlns:f=\"http://www.w3schools.com/furniture\">" +
" <h:table>" +
" <h:tr>" +
" <h:td>Apples</h:td>" +
" <h:td>Bananas</h:td>" +
" </h:tr>" +
" </h:table>" +
"</root>"
beforeEach {
parser = SWXMLHash.config { conf in
conf.shouldProcessNamespaces = true
}.parse(xmlWithNamespace)
}
it("should allow processing namespaces or not") {
expect(parser!["root"]["table"]["tr"]["td"][0].element?.text).to(equal("Apples"))
}
}
}
}
class CrashSpecs: QuickSpec {
override func spec() {
describe("byte order mark crash testing") {
var xml: XMLIndexer?
beforeEach {
let bundle = NSBundle(forClass: SWXMLHashTests.self)
let path = bundle.pathForResource("bom-test", ofType: "xml")
let data = NSData(contentsOfFile: path!)
xml = SWXMLHash.lazy(data!)
}
it("should not explode") {
expect(true)
}
}
}
}