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

The following examples show how to use com.google.api.client.testing.http.MockLowLevelHttpResponse#addHeader() . 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: 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 2
Source File: UpdateRegistrarRdapBaseUrlsActionTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testSecondTldSucceeds() {
  createTld("secondtld");
  httpTransport = new TestHttpTransport();
  action.httpTransport = httpTransport;

  // the first TLD request will return a bad cookie but the second will succeed
  MockLowLevelHttpResponse badLoginResponse = new MockLowLevelHttpResponse();
  badLoginResponse.addHeader("Set-Cookie",
      "Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/mosapi/v1/app; Secure; HttpOnly");

  httpTransport.addNextResponse(badLoginResponse);
  addValidResponses(httpTransport);

  action.run();
}
 
Example 3
Source File: UpdateRegistrarRdapBaseUrlsActionTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testBothFail() {
  createTld("secondtld");
  httpTransport = new TestHttpTransport();
  action.httpTransport = httpTransport;

  MockLowLevelHttpResponse badLoginResponse = new MockLowLevelHttpResponse();
  badLoginResponse.addHeader("Set-Cookie",
      "Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/mosapi/v1/app; Secure; HttpOnly");

  // it should fail for both TLDs
  httpTransport.addNextResponse(badLoginResponse);
  httpTransport.addNextResponse(badLoginResponse);

  assertThat(assertThrows(RuntimeException.class, action::run)).hasMessageThat()
      .isEqualTo("Error contacting MosAPI server. Tried TLDs [secondtld, tld]");
}
 
Example 4
Source File: UpdateRegistrarRdapBaseUrlsActionTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
private static void addValidResponses(TestHttpTransport httpTransport) {
  MockLowLevelHttpResponse loginResponse = new MockLowLevelHttpResponse();
  loginResponse.addHeader(
      "Set-Cookie",
      "JSESSIONID=bogusid; " + "Expires=Tue, 11-Jun-2019 16:34:21 GMT; Path=/; Secure; HttpOnly");
  loginResponse.addHeader(
      "Set-Cookie",
      "id=myAuthenticationId; "
          + "Expires=Tue, 11-Jun-2019 16:34:21 GMT; Path=/mosapi/v1/app; Secure; HttpOnly");

  MockLowLevelHttpResponse listResponse = new MockLowLevelHttpResponse();
  listResponse.setContent(JSON_LIST_REPLY);

  MockLowLevelHttpResponse logoutResponse = new MockLowLevelHttpResponse();
  logoutResponse.addHeader(
      "Set-Cookie",
      "id=id; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/mosapi/v1/app; Secure; HttpOnly");
  httpTransport.addNextResponse(loginResponse);
  httpTransport.addNextResponse(listResponse);
  httpTransport.addNextResponse(logoutResponse);
}
 
Example 5
Source File: HttpHeadersTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testAuthorizationHeader() throws IOException {
  // serialization
  HttpHeaders headers = new HttpHeaders();
  headers.setAuthorization(Arrays.asList("Foo", "Bar"));
  ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  Writer writer = new OutputStreamWriter(outputStream);
  HttpHeaders.serializeHeadersForMultipartRequests(headers, null, null, writer);
  assertEquals(AUTHORIZATION_HEADERS, outputStream.toString());
  // parsing
  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
  response.addHeader("Authorization", "Foo");
  response.addHeader("Authorization", "Bar");
  headers = new HttpHeaders();
  headers.fromHttpResponse(response, null);
  Object authHeader = headers.get("Authorization");
  assertTrue(authHeader.toString(), ImmutableList.of("Foo", "Bar").equals(authHeader));
}
 
Example 6
Source File: GooglePublicKeysManagerTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
@Override
public LowLevelHttpRequest buildRequest(String name, String url) {
  return new MockLowLevelHttpRequest() {
      @Override
    public LowLevelHttpResponse execute() {
      MockLowLevelHttpResponse r = new MockLowLevelHttpResponse();
      r.setStatusCode(200);
      r.addHeader("Cache-Control", "max-age=" + MAX_AGE);
      if (useAgeHeader) {
        r.addHeader("Age", String.valueOf(AGE));
      }
      r.setContentType(Json.MEDIA_TYPE);
      r.setContent(TEST_CERTIFICATES);
      return r;
    }
  };
}
 
Example 7
Source File: CountingLowLevelHttpRequest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
static CountingLowLevelHttpRequest fromStatus(int status, Map<String, String> headers) {
  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse()
      .setStatusCode(status)
      .setZeroContent();
  if (headers != null) {
    for (Map.Entry<String, String> entry : headers.entrySet()) {
      response.addHeader(entry.getKey(), entry.getValue());
    }
  }
  return fromStatus(response);
}
 
Example 8
Source File: GitHubApiTest.java    From copybara with Apache License 2.0 5 votes vote down vote up
@Override
public void trainMockGetWithHeaders(String apiPath, byte[] response,
    ImmutableMap<String, String> headers, int status) {
  String path = String.format("GET https://api.github.com%s", apiPath);
  MockLowLevelHttpResponse httpResponse = new MockLowLevelHttpResponse().setContent(response);
  for (Entry<String, String> entry : headers.entrySet()) {
    httpResponse.addHeader(entry.getKey(), entry.getValue());
  }
  httpResponse.setStatusCode(status);
  requestToResponse.put(path, httpResponse);
  requestValidators.put(path, (r) -> true);
}
 
Example 9
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 10
Source File: UpdateRegistrarRdapBaseUrlsActionTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testFailureCause_ignoresLoginFailure() {
  // Login failures aren't particularly interesting so we should log them, but the final
  // throwable should be some other failure if one existed
  createTld("secondtld");
  httpTransport = new TestHttpTransport();
  action.httpTransport = httpTransport;

  MockLowLevelHttpResponse loginResponse = new MockLowLevelHttpResponse();
  loginResponse.addHeader(
      "Set-Cookie",
      "id=myAuthenticationId; "
          + "Expires=Tue, 11-Jun-2019 16:34:21 GMT; Path=/mosapi/v1/app; Secure; HttpOnly");

  MockLowLevelHttpResponse badListResponse = new MockLowLevelHttpResponse();
  String badListReply = JSON_LIST_REPLY.substring(50);
  badListResponse.setContent(badListReply);

  MockLowLevelHttpResponse logoutResponse = new MockLowLevelHttpResponse();
  logoutResponse.addHeader(
      "Set-Cookie",
      "id=id; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/mosapi/v1/app; Secure; HttpOnly");

  MockLowLevelHttpResponse badLoginResponse = new MockLowLevelHttpResponse();
  badLoginResponse.addHeader(
      "Set-Cookie",
      "Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/mosapi/v1/app; Secure; HttpOnly");

  httpTransport.addNextResponse(loginResponse);
  httpTransport.addNextResponse(badListResponse);
  httpTransport.addNextResponse(logoutResponse);
  httpTransport.addNextResponse(badLoginResponse);

  assertThat(assertThrows(RuntimeException.class, action::run))
      .hasCauseThat()
      .isInstanceOf(JsonSyntaxException.class);
}
 
Example 11
Source File: HttpResponseTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testHeaderParsing() 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.addHeader("accept", "value");
              result.addHeader("foo", "bar");
              result.addHeader("goo", "car");
              result.addHeader("hoo", "dar");
              result.addHeader("hoo", "far");
              result.addHeader("obj", "o");
              result.addHeader("r", "a1");
              result.addHeader("r", "a2");
              result.addHeader("ETAG", ETAG_VALUE);
              return result;
            }
          };
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setResponseHeaders(new MyHeaders());
  HttpResponse response = request.execute();
  assertEquals("value", response.getHeaders().getAccept());
  assertEquals("bar", ((MyHeaders) response.getHeaders()).foo);
  assertEquals(Arrays.asList("o"), ((MyHeaders) response.getHeaders()).obj);
  assertEquals(Arrays.asList("a1", "a2"), Arrays.asList(((MyHeaders) response.getHeaders()).r));
  assertEquals(Arrays.asList("car"), response.getHeaders().get("goo"));
  assertEquals(Arrays.asList("dar", "far"), response.getHeaders().get("hoo"));
  assertEquals(ETAG_VALUE, response.getHeaders().getETag());
}
 
Example 12
Source File: MockHttpTransportHelper.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
private static MockLowLevelHttpResponse setHeaders(
    MockLowLevelHttpResponse response, Map<String, Object> headers, long defaultContentLength) {
  Object contentLength = headers.getOrDefault(CONTENT_LENGTH, defaultContentLength);
  Object contentEncoding = headers.get(CONTENT_ENCODING);
  headers.forEach((h, hv) -> response.addHeader(h, String.valueOf(hv)));
  if (!response.getHeaderNames().contains("x-goog-generation")) {
    response.addHeader("x-goog-generation", "1");
  }
  return response
      .setContentLength(Long.parseLong(String.valueOf(contentLength)))
      .setContentEncoding(contentEncoding == null ? null : String.valueOf(contentEncoding));
}
 
Example 13
Source File: MediaHttpUploaderTest.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
@Override
public LowLevelHttpResponse execute() throws IOException {
  lowLevelExecCalls++;
  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
  String contentRangeHeader = getFirstHeaderValue("Content-Range");
  if (testServerError || testIOException) {
    // TODO(peleyal): add test with two different failures in a row
    switch (lowLevelExecCalls) {
      case 3:
        // This request is where we simulate the error. Read into the bytesReceived array
        // up to maxByteIndexUploadedOnError to simulate the successfully-written bytes.
        int bytesToRead = maxByteIndexUploadedOnError + 1 - bytesUploaded;
        copyBytesToBytesReceivedArray(bytesToRead);
        bytesUploaded += bytesToRead;
        // Send a server error or throw IOException in response to the 3rd request.
        if (testIOException) {
          throw new IOException();
        }
        response.setStatusCode(500);
        return response;
      case 4:
        // This request follows the error. Client should be asking server for its range.

        // Assert that the client sent the correct range query request header.
        if (!contentLengthNotSpecified
            || (2 * MediaHttpUploader.DEFAULT_CHUNK_SIZE >= contentLength)) {
          // Client should send */length if it knows the content length.
          assertEquals("bytes */" + contentLength, contentRangeHeader);
        } else {
          // Client should send */* if it does not know the content length.
          assertEquals("bytes */*", contentRangeHeader);
        }
        // Return 308 if there are more bytes to upload or 308 is forced, else return 200.
        int statusCode = 200;
        if (contentLength != (maxByteIndexUploadedOnError + 1)
            || force308OnRangeQueryResponse) {
          statusCode = 308;
        }
        response.setStatusCode(statusCode);
        // Set the Range header with the bytes uploaded so far.
        response.addHeader("Range", "bytes=0-" + maxByteIndexUploadedOnError);
        return response;
      case 5:
        // If the file finished uploading, but we forced a 308 on request 4, validate
        // response and return 200.
        if (force308OnRangeQueryResponse
            && (contentLength == (maxByteIndexUploadedOnError + 1))) {
          assertEquals("bytes */" + contentLength, contentRangeHeader);
          response.setStatusCode(200);
          response.addHeader("Range", "bytes=0-" + contentLength);
          return response;
        }
        break;
      default:
        break;
    }
  } else if (testClientError) {
    // Return a 411.
    response.setStatusCode(411);
    return response;
  }

  String bytesRange;
  if (bytesUploaded + MediaHttpUploader.DEFAULT_CHUNK_SIZE > contentLength) {
    bytesRange = bytesUploaded + "-" + (contentLength - 1);
  } else {
    bytesRange =
        bytesUploaded + "-" + (bytesUploaded + MediaHttpUploader.DEFAULT_CHUNK_SIZE - 1);
  }
  String expectedContentRange;
  if (contentLength == 0) {
    expectedContentRange = "bytes */0";
  } else if (contentLengthNotSpecified
      && ((bytesUploaded + MediaHttpUploader.DEFAULT_CHUNK_SIZE) < contentLength)) {
    expectedContentRange = "bytes " + bytesRange + "/*";
  } else {
    expectedContentRange = "bytes " + bytesRange + "/" + contentLength;
  }

  assertEquals(expectedContentRange, contentRangeHeader);

  copyBytesToBytesReceivedArray(-1);

  bytesUploaded += MediaHttpUploader.DEFAULT_CHUNK_SIZE;

  if (bytesUploaded >= contentLength) {
    // Return 200 since the upload is complete.
    response.setStatusCode(200);
  } else {
    // Return 308 and the range since the upload is incomplete.
    response.setStatusCode(308);
    response.addHeader("Range", "bytes=" + bytesRange);
  }
  return response;
}
 
Example 14
Source File: MediaHttpDownloaderTest.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
@Override
public LowLevelHttpRequest buildRequest(String name, String url) {
  assertEquals(TEST_REQUEST_URL, url);

  return new MockLowLevelHttpRequest() {
      @Override
    public LowLevelHttpResponse execute() {
      lowLevelExecCalls++;
      MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();

      if (directDownloadEnabled) {
        if (bytesDownloaded != 0) {
          if (lastBytePos == -1) {
            assertEquals("bytes=" + bytesDownloaded + "-", getFirstHeaderValue("Range"));
          } else {
            assertEquals(
                "bytes=" + bytesDownloaded + "-" + lastBytePos, getFirstHeaderValue("Range"));
          }
        }
        if (testServerError && lowLevelExecCalls == 1) {
          // send a server error in the 1st request
          response.setStatusCode(500);
          return response;
        }
        response.setStatusCode(200);
        if (contentLengthIncluded) {
          response.addHeader("Content-Length", String.valueOf(contentLength));
        }
        response.setContent(
            new ByteArrayInputStream(new byte[contentLength - bytesDownloaded]));
        return response;
      }

      // Assert that the required headers are set.
      long currentRequestLastBytePos = bytesDownloaded + TEST_CHUNK_SIZE - 1;
      if (lastBytePos != -1) {
        currentRequestLastBytePos = Math.min(lastBytePos, currentRequestLastBytePos);
      }
      assertEquals("bytes=" + bytesDownloaded + "-" + currentRequestLastBytePos,
          getFirstHeaderValue("Range"));

      if (testServerError && lowLevelExecCalls == 2) {
        // Send a server error in the 2nd request.
        response.setStatusCode(500);
        return response;
      }
      if (testClientError) {
        // Return a 404.
        response.setStatusCode(404);
        return response;
      }

      response.setStatusCode(206);
      int upper;
      if (lastBytePos != -1) {
        upper = Math.min(lastBytePos, contentLength) - 1;
      } else {
        upper = Math.min(bytesDownloaded + TEST_CHUNK_SIZE, contentLength) - 1;
      }
      response.addHeader(
          "Content-Range", "bytes " + bytesDownloaded + "-" + upper + "/" + contentLength);
      int bytesDownloadedCur = upper - bytesDownloaded + 1;
      response.setContent(new ByteArrayInputStream(new byte[bytesDownloadedCur]));
      bytesDownloaded += bytesDownloadedCur;
      return response;
    }
  };
}
 
Example 15
Source File: MockHttpServer.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
private LowLevelHttpResponse execute(MockLowLevelHttpRequest request) throws IOException {

  ActualResponse actualResponse = new ActualResponse(request.getHeaders());
  actualResponses.add(actualResponse);

  MockResponse mockResponse;
  if (mockResponses.isEmpty()) {
    mockResponse = new MockResponse("No mock response body set", 500);
  } else {
    mockResponse = mockResponses.pop();
  }
  
  // Read the raw bytes from the request.
  ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
  request.getStreamingContent().writeTo(byteOutStream);
  final byte[] rawRequestBytes = byteOutStream.toByteArray();

  // Inflate the raw bytes if they are in gzip format.
  boolean isGzipFormat = false;
  List<String> contentEncodingValues = request.getHeaders().get("Content-Encoding");
  if (contentEncodingValues != null && !contentEncodingValues.isEmpty()) {
    isGzipFormat = "gzip".equals(contentEncodingValues.get(0));
  }

  byte[] requestBytes;
  if (isGzipFormat) {
    requestBytes =
        new ByteSource() {
          @Override
          public InputStream openStream() throws IOException {
            return new GZIPInputStream(ByteSource.wrap(rawRequestBytes).openStream());
          }
        }.read();
  } else {
    requestBytes = rawRequestBytes;
  }

  // Convert the (possibly inflated) request bytes to a string.
  String requestBody = ByteSource.wrap(requestBytes).asCharSource(StandardCharsets.UTF_8).read();
  actualResponse.setRequestBody(requestBody);

  if (mockResponse.isValidateUrlMatches() && !getServerUrl().equals(request.getUrl())) {
    throw new ConnectException(
        String.format(
            "Request URL does not match.%n  Expected: %s%n  Actual: %s%n",
            getServerUrl(),
            request.getUrl()));
  }

  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
  // Add the Location response header, which is required by some tests such as
  // BatchJobUploaderTest.
  response.addHeader("Location", getServerUrl());

  response.setStatusCode(mockResponse.getHttpStatus());
  response.setContentType(mockResponse.getContentType());
  response.setContent(mockResponse.getBody());
  return response;
}