org.springframework.restdocs.request.RequestDocumentation Java Examples

The following examples show how to use org.springframework.restdocs.request.RequestDocumentation. 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: ApplicationRestControllerIntegrationTest.java    From genie with Apache License 2.0 6 votes vote down vote up
@Test
void canDeleteTagForApplication() throws Exception {
    this.createConfigResource(
        new Application.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE).withId(ID).build(),
        null
    );
    final String api = APPLICATIONS_API + "/{id}/tags";

    final RestDocumentationFilter deleteFilter = RestAssuredRestDocumentation.document(
        "{class-name}/{method-name}/{step}/",
        Snippets.ID_PATH_PARAM.and(
            RequestDocumentation.parameterWithName("tag").description("The tag to remove")
        )
    );
    this.canDeleteTagForResource(api, ID, NAME, deleteFilter);
}
 
Example #2
Source File: CommandRestControllerIntegrationTest.java    From genie with Apache License 2.0 6 votes vote down vote up
@Test
void canDeleteTagForCommand() throws Exception {
    this.createConfigResource(
        new Command
            .Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS, CHECK_DELAY)
            .withId(ID)
            .build(),
        null
    );
    final String api = COMMANDS_API + "/{id}/tags";

    final RestDocumentationFilter deleteFilter = RestAssuredRestDocumentation.document(
        "{class-name}/{method-name}/{step}/",
        Snippets.ID_PATH_PARAM.and(
            RequestDocumentation.parameterWithName("tag").description("The tag to remove")
        )
    );
    this.canDeleteTagForResource(api, ID, NAME, deleteFilter);
}
 
Example #3
Source File: Snippets.java    From genie with Apache License 2.0 6 votes vote down vote up
private static ParameterDescriptor[] getCommonSearchParameters() {
    return new ParameterDescriptor[]{
        RequestDocumentation
            .parameterWithName("page")
            .description("The page number to get. Default to 0.")
            .optional(),
        RequestDocumentation
            .parameterWithName("size")
            .description("The size of the page to get. Default to 64.")
            .optional(),
        RequestDocumentation
            .parameterWithName("sort")
            .description("The fields to sort the results by. Defaults to 'updated,desc'.")
            .optional(),
    };
}
 
Example #4
Source File: GetGreetingDocTest.java    From skeleton-ws-spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * Generate API documentation for GET /api/greetings/{id}.
 * 
 * @throws Exception Thrown if documentation generation failure occurs.
 */
@Test
public void documentGetGreeting() throws Exception {

    // Generate API Documentation
    final MvcResult result = this.mockMvc
            .perform(RestDocumentationRequestBuilders
                    .get("/api/greetings/{id}", "0").accept(MediaType.APPLICATION_JSON))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andDo(MockMvcRestDocumentation.document("get-greeting",
                    RequestDocumentation.pathParameters(
                            RequestDocumentation.parameterWithName("id").description("The greeting identifier.")),
                    PayloadDocumentation.relaxedResponseFields(
                            PayloadDocumentation.fieldWithPath("id")
                                    .description(
                                            "The identifier. Used to reference specific greetings in API requests.")
                                    .type(JsonFieldType.NUMBER),
                            PayloadDocumentation.fieldWithPath("referenceId")
                                    .description("The supplementary identifier.").type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("text").description("The text.")
                                    .type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("version").description("The entity version.")
                                    .type(JsonFieldType.NUMBER),
                            PayloadDocumentation.fieldWithPath("createdBy").description("The entity creator.")
                                    .type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("createdAt").description("The creation timestamp.")
                                    .type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("updatedBy").description("The last modifier.")
                                    .type(JsonFieldType.STRING).optional(),
                            PayloadDocumentation.fieldWithPath("updatedAt")
                                    .description("The last modification timestamp.").type(JsonFieldType.STRING)
                                    .optional())))
            .andReturn();

    // Perform a simple, standard JUnit assertion to satisfy PMD rule
    Assert.assertEquals("failure - expected HTTP status 200", 200, result.getResponse().getStatus());

}
 
Example #5
Source File: UpdateGreetingDocTest.java    From skeleton-ws-spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * Generate API documentation for PUT /api/greetings/{id}.
 * 
 * @throws Exception Thrown if documentation generation failure occurs.
 */
@Test
public void documentUpdateGreeting() throws Exception {

    // Generate API Documentation
    final MvcResult result = this.mockMvc.perform(RestDocumentationRequestBuilders.put("/api/greetings/{id}", 1)
            .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).content(REQUEST_BODY))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andDo(MockMvcRestDocumentation.document("update-greeting",
                    RequestDocumentation.pathParameters(
                            RequestDocumentation.parameterWithName("id").description("The greeting identifier.")),
                    PayloadDocumentation.relaxedRequestFields(PayloadDocumentation.fieldWithPath("text")
                            .description("The text.").type(JsonFieldType.STRING)),
                    PayloadDocumentation.relaxedResponseFields(
                            PayloadDocumentation
                                    .fieldWithPath("id")
                                    .description(
                                            "The identifier. Used to reference specific greetings in API requests.")
                                    .type(JsonFieldType.NUMBER),
                            PayloadDocumentation.fieldWithPath("referenceId")
                                    .description("The supplementary identifier.").type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("text").description("The text.")
                                    .type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("version").description("The entity version.")
                                    .type(JsonFieldType.NUMBER),
                            PayloadDocumentation.fieldWithPath("createdBy").description("The entity creator.")
                                    .type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("createdAt").description("The creation timestamp.")
                                    .type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("updatedBy").description("The last modifier.")
                                    .type(JsonFieldType.STRING).optional(),
                            PayloadDocumentation.fieldWithPath("updatedAt")
                                    .description("The last modification timestamp.").type(JsonFieldType.STRING)
                                    .optional())))
            .andReturn();

    // Perform a simple, standard JUnit assertion to satisfy PMD rule
    Assert.assertEquals("failure - expected HTTP status 200", 200, result.getResponse().getStatus());

}
 
Example #6
Source File: CommandRestControllerIntegrationTest.java    From genie with Apache License 2.0 5 votes vote down vote up
@Test
void testRemoveClusterCriterionFromCommand() throws Exception {
    final RestDocumentationFilter removeFilter = RestAssuredRestDocumentation.document(
        "{class-name}/{method-name}/{step}/",
        // Path parameters
        Snippets
            .ID_PATH_PARAM
            .and(
                RequestDocumentation
                    .parameterWithName("priority")
                    .description("Priority of the criterion to insert")
            )
    );

    final String id = this.createCommandWithDefaultClusterCriteria();

    RestAssured
        .given(this.getRequestSpecification())
        .filter(removeFilter)
        .when()
        .port(this.port)
        .delete(COMMANDS_API + "/{id}/clusterCriteria/{priority}", id, 1)
        .then()
        .statusCode(HttpStatus.OK.value());

    Assertions
        .assertThat(this.getClusterCriteria(id))
        .hasSize(CLUSTER_CRITERIA.size() - 1)
        .containsExactly(CLUSTER_CRITERIA.get(0));

    // Running again throws 404
    RestAssured
        .given(this.getRequestSpecification())
        .when()
        .port(this.port)
        .delete(COMMANDS_API + "/{id}/clusterCriteria/{priority}", id, 1)
        .then()
        .statusCode(HttpStatus.NOT_FOUND.value());
}
 
Example #7
Source File: ClusterRestControllerIntegrationTest.java    From genie with Apache License 2.0 5 votes vote down vote up
@Test
void canDeleteTagForCluster() throws Exception {
    this.createConfigResource(new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP).withId(ID).build(), null);
    final String api = CLUSTERS_API + "/{id}/tags";
    final RestDocumentationFilter deleteFilter = RestAssuredRestDocumentation.document(
        "{class-name}/{method-name}/{step}/",
        Snippets.ID_PATH_PARAM.and(RequestDocumentation.parameterWithName("tag").description("The tag to remove"))
    );
    this.canDeleteTagForResource(api, ID, NAME, deleteFilter);
}
 
Example #8
Source File: ClusterRestControllerIntegrationTest.java    From genie with Apache License 2.0 5 votes vote down vote up
@Test
void canRemoveCommandFromACluster() throws Exception {
    this.createConfigResource(new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP).withId(ID).build(), null);
    final String clusterCommandsAPI = CLUSTERS_API + "/{id}/commands";

    final RestDocumentationFilter deleteFilter = RestAssuredRestDocumentation.document(
        "{class-name}/{method-name}/{step}/",
        Snippets.ID_PATH_PARAM.and(
            RequestDocumentation.parameterWithName("commandId").description("The id of the command to remove")
        ) // Path parameters
    );

    RestAssured
        .given(this.getRequestSpecification())
        .filter(deleteFilter)
        .when()
        .port(this.port)
        .delete(clusterCommandsAPI + "/{commandId}", ID, UUID.randomUUID().toString())
        .then()
        .statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));

    RestAssured
        .given(this.getRequestSpecification())
        .when()
        .port(this.port)
        .get(clusterCommandsAPI, ID)
        .then()
        .statusCode(Matchers.is(HttpStatus.OK.value()))
        .contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
        .body("$", Matchers.empty());
}
 
Example #9
Source File: ParameterDescriptorWithRamlTypeTest.java    From restdocs-raml with MIT License 4 votes vote down vote up
private void whenParameterDescriptorCreatedFromRestDocsParameter() {
    descriptor = ParameterDescriptorWithRamlType.from(RequestDocumentation.parameterWithName("some")
            .description("some")
            .optional());
}
 
Example #10
Source File: SendGreetingDocTest.java    From skeleton-ws-spring-boot with Apache License 2.0 4 votes vote down vote up
/**
 * Generate API documentation for POST /api/greetings/{id}/send.
 * 
 * @throws Exception Thrown if documentation generation failure occurs.
 */
@Test
public void documentSendGreeting() throws Exception {

    // Generate API Documentation
    final MvcResult result = this.mockMvc
            .perform(RestDocumentationRequestBuilders
                    .post("/api/greetings/{id}/send?wait=true", 1).accept(MediaType.APPLICATION_JSON))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andDo(MockMvcRestDocumentation.document("send-greeting",
                    RequestDocumentation.pathParameters(
                            RequestDocumentation.parameterWithName("id").description("The greeting identifier.")),
                    RequestDocumentation.requestParameters(RequestDocumentation.parameterWithName("wait")
                            .description("Optional. Boolean. Wait for email to be sent.").optional()),
                    PayloadDocumentation.relaxedResponseFields(
                            PayloadDocumentation
                                    .fieldWithPath("id")
                                    .description(
                                            "The identifier. Used to reference specific greetings in API requests.")
                                    .type(JsonFieldType.NUMBER),
                            PayloadDocumentation.fieldWithPath("referenceId")
                                    .description("The supplementary identifier.").type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("text").description("The text.")
                                    .type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("version").description("The entity version.")
                                    .type(JsonFieldType.NUMBER),
                            PayloadDocumentation.fieldWithPath("createdBy").description("The entity creator.")
                                    .type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("createdAt").description("The creation timestamp.")
                                    .type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("updatedBy").description("The last modifier.")
                                    .type(JsonFieldType.STRING).optional(),
                            PayloadDocumentation.fieldWithPath("updatedAt")
                                    .description("The last modification timestamp.").type(JsonFieldType.STRING)
                                    .optional())))
            .andReturn();

    // Perform a simple, standard JUnit assertion to satisfy PMD rule
    Assert.assertEquals("failure - expected HTTP status 200", 200, result.getResponse().getStatus());

}
 
Example #11
Source File: CommandRestControllerIntegrationTest.java    From genie with Apache License 2.0 4 votes vote down vote up
@Test
void canGetClustersForCommand() throws Exception {
    final String placeholder = UUID.randomUUID().toString();
    final String cluster1Id = this.createConfigResource(
        new Cluster.Builder(placeholder, placeholder, placeholder, ClusterStatus.UP).build(),
        null
    );
    final String cluster2Id = this.createConfigResource(
        new Cluster.Builder(placeholder, placeholder, placeholder, ClusterStatus.OUT_OF_SERVICE).build(),
        null
    );
    final String cluster3Id = this.createConfigResource(
        new Cluster
            .Builder(placeholder, placeholder, placeholder, ClusterStatus.TERMINATED)
            .build(),
        null
    );

    final String commandId = this.createConfigResource(
        new Command
            .Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS, CHECK_DELAY)
            .withClusterCriteria(
                Lists.newArrayList(
                    new Criterion.Builder().withId(cluster1Id).build(),
                    new Criterion.Builder().withId(cluster2Id).build(),
                    new Criterion.Builder().withId(cluster3Id).build()
                )
            )
            .build(),
        null
    );

    Assertions
        .assertThat(
            Arrays.stream(
                GenieObjectMapper.getMapper().readValue(
                    RestAssured
                        .given(this.getRequestSpecification())
                        .when()
                        .port(this.port)
                        .get(COMMANDS_API + "/{id}/clusters", commandId)
                        .then()
                        .statusCode(Matchers.is(HttpStatus.OK.value()))
                        .contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
                        .extract()
                        .asByteArray(),
                    new TypeReference<EntityModel<Cluster>[]>() {
                    }
                )
            )
                .map(EntityModel::getContent)
                .filter(Objects::nonNull)
                .map(Cluster::getId)
                .filter(Optional::isPresent)
                .map(Optional::get)
                .collect(Collectors.toList())
        )
        .containsExactlyInAnyOrder(cluster1Id, cluster2Id, cluster3Id);

    // Test filtering
    final RestDocumentationFilter getFilter = RestAssuredRestDocumentation.document(
        "{class-name}/{method-name}/{step}/",
        Snippets.ID_PATH_PARAM, // Path parameters
        RequestDocumentation.requestParameters(
            RequestDocumentation
                .parameterWithName("status")
                .description("The status of clusters to search for")
                .attributes(
                    Attributes.key(Snippets.CONSTRAINTS).value(CommandStatus.values())
                )
                .optional()
        ), // Query Parameters
        Snippets.HAL_CONTENT_TYPE_HEADER, // Response Headers
        PayloadDocumentation.responseFields(
            PayloadDocumentation
                .subsectionWithPath("[]")
                .description("The list of clusters found")
                .attributes(Snippets.EMPTY_CONSTRAINTS)
        )
    );

    RestAssured
        .given(this.getRequestSpecification())
        .filter(getFilter)
        .param("status", ClusterStatus.UP.toString())
        .when()
        .port(this.port)
        .get(COMMANDS_API + "/{id}/clusters", commandId)
        .then()
        .statusCode(Matchers.is(HttpStatus.OK.value()))
        .contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
        .body("$", Matchers.hasSize(1))
        .body("[0].id", Matchers.is(cluster1Id));
}
 
Example #12
Source File: CommandRestControllerIntegrationTest.java    From genie with Apache License 2.0 4 votes vote down vote up
@Test
void testInsertClusterCriterionForCommand() throws Exception {
    final RestDocumentationFilter insertFilter = RestAssuredRestDocumentation.document(
        "{class-name}/{method-name}/{step}/",
        // Path parameters
        Snippets
            .ID_PATH_PARAM
            .and(
                RequestDocumentation
                    .parameterWithName("priority")
                    .description("Priority of the criterion to insert")
            ),
        Snippets.CONTENT_TYPE_HEADER, // Request Header
        Snippets.addClusterCriterionForCommandRequestPayload() // Payload Docs
    );

    final String id = this.createCommandWithDefaultClusterCriteria();
    final Criterion newCriterion = new Criterion
        .Builder()
        .withVersion("4.0.0")
        .withId(UUID.randomUUID().toString())
        .withName("insightCluster")
        .withStatus(ClusterStatus.OUT_OF_SERVICE.name())
        .withTags(Sets.newHashSet("sched:insights", "type:presto"))
        .build();

    RestAssured
        .given(this.getRequestSpecification())
        .filter(insertFilter)
        .contentType(MediaType.APPLICATION_JSON_VALUE)
        .body(GenieObjectMapper.getMapper().writeValueAsBytes(newCriterion))
        .when()
        .port(this.port)
        .put(COMMANDS_API + "/{id}/clusterCriteria/{priority}", id, 1)
        .then()
        .statusCode(HttpStatus.OK.value());

    Assertions
        .assertThat(this.getClusterCriteria(id))
        .hasSize(CLUSTER_CRITERIA.size() + 1)
        .containsExactly(CLUSTER_CRITERIA.get(0), newCriterion, CLUSTER_CRITERIA.get(1));
}
 
Example #13
Source File: ClusterRestControllerIntegrationTest.java    From genie with Apache License 2.0 4 votes vote down vote up
@Test
void canAddCommandsForACluster() throws Exception {
    this.createConfigResource(new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP).withId(ID).build(), null);
    final String clusterCommandsAPI = CLUSTERS_API + "/{id}/commands";

    final RestDocumentationFilter addFilter = RestAssuredRestDocumentation.document(
        "{class-name}/{method-name}/{step}/",
        Snippets.CONTENT_TYPE_HEADER, // Request Headers
        Snippets.ID_PATH_PARAM, // Path parameters
        PayloadDocumentation.requestFields(
            PayloadDocumentation
                .fieldWithPath("[]")
                .description("Array of command ids (in preferred order) to append to the existing list of commands")
                .attributes(Snippets.EMPTY_CONSTRAINTS)
        ) // Request payload
    );

    RestAssured
        .given(this.getRequestSpecification())
        .filter(addFilter)
        .contentType(MediaType.APPLICATION_JSON_VALUE)
        .body(
            GenieObjectMapper
                .getMapper()
                .writeValueAsBytes(Lists.newArrayList(UUID.randomUUID().toString(), UUID.randomUUID().toString()))
        )
        .when()
        .port(this.port)
        .post(clusterCommandsAPI, ID)
        .then()
        .statusCode(Matchers.is(HttpStatus.NO_CONTENT.value()));

    // Test the filtering
    final RestDocumentationFilter getFilter = RestAssuredRestDocumentation.document(
        "{class-name}/{method-name}/{step}/",
        Snippets.ID_PATH_PARAM, // Path parameters
        RequestDocumentation.requestParameters(
            RequestDocumentation
                .parameterWithName("status")
                .description("The status of commands to search for")
                .attributes(Attributes.key(Snippets.CONSTRAINTS).value(CommandStatus.values()))
                .optional()
        ), // Query Parameters
        Snippets.HAL_CONTENT_TYPE_HEADER, // Response Headers
        PayloadDocumentation.responseFields(
            PayloadDocumentation
                .subsectionWithPath("[]")
                .description("The list of commands found")
                .attributes(Snippets.EMPTY_CONSTRAINTS)
        )
    );

    RestAssured
        .given(this.getRequestSpecification())
        .filter(getFilter)
        .param("status", CommandStatus.ACTIVE.toString())
        .when()
        .port(this.port)
        .get(clusterCommandsAPI, ID)
        .then()
        .statusCode(Matchers.is(HttpStatus.OK.value()))
        .contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
        .body("$", Matchers.empty());
}