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

The following examples show how to use com.google.api.client.testing.http.MockLowLevelHttpResponse#setStatusCode() . 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: 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 2
Source File: GoogleAuthTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
private HttpRequest constructHttpRequest(final String content, final int statusCode) throws IOException {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
          result.setContentType("application/json");
          result.setContent(content);
          result.setStatusCode(statusCode);
          return result;
        }
      };
    }
  };
  HttpRequest httpRequest = transport.createRequestFactory().buildGetRequest(new GenericUrl("https://google.com")).setParser(new JsonObjectParser(new JacksonFactory()));
  GoogleAuth.configureErrorHandling(httpRequest);
  return httpRequest;
}
 
Example 3
Source File: OAuth2CredentialsTest.java    From rides-java-sdk with MIT License 6 votes vote down vote up
@Override
public LowLevelHttpRequest buildRequest(String method, final String url) throws IOException {
    return new MockLowLevelHttpRequest() {

        @Override
        public String getUrl() {
            return url;
        }

        @Override
        public LowLevelHttpResponse execute() throws IOException {
            lastRequestUrl = getUrl();
            lastRequestContent = getContentAsString();

            MockLowLevelHttpResponse mock = new MockLowLevelHttpResponse();
            mock.setStatusCode(httpStatusCode);
            mock.setContent(httpResponseContent);

            return mock;
        }
    };
}
 
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: IcannHttpReporterTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
private MockHttpTransport createMockTransport (final ByteSource iirdeaResponse) {
  return new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) {
      mockRequest = new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          response.setStatusCode(200);
          response.setContentType(PLAIN_TEXT_UTF_8.toString());
          response.setContent(iirdeaResponse.read());
          return response;
        }
      };
      mockRequest.setUrl(url);
      return mockRequest;
    }
  };
}
 
Example 6
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 7
Source File: GcsUtilTest.java    From beam with Apache License 2.0 6 votes vote down vote up
@Test
public void testFileSizeWhenFileNotFoundNonBatch() 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"));
}
 
Example 8
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 9
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 10
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 11
Source File: HttpResponseExceptionTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testConstructor_noStatusCode() 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(0);
              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("GET " + SIMPLE_GENERIC_URL);
}
 
Example 12
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 13
Source File: GithubArchiveTest.java    From copybara with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws IOException {
  httpTransport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) {
          String requestString = method + " " + url;
          MockLowLevelHttpRequest request = new MockLowLevelHttpRequest();
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          request.setResponse(response);
          response.setStatusCode(200);
          response.setContent(responseContent);
          if (!url.equals(expectedRequest)) {
            response.setStatusCode(404);
            response.setContent(
                String.format("UNEXPECTED REQUEST (Returning 404) REQUEST: %s, expected: %s",
                    requestString, expectedRequest));
          }
          return request;
        }
      };
  RemoteFileOptions options = new RemoteFileOptions();
  options.transport = () -> new GclientHttpStreamFactory(httpTransport, Duration.ofSeconds(20));
  Console console = new TestingConsole();
  OptionsBuilder optionsBuilder = new OptionsBuilder().setConsole(console);
  optionsBuilder.remoteFile = options;
  skylark = new SkylarkTestExecutor(optionsBuilder);
}
 
Example 14
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 15
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 16
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 17
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 {
  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
  response.setStatusCode(500);
  return response;
}
 
Example 18
Source File: FakeWebServer.java    From healthcare-dicom-dicomweb-adapter with Apache License 2.0 4 votes vote down vote up
public void addResponseWithStatusCode(int statusCode) {
  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
  response.setStatusCode(statusCode);
  responses.add(response);
}
 
Example 19
Source File: HttpHandlerTest.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
/** Tests that the timeout set on the message context is passed to the underlying request. */
@Test
public void testInvokeSetsTimeout() {
  MessageContext messageContext = new MessageContext(axisEngine);
  messageContext.setRequestMessage(requestMessage);
  messageContext.setProperty(MessageContext.TRANS_URL, "https://www.example.com");

  // Do not care about XML parsing for this test, so set the response's status code to 302
  // to trigger an AxisFault.
  MockLowLevelHttpResponse lowLevelHttpResponse = new MockLowLevelHttpResponse();
  lowLevelHttpResponse.setContent("Intentional failure");
  lowLevelHttpResponse.setStatusCode(302);

  /*
   * Set timeout on the message context, then create a custom mock transport that will capture
   * invocations of LowLevelHttpRequest.setTimeout(int, int) and record the arguments passed.
   */
  int timeout = 1234567;
  messageContext.setTimeout(timeout);
  final int[] actualTimeouts = new int[] {Integer.MIN_VALUE, Integer.MIN_VALUE};
  MockLowLevelHttpRequest lowLevelHttpRequest =
      new MockLowLevelHttpRequest() {
        @Override
        public void setTimeout(int connectTimeout, int readTimeout) throws IOException {
          actualTimeouts[0] = connectTimeout;
          actualTimeouts[1] = readTimeout;
          super.setTimeout(connectTimeout, readTimeout);
        }
      };
  lowLevelHttpRequest.setResponse(lowLevelHttpResponse);
  MockHttpTransport mockTransport =
      new MockHttpTransport.Builder().setLowLevelHttpRequest(lowLevelHttpRequest).build();
  httpHandler = new HttpHandler(mockTransport, streamListener);

  try {
    httpHandler.invoke(messageContext);
    fail("Expected an AxisFault");
  } catch (AxisFault e) {
    assertThat(e.getFaultString(), Matchers.containsString("302"));
  }
  assertArrayEquals(
      "Timeouts not set to expected values", new int[] {timeout, timeout}, actualTimeouts);
}
 
Example 20
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;
    }
  };
}