com.jayway.restassured.RestAssured Java Examples
The following examples show how to use
com.jayway.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: EventStreamReadingAT.java From nakadi with MIT License | 6 votes |
@Test(timeout = 10000) @SuppressWarnings("unchecked") public void whenReachKeepAliveLimitThenStreamIsClosed() { // ACT // final int keepAliveLimit = 3; final Response response = RestAssured.given() .param("batch_flush_timeout", "1") .param("stream_keep_alive_limit", keepAliveLimit) .when() .get(streamEndpoint); // ASSERT // response.then().statusCode(HttpStatus.OK.value()).header(HttpHeaders.TRANSFER_ENCODING, "chunked"); final String body = response.print(); final List<Map<String, Object>> batches = deserializeBatches(body); // validate amount of batches and structure of each batch Assert.assertThat(batches, Matchers.hasSize(PARTITIONS_NUM * keepAliveLimit)); batches.forEach(batch -> validateBatchStructure(batch, null)); }
Example #2
Source File: AcceptHeaderTest.java From p3-batchrefine with Apache License 2.0 | 6 votes |
@Test public void testComplexAcceptHeader() throws Exception { String transformURI = fSupport.transformURI("osterie-rdfize.json").toString(); Response response = RestAssured .given().queryParam("refinejson", transformURI).and() .header("Accept", "image/*;q=1,text/*;q=.5,application/rdf+xml;q=.1") .contentType("text/csv") .content(contentsAsBytes("inputs", "osterie", "csv")).when().post() .andReturn(); Assert.assertTrue(MimeUtils.isSameOrSubtype(mimeType(response.contentType()), mimeType("text/*"))); response = RestAssured .given().queryParam("refinejson", transformURI).and() .header("Accept", "image/*;q=0.1,text/*;q=.01,application/rdf+xml;q=.1") .contentType("text/csv") .content(contentsAsBytes("inputs", "osterie", "csv")).when().post() .andReturn(); Assert.assertEquals("application/rdf+xml", response.contentType()); }
Example #3
Source File: SchemaControllerAT.java From nakadi with MIT License | 6 votes |
@Test public void whenGetSchemasThenListWithOffset() throws Exception { createEventType(); RestAssured.given() .when() .get("/event-types/et_test_name/schemas?offset=0&limit=1") .then() .statusCode(HttpStatus.SC_OK) .and() .body("items.size()", Matchers.is(1)) .body("items[0].version", Matchers.equalTo("1.1.0")) .body("_links.next.href", Matchers.equalTo("/event-types/et_test_name/schemas?offset=1&limit=1")) .body("_links.prev", Matchers.nullValue()); RestAssured.given() .when() .get("/event-types/et_test_name/schemas?offset=1&limit=1") .then() .statusCode(HttpStatus.SC_OK) .and() .body("items.size()", Matchers.is(1)) .body("items[0].version", Matchers.equalTo("1.0.0")) .body("_links.next", Matchers.nullValue()) .body("_links.prev.href", Matchers.equalTo("/event-types/et_test_name/schemas?offset=0&limit=1")); }
Example #4
Source File: SchemaControllerAT.java From nakadi with MIT License | 6 votes |
@Test public void whenGetSchemasThenListWithGreatOffset() throws Exception { createEventType(); RestAssured.given() .when() .get("/event-types/et_test_name/schemas?offset=2&limit=5") .then() .statusCode(HttpStatus.SC_OK) .and() .body("items.size()", Matchers.is(0)) .body("_links.next", Matchers.nullValue()) .body("_links.prev", Matchers.nullValue()); RestAssured.given() .when() .get("/event-types/et_test_name/schemas?offset=5&limit=2") .then() .statusCode(HttpStatus.SC_OK) .and() .body("items.size()", Matchers.is(0)) .body("_links.next", Matchers.nullValue()) .body("_links.prev", Matchers.nullValue()); }
Example #5
Source File: NakadiTestUtils.java From nakadi with MIT License | 6 votes |
public static void publishBusinessEventsWithUserDefinedPartition( final String eventType, final Map<String, String> fooToPartition) { final JSONArray jsonArray = new JSONArray( fooToPartition.entrySet().stream().map(entry -> { final JSONObject metadata = new JSONObject(); metadata.put("eid", UUID.randomUUID().toString()); metadata.put("occurred_at", (new DateTime(DateTimeZone.UTC)).toString()); metadata.put("partition", entry.getValue()); final JSONObject event = new JSONObject(); event.put("metadata", metadata); event.put("foo", entry.getKey()); return event; }).collect(Collectors.toList())); RestAssured.given() .body(jsonArray.toString()) .contentType(ContentType.JSON) .post(format("/event-types/{0}/events", eventType)); }
Example #6
Source File: NvdRestServiceMockup.java From steady with Apache License 2.0 | 6 votes |
/** * Starts the server and registers URIs for the different vulnerabilities in {@link NvdRestServiceMockup#CVES}. * @throws IOException */ public NvdRestServiceMockup() { server = new StubServer().run(); RestAssured.port = server.getPort(); System.setProperty(VulasConfiguration.getServiceUrlKey(Service.CVE), "http://localhost:" + server.getPort() + "/nvdrest/vulnerabilities/<ID>"); int cves_registered = 0; for(String cve: CVES) { try { whenHttp(server). match(composite(method(Method.GET), uri("/nvdrest/vulnerabilities/" + cve))). then( stringContent(FileUtil.readFile(Paths.get("./src/test/resources/cves/" + cve + "-new.json"))), contentType("application/json"), charset("UTF-8"), status(HttpStatus.OK_200)); cves_registered++; } catch (IOException e) { System.err.println("Could not register URI for cve [" + cve + "]: " + e.getMessage()); } } if(cves_registered==0) { throw new IllegalStateException("None of the CVEs could be registered"); } }
Example #7
Source File: StubServerSetup.java From steady with Apache License 2.0 | 6 votes |
public StubServerSetup(String group, String artifact, String version) { server = new StubServer().run(); RestAssured.port = server.getPort(); testTenant = this.buildTestTenant(); testSpace = this.buildTestSpace(); testApp = this.buildTestApplication(group, artifact, version); // App context System.setProperty(CoreConfiguration.APP_CTX_GROUP, testApp.getMvnGroup()); System.setProperty(CoreConfiguration.APP_CTX_ARTIF, testApp.getArtifact()); System.setProperty(CoreConfiguration.APP_CTX_VERSI, testApp.getVersion()); // Identify app code System.setProperty(CoreConfiguration.BACKEND_CONNECT, CoreConfiguration.ConnectType.READ_WRITE.toString()); // Identify app code System.setProperty(CoreConfiguration.APP_PREFIXES, "com.acme"); }
Example #8
Source File: ClusteredBounceProxyControllerTest.java From joynr with Apache License 2.0 | 6 votes |
@Test @Ignore("Ignore until servers are started in a separate JVM. Guice static problem") public void testBounceProxyRegistrationAtBpc1() throws Exception { RestAssured.baseURI = bpcUrl1; Response responseRegister = given().log() .all() .queryParam("url4cc", "http://testurl/url4cc") .and() .queryParam("url4bpc", "http://testurl/url4bpc") .when() .put("bounceproxies/?bpid=0.0"); assertEquals(201 /* Created */, responseRegister.getStatusCode()); waitForReplication(); RestAssured.baseURI = bpcUrl2; JsonPath listBps = given().log().all().get("bounceproxies").body().jsonPath(); assertThat(listBps, containsBounceProxy("0.0", "ALIVE")); }
Example #9
Source File: ExampleApplicationTest.java From crnk-example with Apache License 2.0 | 6 votes |
@Before public void setup() { RestAssured.port = port; docs = setupAsciidoc(); client = new CrnkClient("http://localhost:" + port + "/api"); client.addModule(docs); client.addModule(new PlainJsonFormatModule()); client.findModules(); // NPE fix if (AuthConfigFactory.getFactory() == null) { AuthConfigFactory.setFactory(new AuthConfigFactoryImpl()); } }
Example #10
Source File: MessagingLoadDistributionTest.java From joynr with Apache License 2.0 | 6 votes |
private List<ImmutableMessage> getMessagesFromBounceProxy(BounceProxyCommunicationMock bpMock, String channelUrl, String channelId) throws IOException, EncodingException, UnsuppportedVersionException { String previousBaseUri = RestAssured.baseURI; RestAssured.baseURI = Utilities.getUrlWithoutSessionId(channelUrl, "jsessionid"); String sessionId = Utilities.getSessionId(channelUrl, "jsessionid"); /* @formatter:off */ Response response = bpMock.onrequest() .with() .header("X-Atmosphere-tracking-id", bpMock.getReceiverId()) .expect() .statusCode(200) .when() .get(";jsessionid=" + sessionId); /* @formatter:on */ List<ImmutableMessage> messagesFromResponse = bpMock.getJoynrMessagesFromResponse(response); RestAssured.baseURI = previousBaseUri; return messagesFromResponse; }
Example #11
Source File: AcceptHeaderTest.java From p3-batchrefine with Apache License 2.0 | 6 votes |
@Test public void testMultipleAcceptHeaders() throws Exception { String transformURI = fSupport.transformURI("osterie-rdfize.json").toString(); Response response = RestAssured .given().queryParam("refinejson", transformURI).and() .header("Accept", "image/*;q=1,text/*;q=.5,application/rdf+xml;q=.1") .contentType("text/csv") .content(contentsAsBytes("inputs", "osterie", "csv")).when().post() .andReturn(); Assert.assertTrue(MimeUtils.isSameOrSubtype(mimeType(response.contentType()), mimeType("text/*"))); response = RestAssured .given().queryParam("refinejson", transformURI).and() .header("Accept", "image/*;q=1,text/*;q=.5,application/rdf+xml;q=.1", "text/turtle;q=0.7") .contentType("text/csv") .content(contentsAsBytes("inputs", "osterie", "csv")).when().post() .andReturn(); Assert.assertEquals("text/turtle", response.contentType()); }
Example #12
Source File: CheckRestServicesTest.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
@Before public void setup() { RestAssured.basePath = "/knowage/restful-services/2.0"; RestAssured.authentication = basic("biadmin", "biadmin"); String json = get("/customChecks").asString(); ids = JsonPath.from(json).get("checkId"); check.setDescription("testJUnit"); check.setFirstValue(null); check.setLabel("JUnit"); check.setName("Test"); check.setSecondValue(null); check.setValueTypeCd("REGEXP"); check.setValueTypeId(454); }
Example #13
Source File: EventStreamReadingAT.java From nakadi with MIT License | 5 votes |
@Test(timeout = 10000) @SuppressWarnings("unchecked") public void whenReadFromTheEndThenLatestOffsetsInStream() { // ACT // // just stream without X-nakadi-cursors; that should make nakadi to read from the very end final Response response = RestAssured.given() .param("stream_timeout", "2") .param("batch_flush_timeout", "2") .when() .get(streamEndpoint); // ASSERT // response.then().statusCode(HttpStatus.OK.value()).header(HttpHeaders.TRANSFER_ENCODING, "chunked"); final String body = response.print(); final List<Map<String, Object>> batches = deserializeBatches(body); // validate amount of batches and structure of each batch Assert.assertThat(batches, Matchers.hasSize(PARTITIONS_NUM)); batches.forEach(batch -> validateBatchStructure(batch, DUMMY_EVENT)); // validate that the latest offsets in batches correspond to the newest offsets final Set<Cursor> offsets = batches .stream() .map(batch -> { final Map<String, String> cursor = (Map<String, String>) batch.get("cursor"); return new Cursor(cursor.get("partition"), cursor.get("offset")); }) .collect(Collectors.toSet()); Assert.assertThat(offsets, Matchers.equalTo(Sets.newHashSet(initialCursors))); }
Example #14
Source File: VersionIT.java From docker-maven-plugin with Apache License 2.0 | 5 votes |
@Test public void testVersion() { String versionExpected = System.getProperty("jolokia.version"); String jolokiaUrl = System.getProperty("jolokia.url"); RestAssured.baseURI = jolokiaUrl; RestAssured.defaultParser = Parser.JSON; System.out.println("Checking URL: " + jolokiaUrl); // Need to do it that way since Jolokia doesnt return application/json as mimetype by default JsonPath json = with(get("/version").asString()); json.prettyPrint(); assertEquals(versionExpected, json.get("value.agent")); // Alternatively, set the mime type before, then Rest-assured's fluent API can be used given() .param("mimeType", "application/json") .get("/version") .then().assertThat() .header("content-type", containsString("application/json")) .body("value.agent", equalTo(versionExpected)) .body("timestamp", lessThanOrEqualTo((int) (System.currentTimeMillis() / 1000))) .body("status", equalTo(200)) .body("value.protocol", equalTo("7.1")) .body("value.config",notNullValue()); }
Example #15
Source File: VersionIT.java From vertx-stack with Apache License 2.0 | 5 votes |
@Test public void testVersionOfRegularExecContainer() { String containerUrl = System.getProperty("vertx-exec.url"); RestAssured.baseURI = containerUrl; RestAssured.defaultParser = Parser.JSON; System.out.println("Checking URL: " + containerUrl); String version = get("/version").asString(); System.out.println(version); assertEquals(versionExpected, version); }
Example #16
Source File: EventStreamReadingAT.java From nakadi with MIT License | 5 votes |
@Test(timeout = 5000) public void whenStreamLimitLowerThanBatchLimitThenUnprocessableEntity() { RestAssured.given() .param("batch_limit", "10") .param("stream_limit", "5") .when() .get(streamEndpoint) .then() .statusCode(HttpStatus.UNPROCESSABLE_ENTITY.value()) .and() .contentType(Matchers.equalTo("application/problem+json")) .and() .body("detail", Matchers.equalTo("stream_limit can't be lower than batch_limit")); }
Example #17
Source File: MessageWithoutContentTypeTest.java From joynr with Apache License 2.0 | 5 votes |
@Test public void testSendAndReceiveMessage() throws Exception { String channelId = "MessageWithoutContentTypeTest_" + createUuidString(); bpMock.createChannel(channelId); byte[] postPayload = ("payload-" + createUuidString()).getBytes(StandardCharsets.UTF_8); ImmutableMessage messageToSend = bpMock.createImmutableMessage(100000l, postPayload); given().contentType(ContentType.BINARY) .content(messageToSend.getSerializedMessage()) .log() .all() .expect() .response() .statusCode(201) .header("Location", RestAssured.baseURI + "messages/" + messageToSend.getId()) .header("msgId", messageToSend.getId()) .when() .post("/channels/" + channelId + "/messageWithoutContentType"); ScheduledFuture<Response> longPollConsumer = bpMock.longPollInOwnThread(channelId, 30000); Response responseLongPoll = longPollConsumer.get(); List<ImmutableMessage> messagesFromResponse = bpMock.getJoynrMessagesFromResponse(responseLongPoll); Assert.assertEquals(1, messagesFromResponse.size()); ImmutableMessage message = messagesFromResponse.get(0); Assert.assertEquals(postPayload, message.getUnencryptedBody()); }
Example #18
Source File: SingleBounceProxyHostPathTest.java From joynr with Apache License 2.0 | 5 votes |
@Before public void setUp() throws Exception { serverUrl = "http://my-public-internet-domain.com:8119"; System.setProperty(MessagingPropertyKeys.PROPERTY_SERVLET_HOST_PATH, serverUrl); server = ServersUtil.startBounceproxy(); String bounceproxyUrlString = System.getProperty(MessagingPropertyKeys.BOUNCE_PROXY_URL); RestAssured.baseURI = bounceproxyUrlString; }
Example #19
Source File: KeycloakServiceClientTest.java From che with Eclipse Public License 2.0 | 5 votes |
@BeforeMethod public void setUp() throws Exception { keycloakServiceClient = new KeycloakServiceClient(keycloakSettings, jwtParser); Map<String, String> conf = new HashMap<>(); conf.put( AUTH_SERVER_URL_SETTING, RestAssured.baseURI + ":" + RestAssured.port + RestAssured.basePath); conf.put(REALM_SETTING, "che"); when(keycloakSettings.get()).thenReturn(conf); }
Example #20
Source File: AsynchronousTransformerTest.java From p3-batchrefine with Apache License 2.0 | 5 votes |
private Response doRequest(String input, String transform, String format, MimeType contentType) throws Exception { String transformURI = fServers.transformURI(input + "-" + transform + ".json").toString(); Response response = RestAssured.given() .queryParam("refinejson", transformURI) .header("Accept", contentType.toString() + ";q=1.0") .contentType("text/csv") .content(contentsAsBytes("inputs", input, "csv")) .when().post(); Assert.assertEquals(HttpStatus.SC_ACCEPTED, response.getStatusCode()); String location = response.getHeader("location"); Assert.assertTrue(location != null); /* Polls until ready. */ long start = System.currentTimeMillis(); do { response = RestAssured.given() .header("Accept", "text/turtle") .header("Content-Type", "text/turtle") .when().get(location); if (System.currentTimeMillis() - start >= ASYNC_TIMEOUT) { Assert.fail("Asynchronous call timed out."); } Thread.sleep(100); } while (response.statusCode() == HttpStatus.SC_ACCEPTED); return response; }
Example #21
Source File: NakadiTestUtils.java From nakadi with MIT License | 5 votes |
public static void repartitionEventType(final EventType eventType, final int partitionsNumber) throws JsonProcessingException { final EventTypeStatistics defaultStatistic = eventType.getDefaultStatistic(); defaultStatistic.setReadParallelism(partitionsNumber); defaultStatistic.setWriteParallelism(partitionsNumber); eventType.setDefaultStatistic(defaultStatistic); final int statusCode = RestAssured.given() .body(MAPPER.writeValueAsString(eventType)) .contentType(ContentType.JSON) .put(format("/event-types/{0}", eventType.getName())) .getStatusCode(); if (statusCode != 200) { throw new RuntimeException("Failed to repartition event type"); } }
Example #22
Source File: SpringBootSimpleExampleApplicationTests.java From katharsis-framework with Apache License 2.0 | 5 votes |
@Test public void testUpdateTask_withDescriptionTooLong() { Map<String, Object> attributeMap = new ImmutableMap.Builder<String, Object>().put("description", "123456789012345678901") .build(); Map dataMap = ImmutableMap.of("data", ImmutableMap.of("type", "tasks", "id", 1, "attributes", attributeMap)); ValidatableResponse response = RestAssured.given().contentType("application/json").body(dataMap).when() .patch("/api/tasks/1").then().statusCode(HttpStatus.UNPROCESSABLE_ENTITY.value()); response.assertThat().body(matchesJsonSchema(jsonApiSchema)); }
Example #23
Source File: RestAssuredTest.java From raml-tester with Apache License 2.0 | 5 votes |
@Test public void testWithoutBaseUri() throws IOException { RestAssured.baseURI = baseUrlWithPort(); api = RamlLoaders.fromClasspath(RestAssuredTest.class).load("restAssuredWithoutBaseUri.raml"); restAssured = api.createRestAssured(); restAssured.given().get("/base/data").andReturn(); assertThat(restAssured.getLastReport(), checks()); }
Example #24
Source File: EventStreamReadingAT.java From nakadi with MIT License | 5 votes |
@Test(timeout = 5000) public void whenInvalidCursorsThenPreconditionFailed() { RestAssured.given() .header(new Header("X-nakadi-cursors", "[{\"partition\":\"very_wrong_partition\",\"offset\":\"3\"}]")) .when() .get(streamEndpoint) .then() .statusCode(HttpStatus.PRECONDITION_FAILED.value()) .and() .contentType(Matchers.equalTo("application/problem+json")) .and() .body("detail", Matchers.equalTo("non existing partition very_wrong_partition")); }
Example #25
Source File: ResponseFilterTest.java From everrest with Eclipse Public License 2.0 | 5 votes |
@Test public void shouldChangeMethodName() throws Exception { Book book = new Book(); book.setId("123-1235-555"); when(bookStorage.getBook(eq("123-1235-555"))).thenReturn(book); //unsecure call to rest service RestAssured.given(). pathParam("id", "123-1235-555"). when(). get("/books/{id}"). then().statusCode(200).contentType("text/plain").body(equalTo("to be or not to be")); verify(bookStorage).getBook(eq("123-1235-555")); }
Example #26
Source File: RestAssuredTest.java From raml-tester with Apache License 2.0 | 5 votes |
@Before public void before() { RestAssured.baseURI = baseUrlWithPort(); api = RamlLoaders.fromClasspath(RestAssuredTest.class).load("restAssured.raml") .assumingBaseUri("http://nidi.guru/raml/v1"); restAssured = api.createRestAssured(); }
Example #27
Source File: LDPConformanceITest.java From ldp4j with Apache License 2.0 | 5 votes |
@Test @OperateOnDeployment("default") public void testService(@ArquillianResource final URL contextURL) throws Exception { RestAssured. given(). header("Accept",TEXT_TURTLE). baseUri(contextURL.toString()). expect(). statusCode(OK). contentType(TEXT_TURTLE). when(). get(LDPConformanceITest.resolve(contextURL, "ldp4j/api/resource/")); }
Example #28
Source File: RequestMappingLiveTest.java From tutorials with MIT License | 5 votes |
@Test public void givenAcceptHeader_whenGetFoos_thenOk() { RestAssured.given() .accept("application/json") .get(BASE_URI + "foos") .then() .assertThat() .body(containsString("Get some Foos with Header New")); }
Example #29
Source File: NakadiTestUtils.java From nakadi with MIT License | 5 votes |
public static void switchTimelineDefaultStorage(final EventType eventType) { RestAssured.given() .contentType(ContentType.JSON) .body(new JSONObject().put("storage_id", "default")) .post("event-types/{et_name}/timelines", eventType.getName()) .then() .statusCode(HttpStatus.SC_CREATED); }
Example #30
Source File: AnnotatedWebFilterLoadingTest.java From joynr with Apache License 2.0 | 5 votes |
@Test public void testFilter() { RestAssured.given() .expect() .statusCode(200) .header("test-web-filter-header", CoreMatchers.is("was-called")) .get("channels"); }