Here are the examples of the java api class com.google.api.client.testing.http.MockHttpTransport taken from open source projects.
1. GcsUtilTest#testGetSizeBytesWhenFileNotFound()
Project: incubator-beam
File: GcsUtilTest.java
File: GcsUtilTest.java
@Test public void testGetSizeBytesWhenFileNotFound() throws Exception { MockLowLevelHttpResponse notFoundResponse = new MockLowLevelHttpResponse(); notFoundResponse.setContent(""); notFoundResponse.setStatusCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND); MockHttpTransport mockTransport = new MockHttpTransport.Builder().setLowLevelHttpResponse(notFoundResponse).build(); GcsOptions pipelineOptions = gcsOptionsWithTestCredential(); GcsUtil gcsUtil = pipelineOptions.getGcsUtil(); gcsUtil.setStorageClient(new Storage(mockTransport, Transport.getJsonFactory(), null)); thrown.expect(FileNotFoundException.class); gcsUtil.fileSize(GcsPath.fromComponents("testbucket", "testobject")); }
2. BigQueryTableInserterTest#setUp()
Project: incubator-beam
File: BigQueryTableInserterTest.java
File: BigQueryTableInserterTest.java
@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(); options = PipelineOptionsFactory.create(); }
3. BigQueryServicesImplTest#setUp()
Project: incubator-beam
File: BigQueryServicesImplTest.java
File: BigQueryServicesImplTest.java
@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(); }
4. HttpRequestTest#testNotSupportedByDefault()
Project: google-http-java-client
File: HttpRequestTest.java
File: HttpRequestTest.java
public void testNotSupportedByDefault() throws Exception { MockHttpTransport transport = new MockHttpTransport(); HttpRequest request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL); for (String method : BASIC_METHODS) { request.setRequestMethod(method); request.execute(); } for (String method : OTHER_METHODS) { transport = new MockHttpTransport.Builder().setSupportedMethods(ImmutableSet.<String>of()).build(); request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL); request.setRequestMethod(method); try { request.execute(); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { } transport = new MockHttpTransport.Builder().setSupportedMethods(ImmutableSet.of(method)).build(); request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL); request.setRequestMethod(method); request.execute(); } }
5. GoogleCredentialTest#testFromStreamServiceAccountMissingPrivateKeyIdThrows()
Project: google-api-java-client
File: GoogleCredentialTest.java
File: GoogleCredentialTest.java
public void testFromStreamServiceAccountMissingPrivateKeyIdThrows() throws IOException { final String serviceAccountId = "36680232662-vrd7ji19qe3nelgchd0ah2csanun6bnr.apps.googleusercontent.com"; final String serviceAccountEmail = "36680232662-vrd7ji19qgchd0ah2csanun6bnr@developer.gserviceaccount.com"; MockHttpTransport transport = new MockTokenServerTransport(); // Write out user file GenericJson serviceAccountContents = new GenericJson(); serviceAccountContents.setFactory(JSON_FACTORY); serviceAccountContents.put("client_id", serviceAccountId); serviceAccountContents.put("client_email", serviceAccountEmail); serviceAccountContents.put("private_key", SA_KEY_TEXT); serviceAccountContents.put("type", GoogleCredential.SERVICE_ACCOUNT_FILE_TYPE); String json = serviceAccountContents.toPrettyString(); InputStream serviceAccountStream = new ByteArrayInputStream(json.getBytes()); try { GoogleCredential.fromStream(serviceAccountStream, transport, JSON_FACTORY); fail(); } catch (IOException expected) { assertTrue(expected.getMessage().contains("private_key_id")); } }
6. GoogleCredentialTest#testFromStreamServiceAccountMissingPrivateKeyThrows()
Project: google-api-java-client
File: GoogleCredentialTest.java
File: GoogleCredentialTest.java
public void testFromStreamServiceAccountMissingPrivateKeyThrows() throws IOException { final String serviceAccountId = "36680232662-vrd7ji19qe3nelgchd0ah2csanun6bnr.apps.googleusercontent.com"; final String serviceAccountEmail = "36680232662-vrd7ji19qgchd0ah2csanun6bnr@developer.gserviceaccount.com"; MockHttpTransport transport = new MockTokenServerTransport(); // Write out user file GenericJson serviceAccountContents = new GenericJson(); serviceAccountContents.setFactory(JSON_FACTORY); serviceAccountContents.put("client_id", serviceAccountId); serviceAccountContents.put("client_email", serviceAccountEmail); serviceAccountContents.put("private_key_id", SA_KEY_ID); serviceAccountContents.put("type", GoogleCredential.SERVICE_ACCOUNT_FILE_TYPE); String json = serviceAccountContents.toPrettyString(); InputStream serviceAccountStream = new ByteArrayInputStream(json.getBytes()); try { GoogleCredential.fromStream(serviceAccountStream, transport, JSON_FACTORY); fail(); } catch (IOException expected) { assertTrue(expected.getMessage().contains("private_key")); } }
7. GoogleCredentialTest#testFromStreamServiceAccountMissingClientEmailThrows()
Project: google-api-java-client
File: GoogleCredentialTest.java
File: GoogleCredentialTest.java
public void testFromStreamServiceAccountMissingClientEmailThrows() throws IOException { final String serviceAccountId = "36680232662-vrd7ji19qe3nelgchd0ah2csanun6bnr.apps.googleusercontent.com"; MockHttpTransport transport = new MockTokenServerTransport(); // Write out user file GenericJson serviceAccountContents = new GenericJson(); serviceAccountContents.setFactory(JSON_FACTORY); serviceAccountContents.put("client_id", serviceAccountId); serviceAccountContents.put("private_key", SA_KEY_TEXT); serviceAccountContents.put("private_key_id", SA_KEY_ID); serviceAccountContents.put("type", GoogleCredential.SERVICE_ACCOUNT_FILE_TYPE); String json = serviceAccountContents.toPrettyString(); InputStream serviceAccountStream = new ByteArrayInputStream(json.getBytes()); try { GoogleCredential.fromStream(serviceAccountStream, transport, JSON_FACTORY); fail(); } catch (IOException expected) { assertTrue(expected.getMessage().contains("client_email")); } }
8. GoogleCredentialTest#testFromStreamServiceAccountMissingClientIdThrows()
Project: google-api-java-client
File: GoogleCredentialTest.java
File: GoogleCredentialTest.java
public void testFromStreamServiceAccountMissingClientIdThrows() throws IOException { final String serviceAccountEmail = "36680232662-vrd7ji19qgchd0ah2csanun6bnr@developer.gserviceaccount.com"; MockHttpTransport transport = new MockTokenServerTransport(); // Write out user file GenericJson serviceAccountContents = new GenericJson(); serviceAccountContents.setFactory(JSON_FACTORY); serviceAccountContents.put("client_email", serviceAccountEmail); serviceAccountContents.put("private_key", SA_KEY_TEXT); serviceAccountContents.put("private_key_id", SA_KEY_ID); serviceAccountContents.put("type", GoogleCredential.SERVICE_ACCOUNT_FILE_TYPE); String json = serviceAccountContents.toPrettyString(); InputStream serviceAccountStream = new ByteArrayInputStream(json.getBytes()); try { GoogleCredential.fromStream(serviceAccountStream, transport, JSON_FACTORY); fail(); } catch (IOException expected) { assertTrue(expected.getMessage().contains("client_id")); } }
9. GoogleJsonResponseExceptionFactoryTesting#newMock()
Project: google-api-java-client
File: GoogleJsonResponseExceptionFactoryTesting.java
File: GoogleJsonResponseExceptionFactoryTesting.java
/** * Convenience factory method that builds a {@link GoogleJsonResponseException} * from its arguments. The method builds a dummy {@link HttpRequest} and * {@link HttpResponse}, sets the response's status to a user-specified HTTP * error code, suppresses exceptions, and executes the request. This forces * the underlying framework to create, but not throw, a * {@link GoogleJsonResponseException}, which the method retrieves and returns * to the invoker. * * @param jsonFactory the JSON factory that will create all JSON required * by the underlying framework * @param httpCode the desired HTTP error code. Note: do nut specify any codes * that indicate successful completion, e.g. 2XX. * @param reasonPhrase the HTTP reason code that explains the error. For example, * if {@code httpCode} is {@code 404}, the reason phrase should be * {@code NOT FOUND}. * @return the generated {@link GoogleJsonResponseException}, as specified. * @throws IOException if request transport fails. */ public static GoogleJsonResponseException newMock(JsonFactory jsonFactory, int httpCode, String reasonPhrase) throws IOException { MockLowLevelHttpResponse otherServiceUnavaiableLowLevelResponse = new MockLowLevelHttpResponse().setStatusCode(httpCode).setReasonPhrase(reasonPhrase); MockHttpTransport otherTransport = new MockHttpTransport.Builder().setLowLevelHttpResponse(otherServiceUnavaiableLowLevelResponse).build(); HttpRequest otherRequest = otherTransport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL); otherRequest.setThrowExceptionOnExecuteError(false); HttpResponse otherServiceUnavailableResponse = otherRequest.execute(); return GoogleJsonResponseException.from(jsonFactory, otherServiceUnavailableResponse); }
10. GcsUtilTest#testGetSizeBytesWhenFileNotFound()
Project: DataflowJavaSDK
File: GcsUtilTest.java
File: GcsUtilTest.java
@Test public void testGetSizeBytesWhenFileNotFound() throws Exception { MockLowLevelHttpResponse notFoundResponse = new MockLowLevelHttpResponse(); notFoundResponse.setContent(""); notFoundResponse.setStatusCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND); MockHttpTransport mockTransport = new MockHttpTransport.Builder().setLowLevelHttpResponse(notFoundResponse).build(); GcsOptions pipelineOptions = gcsOptionsWithTestCredential(); GcsUtil gcsUtil = pipelineOptions.getGcsUtil(); gcsUtil.setStorageClient(new Storage(mockTransport, Transport.getJsonFactory(), null)); thrown.expect(FileNotFoundException.class); gcsUtil.fileSize(GcsPath.fromComponents("testbucket", "testobject")); }
11. BigQueryTableInserterTest#setUp()
Project: DataflowJavaSDK
File: BigQueryTableInserterTest.java
File: BigQueryTableInserterTest.java
@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(); }
12. BigQueryServicesImplTest#setUp()
Project: DataflowJavaSDK
File: BigQueryServicesImplTest.java
File: BigQueryServicesImplTest.java
@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(); }
13. RetryHttpRequestInitializerTest#testIOExceptionHandlerIsInvokedOnTimeout()
Project: incubator-beam
File: RetryHttpRequestInitializerTest.java
File: RetryHttpRequestInitializerTest.java
/** * Tests that when RPCs fail with {@link SocketTimeoutException}, the IO exception handler * is invoked. */ @Test public void testIOExceptionHandlerIsInvokedOnTimeout() throws Exception { // Counts the number of calls to execute the HTTP request. final AtomicLong executeCount = new AtomicLong(); // 10 is a private internal constant in the Google API Client library. See // com.google.api.client.http.HttpRequest#setNumberOfRetries // TODO: update this test once the private internal constant is public. final int defaultNumberOfRetries = 10; // A mock HTTP request that always throws SocketTimeoutException. MockHttpTransport transport = new MockHttpTransport.Builder().setLowLevelHttpRequest(new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { executeCount.incrementAndGet(); throw new SocketTimeoutException("Fake forced timeout exception"); } }).build(); // A sample HTTP request to BigQuery that uses both default Transport and default // RetryHttpInitializer. Bigquery b = new Bigquery.Builder(transport, Transport.getJsonFactory(), new RetryHttpRequestInitializer()).build(); BigQueryTableInserter inserter = new BigQueryTableInserter(b, PipelineOptionsFactory.create()); TableReference t = new TableReference().setProjectId("project").setDatasetId("dataset").setTableId("table"); try { inserter.insertAll(t, ImmutableList.of(new TableRow())); fail(); } catch (Throwable e) { assertThat(e, Matchers.<Throwable>instanceOf(RuntimeException.class)); assertThat(e.getCause(), Matchers.<Throwable>instanceOf(SocketTimeoutException.class)); assertEquals(1 + defaultNumberOfRetries, executeCount.get()); } }
14. CredentialTest#subtestConstructor()
Project: google-oauth-java-client
File: CredentialTest.java
File: CredentialTest.java
private HttpRequest subtestConstructor(Credential credential) throws Exception { MockHttpTransport transport = new MockHttpTransport(); HttpRequestFactory requestFactory = transport.createRequestFactory(credential); HttpRequest request = requestFactory.buildDeleteRequest(HttpTesting.SIMPLE_GENERIC_URL); request.execute(); return request; }
15. BatchRequestTest#testExecute_checkWriteToNoHeaders()
Project: google-api-java-client
File: BatchRequestTest.java
File: BatchRequestTest.java
public void testExecute_checkWriteToNoHeaders() throws Exception { MockHttpTransport transport = new MockHttpTransport(); HttpRequest request1 = transport.createRequestFactory().buildPostRequest(HttpTesting.SIMPLE_GENERIC_URL, new HttpContent() { @Override public long getLength() { return -1; } @Override public String getType() { return null; } @Override public void writeTo(OutputStream out) { } @Override public boolean retrySupported() { return true; } }); subtestExecute_checkWriteTo(new StringBuilder().append("--__END_OF_PART__\r\n").append("Content-Length: 27\r\n").append("Content-Type: application/http\r\n").append("content-id: 1\r\n").append("content-transfer-encoding: binary\r\n").append("\r\n").append("POST http://google.com/\r\n").append("\r\n").append("\r\n").append("--__END_OF_PART__--\r\n").toString(), request1); }
16. BatchRequestTest#subtestExecute_checkWriteTo()
Project: google-api-java-client
File: BatchRequestTest.java
File: BatchRequestTest.java
private void subtestExecute_checkWriteTo(final String expectedOutput, HttpRequest... requests) throws IOException { MockHttpTransport transport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) { return new MockLowLevelHttpRequest(url) { @Override public LowLevelHttpResponse execute() throws IOException { assertEquals("multipart/mixed; boundary=__END_OF_PART__", getContentType()); ByteArrayOutputStream out = new ByteArrayOutputStream(); getStreamingContent().writeTo(out); assertEquals(expectedOutput, out.toString("UTF-8")); MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); response.setStatusCode(200); response.addHeader("Content-Type", "multipart/mixed; boundary=" + RESPONSE_BOUNDARY); String content2 = "{\"name\": \"" + TEST_NAME + "\", \"number\": \"" + TEST_NUM + "\"}"; StringBuilder responseContent = new StringBuilder(); responseContent.append("--" + RESPONSE_BOUNDARY + "\n").append("Content-Type: application/http\n").append("Content-Transfer-Encoding: binary\n").append("Content-ID: response-1\n\n").append("HTTP/1.1 200 OK\n").append("Content-Type: application/json; charset=UTF-8\n").append("Content-Length: " + content2.length() + "\n\n").append(content2 + "\n\n").append("--" + RESPONSE_BOUNDARY + "--\n\n"); response.setContent(responseContent.toString()); return response; } }; } }; BatchRequest batchRequest = new BatchRequest(transport, null); BatchCallback<Void, Void> callback = new BatchCallback<Void, Void>() { @Override public void onSuccess(Void t, HttpHeaders responseHeaders) { } @Override public void onFailure(Void e, HttpHeaders responseHeaders) { } }; for (HttpRequest request : requests) { batchRequest.queue(request, Void.class, Void.class, callback); } batchRequest.execute(); }
17. BatchRequestTest#testExecute_checkWriteTo()
Project: google-api-java-client
File: BatchRequestTest.java
File: BatchRequestTest.java
public void testExecute_checkWriteTo() throws Exception { String request1Method = HttpMethods.POST; String request1Url = "http://test/dummy/url1"; String request1ContentType = "application/json"; String request1Content = "{\"data\":{\"foo\":{\"v1\":{}}}}"; String request2Method = HttpMethods.GET; String request2Url = "http://test/dummy/url2"; final StringBuilder expectedOutput = new StringBuilder(); expectedOutput.append("--__END_OF_PART__\r\n"); expectedOutput.append("Content-Length: 109\r\n"); expectedOutput.append("Content-Type: application/http\r\n"); expectedOutput.append("content-id: 1\r\n"); expectedOutput.append("content-transfer-encoding: binary\r\n"); expectedOutput.append("\r\n"); expectedOutput.append("POST http://test/dummy/url1\r\n"); expectedOutput.append("Content-Length: 26\r\n"); expectedOutput.append("Content-Type: " + request1ContentType + "\r\n"); expectedOutput.append("\r\n"); expectedOutput.append(request1Content + "\r\n"); expectedOutput.append("--__END_OF_PART__\r\n"); expectedOutput.append("Content-Length: 30\r\n"); expectedOutput.append("Content-Type: application/http\r\n"); expectedOutput.append("content-id: 2\r\n"); expectedOutput.append("content-transfer-encoding: binary\r\n"); expectedOutput.append("\r\n"); expectedOutput.append("GET http://test/dummy/url2\r\n"); expectedOutput.append("\r\n"); expectedOutput.append("\r\n"); expectedOutput.append("--__END_OF_PART__--\r\n"); MockHttpTransport transport = new MockHttpTransport(); HttpRequest request1 = transport.createRequestFactory().buildRequest(request1Method, new GenericUrl(request1Url), new ByteArrayContent(request1ContentType, request1Content.getBytes())); HttpRequest request2 = transport.createRequestFactory().buildRequest(request2Method, new GenericUrl(request2Url), null); subtestExecute_checkWriteTo(expectedOutput.toString(), request1, request2); }
18. RetryHttpRequestInitializerTest#testIOExceptionHandlerIsInvokedOnTimeout()
Project: DataflowJavaSDK
File: RetryHttpRequestInitializerTest.java
File: RetryHttpRequestInitializerTest.java
/** * Tests that when RPCs fail with {@link SocketTimeoutException}, the IO exception handler * is invoked. */ @Test public void testIOExceptionHandlerIsInvokedOnTimeout() throws Exception { // Counts the number of calls to execute the HTTP request. final AtomicLong executeCount = new AtomicLong(); // 10 is a private internal constant in the Google API Client library. See // com.google.api.client.http.HttpRequest#setNumberOfRetries // TODO: update this test once the private internal constant is public. final int defaultNumberOfRetries = 10; // A mock HTTP request that always throws SocketTimeoutException. MockHttpTransport transport = new MockHttpTransport.Builder().setLowLevelHttpRequest(new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { executeCount.incrementAndGet(); throw new SocketTimeoutException("Fake forced timeout exception"); } }).build(); // A sample HTTP request to BigQuery that uses both default Transport and default // RetryHttpInitializer. Bigquery b = new Bigquery.Builder(transport, Transport.getJsonFactory(), new RetryHttpRequestInitializer()).build(); BigQueryTableInserter inserter = new BigQueryTableInserter(b); TableReference t = new TableReference().setProjectId("project").setDatasetId("dataset").setTableId("table"); try { inserter.insertAll(t, ImmutableList.of(new TableRow())); fail(); } catch (Throwable e) { assertThat(e, Matchers.<Throwable>instanceOf(RuntimeException.class)); assertThat(e.getCause(), Matchers.<Throwable>instanceOf(SocketTimeoutException.class)); assertEquals(1 + defaultNumberOfRetries, executeCount.get()); } }