@Test
  @SuppressWarnings("unchecked")
  public void testTarget() throws Exception {
    write = false;
    MockStages.setTargetCapture(
        new Target() {

          @Override
          public List<ConfigIssue> init(Info info, Context context) {
            return Collections.emptyList();
          }

          @Override
          public void write(Batch batch) throws StageException {
            write = true;
            Assert.assertEquals("offset2", batch.getSourceOffset());
          }

          @Override
          public void destroy() {}
        });

    PipelineRunner pipelineRunner = Mockito.mock(PipelineRunner.class);
    Mockito.when(pipelineRunner.getMetrics()).thenReturn(new MetricRegistry());
    Mockito.when(pipelineRunner.getRuntimeInfo()).thenReturn(Mockito.mock(RuntimeInfo.class));
    Pipeline pipeline =
        new Pipeline.Builder(
                MockStages.createStageLibrary(),
                new Configuration(),
                "name",
                "name",
                "0",
                MockStages.createPipelineConfigurationSourceProcessorTarget())
            .build(pipelineRunner);
    StagePipe pipe = (StagePipe) pipeline.getPipes()[8];
    BatchMakerImpl batchMaker = Mockito.mock(BatchMakerImpl.class);
    Mockito.when(batchMaker.getLanes()).thenReturn(ImmutableList.of("t"));

    BatchImpl batch = Mockito.mock(BatchImpl.class);
    Mockito.when(batch.getSourceOffset()).thenReturn("offset2");
    Mockito.when(batch.getSize()).thenReturn(1);

    PipeBatch pipeBatch = Mockito.mock(FullPipeBatch.class);
    Mockito.when(pipeBatch.startStage(Mockito.eq(pipe))).thenReturn(batchMaker);
    Mockito.when(pipeBatch.getBatch(Mockito.eq(pipe))).thenReturn(batch);
    Mockito.when(pipeBatch.getErrorSink()).thenReturn(new ErrorSink());

    Assert.assertTrue(pipe.init(new PipeContext()).isEmpty());
    pipe.process(pipeBatch);
    pipe.destroy();

    Mockito.verify(pipeBatch, Mockito.times(1)).startStage(Mockito.eq(pipe));
    Mockito.verify(pipeBatch, Mockito.times(1)).getBatch(Mockito.eq(pipe));
    Mockito.verify(pipeBatch, Mockito.times(1)).getPreviousOffset();
    Mockito.verify(pipeBatch, Mockito.times(1)).getBatchSize();
    Mockito.verify(pipeBatch, Mockito.times(1)).completeStage(Mockito.eq(batchMaker));
    Mockito.verify(pipeBatch, Mockito.times(1)).getErrorSink();
    Mockito.verifyNoMoreInteractions(pipeBatch);
    Assert.assertTrue(write);
  }
  @Test
  public void shouldCancelOrder() throws IOException {
    // given
    BitMarketCancelResponse response =
        new BitMarketCancelResponse(
            true,
            new BitMarketBalance(createAvailable(), createBlocked()),
            new BitMarketAPILimit(3, 100, 12345000L),
            0,
            null);

    BitMarketAuthenticated bitMarketAuthenticated = mock(BitMarketAuthenticated.class);
    PowerMockito.when(
            bitMarketAuthenticated.cancel(
                Mockito.eq(SPECIFICATION_API_KEY),
                Mockito.any(ParamsDigest.class),
                Mockito.any(SynchronizedValueFactory.class),
                Mockito.eq(12345L)))
        .thenReturn(response);
    Whitebox.setInternalState(tradeService, "bitMarketAuthenticated", bitMarketAuthenticated);

    // when
    boolean cancelled = tradeService.cancelOrder("12345");

    // then
    assertThat(cancelled).isTrue();
  }
  @Test
  public void testCreateNewIfExpired() throws Exception {
    final LocalConnFactory connFactory = Mockito.mock(LocalConnFactory.class);

    final HttpConnection conn1 = Mockito.mock(HttpConnection.class);
    Mockito.when(conn1.isOpen()).thenReturn(true);
    Mockito.when(connFactory.create(Mockito.eq("somehost"))).thenReturn(conn1);

    final LocalConnPool pool = new LocalConnPool(connFactory, 2, 2);

    final Future<LocalPoolEntry> future1 = pool.lease("somehost", null);
    final LocalPoolEntry entry1 = future1.get(1, TimeUnit.SECONDS);
    Assert.assertNotNull(entry1);

    Mockito.verify(connFactory, Mockito.times(1)).create(Mockito.eq("somehost"));

    entry1.updateExpiry(1, TimeUnit.MILLISECONDS);
    pool.release(entry1, true);

    Thread.sleep(200L);

    final Future<LocalPoolEntry> future2 = pool.lease("somehost", null);
    final LocalPoolEntry entry2 = future2.get(1, TimeUnit.SECONDS);
    Assert.assertNotNull(entry2);

    Mockito.verify(connFactory, Mockito.times(2)).create(Mockito.eq("somehost"));

    final PoolStats totals = pool.getTotalStats();
    Assert.assertEquals(0, totals.getAvailable());
    Assert.assertEquals(1, totals.getLeased());
    Assert.assertEquals(Collections.singleton("somehost"), pool.getRoutes());
    final PoolStats stats = pool.getStats("somehost");
    Assert.assertEquals(0, stats.getAvailable());
    Assert.assertEquals(1, stats.getLeased());
  }
  @Test(expected = ExchangeException.class)
  public void shouldFailOnUnsuccessfulLimitOrder() throws IOException {
    // given
    BitMarketTradeResponse response =
        new BitMarketTradeResponse(
            false, null, new BitMarketAPILimit(3, 100, 12345000L), 502, "Invalid message hash");

    BitMarketAuthenticated bitMarketAuthenticated = mock(BitMarketAuthenticated.class);
    PowerMockito.when(
            bitMarketAuthenticated.trade(
                Mockito.eq(SPECIFICATION_API_KEY),
                Mockito.any(ParamsDigest.class),
                Mockito.any(SynchronizedValueFactory.class),
                Mockito.eq("BTCAUD"),
                Mockito.eq("sell"),
                Mockito.eq(BigDecimal.ONE),
                Mockito.eq(BigDecimal.TEN)))
        .thenReturn(response);
    Whitebox.setInternalState(tradeService, "bitMarketAuthenticated", bitMarketAuthenticated);

    // when
    tradeService.placeLimitOrder(
        new LimitOrder(
            Order.OrderType.ASK,
            BigDecimal.ONE,
            CurrencyPair.BTC_AUD,
            "12345",
            null,
            BigDecimal.TEN));

    // then
    fail(
        "BitMarketTradeService should throw ExchangeException when place limit order request was unsuccessful");
  }
  @Test
  public void testPreferencesWithModeEditGuestInPublicLayoutWithPermission() throws Exception {

    _layout.setPrivateLayout(false);

    PowerMockito.mockStatic(PortletLocalServiceUtil.class);

    Mockito.when(PortletLocalServiceUtil.getPortletById(_layout.getCompanyId(), _PORTLET_ID))
        .thenReturn(getGroupPortlet());

    PowerMockito.mockStatic(LayoutPermissionUtil.class);

    Mockito.when(
            LayoutPermissionUtil.contains(
                Mockito.any(PermissionChecker.class),
                Mockito.eq(_layout),
                Mockito.eq(ActionKeys.UPDATE)))
        .thenReturn(true);

    long siteGroupId = _layout.getGroupId();
    boolean modeEditGuest = true;

    PortletPreferencesFactoryUtil.getPortletPreferencesIds(
        siteGroupId, _USER_ID, _layout, _PORTLET_ID, modeEditGuest);
  }
  @Test
  public final void shouldSaveAndSetOwnerEntity() {
    // given
    given(owner.isValid()).willReturn(true);
    given(savedOwner.isValid()).willReturn(true);
    given(ownerDD.save(owner)).willReturn(savedOwner);

    // when
    stateChangeContext.setOwner(owner);

    // then
    verify(ownerDD).save(owner);
    verify(stateChangeEntity, never()).setField(describer.getOwnerFieldName(), owner);
    verify(stateChangeEntity).setField(describer.getOwnerFieldName(), savedOwner);
    verify(messageService, never())
        .addValidationError(
            Mockito.eq(stateChangeContext),
            Mockito.anyString(),
            Mockito.anyString(),
            Mockito.any(String[].class));
    verify(messageService, never())
        .addValidationError(
            Mockito.eq(stateChangeContext),
            Mockito.eq((String) null),
            Mockito.anyString(),
            Mockito.any(String[].class));
    verify(stateChangeEntity, never())
        .setField(describer.getStatusFieldName(), StateChangeStatus.FAILURE.getStringValue());
  }
  @Test
  public void navigate() {
    NavigateAllListener beforeListener = Mockito.mock(NavigateAllListener.class);
    NavigateAllListener afterListener = Mockito.mock(NavigateAllListener.class);

    events().beforeNavigate(beforeListener);
    events().afterNavigate(afterListener);
    goTo(DEFAULT_URL);

    Mockito.verify(beforeListener, Mockito.times(1))
        .on(
            Mockito.eq(DEFAULT_URL),
            Mockito.<WebDriver>anyObject(),
            Mockito.<NavigateAllListener.Direction>anyObject());
    Mockito.verify(afterListener, Mockito.times(1))
        .on(
            Mockito.eq(DEFAULT_URL),
            Mockito.<WebDriver>anyObject(),
            Mockito.<NavigateAllListener.Direction>anyObject());

    getDriver().navigate().refresh();

    Mockito.verify(beforeListener, Mockito.times(1))
        .on(
            (String) Mockito.isNull(),
            Mockito.<WebDriver>anyObject(),
            Mockito.eq(NavigateAllListener.Direction.REFRESH));
    Mockito.verify(afterListener, Mockito.times(1))
        .on(
            (String) Mockito.isNull(),
            Mockito.<WebDriver>anyObject(),
            Mockito.eq(NavigateAllListener.Direction.REFRESH));
  }
  @Test
  public void testTriggerSavepointFailure() throws Exception {
    replaceStdOutAndStdErr();

    try {
      JobID jobId = new JobID();
      ActorGateway jobManager = mock(ActorGateway.class);

      Promise<Object> triggerResponse = new scala.concurrent.impl.Promise.DefaultPromise<>();

      when(jobManager.ask(
              Mockito.eq(new JobManagerMessages.TriggerSavepoint(jobId)),
              Mockito.any(FiniteDuration.class)))
          .thenReturn(triggerResponse.future());

      Exception testException = new Exception("expectedTestException");

      triggerResponse.success(new JobManagerMessages.TriggerSavepointFailure(jobId, testException));

      CliFrontend frontend = new MockCliFrontend(CliFrontendTestUtils.getConfigDir(), jobManager);

      String[] parameters = {jobId.toString()};
      int returnCode = frontend.savepoint(parameters);

      assertTrue(returnCode != 0);
      verify(jobManager, times(1))
          .ask(
              Mockito.eq(new JobManagerMessages.TriggerSavepoint(jobId)),
              Mockito.any(FiniteDuration.class));

      assertTrue(buffer.toString().contains("expectedTestException"));
    } finally {
      restoreStdOutAndStdErr();
    }
  }
Beispiel #9
0
  private void overrideMockedBehaviour() {
    Mockito.doAnswer(
            new Answer<Object>() {
              @Override
              public Object answer(final InvocationOnMock invocation) throws Throwable {
                final Object[] args = invocation.getArguments();
                final NormalizedNode<?, ?> node = (NormalizedNode<?, ?>) args[2];
                if (node.getIdentifier().getNodeType().equals(Ipv4Route.QNAME)
                    || node.getNodeType().equals(IPv4RIBSupport.PREFIX_QNAME)) {
                  PeerTest.this.routes.put((YangInstanceIdentifier) args[1], node);
                }
                return args[1];
              }
            })
        .when(getTransaction())
        .put(
            Mockito.eq(LogicalDatastoreType.OPERATIONAL),
            Mockito.any(YangInstanceIdentifier.class),
            Mockito.any(NormalizedNode.class));

    Mockito.doAnswer(
            new Answer<Object>() {
              @Override
              public Object answer(final InvocationOnMock invocation) throws Throwable {
                final Object[] args = invocation.getArguments();
                PeerTest.this.routes.remove(args[1]);
                return args[1];
              }
            })
        .when(getTransaction())
        .delete(
            Mockito.eq(LogicalDatastoreType.OPERATIONAL),
            Mockito.any(YangInstanceIdentifier.class));
  }
  @Test
  public void testDisposeSavepointSuccess() throws Exception {
    replaceStdOutAndStdErr();

    try {
      String savepointPath = "expectedSavepointPath";
      ActorGateway jobManager = mock(ActorGateway.class);

      Promise<Object> triggerResponse = new scala.concurrent.impl.Promise.DefaultPromise<>();

      when(jobManager.ask(
              Mockito.eq(new JobManagerMessages.DisposeSavepoint(savepointPath)),
              Mockito.any(FiniteDuration.class)))
          .thenReturn(triggerResponse.future());

      triggerResponse.success(JobManagerMessages.getDisposeSavepointSuccess());

      CliFrontend frontend = new MockCliFrontend(CliFrontendTestUtils.getConfigDir(), jobManager);

      String[] parameters = {"-d", savepointPath};
      int returnCode = frontend.savepoint(parameters);

      assertEquals(0, returnCode);
      verify(jobManager, times(1))
          .ask(
              Mockito.eq(new JobManagerMessages.DisposeSavepoint(savepointPath)),
              Mockito.any(FiniteDuration.class));

      String outMsg = buffer.toString();
      assertTrue(outMsg.contains(savepointPath));
      assertTrue(outMsg.contains("disposed"));
    } finally {
      restoreStdOutAndStdErr();
    }
  }
  @Test
  public void testPagingAfterItemWithInvalidAfterId() throws Exception {
    Element rsm =
        new BaseElement(new QName("set", new Namespace("", "http://jabber.org/protocol/rsm")));

    rsm.addElement("after").setText("this is invalid");

    element.addAttribute("node", "/user/[email protected]/posts");

    Mockito.when(channelManager.nodeExists(anyString())).thenReturn(true);

    Mockito.when(channelManager.getNodeMembership(node, jid))
        .thenReturn(
            new NodeMembershipImpl(node, jid, Subscriptions.subscribed, Affiliations.member, null));

    Mockito.when(
            channelManager.getUserFeedItems(
                Mockito.any(JID.class),
                Mockito.any(Date.class),
                Mockito.anyInt(),
                Mockito.any(GlobalItemID.class),
                Mockito.eq(false)))
        .thenReturn(new ClosableIteratorImpl<NodeItem>(new ArrayList<NodeItem>().iterator()));
    Mockito.when(
            channelManager.getCountUserFeedItems(
                Mockito.any(JID.class), Mockito.any(Date.class), Mockito.eq(false)))
        .thenReturn(0);

    userItemsGet.process(element, jid, request, rsm);

    Packet p = queue.poll(100, TimeUnit.MILLISECONDS);

    assertEquals("Error expected", "error", p.getElement().attributeValue("type"));
  }
 @Test
 public void testSignSessionWithMultiplePairs() {
   session.put("hello", "world");
   String content = resolver.dissolveIntoCookieContent(session, true);
   H.Session session1 = new H.Session();
   resolver.resolveFromCookieContent(session1, content, true);
   eq("bar", session1.get("foo"));
   eq("world", session1.get("hello"));
 }
  @Test
  public void testRegistrationTokensAreNotCached() throws Exception {

    AeroGearGCMPushConfiguration config =
        new AeroGearGCMPushConfiguration()
            .setSenderId(TEST_SENDER_ID)
            .setVariantID(TEST_SENDER_VARIANT)
            .setSecret(TEST_SENDER_PASSWORD)
            .setPushServerURI(new URI("https://testuri"));

    AeroGearGCMPushRegistrar registrar = (AeroGearGCMPushRegistrar) config.asRegistrar();
    CountDownLatch latch = new CountDownLatch(1);
    StubHttpProvider provider = new StubHttpProvider();
    UnitTestUtils.setPrivateField(registrar, "httpProviderProvider", provider);

    StubInstanceIDProvider instanceIdProvider = new StubInstanceIDProvider();
    UnitTestUtils.setPrivateField(registrar, "instanceIdProvider", instanceIdProvider);

    UnitTestUtils.setPrivateField(
        registrar,
        "preferenceProvider",
        new Provider<SharedPreferences>() {

          @Override
          public SharedPreferences get(Object... in) {
            return new GCMSharedPreferenceProvider().get(getActivity());
          }
        });

    VoidCallback callback = new VoidCallback(latch);

    registrar.register(super.getActivity(), callback);
    latch.await(5, TimeUnit.SECONDS);
    Assert.assertNotNull(
        new GCMSharedPreferenceProvider()
            .get(getActivity())
            .getString(
                "org.jboss.aerogear.android.unifiedpush.gcm.AeroGearGCMPushRegistrar:"
                    + TEST_SENDER_ID,
                null));

    latch = new CountDownLatch(1);
    callback = new VoidCallback(latch);
    registrar.unregister(super.getActivity(), callback);
    latch.await(5, TimeUnit.SECONDS);
    Assert.assertNull(
        new GCMSharedPreferenceProvider()
            .get(getActivity())
            .getString(
                "org.jboss.aerogear.android.unifiedpush.gcm.AeroGearGCMPushRegistrar:"
                    + TEST_SENDER_ID,
                null));
    Mockito.verify(instanceIdProvider.mock, Mockito.times(1))
        .deleteToken(
            Mockito.eq(TEST_SENDER_ID), Mockito.eq(GoogleCloudMessaging.INSTANCE_ID_SCOPE));
  }
  private void buildMockResponsesExistingProfile() throws Exception {

    // Loading responses for mocks

    // Tenant
    setupTenant();
    when(tenantManager.getByAccountName(RECEIVER)).thenReturn(tenant);

    // CredentialStore
    when(credentialStore.getUriForName(RECEIVER)).thenReturn(RECEIVER_URI);
    when(credentialStore.getUriForAccountName(RECEIVER, SENDER, tenant)).thenReturn(SENDER_URI);
    when(credentialStore.getPassword(RECEIVER, SENDER, tenant)).thenReturn(PASSWORD);

    // Mocking tenantHelper

    mock(TenantHelper.class);
    when(TenantHelper.getTenant(new Long(1))).thenReturn(tenant);
    when(TenantHelper.getCurrentTenant()).thenReturn(tenant);
    // Mocking: DimeServiceAdapter
    Token token = new Token("token", "secret");
    DimeServiceAdapter mockDimeServiceAdapter = mock(DimeServiceAdapter.class);
    when(mockDimeServiceAdapter.getUserToken(RECEIVER, Mockito.any(Tenant.class)))
        .thenReturn(token);
    PersonContact profile = modelFactory.getNCOFactory().createPersonContact();
    when(mockDimeServiceAdapter.getProfile(Mockito.anyString(), Mockito.eq(token)))
        .thenReturn(profile);

    // PowerMockito.whenNew(DimeServiceAdapter.class).withAnyArguments().thenReturn(mockDimeServiceAdapter);
    when(serviceGateway.getDimeServiceAdapter(SENDER)).thenReturn(mockDimeServiceAdapter);

    User user = new User();
    Account account = modelFactory.getDAOFactory().createAccount(SENDER_URI_ON_DEMAND);
    String name = "dummy";
    account.setAccountType(DimeServiceAdapter.NAME);
    account.setPrefLabel(name + "@" + DimeServiceAdapter.NAME);

    user.setAccountUri(SENDER_URI_ON_DEMAND);
    when(userManager.add(Mockito.eq(SENDER))).thenReturn(user);
    when(userManager.addProfile(Mockito.eq(new URIImpl(SENDER_URI_ON_DEMAND)), Mockito.eq(profile)))
        .thenReturn(account);

    // ServiceGateway
    Vector<LivePost> liveposts = new Vector<LivePost>();
    livepost = modelFactory.getDLPOFactory().createLivePost();
    liveposts.add(livepost);
    when(mockDimeServiceAdapter.get(
            Mockito.anyString(),
            Mockito.anyString(),
            Mockito.anyString(),
            Mockito.any(Class.class),
            Mockito.any(Tenant.class)))
        .thenReturn(liveposts);
    when(serviceGateway.getDimeServiceAdapter(RECEIVER_URI)).thenReturn(mockDimeServiceAdapter);
  }
  @Test
  public void testUpdateJobXml() throws Exception {
    String jobName = "pr";
    String xmlString = "<xml>some xml goes here</xml>";

    Mockito.when(client.post_xml(Mockito.anyString(), Mockito.eq(xmlString))).thenReturn(xmlString);
    server.updateJob(jobName, xmlString);

    ArgumentCaptor<String> captureString = ArgumentCaptor.forClass(String.class);
    Mockito.verify(client).post_xml(Mockito.eq("/job/pr/config.xml"), captureString.capture());

    assertEquals(xmlString, captureString.getValue());
  }
  @Test
  public void setCounter() throws TimeoutException, CacheException {
    String cacheKey = "key1";
    int expiration = 900;
    long value = 60;

    cache.setCounter(cacheKey, expiration, value);
    Mockito.verify(cacheClient)
        .set(
            Mockito.eq(getKey(cacheKey)),
            Mockito.eq(expiration),
            Mockito.eq(value),
            Mockito.any(LongToStringTranscoder.class));
  }
  private void testSingleLine(String line, StringBuilder builder, InputStream stream)
      throws IOException {
    int cpuDelay = 10;
    byte[] firstBytes = line.getBytes();
    Mockito.when(stream.available()).thenReturn(firstBytes.length).thenReturn(firstBytes.length);
    Mockito.when(
            stream.read(Mockito.any(byte[].class), Mockito.eq(0), Mockito.eq(firstBytes.length)))
        .thenAnswer(new InputStreamReadDelayedAnswer(0, firstBytes));

    ParseState state = IOUtilities.readLine(stream, builder, "[\n]", 0, 0, cpuDelay);

    Assert.assertEquals(0, state.parseLocation);
    Assert.assertEquals(line, state.currentLine);
  }
  @SuppressWarnings("unchecked")
  @Test
  public void createLockAll() {
    ContentManipulationLockService tested = getTested();

    Mockito.reset(tested.configService);
    Mockito.doAnswer(new StoreValidationgAnswer(ContentManipulationLockService.API_ID_ALL))
        .when(tested.configService)
        .create(Mockito.eq(ContentManipulationLockService.CFGFILE_NAME), Mockito.anyMap());
    tested.createLockAll();
    Mockito.verify(tested.configService)
        .create(Mockito.eq(ContentManipulationLockService.CFGFILE_NAME), Mockito.anyMap());
    Mockito.verifyNoMoreInteractions(tested.configService);
  }
  private void setupMedia() throws Exception {
    final Attachment attachment =
        Attachment.create().name("logo.png").mimeType("image/png").label("small").build();

    final Media content = createMedia("123456", "path/to/content", attachment);

    Mockito.when(this.contentService.getById(Mockito.eq(content.getId()))).thenReturn(content);
    Mockito.when(this.contentService.getByPath(Mockito.eq(content.getPath()))).thenReturn(content);

    this.mediaBytes = ByteSource.wrap(new byte[0]);
    Mockito.when(
            this.contentService.getBinary(
                Mockito.isA(ContentId.class), Mockito.isA(BinaryReference.class)))
        .thenReturn(this.mediaBytes);
  }
Beispiel #20
0
 @Test
 public void verifyMockitoCaptorWorksForMultipleParameterEmitting() {
   EventEmitter emitter = mock(EventEmitter.class);
   emitter.emit("event", "1", "2", "3", "4");
   ArgumentCaptor<String> paramCaptor = ArgumentCaptor.forClass(String.class);
   verify(emitter)
       .emit(
           Mockito.eq("event"),
           paramCaptor.capture(),
           Mockito.anyString(),
           Mockito.same("3"),
           Mockito.eq("4"));
   String s = paramCaptor.getValue();
   Assert.assertEquals("1", s);
 }
  // should be changed after order type convertion fix
  @Test
  public void shouldPlaceBuyLimitOrder() throws IOException {
    // given
    BitMarketTradeResponse responseBuy =
        new BitMarketTradeResponse(
            true,
            new BitMarketTrade(
                12345,
                new BitMarketOrder(
                    12345,
                    "BTCAUD",
                    BigDecimal.ONE,
                    new BigDecimal("1.1"),
                    BigDecimal.ZERO,
                    "BUY",
                    1234567890L),
                new BitMarketBalance(createAvailable(), createBlocked())),
            new BitMarketAPILimit(3, 100, 12345000L),
            0,
            null);

    BitMarketAuthenticated bitMarketAuthenticated = mock(BitMarketAuthenticated.class);
    PowerMockito.when(
            bitMarketAuthenticated.trade(
                Mockito.eq(SPECIFICATION_API_KEY),
                Mockito.any(ParamsDigest.class),
                Mockito.any(SynchronizedValueFactory.class),
                Mockito.eq("BTCAUD"),
                Mockito.eq("buy"),
                Mockito.eq(BigDecimal.ONE),
                Mockito.eq(BigDecimal.TEN)))
        .thenReturn(responseBuy);
    Whitebox.setInternalState(tradeService, "bitMarketAuthenticated", bitMarketAuthenticated);

    // when
    String placedBuy =
        tradeService.placeLimitOrder(
            new LimitOrder(
                Order.OrderType.BID,
                BigDecimal.ONE,
                CurrencyPair.BTC_AUD,
                "12345",
                null,
                BigDecimal.TEN));

    // then
    assertThat(placedBuy).isEqualTo("12345");
  }
  @Test
  public void shouldGetCurrencyPairTradeHistory() throws IOException {
    // given
    final UserTrade[] expectedCpUserTrades = expectedCpUserTrades();

    BitMarketHistoryTradesResponse historyTradesCPResponse =
        parse("trade/example-history-trades-cp-data", BitMarketHistoryTradesResponse.class);
    BitMarketHistoryOperationsResponse marketHistoryOperationsEurResponse =
        parse(
            "trade/example-history-operations-eur-data", BitMarketHistoryOperationsResponse.class);
    BitMarketHistoryOperationsResponse marketHistoryOperationsBtcResponse =
        parse(
            "trade/example-history-operations-btc-data", BitMarketHistoryOperationsResponse.class);

    BitMarketAuthenticated bitMarketAuthenticated = mock(BitMarketAuthenticated.class);
    PowerMockito.when(
            bitMarketAuthenticated.trades(
                Mockito.eq(SPECIFICATION_API_KEY),
                Mockito.any(ParamsDigest.class),
                Mockito.any(SynchronizedValueFactory.class),
                Mockito.eq("BTCEUR"),
                Mockito.eq(1000),
                Mockito.eq(0L)))
        .thenReturn(historyTradesCPResponse);

    PowerMockito.when(
            bitMarketAuthenticated.history(
                Mockito.eq(SPECIFICATION_API_KEY),
                Mockito.any(ParamsDigest.class),
                Mockito.any(SynchronizedValueFactory.class),
                Mockito.eq(Currency.EUR.toString()),
                Mockito.anyInt(),
                Mockito.anyLong()))
        .thenReturn(marketHistoryOperationsEurResponse);
    PowerMockito.when(
            bitMarketAuthenticated.history(
                Mockito.eq(SPECIFICATION_API_KEY),
                Mockito.any(ParamsDigest.class),
                Mockito.any(SynchronizedValueFactory.class),
                Mockito.eq(Currency.BTC.toString()),
                Mockito.anyInt(),
                Mockito.anyLong()))
        .thenReturn(marketHistoryOperationsBtcResponse);

    Whitebox.setInternalState(tradeService, "bitMarketAuthenticated", bitMarketAuthenticated);

    // when
    UserTrades tradesCP =
        tradeService.getTradeHistory(
            new DefaultTradeHistoryParamCurrencyPair(CurrencyPair.BTC_EUR));
    List<UserTrade> userTrades = tradesCP.getUserTrades();

    // then
    assertThat(userTrades).hasSize(2);
    for (int i = 0; i < userTrades.size(); i++) {
      BitMarketAssert.assertEquals(userTrades.get(i), expectedCpUserTrades[i]);
    }
  }
Beispiel #23
0
  private SAMLProperties setupForKeyManager() {
    final ResourceLoader resourceLoader = Mockito.mock(ResourceLoader.class);
    this.config.setResourceLoader(resourceLoader);
    final Resource storeFile = Mockito.mock(Resource.class);

    final SAMLProperties properties = Mockito.mock(SAMLProperties.class);
    this.config.setSamlProperties(properties);

    final String keyStorePassword = UUID.randomUUID().toString();
    final String keyStoreName = UUID.randomUUID().toString() + ".jks";
    final String defaultKeyName = UUID.randomUUID().toString();
    final String defaultKeyPassword = UUID.randomUUID().toString();

    final SAMLProperties.Keystore keyStore = Mockito.mock(SAMLProperties.Keystore.class);
    final SAMLProperties.Keystore.DefaultKey defaultKey =
        Mockito.mock(SAMLProperties.Keystore.DefaultKey.class);
    Mockito.when(properties.getKeystore()).thenReturn(keyStore);
    Mockito.when(keyStore.getName()).thenReturn(keyStoreName);
    Mockito.when(keyStore.getPassword()).thenReturn(keyStorePassword);
    Mockito.when(keyStore.getDefaultKey()).thenReturn(defaultKey);
    Mockito.when(defaultKey.getName()).thenReturn(defaultKeyName);
    Mockito.when(defaultKey.getPassword()).thenReturn(defaultKeyPassword);
    Mockito.when(resourceLoader.getResource(Mockito.eq("classpath:" + keyStoreName)))
        .thenReturn(storeFile);

    return properties;
  }
 @Test
 public void testSignSessionWithOnePair() {
   String content = resolver.dissolveIntoCookieContent(session, true);
   H.Session session1 = new H.Session();
   resolver.resolveFromCookieContent(session1, content, true);
   eq("bar", session1.get("foo"));
 }
Beispiel #25
0
  @Test
  public final void shouldGetPpsForOrderReturnNullIfPpsDoesNotExists() {
    // given
    Long givenOrderId = 1L;

    given(
            dataDefinitionService.get(
                ProductionPerShiftConstants.PLUGIN_IDENTIFIER,
                ProductionPerShiftConstants.MODEL_PRODUCTION_PER_SHIFT))
        .willReturn(dataDefinition);
    SearchQueryBuilder searchCriteriaBuilder = mock(SearchQueryBuilder.class);
    given(
            dataDefinition.find(
                "select id as ppsId from #productionPerShift_productionPerShift where order.id = :orderId"))
        .willReturn(searchCriteriaBuilder);
    given(searchCriteriaBuilder.setMaxResults(Mockito.anyInt())).willReturn(searchCriteriaBuilder);
    given(searchCriteriaBuilder.setLong(Mockito.anyString(), Mockito.eq(givenOrderId)))
        .willReturn(searchCriteriaBuilder);
    given(searchCriteriaBuilder.uniqueResult()).willReturn(null);

    // when
    final Long resultPpsId = ppsHelper.getPpsIdForOrder(givenOrderId);

    // then
    Assert.assertNull(resultPpsId);
  }
  @Test
  public void testEstablishRouteViaProxyTunnelRetryOnAuthChallengeNonPersistentConnection()
      throws Exception {
    final AuthState authState = new AuthState();
    final HttpRoute route = new HttpRoute(target, null, proxy, true);
    final HttpClientContext context = new HttpClientContext();
    final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));
    final HttpResponse response1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 401, "Huh?");
    final InputStream instream1 = Mockito.spy(new ByteArrayInputStream(new byte[] {1, 2, 3}));
    response1.setEntity(EntityBuilder.create().setStream(instream1).build());
    final HttpResponse response2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");

    Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);
    Mockito.when(
            proxyAuthStrategy.isAuthenticationRequested(
                Mockito.eq(proxy), Mockito.same(response1), Mockito.<HttpClientContext>any()))
        .thenReturn(Boolean.TRUE);
    Mockito.when(
            reuseStrategy.keepAlive(Mockito.<HttpResponse>any(), Mockito.<HttpClientContext>any()))
        .thenReturn(Boolean.FALSE);
    Mockito.when(
            requestExecutor.execute(
                Mockito.<HttpRequest>any(),
                Mockito.<HttpClientConnection>any(),
                Mockito.<HttpClientContext>any()))
        .thenReturn(response1, response2);

    mainClientExec.establishRoute(authState, managedConn, route, request, context);

    Mockito.verify(connManager).connect(managedConn, route, 0, context);
    Mockito.verify(connManager).routeComplete(managedConn, route, context);
    Mockito.verify(instream1, Mockito.never()).close();
    Mockito.verify(managedConn).close();
  }
Beispiel #27
0
  protected final void setupTemplates() throws Exception {
    Mockito.when(this.pageTemplateService.getByKey(Mockito.eq(PageTemplateKey.from("my-page"))))
        .thenReturn(createPageTemplate());

    Mockito.when(this.pageDescriptorService.getByKey(Mockito.isA(DescriptorKey.class)))
        .thenReturn(createDescriptor());
  }
  @Test
  public void requestLocation_Success() throws SecurityException {
    final Location expectedLocation = buildFakeLocation(provider);

    // set provider enabled
    setIsProviderEnabled(provider, true);

    // answer
    Mockito.doAnswer(
            new Answer() {
              @Override
              public Object answer(InvocationOnMock invocation) throws Throwable {
                final Object[] args = invocation.getArguments();
                final LocationListener l = (LocationListener) args[1];
                l.onLocationChanged(expectedLocation);
                return null;
              }
            })
        .when(locationManager)
        .requestSingleUpdate(
            Mockito.eq(provider), Mockito.any(LocationListener.class), Mockito.any(Looper.class));

    final RxLocationManager rxLocationManager = getDefaullRxLocationManager();

    final TestSubscriber<Location> subscriber = new TestSubscriber<>();
    rxLocationManager.requestLocation(provider).subscribe(subscriber);
    subscriber.awaitTerminalEvent();
    subscriber.assertCompleted();
    subscriber.assertValue(expectedLocation);
  }
  @Test
  public void shouldGetOpenOrders() throws IOException {
    // given
    final LimitOrder[] expectedOrders = expectedOrders();

    BitMarketOrdersResponse response =
        new BitMarketOrdersResponse(
            true, createOpenOrdersData(), new BitMarketAPILimit(3, 100, 12345000L), 0, null);

    BitMarketAuthenticated bitMarketAuthenticated = mock(BitMarketAuthenticated.class);
    PowerMockito.when(
            bitMarketAuthenticated.orders(
                Mockito.eq(SPECIFICATION_API_KEY),
                Mockito.any(ParamsDigest.class),
                Mockito.any(SynchronizedValueFactory.class)))
        .thenReturn(response);
    Whitebox.setInternalState(tradeService, "bitMarketAuthenticated", bitMarketAuthenticated);

    // when
    OpenOrders orders = tradeService.getOpenOrders();
    List<LimitOrder> openOrders = orders.getOpenOrders();

    // then
    assertThat(openOrders).hasSize(2);
    for (int i = 0; i < openOrders.size(); i++) {
      BitMarketAssert.assertEquals(openOrders.get(i), expectedOrders[i]);
      assertThat(orders.toString()).contains(expectedOrders[i].toString());
    }
  }
  @Test
  public void testContinueReadingAfterEOF() throws Exception {

    // vfs will return only "." and ".." as contents, both leading to itself
    List<DirectoryEntry> dirContents = new ArrayList<>();
    dirContents.add(new DirectoryEntry(".", dirInode, dirStat));
    dirContents.add(new DirectoryEntry("..", dirInode, dirStat));
    Mockito.when(vfs.list(Mockito.eq(dirInode))).thenReturn(dirContents);

    // set up and execute the 1st call - no cookie, but very tight size limit
    RpcCall call =
        new RpcCallBuilder().from("1.2.3.4", "someHost.acme.com", 42).nfs3().noAuth().build();
    READDIR3args args = NfsV3Ops.readDir(dirHandle);
    READDIR3res result = nfsServer.NFSPROC3_READDIR_3(call, args);

    Assert.assertEquals(nfsstat.NFS_OK, result.status); // response ok
    Assert.assertTrue(result.resok.reply.eof); // eof
    AssertXdr.assertXdrEncodable(result);

    // client violates spec - attempts to read more
    // using cookie on last (2nd) entry and returned verifier
    long cookie = result.resok.reply.entries.nextentry.cookie.value.value;
    byte[] cookieVerifier = result.resok.cookieverf.value;
    args = NfsV3Ops.readDir(dirHandle, cookie, cookieVerifier);
    result = nfsServer.NFSPROC3_READDIR_3(call, args);

    Assert.assertEquals(nfsstat.NFSERR_BAD_COOKIE, result.status); // error response
    AssertXdr.assertXdrEncodable(result);
  }