Java 类com.beust.jcommander.internal.Sets 实例源码

项目:cerberus-lifecycle-cli    文件:TokenSupplierTest.java   
@Test
public void sanityTestGet() {

    TokenSupplier supplier = new TokenSupplier();

    Set<String> previous = Sets.newHashSet();
    for (int i = 0; i < 1000; i++) {
        String current = supplier.get();

        // not the same
        assertFalse(previous.contains(current));

        // check length
        assertEquals(24, current.length());

        previous.add(current);
    }
}
项目:nomulus    文件:GetAppliedLabelsCommand.java   
/** Return a set of all fully-qualified domain names with open applications. */
private static Set<String> getDomainApplicationMap(final String tld) {
  return ofy()
      .transact(
          () -> {
            Set<String> labels = Sets.newHashSet();
            List<DomainApplication> domainApplications;
            domainApplications =
                ofy().load().type(DomainApplication.class).filter("tld", tld).list();
            for (DomainApplication domainApplication : domainApplications) {
              // Ignore deleted and rejected applications. They aren't under consideration.
              ApplicationStatus applicationStatus = domainApplication.getApplicationStatus();
              DateTime deletionTime = domainApplication.getDeletionTime();
              if (applicationStatus == REJECTED
                  || isAtOrAfter(ofy().getTransactionTime(), deletionTime)) {
                continue;
              }
              labels.add(domainApplication.getFullyQualifiedDomainName());
            }
            return labels;
          });
}
项目:artifactory    文件:AqlJSonResultTest.java   
private boolean contains(Map resultMap, Map expectedMap) {
    for (Object o : resultMap.keySet()) {
        Object result = resultMap.get(o);
        Object expected = expectedMap.get(o);
        if (result instanceof Map) {
            contains((Map) result, (Map) expected);
        } else if (result instanceof List) {

            Set<Object> resultSet = Sets.newHashSet();
            resultSet.addAll((List) result);
            Set<Object> expectedSet = Sets.newHashSet();
            resultSet.addAll((List) expected);
            contains(resultSet, expectedSet);
        } else if (!result.equals(expected)) {
            return false;
        }
    }
    return true;
}
项目:lsql    文件:LSqlTest.java   
@Test
public void fetchMetaDataForAllTables() throws SQLException {
    createTable("CREATE TABLE table1 (a TEXT, b INT)");
    createTable("CREATE TABLE table2 (c TEXT, d INT)");

    lSql.fetchMetaDataForAllTables();

    Set<String> tableWithColumns = Sets.newHashSet();
    Iterable<Table> tables = lSql.getTables();
    for (Table table : tables) {
        for (Column column : table.getColumns().values()) {
            tableWithColumns.add(table.getTableName() + "-" + column.getJavaColumnName());
        }
    }

    assertTrue(tableWithColumns.contains("table1-a"));
    assertTrue(tableWithColumns.contains("table1-b"));
    assertTrue(tableWithColumns.contains("table2-c"));
    assertTrue(tableWithColumns.contains("table2-d"));
}
项目:amza    文件:AmzaBotEndpointsTest.java   
@Test
public void verifyBatchSetPost() throws Exception {
    Set<Entry<String, String>> set = Sets.newHashSet();
    set.add(new AbstractMap.SimpleEntry<>("foo", "bar"));
    set.add(new AbstractMap.SimpleEntry<>("ham", "eggs"));

    String setJson = new ObjectMapper().writeValueAsString(set);
    Assert.assertEquals(setJson, "[{\"ham\":\"eggs\"},{\"foo\":\"bar\"}]");

    // i.e.
    //
    // curl -X POST \
    //   -H "Content-Type:application/json" \
    //   -d '[{"ham":"eggs"},{"foo":"bar"}]' \
    //   10.126.5.87:10000/api/amzabot/v1/keys
}
项目:occurrence    文件:VerbatimProcessorTest.java   
@Before
public void setUp() throws Exception {
  long now = new Date().getTime();
  zkServer = new TestingServer();
  curator = CuratorFrameworkFactory.builder().connectString(zkServer.getConnectString()).namespace("crawler")
    .retryPolicy(new RetryNTimes(1, 1000)).build();
  curator.start();
  zookeeperConnector = new ZookeeperConnector(curator);

  fragmentService = new FragmentPersistenceServiceMock(new OccurrenceKeyPersistenceServiceMock());
  String json = Resources.toString(Resources.getResource("fragment.json"), org.apache.commons.io.Charsets.UTF_8);
  Fragment fragment = new Fragment(DATASET_KEY, json.getBytes(Charsets.UTF_8), json.getBytes(Charsets.UTF_8),
    Fragment.FragmentType.JSON, EndpointType.DWC_ARCHIVE, new Date(), 1, null, null, new Date().getTime());
  Set<UniqueIdentifier> uniqueIds = Sets.newHashSet();
  uniqueIds.add(new HolyTriplet(DATASET_KEY, "ic", "cc", "cn", null));
  fragmentService.insert(fragment, uniqueIds);
  occurrenceService = new OccurrencePersistenceServiceMock(fragmentService);
  verbatimProcessor = new VerbatimProcessor(fragmentService, occurrenceService, messagePublisher, zookeeperConnector);
  FragmentPersistedListener fragmentPersistedListener = new FragmentPersistedListener(verbatimProcessor);
  MessageListener messageListener = new MessageListener(CONNECTION_PARAMETERS);
  messageListener.listen("frag_persisted_test_" + now, 1, fragmentPersistedListener);
}
项目:occurrence    文件:OccurrenceInterpreterTest.java   
@Before
public void setUp() throws Exception {
  ApiClientConfiguration cfg = new ApiClientConfiguration();;
  cfg.url = URI.create("http://api.gbif-dev.org/v1/");

  FragmentPersistenceService fragmentPersister =
    new FragmentPersistenceServiceMock(new OccurrenceKeyPersistenceServiceMock());
  Fragment fragment = new Fragment(DATASET_KEY, "fake".getBytes(Charsets.UTF_8), "fake".getBytes(Charsets.UTF_8),
    Fragment.FragmentType.JSON, EndpointType.DWC_ARCHIVE, new Date(), 1, null, null, new Date().getTime());
  Set<UniqueIdentifier> uniqueIds = Sets.newHashSet();
  uniqueIds.add(new HolyTriplet(DATASET_KEY, "ic", "cc", "cn", null));
  fragmentPersister.insert(fragment, uniqueIds);
  interpreter = new OccurrenceInterpreter(new DatasetInfoInterpreter(cfg.newApiClient()),
    new TaxonomyInterpreter(cfg.newApiClient()),
    new LocationInterpreter(new CoordinateInterpreter(cfg.newApiClient())));

  verb = buildVerbatim(fragment.getKey());

  verbMod = buildVerbatim(fragment.getKey());
  verbMod.setVerbatimField(DwcTerm.scientificName, "Panthera onca goldmani");
}
项目:ttc2017smartGrids    文件:Parameterized.java   
/**
 * Given an object return the set of classes that it extends
 * or implements.
 *
 * @param arg object to describe
 * @return set of classes that are implemented or extended by that object
 */
private static Set<Class<?>> describeClassTree(Class<?> inputClass) {
  if(inputClass == null) {
    return Collections.emptySet();
  }

  // create result collector
  Set<Class<?>> classes = Sets.newLinkedHashSet();

  // describe tree
  describeClassTree(inputClass, classes);

  return classes;
}
项目:ttc2017smartGrids    文件:Parameterized.java   
/**
 * Given an object return the set of classes that it extends
 * or implements.
 *
 * @param arg object to describe
 * @return set of classes that are implemented or extended by that object
 */
private static Set<Class<?>> describeClassTree(Class<?> inputClass) {
  if(inputClass == null) {
    return Collections.emptySet();
  }

  // create result collector
  Set<Class<?>> classes = Sets.newLinkedHashSet();

  // describe tree
  describeClassTree(inputClass, classes);

  return classes;
}
项目:cerberus-lifecycle-cli    文件:UploadCertFilesPathValidator.java   
@Override
public void validate(final String name, final Path value) throws ParameterException {

    if (value == null) {
        throw new ParameterException("Value must be specified.");
    }

    final File certDirectory = value.toFile();
    final Set<String> filenames = Sets.newHashSet();

    if (!certDirectory.canRead()) {
        throw new ParameterException("Specified path is not readable.");
    }

    if (!certDirectory.isDirectory()) {
        throw new ParameterException("Specified path is not a directory.");
    }


    final FilenameFilter filter = new RegexFileFilter("^.*\\.pem$");
    final File[] files = certDirectory.listFiles(filter);
    Arrays.stream(files).forEach(file -> filenames.add(file.getName()));

    if (!filenames.containsAll(EXPECTED_FILE_NAMES)) {
        final StringJoiner sj = new StringJoiner(", ", "[", "]");
        EXPECTED_FILE_NAMES.stream().forEach(sj::add);
        throw new ParameterException("Not all expected files are present! Expected: " + sj.toString());
    }
}
项目:jira-dvcs-connector    文件:EntityBeanGeneratorTest.java   
@Test
public void beanShouldImplementEqualsAndHashcode() throws Exception
{
    RepositoryPullRequestMapping bean1 = generator.createInstanceOf(RepositoryPullRequestMapping.class);
    RepositoryPullRequestMapping bean2 = generator.createInstanceOf(RepositoryPullRequestMapping.class);

    Set<RepositoryPullRequestMapping> set = Sets.newHashSet();
    set.add(bean1);
    set.add(bean2);
    assertEquals(set.size(), 2);

    set.remove(bean1);
    assertEquals(set.size(), 1);
    assertEquals(true, set.contains(bean2));
}
项目:jira-dvcs-connector    文件:OrganizationTest.java   
@Test
public void testClonedInstance()
{
    final Organization original = new Organization();
    final List<Group> groups = ImmutableList.of(new Group("slug", "group"));
    final Set<Group> defaultGroups = Sets.newHashSet();
    defaultGroups.add(new Group("slug", "default"));

    original.setAutolinkNewRepos(true);
    original.setCredential(new Credential("oauthKey", "oauthSecret", "accessToken"));
    original.setDefaultGroups(defaultGroups);
    original.setDvcsType("bitbucket");
    original.setHostUrl("hostUrl");
    original.setId(100);
    original.setName("name");
    original.setGroups(groups);
    original.setOrganizationUrl("url");
    original.setSmartcommitsOnNewRepos(true);

    Organization clonedOrg = new Organization(original);

    assertThat(clonedOrg).isNotSameAs(original);
    assertThat(EqualsBuilder.reflectionEquals(clonedOrg, original)).isTrue();

    // assert transient fields missed by EqualsBuilder.reflectionEquals
    assertThat(clonedOrg.getCredential().equals(original.getCredential())).isTrue();
    assertThat(clonedOrg.getDefaultGroups().iterator().next()).isSameAs(original.getDefaultGroups().iterator().next());
    assertThat(clonedOrg.getGroups().iterator().next()).isSameAs(original.getGroups().iterator().next());
    }
项目:osm-lib    文件:NodeTrackerTest.java   
/**
 * Check the NodeTracker against a stock Set<Long>.
 * This is done in ranges that will include numbers significantly greater than 2^32
 */
public void testAgainstSet() {
    final int N = 1000;
    // Set N numbers in each of four different ranges.
    Set<Long> numbers = Sets.newHashSet();
    NodeTracker tracker = new NodeTracker();
    for (long lo : new long[] {1L << 6, 1L << 16, 1L << 34, 1L << 50} ) {
        // Simultaneously set up a basic Set<Long> that will serve as a reference
        // and a NodeTracker that we want to test.
        long hi = 0L;
        for (int i = 0; i < 1000; i++) {
            long n = i * i + lo;
            numbers.add(n);
            tracker.add(n);
            hi = n;
        }
        // Check that the two set implementations match for every value in the range (including unset ones).
        // Note that a Set<Long> containing 0L returns false for contains((int)0).
        for (long i = lo; i < hi; i++) {
            if (tracker.contains(i)) {
                assertTrue(numbers.contains(i));
            } else {
                assertFalse(numbers.contains(i));
            }
            if (numbers.contains(i)) {
                assertTrue(tracker.contains(i));
            } else {
                assertFalse(tracker.contains(i));
            }
        }

        assertEquals(numbers.size(), tracker.cardinality());
    }
}
项目:tempto    文件:TestInitializationListener.java   
private Set<Requirement> resolveAllTestsRequirements(ITestContext context)
{
    // we cannot assume that context contains RequirementsAwareTestNGMethod instances here
    // as interceptor is for some reason called after onStart() which uses this method.
    Set<Requirement> allTestsRequirements = Sets.newHashSet();
    for (ITestNGMethod iTestNGMethod : context.getAllTestMethods()) {
        Set<Set<Requirement>> requirementsSets = new TestSpecificRequirementsResolver(configuration).resolve(iTestNGMethod);
        for (Set<Requirement> requirementsSet : requirementsSets) {
            allTestsRequirements.addAll(requirementsSet);
        }
    }
    return allTestsRequirements;
}
项目:tempto    文件:MapConfiguration.java   
@Override
public Set<String> listKeys()
{
    Set<String> acc = Sets.newHashSet();
    listKeys(map, null, acc);
    return acc;
}
项目:lens    文件:DefaultEstimatedQueryCollectionTest.java   
@Test
public void testGetTotalQueryCostForUserWithZeroLaunchedQueries() throws LensException {

  QueryCollection mockQueries = mock(QueryCollection.class);
  when(mockQueries.getQueries(MOCK_USER)).thenReturn(Sets.<QueryContext>newLinkedHashSet());

  EstimatedQueryCollection queries = new DefaultEstimatedQueryCollection(mockQueries);
  QueryCost actualQueryCost = queries.getTotalQueryCost(MOCK_USER);
  assertEquals(actualQueryCost, new StaticQueryCost(0));
}
项目:lens    文件:TestSavedQueryService.java   
@Test
public void testListQuery() {
  final Set<Long> ids = Sets.newHashSet();
  ids.add(saveQuery().getId());
  ids.add(saveQuery().getId());
  ids.add(saveQuery().getId());
  ids.add(saveQuery().getId());
  final ListResponse list = list(0, 4);
  final List<SavedQuery> queries = list.getResoures();
  assertEquals(ids.size(), queries.size());
}
项目:jolt    文件:JsonUtilsTest.java   
@BeforeClass
@SuppressWarnings("unchecked")
public void setup() throws IOException {
    jsonSource = JsonUtils.jsonToObject(jsonSourceString);
    // added for type cast checking
    Set<String> aSet = Sets.newHashSet();
    aSet.add("i");
    aSet.add("j");
    ((Map) jsonSource).put("s", aSet);
}
项目:checklistbank    文件:NormalizerTest.java   
@Test
public void testNeoIndices() throws Exception {
  final UUID datasetKey = datasetKey(1);

  Normalizer norm = Normalizer.create(cfg, datasetKey);
  norm.run();

  openDb(datasetKey);
  compareStats(norm.getStats());

  Set<String> taxonIndices = Sets.newHashSet();
  taxonIndices.add(NeoProperties.TAXON_ID);
  taxonIndices.add(NeoProperties.SCIENTIFIC_NAME);
  taxonIndices.add(NeoProperties.CANONICAL_NAME);
  try (Transaction tx = beginTx()) {
    Schema schema = dao.getNeo().schema();
    for (IndexDefinition idf : schema.getIndexes(Labels.TAXON)) {
      List<String> idxProps = Iterables.asList(idf.getPropertyKeys());
      assertTrue(idxProps.size() == 1);
      assertTrue(taxonIndices.remove(idxProps.get(0)));
    }

    assertNotNull(Iterators.singleOrNull(dao.getNeo().findNodes(Labels.TAXON, NeoProperties.TAXON_ID, "1001")));
    assertNotNull(Iterators.singleOrNull(dao.getNeo().findNodes(Labels.TAXON, NeoProperties.SCIENTIFIC_NAME, "Crepis bakeri Greene")));
    assertNotNull(Iterators.singleOrNull(dao.getNeo().findNodes(Labels.TAXON, NeoProperties.CANONICAL_NAME, "Crepis bakeri")));

    assertNull(Iterators.singleOrNull(dao.getNeo().findNodes(Labels.TAXON, NeoProperties.TAXON_ID, "x1001")));
    assertNull(Iterators.singleOrNull(dao.getNeo().findNodes(Labels.TAXON, NeoProperties.SCIENTIFIC_NAME, "xCrepis bakeri Greene")));
    assertNull(Iterators.singleOrNull(dao.getNeo().findNodes(Labels.TAXON, NeoProperties.CANONICAL_NAME, "xCrepis bakeri")));
  }
}
项目:amza    文件:AmzaBotServiceTest.java   
@Test
public void testBotBatchSetGet() throws Exception {
    Set<Entry<String, String>> entries = Sets.newHashSet();
    for (long i = 0; i < 10; i++) {
        entries.add(new AbstractMap.SimpleEntry<>("key:" + i, "value:" + i));
    }
    service.multiSet(entries);

    for (long i = 0; i < 10; i++) {
        String v = service.get("key:" + i);

        Assert.assertNotNull(v);
        Assert.assertEquals(v, "value:" + i);
    }
}
项目:gtfs-java    文件:QualifiedModeSetSequence.java   
public QualifiedModeSetSequence(String s) {
    for (String seg : s.split(";")) {
        Set<QualifiedMode> qModeSet = Sets.newHashSet();
        for (String qMode : seg.split(",")) {
            qModeSet.add(new QualifiedMode(qMode));
        }
        if (!qModeSet.isEmpty()) {
            this.sets.add(qModeSet);
        }

    }
}
项目:gtfs-java    文件:TripPattern.java   
public void dumpServices() {
    Set<AgencyAndId> services = Sets.newHashSet();
    for (Trip trip : this.trips) {
        services.add(trip.getServiceId());
    }
    LOG.info("route {} : {}", this.route, services);
}
项目:occurrence    文件:OccurrenceMapReader.java   
/**
 * Extracts the spatial issues from the hbase result.
 */
private static String extractOccurrenceIssues(Result result) {
  Set<String> issues = Sets.newHashSet();
  for (OccurrenceIssue issue : OccurrenceIssue.values()) {
    byte[] val = result.getValue(Columns.CF, Bytes.toBytes(Columns.column(issue)));
    if (val != null) {
      issues.add(issue.name());
    }
  }

  return SEMICOLON_JOINER.join(issues);
}
项目:occurrence    文件:OccurrenceKeyPersistenceServiceMock.java   
@Override
public Set<Integer> findKeysByDataset(String datasetKey) {
  Set<Integer> results = Sets.newHashSet();
  for (Map.Entry<String, Integer> entry : cache.entrySet()) {
    if (entry.getKey().startsWith(datasetKey)) {
      results.add(entry.getValue());
    }
  }

  return results;
}
项目:emodb    文件:DefaultDatabusTest.java   
@Test
public void testLazyPollResult() {
    Supplier<Condition> acceptAll = Suppliers.ofInstance(Conditions.alwaysTrue());
    TestDataProvider testDataProvider = new TestDataProvider();

    final Set<String> expectedIds = Sets.newHashSet();

    DatabusEventStore eventStore = mock(DatabusEventStore.class);
    when(eventStore.poll(eq("subscription"), eq(Duration.standardMinutes(1)), any(EventSink.class)))
            .thenAnswer(invocationOnMock -> {
                EventSink sink = (EventSink) invocationOnMock.getArguments()[2];
                // Return 40 updates for records from 40 unique tables
                for (int iteration = 1; iteration <= 40; iteration++) {
                    String id = "a" + iteration;
                    addToPoll(id, "table-" + iteration, "key-" + iteration, false, sink, testDataProvider);
                    expectedIds.add(id);
                }
                return false;
            });
    SubscriptionDAO subscriptionDAO = mock(SubscriptionDAO.class);
    when(subscriptionDAO.getSubscription("subscription")).thenReturn(
            new DefaultOwnedSubscription("subscription", Conditions.alwaysTrue(), new Date(1489090060000L),
                    Duration.standardSeconds(30), "owner"));

    DatabusAuthorizer databusAuthorizer = ConstantDatabusAuthorizer.ALLOW_ALL;

    // Use a clock that advances 1 second after the first call
    Clock clock = mock(Clock.class);
    when(clock.millis())
            .thenReturn(1489090000000L)
            .thenReturn(1489090001000L);

    DefaultDatabus testDatabus = new DefaultDatabus(
            mock(LifeCycleRegistry.class), mock(EventBus.class), testDataProvider, subscriptionDAO,
            eventStore, mock(SubscriptionEvaluator.class), mock(JobService.class),
            mock(JobHandlerRegistry.class), databusAuthorizer, "systemOwnerId", acceptAll, MoreExecutors.sameThreadExecutor(),
            new MetricRegistry(), clock);

    PollResult pollResult = testDatabus.poll("owner", "subscription", Duration.standardMinutes(1), 500);
    assertFalse(pollResult.hasMoreEvents());

    Iterator<Event> events = pollResult.getEventIterator();
    Set<String> actualIds = Sets.newHashSet();
    // Read the entire event list
    while (events.hasNext()) {
        actualIds.add(events.next().getEventKey());
    }
    assertEquals(actualIds, expectedIds);
    // Events should have been loaded in 3 batches.  The first was a synchronous batch that loaded the first 10 events.
    // The seconds should have loaded 25 more events.  The third loaded the final 5 events;
    List<List<Coordinate>> executions = testDataProvider.getExecutions();
    assertEquals(executions.size(), 3);
    assertEquals(executions.get(0).size(), 10);
    assertEquals(executions.get(1).size(), 25);
    assertEquals(executions.get(2).size(), 5);
}
项目:cerberus-lifecycle-cli    文件:RandomStringGeneratorTest.java   
@Test
public void sanityTestGet() {

    RandomStringGenerator generator = new RandomStringGenerator();

    Set<String> previous = Sets.newHashSet();
    for (int i = 0; i < 1000; i++) {

        String current = generator.get();

        // expecting unique Strings
        assertFalse(previous.contains(current));

        // produces 30 or less characters
        assertTrue("failed on " + current, current.length() <= 30);

        // should never be empty
        assertFalse(current.isEmpty());

        previous.add(current);
    }
}
项目:VarJ    文件:DefaultValueTest.java   
public MyOptsWithEmptyDefaults(){
  this.list = Lists.newArrayList();
  this.set = Sets.newLinkedHashSet();
}
项目:VarJ    文件:DefaultValueTest.java   
public static final Set<String> singletonSet(String value){
  Set<String> set = Sets.newLinkedHashSet();
  set.add(value);
  return set;
}
项目:artifactory    文件:BinaryStoreImplBaseTest.java   
@Test
public void testEmpty() throws IOException {
    // Check initialized with folders correctly
    File filestoreDir = getFilestoreFolder(ArtifactoryHome.get());
    assertEquals(binaryStore.getBinariesDir().getAbsolutePath(), filestoreDir.getAbsolutePath());
    File[] files = filestoreDir.listFiles();
    assertNotNull(files);
    assertEquals(files.length, 1);
    File preFolder = files[0];
    assertTrue(preFolder.isDirectory(), "File " + preFolder.getAbsolutePath() + " should be a folder");
    assertEquals(preFolder.getName(), "_pre");

    // Ping all OK => Ping throws exception if something wrong
    binaryStore.ping();

    // Check all is empty
    assertTrue(binaryStore.findAllBinaries().isEmpty());
    assertEquals(binaryStore.getStorageSize(), 0L);

    // Finder should returns null and empty collections
    Set<String> allChecksums = Sets.newHashSet();
    Object[][] binFileData = getBinFileData();
    for (Object[] binFile : binFileData) {
        String sha1 = (String) binFile[1];
        Assert.assertNull(binaryStore.findBinary(sha1));
        allChecksums.add(sha1);
        allChecksums.add((String) binFile[2]);
    }
    assertTrue(binaryStore.findBinaries(allChecksums).isEmpty());

    // Garbage collection should do nothing
    GarbageCollectorInfo collectorInfo = binaryStore.garbageCollect();
    assertEquals(collectorInfo.initialSize, 0L);
    assertEquals(collectorInfo.initialCount, 0);
    assertEquals(collectorInfo.candidatesForDeletion, 0);
    assertEquals(collectorInfo.binariesCleaned, 0);
    assertEquals(collectorInfo.checksumsCleaned, 0);
    assertEquals(collectorInfo.totalSizeCleaned, 0L);

    testPrune(0, 0, 0);

    for (Object[] binData : binFileData) {
        checkSha1OnEmpty((String) binData[1]);
    }
}
项目:lens    文件:MockDriver.java   
@Override
public ImmutableSet<QueryLaunchingConstraint> getQueryConstraints() {
  return ImmutableSet.copyOf(Sets.<QueryLaunchingConstraint>newHashSet());
}
项目:lens    文件:MockDriver.java   
@Override
public ImmutableSet<WaitingQueriesSelectionPolicy> getWaitingQuerySelectionPolicies() {
  return ImmutableSet.copyOf(Sets.<WaitingQueriesSelectionPolicy>newHashSet());
}
项目:checklistbank    文件:NormalizerTest.java   
/**
 * Pro parte synonyms get exploded into several usages/nodes that each have just one accepted taxon!
 */
@Test
public void testProParteSynonyms() throws Exception {
  NormalizerStats stats = normalize(8);
  try (Transaction tx = beginTx()) {
    assertEquals(1, stats.getRoots());
    assertEquals(17, stats.getCount());
    assertEquals(6, stats.getSynonyms());
    assertEquals(17, stats.getCountByOrigin(Origin.SOURCE));
    assertEquals(2, stats.getCountByRank(Rank.GENUS));
    assertEquals(7, stats.getCountByRank(Rank.SPECIES));
    assertEquals(5, stats.getCountByRank(Rank.SUBSPECIES));

    // genus synonym
    NameUsage nu = getUsageByTaxonId("101");
    assertEquals("Cladendula Döring", nu.getScientificName());
    assertEquals(Rank.GENUS, nu.getRank());
    assertEquals(TaxonomicStatus.SYNONYM, nu.getTaxonomicStatus());
    assertTrue(nu.isSynonym());

    NameUsage acc = getUsageByKey(nu.getAcceptedKey());
    assertEquals("Calendula L.", acc.getScientificName());
    assertEquals(Rank.GENUS, acc.getRank());
    assertEquals(TaxonomicStatus.ACCEPTED, acc.getTaxonomicStatus());
    assertFalse(acc.isSynonym());

    // pro parte synonym
    Set<Integer> accIds = Sets.newHashSet();
    List<NameUsage> pps = getUsagesByName("Calendula eckerleinii Ohle");
    assertEquals(1, pps.size());
    for (NameUsage u : pps) {
      assertEquals("Calendula eckerleinii Ohle", u.getScientificName());
      assertEquals(Rank.SPECIES, u.getRank());
      assertEquals(TaxonomicStatus.PROPARTE_SYNONYM, u.getTaxonomicStatus());
      assertTrue(u.isSynonym());
      assertFalse(accIds.contains(u.getAcceptedKey()));
      accIds.add(u.getAcceptedKey());
    }

    for (Integer aid : accIds) {
      acc = getUsageByKey(aid);
      assertFalse(acc.isSynonym());
      assertEquals(TaxonomicStatus.ACCEPTED, acc.getTaxonomicStatus());
      if (acc.getTaxonID().equals("1000")) {
        assertEquals("Calendula arvensis (Vaill.) L.", acc.getScientificName());
        assertEquals(Rank.SPECIES, acc.getRank());
      } else if (acc.getTaxonID().equals("10000")) {
        assertEquals("Calendula incana Willd. subsp. incana", acc.getScientificName());
        assertEquals(Rank.SUBSPECIES, acc.getRank());
      } else if (acc.getTaxonID().equals("10002")) {
        assertEquals("Calendula incana subsp. maderensis (DC.) Ohle", acc.getScientificName());
        assertEquals(Rank.SUBSPECIES, acc.getRank());
      } else {
        fail("Unknown pro parte synonym");
      }
    }
  }
}