org.hamcrest.collection.IsIterableContainingInAnyOrder Java Examples

The following examples show how to use org.hamcrest.collection.IsIterableContainingInAnyOrder. 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 File: UccGraphTraverserTest.java    From metanome-algorithms with Apache License 2.0 6 votes vote down vote up
@Test
public void testTraverseGraph() throws CouldNotReceiveResultException, ColumnNameMismatchException {
  // Setup
  List<PositionListIndex> pliList = fixture.getPLIList();
  LinkedList<String> columnNames = new LinkedList<>();
  Integer i;
  for (i = 0; i < pliList.size(); i++) {
    columnNames.add(i.toString());
  }
  ImmutableList<String> immutableColumnNames = ImmutableList.copyOf(columnNames);

  UccGraphTraverser graph = new UccGraphTraverser();
  graph.init(fixture.getPLIList(), mock(UniqueColumnCombinationResultReceiver.class), "relation",
             immutableColumnNames);
  Collection<ColumnCombinationBitset>
      expectedUniqueColumnCombinations =
      fixture.getExpectedBitset();

  //Execute functionality
  graph.traverseGraph();

  //Check result
  assertThat(graph.getMinimalPositiveColumnCombinations(), IsIterableContainingInAnyOrder
      .containsInAnyOrder(expectedUniqueColumnCombinations.toArray(
          new ColumnCombinationBitset[expectedUniqueColumnCombinations.size()])));
}
 
Example #2
Source File: IterablesExample.java    From levelup-java-examples with Apache License 2.0 6 votes vote down vote up
/**
 * Filter by class type
 */
@Test
public void filter_elements_by_type () {
	
	List<Object> randomObjects = Lists.newArrayList();
	randomObjects.add(new Integer(15));
	randomObjects.add(new Double(12));
	randomObjects.add("hello");
	randomObjects.add(Lists.newArrayList());
	randomObjects.add(Maps.newConcurrentMap());
	randomObjects.add("world");
	
	Iterable<String> strings = Iterables.filter(randomObjects, String.class);
	
	assertThat(strings, IsIterableContainingInAnyOrder.
			<String>containsInAnyOrder("hello", "world"));
}
 
Example #3
Source File: TestPun.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
@Test
public void testPun() {
  Node i = getNode("http://example.org/i");
  Node j = getNode("http://example.org/j");
  Node k = getNode("http://example.org/k");

  RelationshipType p = RelationshipType.withName("http://example.org/p");
  Relationship relationship = getOnlyElement(GraphUtil.getRelationships(i, j, p));
  assertThat("OPE edge should start with the subject.", relationship.getStartNode(), is(i));
  assertThat("OPE edge should end with the target.", relationship.getEndNode(), is(j));
  relationship = getOnlyElement(GraphUtil.getRelationships(i, k, OwlRelationships.RDFS_SUBCLASS_OF));
  assertThat("Subclass edge should start with i.", relationship.getStartNode(), is(i));
  assertThat("Subclass edge should end with k.", relationship.getEndNode(), is(k));
  assertThat("i is both a class an a named individual" , i.getLabels(), 
      is(IsIterableContainingInAnyOrder.containsInAnyOrder(OwlLabels.OWL_CLASS, OwlLabels.OWL_NAMED_INDIVIDUAL)));
}
 
Example #4
Source File: ConfigurationDerivation.java    From ehcache3 with 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 #5
Source File: ConfigurationDerivation.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void updateCache() {
  Configuration configuration = ConfigurationBuilder.newConfigurationBuilder()
    .withCache("cache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10)))
    .build();

  //tag::updateCache[]
  Configuration withOffHeap = configuration.derive()
    .updateCache("cache", cache -> cache.updateResourcePools(
      resources -> ResourcePoolsBuilder.newResourcePoolsBuilder(resources)
        .offheap(100, MemoryUnit.MB)
        .build()))
    .build();
  //end::updateCache[]

  Assert.assertThat(configuration.getCacheConfigurations().get("cache").getResourcePools().getResourceTypeSet(), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP));
  Assert.assertThat(withOffHeap.getCacheConfigurations().get("cache").getResourcePools().getResourceTypeSet(), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP, ResourceType.Core.OFFHEAP));
}
 
Example #6
Source File: MultiGettingStarted.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void multipleRetrieval() {
  XmlMultiConfiguration multipleConfiguration = XmlMultiConfiguration
    .from(getClass().getResource("/configs/docs/multi/multiple-managers.xml"))
    .build();
  XmlMultiConfiguration variantConfiguration = XmlMultiConfiguration
    .from(getClass().getResource("/configs/docs/multi/multiple-variants.xml"))
    .build();

  //tag::multipleRetrieval[]
  Map<String, Configuration> allConfigurations = multipleConfiguration.identities().stream() // <1>
    .collect(Collectors.toMap(i -> i, i -> multipleConfiguration.configuration(i))); // <2>
  Map<String, Configuration> offheapConfigurations = variantConfiguration.identities().stream()
    .collect(Collectors.toMap(i -> i, i -> variantConfiguration.configuration(i, "offheap"))); // <3>
  //end::multipleRetrieval[]

  Assert.assertThat(resourceMap(allConfigurations), AllOf.allOf(
    IsMapContaining.hasEntry(Is.is("foo-manager"), IsMapContaining.hasEntry(Is.is("foo"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP, ResourceType.Core.OFFHEAP))),
    IsMapContaining.hasEntry(Is.is("bar-manager"), IsMapContaining.hasEntry(Is.is("bar"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP, ResourceType.Core.OFFHEAP)))
  ));

  Assert.assertThat(resourceMap(offheapConfigurations), AllOf.allOf(
    IsMapContaining.hasEntry(Is.is("foo-manager"), IsMapContaining.hasEntry(Is.is("foo"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP, ResourceType.Core.OFFHEAP))),
    IsMapContaining.hasEntry(Is.is("bar-manager"), IsMapContaining.hasEntry(Is.is("bar"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP)))
  ));
}
 
Example #7
Source File: MultiGettingStarted.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void multipleVariants() {
  //tag::multipleVariants[]
  XmlMultiConfiguration variantConfiguration = XmlMultiConfiguration
    .from(getClass().getResource("/configs/docs/multi/multiple-variants.xml"))
    .build();

  Configuration fooConfiguration = variantConfiguration.configuration("foo-manager", "offheap"); // <1>
  //end::multipleVariants[]

  Assert.assertThat(resourceMap(variantConfiguration.identities().stream().collect(
    Collectors.toMap(Function.identity(), i -> variantConfiguration.configuration(i, "offheap"))
  )), AllOf.allOf(
    IsMapContaining.hasEntry(Is.is("foo-manager"), IsMapContaining.hasEntry(Is.is("foo"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP, ResourceType.Core.OFFHEAP))),
    IsMapContaining.hasEntry(Is.is("bar-manager"), IsMapContaining.hasEntry(Is.is("bar"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP)))
  ));

  Assert.assertThat(resourceMap(variantConfiguration.identities().stream().collect(
    Collectors.toMap(Function.identity(), i -> variantConfiguration.configuration(i, "heap"))
  )), AllOf.allOf(
    IsMapContaining.hasEntry(Is.is("foo-manager"), IsMapContaining.hasEntry(Is.is("foo"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP))),
    IsMapContaining.hasEntry(Is.is("bar-manager"), IsMapContaining.hasEntry(Is.is("bar"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP)))
  ));
}
 
Example #8
Source File: MultiGettingStarted.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void multipleConfigurations() {
  //tag::multipleManagers[]
  XmlMultiConfiguration multipleConfiguration = XmlMultiConfiguration
    .from(getClass().getResource("/configs/docs/multi/multiple-managers.xml")) // <1>
    .build(); // <2>

  Configuration fooConfiguration = multipleConfiguration.configuration("foo-manager"); // <3>
  //end::multipleManagers[]

  Assert.assertThat(resourceMap(multipleConfiguration.identities().stream().collect(
    Collectors.toMap(Function.identity(), multipleConfiguration::configuration)
  )), AllOf.allOf(
    IsMapContaining.hasEntry(Is.is("foo-manager"), IsMapContaining.hasEntry(Is.is("foo"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP, ResourceType.Core.OFFHEAP))),
    IsMapContaining.hasEntry(Is.is("bar-manager"), IsMapContaining.hasEntry(Is.is("bar"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP, ResourceType.Core.OFFHEAP)))
  ));
}
 
Example #9
Source File: HttpServletRequestFakeTest.java    From takes with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void containsAllHeadersNames() {
    MatcherAssert.assertThat(
        "Can't get the header names",
        Collections.list(
            new HttpServletRequestFake(
                new RqWithHeaders(
                    new RqFake(),
                    "AnyHeader: anyValue",
                    "CrazyHeader: crazyValue"
                )
            ).getHeaderNames()
        ),
        new IsIterableContainingInAnyOrder<>(
            new ListOf<>(
                new IsEqual<>("host"),
                new IsEqual<>("crazyheader"),
                new IsEqual<>("anyheader")
            )
        )
    );
}
 
Example #10
Source File: DataQueryParamsTest.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testFinancialYearPeriodResultsInTwoAggregationYears() {

    DataQueryParams params = DataQueryParams.newBuilder()
        .addDimension( new BaseDimensionalObject( PERIOD_DIM_ID, DimensionType.PERIOD, Lists.newArrayList( peC ) ) )
        .withDataPeriodType( PeriodType.getPeriodTypeFromIsoString( "2017" ) )
        .build();

    ListMap<DimensionalItemObject, DimensionalItemObject> periodMap = params.getDataPeriodAggregationPeriodMap();

    assertThat( periodMap.entrySet(), hasSize( 2 ) );

    assertThat( periodMap.keySet(), IsIterableContainingInAnyOrder.containsInAnyOrder(
        hasProperty( "isoDate", Matchers.is( "2017" ) ),
        hasProperty( "isoDate", Matchers.is( "2018" ) ) )
    );

    assertThat( periodMap.allValues(), hasSize( 2 ));

    assertThat( periodMap.allValues(), IsIterableContainingInAnyOrder.containsInAnyOrder(
        hasProperty( "isoDate", Matchers.is( peC.getIsoDate() ) ),
        hasProperty( "isoDate", Matchers.is( peC.getIsoDate() ) ) )
    );
}
 
Example #11
Source File: ExpressionService2Test.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testGetExpressionOperands()
{
    when( dataElementService.getDataElement( deA.getUid() ) ).thenReturn( deA );
    when( dataElementService.getDataElement( deB.getUid() ) ).thenReturn( deB );
    when( categoryService.getCategoryOptionCombo( coc.getUid() ) ).thenReturn( coc );

    Set<DataElementOperand> operands = target.getExpressionOperands( expressionO, PREDICTOR_EXPRESSION );

    assertEquals( 2, operands.size() );

    assertThat( operands,
            IsIterableContainingInAnyOrder.containsInAnyOrder(
                    allOf( hasProperty( "dataElement", is( deA ) ),
                            hasProperty( "categoryOptionCombo", is( coc) ),
                            hasProperty( "attributeOptionCombo", is( nullValue() ) ) ),
                    allOf( hasProperty( "dataElement", is( deB ) ),
                            hasProperty( "categoryOptionCombo", is( coc ) ),
                            hasProperty( "attributeOptionCombo", is( nullValue() ) ) ) ) );
}
 
Example #12
Source File: TestMetricConfig.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Test
public void tryBasicReport() throws InterruptedException {
  TestReportConfigurator trc1 = new TestReportConfigurator();
  MetricsConfigurator parent1a = new MetricsConfigurator("a", null, trc1, Arrays.asList("a\\.*"), Arrays.asList("a\\.b.*"));
  MetricsConfigurator parent1b = new MetricsConfigurator("b", null, trc1, Arrays.asList(), Arrays.asList());
  MetricsConfigurator parent2 = new MetricsConfigurator("b", null, new TestReportConfigurator(), Arrays.asList("a\\.*"), Arrays.asList("a\\.b.*"));

  Metrics.onChange(Arrays.asList(parent1a));

  {
    Collection<MetricsConfigurator> parent = Metrics.getConfigurators();
    assertEquals(1, parent.size());
    // ensure that reporter was called as expected.
    TestReportConfigurator trc = (TestReportConfigurator) parent.iterator().next().getConfigurator();
    Thread.sleep(120);
    assertTrue(trc.getCount() > 5);
  }

  // make sure that parent 2 is added without changing parent1a.
  Metrics.onChange(Arrays.asList(parent1a, parent2));
  assertThat("swapped item is correct", Arrays.asList(parent1a, parent2), IsIterableContainingInAnyOrder.containsInAnyOrder(Metrics.getConfigurators().toArray()));

  // make sure that parent1a is swapped with parent 1b.
  Metrics.onChange(Arrays.asList(parent1b, parent2));
  assertThat("swapped item is correct", Arrays.asList(parent1b, parent2), IsIterableContainingInAnyOrder.containsInAnyOrder(Metrics.getConfigurators().toArray()));
}
 
Example #13
Source File: IterableContains.java    From alchemy with Apache License 2.0 5 votes vote down vote up
public static <T> Matcher<Iterable<? extends T>> inAnyOrder(Iterable<T> items) {
    final Collection<Matcher<? super T>> matchers = new ArrayList<>();
    for (final Object item : items) {
        matchers.add(IsEqual.equalTo(item));
    }
    return IsIterableContainingInAnyOrder.containsInAnyOrder(matchers);
}
 
Example #14
Source File: IterablesExample.java    From levelup-java-examples with Apache License 2.0 5 votes vote down vote up
/**
 * Combine two iterables
 */
@Test
public void concat_two_iterables () {
	
	List<String> list1 = Lists.newArrayList("one");
	List<String> list2 = Lists.newArrayList("two");
	
	Iterable<String> oneAndTwo = Iterables.concat(list1, list2);
	
	assertThat(oneAndTwo, IsIterableContainingInAnyOrder.
			<String>containsInAnyOrder("one", "two"));
}
 
Example #15
Source File: PruningGraphTest.java    From metanome-algorithms with Apache License 2.0 5 votes vote down vote up
/**
 * Unique Graph tests
 */
@Test
public void testAddSimpleInsert() {
  //Setup
  PruningGraph graph = new PruningGraph(5, 10, true);

  ColumnCombinationBitset actualColumnCombinationAC = fixture.columnCombinationAC;
  ColumnCombinationBitset actualColumnCombinationBC = fixture.columnCombinationBC;

  ColumnCombinationBitset expectedKeyA = fixture.columnCombinationA;
  ColumnCombinationBitset expectedKeyB = fixture.columnCombinationB;
  ColumnCombinationBitset expectedKeyC = fixture.columnCombinationC;

  List<ColumnCombinationBitset> expectedList = new LinkedList<>();
  expectedList.add(actualColumnCombinationAC);
  expectedList.add(actualColumnCombinationBC);

  //Execute functionality
  graph.add(actualColumnCombinationAC);
  graph.add(actualColumnCombinationBC);

  //Check results
  assertTrue(graph.columnCombinationMap.containsKey(expectedKeyA));
  assertEquals(actualColumnCombinationAC, graph.columnCombinationMap.get(expectedKeyA).get(0));

  assertTrue(graph.columnCombinationMap.containsKey(expectedKeyB));
  assertEquals(actualColumnCombinationBC, graph.columnCombinationMap.get(expectedKeyB).get(0));

  assertTrue(graph.columnCombinationMap.containsKey(expectedKeyC));
  assertThat(graph.columnCombinationMap.get(expectedKeyC), IsIterableContainingInAnyOrder
      .containsInAnyOrder(
          expectedList.toArray(new ColumnCombinationBitset[expectedList.size()])));

}
 
Example #16
Source File: SitesToShardsTest.java    From dataflow-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testSiteParsing() throws Exception {
  DoFnTester<String, Contig> sitesToContigsFn =
      DoFnTester.of(new SitesToShards.SitesToContigsFn());
  String [] input = {
      "chrX,2000001,3000000",
      "chrX  2000002 3000000", // tab
      "chrX 2000003 3000000", // space
      "chrX:2000004:3000000", // colon
      " chrX  2000005     3000000 ", // more white space
      "chrX,2000006,3000000,foo,bar", // additional fields
      "17,2000000,3000000",
      "M,2000000,3000000",
      "chr9_gl000199_random,2000000,3000000",
      "GL.123,2000000,3000000",
      "track name=pairedReads description=\"Clone Paired Reads\" useScore=1", // BED header
  };

  Assert.assertThat(sitesToContigsFn.processBundle(input),
      IsIterableContainingInAnyOrder.containsInAnyOrder(
          new Contig("chrX", 2000001, 3000000),
          new Contig("chrX", 2000002, 3000000),
          new Contig("chrX", 2000003, 3000000),
          new Contig("chrX", 2000004, 3000000),
          new Contig("chrX", 2000005, 3000000),
          new Contig("chrX", 2000006, 3000000),
          new Contig("17", 2000000, 3000000),
          new Contig("M", 2000000, 3000000),
          new Contig("chr9_gl000199_random", 2000000, 3000000),
          new Contig("GL.123", 2000000, 3000000)
          ));
}
 
Example #17
Source File: AnnotateVariantsITCase.java    From dataflow-java with Apache License 2.0 5 votes vote down vote up
private void testBase(String[] ARGS, String[] expectedResult) throws Exception {
  // Run the pipeline.
  AnnotateVariants.main(ARGS);

  // Download the pipeline results.
  List<String> results = helper.downloadOutputs(outputPrefix, expectedResult.length);

  // Check the pipeline results.
  assertEquals(expectedResult.length, results.size());
  assertThat(results,
    IsIterableContainingInAnyOrder.containsInAnyOrder(expectedResult));
}
 
Example #18
Source File: TinkerGraphUtilTest.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void labelsAreTranslated() {
  Label label = Label.label("label");
  when(node.getLabels()).thenReturn(newHashSet(label));
  TinkerGraphUtil tgu = new TinkerGraphUtil(curieUtil);
  Vertex v = tgu.addNode(node);
  assertThat((Iterable<String>)v.getProperty("types"), IsIterableContainingInAnyOrder.containsInAnyOrder("label"));
}
 
Example #19
Source File: AndConditionTraverserTest.java    From metanome-algorithms with Apache License 2.0 5 votes vote down vote up
@Test
public void testCalculateConditions() throws Exception {
  //Setup
  PositionListIndex uniquePLI = fixture.getUniquePLIForConditionTest();
  PositionListIndex conditionPLI = fixture.getConditionPLIForConditionTest();
  List<LongArrayList> expectedConditions = fixture.getExpectedConditions();
  //Execute functionality
  List<LongArrayList> unsatisfiedClusters = new LinkedList<>();
  AndConditionTraverser traverser = new AndConditionTraverser(new Dcucc());

  List<LongArrayList>
      actualConditions =
      traverser
          .calculateConditions(uniquePLI, conditionPLI, fixture.getFrequency(),
                               unsatisfiedClusters);
  //Check result
  assertThat(actualConditions,
             IsIterableContainingInAnyOrder.containsInAnyOrder(
                 expectedConditions.toArray()
             )
  );
  assertEquals(unsatisfiedClusters.get(0), fixture.getExpectedUnsatisfiedClusters().get(0));
}
 
Example #20
Source File: PruningGraphTest.java    From metanome-algorithms with Apache License 2.0 5 votes vote down vote up
/**
 * Unique Graph tests
 */
@Test
public void testAddSimpleInsert() {
    //Setup
    PruningGraph graph = new PruningGraph(5, 10, true);

    ColumnCombinationBitset actualColumnCombinationAC = fixture.columnCombinationAC;
    ColumnCombinationBitset actualColumnCombinationBC = fixture.columnCombinationBC;

    ColumnCombinationBitset expectedKeyA = fixture.columnCombinationA;
    ColumnCombinationBitset expectedKeyB = fixture.columnCombinationB;
    ColumnCombinationBitset expectedKeyC = fixture.columnCombinationC;

    List<ColumnCombinationBitset> expectedList = new LinkedList<>();
    expectedList.add(actualColumnCombinationAC);
    expectedList.add(actualColumnCombinationBC);

    //Execute functionality
    graph.add(actualColumnCombinationAC);
    graph.add(actualColumnCombinationBC);

    //Check results
    assertTrue(graph.columnCombinationMap.containsKey(expectedKeyA));
    assertEquals(actualColumnCombinationAC, graph.columnCombinationMap.get(expectedKeyA).get(0));

    assertTrue(graph.columnCombinationMap.containsKey(expectedKeyB));
    assertEquals(actualColumnCombinationBC, graph.columnCombinationMap.get(expectedKeyB).get(0));

    assertTrue(graph.columnCombinationMap.containsKey(expectedKeyC));
    assertThat(graph.columnCombinationMap.get(expectedKeyC), IsIterableContainingInAnyOrder.containsInAnyOrder(expectedList.toArray(new ColumnCombinationBitset[expectedList.size()])));

}
 
Example #21
Source File: ForEachInThreadsTest.java    From cactoos with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testProcIterable() throws Exception {
    final List<Integer> list = new Synced<>(
        new ListOf<>()
    );
    new ForEachInThreads<Integer>(
        new ProcNoNulls<>(
            list::add
        )
    ).exec(
        new ListOf<>(
            1, 2
        )
    );
    new Assertion<>(
        "List does not contain mapped Iterable elements",
        list,
        new IsIterableContainingInAnyOrder<>(
            new ListOf<>(
                new MatcherOf<>(
                    value -> {
                        return value.equals(
                            1
                        );
                    }
                ), new MatcherOf<>(
                    value -> {
                        return value.equals(
                            2
                        );
                    }
                )
            )
        )
    ).affirm();
}
 
Example #22
Source File: AndInThreadsTest.java    From cactoos with MIT License 5 votes vote down vote up
@Test
public void iteratesList() {
    final List<String> list = new Synced<>(new ListOf<>());
    new Assertion<>(
        "Must iterate a list with a procedure",
        new AndInThreads(
            new Mapped<String, Scalar<Boolean>>(
                new FuncOf<>(list::add, () -> true),
                new IterableOf<>("hello", "world")
            )
        ),
        new ScalarHasValue<>(true)
    ).affirm();
    new Assertion<>(
        "Iterable must contain elements in any order",
        list,
        new IsIterableContainingInAnyOrder<String>(
            new ListOf<Matcher<? super String>>(
                new MatcherOf<>(
                    text -> {
                        return "hello".equals(text);
                    }
                ),
                new MatcherOf<>(
                    text -> {
                        return "world".equals(text);
                    }
                )
            )
        )
    ).affirm();
}
 
Example #23
Source File: AndInThreadsTest.java    From cactoos with MIT License 5 votes vote down vote up
@Test
public void worksWithExecServiceProcValues() throws Exception {
    final List<Integer> list = new Synced<>(new ListOf<>());
    final ExecutorService service = Executors.newSingleThreadExecutor();
    new AndInThreads(
        service,
        new ProcNoNulls<Integer>(list::add),
        1, 2
    ).value();
    MatcherAssert.assertThat(
        list,
        new IsIterableContainingInAnyOrder<Integer>(
            new ListOf<Matcher<? super Integer>>(
                new MatcherOf<>(
                    value -> {
                        return value.equals(1);
                    }
                ),
                new MatcherOf<>(
                    value -> {
                        return value.equals(2);
                    }
                )
            )
        )
    );
}
 
Example #24
Source File: AndInThreadsTest.java    From cactoos with MIT License 5 votes vote down vote up
@Test
public void worksWithExecServiceProcIterable() throws Exception {
    final List<Integer> list = new Synced<>(new ListOf<>());
    final ExecutorService service = Executors.newSingleThreadExecutor();
    new AndInThreads(
        service,
        new ProcNoNulls<Integer>(list::add),
        new ListOf<>(1, 2)
    ).value();
    MatcherAssert.assertThat(
        list,
        new IsIterableContainingInAnyOrder<Integer>(
            new ListOf<Matcher<? super Integer>>(
                new MatcherOf<>(
                    value -> {
                        return value.equals(1);
                    }
                ),
                new MatcherOf<>(
                    value -> {
                        return value.equals(2);
                    }
                )
            )
        )
    );
}
 
Example #25
Source File: ComponentDAOTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testBrowseComponentCoordinates() {

  // scatter components and assets
  generateRandomRepositories(10);
  generateRandomContent(10, 100);

  List<Component> browsedComponents = new ArrayList<>();

  try (DataSession<?> session = sessionRule.openSession("content")) {
    ComponentDAO dao = session.access(TestComponentDAO.class);

    assertThat(generatedRepositories().stream()
        .map(ContentRepositoryData::contentRepositoryId)
        .collect(summingInt(dao::countComponents)), is(10));

    // now gather them back by browsing
    generatedRepositories().forEach(r ->
        dao.browseNamespaces(r.repositoryId).forEach(ns ->
            dao.browseNames(r.repositoryId, ns).forEach(n ->
                dao.browseVersions(r.repositoryId, ns, n).forEach(v ->
                    browsedComponents.add(
                        dao.readComponent(r.repositoryId, ns, n, v).get())
    ))));
  }

  // we should have the same components, but maybe in a different order
  // (use hamcrest class directly as javac picks the wrong static varargs method)
  assertThat(browsedComponents, new IsIterableContainingInAnyOrder<>(
      generatedComponents().stream()
      .map(ExampleContentTestSupport::sameCoordinates)
      .collect(toList())));
}
 
Example #26
Source File: ServerPojoTest.java    From vind with Apache License 2.0 5 votes vote down vote up
private void checkPojo(Pojo expected, Pojo actual) {
    assertThat("results[" + expected.id + "]", actual, SamePropertyValuesAs.samePropertyValuesAs(expected));
    assertThat("results[" + expected.id + "].id", actual.id, CoreMatchers.equalTo(expected.id));
    assertThat("results[" + expected.id + "].title", actual.title, CoreMatchers.equalTo(expected.title));
    assertThat("results[" + expected.id + "].content", actual.content, CoreMatchers.equalTo(expected.content));
    assertThat("results[" + expected.id + "].category", actual.category, IsIterableContainingInAnyOrder.containsInAnyOrder(expected.category.toArray()));
}
 
Example #27
Source File: DefaultDataQueryServiceTest.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void assertOrgUnitGroup( String ouGroupUID, DimensionalObject dimension )
{
    assertThat( dimension.getDimensionalKeywords().getGroupBy(), hasSize( 2 ) );

    assertThat( dimension.getDimensionalKeywords().getGroupBy(),
        IsIterableContainingInAnyOrder.containsInAnyOrder(
            allOf( hasProperty( "name", is( "Chiefdom" ) ), hasProperty( "uid", is( ouGroupUID ) ),
                    hasProperty( "code", is( "CODE_001" ) ) ),
            allOf( hasProperty( "name", is( "Sierra Leone" ) ), hasProperty( "uid", is( rootOu.getUid() ) ),
                    hasProperty( "code", is( rootOu.getCode() ) ) ) ) );
}
 
Example #28
Source File: SchemaToDataFetcherTest.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void verifyUniqueFieldsAreSkippedOnReflectionError()
{
    Schema schema = createSchema( DummyDataElement.class, "dummyDataElement",
        Stream.of(
            createUniqueProperty( String.class, "url", true, true ),
            createUniqueProperty( String.class, "code", true, true )).collect(toList())
    );

    mockSession( "SELECT code,url from " + schema.getKlass().getSimpleName() );

    List<Object[]> l = new ArrayList();

    l.add( new Object[] { "abc", "http://ok" } );
    l.add( new Object[] { "bce", "http://-exception" } );
    l.add( new Object[] { "def", "http://also-ok" } );

    when( query.getResultList() ).thenReturn( l );

    List<DataElement> result = (List<DataElement>) subject.fetch( schema );

    assertThat( result, hasSize( 2 ) );

    assertThat( result, IsIterableContainingInAnyOrder.containsInAnyOrder(
        allOf(
                hasProperty( "code", is( "def" ) ),
                hasProperty( "url", is( "http://also-ok" ) )
        ),
        allOf(
                hasProperty( "code", is( "abc" ) ),
                hasProperty( "url", is( "http://ok" ) )
        )
    ) );
}
 
Example #29
Source File: TestTableProviderWithFilterPushDown.java    From beam with Apache License 2.0 5 votes vote down vote up
@Test
public void testIOSourceRel_selectOneFieldsMoreThanOnce() {
  String selectTableStatement = "SELECT b, b, b, b, b FROM TEST";

  BeamRelNode beamRelNode = sqlEnv.parseQuery(selectTableStatement);
  PCollection<Row> result = BeamSqlRelUtils.toPCollection(pipeline, beamRelNode);

  // Calc must not be dropped
  assertThat(beamRelNode, instanceOf(BeamCalcRel.class));
  assertThat(beamRelNode.getInput(0), instanceOf(BeamIOSourceRel.class));
  // Make sure project push-down was done
  List<String> pushedFields = beamRelNode.getInput(0).getRowType().getFieldNames();
  // When performing standalone filter push-down IO should project all fields.
  assertThat(
      pushedFields,
      IsIterableContainingInAnyOrder.containsInAnyOrder("unused1", "id", "name", "unused2", "b"));

  assertEquals(
      Schema.builder()
          .addBooleanField("b")
          .addBooleanField("b0")
          .addBooleanField("b1")
          .addBooleanField("b2")
          .addBooleanField("b3")
          .build(),
      result.getSchema());
  PAssert.that(result)
      .containsInAnyOrder(
          row(result.getSchema(), true, true, true, true, true),
          row(result.getSchema(), false, false, false, false, false));

  pipeline.run().waitUntilFinish(Duration.standardMinutes(2));
}
 
Example #30
Source File: TestTableProviderWithFilterPushDown.java    From beam with Apache License 2.0 5 votes vote down vote up
@Test
public void testIOSourceRel_selectOneFieldsMoreThanOnce_withSupportedPredicate() {
  String selectTableStatement = "SELECT b, b, b, b, b FROM TEST where b";

  // Calc must not be dropped
  BeamRelNode beamRelNode = sqlEnv.parseQuery(selectTableStatement);
  PCollection<Row> result = BeamSqlRelUtils.toPCollection(pipeline, beamRelNode);

  assertThat(beamRelNode, instanceOf(BeamCalcRel.class));
  // Supported predicate should be pushed-down
  assertNull(((BeamCalcRel) beamRelNode).getProgram().getCondition());
  assertThat(beamRelNode.getInput(0), instanceOf(BeamIOSourceRel.class));
  // Make sure project push-down was done
  List<String> pushedFields = beamRelNode.getInput(0).getRowType().getFieldNames();
  assertThat(
      pushedFields,
      IsIterableContainingInAnyOrder.containsInAnyOrder("unused1", "id", "name", "unused2", "b"));

  assertEquals(
      Schema.builder()
          .addBooleanField("b")
          .addBooleanField("b0")
          .addBooleanField("b1")
          .addBooleanField("b2")
          .addBooleanField("b3")
          .build(),
      result.getSchema());
  PAssert.that(result).containsInAnyOrder(row(result.getSchema(), true, true, true, true, true));

  pipeline.run().waitUntilFinish(Duration.standardMinutes(2));
}