/**
   * Verifica il comportamento del metodo doAction nel momento in cui il gruppo da cui si richiede
   * la cancellazione di un contatto non corrisponde ad alcuno dei gruppo che sono presenti nel
   * database del sistema. Il test verifica che in questo caso il testo stampato sulla risposta HTTP
   * sia, come desiderato, la stringa 'null' e che non siano MAI effettuate operazioni di
   * aggiornamento dei dati dell'utente che ha richiesto la cancellazione e che non sia cancellata
   * alcuna voce dalla rubrica.
   *
   * @author Diego Beraldin
   * @version 2.0
   */
  @Test
  public void testDeleteNotExistGroup() throws Exception {
    // impedisce di recuperare l'utente
    when(dao.getGroup(groupId)).thenReturn(null);

    // invoca il metodo da testare
    tester.doAction(request, response);

    // verifica l'output ottenuto
    writer.flush();
    String responseText = writer.toString();
    assertEquals("null", responseText);

    // verifica il corretto utilizzo dei mock
    verify(response).getWriter();
    verify(request).getParameter("contactId");
    verify(request).getParameter("groupId");
    verify(dao).getUserData(username);
    verify(dao).getUserData(contactId);
    verify(dao).getGroup(groupId);
    verifyZeroInteractions(user);
    verifyZeroInteractions(entry);
    verify(dao, never()).delete(any(IAddressBookEntry.class));
    verify(dao, never()).update(any(IUserData.class));
  }
  /**
   * Test prefetchDeltaSignerInfo for failing requests -- the failure should be propagated to the
   * prefetch listener, and requests on the same domain should fail.
   */
  public void test_prefetchDeltaSignerInfo4() throws Exception {
    // This will fail later
    SignerInfoPrefetchResultListener failListener = mock(SignerInfoPrefetchResultListener.class);

    manager.prefetchDeltaSignerInfo(
        getSlowFailingProvider(ticker, EASY_TICKS),
        getRealSignerId(),
        getFakeWaveletName(CertificateManagerImplTest.DOMAIN),
        null,
        failListener);

    // This would succeed later if it weren't for the previous one failing
    SignerInfoPrefetchResultListener successListener = mock(SignerInfoPrefetchResultListener.class);

    manager.prefetchDeltaSignerInfo(
        getSuccessfulProvider(),
        getRealSignerId(),
        getFakeWaveletName(CertificateManagerImplTest.DOMAIN),
        null,
        successListener);
    verifyZeroInteractions(failListener);
    verifyZeroInteractions(successListener);

    // Both callbacks should fail after ticking
    ticker.tick(EASY_TICKS);
    verify(failListener).onFailure(GENERIC_ERROR);
    verify(successListener).onFailure(GENERIC_ERROR);
  }
 public void testJobDispatcher() {
   final MultipleNodeExecutorFactory factory = Mockito.mock(MultipleNodeExecutorFactory.class);
   final MultipleNodeExecutorTuner tuner = new MultipleNodeExecutorTuner(factory);
   final JobDispatcher dispatcher = Mockito.mock(JobDispatcher.class);
   final Map<String, Collection<Capability>> capabilities =
       new HashMap<String, Collection<Capability>>();
   Mockito.when(dispatcher.getAllCapabilities()).thenReturn(capabilities);
   tuner.setJobDispatcher(dispatcher);
   tuner.run();
   Mockito.verifyZeroInteractions(factory);
   capabilities.put("A", Arrays.asList(Capability.instanceOf("Foo")));
   capabilities.put("B", Arrays.asList(Capability.instanceOf("Bar")));
   tuner.run();
   Mockito.verifyZeroInteractions(factory);
   capabilities.put(
       "A",
       Arrays.asList(
           Capability.instanceOf("Foo"),
           Capability.parameterInstanceOf(PlatformCapabilities.NODE_COUNT, 10d)));
   capabilities.put(
       "B",
       Arrays.asList(
           Capability.instanceOf("Bar"),
           Capability.parameterInstanceOf(PlatformCapabilities.NODE_COUNT, 4d)));
   tuner.run();
   Mockito.verify(factory, Mockito.times(1)).setMaximumConcurrency(7);
   Mockito.verify(factory, Mockito.times(1)).invalidateCache();
   Mockito.when(factory.getMaximumConcurrency()).thenReturn(7);
   tuner.run();
   Mockito.verify(factory, Mockito.times(1)).setMaximumConcurrency(7);
   Mockito.verify(factory, Mockito.times(1)).invalidateCache();
 }
  @Test
  public void whenValueHas50CharacterThenNoValidationMessage() throws Exception {
    validator.validate(metadata, valuesOf50Character, configProvider, validationErrors);

    verifyZeroInteractions(validationErrors);
    verifyZeroInteractions(metadata);
  }
Ejemplo n.º 5
0
  @Before
  public void setup() throws Exception {
    // TODO: figure out how initialization can be refactored with @InjectMocks
    final StorageNode n = new StorageNode("node1", storage);
    node = spy(n);

    nodeContext = new StorageExecutionContext(communicationContext, node);
    nodeContext = spy(nodeContext);
    n.configure(nodeContext);
    node.configure(nodeContext);

    Mockito.reset(node);
    verifyZeroInteractions(nodeContext);
    verifyZeroInteractions(storage);
    verifyZeroInteractions(node);

    assertEquals("node1", node.getId());
    assertEquals("NEW", node.getState());

    // verify(node, atLeastOnce()).getId();
    // verify(node).getState();

    verifyZeroInteractions(nodeContext, storage, node);

    doAnswer(
            invocation -> {
              final StorageOperation op = (StorageOperation) invocation.getArguments()[0];
              doReturn(op).when(operationContext).operation();
              return operationContext;
            })
        .when(nodeContext)
        .contextFor(any(StorageOperation.class));
  }
  @Test
  public void whenValuesEmptyThenNoValidationMessage() throws Exception {
    validator.validate(metadata, emptyValues, configProvider, validationErrors);

    verifyZeroInteractions(validationErrors);
    verifyZeroInteractions(metadata);
  }
Ejemplo n.º 7
0
  @Test
  public void
      shouldMakeACallForActivePatient_DoesNotRecordDosageAsNotReported_WhenCalledAfterFirstTime() {
    String PHONE_NUMBER = "1234567890";
    Patient patient = mock(Patient.class);
    PillRegimen pillRegimen = mock(PillRegimen.class);
    Dose dose = mock(Dose.class);
    DateTime now = DateUtil.now();
    TIMES_SENT = 1;

    when(patient.allowAdherenceCalls()).thenReturn(true);
    when(patient.getMobilePhoneNumber()).thenReturn(PHONE_NUMBER);
    when(allPatients.get(PATIENT_DOC_ID)).thenReturn(patient);

    pillReminderCall.execute(
        PATIENT_DOC_ID, NOW.toDate(), TIMES_SENT, TOTAL_TIMES_TO_SEND, RETRY_INTERVAL);

    ArgumentCaptor<CallRequest> callRequestArgumentCaptor =
        ArgumentCaptor.forClass(CallRequest.class);
    verify(callService).initiateCall(callRequestArgumentCaptor.capture());
    verifyZeroInteractions(dailyPillReminderAdherenceService);
    verifyZeroInteractions(dailyPillReminderService);
    Map<String, String> payload = callRequestArgumentCaptor.getValue().getPayload();
    assertEquals(
        String.valueOf(TOTAL_TIMES_TO_SEND), payload.get(PillReminderCall.TOTAL_TIMES_TO_SEND));
    assertEquals(String.valueOf(TIMES_SENT), payload.get(PillReminderCall.TIMES_SENT));
    assertEquals(String.valueOf(RETRY_INTERVAL), payload.get(PillReminderCall.RETRY_INTERVAL));
  }
Ejemplo n.º 8
0
  @Test
  public void testTimes() {
    mockedList.add("once");

    mockedList.add("twice");
    mockedList.add("twice");

    mockedList.add("three times");
    mockedList.add("three times");
    mockedList.add("three times");

    // 下面两个的验证结果一样,因为verify默认验证的就是times(1)
    verify(mockedList).add("once");
    verify(mockedList, times(1)).add("once");

    // 验证具体的执行次数
    verify(mockedList, times(2)).add("twice");
    verify(mockedList, times(3)).add("three times");

    // 使用never验证,never相当于time(0)
    verify(mockedList, never()).add("never happened");

    // 使用atLeast()/atMost
    verify(mockedList, atLeastOnce()).add("three times");
    verify(mockedList, atLeast(2)).add("twice");
    verify(mockedList, atMost(5)).add("three times");

    List mockTwo = mock(List.class);
    // 验证Mock对象没有交互过
    // 如果mockedList在@Before已交互过,验证则不通过
    verifyZeroInteractions(mockedList);
    verifyZeroInteractions(mockTwo); // mockTwo没有交互过
  }
  public void testApplyNoIngestNodes() {
    Task task = mock(Task.class);
    ActionListener actionListener = mock(ActionListener.class);
    ActionFilterChain actionFilterChain = mock(ActionFilterChain.class);
    int totalNodes = randomIntBetween(1, 5);
    IngestProxyActionFilter filter = buildFilter(0, totalNodes);

    String action;
    ActionRequest request;
    if (randomBoolean()) {
      action = IndexAction.NAME;
      request = new IndexRequest().setPipeline("_id");
    } else {
      action = BulkAction.NAME;
      request = new BulkRequest().add(new IndexRequest().setPipeline("_id"));
    }
    try {
      filter.apply(task, action, request, actionListener, actionFilterChain);
      fail("should have failed because there are no ingest nodes");
    } catch (IllegalStateException e) {
      assertThat(
          e.getMessage(),
          equalTo(
              "There are no ingest nodes in this cluster, unable to forward request to an ingest node."));
    }
    verifyZeroInteractions(transportService);
    verifyZeroInteractions(actionFilterChain);
    verifyZeroInteractions(actionListener);
  }
Ejemplo n.º 10
0
 @Test
 public void testUserDeniesFailsLogin() throws IOException, ServletException {
   googleDeniesUserinfo();
   GoogleOauthFilter googleOauthFilter = filterNotYetAuthorised();
   HttpServletResponse response = mock(HttpServletResponse.class);
   HttpServletRequest request =
       request(
           "http",
           "myserver.co.uk",
           "webapp",
           "oauth.html",
           "state=http://myserver.co.uk/webapp/index.html?forename=brian&surname=may",
           "code=4/b--2fGSRhhkub2d0wg7dZoNFUXLN.EluGs0IJqNIcOl05ti8ZT3b3nc9jcwI");
   FilterChain chain = mock(FilterChain.class);
   googleOauthFilter.doFilter(request, response, chain);
   // we expect a redirect to the original page.
   verify(response)
       .sendRedirect("http://myserver.co.uk/webapp/index.html?forename=brian&surname=may");
   verifyZeroInteractions(chain);
   // now check for a redirect to Google as authentication was denied.
   response = mock(HttpServletResponse.class);
   request =
       request("http", "myserver.co.uk", "webapp", "index.html", "forename=brian", "surname=may");
   chain = mock(FilterChain.class);
   googleOauthFilter.doFilter(request, response, chain);
   verifyZeroInteractions(userManager, chain);
   verify(response)
       .sendRedirect(
           "https://accounts.google.com/o/oauth2/auth?client_id=my_id&redirect_uri=http://myserver.co.uk/webapp/oauth.html&response_type=code&scope=http://yetanotherscopse.com/scope%20https://www.googleapis.com/auth/userinfo.profile%20https://www.googleapis.com/auth/userinfo.email&state=http://myserver.co.uk/webapp/index.html?forename%3Dbrian%26surname%3Dmay");
 }
  @Test
  public void isUserInRole() {
    AuthenticationUtilService tested = getTested();

    Mockito.when(tested.httpRequest.isUserInRole(ROLE1)).thenReturn(false);
    Mockito.when(tested.httpRequest.isUserInRole(ROLE2)).thenReturn(true);

    {
      Assert.assertFalse(tested.isUserInRole(null));
      Mockito.verifyZeroInteractions(tested.httpRequest);
    }
    {
      Assert.assertFalse(tested.isUserInRole(""));
      Mockito.verifyZeroInteractions(tested.httpRequest);
    }
    {
      Assert.assertFalse(tested.isUserInRole("  "));
      Mockito.verifyZeroInteractions(tested.httpRequest);
    }
    {
      Assert.assertFalse(tested.isUserInRole(ROLE1));
      Mockito.verify(tested.httpRequest).isUserInRole(ROLE1);
    }
    {
      Assert.assertTrue(tested.isUserInRole(ROLE2));
      Mockito.verify(tested.httpRequest).isUserInRole(ROLE2);
    }
  }
Ejemplo n.º 12
0
  @Test
  public void checkBehavior_of_StorageOperationProcessingDuringRecovery() throws Exception {
    verifyZeroInteractions(storage);
    startNodeAndVerify();

    manageNode(new ControlMessage.Builder().setState(StorageNode.StorageState.RECOVERING.name()));

    for (StorageOperation op : allOperations) {
      node.onStorageRequest(op);
    }

    // all the operations must be queued for further processing after recovery will be completed
    verify(storage, after(2000).never()).process(any());
    verifyZeroInteractions(storage);

    // should process all previously queued operations
    manageNode(new ControlMessage.Builder().setState(StorageNode.StorageState.RUNNING.name()));

    // all the enqueued operation should be processed
    verify(storage, after(1000).times(allOperations.length)).process(any());

    // each successfully processed operation should be acknowledged
    verify(operationContext, times(allOperations.length)).ackOperation(any());

    stopNodeAndVerify();
  }
  /**
   * Test prefetchDeltaSignerInfo for failing requests -- even though the first request fails, the
   * second request on a different domain should succeed.
   */
  public void test_prefetchDeltaSignerInfo6() throws Exception {
    // This will fail later
    SignerInfoPrefetchResultListener failListener = mock(SignerInfoPrefetchResultListener.class);

    manager.prefetchDeltaSignerInfo(
        getSlowFailingProvider(ticker, EASY_TICKS),
        getRealSignerId(),
        getFakeWaveletName(CertificateManagerImplTest.DOMAIN),
        getHashedVersion(),
        failListener);
    verifyZeroInteractions(failListener);

    // This will succeed later, after the failing one fails
    SignerInfoPrefetchResultListener successListener = mock(SignerInfoPrefetchResultListener.class);

    manager.prefetchDeltaSignerInfo(
        getSlowSuccessfulProvider(ticker, EASY_TICKS * 2),
        getRealSignerId(),
        getFakeWaveletName(OTHER_DOMAIN),
        getHashedVersion(),
        successListener);
    verifyZeroInteractions(successListener);

    // The failing request should fail, but successful request left alone
    ticker.tick(EASY_TICKS);
    verifyZeroInteractions(successListener);
    verify(failListener).onFailure(GENERIC_ERROR);

    // The successful request should now succeed
    ticker.tick(EASY_TICKS);
    verify(successListener).onSuccess(Certificates.getRealSignerInfo().toProtoBuf());
    verifyNoMoreInteractions(failListener);
  }
  @Test
  public void testRestoreInstances_nonNullNonMatchingHandler() throws Exception {

    // Prepare stuff
    INotificationMngr notificationMngr = Mockito.mock(INotificationMngr.class);
    IRandomMngr randomMngr = Mockito.mock(IRandomMngr.class);
    IMessagingMngr messagingMngr = Mockito.mock(IMessagingMngr.class);
    ITargetConfigurator targetConfigurator = Mockito.mock(ITargetConfigurator.class);

    ITargetsMngr targetsMngr = Mockito.mock(ITargetsMngr.class);
    Mockito.when(
            targetsMngr.findRawTargetProperties(
                Mockito.any(Application.class), Mockito.anyString()))
        .thenReturn(new HashMap<String, String>(0));

    IConfigurationMngr configurationMngr = new ConfigurationMngrImpl();
    configurationMngr.setWorkingDirectory(this.folder.newFolder());

    final TargetHandler targetHandlerArgument = Mockito.mock(TargetHandler.class);
    Mockito.when(targetHandlerArgument.getTargetId()).thenReturn("some target id");

    final TargetHandler targetHandler = Mockito.mock(TargetHandler.class);
    Mockito.when(targetHandler.getTargetId()).thenReturn("some other target id");

    IInstancesMngr mngr =
        new InstancesMngrImpl(
            messagingMngr, notificationMngr, targetsMngr, randomMngr, targetConfigurator);
    ((InstancesMngrImpl) mngr)
        .setTargetHandlerResolver(
            new TestTargetResolver() {
              @Override
              public TargetHandler findTargetHandler(Map<String, String> targetProperties)
                  throws TargetException {
                return targetHandler;
              }
            });

    TestApplication app = new TestApplication();
    ManagedApplication ma = new ManagedApplication(app);

    // One scoped instance has a machine ID (considered as running somewhere)
    app.getMySqlVm().data.put(Instance.MACHINE_ID, "machine-id");

    // Try to restore instances
    mngr.restoreInstanceStates(ma, targetHandlerArgument);

    // The handler's ID did not match => no restoration and no use of other mocks
    Mockito.verify(targetsMngr, Mockito.only())
        .findRawTargetProperties(Mockito.eq(app), Mockito.anyString());
    Mockito.verify(targetHandler, Mockito.only()).getTargetId();
    Mockito.verify(targetHandlerArgument, Mockito.only()).getTargetId();

    Mockito.verifyZeroInteractions(messagingMngr);
    Mockito.verifyZeroInteractions(randomMngr);

    // No notification was sent since there was no change on Tomcat instances
    Mockito.verifyZeroInteractions(notificationMngr);
    Mockito.verifyZeroInteractions(targetConfigurator);
  }
 @Test
 public void assertConstructorBuildUsesProject() throws IOException, InterruptedException {
   when(build.getProject()).thenReturn(project);
   new BuildVariableResolver(build, computer);
   verify(build).getProject();
   verifyZeroInteractions(project);
   verifyZeroInteractions(computer);
 }
 @Test
 public void assertConstructorBuildUsesProject() {
   when(build.getProject()).thenReturn(project);
   new BuildVariableResolver(build, launcher);
   verify(build).getProject();
   verifyZeroInteractions(project);
   verifyZeroInteractions(launcher);
 }
Ejemplo n.º 17
0
  /**
   * Verify we do not actively perform any actions during the destroy.
   *
   * @throws Exception
   */
  @Test
  public void VerifyActivatorDestroy() throws Exception {

    m_activator.destroy(m_context, m_manager);

    Mockito.verifyZeroInteractions(m_context);
    Mockito.verifyZeroInteractions(m_manager);
  }
 @Test
 @SuppressWarnings("unchecked")
 public void testManifestation() throws Exception {
   LatentMatcher<Object> matcher = new LatentMatcher.Resolved<Object>(this.matcher);
   assertThat(matcher.resolve(typeDescription), is((ElementMatcher) this.matcher));
   verifyZeroInteractions(this.matcher);
   verifyZeroInteractions(typeDescription);
 }
  @Test
  public void updateAuthenticatedContributorProfile() {
    AuthenticationUtilService tested = getTested();
    // case - nobody is authenticated
    {
      Mockito.when(tested.httpRequest.getUserPrincipal()).thenReturn(null);

      Assert.assertFalse(tested.updateAuthenticatedContributorProfile());
      Mockito.verifyZeroInteractions(tested.contributorProfileService);
    }

    Principal p = Mockito.mock(Principal.class);
    // case - provider is authenticated
    {
      Mockito.reset(tested.contributorProfileService, tested.httpRequest);
      Mockito.when(tested.httpRequest.getUserPrincipal()).thenReturn(p);
      Mockito.when(tested.httpRequest.isUserInRole(Role.PROVIDER)).thenReturn(true);

      Assert.assertFalse(tested.updateAuthenticatedContributorProfile());
      Mockito.verifyZeroInteractions(tested.contributorProfileService);
    }

    // case - contributor is authenticated but username not in principal
    {
      Mockito.reset(tested.contributorProfileService, tested.httpRequest, p);
      Mockito.when(tested.httpRequest.getUserPrincipal()).thenReturn(p);
      Mockito.when(tested.httpRequest.isUserInRole(Role.CONTRIBUTOR)).thenReturn(true);

      Assert.assertFalse(tested.updateAuthenticatedContributorProfile());
      Mockito.verifyZeroInteractions(tested.contributorProfileService);
      Mockito.verify(p).getName();
    }

    // case - contributor is authenticated, username is in principal
    {
      p = new ContributorPrincipal("uname");
      Mockito.reset(tested.contributorProfileService, tested.httpRequest);
      Mockito.when(tested.httpRequest.getUserPrincipal()).thenReturn(p);
      Mockito.when(tested.httpRequest.isUserInRole(Role.CONTRIBUTOR)).thenReturn(true);

      Assert.assertTrue(tested.updateAuthenticatedContributorProfile());
      Mockito.verify(tested.contributorProfileService)
          .createOrUpdateProfile(
              ContributorProfileService.FIELD_TSC_JBOSSORG_USERNAME, "uname", false);
      Mockito.verifyNoMoreInteractions(tested.contributorProfileService);
    }

    // case - contributor is authenticated, unsupported type of principal
    {
      p = Mockito.mock(Principal.class);
      Mockito.reset(tested.contributorProfileService, tested.httpRequest);
      Mockito.when(tested.httpRequest.getUserPrincipal()).thenReturn(p);
      Mockito.when(tested.httpRequest.isUserInRole(Role.CONTRIBUTOR)).thenReturn(true);

      Assert.assertFalse(tested.updateAuthenticatedContributorProfile());
      Mockito.verifyNoMoreInteractions(tested.contributorProfileService);
    }
  }
Ejemplo n.º 20
0
  @Test
  public void testBuildUseCaseObservable() throws Exception {
    getRepoList.buildUseCaseObservable();

    verify(mockGithubRepository).repos();
    verifyNoMoreInteractions(mockGithubRepository);
    verifyZeroInteractions(mockThreadExecutor);
    verifyZeroInteractions(mockPostExecutionThread);
  }
Ejemplo n.º 21
0
  /**
   * Test add 0 obligations with no time based trigger on an existing Pii The Obligation Handler
   * should call 0 times persistObject on ObligationTriggerDao, no interaction on Time Based
   * Triggers Handler
   */
  @Test
  public void testAddObligationsEmptyObligationSet() {
    final ObligationsSet obligationSet = new ObligationsSet();
    obligationSet.setObligation(new ArrayList<Obligation>());

    obligationHandler.addObligations(obligationSet, pii);

    verifyZeroInteractions(otDao);
    verifyZeroInteractions(timeBasedTriggerHandler);
  }
  @Test
  public void testHandleEvent_noContext() {

    Application app = new Application("app", new TestApplicationTemplate());
    ManagedApplication ma = new ManagedApplication(app);
    this.autonomicMngr.handleEvent(ma, new MsgNotifAutonomic("app", "/root", "event", null));

    Mockito.verifyZeroInteractions(this.commandsMngr);
    Mockito.verifyZeroInteractions(this.preferencesMngr);
    Assert.assertEquals(0, this.autonomicMngr.getAutonomicInstancesCount());
  }
  @Test
  public void shouldNotDoAnythingIfMotherIsNotRegistered() {
    when(allMothers.findByCaseId("entity id 1")).thenReturn(null);

    service.close(create().build());

    verifyZeroInteractions(pncSchedulesService);
    verifyZeroInteractions(allEligibleCouples);
    verifyZeroInteractions(motherReportingService);
    verifyZeroInteractions(actionService);
  }
Ejemplo n.º 24
0
  @Test
  public void testElementChainIsLazy() {
    WebElement element1Proxy =
        LocatorProxies.createWebElement(
            new ElementLocator() {
              @Override
              public WebElement findElement() {
                return driver.findElement(By.cssSelector("#element1"));
              }

              @Override
              public List<WebElement> findElements() {
                return Arrays.asList(findElement());
              }
            });

    WebElement element2Proxy =
        LocatorProxies.createWebElement(
            new ElementLocator() {
              @Override
              public WebElement findElement() {
                return element1Proxy.findElement(By.cssSelector("#element2"));
              }

              @Override
              public List<WebElement> findElements() {
                return Arrays.asList(findElement());
              }
            });

    WebElement element3Proxy =
        LocatorProxies.createWebElement(
            new ElementLocator() {
              @Override
              public WebElement findElement() {
                return element2Proxy.findElement(By.cssSelector("#element3"));
              }

              @Override
              public List<WebElement> findElements() {
                return Arrays.asList(findElement());
              }
            });

    verifyZeroInteractions(driver);
    verifyZeroInteractions(element1);
    verifyZeroInteractions(element2);
    verifyZeroInteractions(element3);

    element3Proxy.click();
    verify(driver).findElement(By.cssSelector("#element1"));
    verify(element1).findElement(By.cssSelector("#element2"));
    verify(element2).findElement(By.cssSelector("#element3"));
  }
  @Test
  public void shouldNotDoAnythingIfMotherIsNotFoundDuringPNCVisit() throws Exception {
    FormSubmission submission = create().withFormName("pnc_visit").build();

    when(allMothers.exists("entity id 1")).thenReturn(false);

    service.pncVisitHappened(submission);

    verify(allMothers).findByCaseId("entity id 1");
    verifyZeroInteractions(motherReportingService);
    verifyZeroInteractions(childReportingService);
  }
Ejemplo n.º 26
0
 @Theory
 public <E> void parsesErrorScanReply(
     @ForAll @From(Encoded.class) @Encoded.InCharset("US-ASCII") String s,
     @TestedOn(ints = {1, 2, 3, 5, 100}) int bufferSize) {
   @SuppressWarnings("unchecked")
   ArrayBuilderFactory<E, ?> arrayBuilderFactory = mock(ArrayBuilderFactory.class);
   @SuppressWarnings("unchecked")
   BulkStringBuilderFactory<?, E> bulkStringBuilderFactory = mock(BulkStringBuilderFactory.class);
   parsesError(s, bufferSize, scanReply(arrayBuilderFactory, bulkStringBuilderFactory));
   verifyZeroInteractions(arrayBuilderFactory);
   verifyZeroInteractions(bulkStringBuilderFactory);
 }
  /**
   * Test prefetchDeltaSignerInfo for multiple requests on different domains where the first one
   * does not terminate. However the second should terminate, and both callbacks called.
   */
  public void test_prefetchDeltaSignerInfo3() throws Exception {
    // This will never return, but the callback will run later
    SignerInfoPrefetchResultListener deadListener = mock(SignerInfoPrefetchResultListener.class);

    manager.prefetchDeltaSignerInfo(
        getDeadProvider(),
        getRealSignerId(),
        getFakeWaveletName(CertificateManagerImplTest.DOMAIN),
        null,
        deadListener);
    verifyZeroInteractions(deadListener);

    // This should succeed later, after some number of ticks
    SignerInfoPrefetchResultListener slowSuccessListener =
        mock(SignerInfoPrefetchResultListener.class);

    manager.prefetchDeltaSignerInfo(
        getSlowSuccessfulProvider(ticker, EASY_TICKS),
        getRealSignerId(),
        getFakeWaveletName(OTHER_DOMAIN),
        null,
        slowSuccessListener);
    verifyZeroInteractions(slowSuccessListener);

    // This would succeed right now if it didn't have to wait for the slow success
    SignerInfoPrefetchResultListener successListener = mock(SignerInfoPrefetchResultListener.class);

    manager.prefetchDeltaSignerInfo(
        getSuccessfulProvider(),
        getRealSignerId(),
        getFakeWaveletName(OTHER_DOMAIN),
        null,
        successListener);
    verifyZeroInteractions(successListener);

    // After ticking, each callback should run
    ticker.tick(EASY_TICKS);
    verify(deadListener).onSuccess(Certificates.getRealSignerInfo().toProtoBuf());
    verify(slowSuccessListener).onSuccess(Certificates.getRealSignerInfo().toProtoBuf());
    verify(successListener).onSuccess(Certificates.getRealSignerInfo().toProtoBuf());

    // Subsequent calls should also succeed immediately without calling the callback
    SignerInfoPrefetchResultListener nullListener = mock(SignerInfoPrefetchResultListener.class);

    manager.prefetchDeltaSignerInfo(
        null,
        getRealSignerId(),
        getFakeWaveletName(CertificateManagerImplTest.DOMAIN),
        null,
        nullListener);
    verify(nullListener).onSuccess(Certificates.getRealSignerInfo().toProtoBuf());
  }
Ejemplo n.º 28
0
  @Test
  public void shouldNotEvaluateTailWhenZippingTwoSequences() throws Exception {
    // given
    final LazySeq<String> first = cons("A", firstSupplier);
    final LazySeq<Integer> second = cons(1, secondSupplier);

    // when
    first.zip(second, (a, b) -> a + b);

    // then
    verifyZeroInteractions(firstSupplier);
    verifyZeroInteractions(secondSupplier);
  }
Ejemplo n.º 29
0
  @Test
  public void not_recreate_built_in_profiles_from_another_language() throws Exception {
    RulesProfile profile = RulesProfile.create("Default", "java");
    profile.activateRule(Rule.create("pmd", "rule").setSeverity(RulePriority.BLOCKER), null);
    ProfileDefinition profileDefinition = mock(ProfileDefinition.class);
    when(profileDefinition.createProfile(any(ValidationMessages.class))).thenReturn(profile);
    definitions.add(profileDefinition);

    backup.recreateBuiltInProfilesByLanguage("js");

    verifyZeroInteractions(qProfileOperations);
    verifyZeroInteractions(qProfileActiveRuleOperations);
  }
Ejemplo n.º 30
0
 @Test
 public void returnsIfTargetIsNullOnError() throws Exception {
   Picasso picasso = mock(Picasso.class);
   ImageView target = mockImageViewTarget();
   Callback callback = mockCallback();
   ImageViewAction request =
       new ImageViewAction(
           picasso, target, null, false, false, 0, null, URI_KEY_1, null, callback);
   request.target.clear();
   request.error();
   verifyZeroInteractions(target);
   verifyZeroInteractions(callback);
 }