Java Code Examples for okhttp3.mockwebserver.RecordedRequest#getPath()

The following examples show how to use okhttp3.mockwebserver.RecordedRequest#getPath() . 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: MarathonRecorderTest.java    From marathon-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Test that the URL is properly put through the replace macro and able to be populated with
 * Jenkins variables.
 *
 * @throws Exception
 */
@Test
public void testRecorderURLMacro() throws Exception {
    final MarathonRecorder marathonRecorder = new MarathonRecorder(TestUtils.getHttpAddresss(httpServer) + "${BUILD_NUMBER}");
    final FreeStyleProject project          = basicSetup(marathonRecorder);
    final FreeStyleBuild   build            = basicRunWithSuccess(project);

    assertEquals("Only 1 request should be made", 1, httpServer.getRequestCount());
    RecordedRequest request     = httpServer.takeRequest();
    String          requestPath = request.getPath();
    if (requestPath.contains("?")) {
        requestPath = requestPath.substring(0, requestPath.indexOf("?"));
    }

    assertEquals("App URL should have build number",
            "/" + String.valueOf(build.getNumber()) + "/v2/apps/myapp",
            requestPath);
}
 
Example 2
Source File: GeoApiContextTest.java    From google-maps-services-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueryParamsHaveOrderPreserved() throws Exception {
  // This test is important for APIs (such as the speed limits API) where multiple parameters
  // must be provided with the same name with order preserved.

  MockResponse response = new MockResponse();
  response.setResponseCode(200);
  response.setBody("{}");

  server.enqueue(response);
  server.start();

  setMockBaseUrl();
  builder
      .build()
      .get(new ApiConfig("/"), GeocodingApi.Response.class, "a", "1", "a", "2", "a", "3")
      .awaitIgnoreError();

  server.shutdown();
  RecordedRequest request = server.takeRequest();
  String path = request.getPath();
  assertTrue(path.contains("a=1&a=2&a=3"));
}
 
Example 3
Source File: YelpAPITest.java    From yelp-android with MIT License 6 votes vote down vote up
private void verifyRequest(String pathPrefix, Map<String, String> params) throws InterruptedException {
    RecordedRequest recordedRequest = mockServer.takeRequest();
    verifyAuthorizationHeader(recordedRequest.getHeaders().get("Authorization"));

    Assert.assertEquals("GET", recordedRequest.getMethod());

    String path = recordedRequest.getPath();
    Assert.assertTrue(path.startsWith(pathPrefix));
    if (params != null) {
        for (Map.Entry<String, String> param : params.entrySet()) {
            Assert.assertTrue(path.contains(param.getKey() + "=" + param.getValue()));
        }
    }

    Assert.assertEquals(0, recordedRequest.getBodySize());
}
 
Example 4
Source File: KubernetesCrudDispatcher.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Override
public MockResponse dispatch(RecordedRequest request) {
  String path = request.getPath();
  String method = request.getMethod();
  switch (method.toUpperCase()) {
    case POST:
      return handleCreate(path, request.getBody().readUtf8());
    case PUT:
      return handleReplace(path, request.getBody().readUtf8());
    case PATCH:
      return handlePatch(path, request.getBody().readUtf8());
    case GET:
      return detectWatchMode(path)? handleWatch(path): handleGet(path);
    case DELETE:
      return handleDelete(path);
    default:
      return null;
  }
}
 
Example 5
Source File: Dhis2Dispatcher.java    From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
    String method = request.getMethod().toUpperCase(Locale.getDefault());
    String path = request.getPath();

    String fileName = responseController.getBody(method, path);
    int httpCode = responseController.getCode(fileName);

    try {
        String body = fileReader.getStringFromFile(fileName);
        Log.i(DISPATCHER, String.format(method, path, body));
        return new MockResponse().setBody(body).setResponseCode(httpCode);
    } catch (IOException e) {
        return new MockResponse().setResponseCode(500).setBody("Error reading JSON file for MockServer");
    }
}
 
Example 6
Source File: MarathonStepTest.java    From marathon-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Test that the URL is properly put through the replace macro and able to be populated with
 * Jenkins variables.
 *
 * @throws Exception in some special instances
 */
@Test
public void testStepURLMacro() throws Exception {
    final String groovyScript = "node { " +
            "writeFile(encoding: 'utf-8', file: 'marathon.json', text: '{\"id\": \"myapp\"}');\n" +
            "marathon(url: '%s'); " +
            "}";

    TestUtils.enqueueJsonResponse(httpServer, GENERIC_RESPONSE);
    final String      url    = TestUtils.getHttpAddresss(httpServer) + "${BUILD_NUMBER}";
    final String      script = String.format(groovyScript, url);
    final WorkflowJob job    = basicSetupWithScript(script);
    final WorkflowRun run    = basicRunWithSuccess(job);

    assertEquals("Only 1 request should be made", 1, httpServer.getRequestCount());
    RecordedRequest request     = httpServer.takeRequest();
    String          requestPath = request.getPath();
    if (requestPath.contains("?")) {
        requestPath = requestPath.substring(0, requestPath.indexOf("?"));
    }

    assertEquals("App URL should have build number",
            "/" + String.valueOf(run.getNumber()) + "/v2/apps/myapp",
            requestPath);
}
 
Example 7
Source File: LappsRecommenderIntegrationTest.java    From inception with Apache License 2.0 6 votes vote down vote up
private Dispatcher buildDispatcher()
{
    return new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) {
            try {
                String url = request.getPath();
                String body = request.getBody().readUtf8();

                if (request.getPath().equals("/pos/predict")) {
                    String response = "";
                    return new MockResponse().setResponseCode(200).setBody(response);
                } else {
                    throw new RuntimeException("Invalid URL called: " + url);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    };
}
 
Example 8
Source File: CrudDispatcher.java    From mockwebserver with Apache License 2.0 6 votes vote down vote up
@Override
public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
    String path = request.getPath();
    String method = request.getMethod();

    switch (method.toUpperCase()) {
        case POST:
        case PUT:
            return handleCreate(path, request.getBody().readUtf8());
        case PATCH:
            return handlePatch(path, request.getBody().readUtf8());
        case GET:
            return handleGet(path);
        case DELETE:
            return handleDelete(path);
        default:
            return null;
    }
}
 
Example 9
Source File: WebViewDataTest.java    From focus-android with Mozilla Public License 2.0 6 votes vote down vote up
private void assertPathsHaveBeenRequested(MockWebServer webServer, String... paths) throws InterruptedException {
    final List<String> expectedPaths = new ArrayList<>(paths.length);
    Collections.addAll(expectedPaths, paths);

    RecordedRequest request;

    while ((request = webServer.takeRequest(waitingTime, TimeUnit.MILLISECONDS)) != null) {
        if (!expectedPaths.remove(request.getPath())) {
            throw new AssertionError("Unknown path requested: " + request.getPath());
        }
    }

    if (!expectedPaths.isEmpty()) {
        throw new AssertionError("Expected paths not requested: " + expectedPaths);
    }
}
 
Example 10
Source File: RecordedRequestMatcher.java    From auth0-java with MIT License 6 votes vote down vote up
private boolean hasQueryParameter(RecordedRequest item, Description mismatchDescription) {
    String path = item.getPath();
    boolean hasQuery = path.indexOf("?") > 0;
    if (!hasQuery) {
        mismatchDescription.appendText(" query was empty");
        return false;
    }

    String query = path.substring(path.indexOf("?") + 1, path.length());
    String[] parameters = query.split("&");
    for (String p : parameters) {
        if (p.startsWith(String.format("%s=", first))) {
            return true;
        }
    }
    mismatchDescription.appendValueList("Query parameters were {", ", ", "}.", parameters);
    return false;
}
 
Example 11
Source File: RecordedRequestMatcher.java    From auth0-java with MIT License 6 votes vote down vote up
private boolean matchesMethodAndPath(RecordedRequest item, Description mismatchDescription) {
    if (!item.getMethod().equalsIgnoreCase(first)) {
        mismatchDescription.appendText("method was ").appendValue(item.getMethod());
        return false;
    }
    String path = item.getPath();
    boolean hasQuery = path.indexOf("?") > 0;
    if (hasQuery) {
        path = path.substring(0, path.indexOf("?"));
    }
    if (!path.equals(second)) {
        mismatchDescription.appendText("path was ").appendValue(path);
        return false;
    }

    return true;
}
 
Example 12
Source File: UsersClientTest.java    From blog-tutorials with MIT License 6 votes vote down vote up
@Test
public void testMultipleResponseCodes() {

  final Dispatcher dispatcher = new Dispatcher() {
    @Override
    public MockResponse dispatch(RecordedRequest request) {
      switch (request.getPath()) {
        case "/users/1":
          return new MockResponse().setResponseCode(200);
        case "/users/2":
          return new MockResponse().setResponseCode(500);
        case "/users/3":
          return new MockResponse().setResponseCode(200).setBody("{\"id\": 1, \"name\":\"duke\"}");
      }
      return new MockResponse().setResponseCode(404);
    }
  };

  mockWebServer.setDispatcher(dispatcher);

  assertThrows(WebClientResponseException.class, () -> usersClient.getUserById(2L));
  assertThrows(WebClientResponseException.class, () -> usersClient.getUserById(4L));
}
 
Example 13
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 14
Source File: LocalResponseDispatcher.java    From mockstar with MIT License 5 votes vote down vote up
private String getScenario(RecordedRequest request) {
    String scenario = "";

    String path = request.getPath();
    String requestedMethod = request.getMethod().toLowerCase(Locale.US);

    scenario += requestedMethod + path.replace("/", "_") + ".json";
    return scenario;
}
 
Example 15
Source File: RequestMatchersGroup.java    From requestmatcher with Apache License 2.0 4 votes vote down vote up
/**
 * Main assert method called in the {@link okhttp3.mockwebserver.MockWebServer} dispatching.
 */
public void doAssert(@NonNull final RecordedRequest request, final int currentOrder) {

    if (methodMatcher != null) {
        assertThat(METHOD_MSG, HttpMethod.forRequest(request), methodMatcher);
    }

    if (pathMatcher != null) {
        assertThat(PATH_MSG, RequestUtils.getPathOnly(request), pathMatcher);
    }

    final String path = request.getPath();

    if (queryMatcher != null) {

        if (!path.contains("?")) {
            assertThat(QUERIES_MSG, new HashMap<String, String>(0), queryMatcher);
        } else {
            assertThat(QUERIES_MSG, RequestUtils.buildQueryMap(path), queryMatcher);
        }
    }

    if (headersMatcher != null) {
        assertThat(HEADERS_MSG,
                RequestUtils.buildHeadersMap(request.getHeaders()), headersMatcher);
    }

    // clone the body! perhaps we need the request body for a future assertion.
    final String body = request.getBody().clone().readUtf8();

    if (bodyMatcher != null) {
        assertThat(BODY_MSG, body, bodyMatcher);
    }

    if (jsonMatcher != null) {
        assertThat(JSON_MSG, body, jsonMatcher);
    }

    if (orderMatcher != null) {
        assertThat(ORDER_MSG, currentOrder, orderMatcher);
    }
}
 
Example 16
Source File: Dhis2MockServer.java    From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void setRequestDispatcher() {
    final Dispatcher dispatcher = new Dispatcher() {

        @Override
        public MockResponse dispatch(RecordedRequest request) {

            String path = request.getPath();
            if (path.startsWith("/api/me?")) {
                return createMockResponse(USER_JSON);
            } else if ("/api/me/authorization".equals(path)) {
                return createMockResponse(AUTHORITIES_JSON);
            } else if (path.startsWith("/api/system/info?")) {
                return createMockResponse(SYSTEM_INFO_JSON);
            } else if (path.startsWith("/api/systemSettings?")) {
                return createMockResponse(SYSTEM_SETTINGS_JSON);
            } else if (path.startsWith("/api/dataStore/ANDROID_SETTING_APP/general_settings")) {
                return createMockResponse(GENERAL_SETTINGS_JSON);
            } else if (path.startsWith("/api/dataStore/ANDROID_SETTING_APP/dataSet_settings")) {
                return createMockResponse(DATASET_SETTINGS_JSON);
            } else if (path.startsWith("/api/dataStore/ANDROID_SETTING_APP/program_settings")) {
                return createMockResponse(PROGRAM_SETTINGS_JSON);
            } else if (path.startsWith("/api/programs?")) {
                return createMockResponse(PROGRAMS_JSON);
            } else if (path.startsWith("/api/programStages?")) {
                return createMockResponse(PROGRAM_STAGES_JSON);
            } else if (path.startsWith("/api/programRules?")) {
                return createMockResponse(PROGRAM_RULES_JSON);
            } else if (path.startsWith("/api/trackedEntityTypes?")) {
                return createMockResponse(TRACKED_ENTITY_TYPES_JSON);
            } else if (path.startsWith("/api/trackedEntityAttributes?")) {
                return createMockResponse(TRACKED_ENTITY_ATTRIBUTES_JSON);
            } else if (path.startsWith("/api/relationshipTypes?")) {
                return createMockResponse(RELATIONSHIP_TYPES_JSON);
            } else if (path.startsWith("/api/optionSets?")) {
                return createMockResponse(OPTION_SETS_JSON);
            } else if (path.startsWith("/api/options?")) {
                return createMockResponse(OPTIONS_JSON);
            } else if (path.startsWith("/api/optionGroups?")) {
                return createMockResponse(OPTION_GROUPS_JSON);
            } else if (path.startsWith("/api/dataSets?")) {
                return createMockResponse(DATA_SETS_JSON);
            } else if (path.startsWith("/api/dataElements?")) {
                return createMockResponse(DATA_ELEMENTS_JSON);
            } else if (path.startsWith("/api/indicators?")) {
                return createMockResponse(INDICATORS_JSON);
            } else if (path.startsWith("/api/indicatorTypes?")) {
                return createMockResponse(INDICATOR_TYPES_JSON);
            } else if (path.startsWith("/api/categoryCombos?")) {
                return createMockResponse(CATEGORY_COMBOS_JSON);
            } else if (path.startsWith("/api/categories?")) {
                return createMockResponse(CATEGORIES_JSON);
            } else if (path.startsWith("/api/organisationUnits?")) {
                return createMockResponse(ORGANISATION_UNITS_JSON);
            } else if (path.startsWith("/api/organisationUnitLevels?")) {
                return createMockResponse(ORGANISATION_UNIT_LEVELS_JSON);
            } else if (path.startsWith("/api/constants?")) {
                return createMockResponse(CONSTANTS_JSON);
            } else if (path.startsWith("/api/trackedEntityInstances?")) {
                return createMockResponse(TRACKED_ENTITY_INSTANCES_JSON);
            } else if (path.startsWith("/api/events?")) {
                return createMockResponse(EVENTS_JSON);
            } else if (path.startsWith("/api/dataValueSets?")) {
                return createMockResponse(DATA_VALUES_JSON);
            } else if (path.startsWith("/api/completeDataSetRegistrations?")) {
                return createMockResponse(DATA_SET_COMPLETE_REGISTRATIONS_JSON);
            } else if (path.startsWith("/api/dataApprovals/multiple?")) {
                return createMockResponse(DATA_APPROVALS_MULTIPLE_JSON);
            } else {
                return new MockResponse()
                        .setResponseCode(404)
                        .setBody("Path not present in Dhis2MockServer dispatcher");
            }
        }
    };
    server.setDispatcher(dispatcher);
}
 
Example 17
Source File: ServerTest.java    From java-stellar-sdk with Apache License 2.0 4 votes vote down vote up
private Dispatcher buildTestCheckMemoRequiredMockDispatcher() {
    final String memoRequiredResponse = "{\n" +
            "    \"data\": {\n" +
            "        \"config.memo_required\": \"MQ==\"\n" +
            "    }\n" +
            "}";
    final String noMemoRequiredResponse = "{\n" +
            "    \"data\": {\n" +
            "    }\n" +
            "}";
    final String successTransactionResponse =
            "{\n" +
                    "  \"_links\": {\n" +
                    "    \"transaction\": {\n" +
                    "      \"href\": \"/transactions/2634d2cf5adcbd3487d1df042166eef53830115844fdde1588828667bf93ff42\"\n" +
                    "    }\n" +
                    "  },\n" +
                    "  \"hash\": \"2634d2cf5adcbd3487d1df042166eef53830115844fdde1588828667bf93ff42\",\n" +
                    "  \"ledger\": 826150,\n" +
                    "  \"envelope_xdr\": \"AAAAAKu3N77S+cHLEDfVD2eW/CqRiN9yvAKH+qkeLjHQs1u+AAAAZAAMkoMAAAADAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAbYQq8ek1GitmNBUloGnetfWxSpxlsgK48Xi66dIL3MoAAAAAC+vCAAAAAAAAAAAB0LNbvgAAAEDadQ25SNHWTg0L+2wr/KNWd8/EwSNFkX/ncGmBGA3zkNGx7lAow78q8SQmnn2IsdkD9MwICirhsOYDNbaqShwO\",\n" +
                    "  \"result_xdr\": \"AAAAAAAAAGQAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAA=\",\n" +
                    "  \"result_meta_xdr\": \"AAAAAAAAAAEAAAACAAAAAAAMmyYAAAAAAAAAAG2EKvHpNRorZjQVJaBp3rX1sUqcZbICuPF4uunSC9zKAAAAAAvrwgAADJsmAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAQAMmyYAAAAAAAAAAKu3N77S+cHLEDfVD2eW/CqRiN9yvAKH+qkeLjHQs1u+AAAAFzCfYtQADJKDAAAAAwAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAA\"\n" +
                    "}";
    final String rootResponse = "{\n" +
            "  \"_links\": {\n" +
            "    \"account\": {\n" +
            "      \"href\": \"https://horizon.stellar.org/accounts/{account_id}\",\n" +
            "      \"templated\": true\n" +
            "    },\n" +
            "    \"account_transactions\": {\n" +
            "      \"href\": \"https://horizon.stellar.org/accounts/{account_id}/transactions{?cursor,limit,order}\",\n" +
            "      \"templated\": true\n" +
            "    },\n" +
            "    \"assets\": {\n" +
            "      \"href\": \"https://horizon.stellar.org/assets{?asset_code,asset_issuer,cursor,limit,order}\",\n" +
            "      \"templated\": true\n" +
            "    },\n" +
            "    \"metrics\": {\n" +
            "      \"href\": \"https://horizon.stellar.org/metrics\"\n" +
            "    },\n" +
            "    \"order_book\": {\n" +
            "      \"href\": \"https://horizon.stellar.org/order_book{?selling_asset_type,selling_asset_code,selling_asset_issuer,buying_asset_type,buying_asset_code,buying_asset_issuer,limit}\",\n" +
            "      \"templated\": true\n" +
            "    },\n" +
            "    \"self\": {\n" +
            "      \"href\": \"https://horizon.stellar.org/\"\n" +
            "    },\n" +
            "    \"transaction\": {\n" +
            "      \"href\": \"https://horizon.stellar.org/transactions/{hash}\",\n" +
            "      \"templated\": true\n" +
            "    },\n" +
            "    \"transactions\": {\n" +
            "      \"href\": \"https://horizon.stellar.org/transactions{?cursor,limit,order}\",\n" +
            "      \"templated\": true\n" +
            "    }\n" +
            "  },\n" +
            "  \"horizon_version\": \"0.18.0-92259749c681df66a8347f846e94681a24f2a920\",\n" +
            "  \"core_version\": \"stellar-core 11.1.0 (324c1bd61b0e9bada63e0d696d799421b00a7950)\",\n" +
            "  \"history_latest_ledger\": 24345129,\n" +
            "  \"history_elder_ledger\": 1,\n" +
            "  \"core_latest_ledger\": 24345130,\n" +
            "  \"network_passphrase\": \"Public Global Stellar Network ; September 2015\",\n" +
            "  \"current_protocol_version\": 11,\n" +
            "  \"core_supported_protocol_version\": 11\n" +
            "}";

    Dispatcher dispatcher = new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) {
            String path = request.getPath();
            if ("/".equals(path)) {
                return new MockResponse().setResponseCode(200).setBody(rootResponse);
            }
            if (String.format("/accounts/%s", DESTINATION_ACCOUNT_MEMO_REQUIRED_A).equals(path) ||
                    String.format("/accounts/%s", DESTINATION_ACCOUNT_MEMO_REQUIRED_B).equals(path) ||
                    String.format("/accounts/%s", DESTINATION_ACCOUNT_MEMO_REQUIRED_C).equals(path) ||
                    String.format("/accounts/%s", DESTINATION_ACCOUNT_MEMO_REQUIRED_D).equals(path)) {
                return new MockResponse().setResponseCode(200).setBody(memoRequiredResponse);
            } else if (String.format("/accounts/%s", DESTINATION_ACCOUNT_NO_MEMO_REQUIRED).equals(path)) {
                return new MockResponse().setResponseCode(200).setBody(noMemoRequiredResponse);
            } else if (String.format("/accounts/%s", DESTINATION_ACCOUNT_NO_FOUND).equals(path)) {
                return new MockResponse().setResponseCode(404);
            } else if (String.format("/accounts/%s", DESTINATION_ACCOUNT_FETCH_ERROR).equals(path)) {
                return new MockResponse().setResponseCode(400);
            } else if ("/transactions".equals(path)) {
                return new MockResponse().setResponseCode(200).setBody(successTransactionResponse);
            } else {
                return new MockResponse().setResponseCode(404);
            }
        }
    };
    return dispatcher;
}
 
Example 18
Source File: OpenShiftServiceImplTest.java    From syndesis with Apache License 2.0 4 votes vote down vote up
private static Request createFrom(RecordedRequest req) {
    return new Request(req.getMethod(), req.getPath(), req.getBody().readUtf8());
}
 
Example 19
Source File: ZooniverseClientTest.java    From android-galaxyzoo with GNU General Public License v3.0 4 votes vote down vote up
@Test
public void testMoreItems() throws IOException, InterruptedException, ZooniverseClient.RequestMoreItemsException {
    final MockWebServer server = new MockWebServer();

    final String strResponse = getStringFromStream(
            MoreItemsJsonParserTest.class.getClassLoader().getResourceAsStream("test_more_items_response.json"));
    assertNotNull(strResponse);
    server.enqueue(new MockResponse().setBody(strResponse));
    server.start();

    final ZooniverseClient client = createZooniverseClient(server);

    final int COUNT = 10;
    final List<ZooniverseClient.Subject> subjects = client.requestMoreItemsSync(TEST_GROUP_ID, COUNT);
    assertNotNull(subjects);
    assertEquals(COUNT, subjects.size());

    final ZooniverseClient.Subject subject = subjects.get(0);
    assertNotNull(subject);

    assertNotNull(subject.getId());
    assertEquals("16216418", subject.getId());

    // This is apparently always null in the JSON.
    // assertNotNull(subject.getZooniverseId());
    // assertEquals("AGZ00081ls", subject.getZooniverseId());

    // TODO
    // assertNotNull(subject.getGroupId());
    // assertEquals(TEST_GROUP_ID, subject.getGroupId());

    assertNotNull(subject.getLocationStandard());
    assertEquals("https://panoptes-uploads.zooniverse.org/production/subject_location/772f8b1b-b0fe-4dac-9afe-472f3e8d381a.jpeg",
            subject.getLocationStandard());
    /* TODO:
    assertNotNull(subject.getLocationThumbnail());
    assertEquals("http://www.galaxyzoo.org.s3.amazonaws.com/subjects/thumbnail/goods_full_n_27820_thumbnail.jpg",
            subject.getLocationThumbnail());
    assertNotNull(subject.getLocationInverted());
    assertEquals("http://www.galaxyzoo.org.s3.amazonaws.com/subjects/inverted/goods_full_n_27820_inverted.jpg",
            subject.getLocationInverted());
    */


    //Test what the server received:
    assertEquals(1, server.getRequestCount());
    final RecordedRequest request = server.takeRequest();
    assertEquals("GET", request.getMethod());

    //ZooniverseClient uses one of several possible group IDs at random:
    //See com.murrayc.galaxyzoo.app.provider.Config
    // TODO: Use more.  /subjects/queued?http_cache=true&workflow_id=5853fab395ad361930000003&limit=5
    final String possiblePath1 = "/subjects/queued?http_cache=true&workflow_id=" + TEST_GROUP_ID + "&limit=5";
    final String possiblePath2 = "/subjects/queued?http_cache=true&workflow_id=" + Config.SUBJECT_GROUP_ID_GAMA_15 + "&limit=5";

    //TODO: Can we use this?
    // assertThat(request.getPath(), anyOf(is(possiblePath1), is(possiblePath2)));
    final String path = request.getPath();
    assertEquals(possiblePath1, path);
    assertTrue( path.equals(possiblePath1) || path.equals(possiblePath2));

    server.shutdown();
}
 
Example 20
Source File: RequestUtils.java    From requestmatcher with Apache License 2.0 3 votes vote down vote up
public static String getPathOnly(RecordedRequest request) {

        final String path = request.getPath();

        if (!path.contains("?")) {
            return path;
        }

        return path.substring(0, path.indexOf('?'));
    }