io.restassured.specification.RequestSpecification Java Examples

The following examples show how to use io.restassured.specification.RequestSpecification. 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: LoanApplicationServiceTests.java    From spring-cloud-contract with Apache License 2.0 8 votes vote down vote up
@Test
public void shouldSuccessfullyWorkWithMultipart() {
	// given:
	RequestSpecification request = RestAssured.given()
			.baseUri("http://localhost:"+ stubPort + "/")
			.header("Content-Type", "multipart/form-data")
			.multiPart("file1", "filename1", "content1".getBytes())
			.multiPart("file2", "filename1", "content2".getBytes()).multiPart("test",
					"filename1", "{\n  \"status\": \"test\"\n}".getBytes(),
					"application/json");

	// when:
	ResponseOptions response = RestAssured.given().spec(request).post("/tests");

	// then:
	assertThat(response.statusCode()).isEqualTo(200);
	assertThat(response.header("Content-Type")).matches("application/json.*");
	// and:
	DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
	assertThatJson(parsedJson).field("['status']").isEqualTo("ok");
}
 
Example #2
Source File: UserRestServiceQueryTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void testCompleteGetParameters() {

  Map<String, String> queryParameters = getCompleteStringQueryParameters();

  RequestSpecification requestSpecification = given().contentType(POST_JSON_CONTENT_TYPE);
  for (Entry<String, String> paramEntry : queryParameters.entrySet()) {
    requestSpecification.parameter(paramEntry.getKey(), paramEntry.getValue());
  }

  requestSpecification.expect().statusCode(Status.OK.getStatusCode())
    .when().get(USER_QUERY_URL);

  verify(mockQuery).userEmail(MockProvider.EXAMPLE_USER_EMAIL);
  verify(mockQuery).userFirstName(MockProvider.EXAMPLE_USER_FIRST_NAME);
  verify(mockQuery).userLastName(MockProvider.EXAMPLE_USER_LAST_NAME);
  verify(mockQuery).memberOfGroup(MockProvider.EXAMPLE_GROUP_ID);
  verify(mockQuery).memberOfTenant(MockProvider.EXAMPLE_TENANT_ID);

  verify(mockQuery).list();

}
 
Example #3
Source File: HttpLoggingPluginTest.java    From cukes with Apache License 2.0 6 votes vote down vote up
@Test
public void testOutputStream() throws UnsupportedEncodingException {
    when(world.get(LOGGING_REQUEST_INCLUDES, "")).thenReturn("all");

    RequestSpecification specification = RestAssured.given()
        .config(config.getConfig())
        .baseUri("http://google.com")
        .param("q", "hi");

    plugin.beforeRequest(specification);

    specification.get();

    String requestLog = testOut.toString("UTF-8");
    assertThat(requestLog, is(EXPECTED_RESULT));
}
 
Example #4
Source File: GroupRestServiceQueryTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void testCompleteGetParameters() {

  Map<String, Object> queryParameters = getCompleteStringQueryParameters();

  RequestSpecification requestSpecification = given().contentType(POST_JSON_CONTENT_TYPE);
  for (Entry<String, Object> paramEntry : queryParameters.entrySet()) {
    requestSpecification.parameter(paramEntry.getKey(), paramEntry.getValue());
  }

  requestSpecification.expect().statusCode(Status.OK.getStatusCode())
    .when().get(GROUP_QUERY_URL);

  verify(mockQuery).groupName(MockProvider.EXAMPLE_GROUP_NAME);
  verify(mockQuery).groupNameLike("%" + MockProvider.EXAMPLE_GROUP_NAME + "%");
  verify(mockQuery).groupType(MockProvider.EXAMPLE_GROUP_TYPE);
  verify(mockQuery).groupMember(MockProvider.EXAMPLE_USER_ID);
  verify(mockQuery).memberOfTenant(MockProvider.EXAMPLE_TENANT_ID);
  verify(mockQuery).groupId(MockProvider.EXAMPLE_GROUP_ID);
  verify(mockQuery).groupIdIn(MockProvider.EXAMPLE_GROUP_ID, MockProvider.EXAMPLE_GROUP_ID2);

  verify(mockQuery).list();

}
 
Example #5
Source File: AuthorizationRestServiceQueryTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void testCompleteGetParameters() {

  List<Authorization> mockAuthorizations = MockProvider.createMockGlobalAuthorizations();
  AuthorizationQuery mockQuery = setUpMockQuery(mockAuthorizations);

  Map<String, String> queryParameters = getCompleteStringQueryParameters();

  RequestSpecification requestSpecification = given().contentType(POST_JSON_CONTENT_TYPE);
  for (Entry<String, String> paramEntry : queryParameters.entrySet()) {
    requestSpecification.parameter(paramEntry.getKey(), paramEntry.getValue());
  }

  requestSpecification.expect().statusCode(Status.OK.getStatusCode())
    .when().get(SERVICE_PATH);

  verify(mockQuery).authorizationId(MockProvider.EXAMPLE_AUTHORIZATION_ID);
  verify(mockQuery).authorizationType(MockProvider.EXAMPLE_AUTHORIZATION_TYPE);
  verify(mockQuery).userIdIn(new String[]{MockProvider.EXAMPLE_USER_ID, MockProvider.EXAMPLE_USER_ID2});
  verify(mockQuery).groupIdIn(new String[]{MockProvider.EXAMPLE_GROUP_ID, MockProvider.EXAMPLE_GROUP_ID2});
  verify(mockQuery).resourceType(MockProvider.EXAMPLE_RESOURCE_TYPE_ID);
  verify(mockQuery).resourceId(MockProvider.EXAMPLE_RESOURCE_ID);

  verify(mockQuery).list();

}
 
Example #6
Source File: TenantRestServiceQueryTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void completeGetParameters() {
  Map<String, String> queryParameters = getCompleteStringQueryParameters();

  RequestSpecification requestSpecification = given().contentType(POST_JSON_CONTENT_TYPE);
  for (Entry<String, String> paramEntry : queryParameters.entrySet()) {
    requestSpecification.parameter(paramEntry.getKey(), paramEntry.getValue());
  }

  requestSpecification
    .expect().statusCode(Status.OK.getStatusCode())
    .when().get(QUERY_URL);

  verify(mockQuery).tenantId(MockProvider.EXAMPLE_TENANT_ID);
  verify(mockQuery).tenantName(MockProvider.EXAMPLE_TENANT_NAME);
  verify(mockQuery).tenantNameLike("%" + MockProvider.EXAMPLE_TENANT_NAME + "%");
  verify(mockQuery).userMember(MockProvider.EXAMPLE_USER_ID);
  verify(mockQuery).groupMember(MockProvider.EXAMPLE_GROUP_ID);

  verify(mockQuery).list();
}
 
Example #7
Source File: OAuthCukesHttpPlugin.java    From cukes with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeRequest(RequestSpecification requestSpecification) {
    com.google.common.base.Optional<String> authType = worldFacade.get(CukesOptions.AUTH_TYPE);
    if (authType.isPresent()) {
        if (!"OAuth".equalsIgnoreCase(authType.get())) {
            return;
        }
    } else {
        return;
    }
    try {
        Optional<String> authorizationHeader = tokenRetriever.getAuthorizationHeader();
        authorizationHeader.ifPresent(s -> requestSpecification.auth().oauth2(s));
    } catch (IOException e) {
        throw new CukesRuntimeException("Cannot get OAuth token", e);
    }
}
 
Example #8
Source File: DeletedMessagesVaultRequests.java    From james-project with Apache License 2.0 5 votes vote down vote up
static void restoreMessagesForUserWithQuery(RequestSpecification webAdminApi, String user, String criteria) {
    String taskId = webAdminApi.with()
        .body(criteria)
        .post("/deletedMessages/users/" + user + "?action=restore")
    .jsonPath()
        .get("taskId");

    webAdminApi.given()
        .get("/tasks/" + taskId + "/await")
    .then()
        .body("status", is("completed"));
}
 
Example #9
Source File: AbstractBookerService.java    From frameworkium-examples with Apache License 2.0 5 votes vote down vote up
/**
 * @return a Rest Assured {@link RequestSpecification} with the baseUri
 *         (and anything else required by most Capture services).
 */
@Override
protected RequestSpecification getRequestSpec() {
    return RestAssured.given()
            .baseUri(BookerEndpoint.BASE_URI.getUrl())
            .relaxedHTTPSValidation() // trusts even invalid certs
            // .log().all() // uncomment to log each request
            .contentType("application/json")
            .accept("application/json");
}
 
Example #10
Source File: DeletedMessagesVaultRequests.java    From james-project with Apache License 2.0 5 votes vote down vote up
static void purgeVault(RequestSpecification webAdminApi) {
    String taskId =
        webAdminApi.with()
            .queryParam("scope", "expired")
            .delete("/deletedMessages")
        .jsonPath()
            .get("taskId");

    webAdminApi.with()
        .get("/tasks/" + taskId + "/await")
    .then()
        .body("status", is("completed"));
}
 
Example #11
Source File: RestHelper.java    From apicurio-studio with Apache License 2.0 5 votes vote down vote up
public static SessionInfo createEditingSession(RequestSpecification given, ApiDesign apiDesign) {
    // Create editing session
    Headers editingSession = given.expect().statusCode(200)
            .when()
            .get("/api-hub/designs/" + apiDesign.getId() + "/session")
            .getHeaders();
    // Editing session information
    return new SessionInfo(editingSession);
}
 
Example #12
Source File: ConfigurationExtension.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private RequestSpecification defaultRequestSpecification()
{
    RequestSpecBuilder requestSpecification = new RequestSpecBuilder();

    requestSpecification.addFilter( new CookieFilter() );
    requestSpecification.addFilter( new SessionFilter() );
    requestSpecification.addFilter( new AuthFilter() );
    requestSpecification.setContentType( ContentType.JSON );

    return requestSpecification.build();
}
 
Example #13
Source File: SessionConfigurationLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
private static Response simpleResponseSvcRequestLoggingIn(Optional<SessionFilter> sessionFilter) {
    RequestSpecification spec = given().auth()
        .form(USER, PASSWORD);
    sessionFilter.ifPresent(filter -> spec.and()
        .filter(filter));
    return spec.when()
        .get(SESSION_SVC_URL);
}
 
Example #14
Source File: Linshare.java    From james-project with Apache License 2.0 5 votes vote down vote up
public RequestSpecification fakeSmtpRequestSpecification() {
    return new RequestSpecBuilder()
        .setContentType(ContentType.JSON)
        .setAccept(ContentType.JSON)
        .setConfig(newConfig().encoderConfig(encoderConfig().defaultContentCharset(StandardCharsets.UTF_8)))
        .setPort(linshareSmtp.getMappedPort(80))
        .setBaseUri("http://" + linshareSmtp.getContainerIpAddress())
        .build();
}
 
Example #15
Source File: FakeSmtp.java    From james-project with Apache License 2.0 5 votes vote down vote up
private RequestSpecification requestSpecification() {
    return new RequestSpecBuilder()
        .setContentType(ContentType.JSON)
        .setAccept(ContentType.JSON)
        .setConfig(newConfig().encoderConfig(encoderConfig().defaultContentCharset(StandardCharsets.UTF_8)))
        .setPort(80)
        .setBaseUri("http://" + container.getContainerIp())
        .build();
}
 
Example #16
Source File: OpenServiceBrokerApiFixture.java    From spring-cloud-app-broker with Apache License 2.0 5 votes vote down vote up
public RequestSpecification serviceAppBindingRequest() {
	return serviceBrokerSpecification()
		.body("{" +
			"\"service_id\": \"" + serviceDefinitionId + "\"," +
			"\"plan_id\": \"" + planId + "\"," +
			"\"bind_resource\": {" +
			"\"app_guid\": \"" + APP_ID + "\"" +
			"}" +
			"}");
}
 
Example #17
Source File: VertxProducerResourceTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testRouteRegistrationMTLS() {
    RequestSpecification spec = new RequestSpecBuilder()
            .setBaseUri(String.format("%s://%s", url.getProtocol(), url.getHost()))
            .setPort(url.getPort())
            .setKeyStore("client-keystore.jks", "password")
            .setTrustStore("client-truststore.jks", "password")
            .build();
    given().spec(spec).get("/my-path").then().body(containsString("OK"));
}
 
Example #18
Source File: GraphQLTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testSchema() {
    RequestSpecification request = RestAssured.given();
    request.accept(MEDIATYPE_TEXT);
    request.contentType(MEDIATYPE_TEXT);
    Response response = request.get("/graphql/schema.graphql");
    String body = response.body().asString();
    LOG.error(body);

    Assertions.assertEquals(200, response.statusCode());
    Assertions.assertTrue(body.contains("\"Query root\""));
    Assertions.assertTrue(body.contains("type Query {"));
    Assertions.assertTrue(body.contains("ping: TestPojo"));
}
 
Example #19
Source File: BaseCaptureService.java    From frameworkium-examples with Apache License 2.0 5 votes vote down vote up
/**
 * @return a Rest Assured {@link RequestSpecification} with the baseUri
 *         (and anything else required by most Capture services).
 */
@Override
protected RequestSpecification getRequestSpec() {
    return RestAssured.given()
            .baseUri(CaptureEndpoint.BASE_URI.getUrl())
            .relaxedHTTPSValidation() // trusts even invalid certs
            // .log().all() // uncomment to log each request
            .contentType(ContentType.JSON)
            .accept(ContentType.JSON);
}
 
Example #20
Source File: DeletedMessagesVaultRequests.java    From james-project with Apache License 2.0 5 votes vote down vote up
static void exportVaultContent(RequestSpecification webAdminApi, ExportRequest exportRequest) {
    String taskId =
        webAdminApi.with()
            .queryParam("action", "export")
            .queryParam("exportTo", exportRequest.getSharee())
            .body(exportRequest.getMatchingQuery())
            .post("/deletedMessages/users/" + exportRequest.getUserExportFrom())
        .jsonPath()
            .get("taskId");

    webAdminApi.with()
        .get("/tasks/" + taskId + "/await")
    .then()
        .body("status", is("completed"));
}
 
Example #21
Source File: AbstractBookerService.java    From frameworkium-core with Apache License 2.0 5 votes vote down vote up
/**
 * @return a Rest Assured {@link RequestSpecification} with the baseUri
 *         (and anything else required by most Capture services).
 */
@Override
protected RequestSpecification getRequestSpec() {
    return RestAssured.given()
            .baseUri(BookerEndpoint.BASE_URI.getUrl())
            .relaxedHTTPSValidation() // trusts even invalid certs
            // .log().all() // uncomment to log each request
            .contentType("application/json")
            .accept("application/json");
}
 
Example #22
Source File: PreprocessRestRequestBody.java    From cukes with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeRequest(RequestSpecification requestSpecification) {
    String requestBody = this.requestFacade.getRequestBody();
    if (requestBody != null) {
        String processed = templatingEngine.processBody(requestBody);
        requestSpecification.body(processed);
    }
}
 
Example #23
Source File: DLPConfigurationRoutesTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
RequestSpecification buildRequestSpecification(WebAdminServer server) {
    RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();

    return WebAdminUtils
            .buildRequestSpecification(server)
            .setBasePath(DLPConfigurationRoutes.BASE_PATH)
            .build();
}
 
Example #24
Source File: PreprocessGraphQLRequestBody.java    From cukes with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeRequest(RequestSpecification requestSpecification) {
    GraphQLRequest graphQLRequest = requestFacade.getGraphQLRequest();
    if (!Strings.isNullOrEmpty(graphQLRequest.getQuery())) {
        graphQLRequest.setQuery(templatingEngine.processBody(graphQLRequest.getQuery()));
    }
    if (!Strings.isNullOrEmpty(graphQLRequest.getVariables())) {
        graphQLRequest.setVariables(templatingEngine.processBody(graphQLRequest.getVariables()));
    }
    requestSpecification.body(graphQLRequest);
}
 
Example #25
Source File: DomainMappingsRoutesTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
private void assertBadRequest(String toDomain, Function<RequestSpecification, Response> requestingFunction) {
    Map<String, Object> errors = requestingFunction.apply(given().body(toDomain).when())
        .then()
            .statusCode(HttpStatus.BAD_REQUEST_400)
            .contentType(ContentType.JSON)
        .extract()
            .body()
            .jsonPath()
            .getMap(".");

    assertThat(errors)
        .containsEntry("statusCode", HttpStatus.BAD_REQUEST_400)
        .containsEntry("type", "InvalidArgument")
        .hasEntrySatisfying("message", o -> assertThat((String) o).matches("^The domain .* is invalid\\.$"));
}
 
Example #26
Source File: HttpLoggingPlugin.java    From cukes with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeRequest(RequestSpecification requestSpecification) {
    if (!(requestSpecification instanceof FilterableRequestSpecification)) {
        throw new IllegalArgumentException("Cannot retrieve configuration from: " + requestSpecification);
    }

    final FilterableRequestSpecification filterableRequestSpecification = (FilterableRequestSpecification) requestSpecification;

    final RequestLogSpecification logSpec = filterableRequestSpecification.log();
    final List<LogDetail> logDetails = parseLogDetails(world.get(LOGGING_REQUEST_INCLUDES, DEFAULT_REQUEST_INCLUDES));

    details:
    for (LogDetail detail : logDetails) {
        switch (detail) {
            case ALL:
                logSpec.all();
                break details;
            case BODY:
                logSpec.body();
                break;
            case COOKIES:
                logSpec.cookies();
                break;
            case HEADERS:
                logSpec.headers();
                break;
            case METHOD:
                logSpec.method();
                break;
            case PARAMS:
                logSpec.parameters();
                break;
            case URI:
                logSpec.uri();
                break;
        }
    }
}
 
Example #27
Source File: MailQueueRoutesTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
RequestSpecification buildRequestSpecification(WebAdminServer server) {
    return new RequestSpecBuilder()
        .setContentType(ContentType.JSON)
        .setAccept(ContentType.JSON)
        .setBasePath(MailQueueRoutes.BASE_URL)
        .setPort(server.getPort().getValue())
        .setConfig(newConfig().encoderConfig(encoderConfig().defaultContentCharset(StandardCharsets.UTF_8)))
        .build();
}
 
Example #28
Source File: RestControllerIntegrationTestBase.java    From genie with Apache License 2.0 5 votes vote down vote up
<R extends ExecutionEnvironmentDTO> String createConfigResource(
    @NotNull final R resource,
    @Nullable final RestDocumentationFilter documentationFilter
) throws Exception {
    final String endpoint;
    if (resource instanceof Application) {
        endpoint = APPLICATIONS_API;
    } else if (resource instanceof Cluster) {
        endpoint = CLUSTERS_API;
    } else if (resource instanceof Command) {
        endpoint = COMMANDS_API;
    } else {
        throw new IllegalArgumentException("Unexpected type: " + resource.getClass().getCanonicalName());
    }

    final RequestSpecification configRequestSpec = RestAssured
        .given(this.requestSpecification)
        .contentType(MediaType.APPLICATION_JSON_VALUE)
        .body(GenieObjectMapper.getMapper().writeValueAsBytes(resource));

    if (documentationFilter != null) {
        configRequestSpec.filter(documentationFilter);
    }

    return this.getIdFromLocation(
        configRequestSpec
            .when()
            .port(this.port)
            .post(endpoint)
            .then()
            .statusCode(Matchers.is(HttpStatus.CREATED.value()))
            .header(HttpHeaders.LOCATION, Matchers.notNullValue())
            .extract()
            .header(HttpHeaders.LOCATION)
    );
}
 
Example #29
Source File: JiraConfig.java    From frameworkium-core with Apache License 2.0 5 votes vote down vote up
/**
 * Basic request to send to JIRA and authenticate successfully.
 */
public static RequestSpecification getJIRARequestSpec() {
    return RestAssured.given()
            .baseUri(Property.JIRA_URL.getValue())
            .relaxedHTTPSValidation()
            .auth().preemptive().basic(
                    Property.JIRA_USERNAME.getValue(),
                    Property.JIRA_PASSWORD.getValue());
}
 
Example #30
Source File: BaseCaptureService.java    From frameworkium-core with Apache License 2.0 5 votes vote down vote up
/**
 * @return a Rest Assured {@link RequestSpecification} with the baseUri
 *         (and anything else required by most Capture services).
 */
@Override
protected RequestSpecification getRequestSpec() {
    return RestAssured.given()
            .baseUri(CaptureEndpoint.BASE_URI.getUrl())
            .relaxedHTTPSValidation() // trusts even invalid certs
            // .log().all() // uncomment to log each request
            .contentType(ContentType.JSON)
            .accept(ContentType.JSON);
}