org.easymock.Capture Java Examples
The following examples show how to use
org.easymock.Capture.
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: SchedulerLifecycleTest.java From attic-aurora with Apache License 2.0 | 6 votes |
@Test public void testAutoFailover() throws Exception { // Test that when timed failover is initiated, cleanup is done in a way that should allow the // application to tear down cleanly. Specifically, neglecting to call leaderControl.leave() // can result in a lame duck scheduler process. storageUtil.storage.prepare(); expectLoadStorage(); Capture<Runnable> triggerFailover = createCapture(); delayedActions.onAutoFailover(capture(triggerFailover)); delayedActions.onRegistrationTimeout(EasyMock.anyObject()); expectInitializeDriver(); expectFullStartup(); expectLeaderShutdown(); replayAndCreateLifecycle(); LeadershipListener leaderListener = schedulerLifecycle.prepare(); assertEquals(1, statsProvider.getValue(stateGaugeName(State.STORAGE_PREPARED))); leaderListener.onLeading(leaderControl); assertEquals(1, statsProvider.getValue(stateGaugeName(State.LEADER_AWAITING_REGISTRATION))); schedulerLifecycle.registered(new DriverRegistered()); assertEquals(1, statsProvider.getValue(stateGaugeName(State.ACTIVE))); triggerFailover.getValue().run(); }
Example #2
Source File: TestPlaceServiceLevelDowngradeListener.java From arcusplatform with Apache License 2.0 | 6 votes |
@Test public void testDoOnMessageServiceLevelBasic() { PlatformMessage message = createListenerAndMessage(ServiceLevel.BASIC); //setup mocks EasyMock.expect(mockCache.isServiceLevelChange(message)).andReturn(true); EasyMock.expect(mockVideoDao.countByTag(curPlaceId, VideoConstants.TAG_FAVORITE)).andReturn(5l); Capture<Date> deleteTimeCapture = EasyMock.newCapture(CaptureType.LAST); mockVideoDao.addToPurgePinnedRecording(EasyMock.eq(curPlaceId), EasyMock.capture(deleteTimeCapture)); EasyMock.expectLastCall(); replay(); long now = System.currentTimeMillis(); theListener.onMessage(message); Date deleteTime = deleteTimeCapture.getValue(); int deleteDelay = (int) TimeUnit.MILLISECONDS.toDays(deleteTime.getTime() - now); assertEquals(theListener.getPurgePinnedVideosAfterDays(), deleteDelay); verify(); }
Example #3
Source File: BatchUploadProcessorTest.java From training with MIT License | 6 votes |
@Test public void whenNoAppointmentExistsForExistingConsumers_aNewOneShotAppointmentIsCreatedOnTheFirstAvailableServiceSlot() { Capture<Consumer> consumerCapture = new Capture<Consumer>(); Capture<TimeRange> slotCapture = new Capture<TimeRange>(); Appointment appointment = new Appointment(); reset(consumerService); expectFindConsumerByEmail(); expectGetConsumerAppointments(); expect(consumerService.createAppointmentOnServiceSlot(capture(consumerCapture), eq(appointmentDate), capture(slotCapture))).andReturn(appointment); consumerPlatform.getServiceSlots().add(new TimeRange("16:00", "18:00")); run(newLine()); TimeRange slot = slotCapture.getValue(); assertEquals("16:00", slot.getMin()); assertEquals("18:00", slot.getMax()); }
Example #4
Source File: TestModelStore.java From arcusplatform with Apache License 2.0 | 6 votes |
@Test public void testRemoveObjectListener() { Capture<RuleEvent> eventRef = EasyMock.newCapture(); Consumer<RuleEvent> listener = EasyMock.createMock(Consumer.class); listener.accept(EasyMock.capture(eventRef)); EasyMock.expectLastCall(); EasyMock.replay(listener); MessageBody body = MessageBody .buildMessage(Capability.EVENT_DELETED, ImmutableMap.of()); PlatformMessage message = PlatformMessage.createBroadcast(body, address); RuleModelStore store = new RuleModelStore(); store.addModel(ImmutableList.of(attributes)); store.addListener(listener); store.update(message); ModelRemovedEvent event = (ModelRemovedEvent) eventRef.getValue(); assertEquals(RuleEventType.MODEL_REMOVED, event.getType()); assertEquals(address, event.getModel().getAddress()); assertEquals(id, event.getModel().getAttribute(Capability.ATTR_ID)); assertEquals(DeviceCapability.NAMESPACE, event.getModel().getAttribute(Capability.ATTR_TYPE)); EasyMock.verify(listener); }
Example #5
Source File: TestPlatformAlarmIncidentService.java From arcusplatform with Apache License 2.0 | 6 votes |
@Test public void testEscalateAlertWhileAlerting() { IncidentTrigger trigger = IncidentFixtures.createIncidentTrigger(AlertType.CO); AlarmIncident current = IncidentFixtures.createSecurityAlarm(this.serviceLevel); expectCurrentAndReturn(current); Capture<AlarmIncident> incidentCapture = expectUpdate(); replay(); service.addAlert(context, CarbonMonoxideAlarm.NAME, ImmutableList.of(trigger)); AlarmIncident incident = incidentCapture.getValue(); assertIncidentMonitored(incident); assertIncidentTrackers(incident, TrackerState.PREALERT, TrackerState.ALERT); assertIncidentAlert(incident, AlertType.CO, AlertType.SECURITY); assertBroadcastChanged(incident); assertAddAlarm(incident, AlertType.CO, ImmutableList.of(AlertType.CO, AlertType.SECURITY), ImmutableList.of(trigger)); assertBroadcastAlert(AlertType.CO, ImmutableList.of(trigger)); assertNoMessages(); verify(); }
Example #6
Source File: TestPlatformAlarmIncidentService.java From arcusplatform with Apache License 2.0 | 6 votes |
@Test public void testAddAlertCreatesNewIncident() { expectCurrentAndReturnNull(); List<IncidentTrigger> triggers = ImmutableList.of(IncidentFixtures.createIncidentTrigger(AlertType.WATER, IncidentTrigger.EVENT_LEAK)); Capture<AlarmIncident> incidentCapture = expectUpdate(); replay(); service.addAlert(context, WaterAlarm.NAME, triggers); AlarmIncident incident = incidentCapture.getValue(); assertFalse(incident.isMonitored()); //water is not monitored assertIncidentTrackers(incident, TrackerState.ALERT); assertIncidentAlert(incident, AlertType.WATER); assertBroadcastAdded(incident); assertAddAlarm(incident, AlertType.WATER, ImmutableList.of(AlertType.WATER), triggers); assertBroadcastAlert(AlertType.WATER, triggers); assertNoMessages(); verify(); }
Example #7
Source File: SubsystemTestCase.java From arcusplatform with Apache License 2.0 | 6 votes |
private boolean containsMessageWithAttrs(Capture<MessageBody> capturedMsg, final String msgType, final Map<String,Object>attrs) { FluentIterable<MessageBody> matched = FluentIterable.from(capturedMsg.getValues()).filter(new Predicate<MessageBody>() { public boolean apply(MessageBody message) { if(!message.getMessageType().equals(msgType)){ return false; } for(Map.Entry<String,Object>attr:attrs.entrySet()){ if(attr.getValue() == NULL_VALUE) { if( message.getAttributes().get(attr.getKey()) != null ) { System.out.println(String.format("[%s] does not match [expected, actual]=[ %s, %s]",attr.getKey(), null, message.getAttributes().get(attr.getKey()))); return false; }else { continue; } }else if(!attr.getValue().equals(message.getAttributes().get(attr.getKey()))){ System.out.println(String.format("[%s] does not match [expected, actual]=[ %s, %s]",attr.getKey(), attr.getValue(), message.getAttributes().get(attr.getKey()))); return false; } } return true; } }); boolean isMatched = (matched != null && matched.size() > 0); return isMatched; }
Example #8
Source File: CloudantStoreTest.java From todo-apps with Apache License 2.0 | 6 votes |
@Test public void testGet() throws Exception { IMocksControl control = createControl(); Response resp = control.createMock(Response.class); expect(resp.getStatus()).andReturn(200).times(3); Capture<Class<CloudantToDo>> classCapture = new Capture<Class<CloudantToDo>>(); expect(resp.readEntity(capture(classCapture))).andReturn(ctd1); replay(resp); WebTarget wt = createMockWebTarget(); Invocation.Builder builder = createBuilder(); expect(builder.get()).andReturn(resp).times(3); replay(builder); expect(wt.path(eq("bluemix-todo"))).andReturn(wt).times(2); expect(wt.path(eq("todos"))).andReturn(wt); expect(wt.path(eq("_design"))).andReturn(wt).times(1); expect(wt.path(eq("123"))).andReturn(wt); expect(wt.request(eq("application/json"))).andReturn(builder).anyTimes(); replay(wt); CloudantStore store = new CloudantStore(wt); assertEquals(ctd1.getToDo(), store.get("123")); assertEquals(CloudantToDo.class, classCapture.getValue()); verify(resp); verify(wt); verify(builder); }
Example #9
Source File: TestBasicNotificationStrategy.java From arcusplatform with Apache License 2.0 | 6 votes |
@Test public void testMultipleTriggersOfSameTypeOnlyIssueOneNotification() { Capture<CallTreeContext> contextCapture = EasyMock.newCapture(CaptureType.ALL); callTreeExecutor.notifyOwner(EasyMock.capture(contextCapture)); EasyMock.expectLastCall(); setupCallTree(1, callTreeEntry(UUID.randomUUID(), true)); Trigger t = setupTrigger(UUID.randomUUID(), AlertType.CO, "Some Device", "Some Dev Type Hint", 1); Trigger t2 = setupTrigger(UUID.randomUUID(), AlertType.CO, "Some Device", "Some Dev Type Hint", 0); replay(); AlarmIncident incident = incidentBuilder() .withAlert(AlertType.CO) .build(); strategy.execute(incident.getAddress(), incident.getPlaceId(), ImmutableList.of(t, t2)); List<CallTreeContext> contexts = contextCapture.getValues(); assertEquals(1, contexts.size()); assertCallTreeContext(contexts.get(0), NotificationConstants.CO_KEY, NotificationCapability.NotifyRequest.PRIORITY_CRITICAL); verify(); }
Example #10
Source File: CursorCallbackTest.java From mongodb-async-driver with Apache License 2.0 | 6 votes |
/** * Test method for {@link CursorCallback#verify(Reply)} . */ @SuppressWarnings("unchecked") @Test public void testVerifyOnQueryFailed() { final List<Document> docs = Collections.emptyList(); final Query q = new Query("db", "c", BuilderFactory.start().build(), null, 0, 0, 0, false, ReadPreference.PRIMARY, false, false, false, false); final Reply reply = new Reply(0, 0, 0, docs, false, false, true, false); final Callback<MongoIterator<Document>> mockCallback = createMock(Callback.class); final Capture<Throwable> capture = new Capture<Throwable>(); mockCallback.exception(capture(capture)); replay(mockCallback); final CursorCallback callback = new CursorCallback(null, q, false, mockCallback); callback.callback(reply); verify(mockCallback); final Throwable thrown = capture.getValue(); assertThat(thrown, instanceOf(QueryFailedException.class)); }
Example #11
Source File: TestHubAlarmIncidentService.java From arcusplatform with Apache License 2.0 | 6 votes |
@Test public void testAddPreAlertCreatesNewIncident() { expectFindByAndReturnNull(incidentId); List<IncidentTrigger> triggers = ImmutableList.of( IncidentFixtures.createIncidentTrigger(AlertType.SECURITY, IncidentTrigger.EVENT_MOTION), IncidentFixtures.createIncidentTrigger(AlertType.SECURITY, IncidentTrigger.EVENT_MOTION) ); Capture<AlarmIncident> incidentCapture = expectUpdate(); replay(); Date prealert = new Date(); service.addPreAlert(context, SecurityAlarm.NAME, prealert, triggers); AlarmIncident incident = incidentCapture.getValue(); assertIncidentTrackers(incident, TrackerState.PREALERT); assertIncidentPreAlert(incident, prealert); assertBroadcastAdded(incident); assertNoMessages(); verify(); }
Example #12
Source File: TestWBPageModuleController.java From cms with Apache License 2.0 | 6 votes |
@Test public void test_delete_noKey() { try { Object key = EasyMock.expect(requestMock.getAttribute("key")).andReturn(null); String returnJson = "{}"; Capture<HttpServletResponse> captureHttpResponse = new Capture<HttpServletResponse>(); Capture<String> captureData = new Capture<String>(); Capture<Map<String, String>> captureErrors = new Capture<Map<String,String>>(); httpServletToolboxMock.writeBodyResponseAsJson(EasyMock.capture(captureHttpResponse), EasyMock.capture(captureData), EasyMock.capture(captureErrors)); EasyMock.replay(httpServletToolboxMock, requestMock, responseMock, jsonObjectConverterMock, validatorMock, adminStorageMock, objectForControllerMock); controllerForTest.delete(requestMock, responseMock, "/abc"); EasyMock.verify(httpServletToolboxMock, requestMock, responseMock, jsonObjectConverterMock, validatorMock, adminStorageMock, objectForControllerMock); assertTrue (captureErrors.getValue().get("").compareTo(WPBErrors.WB_CANT_DELETE_RECORD) == 0); assertTrue (captureData.getValue().compareTo(returnJson) == 0); assertTrue (captureHttpResponse.getValue() == responseMock); } catch (Exception e) { assertTrue(false); } }
Example #13
Source File: TaskHistoryPrunerTest.java From attic-aurora with Apache License 2.0 | 6 votes |
@Test public void testActivateFutureAndExceedHistoryGoal() { IScheduledTask running = makeTask("a", RUNNING); IScheduledTask killed = copy(running, KILLED); expectNoImmediatePrune(ImmutableSet.of(running)); Capture<Runnable> delayedDelete = expectDefaultDelayedPrune(); // Expect task "a" to be pruned when future is activated. expectDeleteTasks("a"); control.replay(); // Capture future for inactive task "a" changeState(running, killed); clock.advance(ONE_HOUR); assertEquals(0L, statsProvider.getValue(TASKS_PRUNED)); // Execute future to prune task "a" from the system. delayedDelete.getValue().run(); assertEquals(1L, statsProvider.getValue(TASKS_PRUNED)); }
Example #14
Source File: TestPhoenixTransactSQL.java From ambari-metrics with Apache License 2.0 | 6 votes |
@Test public void testPrepareGetAggregatePrecisionHours() throws SQLException { Condition condition = new DefaultCondition( new ArrayList<>(Arrays.asList("cpu_user", "mem_free")), Collections.singletonList("h1"), "a1", "i1", 1407959718L, 1407959918L, Precision.HOURS, null, false); Connection connection = createNiceMock(Connection.class); PreparedStatement preparedStatement = createNiceMock(PreparedStatement.class); Capture<String> stmtCapture = new Capture<String>(); expect(connection.prepareStatement(EasyMock.and(EasyMock.anyString(), EasyMock.capture(stmtCapture)))) .andReturn(preparedStatement); replay(connection, preparedStatement); PhoenixTransactSQL.prepareGetAggregateSqlStmt(connection, condition); String stmt = stmtCapture.getValue(); Assert.assertTrue(stmt.contains("FROM METRIC_AGGREGATE_HOURLY_UUID")); Assert.assertNull(condition.getLimit()); verify(connection, preparedStatement); }
Example #15
Source File: PaymentChannelServerTest.java From bcm-android with GNU General Public License v3.0 | 5 votes |
@Test public void shouldTruncateTooLargeTimeWindow() { final int maxTimeWindow = 40000; final int timeWindow = maxTimeWindow + 1; final TwoWayChannelMessage message = createClientVersionMessage(timeWindow); final Capture<TwoWayChannelMessage> initiateCapture = new Capture<>(); connection.sendToClient(capture(initiateCapture)); replay(connection); dut = new PaymentChannelServer(broadcaster, wallet, Coin.CENT, new PaymentChannelServer.DefaultServerChannelProperties() { @Override public long getMaxTimeWindow() { return maxTimeWindow; } @Override public long getMinTimeWindow() { return 20000; } }, connection); dut.connectionOpen(); dut.receiveMessage(message); long expectedExpire = Utils.currentTimeSeconds() + maxTimeWindow; assertServerVersion(); assertExpireTime(expectedExpire, initiateCapture); }
Example #16
Source File: TestAppLaunchHandler.java From arcusplatform with Apache License 2.0 | 5 votes |
@Test public void testAndroidOsQueryParam() throws Exception { FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "https://app.arcus.com/app/launch?os=android"); expectGetClient(); Capture<SessionHandoff> handoff = captureNewToken(); replay(); FullHttpResponse response = handler.respond(request, mockContext()); assertHandoff(handoff.getValue()); assertRedirectTo(response, "https://dev-app.arcus.com/android/run?token=token"); }
Example #17
Source File: TestAppLaunchHandler.java From arcusplatform with Apache License 2.0 | 5 votes |
@Test public void testWindowsUserAgent() throws Exception { FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "https://app.arcus.com/app/launch"); request.headers().add(HttpHeaders.Names.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"); expectGetClient(); Capture<SessionHandoff> handoff = captureNewToken(); replay(); FullHttpResponse response = handler.respond(request, mockContext()); assertHandoff(handoff.getValue()); assertRedirectTo(response, "https://dev-app.arcus.com/other/run?token=token"); }
Example #18
Source File: TestWBParameterController.java From cms with Apache License 2.0 | 5 votes |
@Test public void test_getAll_ok() { try { EasyMock.expect(requestMock.getParameter("ownerExternalKey")).andReturn(null); List<WPBParameter> allUri = new ArrayList<WPBParameter>(); EasyMock.expect(adminStorageMock.getAllRecords(WPBParameter.class)).andReturn(allUri); String jsonString = "{}"; EasyMock.expect(jsonObjectConverterMock.JSONStringFromListObjects(allUri)).andReturn(jsonString); Capture<HttpServletResponse> captureHttpResponse = new Capture<HttpServletResponse>(); Capture<String> captureData = new Capture<String>(); Capture<Map<String, String>> captureErrors = new Capture<Map<String,String>>(); httpServletToolboxMock.writeBodyResponseAsJson(EasyMock.capture(captureHttpResponse), EasyMock.capture(captureData), EasyMock.capture(captureErrors)); EasyMock.replay(httpServletToolboxMock, requestMock, responseMock, jsonObjectConverterMock, validatorMock, adminStorageMock, objectForControllerMock); controllerForTest.getAll(requestMock, responseMock, "/abc"); EasyMock.verify(httpServletToolboxMock, requestMock, responseMock, jsonObjectConverterMock, validatorMock, adminStorageMock, objectForControllerMock); assertTrue (responseMock == captureHttpResponse.getValue()); assertTrue (captureData.getValue().compareTo(jsonString) == 0); assertTrue (captureErrors.getValue() == null); } catch (WPBException e) { assertTrue(false); } }
Example #19
Source File: TestActionList.java From arcusplatform with Apache License 2.0 | 5 votes |
@Test public void testOverrideContext() throws Exception { Map<String, Object> firstVars = Collections.<String, Object>singletonMap("key", "first"); Map<String, Object> secondVars = Collections.<String, Object>singletonMap("key", "second"); Capture<ActionContext> firstContextRef = Capture.<ActionContext>newInstance(); Capture<ActionContext> secondContextRef = Capture.<ActionContext>newInstance(); Action firstAction = EasyMock.createMock(Action.class); EasyMock.expect(firstAction.getDescription()).andReturn("mock something").anyTimes(); firstAction.execute(EasyMock.capture(firstContextRef)); EasyMock.expectLastCall(); Action secondAction = EasyMock.createMock(Action.class); EasyMock.expect(secondAction.getDescription()).andReturn("mock something else").anyTimes(); secondAction.execute(EasyMock.capture(secondContextRef)); EasyMock.expectLastCall(); EasyMock.replay(firstAction, secondAction); ActionList action = Actions .buildActionList() .addAction(firstAction, firstVars) .addAction(secondAction, secondVars) .build(); assertEquals(ActionList.NAME, action.getName()); assertEquals("first (mock something) then (mock something else)", action.getDescription()); action.execute(context); assertEquals("first", firstContextRef.getValue().getVariable("key")); assertEquals("second", secondContextRef.getValue().getVariable("key")); EasyMock.verify(firstAction, secondAction); }
Example #20
Source File: ShardedConnectionTest.java From mongodb-async-driver with Apache License 2.0 | 5 votes |
/** * Test method for {@link ShardedConnection#connect(Server)}. * * @throws IOException * On a test failure. */ @Test public void testConnectServerAlreadyConnected() throws IOException { final MongoClientConfiguration config = new MongoClientConfiguration(); final Cluster cluster = new Cluster(config, ClusterType.SHARDED); final Server server = cluster.add("localhost:27017"); final Connection mockConnection = createMock(Connection.class); final Connection mockConnection2 = createMock(Connection.class); final ServerSelector mockSelector = createMock(ServerSelector.class); final ProxiedConnectionFactory mockFactory = createMock(ProxiedConnectionFactory.class); final Capture<PropertyChangeListener> listener = new Capture<PropertyChangeListener>(); mockConnection.addPropertyChangeListener(capture(listener)); expectLastCall(); expect(mockFactory.connect(server, config)).andReturn(mockConnection2); mockConnection2.shutdown(true); expectLastCall(); replay(mockConnection, mockConnection2, mockSelector, mockFactory); final ShardedConnection conn = new ShardedConnection(mockConnection, server, cluster, mockSelector, mockFactory, config); assertThat(conn.connect(server), is(mockConnection)); verify(mockConnection, mockConnection2, mockSelector, mockFactory); // For close. reset(mockConnection, mockConnection2, mockSelector, mockFactory); mockConnection.removePropertyChangeListener(listener.getValue()); expectLastCall(); mockConnection.close(); replay(mockConnection, mockConnection2, mockSelector, mockFactory); conn.close(); verify(mockConnection, mockConnection2, mockSelector, mockFactory); }
Example #21
Source File: ClusterTest.java From mongodb-async-driver with Apache License 2.0 | 5 votes |
/** * Test method for {@link Cluster#add(String)}. */ @Test public void testAdd() { myState = new Cluster(new MongoClientConfiguration(), ClusterType.STAND_ALONE); final PropertyChangeListener mockListener = EasyMock .createMock(PropertyChangeListener.class); myState.addListener(mockListener); // Should only get notified of the new server once. final Capture<PropertyChangeEvent> event = new Capture<PropertyChangeEvent>(); mockListener.propertyChange(EasyMock.capture(event)); expectLastCall(); replay(mockListener); final Server ss = myState.add("foo"); assertEquals("foo:" + Server.DEFAULT_PORT, ss.getCanonicalName()); assertSame(ss, myState.add("foo")); verify(mockListener); assertTrue(event.hasCaptured()); assertEquals("server", event.getValue().getPropertyName()); assertSame(myState, event.getValue().getSource()); assertNull(event.getValue().getOldValue()); assertSame(ss, event.getValue().getNewValue()); }
Example #22
Source File: ClusterTest.java From mongodb-async-driver with Apache License 2.0 | 5 votes |
/** * Test method for ensuring the cluster hears when a server becomes not * writable. */ @Test public void testMarkNotWritable() { myState = new Cluster(new MongoClientConfiguration(), ClusterType.STAND_ALONE); final PropertyChangeListener mockListener = EasyMock .createMock(PropertyChangeListener.class); // Should only get notified of the new server once. final Capture<PropertyChangeEvent> event = new Capture<PropertyChangeEvent>(); mockListener.propertyChange(EasyMock.capture(event)); expectLastCall(); replay(mockListener); final Server ss = myState.add("foo"); assertEquals("foo:27017", ss.getCanonicalName()); assertEquals(Server.DEFAULT_PORT, ss.getAddresses().iterator().next() .getPort()); ss.update(PRIMARY_UPDATE); assertTrue(ss.isWritable()); myState.addListener(mockListener); ss.update(SECONDARY_UPDATE); assertFalse(ss.isWritable()); ss.update(SECONDARY_UPDATE); verify(mockListener); assertTrue(event.hasCaptured()); assertEquals("writable", event.getValue().getPropertyName()); assertSame(myState, event.getValue().getSource()); assertEquals(Boolean.TRUE, event.getValue().getOldValue()); assertEquals(Boolean.FALSE, event.getValue().getNewValue()); }
Example #23
Source File: ChromeDevToolsServiceImplTest.java From chrome-devtools-java-client with Apache License 2.0 | 5 votes |
@Test public void testInvokeVoidMethodWithError() throws WebSocketServiceException, IOException { MethodInvocation methodInvocation = new MethodInvocation(); methodInvocation.setId(1L); methodInvocation.setMethod("SomeMethod"); methodInvocation.setParams(new HashMap<>()); methodInvocation.getParams().put("param", "value"); Capture<String> messageCapture = Capture.newInstance(); webSocketService.send(capture(messageCapture)); replayAll(); resolveMessage( "{\"id\":1,\"error\":{\"code\":1,\"message\":\"Error message for id 1\",\"data\": \"Test data\"}}"); ChromeDevToolsInvocationException capturedException = null; try { service.invoke(null, Void.TYPE, null, methodInvocation); } catch (ChromeDevToolsInvocationException ex) { capturedException = ex; } verifyAll(); assertNotNull(capturedException); assertEquals(1, (long) capturedException.getCode()); assertEquals("Error message for id 1: Test data", capturedException.getMessage()); }
Example #24
Source File: TaskTimeoutTest.java From attic-aurora with Apache License 2.0 | 5 votes |
private Capture<Runnable> expectTaskWatch(Amount<Long, Time> expireIn) { Capture<Runnable> capture = createCapture(); expect(executor.schedule( EasyMock.capture(capture), eq(expireIn.as(Time.MILLISECONDS).longValue()), eq(TimeUnit.MILLISECONDS))) .andReturn(null); return capture; }
Example #25
Source File: ActionHistoryProviderTest.java From seldon-server with Apache License 2.0 | 5 votes |
@Test public void test_add_actions_is_run() { mockClientConfigHandler.addListener((ClientConfigUpdateListener) EasyMock.anyObject()); EasyMock.expectLastCall().once(); replay(mockClientConfigHandler); Map<String,ActionHistory> beans = new HashMap<String,ActionHistory>(); Capture<Class<?>> classCapture1 = new Capture<Class<?>>(); Capture<Class<?>> classCapture2 = new Capture<Class<?>>(); mockApplicationContext.getBeansOfType(EasyMock.capture(classCapture1)); EasyMock.expectLastCall().andReturn(beans).once(); mockApplicationContext.getBean((String)EasyMock.anyObject(),EasyMock.capture(classCapture2)); EasyMock.expectLastCall().andReturn(mockRedisActionHistory).once(); replay(mockApplicationContext); ActionHistoryProvider p = new ActionHistoryProvider(mockClientConfigHandler); verify(mockClientConfigHandler); mockRedisActionHistory.addAction((String) EasyMock.anyObject(), EasyMock.anyLong(), EasyMock.anyLong()); EasyMock.expectLastCall().once(); replay(mockRedisActionHistory); p.setApplicationContext(mockApplicationContext); final String client = "client1"; p.configUpdated(client, ActionHistoryProvider.ACTION_HISTORY_KEY, "{\"type\":\"redisActionHistory\",\"addActions\":true}"); p.addAction(client, 1L, 1l); verify(mockApplicationContext); verify(mockRedisActionHistory); Assert.assertEquals(classCapture1.getValue(), ActionHistory.class); Assert.assertEquals(classCapture2.getValue(), ActionHistory.class); }
Example #26
Source File: TestConsoleLicenseGenerator.java From java-license-manager with Apache License 2.0 | 5 votes |
@Test public void testMain01() throws Exception { final ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); final PrintStream stream = new PrintStream(byteStream, true, StandardCharsets.UTF_8.name()); final Capture<String> errorCapture = EasyMock.newCapture(); this.device.registerShutdownHook(EasyMock.anyObject(Thread.class)); EasyMock.expectLastCall().once(); this.device.out(); EasyMock.expectLastCall().andReturn(stream); this.device.exit(0); EasyMock.expectLastCall().andThrow(new ThisExceptionMeansTestSucceededException()); this.device.printErrLn(EasyMock.capture(errorCapture)); EasyMock.expectLastCall().once(); this.device.exit(EasyMock.anyInt()); EasyMock.expectLastCall().anyTimes(); EasyMock.replay(this.device); Field consoleField = ConsoleLicenseGenerator.class.getDeclaredField("TEST_CONSOLE"); consoleField.setAccessible(true); consoleField.set(null, this.device); try { ConsoleLicenseGenerator.main("-help"); } finally { consoleField.set(null, null); } assertTrue(errorCapture.getValue().contains("ThisExceptionMeansTestSucceededException")); String output = byteStream.toString(); assertTrue(output, output.toLowerCase().contains("usage")); assertTrue(output, output.contains("ConsoleLicenseGenerator -help")); }
Example #27
Source File: TaxonomyServiceTest.java From incubator-atlas with Apache License 2.0 | 5 votes |
@Test public void testGetTaxonomies() throws Exception { MetadataService metadataService = createStrictMock(MetadataService.class); AtlasTypeDefStore typeDefStore = createStrictMock(AtlasTypeDefStore.class); ResourceProvider taxonomyResourceProvider = createStrictMock(ResourceProvider.class); ResourceProvider termResourceProvider = createStrictMock(ResourceProvider.class); UriInfo uriInfo = createNiceMock(UriInfo.class); URI uri = new URI("http://localhost:21000/api/atlas/v1/taxonomies?name:testTaxonomy"); JsonSerializer serializer = createStrictMock(JsonSerializer.class); Capture<Request> requestCapture = newCapture(); Collection<Map<String, Object>> resultPropertyMaps = new ArrayList<>(); Map<String, Object> propertyMap = new HashMap<>(); propertyMap.put("name", "testTaxonomy"); resultPropertyMaps.add(propertyMap); Result result = new Result(resultPropertyMaps); // set mock expectations expect(uriInfo.getRequestUri()).andReturn(uri); expect(taxonomyResourceProvider.getResources(capture(requestCapture))).andReturn(result); expect(serializer.serialize(result, uriInfo)).andReturn("Taxonomy Get Response"); expect(metadataService.getTypeDefinition(TaxonomyResourceProvider.TAXONOMY_TERM_TYPE)).andReturn(TaxonomyResourceProvider.TAXONOMY_TERM_TYPE + "-definition"); replay(uriInfo, metadataService, taxonomyResourceProvider, termResourceProvider, serializer); // instantiate service and invoke method being tested TestTaxonomyService service = new TestTaxonomyService( metadataService, typeDefStore, taxonomyResourceProvider, termResourceProvider, serializer); Response response = service.getTaxonomies(null, uriInfo); Request request = requestCapture.getValue(); assertTrue(request.getQueryProperties().isEmpty()); assertEquals(request.getQueryString(), "name:testTaxonomy"); assertEquals(response.getStatus(), 200); assertEquals(response.getEntity(), "Taxonomy Get Response"); verify(uriInfo, taxonomyResourceProvider, termResourceProvider, serializer); }
Example #28
Source File: SolManBackendCreateTransportTest.java From devops-cm-client with Apache License 2.0 | 5 votes |
@Before public void setup() throws Exception { super.setup(); owner = Capture.newInstance(); description = Capture.newInstance(); developmentSystemId = Capture.newInstance(); }
Example #29
Source File: TestHttpServletToolbox.java From cms with Apache License 2.0 | 5 votes |
@Test public void testWriteBodyResponseAsJson_exception() { try { HashMap<String, String> errors = new HashMap<String, String>(); String data = "data"; HttpServletResponse responseMock = EasyMock.createMock(HttpServletResponse.class); ServletOutputStream outputStream = PowerMock.createMock(ServletOutputStream.class); EasyMock.expect(responseMock.getOutputStream()).andThrow(new IOException()); responseMock.setContentType("application/json"); responseMock.setContentType("application/json"); responseMock.setCharacterEncoding("UTF-8"); Capture<byte[]> captureContent = new Capture<byte[]>(); Capture<Integer> captureInt = new Capture<Integer>(); EasyMock.expect(responseMock.getOutputStream()).andReturn(outputStream); responseMock.setContentLength(EasyMock.captureInt(captureInt)); outputStream.write(EasyMock.capture(captureContent)); outputStream.flush(); EasyMock.replay(responseMock, outputStream); httpServletToolbox.writeBodyResponseAsJson(responseMock, data, errors); EasyMock.verify(responseMock, outputStream); org.json.JSONObject json = new org.json.JSONObject(new String (captureContent.getValue())); Integer captureContentLen = json.toString().length(); assertTrue (json.getString("status").compareTo("FAIL") == 0); assertTrue (json.getString("payload").compareTo("{}") == 0); assertTrue (json.getJSONObject("errors").toString().compareTo("{\"reason\":\"WB_UNKNOWN_ERROR\"}") == 0); assertTrue (captureInt.getValue().compareTo(captureContentLen) == 0); } catch (Exception e) { assertTrue(false); } }
Example #30
Source File: PaymentChannelServerTest.java From bcm-android with GNU General Public License v3.0 | 5 votes |
private void assertExpireTime(long expectedExpire, Capture<TwoWayChannelMessage> initiateCapture) { final TwoWayChannelMessage response = initiateCapture.getValue(); final MessageType type = response.getType(); assertEquals("Wrong type " + type, MessageType.INITIATE, type); final long actualExpire = response.getInitiate().getExpireTimeSecs(); assertTrue("Expire time too small " + expectedExpire + " > " + actualExpire, expectedExpire <= actualExpire); assertTrue("Expire time too large " + expectedExpire + "<" + actualExpire, expectedExpire >= actualExpire); }