Java Code Examples for io.restassured.response.Response

The following examples show how to use io.restassured.response.Response. These examples are extracted from open source projects. 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 Project: prebid-server-java   Source File: ApplicationTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 2
@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
@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 4
@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 5
Source Project: heat   Source File: BasicChecks.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 6
@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 7
Source Project: heat   Source File: OperationHandler.java    License: Apache License 2.0 6 votes vote down vote up
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 8
Source Project: tracksrestcasestudy   Source File: TracksAppAsApi.java    License: MIT License 6 votes vote down vote up
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 9
Source Project: microprofile-metrics   Source File: ReusedMetricsTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 10
Source Project: carina   Source File: NotificationUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 11
@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 12
@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 13
@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 14
@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 15
Source Project: heat   Source File: OperationHandler.java    License: Apache License 2.0 6 votes vote down vote up
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 16
Source Project: tutorials   Source File: UserInfoEndpointLiveTest.java    License: MIT License 6 votes vote down vote up
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 17
Source Project: tracksrestcasestudy   Source File: TracksAppAsApi.java    License: MIT License 6 votes vote down vote up
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 18
@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 19
Source Project: quarkus   Source File: ArtemisHealthCheckTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    Response response = RestAssured.with().get("/health/ready");
    Assertions.assertEquals(Status.OK.getStatusCode(), response.statusCode());

    Map<String, Object> body = response.as(new TypeRef<Map<String, Object>>() {
    });
    Assertions.assertEquals("UP", body.get("status"));

    @SuppressWarnings("unchecked")
    List<Map<String, Object>> checks = (List<Map<String, Object>>) body.get("checks");
    Assertions.assertEquals(1, checks.size());
    Assertions.assertEquals("Artemis JMS health check", checks.get(0).get("name"));
}
 
Example 20
Source Project: prebid-server-java   Source File: IxTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void openrtb2AuctionShouldRespondWithBidsFromIx() throws IOException, JSONException {
    // given
    // ix bid response for imp 6
    WIRE_MOCK_RULE.stubFor(post(urlPathEqualTo("/ix-exchange"))
            .withRequestBody(equalToJson(jsonFrom("openrtb2/ix/test-ix-bid-request-1.json")))
            .willReturn(aResponse().withBody(jsonFrom("openrtb2/ix/test-ix-bid-response-1.json"))));

    // ix bid response for imp 61
    WIRE_MOCK_RULE.stubFor(post(urlPathEqualTo("/ix-exchange"))
            .withRequestBody(equalToJson(jsonFrom("openrtb2/ix/test-ix-bid-request-2.json")))
            .willReturn(aResponse().withBody(jsonFrom("openrtb2/ix/test-ix-bid-response-2.json"))));

    // pre-bid cache
    WIRE_MOCK_RULE.stubFor(post(urlPathEqualTo("/cache"))
            .withRequestBody(equalToJson(jsonFrom("openrtb2/ix/test-cache-ix-request.json")))
            .willReturn(aResponse().withBody(jsonFrom("openrtb2/ix/test-cache-ix-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":{"ix":"IE-UID"}}
            .cookie("uids", "eyJ1aWRzIjp7Iml4IjoiSUUtVUlEIn19")
            .body(jsonFrom("openrtb2/ix/test-auction-ix-request.json"))
            .post("/openrtb2/auction");

    // then
    final String expectedAuctionResponse = openrtbAuctionResponseFrom(
            "openrtb2/ix/test-auction-ix-response.json",
            response, singletonList(IX));

    JSONAssert.assertEquals(expectedAuctionResponse, response.asString(), JSONCompareMode.NON_EXTENSIBLE);
}
 
Example 21
Source Project: tutorials   Source File: AbstractBasicLiveTest.java    License: MIT License 5 votes vote down vote up
@Test
public void whenSecondPageOfResourcesAreRetrieved_thenFirstPageIsPrevious() {
    create();
    create();

    final Response response = RestAssured.get(getURL() + "?page=1&size=2");

    final String uriToPrevPage = extractURIByRel(response.getHeader(HttpHeaders.LINK), "prev");
    assertEquals(getURL() + "?page=0&size=2", uriToPrevPage);
}
 
Example 22
Source Project: tutorials   Source File: JPASpecificationLiveTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenFirstNameInverse_whenGettingListOfUsers_thenCorrect() {
    final Response response = RestAssured.get(URL_PREFIX + "firstName!john");
    final String result = response.body()
        .asString();

    assertTrue(result.contains(userTom.getEmail()));
    assertFalse(result.contains(userJohn.getEmail()));
}
 
Example 23
Source Project: seed   Source File: Jersey2IT.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@Test
public void basicResource() throws JSONException {
    Response response = expect().statusCode(200).given().contentType(MediaType.APPLICATION_JSON).body(
            "{ \"body\": \"hello world!\", \"author\": \"test\" }").post(baseUrl + "/message");
    JSONAssert.assertEquals(response.asString(), "{\"body\":\"test says: hello world!\",\"author\":\"computer\"}",
            true);
}
 
Example 24
Source Project: heat   Source File: OperationHandler.java    License: Apache License 2.0 5 votes vote down vote up
private boolean multipleModeOperationExecution() {
    boolean isExecutionOk = false;

    String operation = loadOperationToExecuteOrDefault(ArithmeticalValidator.MATH_OPERATOR_EQUAL_TO);
    String fieldCheckFormat = loadFieldCheckFormatOrDefault(BasicMultipleChecks.DEFAULT_FORMAT_OF_TYPE_CHECK);
    String firstObj = retrieveObj(JSON_ELEM_ACTUAL_VALUE, fieldsToCheck, (Map<String, Response>) responses);
    String secondObj = retrieveObj(JSON_ELEM_EXPECTED_VALUE, fieldsToCheck, (Map<String, Response>) responses);
    checkDescription = fieldsToCheck.get(JSON_ELEM_DESCRIPTION).toString();
    isExecutionOk = mathOrStringChecks(operation, firstObj, secondObj, fieldCheckFormat);

    return isExecutionOk;
}
 
Example 25
Source Project: api-framework   Source File: BookingApi.java    License: MIT License 5 votes vote down vote up
public static Response postBooking(Booking payload) {
    return given()
            .contentType(ContentType.JSON)
            .body(payload)
            .when()
            .post(apiUrl);
}
 
Example 26
Source Project: spring-security-oauth   Source File: TokenRevocationLiveTest.java    License: MIT License 5 votes vote down vote up
private String obtainRefreshToken(String clientId, final String refreshToken) {
    final Map<String, String> params = new HashMap<String, String>();
    params.put("grant_type", "refresh_token");
    params.put("client_id", clientId);
    params.put("refresh_token", refreshToken);
    final Response response = RestAssured.given().auth().preemptive().basic(clientId, "secret").and().with().params(params).when().post("http://localhost:8081/spring-security-oauth-server/oauth/token");
    return response.jsonPath().getString("access_token");
}
 
Example 27
Source Project: tutorials   Source File: RestApiLiveTest.java    License: MIT License 5 votes vote down vote up
@Test
public void whenInvalidBook_thenError() {
    final Book book = createRandomBook();
    book.setAuthor(null);

    final Response response = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE).body(book).post(API_URI);
    assertEquals(HttpStatus.CONFLICT.value(), response.getStatusCode());
}
 
Example 28
Source Project: herd-mdl   Source File: HerdRestUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get business object notification
 *
 * @param user             user to perform rest call
 * @param namespace        namespace
 * @param notificationName notification name
 * @return Response
 */
public static Response deleteBusinessObjectNotification(User user, String namespace, String notificationName) {
    Response response = given().spec(getHerdBaseRequestSpecification(user))
        .pathParam("namespace", namespace)
        .pathParam("notificationName", notificationName)
        .delete(DELETE_BUSINESS_OBJECT_NOTIFICATION_URL);
    LOGGER.debug(prettyJsonResponse(response));
    return response;
}
 
Example 29
Source Project: quarkus   Source File: RolesAllowedUnitTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test()
public void testPermitAllOnClass() {
    io.restassured.response.Response response = RestAssured.given().auth()
            .oauth2(token)
            .when()
            .get("/permit-all-endpoint/greet").andReturn();

    Assertions.assertEquals(HttpURLConnection.HTTP_OK, response.getStatusCode());
    String replyString = response.body().asString();
    Assertions.assertEquals("hello", replyString);
}
 
Example 30
@Test
public void testInstanceRetrievalByListWithDuplicateAsPost() {
  List<ProcessInstance> mockProcessInstanceList = new ArrayList<ProcessInstance>();

  mockProcessInstanceList.add(MockProvider.createMockInstance());
  mockProcessInstanceList.add(MockProvider.createAnotherMockInstance());

  ProcessInstanceQuery instanceQuery = mock(ProcessInstanceQuery.class);

  when(instanceQuery.list()).thenReturn(mockProcessInstanceList);
  when(processEngine.getRuntimeService().createProcessInstanceQuery()).thenReturn(instanceQuery);

  Map<String, Set<String>> params = new HashMap<String, Set<String>>();
  Set<String> processInstanceIds = MockProvider.createMockSetFromList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID_LIST);
  params.put("processInstanceIds", processInstanceIds);

  Response response = given()
      .contentType(POST_JSON_CONTENT_TYPE)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.OK.getStatusCode())
      .when()
        .post(PROCESS_INSTANCE_QUERY_URL);

  // assert query invocation
  InOrder inOrder = Mockito.inOrder(instanceQuery);
  inOrder.verify(instanceQuery).processInstanceIds(processInstanceIds);
  inOrder.verify(instanceQuery).list();

  String content = response.asString();
  List<String> instances = from(content).getList("");
  Assert.assertEquals("There should be two process definitions returned.", 2, instances.size());

  String returnedInstanceId1 = from(content).getString("[0].id");
  String returnedInstanceId2 = from(content).getString("[1].id");

  Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, returnedInstanceId1);
  Assert.assertEquals(MockProvider.ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID, returnedInstanceId2);
}