1
2
3
4
5 package com.jcabi.http.response;
6
7 import com.jcabi.http.Response;
8 import com.jcabi.http.request.FakeRequest;
9 import com.jcabi.xml.XML;
10 import org.apache.commons.lang3.StringUtils;
11 import org.hamcrest.MatcherAssert;
12 import org.hamcrest.Matchers;
13 import org.junit.jupiter.api.Test;
14
15
16
17
18
19
20 @SuppressWarnings("PMD.TooManyMethods")
21 final class XmlResponseTest {
22
23
24
25
26
27 @Test
28 void findsDocumentNodesWithXpath() throws Exception {
29 final XmlResponse response = new XmlResponse(
30 new FakeRequest()
31 .withBody("<r><a>\u0443\u0440\u0430!</a><a>B</a></r>")
32 .fetch()
33 );
34 MatcherAssert.assertThat(
35 "should be equal 2",
36 response.xml().xpath("//a/text()"),
37 Matchers.hasSize(2)
38 );
39 MatcherAssert.assertThat(
40 "should contains '\u0443\u0440\u0430'",
41 response.xml().xpath("/r/a/text()"),
42 Matchers.hasItem("\u0443\u0440\u0430!")
43 );
44 }
45
46
47
48
49
50 @Test
51 void assertsWithXpath() throws Exception {
52 final Response resp = new FakeRequest()
53 .withBody("<x a='1'><!-- hi --><y>\u0443\u0440\u0430!</y></x>")
54 .fetch();
55 new XmlResponse(resp)
56 .assertXPath("//y[.='\u0443\u0440\u0430!']")
57 .assertXPath("/x/@a")
58 .assertXPath("/x/comment()")
59 .assertXPath("/x/y[contains(.,'\u0430')]");
60 }
61
62
63
64
65
66 @Test
67 void assertsWithXpathAndNamespaces() throws Exception {
68 final Response resp = new FakeRequest().withBody(
69 StringUtils.join(
70 "<html xmlns='http://www.w3.org/1999/xhtml'>",
71 "<div>\u0443\u0440\u0430!</div></html>"
72 )
73 ).fetch();
74 new XmlResponse(resp)
75 .assertXPath("/xhtml:html/xhtml:div")
76 .assertXPath("//xhtml:div[.='\u0443\u0440\u0430!']");
77 }
78
79
80
81
82
83 @Test
84 void assertsWithXpathWithCustomNamespace() throws Exception {
85 final XmlResponse response = new XmlResponse(
86 new FakeRequest()
87 .withBody("<a xmlns='urn:foo'><b>yes!</b></a>")
88 .fetch()
89 ).registerNs("foo", "urn:foo");
90 final XML xml = response.xml();
91 MatcherAssert.assertThat(
92 "should be equal to 'yes!'",
93 xml.xpath("//foo:b/text()").get(0),
94 Matchers.equalTo("yes!")
95 );
96 MatcherAssert.assertThat(
97 "should be empty",
98 xml.nodes("/foo:a/foo:b"),
99 Matchers.not(Matchers.empty())
100 );
101 }
102
103
104
105
106
107 @Test
108 void findsDocumentNodesWithXpathAndReturnsThem() throws Exception {
109 final XmlResponse response = new XmlResponse(
110 new FakeRequest()
111 .withBody("<root><a><x>1</x></a><a><x>2</x></a></root>")
112 .fetch()
113 );
114 MatcherAssert.assertThat(
115 "should be equal 2",
116 response.xml().nodes("//a"),
117 Matchers.hasSize(2)
118 );
119 MatcherAssert.assertThat(
120 "should be equal 1",
121 response.xml().nodes("/root/a").get(0).xpath("x/text()").get(0),
122 Matchers.equalTo("1")
123 );
124 }
125
126 }