org.hamcrest.core.IsCollectionContaining Java Examples

The following examples show how to use org.hamcrest.core.IsCollectionContaining. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: cactoos   Author: yegor256   File: BehavesAsMap.java    License: MIT License 6 votes vote down vote up
@Override
public boolean matchesSafely(final Map<K, V> map) {
    MatcherAssert.assertThat(
        "Doesn't contain the key",
        map,
        new IsMapContaining<>(
            new IsEqual<>(this.key),
            new IsEqual<>(this.value)
        )
    );
    MatcherAssert.assertThat(
        "Doesn't contain the key in #keySet()",
        map.keySet(),
        new IsCollectionContaining<>(new IsEqual<>(this.key))
    );
    MatcherAssert.assertThat(
        "Doesn't contain the value in #values()",
        map.values(),
        new IsCollectionContaining<>(new IsEqual<>(this.value))
    );
    return true;
}
 
Example #2
Source Project: cactoos   Author: yegor256   File: SetOfTest.java    License: MIT License 6 votes vote down vote up
@Test
public void behaveAsSetMergedCollectionsOfLiteralsWithDuplicates() {
    new Assertion<>(
        "Must keep unique string literals",
        new SetOf<String>(
            new Joined<String>(
                new IterableOf<>("cc", "ff"),
                new IterableOf<>("aa", "bb", "cc", "dd")
            )
        ),
        new AllOf<>(
            new IterableOf<Matcher<? super SetOf<String>>>(
                new HasSize(5),
                new IsCollectionContaining<>(new IsEqual<>("aa")),
                new IsCollectionContaining<>(new IsEqual<>("bb")),
                new IsCollectionContaining<>(new IsEqual<>("cc")),
                new IsCollectionContaining<>(new IsEqual<>("dd")),
                new IsCollectionContaining<>(new IsEqual<>("ff"))
            )
        )
    ).affirm();
}
 
Example #3
Source Project: cactoos   Author: yegor256   File: SetOfTest.java    License: MIT License 6 votes vote down vote up
@Test
public void behaveAsSetWithOriginalDuplicationsOfCharsInTheMiddle() {
    new Assertion<>(
        "Must keep unique characters",
        new SetOf<>('a', 'b', 'b', 'c', 'a', 'b', 'd'),
        new AllOf<>(
            new IterableOf<Matcher<? super SetOf<Character>>>(
                new HasSize(4),
                new IsCollectionContaining<>(new IsEqual<>('a')),
                new IsCollectionContaining<>(new IsEqual<>('b')),
                new IsCollectionContaining<>(new IsEqual<>('c')),
                new IsCollectionContaining<>(new IsEqual<>('d'))
            )
        )
    ).affirm();
}
 
Example #4
Source Project: cactoos   Author: yegor256   File: SetOfTest.java    License: MIT License 6 votes vote down vote up
@Test
public void behaveAsSetWithOriginalDuplicationsOfTextsInTheMiddle() {
    new Assertion<>(
        "Must keep unique TextOf objects",
        new SetOf<>(
            new TextOf("12345"),
            new TextOf("67890"),
            new TextOf("12345"),
            new TextOf("00000")
        ),
        new AllOf<>(
            new IterableOf<Matcher<? super SetOf<TextOf>>>(
                new HasSize(3),
                new IsCollectionContaining<>(
                    new IsEqual<>(new TextOf("12345"))
                ),
                new IsCollectionContaining<>(
                    new IsEqual<>(new TextOf("67890"))
                ),
                new IsCollectionContaining<>(
                    new IsEqual<>(new TextOf("00000"))
                )
            )
        )
    ).affirm();
}
 
Example #5
Source Project: swblocks-decisiontree   Author: jpmorganchase   File: GroupDriverTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSplittingDrivers() {
    final List<InputDriver> subDriverList = createSubInputDrivers("test");
    final InputDriver subDriver = new GroupDriver("sub1", subDriverList);

    final List<InputDriver> drivers = new ArrayList<>(2);
    drivers.add(subDriver);
    drivers.add(new StringDriver("string1"));
    drivers.add(new RegexDriver("regex.?"));

    final GroupDriver group = new GroupDriver("group", drivers);
    assertNotNull(group);

    assertThat(group.convertDrivers(),
            IsCollectionContaining.hasItems("string1", "regex.?", "VG:sub1:test1:test2:test3:tes.?4"));

    final List<String> nonGroupDrivers = new ArrayList<>();
    final List<String> groupDrivers = new ArrayList<>();

    GroupDriver.convertDriversIntoDriversAndGroups(Arrays.asList(group.getSubDrivers(false)),
            nonGroupDrivers, groupDrivers);
    assertEquals("VG:sub1:test1:test2:test3:tes.?4", groupDrivers.get(0));
    assertThat(nonGroupDrivers, IsCollectionContaining.hasItems("string1", "regex.?"));
}
 
Example #6
Source Project: swblocks-decisiontree   Author: jpmorganchase   File: EvaluatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testEvaluatorWithRegexMultipleRules() {
    final Builder<RuleSetBuilder, DecisionTreeRuleSet> ruleSetBuilder =
            CommisionRuleSetSupplier.getCommissionRuleSetWithRegex();

    final DecisionTreeRuleSet ruleSet = ruleSetBuilder.build();
    final TreeNode node = constructTree(ruleSet);

    final List<EvaluationResult> results = Evaluator.evaluateAllResults(Arrays.asList("ELECTRONIC", "CME", "S&P",
            "US", "INDEX"), null, node);

    assertNotNull(results);
    assertEquals(3, results.size());
    final List<UUID> idResults = results.stream().map(EvaluationResult::getRuleIdentifier)
            .collect(Collectors.toList());
    assertThat(idResults, IsCollectionContaining.hasItems(new UUID(0, 0), new UUID(0, 1), new UUID(0, 7)));

    final Optional<UUID> result = Evaluator.singleEvaluate(Arrays.asList("ELECTRONIC", "CME", "S&P",
            "US", "INDEX"), null, node);
    assertTrue(result.isPresent());
    assertEquals(new UUID(0, 7), result.get());
}
 
Example #7
Source Project: swblocks-decisiontree   Author: jpmorganchase   File: EvaluatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testEvaluatorWithRegexMultipleRulesAndWildcards() {
    final Builder<RuleSetBuilder, DecisionTreeRuleSet> ruleSetBuilder =
            CommisionRuleSetSupplier.getCommissionRuleSetWithRegex();

    final DecisionTreeRuleSet ruleSet = ruleSetBuilder.build();
    final TreeNode node = constructTree(ruleSet);

    final List<EvaluationResult> results = Evaluator.evaluateAllResultsWithWildcards(
            Arrays.asList("ELECTRONIC", "CME", "S&P", "US", "INDEX"), null, node);

    assertNotNull(results);
    assertEquals(4, results.size());
    assertThat(results.stream().map(EvaluationResult::getRuleIdentifier).collect(Collectors.toList()),
            IsCollectionContaining.hasItems(new UUID(0, 0),
                    new UUID(0, 1), new UUID(0, 4),
                    new UUID(0, 7)));
}
 
Example #8
Source Project: swblocks-decisiontree   Author: jpmorganchase   File: DriverCacheTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFindByType() {
    final DriverCache cache = new DriverCache();
    final InputDriver stringDriver = new StringDriver("testString1");
    final InputDriver stringDriver2 = new StringDriver("testString2");
    final InputDriver regexDriver = new RegexDriver("tes.?");
    final InputDriver groupDriver = new GroupDriver("testGroup", Arrays.asList(
            new StringDriver("testSub1"), new StringDriver("testSub2")));
    cache.put(stringDriver);
    cache.put(stringDriver2);
    cache.put(regexDriver);
    cache.put(groupDriver);
    final List<InputDriver> regexResults = cache.findByInputDriverType(InputValueType.REGEX);
    assertNotNull(regexResults);
    assertEquals(regexDriver, regexResults.get(0));
    final List<InputDriver> groupDrivers = cache.findByInputDriverType(InputValueType.VALUE_GROUP);
    assertEquals(groupDriver, groupDrivers.get(0));
    final List<InputDriver> stringDrivers = cache.findByInputDriverType(InputValueType.STRING);
    assertThat(stringDrivers, IsCollectionContaining.hasItems(stringDriver, stringDriver2));
}
 
Example #9
Source Project: swblocks-decisiontree   Author: jpmorganchase   File: DecisionTreeRuleSetTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFindingInputDrivers() {
    final DecisionTreeRuleSet commisssionRuleSet = CommisionRuleSetSupplier.getCommissionRuleSetWithRegex().build();
    List<InputDriver> driversByType = commisssionRuleSet.getDriversByType(InputValueType.STRING);
    assertNotNull(driversByType);
    assertEquals(11, driversByType.size());
    assertThat(driversByType,
            IsCollectionContaining.hasItems(new StringDriver("VOICE"), new StringDriver("RATE"),
                    new StringDriver("UK"), new StringDriver("*"), new StringDriver("CME"),
                    new StringDriver("INDEX"), new StringDriver("S&P"),
                    new StringDriver("US"), new StringDriver("ED"), new StringDriver("NDK")));

    driversByType = commisssionRuleSet.getDriversByType(InputValueType.REGEX);
    assertNotNull(driversByType);
    assertEquals(3, driversByType.size());
    assertThat(driversByType, IsCollectionContaining.hasItems(new RegexDriver("AP.?C"),
            new RegexDriver("C.?E"), new RegexDriver("^[A-Z]{1,2}[A-Z][0-9]{1,2}$")));
}
 
Example #10
Source Project: swblocks-decisiontree   Author: jpmorganchase   File: DomainSerialiserTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void convertStringToGroupDriver() {
    final DriverCache cache = new DriverCache();
    final String testString = "VG:TestGroup:Test1:Test2:Test3";
    final Supplier<InputDriver> groupSupplier = DomainSerialiser.createInputDriver(testString, cache);
    final InputDriver groupDriver = groupSupplier.get();
    assertNotNull(groupDriver);
    assertEquals("TestGroup", groupDriver.getValue());
    assertEquals(InputValueType.VALUE_GROUP, groupDriver.getType());
    assertEquals(groupDriver, cache.get("TestGroup", InputValueType.VALUE_GROUP));
    final InputDriver[] drivers = ((GroupDriver) groupDriver).getSubDrivers(false);
    final InputDriver[] expected = {new StringDriver("Test1"), new StringDriver("Test2"),
            new StringDriver("Test3")};
    assertThat(Arrays.asList(drivers), IsCollectionContaining.hasItems(expected));

    List<String> serialisedDrivers = DomainSerialiser.convertDriversWithSubGroups(Arrays.asList(groupDriver));
    assertNotNull(serialisedDrivers);
    assertEquals(1, serialisedDrivers.size());
    assertEquals(testString, serialisedDrivers.get(0));

    serialisedDrivers = DomainSerialiser.convertDrivers(new InputDriver[]{groupDriver});
    assertNotNull(serialisedDrivers);
    assertEquals(1, serialisedDrivers.size());
    assertEquals(groupDriver.toString(), serialisedDrivers.get(0));
}
 
Example #11
Source Project: swblocks-decisiontree   Author: jpmorganchase   File: DomainSerialiserTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@Ignore("The support for a blank token at the end is not working.  Putting in test and will return to it.")
public void testEmptyTokensAtEndOfGroupDriver() {
    final DriverCache cache = new DriverCache();
    final String testString = "VG:TestGroup:Test1:Test2:Test3::VG:SubGroup:Test4:Test5:";
    final Supplier<InputDriver> groupSupplier = DomainSerialiser.createInputDriver(testString, cache);
    final InputDriver groupDriver = groupSupplier.get();
    assertNotNull(groupDriver);
    final InputDriver[] drivers = ((GroupDriver) groupDriver).getSubDrivers(false);
    final InputDriver[] expectedList = new InputDriver[]{
            new StringDriver("Test1"), new StringDriver("Test2"), new StringDriver("Test3"),
            new StringDriver(""),
            new GroupDriver("SubGroup",
                    Arrays.asList(new StringDriver("Test4"), new StringDriver("Test5"),
                            new StringDriver("")))};
    assertEquals(expectedList.length, drivers.length);
    assertThat(Arrays.asList(drivers), IsCollectionContaining.hasItems(expectedList));

    final List<String> serialisedDrivers = DomainSerialiser.convertDrivers(new InputDriver[]{groupDriver});
    assertEquals(testString, serialisedDrivers.get(0));
}
 
Example #12
Source Project: swblocks-decisiontree   Author: jpmorganchase   File: DomainSerialiserTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testConvertGroupDrivers() {
    final Builder<RuleBuilder, DecisionTreeRule> ruleBuilder = RuleBuilder.creator();
    final DriverCache cache = new DriverCache();
    final List<String> testInputs = Arrays.asList("VG:VG1:test1:test2:test3:test4", "singleTest",
            "VG:VG2:test10:test20:test30:test40:VG:VG3:test50:test9.?:test200.*");
    ruleBuilder.with(RuleBuilder::input, testInputs);
    ruleBuilder.with(RuleBuilder::cache, cache);
    ruleBuilder.with(RuleBuilder::setDriverCount, 3L);
    ruleBuilder.with(RuleBuilder::setId, new UUID(0, 1));
    ruleBuilder.with(RuleBuilder::output, Collections.singletonMap("outputDriver", "result"));
    final DecisionTreeRule rule = ruleBuilder.build();
    assertNotNull(rule);
    final InputDriver[] derivedInputDrivers = rule.getDrivers();

    List<String> result = DomainSerialiser.convertDriversWithSubGroups(Arrays.asList(derivedInputDrivers));
    assertNotNull(result);
    assertEquals(testInputs, result);

    result = DomainSerialiser.convertDrivers(derivedInputDrivers);
    assertNotNull(result);
    assertThat(result, IsCollectionContaining.hasItems("VG:VG1", "singleTest", "VG:VG2"));
}
 
Example #13
Source Project: JWTDecode.Android   Author: auth0   File: JWTTest.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("ConstantConditions")
@Test
public void shouldNotRemoveKnownPublicClaimsFromTree() {
    JWT jwt = new JWT("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCIsInN1YiI6ImVtYWlscyIsImF1ZCI6InVzZXJzIiwiaWF0IjoxMDEwMTAxMCwiZXhwIjoxMTExMTExMSwibmJmIjoxMDEwMTAxMSwianRpIjoiaWRpZCIsInJvbGVzIjoiYWRtaW4ifQ.jCchxb-mdMTq5EpeVMSQyTp6zSwByKnfl9U-Zc9kg_w");

    assertThat(jwt, is(notNullValue()));
    assertThat(jwt.getIssuer(), is("auth0"));
    assertThat(jwt.getSubject(), is("emails"));
    assertThat(jwt.getAudience(), is(IsCollectionContaining.hasItem("users")));
    assertThat(jwt.getIssuedAt().getTime(), is(10101010L * 1000));
    assertThat(jwt.getExpiresAt().getTime(), is(11111111L * 1000));
    assertThat(jwt.getNotBefore().getTime(), is(10101011L * 1000));
    assertThat(jwt.getId(), is("idid"));

    assertThat(jwt.getClaim("roles").asString(), is("admin"));
    assertThat(jwt.getClaim("iss").asString(), is("auth0"));
    assertThat(jwt.getClaim("sub").asString(), is("emails"));
    assertThat(jwt.getClaim("aud").asString(), is("users"));
    assertThat(jwt.getClaim("iat").asDouble(), is(10101010D));
    assertThat(jwt.getClaim("exp").asDouble(), is(11111111D));
    assertThat(jwt.getClaim("nbf").asDouble(), is(10101011D));
    assertThat(jwt.getClaim("jti").asString(), is("idid"));
}
 
Example #14
Source Project: lucene-solr   Author: apache   File: TestDynamicFieldNamesIndexCorrectly.java    License: Apache License 2.0 6 votes vote down vote up
private void assertThatDocsHaveCorrectFields(final Collection<SolrInputDocument> solrDocs,
    final SolrDocumentList resultDocs) {
  assertEquals("Wrong number of docs found", resultDocs.getNumFound(), solrDocs.size());
  final Map<Object,SolrDocument> resultMap = resultDocs.stream()
      .collect(Collectors.toMap(doc -> doc.getFieldValue("id"), doc -> doc));
  Iterator<SolrInputDocument> it = solrDocs.iterator();
  while (it.hasNext()) {
    final SolrInputDocument inDoc = it.next();
    final String id = inDoc.getField("id").getValue().toString();
    final SolrDocument resultDoc = resultMap.get(id);
    final Collection<String> resultFieldNames = resultDoc.getFieldNames();
    inDoc
        .getFieldNames()
        .forEach(
            fieldName -> {
              assertThat(
                  String.format(Locale.ROOT, "Doc %s does not have field %s, it has %s", id, fieldName,
                      resultFieldNames),
                  resultFieldNames, new IsCollectionContaining<>(new IsEqual<>(fieldName)));
            });
  }
}
 
Example #15
Source Project: openhab-core   Author: openhab   File: ChannelTypeResourceTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void returnLinkableItemTypesForTriggerChannelType() throws IOException {
    ChannelType channelType = mockChannelType("ct");
    ChannelTypeUID uid = channelType.getUID();
    ProfileTypeUID profileTypeUID = new ProfileTypeUID("system:profileType");

    when(channelTypeRegistry.getChannelType(uid)).thenReturn(channelType);

    TriggerProfileType profileType = mock(TriggerProfileType.class);
    when(profileType.getUID()).thenReturn(profileTypeUID);
    when(profileType.getSupportedChannelTypeUIDs()).thenReturn(Collections.singletonList(uid));
    when(profileType.getSupportedItemTypes()).thenReturn(Arrays.asList("Switch", "Dimmer"));

    when(profileTypeRegistry.getProfileTypes()).thenReturn(Collections.singletonList(profileType));

    Response response = channelTypeResource.getLinkableItemTypes(uid.getAsString());

    verify(channelTypeRegistry).getChannelType(uid);
    verify(profileTypeRegistry).getProfileTypes();
    assertThat(response.getStatus(), is(200));
    assertThat((Set<String>) response.getEntity(), IsCollectionContaining.hasItems("Switch", "Dimmer"));
}
 
Example #16
Source Project: docker-workflow-plugin   Author: jenkinsci   File: DockerUtilsTest.java    License: MIT License 6 votes vote down vote up
@Test public void parseBuildArgsOverridingDefaults() throws IOException, InterruptedException {

        Dockerfile dockerfile = getDockerfileDefaultArgs();

        final String registry = "http://private.registry:5000/";
        final String key_registry = "REGISTRY_URL";
        final String key_tag = "TAG";
        final String tag = "1.2.3";
        final String commangLine = "docker build -t hello-world --build-arg "+key_tag+"="+tag+
            " --build-arg "+key_registry+"="+registry;
        Map<String, String> buildArgs = DockerUtils.parseBuildArgs(dockerfile, commangLine);

        Assert.assertThat(buildArgs.keySet(), IsCollectionWithSize.hasSize(2));
        Assert.assertThat(buildArgs.keySet(), IsCollectionContaining.hasItems(key_registry, key_tag));
        Assert.assertThat(buildArgs.get(key_registry), IsEqual.equalTo(registry));
        Assert.assertThat(buildArgs.get(key_tag), IsEqual.equalTo(tag));
    }
 
Example #17
Source Project: testcontainers-java   Author: testcontainers   File: DirectoryTarResourceTest.java    License: MIT License 6 votes vote down vote up
public static <T> Matcher<Iterable<? super T>> exactlyNItems(final int n, Matcher<? super T> elementMatcher) {
    return new IsCollectionContaining<T>(elementMatcher) {
        @Override
        protected boolean matchesSafely(Iterable<? super T> collection, Description mismatchDescription) {
            int count = 0;
            boolean isPastFirst = false;

            for (Object item : collection) {

                if (elementMatcher.matches(item)) {
                    count++;
                }
                if (isPastFirst) {
                    mismatchDescription.appendText(", ");
                }
                elementMatcher.describeMismatch(item, mismatchDescription);
                isPastFirst = true;
            }

            if (count != n) {
                mismatchDescription.appendText(". Expected exactly " + n + " but got " + count);
            }
            return count == n;
        }
    };
}
 
Example #18
Source Project: takes   Author: yegor256   File: HttpServletRequestFakeTest.java    License: MIT License 6 votes vote down vote up
@Test
public void containsAHeaderAndItsValue() {
    MatcherAssert.assertThat(
        "Can't get the headers",
        Collections.list(
            new HttpServletRequestFake(
                new RqWithHeaders(
                    new RqFake(),
                    "TestHeader: someValue",
                    "SomeHeader: testValue"
                )
            ).getHeaders("testheader")
        ),
        new IsCollectionContaining<>(
            new IsEqual<>("someValue")
        )
    );
}
 
Example #19
Source Project: ehcache3   Author: ehcache   File: XmlConfigurationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testWriteBehind() throws Exception {
  final URL resource = XmlConfigurationTest.class.getResource("/configs/writebehind-cache.xml");
  XmlConfiguration xmlConfig = new XmlConfiguration(resource);

  Collection<ServiceConfiguration<?, ?>> serviceConfiguration = xmlConfig.getCacheConfigurations().get("bar").getServiceConfigurations();

  assertThat(serviceConfiguration, IsCollectionContaining.hasItem(instanceOf(WriteBehindConfiguration.class)));

  serviceConfiguration = xmlConfig.newCacheConfigurationBuilderFromTemplate("example", Number.class, String.class).build().getServiceConfigurations();

  assertThat(serviceConfiguration, IsCollectionContaining.hasItem(instanceOf(WriteBehindConfiguration.class)));

  for (ServiceConfiguration<?, ?> configuration : serviceConfiguration) {
    if(configuration instanceof WriteBehindConfiguration) {
      BatchingConfiguration batchingConfig = ((WriteBehindConfiguration) configuration).getBatchingConfiguration();
      assertThat(batchingConfig.getMaxDelay(), is(10L));
      assertThat(batchingConfig.getMaxDelayUnit(), is(SECONDS));
      assertThat(batchingConfig.isCoalescing(), is(false));
      assertThat(batchingConfig.getBatchSize(), is(2));
      assertThat(((WriteBehindConfiguration) configuration).getConcurrency(), is(1));
      assertThat(((WriteBehindConfiguration) configuration).getMaxQueueSize(), is(10));
      break;
    }
  }
}
 
Example #20
Source Project: ehcache3   Author: ehcache   File: ConfigurationDerivation.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void withServiceCreation() {
  Configuration configuration = ConfigurationBuilder.newConfigurationBuilder()
    .withCache("cache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10)))
    .build();

  //tag::withServiceCreation[]
  Configuration withBoundedThreads = configuration.derive()
    .withService(new PooledExecutionServiceConfiguration()
      .addDefaultPool("default", 1, 16))
    .build();
  //end::withServiceCreation[]

  Assert.assertThat(configuration.getServiceCreationConfigurations(), IsNot.not(IsCollectionContaining.hasItem(IsInstanceOf.instanceOf(PooledExecutionServiceConfiguration.class))));
  PooledExecutionServiceConfiguration serviceCreationConfiguration = ServiceUtils.findSingletonAmongst(PooledExecutionServiceConfiguration.class, withBoundedThreads.getServiceCreationConfigurations());
  Assert.assertThat(serviceCreationConfiguration.getDefaultPoolAlias(), Is.is("default"));
  Assert.assertThat(serviceCreationConfiguration.getPoolConfigurations().keySet(), IsIterableContainingInAnyOrder.containsInAnyOrder("default"));
  PooledExecutionServiceConfiguration.PoolConfiguration pool = serviceCreationConfiguration.getPoolConfigurations().get("default");
  Assert.assertThat(pool.minSize(), Is.is(1));
  Assert.assertThat(pool.maxSize(), Is.is(16));
}
 
Example #21
Source Project: ehcache3   Author: ehcache   File: ConfigurationDerivation.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void withService() {
  Configuration configuration = ConfigurationBuilder.newConfigurationBuilder()
    .withCache("cache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10)))
    .build();

  //tag::withService[]
  Configuration withThrowingStrategy = configuration.derive()
    .updateCache("cache", existing -> existing.withService(
      new DefaultResilienceStrategyConfiguration(new ThrowingResilienceStrategy<>())
    ))
    .build();
  //end::withService[]


  Assert.assertThat(configuration.getServiceCreationConfigurations(), IsNot.not(IsCollectionContaining.hasItem(
    IsInstanceOf.instanceOf(DefaultResilienceStrategyConfiguration.class))));

  DefaultResilienceStrategyConfiguration resilienceStrategyConfiguration =
    ServiceUtils.findSingletonAmongst(DefaultResilienceStrategyConfiguration.class,
      withThrowingStrategy.getCacheConfigurations().get("cache").getServiceConfigurations());
  Assert.assertThat(resilienceStrategyConfiguration.getInstance(), IsInstanceOf.instanceOf(ThrowingResilienceStrategy.class));
}
 
Example #22
Source Project: ehcache3   Author: ehcache   File: WriteBehindProviderFactoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testAddingWriteBehindConfigurationAtCacheLevel() {
  CacheManagerBuilder<CacheManager> cacheManagerBuilder = CacheManagerBuilder.newCacheManagerBuilder();
  WriteBehindConfiguration<?> writeBehindConfiguration = WriteBehindConfigurationBuilder.newBatchedWriteBehindConfiguration(Long.MAX_VALUE, SECONDS, 1)
      .concurrencyLevel(3)
      .queueSize(10)
      .build();
  Class<CacheLoaderWriter<?, ?>> klazz = (Class<CacheLoaderWriter<?, ?>>) (Class) (SampleLoaderWriter.class);
  CacheManager cacheManager = cacheManagerBuilder.build(true);
  final Cache<Long, String> cache = cacheManager.createCache("cache",
      CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(100))
          .withService(writeBehindConfiguration)
          .withService(new DefaultCacheLoaderWriterConfiguration(klazz))
          .build());
  Collection<ServiceConfiguration<?, ?>> serviceConfiguration = cache.getRuntimeConfiguration()
      .getServiceConfigurations();
  assertThat(serviceConfiguration, IsCollectionContaining.<ServiceConfiguration<?, ?>>hasItem(instanceOf(WriteBehindConfiguration.class)));
  cacheManager.close();
}
 
Example #23
Source Project: ehcache3   Author: ehcache   File: ServiceProviderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSupportsMultipleAuthoritativeTierProviders() throws Exception {

  ServiceLocator.DependencySet dependencySet = dependencySet();

  OnHeapStore.Provider cachingTierProvider = new OnHeapStore.Provider();
  OffHeapStore.Provider authoritativeTierProvider = new OffHeapStore.Provider();
  OffHeapDiskStore.Provider diskStoreProvider = new OffHeapDiskStore.Provider();

  dependencySet.with(cachingTierProvider);
  dependencySet.with(authoritativeTierProvider);
  dependencySet.with(diskStoreProvider);
  dependencySet.with(mock(DiskResourceService.class));
  dependencySet.with(mock(CacheManagerProviderService.class, Answers.RETURNS_DEEP_STUBS));

  ServiceLocator serviceLocator = dependencySet.build();
  serviceLocator.startAllServices();

  assertThat(serviceLocator.getServicesOfType(CachingTier.Provider.class),
    IsCollectionContaining.<CachingTier.Provider>hasItem(IsSame.<CachingTier.Provider>sameInstance(cachingTierProvider)));
  assertThat(serviceLocator.getServicesOfType(AuthoritativeTier.Provider.class),
    IsCollectionContaining.<AuthoritativeTier.Provider>hasItem(IsSame.<AuthoritativeTier.Provider>sameInstance(authoritativeTierProvider)));
  assertThat(serviceLocator.getServicesOfType(OffHeapDiskStore.Provider.class),
    IsCollectionContaining.<OffHeapDiskStore.Provider>hasItem(IsSame.<OffHeapDiskStore.Provider>sameInstance(diskStoreProvider)));
}
 
Example #24
Source Project: java-jwt   Author: auth0   File: PayloadDeserializerTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldGetStringArrayWhenParsingArrayNode() throws Exception {
    Map<String, JsonNode> tree = new HashMap<>();
    List<JsonNode> subNodes = new ArrayList<>();
    TextNode textNode1 = new TextNode("one");
    TextNode textNode2 = new TextNode("two");
    subNodes.add(textNode1);
    subNodes.add(textNode2);
    ArrayNode arrNode = new ArrayNode(JsonNodeFactory.instance, subNodes);
    tree.put("key", arrNode);

    List<String> values = deserializer.getStringOrArray(tree, "key");
    assertThat(values, is(notNullValue()));
    assertThat(values, is(IsCollectionWithSize.hasSize(2)));
    assertThat(values, is(IsCollectionContaining.hasItems("one", "two")));
}
 
Example #25
Source Project: smarthome   Author: eclipse-archived   File: ChannelTypeResourceTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void returnLinkableItemTypesForTriggerChannelType() throws IOException {
    ChannelType channelType = mockChannelType("ct");
    ChannelTypeUID uid = channelType.getUID();
    ProfileTypeUID profileTypeUID = new ProfileTypeUID("system:profileType");

    when(channelTypeRegistry.getChannelType(uid)).thenReturn(channelType);

    TriggerProfileType profileType = mock(TriggerProfileType.class);
    when(profileType.getUID()).thenReturn(profileTypeUID);
    when(profileType.getSupportedChannelTypeUIDs()).thenReturn(Collections.singletonList(uid));
    when(profileType.getSupportedItemTypes()).thenReturn(Arrays.asList("Switch", "Dimmer"));

    when(profileTypeRegistry.getProfileTypes()).thenReturn(Collections.singletonList(profileType));

    Response response = channelTypeResource.getLinkableItemTypes(uid.getAsString());

    verify(channelTypeRegistry).getChannelType(uid);
    verify(profileTypeRegistry).getProfileTypes();
    assertThat(response.getStatus(), is(200));
    assertThat((Set<String>) response.getEntity(), IsCollectionContaining.hasItems("Switch", "Dimmer"));
}
 
Example #26
Source Project: client_java   Author: prometheus   File: CustomMatchers.java    License: Apache License 2.0 6 votes vote down vote up
public static <T> Matcher<Iterable<? super T>> exactlyNItems(final int n, final Matcher<? super T> elementMatcher) {
  return new IsCollectionContaining<T>(elementMatcher) {
    @Override
    protected boolean matchesSafely(Iterable<? super T> collection, Description mismatchDescription) {
      int count = 0;
      boolean isPastFirst = false;

      for (Object item : collection) {

        if (elementMatcher.matches(item)) {
          count++;
        }
        if (isPastFirst) {
          mismatchDescription.appendText(", ");
        }
        elementMatcher.describeMismatch(item, mismatchDescription);
        isPastFirst = true;
      }

      if (count != n) {
        mismatchDescription.appendText(". Expected exactly " + n + " but got " + count);
      }
      return count == n;
    }
  };
}
 
Example #27
Source Project: zendesk-java-client   Author: cloudbees-oss   File: RealSmokeTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void getArticlesFromAnyLabels() throws Exception {
    createClientWithTokenOrPassword();
    /*
     Given 3 articles
        Article 1 with title "SomeLabelOne" and label "SomeLabelA"
        Article 2 with title "SomeLabelTwo" and labels "SomeLabelB" and "SomeLabelC"
        Article 3 with title "SomeLabelThree" and label "SomeLabelD"
     When a search by labels "SomeLabelA", "SomeLabelB"
     Then we get Article 1 and Article 2 but not Article 3
        because Article 1 and 2 have at least one of the labels, Article 3 has none
     */
    Iterable<Article> result = instance.getArticlesFromAnyLabels(Arrays.asList("SomeLabelA", "SomeLabelB"));
    Set<String> actualTitles = extractTitles(result);
    assertThat(actualTitles.size(), is(2));
    assertThat(actualTitles, IsCollectionContaining.hasItems("SomeLabelOne", "SomeLabelTwo"));
}
 
Example #28
Source Project: zendesk-java-client   Author: cloudbees-oss   File: RealSmokeTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void getArticlesFromAllLabels() throws Exception {
    createClientWithTokenOrPassword();
    /*
     Given 2 articles
        Article 1 with title "AllLabelOne" and label "AllLabelA"
        Article 2 with title "AllLabelTwo" and labels "AllLabelA" and "AllLabelB"
     When a search by labels "AllLabelA", "AllLabelB"
     Then we get Article 2 but not Article 1
        because Article 2 has both labels and Article 1 has only one
     */
    Iterable<Article> result = instance.getArticlesFromAllLabels(Arrays.asList("AllLabelA", "AllLabelB"));
    Set<String> actualTitles = extractTitles(result);
    assertThat(actualTitles.size(), is(1));
    assertThat(actualTitles, IsCollectionContaining.hasItems("AllLabelTwo"));
}
 
Example #29
Source Project: cactoos   Author: yegor256   File: RemoveDeletesValues.java    License: MIT License 5 votes vote down vote up
@Override
public boolean matchesSafely(final Map<K, V> map) {
    map.remove(this.key);
    MatcherAssert.assertThat(
        "Contains the key/value after remove",
        map,
        new IsNot<>(
            new IsMapContaining<>(
                new IsEqual<>(this.key),
                new IsEqual<>(this.value)
            )
        )
    );
    MatcherAssert.assertThat(
        "Contains the key in #keySet() after remove",
        map.keySet(),
        new IsNot<>(
            new IsCollectionContaining<>(new IsEqual<>(this.key))
        )
    );
    MatcherAssert.assertThat(
        "Contains the value in #values() after remove",
        map.values(),
        new IsNot<>(
            new IsCollectionContaining<>(new IsEqual<>(this.value))
        )
    );
    return true;
}
 
Example #30
Source Project: cactoos   Author: yegor256   File: SetOfTest.java    License: MIT License 5 votes vote down vote up
@Test
public void behaveAsSetWithOriginalDuplicationsInTheTail() {
    new Assertion<>(
        "Must keep unique integer numbers",
        new SetOf<>(1, 2, 2),
        new AllOf<>(
            new IterableOf<Matcher<? super SetOf<Integer>>>(
                new HasSize(2),
                new IsCollectionContaining<>(new IsEqual<>(1)),
                new IsCollectionContaining<>(new IsEqual<>(2))
            )
        )
    ).affirm();
}