@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 testOnNodeRemoved() {
   OperationsNodeInfo nodeInfo = Mockito.mock(OperationsNodeInfo.class);
   ConnectionInfo connectionInfo = Mockito.mock(ConnectionInfo.class);
   Mockito.when(nodeInfo.getConnectionInfo()).thenReturn(connectionInfo);
   Map<String, OperationsNodeInfo> opsMap = Mockito.mock(Map.class);
   ReflectionTestUtils.setField(service, "opsMap", opsMap);
   DefaultOperationsServerListService.Memorizer memorizer =
       Mockito.mock(DefaultOperationsServerListService.Memorizer.class);
   ReflectionTestUtils.setField(service, "cache", memorizer);
   service.onNodeRemoved(nodeInfo);
   Mockito.verify(opsMap, Mockito.only()).remove(Mockito.anyString());
   Mockito.verify(memorizer, Mockito.only()).clear();
 }
  @Test
  public void copyToDelegatesToDescriptorFactoryAndUsesReturnedDescriptor() {
    // Arrange:
    final TestContext context = new TestContext();
    final WalletNamePasswordPair pair = createPair("n", "p");
    final OutputStream outputStream = Mockito.mock(OutputStream.class);
    Mockito.when(context.descriptor.openRead(StorableEntityReadMode.Raw))
        .thenReturn(new ByteArrayInputStream("test".getBytes()));

    // Act:
    context.walletServices.copyTo(pair, outputStream);

    // Assert:
    Mockito.verify(context.descriptorFactory, Mockito.only())
        .openExisting(pair, new WalletFileExtension());
    Mockito.verify(context.descriptor, Mockito.only()).openRead(StorableEntityReadMode.Raw);
  }
  @Test
  public void testNotificationsWhenUndeployingScopedInstances_changeInstanceState()
      throws Exception {

    // Prepare stuff
    final TestApplication app = new TestApplication();
    final Map<Instance, List<InstanceStatus>> instanceToStatusHistory = new HashMap<>();
    INotificationMngr notificationMngr =
        new NotificationMngrImpl() {
          @Override
          public void instance(Instance instance, Application application, EventType eventType) {

            Assert.assertEquals(EventType.CHANGED, eventType);
            Assert.assertEquals(app, application);

            List<InstanceStatus> status = instanceToStatusHistory.get(instance);
            if (status == null) {
              status = new ArrayList<>();
              instanceToStatusHistory.put(instance, status);
            }

            status.add(instance.getStatus());
          }
        };

    ITargetsMngr targetsMngr = Mockito.mock(ITargetsMngr.class);
    IRandomMngr randomMngr = Mockito.mock(IRandomMngr.class);
    ITargetConfigurator targetConfigurator = Mockito.mock(ITargetConfigurator.class);

    IMessagingMngr messagingMngr = Mockito.mock(IMessagingMngr.class);
    Mockito.when(messagingMngr.getMessagingClient()).thenReturn(Mockito.mock(IDmClient.class));

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

    IInstancesMngr mngr =
        new InstancesMngrImpl(
            messagingMngr, notificationMngr, targetsMngr, randomMngr, targetConfigurator);
    ((InstancesMngrImpl) mngr).setTargetHandlerResolver(new TestTargetResolver());

    // Make one of our VM being fully deployed
    ManagedApplication ma = new ManagedApplication(app);
    app.getTomcatVm().setStatus(InstanceStatus.DEPLOYED_STARTED);
    app.getTomcat().setStatus(InstanceStatus.DEPLOYED_STARTED);
    app.getWar().setStatus(InstanceStatus.DEPLOYED_STARTED);

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

    // Stop everything
    mngr.changeInstanceState(ma, app.getTomcatVm(), InstanceStatus.NOT_DEPLOYED);

    // Check notifications
    Assert.assertEquals(3, instanceToStatusHistory.size());
    List<InstanceStatus> statusHistory = instanceToStatusHistory.get(app.getTomcatVm());
    Assert.assertNotNull(statusHistory);
    Assert.assertEquals(
        Arrays.asList(InstanceStatus.UNDEPLOYING, InstanceStatus.NOT_DEPLOYED), statusHistory);

    statusHistory = instanceToStatusHistory.get(app.getTomcat());
    Assert.assertNotNull(statusHistory);
    Assert.assertEquals(Arrays.asList(InstanceStatus.NOT_DEPLOYED), statusHistory);

    statusHistory = instanceToStatusHistory.get(app.getWar());
    Assert.assertNotNull(statusHistory);
    Assert.assertEquals(Arrays.asList(InstanceStatus.NOT_DEPLOYED), statusHistory);

    Mockito.verify(targetConfigurator, Mockito.only())
        .cancelCandidate(Mockito.any(TargetHandlerParameters.class), Mockito.eq(app.getTomcatVm()));
  }
  @Test
  public void testRestoreInstances_rightHandler_vmNotRunning() throws Exception {

    // Prepare stuff
    Map<String, String> targetProperties = new HashMap<>(0);

    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(targetProperties);

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

    final TargetHandler targetHandlerArgument = Mockito.mock(TargetHandler.class);
    Mockito.when(targetHandlerArgument.getTargetId()).thenReturn("some 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 targetHandlerArgument;
              }
            });

    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
    Assert.assertEquals(InstanceStatus.NOT_DEPLOYED, app.getMySqlVm().getStatus());
    app.getMySqlVm().setStatus(InstanceStatus.DEPLOYED_STARTED);

    Mockito.when(
            targetHandlerArgument.isMachineRunning(
                Mockito.any(TargetHandlerParameters.class), Mockito.eq("machine-id")))
        .thenReturn(false);

    mngr.restoreInstanceStates(ma, targetHandlerArgument);
    Assert.assertEquals(InstanceStatus.NOT_DEPLOYED, app.getMySqlVm().getStatus());

    // The handler's ID matched and the VM is NOT running => no message was sent.
    Mockito.verify(targetsMngr, Mockito.only())
        .findRawTargetProperties(Mockito.eq(app), Mockito.anyString());
    Mockito.verify(targetHandlerArgument, Mockito.times(1))
        .isMachineRunning(Mockito.any(TargetHandlerParameters.class), Mockito.eq("machine-id"));

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

    // A notification was sent for the instance whose state changed
    Mockito.verify(notificationMngr)
        .instance(Mockito.any(Instance.class), Mockito.eq(app), Mockito.eq(EventType.CHANGED));
  }