Java Examples for com.squareup.okhttp.mockwebserver.MockResponse

The following java examples will help you to understand the usage of com.squareup.okhttp.mockwebserver.MockResponse. These source code samples are taken from different open source projects.

Example 1
Project: SeaCloudsPlatform-master  File: SeaCloudsMonitoringInitializationPolicyTest.java View source code
@Test(enabled = true)
public void testAttachMonitorPolicyToApplicationMock() {
    HttpUrl serverUrl = mockWebServer.url("/");
    mockWebServer.enqueue(new MockResponse().setHeader(HttpHeaders.ACCEPT, MediaType.JSON_UTF_8.toString()).setHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString()));
    mockWebServer.enqueue(new MockResponse().setHeader(HttpHeaders.ACCEPT, MediaType.JSON_UTF_8.toString()).setHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString()));
    final TestSoftwareWithSensors childX = app.createAndManageChild(EntitySpec.create(TestSoftwareWithSensors.class).configure(BrooklynCampConstants.PLAN_ID, "childX"));
    final TestSoftwareWithSensors childY = app.createAndManageChild(EntitySpec.create(TestSoftwareWithSensors.class).configure(BrooklynCampConstants.PLAN_ID, "childY"));
    app.createAndManageChild(EntitySpec.create(EmptySoftwareProcess.class).configure(BrooklynCampConstants.PLAN_ID, "childZ"));
    app.policies().add(PolicySpec.create(SeaCloudsMonitoringInitializationPolicies.class).configure(SeaCloudsMonitoringInitializationPolicies.TARGET_ENTITIES, ImmutableList.of("childX", "childY")).configure(SeaCloudsMonitoringInitializationPolicies.SEACLOUDS_DC_ENDPOINT, serverUrl.toString()));
    app.start(ImmutableList.of(loc));
    assertTrue(Iterables.getOnlyElement(app.policies()) instanceof SeaCloudsMonitoringInitializationPolicies);
    Asserts.succeedsEventually(new Runnable() {

        public void run() {
            assertNotNull(app.getAttribute(SeaCloudsMonitoringInitializationPolicies.MONITORING_CONFIGURED));
            assertTrue(app.getAttribute(SeaCloudsMonitoringInitializationPolicies.MONITORING_CONFIGURED));
            assertTrue(app.getAttribute(Startable.SERVICE_UP));
            assertTrue(childX.getAttribute(Startable.SERVICE_UP));
            assertTrue(childY.getAttribute(Startable.SERVICE_UP));
        }
    });
}
Example 2
Project: denominator-master  File: UltraDNSTest.java View source code
@Test
public void retryOnSystemError() throws Exception {
    server.enqueueError(SYSTEM_ERROR, "System Error");
    server.enqueue(new MockResponse().setBody(getNeustarNetworkStatusResponse));
    assertThat(mockApi().getNeustarNetworkStatus()).isEqualTo(NetworkStatus.GOOD);
    server.assertSoapBody(getNeustarNetworkStatus);
    server.assertSoapBody(getNeustarNetworkStatus);
}
Example 3
Project: The-missing-Android-Guideline-master  File: CheckTaskTest.java View source code
public void test() throws Exception {
    // Create a MockWebServer. These are lean enough that you can create a new
    // instance for every unit test.
    MockWebServer server = new MockWebServer();
    server.enqueue(new MockResponse().setBody("hello, world!"));
    server.start();
    Bus bus = Mockito.mock(Bus.class);
    new CheckTask(bus, "michaelgruczel", "The-missing-android-guideline", new OkHttpClient()).execute();
    wait(2000);
    Mockito.verify(bus, Mockito.times(1)).post(Matchers.eq(CheckEvent.class));
    server.shutdown();
}
Example 4
Project: api-java-client-master  File: CloudApiTest.java View source code
public void testCreateVirtualAppliance() throws Exception {
    MockResponse response = //
    new MockResponse().setHeader("Content-Type", //
    VirtualApplianceDto.SHORT_MEDIA_TYPE_JSON).setBody(payloadFromResource("vapp.json"));
    server.enqueue(response);
    server.start();
    VirtualDatacenterDto dto = new VirtualDatacenterDto();
    RESTLink link = new RESTLink("virtualappliances", "/cloud/virtualdatacenters/1/virtualappliances");
    link.setType(VirtualAppliancesDto.SHORT_MEDIA_TYPE_JSON);
    dto.addLink(link);
    newApiClient().getCloudApi().createVirtualAppliance(dto, "VAPP");
    RecordedRequest request = server.takeRequest();
    assertRequest(request, "POST", VIRTUALDATACENTERS_URL + "/1/virtualappliances");
    assertAccept(request, VirtualApplianceDto.SHORT_MEDIA_TYPE_JSON, SingleResourceTransportDto.API_VERSION);
    assertContentType(request, VirtualApplianceDto.SHORT_MEDIA_TYPE_JSON, SingleResourceTransportDto.API_VERSION);
    VirtualApplianceDto requestBody = readBody(request, VirtualApplianceDto.class);
    assertEquals(requestBody.getName(), "VAPP");
}
Example 5
Project: Dagger-2-Example-master  File: PokemonDetailsTest.java View source code
@Test
public void nameOk() throws Exception {
    PokemonTestApp.getMockWebServer().enqueue(new MockResponse().setResponseCode(200).setBody(ResourceUtils.readFromFile("charizard.json")));
    String resourceUri = "api/v1/pokemon/6/";
    Pokemon pokemon = new Pokemon();
    pokemon.setResourceUri(resourceUri);
    Activity activity = buildActivity(pokemon);
    RecordedRequest request = takeLastRequest();
    //Check that name in details is displayed properly.
    assertThat(activity.findViewById(R.id.name)).isVisible();
    assertThat((TextView) activity.findViewById(R.id.name)).hasText("Charizard");
}
Example 6
Project: DevConSummit-master  File: AuthTestCase.java View source code
public void testShouldReturnTokenFromResponseString() {
    final CountDownLatch signal = new CountDownLatch(1);
    mockWebServer.enqueue(new MockResponse().setBody("{status_code: 200, message: " + "\"Successfully authenticated\", authentication_token: \"" + Mocker.TOKEN + "\"}"));
    authService.authenticate(Mocker.USERNAME_VALID, Mocker.PASSWORD_VALID, new AuthService.AuthCallback() {

        @Override
        public void onAuthenticated(String token) {
            signal.countDown();
            assertEquals(Mocker.TOKEN, token);
        }

        @Override
        public void onAuthenticationFailed(Integer statusCode, String message) {
            signal.countDown();
            assertFalse();
        }
    });
    try {
        signal.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    try {
        RecordedRequest request1 = mockWebServer.takeRequest();
        assertEquals("/tokens", request1.getPath());
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
Example 7
Project: ecampus-client-android-master  File: BulletinServiceTest.java View source code
@Override
public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
    String p = request.getPath();
    MockResponse response = new MockResponse().setResponseCode(200);
    if (p.matches("/board/all.*") || p.matches("/board/moderator/all.*")) {
        return response.setBody(jsonReader.readString("json/bulletins.json"));
    } else if (p.equals("/board") || p.equals("/board/" + BULLETIN_ID)) {
        return response.setBody(jsonReader.readString("json/ok.json"));
    } else if (p.equals("/board/" + BULLETIN_ID + "/recipient")) {
        return response.setBody(jsonReader.readString("json/bull_recipients.json"));
    } else if (p.equals("/subdivision/" + SUBDIV_ID + "/children")) {
        return response.setBody(jsonReader.readString("json/desc_subdivision.json"));
    } else if (p.equals("/roles")) {
        return response.setBody(jsonReader.readString("json/roles" + ".json"));
    } else if (p.equals("/subdivision/" + SUBDIV_ID + "/group")) {
        return response.setBody(jsonReader.readString("json/groups.json"));
    }
    return new MockResponse().setResponseCode(404);
}
Example 8
Project: hystrix-monitor-master  File: HystrixMonitorTest.java View source code
@BeforeClass
public static void given_mock_web_server_is_started() throws IOException {
    mockWebServer = new MockWebServer();
    InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("hystrix_circuit_breaker_opened.txt");
    String hystrixEvent = new Scanner(resourceAsStream, UTF_8.name()).useDelimiter("\\A").next();
    mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody(hystrixEvent));
    mockWebServer.play(6543);
}
Example 9
Project: jclouds-master  File: AWSEC2ComputeServiceApiMockTest.java View source code
public void launchVPCSpotInstanceSubnetId() throws Exception {
    enqueueRegions(DEFAULT_REGION);
    enqueueXml(DEFAULT_REGION, "/availabilityZones.xml");
    enqueueXml(DEFAULT_REGION, "/describe_images.xml");
    enqueueXml(DEFAULT_REGION, "/describe_images_cc.xml");
    enqueueXml(DEFAULT_REGION, "/describe_subnets.xml");
    enqueueXml(DEFAULT_REGION, "/created_securitygroup.xml");
    enqueueXml(DEFAULT_REGION, "/new_securitygroup.xml");
    enqueueXml(DEFAULT_REGION, "/new_securitygroup.xml");
    enqueueXml(DEFAULT_REGION, "/authorize_securitygroup_ingress_response.xml");
    enqueueXml(DEFAULT_REGION, "/request_spot_instances-ebs.xml");
    enqueueXml(DEFAULT_REGION, "/request_spot_instances-ebs.xml");
    enqueueXml(DEFAULT_REGION, "/describe_images_ebs.xml");
    // create tags
    enqueue(DEFAULT_REGION, new MockResponse());
    ComputeService computeService = computeService();
    Template template = computeService.templateBuilder().locationId("us-east-1a").build();
    template.getOptions().as(AWSEC2TemplateOptions.class).spotPrice(1f).subnetId("subnet-9d4a7b6c").keyPair("Demo").blockUntilRunning(false);
    NodeMetadata node = Iterables.getOnlyElement(computeService.createNodesInGroup("test", 1, template));
    assertEquals(node.getId(), "us-east-1/sir-228e6406");
    assertPosted(DEFAULT_REGION, "Action=DescribeRegions");
    assertPosted(DEFAULT_REGION, "Action=DescribeAvailabilityZones");
    assertPosted(DEFAULT_REGION, "Action=DescribeImages&Filter.1.Name=owner-id&Filter.1.Value.1=137112412989&Filter.1.Value.2=801119661308&Filter.1.Value.3=063491364108&Filter.1.Value.4=099720109477&Filter.1.Value.5=411009282317&Filter.2.Name=state&Filter.2.Value.1=available&Filter.3.Name=image-type&Filter.3.Value.1=machine");
    assertPosted(DEFAULT_REGION, "Action=DescribeImages&Filter.1.Name=virtualization-type&Filter.1.Value.1=hvm&Filter.2.Name=architecture&Filter.2.Value.1=x86_64&Filter.3.Name=owner-id&Filter.3.Value.1=137112412989&Filter.3.Value.2=099720109477&Filter.4.Name=hypervisor&Filter.4.Value.1=xen&Filter.5.Name=state&Filter.5.Value.1=available&Filter.6.Name=image-type&Filter.6.Value.1=machine&Filter.7.Name=root-device-type&Filter.7.Value.1=ebs");
    assertPosted(DEFAULT_REGION, "Action=DescribeSubnets&SubnetId.1=subnet-9d4a7b6c");
    assertPosted(DEFAULT_REGION, "Action=CreateSecurityGroup&GroupName=jclouds%23test&GroupDescription=jclouds%23test&VpcId=vpc-1a2b3c4d");
    assertPosted(DEFAULT_REGION, "Action=DescribeSecurityGroups&Filter.1.Name=group-name&Filter.1.Value.1=jclouds%23test");
    assertPosted(DEFAULT_REGION, "Action=DescribeSecurityGroups&GroupId.1=sg-3c6ef654");
    assertPosted(DEFAULT_REGION, "Action=AuthorizeSecurityGroupIngress&GroupId=sg-3c6ef654&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=22&IpPermissions.0.ToPort=22&IpPermissions.0.IpRanges.0.CidrIp=0.0.0.0/0&IpPermissions.1.IpProtocol=tcp&IpPermissions.1.FromPort=0&IpPermissions.1.ToPort=65535&IpPermissions.1.Groups.0.UserId=993194456877&IpPermissions.1.Groups.0.GroupId=sg-3c6ef654&IpPermissions.2.IpProtocol=udp&IpPermissions.2.FromPort=0&IpPermissions.2.ToPort=65535&IpPermissions.2.Groups.0.UserId=993194456877&IpPermissions.2.Groups.0.GroupId=sg-3c6ef654");
    assertPosted(DEFAULT_REGION, "Action=RequestSpotInstances&SpotPrice=1.0&InstanceCount=1&LaunchSpecification.ImageId=ami-" + getDefaultImageId() + "&LaunchSpecification.Placement.AvailabilityZone=us-east-1a&LaunchSpecification.SecurityGroupId.1=sg-3c6ef654&LaunchSpecification.InstanceType=" + getDefaultSmallestInstanceType() + "&LaunchSpecification.SubnetId=subnet-9d4a7b6c&LaunchSpecification.KeyName=Demo&LaunchSpecification.UserData=I2Nsb3VkLWNvbmZpZwpyZXBvX3VwZ3JhZGU6IG5vbmUK");
    assertPosted(DEFAULT_REGION, "Action=DescribeSpotInstanceRequests&SpotInstanceRequestId.1=sir-228e6406");
    assertPosted(DEFAULT_REGION, "Action=DescribeImages&ImageId.1=ami-595a0a1c");
    assertPosted(DEFAULT_REGION, "Action=CreateTags&Tag.1.Key=Name&Tag.1.Value=test-228e6406&ResourceId.1=sir-228e6406");
}
Example 10
Project: jclouds-labs-openstack-master  File: LBaaSApiMockTest.java View source code
public void testWhenNamespaceInExtensionsLBaaSPresent() throws IOException {
    MockWebServer server = mockOpenStackServer();
    server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource("/access.json"))));
    server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource("/extension_list_with_lbaas_v1_response.json"))));
    try {
        NeutronApi neutronApi = api(server.getUrl("/").toString(), "openstack-neutron", overrides);
        Optional<LBaaSApi> lbaasApiExtension = neutronApi.getLBaaSApi("RegionOne");
        assertAuthentication(server);
        /*
          * Check response
          */
        assertNotNull(lbaasApiExtension);
        assertEquals(lbaasApiExtension.isPresent(), true, "LBaaS API Version 1 is expected to be available");
    } finally {
        server.shutdown();
    }
}
Example 11
Project: MVPAndroidBootstrap-master  File: ConnectivityAwereUrlClientTest.java View source code
@Test
public void test400Retry() throws Exception {
    assertThat(connectivityAwareUrlClient).isNotNull();
    mockWebServer.enqueue(new MockResponse().setResponseCode(400));
    mockWebServer.enqueue(new MockResponse().setResponseCode(400));
    mockWebServer.enqueue(new MockResponse().setResponseCode(400));
    boolean isThrown = false;
    try {
        sodaService.cola("pepsi");
        fail("shoud not reach this");
    } catch (RetrofitError error) {
        if (error.getCause() instanceof ConnectionError) {
            isThrown = true;
        } else {
            fail("shoud not reach this");
        }
    }
    assertThat(isThrown).isTrue();
}
Example 12
Project: open-data-service-master  File: HttpSenderTest.java View source code
@Test
public final void testSuccess() throws Throwable {
    MockWebServer server = new MockWebServer();
    server.enqueue(new MockResponse().setResponseCode(200));
    server.play();
    String path = "/foo/bar/data/";
    String callbackUrl = server.getUrl(path).toString();
    ObjectNode sentData = new ObjectNode(JsonNodeFactory.instance);
    sentData.put("sourceId", SOURCE_ID);
    ArrayNode data = sentData.putArray("data");
    data.addObject().put("hello", "world");
    data.addObject().put("and", "again");
    setupSender(new HttpClient(SOURCE_ID, callbackUrl, true));
    sender.onNewDataStart();
    for (JsonNode item : data) sender.onNewDataItem((ObjectNode) item);
    sender.onNewDataComplete();
    assertEquals(SenderResult.Status.SUCCESS, sender.getSenderResult().getStatus());
    RecordedRequest request = server.takeRequest();
    assertEquals(path, request.getPath());
    assertEquals(sentData.toString(), request.getUtf8Body());
    server.shutdown();
}
Example 13
Project: smartcache-master  File: CallbackTest.java View source code
@Test
public void dispatch_isGood() throws Exception {
    /* Set up the mock webserver */
    MockResponse resp = new MockResponse();
    resp.setBody("VERY_BASIC_BODY");
    server.enqueue(resp);
    server.enqueue(resp.clone());
    Retrofit r = new Retrofit.Builder().baseUrl(server.url("/")).addConverterFactory(new ToStringConverterFactory()).addCallAdapterFactory(buildSmartCacheFactory()).build();
    DemoService demoService = r.create(DemoService.class);
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Response<String>> responseRef = new AtomicReference<>();
    demoService.getHome().enqueue(new Callback<String>() {

        @Override
        public void onResponse(Response<String> response, Retrofit retrofit) {
            responseRef.set(response);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail("Failure executing the request.");
        }
    });
    assertTrue(latch.await(1, TimeUnit.SECONDS));
    assertEquals(responseRef.get().body(), "VERY_BASIC_BODY");
    final CountDownLatch latch2 = new CountDownLatch(2);
    final AtomicReference<Response<String>> response2Ref = new AtomicReference<>();
    demoService.getHome().enqueue(new Callback<String>() {

        @Override
        public void onResponse(Response<String> response, Retrofit retrofit) {
            latch2.countDown();
            if (latch2.getCount() == 1) {
                // the cache hit one.
                response2Ref.set(response);
            } else {
                // the network one.
                assertEquals(response.body(), response2Ref.get().body());
            }
        }

        @Override
        public void onFailure(Throwable t) {
            fail("Failure executing the request.");
        }
    });
    assertTrue(latch2.await(1, TimeUnit.SECONDS));
}
Example 14
Project: comsat-master  File: URLConnectionTest.java View source code
@Test
public void requestHeaders() throws IOException, InterruptedException {
    server.enqueue(new MockResponse());
    connection = client.open(server.getUrl("/"));
    connection.addRequestProperty("D", "e");
    connection.addRequestProperty("D", "f");
    assertEquals("f", connection.getRequestProperty("D"));
    assertEquals("f", connection.getRequestProperty("d"));
    Map<String, List<String>> requestHeaders = connection.getRequestProperties();
    assertEquals(newSet("e", "f"), new LinkedHashSet<>(requestHeaders.get("D")));
    assertEquals(newSet("e", "f"), new LinkedHashSet<>(requestHeaders.get("d")));
    try {
        requestHeaders.put("G", Arrays.asList("h"));
        fail("Modified an unmodifiable view.");
    } catch (UnsupportedOperationException expected) {
    }
    try {
        requestHeaders.get("D").add("i");
        fail("Modified an unmodifiable view.");
    } catch (UnsupportedOperationException expected) {
    }
    try {
        connection.setRequestProperty(null, "j");
        fail();
    } catch (NullPointerException expected) {
    }
    try {
        connection.addRequestProperty(null, "k");
        fail();
    } catch (NullPointerException expected) {
    }
    connection.setRequestProperty("NullValue", null);
    assertNull(connection.getRequestProperty("NullValue"));
    connection.addRequestProperty("AnotherNullValue", null);
    assertNull(connection.getRequestProperty("AnotherNullValue"));
    connection.getResponseCode();
    RecordedRequest request = server.takeRequest();
    assertEquals(Arrays.asList("e", "f"), request.getHeaders().values("D"));
    assertNull(request.getHeader("NullValue"));
    assertNull(request.getHeader("AnotherNullValue"));
    assertNull(request.getHeader("G"));
    assertNull(request.getHeader("null"));
    try {
        connection.addRequestProperty("N", "o");
        fail("Set header after connect");
    } catch (IllegalStateException expected) {
    }
    try {
        connection.setRequestProperty("P", "q");
        fail("Set header after connect");
    } catch (IllegalStateException expected) {
    }
    try {
        connection.getRequestProperties();
        fail();
    } catch (IllegalStateException expected) {
    }
}
Example 15
Project: fh-android-sdk-master  File: FHSDKTest.java View source code
public void actTest(boolean async) throws Exception {
    String cloudHost = FH.getCloudHost();
    System.out.println("cloud host is " + cloudHost);
    // the fhconfig.local.properties file exists, use the host value from that
    // file as the cloud host
    assertEquals("http://localhost:9000", cloudHost);
    // mock response for act call
    MockResponse actSuccessResponse = new MockResponse();
    actSuccessResponse.addHeader("Content-Type", "application/json");
    actSuccessResponse.setBody("{'status':'ok', 'type': 'act'}");
    mockWebServer.enqueue(actSuccessResponse);
    FHAct actCall = FH.buildActRequest("test", new JSONObject());
    FHActCallback callback = new FHActCallback() {

        @Override
        public void success(FHResponse pResponse) {
            resJson = pResponse.getJson();
        }

        @Override
        public void fail(FHResponse pResponse) {
            resJson = null;
        }
    };
    if (async) {
        runAsyncRequest(actCall, callback);
    } else {
        actCall.execute(callback);
    }
    assertEquals(resJson.getString("type"), "act");
    // verify request object
    RecordedRequest request = mockWebServer.takeRequest();
    assertEquals("POST", request.getMethod().toUpperCase());
    assertEquals("/cloud/test", request.getPath());
    String requestBody = new String(request.getBody().readUtf8());
    JSONObject requestJson = new JSONObject(requestBody);
    assertTrue(requestJson.has("__fh"));
    JSONObject fhParams = requestJson.getJSONObject("__fh");
    String deviceId = fhParams.optString("cuid", null);
    assertEquals(getDeviceId(), deviceId);
}
Example 16
Project: hadoop-release-2.6.0-master  File: TestConcurrentDataReadOperations.java View source code
@Override
public MockResponse dispatch(RecordedRequest recordedRequest) throws InterruptedException {
    CreateTestData currentRequest = null;
    for (CreateTestData local : testData) {
        if (recordedRequest.getPath().contains(local.path.toString())) {
            currentRequest = local;
            break;
        }
    }
    if (currentRequest == null) {
        new MockResponse().setBody("Request data not found").setResponseCode(501);
    }
    if (recordedRequest.getRequestLine().contains("op=GETFILESTATUS")) {
        return new MockResponse().setResponseCode(200).setBody(TestADLResponseData.getGetFileStatusJSONResponse(currentRequest.data.length));
    }
    if (recordedRequest.getRequestLine().contains("op=OPEN")) {
        String request = recordedRequest.getRequestLine();
        int offset = 0;
        int byteCount = 0;
        Pattern pattern = Pattern.compile("offset=([0-9]+)");
        Matcher matcher = pattern.matcher(request);
        if (matcher.find()) {
            LOG.debug(matcher.group(1));
            offset = Integer.parseInt(matcher.group(1));
        }
        pattern = Pattern.compile("length=([0-9]+)");
        matcher = pattern.matcher(request);
        if (matcher.find()) {
            LOG.debug(matcher.group(1));
            byteCount = Integer.parseInt(matcher.group(1));
        }
        Buffer buf = new Buffer();
        buf.write(currentRequest.data, offset, Math.min(currentRequest.data.length - offset, byteCount));
        return new MockResponse().setResponseCode(200).setChunkedBody(buf, 4 * 1024 * 1024);
    }
    return new MockResponse().setBody("NOT SUPPORTED").setResponseCode(501);
}
Example 17
Project: stratos-master  File: AWSEC2ComputeServiceApiMockTest.java View source code
public void launchVPCSpotInstanceSubnetId() throws Exception {
    enqueueRegions(DEFAULT_REGION);
    enqueueXml(DEFAULT_REGION, "/availabilityZones.xml");
    enqueueXml(DEFAULT_REGION, "/describe_images.xml");
    enqueueXml(DEFAULT_REGION, "/describe_images_cc.xml");
    enqueueXml(DEFAULT_REGION, "/request_spot_instances-ebs.xml");
    enqueueXml(DEFAULT_REGION, "/request_spot_instances-ebs.xml");
    enqueueXml(DEFAULT_REGION, "/describe_images_ebs.xml");
    // create tags
    enqueue(DEFAULT_REGION, new MockResponse());
    ComputeService computeService = computeService();
    Template template = computeService.templateBuilder().locationId("us-east-1a").build();
    template.getOptions().as(AWSEC2TemplateOptions.class).spotPrice(1f).subnetId("subnet-xyz").keyPair("Demo").blockUntilRunning(false);
    NodeMetadata node = Iterables.getOnlyElement(computeService.createNodesInGroup("test", 1, template));
    assertEquals(node.getId(), "us-east-1/sir-228e6406");
    assertPosted(DEFAULT_REGION, "Action=DescribeRegions");
    assertPosted(DEFAULT_REGION, "Action=DescribeAvailabilityZones");
    assertPosted(DEFAULT_REGION, "Action=DescribeImages&Filter.1.Name=owner-id&Filter.1.Value.1=137112412989&Filter.1.Value.2=801119661308&Filter.1.Value.3=063491364108&Filter.1.Value.4=099720109477&Filter.1.Value.5=411009282317&Filter.2.Name=state&Filter.2.Value.1=available&Filter.3.Name=image-type&Filter.3.Value.1=machine");
    assertPosted(DEFAULT_REGION, "Action=DescribeImages&Filter.1.Name=virtualization-type&Filter.1.Value.1=hvm&Filter.2.Name=architecture&Filter.2.Value.1=x86_64&Filter.3.Name=owner-id&Filter.3.Value.1=137112412989&Filter.3.Value.2=099720109477&Filter.4.Name=hypervisor&Filter.4.Value.1=xen&Filter.5.Name=state&Filter.5.Value.1=available&Filter.6.Name=image-type&Filter.6.Value.1=machine&Filter.7.Name=root-device-type&Filter.7.Value.1=ebs");
    assertPosted(DEFAULT_REGION, "Action=RequestSpotInstances&SpotPrice=1.0&InstanceCount=1&LaunchSpecification.ImageId=ami-" + getDefaultImageId() + "&LaunchSpecification.Placement.AvailabilityZone=us-east-1a&LaunchSpecification.InstanceType=" + getDefaultSmallestInstanceType() + "&LaunchSpecification.SubnetId=subnet-xyz&LaunchSpecification.KeyName=Demo&LaunchSpecification.UserData=I2Nsb3VkLWNvbmZpZwpyZXBvX3VwZ3JhZGU6IG5vbmUK");
    assertPosted(DEFAULT_REGION, "Action=DescribeSpotInstanceRequests&SpotInstanceRequestId.1=sir-228e6406");
    assertPosted(DEFAULT_REGION, "Action=DescribeImages&ImageId.1=ami-595a0a1c");
    assertPosted(DEFAULT_REGION, "Action=CreateTags&Tag.1.Key=Name&Tag.1.Value=test-228e6406&ResourceId.1=sir-228e6406");
}
Example 18
Project: vtm-master  File: OkHttpEngineTest.java View source code
@Before
public void setUp() throws Exception {
    mockResponse = new MockResponse();
    mockResponse.setBody("TEST RESPONSE".getBytes());
    server = new MockWebServer();
    server.enqueue(mockResponse);
    server.play();
    engine = (OkHttpEngine) new OkHttpEngine.OkHttpFactory().create(new OSciMap4TileSource(server.getUrl("/tiles/vtm").toString()));
}
Example 19
Project: cfg4j-master  File: SimpleConfigurationProviderIntegrationTest.java View source code
@Override
public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
    switch(request.getPath()) {
        case "/v1/agent/self":
            return new MockResponse().setResponseCode(200).setBody(PING_RESPONSE);
        case "/v1/kv/?recurse=true":
            return new MockResponse().setResponseCode(200).addHeader("Content-Type", "application/json; charset=utf-8").setBody("[{\"CreateIndex\":1,\"ModifyIndex\":1,\"LockIndex\":0,\"Key\":\"us-west-1/featureA.toggle\",\"Flags\":0,\"Value\":\"ZGlzYWJsZWQ=\"}]");
    }
    return new MockResponse().setResponseCode(404);
}
Example 20
Project: serenity-android-master  File: SimpleXmlRequestTest.java View source code
@Before
public void setUp() throws Exception {
    Robolectric.getFakeHttpLayer().interceptHttpRequests(false);
    Robolectric.getFakeHttpLayer().interceptResponseContent(false);
    webserver = new MockWebServer();
    MockResponse response = new MockResponse();
    InputStream xmlStream = this.getClass().getResourceAsStream("/resources/index.xml");
    response.setBody(xmlStream, 1198l);
    webserver.enqueue(response);
    webserver.play();
}
Example 21
Project: tinify-java-master  File: SourceTest.java View source code
@Test(expected = AccountException.class)
public void withInvalidApiKeyFromFileShouldThrowAccountException() throws Exception, IOException, URISyntaxException {
    Tinify.setKey("invalid");
    server.enqueue(new MockResponse().setResponseCode(401).setBody("{'error':'Unauthorized','message':'Credentials are invalid'}"));
    String filePath = Paths.get(getClass().getResource("/dummy.png").toURI()).toAbsolutePath().toString();
    Source.fromFile(filePath);
}
Example 22
Project: analytics-android-master  File: ClientTest.java View source code
@Test
public void upload() throws Exception {
    server.enqueue(new MockResponse());
    Client.Connection connection = client.upload();
    assertThat(connection.os).isNotNull();
    assertThat(connection.is).isNull();
    // consume the response.
    assertThat(connection.connection.getResponseCode()).isEqualTo(200);
    RecordedRequestAssert.assertThat(server.takeRequest()).hasRequestLine("POST /v1/import HTTP/1.1").containsHeader("Content-Type", "application/json").containsHeader("Content-Encoding", "gzip").containsHeader("Authorization", "Basic Zm9vOg==");
}
Example 23
Project: external-resources-master  File: DownloaderTest.java View source code
@Before
public void setUp() throws Exception {
    initMocks(this);
    setDefaultConfiguration();
    when(context.getApplicationContext()).thenReturn(RuntimeEnvironment.application);
    final String successJson = IOUtils.toString(getClass().getResourceAsStream("/test.json"), "UTF-8");
    server.setDispatcher(new Dispatcher() {

        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            if (request.getPath().startsWith("/success")) {
                return new MockResponse().setResponseCode(200).setBody(successJson);
            } else {
                return new MockResponse().setResponseCode(400);
            }
        }
    });
}
Example 24
Project: jclouds-labs-aws-master  File: GlacierClientMockTest.java View source code
@Test
public void testCreateVault() throws InterruptedException {
    MockResponse mr = buildBaseResponse(201);
    mr.addHeader(HttpHeaders.LOCATION, VAULT_LOCATION);
    server.enqueue(mr);
    assertThat(client.createVault(VAULT_NAME)).isEqualTo(URI.create(server.getUrl("/") + VAULT_LOCATION.substring(1)));
    assertEquals(server.takeRequest().getRequestLine(), "PUT /-/vaults/" + VAULT_NAME + " " + HTTP);
}
Example 25
Project: js-android-sdk-master  File: RepositoryRestApiTest.java View source code
@Test
public void requestForSearchShouldParseHeaderResultCount() throws Exception {
    MockResponse mockResponse = MockResponseFactory.create200().setBody(searchResponse.asString()).addHeader("Result-Count", "100");
    mWebMockRule.enqueue(mockResponse);
    ResourceSearchResult response = restApiUnderTest.searchResources(null);
    assertThat(response.getResultCount(), is(100));
}
Example 26
Project: marathon-maven-plugin-master  File: DeployMojoTest.java View source code
@Test
public void testSuccessfulDeployAppNotCreatedYet() throws Exception {
    server.enqueue(new MockResponse().setResponseCode(404));
    server.enqueue(new MockResponse().setResponseCode(200));
    final DeployMojo mojo = lookupDeployMojo();
    assertNotNull(mojo);
    mojo.execute();
    assertEquals(2, server.getRequestCount());
    RecordedRequest getAppRequest = server.takeRequest();
    assertEquals(MARATHON_PATH + APP_ID, getAppRequest.getPath());
    assertEquals("GET", getAppRequest.getMethod());
    RecordedRequest createAppRequest = server.takeRequest();
    assertEquals(MARATHON_PATH, createAppRequest.getPath());
    assertEquals("POST", createAppRequest.getMethod());
    App requestApp = ModelUtils.GSON.fromJson(createAppRequest.getBody().readUtf8(), App.class);
    assertNotNull(requestApp);
    assertEquals(APP_ID, requestApp.getId());
}
Example 27
Project: ncmb_android-master  File: NCMBDispatcher.java View source code
@Override
public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
    InputStream input = null;
    try {
        input = new FileInputStream(new File("src/test/assets/yaml/mbaas.yml"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    Yaml yaml = new Yaml();
    Map<String, Object> map = null;
    Map<String, Object> requestMap = null;
    Map<String, Object> responseMap = null;
    String requestBody = null;
    for (Object data : yaml.loadAll(input)) {
        map = (Map<String, Object>) data;
        requestMap = (Map) map.get("request");
        responseMap = (Map) map.get("response");
        String[] pathAndQuery = request.getPath().split("\\?", 0);
        String path = pathAndQuery[0];
        String query = null;
        if (pathAndQuery.length > 1) {
            query = pathAndQuery[1];
        }
        if (!requestMap.get("url").equals(path)) {
            continue;
        //return defaultErrorResponse();
        }
        if (requestMap.get("url").equals("/2013-09-01/classes/ResponseSignatureTest")) {
            return new MockResponse().setResponseCode((int) responseMap.get("status")).setHeader("Content-Type", "application/json").setHeader("X-NCMB-Response-Signature", "tLdHmmi7td5+YnjdPxhPYfjV6Lh8pZNBrd2kH7EejnU=").setBody(readJsonResponse(responseMap.get("file").toString()));
        }
        if (!requestMap.get("method").equals(request.getMethod())) {
            continue;
        //return defaultErrorResponse();
        }
        if (query != null) {
            if (requestMap.containsKey("query")) {
                Object mockQuery = requestMap.get("query");
                String mockQueryStr = new Gson().toJson(mockQuery);
                if (!checkRequestQuery(mockQueryStr, query)) {
                    continue;
                }
            } else {
                continue;
            }
        }
        if (requestMap.containsKey("body")) {
            try {
                if (requestBody == null) {
                    requestBody = request.getBody().readString(request.getBodySize(), Charset.forName("UTF-8"));
                }
                Object mockBody = requestMap.get("body");
                Gson gson = new GsonBuilder().serializeNulls().create();
                String mockBodyStr = gson.toJson(mockBody);
                System.out.println("mock:" + mockBodyStr);
                System.out.println("req:" + requestBody);
                if (checkRequestBody(mockBodyStr, requestBody)) {
                    //Responseã‚’return
                    return new MockResponse().setResponseCode((int) responseMap.get("status")).setHeader("Content-Type", "application/json").setBody(readJsonResponse(responseMap.get("file").toString()));
                } else {
                    continue;
                }
            } catch (IOException e) {
                return defaultErrorResponse();
            }
        }
        if (requestMap.containsKey("header")) {
            Headers requestHeaders = request.getHeaders();
            Gson gson = new GsonBuilder().serializeNulls().create();
            String mock = gson.toJson(requestMap.get("header"));
            try {
                JSONObject mockHeaders = new JSONObject(requestMap.get("header").toString());
                //System.out.println("mock:" + mockHeaders);
                //System.out.println("req:" + requestHeaders);
                Iterator keys = mockHeaders.keys();
                while (keys.hasNext()) {
                    String key = (String) keys.next();
                    if (requestHeaders.get(key) != null && requestHeaders.get(key).equals(mockHeaders.getString(key))) {
                        return new MockResponse().setResponseCode((int) responseMap.get("status")).setHeader("Content-Type", "application/json").setBody(readJsonResponse(responseMap.get("file").toString()));
                    }
                }
            } catch (JSONException e) {
                return defaultErrorResponse();
            }
            continue;
        }
        return new MockResponse().setResponseCode((int) responseMap.get("status")).setHeader("Content-Type", "application/json").setBody(readJsonResponse(responseMap.get("file").toString()));
    }
    return defaultErrorResponse();
}
Example 28
Project: pelias-android-sdk-master  File: PeliasTest.java View source code
@Test
public void setEndpoint_shouldChangeServiceEndpoint() throws Exception {
    final MockWebServer server = new MockWebServer();
    MockResponse response = new MockResponse();
    server.enqueue(response);
    server.play();
    Pelias pelias = new Pelias(server.getUrl("/").toString());
    pelias.setRequestHandler(new PeliasRequestHandler() {

        @Override
        public Map<String, String> headersForRequest() {
            HashMap<String, String> headers = new HashMap();
            headers.put("TEST_HEADER", "TEST_HEADER_VALUE");
            return headers;
        }

        @Override
        public Map<String, String> queryParamsForRequest() {
            HashMap<String, String> params = new HashMap();
            params.put("TEST_PARAM", "TEST_PARAM_VALUE");
            return params;
        }
    });
    pelias.suggest("test", 1.0, 2.0, callback);
    RecordedRequest request = server.takeRequest();
    assertThat(request.getPath()).contains("/autocomplete");
    assertThat(request.getHeader("TEST_HEADER")).isEqualTo("TEST_HEADER_VALUE");
    assertThat(request.getPath()).contains("TEST_PARAM");
    server.shutdown();
}
Example 29
Project: recommendations-master  File: PoisApiTest.java View source code
@Test
public void testSearchByCategory() throws Exception {
    Location location = new Location();
    location.setLatitude(19.053528);
    location.setLongitude(-98.283187);
    Category category = new Category();
    category.setName("Coffee Shop");
    category.setIconUrl("https://ss3.4sqi.net/img/categories_v2/food/default_88.png");
    category.setFoursquareId("4bf58dd8d48988d1e0931735");
    Poi poi1 = new Poi();
    poi1.setName("Starbucks");
    poi1.setLocation(new Location());
    poi1.getLocation().setLatitude(19.051916205742696);
    poi1.getLocation().setLongitude(-98.21938276290894);
    poi1.setFoursquareId("4c2ec541ac0ab713fa9b1b1e");
    poi1.setFoursquareRating(7.4);
    poi1.setCategories(new Category[] { category });
    Poi poi2 = new Poi();
    poi2.setName("Profética - Casa de la Lectura");
    poi2.setLocation(new Location());
    poi2.getLocation().setLatitude(19.04288527071933);
    poi2.getLocation().setLongitude(-98.20153534412384);
    poi2.setFoursquareId("4baace32f964a520a7873ae3");
    poi2.setFoursquareRating(8.9);
    poi2.setCategories(new Category[] { category });
    Poi[] expectedResponse = { poi1, poi2 };
    mockWebServer.enqueue(new MockResponse().setStatus("HTTP/1.1 500 Internal Server Error").setBody(getJsonFrom("responses/pois.json")));
    Poi[] actualResponse = poisApi.awaitSearchByCategory(location, 20_000, category.getFoursquareId());
    assertThat(actualResponse).isNotNull().isNotEmpty().hasSize(expectedResponse.length).isEqualTo(expectedResponse);
}
Example 30
Project: rox-android-master  File: PoisApiTest.java View source code
@Test
public void testSearchByCategory() throws Exception {
    Location location = new Location();
    location.setLatitude(19.053528);
    location.setLongitude(-98.283187);
    Category category = new Category();
    category.setName("Coffee Shop");
    category.setIconUrl("https://ss3.4sqi.net/img/categories_v2/food/default_88.png");
    category.setFoursquareId("4bf58dd8d48988d1e0931735");
    Poi poi1 = new Poi();
    poi1.setName("Starbucks");
    poi1.setLocation(new Location());
    poi1.getLocation().setLatitude(19.051916205742696);
    poi1.getLocation().setLongitude(-98.21938276290894);
    poi1.setFoursquareId("4c2ec541ac0ab713fa9b1b1e");
    poi1.setFoursquareRating(7.4);
    poi1.setCategories(new Category[] { category });
    Poi poi2 = new Poi();
    poi2.setName("Profética - Casa de la Lectura");
    poi2.setLocation(new Location());
    poi2.getLocation().setLatitude(19.04288527071933);
    poi2.getLocation().setLongitude(-98.20153534412384);
    poi2.setFoursquareId("4baace32f964a520a7873ae3");
    poi2.setFoursquareRating(8.9);
    poi2.setCategories(new Category[] { category });
    Poi[] expectedResponse = { poi1, poi2 };
    mockWebServer.enqueue(new MockResponse().setStatus("HTTP/1.1 500 Internal Server Error").setBody(getJsonFrom("responses/pois.json")));
    Poi[] actualResponse = poisApi.awaitSearchByCategory(location, 20_000, category.getFoursquareId());
    assertThat(actualResponse).isNotNull().isNotEmpty().hasSize(expectedResponse.length).isEqualTo(expectedResponse);
}
Example 31
Project: stetho-master  File: StethoInterceptorTest.java View source code
@Test
public void testWithRequestCompression() throws IOException {
    AtomicReference<NetworkEventReporter.InspectorRequest> capturedRequest = hookAlmostRealRequestWillBeSent(mMockEventReporter);
    MockWebServer server = new MockWebServer();
    server.start();
    server.enqueue(new MockResponse().setBody("Success!"));
    final byte[] decompressed = "Request text".getBytes();
    final byte[] compressed = compress(decompressed);
    assertNotEquals("Bogus test: decompressed and compressed lengths match", compressed.length, decompressed.length);
    RequestBody compressedBody = RequestBody.create(MediaType.parse("text/plain"), compress(decompressed));
    Request request = new Request.Builder().url(server.getUrl("/")).addHeader("Content-Encoding", "gzip").post(compressedBody).build();
    Response response = mClientWithInterceptor.newCall(request).execute();
    // Force a read to complete the flow.
    response.body().string();
    assertArrayEquals(decompressed, capturedRequest.get().body());
    Mockito.verify(mMockEventReporter).dataSent(anyString(), eq(decompressed.length), eq(compressed.length));
    server.shutdown();
}
Example 32
Project: WordPress-Android-master  File: HealthCheckTest.java View source code
@Override
public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
    for (Map.Entry<RecordedRequest, MockResponse> reqResp : mockRequestResponses.entrySet()) {
        final RecordedRequest mockRequest = reqResp.getKey();
        if (mockRequest.getRequestLine().equals(request.getRequestLine())) {
            return reqResp.getValue();
        }
    }
    return new MockResponse().setResponseCode(404).setBody("");
}
Example 33
Project: rest-assured-master  File: JsonSchemaValidationITest.java View source code
@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();
    }
}
Example 34
Project: tisana4j-master  File: MockedServerTest.java View source code
@Test
public void testGetData() throws Exception {
    String data = "ColumnA,ColumnB,ColumnC\r\nA,B,c\r\n,a,b,c\r\n";
    MockResponse response = new MockResponse();
    response.setResponseCode(200);
    response.addHeader("Content-Type", "text/csv");
    response.setBody(data);
    server.enqueue(response);
    server.start(9999);
    InputStream stream = client.getData(server.getUrl("/get/csv"), null);
    byte[] b = new byte[1024];
    int r = stream.read(b);
    assertTrue(r > 0);
    String out = new String(b);
    String[] lines = out.split("\r\n");
    assertEquals(4, lines.length);
}
Example 35
Project: wasp-master  File: WaspTest.java View source code
@Test
public void voidCallbackGetForSuccess() throws Exception {
    MockResponse response = new MockResponse().addHeader("Content-Type", "application/json; charset=utf-8").setBody("{\n" + "  \"no\": 123,\n" + "  \"name\": \"Hello\"\n" + "}");
    server.enqueue(response);
    MyApiVoid myApi = new Wasp.Builder(context).setEndpoint(server.url("/v1").toString()).setNetworkStack(VolleyNetworkStack.newInstance(requestQueue)).build().create(MyApiVoid.class);
    final CountDownLatch latch = new CountDownLatch(1);
    myApi.getUser(new Callback<User>() {

        @Override
        public void onSuccess(Response response, User user) {
            assertThat(response).isNotNull();
            assertThat(user).isNotNull();
            assertThat(user.name).isEqualTo("Hello");
            assertThat(user.no).isEqualTo(123);
            latch.countDown();
        }

        @Override
        public void onError(WaspError error) {
            fail(error.getErrorMessage());
        }
    });
    RecordedRequest request = server.takeRequest();
    assertThat(request.getPath()).isEqualTo("/v1/user");
    assertThat(request.getMethod()).isEqualTo("GET");
    assertTrue(latch.await(TIMEOUT, TimeUnit.SECONDS));
    verify(executor).execute(any(Runnable.class));
    verifyNoMoreInteractions(executor);
}
Example 36
Project: android-galaxyzoo-master  File: ZooniverseClientTest.java View source code
@Test
public void testMoreItems() throws IOException, InterruptedException, ZooniverseClient.RequestMoreItemsException {
    final MockWebServer server = new MockWebServer();
    final String strResponse = getStringFromStream(MoreItemsJsonParserTest.class.getClassLoader().getResourceAsStream("test_more_items_response.json"));
    assertNotNull(strResponse);
    server.enqueue(new MockResponse().setBody(strResponse));
    server.start();
    final ZooniverseClient client = createZooniverseClient(server);
    final int COUNT = 5;
    final List<ZooniverseClient.Subject> subjects = client.requestMoreItemsSync(COUNT);
    assertNotNull(subjects);
    assertTrue(subjects.size() == COUNT);
    final ZooniverseClient.Subject subject = subjects.get(0);
    assertNotNull(subject);
    assertNotNull(subject.getSubjectId());
    assertEquals(subject.getSubjectId(), "5500684569736d5964271400");
    assertNotNull(subject.getZooniverseId());
    assertEquals(subject.getZooniverseId(), "AGZ00081ls");
    assertNotNull(subject.getGroupId());
    assertEquals(subject.getGroupId(), TEST_GROUP_ID);
    assertNotNull(subject.getLocationStandard());
    assertEquals(subject.getLocationStandard(), "http://www.galaxyzoo.org.s3.amazonaws.com/subjects/standard/goods_full_n_27820_standard.jpg");
    assertNotNull(subject.getLocationThumbnail());
    assertEquals(subject.getLocationThumbnail(), "http://www.galaxyzoo.org.s3.amazonaws.com/subjects/thumbnail/goods_full_n_27820_thumbnail.jpg");
    assertNotNull(subject.getLocationInverted());
    assertEquals(subject.getLocationInverted(), "http://www.galaxyzoo.org.s3.amazonaws.com/subjects/inverted/goods_full_n_27820_inverted.jpg");
    //Test what the server received:
    assertEquals(1, server.getRequestCount());
    final RecordedRequest request = server.takeRequest();
    assertEquals("GET", request.getMethod());
    //ZooniverseClient uses one of several possible group IDs at random:
    //See com.murrayc.galaxyzoo.app.provider.Config
    final String possiblePath1 = "/groups/" + TEST_GROUP_ID + "/subjects?limit=5";
    final String possiblePath2 = "/groups/" + Config.SUBJECT_GROUP_ID_DECALS_DR2 + "/subjects?limit=5";
    final String possiblePath3 = "/groups/" + Config.SUBJECT_GROUP_ID_FERENGI2 + "/subjects?limit=5";
    final String possiblePath4 = "/groups/" + Config.SUBJECT_GROUP_ID_SDSS_LOST_SET + "/subjects?limit=5";
    //TODO: Can we use this?
    // assertThat(request.getPath(), anyOf(is(possiblePath1), is(possiblePath2)));
    final String path = request.getPath();
    assertTrue(path.equals(possiblePath1) || path.equals(possiblePath2) || path.equals(possiblePath3) || path.equals(possiblePath4));
    server.shutdown();
}
Example 37
Project: async-google-pubsub-client-master  File: PubsubTest.java View source code
@Test
public void testListTopics() throws Exception {
    final PubsubFuture<TopicList> future = pubsub.listTopics(PROJECT);
    final String expectedPath = BASE_PATH + "projects/" + PROJECT + "/topics";
    assertThat(future.operation(), is("list topics"));
    assertThat(future.method(), is("GET"));
    assertThat(future.uri(), is(server.getUrl(expectedPath).toString()));
    assertThat(future.payloadSize(), is(0L));
    final RecordedRequest request = server.takeRequest(10, SECONDS);
    assertThat(request.getMethod(), is("GET"));
    assertThat(request.getPath(), is(expectedPath));
    assertRequestHeaders(request);
    final TopicList response = TopicList.of(Topic.of(PROJECT, TOPIC_1), Topic.of(PROJECT, TOPIC_2));
    server.enqueue(new MockResponse().setBody(json(response)));
    final TopicList topicList = future.get(10, SECONDS);
    assertThat(topicList, is(response));
}
Example 38
Project: uberpay-wallet-master  File: ServerTest.java View source code
@Test
public void testGetCoins() throws ShapeShiftException, IOException, InterruptedException, JSONException {
    // Schedule some responses.
    server.enqueue(new MockResponse().setBody(GET_COINS_JSON));
    ShapeShiftCoins coinsReply = shapeShift.getCoins();
    assertFalse(coinsReply.isError);
    assertEquals(3, coinsReply.coins.size());
    assertEquals(1, coinsReply.availableCoinTypes.size());
    assertEquals(BTC, coinsReply.availableCoinTypes.get(0));
    JSONObject coinsJson = new JSONObject(GET_COINS_JSON);
    for (ShapeShiftCoin coin : coinsReply.coins) {
        JSONObject json = coinsJson.getJSONObject(coin.symbol);
        assertEquals(json.getString("name"), coin.name);
        assertEquals(json.getString("symbol"), coin.symbol);
        assertEquals(json.getString("image"), coin.image.toString());
        assertEquals(json.getString("status").equals("available"), coin.isAvailable);
    }
    // Optional: confirm that your app made the HTTP requests you were expecting.
    RecordedRequest request = server.takeRequest();
    assertEquals("/getcoins", request.getPath());
}
Example 39
Project: Avengers-master  File: CharacterListActivityInstrumentationTest.java View source code
@Test
public void showCharacters() {
    mMockWebServer.enqueue(new MockResponse().setBody(TestData.TWENTY_CHARACTERS_JSON));
    mCharacterListIntentRule.launchActivity(null);
    onView(withId(R.id.activity_avengers_recycler)).check(matches(isDisplayed()));
}
Example 40
Project: OkLog-master  File: LogDataInterceptorUnitTest.java View source code
@Override
protected void newCall(MockResponse mockResponse) throws IOException {
    newCall(request().build(), mockResponse);
}