method2testcases
stringlengths 118
6.63k
|
---|
### Question:
ConceptsBySearch extends ConceptAction { @Override Concepts get() throws ObservationController.LoadObservationException { return controller.searchObservationsGroupedByConcepts(term, patientUuid); } ConceptsBySearch(ConceptController conceptController, ObservationController controller, String patientUuid, String term); @Override String toString(); }### Answer:
@Test public void shouldSearchObservationsByUuidAndTerm() throws ObservationController.LoadObservationException { ObservationController controller = mock(ObservationController.class); ConceptController conceptController = mock(ConceptController.class); ConceptsBySearch conceptsBySearch = new ConceptsBySearch(conceptController,controller, "uuid", "term"); conceptsBySearch.get(); verify(controller).searchObservationsGroupedByConcepts("term", "uuid"); } |
### Question:
EntityUtils { @SuppressWarnings({ "unchecked", "rawtypes" }) public static Class<? extends Serializable> primaryKeyClass(Class<?> entityClass) { if (entityClass.isAnnotationPresent(IdClass.class)) { return entityClass.getAnnotation(IdClass.class).value(); } Class clazz = PersistenceUnitDescriptorProvider.getInstance().primaryKeyIdClass(entityClass); if (clazz != null) { return clazz; } Property<Serializable> property = primaryKeyProperty(entityClass); return property.getJavaClass(); } private EntityUtils(); @SuppressWarnings({ "unchecked", "rawtypes" }) static Class<? extends Serializable> primaryKeyClass(Class<?> entityClass); static Object primaryKeyValue(Object entity); static Object primaryKeyValue(Object entity, Property<Serializable> primaryKeyProperty); static String entityName(Class<?> entityClass); static String tableName(Class<?> entityClass, EntityManager entityManager); static boolean isEntityClass(Class<?> entityClass); static Property<Serializable> primaryKeyProperty(Class<?> entityClass); static Property<Serializable> getVersionProperty(Class<?> entityClass); }### Answer:
@Test public void should_find_id_property_class() { Class<? extends Serializable> pkClass = EntityUtils.primaryKeyClass(Tee.class); Assert.assertEquals(TeeId.class, pkClass); }
@Test public void should_find_id_class() { Class<? extends Serializable> pkClass = EntityUtils.primaryKeyClass(Tee2.class); Assert.assertEquals(TeeId.class, pkClass); } |
### Question:
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override public E findBy(PK primaryKey) { Query query = context.getMethod().getAnnotation(Query.class); if (query != null && query.hints().length > 0) { Map<String, Object> hints = new HashMap<String, Object>(); for (QueryHint hint : query.hints()) { hints.put(hint.name(), hint.value()); } return entityManager().find(entityClass(), primaryKey, hints); } else { return entityManager().find(entityClass(), primaryKey); } } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }### Answer:
@Test public void should_find_by_pk() throws Exception { Simple simple = testData.createSimple("testFindByPk"); Simple find = repo.findBy(simple.getId()); assertEquals(simple.getName(), find.getName()); }
@Test @SuppressWarnings("unchecked") public void should_find_by_example() throws Exception { Simple simple = testData.createSimple("testFindByExample"); List<Simple> find = repo.findBy(simple, Simple_.name); assertNotNull(find); assertFalse(find.isEmpty()); assertEquals(simple.getName(), find.get(0).getName()); }
@Test @SuppressWarnings("unchecked") public void should_find_by_example_with_start_and_max() throws Exception { Simple simple = testData.createSimple("testFindByExample1", Integer.valueOf(10)); testData.createSimple("testFindByExample1", Integer.valueOf(10)); List<Simple> find = repo.findBy(simple, 0, 1, Simple_.name, Simple_.counter); assertNotNull(find); assertFalse(find.isEmpty()); assertEquals(1, find.size()); assertEquals(simple.getName(), find.get(0).getName()); }
@Test @SuppressWarnings("unchecked") public void should_find_by_example_with_no_attributes() throws Exception { Simple simple = testData.createSimple("testFindByExample"); SingularAttribute<Simple, ?>[] attributes = new SingularAttribute[] {}; List<Simple> find = repo.findBy(simple, attributes); assertNotNull(find); assertFalse(find.isEmpty()); assertEquals(simple.getName(), find.get(0).getName()); } |
### Question:
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override public Optional<E> findOptionalBy(PK primaryKey) { E found = null; try { found = findBy(primaryKey); } catch (Exception e) { } return Optional.ofNullable(found); } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }### Answer:
@Test public void should_find__by_pk() throws Exception { Simple simple = testData.createSimple("testFindByPk"); Optional<Simple> find = repo.findOptionalBy(simple.getId()); assertEquals(simple.getName(), find.get().getName()); } |
### Question:
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @SuppressWarnings("unchecked") @Override public List<E> findAll() { return context.applyRestrictions(entityManager().createQuery(allQuery(), entityClass())).getResultList(); } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }### Answer:
@Test public void should_find_all() { testData.createSimple("testFindAll1"); testData.createSimple("testFindAll2"); List<Simple> find = repo.findAll(); assertEquals(2, find.size()); }
@Test public void should_find_by_all_with_start_and_max() { testData.createSimple("testFindAll1"); testData.createSimple("testFindAll2"); List<Simple> find = repo.findAll(0, 1); assertEquals(1, find.size()); } |
### Question:
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override public List<E> findByLike(E example, SingularAttribute<E, ?>... attributes) { return findByLike(example, -1, -1, attributes); } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }### Answer:
@Test @SuppressWarnings({ "unchecked" }) public void should_find_by_like() { testData.createSimple("testFindAll1"); testData.createSimple("testFindAll2"); Simple example = new Simple("test"); List<Simple> find = repo.findByLike(example, Simple_.name); assertEquals(2, find.size()); }
@Test @SuppressWarnings("unchecked") public void should_find_by_like_with_start_and_max() { testData.createSimple("testFindAll1"); testData.createSimple("testFindAll2"); Simple example = new Simple("test"); List<Simple> find = repo.findByLike(example, 1, 10, Simple_.name); assertEquals(1, find.size()); }
@Test @SuppressWarnings("unchecked") public void should_find_by_like_non_string() { testData.createSimple("testFindAll1", 1); testData.createSimple("testFindAll2", 2); Simple example = new Simple("test"); example.setCounter(1); List<Simple> find = repo.findByLike(example, Simple_.name, Simple_.counter); assertEquals(1, find.size()); } |
### Question:
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override public Long count() { return (Long) context.applyRestrictions(entityManager().createQuery(countQuery(), Long.class)) .getSingleResult(); } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }### Answer:
@Test public void should_count_all() { testData.createSimple("testCountAll"); Long result = repo.count(); assertEquals(Long.valueOf(1), result); }
@Test @SuppressWarnings("unchecked") public void should_count_with_attributes() { Simple simple = testData.createSimple("testFindAll1", Integer.valueOf(55)); testData.createSimple("testFindAll2", Integer.valueOf(55)); Long result = repo.count(simple, Simple_.name, Simple_.counter); assertEquals(Long.valueOf(1), result); }
@Test @SuppressWarnings("unchecked") public void should_count_with_no_attributes() { Simple simple = testData.createSimple("testFindAll1"); testData.createSimple("testFindAll2"); SingularAttribute<Simple, Object>[] attributes = new SingularAttribute[] {}; Long result = repo.count(simple, attributes); assertEquals(Long.valueOf(2), result); } |
### Question:
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override public Long countLike(E example, SingularAttribute<E, ?>... attributes) { return executeCountQuery(example, true, attributes); } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }### Answer:
@Test @SuppressWarnings("unchecked") public void should_count_by_like() { testData.createSimple("testFindAll1"); testData.createSimple("testFindAll2"); Simple example = new Simple("test"); Long count = repo.countLike(example, Simple_.name); assertEquals(Long.valueOf(2), count); } |
### Question:
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override @RequiresTransaction public void removeAndFlush(E entity) { entityManager().remove(entity); flush(); } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }### Answer:
@Test public void should_remove_and_flush() { Simple simple = testData.createSimple("testRemoveAndFlush"); repo.removeAndFlush(simple); Simple lookup = getEntityManager().find(Simple.class, simple.getId()); assertNull(lookup); } |
### Question:
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @SuppressWarnings("unchecked") @Override public PK getPrimaryKey(E entity) { return (PK) persistenceUnitUtil().getIdentifier(entity); } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }### Answer:
@Test public void should_return_entity_primary_key() { Simple simple = testData.createSimple("should_return_entity_primary_key"); Long id = simple.getId(); Long primaryKey = repo.getPrimaryKey(simple); assertNotNull(primaryKey); assertEquals(id, primaryKey); }
@Test public void should_return_null_primary_key() { Simple simple = new Simple("should_return_null_primary_key"); Long primaryKey = repo.getPrimaryKey(simple); assertNull(primaryKey); }
@Test public void should_return_entity_primary_key_detached_entity() { Simple simple = testData.createSimple("should_return_entity_primary_key"); Long id = simple.getId(); getEntityManager().detach(simple); Long primaryKey = repo.getPrimaryKey(simple); assertNotNull(primaryKey); assertEquals(id, primaryKey); } |
### Question:
AuditEntityListener { @PrePersist public void persist(Object entity) { BeanManager beanManager = BeanManagerProvider.getInstance().getBeanManager(); Set<Bean<?>> beans = beanManager.getBeans(PrePersistAuditListener.class); for (Bean<?> bean : beans) { PrePersistAuditListener result = (PrePersistAuditListener) beanManager.getReference( bean, PrePersistAuditListener.class, beanManager.createCreationalContext(bean)); result.prePersist(entity); } } @PrePersist void persist(Object entity); @PreUpdate void update(Object entity); }### Answer:
@Test public void should_set_creation_date() throws Exception { AuditedEntity entity = new AuditedEntity(); getEntityManager().persist(entity); getEntityManager().flush(); assertNotNull(entity.getCreated()); assertNotNull(entity.getModified()); assertEquals(entity.getCreated().getTime(), entity.getModified()); }
@Test public void should_set_modification_date() throws Exception { AuditedEntity entity = new AuditedEntity(); getEntityManager().persist(entity); getEntityManager().flush(); entity = getEntityManager().find(AuditedEntity.class, entity.getId()); entity.setName("test"); getEntityManager().flush(); assertNotNull(entity.getGregorianModified()); assertNotNull(entity.getTimestamp()); }
@Test public void should_set_changing_principal() { AuditedEntity entity = new AuditedEntity(); getEntityManager().persist(entity); getEntityManager().flush(); entity = getEntityManager().find(AuditedEntity.class, entity.getId()); entity.setName("test"); getEntityManager().flush(); assertNotNull(entity.getChanger()); assertEquals(who, entity.getChanger()); assertNotNull(entity.getPrincipal()); assertEquals(who, entity.getPrincipal().getName()); assertNotNull(entity.getChangerOnly()); assertEquals(who, entity.getChangerOnly()); assertNotNull(entity.getChangerOnlyPrincipal()); assertEquals(who, entity.getChangerOnlyPrincipal().getName()); }
@Test public void should_set_creating_principal() { AuditedEntity entity = new AuditedEntity(); getEntityManager().persist(entity); getEntityManager().flush(); assertNotNull(entity.getCreator()); assertEquals(who, entity.getCreator()); assertNotNull(entity.getCreatorPrincipal()); assertEquals(who, entity.getCreatorPrincipal().getName()); assertNotNull(entity.getChanger()); assertEquals(who, entity.getChanger()); assertNotNull(entity.getPrincipal()); assertEquals(who, entity.getPrincipal().getName()); assertNull(entity.getChangerOnly()); assertNull(entity.getChangerOnlyPrincipal()); } |
### Question:
EntityUtils { public static boolean isEntityClass(Class<?> entityClass) { return entityClass.isAnnotationPresent(Entity.class) || PersistenceUnitDescriptorProvider.getInstance().isEntity(entityClass); } private EntityUtils(); @SuppressWarnings({ "unchecked", "rawtypes" }) static Class<? extends Serializable> primaryKeyClass(Class<?> entityClass); static Object primaryKeyValue(Object entity); static Object primaryKeyValue(Object entity, Property<Serializable> primaryKeyProperty); static String entityName(Class<?> entityClass); static String tableName(Class<?> entityClass, EntityManager entityManager); static boolean isEntityClass(Class<?> entityClass); static Property<Serializable> primaryKeyProperty(Class<?> entityClass); static Property<Serializable> getVersionProperty(Class<?> entityClass); }### Answer:
@Test public void should_accept_entity_class() { boolean isValid = EntityUtils.isEntityClass(Simple.class); Assert.assertTrue(isValid); }
@Test public void should_not_accept_class_without_entity_annotation() { boolean isValid = EntityUtils.isEntityClass(EntityWithoutId.class); Assert.assertFalse(isValid); } |
### Question:
PrincipalProvider extends AuditProvider { @Override public void prePersist(Object entity) { updatePrincipal(entity, true); } @Override void prePersist(Object entity); @Override void preUpdate(Object entity); }### Answer:
@Test public void should_set_users_for_creation() { String creator = "creator"; MockPrincipalProvider provider = new MockPrincipalProvider(creator); AuditedEntity entity = new AuditedEntity(); provider.prePersist(entity); assertNotNull(entity.getCreator()); assertNotNull(entity.getCreatorPrincipal()); assertNotNull(entity.getChanger()); assertEquals(entity.getCreator(), creator); assertEquals(entity.getCreatorPrincipal().getName(), creator); assertEquals(entity.getChanger(), creator); assertNull(entity.getChangerOnly()); assertNull(entity.getChangerOnlyPrincipal()); }
@Test(expected = AuditPropertyException.class) public void should_fail_on_invalid_entity() { PrincipalProviderTest.InvalidEntity entity = new PrincipalProviderTest.InvalidEntity(); new MockPrincipalProvider("").prePersist(entity); fail(); } |
### Question:
PrincipalProvider extends AuditProvider { @Override public void preUpdate(Object entity) { updatePrincipal(entity, false); } @Override void prePersist(Object entity); @Override void preUpdate(Object entity); }### Answer:
@Test public void should_set_users_for_update() { String changer = "changer"; MockPrincipalProvider provider = new MockPrincipalProvider(changer); AuditedEntity entity = new AuditedEntity(); provider.preUpdate(entity); assertNotNull(entity.getChanger()); assertNotNull(entity.getChangerOnly()); assertNotNull(entity.getChangerOnlyPrincipal()); assertEquals(entity.getChanger(), changer); assertEquals(entity.getChangerOnly(), changer); assertEquals(entity.getChangerOnlyPrincipal().getName(), changer); assertNull(entity.getCreator()); assertNull(entity.getCreatorPrincipal()); } |
### Question:
TimestampsProvider extends AuditProvider { @Override public void prePersist(Object entity) { updateTimestamps(entity, true); } @Override void prePersist(Object entity); @Override void preUpdate(Object entity); }### Answer:
@Test public void should_set_dates_for_creation() { AuditedEntity entity = new AuditedEntity(); new TimestampsProvider().prePersist(entity); assertNotNull(entity.getCreated()); assertNotNull(entity.getModified()); assertNull(entity.getGregorianModified()); assertNull(entity.getTimestamp()); }
@Test(expected = AuditPropertyException.class) public void should_fail_on_invalid_entity() { InvalidEntity entity = new InvalidEntity(); new TimestampsProvider().prePersist(entity); fail(); } |
### Question:
TimestampsProvider extends AuditProvider { @Override public void preUpdate(Object entity) { updateTimestamps(entity, false); } @Override void prePersist(Object entity); @Override void preUpdate(Object entity); }### Answer:
@Test public void should_set_dates_for_update() { AuditedEntity entity = new AuditedEntity(); new TimestampsProvider().preUpdate(entity); assertNull(entity.getCreated()); assertNotNull(entity.getModified()); assertNotNull(entity.getGregorianModified()); assertNotNull(entity.getTimestamp()); } |
### Question:
QueryRoot extends QueryPart { public static QueryRoot create(String method, RepositoryMetadata repo, RepositoryMethodPrefix prefix) { QueryRoot root = new QueryRoot(repo.getEntityMetadata().getEntityName(), prefix); root.build(method, method, repo); root.createJpql(); return root; } protected QueryRoot(String entityName, RepositoryMethodPrefix methodPrefix); static QueryRoot create(String method, RepositoryMetadata repo, RepositoryMethodPrefix prefix); String getJpqlQuery(); List<ParameterUpdate> getParameterUpdates(); static final QueryRoot UNKNOWN_ROOT; }### Answer:
@Test(expected = MethodExpressionException.class) public void should_fail_in_where() { final String name = "findByInvalid"; QueryRoot.create(name, repo, prefix(name)); }
@Test(expected = MethodExpressionException.class) public void should_fail_with_prefix_only() { final String name = "findBy"; QueryRoot.create(name, repo, prefix(name)); }
@Test(expected = MethodExpressionException.class) public void should_fail_in_order_by() { final String name = "findByNameOrderByInvalidDesc"; QueryRoot.create(name, repo, prefix(name)); } |
### Question:
ClassUtils { public static Method extractPossiblyGenericMethod(Class<?> clazz, Method sourceMethod) { Method exactMethod = extractMethod(clazz, sourceMethod); if (exactMethod == null) { String methodName = sourceMethod.getName(); Class<?>[] parameterTypes = sourceMethod.getParameterTypes(); for (Method method : clazz.getMethods()) { if (method.getName().equals(methodName) && allSameType(method.getParameterTypes(), parameterTypes)) { return method; } } return null; } else { return exactMethod; } } private ClassUtils(); static ClassLoader getClassLoader(Object o); static boolean isProxyableClass(Type type); static Class<T> tryToLoadClassForName(String name, Class<T> targetType); static Class<T> tryToLoadClassForName(String name, Class<T> targetType, ClassLoader classLoader); static Class tryToLoadClassForName(String name); static Class tryToLoadClassForName(String name, ClassLoader classLoader); static Class loadClassForName(String name); static T tryToInstantiateClass(Class<T> targetClass); static T tryToInstantiateClassForName(String className, Class<T> targetType); static Object tryToInstantiateClassForName(String className); static Object instantiateClassForName(String className); static String getJarVersion(Class targetClass); static String getRevision(Class targetClass); static boolean containsMethod(Class<?> targetClass, Method method); static Method extractMethod(Class<?> clazz, Method sourceMethod); static boolean containsPossiblyGenericMethod(Class<?> targetClass, Method method); static Method extractPossiblyGenericMethod(Class<?> clazz, Method sourceMethod); static boolean returns(Method method, Class<?> clazz); }### Answer:
@Test public void shouldNotRetrieveMethodBasedOnSameReturnType() throws Exception { Method m = InnerTwo.class.getMethod("getCollection"); Method method = ClassUtils.extractPossiblyGenericMethod(InnerOne.class, m); Assert.assertEquals(InnerOne.class.getMethod("getCollection"), method); }
@Test public void shouldRetrieveMethodBasedOnCastableType() throws Exception { Method m = InnerThree.class.getMethod("getCollection"); Method method = ClassUtils.extractPossiblyGenericMethod(InnerOne.class, m); Assert.assertEquals(InnerOne.class.getMethod("getCollection"), method); } |
### Question:
QueryStringExtractorFactory { public String extract(final Query query) { for (final QueryStringExtractor extractor : extractors) { final String compare = extractor.getClass().getAnnotation(ProviderSpecific.class).value(); final Object implQuery = toImplQuery(compare, query); if (implQuery != null) { return extractor.extractFrom(implQuery); } } throw new RuntimeException("Persistence provider not supported"); } String extract(final Query query); }### Answer:
@Test public void should_unwrap_query_even_proxied() { String extracted = factory.extract((Query) newProxyInstance(currentThread().getContextClassLoader(), new Class[] { Query.class }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("toString")) { return "Unknown provider wrapper for tests."; } if (method.getName().equals("unwrap")) { Class<?> clazz = (Class<?>) args[0]; if (clazz.getName().contains("hibernate") || clazz.getName().contains("openjpa") || clazz.getName().contains("eclipse")) { return createProxy(clazz); } else { throw new PersistenceException("Unable to unwrap for " + clazz); } } return null; } }) ); assertEquals(QUERY_STRING, extracted); } |
### Question:
ParameterUtil { public static String getName(Method method, int parameterIndex) { if (!isParameterSupported() || method == null) { return null; } try { Object[] parameters = (Object[]) getParametersMethod.invoke(method); return (String) getNameMethod.invoke(parameters[parameterIndex]); } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } return null; } static boolean isParameterSupported(); static String getName(Method method, int parameterIndex); }### Answer:
@Test public void shouldReturnNameOrNull() throws Exception { Method method = getClass().getDeclaredMethod("someMethod", String.class); String parameterName = ParameterUtil.getName(method, 0); Assert.assertTrue(parameterName.equals("arg0") || parameterName.equals("firstParameter")); } |
### Question:
PropertyFileUtils { public static Enumeration<URL> resolvePropertyFiles(String propertyFileName) throws IOException { if (propertyFileName != null && (propertyFileName.contains(": { Vector<URL> propertyFileUrls = new Vector<URL>(); URL url = new URL(propertyFileName); if (propertyFileName.startsWith("file:")) { try { File file = new File(url.toURI()); if (file.exists()) { propertyFileUrls.add(url); } } catch (URISyntaxException e) { throw new IllegalStateException("Property file URL is malformed", e); } } else { propertyFileUrls.add(url); } return propertyFileUrls.elements(); } if (propertyFileName != null) { File file = new File(propertyFileName); if (file.exists()) { return Collections.enumeration(Collections.singleton(file.toURI().toURL())); } } ClassLoader cl = ClassUtils.getClassLoader(null); Enumeration<URL> propertyFileUrls = cl.getResources(propertyFileName); if (!propertyFileUrls.hasMoreElements()) { cl = PropertyFileUtils.class.getClassLoader(); propertyFileUrls = cl.getResources(propertyFileName); } return propertyFileUrls; } private PropertyFileUtils(); static Enumeration<URL> resolvePropertyFiles(String propertyFileName); static Properties loadProperties(URL url); static ResourceBundle getResourceBundle(String bundleName); static ResourceBundle getResourceBundle(String bundleName, Locale locale); }### Answer:
@Test public void run() throws IOException, URISyntaxException { test.result = PropertyFileUtils.resolvePropertyFiles(test.file); test.run(); } |
### Question:
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override @RequiresTransaction public E save(E entity) { if (context.isNew(entity)) { entityManager().persist(entity); return entity; } return entityManager().merge(entity); } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }### Answer:
@Test public void should_save() throws Exception { Simple simple = new Simple("test"); simple = repo.save(simple); assertNotNull(simple.getId()); }
@Test public void should_merge() throws Exception { Simple simple = testData.createSimple("testMerge"); Long id = simple.getId(); final String newName = "testMergeUpdated"; simple.setName(newName); simple = repo.save(simple); assertEquals(id, simple.getId()); assertEquals(newName, simple.getName()); }
@Test public void should_save_with_string_id() { SimpleStringId foo = new SimpleStringId("foo", "bar"); foo = stringIdRepo.save(foo); assertNotNull(foo); } |
### Question:
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override @RequiresTransaction public E saveAndFlush(E entity) { E result = save(entity); flush(); return result; } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }### Answer:
@Test public void should_save_and_flush() throws Exception { Simple simple = new Simple("test"); simple = repo.saveAndFlush(simple); Simple fetch = (Simple) getEntityManager() .createNativeQuery("select * from SIMPLE_TABLE where id = ?", Simple.class) .setParameter(1, simple.getId()) .getSingleResult(); assertEquals(simple.getId(), fetch.getId()); } |
### Question:
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override @RequiresTransaction public void refresh(E entity) { entityManager().refresh(entity); } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }### Answer:
@Test public void should_refresh() throws Exception { final String name = "testRefresh"; Simple simple = testData.createSimple(name); simple.setName("override"); repo.refresh(simple); assertEquals(name, simple.getName()); } |
### Question:
PluginRegisterService { public CompletableFuture<Response> register(Long userId, PluginReqisterQuery pluginReqisterQuery, PluginUpdate pluginUpdate, String authorization) { validateSubscription(pluginReqisterQuery); checkAuthServiceAvailable(); return persistPlugin(pluginUpdate, pluginReqisterQuery.constructFilterString(), userId).thenApply(pluginVO -> { JwtTokenVO jwtTokenVO = createPluginTokens(pluginVO.getTopicName(), authorization); JsonObject response = createTokenResponse(pluginVO.getTopicName(), jwtTokenVO); return ResponseFactory.response(CREATED, response, PLUGIN_SUBMITTED); }); } @Autowired PluginRegisterService(
HiveValidator hiveValidator,
PluginService pluginService,
FilterService filterService, RpcClient rpcClient,
KafkaTopicService kafkaTopicService,
LongIdGenerator idGenerator,
HttpRestHelper httpRestHelper,
WebSocketKafkaProxyConfig webSocketKafkaProxyConfig,
Gson gson); CompletableFuture<Response> register(Long userId, PluginReqisterQuery pluginReqisterQuery, PluginUpdate pluginUpdate,
String authorization); @Transactional CompletableFuture<Response> update(PluginVO existingPlugin, PluginUpdateQuery pluginUpdateQuery); @Transactional CompletableFuture<Response> delete(PluginVO existingPlugin); CompletableFuture<List<PluginVO>> list(String name, String namePattern, String topicName, Integer status, Long userId,
String sortField, String sortOrderSt, Integer take, Integer skip,
HivePrincipal principal); CompletableFuture<List<PluginVO>> list(ListPluginRequest listPluginRequest); CompletableFuture<EntityCountResponse> count(String name, String namePattern, String topicName,
Integer status, Long userId, HivePrincipal principal); CompletableFuture<EntityCountResponse> count(CountPluginRequest countPluginRequest); }### Answer:
@Test public void shouldRegisterPlugin() throws Exception { PluginReqisterQuery pluginReqisterQuery = new PluginReqisterQuery(); pluginReqisterQuery.setReturnCommands(true); pluginReqisterQuery.setReturnUpdatedCommands(true); pluginReqisterQuery.setReturnNotifications(true); PluginUpdate pluginUpdate = new PluginUpdate(); given(webSocketKafkaProxyConfig.getProxyPluginConnect()).willReturn(PROXY_PLUGIN_ENDPOINT); given(httpRestHelper.post(any(), any(), any(), any())).willReturn(createJwtTokenVO(ACCESS_TOKEN, REFRESH_TOKEN)); doAnswer(invocation -> { Object[] args = invocation.getArguments(); Request request = (Request)args[0]; ResponseConsumer responseConsumer = (ResponseConsumer)args[1]; responseConsumer.accept(Response.newBuilder() .withBody(request.getBody()) .buildSuccess()); return null; }).when(rpcClient).call(any(), any()); JsonObject actual = (JsonObject) pluginRegisterService.register(1L, pluginReqisterQuery, pluginUpdate, AUTHORIZATION).join().getEntity(); assertEquals(actual.get(ACCESS_TOKEN).getAsString(), ACCESS_TOKEN); assertEquals(actual.get(REFRESH_TOKEN).getAsString(), REFRESH_TOKEN); assertEquals(actual.get(PROXY_PLUGIN_ENDPOINT).getAsString(), PROXY_PLUGIN_ENDPOINT); verify(rpcClient, times(0)).call(any(), any()); } |
### Question:
FormController implements FxmlController { protected List<FormFieldController> findInvalidFields() { return subscribedFields.values().stream().filter(not(FormFieldController::isValid)).collect(Collectors.toList()); } void subscribeToField(FormFieldController formField); void unsubscribeToField(FormFieldController formField); T getField(String formFieldName); abstract void submit(); }### Answer:
@Test public void findingInvalidFieldsReturnsInvalidOnes() { assertThat(formController.findInvalidFields()).containsExactly(INVALID_FIELD); } |
### Question:
Stages { public static CompletionStage<Stage> stageOf(final String title, final Pane rootPane) { return FxAsync.computeOnFxThread( Tuple.of(title, rootPane), titleAndPane -> { final Stage stage = new Stage(StageStyle.DECORATED); stage.setTitle(title); stage.setScene(new Scene(rootPane)); return stage; } ); } private Stages(); static CompletionStage<Stage> stageOf(final String title, final Pane rootPane); static CompletionStage<Stage> scheduleDisplaying(final Stage stage); static CompletionStage<Stage> scheduleDisplaying(final CompletionStage<Stage> stageCreationResult); static CompletionStage<Stage> scheduleHiding(final Stage stage); static CompletionStage<Stage> scheduleHiding(final CompletionStage<Stage> stageCreationResult); static CompletionStage<Stage> setStylesheet(final Stage stage, final String stylesheet); static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final String stylesheet); static CompletionStage<Stage> setStylesheet(final Stage stage, final FxmlStylesheet stylesheet); static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final FxmlStylesheet stylesheet); }### Answer:
@Test public void stageOf() throws ExecutionException, InterruptedException { final Pane newPane = new Pane(); Stages.stageOf(stageTitle, newPane) .thenAccept(stage -> { assertThat(stage.getScene().getRoot()).isEqualTo(newPane); assertThat(stage.getTitle()).isEqualTo(stageTitle); }) .toCompletableFuture().get(); } |
### Question:
Stages { public static CompletionStage<Stage> scheduleDisplaying(final Stage stage) { LOG.debug( "Requested displaying of stage {} with title : \"{}\"", stage, stage.getTitle() ); return FxAsync.doOnFxThread( stage, Stage::show ); } private Stages(); static CompletionStage<Stage> stageOf(final String title, final Pane rootPane); static CompletionStage<Stage> scheduleDisplaying(final Stage stage); static CompletionStage<Stage> scheduleDisplaying(final CompletionStage<Stage> stageCreationResult); static CompletionStage<Stage> scheduleHiding(final Stage stage); static CompletionStage<Stage> scheduleHiding(final CompletionStage<Stage> stageCreationResult); static CompletionStage<Stage> setStylesheet(final Stage stage, final String stylesheet); static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final String stylesheet); static CompletionStage<Stage> setStylesheet(final Stage stage, final FxmlStylesheet stylesheet); static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final FxmlStylesheet stylesheet); }### Answer:
@Test public void scheduleDisplaying() throws ExecutionException, InterruptedException { Stages.scheduleDisplaying(testStage) .thenAccept(stage -> assertThat(testStage.isShowing()).isTrue()) .toCompletableFuture().get(); } |
### Question:
Stages { public static CompletionStage<Stage> scheduleHiding(final Stage stage) { LOG.debug( "Requested hiding of stage {} with title : \"{}\"", stage, stage.getTitle() ); return FxAsync.doOnFxThread( stage, Stage::hide ); } private Stages(); static CompletionStage<Stage> stageOf(final String title, final Pane rootPane); static CompletionStage<Stage> scheduleDisplaying(final Stage stage); static CompletionStage<Stage> scheduleDisplaying(final CompletionStage<Stage> stageCreationResult); static CompletionStage<Stage> scheduleHiding(final Stage stage); static CompletionStage<Stage> scheduleHiding(final CompletionStage<Stage> stageCreationResult); static CompletionStage<Stage> setStylesheet(final Stage stage, final String stylesheet); static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final String stylesheet); static CompletionStage<Stage> setStylesheet(final Stage stage, final FxmlStylesheet stylesheet); static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final FxmlStylesheet stylesheet); }### Answer:
@Test public void scheduleHiding() throws ExecutionException, InterruptedException { Stages.scheduleHiding(testStage) .thenAccept(stage -> assertThat(testStage.isShowing()).isFalse()) .toCompletableFuture().get(); } |
### Question:
Stages { public static CompletionStage<Stage> setStylesheet(final Stage stage, final String stylesheet) { LOG.info( "Setting stylesheet {} for stage {}({})", stylesheet, stage.toString(), stage.getTitle() ); return FxAsync.doOnFxThread( stage, theStage -> { final Scene stageScene = theStage.getScene(); stageScene.getStylesheets().clear(); stageScene.getStylesheets().add(stylesheet); } ); } private Stages(); static CompletionStage<Stage> stageOf(final String title, final Pane rootPane); static CompletionStage<Stage> scheduleDisplaying(final Stage stage); static CompletionStage<Stage> scheduleDisplaying(final CompletionStage<Stage> stageCreationResult); static CompletionStage<Stage> scheduleHiding(final Stage stage); static CompletionStage<Stage> scheduleHiding(final CompletionStage<Stage> stageCreationResult); static CompletionStage<Stage> setStylesheet(final Stage stage, final String stylesheet); static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final String stylesheet); static CompletionStage<Stage> setStylesheet(final Stage stage, final FxmlStylesheet stylesheet); static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final FxmlStylesheet stylesheet); }### Answer:
@Test public void setStylesheet() throws ExecutionException, InterruptedException { final CompletionStage<Stage> setStyleAsyncOp = Stages.setStylesheet(testStage, TEST_STYLE); final Stage stage = setStyleAsyncOp.toCompletableFuture().get(); final ObservableList<String> stylesheets = stage.getScene().getStylesheets(); assertThat(stylesheets).hasSize(1); assertThat(stylesheets).containsExactly(TEST_STYLE.getExternalForm()); }
@Test public void setStylesheetPostAsync() throws ExecutionException, InterruptedException { Try.of(() -> testStage) .map(Stages::scheduleDisplaying) .map(cs -> Stages.setStylesheet(cs, TEST_STYLE)) .get() .toCompletableFuture() .get(); await().until(() -> testStage.getScene().getStylesheets().contains(TEST_STYLE.getExternalForm())); assertThat(testStage.getScene().getStylesheets()).containsExactly(TEST_STYLE.getExternalForm()); } |
### Question:
Panes { public static <T extends Pane> CompletionStage<T> setContent(final T parent, final Node content) { return FxAsync.doOnFxThread(parent, parentNode -> { parentNode.getChildren().clear(); parentNode.getChildren().add(content); }); } private Panes(); static CompletionStage<T> setContent(final T parent, final Node content); }### Answer:
@Test public void setContent() { assertThat(container.getChildren()) .hasSize(1) .hasOnlyElementsOfType(Button.class); embedded = new Pane(); Panes.setContent(container, embedded) .whenCompleteAsync((res, err) -> { assertThat(err).isNull(); assertThat(res).isNotNull(); assertThat(res).isEqualTo(container); assertThat(container.getChildren()) .hasSize(1) .hasOnlyElementsOfType(embedded.getClass()); }); } |
### Question:
Properties { public static <T, P extends ObservableValue<T>> P newPropertyWithCallback(Supplier<P> propertyFactory, Consumer<T> callback) { final P property = propertyFactory.get(); whenPropertyIsSet(property, callback); return property; } private Properties(); static P newPropertyWithCallback(Supplier<P> propertyFactory, Consumer<T> callback); static void whenPropertyIsSet(P property, Consumer<T> doWhenSet); static void whenPropertyIsSet(P property, Function<A, B> adapter, Consumer<B> doWhenSet); static void bind(ObservableValue<S> from, Function<S, C> adapter, Property<C> to); static void whenPropertyIsSet(P property, Runnable doWhenSet); }### Answer:
@Test public void shouldCallDirectlyIfSetWithValue() { final Object element = new Object(); final Property<Object> called = new SimpleObjectProperty<>(null); Properties.newPropertyWithCallback(() -> new SimpleObjectProperty<>(element), called::setValue); assertThat(called.getValue()).isSameAs(element); }
@Test public void shouldCallConsumerOnEverySetCall() { final Property<Integer> called = new SimpleObjectProperty<>(); final Property<Integer> property = Properties.newPropertyWithCallback(SimpleObjectProperty::new, called::setValue); assertThat(called.getValue()).isNull(); IntStream.range(0, 1000).forEach(value -> { property.setValue(value); assertThat(called.getValue()).isEqualTo(value); }); } |
### Question:
Properties { public static <T, P extends ObservableValue<T>> void whenPropertyIsSet(P property, Consumer<T> doWhenSet) { whenPropertyIsSet(property, () -> doWhenSet.accept(property.getValue())); } private Properties(); static P newPropertyWithCallback(Supplier<P> propertyFactory, Consumer<T> callback); static void whenPropertyIsSet(P property, Consumer<T> doWhenSet); static void whenPropertyIsSet(P property, Function<A, B> adapter, Consumer<B> doWhenSet); static void bind(ObservableValue<S> from, Function<S, C> adapter, Property<C> to); static void whenPropertyIsSet(P property, Runnable doWhenSet); }### Answer:
@Test public void awaitCallsDirectlyIfSet() { final Property<Object> valuedProp = new SimpleObjectProperty<>(new Object()); final Property<Object> listener = new SimpleObjectProperty<>(); whenPropertyIsSet(valuedProp, listener::setValue); assertThat(listener.getValue()).isEqualTo(valuedProp.getValue()); }
@Test public void awaitCallsAwaitsSetIfNullOriginally() { final Property<Object> valuedProp = new SimpleObjectProperty<>(); final Property<Object> listener = new SimpleObjectProperty<>(); whenPropertyIsSet(valuedProp, listener::setValue); assertThat(listener.getValue()).isNull(); valuedProp.setValue(new Object()); assertThat(listener.getValue()).isEqualTo(valuedProp.getValue()); }
@Test public void awaitShouldCallConsumerOnEverySetCall() { final Property<Integer> called = new SimpleObjectProperty<>(); final Property<Integer> property = new SimpleObjectProperty<>(); whenPropertyIsSet(property, called::setValue); assertThat(called.getValue()).isNull(); IntStream.range(0, 1000).forEach(value -> { property.setValue(value); assertThat(called.getValue()).isEqualTo(value); }); } |
### Question:
FormFieldController implements FxmlController { public boolean validate(F fieldValue) { return true; } abstract String getFieldName(); abstract F getFieldValue(); boolean validate(F fieldValue); boolean isValid(); void onValid(); void onInvalid(String reason); }### Answer:
@Test public void defaultValidationIsNoop() { final FormFieldController sampleFieldController = new FormFieldController() { @Override public void initialize() { } @Override public String getFieldName() { return "Sample"; } @Override public Object getFieldValue() { return null; } @Override public void onValid() { throw new RuntimeException("Should not be called by default!"); } @Override public void onInvalid(String reason) { throw new RuntimeException("Should not be called by default!"); } }; assertThat(sampleFieldController.validate(null)).isTrue(); } |
### Question:
Resources { public static Try<Path> getResourcePath(final String resourceRelativePath) { return Try.of(() -> new ClassPathResource(resourceRelativePath)) .filter(ClassPathResource::exists) .map(ClassPathResource::getPath) .map(Paths::get); } private Resources(); static Try<Path> getResourcePath(final String resourceRelativePath); static Try<URL> getResourceURL(final String resourceRelativePath); static Either<Seq<Throwable>, Seq<Path>> listFiles(Path directory); static final PathMatchingResourcePatternResolver PATH_MATCHING_RESOURCE_RESOLVER; }### Answer:
@Test public void path_of_existing_file() { final Try<Path> fileThatExists = Resources.getResourcePath( PATH_UTIL_TESTS_FOLDER + EXISTING_FILE_NAME ); assertThat(fileThatExists.isSuccess()).isTrue(); fileThatExists.mapTry(Files::readAllLines).onSuccess( content -> assertThat(content) .hasSize(1) .containsExactly(EXISTING_FILE_CONTENT) ); }
@Test public void getResourcePath_should_display_path_tried() { final Try<Path> fileThatDoesntExist = Resources.getResourcePath( PATH_UTIL_TESTS_FOLDER + NONEXISTING_FILE_NAME ); assertThat(fileThatDoesntExist.isFailure()).isTrue(); assertThat(fileThatDoesntExist.getCause().getMessage()).contains(PATH_UTIL_TESTS_FOLDER + NONEXISTING_FILE_NAME); } |
### Question:
Resources { public static Try<URL> getResourceURL(final String resourceRelativePath) { return Try.of(() -> new ClassPathResource(resourceRelativePath)) .mapTry(ClassPathResource::getURL); } private Resources(); static Try<Path> getResourcePath(final String resourceRelativePath); static Try<URL> getResourceURL(final String resourceRelativePath); static Either<Seq<Throwable>, Seq<Path>> listFiles(Path directory); static final PathMatchingResourcePatternResolver PATH_MATCHING_RESOURCE_RESOLVER; }### Answer:
@Test public void getResourceURL_should_display_path_tried() { final Try<URL> fileThatDoesntExist = Resources.getResourceURL( PATH_UTIL_TESTS_FOLDER + NONEXISTING_FILE_NAME ); assertThat(fileThatDoesntExist.isFailure()).isTrue(); assertThat(fileThatDoesntExist.getCause().getMessage()).contains( PATH_UTIL_TESTS_FOLDER + NONEXISTING_FILE_NAME ); } |
### Question:
ExceptionHandler { public Pane asPane() { return this.asPane(this.exception.getMessage()); } ExceptionHandler(final Throwable exception); Pane asPane(); Pane asPane(final String userReadableError); static Pane fromThrowable(final Throwable throwable); static CompletionStage<Stage> displayExceptionPane(
final String title,
final String readable,
final Throwable exception
); }### Answer:
@Test public void asPane() { final Label errLabel = (Label) this.ERR_PANE.getChildren().filtered(node -> node instanceof Label).get(0); assertThat(errLabel.getText()).isEqualTo(this.EXCEPTION.getMessage()); } |
### Question:
ExceptionHandler { public static CompletionStage<Stage> displayExceptionPane( final String title, final String readable, final Throwable exception ) { final Pane exceptionPane = new ExceptionHandler(exception).asPane(readable); final CompletionStage<Stage> exceptionStage = Stages.stageOf(title, exceptionPane); return exceptionStage.thenCompose(Stages::scheduleDisplaying); } ExceptionHandler(final Throwable exception); Pane asPane(); Pane asPane(final String userReadableError); static Pane fromThrowable(final Throwable throwable); static CompletionStage<Stage> displayExceptionPane(
final String title,
final String readable,
final Throwable exception
); }### Answer:
@Test public void displayExceptionPane() throws ExecutionException, InterruptedException, TimeoutException { final CompletionStage<Stage> asyncDisplayedStage = ExceptionHandler.displayExceptionPane( this.EXCEPTION_TEXT, this.EXCEPTION_TEXT_READABLE, this.EXCEPTION ); final Stage errStage = asyncDisplayedStage.toCompletableFuture().get(5, TimeUnit.SECONDS); assertThat(errStage.isShowing()).isTrue(); } |
### Question:
ComponentListCell extends ListCell<T> { @Override protected void updateItem(final T item, final boolean empty) { super.updateItem(item, empty); if (item == null || empty) { setGraphic(null); setVisible(false); setManaged(false); } else { setVisible(true); setManaged(true); } Platform.runLater(() -> { cellController.updateWithValue(item); cellController.selectedProperty(selectedProperty()); if (getGraphic() == null) { setGraphic(cellNode); } }); } ComponentListCell(final EasyFxml easyFxml, final FxmlComponent cellNode); @SuppressWarnings("unchecked") ComponentListCell(final FxmlLoadResult<Pane, ComponentCellFxmlController> loadResult); ComponentListCell(final Pane cellNode, final ComponentCellFxmlController<T> controller); }### Answer:
@Test public void updateItem() { final AtomicBoolean initialized = new AtomicBoolean(false); final BooleanProperty readProp = new SimpleBooleanProperty(false); final AtomicReference<String> value = new AtomicReference<>(""); final Pane pane = new Pane(); final ComponentCellFxmlController<String> clvcc = new ComponentCellFxmlController<>() { @Override public void updateWithValue(String newValue) { value.set(newValue); } @Override public void selectedProperty(final BooleanExpression selected) { readProp.bind(selected); } @Override public void initialize() { if (initialized.get()) { throw new IllegalStateException("Double init!"); } initialized.set(true); } }; final TestListCell testListViewCell = new TestListCell(pane, clvcc); testListViewCell.updateItem("TEST", false); await().until(() -> value.get().equals("TEST")); testListViewCell.updateItem("TEST2", false); await().until(() -> value.get().equals("TEST2")); testListViewCell.updateItem(null, true); await().until(() -> value.get() == null); } |
### Question:
BrowserSupport { public Try<Void> openUrl(final String url) { return Try.run(() -> hostServices.showDocument(url)) .onFailure(cause -> onException(cause, url)); } @Autowired BrowserSupport(HostServices hostServices); Try<Void> openUrl(final String url); Try<Void> openUrl(final URL url); }### Answer:
@Test public void openUrl_good_url() { workaroundOpenJfxHavingAwfulBrowserSupport(() -> browserSupport.openUrl("https: }
@Test public void openUrl_bad_url() { workaroundOpenJfxHavingAwfulBrowserSupport(() -> { Try<Void> invalidUrlOpening = browserSupport.openUrl("not_a_url"); assertThat(invalidUrlOpening.isFailure()).isFalse(); }); }
@Test public void browse_ioe() { workaroundOpenJfxHavingAwfulBrowserSupport(() -> { Try<Void> nullUrlOpening = browserSupport.openUrl((URL) null); assertThat(nullUrlOpening.isFailure()).isTrue(); assertThat(nullUrlOpening.getCause()).isInstanceOf(NullPointerException.class); }); } |
### Question:
StringFormFieldController extends FormFieldController<String> { @Override public void initialize() { validateValueOnChange(); } @Override void initialize(); abstract ObservableValue<String> getObservableValue(); @Override String getFieldValue(); }### Answer:
@Test public void validatesOnEveryPropertyChangeByDefault() { sampleFieldController.initialize(); assertThat(validationCount.get()).isEqualTo(0); sampleProp.setValue("new value"); assertThat(validationCount.get()).isEqualTo(1); } |
### Question:
FxmlLoadResult implements Tuple { public Try<NODE> getNode() { return node; } FxmlLoadResult(Try<NODE> node, Try<CONTROLLER> controller); FxmlLoadResult<NODE, CONTROLLER> afterNodeLoaded(final Consumer<NODE> onNodeLoaded); FxmlLoadResult<NODE, CONTROLLER> afterControllerLoaded(final Consumer<CONTROLLER> onControllerLoaded); Try<NODE> getNode(); Try<CONTROLLER> getController(); Try<Pane> orExceptionPane(); Pane getNodeOrExceptionPane(); @Override int arity(); @Override Seq<?> toSeq(); }### Answer:
@Test public void getNode() { assertThat(fxmlLoadResult.getNode().get()).isEqualTo(TEST_NODE); } |
### Question:
FxmlLoadResult implements Tuple { public Try<Pane> orExceptionPane() { return ((Try<Pane>) getNode()).recover(ExceptionHandler::fromThrowable); } FxmlLoadResult(Try<NODE> node, Try<CONTROLLER> controller); FxmlLoadResult<NODE, CONTROLLER> afterNodeLoaded(final Consumer<NODE> onNodeLoaded); FxmlLoadResult<NODE, CONTROLLER> afterControllerLoaded(final Consumer<CONTROLLER> onControllerLoaded); Try<NODE> getNode(); Try<CONTROLLER> getController(); Try<Pane> orExceptionPane(); Pane getNodeOrExceptionPane(); @Override int arity(); @Override Seq<?> toSeq(); }### Answer:
@Test public void orExceptionPane() { final FxmlLoadResult<Node, FxmlController> loadResult = new FxmlLoadResult<>( Try.failure(new RuntimeException("TEST")), Try.failure(new RuntimeException("TEST")) ); assertThat(loadResult.orExceptionPane().isSuccess()).isTrue(); } |
### Question:
FxmlLoadResult implements Tuple { public Try<CONTROLLER> getController() { return controller; } FxmlLoadResult(Try<NODE> node, Try<CONTROLLER> controller); FxmlLoadResult<NODE, CONTROLLER> afterNodeLoaded(final Consumer<NODE> onNodeLoaded); FxmlLoadResult<NODE, CONTROLLER> afterControllerLoaded(final Consumer<CONTROLLER> onControllerLoaded); Try<NODE> getNode(); Try<CONTROLLER> getController(); Try<Pane> orExceptionPane(); Pane getNodeOrExceptionPane(); @Override int arity(); @Override Seq<?> toSeq(); }### Answer:
@Test public void getController() { assertThat(fxmlLoadResult.getController().get()).isEqualTo(TEST_CONTROLLER); } |
### Question:
FxmlLoadResult implements Tuple { @Override public int arity() { return 2; } FxmlLoadResult(Try<NODE> node, Try<CONTROLLER> controller); FxmlLoadResult<NODE, CONTROLLER> afterNodeLoaded(final Consumer<NODE> onNodeLoaded); FxmlLoadResult<NODE, CONTROLLER> afterControllerLoaded(final Consumer<CONTROLLER> onControllerLoaded); Try<NODE> getNode(); Try<CONTROLLER> getController(); Try<Pane> orExceptionPane(); Pane getNodeOrExceptionPane(); @Override int arity(); @Override Seq<?> toSeq(); }### Answer:
@Test public void arity() { assertThat(fxmlLoadResult.arity()).isEqualTo(2); } |
### Question:
FxmlLoadResult implements Tuple { @Override public Seq<?> toSeq() { return List.of(node, controller); } FxmlLoadResult(Try<NODE> node, Try<CONTROLLER> controller); FxmlLoadResult<NODE, CONTROLLER> afterNodeLoaded(final Consumer<NODE> onNodeLoaded); FxmlLoadResult<NODE, CONTROLLER> afterControllerLoaded(final Consumer<CONTROLLER> onControllerLoaded); Try<NODE> getNode(); Try<CONTROLLER> getController(); Try<Pane> orExceptionPane(); Pane getNodeOrExceptionPane(); @Override int arity(); @Override Seq<?> toSeq(); }### Answer:
@Test public void toSeq() { assertThat( fxmlLoadResult.toSeq() .map(Try.class::cast) .map(Try::get) .toJavaList() ).containsExactlyInAnyOrder(TEST_NODE, TEST_CONTROLLER); } |
### Question:
FxmlLoader extends FXMLLoader { public void onSuccess(final Node loadResult) { this.onSuccess.accept(loadResult); } @Autowired FxmlLoader(ApplicationContext context); void setOnSuccess(final Consumer<Node> onSuccess); void onSuccess(final Node loadResult); void setOnFailure(final Consumer<Throwable> onFailure); void onFailure(final Throwable cause); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void onSuccess() { new FxmlLoader(context).onSuccess(null); assertThat(succ).isEqualTo(0); assertThat(fail).isEqualTo(0); fxmlLoader.onSuccess(null); assertThat(succ).isEqualTo(1); assertThat(fail).isEqualTo(0); } |
### Question:
FxmlLoader extends FXMLLoader { public void onFailure(final Throwable cause) { this.onFailure.accept(cause); } @Autowired FxmlLoader(ApplicationContext context); void setOnSuccess(final Consumer<Node> onSuccess); void onSuccess(final Node loadResult); void setOnFailure(final Consumer<Throwable> onFailure); void onFailure(final Throwable cause); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void onFailure() { new FxmlLoader(context).onFailure(null); assertThat(succ).isEqualTo(0); assertThat(fail).isEqualTo(0); fxmlLoader.onFailure(null); assertThat(succ).isEqualTo(0); assertThat(fail).isEqualTo(1); } |
### Question:
DefaultEasyFxml implements EasyFxml { @Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); } @Autowired protected DefaultEasyFxml(
final ApplicationContext context,
final ControllerManager controllerManager,
EasyFxmlProperties easyFxmlProperties
); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component, final Selector selector); @Override FxmlLoadResult<NODE, CONTROLLER> load(
final FxmlComponent component,
final Class<? extends NODE> componentClass,
final Class<? extends CONTROLLER> controllerClass
); @Override FxmlLoadResult<NODE, CONTROLLER> load(
final FxmlComponent component,
final Class<? extends NODE> nodeClass,
final Class<? extends CONTROLLER> controllerClass,
final Selector selector
); }### Answer:
@Test public void loadAsPaneSingle() throws InterruptedException, ExecutionException, TimeoutException { Pane testPane = this.assertSuccessAndGet(this.easyFxml.load(paneWithButtonComponent).getNode()); assertThat(testPane.getChildren()).hasSize(1); assertThat(testPane.getChildren().get(0).getClass()).isEqualTo(Button.class); this.assertControllerBoundToTestPane( testPane, this.controllerManager.getSingle(paneWithButtonComponent) ); }
@Test public void loadAsPaneMultiple() throws InterruptedException, ExecutionException, TimeoutException { Object selector = new Object(); Pane testPane = this.assertSuccessAndGet(this.easyFxml.load(paneWithButtonComponent, new Selector(selector)).getNode()); this.assertControllerBoundToTestPane( testPane, this.controllerManager.getMultiple(paneWithButtonComponent, new Selector(selector)) ); assertThat(testPane.getChildren()).hasSize(1); assertThat(testPane.getChildren().get(0).getClass()).isEqualTo(Button.class); }
@Test public void loadWithTypeSuccess() throws InterruptedException, ExecutionException, TimeoutException { Pane testPane = this.assertSuccessAndGet(this.easyFxml.load( paneWithButtonComponent, Pane.class, FxmlController.class ).getNode()); this.assertControllerBoundToTestPane( testPane, this.controllerManager.getSingle(paneWithButtonComponent) ); }
@Test public void loadWithTypeSingleInvalidClassFailure() { this.assertPaneFailedLoadingAndDidNotRegister( () -> this.easyFxml.load(buttonComponent, Pane.class, FxmlController.class).getNode(), this.controllerManager.getSingle(buttonComponent), ClassCastException.class ); }
@Test public void loadWithTypeSingleInvalidFileFailure() { this.assertPaneFailedLoadingAndDidNotRegister( () -> this.easyFxml.load(invalidComponent).getNode(), this.controllerManager.getSingle(invalidComponent), LoadException.class ); }
@Test public void loadWithTypeMultipleInvalidClassFailure() { Object selector = new Object(); this.assertPaneFailedLoadingAndDidNotRegister( () -> this.easyFxml.load(buttonComponent, Pane.class, NoControllerClass.class, new Selector(selector)).getNode(), this.controllerManager.getMultiple(buttonComponent, new Selector(selector)), ClassCastException.class ); }
@Test public void loadWithTypeMultipleInvalidFileFailure() { Object selector = new Object(); this.assertPaneFailedLoadingAndDidNotRegister( () -> this.easyFxml.load(invalidComponent, new Selector(selector)).getNode(), this.controllerManager.getMultiple(invalidComponent, new Selector(selector)), LoadException.class ); } |
### Question:
StringFormFieldController extends FormFieldController<String> { protected boolean isNullOrBlank() { final String fieldValue = getFieldValue(); return fieldValue == null || fieldValue.isBlank(); } @Override void initialize(); abstract ObservableValue<String> getObservableValue(); @Override String getFieldValue(); }### Answer:
@Test public void isNullOrBlankMatches() { Stream.of(null, "", "\t \n ").forEach(nullOrBlank -> { sampleProp.setValue(nullOrBlank); assertThat(sampleFieldController.isNullOrBlank()).isTrue(); }); sampleProp.setValue("Non null nor empty/blank string"); assertThat(sampleFieldController.isNullOrBlank()).isFalse(); } |
### Question:
AbstractInstanceManager { public V registerSingle(final K parent, final V instance) { return this.singletons.put(parent, instance); } V registerSingle(final K parent, final V instance); V registerMultiple(
final K parent,
final Selector selector,
final V instance
); Option<V> getMultiple(final K parent, final Selector selector); List<V> getAll(final K parent); List<V> getMultiples(final K parent); Option<V> getSingle(final K parent); }### Answer:
@Test public void registerSingle() { this.instanceManager.registerSingle(PARENT, ACTUAL_1); assertThat(this.instanceManager.getSingle(PARENT).get()).isEqualTo(ACTUAL_1); } |
### Question:
AbstractInstanceManager { public V registerMultiple( final K parent, final Selector selector, final V instance ) { if (!this.prototypes.containsKey(parent)) { this.prototypes.put(parent, new ConcurrentHashMap<>()); } return this.prototypes.get(parent).put(selector, instance); } V registerSingle(final K parent, final V instance); V registerMultiple(
final K parent,
final Selector selector,
final V instance
); Option<V> getMultiple(final K parent, final Selector selector); List<V> getAll(final K parent); List<V> getMultiples(final K parent); Option<V> getSingle(final K parent); }### Answer:
@Test public void registerMultiple() { this.instanceManager.registerMultiple(PARENT, SEL_1, ACTUAL_1); this.instanceManager.registerMultiple(PARENT, SEL_2, ACTUAL_2); assertThat(this.instanceManager.getMultiple(PARENT, SEL_1).get()).isEqualTo(ACTUAL_1); assertThat(this.instanceManager.getMultiple(PARENT, SEL_2).get()).isEqualTo(ACTUAL_2); } |
### Question:
AbstractInstanceManager { public List<V> getAll(final K parent) { final List<V> all = this.getMultiples(parent); this.getSingle(parent).peek(all::add); return all; } V registerSingle(final K parent, final V instance); V registerMultiple(
final K parent,
final Selector selector,
final V instance
); Option<V> getMultiple(final K parent, final Selector selector); List<V> getAll(final K parent); List<V> getMultiples(final K parent); Option<V> getSingle(final K parent); }### Answer:
@Test public void getAll() { this.instanceManager.registerSingle(PARENT, ACTUAL_1); this.instanceManager.registerSingle(PARENT, ACTUAL_2); this.instanceManager.registerMultiple(PARENT, SEL_1, ACTUAL_1); this.instanceManager.registerMultiple(PARENT, SEL_2, ACTUAL_2); final List<String> all = this.instanceManager.getAll(PARENT); assertThat(all).containsExactlyInAnyOrder( ACTUAL_1, ACTUAL_2, ACTUAL_2 ); } |
### Question:
AbstractInstanceManager { public List<V> getMultiples(final K parent) { return new ArrayList<>(Option.of(this.prototypes.get(parent)) .map(Map::values) .getOrElse(Collections.emptyList())); } V registerSingle(final K parent, final V instance); V registerMultiple(
final K parent,
final Selector selector,
final V instance
); Option<V> getMultiple(final K parent, final Selector selector); List<V> getAll(final K parent); List<V> getMultiples(final K parent); Option<V> getSingle(final K parent); }### Answer:
@Test public void getMultiples() { this.instanceManager.registerMultiple(PARENT, SEL_1, ACTUAL_1); this.instanceManager.registerMultiple(PARENT, SEL_2, ACTUAL_2); assertThat(this.instanceManager.getMultiples(PARENT)).containsExactlyInAnyOrder(ACTUAL_1, ACTUAL_2); } |
### Question:
FxApplication extends Application { @Override public void start(final Stage primaryStage) { this.springContext.getBean(FxUiManager.class).startGui(primaryStage); } @Override void init(); @Override void start(final Stage primaryStage); @Override void stop(); }### Answer:
@Test public void start() throws Exception { TestFxApplication.main(); } |
### Question:
FxUiManager { public void startGui(final Stage mainStage) { try { onStageCreated(mainStage); final Scene mainScene = getScene(mainComponent()); onSceneCreated(mainScene); mainStage.setScene(mainScene); mainStage.setTitle(title()); Option.ofOptional(getStylesheet()) .filter(style -> !FxmlStylesheets.DEFAULT_JAVAFX_STYLE.equals(style)) .peek(stylesheet -> this.setTheme(stylesheet, mainStage)); mainStage.show(); } catch (Throwable t) { throw new RuntimeException("There was a failure during start-up of the application.", t); } } void startGui(final Stage mainStage); @Autowired void setEasyFxml(EasyFxml easyFxml); }### Answer:
@Test public void startGui() { Platform.runLater(() -> testFxUiManager.startGui(stage)); } |
### Question:
FxAsync { public static <T> CompletionStage<T> doOnFxThread(final T element, final Consumer<T> action) { return CompletableFuture.supplyAsync(() -> { action.accept(element); return element; }, Platform::runLater); } private FxAsync(); static CompletionStage<T> doOnFxThread(final T element, final Consumer<T> action); static CompletionStage<U> computeOnFxThread(final T element, final Function<T, U> compute); }### Answer:
@Test public void doOnFxThread() throws ExecutionException, InterruptedException { FxAsync.doOnFxThread( fxThread, expected -> assertThat(Thread.currentThread()).isEqualTo(expected) ).toCompletableFuture().get(); } |
### Question:
FxAsync { public static <T, U> CompletionStage<U> computeOnFxThread(final T element, final Function<T, U> compute) { return CompletableFuture.supplyAsync(() -> compute.apply(element), Platform::runLater); } private FxAsync(); static CompletionStage<T> doOnFxThread(final T element, final Consumer<T> action); static CompletionStage<U> computeOnFxThread(final T element, final Function<T, U> compute); }### Answer:
@Test public void computeOnFxThread() throws ExecutionException, InterruptedException { FxAsync.computeOnFxThread( fxThread, expected -> assertThat(Thread.currentThread()).isEqualTo(expected) ).toCompletableFuture().get(); } |
### Question:
Buttons { public static void setOnClick(final Button button, final Runnable action) { button.setOnAction(e -> Platform.runLater(action)); } private Buttons(); static void setOnClick(final Button button, final Runnable action); static void setOnClickWithNode(final Button button, final Node node, final Consumer<Node> action); }### Answer:
@Test public void setOnClick() { final AtomicBoolean success = new AtomicBoolean(false); final Button testButton = new Button("TEST_BUTTON"); Buttons.setOnClick(testButton, () -> success.set(true)); withNodes(testButton) .startWhen(() -> point(testButton).query() != null) .willDo(() -> clickOn(testButton, PRIMARY)) .andAwaitFor(success::get); assertThat(success).isTrue(); } |
### Question:
Buttons { public static void setOnClickWithNode(final Button button, final Node node, final Consumer<Node> action) { setOnClick(button, () -> action.accept(node)); } private Buttons(); static void setOnClick(final Button button, final Runnable action); static void setOnClickWithNode(final Button button, final Node node, final Consumer<Node> action); }### Answer:
@Test public void setOnClickWithNode() { final Button testButton = new Button("Test button"); final Label testLabel = new Label("Test label"); Buttons.setOnClickWithNode(testButton, testLabel, label -> label.setVisible(false)); withNodes(testButton, testLabel) .startWhen(() -> point(testButton).query() != null) .willDo(() -> clickOn(testButton, PRIMARY)) .andAwaitFor(() -> !testLabel.isVisible()); assertThat(testLabel.isVisible()).isFalse(); } |
### Question:
Nodes { public static void centerNode(final Node node, final Double marginSize) { AnchorPane.setTopAnchor(node, marginSize); AnchorPane.setBottomAnchor(node, marginSize); AnchorPane.setLeftAnchor(node, marginSize); AnchorPane.setRightAnchor(node, marginSize); } private Nodes(); static void centerNode(final Node node, final Double marginSize); static void hideAndResizeParentIf(
final Node node,
final ObservableValue<? extends Boolean> condition
); static void autoresizeContainerOn(
final Node node,
final ObservableValue<?> observableValue
); static void bindContentBiasCalculationTo(
final Node node,
final ObservableValue<? extends Boolean> observableValue
); }### Answer:
@Test public void centerNode() { Nodes.centerNode(this.testButton, MARGIN); } |
### Question:
Nodes { public static void hideAndResizeParentIf( final Node node, final ObservableValue<? extends Boolean> condition ) { autoresizeContainerOn(node, condition); bindContentBiasCalculationTo(node, condition); } private Nodes(); static void centerNode(final Node node, final Double marginSize); static void hideAndResizeParentIf(
final Node node,
final ObservableValue<? extends Boolean> condition
); static void autoresizeContainerOn(
final Node node,
final ObservableValue<?> observableValue
); static void bindContentBiasCalculationTo(
final Node node,
final ObservableValue<? extends Boolean> observableValue
); }### Answer:
@Test public void testAutosizeHelpers() { final BooleanProperty shouldDisplay = new SimpleBooleanProperty(true); final Button testButton = new Button(); Nodes.hideAndResizeParentIf(testButton, shouldDisplay); assertThat(testButton.isManaged()).isTrue(); assertThat(testButton.isVisible()).isTrue(); shouldDisplay.setValue(false); assertThat(testButton.isManaged()).isFalse(); assertThat(testButton.isVisible()).isFalse(); } |
### Question:
JenkinsLinterErrorBuilder { public JenkinsLinterError build(String line) { if (line==null){ return null; } Matcher matcher = ERROR_PATTERN.matcher(line); if (! matcher.find()){ return null; } JenkinsLinterError error = new JenkinsLinterError(); error.message=line; error.line = Integer.valueOf(matcher.group(1)); error.column = Integer.valueOf(matcher.group(2)); return error; } JenkinsLinterError build(String line); }### Answer:
@Test public void workflowscript_missing_required_againt_at_line_1_comma_column1__is_recognized_as_error() { String line = "WorkflowScript: 1: Missing required section \"agent\" @ line 1, column 1."; JenkinsLinterError error = builderToTest.build(line); assertNotNull(error); assertEquals(1,error.getLine()); assertEquals(1,error.getColumn()); assertEquals(line,error.getMessage()); }
@Test public void workflowscript_no_stages_specified_at_line_3_comma_column2__is_recognized_as_error() { String line = "WorkflowScript: 2: No stages specified @ line 3, column 2."; JenkinsLinterError error = builderToTest.build(line); assertNotNull(error); assertEquals(3,error.getLine()); assertEquals(2,error.getColumn()); assertEquals(line,error.getMessage()); }
@Test public void workflowscript_no_stages_specified_at_line_3000_comma_column22__is_recognized_as_error() { String line = "WorkflowScript: 2: No stages specified @ line 3000, column 22."; JenkinsLinterError error = builderToTest.build(line); assertNotNull(error); assertEquals(3000,error.getLine()); assertEquals(22,error.getColumn()); assertEquals(line,error.getMessage()); }
@Test public void errors_encountered_validating_jenkinsfile_is_not_an_error_itself() { String line = "Errors encountered validating Jenkinsfile:"; JenkinsLinterError error = builderToTest.build(line); assertNull(error); }
@Test public void infotext_about_pipeline_code_is_not_a_error() { String line = " pipeline{"; JenkinsLinterError error = builderToTest.build(line); assertNull(error); } |
### Question:
AbstractJenkinsCLICommand implements JenkinsCLICommand<T, P> { protected String[] createCommands(JenkinsCLIConfiguration configuration, P parameter, boolean hidePasswords) { return createExecutionStrings(configuration, hidePasswords); } final T execute(JenkinsCLIConfiguration configuration, P parameter); }### Answer:
@Test public void commands_hidden_expected_output_done() { String expected = "[java, -Dhttp.proxyPassword=******, -Dhttps.proxyPassword=******, -jar, thePath, -s, http: String[] commands = commandToTest.createCommands(configuration, parameter, true); List<String> list = Arrays.asList(commands); assertEquals(expected, list.toString()); }
@Test public void commands_hidden_contains_no_http_proxy_passwords() throws Exception { String[] commands = commandToTest.createCommands(configuration, parameter, true); List<String> list = Arrays.asList(commands); assertFalse(list.contains(DHTTP_PROXY_PASSWORD_MYSECRET1)); assertFalse(list.contains(DHTTPS_PROXY_PASSWORD_MYSECRET2)); }
@Test public void commands_NOT_hidden_contains_http_proxy_passwords() throws Exception { String[] commands = commandToTest.createCommands(configuration, parameter, false); List<String> list = Arrays.asList(commands); assertTrue(list.contains(DHTTP_PROXY_PASSWORD_MYSECRET1)); assertTrue(list.contains(DHTTPS_PROXY_PASSWORD_MYSECRET2)); }
@Test public void command_auth_no_proxy_set() throws Exception { String[] commands = commandToTest.createCommands(configuration, parameter, true); List<String> list = Arrays.asList(commands); System.out.println(list); }
@Test public void commands_NOT_hidden_expected_output_done() { String expected = "[java, -Dhttp.proxyPassword=mysecret1, -Dhttps.proxyPassword=mysecret2, -jar, thePath, -s, http: String[] commands = commandToTest.createCommands(configuration, parameter, false); List<String> list = Arrays.asList(commands); assertEquals(expected, list.toString()); } |
### Question:
JenkinsDefaultURLProvider { public String getDefaultJenkinsURL() { String jenkinsURL = getJENKINS_URL(); if (jenkinsURL != null && jenkinsURL.trim().length() > 0) { return jenkinsURL; } return getLocalhostURL(); } String getDefaultJenkinsURL(); String createDefaultURLDescription(); }### Answer:
@Test public void system_provider_returns_null_for_JENKINS_URL___then_fallback_url_with_localhost_is_returned() { when(mockedSystemAdapter.getEnv("JENKINS_URL")).thenReturn(null); assertEquals("http: }
@Test public void system_provider_returns_empty_string_for_JENKINS_URL___then_fallback_url_with_localhost_is_returned() { when(mockedSystemAdapter.getEnv("JENKINS_URL")).thenReturn(""); assertEquals("http: }
@Test public void system_provider_returns_blubber_for_JENKINS_URL___then_blubber_is_returned() { when(mockedSystemAdapter.getEnv("JENKINS_URL")).thenReturn("blubber"); assertEquals("blubber", providerToTest.getDefaultJenkinsURL()); } |
### Question:
JenkinsDefaultURLProvider { public String createDefaultURLDescription() { String jenkinsURL = getJENKINS_URL(); if (jenkinsURL != null) { return "JENKINS_URL defined as " + jenkinsURL + ". Using this as default value"; } return "No JENKINS_URL env defined, so using " + getLocalhostURL() + " as default value"; } String getDefaultJenkinsURL(); String createDefaultURLDescription(); }### Answer:
@Test public void system_provider_returns_null_for_JENKINS_URL___then_description_about_missing_JENKINS_URL_and_usage_of_localhost_is_returned() { when(mockedSystemAdapter.getEnv("JENKINS_URL")).thenReturn(null); assertEquals("No JENKINS_URL env defined, so using http: }
@Test public void system_provider_returns_blubber_for_JENKINS_URL___then_description_JENKINS_URLthen_blubber_is_returned() { when(mockedSystemAdapter.getEnv("JENKINS_URL")).thenReturn("blubber"); assertEquals("JENKINS_URL defined as blubber. Using this as default value", providerToTest.createDefaultURLDescription()); } |
### Question:
JenkinsWordCompletion extends AbstractWordCodeCompletition { @Override public Set<ProposalProvider> calculate(String source, int offset) { if (source.trim().length()==0){ return Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); } String parentAsText = ""; JenkinsModelBuilder builder = new JenkinsModelBuilder(new ByteArrayInputStream(source.getBytes())); BuildContext builderContext = new BuildContext(); Item item = null; try { Model model = builder.build(builderContext); item = model.getParentItemOf(offset); } catch (ModelBuilderException e) { EclipseUtil.logError("Cannot build proposal model", e, JenkinsEditorActivator.getDefault()); return Collections.emptySet(); } if (item.isRoot()){ Set<ProposalProvider> set = Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); return set; } parentAsText=item.getIdentifier(); List<Node> foundParents = model.findByKeyword(parentAsText); if (foundParents.isEmpty()){ return Collections.emptySet(); } return fetchChildrenProposalsForParents(source, offset, foundParents); } JenkinsWordCompletion(); @Override Set<ProposalProvider> calculate(String source, int offset); @Override void reset(); }### Answer:
@Test public void an_empty_source_will_result_in_pipeline() { Set<ProposalProvider> result = completion.calculate(source0, 0); assertFalse(result.isEmpty()); assertEquals(1,result.size()); ProposalProvider provider = result.iterator().next(); assertTrue(provider.getLabel().equals("pipeline")); List<String> template = provider.getCodeTemplate(); assertEquals(3, template.size()); Iterator<String> it = template.iterator(); assertEquals(it.next(), "pipeline {"); assertEquals(it.next(), " "+SourceCodeBuilder.CURSOR_TAG); assertEquals(it.next(), "}"); }
@Test public void an_pip_source_will_result_in_pipeline() { Set<ProposalProvider> result = completion.calculate("pip", 0); assertFalse(result.isEmpty()); assertEquals(1,result.size()); ProposalProvider provider = result.iterator().next(); assertTrue(provider.getLabel().equals("pipeline")); List<String> template = provider.getCodeTemplate(); assertEquals(3, template.size()); Iterator<String> it = template.iterator(); assertEquals(it.next(), "pipeline {"); assertEquals(it.next(), " "+SourceCodeBuilder.CURSOR_TAG); assertEquals(it.next(), "}"); }
@Test public void after_pipeline_agent_is_suggested() { Set<ProposalProvider> result = completion.calculate(source1, source1_pipeline_block_index); assertLabelFound("agent",result); }
@Test public void after_pipeline_stage_is_suggested() { Set<ProposalProvider> result = completion.calculate(source1, source1_pipeline_block_index); assertLabelFound("stages",result); }
@Test public void after_pipeline_pipeline_is_NOT_suggested() { Set<ProposalProvider> result = completion.calculate(source1, source1_pipeline_block_index); assertNOLabelFound("pipeline",result); } |
### Question:
SystemPropertyListBuilder { public String build(String type, String key, String value){ StringBuilder sb = new StringBuilder(); sb.append("-D"); sb.append(type); sb.append('.'); sb.append(key); sb.append('='); sb.append(value); return sb.toString(); } String build(String type, String key, String value); }### Answer:
@Test public void prefix_key_value_returned_as_system_property_entry() { assertEquals("-Dprefix.key=value",builderToTest.build("prefix", "key", "value")); }
@Test public void null_key_value_returned_as_system_property_entry() { assertEquals("-Dnull.key=value",builderToTest.build(null, "key", "value")); }
@Test public void prefix_null_value_returned_as_system_property_entry() { assertEquals("-Dprefix.null=value",builderToTest.build("prefix", null, "value")); }
@Test public void prefix_key_null_returned_as_system_property_entry() { assertEquals("-Dprefix.key=null",builderToTest.build("prefix", "key",null)); } |
### Question:
SeasonAnalyticsJdbcDao extends JdbcDaoSupport implements SeasonAnalyticsDao { @Override public SeasonAnalytics fetchByYear(Integer year) { SeasonAnalytics ret = null; String sql = "SELECT * FROM " + TABLE_NAME + " WHERE year = ?"; Object[] args = { year }; List<SeasonAnalytics> results = getJdbcTemplate().query(sql, args, new SeasonAnalyticsRowMapper()); if (results.size() > 0) { if (results.size() > 1) { log.warn("Expected 1 result from query, instead got " + results.size() + "!"); } ret = results.get(0); } else { log.warn("Requested year (" + year + ") does not exist in the DB!"); } return ret; } SeasonAnalyticsJdbcDao(DataSource dataSource); @Override SeasonAnalytics fetchByYear(Integer year); }### Answer:
@Test public void testFetchByYear_2010() { log.info("*** BEGIN Test ***"); Integer year = 2010; SeasonAnalytics seasonAnalytics = classUnderTest.fetchByYear(year); assertNotNull(seasonAnalytics); log.info("*** END Test ***"); }
@Test public void testFetchByYear_2011() { log.info("*** BEGIN Test ***"); Integer year = 2011; SeasonAnalytics seasonAnalytics = classUnderTest.fetchByYear(year); assertNotNull(seasonAnalytics); log.info("*** END Test ***"); }
@Test public void testFetchByYear_2012() { log.info("*** BEGIN Test ***"); Integer year = 2012; SeasonAnalytics seasonAnalytics = classUnderTest.fetchByYear(year); assertNotNull(seasonAnalytics); log.info("*** END Test ***"); }
@Test public void testFetchByYear_2013() { log.info("*** BEGIN Test ***"); Integer year = 2013; SeasonAnalytics seasonAnalytics = classUnderTest.fetchByYear(year); assertNotNull(seasonAnalytics); log.info("*** END Test ***"); }
@Test public void testFetchByYear_2014() { log.info("*** BEGIN Test ***"); Integer year = 2014; SeasonAnalytics seasonAnalytics = classUnderTest.fetchByYear(year); assertNotNull(seasonAnalytics); log.info("*** END Test ***"); }
@Test public void testFetchByYear_2015() { log.info("*** BEGIN Test ***"); Integer year = 2015; SeasonAnalytics seasonAnalytics = classUnderTest.fetchByYear(year); assertNotNull(seasonAnalytics); log.info("*** END Test ***"); }
@Test public void testFetchByYear_2016() { log.info("*** BEGIN Test ***"); Integer year = 2016; SeasonAnalytics seasonAnalytics = classUnderTest.fetchByYear(year); assertNotNull(seasonAnalytics); log.info("*** END Test ***"); }
@Test public void testFetchByYear_2017() { log.info("*** BEGIN Test ***"); Integer year = 2017; SeasonAnalytics seasonAnalytics = classUnderTest.fetchByYear(year); assertNotNull(seasonAnalytics); log.info("*** END Test ***"); } |
### Question:
SeasonDataJdbcDao extends JdbcDaoSupport implements SeasonDataDao { @Override public List<SeasonData> fetchAllByYear(Integer year) { List<SeasonData> ret = null; String sql = "SELECT t.* FROM " + TABLE_NAME + " t WHERE t.year = ?"; Object[] args = { year }; ret = getJdbcTemplate().query(sql, args, new SeasonDataRowMapper()); return ret; } SeasonDataJdbcDao(DataSource dataSource); @Override List<SeasonData> fetchAllByYear(Integer year); @Override SeasonData fetchByYearAndTeamName(Integer year, String teamName); }### Answer:
@Test public void testFetchAllByYear_2013() { log.info("*** BEGIN Test ***"); Integer year = 2013; List<SeasonData> results = classUnderTest.fetchAllByYear(year); assertEquals(68, results.size()); log.info("*** END Test ***"); }
@Test public void testFetchAllByYear_2014() { log.info("*** BEGIN Test ***"); Integer year = 2014; List<SeasonData> results = classUnderTest.fetchAllByYear(year); assertEquals(68, results.size()); log.info("*** END Test ***"); }
@Test public void testFetchAllByYear_2015() { log.info("*** BEGIN Test ***"); Integer year = 2015; List<SeasonData> results = classUnderTest.fetchAllByYear(year); assertEquals(68, results.size()); log.info("*** END Test ***"); }
@Test public void testFetchAllByYear_2016() { log.info("*** BEGIN Test ***"); Integer year = 2016; List<SeasonData> results = classUnderTest.fetchAllByYear(year); assertEquals(68, results.size()); log.info("*** END Test ***"); }
@Test public void testFetchAllByYear_2017() { log.info("*** BEGIN Test ***"); Integer year = 2017; List<SeasonData> results = classUnderTest.fetchAllByYear(year); assertEquals(68, results.size()); log.info("*** END Test ***"); }
@Test public void testFetchAllByYear_2011() { log.info("*** BEGIN Test ***"); Integer year = 2011; List<SeasonData> results = classUnderTest.fetchAllByYear(year); assertEquals(68, results.size()); log.info("*** END Test ***"); }
@Test public void testFetchAllByYear_2012() { log.info("*** BEGIN Test ***"); Integer year = 2012; List<SeasonData> results = classUnderTest.fetchAllByYear(year); assertEquals(68, results.size()); log.info("*** END Test ***"); } |
### Question:
SeasonDataJdbcDao extends JdbcDaoSupport implements SeasonDataDao { @Override public SeasonData fetchByYearAndTeamName(Integer year, String teamName) { SeasonData ret = null; String sql = "SELECT t.* FROM " + TABLE_NAME + " t WHERE t.year = ? AND t.team_name = ?"; Object[] args = { year, teamName }; List<SeasonData> results = getJdbcTemplate().query(sql, args, new SeasonDataRowMapper()); if (results.size() > 0) { if (results.size() > 1) { log.warn("Expected 1 result from query, instead got " + results.size() + "!"); } ret = results.get(0); } else { log.warn("Requested team/year combination (" + teamName + "/" + year + ") does not exist in the DB!"); } return ret; } SeasonDataJdbcDao(DataSource dataSource); @Override List<SeasonData> fetchAllByYear(Integer year); @Override SeasonData fetchByYearAndTeamName(Integer year, String teamName); }### Answer:
@Test public void testFetchByYearAndTeamName_2011() { log.info("*** BEGIN Test ***"); Integer year = 2011; String teamName = "Kentucky"; SeasonData result = classUnderTest.fetchByYearAndTeamName(year, teamName); assertEquals("Kentucky", result.getTeamName()); log.info("*** END Test ***"); }
@Test public void testFetchByYearAndTeamName_2012() { log.info("*** BEGIN Test ***"); Integer year = 2012; String teamName = "Kentucky"; SeasonData result = classUnderTest.fetchByYearAndTeamName(year, teamName); assertEquals("Kentucky", result.getTeamName()); log.info("*** END Test ***"); }
@Test public void testFetchByYearAndTeamName_2013() { log.info("*** BEGIN Test ***"); Integer year = 2013; String teamName = "Kentucky"; SeasonData result = classUnderTest.fetchByYearAndTeamName(year, teamName); assertNull(result); teamName = "Duke"; result = classUnderTest.fetchByYearAndTeamName(year, teamName); assertEquals("Duke", result.getTeamName()); log.info("*** END Test ***"); }
@Test public void testFetchByYearAndTeamName_2014() { log.info("*** BEGIN Test ***"); Integer year = 2014; String teamName = "Kentucky"; SeasonData result = classUnderTest.fetchByYearAndTeamName(year, teamName); assertEquals("Kentucky", result.getTeamName()); log.info("*** END Test ***"); }
@Test public void testFetchByYearAndTeamName_2015() { log.info("*** BEGIN Test ***"); Integer year = 2015; String teamName = "Kentucky"; SeasonData result = classUnderTest.fetchByYearAndTeamName(year, teamName); assertEquals("Kentucky", result.getTeamName()); log.info("*** END Test ***"); }
@Test public void testFetchByYearAndTeamName_2016() { log.info("*** BEGIN Test ***"); Integer year = 2016; String teamName = "Kentucky"; SeasonData result = classUnderTest.fetchByYearAndTeamName(year, teamName); assertEquals("Kentucky", result.getTeamName()); log.info("*** END Test ***"); }
@Test public void testFetchByYearAndTeamName_2017() { log.info("*** BEGIN Test ***"); Integer year = 2017; String teamName = "Kentucky"; SeasonData result = classUnderTest.fetchByYearAndTeamName(year, teamName); assertEquals("Kentucky", result.getTeamName()); log.info("*** END Test ***"); } |
### Question:
TournamentAnalyticsJdbcDao extends JdbcDaoSupport implements TournamentAnalyticsDao { @Override public TournamentAnalytics fetchByYear(Integer year) { TournamentAnalytics ret = null; String sql = "SELECT * FROM " + TABLE_NAME + " WHERE year = ?"; Object[] args = { year }; List<TournamentAnalytics> results = getJdbcTemplate().query(sql, args, new TournamentAnalyticsRowMapper()); if (results.size() > 0) { if (results.size() > 1) { log.warn("Expected 1 result from query, instead got " + results.size() + "!"); } ret = results.get(0); } else { log.warn("Requested year (" + year + ") does not exist in the DB!"); } return ret; } TournamentAnalyticsJdbcDao(DataSource dataSource); @Override TournamentAnalytics fetchByYear(Integer year); }### Answer:
@Test @DisplayName("Testing fetchByYear()") public void fetchByYear() { assertAll( () -> { Integer year = 2010; TournamentAnalytics tournamentAnalytics = classUnderTest.fetchByYear(year); assertNotNull(tournamentAnalytics); assertEquals(Integer.valueOf(44), tournamentAnalytics.getMinScore()); assertEquals(Integer.valueOf(101), tournamentAnalytics.getMaxScore()); }, () -> { Integer year = 2011; TournamentAnalytics tournamentAnalytics = classUnderTest.fetchByYear(year); assertNotNull(tournamentAnalytics); assertEquals(Integer.valueOf(41), tournamentAnalytics.getMinScore()); assertEquals(Integer.valueOf(102), tournamentAnalytics.getMaxScore()); }, () -> { Integer year = 2012; TournamentAnalytics tournamentAnalytics = classUnderTest.fetchByYear(year); assertNotNull(tournamentAnalytics); assertEquals(Integer.valueOf(41), tournamentAnalytics.getMinScore()); assertEquals(Integer.valueOf(102), tournamentAnalytics.getMaxScore()); }, () -> { Integer year = 2013; TournamentAnalytics tournamentAnalytics = classUnderTest.fetchByYear(year); assertNotNull(tournamentAnalytics); assertEquals(Integer.valueOf(34), tournamentAnalytics.getMinScore()); assertEquals(Integer.valueOf(95), tournamentAnalytics.getMaxScore()); }, () -> { Integer year = 2014; TournamentAnalytics tournamentAnalytics = classUnderTest.fetchByYear(year); assertNotNull(tournamentAnalytics); assertEquals(Integer.valueOf(35), tournamentAnalytics.getMinScore()); assertEquals(Integer.valueOf(93), tournamentAnalytics.getMaxScore()); }, () -> { Integer year = 2015; TournamentAnalytics tournamentAnalytics = classUnderTest.fetchByYear(year); assertNotNull(tournamentAnalytics); assertEquals(Integer.valueOf(39), tournamentAnalytics.getMinScore()); assertEquals(Integer.valueOf(94), tournamentAnalytics.getMaxScore()); }, () -> { Integer year = 2016; TournamentAnalytics tournamentAnalytics = classUnderTest.fetchByYear(year); assertNotNull(tournamentAnalytics); assertEquals(Integer.valueOf(43), tournamentAnalytics.getMinScore()); assertEquals(Integer.valueOf(105), tournamentAnalytics.getMaxScore()); }, () -> { Integer year = 2017; TournamentAnalytics tournamentAnalytics = classUnderTest.fetchByYear(year); assertNotNull(tournamentAnalytics); assertEquals(Integer.valueOf(39), tournamentAnalytics.getMinScore()); assertEquals(Integer.valueOf(103), tournamentAnalytics.getMaxScore()); }); } |
### Question:
TournamentResultJdbcDao extends JdbcDaoSupport implements TournamentResultDao { @Override public List<TournamentResult> fetchAllByYear(Integer year) { String sql = "SELECT t.* FROM " + TABLE_NAME + " t WHERE t.year = ? ORDER BY t.game_date"; Object[] args = { year }; List<TournamentResult> results = getJdbcTemplate().query(sql, new TournamentResultRowMapper(), args); return results; } TournamentResultJdbcDao(DataSource dataSource); @Override List<TournamentResult> fetchAllByYear(Integer year); }### Answer:
@Test public void testFetchAllByYear_2011() { log.info("*** BEGIN Test ***"); Integer year = 2011; List<TournamentResult> results = classUnderTest.fetchAllByYear(year); assertEquals(67, results.size()); log.info("*** END Test ***"); }
@Test public void testFetchAllByYear_2012() { log.info("*** BEGIN Test ***"); Integer year = 2012; List<TournamentResult> results = classUnderTest.fetchAllByYear(year); assertEquals(67, results.size()); log.info("*** END Test ***"); }
@Test public void testFetchAllByYear_2013() { log.info("*** BEGIN Test ***"); Integer year = 2013; List<TournamentResult> results = classUnderTest.fetchAllByYear(year); assertEquals(67, results.size()); log.info("*** END Test ***"); }
@Test public void testFetchAllByYear_2014() { log.info("*** BEGIN Test ***"); Integer year = 2014; List<TournamentResult> results = classUnderTest.fetchAllByYear(year); assertEquals(67, results.size()); log.info("*** END Test ***"); }
@Test public void testFetchAllByYear_2015() { log.info("*** BEGIN Test ***"); Integer year = 2015; List<TournamentResult> results = classUnderTest.fetchAllByYear(year); assertEquals(67, results.size()); log.info("*** END Test ***"); }
@Test public void testFetchAllByYear_2016() { log.info("*** BEGIN Test ***"); Integer year = 2016; List<TournamentResult> results = classUnderTest.fetchAllByYear(year); assertEquals(67, results.size()); log.info("*** END Test ***"); } |
### Question:
MlpNetworkTrainer implements LearningEventListener { protected static Integer[] computeYearsToTrain(String[] args) { Integer[] ret = new Integer[args.length - 1]; for (int aa = 0; aa < args.length - 1; aa++) { Integer year = Integer.valueOf(args[aa]); NetworkUtils.validateYear(year); ret[aa] = year; } return ret; } MlpNetworkTrainer(ApplicationContext applicationContext); SeasonData pullSeasonData(Integer year, String teamName); List<TournamentResult> pullTournamentResults(Integer year); SeasonAnalytics pullSeasonAnalytics(Integer year); static void main(String[] args); void go(String[] args); @SuppressWarnings("unchecked") @Override void handleLearningEvent(LearningEvent event); static final TransferFunctionType NEURON_PROPERTY_TRANSFER_FUNCTION; }### Answer:
@Test public void testComputeYearsToTrain() { String[] args = { "2010", "2011", "2012", "2013,2014" }; Integer[] expectedYearsToTrain = { 2010, 2011, 2012 }; Integer[] actualYearsToTrain = MlpNetworkTrainer.computeYearsToTrain(args); assertArrayEquals(expectedYearsToTrain, actualYearsToTrain); } |
### Question:
MlpNetworkTrainer implements LearningEventListener { protected static Integer[] computeYearsToSimulate(String[] args) { Integer[] ret = null; String yearsToSimulate = args[args.length - 1]; StringTokenizer strtok = new StringTokenizer(yearsToSimulate, ","); List<Integer> yts = new ArrayList<>(); while (strtok.hasMoreTokens()) { Integer year = Integer.valueOf(strtok.nextToken()); NetworkUtils.validateYear(year); yts.add(year); } ret = yts.toArray(new Integer[yts.size()]); return ret; } MlpNetworkTrainer(ApplicationContext applicationContext); SeasonData pullSeasonData(Integer year, String teamName); List<TournamentResult> pullTournamentResults(Integer year); SeasonAnalytics pullSeasonAnalytics(Integer year); static void main(String[] args); void go(String[] args); @SuppressWarnings("unchecked") @Override void handleLearningEvent(LearningEvent event); static final TransferFunctionType NEURON_PROPERTY_TRANSFER_FUNCTION; }### Answer:
@Test public void testComputeYearsToSimulate() { String[] args = { "2010", "2011", "2012", "2013,2014" }; Integer[] expectedYearsToSimulate = { 2013, 2014 }; Integer[] actualYearsToSimulate = MlpNetworkTrainer.computeYearsToSimulate(args); assertArrayEquals(expectedYearsToSimulate, actualYearsToSimulate); } |
### Question:
HttpResponseParser { static String parseCreatedIndexResponse(HttpEntity entity) { return JsonHandler.readValue(entity).get(Field.INDEX); } }### Answer:
@Test public void parseCreatedIndexResponseTest() { String path = "/responses/create-index.json"; String index = HttpResponseParser.parseCreatedIndexResponse(getEntityFromResponse(path)); assertEquals("idxtest", index); } |
### Question:
GrscicollInterpreter { @VisibleForTesting static OccurrenceIssue getInstitutionMatchNoneIssue(Status status) { if (status == Status.AMBIGUOUS || status == Status.AMBIGUOUS_MACHINE_TAGS) { return OccurrenceIssue.AMBIGUOUS_INSTITUTION; } if (status == Status.AMBIGUOUS_OWNER) { return OccurrenceIssue.POSSIBLY_ON_LOAN; } return OccurrenceIssue.INSTITUTION_MATCH_NONE; } static BiConsumer<ExtendedRecord, GrscicollRecord> grscicollInterpreter(
KeyValueStore<GrscicollLookupRequest, GrscicollLookupResponse> kvStore, MetadataRecord mdr); }### Answer:
@Test public void getInstitutionMatchNoneIssuesTest() { assertEquals( OccurrenceIssue.INSTITUTION_MATCH_NONE, GrscicollInterpreter.getInstitutionMatchNoneIssue(null)); assertEquals( OccurrenceIssue.AMBIGUOUS_INSTITUTION, GrscicollInterpreter.getInstitutionMatchNoneIssue(Status.AMBIGUOUS)); assertEquals( OccurrenceIssue.AMBIGUOUS_INSTITUTION, GrscicollInterpreter.getInstitutionMatchNoneIssue(Status.AMBIGUOUS_MACHINE_TAGS)); assertEquals( OccurrenceIssue.POSSIBLY_ON_LOAN, GrscicollInterpreter.getInstitutionMatchNoneIssue(Status.AMBIGUOUS_OWNER)); } |
### Question:
GrscicollInterpreter { @VisibleForTesting static OccurrenceIssue getCollectionMatchNoneIssue(Status status) { if (status == Status.AMBIGUOUS || status == Status.AMBIGUOUS_MACHINE_TAGS) { return OccurrenceIssue.AMBIGUOUS_COLLECTION; } if (status == Status.AMBIGUOUS_INSTITUTION_MISMATCH) { return OccurrenceIssue.INSTITUTION_COLLECTION_MISMATCH; } return OccurrenceIssue.COLLECTION_MATCH_NONE; } static BiConsumer<ExtendedRecord, GrscicollRecord> grscicollInterpreter(
KeyValueStore<GrscicollLookupRequest, GrscicollLookupResponse> kvStore, MetadataRecord mdr); }### Answer:
@Test public void getCollectionMatchNoneIssuesTest() { assertEquals( OccurrenceIssue.COLLECTION_MATCH_NONE, GrscicollInterpreter.getCollectionMatchNoneIssue(null)); assertEquals( OccurrenceIssue.AMBIGUOUS_COLLECTION, GrscicollInterpreter.getCollectionMatchNoneIssue(Status.AMBIGUOUS)); assertEquals( OccurrenceIssue.AMBIGUOUS_COLLECTION, GrscicollInterpreter.getCollectionMatchNoneIssue(Status.AMBIGUOUS_MACHINE_TAGS)); assertEquals( OccurrenceIssue.INSTITUTION_COLLECTION_MISMATCH, GrscicollInterpreter.getCollectionMatchNoneIssue(Status.AMBIGUOUS_INSTITUTION_MISMATCH)); } |
### Question:
EsClient implements AutoCloseable { public static EsClient from(EsConfig config) { return new EsClient(config); } private EsClient(EsConfig config); static EsClient from(EsConfig config); Response performGetRequest(String endpoint); Response performPutRequest(String endpoint, Map<String, String> params, HttpEntity body); Response performPostRequest(String endpoint, Map<String, String> params, HttpEntity body); Response performDeleteRequest(String endpoint); @Override @SneakyThrows void close(); }### Answer:
@Test(expected = IllegalArgumentException.class) public void createClientFromEmptyHostsTest() { EsClient.from(EsConfig.from()); }
@Test(expected = NullPointerException.class) public void createClientFromNullConfigTest() { EsClient.from(null); } |
### Question:
TaxonomyInterpreter { @VisibleForTesting protected static boolean checkFuzzy(NameUsageMatch usageMatch, SpeciesMatchRequest matchRequest) { boolean isFuzzy = MatchType.FUZZY == usageMatch.getDiagnostics().getMatchType(); boolean isEmptyTaxa = Strings.isNullOrEmpty(matchRequest.getKingdom()) && Strings.isNullOrEmpty(matchRequest.getPhylum()) && Strings.isNullOrEmpty(matchRequest.getClazz()) && Strings.isNullOrEmpty(matchRequest.getOrder()) && Strings.isNullOrEmpty(matchRequest.getFamily()); return isFuzzy && isEmptyTaxa; } static BiConsumer<ExtendedRecord, TaxonRecord> taxonomyInterpreter(
KeyValueStore<SpeciesMatchRequest, NameUsageMatch> kvStore); }### Answer:
@Test public void checkFuzzyPositiveTest() { SpeciesMatchRequest matchRequest = SpeciesMatchRequest.builder() .withKingdom("") .withPhylum("") .withClazz("") .withOrder("") .withFamily("") .withGenus("something") .build(); NameUsageMatch usageMatch = new NameUsageMatch(); Diagnostics diagnostics = new Diagnostics(); diagnostics.setMatchType(MatchType.FUZZY); usageMatch.setDiagnostics(diagnostics); boolean result = TaxonomyInterpreter.checkFuzzy(usageMatch, matchRequest); Assert.assertTrue(result); }
@Test public void checkFuzzyNegativeTest() { SpeciesMatchRequest matchRequest = SpeciesMatchRequest.builder() .withKingdom("") .withPhylum("") .withClazz("") .withOrder("") .withFamily("something") .withGenus("something") .build(); NameUsageMatch usageMatch = new NameUsageMatch(); Diagnostics diagnostics = new Diagnostics(); diagnostics.setMatchType(MatchType.FUZZY); usageMatch.setDiagnostics(diagnostics); boolean result = TaxonomyInterpreter.checkFuzzy(usageMatch, matchRequest); Assert.assertFalse(result); }
@Test public void checkFuzzyHighrankTest() { SpeciesMatchRequest matchRequest = SpeciesMatchRequest.builder() .withKingdom("") .withPhylum("") .withClazz("") .withOrder("") .withFamily("") .withGenus("something") .build(); NameUsageMatch usageMatch = new NameUsageMatch(); Diagnostics diagnostics = new Diagnostics(); diagnostics.setMatchType(MatchType.HIGHERRANK); usageMatch.setDiagnostics(diagnostics); boolean result = TaxonomyInterpreter.checkFuzzy(usageMatch, matchRequest); Assert.assertFalse(result); } |
### Question:
EsConfig { public static EsConfig from(String... hostsAddresses) { return new EsConfig(hostsAddresses); } private EsConfig(@NonNull String[] hostsAddresses); static EsConfig from(String... hostsAddresses); List<URL> getHosts(); String[] getRawHosts(); }### Answer:
@Test(expected = NullPointerException.class) public void createConfigNullHostsTest() { EsConfig.from((String[]) null); }
@Test(expected = IllegalArgumentException.class) public void createConfigInvalidHostsTest() { EsConfig.from("wrong url"); thrown.expectMessage(CoreMatchers.containsString("is not a valid url")); } |
### Question:
OccurrenceHdfsRecordConverter { private static BiConsumer<OccurrenceHdfsRecord, SpecificRecordBase> multimediaMapper() { return (hr, sr) -> { MultimediaRecord mr = (MultimediaRecord) sr; List<String> mediaTypes = mr.getMultimediaItems().stream() .filter(i -> !Strings.isNullOrEmpty(i.getType())) .map(Multimedia::getType) .map(TextNode::valueOf) .map(TextNode::asText) .collect(Collectors.toList()); hr.setExtMultimedia(MediaSerDeserUtils.toJson(mr.getMultimediaItems())); setCreatedIfGreater(hr, mr.getCreated()); hr.setMediatype(mediaTypes); }; } static OccurrenceHdfsRecord toOccurrenceHdfsRecord(SpecificRecordBase... records); }### Answer:
@Test public void multimediaMapperTest() { MultimediaRecord multimediaRecord = new MultimediaRecord(); multimediaRecord.setId("1"); Multimedia multimedia = new Multimedia(); multimedia.setType(MediaType.StillImage.name()); multimedia.setLicense(License.CC_BY_4_0.name()); multimedia.setSource("image.jpg"); multimediaRecord.setMultimediaItems(Collections.singletonList(multimedia)); OccurrenceHdfsRecord hdfsRecord = toOccurrenceHdfsRecord(multimediaRecord); List<Multimedia> media = MediaSerDeserUtils.fromJson(hdfsRecord.getExtMultimedia()); Assert.assertEquals(media.get(0), multimedia); Assert.assertTrue(hdfsRecord.getMediatype().contains(MediaType.StillImage.name())); } |
### Question:
OccurrenceHdfsRecordConverter { private static BiConsumer<OccurrenceHdfsRecord, SpecificRecordBase> temporalMapper() { return (hr, sr) -> { TemporalRecord tr = (TemporalRecord) sr; Optional.ofNullable(tr.getDateIdentified()) .map(STRING_TO_DATE) .ifPresent(date -> hr.setDateidentified(date.getTime())); Optional.ofNullable(tr.getModified()) .map(STRING_TO_DATE) .ifPresent(date -> hr.setModified(date.getTime())); hr.setDay(tr.getDay()); hr.setMonth(tr.getMonth()); hr.setYear(tr.getYear()); if (Objects.nonNull(tr.getStartDayOfYear())) { hr.setStartdayofyear(tr.getStartDayOfYear().toString()); } else { hr.setStartdayofyear(null); } if (Objects.nonNull(tr.getEndDayOfYear())) { hr.setEnddayofyear(tr.getEndDayOfYear().toString()); } else { hr.setEnddayofyear(null); } if (tr.getEventDate() != null && tr.getEventDate().getGte() != null) { Optional.ofNullable(tr.getEventDate().getGte()) .map(STRING_TO_DATE) .ifPresent(eventDate -> hr.setEventdate(eventDate.getTime())); } else { TemporalUtils.getTemporal(tr.getYear(), tr.getMonth(), tr.getDay()) .map(TEMPORAL_TO_DATE) .ifPresent(eventDate -> hr.setEventdate(eventDate.getTime())); } setCreatedIfGreater(hr, tr.getCreated()); addIssues(tr.getIssues(), hr); }; } static OccurrenceHdfsRecord toOccurrenceHdfsRecord(SpecificRecordBase... records); }### Answer:
@Test public void temporalMapperTest() { String rawEventDate = "2019-01-01"; Long eventDate = LocalDate.of(2019, 1, 1).atStartOfDay().toInstant(ZoneOffset.UTC).toEpochMilli(); TemporalRecord temporalRecord = TemporalRecord.newBuilder() .setId("1") .setDay(1) .setYear(2019) .setMonth(1) .setStartDayOfYear(1) .setEventDate(EventDate.newBuilder().setLte(rawEventDate).build()) .setDateIdentified(rawEventDate) .setModified(rawEventDate) .build(); OccurrenceHdfsRecord hdfsRecord = toOccurrenceHdfsRecord(temporalRecord); Assert.assertEquals(Integer.valueOf(1), hdfsRecord.getDay()); Assert.assertEquals(Integer.valueOf(1), hdfsRecord.getMonth()); Assert.assertEquals(Integer.valueOf(2019), hdfsRecord.getYear()); Assert.assertEquals("1", hdfsRecord.getStartdayofyear()); Assert.assertEquals(eventDate, hdfsRecord.getEventdate()); Assert.assertEquals(eventDate, hdfsRecord.getDateidentified()); Assert.assertEquals(eventDate, hdfsRecord.getModified()); } |
### Question:
OccurrenceHdfsRecordConverter { private static BiConsumer<OccurrenceHdfsRecord, SpecificRecordBase> metadataMapper() { return (hr, sr) -> { MetadataRecord mr = (MetadataRecord) sr; hr.setCrawlid(mr.getCrawlId()); hr.setDatasetkey(mr.getDatasetKey()); hr.setDatasetname(mr.getDatasetTitle()); hr.setInstallationkey(mr.getInstallationKey()); hr.setProtocol(mr.getProtocol()); hr.setNetworkkey(mr.getNetworkKeys()); hr.setPublisher(mr.getPublisherTitle()); hr.setPublishingorgkey(mr.getPublishingOrganizationKey()); hr.setLastcrawled(mr.getLastCrawled()); hr.setProjectid(mr.getProjectId()); hr.setProgrammeacronym(mr.getProgrammeAcronym()); hr.setHostingorganizationkey(mr.getHostingOrganizationKey()); if (hr.getLicense() == null) { hr.setLicense(mr.getLicense()); } setCreatedIfGreater(hr, mr.getCreated()); addIssues(mr.getIssues(), hr); }; } static OccurrenceHdfsRecord toOccurrenceHdfsRecord(SpecificRecordBase... records); }### Answer:
@Test public void metadataMapperTest() { String datasetKey = UUID.randomUUID().toString(); String nodeKey = UUID.randomUUID().toString(); String installationKey = UUID.randomUUID().toString(); String organizationKey = UUID.randomUUID().toString(); List<String> networkKey = Collections.singletonList(UUID.randomUUID().toString()); MetadataRecord metadataRecord = MetadataRecord.newBuilder() .setId("1") .setDatasetKey(datasetKey) .setCrawlId(1) .setDatasetPublishingCountry(Country.COSTA_RICA.getIso2LetterCode()) .setLicense(License.CC_BY_4_0.name()) .setNetworkKeys(networkKey) .setDatasetTitle("TestDataset") .setEndorsingNodeKey(nodeKey) .setInstallationKey(installationKey) .setLastCrawled(new Date().getTime()) .setProtocol(EndpointType.DWC_ARCHIVE.name()) .setPublisherTitle("Pub") .setPublishingOrganizationKey(organizationKey) .build(); OccurrenceHdfsRecord hdfsRecord = toOccurrenceHdfsRecord(metadataRecord); Assert.assertEquals(datasetKey, hdfsRecord.getDatasetkey()); Assert.assertEquals(networkKey, hdfsRecord.getNetworkkey()); Assert.assertEquals(installationKey, hdfsRecord.getInstallationkey()); Assert.assertEquals(organizationKey, hdfsRecord.getPublishingorgkey()); Assert.assertEquals(License.CC_BY_4_0.name(), hdfsRecord.getLicense()); } |
### Question:
OccurrenceHdfsRecordConverter { public static OccurrenceHdfsRecord toOccurrenceHdfsRecord(SpecificRecordBase... records) { OccurrenceHdfsRecord occurrenceHdfsRecord = new OccurrenceHdfsRecord(); occurrenceHdfsRecord.setIssue(new ArrayList<>()); for (SpecificRecordBase record : records) { Optional.ofNullable(converters.get(record.getClass())) .ifPresent(consumer -> consumer.accept(occurrenceHdfsRecord, record)); } Optional<SpecificRecordBase> erOpt = Arrays.stream(records).filter(x -> x instanceof ExtendedRecord).findFirst(); Optional<SpecificRecordBase> brOpt = Arrays.stream(records).filter(x -> x instanceof BasicRecord).findFirst(); if (erOpt.isPresent() && brOpt.isPresent()) { setIdentifier((BasicRecord) brOpt.get(), (ExtendedRecord) erOpt.get(), occurrenceHdfsRecord); } return occurrenceHdfsRecord; } static OccurrenceHdfsRecord toOccurrenceHdfsRecord(SpecificRecordBase... records); }### Answer:
@Test public void issueMappingTest() { String[] issues = { OccurrenceIssue.IDENTIFIED_DATE_INVALID.name(), OccurrenceIssue.MODIFIED_DATE_INVALID.name(), OccurrenceIssue.RECORDED_DATE_UNLIKELY.name() }; TemporalRecord temporalRecord = TemporalRecord.newBuilder() .setId("1") .setDay(1) .setYear(2019) .setMonth(1) .setStartDayOfYear(1) .setIssues(IssueRecord.newBuilder().setIssueList(Arrays.asList(issues)).build()) .build(); OccurrenceHdfsRecord hdfsRecord = toOccurrenceHdfsRecord(temporalRecord); Assert.assertArrayEquals(issues, hdfsRecord.getIssue().toArray(new String[issues.length])); } |
### Question:
OccurrenceHdfsRecordConverter { private static BiConsumer<OccurrenceHdfsRecord, SpecificRecordBase> grscicollMapper() { return (hr, sr) -> { GrscicollRecord gr = (GrscicollRecord) sr; if (gr.getInstitutionMatch() != null) { Institution institution = gr.getInstitutionMatch().getInstitution(); if (institution != null) { hr.setInstitutionkey(institution.getKey()); } } if (gr.getCollectionMatch() != null) { Collection collection = gr.getCollectionMatch().getCollection(); if (collection != null) { hr.setCollectionkey(collection.getKey()); } } }; } static OccurrenceHdfsRecord toOccurrenceHdfsRecord(SpecificRecordBase... records); }### Answer:
@Test public void grscicollMapperTest() { Institution institution = Institution.newBuilder() .setCode("I1") .setKey("cb0098db-6ff6-4a5d-ad29-51348d114e41") .build(); InstitutionMatch institutionMatch = InstitutionMatch.newBuilder() .setInstitution(institution) .setMatchType(MatchType.EXACT.name()) .build(); Collection collection = Collection.newBuilder() .setKey("5c692584-d517-48e8-93a8-a916ba131d9b") .setCode("C1") .build(); CollectionMatch collectionMatch = CollectionMatch.newBuilder() .setCollection(collection) .setMatchType(MatchType.FUZZY.name()) .build(); GrscicollRecord record = GrscicollRecord.newBuilder() .setId("1") .setInstitutionMatch(institutionMatch) .setCollectionMatch(collectionMatch) .build(); OccurrenceHdfsRecord hdfsRecord = toOccurrenceHdfsRecord(record); Assert.assertEquals(institution.getKey(), hdfsRecord.getInstitutionkey()); Assert.assertEquals(collection.getKey(), hdfsRecord.getCollectionkey()); } |
### Question:
JsonConverter { @Override public String toString() { return toJson().toString(); } ObjectNode toJson(); @Override String toString(); }### Answer:
@Test public void createSimpleJsonFromSpecificRecordBase() { ExtendedRecord extendedRecord = ExtendedRecord.newBuilder().setId("777").setCoreRowType("core").build(); TemporalRecord temporalRecord = TemporalRecord.newBuilder() .setId("777") .setEventDate(EventDate.newBuilder().setLte("01-01-2018").setGte("01-01-2011").build()) .setDay(1) .setYear(2000) .setStartDayOfYear(1) .build(); LocationRecord locationRecord = LocationRecord.newBuilder() .setId("777") .setCountry("Country") .setCountryCode("Code 1'2\"") .setDecimalLatitude(1d) .setDecimalLongitude(2d) .build(); MetadataRecord metadataRecord = MetadataRecord.newBuilder() .setId("777") .setNetworkKeys(Collections.singletonList("NK1")) .build(); String expected = "{\"id\":\"777\",\"coreRowType\":\"core\",\"coreTerms\":\"{}\",\"extensions\":\"{}\",\"year\":2000," + "\"day\":1,\"eventDate\":{\"gte\":\"01-01-2011\",\"lte\":\"01-01-2018\"},\"startDayOfYear\":1," + "\"issues\":{},\"country\":\"Country\",\"countryCode\":\"Code 1'2\\\"\",\"decimalLatitude\":1.0," + "\"decimalLongitude\":2.0,\"networkKeys\":[\"NK1\"]}"; String result = JsonConverter.builder() .record(extendedRecord) .record(temporalRecord) .record(locationRecord) .record(metadataRecord) .build() .toString(); Assert.assertTrue(JsonValidationUtils.isValid(result)); Assert.assertEquals(expected, result); } |
### Question:
DwcaToAvroConverter extends ConverterToVerbatim { @Override protected long convert(Path inputPath, SyncDataFileWriter<ExtendedRecord> dataFileWriter) throws IOException { DwcaReader reader = DwcaReader.fromLocation(inputPath.toString()); log.info("Exporting the DwC Archive to Avro started {}", inputPath); while (reader.advance()) { ExtendedRecord record = reader.getCurrent(); if (!record.getId().equals(ExtendedRecordConverter.getRecordIdError())) { dataFileWriter.append(record); } } reader.close(); return reader.getRecordsReturned(); } static void main(String... args); }### Answer:
@Test public void avroDeserializingNoramlIdTest() throws IOException { DwcaToAvroConverter.create().inputPath(inpPath).outputPath(outPath).convert(); File verbatim = new File(outPath); Assert.assertTrue(verbatim.exists()); DatumReader<ExtendedRecord> datumReader = new SpecificDatumReader<>(ExtendedRecord.class); try (DataFileReader<ExtendedRecord> dataFileReader = new DataFileReader<>(verbatim, datumReader)) { while (dataFileReader.hasNext()) { ExtendedRecord record = dataFileReader.next(); Assert.assertNotNull(record); Assert.assertNotNull(record.getId()); } } Files.deleteIfExists(verbatim.toPath()); } |
### Question:
OccurrenceExtensionConverter { public static Optional<ExtendedRecord> convert( Map<String, String> coreMap, Map<String, String> extMap) { String id = extMap.get(DwcTerm.occurrenceID.qualifiedName()); if (!Strings.isNullOrEmpty(id)) { ExtendedRecord extendedRecord = ExtendedRecord.newBuilder().setId(id).build(); extendedRecord.getCoreTerms().putAll(coreMap); extendedRecord.getCoreTerms().putAll(extMap); return Optional.of(extendedRecord); } return Optional.empty(); } static Optional<ExtendedRecord> convert(
Map<String, String> coreMap, Map<String, String> extMap); }### Answer:
@Test public void occurrenceAsExtensionTest() { String id = "1"; String somethingCore = "somethingCore"; String somethingExt = "somethingExt"; Map<String, String> coreMap = Collections.singletonMap(somethingCore, somethingCore); Map<String, String> extMap = new HashMap<>(2); extMap.put(DwcTerm.occurrenceID.qualifiedName(), id); extMap.put(somethingExt, somethingExt); Optional<ExtendedRecord> result = OccurrenceExtensionConverter.convert(coreMap, extMap); Assert.assertTrue(result.isPresent()); ExtendedRecord erResult = result.get(); Assert.assertEquals(id, erResult.getId()); Assert.assertEquals(somethingCore, erResult.getCoreTerms().get(somethingCore)); Assert.assertEquals(somethingExt, erResult.getCoreTerms().get(somethingExt)); } |
### Question:
AvroReader { public static <T extends Record> Map<String, T> readRecords( String hdfsSiteConfig, String coreSiteConfig, Class<T> clazz, String path) { FileSystem fs = FsUtils.getFileSystem(hdfsSiteConfig, coreSiteConfig, path); List<Path> paths = parseWildcardPath(fs, path); return readRecords(fs, clazz, paths); } static Map<String, T> readUniqueRecords(
String hdfsSiteConfig, String coreSiteConfig, Class<T> clazz, String path); static Map<String, T> readRecords(
String hdfsSiteConfig, String coreSiteConfig, Class<T> clazz, String path); }### Answer:
@Test public void regularExtendedRecordsTest() throws IOException { ExtendedRecord expectedOne = ExtendedRecord.newBuilder().setId("1").build(); ExtendedRecord expectedTwo = ExtendedRecord.newBuilder().setId("2").build(); ExtendedRecord expectedThree = ExtendedRecord.newBuilder().setId("3").build(); writeExtendedRecords(verbatimPath1, expectedOne, expectedTwo, expectedThree); Map<String, ExtendedRecord> result = AvroReader.readRecords("", "", ExtendedRecord.class, verbatimPath1.toString()); assertMap(result, expectedOne, expectedTwo, expectedThree); Files.deleteIfExists(Paths.get(verbatimPath1.toString())); }
@Test public void regularExtendedRecordsWildcardTest() throws IOException { ExtendedRecord expectedOne = ExtendedRecord.newBuilder().setId("1").build(); ExtendedRecord expectedTwo = ExtendedRecord.newBuilder().setId("2").build(); ExtendedRecord expectedThree = ExtendedRecord.newBuilder().setId("3").build(); ExtendedRecord expectedFour = ExtendedRecord.newBuilder().setId("4").build(); ExtendedRecord expectedFive = ExtendedRecord.newBuilder().setId("5").build(); ExtendedRecord expectedSix = ExtendedRecord.newBuilder().setId("6").build(); writeExtendedRecords(verbatimPath1, expectedOne, expectedTwo, expectedThree); writeExtendedRecords(verbatimPath2, expectedFour, expectedFive, expectedSix); Map<String, ExtendedRecord> result = AvroReader.readRecords( "", "", ExtendedRecord.class, new Path("target/verbatim*.avro").toString()); assertMap( result, expectedOne, expectedTwo, expectedThree, expectedFour, expectedFive, expectedSix); Files.deleteIfExists(Paths.get(verbatimPath1.toString())); Files.deleteIfExists(Paths.get(verbatimPath2.toString())); } |
### Question:
TemporalParser implements Serializable { protected static boolean isValidDate(TemporalAccessor temporalAccessor) { LocalDate upperBound = LocalDate.now().plusDays(1); return isValidDate(temporalAccessor, Range.closed(MIN_LOCAL_DATE, upperBound)); } private TemporalParser(List<DateComponentOrdering> orderings); static TemporalParser create(List<DateComponentOrdering> orderings); static TemporalParser create(); OccurrenceParseResult<TemporalAccessor> parseRecordedDate(
String year, String month, String day, String dateString); OccurrenceParseResult<TemporalAccessor> parseRecordedDate(String dateString); OccurrenceParseResult<TemporalAccessor> parseLocalDate(
String dateString, Range<LocalDate> likelyRange, OccurrenceIssue unlikelyIssue); }### Answer:
@Test public void testIsValidDate() { assertTrue(TemporalParser.isValidDate(Year.of(2005))); assertTrue(TemporalParser.isValidDate(YearMonth.of(2005, 1))); assertTrue(TemporalParser.isValidDate(LocalDate.of(2005, 1, 1))); assertTrue(TemporalParser.isValidDate(LocalDateTime.of(2005, 1, 1, 2, 3, 4))); assertTrue(TemporalParser.isValidDate(LocalDate.now())); assertTrue(TemporalParser.isValidDate(LocalDateTime.now().plus(23, ChronoUnit.HOURS))); assertFalse(TemporalParser.isValidDate(YearMonth.of(1599, 12))); assertFalse(TemporalParser.isValidDate(LocalDate.now().plusDays(2))); } |
### Question:
XmlToAvroConverter extends ConverterToVerbatim { @Override public long convert(Path inputPath, SyncDataFileWriter<ExtendedRecord> dataFileWriter) { return ExtendedRecordConverter.create(executor).toAvro(inputPath.toString(), dataFileWriter); } XmlToAvroConverter executor(ExecutorService executor); XmlToAvroConverter xmlReaderParallelism(int xmlReaderParallelism); static void main(String... args); @Override long convert(Path inputPath, SyncDataFileWriter<ExtendedRecord> dataFileWriter); }### Answer:
@Test public void avroDeserializingNoramlIdTest() throws IOException { String inputPath = inpPath + "61"; XmlToAvroConverter.create().inputPath(inputPath).outputPath(outPath).convert(); File verbatim = new File(outPath); Assert.assertTrue(verbatim.exists()); DatumReader<ExtendedRecord> datumReader = new SpecificDatumReader<>(ExtendedRecord.class); try (DataFileReader<ExtendedRecord> dataFileReader = new DataFileReader<>(verbatim, datumReader)) { while (dataFileReader.hasNext()) { ExtendedRecord record = dataFileReader.next(); Assert.assertNotNull(record); Assert.assertNotNull(record.getId()); Assert.assertTrue(record.getId().contains("catalog")); } } Files.deleteIfExists(verbatim.toPath()); } |
### Question:
WikidataValidator implements IdentifierSchemeValidator { @Override public boolean isValid(String value) { if (Strings.isNullOrEmpty(value)) { return false; } Matcher matcher = WIKIDATA_PATTERN.matcher(value); return matcher.matches(); } @Override boolean isValid(String value); @Override String normalize(String value); }### Answer:
@Test public void isValidTest() { WikidataValidator validator = new WikidataValidator(); assertTrue(validator.isValid("https: assertTrue(validator.isValid("https: assertTrue(validator.isValid("https: assertTrue(validator.isValid("http: assertTrue(validator.isValid("http: assertTrue(validator.isValid("http: assertTrue(validator.isValid("wikidata.org/wiki/Property:P569")); assertTrue(validator.isValid("www.wikidata.org/wiki/Lexeme:L1")); assertTrue(validator.isValid("www.wikidata.org/entity/ID")); assertFalse(validator.isValid(null)); assertFalse(validator.isValid("")); assertFalse(validator.isValid("http.wikidata.org/entity/ID")); assertFalse(validator.isValid("ftp: assertFalse(validator.isValid("http: assertFalse(validator.isValid("https: assertFalse(validator.isValid("https: assertFalse(validator.isValid("https: assertFalse(validator.isValid("http: assertFalse(validator.isValid("https: assertFalse(validator.isValid("awdawdawd")); } |
### Question:
WikidataValidator implements IdentifierSchemeValidator { @Override public String normalize(String value) { Preconditions.checkNotNull(value, "Identifier value can't be null"); String trimmedValue = value.trim(); Matcher matcher = WIKIDATA_PATTERN.matcher(trimmedValue); if (matcher.matches()) { return value; } throw new IllegalArgumentException(value + " it not a valid Wikidata"); } @Override boolean isValid(String value); @Override String normalize(String value); }### Answer:
@Test public void normalizeTest() { WikidataValidator validator = new WikidataValidator(); assertEquals( "https: validator.normalize("https: assertEquals( "https: validator.normalize("https: assertEquals( "https: validator.normalize("https: assertEquals( "http: validator.normalize("http: assertEquals( "http: validator.normalize("http: assertEquals( "http: validator.normalize("http: assertEquals( "wikidata.org/wiki/Property:P569", validator.normalize("wikidata.org/wiki/Property:P569")); assertEquals( "www.wikidata.org/wiki/Lexeme:L1", validator.normalize("www.wikidata.org/wiki/Lexeme:L1")); assertEquals("www.wikidata.org/entity/ID", validator.normalize("www.wikidata.org/entity/ID")); }
@Test(expected = IllegalArgumentException.class) public void normalizExeptionTest() { WikidataValidator validator = new WikidataValidator(); validator.normalize("awdawd"); } |
### Question:
AgentIdentifierParser { public static Set<AgentIdentifier> parse(String raw) { if (Strings.isNullOrEmpty(raw)) { return Collections.emptySet(); } return Stream.of(raw.split(DELIMITER)) .map(String::trim) .map(AgentIdentifierParser::parseValue) .collect(Collectors.toSet()); } static Set<AgentIdentifier> parse(String raw); }### Answer:
@Test public void parseNullTest() { Set<AgentIdentifier> set = AgentIdentifierParser.parse(null); assertTrue(set.isEmpty()); }
@Test public void parseEmptyTest() { String raw = ""; Set<AgentIdentifier> set = AgentIdentifierParser.parse(raw); assertTrue(set.isEmpty()); }
@Test public void parseEmptyDelimitrTest() { String raw = "|||"; Set<AgentIdentifier> set = AgentIdentifierParser.parse(raw); assertTrue(set.isEmpty()); }
@Test public void parseOrcidTest() { Set<AgentIdentifier> expected = Collections.singleton( AgentIdentifier.newBuilder() .setType(AgentIdentifierType.ORCID.name()) .setValue("https: .build()); String raw = "https: Set<AgentIdentifier> set = AgentIdentifierParser.parse(raw); assertFalse(set.isEmpty()); assertEquals(expected, set); }
@Test public void parseOrcidWithoutSchemaTest() { Set<AgentIdentifier> expected = Collections.singleton( AgentIdentifier.newBuilder() .setType(AgentIdentifierType.ORCID.name()) .setValue("https: .build()); String raw = "0000-0002-0144-1997"; Set<AgentIdentifier> set = AgentIdentifierParser.parse(raw); assertFalse(set.isEmpty()); assertEquals(expected, set); }
@Test public void parseWikidataTest() { Set<AgentIdentifier> expected = Collections.singleton( AgentIdentifier.newBuilder() .setType(AgentIdentifierType.WIKIDATA.name()) .setValue("https: .build()); String raw = "https: Set<AgentIdentifier> set = AgentIdentifierParser.parse(raw); assertFalse(set.isEmpty()); assertEquals(expected, set); }
@Test public void parseWikidataWithoutSchemaTest() { Set<AgentIdentifier> expected = Collections.singleton( AgentIdentifier.newBuilder() .setType(AgentIdentifierType.WIKIDATA.name()) .setValue("wikidata.org/wiki/0000") .build()); String raw = "wikidata.org/wiki/0000"; Set<AgentIdentifier> set = AgentIdentifierParser.parse(raw); assertFalse(set.isEmpty()); assertEquals(expected, set); }
@Test public void parseOtherTest() { Set<AgentIdentifier> expected = Collections.singleton( AgentIdentifier.newBuilder() .setType(AgentIdentifierType.OTHER.name()) .setValue("something") .build()); String raw = "something"; Set<AgentIdentifier> set = AgentIdentifierParser.parse(raw); assertFalse(set.isEmpty()); assertEquals(expected, set); }
@Test public void parseMixedTest() { Set<AgentIdentifier> expected = Stream.of( AgentIdentifier.newBuilder() .setType(AgentIdentifierType.ORCID.name()) .setValue("https: .build(), AgentIdentifier.newBuilder() .setType(AgentIdentifierType.WIKIDATA.name()) .setValue("wikidata.org/wiki/0000") .build(), AgentIdentifier.newBuilder() .setType(AgentIdentifierType.OTHER.name()) .setValue("something") .build()) .collect(Collectors.toSet()); String raw = "wikidata.org/wiki/0000| something|0000-0002-0144-1997"; Set<AgentIdentifier> set = AgentIdentifierParser.parse(raw); assertFalse(set.isEmpty()); assertEquals(expected, set); } |
### Question:
XmlSanitizingReader extends FilterReader { @Override public boolean ready() throws IOException { return (!endOfStreamReached && in.ready()); } XmlSanitizingReader(Reader in); @Override synchronized int read(); @Override synchronized int read(char[] buffer, int offset, int length); @Override boolean ready(); @Override synchronized void close(); @Override boolean markSupported(); }### Answer:
@Test public void testBadXmlFileReadWithBufferedReaderReadLines() throws IOException { String fileName = getClass().getResource("/responses/problematic/spanish_bad_xml.gz").getFile(); File file = new File(fileName); FileInputStream fis = new FileInputStream(file); GZIPInputStream inputStream = new GZIPInputStream(fis); StringBuilder sb = new StringBuilder(); try (BufferedReader buffReader = new BufferedReader( new XmlSanitizingReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)))) { while (buffReader.ready()) { String line = buffReader.readLine(); sb.append(line); } } assertEquals(6097, sb.toString().trim().length()); } |
### Question:
HashUtils { public static String getSha1(String... strings) { return getHash("SHA-1", strings); } static String getSha1(String... strings); }### Answer:
@Test public void sha1Test() { String value = "af91c6ca-da34-4e49-ace3-3b125dbeab3c"; String expected = "3521a4e173f1c42a18d431d128720dc60e430a73"; String result = HashUtils.getSha1(value); Assert.assertEquals(expected, result); }
@Test public void sha1TwoValueTest() { String value1 = "af91c6ca-da34-4e49-ace3-3b125dbeab3c"; String value2 = "f033adff-4dc4-4d20-9da0-4ed24cf59b61"; String expected = "74cf926f4871c8f98acf392b098e406ab82765b5"; String result = HashUtils.getSha1(value1, value2); Assert.assertEquals(expected, result); } |
### Question:
TemporalUtils { public static Optional<Temporal> getTemporal(Integer year, Integer month, Integer day) { try { if (year != null && month != null && day != null) { return Optional.of(LocalDate.of(year, month, day)); } if (year != null && month != null) { return Optional.of(YearMonth.of(year, month)); } if (year != null) { return Optional.of(Year.of(year)); } } catch (RuntimeException ex) { log.warn(ex.getLocalizedMessage()); } return Optional.empty(); } static Optional<Temporal> getTemporal(Integer year, Integer month, Integer day); }### Answer:
@Test public void nullTest() { Integer year = null; Integer month = null; Integer day = null; Optional<Temporal> temporal = TemporalUtils.getTemporal(year, month, day); assertFalse(temporal.isPresent()); }
@Test public void nullYearTest() { Integer year = null; Integer month = 10; Integer day = 1; Optional<Temporal> temporal = TemporalUtils.getTemporal(year, month, day); assertFalse(temporal.isPresent()); }
@Test public void nullYearMonthTest() { Integer year = null; Integer month = null; Integer day = 1; Optional<Temporal> temporal = TemporalUtils.getTemporal(year, month, day); assertFalse(temporal.isPresent()); }
@Test public void yearTest() { Integer year = 2000; Integer month = null; Integer day = null; Year expected = Year.of(year); Optional<Temporal> temporal = TemporalUtils.getTemporal(year, month, day); assertTrue(temporal.isPresent()); assertEquals(expected, temporal.get()); }
@Test public void yearMonthTest() { Integer year = 2000; Integer month = 10; Integer day = null; YearMonth expected = YearMonth.of(year, month); Optional<Temporal> temporal = TemporalUtils.getTemporal(year, month, day); assertTrue(temporal.isPresent()); assertEquals(expected, temporal.get()); }
@Test public void localDateTest() { Integer year = 2000; Integer month = 10; Integer day = 10; LocalDate expected = LocalDate.of(year, month, day); Optional<Temporal> temporal = TemporalUtils.getTemporal(year, month, day); assertTrue(temporal.isPresent()); assertEquals(expected, temporal.get()); }
@Test public void monthNullTest() { Integer year = 2000; Integer month = null; Integer day = 10; Year expected = Year.of(year); Optional<Temporal> temporal = TemporalUtils.getTemporal(year, month, day); assertTrue(temporal.isPresent()); assertEquals(expected, temporal.get()); }
@Test public void wrongDayMonthTest() { Integer year = 2000; Integer month = 11; Integer day = 31; Optional<Temporal> temporal = TemporalUtils.getTemporal(year, month, day); assertFalse(temporal.isPresent()); } |
### Question:
PropertyPrioritizer { protected static String findHighestPriority(Set<PrioritizedProperty> props) { return props.stream() .min( Comparator.comparing(PrioritizedProperty::getPriority) .thenComparing(PrioritizedProperty::getProperty)) .map(PrioritizedProperty::getProperty) .orElse(null); } abstract void resolvePriorities(); void addPrioritizedProperty(PrioritizedProperty prop); }### Answer:
@Test public void findHighestPriorityTest() { String expected = "Aa"; Set<PrioritizedProperty> set = new TreeSet<>(Comparator.comparing(PrioritizedProperty::getProperty)); set.add(new PrioritizedProperty(PrioritizedPropertyNameEnum.COLLECTOR_NAME, 1, "Aa")); set.add(new PrioritizedProperty(PrioritizedPropertyNameEnum.COLLECTOR_NAME, 1, "Bb")); set.add(new PrioritizedProperty(PrioritizedPropertyNameEnum.COLLECTOR_NAME, 1, "Cc")); String result = PropertyPrioritizer.findHighestPriority(set); Assert.assertEquals(expected, result); }
@Test public void reverseFindHighestPriorityTest() { String expected = "Aa"; Set<PrioritizedProperty> set = new TreeSet<>(Comparator.comparing(PrioritizedProperty::getProperty).reversed()); set.add(new PrioritizedProperty(PrioritizedPropertyNameEnum.COLLECTOR_NAME, 1, "Cc")); set.add(new PrioritizedProperty(PrioritizedPropertyNameEnum.COLLECTOR_NAME, 1, "Bb")); set.add(new PrioritizedProperty(PrioritizedPropertyNameEnum.COLLECTOR_NAME, 1, "Aa")); String result = PropertyPrioritizer.findHighestPriority(set); Assert.assertEquals(expected, result); } |
### Question:
IngestMetricsBuilder { public static IngestMetrics createInterpretedToEsIndexMetrics() { return IngestMetrics.create().addMetric(GbifJsonTransform.class, AVRO_TO_JSON_COUNT); } static IngestMetrics createVerbatimToInterpretedMetrics(); static IngestMetrics createInterpretedToEsIndexMetrics(); static IngestMetrics createInterpretedToHdfsViewMetrics(); }### Answer:
@Test public void createInterpretedToEsIndexMetricsTest() { IngestMetrics metrics = IngestMetricsBuilder.createInterpretedToEsIndexMetrics(); metrics.incMetric(AVRO_TO_JSON_COUNT); MetricResults result = metrics.getMetricsResult(); Map<String, Long> map = new HashMap<>(); result .allMetrics() .getCounters() .forEach(mr -> map.put(mr.getName().getName(), mr.getAttempted())); Assert.assertEquals(1, map.size()); Assert.assertEquals(Long.valueOf(1L), map.get(AVRO_TO_JSON_COUNT)); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.