View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit;
16  
17  import static java.nio.charset.StandardCharsets.ISO_8859_1;
18  
19  import java.io.IOException;
20  import java.io.ObjectInputStream;
21  import java.io.ObjectOutputStream;
22  import java.io.Serializable;
23  import java.net.URL;
24  import java.nio.charset.Charset;
25  import java.util.ArrayList;
26  import java.util.Collections;
27  import java.util.HashMap;
28  import java.util.List;
29  import java.util.Map;
30  import java.util.concurrent.atomic.AtomicInteger;
31  
32  import org.apache.commons.logging.Log;
33  import org.apache.commons.logging.LogFactory;
34  import org.htmlunit.util.ArrayUtils;
35  import org.htmlunit.util.MimeType;
36  import org.htmlunit.util.NameValuePair;
37  
38  /**
39   * A fake {@link WebConnection} designed to mock out the actual HTTP connections.
40   *
41   * @author Mike Bowler
42   * @author Noboru Sinohara
43   * @author Marc Guillemot
44   * @author Brad Clarke
45   * @author Ahmed Ashour
46   * @author Ronald Brill
47   */
48  public class MockWebConnection implements WebConnection, Serializable {
49  
50      private static final Log LOG = LogFactory.getLog(MockWebConnection.class);
51  
52      private final Map<String, IOException> throwableMap_ = new HashMap<>();
53      private final Map<String, RawResponseData> responseMap_ = new HashMap<>();
54      private RawResponseData defaultResponse_;
55      private volatile WebRequest lastRequest_;
56      private final AtomicInteger requestCount_ = new AtomicInteger();
57      private final List<URL> requestedUrls_ = Collections.synchronizedList(new ArrayList<>());
58  
59      /**
60       * Contains the raw data configured for a response.
61       */
62      public static class RawResponseData implements Serializable {
63          private final List<NameValuePair> headers_;
64          private final byte[] byteContent_;
65          private final String stringContent_;
66          private final int statusCode_;
67          private final String statusMessage_;
68          private transient Charset charset_;
69  
70          RawResponseData(final byte[] byteContent, final int statusCode, final String statusMessage,
71                  final String contentType, final List<NameValuePair> headers) {
72              byteContent_ = byteContent;
73              stringContent_ = null;
74              charset_ = null;
75              statusCode_ = statusCode;
76              statusMessage_ = statusMessage;
77              headers_ = compileHeaders(headers, contentType);
78          }
79  
80          RawResponseData(final String stringContent, final Charset charset, final int statusCode,
81                  final String statusMessage, final String contentType, final List<NameValuePair> headers) {
82              byteContent_ = null;
83              charset_ = charset;
84              stringContent_ = stringContent;
85              statusCode_ = statusCode;
86              statusMessage_ = statusMessage;
87              headers_ = compileHeaders(headers, contentType);
88          }
89  
90          private static List<NameValuePair> compileHeaders(final List<NameValuePair> headers, final String contentType) {
91              final List<NameValuePair> compiledHeaders = new ArrayList<>();
92              if (headers != null) {
93                  compiledHeaders.addAll(headers);
94              }
95              if (contentType != null) {
96                  compiledHeaders.add(new NameValuePair(HttpHeader.CONTENT_TYPE, contentType));
97              }
98              return compiledHeaders;
99          }
100 
101         WebResponseData asWebResponseData() {
102             final byte[] content;
103             if (byteContent_ != null) {
104                 content = byteContent_;
105             }
106             else if (stringContent_ == null) {
107                 content = ArrayUtils.EMPTY_BYTE_ARRAY;
108             }
109             else {
110                 content = stringContent_.getBytes(charset_);
111             }
112             return new WebResponseData(content, statusCode_, statusMessage_, headers_);
113         }
114 
115         /**
116          * Returns the configured response headers.
117          *
118          * @return the headers
119          */
120         public List<NameValuePair> getHeaders() {
121             return headers_;
122         }
123 
124         /**
125          * Returns the configured response content as a byte array.
126          *
127          * @return the byte content, or {@code null} if string content was configured
128          */
129         public byte[] getByteContent() {
130             return byteContent_;
131         }
132 
133         /**
134          * Returns the configured response content as a string.
135          *
136          * @return the string content, or {@code null} if byte content was configured
137          */
138         public String getStringContent() {
139             return stringContent_;
140         }
141 
142         /**
143          * Returns the configured HTTP status code.
144          *
145          * @return the status code
146          */
147         public int getStatusCode() {
148             return statusCode_;
149         }
150 
151         /**
152          * Returns the configured HTTP status message.
153          *
154          * @return the status message
155          */
156         public String getStatusMessage() {
157             return statusMessage_;
158         }
159 
160         /**
161          * Returns the configured charset, or {@code null} if byte content was configured.
162          *
163          * @return the charset, or {@code null} for byte content
164          */
165         public Charset getCharset() {
166             return charset_;
167         }
168 
169         private void writeObject(final ObjectOutputStream oos) throws IOException {
170             oos.defaultWriteObject();
171             oos.writeObject(charset_ == null ? null : charset_.name());
172         }
173 
174         private void readObject(final ObjectInputStream ois) throws ClassNotFoundException, IOException {
175             ois.defaultReadObject();
176             final String charsetName = (String) ois.readObject();
177             if (charsetName != null) {
178                 charset_ = Charset.forName(charsetName);
179             }
180         }
181     }
182 
183     /**
184      * {@inheritDoc}
185      */
186     @Override
187     public WebResponse getResponse(final WebRequest request) throws IOException {
188         final RawResponseData rawResponse = getRawResponse(request);
189         return new WebResponse(rawResponse.asWebResponseData(), request, 0);
190     }
191 
192     /**
193      * Returns the raw response configured for the given request.
194      *
195      * <p>The request is always recorded (incrementing {@link #getRequestCount()} and
196      * appending to {@link #getRequestedUrls()}) before any configured {@link IOException}
197      * is thrown, mirroring real HTTP behaviour where the request was dispatched even
198      * if the connection subsequently failed.
199      * </p>
200      *
201      * <p>URL lookup first tries an exact match (including query string), then retries
202      * without the query string, then falls back to the default response. If no default
203      * has been set an {@link IllegalStateException} is thrown.
204      * </p>
205      *
206      * @param request the request
207      * @return the raw response
208      * @throws IOException if an {@link IOException} has been registered for the URL
209      *         via {@link #setThrowable(URL, IOException)}
210      * @throws IllegalStateException if no response or default response is configured
211      *         for the URL
212      */
213     public RawResponseData getRawResponse(final WebRequest request) throws IOException {
214         final URL url = request.getUrl();
215 
216         if (LOG.isDebugEnabled()) {
217             LOG.debug("Getting response for " + url.toExternalForm());
218         }
219 
220         lastRequest_ = request;
221         requestCount_.incrementAndGet();
222         requestedUrls_.add(url);
223 
224         String urlString = url.toExternalForm();
225         final IOException throwable = throwableMap_.get(urlString);
226         if (throwable != null) {
227             // wrap to produce a stack trace pointing to this call site rather than
228             // to where the IOException was originally constructed
229             throw new IOException(throwable.getMessage(), throwable);
230         }
231 
232         RawResponseData rawResponse = responseMap_.get(urlString);
233         if (rawResponse == null) {
234             // try to find without query params
235             final int queryStart = urlString.lastIndexOf('?');
236             if (queryStart > -1) {
237                 urlString = urlString.substring(0, queryStart);
238                 rawResponse = responseMap_.get(urlString);
239             }
240 
241             // fall back to default
242             if (rawResponse == null) {
243                 rawResponse = defaultResponse_;
244                 if (rawResponse == null) {
245                     throw new IllegalStateException("No response specified that can handle URL "
246                          + request.getHttpMethod()
247                          + " [" + urlString + "]");
248                 }
249             }
250         }
251 
252         return rawResponse;
253     }
254 
255     /**
256      * Returns an unmodifiable list of all URLs requested so far, in request order.
257      *
258      * @return the list of requested URLs
259      */
260     public List<URL> getRequestedUrls() {
261         return Collections.unmodifiableList(requestedUrls_);
262     }
263 
264     /**
265      * Returns an unmodifiable list of requested URLs relativized against the given base URL.
266      * If a requested URL starts with {@code relativeTo}, the base is stripped; otherwise
267      * the full URL string is returned as-is.
268      *
269      * <p>Note: the base URL string is compared as a plain prefix. Ensure {@code relativeTo}
270      * has a trailing slash if needed to avoid unintended partial matches
271      * (e.g. {@code http://localhost/} rather than {@code http://localhost}).
272      * </p>
273      *
274      * @param relativeTo the base URL whose prefix should be stripped from each requested URL
275      * @return the list of relative (or absolute, if not matching) URL strings
276      */
277     public List<String> getRequestedUrls(final URL relativeTo) {
278         final String baseUrl = relativeTo.toString();
279         final List<String> response = new ArrayList<>();
280         for (final URL url : requestedUrls_) {
281             String s = url.toString();
282             if (s.startsWith(baseUrl)) {
283                 s = s.substring(baseUrl.length());
284             }
285             response.add(s);
286         }
287 
288         return Collections.unmodifiableList(response);
289     }
290 
291     /**
292      * Returns the HTTP method that was used in the last call to
293      * {@link #getResponse(WebRequest)}.
294      *
295      * @return the HTTP method of the last request
296      * @throws IllegalStateException if no request has been made yet
297      */
298     public HttpMethod getLastMethod() {
299         return getLastWebRequest().getHttpMethod();
300     }
301 
302     /**
303      * Returns the request parameters that were used in the last call to
304      * {@link #getResponse(WebRequest)}.
305      *
306      * @return the parameters of the last request
307      * @throws IllegalStateException if no request has been made yet
308      */
309     public List<NameValuePair> getLastParameters() {
310         return getLastWebRequest().getRequestParameters();
311     }
312 
313     /**
314      * Sets the response that will be returned when the specified URL is requested.
315      *
316      * @param url the URL that will return the given response
317      * @param content the content to return
318      * @param statusCode the status code to return
319      * @param statusMessage the status message to return
320      * @param contentType the content type to return
321      * @param headers the response headers to return
322      */
323     public void setResponse(final URL url, final String content, final int statusCode,
324             final String statusMessage, final String contentType,
325             final List<NameValuePair> headers) {
326 
327         setResponse(
328                 url,
329                 content,
330                 statusCode,
331                 statusMessage,
332                 contentType,
333                 ISO_8859_1,
334                 headers);
335     }
336 
337     /**
338      * Sets the response that will be returned when the specified URL is requested.
339      *
340      * @param url the URL that will return the given response
341      * @param content the content to return
342      * @param statusCode the status code to return
343      * @param statusMessage the status message to return
344      * @param contentType the content type to return
345      * @param charset the charset
346      * @param headers the response headers to return
347      */
348     public void setResponse(final URL url, final String content, final int statusCode,
349             final String statusMessage, final String contentType, final Charset charset,
350             final List<NameValuePair> headers) {
351 
352         final RawResponseData responseEntry = buildRawResponseData(content, charset, statusCode, statusMessage,
353                 contentType, headers);
354         responseMap_.put(url.toExternalForm(), responseEntry);
355     }
356 
357     /**
358      * Sets the exception that will be thrown when the specified URL is requested.
359      *
360      * <p>The stored exception is wrapped at throw time so that the stack trace
361      * points to the actual call site rather than to where the exception was constructed.
362      * </p>
363      *
364      * @param url the URL that will force the exception
365      * @param throwable the {@link IOException} to throw
366      */
367     public void setThrowable(final URL url, final IOException throwable) {
368         throwableMap_.put(url.toExternalForm(), throwable);
369     }
370 
371     /**
372      * Sets the response that will be returned when the specified URL is requested.
373      *
374      * @param url the URL that will return the given response
375      * @param content the content to return
376      * @param statusCode the status code to return
377      * @param statusMessage the status message to return
378      * @param contentType the content type to return
379      * @param headers the response headers to return
380      */
381     public void setResponse(final URL url, final byte[] content, final int statusCode,
382             final String statusMessage, final String contentType,
383             final List<NameValuePair> headers) {
384 
385         final RawResponseData responseEntry = buildRawResponseData(content, statusCode, statusMessage, contentType,
386             headers);
387         responseMap_.put(url.toExternalForm(), responseEntry);
388     }
389 
390     private static RawResponseData buildRawResponseData(final byte[] content, final int statusCode,
391             final String statusMessage, final String contentType, final List<NameValuePair> headers) {
392         return new RawResponseData(content, statusCode, statusMessage, contentType, headers);
393     }
394 
395     private static RawResponseData buildRawResponseData(final String content, Charset charset, final int statusCode,
396             final String statusMessage, final String contentType, final List<NameValuePair> headers) {
397 
398         if (charset == null) {
399             charset = ISO_8859_1;
400         }
401         return new RawResponseData(content, charset, statusCode, statusMessage, contentType, headers);
402     }
403 
404     /**
405      * Convenient method that is the same as calling
406      * {@link #setResponse(URL,String,int,String,String,List)} with a status
407      * of "200 OK", a content type of "text/html" and no additional headers.
408      *
409      * @param url the URL that will return the given response
410      * @param content the content to return
411      */
412     public void setResponse(final URL url, final String content) {
413         setResponse(url, content, 200, "OK", MimeType.TEXT_HTML, null);
414     }
415 
416     /**
417      * Convenient method that is the same as calling
418      * {@link #setResponse(URL,String,int,String,String,List)} with a status
419      * of "200 OK" and no additional headers.
420      *
421      * @param url the URL that will return the given response
422      * @param content the content to return
423      * @param contentType the content type to return
424      */
425     public void setResponse(final URL url, final String content, final String contentType) {
426         setResponse(url, content, 200, "OK", contentType, null);
427     }
428 
429     /**
430      * Convenient method that is the same as calling
431      * {@link #setResponse(URL, String, int, String, String, Charset, List)} with a status
432      * of "200 OK" and no additional headers.
433      *
434      * @param url the URL that will return the given response
435      * @param content the content to return
436      * @param contentType the content type to return
437      * @param charset the charset
438      */
439     public void setResponse(final URL url, final String content, final String contentType, final Charset charset) {
440         setResponse(url, content, 200, "OK", contentType, charset, null);
441     }
442 
443     /**
444      * Specify a generic HTML page that will be returned when the given URL is specified.
445      * The page will contain only minimal HTML to satisfy the HTML parser but will contain
446      * the specified title so that tests can check for titleText.
447      *
448      * @param url the URL that will return the given response
449      * @param title the title of the page
450      */
451     public void setResponseAsGenericHtml(final URL url, final String title) {
452         final String content = "<!DOCTYPE html><html><head><title>" + title + "</title></head><body></body></html>";
453         setResponse(url, content);
454     }
455 
456     /**
457      * Sets the response that will be returned when a URL is requested that does
458      * not have a specific response configured for it.
459      *
460      * @param content the content to return
461      * @param statusCode the status code to return
462      * @param statusMessage the status message to return
463      * @param contentType the content type to return
464      */
465     public void setDefaultResponse(final String content, final int statusCode,
466             final String statusMessage, final String contentType) {
467 
468         defaultResponse_ = buildRawResponseData(content, null, statusCode, statusMessage, contentType, null);
469     }
470 
471     /**
472      * Sets the response that will be returned when a URL is requested that does
473      * not have a specific response configured for it.
474      *
475      * @param content the content to return
476      * @param statusCode the status code to return
477      * @param statusMessage the status message to return
478      * @param contentType the content type to return
479      */
480     public void setDefaultResponse(final byte[] content, final int statusCode,
481             final String statusMessage, final String contentType) {
482 
483         defaultResponse_ = buildRawResponseData(content, statusCode, statusMessage, contentType, null);
484     }
485 
486     /**
487      * Sets the response that will be returned when a URL is requested that does
488      * not have a specific response configured for it.
489      *
490      * @param content the content to return
491      */
492     public void setDefaultResponse(final String content) {
493         setDefaultResponse(content, 200, "OK", MimeType.TEXT_HTML);
494     }
495 
496     /**
497      * Sets the response that will be returned when a URL is requested that does
498      * not have a specific response configured for it.
499      *
500      * @param content the content to return
501      * @param contentType the content type to return
502      */
503     public void setDefaultResponse(final String content, final String contentType) {
504         setDefaultResponse(content, 200, "OK", contentType, null);
505     }
506 
507     /**
508      * Sets the response that will be returned when a URL is requested that does
509      * not have a specific response configured for it.
510      *
511      * @param content the content to return
512      * @param contentType the content type to return
513      * @param charset the charset
514      */
515     public void setDefaultResponse(final String content, final String contentType, final Charset charset) {
516         setDefaultResponse(content, 200, "OK", contentType, charset, null);
517     }
518 
519     /**
520      * Sets the response that will be returned when a URL is requested that does
521      * not have a specific response configured for it.
522      *
523      * @param content the content to return
524      * @param statusCode the status code to return
525      * @param statusMessage the status message to return
526      * @param contentType the content type to return
527      * @param headers the response headers to return
528      */
529     public void setDefaultResponse(final String content, final int statusCode,
530             final String statusMessage, final String contentType,
531             final List<NameValuePair> headers) {
532 
533         defaultResponse_ = buildRawResponseData(content, null, statusCode, statusMessage, contentType, headers);
534     }
535 
536     /**
537      * Sets the response that will be returned when a URL is requested that does
538      * not have a specific response configured for it.
539      *
540      * @param content the content to return
541      * @param statusCode the status code to return
542      * @param statusMessage the status message to return
543      * @param contentType the content type to return
544      * @param charset the charset
545      * @param headers the response headers to return
546      */
547     public void setDefaultResponse(final String content, final int statusCode,
548             final String statusMessage, final String contentType, final Charset charset,
549             final List<NameValuePair> headers) {
550 
551         defaultResponse_ = buildRawResponseData(content, charset, statusCode, statusMessage, contentType, headers);
552     }
553 
554     /**
555      * Returns the additional headers that were used in the last call
556      * to {@link #getResponse(WebRequest)}.
557      *
558      * @return the additional headers of the last request
559      * @throws IllegalStateException if no request has been made yet
560      */
561     public Map<String, String> getLastAdditionalHeaders() {
562         return getLastWebRequest().getAdditionalHeaders();
563     }
564 
565     /**
566      * Returns the {@link WebRequest} that was used in the last call
567      * to {@link #getResponse(WebRequest)}.
568      *
569      * @return the last {@link WebRequest}
570      * @throws IllegalStateException if no request has been made yet
571      */
572     public WebRequest getLastWebRequest() {
573         if (lastRequest_ == null) {
574             throw new IllegalStateException("No request has been made yet.");
575         }
576         return lastRequest_;
577     }
578 
579     /**
580      * Returns the number of requests made to this mock web connection.
581      *
582      * @return the number of requests made to this mock web connection
583      */
584     public int getRequestCount() {
585         return requestCount_.get();
586     }
587 
588     /**
589      * Returns whether a response has been configured for the given URL.
590      *
591      * @param url the URL to check
592      * @return {@code true} if a response has been configured for the URL; {@code false} otherwise
593      */
594     public boolean hasResponse(final URL url) {
595         return responseMap_.containsKey(url.toExternalForm());
596     }
597 
598     /**
599      * Delegates to {@link #clear()}, resetting all configured responses, recorded
600      * requests, and request counts.
601      */
602     @Override
603     public void close() {
604         clear();
605     }
606 
607     /**
608      * Resets all state: clears all configured responses and throwables, the default
609      * response, the last request, the request count, and the list of requested URLs.
610      *
611      * <p>Note: {@link #close()} delegates to this method, so using this connection</p>
612      * in a try-with-resources block will reset all configured state on exit.
613      */
614     public void clear() {
615         throwableMap_.clear();
616         responseMap_.clear();
617         defaultResponse_ = null;
618         lastRequest_ = null;
619         requestCount_.set(0);
620         requestedUrls_.clear();
621     }
622 }