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

The following examples show how to use com.google.api.client.testing.http.MockLowLevelHttpResponse#setContent() . 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: 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 2
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 3
Source File: GitHubApiTransportImplTest.java    From copybara with Apache License 2.0 6 votes vote down vote up
@Test
public void testPasswordHeaderSet() throws Exception {
  Map<String, List<String>> headers = new HashMap<>();
  httpTransport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          headers.putAll(this.getHeaders());
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          response.setContent("foo");
          return response;
        }
      };
    }
  };
  transport = new GitHubApiTransportImpl(repo, httpTransport, "store", new TestingConsole());
  transport.get("foo/bar", String.class);
  assertThat(headers).containsEntry("authorization", ImmutableList.of("Basic dXNlcjpTRUNSRVQ="));
}
 
Example 4
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 5
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 6
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 7
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 8
Source File: HttpResponseTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void subtestContentLoggingLimit(
    final String content,
    int contentLoggingLimit,
    boolean loggingEnabled,
    String... expectedMessages)
    throws Exception {
  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(content);
              result.setContentType("text/plain");
              return result;
            }
          };
        }
      };
  HttpTransport.LOGGER.setLevel(Level.CONFIG);

  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setLoggingEnabled(loggingEnabled);
  HttpResponse response = request.execute();
  assertEquals(loggingEnabled, response.isLoggingEnabled());

  response.setContentLoggingLimit(contentLoggingLimit);
  LogRecordingHandler recorder = new LogRecordingHandler();
  HttpTransport.LOGGER.addHandler(recorder);
  response.parseAsString();
  assertEquals(Arrays.asList(expectedMessages), recorder.messages());
}
 
Example 9
Source File: FirebaseProjectManagementServiceImplTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void createAndroidApp() throws Exception {
  firstRpcResponse.setContent(CREATE_ANDROID_RESPONSE);
  MockLowLevelHttpResponse secondRpcResponse = new MockLowLevelHttpResponse();
  secondRpcResponse.setContent(CREATE_ANDROID_GET_OPERATION_ATTEMPT_1_RESPONSE);
  MockLowLevelHttpResponse thirdRpcResponse = new MockLowLevelHttpResponse();
  thirdRpcResponse.setContent(CREATE_ANDROID_GET_OPERATION_ATTEMPT_2_RESPONSE);
  serviceImpl = initServiceImpl(
      ImmutableList.of(
          firstRpcResponse, secondRpcResponse, thirdRpcResponse),
      interceptor);

  AndroidApp androidApp =
      serviceImpl.createAndroidApp(PROJECT_ID, PACKAGE_NAME, DISPLAY_NAME);

  assertEquals(ANDROID_APP_ID, androidApp.getAppId());
  String firstRpcExpectedUrl = String.format(
      "%s/v1beta1/projects/%s/androidApps", FIREBASE_PROJECT_MANAGEMENT_URL, PROJECT_ID);
  String secondRpcExpectedUrl = String.format(
      "%s/v1/operations/projects/test-project-id/apps/SomeToken",
      FIREBASE_PROJECT_MANAGEMENT_URL);
  String thirdRpcExpectedUrl = secondRpcExpectedUrl;
  checkRequestHeader(0, firstRpcExpectedUrl, HttpMethod.POST);
  checkRequestHeader(1, secondRpcExpectedUrl, HttpMethod.GET);
  checkRequestHeader(2, thirdRpcExpectedUrl, HttpMethod.GET);
  ImmutableMap<String, String> firstRpcPayload = ImmutableMap.<String, String>builder()
      .put("package_name", PACKAGE_NAME)
      .put("display_name", DISPLAY_NAME)
      .build();
  checkRequestPayload(0, firstRpcPayload);
}
 
Example 10
Source File: FirebaseProjectManagementServiceImplTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void listAndroidAppsMultiplePages() throws Exception {
  firstRpcResponse.setContent(LIST_ANDROID_APPS_PAGE_1_RESPONSE);
  MockLowLevelHttpResponse secondRpcResponse = new MockLowLevelHttpResponse();
  secondRpcResponse.setContent(LIST_ANDROID_APPS_PAGE_2_RESPONSE);
  serviceImpl = initServiceImpl(
      ImmutableList.of(firstRpcResponse, secondRpcResponse),
      interceptor);

  List<AndroidApp> androidAppList = serviceImpl.listAndroidApps(PROJECT_ID);

  String firstRpcExpectedUrl = String.format(
      "%s/v1beta1/projects/%s/androidApps?page_size=%d",
      FIREBASE_PROJECT_MANAGEMENT_URL,
      PROJECT_ID,
      MAXIMUM_LIST_APPS_PAGE_SIZE);
  String secondRpcExpectedUrl = String.format(
      "%s/v1beta1/projects/%s/androidApps?page_token=next-page-token&page_size=%d",
      FIREBASE_PROJECT_MANAGEMENT_URL,
      PROJECT_ID,
      MAXIMUM_LIST_APPS_PAGE_SIZE);
  checkRequestHeader(0, firstRpcExpectedUrl, HttpMethod.GET);
  checkRequestHeader(1, secondRpcExpectedUrl, HttpMethod.GET);
  assertEquals(androidAppList.size(), 2);
  assertEquals(androidAppList.get(0).getAppId(), "test-android-app-id-1");
  assertEquals(androidAppList.get(1).getAppId(), "test-android-app-id-2");
}
 
Example 11
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 12
Source File: HttpResponseTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testDisconnectWithContent() 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 {
              lowLevelHttpResponse.setContentType(Json.MEDIA_TYPE);
              lowLevelHttpResponse.setContent(SAMPLE);
              return lowLevelHttpResponse;
            }
          };
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  HttpResponse response = request.execute();

  assertFalse(lowLevelHttpResponse.isDisconnected());
  TestableByteArrayInputStream content =
      (TestableByteArrayInputStream) lowLevelHttpResponse.getContent();
  assertFalse(content.isClosed());
  response.disconnect();
  assertTrue(lowLevelHttpResponse.isDisconnected());
  assertTrue(content.isClosed());
}
 
Example 13
Source File: FirebaseProjectManagementServiceImplTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void createIosApp() throws Exception {
  firstRpcResponse.setContent(CREATE_IOS_RESPONSE);
  MockLowLevelHttpResponse secondRpcResponse = new MockLowLevelHttpResponse();
  secondRpcResponse.setContent(CREATE_IOS_GET_OPERATION_ATTEMPT_1_RESPONSE);
  MockLowLevelHttpResponse thirdRpcResponse = new MockLowLevelHttpResponse();
  thirdRpcResponse.setContent(CREATE_IOS_GET_OPERATION_ATTEMPT_2_RESPONSE);
  serviceImpl = initServiceImpl(
      ImmutableList.of(
          firstRpcResponse, secondRpcResponse, thirdRpcResponse),
      interceptor);

  IosApp iosApp = serviceImpl.createIosApp(PROJECT_ID, BUNDLE_ID, DISPLAY_NAME);

  assertEquals(IOS_APP_ID, iosApp.getAppId());
  String firstRpcExpectedUrl = String.format(
      "%s/v1beta1/projects/%s/iosApps", FIREBASE_PROJECT_MANAGEMENT_URL, PROJECT_ID);
  String secondRpcExpectedUrl = String.format(
      "%s/v1/operations/projects/test-project-id/apps/SomeToken",
      FIREBASE_PROJECT_MANAGEMENT_URL);
  String thirdRpcExpectedUrl = secondRpcExpectedUrl;
  checkRequestHeader(0, firstRpcExpectedUrl, HttpMethod.POST);
  checkRequestHeader(1, secondRpcExpectedUrl, HttpMethod.GET);
  checkRequestHeader(2, thirdRpcExpectedUrl, HttpMethod.GET);
  ImmutableMap<String, String> firstRpcPayload = ImmutableMap.<String, String>builder()
      .put("bundle_id", BUNDLE_ID)
      .put("display_name", DISPLAY_NAME)
      .build();
  checkRequestPayload(0, firstRpcPayload);
}
 
Example 14
Source File: DatastoreTest.java    From google-cloud-datastore with Apache License 2.0 5 votes vote down vote up
@Override
public HttpRequestFactory makeClient(DatastoreOptions options) {
  HttpTransport transport = new MockHttpTransport() {
      @Override
      public LowLevelHttpRequest buildRequest(String method, String url) {
        return new MockLowLevelHttpRequest(url) {
          @Override
          public LowLevelHttpResponse execute() throws IOException {
            lastPath = new GenericUrl(getUrl()).getRawPath();
            lastMimeType = getContentType();
            lastCookies = getHeaderValues("Cookie");
            lastApiFormatHeaderValue =
                Iterables.getOnlyElement(getHeaderValues("X-Goog-Api-Format-Version"));
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            getStreamingContent().writeTo(out);
            lastBody = out.toByteArray();
            if (nextException != null) {
              throw nextException;
            }
            MockLowLevelHttpResponse response = new MockLowLevelHttpResponse()
                .setStatusCode(nextStatus)
                .setContentType("application/x-protobuf");
            if (nextError != null) {
              assertNull(nextResponse);
              response.setContent(new TestableByteArrayInputStream(nextError.toByteArray()));
            } else {
              response.setContent(new TestableByteArrayInputStream(nextResponse.toByteArray()));
            }
            return response;
          }
        };
      }
    };
  Credential credential = options.getCredential();
  return transport.createRequestFactory(credential);
}
 
Example 15
Source File: FirebaseProjectManagementServiceImplTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void listIosAppsMultiplePages() throws Exception {
  firstRpcResponse.setContent(LIST_IOS_APPS_PAGE_1_RESPONSE);
  MockLowLevelHttpResponse secondRpcResponse = new MockLowLevelHttpResponse();
  secondRpcResponse.setContent(LIST_IOS_APPS_PAGE_2_RESPONSE);
  serviceImpl = initServiceImpl(
      ImmutableList.of(firstRpcResponse, secondRpcResponse),
      interceptor);

  List<IosApp> iosAppList = serviceImpl.listIosApps(PROJECT_ID);

  String firstRpcExpectedUrl = String.format(
      "%s/v1beta1/projects/%s/iosApps?page_size=%d",
      FIREBASE_PROJECT_MANAGEMENT_URL,
      PROJECT_ID,
      MAXIMUM_LIST_APPS_PAGE_SIZE);
  String secondRpcExpectedUrl = String.format(
      "%s/v1beta1/projects/%s/iosApps?page_token=next-page-token&page_size=%d",
      FIREBASE_PROJECT_MANAGEMENT_URL,
      PROJECT_ID,
      MAXIMUM_LIST_APPS_PAGE_SIZE);
  checkRequestHeader(0, firstRpcExpectedUrl, HttpMethod.GET);
  checkRequestHeader(1, secondRpcExpectedUrl, HttpMethod.GET);
  assertEquals(iosAppList.size(), 2);
  assertEquals(iosAppList.get(0).getAppId(), "test-ios-app-id-1");
  assertEquals(iosAppList.get(1).getAppId(), "test-ios-app-id-2");
}
 
Example 16
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 17
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 18
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 19
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 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;
    }
  };
}