com.google.api.client.testing.http.HttpTesting Java Examples

The following examples show how to use com.google.api.client.testing.http.HttpTesting. 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: CredentialTest.java    From google-oauth-java-client with Apache License 2.0 6 votes vote down vote up
private void subtestRefreshToken_request(AccessTokenTransport transport, int expectedCalls)
    throws Exception {
  Credential credential =
      new Credential.Builder(BearerToken.queryParameterAccessMethod()).setTransport(transport)
          .setJsonFactory(JSON_FACTORY)
          .setTokenServerUrl(TOKEN_SERVER_URL)
          .setClientAuthentication(new BasicAuthentication(CLIENT_ID, CLIENT_SECRET))
          .build()
          .setRefreshToken(REFRESH_TOKEN)
          .setAccessToken(ACCESS_TOKEN);
  HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
  HttpRequest request = requestFactory.buildDeleteRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setThrowExceptionOnExecuteError(false);
  request.execute();

  assertEquals(expectedCalls, transport.calls);
}
 
Example #2
Source File: NetHttpRequestTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testInterruptedWriteWithResponse() throws Exception {
  MockHttpURLConnection connection =
      new MockHttpURLConnection(new URL(HttpTesting.SIMPLE_URL)) {
        @Override
        public OutputStream getOutputStream() throws IOException {
          return new OutputStream() {
            @Override
            public void write(int b) throws IOException {
              throw new IOException("Error writing request body to server");
            }
          };
        }
      };
  connection.setResponseCode(401);
  connection.setRequestMethod("POST");
  NetHttpRequest request = new NetHttpRequest(connection);
  InputStream is = NetHttpRequestTest.class.getClassLoader().getResourceAsStream("file.txt");
  HttpContent content = new InputStreamContent("text/plain", is);
  request.setStreamingContent(content);

  LowLevelHttpResponse response = request.execute();
  assertEquals(401, response.getStatusCode());
}
 
Example #3
Source File: UploadIdResponseInterceptorTest.java    From beam with Apache License 2.0 6 votes vote down vote up
/**
 * Builds an HttpResponse with the given string response.
 *
 * @param header header value to provide or null if none.
 * @param uploadId upload id to provide in the url upload id param or null if none.
 * @param uploadType upload type to provide in url upload type param or null if none.
 * @return HttpResponse with the given parameters
 * @throws IOException
 */
private HttpResponse buildHttpResponse(String header, String uploadId, String uploadType)
    throws IOException {
  MockHttpTransport.Builder builder = new MockHttpTransport.Builder();
  MockLowLevelHttpResponse resp = new MockLowLevelHttpResponse();
  builder.setLowLevelHttpResponse(resp);
  resp.setStatusCode(200);
  GenericUrl url = new GenericUrl(HttpTesting.SIMPLE_URL);
  if (header != null) {
    resp.addHeader("X-GUploader-UploadID", header);
  }
  if (uploadId != null) {
    url.put("upload_id", uploadId);
  }
  if (uploadType != null) {
    url.put("uploadType", uploadType);
  }
  return builder.build().createRequestFactory().buildGetRequest(url).execute();
}
 
Example #4
Source File: DirectoryGroupsConnectionTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/** 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) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() {
          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());
}
 
Example #5
Source File: NetHttpTransportTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testAbruptTerminationIsNoticedWithContentLength() throws Exception {
  String incompleteBody = "" + "Fixed size body test.\r\n" + "Incomplete response.";
  byte[] buf = StringUtils.getBytesUtf8(incompleteBody);
  MockHttpURLConnection connection =
      new MockHttpURLConnection(new URL(HttpTesting.SIMPLE_URL))
          .setResponseCode(200)
          .addHeader("Content-Length", "205")
          .setInputStream(new ByteArrayInputStream(buf));
  connection.setRequestMethod("GET");
  NetHttpRequest request = new NetHttpRequest(connection);
  setContent(request, null, "");
  NetHttpResponse response = (NetHttpResponse) (request.execute());

  InputStream in = response.getContent();
  boolean thrown = false;
  try {
    while (in.read() != -1) {
      // This space is intentionally left blank.
    }
  } catch (IOException ioe) {
    thrown = true;
  }
  assertTrue(thrown);
}
 
Example #6
Source File: NetHttpTransportTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testAbruptTerminationIsNoticedWithContentLengthWithReadToBuf() throws Exception {
  String incompleteBody = "" + "Fixed size body test.\r\n" + "Incomplete response.";
  byte[] buf = StringUtils.getBytesUtf8(incompleteBody);
  MockHttpURLConnection connection =
      new MockHttpURLConnection(new URL(HttpTesting.SIMPLE_URL))
          .setResponseCode(200)
          .addHeader("Content-Length", "205")
          .setInputStream(new ByteArrayInputStream(buf));
  connection.setRequestMethod("GET");
  NetHttpRequest request = new NetHttpRequest(connection);
  setContent(request, null, "");
  NetHttpResponse response = (NetHttpResponse) (request.execute());

  InputStream in = response.getContent();
  boolean thrown = false;
  try {
    while (in.read(new byte[100]) != -1) {
      // This space is intentionally left blank.
    }
  } catch (IOException ioe) {
    thrown = true;
  }
  assertTrue(thrown);
}
 
Example #7
Source File: HttpResponseTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testParseAsString_noContentType() 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 result = new MockLowLevelHttpResponse();
              result.setContent(SAMPLE2);
              return result;
            }
          };
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  HttpResponse response = request.execute();
  assertEquals(SAMPLE2, response.parseAsString());
}
 
Example #8
Source File: HttpResponseTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testParseAsString_validContentType() 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 result = new MockLowLevelHttpResponse();
              result.setContent(SAMPLE2);
              result.setContentType(VALID_CONTENT_TYPE);
              return result;
            }
          };
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);

  HttpResponse response = request.execute();
  assertEquals(SAMPLE2, response.parseAsString());
  assertEquals(VALID_CONTENT_TYPE, response.getContentType());
  assertNotNull(response.getMediaType());
}
 
Example #9
Source File: HttpResponseTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testParseAsString_validContentTypeWithParams() 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 result = new MockLowLevelHttpResponse();
              result.setContent(SAMPLE2);
              result.setContentType(VALID_CONTENT_TYPE_WITH_PARAMS);
              return result;
            }
          };
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);

  HttpResponse response = request.execute();
  assertEquals(SAMPLE2, response.parseAsString());
  assertEquals(VALID_CONTENT_TYPE_WITH_PARAMS, response.getContentType());
  assertNotNull(response.getMediaType());
}
 
Example #10
Source File: HttpResponseTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testParseAsString_invalidContentType() 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 result = new MockLowLevelHttpResponse();
              result.setContent(SAMPLE2);
              result.setContentType(INVALID_CONTENT_TYPE);
              return result;
            }
          };
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);

  HttpResponse response = request.execute();
  assertEquals(SAMPLE2, response.parseAsString());
  assertEquals(INVALID_CONTENT_TYPE, response.getContentType());
  assertNull(response.getMediaType());
}
 
Example #11
Source File: HttpResponseTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
private void subtestStatusCode_negative(boolean throwExceptionOnExecuteError) throws Exception {
  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
          return new MockLowLevelHttpRequest()
              .setResponse(new MockLowLevelHttpResponse().setStatusCode(-1));
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setThrowExceptionOnExecuteError(throwExceptionOnExecuteError);
  try {
    // HttpResponse converts a negative status code to zero
    HttpResponse response = request.execute();
    assertEquals(0, response.getStatusCode());
    assertFalse(throwExceptionOnExecuteError);
  } catch (HttpResponseException e) {
    // exception should be thrown only if throwExceptionOnExecuteError is true
    assertTrue(throwExceptionOnExecuteError);
    assertEquals(0, e.getStatusCode());
  }
}
 
Example #12
Source File: RetryDeterminerTest.java    From hadoop-connectors with Apache License 2.0 6 votes vote down vote up
HttpResponseException makeHttpException(int status) throws IOException {
  MockHttpTransport.Builder builder = new MockHttpTransport.Builder();
  MockLowLevelHttpResponse resp = new MockLowLevelHttpResponse();
  resp.setStatusCode(status);
  builder.setLowLevelHttpResponse(resp);
  try {
    HttpResponse res =
        builder.build()
            .createRequestFactory()
            .buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL)
            .execute();
    return new HttpResponseException(res);
  } catch (HttpResponseException exception) {
    return exception; // Throws the exception we want anyway, so just return it.
  }
}
 
Example #13
Source File: HttpResponseTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testDisconnectWithNoContent() throws Exception {
  final MockLowLevelHttpResponse lowLevelHttpResponse = new MockLowLevelHttpResponse();

  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
          return new MockLowLevelHttpRequest() {
            @Override
            public LowLevelHttpResponse execute() throws IOException {
              return lowLevelHttpResponse;
            }
          };
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  HttpResponse response = request.execute();

  assertFalse(lowLevelHttpResponse.isDisconnected());
  response.disconnect();
  assertTrue(lowLevelHttpResponse.isDisconnected());
}
 
Example #14
Source File: MockHttpTransportHelper.java    From hadoop-connectors with Apache License 2.0 6 votes vote down vote up
public static HttpResponse fakeResponse(Map<String, Object> headers, InputStream content)
    throws IOException {
  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) {
          return new MockLowLevelHttpRequest() {
            @Override
            public LowLevelHttpResponse execute() {
              MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
              headers.forEach((h, hv) -> response.addHeader(h, String.valueOf(hv)));
              return response.setContent(content);
            }
          };
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  return request.execute();
}
 
Example #15
Source File: HttpResponseTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testGetContent_gzipNoContent() throws IOException {
  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, final String url)
            throws IOException {
          return new MockLowLevelHttpRequest() {
            @Override
            public LowLevelHttpResponse execute() throws IOException {
              MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
              result.setContent("");
              result.setContentEncoding("gzip");
              result.setContentType("text/plain");
              return result;
            }
          };
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildHeadRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.execute().getContent();
}
 
Example #16
Source File: HttpResponseTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testGetContent_gzipEncoding_ReturnRawStream() throws IOException {
  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, final String url)
            throws IOException {
          return new MockLowLevelHttpRequest() {
            @Override
            public LowLevelHttpResponse execute() throws IOException {
              MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
              result.setContent("");
              result.setContentEncoding("gzip");
              result.setContentType("text/plain");
              return result;
            }
          };
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildHeadRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setResponseReturnRawInputStream(true);
  assertFalse(
      "it should not decompress stream",
      request.execute().getContent() instanceof GZIPInputStream);
}
 
Example #17
Source File: HttpResponseTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testGetContent_otherEncodingWithgzipInItsName_GzipIsNotUsed() throws IOException {
  final MockLowLevelHttpResponse mockResponse = new MockLowLevelHttpResponse();
  mockResponse.setContent("abcd");
  mockResponse.setContentEncoding("otherEncodingWithgzipInItsName");
  mockResponse.setContentType("text/plain");

  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, final String url)
            throws IOException {
          return new MockLowLevelHttpRequest() {
            @Override
            public LowLevelHttpResponse execute() throws IOException {
              return mockResponse;
            }
          };
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildHeadRequest(HttpTesting.SIMPLE_GENERIC_URL);
  // If gzip was used on this response, an exception would be thrown
  HttpResponse response = request.execute();
  assertEquals("abcd", response.parseAsString());
}
 
Example #18
Source File: HttpResponseTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testDownload() 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 result = new MockLowLevelHttpResponse();
              result.setContentType(Json.MEDIA_TYPE);
              result.setContent(SAMPLE);
              return result;
            }
          };
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  HttpResponse response = request.execute();
  ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  response.download(outputStream);
  assertEquals(SAMPLE, outputStream.toString("UTF-8"));
}
 
Example #19
Source File: HttpRequestTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testExecute_redirectWithIncorrectContentRetryableSetting() throws Exception {
  // TODO(yanivi): any way we can warn user about this?
  RedirectTransport fakeTransport = new RedirectTransport();
  String contentValue = "hello";
  fakeTransport.expectedContent = new String[] {contentValue, ""};
  byte[] bytes = StringUtils.getBytesUtf8(contentValue);
  InputStreamContent content =
      new InputStreamContent(
          new HttpMediaType("text/plain").setCharsetParameter(Charsets.UTF_8).build(),
          new ByteArrayInputStream(bytes));
  content.setRetrySupported(true);
  HttpRequest request =
      fakeTransport
          .createRequestFactory()
          .buildPostRequest(HttpTesting.SIMPLE_GENERIC_URL, content);
  HttpResponse resp = request.execute();
  assertEquals(200, resp.getStatusCode());
  assertEquals(2, fakeTransport.lowLevelExecCalls);
}
 
Example #20
Source File: HttpResponseTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testParseAsString_utf8() 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 result = new MockLowLevelHttpResponse();
              result.setContentType(Json.MEDIA_TYPE);
              result.setContent(SAMPLE);
              return result;
            }
          };
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  HttpResponse response = request.execute();
  assertEquals(SAMPLE, response.parseAsString());
}
 
Example #21
Source File: HttpRequestTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void test301RedirectWithBackOffUnsuccessfulResponseNotHandled() throws Exception {
  // Create an Unsuccessful response handler that always returns false.
  MockHttpUnsuccessfulResponseHandler handler = new MockHttpUnsuccessfulResponseHandler(false);
  // Set up RedirectTransport to redirect on the first request and then return success.
  RedirectTransport fakeTransport = new RedirectTransport();
  HttpRequest request =
      fakeTransport.createRequestFactory().buildGetRequest(new GenericUrl("http://gmail.com"));

  MockBackOff backOff = new MockBackOff();
  setBackOffUnsuccessfulResponseHandler(request, backOff, handler);

  HttpResponse resp = request.execute();

  Assert.assertEquals(200, resp.getStatusCode());
  // Assert that the redirect logic was invoked because the response handler could not handle the
  // request. The request url should have changed from http://gmail.com to http://google.com
  Assert.assertEquals(HttpTesting.SIMPLE_URL, request.getUrl().toString());
  Assert.assertEquals(2, fakeTransport.lowLevelExecCalls);
  // Assert that the backoff was not invoked since it's not required for 3xx errors
  Assert.assertEquals(0, backOff.getNumberOfTries());
}
 
Example #22
Source File: BatchRequestTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testExecute_checkWriteToNoHeaders() throws IOException {
  MockHttpTransport transport = new MockHttpTransport();
  HttpRequest request = 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;
        }
      });
  String expected = new StringBuilder()
    .append("Content-Length: 36\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/ HTTP/1.1\r\n").append("\r\n").append("\r\n")
    .append("--__END_OF_PART__").toString();
  subtestExecute_checkWriteTo(expected, expected, request);
}
 
Example #23
Source File: MethodOverrideTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testInterceptMaxLength() throws IOException {
  HttpTransport transport = new MockHttpTransport();
  GenericUrl url = new GenericUrl(HttpTesting.SIMPLE_URL);
  url.set("a", "foo");
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  new MethodOverride().intercept(request);
  assertEquals(HttpMethods.GET, request.getRequestMethod());
  assertNull(request.getHeaders().get(MethodOverride.HEADER));
  assertNull(request.getContent());
  char[] arr = new char[MethodOverride.MAX_URL_LENGTH];
  Arrays.fill(arr, 'x');
  url.set("a", new String(arr));
  request.setUrl(url);
  new MethodOverride().intercept(request);
  assertEquals(HttpMethods.POST, request.getRequestMethod());
  assertEquals(HttpMethods.GET, request.getHeaders().get(MethodOverride.HEADER));
  assertEquals(HttpTesting.SIMPLE_GENERIC_URL, request.getUrl());
  char[] arr2 = new char[arr.length + 2];
  Arrays.fill(arr2, 'x');
  arr2[0] = 'a';
  arr2[1] = '=';
  UrlEncodedContent content = (UrlEncodedContent) request.getContent();
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  content.writeTo(out);
  assertEquals(new String(arr2), out.toString());
}
 
Example #24
Source File: HttpRequestTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testExecute_redirects() throws Exception {
  class MyTransport extends MockHttpTransport {
    int count = 1;

    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      // expect that it redirected to new URL every time using the count
      assertEquals(HttpTesting.SIMPLE_URL + "_" + count, url);
      count++;
      return new MockLowLevelHttpRequest()
          .setResponse(
              new MockLowLevelHttpResponse()
                  .setStatusCode(HttpStatusCodes.STATUS_CODE_MOVED_PERMANENTLY)
                  .setHeaderNames(Arrays.asList("Location"))
                  .setHeaderValues(Arrays.asList(HttpTesting.SIMPLE_URL + "_" + count)));
    }
  }
  MyTransport transport = new MyTransport();
  HttpRequest request =
      transport
          .createRequestFactory()
          .buildGetRequest(new GenericUrl(HttpTesting.SIMPLE_URL + "_" + transport.count));
  try {
    request.execute();
    fail("expected " + HttpResponseException.class);
  } catch (HttpResponseException e) {
    assertEquals(HttpStatusCodes.STATUS_CODE_MOVED_PERMANENTLY, e.getStatusCode());
  }
}
 
Example #25
Source File: HttpRequestTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testExecuteAsync()
    throws IOException, InterruptedException, ExecutionException, TimeoutException {
  MockExecutor mockExecutor = new MockExecutor();
  HttpTransport transport = new MockHttpTransport();
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  Future<HttpResponse> futureResponse = request.executeAsync(mockExecutor);

  assertFalse(futureResponse.isDone());
  mockExecutor.actuallyRun();
  assertTrue(futureResponse.isDone());
  assertNotNull(futureResponse.get(10, TimeUnit.MILLISECONDS));
}
 
Example #26
Source File: AbstractGoogleJsonClientTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testExecuteUnparsed_error() throws Exception {
  HttpTransport transport = new MockHttpTransport() {
      @Override
    public LowLevelHttpRequest buildRequest(String name, String url) {
      return new MockLowLevelHttpRequest() {
          @Override
        public LowLevelHttpResponse execute() {
          MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
          result.setStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED);
          result.setContentType(Json.MEDIA_TYPE);
          result.setContent("{\"error\":{\"code\":401,\"errors\":[{\"domain\":\"global\","
              + "\"location\":\"Authorization\",\"locationType\":\"header\","
              + "\"message\":\"me\",\"reason\":\"authError\"}],\"message\":\"me\"}}");
          return result;
        }
      };
    }
  };
  JsonFactory jsonFactory = new JacksonFactory();
  MockGoogleJsonClient client = new MockGoogleJsonClient.Builder(
      transport, jsonFactory, HttpTesting.SIMPLE_URL, "", null, false).setApplicationName(
      "Test Application").build();
  MockGoogleJsonClientRequest<String> request =
      new MockGoogleJsonClientRequest<String>(client, "GET", "foo", null, String.class);
  try {
    request.executeUnparsed();
    fail("expected " + GoogleJsonResponseException.class);
  } catch (GoogleJsonResponseException e) {
    // expected
    GoogleJsonError details = e.getDetails();
    assertEquals("me", details.getMessage());
    assertEquals("me", details.getErrors().get(0).getMessage());
  }
}
 
Example #27
Source File: CommonGoogleClientRequestInitializerTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testInitializeSetsRequestReason() throws IOException {
  GoogleClientRequestInitializer requestInitializer = CommonGoogleClientRequestInitializer.newBuilder()
      .setRequestReason("some request reason")
      .build();
  MockGoogleClient client = new MockGoogleClient.Builder(new MockHttpTransport(), HttpTesting.SIMPLE_URL, "test/", null, null)
      .setGoogleClientRequestInitializer(requestInitializer)
      .setApplicationName("My Application")
      .build();
  MyRequest request = new MyRequest(client, "GET", "", null, String.class);
  requestInitializer.initialize(request);
  HttpHeaders headers = request.getRequestHeaders();
  assertEquals("some request reason", headers.get("X-Goog-Request-Reason"));
}
 
Example #28
Source File: CommonGoogleClientRequestInitializerTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testInitializeSetsUserProject() throws IOException {
  GoogleClientRequestInitializer requestInitializer = CommonGoogleClientRequestInitializer.newBuilder()
      .setUserProject("my quota project")
      .build();
  MockGoogleClient client = new MockGoogleClient.Builder(new MockHttpTransport(), HttpTesting.SIMPLE_URL, "test/", null, null)
      .setGoogleClientRequestInitializer(requestInitializer)
      .setApplicationName("My Application")
      .build();
  MyRequest request = new MyRequest(client, "GET", "", null, String.class);
  requestInitializer.initialize(request);
  HttpHeaders headers = request.getRequestHeaders();
  assertEquals("my quota project", headers.get("X-Goog-User-Project"));
}
 
Example #29
Source File: CommonGoogleClientRequestInitializerTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testInitializeSetsUserAgent() throws IOException {
  GoogleClientRequestInitializer requestInitializer = CommonGoogleClientRequestInitializer.newBuilder()
      .setUserAgent("test user agent")
      .build();
  MockGoogleClient client = new MockGoogleClient.Builder(new MockHttpTransport(), HttpTesting.SIMPLE_URL, "test/", null, null)
      .setGoogleClientRequestInitializer(requestInitializer)
      .setApplicationName("My Application")
      .build();
  MyRequest request = new MyRequest(client, "GET", "", null, String.class);
  requestInitializer.initialize(request);
  HttpHeaders headers = request.getRequestHeaders();
  assertEquals("test user agent", headers.getUserAgent());
}
 
Example #30
Source File: MockHttpUrlConnectionTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testSetInputStreamAndInputStreamImmutable() throws IOException {
  MockHttpURLConnection connection = new MockHttpURLConnection(new URL(HttpTesting.SIMPLE_URL));
  connection.setInputStream(new ByteArrayInputStream(StringUtils.getBytesUtf8(RESPONSE_BODY)));
  connection.setInputStream(new ByteArrayInputStream(StringUtils.getBytesUtf8("override")));
  byte[] buf = new byte[10];
  InputStream in = connection.getInputStream();
  int n = 0, bytes = 0;
  while ((n = in.read(buf)) != -1) {
    bytes += n;
  }
  assertEquals(RESPONSE_BODY, new String(buf, 0, bytes));
}