Java 类com.google.api.client.http.LowLevelHttpResponse 实例源码

项目:elasticsearch_my    文件:MockHttpTransport.java   
@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
    return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
            String rawPath = url;
            Map<String, String> params = new HashMap<>();

            int pathEndPos = url.indexOf('?');
            if (pathEndPos != -1) {
                rawPath = url.substring(0, pathEndPos);
                RestUtils.decodeQueryString(url, pathEndPos + 1, params);
            }

            Handler handler = handlers.retrieve(method + " " + rawPath, params);
            if (handler != null) {
                return handler.execute(rawPath, params, this);
            }
            return newMockError(RestStatus.INTERNAL_SERVER_ERROR, "Unable to handle request [method=" + method + ", url=" + url + "]");
        }
    };
}
项目:elasticsearch_my    文件:GceMockUtils.java   
protected static HttpTransport configureMock() {
    return new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, final String url) throws IOException {
            return new MockLowLevelHttpRequest() {
                @Override
                public LowLevelHttpResponse execute() throws IOException {
                    MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
                    response.setStatusCode(200);
                    response.setContentType(Json.MEDIA_TYPE);
                    if (url.startsWith(GCE_METADATA_URL)) {
                        logger.info("--> Simulate GCE Auth/Metadata response for [{}]", url);
                        response.setContent(readGoogleInternalJsonResponse(url));
                    } else {
                        logger.info("--> Simulate GCE API response for [{}]", url);
                        response.setContent(readGoogleApiJsonResponse(url));
                    }

                    return response;
                }
            };
        }
    };
}
项目:endpoints-management-java    文件:DefautKeyUriSupplierTest.java   
@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
  callCount ++;

  if (!HttpMethods.GET.equals(method) || !expectedUrl.equals(url)) {
    // Throw RuntimeException to fail the test.
    throw new RuntimeException();
  }

  return new MockLowLevelHttpRequest() {
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
      response.setStatusCode(HttpStatusCodes.STATUS_CODE_OK);
      response.setContentType(Json.MEDIA_TYPE);
      response.setContent(jsonResponse);
      return response;
    }
  };
}
项目:endpoints-management-java    文件:DefaultJwksSupplierTest.java   
@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
  return new MockLowLevelHttpRequest() {
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      if (ioException != null) {
        throw ioException;
      }
      MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
      response.setStatusCode(HttpStatus.SC_ACCEPTED);
      response.setContentType(Json.MEDIA_TYPE);
      response.setContent(content);
      return response;
    }
  };
}
项目:dnsimple-java    文件:DnsimpleTestBase.java   
/**
 * Return a Client that is mocked to return the given HTTP response.
 *
 * @param httpResponse The full HTTP response data
 * @return The Client instance
 */
public Client mockClient(final String httpResponse) {
  Client client = new Client();

  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          return mockResponse(response, httpResponse);
        }
      };
    }
  };

  client.setTransport(transport);

  return client;
}
项目:endpoints-java    文件:GoogleAuthTest.java   
private HttpRequest constructHttpRequest(final String content) 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);
          return result;
        }
      };
    }
  };
  return transport.createRequestFactory().buildGetRequest(new GenericUrl("https://google.com"))
      .setParser(new JsonObjectParser(new JacksonFactory()));
}
项目:kafka-connect-splunk    文件:SplunkHttpSinkTaskTest.java   
@Test
public void normal() throws IOException {
  Collection<SinkRecord> sinkRecords = new ArrayList<>();
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp", "sourcetype", "txt", "index", "main"));

  final LowLevelHttpRequest httpRequest = mock(LowLevelHttpRequest.class, CALLS_REAL_METHODS);
  LowLevelHttpResponse httpResponse = getResponse(200);
  when(httpRequest.execute()).thenReturn(httpResponse);

  this.task.transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return httpRequest;
    }
  };

  this.task.httpRequestFactory = this.task.transport.createRequestFactory(this.task.httpRequestInitializer);
  this.task.put(sinkRecords);
}
项目:kafka-connect-splunk    文件:SplunkHttpSinkTaskTest.java   
@Test
public void contentLengthTooLarge() throws IOException {
  Collection<SinkRecord> sinkRecords = new ArrayList<>();
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp", "sourcetype", "txt", "index", "main"));

  final LowLevelHttpRequest httpRequest = mock(LowLevelHttpRequest.class, CALLS_REAL_METHODS);
  LowLevelHttpResponse httpResponse = getResponse(417);
  when(httpResponse.getContentType()).thenReturn("text/html");
  when(httpRequest.execute()).thenReturn(httpResponse);

  this.task.transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return httpRequest;
    }
  };

  this.task.httpRequestFactory = this.task.transport.createRequestFactory(this.task.httpRequestInitializer);
  assertThrows(org.apache.kafka.connect.errors.ConnectException.class, () -> this.task.put(sinkRecords));
}
项目:kafka-connect-splunk    文件:SplunkHttpSinkTaskTest.java   
@Test
public void invalidToken() throws IOException {
  Collection<SinkRecord> sinkRecords = new ArrayList<>();
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp", "sourcetype", "txt", "index", "main"));

  final LowLevelHttpRequest httpRequest = mock(LowLevelHttpRequest.class, CALLS_REAL_METHODS);
  LowLevelHttpResponse httpResponse = getResponse(403);
  when(httpRequest.execute()).thenReturn(httpResponse);

  this.task.transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return httpRequest;
    }
  };

  this.task.httpRequestFactory = this.task.transport.createRequestFactory(this.task.httpRequestInitializer);
  assertThrows(org.apache.kafka.connect.errors.ConnectException.class, () -> this.task.put(sinkRecords));
}
项目:kafka-connect-splunk    文件:SplunkHttpSinkTaskTest.java   
@Test
public void invalidIndex() throws IOException {
  Collection<SinkRecord> sinkRecords = new ArrayList<>();
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp", "sourcetype", "txt", "index", "main"));

  final LowLevelHttpRequest httpRequest = mock(LowLevelHttpRequest.class, CALLS_REAL_METHODS);
  LowLevelHttpResponse httpResponse = getResponse(400);
  when(httpRequest.execute()).thenReturn(httpResponse);

  this.task.transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return httpRequest;
    }
  };

  this.task.httpRequestFactory = this.task.transport.createRequestFactory(this.task.httpRequestInitializer);
  assertThrows(org.apache.kafka.connect.errors.ConnectException.class, () -> this.task.put(sinkRecords));
}
项目:beam    文件:BigQueryServicesImplTest.java   
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);

  // A mock transport that lets us mock the API responses.
  MockHttpTransport transport =
      new MockHttpTransport.Builder()
          .setLowLevelHttpRequest(
              new MockLowLevelHttpRequest() {
                @Override
                public LowLevelHttpResponse execute() throws IOException {
                  return response;
                }
              })
          .build();

  // A sample BigQuery API client that uses default JsonFactory and RetryHttpInitializer.
  bigquery =
      new Bigquery.Builder(
              transport, Transport.getJsonFactory(), new RetryHttpRequestInitializer())
          .build();
}
项目:nomulus    文件:IcannHttpReporterTest.java   
private MockHttpTransport createMockTransport (final ByteSource iirdeaResponse) {
  return new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      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;
    }
  };
}
项目:nomulus    文件:DirectoryGroupsConnectionTest.java   
/** 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) throws IOException {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          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());
}
项目:java-docs-samples    文件:FirebaseChannelTest.java   
@Test
public void sendFirebaseMessage_create() throws Exception {
  // Mock out the firebase response. See
  // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing
  MockHttpTransport mockHttpTransport = spy(new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          response.setStatusCode(200);
          return response;
        }
      };
    }
  });
  FirebaseChannel.getInstance(null).httpTransport = mockHttpTransport;

  firebaseChannel.sendFirebaseMessage("my_key", new Game());

  verify(mockHttpTransport, times(1)).buildRequest(
      "PATCH", FIREBASE_DB_URL + "/channels/my_key.json");
}
项目:java-docs-samples    文件:FirebaseChannelTest.java   
@Test
public void sendFirebaseMessage_delete() throws Exception {
  // Mock out the firebase response. See
  // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing
  MockHttpTransport mockHttpTransport = spy(new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          response.setStatusCode(200);
          return response;
        }
      };
    }
  });
  FirebaseChannel.getInstance(null).httpTransport = mockHttpTransport;

  firebaseChannel.sendFirebaseMessage("my_key", null);

  verify(mockHttpTransport, times(1)).buildRequest(
      "DELETE", FIREBASE_DB_URL + "/channels/my_key.json");
}
项目:java-docs-samples    文件:FirebaseChannelTest.java   
@Test
public void firebasePut() throws Exception {
  // Mock out the firebase response. See
  // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing
  MockHttpTransport mockHttpTransport = spy(new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          response.setStatusCode(200);
          return response;
        }
      };
    }
  });
  FirebaseChannel.getInstance(null).httpTransport = mockHttpTransport;
  Game game = new Game();

  firebaseChannel.firebasePut(FIREBASE_DB_URL + "/my/path", game);

  verify(mockHttpTransport, times(1)).buildRequest("PUT", FIREBASE_DB_URL + "/my/path");
}
项目:java-docs-samples    文件:FirebaseChannelTest.java   
@Test
public void firebasePatch() throws Exception {
  // Mock out the firebase response. See
  // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing
  MockHttpTransport mockHttpTransport = spy(new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          response.setStatusCode(200);
          return response;
        }
      };
    }
  });
  FirebaseChannel.getInstance(null).httpTransport = mockHttpTransport;
  Game game = new Game();

  firebaseChannel.firebasePatch(FIREBASE_DB_URL + "/my/path", game);

  verify(mockHttpTransport, times(1)).buildRequest("PATCH", FIREBASE_DB_URL + "/my/path");
}
项目:java-docs-samples    文件:FirebaseChannelTest.java   
@Test
public void firebasePost() throws Exception {
  // Mock out the firebase response. See
  // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing
  MockHttpTransport mockHttpTransport = spy(new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          response.setStatusCode(200);
          return response;
        }
      };
    }
  });
  FirebaseChannel.getInstance(null).httpTransport = mockHttpTransport;
  Game game = new Game();

  firebaseChannel.firebasePost(FIREBASE_DB_URL + "/my/path", game);

  verify(mockHttpTransport, times(1)).buildRequest("POST", FIREBASE_DB_URL + "/my/path");
}
项目:java-docs-samples    文件:FirebaseChannelTest.java   
@Test
public void firebaseGet() throws Exception {
  // Mock out the firebase response. See
  // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing
  MockHttpTransport mockHttpTransport = spy(new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          response.setStatusCode(200);
          return response;
        }
      };
    }
  });
  FirebaseChannel.getInstance(null).httpTransport = mockHttpTransport;

  firebaseChannel.firebaseGet(FIREBASE_DB_URL + "/my/path");

  verify(mockHttpTransport, times(1)).buildRequest("GET", FIREBASE_DB_URL + "/my/path");
}
项目:java-docs-samples    文件:FirebaseChannelTest.java   
@Test
public void firebaseDelete() throws Exception {
  // Mock out the firebase response. See
  // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing
  MockHttpTransport mockHttpTransport = spy(new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          response.setStatusCode(200);
          return response;
        }
      };
    }
  });
  FirebaseChannel.getInstance(null).httpTransport = mockHttpTransport;

  firebaseChannel.firebaseDelete(FIREBASE_DB_URL + "/my/path");

  verify(mockHttpTransport, times(1)).buildRequest("DELETE", FIREBASE_DB_URL + "/my/path");
}
项目:java-docs-samples    文件:FirebaseChannelTest.java   
@Test
public void firebaseGet() throws Exception {
  // Mock out the firebase response. See
  // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing
  MockHttpTransport mockHttpTransport =
      spy(
          new MockHttpTransport() {
            @Override
            public LowLevelHttpRequest buildRequest(String method, String url)
                throws IOException {
              return new MockLowLevelHttpRequest() {
                @Override
                public LowLevelHttpResponse execute() throws IOException {
                  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
                  response.setStatusCode(200);
                  return response;
                }
              };
            }
          });
  FirebaseChannel.getInstance().httpTransport = mockHttpTransport;

  firebaseChannel.firebaseGet(FIREBASE_DB_URL + "/my/path");

  verify(mockHttpTransport, times(1)).buildRequest("GET", FIREBASE_DB_URL + "/my/path");
}
项目:java-docs-samples    文件:FirebaseChannelTest.java   
@Test
public void firebaseDelete() throws Exception {
  // Mock out the firebase response. See
  // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing
  MockHttpTransport mockHttpTransport =
      spy(
          new MockHttpTransport() {
            @Override
            public LowLevelHttpRequest buildRequest(String method, String url)
                throws IOException {
              return new MockLowLevelHttpRequest() {
                @Override
                public LowLevelHttpResponse execute() throws IOException {
                  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
                  response.setStatusCode(200);
                  return response;
                }
              };
            }
          });
  FirebaseChannel.getInstance().httpTransport = mockHttpTransport;

  firebaseChannel.firebaseDelete(FIREBASE_DB_URL + "/my/path");

  verify(mockHttpTransport, times(1)).buildRequest("DELETE", FIREBASE_DB_URL + "/my/path");
}
项目:java-docs-samples    文件:TextAppTest.java   
@Before public void setUp() throws Exception {
  // Mock out the vision service for unit tests.
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          response.setStatusCode(200);
          response.setContentType(Json.MEDIA_TYPE);
          response.setContent("{\"responses\": [{\"textAnnotations\": []}]}");
          return response;
        }
      };
    }
  };
  Vision vision = new Vision(transport, jsonFactory, null);

  appUnderTest = new TextApp(vision, null /* index */);
}
项目:slamon-java-lib    文件:AfmCommunicatorTests.java   
@Test
public void testServerError() throws Exception {
    mockCommunicator.httpRequests = new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
            return new MockLowLevelHttpRequest() {
                public LowLevelHttpResponse execute() throws IOException {
                    MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
                    result.setStatusCode(500);
                    return result;
                }
            };
        }
    }.createRequestFactory();
    expectedException.expect(AfmCommunicator.TemporaryException.class);
    mockCommunicator.requestTasks("", "", new HashMap<String, Integer>(), 1, new ArrayList<Task>());
}
项目:slamon-java-lib    文件:AfmCommunicatorTests.java   
@Test
public void testClientError() throws Exception {
    mockCommunicator.httpRequests = new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
            return new MockLowLevelHttpRequest() {
                public LowLevelHttpResponse execute() throws IOException {
                    MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
                    result.setStatusCode(400);
                    return result;
                }
            };
        }

    }.createRequestFactory();
    expectedException.expect(AfmCommunicator.FatalException.class);
    mockCommunicator.requestTasks("", "", new HashMap<String, Integer>(), 1, new ArrayList<Task>());
}
项目:SLAMon    文件:AfmCommunicatorTests.java   
@Test
public void testServerError() throws Exception {
    mockCommunicator.httpRequests = new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
            return new MockLowLevelHttpRequest() {
                public LowLevelHttpResponse execute() throws IOException {
                    MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
                    result.setStatusCode(500);
                    return result;
                }
            };
        }
    }.createRequestFactory();
    expectedException.expect(AfmCommunicator.TemporaryException.class);
    mockCommunicator.requestTasks("", "", new HashMap<String, Integer>(), 1, new ArrayList<Task>());
}
项目:SLAMon    文件:AfmCommunicatorTests.java   
@Test
public void testClientError() throws Exception {
    mockCommunicator.httpRequests = new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
            return new MockLowLevelHttpRequest() {
                public LowLevelHttpResponse execute() throws IOException {
                    MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
                    result.setStatusCode(400);
                    return result;
                }
            };
        }

    }.createRequestFactory();
    expectedException.expect(AfmCommunicator.FatalException.class);
    mockCommunicator.requestTasks("", "", new HashMap<String, Integer>(), 1, new ArrayList<Task>());
}
项目:SLAMon    文件:JupsTest.java   
@Test
public void testPostIOError() throws InterruptedException, ExecutionException, TimeoutException {

    Jups jups = new Jups(HttpTesting.SIMPLE_URL, "APP_ID", "SECRET");
    jups.mHttpTransport = new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
            return new MockLowLevelHttpRequest() {
                @Override
                public LowLevelHttpResponse execute() throws IOException {
                    throw new IOException("test");
                }
            };
        }
    };

    String result = jups.send(new PushNotification("MASTER_VARIANT_ID", "VARIANT_ID", "ALERT_MESSAGE", "SOUND"), "TEST_UUID");
    assertEquals("Push notification should have failed", result, "failed");
}
项目:SLAMon    文件:AfmTest.java   
@Test
public void testPostIOError() throws InterruptedException, ExecutionException, TimeoutException {

    Afm afm = Afm.get(HttpTesting.SIMPLE_URL);
    afm.mHttpTransport = new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
            return new MockLowLevelHttpRequest() {
                @Override
                public LowLevelHttpResponse execute() throws IOException {
                    throw new IOException("test");
                }
            };
        }
    };

    FutureCallback result = new FutureCallback();
    afm.postTask(new Task("TASK_UUID", "TEST_UUID", "wait", 1), result);

    Task resultTask = result.task.get(5000, TimeUnit.MILLISECONDS);
    assertFalse("Task should have failed", result.succeeded);
    assertNotNull("Task should have been returned.", resultTask);
    assertNotNull("Error should be set.", resultTask.task_error);
}
项目:SLAMon    文件:HttpGetHandlerTest.java   
@Test
public void testHttpError() throws Exception {
    handler.requestFactory = new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
            return new MockLowLevelHttpRequest() {
                @Override
                public LowLevelHttpResponse execute() throws IOException {
                    return new MockLowLevelHttpResponse().setStatusCode(500);
                }
            };
        }
    }.createRequestFactory();
    Map<String, Object> map = new HashMap<>();
    map.put("url", "http://url.to.be.tested");
    expectedException.expect(HttpResponseException.class);
    Map<String, Object> result = handler.execute(map);
}
项目:SLAMon    文件:HttpGetHandlerTest.java   
@Test
public void testHttpOk() throws Exception {
    handler.requestFactory = new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
            return new MockLowLevelHttpRequest() {
                @Override
                public LowLevelHttpResponse execute() throws IOException {
                    return new MockLowLevelHttpResponse().setStatusCode(200);
                }
            };
        }
    }.createRequestFactory();
    Map<String, Object> map = new HashMap<>();
    map.put("url", "http://url.to.be.tested");
    Map<String, Object> result = handler.execute(map);
    assertEquals(200, result.get("status"));
}
项目:rides-java-sdk    文件:OAuth2CredentialsTest.java   
@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;
        }
    };
}
项目:webhose-java    文件:WebhoseClientTest.java   
@Test
public void testSimpleRequest() throws IOException {
    WebhoseClient.HTTP_TRANSPORT = new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
            return new MockLowLevelHttpRequest() {
                @Override
                public LowLevelHttpResponse execute() throws IOException {
                    MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
                    response.setStatusCode(200);
                    response.setContentType("application/json");
                    response.setContent("{\"totalResults\":123}");
                    return response;
                }
            };
        }
    };


    WebhoseClient client = new WebhoseClient("test-api-key");
    WebhoseResponse apple = client.search("apple");
    assertThat(apple.totalResults, is(123));
}
项目:bigdata-interop    文件:GoogleCloudStorageTest.java   
private HttpResponse createFakeResponse(final String responseHeader, final String responseValue,
                                        final InputStream content) throws IOException {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      MockLowLevelHttpRequest req = new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          return new MockLowLevelHttpResponse()
              .addHeader(responseHeader, responseValue)
              .setContent(content);
        }
      };
      return req;
    }
  };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  return request.execute();
}
项目:Orpheus    文件:OkLowLevelHttpRequest.java   
@Override
public LowLevelHttpResponse execute() throws IOException {
    if (getStreamingContent() != null) {
        String contentType = getContentType();
        String contentEncoding = getContentEncoding();
        if (contentEncoding != null) {
            addHeader("Content-Encoding", contentEncoding);
        }
        long contentLength = getContentLength();
        //TODO handle upload properly
        ByteArrayOutputStream out = new ByteArrayOutputStream(contentLength > 0 ? (int) contentLength : 1024);
        try {
            getStreamingContent().writeTo(out);
            MediaType mediaType = MediaType.parse(contentType);
            RequestBody body = RequestBody.create(mediaType, out.toByteArray());
            builder.method(method, body);
        } finally {
            out.close();
        }
    } else {
        builder.method(method, null);
    }
    Response response = okClient.newCall(builder.build()).execute();
    return new OkLowLevelHttpResponse(response);
}
项目:go-puppet-forge-poller    文件:ForgeTest.java   
@Before
public void setUp() throws Exception {
    httpTransport = new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, final String url) throws IOException {
            return new MockLowLevelHttpRequest() {
                @Override
                public LowLevelHttpResponse execute() throws IOException {
                    assertThat("Unexpected request to " + url, responses.keySet(), hasItem(url));
                    return responses.get(url);
                }
            };
        }
    };

    forge = new Forge(new URL("http://forge.example.com/forge"), httpTransport);
}
项目:googleads-java-lib    文件:BatchJobUploaderTest.java   
/**
 * Tests that IOExceptions from executing an upload request are propagated properly.
 */
@SuppressWarnings("rawtypes")
@Test
public void testUploadBatchJobOperations_ioException_fails() throws Exception {
  final IOException ioException = new IOException("mock IO exception");
  MockLowLevelHttpRequest lowLevelHttpRequest = new MockLowLevelHttpRequest(){
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      throw ioException;
    }
  };
  when(uploadBodyProvider.getHttpContent(request, true, true))
      .thenReturn(new ByteArrayContent(null, "foo".getBytes(UTF_8)));
  MockHttpTransport transport = new MockHttpTransport.Builder()
      .setLowLevelHttpRequest(lowLevelHttpRequest).build();
  uploader = new BatchJobUploader(adWordsSession, transport, batchJobLogger);
  BatchJobUploadStatus uploadStatus =
      new BatchJobUploadStatus(0, URI.create("http://www.example.com"));
  thrown.expect(BatchJobException.class);
  thrown.expectCause(Matchers.sameInstance(ioException));
  uploader.uploadIncrementalBatchJobOperations(request, true, uploadStatus);
}
项目:googleads-java-lib    文件:BatchJobUploaderTest.java   
/**
 * Tests that IOExceptions from initiating an upload are propagated properly.
 */
@SuppressWarnings("rawtypes")
@Test
public void testUploadBatchJobOperations_initiateFails_fails() throws Exception {
  final IOException ioException = new IOException("mock IO exception");
  MockLowLevelHttpRequest lowLevelHttpRequest = new MockLowLevelHttpRequest(){
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      throw ioException;
    }
  };
  when(uploadBodyProvider.getHttpContent(request, true, true))
      .thenReturn(new ByteArrayContent(null, "foo".getBytes(UTF_8)));
  MockHttpTransport transport = new MockHttpTransport.Builder()
      .setLowLevelHttpRequest(lowLevelHttpRequest).build();
  uploader = new BatchJobUploader(adWordsSession, transport, batchJobLogger);
  thrown.expect(BatchJobException.class);
  thrown.expectCause(Matchers.sameInstance(ioException));
  thrown.expectMessage("initiate upload");
  uploader.uploadIncrementalBatchJobOperations(request, true, new BatchJobUploadStatus(
      0, URI.create("http://www.example.com")));
}
项目:endpoints-management-java    文件:ServiceConfigSupplierTest.java   
@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
  return new MockLowLevelHttpRequest() {
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      Response storedResponse = responses.removeFirst();
      MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
      response.setStatusCode(storedResponse.statusCode);
      response.setContentType(Json.MEDIA_TYPE);
      response.setContent(storedResponse.content);
      return response;
    }
  };
}
项目:endpoints-management-java    文件:ControlFilterTest.java   
@Override
public LowLevelHttpResponse execute() throws IOException {
  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
  if (hasMetadata) {
    response.addHeader("Metadata-Flavor", "Google");
    return response;
  }
  throw new IOException("emulated server exception");
}