Java Code Examples for io.restassured.RestAssured

The following examples show how to use io.restassured.RestAssured. 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: smallrye-open-api   Source File: BaseTckTest.java    License: 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 2
Source Project: quarkus   Source File: FlywayDevModeTest.java    License: 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 3
Source Project: camel-quarkus   Source File: MicroProfileHealthTest.java    License: 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 4
Source Project: quarkus   Source File: PrimitiveInjectionUnitTest.java    License: 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 5
Source Project: quarkus   Source File: HealthCheckDefaultScopeTest.java    License: 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 6
Source Project: james-project   Source File: UserMailboxesRoutesTest.java    License: 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 7
Source Project: quarkus   Source File: OpenApiDefaultPathTestCase.java    License: 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 8
Source Project: quarkus   Source File: NotFoundExceptionMapperTestCase.java    License: 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 9
Source Project: james-project   Source File: WebAdminServerTest.java    License: 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 10
Source Project: quarkus   Source File: OpenApiHotReloadTest.java    License: 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 11
Source Project: quarkus   Source File: DevModeConstraintValidationTest.java    License: Apache License 2.0 6 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 12
Source Project: api-layer   Source File: PassTicketTest.java    License: Eclipse Public License 2.0 6 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 13
@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 14
Source Project: quarkus   Source File: GreetingTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testVertx() {
    RestAssured.when().get("/vertx/hello").then()
            .statusCode(200)
            .contentType("text/plain")
            .body(equalTo("hello vertx"));
}
 
Example 15
Source Project: quarkus   Source File: ElytronSecurityJdbcTest.java    License: 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);
}
 
Example 16
Source Project: tutorials   Source File: JPASpecificationLiveTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenFirstNameSuffix_whenGettingListOfUsers_thenCorrect() {
    final Response response = RestAssured.get(URL_PREFIX + "firstName:*n");
    final String result = response.body()
        .asString();

    assertTrue(result.contains(userJohn.getEmail()));
    assertFalse(result.contains(userTom.getEmail()));
}
 
Example 17
Source Project: camel-quarkus   Source File: MustacheTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void templateWithPartials() {
    RestAssured.get("/mustache/templateWithPartials")
            .then()
            .statusCode(200)
            .body(is("\nStart-\nIncluded-End"));
}
 
Example 18
Source Project: quarkus   Source File: PermitDenyAllTestCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test()
public void testUncoveredMethod() {

    RestAssured
            .given()
            .when()
            .get("/unmentioned")
            .then()
            .assertThat()
            .statusCode(200)
            .body(equalTo(":/unmentioned"));

    RestAssured
            .given()
            .auth()
            .basic("test", "test")
            .when()
            .get("/unmentioned")
            .then()
            .assertThat()
            .statusCode(200)
            .body(equalTo(":/unmentioned"));

    RestAssured
            .given()
            .auth()
            .preemptive()
            .basic("test", "test")
            .when()
            .get("/unmentioned")
            .then()
            .assertThat()
            .statusCode(200)
            .body(equalTo("test:/unmentioned"));
}
 
Example 19
Source Project: james-project   Source File: DLPConfigurationRoutesTest.java    License: 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 20
Source Project: quarkus   Source File: BearerTokenAuthorizationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSecureAccessSuccessCustomPrincipal() {
    for (String username : Arrays.asList("alice", "jdoe", "admin")) {
        RestAssured.given().auth().oauth2(getAccessToken(username))
                .when().get("/api/users/me")
                .then()
                .statusCode(200)
                .body("userName", equalTo(username + "@gmail.com"));
    }
}
 
Example 21
Source Project: quarkus   Source File: VertxSerializerRegistrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSendingJsonArrays() {
    RestAssured
            .given()
            .body(new JsonArray()
                    .add(new JsonArray()
                            .add(new JsonObject().put("name", "bob").put("kind", "cat"))
                            .add(new JsonObject().put("name", "titi").put("kind", "bird")))
                    .encode())
            .header("Content-Type", "application/json")
            .post("/test/arrays")
            .then().statusCode(204);
}
 
Example 22
Source Project: camel-quarkus   Source File: DozerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDozerEndpoint() {
    RestAssured.get("/dozer/map")
            .then()
            .statusCode(200)
            .body("address", notNullValue(),
                    "address.zip", is("12345"),
                    "address.street", is("Camel Street"));
}
 
Example 23
Source Project: api-layer   Source File: PassTicketTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
@TestsNotMeantForZowe
public void doTicketWithValidCookieAndCertificate() {
    RestAssured.config = RestAssured.config().sslConfig(getConfiguredSslConfig());
    String jwt = gatewayToken();
    log.info(APPLICATION_NAME);
    TicketRequest ticketRequest = new TicketRequest(APPLICATION_NAME);

    // Generate ticket
    TicketResponse ticketResponse = given()
        .contentType(JSON)
        .body(ticketRequest)
        .cookie(COOKIE, jwt)
    .when()
        .post(String.format("%s://%s:%d%s", SCHEME, HOST, PORT, TICKET_ENDPOINT))
    .then()
        .statusCode(is(SC_OK))
        .extract().body().as(TicketResponse.class);

    assertEquals(jwt, ticketResponse.getToken());
    assertEquals(USERNAME, ticketResponse.getUserId());
    assertEquals(APPLICATION_NAME, ticketResponse.getApplicationName());

    // Validate ticket
    given()
         .auth().preemptive().basic(USERNAME, ticketResponse.getTicket())
         .param("appliId", APPLICATION_NAME)
    .when()
        .get(String.format("%s://%s:%d%s%s", SCHEME, HOST, PORT, DISCOVERABLECLIENT_BASE_PATH, PASSTICKET_TEST_ENDPOINT))
    .then()
        .statusCode(is(SC_OK));
}
 
Example 24
Source Project: frameworkium-bdd   Source File: BikePointService.java    License: Apache License 2.0 5 votes vote down vote up
public BikePoints getAllBikePoints() {
    Place[] places = RestAssured.given()
            .contentType("application/json")
            .when()
            .get(URL)
            .then()
            .statusCode(200)
            .extract()
            .as(Place[].class);

    return new BikePoints(places);
}
 
Example 25
Source Project: tutorials   Source File: SpringBootBootstrapLiveTest.java    License: MIT License 5 votes vote down vote up
@Test
public void whenCreateNewBook_thenCreated() {
    final Book book = createRandomBook();

    final Response response = RestAssured.given()
        .contentType(MediaType.APPLICATION_JSON_VALUE)
        .body(book)
        .post(API_ROOT);
    assertEquals(HttpStatus.CREATED.value(), response.getStatusCode());
}
 
Example 26
Source Project: quarkus   Source File: ContextPathTestCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testNoSlash() {
    RestAssured.given().redirects().follow(false).when().get("/foo").then()
            .statusCode(302);
    RestAssured.when().get("/foo").then()
            .statusCode(200)
            .body(is("index"));
}
 
Example 27
Source Project: quarkus   Source File: RolesAllowedUnitTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Validate a request with MP-JWT SecurityContext.getUserPrincipal() is a JsonWebToken
 *
 */
@Test()
public void getPrincipalClass() {
    io.restassured.response.Response response = RestAssured.given().auth()
            .oauth2(token)
            .when()
            .get("/endp/getPrincipalClass").andReturn();

    Assertions.assertEquals(HttpURLConnection.HTTP_OK, response.getStatusCode());
    String replyString = response.body().asString();
    // Must return isJsonWebToken:true
    Assertions.assertEquals("isJsonWebToken:true", replyString);
}
 
Example 28
Source Project: tracksrestcasestudy   Source File: RestAssuredXMLExamplesTest.java    License: MIT License 5 votes vote down vote up
@Test
public void simpleXmlRestAssuredExample(){
    RestAssured.when().get(xmlendpoint).
        then().assertThat().
            body("projects.project[0].name",
                 equalTo("A New Projectaniheeiadtatd"));
}
 
Example 29
@BeforeEach
void beforeEach() throws Exception {
    blobIdFactory = new HashBlobId.Factory();
    blobStore = spy(new MemoryBlobStore(blobIdFactory, new MemoryDumbBlobStore()));
    clock = new UpdatableTickingClock(OLD_DELETION_DATE.toInstant());
    vault = spy(new BlobStoreDeletedMessageVault(new RecordingMetricFactory(), new MemoryDeletedMessageMetadataVault(),
        blobStore, new BucketNameGenerator(clock), clock,
        RetentionConfiguration.DEFAULT));
    InMemoryIntegrationResources inMemoryResource = InMemoryIntegrationResources.defaultResources();
    mailboxManager = spy(inMemoryResource.getMailboxManager());

    taskManager = new MemoryTaskManager(new Hostname("foo"));
    JsonTransformer jsonTransformer = new JsonTransformer();

    RestoreService vaultRestore = new RestoreService(vault, mailboxManager);
    blobExporting = spy(new NoopBlobExporting());
    zipper = new DeletedMessageZipper();
    exportService = new ExportService(blobExporting, blobStore, zipper, vault);
    QueryTranslator queryTranslator = new QueryTranslator(new InMemoryId.Factory());
    usersRepository = createUsersRepository();
    MessageId.Factory messageIdFactory = new InMemoryMessageId.Factory();
    webAdminServer = WebAdminUtils.createWebAdminServer(
            new TasksRoutes(taskManager, jsonTransformer,
                DTOConverter.of(
                    WebAdminDeletedMessagesVaultDeleteTaskAdditionalInformationDTO.module(messageIdFactory),
                    DeletedMessagesVaultExportTaskAdditionalInformationDTO.module(),
                    WebAdminDeletedMessagesVaultRestoreTaskAdditionalInformationDTO.module(),
                    BlobStoreVaultGarbageCollectionTaskAdditionalInformationDTO.module())),
            new DeletedMessagesVaultRoutes(vault, vaultRestore, exportService, jsonTransformer, taskManager, queryTranslator, usersRepository, messageIdFactory))
        .start();
    RestAssured.requestSpecification = WebAdminUtils.buildRequestSpecification(webAdminServer)
        .setBasePath(DeletedMessagesVaultRoutes.ROOT_PATH)
        .log(LogDetail.METHOD)
        .build();
}
 
Example 30
Source Project: quarkus   Source File: MappingTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testNoopGet() {
    RestAssured.given()
            .config(RestAssured.config.encoderConfig(
                    EncoderConfig.encoderConfig().appendDefaultContentCharsetToContentTypeIfUndefined(false)))
            .contentType("")
            .get("/noop")
            .then().statusCode(204)
            .header("ce-id", nullValue())
            .header("ce-type", nullValue())
            .header("ce-source", nullValue());
}