-
Notifications
You must be signed in to change notification settings - Fork 34
/
XMLDocumentTest.java
429 lines (405 loc) · 13.9 KB
/
XMLDocumentTest.java
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
/*
* Copyright (c) 2012-2022, jcabi.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met: 1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer. 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution. 3) Neither the name of the jcabi.com nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jcabi.xml;
import com.jcabi.matchers.XhtmlMatchers;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.lang3.StringUtils;
import org.cactoos.io.TeeInput;
import org.cactoos.scalar.LengthOf;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.hamcrest.core.IsEqual;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* Test case for {@link XMLDocument}.
*
* @since 0.1
* @checkstyle AbbreviationAsWordInNameCheck (5 lines)
* @todo #221:30min Implement XPath 2.0 evaluations.
* We have to implement XPath 2.0 evaluations in order to support more complex XPath queries.
* For example, the following query is not supported:
* //o[@base and @ver]/concat(@base,'|',@ver)
* When we implement XPath 2.0 evaluations, we should remove the @Disabled annotation from
* findsXpathWithFunctionThatReturnsSeveralItems test.
*/
@SuppressWarnings({"PMD.TooManyMethods", "PMD.DoNotUseThreads"})
final class XMLDocumentTest {
@Test
void findsDocumentNodesWithXpath() {
final XML doc = new XMLDocument(
"<r><a>\u0443\u0440\u0430!</a><a>B</a></r>"
);
MatcherAssert.assertThat(
doc.xpath("//a/text()"),
Matchers.hasSize(2)
);
MatcherAssert.assertThat(
doc.xpath("/r/a/text()"),
Matchers.hasItem("\u0443\u0440\u0430!")
);
}
@Test
void findWithXpathListEqualsToJavaUtilList() {
MatcherAssert.assertThat(
new XMLDocument(
"<does><not><matter/></not></does>"
).xpath("//missing/text()"),
new IsEqual<>(
Collections.<String>emptyList()
)
);
MatcherAssert.assertThat(
new XMLDocument(
"<root><item>first</item><item>second</item></root>"
).xpath("//root/item[1]/text()"),
new IsEqual<>(
Collections.singletonList("first")
)
);
MatcherAssert.assertThat(
new XMLDocument(
"<root><item>abc</item><item>def</item></root>"
).xpath("/root/item/text()"),
new IsEqual<>(
Arrays.asList("abc", "def")
)
);
}
@Test
void findsWithXpathAndNamespaces() {
final XML doc = new XMLDocument(
"<html xmlns='http://www.w3.org/1999/xhtml'><div>\u0443\u0440\u0430!</div></html>"
);
MatcherAssert.assertThat(
doc.nodes("/xhtml:html/xhtml:div"),
Matchers.hasSize(1)
);
MatcherAssert.assertThat(
doc.nodes("//xhtml:div[.='\u0443\u0440\u0430!']"),
Matchers.hasSize(1)
);
}
@Test
void findsWithXpathWithCustomNamespace() throws Exception {
final File file = Files.createTempDirectory("")
.resolve("x.xml").toFile();
new LengthOf(
new TeeInput(
"<a xmlns='urn:foo'><b>\u0433!</b></a>",
file
)
).value();
final XML doc = new XMLDocument(file).registerNs("f", "urn:foo");
MatcherAssert.assertThat(
doc.nodes("/f:a/f:b[.='\u0433!']"),
Matchers.hasSize(1)
);
MatcherAssert.assertThat(
doc.xpath("//f:b/text()").get(0),
Matchers.equalTo("\u0433!")
);
}
@Test
void findsDocumentNodesWithXpathAndReturnsThem() throws Exception {
final XML doc = new XMLDocument(
new ByteArrayInputStream(
"<root><a><x>1</x></a><a><x>2</x></a></root>".getBytes()
)
);
MatcherAssert.assertThat(
doc.nodes("//a"),
Matchers.hasSize(2)
);
MatcherAssert.assertThat(
doc.nodes("/root/a").get(0).xpath("x/text()").get(0),
Matchers.equalTo("1")
);
}
@Test
void convertsItselfToXml() {
final XML doc = new XMLDocument("<hello><a/></hello>");
MatcherAssert.assertThat(
doc.toString(),
Matchers.hasToString(XhtmlMatchers.hasXPath("/hello/a"))
);
}
@Test
void retrievesDomNode() throws Exception {
final XML doc = new XMLDocument(
this.getClass().getResource("simple.xml")
);
MatcherAssert.assertThat(
doc.nodes("/root/simple").get(0).node().getNodeName(),
Matchers.equalTo("simple")
);
MatcherAssert.assertThat(
doc.nodes("//simple").get(0).node().getNodeType(),
Matchers.equalTo(Node.ELEMENT_NODE)
);
}
@Test
void throwsCustomExceptionWhenXpathNotFound() {
try {
new XMLDocument("<root/>").xpath("/absent-node/text()").get(0);
MatcherAssert.assertThat("exception expected here", false);
} catch (final IndexOutOfBoundsException ex) {
MatcherAssert.assertThat(
ex.getMessage(),
Matchers.allOf(
Matchers.containsString("/absent-node/text("),
Matchers.containsString("<root/")
)
);
}
}
@Test
void throwsWhenXpathQueryIsBroken() {
try {
new XMLDocument("<root-99/>").xpath("/*/hello()");
MatcherAssert.assertThat("exception expected", false);
} catch (final IllegalArgumentException ex) {
MatcherAssert.assertThat(
ex.getMessage(),
Matchers.containsString("XPathFactoryImpl")
);
}
}
@Test
void preservesProcessingInstructions() {
MatcherAssert.assertThat(
new XMLDocument("<?xml version='1.0'?><?x test?><a/>"),
Matchers.hasToString(Matchers.containsString("<?x test?>"))
);
}
@Test
void preservesDomStructureWhenXpath() {
final XML doc = new XMLDocument(
"<root><item1/><item2/><item3/></root>"
);
final XML item = doc.nodes("//root/item2").get(0);
MatcherAssert.assertThat(
item.nodes("..").get(0).xpath("name()").get(0),
Matchers.equalTo("root")
);
}
@Test
void printsWithAndWithoutXmlHeader() {
final XML doc = new XMLDocument("<hey/>");
MatcherAssert.assertThat(
doc,
Matchers.hasToString(Matchers.startsWith("<?xml "))
);
MatcherAssert.assertThat(
doc.nodes("/*").get(0),
Matchers.hasToString(Matchers.startsWith("<hey"))
);
}
@Test
void parsesInMultipleThreads() throws Exception {
final int timeout = 10;
final int loop = 100;
final Runnable runnable = () -> MatcherAssert.assertThat(
new XMLDocument("<root><hey/></root>"),
XhtmlMatchers.hasXPath("/root/hey")
);
final ExecutorService service = Executors.newFixedThreadPool(5);
for (int count = 0; count < loop; count += 1) {
service.submit(runnable);
}
service.shutdown();
MatcherAssert.assertThat(
service.awaitTermination(timeout, TimeUnit.SECONDS),
Matchers.is(true)
);
service.shutdownNow();
}
@Test
void xpathInMultipleThreads() throws Exception {
final int timeout = 30;
final int repeat = 1000;
final int loop = 50;
final XML xml = new XMLDocument(
String.format(
"<a><b>test text</b><c>%s</c></a>",
StringUtils.repeat(
"<beta>some text \u20ac</beta> ",
repeat
)
)
);
final Runnable runnable = () -> {
MatcherAssert.assertThat(
xml.xpath("/a/b/text()").get(0),
Matchers.equalTo("test text")
);
MatcherAssert.assertThat(
xml.nodes("/a").get(0).nodes("c"),
Matchers.iterableWithSize(1)
);
};
final ExecutorService service = Executors.newFixedThreadPool(5);
for (int count = 0; count < loop; count += 1) {
service.submit(runnable);
}
service.shutdown();
MatcherAssert.assertThat(
service.awaitTermination(timeout, TimeUnit.SECONDS),
Matchers.is(true)
);
service.shutdownNow();
}
@Test
void printsInMultipleThreads() throws Exception {
final int repeat = 1000;
final int loop = 50;
final XML xml = new XMLDocument(
String.format(
"<root><data>%s</data></root>",
StringUtils.repeat(
"<alpha>some text \u20ac</alpha> ",
repeat
)
)
);
final AtomicInteger done = new AtomicInteger();
final Runnable runnable = () -> {
MatcherAssert.assertThat(
xml.toString(),
XhtmlMatchers.hasXPath("/root/data/alpha")
);
done.incrementAndGet();
};
final ExecutorService service = Executors.newFixedThreadPool(5);
for (int count = 0; count < loop; count += 1) {
service.submit(runnable);
}
service.shutdown();
while (true) {
if (done.get() == loop) {
break;
}
if (service.awaitTermination(1L, TimeUnit.MILLISECONDS)) {
break;
}
}
MatcherAssert.assertThat(
service.awaitTermination(1L, TimeUnit.SECONDS),
Matchers.is(true)
);
service.shutdownNow();
}
@Test
void performsXpathCalculations() {
final XML xml = new XMLDocument("<x><a/><a/><a/></x>");
MatcherAssert.assertThat(
xml.xpath("count(//x/a)"),
Matchers.iterableWithSize(1)
);
MatcherAssert.assertThat(
xml.xpath("count(//a)").get(0),
Matchers.equalTo("3")
);
}
@Test
void buildsDomNode() {
final XML doc = new XMLDocument("<?xml version='1.0'?><f/>");
MatcherAssert.assertThat(
doc.node(),
Matchers.instanceOf(Document.class)
);
MatcherAssert.assertThat(
doc.nodes("/f").get(0).node(),
Matchers.instanceOf(Element.class)
);
}
@Test
void comparesToAnotherDocument() {
MatcherAssert.assertThat(
new XMLDocument("<hi>\n<dude> </dude></hi>"),
Matchers.equalTo(new XMLDocument("<hi><dude> </dude></hi>"))
);
MatcherAssert.assertThat(
new XMLDocument("<hi><man></man></hi>"),
Matchers.not(
Matchers.equalTo(new XMLDocument("<hi><man> </man></hi>"))
)
);
}
@Test
void preservesXmlNamespaces() {
final String xml = "<a xmlns='http://www.w3.org/1999/xhtml'><b/></a>";
MatcherAssert.assertThat(
new XMLDocument(xml),
XhtmlMatchers.hasXPath("/xhtml:a/xhtml:b")
);
}
@Test
void preservesImmutability() {
final XML xml = new XMLDocument("<r1><a/></r1>");
final Node node = xml.nodes("/r1/a").get(0).node();
node.appendChild(node.getOwnerDocument().createElement("h9"));
MatcherAssert.assertThat(
xml,
XhtmlMatchers.hasXPath("/r1/a[not(h9)]")
);
}
@Test
void appliesXpathToClonedNode() {
final XML xml = new XMLDocument("<t6><z9 a='433'/></t6>");
final XML root = xml.nodes("/t6").get(0);
MatcherAssert.assertThat(
root.xpath("//z9/@a").get(0),
Matchers.equalTo("433")
);
}
@Test
@Disabled
void findsXpathWithFunctionThatReturnsSeveralItems() {
MatcherAssert.assertThat(
"XMLDocument can handle XPath 2.0 feature - XPath evaluation of concat method, but it can't",
new XMLDocument(
"<o><o base='a' ver='1'/><o base='b' ver='2'/></o>"
).xpath("//o[@base and @ver]/concat(@base,'|',@ver)"),
Matchers.hasItems("a|1", "b|2")
);
}
}