@Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { String rawPath = url; Map<String, String> params = new HashMap<>(); int pathEndPos = url.indexOf('?'); if (pathEndPos != -1) { rawPath = url.substring(0, pathEndPos); RestUtils.decodeQueryString(url, pathEndPos + 1, params); } Handler handler = handlers.retrieve(method + " " + rawPath, params); if (handler != null) { return handler.execute(rawPath, params, this); } return newMockError(RestStatus.INTERNAL_SERVER_ERROR, "Unable to handle request [method=" + method + ", url=" + url + "]"); } }; }
protected static HttpTransport configureMock() { return new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, final String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); response.setStatusCode(200); response.setContentType(Json.MEDIA_TYPE); if (url.startsWith(GCE_METADATA_URL)) { logger.info("--> Simulate GCE Auth/Metadata response for [{}]", url); response.setContent(readGoogleInternalJsonResponse(url)); } else { logger.info("--> Simulate GCE API response for [{}]", url); response.setContent(readGoogleApiJsonResponse(url)); } return response; } }; } }; }
@Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { callCount ++; if (!HttpMethods.GET.equals(method) || !expectedUrl.equals(url)) { // Throw RuntimeException to fail the test. throw new RuntimeException(); } return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); response.setStatusCode(HttpStatusCodes.STATUS_CODE_OK); response.setContentType(Json.MEDIA_TYPE); response.setContent(jsonResponse); return response; } }; }
@Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { if (ioException != null) { throw ioException; } MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); response.setStatusCode(HttpStatus.SC_ACCEPTED); response.setContentType(Json.MEDIA_TYPE); response.setContent(content); return response; } }; }
/** * Return a Client that is mocked to return the given HTTP response. * * @param httpResponse The full HTTP response data * @return The Client instance */ public Client mockClient(final String httpResponse) { Client client = new Client(); HttpTransport transport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); return mockResponse(response, httpResponse); } }; } }; client.setTransport(transport); return client; }
private HttpRequest constructHttpRequest(final String content) throws IOException { HttpTransport transport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { MockLowLevelHttpResponse result = new MockLowLevelHttpResponse(); result.setContentType("application/json"); result.setContent(content); return result; } }; } }; return transport.createRequestFactory().buildGetRequest(new GenericUrl("https://google.com")) .setParser(new JsonObjectParser(new JacksonFactory())); }
@Test public void normal() throws IOException { Collection<SinkRecord> sinkRecords = new ArrayList<>(); SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com")); SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp")); SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp", "sourcetype", "txt", "index", "main")); final LowLevelHttpRequest httpRequest = mock(LowLevelHttpRequest.class, CALLS_REAL_METHODS); LowLevelHttpResponse httpResponse = getResponse(200); when(httpRequest.execute()).thenReturn(httpResponse); this.task.transport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return httpRequest; } }; this.task.httpRequestFactory = this.task.transport.createRequestFactory(this.task.httpRequestInitializer); this.task.put(sinkRecords); }
@Test public void contentLengthTooLarge() throws IOException { Collection<SinkRecord> sinkRecords = new ArrayList<>(); SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com")); SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp")); SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp", "sourcetype", "txt", "index", "main")); final LowLevelHttpRequest httpRequest = mock(LowLevelHttpRequest.class, CALLS_REAL_METHODS); LowLevelHttpResponse httpResponse = getResponse(417); when(httpResponse.getContentType()).thenReturn("text/html"); when(httpRequest.execute()).thenReturn(httpResponse); this.task.transport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return httpRequest; } }; this.task.httpRequestFactory = this.task.transport.createRequestFactory(this.task.httpRequestInitializer); assertThrows(org.apache.kafka.connect.errors.ConnectException.class, () -> this.task.put(sinkRecords)); }
@Test public void invalidToken() throws IOException { Collection<SinkRecord> sinkRecords = new ArrayList<>(); SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com")); SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp")); SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp", "sourcetype", "txt", "index", "main")); final LowLevelHttpRequest httpRequest = mock(LowLevelHttpRequest.class, CALLS_REAL_METHODS); LowLevelHttpResponse httpResponse = getResponse(403); when(httpRequest.execute()).thenReturn(httpResponse); this.task.transport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return httpRequest; } }; this.task.httpRequestFactory = this.task.transport.createRequestFactory(this.task.httpRequestInitializer); assertThrows(org.apache.kafka.connect.errors.ConnectException.class, () -> this.task.put(sinkRecords)); }
@Test public void invalidIndex() throws IOException { Collection<SinkRecord> sinkRecords = new ArrayList<>(); SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com")); SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp")); SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp", "sourcetype", "txt", "index", "main")); final LowLevelHttpRequest httpRequest = mock(LowLevelHttpRequest.class, CALLS_REAL_METHODS); LowLevelHttpResponse httpResponse = getResponse(400); when(httpRequest.execute()).thenReturn(httpResponse); this.task.transport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return httpRequest; } }; this.task.httpRequestFactory = this.task.transport.createRequestFactory(this.task.httpRequestInitializer); assertThrows(org.apache.kafka.connect.errors.ConnectException.class, () -> this.task.put(sinkRecords)); }
@Before public void setUp() { MockitoAnnotations.initMocks(this); // A mock transport that lets us mock the API responses. MockHttpTransport transport = new MockHttpTransport.Builder() .setLowLevelHttpRequest( new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { return response; } }) .build(); // A sample BigQuery API client that uses default JsonFactory and RetryHttpInitializer. bigquery = new Bigquery.Builder( transport, Transport.getJsonFactory(), new RetryHttpRequestInitializer()) .build(); }
private MockHttpTransport createMockTransport (final ByteSource iirdeaResponse) { return new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { mockRequest = new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); response.setStatusCode(200); response.setContentType(PLAIN_TEXT_UTF_8.toString()); response.setContent(iirdeaResponse.read()); return response; } }; mockRequest.setUrl(url); return mockRequest; } }; }
/** Returns a valid GoogleJsonResponseException for the given status code and error message. */ private GoogleJsonResponseException makeResponseException( final int statusCode, final String message) throws Exception { HttpTransport transport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); response.setStatusCode(statusCode); response.setContentType(Json.MEDIA_TYPE); response.setContent(String.format( "{\"error\":{\"code\":%d,\"message\":\"%s\",\"domain\":\"global\"," + "\"reason\":\"duplicate\"}}", statusCode, message)); return response; }}; }}; HttpRequest request = transport.createRequestFactory() .buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL) .setThrowExceptionOnExecuteError(false); return GoogleJsonResponseException.from(new JacksonFactory(), request.execute()); }
@Test public void sendFirebaseMessage_create() throws Exception { // Mock out the firebase response. See // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing MockHttpTransport mockHttpTransport = spy(new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); response.setStatusCode(200); return response; } }; } }); FirebaseChannel.getInstance(null).httpTransport = mockHttpTransport; firebaseChannel.sendFirebaseMessage("my_key", new Game()); verify(mockHttpTransport, times(1)).buildRequest( "PATCH", FIREBASE_DB_URL + "/channels/my_key.json"); }
@Test public void sendFirebaseMessage_delete() throws Exception { // Mock out the firebase response. See // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing MockHttpTransport mockHttpTransport = spy(new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); response.setStatusCode(200); return response; } }; } }); FirebaseChannel.getInstance(null).httpTransport = mockHttpTransport; firebaseChannel.sendFirebaseMessage("my_key", null); verify(mockHttpTransport, times(1)).buildRequest( "DELETE", FIREBASE_DB_URL + "/channels/my_key.json"); }
@Test public void firebasePut() throws Exception { // Mock out the firebase response. See // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing MockHttpTransport mockHttpTransport = spy(new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); response.setStatusCode(200); return response; } }; } }); FirebaseChannel.getInstance(null).httpTransport = mockHttpTransport; Game game = new Game(); firebaseChannel.firebasePut(FIREBASE_DB_URL + "/my/path", game); verify(mockHttpTransport, times(1)).buildRequest("PUT", FIREBASE_DB_URL + "/my/path"); }
@Test public void firebasePatch() throws Exception { // Mock out the firebase response. See // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing MockHttpTransport mockHttpTransport = spy(new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); response.setStatusCode(200); return response; } }; } }); FirebaseChannel.getInstance(null).httpTransport = mockHttpTransport; Game game = new Game(); firebaseChannel.firebasePatch(FIREBASE_DB_URL + "/my/path", game); verify(mockHttpTransport, times(1)).buildRequest("PATCH", FIREBASE_DB_URL + "/my/path"); }
@Test public void firebasePost() throws Exception { // Mock out the firebase response. See // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing MockHttpTransport mockHttpTransport = spy(new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); response.setStatusCode(200); return response; } }; } }); FirebaseChannel.getInstance(null).httpTransport = mockHttpTransport; Game game = new Game(); firebaseChannel.firebasePost(FIREBASE_DB_URL + "/my/path", game); verify(mockHttpTransport, times(1)).buildRequest("POST", FIREBASE_DB_URL + "/my/path"); }
@Test public void firebaseGet() throws Exception { // Mock out the firebase response. See // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing MockHttpTransport mockHttpTransport = spy(new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); response.setStatusCode(200); return response; } }; } }); FirebaseChannel.getInstance(null).httpTransport = mockHttpTransport; firebaseChannel.firebaseGet(FIREBASE_DB_URL + "/my/path"); verify(mockHttpTransport, times(1)).buildRequest("GET", FIREBASE_DB_URL + "/my/path"); }
@Test public void firebaseDelete() throws Exception { // Mock out the firebase response. See // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing MockHttpTransport mockHttpTransport = spy(new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); response.setStatusCode(200); return response; } }; } }); FirebaseChannel.getInstance(null).httpTransport = mockHttpTransport; firebaseChannel.firebaseDelete(FIREBASE_DB_URL + "/my/path"); verify(mockHttpTransport, times(1)).buildRequest("DELETE", FIREBASE_DB_URL + "/my/path"); }
@Test public void firebaseGet() throws Exception { // Mock out the firebase response. See // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing MockHttpTransport mockHttpTransport = spy( new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); response.setStatusCode(200); return response; } }; } }); FirebaseChannel.getInstance().httpTransport = mockHttpTransport; firebaseChannel.firebaseGet(FIREBASE_DB_URL + "/my/path"); verify(mockHttpTransport, times(1)).buildRequest("GET", FIREBASE_DB_URL + "/my/path"); }
@Test public void firebaseDelete() throws Exception { // Mock out the firebase response. See // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing MockHttpTransport mockHttpTransport = spy( new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); response.setStatusCode(200); return response; } }; } }); FirebaseChannel.getInstance().httpTransport = mockHttpTransport; firebaseChannel.firebaseDelete(FIREBASE_DB_URL + "/my/path"); verify(mockHttpTransport, times(1)).buildRequest("DELETE", FIREBASE_DB_URL + "/my/path"); }
@Before public void setUp() throws Exception { // Mock out the vision service for unit tests. JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); HttpTransport transport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); response.setStatusCode(200); response.setContentType(Json.MEDIA_TYPE); response.setContent("{\"responses\": [{\"textAnnotations\": []}]}"); return response; } }; } }; Vision vision = new Vision(transport, jsonFactory, null); appUnderTest = new TextApp(vision, null /* index */); }
@Test public void testServerError() throws Exception { mockCommunicator.httpRequests = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return new MockLowLevelHttpRequest() { public LowLevelHttpResponse execute() throws IOException { MockLowLevelHttpResponse result = new MockLowLevelHttpResponse(); result.setStatusCode(500); return result; } }; } }.createRequestFactory(); expectedException.expect(AfmCommunicator.TemporaryException.class); mockCommunicator.requestTasks("", "", new HashMap<String, Integer>(), 1, new ArrayList<Task>()); }
@Test public void testClientError() throws Exception { mockCommunicator.httpRequests = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return new MockLowLevelHttpRequest() { public LowLevelHttpResponse execute() throws IOException { MockLowLevelHttpResponse result = new MockLowLevelHttpResponse(); result.setStatusCode(400); return result; } }; } }.createRequestFactory(); expectedException.expect(AfmCommunicator.FatalException.class); mockCommunicator.requestTasks("", "", new HashMap<String, Integer>(), 1, new ArrayList<Task>()); }
@Test public void testPostIOError() throws InterruptedException, ExecutionException, TimeoutException { Jups jups = new Jups(HttpTesting.SIMPLE_URL, "APP_ID", "SECRET"); jups.mHttpTransport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { throw new IOException("test"); } }; } }; String result = jups.send(new PushNotification("MASTER_VARIANT_ID", "VARIANT_ID", "ALERT_MESSAGE", "SOUND"), "TEST_UUID"); assertEquals("Push notification should have failed", result, "failed"); }
@Test public void testPostIOError() throws InterruptedException, ExecutionException, TimeoutException { Afm afm = Afm.get(HttpTesting.SIMPLE_URL); afm.mHttpTransport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { throw new IOException("test"); } }; } }; FutureCallback result = new FutureCallback(); afm.postTask(new Task("TASK_UUID", "TEST_UUID", "wait", 1), result); Task resultTask = result.task.get(5000, TimeUnit.MILLISECONDS); assertFalse("Task should have failed", result.succeeded); assertNotNull("Task should have been returned.", resultTask); assertNotNull("Error should be set.", resultTask.task_error); }
@Test public void testHttpError() throws Exception { handler.requestFactory = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { return new MockLowLevelHttpResponse().setStatusCode(500); } }; } }.createRequestFactory(); Map<String, Object> map = new HashMap<>(); map.put("url", "http://url.to.be.tested"); expectedException.expect(HttpResponseException.class); Map<String, Object> result = handler.execute(map); }
@Test public void testHttpOk() throws Exception { handler.requestFactory = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { return new MockLowLevelHttpResponse().setStatusCode(200); } }; } }.createRequestFactory(); Map<String, Object> map = new HashMap<>(); map.put("url", "http://url.to.be.tested"); Map<String, Object> result = handler.execute(map); assertEquals(200, result.get("status")); }
@Override public LowLevelHttpRequest buildRequest(String method, final String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public String getUrl() { return url; } @Override public LowLevelHttpResponse execute() throws IOException { lastRequestUrl = getUrl(); lastRequestContent = getContentAsString(); MockLowLevelHttpResponse mock = new MockLowLevelHttpResponse(); mock.setStatusCode(httpStatusCode); mock.setContent(httpResponseContent); return mock; } }; }
@Test public void testSimpleRequest() throws IOException { WebhoseClient.HTTP_TRANSPORT = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); response.setStatusCode(200); response.setContentType("application/json"); response.setContent("{\"totalResults\":123}"); return response; } }; } }; WebhoseClient client = new WebhoseClient("test-api-key"); WebhoseResponse apple = client.search("apple"); assertThat(apple.totalResults, is(123)); }
private HttpResponse createFakeResponse(final String responseHeader, final String responseValue, final InputStream content) throws IOException { HttpTransport transport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { MockLowLevelHttpRequest req = new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { return new MockLowLevelHttpResponse() .addHeader(responseHeader, responseValue) .setContent(content); } }; return req; } }; HttpRequest request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL); return request.execute(); }
@Override public LowLevelHttpResponse execute() throws IOException { if (getStreamingContent() != null) { String contentType = getContentType(); String contentEncoding = getContentEncoding(); if (contentEncoding != null) { addHeader("Content-Encoding", contentEncoding); } long contentLength = getContentLength(); //TODO handle upload properly ByteArrayOutputStream out = new ByteArrayOutputStream(contentLength > 0 ? (int) contentLength : 1024); try { getStreamingContent().writeTo(out); MediaType mediaType = MediaType.parse(contentType); RequestBody body = RequestBody.create(mediaType, out.toByteArray()); builder.method(method, body); } finally { out.close(); } } else { builder.method(method, null); } Response response = okClient.newCall(builder.build()).execute(); return new OkLowLevelHttpResponse(response); }
@Before public void setUp() throws Exception { httpTransport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, final String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { assertThat("Unexpected request to " + url, responses.keySet(), hasItem(url)); return responses.get(url); } }; } }; forge = new Forge(new URL("http://forge.example.com/forge"), httpTransport); }
/** * Tests that IOExceptions from executing an upload request are propagated properly. */ @SuppressWarnings("rawtypes") @Test public void testUploadBatchJobOperations_ioException_fails() throws Exception { final IOException ioException = new IOException("mock IO exception"); MockLowLevelHttpRequest lowLevelHttpRequest = new MockLowLevelHttpRequest(){ @Override public LowLevelHttpResponse execute() throws IOException { throw ioException; } }; when(uploadBodyProvider.getHttpContent(request, true, true)) .thenReturn(new ByteArrayContent(null, "foo".getBytes(UTF_8))); MockHttpTransport transport = new MockHttpTransport.Builder() .setLowLevelHttpRequest(lowLevelHttpRequest).build(); uploader = new BatchJobUploader(adWordsSession, transport, batchJobLogger); BatchJobUploadStatus uploadStatus = new BatchJobUploadStatus(0, URI.create("http://www.example.com")); thrown.expect(BatchJobException.class); thrown.expectCause(Matchers.sameInstance(ioException)); uploader.uploadIncrementalBatchJobOperations(request, true, uploadStatus); }
/** * Tests that IOExceptions from initiating an upload are propagated properly. */ @SuppressWarnings("rawtypes") @Test public void testUploadBatchJobOperations_initiateFails_fails() throws Exception { final IOException ioException = new IOException("mock IO exception"); MockLowLevelHttpRequest lowLevelHttpRequest = new MockLowLevelHttpRequest(){ @Override public LowLevelHttpResponse execute() throws IOException { throw ioException; } }; when(uploadBodyProvider.getHttpContent(request, true, true)) .thenReturn(new ByteArrayContent(null, "foo".getBytes(UTF_8))); MockHttpTransport transport = new MockHttpTransport.Builder() .setLowLevelHttpRequest(lowLevelHttpRequest).build(); uploader = new BatchJobUploader(adWordsSession, transport, batchJobLogger); thrown.expect(BatchJobException.class); thrown.expectCause(Matchers.sameInstance(ioException)); thrown.expectMessage("initiate upload"); uploader.uploadIncrementalBatchJobOperations(request, true, new BatchJobUploadStatus( 0, URI.create("http://www.example.com"))); }
@Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { Response storedResponse = responses.removeFirst(); MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); response.setStatusCode(storedResponse.statusCode); response.setContentType(Json.MEDIA_TYPE); response.setContent(storedResponse.content); return response; } }; }
@Override public LowLevelHttpResponse execute() throws IOException { MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); if (hasMetadata) { response.addHeader("Metadata-Flavor", "Google"); return response; } throw new IOException("emulated server exception"); }