Search in sources :

Example 31 with MockResponse

use of com.squareup.okhttp.mockwebserver.MockResponse in project data-transfer-project by google.

the class MicrosoftCalendarImportTest method testImport.

@Test
@SuppressWarnings("unchecked")
public void testImport() throws Exception {
    server.enqueue(new MockResponse().setBody(BATCH_CALENDAR_RESPONSE));
    server.enqueue(new MockResponse().setResponseCode(201).setBody(BATCH_EVENT_RESPONSE));
    server.start();
    HttpUrl baseUrl = server.url("");
    MicrosoftCalendarImporter importer = new MicrosoftCalendarImporter(baseUrl.toString(), client, mapper, transformerService, jobStore);
    CalendarModel calendarModel = new CalendarModel("OldId1", "name", "name");
    CalendarAttendeeModel attendeeModel = new CalendarAttendeeModel("Test Attendee", "test@test.com", false);
    CalendarEventModel.CalendarEventTime start = new CalendarEventModel.CalendarEventTime(ZonedDateTime.now(ZoneId.of("GMT")).toOffsetDateTime(), false);
    CalendarEventModel.CalendarEventTime end = new CalendarEventModel.CalendarEventTime(ZonedDateTime.now(ZoneId.of("GMT")).toOffsetDateTime(), false);
    CalendarEventModel eventModel = new CalendarEventModel("OldId1", "Event1", "Test Notes", singletonList(attendeeModel), "Location1", start, end);
    CalendarContainerResource resource = new CalendarContainerResource(singleton(calendarModel), singleton(eventModel));
    ImportResult result = importer.importItem(JOB_ID, token, resource);
    Assert.assertEquals(ImportResult.ResultType.OK, result.getType());
    // verify the batch calendar request
    RecordedRequest calendarBatch = server.takeRequest();
    Map<String, Object> calendarBody = (Map<String, Object>) mapper.readValue(calendarBatch.getBody().readUtf8(), Map.class);
    List<Map<String, Object>> calendarRequests = (List<Map<String, Object>>) calendarBody.get("requests");
    Assert.assertNotNull(calendarRequests);
    Assert.assertEquals(1, calendarRequests.size());
    Map<String, Object> calendarRequest = calendarRequests.get(0);
    Assert.assertNotNull(calendarRequest.get("headers"));
    Assert.assertEquals("POST", calendarRequest.get("method"));
    Assert.assertEquals("/v1.0/me/calendars", calendarRequest.get("url"));
    Map<String, Object> calendarRequestBody = (Map<String, Object>) calendarRequest.get("body");
    Assert.assertNotNull(calendarRequestBody);
    Assert.assertEquals("name", calendarRequestBody.get("name"));
    // verify the calendar id mapping from old id to new id was saved
    Assert.assertEquals("NewId1", jobStore.findData(TempCalendarData.class, JOB_ID).getImportedId("OldId1"));
    // verify the batch event request
    RecordedRequest eventBatch = server.takeRequest();
    Map<String, Object> eventRequests = (Map<String, Object>) mapper.readValue(eventBatch.getBody().readUtf8(), Map.class);
    Map<String, Object> eventRequest = (Map<String, Object>) ((List<Map<String, Object>>) eventRequests.get("requests")).get(0);
    Assert.assertNotNull(eventRequest.get("headers"));
    Assert.assertEquals("POST", eventRequest.get("method"));
    Assert.assertEquals("/v1.0/me/calendars/NewId1/events", // verify the URL is contructed correctly with NewId
    eventRequest.get("url"));
    Map<String, Object> eventRequestBody = (Map<String, Object>) eventRequest.get("body");
    Assert.assertNotNull(eventRequestBody);
    Assert.assertEquals("Event1", eventRequestBody.get("subject"));
    Map<String, Object> location = (Map<String, Object>) eventRequestBody.get("location");
    Assert.assertEquals("Location1", location.get("displayName"));
    Assert.assertEquals("Default", location.get("locationType"));
    Map<String, Object> body = (Map<String, Object>) eventRequestBody.get("body");
    Assert.assertEquals("Test Notes", body.get("content"));
    Assert.assertEquals("HTML", body.get("contentType"));
    List<Map<String, Object>> attendees = (List<Map<String, Object>>) eventRequestBody.get("attendees");
    Assert.assertEquals(1, attendees.size());
    Map<String, Object> attendee = (Map<String, Object>) attendees.get(0);
    Assert.assertEquals("required", attendee.get("type"));
    Map<String, Object> emailAddress = (Map<String, Object>) attendee.get("emailAddress");
    Assert.assertEquals("test@test.com", emailAddress.get("address"));
    Assert.assertEquals("Test Attendee", emailAddress.get("name"));
    // verify dates
    Map<String, Object> startDate = (Map<String, Object>) eventRequestBody.get("start");
    Assert.assertNotNull(startDate.get("dateTime"));
    Assert.assertEquals("UTC", startDate.get("timeZone"));
    Map<String, Object> endDate = (Map<String, Object>) eventRequestBody.get("end");
    Assert.assertNotNull(endDate.get("dateTime"));
    Assert.assertEquals("UTC", endDate.get("timeZone"));
}
Also used : RecordedRequest(com.squareup.okhttp.mockwebserver.RecordedRequest) MockResponse(com.squareup.okhttp.mockwebserver.MockResponse) MicrosoftCalendarImporter(org.dataportabilityproject.transfer.microsoft.calendar.MicrosoftCalendarImporter) ImportResult(org.dataportabilityproject.spi.transfer.provider.ImportResult) CalendarModel(org.dataportabilityproject.types.transfer.models.calendar.CalendarModel) CalendarEventModel(org.dataportabilityproject.types.transfer.models.calendar.CalendarEventModel) CalendarContainerResource(org.dataportabilityproject.types.transfer.models.calendar.CalendarContainerResource) HttpUrl(com.squareup.okhttp.HttpUrl) CalendarAttendeeModel(org.dataportabilityproject.types.transfer.models.calendar.CalendarAttendeeModel) Collections.singletonList(java.util.Collections.singletonList) List(java.util.List) Map(java.util.Map) Test(org.junit.Test)

Example 32 with MockResponse

use of com.squareup.okhttp.mockwebserver.MockResponse in project rest-assured by rest-assured.

the class JsonSchemaValidationITest method json_schema_validator_supports_matching_uri_json_schema_as_json_node.

@Test
public void json_schema_validator_supports_matching_uri_json_schema_as_json_node() throws Exception {
    // Given
    String schema = IOUtils.toString(Thread.currentThread().getContextClassLoader().getResourceAsStream("products-schema.json"));
    MockWebServer server = new MockWebServer();
    server.enqueue(new MockResponse().setResponseCode(200).setBody(schema));
    server.play();
    try {
        get("/products").then().assertThat().body(JsonSchemaValidator.matchesJsonSchema(new URI("http://localhost:" + server.getPort())).using(settings().parseUriAndUrlsAsJsonNode(true)));
    } finally {
        server.shutdown();
    }
}
Also used : MockResponse(com.squareup.okhttp.mockwebserver.MockResponse) MockWebServer(com.squareup.okhttp.mockwebserver.MockWebServer) URI(java.net.URI) Test(org.junit.Test)

Example 33 with MockResponse

use of com.squareup.okhttp.mockwebserver.MockResponse in project enroscar by stanfy.

the class BaseFileCacheTest method testCache.

@Test
public void testCache() throws IOException {
    final String text = "ABC";
    getWebServer().enqueue(new MockResponse().setBody(text));
    final URL url = getWebServer().getUrl("/");
    final URLConnection connection = url.openConnection();
    // real request has been successfully performed
    assertResponse(connection, text, false);
    // cache entry has been written
    assertThat(cache.getWriteSuccessCount()).isEqualTo(1);
    assertThat(cache.getHitCount()).isZero();
    final URLConnection secondConnection = url.openConnection();
    // real request has not been performed
    assertResponse(secondConnection, text, true);
    // nothing has been written
    assertThat(cache.getWriteSuccessCount()).isEqualTo(1);
    assertThat(cache.getHitCount()).isEqualTo(1);
    // check disk content
    final DiskLruCache diskCache = cache.getDiskCache();
    assertThat(diskCache.size()).isGreaterThan((long) text.length());
    // 3 filed should be here: journal, body, metadata
    assertThat(diskCache.getDirectory().list().length).isEqualTo(3);
}
Also used : MockResponse(com.squareup.okhttp.mockwebserver.MockResponse) DiskLruCache(com.jakewharton.disklrucache.DiskLruCache) URL(java.net.URL) URLConnection(java.net.URLConnection) Test(org.junit.Test)

Example 34 with MockResponse

use of com.squareup.okhttp.mockwebserver.MockResponse in project enroscar by stanfy.

the class LoaderSetTest method shouldWaitFor3Requests.

@Ignore
@Test
public void shouldWaitFor3Requests() throws Throwable {
    // enqueue
    getWebServer().enqueue(new MockResponse().setBody("R1"));
    getWebServer().enqueue(new MockResponse().setBody("R2"));
    getWebServer().enqueue(new MockResponse().setBody("R3"));
    final URL url = getWebServer().getUrl("/");
    final Fragment fragment = createFragment();
    final LoaderManager loaderManager = fragment.getLoaderManager();
    assertThat(loaderManager).isNotNull();
    final CountDownLatch waiter = new CountDownLatch(1);
    // describe loader
    final LoaderSet set = LoaderSet.build(getApplication()).withManager(loaderManager).withCallbacks(new LoaderSet.SetCallbacksAdapter<ResponseData<String>>() {

        @Override
        public Loader<ResponseData<String>> onCreateLoader(final int id, final Bundle args) {
            return new MyRequestBuilder<String>(getApplication()) {
            }.setUrl(url.toString()).setFormat("string").getLoader();
        }
    }, 1).withCallbacks(new LoaderSet.SetCallbacksAdapter<ResponseData<String>>() {

        @Override
        public Loader<ResponseData<String>> onCreateLoader(final int id, final Bundle args) {
            return new MyRequestBuilder<String>(getApplication()) {
            }.setUrl(url.toString()).setFormat("string").getLoader();
        }
    }, 2, 3).create();
    final LoaderSet.LoaderSetCallback callbacks = new LoaderSet.LoaderSetCallback() {

        @Override
        public void onLoadFinished(final Object[] data) {
            Log.i("ChainTest", Arrays.toString(data));
            waiter.countDown();
        }
    };
    set.init(null, callbacks);
    // TODO finish it
    waitAndAssert(new Waiter<Object[]>() {

        @Override
        public Object[] waitForData() {
            try {
                waiter.await(2, TimeUnit.SECONDS);
                return LoaderSetAccess.getResults(set);
            } catch (final InterruptedException e) {
                return null;
            }
        }
    }, new Asserter<Object[]>() {

        @SuppressWarnings("unchecked")
        @Override
        public void makeAssertions(final Object[] data) throws Exception {
            assertThat(data.length).isEqualTo(3);
            assertThat(((ResponseData<String>) data[0]).getModel()).isEqualTo("R1");
            assertThat(((ResponseData<String>) data[1]).getModel()).isEqualTo("R2");
            assertThat(((ResponseData<String>) data[2]).getModel()).isEqualTo("R3");
        }
    });
}
Also used : Loader(android.support.v4.content.Loader) Fragment(android.support.v4.app.Fragment) URL(java.net.URL) MockResponse(com.squareup.okhttp.mockwebserver.MockResponse) Bundle(android.os.Bundle) ResponseData(com.stanfy.enroscar.content.loader.ResponseData) CountDownLatch(java.util.concurrent.CountDownLatch) LoaderManager(android.support.v4.app.LoaderManager) LoaderSet(com.stanfy.enroscar.content.loader.LoaderSet) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 35 with MockResponse

use of com.squareup.okhttp.mockwebserver.MockResponse in project enroscar by stanfy.

the class ContentHandlerTest method scheduleBadMethodResponse.

private String scheduleBadMethodResponse() {
    final String text = "Bad request";
    getWebServer().enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_BAD_METHOD).setBody(text));
    return text;
}
Also used : MockResponse(com.squareup.okhttp.mockwebserver.MockResponse)

Aggregations

MockResponse (com.squareup.okhttp.mockwebserver.MockResponse)39 Test (org.junit.Test)34 Path (org.apache.hadoop.fs.Path)18 MockWebServer (com.squareup.okhttp.mockwebserver.MockWebServer)10 FileStatus (org.apache.hadoop.fs.FileStatus)6 AclEntry (org.apache.hadoop.fs.permission.AclEntry)5 RecordedRequest (com.squareup.okhttp.mockwebserver.RecordedRequest)4 AbstractMockServerTest (com.stanfy.enroscar.net.test.AbstractMockServerTest)4 ArrayList (java.util.ArrayList)4 Buffer (okio.Buffer)4 HttpUrl (com.squareup.okhttp.HttpUrl)3 URL (java.net.URL)3 URLConnection (java.net.URLConnection)3 Request (com.squareup.okhttp.Request)2 Response (com.squareup.okhttp.Response)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 HttpURLConnection (java.net.HttpURLConnection)2 URI (java.net.URI)2