/*
   * @see DATAREDIS-415
   */
  @Test
  public void interruptAtStart() throws Exception {

    final Thread main = Thread.currentThread();

    // interrupt thread once Executor.execute is called
    doAnswer(
            new Answer<Object>() {

              @Override
              public Object answer(final InvocationOnMock invocationOnMock) throws Throwable {

                main.interrupt();
                return null;
              }
            })
        .when(executorMock)
        .execute(any(Runnable.class));

    container.addMessageListener(adapter, new ChannelTopic("a"));
    container.start();

    // reset the interrupted flag to not destroy the teardown
    assertThat(Thread.interrupted(), is(true));

    assertThat(container.isRunning(), is(false));
  }
コード例 #2
0
 @Test
 @SuppressWarnings("unchecked")
 public void getComponentSubscriptionByAnAuthenticatedUser() throws Exception {
   WebResource resource = resource();
   UserDetailWithProfiles user = new UserDetailWithProfiles();
   user.setFirstName("Bart");
   user.setLastName("Simpson");
   user.setId("10");
   user.addProfile(COMPONENT_ID, SilverpeasRole.writer);
   user.addProfile(COMPONENT_ID, SilverpeasRole.user);
   String sessionKey = authenticate(user);
   SubscriptionService mockedSubscriptionService = mock(SubscriptionService.class);
   ComponentSubscription subscription = new ComponentSubscription("10", COMPONENT_ID);
   Collection<ComponentSubscription> subscriptions = Lists.newArrayList(subscription);
   when((Collection<ComponentSubscription>)
           mockedSubscriptionService.getUserSubscriptionsByComponent("10", COMPONENT_ID))
       .thenReturn(subscriptions);
   getTestResources()
       .getMockableSubscriptionService()
       .setImplementation(mockedSubscriptionService);
   SubscriptionEntity[] entities =
       resource
           .path(SUBSCRIPTION_RESOURCE_PATH)
           .header(HTTP_SESSIONKEY, sessionKey)
           .accept(MediaType.APPLICATION_JSON)
           .get(SubscriptionEntity[].class);
   assertNotNull(entities);
   assertThat(entities.length, is(1));
   assertThat(entities[0], SubscriptionEntityMatcher.matches((Subscription) subscription));
 }
コード例 #3
0
  @Test
  public void shouldLateJoinTransmission() {
    final int length = 8;
    final int recordLength = length + HEADER_LENGTH;
    final int recordLengthAligned = align(recordLength, RECORD_ALIGNMENT);
    final long tail = (CAPACITY * 3L) + HEADER_LENGTH + recordLengthAligned;
    final long latestRecord = tail - recordLengthAligned;
    final int recordOffset = (int) latestRecord & (CAPACITY - 1);

    when(buffer.getLongVolatile(TAIL_INTENT_COUNTER_OFFSET)).thenReturn(tail);
    when(buffer.getLongVolatile(TAIL_COUNTER_INDEX)).thenReturn(tail);
    when(buffer.getLong(LATEST_COUNTER_INDEX)).thenReturn(latestRecord);

    when(buffer.getInt(lengthOffset(recordOffset))).thenReturn(recordLength);
    when(buffer.getInt(typeOffset(recordOffset))).thenReturn(MSG_TYPE_ID);

    assertTrue(broadcastReceiver.receiveNext());
    assertThat(broadcastReceiver.typeId(), is(MSG_TYPE_ID));
    assertThat(broadcastReceiver.buffer(), is(buffer));
    assertThat(broadcastReceiver.offset(), is(msgOffset(recordOffset)));
    assertThat(broadcastReceiver.length(), is(length));

    assertTrue(broadcastReceiver.validate());
    assertThat(broadcastReceiver.lappedCount(), is(greaterThan(0L)));
  }
コード例 #4
0
ファイル: FutureResponseTest.java プロジェクト: drbild/c2dm4j
 @Test
 public void setIsDoneReturnsTrueIffResponse() {
   Response response = mock(Response.class);
   assertThat(cut.isDone(), is(false));
   cut.setResponse(response);
   assertThat(cut.isDone(), is(true));
 }
コード例 #5
0
  @Test
  public void shouldReceiveFirstMessageFromBuffer() {
    final int length = 8;
    final int recordLength = length + HEADER_LENGTH;
    final int recordLengthAligned = align(recordLength, RECORD_ALIGNMENT);
    final long tail = recordLengthAligned;
    final long latestRecord = tail - recordLengthAligned;
    final int recordOffset = (int) latestRecord;

    when(buffer.getLongVolatile(TAIL_INTENT_COUNTER_OFFSET)).thenReturn(tail);
    when(buffer.getLongVolatile(TAIL_COUNTER_INDEX)).thenReturn(tail);
    when(buffer.getInt(lengthOffset(recordOffset))).thenReturn(recordLength);
    when(buffer.getInt(typeOffset(recordOffset))).thenReturn(MSG_TYPE_ID);

    assertTrue(broadcastReceiver.receiveNext());
    assertThat(broadcastReceiver.typeId(), is(MSG_TYPE_ID));
    assertThat(broadcastReceiver.buffer(), is(buffer));
    assertThat(broadcastReceiver.offset(), is(msgOffset(recordOffset)));
    assertThat(broadcastReceiver.length(), is(length));

    assertTrue(broadcastReceiver.validate());

    final InOrder inOrder = inOrder(buffer);
    inOrder.verify(buffer).getLongVolatile(TAIL_COUNTER_INDEX);
    inOrder.verify(buffer).getLongVolatile(TAIL_INTENT_COUNTER_OFFSET);
  }
コード例 #6
0
 @Test
 public void loadTranslations_OnlyName() throws IOException {
   when(bufferedReaderMock.readLine()).thenReturn("DictionnaireTest");
   IDictionary dictionary = dictionaryParser.loadTranslations(bufferedReaderMock);
   assertThat(dictionary.getName(), is(equalTo("DictionnaireTest")));
   assertThat(dictionary.isEmpty(), is(equalTo(true)));
 }
  /** @see DATAREST-609 */
  @Test
  public void addsSelfAndSingleResourceLinkToResourceByDefault() throws Exception {

    Projector projector = mock(Projector.class);

    when(projector.projectExcerpt(anyObject())).thenAnswer(new ReturnsArgumentAt(0));

    PersistentEntityResourceAssembler assembler =
        new PersistentEntityResourceAssembler(
            entities,
            projector,
            associations,
            new DefaultSelfLinkProvider(
                entities, entityLinks, Collections.<EntityLookup<?>>emptyList()));

    User user = new User();
    user.id = BigInteger.valueOf(4711);

    PersistentEntityResource resource = assembler.toResource(user);

    Links links = new Links(resource.getLinks());

    assertThat(links, is(Matchers.<Link>iterableWithSize(2)));
    assertThat(links.getLink("self").getVariables(), is(Matchers.empty()));
    assertThat(links.getLink("user").getVariableNames(), is(hasItem("projection")));
  }
コード例 #8
0
 @Test
 @SuppressWarnings("unchecked")
 public void getComponentSubscribersByAnAuthenticatedUser() throws Exception {
   WebResource resource = resource();
   UserDetailWithProfiles user = new UserDetailWithProfiles();
   user.setFirstName("Bart");
   user.setLastName("Simpson");
   user.setId("10");
   user.addProfile(COMPONENT_ID, SilverpeasRole.writer);
   user.addProfile(COMPONENT_ID, SilverpeasRole.user);
   String sessionKey = authenticate(user);
   SubscriptionService mockedSubscriptionService = mock(SubscriptionService.class);
   List<String> subscribers = Lists.newArrayList("5", "6", "7", "20");
   when(mockedSubscriptionService.getSubscribers(new ForeignPK("0", COMPONENT_ID)))
       .thenReturn(subscribers);
   getTestResources()
       .getMockableSubscriptionService()
       .setImplementation(mockedSubscriptionService);
   String[] entities =
       resource
           .path(SUBSCRIPTION_RESOURCE_PATH + "/subscribers/0")
           .header(HTTP_SESSIONKEY, sessionKey)
           .accept(MediaType.APPLICATION_JSON)
           .get(String[].class);
   assertNotNull(entities);
   assertThat(entities.length, is(4));
   assertThat(entities, is(new String[] {"5", "6", "7", "20"}));
 }
コード例 #9
0
ファイル: FutureResponseTest.java プロジェクト: drbild/c2dm4j
 @Test
 public void setIsDoneReturnsTrueIffThrowable() {
   Throwable throwable = mock(Throwable.class);
   assertThat(cut.isDone(), is(false));
   cut.setThrowable(throwable);
   assertThat(cut.isDone(), is(true));
 }
コード例 #10
0
  @Test
  public void shouldDealWithRecordBecomingInvalidDueToOverwrite() {
    final int length = 8;
    final int recordLength = length + HEADER_LENGTH;
    final int recordLengthAligned = align(recordLength, RECORD_ALIGNMENT);
    final long tail = recordLengthAligned;
    final long latestRecord = tail - recordLengthAligned;
    final int recordOffset = (int) latestRecord;

    when(buffer.getLongVolatile(TAIL_INTENT_COUNTER_OFFSET))
        .thenReturn(tail)
        .thenReturn(tail + (CAPACITY - (recordLengthAligned)));
    when(buffer.getLongVolatile(TAIL_COUNTER_INDEX)).thenReturn(tail);

    when(buffer.getInt(lengthOffset(recordOffset))).thenReturn(recordLength);
    when(buffer.getInt(typeOffset(recordOffset))).thenReturn(MSG_TYPE_ID);

    assertTrue(broadcastReceiver.receiveNext());
    assertThat(broadcastReceiver.typeId(), is(MSG_TYPE_ID));
    assertThat(broadcastReceiver.buffer(), is(buffer));
    assertThat(broadcastReceiver.offset(), is(msgOffset(recordOffset)));
    assertThat(broadcastReceiver.length(), is(length));

    assertFalse(
        broadcastReceiver.validate()); // Need to receiveNext() to catch up with transmission again.

    final InOrder inOrder = inOrder(buffer);
    inOrder.verify(buffer).getLongVolatile(TAIL_COUNTER_INDEX);
  }
コード例 #11
0
  @Test
  public void findsAndReturnsAllTrophiesForAGivenGameType() {
    final Collection<Trophy> trophies = underTest.findForGameType(GAME_TYPE);

    assertThat(trophies.size(), is(equalTo(2)));
    assertThat(trophies, hasItem(TROPHY1));
    assertThat(trophies, hasItem(TROPHY2));
  }
コード例 #12
0
  @Test
  public void verifyThatAfterHwSelectEventGetHwRequestIsSend() {
    fireHomeworkSelectEvent();

    GetHomeworkDetails action = verifyAction(GetHomeworkDetails.class);
    assertThat(action.getStudentId(), is(1234));
    assertThat(action.getHomeworkId(), is(567));
  }
  @Test
  public void immediateFlushIsSane() {
    encoder.setImmediateFlush(true);
    assertThat(encoder.isImmediateFlush(), is(true));

    encoder.setImmediateFlush(false);
    assertThat(encoder.isImmediateFlush(), is(false));
  }
コード例 #14
0
  /** @see DATAREST-217 */
  @Test
  public void defaultsSupportedHttpMethodsForItemResource() {

    assertThat(
        information.getSupportedMethods(ResourceType.ITEM), hasItems(GET, PUT, PATCH, DELETE));
    assertThat(information.getSupportedMethods(ResourceType.ITEM), not(hasItems(POST)));

    assertThat(information.getSupportedMethods(COLLECTION), hasItems(GET, POST));
    assertThat(information.getSupportedMethods(COLLECTION), not(hasItems(PUT, PATCH, DELETE)));
  }
コード例 #15
0
  @Test
  public void test_sugar_assertThat() {
    assertThat(true);

    try {
      assertThat(false);
      fail();
    } catch (AssertionError e) {
      assertThat(e.getMessage(), is("Expected true but is false"));
    }
  }
コード例 #16
0
 @Test
 public void loadTranslations_containsTranslation() throws IOException {
   when(bufferedReaderMock.readLine())
       .thenReturn("DictionnaireTest")
       .thenReturn("contre = against")
       .thenReturn("");
   IDictionary dictionary = dictionaryParser.loadTranslations(bufferedReaderMock);
   assertThat(dictionary.getName(), is(equalTo("DictionnaireTest")));
   assertThat(dictionary.getTranslation("contre"), hasItem("against"));
   assertThat(dictionary.isEmpty(), is(equalTo(false)));
 }
  /** @see DATAREST-111 */
  @Test
  public void looksUpRepositoryEntityControllerMethodCorrectly() throws Exception {

    when(mappings.exportsTopLevelResourceFor("people")).thenReturn(true);
    mockRequest = new MockHttpServletRequest("GET", "/people");

    HandlerMethod method = handlerMapping.lookupHandlerMethod("/people", mockRequest);

    assertThat(method, is(notNullValue()));
    assertThat(method.getMethod(), is(listEntitiesMethod));
  }
コード例 #18
0
  @Test
  public void canCreateCompositeAnnotator() {

    Annotator annotator1 = mock(Annotator.class);
    Annotator annotator2 = mock(Annotator.class);

    CompositeAnnotator composite = factory.getAnnotator(annotator1, annotator2);

    assertThat(composite.annotators.length, equalTo(2));
    assertThat(composite.annotators[0], is(equalTo(annotator1)));
    assertThat(composite.annotators[1], is(equalTo(annotator2)));
  }
コード例 #19
0
    @Test
    public void itHasAnArrayOfGroups() throws Exception {
      final XmlsonObject representation = presenter.present(accounts, USD, Locale.PRC);

      final XmlsonArray groups = (XmlsonArray) representation.get("account-groups");
      assertThat(groups.getMembers().size(), is(1));

      final XmlsonObject group = (XmlsonObject) groups.getMembers().get(0);
      assertThat(group.getName(), is("group"));

      verify(accountGroupPresenter).present(this.group, USD, Locale.PRC);
    }
コード例 #20
0
  /** @see DATAMONGO-812 */
  @Test
  public void testUpdateShouldAllowMultiplePushEachForDifferentFields() {

    Update update =
        new Update().push("category").each("spring", "data").push("type").each("mongodb");
    DBObject mappedObject =
        mapper.getMappedObject(update.getUpdateObject(), context.getPersistentEntity(Object.class));

    DBObject push = getAsDBObject(mappedObject, "$push");
    assertThat(getAsDBObject(push, "category").containsField("$each"), is(true));
    assertThat(getAsDBObject(push, "type").containsField("$each"), is(true));
  }
コード例 #21
0
    @Test
    public void itHasAnArrayOfAccounts() throws Exception {
      final XmlsonObject representation = presenter.present(accounts, USD, Locale.PRC);

      final XmlsonArray accounts = (XmlsonArray) representation.get("accounts");
      assertThat(accounts.getMembers().size(), is(1));

      final XmlsonObject account = (XmlsonObject) accounts.getMembers().get(0);
      assertThat(account.getName(), is("account"));

      verify(accountPresenter).present(this.account, Locale.PRC);
    }
 @Test
 public void verifyRequestParameterTrigger() throws Exception {
   // opt-in parameter only
   assertThat(
       strategy.resolve(VALID_PROVIDERS, mockRequest(MFA_PROVIDER_ID_1), null, null).orElse(null),
       is(MFA_PROVIDER_ID_1));
   assertThat(
       strategy.resolve(VALID_PROVIDERS, mockRequest(MFA_PROVIDER_ID_2), null, null).orElse(null),
       is(MFA_PROVIDER_ID_2));
   assertThat(
       strategy.resolve(VALID_PROVIDERS, mockRequest(MFA_INVALID), null, null).isPresent(),
       is(false));
 }
コード例 #23
0
  @Test
  public void acknowledgeTopUpResultShouldPutAcknowledgedResultIntoCache() {
    final TopUpAcknowledgeRequest topUpAcknowledgeRequest =
        new TopUpAcknowledgeRequest(PLAYER_ID, new DateTime());

    underTest.acknowledgeTopUpResult(topUpAcknowledgeRequest);

    assertThat(topUpStatusCache.getStatistics().getMemoryStoreObjectCount(), is(1L));
    TopUpResultService.TopUpStatusCacheEntry entry =
        (TopUpResultService.TopUpStatusCacheEntry) topUpStatusCache.get(PLAYER_ID).getObjectValue();
    assertThat(entry.getTopUpStatus(), is(ACKNOWLEDGED));
    assertThat(entry.getLastTopUpDate(), is(topUpAcknowledgeRequest.getTopUpDate()));
  }
コード例 #24
0
  /** @see DATAMONGO-812 */
  @Test
  public void updateMapperShouldConvertPushWhithoutAddingClassInformationWhenUsedWithEvery() {

    Update update = new Update().push("values").each("spring", "data", "mongodb");

    DBObject mappedObject =
        mapper.getMappedObject(update.getUpdateObject(), context.getPersistentEntity(Model.class));
    DBObject push = getAsDBObject(mappedObject, "$push");
    DBObject values = getAsDBObject(push, "values");

    assertThat(push.get("_class"), nullValue());
    assertThat(values.get("_class"), nullValue());
  }
コード例 #25
0
ファイル: AlarmTest.java プロジェクト: paucls/katas
  @Test
  public void check_should_set_alarm_off_when_pressure_is_in_range() {
    when(sensorMock.popNextPressurePsiValue()).thenReturn(17.00);

    alarm.check();

    assertThat(alarm.isAlarmOn(), is(false));

    when(sensorMock.popNextPressurePsiValue()).thenReturn(21.00);

    alarm.check();

    assertThat(alarm.isAlarmOn(), is(false));
  }
コード例 #26
0
  /** @see DATAMONGO-407 */
  @Test
  public void updateMapperShouldSupportNestedCollectionElementUpdates() {

    Update update = Update.update("list.$.value", "foo").set("list.$.otherValue", "bar");

    UpdateMapper mapper = new UpdateMapper(converter);
    DBObject mappedObject =
        mapper.getMappedObject(
            update.getUpdateObject(), context.getPersistentEntity(ParentClass.class));

    DBObject set = getAsDBObject(mappedObject, "$set");
    assertThat(set.get("aliased.$.value"), is((Object) "foo"));
    assertThat(set.get("aliased.$.otherValue"), is((Object) "bar"));
  }
  @Test
  @SuppressWarnings("unchecked")
  public void returnsSingleElementCollectionForTargetThatReturnsNonCollection() throws Throwable {

    MethodInterceptor methodInterceptor =
        new ProjectingMethodInterceptor(new ProxyProjectionFactory(), interceptor);

    Helper reference = mock(Helper.class);
    Object result = methodInterceptor.invoke(mockInvocationOf("getHelperCollection", reference));

    assertThat(result, is((Matcher<Object>) instanceOf(Collection.class)));
    assertThat((Collection<?>) result, hasSize(1));
    assertThat((Collection<Object>) result, hasItem(instanceOf(HelperProjection.class)));
  }
コード例 #28
0
  @Test
  public void
      getTopUpResultShouldDelegateToTopUpServiceAndNotCacheResultWhenPlayerHasNoCachedResultAndHasBeenToppedUpButNotAcknowledgedTopUp() {
    final TopUpResult topUpResult = new TopUpResult(PLAYER_ID, CREDITED, new DateTime());
    when(dailyAwardPromotionService.getTopUpResult(PLAYER_ID, WEB)).thenReturn(topUpResult);

    final TopUpResult actualTopUpResult = underTest.getTopUpResult(PLAYER_ID, WEB);

    // check that result wasn't cached before
    assertThat(topUpStatusCache.getStatistics().getCacheHits(), is(0L));
    // check that result wasn't cached after
    assertThat(topUpStatusCache.getStatistics().getMemoryStoreObjectCount(), is(0L));

    assertThat(actualTopUpResult, is(topUpResult));
  }
コード例 #29
0
  /** @see DATAMONGO-943 */
  @Test
  public void updatePushEachAtPositionWorksCorrectlyWhenGivenPositionNull() {

    Update update =
        new Update().push("key").atPosition(null).each(Arrays.asList("Arya", "Arry", "Weasel"));

    DBObject mappedObject =
        mapper.getMappedObject(update.getUpdateObject(), context.getPersistentEntity(Object.class));

    DBObject push = getAsDBObject(mappedObject, "$push");
    DBObject key = getAsDBObject(push, "key");

    assertThat(key.containsField("$position"), is(false));
    assertThat(getAsDBObject(push, "key").containsField("$each"), is(true));
  }
コード例 #30
0
  @Given("^the user has an SSH key in the key store$")
  public void theUserHasAnSSHKeyInTheKeyStore() throws Throwable {
    String contents = IOUtils.toString(UserApiDefinitions.class.getResource("/test_rsa.pub"));
    KeyHolder keyHolder = new KeyHolder(userModel.getName(), contents);
    keyStore.put(keyHolder);
    assertThat(getKeysApi().listSshKeys(), Matchers.not(Matchers.empty()));

    SshKeyModel sshKeyModel = new SshKeyModel();
    sshKeyModel.setContents(contents);
    sshKeyModel.setName(keyHolder.getName());
    Collection<ConstraintViolation<SshKeyModel>> violations = validator.validate(sshKeyModel);
    assertThat(violations, Matchers.empty());

    resetMockCounters();
  }