io.restassured.RestAssured Java Examples

The following examples show how to use io.restassured.RestAssured. 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: DevModeConstraintValidationTest.java    From quarkus with Apache License 2.0 7 votes vote down vote up
@Test
public void testNewConstraintHotReplacement() {
    RestAssured.given()
            .header("Content-Type", "application/json")
            .when()
            .body("{}")
            .post("/test/validate")
            .then()
            .body(containsString("ok"));

    TEST.addSourceFile(NewConstraint.class);
    TEST.addSourceFile(NewValidator.class);
    TEST.modifySourceFile("TestBean.java", s -> s.replace("// <placeholder2>",
            "@NewConstraint"));

    RestAssured.given()
            .header("Content-Type", "application/json")
            .when()
            .body("{}")
            .post("/test/validate")
            .then()
            .body(containsString("My new constraint message"));
}
 
Example #2
Source File: MetadataApiControllerIT.java    From molgenis with GNU Lesser General Public License v3.0 7 votes vote down vote up
@ParameterizedTest
@ValueSource(
    strings = {
      "Identifiable",
      "Describable",
      "MyNumbers",
      "MyStrings",
      "MyDataset",
      "MyOneToMany"
    })
@Order(1)
void testCreateMetadataEntityTypeIdentifiable(String datasetName) throws IOException {
  String bodyJson =
      TestResourceUtils.getRenderedString(
          getClass(),
          "createMetadataEntityType" + datasetName + ".json",
          ImmutableMap.of("baseUri", RestAssured.baseURI));

  given()
      .contentType(APPLICATION_JSON_VALUE)
      .body(bodyJson)
      .post("/api/metadata")
      .then()
      .statusCode(CREATED.value())
      .header(LOCATION, RestAssured.baseURI + "/api/metadata/v3meta_" + datasetName);
}
 
Example #3
Source File: PassTicketTest.java    From api-layer with Eclipse Public License 2.0 7 votes vote down vote up
@Test
public void doTicketWithoutToken() {
    String expectedMessage = "No authorization token provided for URL '" + TICKET_ENDPOINT + "'";

    RestAssured.config = RestAssured.config().sslConfig(getConfiguredSslConfig());
    TicketRequest ticketRequest = new TicketRequest(APPLICATION_NAME);

    given()
        .contentType(JSON)
        .body(ticketRequest)
    .when()
        .post(String.format("%s://%s:%d%s", SCHEME, HOST, PORT, TICKET_ENDPOINT))
    .then()
        .statusCode(is(SC_UNAUTHORIZED))
        .body("messages.find { it.messageNumber == 'ZWEAG131E' }.messageContent", equalTo(expectedMessage));
}
 
Example #4
Source File: BaseTckTest.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static final void setUp() throws Exception {
    String portEnv = System.getProperty("smallrye.openapi.server.port");
    if (portEnv == null || portEnv.isEmpty()) {
        portEnv = "8082";
    }
    HTTP_PORT = Integer.valueOf(portEnv);
    // Set RestAssured default port directly. A bit nasty, but we have no easy way to change
    // AppTestBase#callEndpoint in the upstream. They also seem to do it this way, so it's no worse
    // than what's there.
    RestAssured.port = HTTP_PORT;
    // Set up a little HTTP server so that Rest assured has something to pull /openapi from
    System.out.println("Starting TCK test server on port " + HTTP_PORT);
    server = HttpServer.create(new InetSocketAddress(HTTP_PORT), 0);
    server.createContext("/openapi", new MyHandler());
    server.setExecutor(null);
    server.start();

    // Register a filter that performs YAML to JSON conversion
    // Called here because the TCK's AppTestBase#setUp() is not called. (Remove for 2.0)
    RestAssured.filters(new YamlToJsonFilter());
}
 
Example #5
Source File: WebAdminServerTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
public void aSecondRouteWithSameEndpointShouldNotOverridePreviouslyDefinedRoutesWhenPublic() {
    String firstAnswer = "1";
    String secondAnswer = "2";
    WebAdminServer server = WebAdminUtils.createWebAdminServer(
        myPrivateRouteWithConstAnswer(firstAnswer),
        myPublicRouteWithConstAnswer(secondAnswer));
    server.start();

    try {
        RestAssured.requestSpecification = WebAdminUtils.buildRequestSpecification(server)
            .setBasePath("/myRoute")
            .build();

        when()
            .get()
        .then()
            .body(is(firstAnswer));
    } finally {
        server.destroy();
    }
}
 
Example #6
Source File: FlywayDevModeTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("Injecting (default) flyway should fail if there is no datasource configured")
public void testAddingFlyway() {
    RestAssured.get("fly").then().statusCode(500);
    config.modifyResourceFile("application.properties", new Function<String, String>() {
        @Override
        public String apply(String s) {
            return "quarkus.datasource.db-kind=h2\n" +
                    "quarkus.datasource.username=sa\n" +
                    "quarkus.datasource.password=sa\n" +
                    "quarkus.datasource.jdbc.url=jdbc:h2:tcp://localhost/mem:test-quarkus-migrate-at-start;DB_CLOSE_DELAY=-1\n"
                    +
                    "quarkus.flyway.migrate-at-start=true";
        }
    });
    RestAssured.get("/fly").then().statusCode(200);

}
 
Example #7
Source File: OpenApiHotReloadTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddingAndUpdatingResource() {
    RestAssured.get("/openapi").then()
            .statusCode(200)
            .body(containsString("/api"));

    TEST.addSourceFile(MySecondResource.class);

    RestAssured.get("/openapi").then()
            .statusCode(200)
            .body(containsString("/api"))
            .body(containsString("/my-second-api"));

    TEST.modifySourceFile("MySecondResource.java", s -> s.replace("my-second-api", "/foo"));

    RestAssured.get("/openapi").then()
            .statusCode(200)
            .body(containsString("/api"))
            .body(not(containsString("/my-second-api")))
            .body(containsString("/foo"));
}
 
Example #8
Source File: MicroProfileHealthTest.java    From camel-quarkus with Apache License 2.0 6 votes vote down vote up
@Test
public void testRouteStoppedDownStatus() {
    try {
        RestAssured.get("/microprofile-health/route/healthyRoute/stop")
                .then()
                .statusCode(204);

        RestAssured.when().get("/health").then()
                .contentType(ContentType.JSON)
                .header("Content-Type", containsString("charset=UTF-8"))
                .body("status", is("DOWN"),
                        "checks.data.'route:healthyRoute'", containsInAnyOrder(null, null, "DOWN"));
    } finally {
        RestAssured.get("/microprofile-health/route/healthyRoute/start")
                .then()
                .statusCode(204);
    }
}
 
Example #9
Source File: HealthCheckDefaultScopeTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Test
public void testHealth() {
    // the health check does not set a content type so we need to force the parser
    try {
        RestAssured.defaultParser = Parser.JSON;
        when().get("/health/live").then()
                .body("status", is("UP"),
                        "checks.status", contains("UP"),
                        "checks.name", contains("noScope"));
        when().get("/health/live").then()
                .body("status", is("DOWN"),
                        "checks.status", contains("DOWN"),
                        "checks.name", contains("noScope"));
    } finally {
        RestAssured.reset();
    }
}
 
Example #10
Source File: NotFoundExceptionMapperTestCase.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotDisplayDeletedFileIn404ErrorPage() {
    String TEST_CONTENT = "test html content";
    test.addResourceFile(META_INF_RESOURCES + "test.html", TEST_CONTENT);

    RestAssured
            .get("/test.html")
            .then()
            .statusCode(200)
            .body(containsString(TEST_CONTENT)); // check that test.html is live reloaded

    test.deleteResourceFile(META_INF_RESOURCES + "test.html"); // delete test.html file

    RestAssured
            .given()
            .accept(ContentType.HTML)
            .when()
            .get("/test.html")
            .then() // try to load static file
            .statusCode(404)
            .body(not(containsString("test.html"))); // check that test.html is not displayed

}
 
Example #11
Source File: OpenApiDefaultPathTestCase.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Test
public void testOpenApiPathAccessResource() {
    RestAssured.given().header("Accept", "application/yaml")
            .when().get(OPEN_API_PATH)
            .then().header("Content-Type", "application/yaml;charset=UTF-8");
    RestAssured.given().queryParam("format", "YAML")
            .when().get(OPEN_API_PATH)
            .then().header("Content-Type", "application/yaml;charset=UTF-8");
    RestAssured.given().header("Accept", "application/json")
            .when().get(OPEN_API_PATH)
            .then().header("Content-Type", "application/json;charset=UTF-8");
    RestAssured.given().queryParam("format", "JSON")
            .when().get(OPEN_API_PATH)
            .then()
            .header("Content-Type", "application/json;charset=UTF-8")
            .body("openapi", Matchers.startsWith("3.0"))
            .body("info.title", Matchers.equalTo("Generated API"))
            .body("paths", Matchers.hasKey("/resource"));
}
 
Example #12
Source File: PrimitiveInjectionUnitTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
/**
 * Verify that the token upn claim is as expected
 */
@Test()
public void verifyInjectedUPN() {
    io.restassured.response.Response response = RestAssured.given().auth()
            .oauth2(token)
            .when()
            .queryParam(Claims.upn.name(), "[email protected]")
            .queryParam(Claims.auth_time.name(), authTimeClaim)
            .get("/endp/verifyInjectedUPN").andReturn();

    Assertions.assertEquals(HttpURLConnection.HTTP_OK, response.getStatusCode());
    String replyString = response.body().asString();
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Assertions.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
Example #13
Source File: UserMailboxesRoutesTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
private void createServer(MailboxManager mailboxManager, MailboxSessionMapperFactory mapperFactory, MailboxId.Factory mailboxIdFactory, ListeningMessageSearchIndex searchIndex) throws Exception {
    usersRepository = mock(UsersRepository.class);
    when(usersRepository.contains(USERNAME)).thenReturn(true);

    taskManager = new MemoryTaskManager(new Hostname("foo"));
    ReIndexerPerformer reIndexerPerformer = new ReIndexerPerformer(
        mailboxManager,
        searchIndex,
        mapperFactory);
    ReIndexer reIndexer = new ReIndexerImpl(
        reIndexerPerformer,
        mailboxManager,
        mapperFactory);

    webAdminServer = WebAdminUtils.createWebAdminServer(
            new UserMailboxesRoutes(new UserMailboxesService(mailboxManager, usersRepository), new JsonTransformer(),
                taskManager,
                ImmutableSet.of(new UserMailboxesRoutes.UserReIndexingTaskRegistration(reIndexer))),
            new TasksRoutes(taskManager, new JsonTransformer(),
                DTOConverter.of(WebAdminUserReindexingTaskAdditionalInformationDTO.serializationModule(mailboxIdFactory))))
        .start();

    RestAssured.requestSpecification = WebAdminUtils.buildRequestSpecification(webAdminServer)
        .setBasePath(USERS_BASE + SEPARATOR + USERNAME.asString() + SEPARATOR + UserMailboxesRoutes.MAILBOXES)
        .build();
}
 
Example #14
Source File: JobRestControllerIntegrationTest.java    From genie with Apache License 2.0 5 votes vote down vote up
private void createAnApplication(final String id, final String appName) throws Exception {
    final String setUpFile = this.getResourceURI(BASE_DIR + id + FILE_DELIMITER + "setupfile");

    final String depFile1 = this.getResourceURI(BASE_DIR + id + FILE_DELIMITER + "dep1");
    final String depFile2 = this.getResourceURI(BASE_DIR + id + FILE_DELIMITER + "dep2");
    final Set<String> app1Dependencies = Sets.newHashSet(depFile1, depFile2);

    final String configFile1 = this.getResourceURI(BASE_DIR + id + FILE_DELIMITER + "config1");
    final String configFile2 = this.getResourceURI(BASE_DIR + id + FILE_DELIMITER + "config2");
    final Set<String> app1Configs = Sets.newHashSet(configFile1, configFile2);

    final Application app = new Application.Builder(
        appName,
        APP1_USER,
        APP1_VERSION,
        ApplicationStatus.ACTIVE)
        .withId(id)
        .withSetupFile(setUpFile)
        .withConfigs(app1Configs)
        .withDependencies(app1Dependencies)
        .build();

    RestAssured
        .given(this.getRequestSpecification())
        .contentType(MediaType.APPLICATION_JSON_VALUE)
        .body(GenieObjectMapper.getMapper().writeValueAsBytes(app))
        .when()
        .port(this.port)
        .post(APPLICATIONS_API)
        .then()
        .statusCode(Matchers.is(HttpStatus.CREATED.value()))
        .header(HttpHeaders.LOCATION, Matchers.notNullValue());
}
 
Example #15
Source File: KafkaProducerTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
    KafkaConsumer<Integer, String> consumer = createConsumer();
    RestAssured.with().body("hello").post("/kafka");
    ConsumerRecord<Integer, String> records = consumer.poll(Duration.ofMillis(10000)).iterator().next();
    Assertions.assertEquals(records.key(), (Integer) 0);
    Assertions.assertEquals(records.value(), "hello");
}
 
Example #16
Source File: CsvTest.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void json2csv() {
    RestAssured.given() //
            .contentType(ContentType.JSON)
            .accept(ContentType.TEXT)
            .body("[{\"name\":\"Melwah\", \"species\":\"Camelus Dromedarius\"},{\"name\":\"Al Hamra\", \"species\":\"Camelus Dromedarius\"}]")
            .post("/csv/json-to-csv")
            .then()
            .statusCode(200)
            .body(is("Melwah,Camelus Dromedarius\r\nAl Hamra,Camelus Dromedarius\r\n"));
}
 
Example #17
Source File: CsvRecordTest.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void csvToJsonShouldSucceed() {
    CsvOrder order = RestAssured.given() //
            .contentType(ContentType.TEXT).body(CSV).get("/bindy/csvToJson").then().statusCode(200).extract()
            .as(CsvOrder.class);

    assertNotNull(order);
    assertNotNull(order.getNameWithLengthSuffix());
    assertEquals("bindy-order-name-16-19", order.getNameWithLengthSuffix().toString());
    assertEquals("B_ND_-C__NTR_", order.getCountry());
}
 
Example #18
Source File: RestApiLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenDeleteCreatedReview_thenOk() {
    // create
    final BookReview review = createRandomReview();
    final String location = createReviewAsUri(review);

    // delete
    Response response = RestAssured.delete(location);
    assertEquals(HttpStatus.NO_CONTENT.value(), response.getStatusCode());

    // confirm it was deleted
    response = RestAssured.get(location);
    assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatusCode());
}
 
Example #19
Source File: LdapSecurityRealmTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * Test access a secured jaxrs resource with authentication, and authorization. should see 200 success code.
 */
@Test
public void testJaxrsGetRoleSuccess() {
    RestAssured.given().auth().preemptive().basic("standardUser", "standardUserPassword")
            .when().get("/jaxrs-secured/roles-class").then()
            .statusCode(200);
}
 
Example #20
Source File: CurlLoggingRestAssuredConfigFactoryTest.java    From curl-logger with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void shouldSentRequestWhenUsingConfigurationFactory() {
  RestAssured.given()
      .config(CurlLoggingRestAssuredConfigFactory.createConfig(Options.builder().useShortForm().build()))
      .baseUri(MOCK_BASE_URI)
      .port(MOCK_PORT)
      .when()
      .get("/anypath2")
      .then()
      .statusCode(200);
}
 
Example #21
Source File: JdbcSecurityRealmTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * Test access a secured jaxrs resource with authentication, and authorization. should see 200 success code.
 */
@Test
public void testJaxrsPathUserRoleSuccess() {
    RestAssured.given().auth().preemptive().basic("user", "user")
            .when().get("/jaxrs-secured/parameterized-paths/my/banking/view").then()
            .statusCode(200);
}
 
Example #22
Source File: MustacheTest.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Test
void templateUriFromHeader() {
    RestAssured.given()
            .contentType(ContentType.TEXT)
            .body("UriFromHeader")
            .post("/mustache/templateUriFromHeader")
            .then()
            .statusCode(200)
            .body(is("\nAnother body 'UriFromHeader'!"));
}
 
Example #23
Source File: AgroalDevModeTestCase.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testAgroalHotReplacement() {
    RestAssured
            .get("/dev/user")
            .then()
            .body(Matchers.equalTo("USERNAME-NAMED"));
    test.modifyResourceFile("application.properties", s -> s.replace("USERNAME-NAMED", "OTHER-USER"));

    RestAssured
            .get("/dev/user")
            .then()
            .body(Matchers.equalTo("OTHER-USER"));
}
 
Example #24
Source File: PdfTest.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Order(1)
@Test
public void createFromTextShouldReturnANewPdfDocument() throws IOException {
    byte[] bytes = RestAssured.given().contentType(ContentType.TEXT)
            .body("content to be included in the created pdf document").post("/pdf/createFromText").then().statusCode(201)
            .extract().asByteArray();

    PDDocument doc = PDDocument.load(bytes);
    PDFTextStripper pdfTextStripper = new PDFTextStripper();
    String text = pdfTextStripper.getText(doc);
    assertEquals(1, doc.getNumberOfPages());
    assertTrue(text.contains("content to be included in the created pdf document"));
    doc.close();
}
 
Example #25
Source File: JobRestControllerIntegrationTest.java    From genie with Apache License 2.0 5 votes vote down vote up
private void checkJobCommand(final int documentationId, final String id) {
    final RestDocumentationFilter getResultFilter = RestAssuredRestDocumentation.document(
        "{class-name}/" + documentationId + "/getJobCommand/",
        Snippets.ID_PATH_PARAM, // Path parameters
        Snippets.HAL_CONTENT_TYPE_HEADER, // Response Headers
        Snippets.getCommandResponsePayload(), // Response fields
        Snippets.COMMAND_LINKS // Links
    );

    RestAssured
        .given(this.getRequestSpecification())
        .filter(getResultFilter)
        .when()
        .port(this.port)
        .get(JOBS_API + "/{id}/command", id)
        .then()
        .statusCode(Matchers.is(HttpStatus.OK.value()))
        .contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
        .body(ID_PATH, Matchers.is(CMD1_ID))
        .body(CREATED_PATH, Matchers.notNullValue())
        .body(UPDATED_PATH, Matchers.notNullValue())
        .body(NAME_PATH, Matchers.is(CMD1_NAME))
        .body(USER_PATH, Matchers.is(CMD1_USER))
        .body(VERSION_PATH, Matchers.is(CMD1_VERSION))
        .body("executable", Matchers.is(CMD1_EXECUTABLE))
        .body("executableAndArguments", Matchers.equalTo(CMD1_EXECUTABLE_AND_ARGS));
}
 
Example #26
Source File: ExceptionHandlingTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testPojoWithResponseEntityException() {
    RestAssured.when().get("/exception/re/pojo").then()
            .contentType("application/json")
            .body(containsString("bad state"))
            .body(containsString("/exception/re/pojo"))
            .statusCode(402)
            .header("custom-header", "custom-value");
}
 
Example #27
Source File: Base64Test.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    byte[] body;

    ExtractableResponse response = RestAssured.given() //
            .contentType(ContentType.BINARY).body("Hello World".getBytes()).post("/base64/post") //
            .then().extract();

    body = response.body().asByteArray();
    Assertions.assertNotNull(body);

    Assertions.assertEquals("SGVsbG8gV29ybGQ\n", new String(body));
}
 
Example #28
Source File: BaseIT.java    From validator with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    final String port = System.getProperty("daemon.port");
    if (port != null) {
        RestAssured.port = Integer.valueOf(port);
    }
    final String baseHost = System.getProperty("daemon.host");
    if (baseHost != null) {
        RestAssured.baseURI = baseHost;
    }
    RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();
}
 
Example #29
Source File: SoapTest.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnmarshalSoap12() {
    final String msg = UUID.randomUUID().toString().replace("-", "");
    String resp = RestAssured.given()
            .contentType(ContentType.XML).body(getSoapMessage("1.2", msg)).post("/soap/unmarshal/1.2") //
            .then().statusCode(201)
            .extract().body().asString();
    assertThat(resp).isEqualTo(msg);
}
 
Example #30
Source File: ElytronSecurityJdbcTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
void forbidden_not_authenticated() {
    RestAssured.given()
            .redirects().follow(false)
            .when()
            .get("/api/forbidden")
            .then()
            .statusCode(302);
}