Java Code Examples for com.google.api.client.testing.http.MockLowLevelHttpResponse#setContentType()

The following examples show how to use com.google.api.client.testing.http.MockLowLevelHttpResponse#setContentType() . 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: 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 2
Source File: CustomTokenRequestTest.java    From google-oauth-java-client with Apache License 2.0 6 votes vote down vote up
@Override
public LowLevelHttpRequest buildRequest(String method, String url) {
  return new MockLowLevelHttpRequest(url) {
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
      response.setContentType(Json.MEDIA_TYPE);
      IdTokenResponse json = new IdTokenResponse();
      json.setAccessToken("abc");
      json.setRefreshToken("def");
      json.setExpiresInSeconds(3600L);
      json.setIdToken(JWT_ENCODED_CONTENT);
      response.setContent(JSON_FACTORY.toString(json));
      return response;
    }
  };
}
 
Example 3
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 4
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 5
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 6
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 7
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 8
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 9
Source File: HttpResponseExceptionTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testInvalidCharset() 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.setStatusCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND);
              result.setReasonPhrase("Not Found");
              result.setContentType("text/plain; charset=");
              result.setContent("Unable to find resource");
              return result;
            }
          };
        }
      };
  final HttpRequest request =
      transport.createRequestFactory().buildGetRequest(SIMPLE_GENERIC_URL);
  HttpResponseException responseException =
      assertThrows(
          HttpResponseException.class,
          new ThrowingRunnable() {
            @Override
            public void run() throws Throwable {
              request.execute();
            }
          });

  assertThat(responseException)
      .hasMessageThat()
      .isEqualTo("404 Not Found\nGET " + SIMPLE_GENERIC_URL);
}
 
Example 10
Source File: HttpResponseExceptionTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testUnsupportedCharset() 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.setStatusCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND);
              result.setReasonPhrase("Not Found");
              result.setContentType("text/plain; charset=invalid-charset");
              result.setContent("Unable to find resource");
              return result;
            }
          };
        }
      };
  final HttpRequest request =
      transport.createRequestFactory().buildGetRequest(SIMPLE_GENERIC_URL);
  HttpResponseException responseException =
      assertThrows(
          HttpResponseException.class,
          new ThrowingRunnable() {
            @Override
            public void run() throws Throwable {
              request.execute();
            }
          });
  assertThat(responseException)
      .hasMessageThat()
      .isEqualTo("404 Not Found\nGET " + SIMPLE_GENERIC_URL);
}
 
Example 11
Source File: FakeWebServer.java    From healthcare-dicom-dicomweb-adapter with Apache License 2.0 5 votes vote down vote up
public void addWadoResponse(byte[] dicomInstance) throws IOException {
  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
  response.setStatusCode(200);
  response.setContentType("application/dicom; transfer-syntax=*");
  response.setContent(dicomInstance);
  responses.add(response);
}
 
Example 12
Source File: AbstractGoogleClientRequestTest.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(final String method, final String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() {
          assertEquals("GET", method);
          assertEquals("https://www.googleapis.com/test/path/v1/tests/foo", url);
          MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
          result.setStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED);
          result.setContentType(Json.MEDIA_TYPE);
          result.setContent(ERROR_CONTENT);
          return result;
        }
      };
    }
  };
  MockGoogleClient client = new MockGoogleClient.Builder(
      transport, ROOT_URL, SERVICE_PATH, JSON_OBJECT_PARSER, null).setApplicationName(
      "Test Application").build();
  MockGoogleClientRequest<String> request = new MockGoogleClientRequest<String>(
      client, HttpMethods.GET, URI_TEMPLATE, null, String.class);
  try {
    request.put("testId", "foo");
    request.executeUnparsed();
    fail("expected " + HttpResponseException.class);
  } catch (HttpResponseException e) {
    // expected
    assertEquals("401" + StringUtils.LINE_SEPARATOR + ERROR_CONTENT, e.getMessage());
  }
}
 
Example 13
Source File: DataflowWorkUnitClientTest.java    From beam with Apache License 2.0 5 votes vote down vote up
private LowLevelHttpResponse generateMockResponse(WorkItem... workItems) throws Exception {
  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
  response.setContentType(Json.MEDIA_TYPE);
  LeaseWorkItemResponse lease = new LeaseWorkItemResponse();
  lease.setWorkItems(Lists.newArrayList(workItems));
  // N.B. Setting the factory is necessary in order to get valid JSON.
  lease.setFactory(Transport.getJsonFactory());
  response.setContent(lease.toPrettyString());
  return response;
}
 
Example 14
Source File: HttpResponseTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testParseAs_classNoContent() throws Exception {
  final MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();

  for (final int status :
      new int[] {
        HttpStatusCodes.STATUS_CODE_NO_CONTENT, HttpStatusCodes.STATUS_CODE_NOT_MODIFIED, 102
      }) {
    HttpTransport transport =
        new MockHttpTransport() {
          @Override
          public LowLevelHttpRequest buildRequest(String method, final String url)
              throws IOException {
            return new MockLowLevelHttpRequest() {
              @Override
              public LowLevelHttpResponse execute() throws IOException {
                result.setStatusCode(status);
                result.setContentType(null);
                result.setContent(new ByteArrayInputStream(new byte[0]));
                return result;
              }
            };
          }
        };

    // Confirm that 'null' is returned when getting the response object of a
    // request with no message body.
    Object parsed =
        transport
            .createRequestFactory()
            .buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL)
            .setThrowExceptionOnExecuteError(false)
            .execute()
            .parseAs(Object.class);
    assertNull(parsed);
  }
}
 
Example 15
Source File: HttpResponseTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testParseAs_typeNoContent() throws Exception {
  final MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();

  for (final int status :
      new int[] {
        HttpStatusCodes.STATUS_CODE_NO_CONTENT, HttpStatusCodes.STATUS_CODE_NOT_MODIFIED, 102
      }) {
    HttpTransport transport =
        new MockHttpTransport() {
          @Override
          public LowLevelHttpRequest buildRequest(String method, final String url)
              throws IOException {
            return new MockLowLevelHttpRequest() {
              @Override
              public LowLevelHttpResponse execute() throws IOException {
                result.setStatusCode(status);
                result.setContentType(null);
                result.setContent(new ByteArrayInputStream(new byte[0]));
                return result;
              }
            };
          }
        };

    // Confirm that 'null' is returned when getting the response object of a
    // request with no message body.
    Object parsed =
        transport
            .createRequestFactory()
            .buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL)
            .setThrowExceptionOnExecuteError(false)
            .execute()
            .parseAs((Type) Object.class);
    assertNull(parsed);
  }
}
 
Example 16
Source File: CustomHttpErrorsTest.java    From beam with Apache License 2.0 5 votes vote down vote up
private static MockLowLevelHttpResponse createResponse(int code, String body) {
  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
  response.addHeader("custom_header", "value");
  response.setStatusCode(code);
  response.setContentType(Json.MEDIA_TYPE);
  response.setContent(body);
  return response;
}
 
Example 17
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 18
Source File: FakeWebServer.java    From healthcare-dicom-dicomweb-adapter with Apache License 2.0 5 votes vote down vote up
public void addJsonResponse(String jsonResponse) {
  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
  response.setStatusCode(200);
  response.setContentType("application/json");
  response.setContent(new ByteArrayInputStream(jsonResponse.getBytes()));
  responses.add(response);
}
 
Example 19
Source File: YouTubeSampleTest.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
@Test
public void testParsing() throws IOException {
  final InputStream contents = getClass().getClassLoader().getResourceAsStream("youtube-search.json");
  Preconditions.checkNotNull(contents);
  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(contents);
              return result;
            }
          };
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setParser(new JsonObjectParser(new GsonFactory()));
  HttpResponse response = request.execute();

  YouTubeSample.ListResponse listResponse = YouTubeSample.parseJson(response);
  assertEquals(5, listResponse.getPageInfo().getResultsPerPage());
  assertEquals(1000000, listResponse.getPageInfo().getTotalResults());
  assertEquals(5, listResponse.getSearchResults().size());
  for (YouTubeSample.SearchResult searchResult : listResponse.getSearchResults()) {
    assertEquals("youtube#searchResult", searchResult.getKind());
    assertNotNull(searchResult.getId());
    assertEquals("youtube#video", searchResult.getId().getKind());
    assertNotNull(searchResult.getId().getVideoId());
    YouTubeSample.Snippet snippet = searchResult.getSnippet();
    assertNotNull(snippet);
    assertNotNull(snippet.getChannelId());
    assertNotNull(snippet.getDescription());
    assertNotNull(snippet.getTitle());
    assertNotNull(snippet.getPublishedAt());
    Map<String, YouTubeSample.Thumbnail> thumbnails = snippet.getThumbnails();
    assertNotNull(thumbnails);

    for (Map.Entry<String, YouTubeSample.Thumbnail> entry : thumbnails.entrySet()) {
      assertNotNull(entry.getKey());
      YouTubeSample.Thumbnail thumbnail = entry.getValue();
      assertNotNull(thumbnail);
      assertNotNull(thumbnail.getUrl());
      assertNotNull(thumbnail.getWidth());
      assertNotNull(thumbnail.getHeight());
    }
  }
}
 
Example 20
Source File: HttpResponseTest.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
private void do_testGetContent_gzipEncoding_finishReading(String contentEncoding)
    throws IOException {
  byte[] dataToCompress = "abcd".getBytes(StandardCharsets.UTF_8);
  byte[] mockBytes;
  try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream(dataToCompress.length);
      GZIPOutputStream zipStream = new GZIPOutputStream((byteStream))) {
    zipStream.write(dataToCompress);
    zipStream.close();

    // GZIPInputStream uses a default buffer of 512B. Add enough content to exceed this
    // limit, so that some content will be left in the connection.
    for (int i = 0; i < 1024; i++) {
      byteStream.write('7');
    }
    mockBytes = byteStream.toByteArray();
  }
  final MockLowLevelHttpResponse mockResponse = new MockLowLevelHttpResponse();
  mockResponse.setContent(mockBytes);
  mockResponse.setContentEncoding(contentEncoding);
  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);
  HttpResponse response = request.execute();
  try (TestableByteArrayInputStream output =
      (TestableByteArrayInputStream) mockResponse.getContent()) {
    assertFalse(output.isClosed());
    assertEquals("abcd", response.parseAsString());
    assertTrue(output.isClosed());
    // The underlying stream should be fully consumed, even if gzip only returns some of it.
    assertEquals(-1, output.read());
  }
}