View Javadoc
1   /*
2    * Copyright (c) 2011-2022, jcabi.com
3    * All rights reserved.
4    *
5    * Redistribution and use in source and binary forms, with or without
6    * modification, are permitted provided that the following conditions
7    * are met: 1) Redistributions of source code must retain the above
8    * copyright notice, this list of conditions and the following
9    * disclaimer. 2) Redistributions in binary form must reproduce the above
10   * copyright notice, this list of conditions and the following
11   * disclaimer in the documentation and/or other materials provided
12   * with the distribution. 3) Neither the name of the jcabi.com nor
13   * the names of its contributors may be used to endorse or promote
14   * products derived from this software without specific prior written
15   * permission.
16   *
17   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18   * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
19   * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
20   * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
21   * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
22   * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23   * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24   * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25   * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
28   * OF THE POSSIBILITY OF SUCH DAMAGE.
29   */
30  package com.jcabi.http.request;
31  
32  import com.jcabi.http.Request;
33  import com.jcabi.http.response.RestResponse;
34  import jakarta.ws.rs.core.HttpHeaders;
35  import jakarta.ws.rs.core.MediaType;
36  import java.io.ByteArrayInputStream;
37  import java.net.HttpURLConnection;
38  import java.net.URI;
39  import java.nio.charset.StandardCharsets;
40  import org.hamcrest.MatcherAssert;
41  import org.hamcrest.Matchers;
42  import org.junit.jupiter.api.Assertions;
43  import org.junit.jupiter.api.Test;
44  import org.junit.jupiter.api.function.Executable;
45  
46  /**
47   * Test case for {@link FakeRequest}.
48   * @since 1.0
49   */
50  final class FakeRequestTest {
51  
52      /**
53       * FakeRequest can fetch a fake response.
54       * @throws Exception If something goes wrong inside
55       */
56      @Test
57      void sendsHttpRequestAndProcessesHttpResponse() throws Exception {
58          this.generateMainRequest()
59              .withBody("how are you?")
60              .uri().path("/helloall").back()
61              .method(Request.POST)
62              .fetch().as(RestResponse.class)
63              .assertStatus(HttpURLConnection.HTTP_OK)
64              .assertHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN)
65              .assertBody(Matchers.containsString("are you?"));
66      }
67  
68      /**
69       * FakeRequest can fetch a fake response with binary response.
70       * @throws Exception If something goes wrong inside.
71       */
72      @Test
73      void sendsHttpRequestAndProcessesHttpBinaryResponse()
74          throws Exception {
75          final byte[] content = "Binary body content".getBytes();
76          this.generateMainRequest()
77              .withBody(content)
78              .uri().path("/binContent").back()
79              .method(Request.POST)
80              .fetch().as(RestResponse.class)
81              .assertStatus(HttpURLConnection.HTTP_OK)
82              .assertHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN)
83              .assertBinary(Matchers.equalTo(content));
84      }
85  
86      /**
87       * FakeRequest can change URI.
88       * @throws Exception If something goes wrong inside
89       */
90      @Test
91      void changesUri() throws Exception {
92          MatcherAssert.assertThat(
93              new FakeRequest()
94                  .uri().set(new URI("http://facebook.com")).back()
95                  .uri().get().toString(),
96              Matchers.endsWith("facebook.com/")
97          );
98      }
99  
100     /**
101      * FakeRequest can change URI in response.
102      * @throws Exception If something goes wrong inside
103      */
104     @Test
105     void changesUriInResponse() throws Exception {
106         MatcherAssert.assertThat(
107             new FakeRequest()
108                 .uri().set(new URI("http://google.com")).back()
109                 .fetch().back()
110                 .uri().get().toString(),
111             Matchers.containsString("google.com")
112         );
113     }
114 
115     /**
116      * FakeRequest.fetch(InputStream) throws an exception if a non-empty body
117      * has been previously set.
118      */
119     @Test
120     void fetchThrowsExceptionWhenBodyIsNotEmpty() {
121         Assertions.assertThrows(
122             IllegalStateException.class,
123             new Executable() {
124                 @Override
125                 public void execute() throws Throwable {
126                     new FakeRequest()
127                         .withStatus(HttpURLConnection.HTTP_OK)
128                         .withBody("blah")
129                         .fetch(
130                             new ByteArrayInputStream(
131                                 "foo".getBytes(StandardCharsets.UTF_8)
132                             )
133                         );
134                 }
135             }
136         );
137     }
138 
139     /**
140      * FakeRequest returns the Response Body if the Request Body is set.
141      * @throws Exception If something goes wrong inside.
142      * @link https://github.com/jcabi/jcabi-http/issues/47
143      */
144     @Test
145     void fakeRequestReturnsResponseBody() throws Exception {
146         final String response = "the response body";
147         final String request = "the request body";
148         new FakeRequest().withBody(response)
149             .body().set(request).back()
150             .fetch()
151             .as(RestResponse.class)
152             .assertBody(
153                 Matchers.allOf(
154                     Matchers.is(response),
155                     Matchers.not(Matchers.is(request))
156                 )
157             );
158     }
159 
160     /**
161      * FakeRequest can identify itself uniquely.
162      */
163     @Test
164     void identifiesUniquely() {
165         MatcherAssert.assertThat(
166             new FakeRequest().header("header-1", "value-1"),
167             Matchers.not(
168                 Matchers.equalTo(
169                     new FakeRequest().header("header-2", "value-2")
170                 )
171             )
172         );
173         MatcherAssert.assertThat(
174             new FakeRequest(),
175             Matchers.equalTo(new FakeRequest())
176         );
177     }
178 
179     /**
180      * Helper method that generates a FakeRequest.
181      * @return An instance of FakeRequest.
182      */
183     private FakeRequest generateMainRequest() {
184         return new FakeRequest()
185             .withStatus(HttpURLConnection.HTTP_OK)
186             .withReason("OK")
187             .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN);
188     }
189 
190 }