Package com.google.api.client.testing.http

Examples of com.google.api.client.testing.http.MockLowLevelHttpResponse


      @Override
      public LowLevelHttpRequest buildRequest(String method, String url) {
        return new MockLowLevelHttpRequest(url) {
          @Override
          public LowLevelHttpResponse execute() {
            MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
            if (!checkAuth.checkAuth(this)) {
              response.setStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED);
              if (resetAccessToken) {
                credential.setAccessToken(NEW_ACCESS_TOKEN);
              }
            }
            return response;
View Full Code Here


      @Override
      public LowLevelHttpRequest buildRequest(String method, String url) {
        return new MockLowLevelHttpRequest(url) {
          @Override
          public LowLevelHttpResponse execute() {
            MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
            if (!checkAuth.checkAuth(this)) {
              response.setStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED);
              if (resetAccessToken) {
                credential.setAccessToken(NEW_ACCESS_TOKEN);
              }
            }
            return response;
View Full Code Here

    public LowLevelHttpRequest buildRequest(String method, String url) {
      return new MockLowLevelHttpRequest(url) {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          calls++;
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          response.setContentType(Json.MEDIA_TYPE);
          GenericData responseData;
          if (statusCode == 401 || wwwAuthenticate != null) {
            // return 401 or invalid_token error (with the given status code), and then reset
            // wwwAuthenticate and statusCode - so next request to refresh the token will succeed
            if (wwwAuthenticate != null) {
              response.addHeader("WWW-Authenticate", wwwAuthenticate);
              wwwAuthenticate = null;
            }

            response.setStatusCode(statusCode);
            statusCode = 200;
            return response;
          }
          if (statusCode != 200) {
            TokenErrorResponse json = new TokenErrorResponse();
            json.setError("invalid_client");
            responseData = json;
            response.setStatusCode(statusCode);
          } else {
            TokenResponse json = new TokenResponse();
            json.setAccessToken(NEW_ACCESS_TOKEN);
            json.setRefreshToken(NEW_REFRESH_TOKEN);
            json.setExpiresInSeconds(EXPIRES_IN);
            responseData = json;
          }
          response.setContent(JSON_FACTORY.toString(responseData));
          return response;
        }
      };
    }
View Full Code Here

    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) {
      return new MockLowLevelHttpRequest(url) {
          @Override
        public LowLevelHttpResponse execute() throws IOException {
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          response.setContentType("UTF-8");
          GenericData responseData;
          if (error) {
            TokenErrorResponse json = new TokenErrorResponse();
            json.setError("invalid_client");
            responseData = json;
            response.setStatusCode(400);
          } else {
            TokenResponse json = new TokenResponse();
            json.setAccessToken(NEW_ACCESS_TOKEN);
            json.setRefreshToken(NEW_REFRESH_TOKEN);
            json.setExpiresInSeconds(EXPIRES_IN);
            responseData = json;
          }
          response.setContent(JSON_FACTORY.toString(responseData));
          return response;
        }
      };
    }
View Full Code Here

              assertEquals(
                  Integer.toString(contentLength), getFirstHeaderValue("x-upload-content-length"));
            }
            assertEquals(TEST_CONTENT_TYPE, getFirstHeaderValue("x-upload-content-type"));
            // This is the initiation call. Return 200 with the upload URI.
            MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
            response.setStatusCode(200);
            response.addHeader("Location", TEST_UPLOAD_URL);
            return response;
          }
        };
      }
      assertEquals(TEST_UPLOAD_URL, url);

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

          String bytesRange =
              bytesUploaded + "-" + (bytesUploaded + MediaHttpUploader.DEFAULT_CHUNK_SIZE - 1);
          String expectedContentRange = "bytes " + bytesRange + "/" + contentLength;
          assertEquals(expectedContentRange, getFirstHeaderValue("Content-Range"));
          bytesUploaded += MediaHttpUploader.DEFAULT_CHUNK_SIZE;

          if (bytesUploaded == contentLength) {
            // Return 200 since the upload is complete.
            response.setStatusCode(200);
            response.setContent("{\"foo\":\"somevalue\"}");
            response.setContentType(Json.MEDIA_TYPE);
          } else {
            // Return 308 and the range since the upload is incomplete.
            response.setStatusCode(308);
            response.addHeader("Range", bytesRange);
          }
          return response;
        }
      };
    }
View Full Code Here

            }
            if (assertTestHeaders) {
              assertEquals("test-header-value", getFirstHeaderValue("test-header-name"));
            }
            // This is the initiation call.
            MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
            assertFalse(directUploadEnabled && testIOException);
            if (directUploadEnabled && testServerError && lowLevelExecCalls == 1) {
              // send a server error in the 1st request of a direct upload
              response.setStatusCode(500);
            } else if (testAuthenticationError) {
              // Return 404.
              response.setStatusCode(404);
            } else {
              // Return 200 with the upload URI.
              response.setStatusCode(200);
              if (!directUploadEnabled) {
                response.addHeader("Location", TEST_UPLOAD_URL);
              }
            }
            return response;
          }
        };
      }
      assertEquals(TEST_UPLOAD_URL, url);
      assertEquals("PUT", name);
      return new MockLowLevelHttpRequest() {
          @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:
                int bytesToRead = maxByteIndexUploadedOnError + 1 - bytesUploaded;
                copyBytesToBytesReceivedArray(bytesToRead);
                bytesUploaded += bytesToRead;
                // Send a server error or throw IOException in the 3rd request
                if (testIOException) {
                  throw new IOException();
                }
                response.setStatusCode(500);
                return response;
              case 4:
                // Assert that the 4th request is a range query request.
                if (contentLengthNotSpecified) {
                  assertEquals("bytes */*", contentRangeHeader);
                } else {
                  assertEquals("bytes */" + contentLength, contentRangeHeader);
                }
                // Return 308 in case there are more bytes to upload, otherwise return 200.
                // set the Range header with the bytes uploaded so far.
                response.setStatusCode(
                    contentLength == maxByteIndexUploadedOnError + 1 ? 200 : 308);
                bytesUploaded = maxByteIndexUploadedOnError + 1;
                response.addHeader("Range", "bytes=0-" + maxByteIndexUploadedOnError);
                return response;
              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;
        }

        void copyBytesToBytesReceivedArray(int length) throws IOException {
View Full Code Here

          public LowLevelHttpResponse execute() throws IOException {
            assertEquals("multipart/mixed; boundary=__END_OF_PART__", getContentType());
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            getStreamingContent().writeTo(out);
            assertEquals(expectedOutput, out.toString("UTF-8"));
            MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
            response.setStatusCode(200);
            response.addHeader("Content-Type", "multipart/mixed; boundary=" + RESPONSE_BOUNDARY);
            String content2 = "{\"name\": \"" + TEST_NAME + "\", \"number\": \"" + TEST_NUM + "\"}";
            StringBuilder responseContent = new StringBuilder();
            responseContent.append("--" + RESPONSE_BOUNDARY + "\n")
                .append("Content-Type: application/http\n")
                .append("Content-Transfer-Encoding: binary\n").append("Content-ID: response-1\n\n")
                .append("HTTP/1.1 200 OK\n")
                .append("Content-Type: application/json; charset=UTF-8\n")
                .append("Content-Length: " + content2.length() + "\n\n").append(content2 + "\n\n")
                .append("--" + RESPONSE_BOUNDARY + "--\n\n");
            response.setContent(responseContent.toString());
            return response;
          }
        };
      }
    };
View Full Code Here

    public LowLevelHttpRequest buildRequest(String name, String url) {
      actualCalls++;
      return new MockLowLevelHttpRequest() {
          @Override
        public LowLevelHttpResponse execute() throws IOException {
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          response.setStatusCode(200);
          response.addHeader("Content-Type", "multipart/mixed; boundary=" + RESPONSE_BOUNDARY);
          String contentType =
              testBinary ? "application/x-protobuf" : "application/json; charset=UTF-8";
          byte[] content1 = testBinary ? MockData.Class1.newBuilder()
              .setId(TEST_ID)
              .setKind(TEST_KIND)
              .build().toByteArray()
              : utf8Encode("{\n \"id\": \"" + TEST_ID + "\",\n \"kind\": \""
                  + TEST_KIND.replace("\n", "\\n") + "\"\n}");
          byte[] content2 = testBinary ? MockData.Class2.newBuilder()
              .setName(TEST_NAME)
              .setNumber(TEST_NUM)
              .build().toByteArray()
              : utf8Encode("{\"name\": \"" + TEST_NAME + "\", \"number\": \"" + TEST_NUM + "\"}");
          byte[] errorContent = testBinary ? ErrorOutput.ErrorBody.newBuilder()
              .setError(ErrorOutput.ErrorProto.newBuilder()
                  .setCode(ERROR_CODE)
                  .setMessage(ERROR_MSG)
                  .addErrors(ErrorOutput.IndividualError.newBuilder()
                      .setDomain(ERROR_DOMAIN)
                      .setReason(ERROR_REASON)
                      .setMessage(ERROR_MSG))
              ).build().toByteArray()
              : utf8Encode("{\"error\": { \"errors\": [{\"domain\": \"" + ERROR_DOMAIN + "\","
                  + "\"reason\": \"" + ERROR_REASON + "\", \"message\": \"" + ERROR_MSG + "\"}],"
                  + "\"code\": " + ERROR_CODE + ", \"message\": \"" + ERROR_MSG + "\"}}");
          ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
          Writer responseContent = new OutputStreamWriter(outputStream, "ISO-8859-1");
          if (returnSuccessAuthenticatedContent || (testExponentialBackOff && actualCalls > 1)
              || (testRedirect && actualCalls > 1)) {
            if (returnSuccessAuthenticatedContent || actualCalls == callsBeforeSuccess) {
              responseContent.append("--" + RESPONSE_BOUNDARY + "\n")
                  .append("Content-Type: application/http\n")
                  .append("Content-Transfer-Encoding: binary\n")
                  .append("Content-ID: response-1\n\n").append("HTTP/1.1 200 OK\n")
                  .append("Content-Type: " + contentType + "\n");
              if (!testMissingLength) {
                responseContent.append("Content-Length: " + content2.length + "\n");
              }
              responseContent.append("\n");
              responseContent.flush();
              outputStream.write(content2);
              responseContent.append("\n--" + RESPONSE_BOUNDARY + "--\n\n");
            } else {
              responseContent.append("--" + RESPONSE_BOUNDARY + "\n")
                  .append("Content-Type: application/http\n")
                  .append("Content-Transfer-Encoding: binary\n")
                  .append("Content-ID: response-1\n\n")
                  .append("HTTP/1.1 " + ERROR_CODE + " Not Found\n")
                  .append("Content-Type: " + contentType + "\n");
                  if (!testMissingLength) {
                    responseContent.append("Content-Length: " + errorContent.length + "\n");
                  }
                  responseContent.append("\n");
                  responseContent.flush();
                  outputStream.write(errorContent);
                  responseContent.append("\n--" + RESPONSE_BOUNDARY + "--\n\n");
            }
          } else if (returnErrorAuthenticatedContent) {
            responseContent.append("Content-Type: application/http\n")
                .append("Content-Transfer-Encoding: binary\n").append("Content-ID: response-1\n\n");
            responseContent.append("HTTP/1.1 " + ERROR_CODE + " Not Found\n")
                .append("Content-Type: " + contentType + "\n");
            if (!testMissingLength) {
              responseContent.append("Content-Length: " + errorContent.length + "\n");
            }
            responseContent.append("\n");
            responseContent.flush();
            outputStream.write(errorContent);
            responseContent.append("\n--" + RESPONSE_BOUNDARY + "--\n\n");
          } else {
            responseContent.append("--" + RESPONSE_BOUNDARY + "\n")
                .append("Content-Type: application/http\n")
                .append("Content-Transfer-Encoding: binary\n").append("Content-ID: response-1\n\n")
                .append("HTTP/1.1 200 OK\n")
                .append("Content-Type: " + contentType + "\n");
            if (!testMissingLength) {
              responseContent.append("Content-Length: " + content1.length + "\n");
            }
            responseContent.append("\n");
            responseContent.flush();
            outputStream.write(content1);
            responseContent
                .append("\n--" + RESPONSE_BOUNDARY + "\n")
                .append("Content-Type: application/http\n")
                .append("Content-Transfer-Encoding: binary\n")
                .append("Content-ID: response-2\n\n");

            if (testServerError) {
              responseContent.append("HTTP/1.1 " + ERROR_CODE + " Not Found\n")
                  .append("Content-Type: " + contentType + "\n");
              if (!testMissingLength) {
                responseContent.append("Content-Length: " + errorContent.length + "\n");
              }
              responseContent.append("\n");
              responseContent.flush();
              outputStream.write(errorContent);
              responseContent.append("\n--" + RESPONSE_BOUNDARY + "--\n\n");
            } else if (testAuthenticationError) {
              responseContent.append("HTTP/1.1 401 Unauthorized\n")
                  .append("Content-Type: application/json; charset=UTF-8\n\n")
                  .append("--" + RESPONSE_BOUNDARY + "--\n\n");
            } else if (testRedirect && actualCalls == 1) {
              responseContent.append("HTTP/1.1 301 MovedPermanently\n")
                  .append("Content-Type: " + contentType + "\n")
                  .append("Location: http://redirect/location\n\n")
                  .append("--" + RESPONSE_BOUNDARY + "--\n\n");
            } else {
              responseContent.append("HTTP/1.1 200 OK\n")
                  .append("Content-Type: " + contentType + "\n");
                  if (!testMissingLength) {
                    responseContent.append("Content-Length: " + content2.length + "\n");
                  }
                  responseContent.append("\n");
                  responseContent.flush();
                  outputStream.write(content2);
                  responseContent.append("\n--" + RESPONSE_BOUNDARY + "--\n\n");
            }
          }
          responseContent.flush();
          response.setContent(outputStream.toByteArray());
          return response;
        }

        // Short-hand to encode a String as a UTF-8 byte array
        private byte[] utf8Encode(String string) {
View Full Code Here

    @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;
        }
      };
    }
View Full Code Here

      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);
            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 = 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;
        }
      };
    }
View Full Code Here

TOP

Related Classes of com.google.api.client.testing.http.MockLowLevelHttpResponse

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.