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