private static final LdapConnection verify( LdapConnection connection, VerificationMode mode ) { if ( MOCK_UTIL.isMock( connection ) ) { return org.mockito.Mockito.verify( connection, mode ); } else { if ( connection instanceof Wrapper ) { @SuppressWarnings("unchecked") LdapConnection unwrapped = ( ( Wrapper<LdapConnection> ) connection ).wrapped(); return verify( unwrapped, mode ); } } throw new NotAMockException( "connection is not a mock, nor a wrapper for a connection that is one" ); }
/** * Wait for the coordinator task to complete, and verify all the mocks * @param task to wait on * @throws Exception on unexpected failure */ private void waitAndVerifyProc(Procedure proc, VerificationMode prepare, VerificationMode commit, VerificationMode cleanup, VerificationMode finish, boolean opHasError) throws Exception { boolean caughtError = false; try { proc.waitForCompleted(); } catch (ForeignException fe) { caughtError = true; } // make sure that the task called all the expected phases Mockito.verify(proc, prepare).sendGlobalBarrierStart(); Mockito.verify(proc, commit).sendGlobalBarrierReached(); Mockito.verify(proc, finish).sendGlobalBarrierComplete(); assertEquals("Operation error state was unexpected", opHasError, proc.getErrorMonitor() .hasException()); assertEquals("Operation error state was unexpected", opHasError, caughtError); }
/** * Wait for the coordinator task to complete, and verify all the mocks * @param task to wait on * @throws Exception on unexpected failure */ private void waitAndVerifySubproc(Subprocedure op, VerificationMode prepare, VerificationMode commit, VerificationMode cleanup, VerificationMode finish, boolean opHasError) throws Exception { boolean caughtError = false; try { op.waitForLocallyCompleted(); } catch (ForeignException fe) { caughtError = true; } // make sure that the task called all the expected phases Mockito.verify(op, prepare).acquireBarrier(); Mockito.verify(op, commit).insideBarrier(); // We cannot guarantee that cleanup has run so we don't check it. assertEquals("Operation error state was unexpected", opHasError, op.getErrorCheckable() .hasException()); assertEquals("Operation error state was unexpected", opHasError, caughtError); }
private void saleMade(final boolean isDryRun) { final Investment i = mock(); final Zonky zonky = mockApi(i); final Portfolio portfolio = Portfolio.create(zonky); new Selling(ALL_ACCEPTING, isDryRun).accept(portfolio, mockAuthentication(zonky)); final List<Event> e = getNewEvents(); Assertions.assertThat(e).hasSize(5); SoftAssertions.assertSoftly(softly -> { softly.assertThat(e.get(0)).isInstanceOf(SellingStartedEvent.class); softly.assertThat(e.get(1)).isInstanceOf(SaleRecommendedEvent.class); softly.assertThat(e.get(2)).isInstanceOf(SaleRequestedEvent.class); softly.assertThat(e.get(3)).isInstanceOf(SaleOfferedEvent.class); softly.assertThat(e.get(4)).isInstanceOf(SellingCompletedEvent.class); }); final VerificationMode m = isDryRun ? Mockito.never() : Mockito.times(1); Mockito.verify(i, m).setIsOnSmp(ArgumentMatchers.eq(true)); Mockito.verify(zonky, m).sell(ArgumentMatchers.eq(i)); }
private void verifyConceptDependencies(Boolean optional, boolean status, VerificationMode visitVerification, VerificationMode skipVerification) throws RuleException { Concept dependencyConcept1 = Concept.Builder.newConcept().id("test:DependencyConcept1").get(); Concept dependencyConcept2 = Concept.Builder.newConcept().id("test:DependencyConcept2").get(); Map<String, Boolean> requiresConcepts = new HashMap<>(); requiresConcepts.put("test:DependencyConcept1", optional); requiresConcepts.put("test:DependencyConcept2", optional); Concept concept = Concept.Builder.newConcept().id("test:Concept").requiresConceptIds(requiresConcepts).get(); Constraint constraint = Constraint.Builder.newConstraint().id("test:Constraint").requiresConceptIds(requiresConcepts).get(); when(visitor.visitConcept(dependencyConcept1, null)).thenReturn(status); when(visitor.visitConcept(dependencyConcept2, null)).thenReturn(status); RuleSet ruleSet = RuleSetBuilder.newInstance().addConcept(dependencyConcept1).addConcept(dependencyConcept2).addConcept(concept) .addConstraint(constraint).getRuleSet(); RuleSelection ruleSelection = RuleSelection.Builder.newInstance().addConceptId(concept.getId()).addConstraintId(constraint.getId()).get(); ruleExecutor.execute(ruleSet, ruleSelection); verify(visitor).visitConcept(dependencyConcept1, null); verify(visitor).visitConcept(dependencyConcept2, null); verify(visitor, visitVerification).visitConcept(concept, null); verify(visitor, skipVerification).skipConcept(concept, null); verify(visitor, visitVerification).visitConstraint(constraint, null); verify(visitor, skipVerification).skipConstraint(constraint, null); }
private void verifyMessagesSynchronizer(VerificationMode verificationMode) throws InterruptedException { mobileMessagingCore.addSyncMessagesIds("test-message-id"); given(mobileApiMessages.sync(any(SyncMessagesBody.class))).willReturn(new SyncMessagesResponse(new ArrayList<MessageResponse>() {{ add(new MessageResponse( "test-message-id", "this is title", "body", "sound", "true", "false", "UNKNOWN", "{}", "{}" )); }})); messagesSynchronizer.sync(); verify(mobileApiMessages, verificationMode).sync(any(SyncMessagesBody.class)); }
private void verifyGeoReporting(VerificationMode verificationMode) throws InterruptedException { // Given GeoReport report1 = createReport(context, "signalingMessageId1", "campaignId1", "messageId1", true, createArea("areaId1")); GeoReport report2 = createReport(context, "signalingMessageId2", "campaignId2", "messageId2", true, createArea("areaId2")); GeoReport report3 = createReport(context, "signalingMessageId3", "campaignId3", "messageId3", true, createArea("areaId3")); createMessage(context, "signalingMessageId1", "campaignId1", true, report1.getArea(), report2.getArea()); createMessage(context, "signalingMessageId2", "campaignId2", true, report3.getArea()); given(mobileApiGeo.report(any(EventReportBody.class))).willReturn(new EventReportResponse()); // When geoReporter.synchronize(); // Then //noinspection unchecked verify(geoBroadcaster, verificationMode).geoReported(any(List.class)); }
private void assertAclsApplied(ContainerName containerName, List<ContainerAclSpec> containerAclSpecs, VerificationMode verificationMode) { StringBuilder expectedCommand = new StringBuilder() .append("ip6tables -F INPUT; ") .append("ip6tables -P INPUT DROP; ") .append("ip6tables -P FORWARD DROP; ") .append("ip6tables -P OUTPUT ACCEPT; ") .append("ip6tables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT; ") .append("ip6tables -A INPUT -i lo -j ACCEPT; ") .append("ip6tables -A INPUT -p ipv6-icmp -j ACCEPT; "); containerAclSpecs.forEach(aclSpec -> expectedCommand.append("ip6tables -A INPUT -s " + aclSpec.ipAddress() + "/128 -j ACCEPT; ")); expectedCommand.append("ip6tables -A INPUT -j REJECT"); verify(dockerOperations, verificationMode).executeCommandInNetworkNamespace( eq(containerName), eq("/bin/sh"), eq("-c"), eq(expectedCommand.toString())); }
@Test public void runImage_withStandaloneImage_shouldStartDockerContainer() throws IOException, InterruptedException, DockerClient.DockerClientException { DockerClient client = new DockerClient(build,launcher,listener); client.runImage("imagename","containername"); verify(launcher, new VerificationMode() { public void verify(VerificationData verificationData) { assertEquals(verificationData.getAllInvocations().size(),1); Launcher.ProcStarter ps = (Launcher.ProcStarter) verificationData.getAllInvocations().get(0).getRawArguments()[0]; String cmd = StringUtils.join(ps.cmds()," "); assertEquals("docker run -d --name containername imagename",cmd); } }).launch(Matchers.<Launcher.ProcStarter>any()); }
/** * Verifies certain behavior happened at least once / exact number of times * / never. E.g: * * <pre> * verifyNew(ClassWithStaticMethod.class, times(5)); * * verifyNew(ClassWithStaticMethod.class, atLeast(2)); * * //you can use flexible argument matchers, e.g: * verifyNew(ClassWithStaticMethod.class, atLeastOnce()); * </pre> * * <b>times(1) is the default</b> and can be omitted * <p> * * @param mock * to be verified * @param mode * times(x), atLeastOnce() or never() */ @SuppressWarnings("unchecked") public static <T> ConstructorArgumentsVerification verifyNew(Class<?> mock, VerificationMode mode) { if (mock == null) { throw new IllegalArgumentException("Class to verify cannot be null"); } else if (mode == null) { throw new IllegalArgumentException("Verify mode cannot be null"); } NewInvocationControl<?> invocationControl = MockRepository.getNewInstanceControl(mock); MockRepository.putAdditionalState("VerificationMode", POWERMOCKITO_CORE.wrapInMockitoSpecificVerificationMode( mock, mode)); if (invocationControl == null) { throw new IllegalStateException(String.format(NO_OBJECT_CREATION_ERROR_MESSAGE_TEMPLATE, Whitebox.getType( mock).getName())); } try { invocationControl.verify(); } finally { MockRepository.removeAdditionalState("VerificationMode"); } return new DefaultConstructorArgumentsVerfication<T>((NewInvocationControl<T>) invocationControl, mock); }
private void notifyLibraryOfConnection(final VerificationMode times) { verify(inboundPublication, times).saveManageSession(eq(LIBRARY_ID), eq(connectionId.getValue()), anyLong(), anyInt(), anyInt(), anyLong(), eq(LogonStatus.NEW), eq(SlowStatus.NOT_SLOW), eq(INITIATOR), any(), anyInt(), anyLong(), anyInt(), any(), any(), any(), any(), any(), any(), any()); }
private void verifySessionExistsSaved(final VerificationMode times, final LogonStatus status) { verify(inboundPublication, times).saveManageSession(eq(LIBRARY_ID), eq(connectionId.getValue()), anyLong(), anyInt(), anyInt(), anyLong(), eq(status), any(), // todo(Nick): Should be NOT_SLOW? , any(), any(), anyInt(), anyLong(), anyInt(), any(), any(), any(), any(), any(), any(), any()); }
protected void verifyNamedOutput(MultipleOutputs multiOut, String name, Object key, Object value, String path, VerificationMode mode) { ArgumentCaptor keyArg = ArgumentCaptor.forClass(key.getClass()); ArgumentCaptor valueArg = ArgumentCaptor.forClass(value.getClass()); try { if (name == null) { verify(multiOut, mode).write(keyArg.capture(), valueArg.capture(), path); } else { if (path == null) { verify(multiOut, mode).write(eq(name), keyArg.capture(), valueArg.capture()); assertEquals(key, keyArg.getValue()); assertEquals(value, valueArg.getValue()); } else { verify(multiOut, mode).write(name, keyArg.capture(), valueArg.capture(), path); } } } catch (IOException | InterruptedException e) { fail(e.getMessage()); } }
@Test public void it_should_not_throw_exception_if_scripts_does_not_exist() throws Exception { T mojo = createMojo("mojo-without-scripts", false); writePrivate(mojo, "failOnMissingScript", false); CommandResult result = createResult(false); CommandExecutor executor = readPrivate(mojo, "executor"); ArgumentCaptor<Command> cmdCaptor = ArgumentCaptor.forClass(Command.class); when(executor.execute(any(File.class), cmdCaptor.capture(), any(NpmLogger.class))).thenReturn(result); mojo.execute(); VerificationMode verificationModeLog = isStandardScript() ? never() : times(1); VerificationMode verificationModeExecutor = isStandardScript() ? times(1) : never(); Log logger = readPrivate(mojo, "log"); verify(logger, verificationModeLog).warn("Cannot execute npm run " + script() + " command: it is not defined in package.json, skipping."); verify(logger, never()).error("Cannot execute npm run " + script() + " command: it is not defined in package.json."); verify(executor, verificationModeExecutor).execute(any(File.class), any(Command.class), any(NpmLogger.class)); }
/** * Helper to verify that permissions have been set correctly on the child * * @param parent parent node * @param child child node * @param read verification mode relating to setting read on the child * @param filling verification mode relating to setting filling on the child */ private void verifyInitPermissions(NodeRef parent, NodeRef child, VerificationMode read, VerificationMode filling) { // verify the core permissions are set-up correctly verifyInitPermissions(child); // verify the permissions came from the correct parent verify(mockedPermissionService).getAllSetPermissions(parent); // verify all the inherited permissions are set correctly (note read are not inherited from fileplan) verify(mockedPermissionService, filling).setPermission(child, AUTHORITY2, RMPermissionModel.FILING, true); verify(mockedPermissionService, read).setPermission(child, AUTHORITY, RMPermissionModel.READ_RECORDS, true); // verify that there are no unaccounted for interactions with the permission service verifyNoMoreInteractions(mockedPermissionService); }
private void verifyResendsSent(Alarm alarm, AlarmDefinition alarmDefinition) { for (final MetricDefinitionAndTenantId mdtid : alarm.getAlarmedMetrics()) { for (final SubAlarm subAlarm : alarm.getSubAlarms()) { // This is not the real check but is sufficient for this test final VerificationMode wanted; if (subAlarm.getExpression().getMetricDefinition().name.equals(mdtid.metricDefinition.name)) { wanted = times(1); } else { wanted = never(); } verify(collector, wanted).emit( EventProcessingBolt.METRIC_ALARM_EVENT_STREAM_ID, new Values(EventProcessingBolt.RESEND, new TenantIdAndMetricName(mdtid), mdtid, alarmDefinition.getId(), subAlarm.getId())); } } }
private void testOnSyncPalette(boolean noContext) { loadContent(); VerificationMode count = times(1); if (noContext) { when(editorHelper.getContent()).thenReturn(null); count = never(); } FormEditorPresenter presenterSpy = spy(presenter); String formId = presenterSpy.getFormDefinition().getId(); presenterSpy.onSyncPalette(formId); Collection<FieldDefinition> availableFieldsValues = editorHelper.getAvailableFields().values(); verify(presenterSpy, count).removeAllDraggableGroupComponent(presenter.getFormDefinition().getFields()); verify(presenterSpy, count).removeAllDraggableGroupComponent(availableFieldsValues); verify(presenterSpy, count).addAllDraggableGroupComponent(availableFieldsValues); }
public void testOnRemoveComponent(boolean noContext) { loadContent(); loadAvailableFields(); addAllFields(); VerificationMode count = times(1); if (noContext) { when(editorHelper.getContent()).thenReturn(null); count = never(); } FormEditorPresenter presenterSpy = spy(presenter); String formId = presenterSpy.getFormDefinition().getId(); FieldDefinition field = editorHelper.getFormDefinition().getFields().get(0); ComponentRemovedEvent event = new ComponentRemovedEvent(createLayoutComponent(presenter.getFormDefinition(), field), false); presenterSpy.onRemoveComponent(event); verify(presenterSpy, count).onSyncPalette(formId); verify(editorHelper, count).removeField(anyString(), anyBoolean()); }