io.restassured.response.Response Java Examples
The following examples show how to use
io.restassured.response.Response.
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: DecisionRequirementsDefinitionRestServiceQueryTest.java From camunda-bpm-platform with Apache License 2.0 | 6 votes |
@Test public void testDecisionRequirementsDefinitionRetrievalByList() { mockedQuery = createMockQuery(MockProvider.createMockTwoDecisionRequirementsDefinitions()); Response response = given() .queryParam("decisionRequirementsDefinitionIdIn", MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID_LIST) .then().expect() .statusCode(Status.OK.getStatusCode()) .when() .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL); // assert query invocation InOrder inOrder = Mockito.inOrder(mockedQuery); inOrder.verify(mockedQuery).decisionRequirementsDefinitionIdIn(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID, MockProvider.ANOTHER_EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID); inOrder.verify(mockedQuery).list(); String content = response.asString(); List<String> definitions = from(content).getList(""); assertThat(definitions).hasSize(2); String returnedDefinitionId1 = from(content).getString("[0].id"); String returnedDefinitionId2 = from(content).getString("[1].id"); assertThat(returnedDefinitionId1).isEqualTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID); assertThat(returnedDefinitionId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID); }
Example #2
Source File: HistoricExternalTaskLogRestServiceQueryTest.java From camunda-bpm-platform with Apache License 2.0 | 6 votes |
@Test public void testQueryWithoutTenantIdPostParameter() { // given mockedQuery = setUpMockHistoricExternalTaskLogQuery(Collections.singletonList(MockProvider.createMockHistoricExternalTaskLog(null))); Map<String, Object> queryParameters = Collections.singletonMap("withoutTenantId", (Object) true); // when Response response = given() .contentType(POST_JSON_CONTENT_TYPE) .body(queryParameters) .expect() .statusCode(Status.OK.getStatusCode()) .when() .post(HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL); // then verify(mockedQuery).withoutTenantId(); verify(mockedQuery).list(); String content = response.asString(); List<String> definitions = from(content).getList(""); assertThat(definitions).hasSize(1); String returnedTenantId = from(content).getString("[0].tenantId"); assertThat(returnedTenantId).isEqualTo(null); }
Example #3
Source File: NotificationUtils.java From carina with Apache License 2.0 | 6 votes |
/** * get Push Service Response * * @param contentType String * @param request String * @param url String * @param responseLog boolean * @return JsonObject */ public static JsonObject getPushServiceResponse(String contentType, String request, String url, boolean responseLog) { try { LOGGER.info("Request url: " + url); Response response = RestUtil.sendHttpPost(contentType, request, url.toString(), responseLog); if (response.getStatusCode() == 200) { LOGGER.debug("Call passed with status code '" + response.getStatusCode() + "'. "); JsonParser parser = new JsonParser(); return parser.parse(response.asString()).getAsJsonObject(); } else { LOGGER.error("Call failed with status code '" + response.getStatusCode() + "'. "); } } catch (Exception e) { LOGGER.error("getPushServiceResponse failure", e); } return null; }
Example #4
Source File: BasicChecks.java From heat with Apache License 2.0 | 6 votes |
/** * Json Schema validation. * * @param isBlocking boolean value: if it is true, in case of failure the * test stops running, otherwise it will go on running with the other checks * (the final result does not change) * @param resp Response retrieved * @param jsonSchemaPath path of the json schema to use for the check * @return true if the check is ok, false otherwise */ private boolean validateSchema(boolean isBlocking, Response resp, String jsonSchemaPath) { boolean isCheckOk = true; try { JsonSchemaValidator validator = JsonSchemaValidator.matchesJsonSchemaInClasspath(jsonSchemaPath); resp.then().assertThat().body(validator); logUtils.debug("json schema validation OK"); } catch (Exception oEx) { isCheckOk = false; logUtils.error("json schema validation NOT OK"); assertionHandler.assertion(isBlocking, "fail", logUtils.getTestCaseDetails() + "BasicChecks - validateSchema >> validation schema failed. -- exception: " + oEx.getLocalizedMessage()); } return isCheckOk; }
Example #5
Source File: DeploymentRestServiceInteractionTest.java From camunda-bpm-platform with Apache License 2.0 | 6 votes |
@Test public void testGetDeploymentDmnResourceData() { Resource resource = MockProvider.createMockDeploymentDmnResource(); List<Resource> resources = new ArrayList<Resource>(); resources.add(resource); InputStream input = new ByteArrayInputStream(createMockDeploymentResourceByteData()); when(mockRepositoryService.getDeploymentResources(eq(EXAMPLE_DEPLOYMENT_ID))).thenReturn(resources); when(mockRepositoryService.getResourceAsStreamById(eq(EXAMPLE_DEPLOYMENT_ID), eq(EXAMPLE_DEPLOYMENT_DMN_RESOURCE_ID))).thenReturn(input); Response response = given() .pathParam("id", EXAMPLE_DEPLOYMENT_ID) .pathParam("resourceId", EXAMPLE_DEPLOYMENT_DMN_RESOURCE_ID) .then() .expect() .statusCode(Status.OK.getStatusCode()) .contentType(ContentType.XML) .header("Content-Disposition", "attachment; filename=\"" + MockProvider.EXAMPLE_DEPLOYMENT_DMN_RESOURCE_NAME + "\"") .when().get(SINGLE_RESOURCE_DATA_URL); String responseContent = response.asString(); assertNotNull(responseContent); }
Example #6
Source File: DecisionRequirementsDefinitionRestServiceQueryTest.java From camunda-bpm-platform with Apache License 2.0 | 6 votes |
@Test public void testDecisionRequirementsDefinitionWithoutTenantId() { Response response = given() .queryParam("withoutTenantId", true) .then().expect() .statusCode(Status.OK.getStatusCode()) .when() .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL); verify(mockedQuery).withoutTenantId(); verify(mockedQuery).list(); String content = response.asString(); List<String> definitions = from(content).getList(""); assertThat(definitions).hasSize(1); String returnedTenantId1 = from(content).getString("[0].tenantId"); assertThat(returnedTenantId1).isEqualTo(null); }
Example #7
Source File: ReusedMetricsTest.java From microprofile-metrics with Apache License 2.0 | 6 votes |
@Test @RunAsClient @InSequence(2) public void testSharedCounter() { Header acceptJson = new Header("Accept", APPLICATION_JSON); Response resp = given().header(acceptJson).get("/metrics/application"); JsonPath filteredJSONPath = new JsonPath(resp.jsonPath().prettify().replaceAll(JSON_APP_LABEL_REGEX, JSON_APP_LABEL_REGEXS_SUB)); ResponseBuilder responseBuilder = new ResponseBuilder(); responseBuilder.clone(resp); responseBuilder.setBody(filteredJSONPath.prettify()); resp = responseBuilder.build(); resp.then() .assertThat().body("'countMe2;tier=integration'", equalTo(1)) .assertThat().body("'org.eclipse.microprofile.metrics.test.MetricAppBean2.meterMe2'.'count;tier=integration'", equalTo(1)) .assertThat().body("'timeMe2'.'count;tier=integration'", equalTo(1)) .assertThat().body("'simplyTimeMe2'.'count;tier=integration'", equalTo(1)); }
Example #8
Source File: ApplicationTest.java From prebid-server-java with Apache License 2.0 | 6 votes |
@Test public void vtrackShouldReturnJsonWithUids() throws JSONException, IOException { // given and when WIRE_MOCK_RULE.stubFor(post(urlPathEqualTo("/cache")) .withRequestBody(equalToJson(jsonFrom("vtrack/test-cache-request.json"), true, false)) .willReturn(aResponse().withBody(jsonFrom("vtrack/test-vtrack-response.json")))); final Response response = given(SPEC) .when() .body(jsonFrom("vtrack/test-vtrack-request.json")) .queryParam("a", "14062") .post("/vtrack"); // then JSONAssert.assertEquals("{\"responses\":[{\"uuid\":\"94531ab8-c662-4fc7-904e-6b5d3be43b1a\"}]}", response.asString(), JSONCompareMode.NON_EXTENSIBLE); }
Example #9
Source File: DeploymentRestServiceInteractionTest.java From camunda-bpm-platform with Apache License 2.0 | 6 votes |
@Test public void testRedeployDeploymentEmptyRequestBody() { Response response = given() .pathParam("id", MockProvider.EXAMPLE_DEPLOYMENT_ID) .contentType(POST_JSON_CONTENT_TYPE) .body("{}") .expect() .statusCode(Status.OK.getStatusCode()) .contentType(ContentType.JSON) .when() .post(REDEPLOY_DEPLOYMENT_URL); verify(mockDeploymentBuilder).addDeploymentResources(eq(MockProvider.EXAMPLE_DEPLOYMENT_ID)); verify(mockDeploymentBuilder).nameFromDeployment(eq(MockProvider.EXAMPLE_DEPLOYMENT_ID)); verify(mockDeploymentBuilder, never()).addDeploymentResourceById(anyString(), anyString()); verify(mockDeploymentBuilder, never()).addDeploymentResourcesById(eq(MockProvider.EXAMPLE_DEPLOYMENT_ID), anyListOf(String.class)); verify(mockDeploymentBuilder, never()).addDeploymentResourceByName(anyString(), anyString()); verify(mockDeploymentBuilder, never()).addDeploymentResourcesByName(eq(MockProvider.EXAMPLE_DEPLOYMENT_ID), anyListOf(String.class)); verify(mockDeploymentBuilder).source(null); verify(mockDeploymentBuilder).deployWithResult(); verifyDeployment(mockDeployment, response); }
Example #10
Source File: HistoricJobLogRestServiceQueryTest.java From camunda-bpm-platform with Apache License 2.0 | 6 votes |
@Test public void testQueryWithoutTenantIdQueryParameter() { // given HistoricJobLog jobLog = MockProvider.createMockHistoricJobLog(null); mockedQuery = setUpMockHistoricJobLogQuery(Collections.singletonList(jobLog)); // when Response response = given() .queryParam("withoutTenantId", true) .then().expect() .statusCode(Status.OK.getStatusCode()) .when() .get(HISTORIC_JOB_LOG_RESOURCE_URL); // then verify(mockedQuery).withoutTenantId(); verify(mockedQuery).list(); String content = response.asString(); List<String> definitions = from(content).getList(""); assertThat(definitions).hasSize(1); String returnedTenantId = from(content).getString("[0].tenantId"); assertThat(returnedTenantId).isEqualTo(null); }
Example #11
Source File: OperationHandler.java From heat with Apache License 2.0 | 6 votes |
private String retrieveObj(String objName, Map<String, Object> singleCheckMap, Map<String, Response> mapServiceIdResponse) { Map<String, Object> objMapRetrieved = (Map<String, Object>) singleCheckMap.get(objName); String strRetrieved = ""; try { if (objMapRetrieved.containsKey(JSON_ELEM_ACTUAL_VALUE)) { if (objMapRetrieved.containsKey(JSON_ELEM_REFERRING_OBJECT)) { Response rsp = mapServiceIdResponse.get(objMapRetrieved.get(JSON_ELEM_REFERRING_OBJECT).toString()); DataExtractionSupport dataSupport = new DataExtractionSupport(this.logUtils); strRetrieved = dataSupport.process(objMapRetrieved.get(JSON_ELEM_ACTUAL_VALUE), rsp, retrievedParameters); } else { if (!objMapRetrieved.get(JSON_ELEM_ACTUAL_VALUE).toString().contains(PlaceholderHandler.PLACEHOLDER_SYMBOL_BEGIN)) { strRetrieved = objMapRetrieved.get(JSON_ELEM_ACTUAL_VALUE).toString(); } else { throw new HeatException(this.logUtils.getExceptionDetails() + "Input Json does not contain 'referringObjectName' field"); } } } else { throw new HeatException(this.logUtils.getExceptionDetails() + "Input Json does not contain 'actualValue' field"); } } catch (Exception oEx) { throw new HeatException(this.logUtils.getExceptionDetails() + "Exception occurred: '" + oEx.getLocalizedMessage() + "'"); } return strRetrieved; }
Example #12
Source File: UserInfoEndpointLiveTest.java From tutorials with MIT License | 6 votes |
private String obtainAccessTokenUsingAuthorizationCodeFlow(String username, String password) { final String authServerUri = "http://localhost:8081/auth"; final String redirectUrl = "http://www.example.com/"; final String authorizeUrl = authServerUri + "/oauth/authorize?response_type=code&client_id=SampleClientId&redirect_uri=" + redirectUrl; final String tokenUrl = authServerUri + "/oauth/token"; // user login Response response = RestAssured.given().formParams("username", username, "password", password).post(authServerUri + "/login"); final String cookieValue = response.getCookie("JSESSIONID"); // get authorization code RestAssured.given().cookie("JSESSIONID", cookieValue).get(authorizeUrl); response = RestAssured.given().cookie("JSESSIONID", cookieValue).post(authorizeUrl); assertEquals(HttpStatus.FOUND.value(), response.getStatusCode()); final String location = response.getHeader(HttpHeaders.LOCATION); final String code = location.substring(location.indexOf("code=") + 5); // get access token Map<String, String> params = new HashMap<String, String>(); params.put("grant_type", "authorization_code"); params.put("code", code); params.put("client_id", "SampleClientId"); params.put("redirect_uri", redirectUrl); response = RestAssured.given().auth().basic("SampleClientId", "secret").formParams(params).post(tokenUrl); return response.jsonPath().getString("access_token"); }
Example #13
Source File: OperationHandler.java From heat with Apache License 2.0 | 6 votes |
private boolean checkGenericFields(Object actualValue, String expectedValue) { boolean isExecutionOk; String processedActualValue = dataExtractionSupport.process(actualValue, (Response) responses, retrievedParameters); String operationToExecute = loadOperationToExecuteOrDefault(StringValidator.STRING_OPERATOR_EQUALS_TO); loadCheckDescription(); String operationDescription = checkDescription + " --> '" + processedActualValue + "' '" + operationToExecute + "' '" + expectedValue + "'"; this.logUtils.debug("{}: actualValue '{}' (processed '{}') / operation '{}' / expectedValue '{}'", checkDescription, actualValue, processedActualValue, operationToExecute, expectedValue); try { String fieldCheckFormat = loadFieldCheckFormatOrDefault("int"); isExecutionOk = mathOrStringChecks(operationToExecute, processedActualValue, expectedValue, fieldCheckFormat); } catch (Exception oEx) { logUtils.error("Exception: class {}, cause {}, message {}", oEx.getClass(), oEx.getCause(), oEx.getLocalizedMessage()); operationDescription = "<" + operationDescription + ">"; throw new HeatException(logUtils.getExceptionDetails() + "It is not possible to execute the check " + operationDescription); } return isExecutionOk; }
Example #14
Source File: RequestVerifierFilter.java From spring-cloud-netflix with Apache License 2.0 | 6 votes |
@Override public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec, FilterContext context) { Map<String, Object> configuration = getConfiguration(requestSpec, context); configuration.put("contract.jsonPaths", this.jsonPaths.keySet()); Response response = context.next(requestSpec, responseSpec); if (requestSpec.getBody() != null && !this.jsonPaths.isEmpty()) { String actual = new String((byte[]) requestSpec.getBody()); for (JsonPath jsonPath : this.jsonPaths.values()) { new JsonPathValue(jsonPath, actual).assertHasValue(Object.class, "an object"); } } if (this.builder != null) { this.builder.willReturn(getResponseDefinition(response)); StubMapping stubMapping = this.builder.build(); MatchResult match = stubMapping.getRequest() .match(new WireMockRestAssuredRequestAdapter(requestSpec)); assertThat(match.isExactMatch()).as("wiremock did not match request") .isTrue(); configuration.put("contract.stubMapping", stubMapping); } return response; }
Example #15
Source File: TracksAppAsApi.java From tracksrestcasestudy with MIT License | 6 votes |
private Response loginUserPost(String username, String password, String authenticityToken) { UrlParams params = new UrlParams(); params.add("utf8","%E2%9C%93"); params.addEncoded("authenticity_token", authenticityToken); params.add("user_login", username); params.add("user_password", password); params.add("user_noexpiry", "on"); params.add("login", "Sign+in"); Response response = httpMessageSender.postFormMessageTo( params.toString(), "/login"); return response; }
Example #16
Source File: HistoricCaseActivityInstanceRestServiceQueryTest.java From camunda-bpm-platform with Apache License 2.0 | 6 votes |
@Test public void testFinishedHistoricCaseActivityQuery() { Response response = given() .queryParam("finished", true) .then().expect() .statusCode(Status.OK.getStatusCode()) .when() .get(HISTORIC_CASE_ACTIVITY_INSTANCE_RESOURCE_URL); InOrder inOrder = inOrder(mockedQuery); inOrder.verify(mockedQuery).ended(); inOrder.verify(mockedQuery).list(); String content = response.asString(); List<String> instances = from(content).getList(""); Assert.assertEquals(1, instances.size()); Assert.assertNotNull(instances.get(0)); String returnedCaseDefinitionId = from(content).getString("[0].caseDefinitionId"); String returnedActivityEndTime = from(content).getString("[0].endTime"); Assert.assertEquals(MockProvider.EXAMPLE_CASE_DEFINITION_ID, returnedCaseDefinitionId); Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_END_TIME, returnedActivityEndTime); }
Example #17
Source File: TracksAppAsApi.java From tracksrestcasestudy with MIT License | 6 votes |
private Response createUserPost(String username, String password, String authenticityToken, Map<String, String> loggedInCookieJar) { UrlParams params = new UrlParams(); params.add("utf8","%E2%9C%93"); params.addEncoded("authenticity_token", authenticityToken); params.add("user%5Blogin%5D", username); params.add("user%5Bpassword%5D", password); params.add("user%5Bpassword_confirmation%5D", password); Response response = httpMessageSender.postFormMessageTo( params.toString(), "/users", loggedInCookieJar); return response; }
Example #18
Source File: HistoricProcessInstanceRestServiceInteractionTest.java From camunda-bpm-platform with Apache License 2.0 | 6 votes |
@Test public void shouldSetRemovalTime_Response() { SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder builderMock = mock(SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder.class, RETURNS_DEEP_STUBS); when(historyServiceMock.setRemovalTimeToHistoricProcessInstances()).thenReturn(builderMock); Batch batchEntity = MockProvider.createMockBatch(); when(builderMock.executeAsync()).thenReturn(batchEntity); Response response = given() .contentType(ContentType.JSON) .body(Collections.emptyMap()) .then() .expect().statusCode(Status.OK.getStatusCode()) .when() .post(SET_REMOVAL_TIME_HISTORIC_PROCESS_INSTANCES_ASYNC_URL); verifyBatchJson(response.asString()); }
Example #19
Source File: SentinelJaxRsQuarkusAdapterTest.java From Sentinel with Apache License 2.0 | 5 votes |
@Test public void testCustomRequestOriginParser() { String url = "/test/hello"; String resourceName = "GET:" + url; String limitOrigin = "appB"; final String headerName = "X-APP"; configureRulesFor(resourceName, 0, limitOrigin); SentinelJaxRsConfig.setRequestOriginParser(new RequestOriginParser() { @Override public String parseOrigin(ContainerRequestContext request) { String origin = request.getHeaderString(headerName); return origin != null ? origin : ""; } }); Response response = given() .header(headerName, "appA").get(url); response.then().statusCode(200).body(equalTo(HELLO_STR)); Response blockedResp = given() .header(headerName, "appB") .get(url); blockedResp.then().statusCode(javax.ws.rs.core.Response.Status.TOO_MANY_REQUESTS.getStatusCode()) .body(equalTo("Blocked by Sentinel (flow limiting)")); ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName); assertNotNull(cn); assertEquals(1, cn.passQps(), 0.01); assertEquals(1, cn.blockQps(), 0.01); }
Example #20
Source File: MessageRestServiceTest.java From camunda-bpm-platform with Apache License 2.0 | 5 votes |
@Test public void testFullMessageCorrelationAllWithMixedResult() { //given when(messageCorrelationBuilderMock.correlateAllWithResult()).thenReturn(mixedResultList); String messageName = "aMessageName"; Map<String, Object> messageParameters = new HashMap<>(); messageParameters.put("messageName", messageName); messageParameters.put("all", true); messageParameters.put("resultEnabled", true); //when Response response = given().contentType(POST_JSON_CONTENT_TYPE) .body(messageParameters) .then().expect() .contentType(ContentType.JSON) .statusCode(Status.OK.getStatusCode()) .when().post(MESSAGE_URL); //then assertNotNull(response); String content = response.asString(); assertTrue(!content.isEmpty()); List<HashMap> results = from(content).getList(""); assertEquals(4, results.size()); for (int i = 0; i < 2; i++) { String resultType = from(content).get("[" + i + "].resultType"); assertNotNull(resultType); if (resultType.equals(MessageCorrelationResultType.Execution.name())) { checkExecutionResult(content, i); } else { checkProcessInstanceResult(content, i); } } verify(runtimeServiceMock).createMessageCorrelation(eq(messageName)); verify(messageCorrelationBuilderMock).correlateAllWithResult(); }
Example #21
Source File: CaseDefinitionRestServiceInteractionTest.java From camunda-bpm-platform with Apache License 2.0 | 5 votes |
@Test public void testCaseDefinitionCmmnXmlRetrieval_ByKey() { Response response = given() .pathParam("key", MockProvider.EXAMPLE_CASE_DEFINITION_KEY) .then() .expect() .statusCode(Status.OK.getStatusCode()) .when() .get(XML_DEFINITION_BY_KEY_URL); String responseContent = response.asString(); Assert.assertTrue(responseContent.contains(MockProvider.EXAMPLE_CASE_DEFINITION_ID)); Assert.assertTrue(responseContent.contains("<?xml")); }
Example #22
Source File: MarsmediaTest.java From prebid-server-java with Apache License 2.0 | 5 votes |
@Test public void openrtb2AuctionShouldRespondWithBidsFromMarsmedia() throws IOException, JSONException { // given // Marsmedia bid response for imp 001 WIRE_MOCK_RULE.stubFor(post(urlPathEqualTo("/marsmedia-exchange&zone=zone_1")) //.withQueryParam("zone", equalTo("zone_1")) .withHeader("x-openrtb-version", equalTo("2.5")) .withHeader("DNT", equalTo("2")) .withHeader("Accept-Language", equalTo("en")) .withRequestBody(equalToJson(jsonFrom("openrtb2/marsmedia/test-marsmedia-bid-request-1.json"))) .willReturn(aResponse().withBody(jsonFrom("openrtb2/marsmedia/test-marsmedia-bid-response-1.json")))); // pre-bid cache WIRE_MOCK_RULE.stubFor(post(urlPathEqualTo("/cache")) .withRequestBody(equalToJson(jsonFrom("openrtb2/marsmedia/test-cache-marsmedia-request.json"))) .willReturn(aResponse().withBody(jsonFrom("openrtb2/marsmedia/test-cache-marsmedia-response.json")))); // when final Response response = given(SPEC) .header("Referer", "http://www.example.com") .header("X-Forwarded-For", "193.168.244.1") .header("User-Agent", "userAgent") .header("Origin", "http://www.example.com") // this uids cookie value stands for {"uids":{"marsmedia":"MM-UID"}} .cookie("uids", "eyJ1aWRzIjp7Im1hcnNtZWRpYSI6Ik1NLVVJRCJ9fQ==") .body(jsonFrom("openrtb2/marsmedia/test-auction-marsmedia-request.json")) .post("/openrtb2/auction"); // then final String expectedAuctionResponse = openrtbAuctionResponseFrom( "openrtb2/marsmedia/test-auction-marsmedia-response.json", response, singletonList("marsmedia")); JSONAssert.assertEquals(expectedAuctionResponse, response.asString(), JSONCompareMode.NON_EXTENSIBLE); }
Example #23
Source File: AbstractDebeziumTest.java From camel-quarkus with Apache License 2.0 | 5 votes |
@Test @Order(1) public void testInsert() throws SQLException { if (getConnection() == null) { LOG.warn("Test 'testInsert' is skipped, because container is not running."); return; } int i = 0; while (i++ < REPEAT_COUNT) { executeUpdate(String.format("INSERT INTO %s (name, city) VALUES ('%s', '%s')", getCompanyTableName(), COMPANY_1 + "_" + i, CITY_1)); Response response = receiveResponse(); //if status code is 204 (no response), try again if (response.getStatusCode() == 204) { LOG.debug("Response code 204. Debezium is not running yet, repeating (" + i + "/" + REPEAT_COUNT + ")"); continue; } response .then() .statusCode(200) .body(containsString((COMPANY_1 + "_" + i))); //if response is valid, no need for another inserts break; } Assert.assertTrue("Debezium does not respond (consider changing timeout in AbstractDebeziumResource).", i < REPEAT_COUNT); }
Example #24
Source File: HistoricActivityInstanceRestServiceQueryTest.java From camunda-bpm-platform with Apache License 2.0 | 5 votes |
@Test public void testFinishedHistoricActivityQueryAsPost() { Map<String, Boolean> body = new HashMap<String, Boolean>(); body.put("finished", true); Response response = given() .contentType(POST_JSON_CONTENT_TYPE) .body(body) .then() .expect() .statusCode(Status.OK.getStatusCode()) .when() .post(HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL); InOrder inOrder = inOrder(mockedQuery); inOrder.verify(mockedQuery).finished(); inOrder.verify(mockedQuery).list(); String content = response.asString(); List<String> instances = from(content).getList(""); Assert.assertEquals("There should be one activity instance returned.", 1, instances.size()); Assert.assertNotNull("The returned activity instance should not be null.", instances.get(0)); String returnedProcessInstanceId = from(content).getString("[0].processInstanceId"); String returnedProcessDefinitionId = from(content).getString("[0].processDefinitionId"); String returnedActivityEndTime = from(content).getString("[0].endTime"); Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, returnedProcessInstanceId); Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, returnedProcessDefinitionId); Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_END_TIME, returnedActivityEndTime); }
Example #25
Source File: PulsepointTest.java From prebid-server-java with Apache License 2.0 | 5 votes |
@Test public void auctionShouldRespondWithBidsFromPulsepoint() throws IOException { // given // pulsepoint bid response for ad unit 6 WIRE_MOCK_RULE.stubFor(post(urlPathEqualTo("/pulsepoint-exchange")) .withRequestBody(equalToJson(jsonFrom("auction/pulsepoint/test-pulsepoint-bid-request-1.json"))) .willReturn(aResponse().withBody(jsonFrom("auction/pulsepoint/test-pulsepoint-bid-response-1.json")))); // pre-bid cache WIRE_MOCK_RULE.stubFor(post(urlPathEqualTo("/cache")) .withRequestBody(equalToJson(jsonFrom("auction/pulsepoint/test-cache-pulsepoint-request.json"))) .willReturn(aResponse().withBody(jsonFrom("auction/pulsepoint/test-cache-pulsepoint-response.json")))); // when final Response response = given(SPEC) .header("Referer", "http://www.example.com") .header("X-Forwarded-For", "193.168.244.1") .header("User-Agent", "userAgent") .header("Origin", "http://www.example.com") //this uids cookie value stands for {"uids":{"pulsepoint":"PP-UID"}} .cookie("uids", "eyJ1aWRzIjp7InB1bHNlcG9pbnQiOiJQUC1VSUQifX0=") .queryParam("debug", "1") .body(jsonFrom("auction/pulsepoint/test-auction-pulsepoint-request.json")) .post("/auction"); // then assertThat(response.header("Cache-Control")).isEqualTo("no-cache, no-store, must-revalidate"); assertThat(response.header("Pragma")).isEqualTo("no-cache"); assertThat(response.header("Expires")).isEqualTo("0"); assertThat(response.header("Access-Control-Allow-Credentials")).isEqualTo("true"); assertThat(response.header("Access-Control-Allow-Origin")).isEqualTo("http://www.example.com"); final String expectedAuctionResponse = legacyAuctionResponseFrom( "auction/pulsepoint/test-auction-pulsepoint-response.json", response, singletonList(PULSEPOINT)); assertThat(response.asString()).isEqualTo(expectedAuctionResponse); }
Example #26
Source File: BookingDateConflictIT.java From restful-booker-platform with GNU General Public License v3.0 | 5 votes |
@Test public void testBookingConflict(){ String token = "abc123"; LocalDate checkindate = LocalDate.of(2018, Month.JANUARY, 1); LocalDate checkoutdate = LocalDate.of(2018, Month.JANUARY, 2); Booking bookingPayload = new Booking.BookingBuilder() .setRoomid(1) .setFirstname("Mark") .setLastname("Winteringham") .setDepositpaid(true) .setCheckin(checkindate) .setCheckout(checkoutdate) .setEmail("[email protected]") .setPhone("01234123123") .build(); given() .cookie("token", token) .contentType(ContentType.JSON) .body(bookingPayload) .when() .post("http://localhost:3000/booking/"); Response bookingResponse = given() .cookie("token", token) .contentType(ContentType.JSON) .body(bookingPayload) .when() .post("http://localhost:3000/booking/"); assertThat(bookingResponse.statusCode(), equalTo(409)); }
Example #27
Source File: HistoricActivityInstanceRestServiceQueryTest.java From camunda-bpm-platform with Apache License 2.0 | 5 votes |
@Test public void testQueryFilterWithoutTenantIdPostParameter() { // given HistoricActivityInstance activityInstance = MockProvider.createMockHistoricActivityInstance(null); mockedQuery = setUpMockHistoricActivityInstanceQuery(Collections.singletonList(activityInstance)); Map<String, Object> queryParameters = Collections.singletonMap("withoutTenantId", (Object) true); // when Response response = given() .contentType(POST_JSON_CONTENT_TYPE) .body(queryParameters) .expect() .statusCode(Status.OK.getStatusCode()) .when() .post(HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL); // then verify(mockedQuery).withoutTenantId(); verify(mockedQuery).list(); String content = response.asString(); List<String> definitions = from(content).getList(""); assertThat(definitions).hasSize(1); String returnedTenantId = from(content).getString("[0].tenantId"); assertThat(returnedTenantId).isEqualTo(null); }
Example #28
Source File: ProcessDefinitionRestServiceInteractionTest.java From camunda-bpm-platform with Apache License 2.0 | 5 votes |
@Test public void testProcessDefinitionBpmn20XmlRetrieval() { // Rest-assured has problems with extracting json with escaped quotation marks, i.e. the xml content in our case Response response = given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) .then() .expect() .statusCode(Status.OK.getStatusCode()) // .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) // .body("bpmn20Xml", startsWith("<?xml")) .when().get(XML_DEFINITION_URL); String responseContent = response.asString(); Assert.assertTrue(responseContent.contains(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)); Assert.assertTrue(responseContent.contains("<?xml")); }
Example #29
Source File: BrightrollTest.java From prebid-server-java with Apache License 2.0 | 5 votes |
@Test public void openrtb2AuctionShouldRespondWithBidsFromBrightroll() throws IOException, JSONException { // given // brightroll bid response for imp 15 WIRE_MOCK_RULE.stubFor(post(urlPathEqualTo("/brightroll-exchange")) .withQueryParam("publisher", equalTo("businessinsider")) .withHeader("Content-Type", equalToIgnoreCase("application/json;charset=utf-8")) .withHeader("Accept", equalTo("application/json")) .withHeader("User-Agent", equalTo("userAgent")) .withHeader("X-Forwarded-For", equalTo("193.168.244.1")) .withHeader("DNT", equalTo("2")) .withHeader("Accept-Language", equalTo("en")) .withHeader("x-openrtb-version", equalTo("2.5")) .withRequestBody(equalToJson(jsonFrom("openrtb2/brightroll/test-brightroll-bid-request-1.json"))) .willReturn(aResponse().withBody(jsonFrom("openrtb2/brightroll/test-brightroll-bid-response-1.json")))); // pre-bid cache WIRE_MOCK_RULE.stubFor(post(urlPathEqualTo("/cache")) .withRequestBody(equalToJson(jsonFrom("openrtb2/brightroll/test-cache-brightroll-request.json"))) .willReturn(aResponse().withBody(jsonFrom("openrtb2/brightroll/test-cache-brightroll-response.json")))); // when final Response response = given(SPEC) .header("Referer", "http://www.example.com") .header("X-Forwarded-For", "193.168.244.1") .header("User-Agent", "userAgent") .header("Origin", "http://www.example.com") // this uids cookie value stands for{"uids":{"brightroll":"BR-UID"}} .cookie("uids", "eyJ1aWRzIjp7ImJyaWdodHJvbGwiOiJCUi1VSUQifX0=") .body(jsonFrom("openrtb2/brightroll/test-auction-brightroll-request.json")) .post("/openrtb2/auction"); // then final String expectedAuctionResponse = openrtbAuctionResponseFrom( "openrtb2/brightroll/test-auction-brightroll-response.json", response, singletonList("brightroll")); JSONAssert.assertEquals(expectedAuctionResponse, response.asString(), JSONCompareMode.NON_EXTENSIBLE); }
Example #30
Source File: DeploymentRestServiceInteractionTest.java From camunda-bpm-platform with Apache License 2.0 | 5 votes |
@Test public void testCreateCompleteDrdDeployment() throws Exception { // given DeploymentWithDefinitions mockDeployment = MockProvider.createMockDeploymentWithDefinitions(); when(mockDeployment.getDeployedCaseDefinitions()).thenReturn(null); when(mockDeployment.getDeployedProcessDefinitions()).thenReturn(null); when(mockDeploymentBuilder.deployWithResult()).thenReturn(mockDeployment); // when resourceNames.addAll(Arrays.asList("data", "more-data")); Response response = given() .multiPart("data", "unspecified", createMockDeploymentResourceByteData()) .multiPart("more-data", "unspecified", createMockDeploymentResourceBpmnData()) .multiPart("deployment-name", MockProvider.EXAMPLE_DEPLOYMENT_ID) .multiPart("enable-duplicate-filtering", "true") .expect() .statusCode(Status.OK.getStatusCode()) .when() .post(CREATE_DEPLOYMENT_URL); // then verifyCreatedDrdDeployment(mockDeployment, response); verify(mockDeploymentBuilder).name(MockProvider.EXAMPLE_DEPLOYMENT_ID); verify(mockDeploymentBuilder).enableDuplicateFiltering(false); }