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 package com.jcabi.http.response;
31
32 import com.jcabi.http.Response;
33 import com.jcabi.http.request.FakeRequest;
34 import com.jcabi.xml.XML;
35 import org.apache.commons.lang3.StringUtils;
36 import org.hamcrest.MatcherAssert;
37 import org.hamcrest.Matchers;
38 import org.junit.jupiter.api.Test;
39
40
41
42
43
44
45 @SuppressWarnings("PMD.TooManyMethods")
46 final class XmlResponseTest {
47
48
49
50
51
52 @Test
53 void findsDocumentNodesWithXpath() throws Exception {
54 final XmlResponse response = new XmlResponse(
55 new FakeRequest()
56 .withBody("<r><a>\u0443\u0440\u0430!</a><a>B</a></r>")
57 .fetch()
58 );
59 MatcherAssert.assertThat(
60 response.xml().xpath("//a/text()"),
61 Matchers.hasSize(2)
62 );
63 MatcherAssert.assertThat(
64 response.xml().xpath("/r/a/text()"),
65 Matchers.hasItem("\u0443\u0440\u0430!")
66 );
67 }
68
69
70
71
72
73 @Test
74 void assertsWithXpath() throws Exception {
75 final Response resp = new FakeRequest()
76 .withBody("<x a='1'><!-- hi --><y>\u0443\u0440\u0430!</y></x>")
77 .fetch();
78 new XmlResponse(resp)
79 .assertXPath("//y[.='\u0443\u0440\u0430!']")
80 .assertXPath("/x/@a")
81 .assertXPath("/x/comment()")
82 .assertXPath("/x/y[contains(.,'\u0430')]");
83 }
84
85
86
87
88
89 @Test
90 void assertsWithXpathAndNamespaces() throws Exception {
91 final Response resp = new FakeRequest().withBody(
92 StringUtils.join(
93 "<html xmlns='http://www.w3.org/1999/xhtml'>",
94 "<div>\u0443\u0440\u0430!</div></html>"
95 )
96 ).fetch();
97 new XmlResponse(resp)
98 .assertXPath("/xhtml:html/xhtml:div")
99 .assertXPath("//xhtml:div[.='\u0443\u0440\u0430!']");
100 }
101
102
103
104
105
106 @Test
107 void assertsWithXpathWithCustomNamespace() throws Exception {
108 final XmlResponse response = new XmlResponse(
109 new FakeRequest()
110 .withBody("<a xmlns='urn:foo'><b>yes!</b></a>")
111 .fetch()
112 ).registerNs("foo", "urn:foo");
113 final XML xml = response.xml();
114 MatcherAssert.assertThat(
115 xml.xpath("//foo:b/text()").get(0),
116 Matchers.equalTo("yes!")
117 );
118 MatcherAssert.assertThat(
119 xml.nodes("/foo:a/foo:b"),
120 Matchers.not(Matchers.empty())
121 );
122 }
123
124
125
126
127
128 @Test
129 void findsDocumentNodesWithXpathAndReturnsThem() throws Exception {
130 final XmlResponse response = new XmlResponse(
131 new FakeRequest()
132 .withBody("<root><a><x>1</x></a><a><x>2</x></a></root>")
133 .fetch()
134 );
135 MatcherAssert.assertThat(
136 response.xml().nodes("//a"),
137 Matchers.hasSize(2)
138 );
139 MatcherAssert.assertThat(
140 response.xml().nodes("/root/a").get(0).xpath("x/text()").get(0),
141 Matchers.equalTo("1")
142 );
143 }
144
145 }