okhttp3.mockwebserver.Dispatcher Java Examples

The following examples show how to use okhttp3.mockwebserver.Dispatcher. 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: Benchmark.java    From jus with Apache License 2.0 7 votes vote down vote up
private MockWebServer startServer(States.GenericState state) throws IOException {
  Logger.getLogger(MockWebServer.class.getName()).setLevel(Level.WARNING);
  MockWebServer server = new MockWebServer();

  if (state.tls) {
    SslClient sslClient = SslClient.localhost();
    server.useHttps(sslClient.socketFactory, false);
    server.setProtocols(state.protocols);
  }

  final MockResponse response = newResponse(state);
  server.setDispatcher(new Dispatcher() {
    @Override public MockResponse dispatch(RecordedRequest request) {
      return response;
    }
  });

  server.start();
  return server;
}
 
Example #2
Source File: RequestSamplingTest.java    From brave with Apache License 2.0 6 votes vote down vote up
@Before public void setup() {
  server.setDispatcher(new TracingDispatcher(httpTracing, new Dispatcher() {
    OkHttpClient tracedClient = client.newBuilder()
      .addNetworkInterceptor(new TracingInterceptor(httpTracing)).build();

    @Override public MockResponse dispatch(RecordedRequest request) {
      if (request.getPath().equals("/next")) return new MockResponse().setBody("next");
      Call next = tracedClient.newCall(new Request.Builder().url(server.url("/next")).build());
      try (ResponseBody responseBody = next.execute().body()) {
        return new MockResponse().setBody(responseBody.string());
      } catch (IOException e) {
        return new MockResponse().setBody(e.getMessage()).setResponseCode(500);
      }
    }
  }));
}
 
Example #3
Source File: ITSpringConfiguredReactorClient.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Test
public void cancelInFlight() throws Exception {
	BaseSubscriber<Integer> subscriber = new BaseSubscriber<Integer>() {
	};

	CountDownLatch latch = new CountDownLatch(1);

	server.setDispatcher(new Dispatcher() {
		@Override
		public MockResponse dispatch(RecordedRequest request) {
			subscriber.cancel();
			latch.countDown();
			return new MockResponse();
		}
	});

	getMono(client, "/foo").subscribe(subscriber);

	latch.await();

	assertThat(server.getRequestCount()).isOne();

	this.testSpanHandler.takeRemoteSpanWithErrorMessage(CLIENT, "CANCELLED");
}
 
Example #4
Source File: MapboxRouteTilesTest.java    From mapbox-java with MIT License 6 votes vote down vote up
@Before
public void setUp() throws IOException {
  server = new MockWebServer();

  server.setDispatcher(new Dispatcher() {
    @Override
    public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
      okio.Buffer buffer = new okio.Buffer();
      try {
        buffer.writeAll(Okio.source(new File("src/test/resources/2018-10-31T15_28_22.155Z.tar")));
      } catch (IOException ioException) {
        throw new RuntimeException(ioException);
      }
      return new MockResponse().setBody(buffer);
    }
  });

  server.start();
  mockUrl = server.url("");
}
 
Example #5
Source File: IsochroneTestUtils.java    From mapbox-java with MIT License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    server = new MockWebServer();
    server.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            try {
                String response = loadJsonFixture(ISOCHRONE_WITH_POLYGONS_VALID);
                if (request.getPath().contains("polygons=false")) {
                    response = loadJsonFixture(ISOCHRONE_NO_POLYGONS_VALID);
                }
                return new MockResponse().setBody(response);
            } catch (IOException ioException) {
                throw new RuntimeException(ioException);
            }
        }
    });
    server.start();
    mockUrl = server.url("");
}
 
Example #6
Source File: TilequeryTestUtils.java    From mapbox-java with MIT License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    server = new MockWebServer();
    server.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            try {
                String response = loadJsonFixture(TILEQUERY_VALID);
                if (request.getPath().contains("limit")) {
                    response = loadJsonFixture(TILEQUERY_ALL_PARAM_VALID);
                }
                return new MockResponse().setBody(response);
            } catch (IOException ioException) {
                throw new RuntimeException(ioException);
            }
        }
    });
    server.start();
    mockUrl = server.url("");
}
 
Example #7
Source File: MapboxSpeechTest.java    From mapbox-java with MIT License 6 votes vote down vote up
@Before
public void setUp() throws IOException {
  mockWebServer = new MockWebServer();

  mockWebServer.setDispatcher(new Dispatcher() {
    @Override
    public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
      okio.Buffer buffer = new okio.Buffer();
      try {
        buffer.writeAll(Okio.source(new File("src/test/resources/test_response.mp3")));
      } catch (IOException ioException) {
        throw new RuntimeException(ioException);
      }
      return new MockResponse().setBody(buffer);
    }
  });

  mockWebServer.start();
  mockUrl = mockWebServer.url("");

}
 
Example #8
Source File: OAuthApiConnectionTest.java    From Wikidata-Toolkit with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void init() throws IOException {
    Dispatcher dispatcher = new Dispatcher() {

        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            switch (request.getBody().readUtf8()) {
                case "languages=fr&assert=user&format=json&action=wbgetentities&ids=Q8&sitefilter=enwiki&props=info%7Cdatatype%7Clabels%7Caliases%7Cdescriptions%7Csitelinks":
                    return new MockResponse()
                            .addHeader("Content-Type", "application/json; charset=utf-8")
                            .setBody("{\"entities\":{\"Q8\":{\"pageid\":134,\"ns\":0,\"title\":\"Q8\",\"lastrevid\":1174289176,\"modified\":\"2020-05-05T12:39:07Z\",\"type\":\"item\",\"id\":\"Q8\",\"labels\":{\"fr\":{\"language\":\"fr\",\"value\":\"bonheur\"}},\"descriptions\":{\"fr\":{\"language\":\"fr\",\"value\":\"état émotionnel\"}},\"aliases\":{\"fr\":[{\"language\":\"fr\",\"value\":\":)\"},{\"language\":\"fr\",\"value\":\"\uD83D\uDE04\"},{\"language\":\"fr\",\"value\":\"\uD83D\uDE03\"}]},\"sitelinks\":{\"enwiki\":{\"site\":\"enwiki\",\"title\":\"Happiness\",\"badges\":[]}}}},\"success\":1}");
                case "meta=userinfo&assert=user&format=json&action=query":
                    return new MockResponse()
                            .addHeader("Content-Type", "application/json; charset=utf-8")
                            .setBody("{\"batchcomplete\":\"\",\"query\":{\"userinfo\":{\"id\":2333,\"name\":\"foo\"}}}");
                default:
                    return new MockResponse().setResponseCode(404);
            }
        }
    };

    server = new MockWebServer();
    server.setDispatcher(dispatcher);
    server.start();
}
 
Example #9
Source File: UsersClientTest.java    From blog-tutorials with MIT License 6 votes vote down vote up
@Test
public void testMultipleResponseCodes() {

  final Dispatcher dispatcher = new Dispatcher() {
    @Override
    public MockResponse dispatch(RecordedRequest request) {
      switch (request.getPath()) {
        case "/users/1":
          return new MockResponse().setResponseCode(200);
        case "/users/2":
          return new MockResponse().setResponseCode(500);
        case "/users/3":
          return new MockResponse().setResponseCode(200).setBody("{\"id\": 1, \"name\":\"duke\"}");
      }
      return new MockResponse().setResponseCode(404);
    }
  };

  mockWebServer.setDispatcher(dispatcher);

  assertThrows(WebClientResponseException.class, () -> usersClient.getUserById(2L));
  assertThrows(WebClientResponseException.class, () -> usersClient.getUserById(4L));
}
 
Example #10
Source File: ExternalRecommenderIntegrationTest.java    From inception with Apache License 2.0 6 votes vote down vote up
private Dispatcher buildDispatcher()
{
    return new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) {
            try {
                String body = request.getBody().readUtf8();
                requestBodies.add(body);

                if (request.getPath().equals("/train")) {
                    remoteRecommender.train(body);
                    return new MockResponse().setResponseCode(204);
                } else if (request.getPath().equals("/predict")) {
                    String response = remoteRecommender.predict(body);
                    return new MockResponse().setResponseCode(200).setBody(response);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            System.err.println("Unknown URL: " + request.getPath());
            return new MockResponse().setResponseCode(404);
        }
    };
}
 
Example #11
Source File: LappsRecommenderIntegrationTest.java    From inception with Apache License 2.0 6 votes vote down vote up
private Dispatcher buildDispatcher()
{
    return new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) {
            try {
                String url = request.getPath();
                String body = request.getBody().readUtf8();

                if (request.getPath().equals("/pos/predict")) {
                    String response = "";
                    return new MockResponse().setResponseCode(200).setBody(response);
                } else {
                    throw new RuntimeException("Invalid URL called: " + url);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    };
}
 
Example #12
Source File: LoggingTest.java    From java-cloudant with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setupMockWebServer() throws Exception {
    mockWebServer = mockWebServerExt.get();
    // Set a dispatcher that always returns 200 OK
    mockWebServer.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            return new MockResponse();
        }
    });
    client = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer)
            .build();
}
 
Example #13
Source File: MockWebServerDispatcherTest.java    From AndroidHttpMockingExamples with Apache License 2.0 5 votes vote down vote up
/**
 * Test okhttp mockwebserver Dispatcher
 */
@Test
public void testMockWebServerDispatcher() {
    activity = activityRule.getActivity();
    logger.debug("testMockWebServerDispatcher");

    //Use a dispatcher
    final Dispatcher dispatcher = new Dispatcher() {

        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            if (request.getPath().equals("/api/840dbdf2737a7ff9/conditions/q/CA/atlanta.json")) {
                String jsonBody = asset(activity, "atlanta-conditions.json");
                return new MockResponse().setResponseCode(200).setBody(jsonBody);
            }
            return new MockResponse().setResponseCode(404);
        }
    };
    mMockWebServer.setDispatcher(dispatcher);

    String okhttpMockWebServerUrl = mMockWebServer.url("/").toString();
    logger.debug("okhttp mockserver URL: " + okhttpMockWebServerUrl);
    activity.setWeatherServiceManager(new WeatherServiceManager(okhttpMockWebServerUrl));

    Spoon.screenshot(activity, "one");
    onView(ViewMatchers.withId(R.id.editText)).perform(replaceText("atlanta"));
    onView(withId(R.id.button)).perform(click());
    Spoon.screenshot(activity, "two");
    onView(withId(R.id.textView)).check(matches(withText(containsString("GA"))));
}
 
Example #14
Source File: MockWebServerPlusTest.java    From mockwebserverplus with Apache License 2.0 5 votes vote down vote up
@Test public void interceptDispatch() throws InterruptedException, IOException {
  Dispatcher dispatcher = spy(new QueueDispatcher());
  server.setDispatcher(dispatcher);
  server.enqueue(new MockResponse());

  execute();

  verify(dispatcher).dispatch(any(RecordedRequest.class));
}
 
Example #15
Source File: GoogleIdTokenAuthTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void testGCEMetadataToken() throws IOException, GeneralSecurityException, InterruptedException {
  metadataServer.setDispatcher(new Dispatcher() {
    @Override
    public MockResponse dispatch(RecordedRequest request) {
      final MockResponse response = new MockResponse()
          .setHeader("Metadata-Flavor", "Google");
      if (request.getPath().equals("/")) {
        return response;
      }
      if (!"Google".equals(request.getHeader("Metadata-Flavor"))) {
        return response.setResponseCode(404);
      }
      if (request.getPath().startsWith("/computeMetadata/v1/instance/service-accounts/default/identity?")) {
        return response
            .setBody(TEST_ID_TOKEN)
            .setHeader("Metadata-Flavor", "Google");
      }
      return response.setResponseCode(404);
    }
  });
  metadataServer.start();
  environmentVariables.set("GCE_METADATA_HOST", "127.0.0.1:" + metadataServer.getPort());
  final GoogleIdTokenAuth idTokenAuth = GoogleIdTokenAuth.of(ComputeEngineCredentials.create());
  final Optional<String> token = idTokenAuth.getToken("http://styx.foo.bar");
  assertThat(token, is(Optional.of(TEST_ID_TOKEN)));
  final RecordedRequest tokenRequest = metadataServer.takeRequest();
  assertThat(tokenRequest.getPath(), is("/computeMetadata/v1/instance/service-accounts/default/identity"
                                        + "?audience=http://styx.foo.bar&format=full"));
  assertThat(tokenRequest.getHeader("Metadata-Flavor"), is("Google"));
}
 
Example #16
Source File: DefaultMockServer.java    From mockwebserver with Apache License 2.0 5 votes vote down vote up
public DefaultMockServer(Context context, MockWebServer server, Map<ServerRequest, Queue<ServerResponse>> responses, Dispatcher dispatcher, boolean useHttps) {
  this.context = context;
  this.useHttps = useHttps;
  this.server = server;
  this.responses = responses;
  this.server.setDispatcher(dispatcher);
}
 
Example #17
Source File: GeocodingTestUtils.java    From mapbox-java with MIT License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  server = new MockWebServer();
  server.setDispatcher(new Dispatcher() {
    @Override
    public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
      try {
        String response;
        if (request.getPath().contains(GeocodingCriteria.MODE_PLACES_PERMANENT)) {
          response = loadJsonFixture(FORWARD_BATCH_GEOCODING);
        } else if (request.getPath().contains("1600") && !request.getPath().contains("nw")) {
          response = loadJsonFixture(FORWARD_VALID);
        } else if (request.getPath().contains("nw")) {
          response = loadJsonFixture(FORWARD_GEOCODING);
        } else if (request.getPath().contains("sandy")) {
          response = loadJsonFixture(FORWARD_INVALID);
        } else if (request.getPath().contains("%20and%20")) {
          response = loadJsonFixture(FORWARD_INTERSECTION);
        } else {
          response = loadJsonFixture(FORWARD_VALID_ZH);
        }
        return new MockResponse().setBody(response);
      } catch (IOException ioException) {
        throw new RuntimeException(ioException);
      }
    }
  });
  server.start();
  mockUrl = server.url("");
}
 
Example #18
Source File: MapboxMatrixTest.java    From mapbox-java with MIT License 5 votes vote down vote up
@Before
public void setUp() throws IOException {
  server = new MockWebServer();

  server.setDispatcher(new Dispatcher() {

    @Override
    public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
      try {
        String resource;
        if (request.getPath().contains("walking")) {
          resource = DIRECTIONS_MATRIX_WALKING_1X3_FIXTURE;

        } else if (request.getPath().contains("cycling")) {
          resource = DIRECTIONS_MATRIX_CYCLING_2X3_FIXTURE;

        } else { // driving
          resource = DIRECTIONS_MATRIX_DRIVING_3X3_FIXTURE;
        }
        String response = loadJsonFixture(resource);
        return new MockResponse().setBody(response);
      } catch (IOException ioException) {
        throw new RuntimeException(ioException);
      }
    }
  });
  server.start();
  mockUrl = server.url("");

  positions = new ArrayList<>();
  positions.add(Point.fromLngLat(-122.42, 37.78));
  positions.add(Point.fromLngLat(-122.45, 37.91));
  positions.add(Point.fromLngLat(-122.48, 37.73));
}
 
Example #19
Source File: ActivityWithMockingNetworkUITest.java    From adamant-android with GNU General Public License v3.0 5 votes vote down vote up
@Before
public void setup() throws IOException {
    super.setup();
    Dispatcher dispatcher = provideDispatcher(testNameRule.getMethodName());
    if (dispatcher != null) {
        mockWebServer.setDispatcher(dispatcher);
    }
    mockWebServer.start(8080);

    startActivity(testNameRule.getMethodName());

    Intents.init();
}
 
Example #20
Source File: OptimizationWaypointTest.java    From mapbox-java with MIT License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  final String json = loadJsonFixture(OPTIMIZATION_FIXTURE);
  object = new JsonParser().parse(json).getAsJsonObject();

  server = new MockWebServer();
  server.setDispatcher(new Dispatcher() {
    @Override
    public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
      return new MockResponse().setBody(json);
    }
  });
  server.start();
  mockUrl = server.url("");
}
 
Example #21
Source File: OptimizationResponseTest.java    From mapbox-java with MIT License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  final String json = loadJsonFixture(OPTIMIZATION_FIXTURE);
  object = new JsonParser().parse(json).getAsJsonObject();

  server = new MockWebServer();
  server.setDispatcher(new Dispatcher() {
    @Override
    public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
      return new MockResponse().setBody(json);
    }
  });
  server.start();
  mockUrl = server.url("");
}
 
Example #22
Source File: PincodeInAccessModeUINetworkTest.java    From adamant-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Dispatcher provideDispatcher(String testName) {
    switch (testName) {
        case "uiNetDropPinWithFailFCMPushUnsubscribe": {
            return new ServerDownOnSendMessageDispatcher(application);
        }
        case "uiNetSuccessAccessByPincode": {
            return new SuccessAuthorizationDispatcher(application);
        }
        default:
            return null;
    }
}
 
Example #23
Source File: EmbeddedApollo.java    From apollo with Apache License 2.0 5 votes vote down vote up
@Override
protected void before() throws Throwable {
  clear();
  server = new MockWebServer();
  final Dispatcher dispatcher = new Dispatcher() {
    @Override
    public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
      if (request.getPath().startsWith("/notifications/v2")) {
        String notifications = request.getRequestUrl().queryParameter("notifications");
        return new MockResponse().setResponseCode(200).setBody(mockLongPollBody(notifications));
      }
      if (request.getPath().startsWith("/configs")) {
        List<String> pathSegments = request.getRequestUrl().pathSegments();
        // appId and cluster might be used in the future
        String appId = pathSegments.get(1);
        String cluster = pathSegments.get(2);
        String namespace = pathSegments.get(3);
        return new MockResponse().setResponseCode(200).setBody(loadConfigFor(namespace));
      }
      return new MockResponse().setResponseCode(404);
    }
  };

  server.setDispatcher(dispatcher);
  server.start();

  mockConfigServiceUrl("http://localhost:" + server.getPort());

  super.before();
}
 
Example #24
Source File: ReverseProxyFunctionalTest.java    From xio with Apache License 2.0 5 votes vote down vote up
void setupBack(boolean h2, boolean isSecondServer) throws Exception {
  String back = h2 ? "h2" : "h1";

  TlsConfig tlsConfig =
      TlsConfig.builderFrom(config.getConfig("xio." + back + "BackendServer.settings.tls"))
          .build();
  List<Protocol> protocols;
  if (h2) {
    protocols = Arrays.asList(HTTP_2, HTTP_1_1);
  } else {
    protocols = Collections.singletonList(HTTP_1_1);
  }

  MockWebServer server =
      OkHttpUnsafe.getSslMockWebServer(
          getKeyManagers(tlsConfig.getPrivateKey(), tlsConfig.getCertificateAndChain()));
  server.setProtocols(protocols);
  server.setDispatcher(
      new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
          String index = Optional.ofNullable(request.getHeader("x_index")).orElse("unknown");
          return new MockResponse()
              .addHeader("x_index", index)
              .setBody("hello, world")
              .setSocketPolicy(SocketPolicy.KEEP_OPEN);
        }
      });
  if (isSecondServer) {
    this.backEnd2 = server;
    server.start(8442);
  } else {
    this.backEnd1 = server;
    server.start(8443);
  }
}
 
Example #25
Source File: LoginUINetworkTest.java    From adamant-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Dispatcher provideDispatcher(String testName) {
    switch (testName) {
        case "uiNetSuccessLogin": {
            return new SuccessAuthorizationDispatcher(InstrumentationRegistry.getInstrumentation().getTargetContext());
        }
    }

    return null;
}
 
Example #26
Source File: FederationV2CapacityGroupResourceTest.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private Dispatcher newDispatcher(ApplicationSLA capacityGroup) {
    return new Dispatcher() {

        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            if (request.getPath().equals(API_PATH + "?extended=false")) {
                return newMockGetResult(Collections.singletonList(capacityGroup));
            }
            if (request.getPath().equals(API_PATH + '/' + capacityGroup.getAppName() + "?extended=false")) {
                return newMockGetResult(capacityGroup);
            }
            return new MockResponse().setResponseCode(404);
        }
    };
}
 
Example #27
Source File: BasicApiConnectionTest.java    From Wikidata-Toolkit with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void init() throws Exception {
	Dispatcher dispatcher = new Dispatcher() {

		@Override
		public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
			if ("/w/api.php?languages=fr&format=json&action=wbgetentities&ids=Q8&sitefilter=enwiki&props=info".equals(request.getPath())) {
				return new MockResponse()
						.setHeader("Content-Type", "application/json; charset=utf-8")
						.setBody("{\"entities\":{\"Q8\":{\"pageid\":134,\"ns\":0,\"title\":\"Q8\",\"lastrevid\":1174289176,\"modified\":\"2020-05-05T12:39:07Z\",\"type\":\"item\",\"id\":\"Q8\"}},\"success\":1}\n");
			}
			try {
				switch (request.getBody().readUtf8()) {
					case "meta=tokens&format=json&action=query&type=login":
						return makeJsonResponseFrom("/query-login-token.json");
					case "lgtoken=b5780b6e2f27e20b450921d9461010b4&lgpassword=password&format=json&action=login&lgname=username":
						return makeJsonResponseFrom("/loginSuccess.json");
					case "lgtoken=b5780b6e2f27e20b450921d9461010b4&lgpassword=password1&format=json&action=login&lgname=username1":
						return makeJsonResponseFrom("/loginError.json");
					case "meta=tokens&assert=user&format=json&action=query&type=csrf":
						return makeJsonResponseFrom("/query-csrf-token-loggedin-response.json");
					case "assert=user&format=json&action=logout&token=42307b93c79b0cb558d2dfb4c3c92e0955e06041%2B%5C":
						return new MockResponse().setHeader("Content-Type", "application/json; charset=utf-8").setBody("{}");
					case "assert=user&format=json&action=query":
						return makeJsonResponseFrom("/assert-user-failed.json");
				}
			}catch (Exception e) {
				return new MockResponse().setResponseCode(404);
			}
			return new MockResponse().setResponseCode(404);
		}
	};

	server = new MockWebServer();
	server.setDispatcher(dispatcher);
	server.start();
}
 
Example #28
Source File: CloudantClientTests.java    From java-cloudant with Apache License 2.0 5 votes vote down vote up
@Test
public void gatewayStyleURL() throws Exception {

    final String gatewayPath = "/gateway";

    // Set a dispatcher that returns 200 if the requests have the correct path /gateway/_all_dbs
    // Otherwise return 400.
    server.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            if (request.getPath().equals(gatewayPath + "/_all_dbs")) {
                return new MockResponse();
            } else {
                return new MockResponse().setResponseCode(400);
            }
        }
    });

    // Build a client with a URL that includes a path
    CloudantClient c = ClientBuilder.url(new URL(server.url(gatewayPath).toString())).build();
    // If the request path is wrong this call will return 400 and throw an exception failing the
    // test.
    c.getAllDbs();

    // Build a client with a URL that includes a path with a trailing /
    c = ClientBuilder.url(new URL(server.url(gatewayPath + "/").toString())).build();
    // If the request path is wrong this call will return 400 and throw an exception failing the
    // test.
    c.getAllDbs();
}
 
Example #29
Source File: ChatListUINetworkTest.java    From adamant-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Dispatcher provideDispatcher(String testName) {
    switch (testName) {
        case "uiNetChatlistTimeoutRestoring" : {
            return new ChatListPeriodicTimeoutDispatcher(application);
        }
        case "uiNetContactlistTimeoutRestoring" : {
            return new ContactsListPeriodicTimeoutDispatcher(application);
        }
    }
    return null;
}
 
Example #30
Source File: ServerTest.java    From java-stellar-sdk with Apache License 2.0 4 votes vote down vote up
private Dispatcher buildTestCheckMemoRequiredMockDispatcher() {
    final String memoRequiredResponse = "{\n" +
            "    \"data\": {\n" +
            "        \"config.memo_required\": \"MQ==\"\n" +
            "    }\n" +
            "}";
    final String noMemoRequiredResponse = "{\n" +
            "    \"data\": {\n" +
            "    }\n" +
            "}";
    final String successTransactionResponse =
            "{\n" +
                    "  \"_links\": {\n" +
                    "    \"transaction\": {\n" +
                    "      \"href\": \"/transactions/2634d2cf5adcbd3487d1df042166eef53830115844fdde1588828667bf93ff42\"\n" +
                    "    }\n" +
                    "  },\n" +
                    "  \"hash\": \"2634d2cf5adcbd3487d1df042166eef53830115844fdde1588828667bf93ff42\",\n" +
                    "  \"ledger\": 826150,\n" +
                    "  \"envelope_xdr\": \"AAAAAKu3N77S+cHLEDfVD2eW/CqRiN9yvAKH+qkeLjHQs1u+AAAAZAAMkoMAAAADAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAbYQq8ek1GitmNBUloGnetfWxSpxlsgK48Xi66dIL3MoAAAAAC+vCAAAAAAAAAAAB0LNbvgAAAEDadQ25SNHWTg0L+2wr/KNWd8/EwSNFkX/ncGmBGA3zkNGx7lAow78q8SQmnn2IsdkD9MwICirhsOYDNbaqShwO\",\n" +
                    "  \"result_xdr\": \"AAAAAAAAAGQAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAA=\",\n" +
                    "  \"result_meta_xdr\": \"AAAAAAAAAAEAAAACAAAAAAAMmyYAAAAAAAAAAG2EKvHpNRorZjQVJaBp3rX1sUqcZbICuPF4uunSC9zKAAAAAAvrwgAADJsmAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAQAMmyYAAAAAAAAAAKu3N77S+cHLEDfVD2eW/CqRiN9yvAKH+qkeLjHQs1u+AAAAFzCfYtQADJKDAAAAAwAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAA\"\n" +
                    "}";
    final String rootResponse = "{\n" +
            "  \"_links\": {\n" +
            "    \"account\": {\n" +
            "      \"href\": \"https://horizon.stellar.org/accounts/{account_id}\",\n" +
            "      \"templated\": true\n" +
            "    },\n" +
            "    \"account_transactions\": {\n" +
            "      \"href\": \"https://horizon.stellar.org/accounts/{account_id}/transactions{?cursor,limit,order}\",\n" +
            "      \"templated\": true\n" +
            "    },\n" +
            "    \"assets\": {\n" +
            "      \"href\": \"https://horizon.stellar.org/assets{?asset_code,asset_issuer,cursor,limit,order}\",\n" +
            "      \"templated\": true\n" +
            "    },\n" +
            "    \"metrics\": {\n" +
            "      \"href\": \"https://horizon.stellar.org/metrics\"\n" +
            "    },\n" +
            "    \"order_book\": {\n" +
            "      \"href\": \"https://horizon.stellar.org/order_book{?selling_asset_type,selling_asset_code,selling_asset_issuer,buying_asset_type,buying_asset_code,buying_asset_issuer,limit}\",\n" +
            "      \"templated\": true\n" +
            "    },\n" +
            "    \"self\": {\n" +
            "      \"href\": \"https://horizon.stellar.org/\"\n" +
            "    },\n" +
            "    \"transaction\": {\n" +
            "      \"href\": \"https://horizon.stellar.org/transactions/{hash}\",\n" +
            "      \"templated\": true\n" +
            "    },\n" +
            "    \"transactions\": {\n" +
            "      \"href\": \"https://horizon.stellar.org/transactions{?cursor,limit,order}\",\n" +
            "      \"templated\": true\n" +
            "    }\n" +
            "  },\n" +
            "  \"horizon_version\": \"0.18.0-92259749c681df66a8347f846e94681a24f2a920\",\n" +
            "  \"core_version\": \"stellar-core 11.1.0 (324c1bd61b0e9bada63e0d696d799421b00a7950)\",\n" +
            "  \"history_latest_ledger\": 24345129,\n" +
            "  \"history_elder_ledger\": 1,\n" +
            "  \"core_latest_ledger\": 24345130,\n" +
            "  \"network_passphrase\": \"Public Global Stellar Network ; September 2015\",\n" +
            "  \"current_protocol_version\": 11,\n" +
            "  \"core_supported_protocol_version\": 11\n" +
            "}";

    Dispatcher dispatcher = new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) {
            String path = request.getPath();
            if ("/".equals(path)) {
                return new MockResponse().setResponseCode(200).setBody(rootResponse);
            }
            if (String.format("/accounts/%s", DESTINATION_ACCOUNT_MEMO_REQUIRED_A).equals(path) ||
                    String.format("/accounts/%s", DESTINATION_ACCOUNT_MEMO_REQUIRED_B).equals(path) ||
                    String.format("/accounts/%s", DESTINATION_ACCOUNT_MEMO_REQUIRED_C).equals(path) ||
                    String.format("/accounts/%s", DESTINATION_ACCOUNT_MEMO_REQUIRED_D).equals(path)) {
                return new MockResponse().setResponseCode(200).setBody(memoRequiredResponse);
            } else if (String.format("/accounts/%s", DESTINATION_ACCOUNT_NO_MEMO_REQUIRED).equals(path)) {
                return new MockResponse().setResponseCode(200).setBody(noMemoRequiredResponse);
            } else if (String.format("/accounts/%s", DESTINATION_ACCOUNT_NO_FOUND).equals(path)) {
                return new MockResponse().setResponseCode(404);
            } else if (String.format("/accounts/%s", DESTINATION_ACCOUNT_FETCH_ERROR).equals(path)) {
                return new MockResponse().setResponseCode(400);
            } else if ("/transactions".equals(path)) {
                return new MockResponse().setResponseCode(200).setBody(successTransactionResponse);
            } else {
                return new MockResponse().setResponseCode(404);
            }
        }
    };
    return dispatcher;
}