/**
   * Test the temporary certificate import by using a valid domestic DV certificate and checking if
   * the internal variables representing the last temporary imported certificate are set.
   */
  @Test
  public void testImportCertificateTemporary() {
    // prepare the mock
    new NonStrictExpectations() {
      {
        mockedCardStateAccessor.getObject(
            withInstanceOf(TrustPointIdentifier.class), withInstanceOf(Scope.class));
        result = trustPoint;
        mockedCardStateAccessor.getObject(
            withInstanceOf(DateTimeObjectIdentifier.class), withInstanceOf(Scope.class));
        result = currentDate;
        certificate.getEffectiveDate();
        result = current;
        certificate.getExpirationDate();
        result = future;
        certificate.getCertificateHolderAuthorizationTemplate();
        result = isDvDomesticChat;
        certificate.getCertificateHolderReference();
        result = chr;
      }
    };

    // call MUT
    Deencapsulation.invoke(taProtocol, "importCertificate", certificate, issuingCertificate);

    assertEquals(
        Deencapsulation.getField(taProtocol, "mostRecentTemporaryCertificate"), certificate);
  }
  /** test proper scheduling of updates */
  @Test
  public void testUpdateScheduling(
      @Mocked(
              methods = {"scheduleLocationUpdates"},
              inverse = true)
          final LegacyLocationProcessor llp,
      @Mocked final LocationManager locationManager,
      @Mocked final Intent intent,
      @Mocked final PendingIntent pi,
      @Mocked final Context context) {

    Deencapsulation.setField(llp, "locationManager", locationManager);
    Deencapsulation.setField(llp, "sendUpdatesIntent", intent);
    Deencapsulation.setField(llp, "context", context);

    new Expectations() {
      {
        PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        returns(pi);
        locationManager.requestLocationUpdates("bramble", 0, 0, pi);
      }
    };

    Deencapsulation.invoke(llp, "scheduleLocationUpdates", "bramble");
  }
  /** shall shedule location update properly */
  @Test
  public void testScheduleCancelation(
      @Mocked(
              methods = {"scheduleCancelationIntent"},
              inverse = true)
          final LegacyLocationProcessor llp,
      @Mocked final AlarmManager alarmManager,
      @Mocked System system,
      @Mocked final PendingIntent pendingIntent,
      @Mocked final Intent intent,
      @Mocked final Context context) {

    Deencapsulation.setField(llp, "stopUpdatesIntent", intent);
    Deencapsulation.setField(llp, "context", context);

    new Expectations() {
      {
        PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        returns(pendingIntent);

        context.getSystemService(Context.ALARM_SERVICE);
        returns(alarmManager);

        System.currentTimeMillis();
        returns(239l);

        alarmManager.set(
            AlarmManager.ELAPSED_REALTIME,
            239 + LegacyLocationProcessor.CANCEL_INTERVAL,
            pendingIntent);
      }
    };

    Deencapsulation.invoke(llp, "scheduleCancelationIntent");
  }
  @Test
  public void testExtractTerminalSector() {
    // prepare the mock
    final HashSet<CertificateExtension> extensions = new HashSet<>();
    extensions.add(certificateExtension);

    PrimitiveTlvDataObject firstObject =
        new PrimitiveTlvDataObject(TlvConstants.TAG_80, new byte[] {1, 2, 3, 4});
    PrimitiveTlvDataObject secondObject =
        new PrimitiveTlvDataObject(TlvConstants.TAG_81, new byte[] {5, 6, 7, 8});
    final TlvDataObjectContainer dataObjects = new TlvDataObjectContainer(firstObject);
    dataObjects.addTlvDataObject(secondObject);

    new NonStrictExpectations() {
      {
        certificate.getCertificateExtensions();
        result = extensions;
        certificateExtension.getObjectIdentifier();
        result = TaOid.id_Sector;
        certificateExtension.getDataObjects();
        result = dataObjects;
      }
    };
    Deencapsulation.invoke(taProtocol, "extractTerminalSector", certificate);
    assertArrayEquals(
        firstObject.getValueField(),
        (byte[]) Deencapsulation.getField(taProtocol, "firstSectorPublicKeyHash"));
    assertArrayEquals(
        secondObject.getValueField(),
        (byte[]) Deencapsulation.getField(taProtocol, "secondSectorPublicKeyHash"));
  }
  @Test
  public void testSampleCommandArgTypes() {

    Deencapsulation.invoke(sut, "scanClasspathForCommands");
    Map commandArgTypes = Deencapsulation.getField(sut, "commandTypesMap");

    assertTrue(commandArgTypes.size() > 0);

    List types = (List) commandArgTypes.get("sample");

    assertNotNull(types);

    assertEquals(1, types.size());
    assertEquals(String.class, types.get(0));
  }
  // Tests_SRS_AMQPSIOTHUBCONNECTIONBASEHANDLER_14_046: [The function shall open the Sender (Proton)
  // link.]
  // Tests_SRS_AMQPSIOTHUBCONNECTIONBASEHANDLER_14_047: [The function shall return a new
  // CompletableFuture for the sent message.]
  // Tests_SRS_AMQPSIOTHUBCONNECTIONBASEHANDLER_14_048: [The function shall lock sending on the
  // AmqpsIotHubConnection.]
  @Test
  public void createBinaryMessageOpensSenderAndLocksSending(
      @Mocked final CompletableFuture<Integer> mockFuture) {
    final String hostName = "test.host.name";
    final String deviceId = "test-deviceId";
    final String userName = "******";
    final String sasToken = "test-token";
    final byte[] msgBody = {0x61, 0x62, 0x63};
    final Object messageId = "123";

    new NonStrictExpectations() {
      {
        new CompletableFuture<Integer>();
        result = mockFuture;
      }
    };

    AmqpsIotHubConnectionBaseHandler handler =
        new AmqpsIotHubConnectionBaseHandler(
            hostName, userName, sasToken, deviceId, mockIotHubConnection);
    Deencapsulation.setField(handler, "sender", mockSender);

    CompletableFuture<Integer> actualFuture = handler.createBinaryMessage(msgBody, messageId);

    assertEquals(CompletableFuture.class, actualFuture.getClass());

    new Verifications() {
      {
        Deencapsulation.invoke(mockIotHubConnection, "lockSending");
        mockSender.open();
      }
    };
  }
  // Tests_SRS_AMQPSIOTHUBCONNECTIONBASEHANDLER_14_043: [The function shall create a Binary (Proton)
  // object from the content array.]
  // Tests_SRS_AMQPSIOTHUBCONNECTIONBASEHANDLER_14_044: [The function shall create a data Section
  // (Proton) object from the Binary.]
  // Tests_SRS_AMQPSIOTHUBCONNECTIONBASEHANDLER_14_045: [The function shall set the Message body to
  // the created data Section.]
  @Test
  public void createBinaryMessageSetsBodyFromContent() {
    final String hostName = "test.host.name";
    final String deviceId = "test-deviceId";
    final String userName = "******";
    final String sasToken = "test-token";
    final byte[] msgBody = {0x61, 0x62, 0x63};
    final Object messageId = "123";

    AmqpsIotHubConnectionBaseHandler handler =
        new AmqpsIotHubConnectionBaseHandler(
            hostName, userName, sasToken, deviceId, mockIotHubConnection);
    Deencapsulation.setField(handler, "sender", mockSender);

    handler.createBinaryMessage(msgBody, messageId);

    new Verifications() {
      {
        mockBinary = new Binary(msgBody);
        mockSection = new Data(mockBinary);
        Message m = Deencapsulation.getField(handler, "outgoingMessage");
        m.setBody(mockSection);
      }
    };
  }
  // Tests_SRS_AMQPSIOTHUBCONNECTIONBASEHANDLER_14_041: [The function shall set the ‘to’ property on
  // the Message object using the created event path.]
  // Tests_SRS_AMQPSIOTHUBCONNECTIONBASEHANDLER_14_042: [The function shall set the ‘messageId’
  // property on the Message object if the messageId is not null.]
  @Test
  public void createBinaryMessageSetsToPropertyAndMessageIDIfNotNull() {
    final String hostName = "test.host.name";
    final String deviceId = "test-deviceId";
    final String userName = "******";
    final String sasToken = "test-token";
    final byte[] msgBody = {0x61, 0x62, 0x63};
    final Object messageId = "123";
    final String expectedEndpoint = "/devices/test-deviceId/messages/events";

    new NonStrictExpectations() {
      {
        new Properties();
        result = mockProperties;
      }
    };

    AmqpsIotHubConnectionBaseHandler handler =
        new AmqpsIotHubConnectionBaseHandler(
            hostName, userName, sasToken, deviceId, mockIotHubConnection);
    Deencapsulation.setField(handler, "sender", mockSender);
    handler.createBinaryMessage(msgBody, null);
    handler.createBinaryMessage(msgBody, messageId);

    new Verifications() {
      {
        mockProperties.setTo(expectedEndpoint);
        times = 2;
        mockProperties.setMessageId(messageId);
        times = 1;
        mockMessage.setProperties(mockProperties);
        times = 2;
      }
    };
  }
  /** Sets the up. */
  @Before
  public void setUp() {
    this.dynamicAuthenticationFilter = new DynamicAuthenticationFilter();

    this.request = Mockito.mock(MockServletRequest.class, Mockito.CALLS_REAL_METHODS);
    Deencapsulation.setField(this.request, new HashMap<String, String>());
  }
  // Tests_SRS_AMQPSIOTHUBCONNECTIONBASEHANDLER_14_016: [If the link was locally closed before the
  // current message is sent, the sent message CompletableFuture will be completed exceptionally
  // with a new HandlerException.]
  @Test
  public void onLinkLocalCloseClosesBeforeSendCompletesExceptionally(
      @Mocked final CompletableFuture<Integer> mockFuture) {
    final String hostName = "test.host.name";
    final String deviceId = "test-deviceId";
    final String userName = "******";
    final String sasToken = "test-token";
    final String receiveTag = "receiver";

    new NonStrictExpectations() {
      {
        mockEvent.getLink();
        result = mockReceiver;
        mockReceiver.getName();
        result = receiveTag;
        mockFuture.isDone();
        result = false;
      }
    };

    AmqpsIotHubConnectionBaseHandler handler =
        new AmqpsIotHubConnectionBaseHandler(
            hostName, userName, sasToken, deviceId, mockIotHubConnection);

    Deencapsulation.setField(handler, "currentSentMessageFuture", mockFuture);
    handler.onLinkLocalClose(mockEvent);

    new Verifications() {
      {
        mockFuture.completeExceptionally((HandlerException) any);
      }
    };
  }
  // Tests_SRS_AMQPSIOTHUBCONNECTIONBASEHANDLER_14_022: [If the link is the Sender link and the
  // message was sent successfully over this link, the event handler shall reset the private Sender
  // (Proton) member variable and open the AmqpsIotHubConnection for sending.]
  @Test
  public void onLinkRemoteCloseResetsSenderAndOpens(
      @Mocked final CompletableFuture<Integer> mockFuture) {
    final String hostName = "test.host.name";
    final String deviceId = "test-deviceId";
    final String userName = "******";
    final String sasToken = "test-token";
    final String sendTag = "sender";

    new NonStrictExpectations() {
      {
        mockEvent.getLink();
        result = mockSender;
        mockSender.getName();
        result = sendTag;
        mockFuture.isCompletedExceptionally();
        result = false;
      }
    };

    AmqpsIotHubConnectionBaseHandler handler =
        new AmqpsIotHubConnectionBaseHandler(
            hostName, userName, sasToken, deviceId, mockIotHubConnection);
    Deencapsulation.setField(handler, "currentSentMessageFuture", mockFuture);
    handler.onLinkRemoteClose(mockEvent);

    new Verifications() {
      {
        mockEvent.getSession().sender(sendTag);
        Deencapsulation.invoke(mockIotHubConnection, "openSending");
      }
    };
  }
  @Test
  public void testMultiArgCommand() {

    Command command =
        sut.instantiateCommand(
            "multiArg", new String[] {"string value", "5687", "true", "23"}, source());

    assertNotNull(command);

    assertTrue(command instanceof MultiArgCommand);

    assertEquals("string value", Deencapsulation.getField(command, "string"));
    assertEquals(5687, Deencapsulation.getField(command, "integer"));
    assertEquals(true, Deencapsulation.getField(command, "bool"));
    assertEquals((byte) 23, Deencapsulation.getField(command, "bytee"));
  }
  // Tests_SRS_AMQPSIOTHUBCONNECTIONBASEHANDLER_14_035: [If the Connection was remotely closed
  // abnormally, the event handler shall complete the sent message CompletableFuture with a new
  // HandlerException.]
  @Test
  public void onConnectionRemoteCloseClosesAbnormallyCompletesMessageExceptionally(
      @Mocked final CompletableFuture<Integer> mockFuture) {
    final String hostName = "test.host.name";
    final String deviceId = "test-deviceId";
    final String userName = "******";
    final String sasToken = "test-token";

    new NonStrictExpectations() {
      {
        mockEvent.getConnection();
        result = mockConnection;
        mockConnection.getCondition();
        result = new ErrorCondition();
      }
    };

    AmqpsIotHubConnectionBaseHandler handler =
        new AmqpsIotHubConnectionBaseHandler(
            hostName, userName, sasToken, deviceId, mockIotHubConnection);
    Deencapsulation.setField(handler, "currentSentMessageFuture", mockFuture);
    handler.onConnectionRemoteClose(mockEvent);

    new Verifications() {
      {
        mockFuture.completeExceptionally((HandlerException) any);
      }
    };
  }
  // Tests_SRS_AMQPSIOTHUBCONNECTIONBASEHANDLER_14_014: [If the event type is DELIVERY, the event
  // handler shall close the Sender link.]
  @Test
  public void onDeliveryClosesSender() {
    final String hostName = "test.host.name";
    final String deviceId = "test-deviceId";
    final String userName = "******";
    final String sasToken = "test-token";
    final String sendTag = "sender";

    new NonStrictExpectations() {
      {
        mockEvent.getLink();
        result = mockSender;
        mockSender.getName();
        result = sendTag;
        mockEvent.getType();
        result = Event.Type.DELIVERY;
        mockEvent.getDelivery();
        result = mockDelivery;
      }
    };

    AmqpsIotHubConnectionBaseHandler handler =
        new AmqpsIotHubConnectionBaseHandler(
            hostName, userName, sasToken, deviceId, mockIotHubConnection);

    Deencapsulation.setField(handler, "sender", mockSender);

    handler.onDelivery(mockEvent);

    new Verifications() {
      {
        mockSender.close();
      }
    };
  }
 @Test
 public void testGetVmStateReturnsCorrectResults() {
   assertEquals(
       VmState.ERROR,
       Deencapsulation.invoke(azurePackVirtualMachineSupport, "getVmState", "Update Failed"));
   assertEquals(
       VmState.ERROR,
       Deencapsulation.invoke(azurePackVirtualMachineSupport, "getVmState", "Creation Failed"));
   assertEquals(
       VmState.ERROR,
       Deencapsulation.invoke(
           azurePackVirtualMachineSupport, "getVmState", "Customization Failed"));
   assertEquals(
       VmState.ERROR,
       Deencapsulation.invoke(azurePackVirtualMachineSupport, "getVmState", "Missing"));
   assertEquals(
       VmState.PENDING,
       Deencapsulation.invoke(azurePackVirtualMachineSupport, "getVmState", "Creating..."));
   assertEquals(
       VmState.PENDING,
       Deencapsulation.invoke(
           azurePackVirtualMachineSupport, "getVmState", "UnrecognizableState"));
   assertEquals(
       VmState.RUNNING,
       Deencapsulation.invoke(azurePackVirtualMachineSupport, "getVmState", "running"));
 }
  /** test proper initialisation sequence. */
  @Test
  public void testProperInitialisation(
      @Mocked final Context context,
      @Mocked final Configuration configuration,
      @Mocked final LocationManager locationManager,
      @Mocked final Intent req,
      @Mocked final Intent cancel) {
    new Expectations() {
      {
        Configuration.getInstance(context);
        returns(configuration);
        context.getSystemService(Context.LOCATION_SERVICE);
        returns(locationManager);

        new Intent(LocationProcessor.LOCATION_CHANGE_INTENT);
        returns(req);

        new Intent(LocationProcessor.LOCATION_CHANGE_INTENT)
            .putExtra(LocationProcessor.LOCATION_STOP_UPDATES, withAny("string"));
        returns(cancel);
      }
    };

    final LegacyLocationProcessor llp = new LegacyLocationProcessor(context);

    assertSame(context, Deencapsulation.getField(llp, "context"));
    assertSame(configuration, Deencapsulation.getField(llp, "configuration"));
    assertSame(locationManager, Deencapsulation.getField(llp, "locationManager"));

    //  System.err.println("send: " + req);
    //  System.err.println("send: " + Deencapsulation.getField(llp, "sendUpdatesIntent"));
    //  System.err.println("cancel: " + cancel);
    //  System.err.println("cancel: " + Deencapsulation.getField(llp, "stopUpdatesIntent"));

    // TODO: this fails for unknown cause , investigate.
    // assertSame(req, Deencapsulation.getField(llp, "sendUpdatesIntent"));

    assertSame(cancel, Deencapsulation.getField(llp, "stopUpdatesIntent"));

    // nothing else is allowed
    new FullVerifications() {
      {
      }
    };
  }
  // Tests_SRS_AMQPSIOTHUBCONNECTIONBASEHANDLER_14_017: [The event handler shall get the Sender
  // (Proton) object from the link.]
  // Tests_SRS_AMQPSIOTHUBCONNECTIONBASEHANDLER_14_018: [The event handler shall encode the message
  // and copy the contents to the byte buffer.]
  // Tests_SRS_AMQPSIOTHUBCONNECTIONBASEHANDLER_14_019: [The event handler shall set the delivery
  // tag on the Sender (Proton) object.]
  // Tests_SRS_AMQPSIOTHUBCONNECTIONBASEHANDLER_14_020: [The event handler shall send the encoded
  // bytes.]
  // Tests_SRS_AMQPSIOTHUBCONNECTIONBASEHANDLER_14_021: [The event handler shall advance the Sender
  // and complete the sent message CompletableFuture using the Delivery (Proton) object hash code.]
  @Test
  public void onLinkFlowFullTest(@Mocked final CompletableFuture<Integer> mockFuture) {
    final String hostName = "test.host.name";
    final String deviceId = "test-deviceId";
    final String userName = "******";
    final String sasToken = "test-token";
    final byte[] msgBody = {0x61, 0x62, 0x63};
    final int tag = 0;

    new NonStrictExpectations() {
      {
        mockMessage.encode(msgBody, 0, msgBody.length);
        result = 3;
        mockEvent.getLink();
        result = mockSender;
        mockSender.getCredit();
        result = 1;
        mockSender.getUnsettled();
        result = 0;
      }
    };

    AmqpsIotHubConnectionBaseHandler handler =
        new AmqpsIotHubConnectionBaseHandler(
            hostName, userName, sasToken, deviceId, mockIotHubConnection);

    Deencapsulation.setField(handler, "sender", mockSender);
    Deencapsulation.setField(handler, "currentSentMessageFuture", mockFuture);
    handler.createBinaryMessage(msgBody, null);
    handler.onLinkFlow(mockEvent);

    new Verifications() {
      {
        mockEvent.getLink();
        byte[] buffer = new byte[1024];
        int length = mockMessage.encode(buffer, 0, buffer.length);
        byte[] deliveryTag = String.valueOf(tag).getBytes();
        Delivery d = mockSender.delivery(deliveryTag);
        mockSender.send((byte[]) any, 0, length);

        mockSender.advance();
        mockFuture.complete(d.hashCode());
      }
    };
  }
  @Test(groups = "AllEnv")
  public void getWindowLocationを呼ばれても設定にない場合は初期設定位置を返すよ() {
    Deencapsulation.setField(ServerProperties.INSTANCE, "fProperties", new Properties());

    final Point actual = ServerProperties.INSTANCE.getWindowLocation();

    assertEquals(actual.x, 0);
    assertEquals(actual.y, 0);
  }
  @Test(groups = "AllEnv")
  public void getWindowSizeを呼ばれても設定にない場合は初期設定サイズを返すよ() {
    Deencapsulation.setField(ServerProperties.INSTANCE, "fProperties", new Properties());

    final Dimension actual = ServerProperties.INSTANCE.getWindowSize();

    assertEquals(actual.width, 250);
    assertEquals(actual.height, 250);
  }
  /** shall request updates from enabled providers and */
  @Test
  public void testProperUpdateRequest(
      @Mocked final LocationManager locationManager,
      @Mocked final Context context,
      @Mocked final Configuration configuration,
      @Cascading Intent intent,
      @Mocked Log log,
      @Mocked(methods = {"scheduleLocationUpdates", "scheduleCancelationIntent"})
          final LegacyLocationProcessor llp) {

    Deencapsulation.setField(llp, "locationManager", locationManager);
    Deencapsulation.setField(llp, "configuration", configuration);
    new Expectations() {

      {
        configuration.getLocationProvider();
        returns("grumple|grample|grimple");

        locationManager.isProviderEnabled("grumple");
        returns(true);
        Log.d(LegacyLocationProcessor.LOG_TAG, withAny(""));
        invoke(llp, "scheduleLocationUpdates", "grumple");

        locationManager.isProviderEnabled("grample");
        returns(false);

        locationManager.isProviderEnabled("grimple");
        returns(true);

        Log.d(LegacyLocationProcessor.LOG_TAG, withAny(""));
        invoke(llp, "scheduleLocationUpdates", "grimple");

        invoke(llp, "scheduleCancelationIntent");
      }
    };

    llp.requestLocationUpdate();

    // nothing else is allowed
    new FullVerifications() {
      {
      }
    };
  }
  // Tests_SRS_AMQPSIOTHUBCONNECTIONBASEHANDLER_14_037: [If the Connection and Session (Proton) are
  // not opened before a constant number of seconds, this handler will inform the
  // AmqpsIotHubConnection that the Connection was not opened in time.]
  @Test(expected = ExecutionException.class)
  public void onConnectionLocalOpenTimesOut() throws ExecutionException, InterruptedException {
    final String hostName = "test.host.name";
    final String deviceId = "test-deviceId";
    final String userName = "******";
    final String sasToken = "test-token";

    AmqpsIotHubConnectionBaseHandler handler =
        new AmqpsIotHubConnectionBaseHandler(
            hostName, userName, sasToken, deviceId, mockIotHubConnection);

    Deencapsulation.setField(
        mockIotHubConnection, "reactorReady", new CompletableFuture<Boolean>());
    handler.onConnectionLocalOpen(mockEvent);
    CompletableFuture<Boolean> future =
        Deencapsulation.getField(mockIotHubConnection, "reactorReady");

    future.get();
  }
  @Test
  public void testSimpleCommand() {

    Command command = sut.instantiateCommand("sample", new String[] {"command argument"}, source());

    assertNotNull(command);

    assertTrue(command instanceof SampleCommand);

    assertEquals("command argument", Deencapsulation.getField(command, "arg"));
  }
  // Tests_SRS_AMQPSIOTHUBCONNECTIONBASEHANDLER_14_002: [The constructor shall copy all input
  // parameters to private member variables for event processing.]
  // Tests_SRS_AMQPSIOTHUBCONNECTIONBASEHANDLER_14_003: [The constructor shall concatenate the host
  // name with the port.]
  // Tests_SRS_AMQPSIOTHUBCONNECTIONBASEHANDLER_14_004: [The constructor shall initialize the sender
  // and receiver endpoint private member variables using the ENDPOINT_FORMAT constants and
  // deviceID.]
  // Tests_SRS_AMQPSIOTHUBCONNECTIONBASEHANDLER_14_005: [The constructor shall initialize a new
  // Handshaker (Proton) object to handle communication handshake.]
  // Tests_SRS_AMQPSIOTHUBCONNECTIONBASEHANDLER_14_006: [The constructor shall initialize a new
  // FlowController (Proton) object to handle communication flow.]
  @Test
  public void constructorCopiesAllData() {
    final String hostName = "test.host.name";
    final String deviceId = "test-deviceId";
    final String userName = "******";
    final String sasToken = "test-token";

    final AmqpsIotHubConnectionBaseHandler handler =
        new AmqpsIotHubConnectionBaseHandler(
            hostName, userName, sasToken, deviceId, mockIotHubConnection);

    final String expectedSendEndpoint = "/devices/test-deviceId/messages/events";
    final String expectedReceiveEndpoint = "/devices/test-deviceId/messages/devicebound";

    String actualHostName = Deencapsulation.getField(handler, "hostName");
    String actualDeviceId = Deencapsulation.getField(handler, "deviceID");
    String actualUserName = Deencapsulation.getField(handler, "userName");
    String actualSasToken = Deencapsulation.getField(handler, "sasToken");
    String actualSendEndpoint = Deencapsulation.getField(handler, "sendEndpoint");
    String actualReceiveEndpoint = Deencapsulation.getField(handler, "receiveEndpoint");

    assertEquals(String.format("%s:%d", hostName, PORT), actualHostName);
    assertEquals(userName, actualUserName);
    assertEquals(deviceId, actualDeviceId);
    assertEquals(sasToken, actualSasToken);
    assertEquals(expectedSendEndpoint, actualSendEndpoint);
    assertEquals(expectedReceiveEndpoint, actualReceiveEndpoint);

    new Verifications() {
      {
        mockHandshaker = new Handshaker();
        mockFlowController = new FlowController();
      }
    };
  }
  /** when locationis received, shall stop updates immediately */
  @Test
  public void testThatLocationRequestUsCanceledUponLocationReceiving(
      @Mocked("stopUpdates") final LegacyLocationProcessor llp,
      @NonStrict final Location location,
      @NonStrict Log log) {

    new Expectations() {
      {
        llp.stopUpdates();
      }
    };

    assertSame(location, llp.processLocationUpdate(location));
    assertSame(location, Deencapsulation.getField(llp, "cached"));
  }
 @Test
 public void testIsCertificateIssuerValidNegativeCvcaTerminal() {
   // prepare the mock
   new NonStrictExpectations() {
     {
       certificate.getCertificateHolderAuthorizationTemplate();
       result = isTerminalChat;
       issuingCertificate.getCertificateHolderAuthorizationTemplate();
       result = isCvcaChat;
     }
   };
   // call MUT
   assertTrue(
       !(boolean)
           Deencapsulation.invoke(
               taProtocol, "isCertificateIssuerValid", certificate, issuingCertificate));
 }
 /** Positive test for the date validity checks using domestic dv certificate */
 @Test
 public void testCheckValidityDvDomesticPositive() {
   // prepare the mock
   new NonStrictExpectations() {
     {
       mockedCardStateAccessor.getObject(
           withInstanceOf(DateTimeObjectIdentifier.class), withInstanceOf(Scope.class));
       result = currentDate;
       certificate.getCertificateHolderAuthorizationTemplate();
       result = isDvDomesticChat;
       certificate.getExpirationDate();
       result = future;
     }
   };
   // call MUT
   assertTrue(
       (boolean)
           Deencapsulation.invoke(taProtocol, "checkValidity", certificate, issuingCertificate));
 }
  /**
   * Positive test for the update date mechanism that uses an accurate terminal certificate (signed
   * by domestic DV)
   */
  @Test
  public void testUpdateDatePositive() {

    // prepare the mock
    new NonStrictExpectations() {
      {
        mockedCardStateAccessor.getObject(
            withInstanceOf(DateTimeObjectIdentifier.class), withInstanceOf(Scope.class));
        result = currentDate;
        certificate.getCertificateHolderAuthorizationTemplate();
        result = isCvcaChat;
        certificate.getEffectiveDate();
        result = future;
      }
    };

    // call MUT
    Deencapsulation.invoke(taProtocol, "updateDate", certificate, issuingCertificate);
    assertEquals(future, currentDate.getDate());
  }
  // Tests_SRS_AMQPSIOTHUBCONNECTIONBASEHANDLER_14_040: [The function shall create a new Message
  // (Proton) object.]
  @Test
  public void createBinaryMessageCreatesNewProtonMessage() {
    final String hostName = "test.host.name";
    final String deviceId = "test-deviceId";
    final String userName = "******";
    final String sasToken = "test-token";
    final byte[] msgBody = {0x61, 0x62, 0x63};

    AmqpsIotHubConnectionBaseHandler handler =
        new AmqpsIotHubConnectionBaseHandler(
            hostName, userName, sasToken, deviceId, mockIotHubConnection);
    Deencapsulation.setField(handler, "sender", mockSender);
    handler.createBinaryMessage(msgBody, null);

    new Verifications() {
      {
        mockMessage = mockProton.message();
      }
    };
  }
  // Tests_SRS_AMQPSIOTHUBCONNECTIONBASEHANDLER_14_036: [The event handler shall inform the
  // AmqpsIotHubConnection that the Reactor (Proton) is ready.]
  @Test
  public void onSessionRemoteOpenInformsReactorReady() {
    final String hostName = "test.host.name";
    final String deviceId = "test-deviceId";
    final String userName = "******";
    final String sasToken = "test-token";
    final CompletableFuture<Boolean> future = new CompletableFuture<>();

    AmqpsIotHubConnectionBaseHandler handler =
        new AmqpsIotHubConnectionBaseHandler(
            hostName, userName, sasToken, deviceId, mockIotHubConnection);

    Deencapsulation.setField(mockIotHubConnection, "reactorReady", future);
    handler.onSessionRemoteOpen(mockEvent);

    new Verifications() {
      {
        future.complete(new Boolean(true));
      }
    };
  }
  // Tests_SRS_AMQPSIOTHUBCONNECTIONBASEHANDLER_14_013: [If the event type is DELIVERY, the event
  // handler shall note the remote delivery state and use it and the Delivery (Proton) hash code to
  // inform the AmqpsIotHubConnection of the message receipt.]
  @Test
  public void onDeliveryAckToConnection() {
    final String hostName = "test.host.name";
    final String deviceId = "test-deviceId";
    final String userName = "******";
    final String sasToken = "test-token";
    final String sendTag = "sender";
    final int hash = 12345;

    new NonStrictExpectations() {
      {
        mockEvent.getLink();
        result = mockSender;
        mockSender.getName();
        result = sendTag;
        mockEvent.getType();
        result = Event.Type.DELIVERY;
        mockEvent.getDelivery();
        result = mockDelivery;
        mockDelivery.getRemoteState();
        result = Accepted.getInstance();
      }
    };

    AmqpsIotHubConnectionBaseHandler handler =
        new AmqpsIotHubConnectionBaseHandler(
            hostName, userName, sasToken, deviceId, mockIotHubConnection);

    Deencapsulation.setField(handler, "sender", mockSender);

    handler.onDelivery(mockEvent);

    new Verifications() {
      {
        mockEvent.getDelivery();
        mockDelivery.getRemoteState();
        Deencapsulation.invoke(mockIotHubConnection, "acknowledge", mockDelivery.hashCode(), true);
      }
    };
  }