1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.htmlunit.javascript.host.xml;
16
17 import java.net.URL;
18
19 import org.htmlunit.MiniServer;
20 import org.htmlunit.MockWebConnection;
21 import org.htmlunit.WebDriverTestCase;
22 import org.htmlunit.WebTestCase;
23 import org.htmlunit.junit.BrowserRunner;
24 import org.junit.After;
25 import org.junit.Before;
26 import org.junit.Test;
27 import org.junit.runner.RunWith;
28 import org.openqa.selenium.WebDriver;
29
30
31
32
33
34
35
36 @RunWith(BrowserRunner.class)
37 public final class XMLHttpRequestSentContentTest extends WebDriverTestCase {
38
39
40
41
42
43 @Before
44 public void before() throws Exception {
45
46 shutDownAll();
47 MiniServer.resetDropRequests();
48 }
49
50
51
52
53
54 @After
55 public void after() throws Exception {
56 MiniServer.resetDropRequests();
57 }
58
59
60
61
62 @Test
63 public void getShouldNotSendBody() throws Exception {
64 testSendBody("GET", false);
65 }
66
67
68
69
70 @Test
71 public void postShouldSendBody() throws Exception {
72 testSendBody("POST", true);
73 }
74
75
76
77
78 @Test
79 public void putShouldSendBody() throws Exception {
80 testSendBody("PUT", true);
81 }
82
83
84
85
86 @Test
87 public void patchShouldSendBody() throws Exception {
88 testSendBody("PATCH", true);
89 }
90
91
92
93
94 @Test
95 public void deleteShouldSendBody() throws Exception {
96 testSendBody("DELETE", true);
97 }
98
99
100
101
102 @Test
103 public void optionsShouldSendBody() throws Exception {
104 testSendBody("OPTIONS", true);
105 }
106
107
108
109
110 @Test
111 public void headShouldNotSendBody() throws Exception {
112 testSendBody("HEAD", false);
113 }
114
115 private void testSendBody(final String method, final boolean bodyIncluded) throws Exception {
116 final String html = DOCTYPE_HTML
117 + "<html><head><script>\n"
118 + " function test() {\n"
119 + " var xhr = new XMLHttpRequest();\n"
120 + " xhr.open('" + method + "', 'second.html?a=x', false);\n"
121 + " let body = new URLSearchParams();\n"
122 + " body.append('x', 'body');\n"
123 + " xhr.send(body);\n"
124 + " }\n"
125 + "</script></head>\n"
126 + "<body onload='test()'></body></html>";
127
128 final MockWebConnection mockWebConnection = getMockWebConnection();
129 mockWebConnection.setResponse(WebTestCase.URL_FIRST, html);
130 mockWebConnection.setDefaultResponse("");
131
132 try (MiniServer miniServer = new MiniServer(PORT, mockWebConnection)) {
133 miniServer.start();
134
135 final WebDriver driver = getWebDriver();
136 driver.get(WebTestCase.URL_FIRST.toExternalForm());
137
138 assertEquals(2, mockWebConnection.getRequestCount());
139 assertEquals(new URL(WebTestCase.URL_FIRST, "second.html?a=x"),
140 mockWebConnection.getLastWebRequest().getUrl());
141
142 if (bodyIncluded) {
143 assertTrue(miniServer.getLastRequest(), miniServer.getLastRequest().contains("\nx=body"));
144 }
145 else {
146 assertTrue(miniServer.getLastRequest(), !miniServer.getLastRequest().contains("\nx=body"));
147 }
148 }
149 }
150 }