Java Code Examples for okhttp3.mockwebserver.MockResponse#setResponseCode()

The following examples show how to use okhttp3.mockwebserver.MockResponse#setResponseCode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: KubernetesCrudDispatcher.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
/**
 * Performs a get for the corresponding object from the in-memory db.
 *
 * @param path The path.
 * @return The {@link MockResponse}
 */
@Override
public MockResponse handleGet(String path) {
  MockResponse response = new MockResponse();
  List<String> items = new ArrayList<>();
  AttributeSet query = attributeExtractor.fromPath(path);

  map.entrySet().stream().filter(entry -> entry.getKey()
    .matches(query)).forEach(entry -> {
    LOGGER.debug("Entry found for query {} : {}", query, entry);
    items.add(entry.getValue());
  });

  if (query.containsKey(KubernetesAttributesExtractor.NAME)) {
    if (!items.isEmpty()) {
      response.setBody(items.get(0));
      response.setResponseCode(HttpURLConnection.HTTP_OK);
    } else {
      response.setResponseCode(HttpURLConnection.HTTP_NOT_FOUND);
    }
  } else {
    response.setBody(responseComposer.compose(items));
    response.setResponseCode(HttpURLConnection.HTTP_OK);
  }
  return response;
}
 
Example 2
Source File: SimpleResponse.java    From mockwebserver with Apache License 2.0 6 votes vote down vote up
public MockResponse toMockResponse(RecordedRequest request) {
  MockResponse mockResponse = new MockResponse();
  mockResponse.setHeaders(bodyProvider.getHeaders());
  mockResponse.setResponseCode(bodyProvider.getStatusCode(request));

  if (webSocketSession != null) {
    mockResponse.withWebSocketUpgrade(webSocketSession);
  } else {
    mockResponse.setBody(bodyProvider.getBody(request));
  }

  if (responseDelay > 0) {
    mockResponse.setBodyDelay(responseDelay, responseDelayUnit);
  }

  return mockResponse;
}
 
Example 3
Source File: ZooniverseClientTest.java    From android-galaxyzoo with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testMoreItemsWithBadResponseCode() throws IOException {
    final MockWebServer server = new MockWebServer();

    final MockResponse response = new MockResponse();
    response.setResponseCode(HttpURLConnection.HTTP_NOT_FOUND);
    response.setBody("test nonsense failure message");
    server.enqueue(response);
    server.start();

    final ZooniverseClient client = createZooniverseClient(server);

    //Mostly we want to check that it doesn't crash on a bad HTTP response.

    try {
        final List<ZooniverseClient.Subject> subjects = client.requestMoreItemsSync(TEST_GROUP_ID, 5);
        assertTrue((subjects == null) || (subjects.isEmpty()));
    } catch (final ZooniverseClient.RequestMoreItemsException e) {
        assertNotNull(e.getMessage());
        //assertTrue(e.getCause() instanceof ExecutionException);
    }

    server.shutdown();
}
 
Example 4
Source File: CrudDispatcher.java    From mockwebserver with Apache License 2.0 6 votes vote down vote up
/**
 * Patches the specified object to the in-memory db.
 *
 * @param path
 * @param s
 * @return
 */
public MockResponse handlePatch(String path, String s) {
    MockResponse response = new MockResponse();
    String body = doGet(path);
    if (body == null) {
        response.setResponseCode(404);
    } else {
        try {
            JsonNode patch = context.getMapper().readTree(s);
            JsonNode source = context.getMapper().readTree(body);
            JsonNode updated = JsonPatch.apply(patch, source);
            String updatedAsString = context.getMapper().writeValueAsString(updated);
            AttributeSet features = AttributeSet.merge(attributeExtractor.fromPath(path),
                    attributeExtractor.fromResource(updatedAsString));
            map.put(features, updatedAsString);
            response.setResponseCode(202);
            response.setBody(updatedAsString);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
    return response;
}
 
Example 5
Source File: RawJSONMockResponse.java    From android-sdk with MIT License 6 votes vote down vote up
public static MockResponse fromRawResource(InputStream inputStream) throws IOException, JSONException {

        String theString = Utils.toString(inputStream);
        JSONObject json = new JSONObject(theString);
        MockResponse value = new MockResponse();

        value.setBody(json.getJSONObject("body").toString());
        value.setResponseCode(json.optInt("statusCode", 200));

        JSONObject headers = json.optJSONObject("headers");
        if (headers != null) {
            Iterator<String> keys = headers.keys();
            while (keys.hasNext()) {
                String key = keys.next();
                value.addHeader(key, headers.get(key));
            }
        }

        return value;
    }
 
Example 6
Source File: MainPresenterImplTest.java    From mockstar with MIT License 6 votes vote down vote up
@Test
public void testDemoResponseError503() {
    reset(mainSceneMock);
    MainPresenterImpl presenter = new MainPresenterImpl(schedulersProvider, pokeDataSource);

    MockResponse response = new MockResponse();
    response.setResponseCode(HttpURLConnection.HTTP_UNAVAILABLE);

    getErrorMockWebServer().enqueue(response);

    presenter.onSceneAdded(mainSceneMock, null);

    testScheduler.triggerActions();

    verify(mainSceneMock, times(0)).setApiText(anyString());
    verify(mainSceneMock, times(1)).showErrorDialog("Fire on the Server");
}
 
Example 7
Source File: ZooniverseClientTest.java    From android-galaxyzoo with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testUploadWithFailure() throws IOException {
    final MockWebServer server = new MockWebServer();

    final MockResponse response = new MockResponse();
    response.setResponseCode(HttpURLConnection.HTTP_UNAUTHORIZED);
    response.setBody("test nonsense failure message");
    server.enqueue(response);
    server.start();

    final ZooniverseClient client = createZooniverseClient(server);

    final List<HttpUtils.NameValuePair> values = new ArrayList<>();
    values.add(new HttpUtils.NameValuePair("test nonsense", "12345"));

    try {
        final boolean result = client.uploadClassificationSync("testAuthName",
                "testAuthApiKey", TEST_GROUP_ID, values);
        assertFalse(result);
    } catch (final ZooniverseClient.UploadException e) {
        //This is (at least with okhttp.mockwebserver) a normal
        //event if the upload was refused via an error response code.
        assertTrue(e.getCause() instanceof IOException);
    }

    server.shutdown();
}
 
Example 8
Source File: CrudDispatcher.java    From mockwebserver with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the specified object to the in-memory db.
 *
 * @param path
 * @param s
 * @return
 */
public MockResponse handleCreate(String path, String s) {
    MockResponse response = new MockResponse();
    AttributeSet features = AttributeSet.merge(attributeExtractor.fromPath(path), attributeExtractor.fromResource(s));
    map.put(features, s);
    response.setBody(s);
    response.setResponseCode(202);
    return response;
}
 
Example 9
Source File: CrudDispatcher.java    From mockwebserver with Apache License 2.0 5 votes vote down vote up
/**
 * Performs a get for the corresponding object from the in-memory db.
 *
 * @param path The path.
 * @return The {@link MockResponse}
 */
public MockResponse handleGet(String path) {
    MockResponse response = new MockResponse();

    String body = doGet(path);
    if (body == null) {
        response.setResponseCode(404);
    } else {
        response.setResponseCode(200);
        response.setBody(body);
    }
    return response;
}
 
Example 10
Source File: ChunkedResponse.java    From mockwebserver with Apache License 2.0 5 votes vote down vote up
public MockResponse toMockResponse(RecordedRequest request) {
    MockResponse mockResponse = new MockResponse();
    mockResponse.setHeaders(bodyProvider.getHeaders());
    mockResponse.setChunkedBody(concatBody(request), DEFAULT_MAX_CHUNK_SIZE);
    mockResponse.setResponseCode(bodyProvider.getStatusCode(request));

    if (responseDelay > 0) {
        mockResponse.setBodyDelay(responseDelay, responseDelayUnit);
    }

    return mockResponse;
}
 
Example 11
Source File: MockWebServerTest.java    From mapbox-events-android with MIT License 5 votes vote down vote up
void enqueueMockResponse(int code, String fileName) throws IOException {
  mockResponse = new MockResponse();
  mockResponse.setResponseCode(code);
  String fileContent = obtainContentFromFile(fileName);
  mockResponse.setBody(fileContent);
  server.enqueue(mockResponse);
}
 
Example 12
Source File: MatchableCallsRequestDispatcher.java    From RESTMock with Apache License 2.0 5 votes vote down vote up
MockResponse createErrorResponse(Exception e) {
    MockResponse response = new MockResponse();
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    e.printStackTrace(pw);
    response.setBody(sw.toString());
    response.setResponseCode(500);
    return response;
}
 
Example 13
Source File: Dhis2MockServer.java    From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@NonNull
private MockResponse createMockResponse(String fileName) {
    try {
        String body = fileReader.getStringFromFile(fileName);
        MockResponse response = new MockResponse();
        response.setResponseCode(OK_CODE);
        response.setBody(body);
        return response;
    } catch (IOException e) {
        return new MockResponse().setResponseCode(500).setBody("Error reading JSON file for MockServer");
    }
}
 
Example 14
Source File: AuthenticationTests.java    From edx-app-android with Apache License 2.0 5 votes vote down vote up
@Override
public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
    MockResponse response = new MockResponse();

    String path = request.getPath();
    String header = request.getHeader("Authorization");

    response.setResponseCode(HttpStatus.NOT_FOUND);
    try {
        if (path.equals("/oauth2/access_token/")) {
            response.setResponseCode(HttpStatus.OK).setBody(MockDataUtil.getMockResponse("post_oauth2_access_token"));
        } else if (path.equals("/dummy/endpoint/")) {
            switch (header) {
                case "expired_token":
                    response.setResponseCode(HttpStatus.UNAUTHORIZED)
                            .addHeader("Authorization", "old_access_token")
                            .setBody(MockDataUtil.getMockResponse("401_expired_token_body"));
                    break;
                case "Bearer dummy":
                    response.setResponseCode(HttpStatus.OK);
                    break;
                case "401_not_caused_by_expired_token":
                    response.setResponseCode(HttpStatus.UNAUTHORIZED);
                    break;
            }
        }
    } catch (IOException exception) {
        exception.printStackTrace();
    }
    return response;
}
 
Example 15
Source File: MainPresenterImplTest.java    From mockstar with MIT License 4 votes vote down vote up
@Test
public void testDemoResponseError404() {
    reset(mainSceneMock);

    MainPresenterImpl presenter = new MainPresenterImpl(schedulersProvider, pokeDataSource);

    MockResponse response = new MockResponse();
    response.setResponseCode(HttpURLConnection.HTTP_NOT_FOUND);

    getErrorMockWebServer().enqueue(response);

    presenter.onSceneAdded(mainSceneMock, null);

    testScheduler.triggerActions();

    verify(mainSceneMock, times(1)).showErrorDialog("Lost!");
    verify(mainSceneMock, times(0)).setApiText(anyString());
}
 
Example 16
Source File: KubernetesCrudDispatcher.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
/**
 * Patches the specified object to the in-memory db.
 *
 * @param path
 * @param s
 * @return The {@link MockResponse}
 */
@Override
public MockResponse handlePatch(String path, String s) {
  MockResponse response = new MockResponse();
  String body = fetchResource(path);
  if (body == null) {
    response.setResponseCode(HttpURLConnection.HTTP_NOT_FOUND);
  } else {
    try {
      JsonNode patch = context.getMapper().readTree(s);
      JsonNode source = context.getMapper().readTree(body);
      JsonNode updated = JsonPatch.apply(patch, source);
      String updatedAsString = context.getMapper().writeValueAsString(updated);

      AttributeSet attributeSet = null;

      AttributeSet query = attributeExtractor.fromPath(path);

      attributeSet = map.entrySet().stream()
        .filter(entry -> entry.getKey().matches(query))
        .findFirst().orElseThrow(IllegalStateException::new).getKey();

      map.remove(attributeSet);
      AttributeSet newAttributeSet = AttributeSet.merge(attributeSet, attributeExtractor.fromResource(updatedAsString));
      map.put(newAttributeSet, updatedAsString);

      final AtomicBoolean flag = new AtomicBoolean(false);
      AttributeSet finalAttributeSet = attributeSet;
      watchEventListeners.stream()
        .filter(watchEventsListener -> watchEventsListener.attributeMatches(finalAttributeSet))
        .forEach(watchEventsListener -> {
            flag.set(true);
            watchEventsListener.sendWebSocketResponse(updatedAsString, "MODIFIED");
        });

      if (!flag.get()) {
        watchEventListeners.stream()
          .filter(watchEventsListener -> watchEventsListener.attributeMatches(newAttributeSet))
          .forEach(watchEventsListener -> watchEventsListener.sendWebSocketResponse(updatedAsString, "ADDED"));
      }

      response.setResponseCode(HttpURLConnection.HTTP_ACCEPTED);
      response.setBody(updatedAsString);
    } catch (JsonProcessingException e) {
      throw new IllegalArgumentException(e);
    }
  }
  return response;
}
 
Example 17
Source File: GeoApiContextTest.java    From google-maps-services-java with Apache License 2.0 4 votes vote down vote up
private MockResponse createMockGoodResponse() {
  MockResponse response = new MockResponse();
  response.setResponseCode(200);
  response.setBody(
      "{\n"
          + "   \"results\" : [\n"
          + "      {\n"
          + "         \"address_components\" : [\n"
          + "            {\n"
          + "               \"long_name\" : \"1600\",\n"
          + "               \"short_name\" : \"1600\",\n"
          + "               \"types\" : [ \"street_number\" ]\n"
          + "            }\n"
          + "         ],\n"
          + "         \"formatted_address\" : \"1600 Amphitheatre Parkway, Mountain View, "
          + "CA 94043, USA\",\n"
          + "         \"geometry\" : {\n"
          + "            \"location\" : {\n"
          + "               \"lat\" : 37.4220033,\n"
          + "               \"lng\" : -122.0839778\n"
          + "            },\n"
          + "            \"location_type\" : \"ROOFTOP\",\n"
          + "            \"viewport\" : {\n"
          + "               \"northeast\" : {\n"
          + "                  \"lat\" : 37.4233522802915,\n"
          + "                  \"lng\" : -122.0826288197085\n"
          + "               },\n"
          + "               \"southwest\" : {\n"
          + "                  \"lat\" : 37.4206543197085,\n"
          + "                  \"lng\" : -122.0853267802915\n"
          + "               }\n"
          + "            }\n"
          + "         },\n"
          + "         \"types\" : [ \"street_address\" ]\n"
          + "      }\n"
          + "   ],\n"
          + "   \"status\" : \"OK\"\n"
          + "}");

  return response;
}
 
Example 18
Source File: Dhis2MockServer.java    From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void enqueueMockResponse(int code, String response) {
    MockResponse mockResponse = new MockResponse();
    mockResponse.setResponseCode(code);
    mockResponse.setBody(response);
    server.enqueue(mockResponse);
}
 
Example 19
Source File: MockWebServerUtil.java    From gandalf with Apache License 2.0 3 votes vote down vote up
/**
 * Starts a mock web server to return the bootstrap file set using setMockBootstrapRes(Context context, int rawResourceId)
 * @param context
 * @return
 */
public static String startMockWebServer(@NonNull final Context context) {

    shutdownWebServer();
    mockWebServer = new MockWebServer();

    try {
        mockWebServer.start();

        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);

        int mockBootstrapResId = sharedPreferences.getInt(KEY_BOOTSTRAP_RES_ID, R.raw.no_action_bootstrap);

        String mockBootstrapJsonBody = getMockJsonBootstrap(context, mockBootstrapResId);

        MockResponse mockResponse = new MockResponse();
        mockResponse.setResponseCode(200);
        mockResponse.setBody(mockBootstrapJsonBody);
        mockResponse.setBodyDelay(2, TimeUnit.SECONDS);

        mockWebServer.enqueue(mockResponse);

    } catch (IOException e) {
        throw new RuntimeException("Problem starting mock web server");
    }


    return String.valueOf(mockWebServer.url(""));
}
 
Example 20
Source File: MatchableCall.java    From RESTMock with Apache License 2.0 3 votes vote down vote up
/**
 * <p>Makes this {@code MatchableCall} return  given {@code responseStrings} responses (one by one) with the specified {@code
 * responseCode} as a
 * http status code</p>
 *
 * <p>This {@code MatchableCall} will be automatically scheduled within the {@code RESTMockServer} if you want to prevent that, see
 * {@link MatchableCall#dontSet()}</p>
 *
 * <p>If you specify more than one response, each consecutive call to server will return next response from the list, if number of
 * requests exceeds number of specified responses, the last response will be repeated</p>
 *
 * @param responseCode    a http response code to use for the response.
 * @param responseStrings strings to return for this matchableCall's request one for each consecutive request, last string
 *                        will be returned for all requests exceeding number of defined responses.
 * @return this {@code MatchableCall}
 */
public MatchableCall thenReturnString(int responseCode, String... responseStrings) {
    MockResponse[] mockResponses = new MockResponse[responseStrings.length];
    int i = 0;
    for (String responseString : responseStrings) {
        MockResponse response = new MockResponse();
        response.setBody(responseString);
        response.setResponseCode(responseCode);
        mockResponses[i++] = response;
    }
    return thenReturn(mockResponses);
}