src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
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> primaryKe... | @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); } |
PrincipalProvider extends AuditProvider { @Override public void prePersist(Object entity) { updatePrincipal(entity, true); } @Override void prePersist(Object entity); @Override void preUpdate(Object entity); } | @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(ent... |
PrincipalProvider extends AuditProvider { @Override public void preUpdate(Object entity) { updatePrincipal(entity, false); } @Override void prePersist(Object entity); @Override void preUpdate(Object entity); } | @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.getC... |
TimestampsProvider extends AuditProvider { @Override public void prePersist(Object entity) { updateTimestamps(entity, true); } @Override void prePersist(Object entity); @Override void preUpdate(Object entity); } | @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 = AuditProp... |
TimestampsProvider extends AuditProvider { @Override public void preUpdate(Object entity) { updateTimestamps(entity, false); } @Override void prePersist(Object entity); @Override void preUpdate(Object entity); } | @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()); } |
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 entityNa... | @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, re... |
ValueExpressionEvaluationInputStream extends InputStream { @Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { retu... | @Test public void testStreamWithoutExpression_mustBeUnmodified() throws Exception { final String data = "aa\nbbbb\ncccc\ndddd\n\n"; byte[] dataArray = data.getBytes(); ValueExpressionEvaluationInputStream inputStream = new ValueExpressionEvaluationInputStream( FacesContext.getCurrentInstance(), new ByteArrayInputStream... |
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.g... | @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 shouldRetrieve... |
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.ex... | @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.getN... |
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... | @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")); } |
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 { F... | @Test public void run() throws IOException, URISyntaxException { test.result = PropertyFileUtils.resolvePropertyFiles(test.file); test.run(); } |
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 @... | @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";... |
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 @Req... | @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(si... |
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... | @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()); } |
PluginRegisterService { public CompletableFuture<Response> register(Long userId, PluginReqisterQuery pluginReqisterQuery, PluginUpdate pluginUpdate, String authorization) { validateSubscription(pluginReqisterQuery); checkAuthServiceAvailable(); return persistPlugin(pluginUpdate, pluginReqisterQuery.constructFilterStrin... | @Test public void shouldRegisterPlugin() throws Exception { PluginReqisterQuery pluginReqisterQuery = new PluginReqisterQuery(); pluginReqisterQuery.setReturnCommands(true); pluginReqisterQuery.setReturnUpdatedCommands(true); pluginReqisterQuery.setReturnNotifications(true); PluginUpdate pluginUpdate = new PluginUpdate... |
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 form... | @Test public void findingInvalidFieldsReturnsInvalidOnes() { assertThat(formController.findInvalidFields()).containsExactly(INVALID_FIELD); } |
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 S... | @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(); } |
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... | @Test public void scheduleDisplaying() throws ExecutionException, InterruptedException { Stages.scheduleDisplaying(testStage) .thenAccept(stage -> assertThat(testStage.isShowing()).isTrue()) .toCompletableFuture().get(); } |
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 rootPan... | @Test public void scheduleHiding() throws ExecutionException, InterruptedException { Stages.scheduleHiding(testStage) .thenAccept(stage -> assertThat(testStage.isShowing()).isFalse()) .toCompletableFuture().get(); } |
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.getSt... | @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(); a... |
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 ... | @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(c... |
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> propertyFact... | @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 v... |
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 whe... | @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 ... |
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); } | @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 ... |
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 resourceRe... | @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(EXISTI... |
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 St... | @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 +... |
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 St... | @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()); } |
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 e... | @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.toComplet... |
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.upd... | @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 ComponentCe... |
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); } | @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()).i... |
StringFormFieldController extends FormFieldController<String> { @Override public void initialize() { validateValueOnChange(); } @Override void initialize(); abstract ObservableValue<String> getObservableValue(); @Override String getFieldValue(); } | @Test public void validatesOnEveryPropertyChangeByDefault() { sampleFieldController.initialize(); assertThat(validationCount.get()).isEqualTo(0); sampleProp.setValue("new value"); assertThat(validationCount.get()).isEqualTo(1); } |
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> onControllerLoa... | @Test public void getNode() { assertThat(fxmlLoadResult.getNode().get()).isEqualTo(TEST_NODE); } |
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, CONTROLL... | @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(); } |
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<CONTROLLE... | @Test public void getController() { assertThat(fxmlLoadResult.getController().get()).isEqualTo(TEST_CONTROLLER); } |
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> onControllerLoad... | @Test public void arity() { assertThat(fxmlLoadResult.arity()).isEqualTo(2); } |
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<C... | @Test public void toSeq() { assertThat( fxmlLoadResult.toSeq() .map(Try.class::cast) .map(Try::get) .toJavaList() ).containsExactlyInAnyOrder(TEST_NODE, TEST_CONTROLLER); } |
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 o... | @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); } |
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 onFail... | @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); } |
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 controllerMa... | @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.c... |
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(); } | @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(); } |
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(fi... | @Test public void registerSingle() { this.instanceManager.registerSingle(PARENT, ACTUAL_1); assertThat(this.instanceManager.getSingle(PARENT).get()).isEqualTo(ACTUAL_1); } |
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... | @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()).... |
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... | @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(... |
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... | @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); } |
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(); } | @Test public void start() throws Exception { TestFxApplication.main(); } |
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... | @Test public void startGui() { Platform.runLater(() -> testFxUiManager.startGui(stage)); } |
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); s... | @Test public void doOnFxThread() throws ExecutionException, InterruptedException { FxAsync.doOnFxThread( fxThread, expected -> assertThat(Thread.currentThread()).isEqualTo(expected) ).toCompletableFuture().get(); } |
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 Com... | @Test public void computeOnFxThread() throws ExecutionException, InterruptedException { FxAsync.computeOnFxThread( fxThread, expected -> assertThat(Thread.currentThread()).isEqualTo(expected) ).toCompletableFuture().get(); } |
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> ac... | @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)) .an... |
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 nod... | @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... |
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, ... | @Test public void centerNode() { Nodes.centerNode(this.testButton, MARGIN); } |
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 hideAndResize... | @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.setValu... |
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.c... | @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()); assertEqual... |
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); } | @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, l... |
JenkinsDefaultURLProvider { public String getDefaultJenkinsURL() { String jenkinsURL = getJENKINS_URL(); if (jenkinsURL != null && jenkinsURL.trim().length() > 0) { return jenkinsURL; } return getLocalhostURL(); } String getDefaultJenkinsURL(); String createDefaultURLDescription(); } | @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(... |
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... | @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_blubbe... |
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 = ""; JenkinsModelBui... | @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 = p... |
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); } | @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 v... |
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, ar... | @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 = 20... |
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 SeasonDataRowMapp... | @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 ... |
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> re... | @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 testFetchB... |
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 = getJdbcTemp... | @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.value... |
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().q... | @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... |
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; } Mlp... | @Test public void testComputeYearsToTrain() { String[] args = { "2010", "2011", "2012", "2013,2014" }; Integer[] expectedYearsToTrain = { 2010, 2011, 2012 }; Integer[] actualYearsToTrain = MlpNetworkTrainer.computeYearsToTrain(args); assertArrayEquals(expectedYearsToTrain, actualYearsToTrain); } |
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.hasMoreTo... | @Test public void testComputeYearsToSimulate() { String[] args = { "2010", "2011", "2012", "2013,2014" }; Integer[] expectedYearsToSimulate = { 2013, 2014 }; Integer[] actualYearsToSimulate = MlpNetworkTrainer.computeYearsToSimulate(args); assertArrayEquals(expectedYearsToSimulate, actualYearsToSimulate); } |
HttpResponseParser { static String parseCreatedIndexResponse(HttpEntity entity) { return JsonHandler.readValue(entity).get(Field.INDEX); } } | @Test public void parseCreatedIndexResponseTest() { String path = "/responses/create-index.json"; String index = HttpResponseParser.parseCreatedIndexResponse(getEntityFromResponse(path)); assertEquals("idxtest", index); } |
TemporalInterpreter implements Serializable { public void interpretTemporal(ExtendedRecord er, TemporalRecord tr) { String year = extractValue(er, DwcTerm.year); String month = extractValue(er, DwcTerm.month); String day = extractValue(er, DwcTerm.day); String eventDate = extractValue(er, DwcTerm.eventDate); String nor... | @Test public void testTextDate() { Map<String, String> map = new HashMap<>(); map.put(DwcTerm.eventDate.qualifiedName(), "Fri Aug 12 15:19:20 EST 2011"); ExtendedRecord er = ExtendedRecord.newBuilder().setId("1").setCoreTerms(map).build(); TemporalRecord tr = TemporalRecord.newBuilder().setId("1").build(); TemporalInte... |
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; } r... | @Test public void getInstitutionMatchNoneIssuesTest() { assertEquals( OccurrenceIssue.INSTITUTION_MATCH_NONE, GrscicollInterpreter.getInstitutionMatchNoneIssue(null)); assertEquals( OccurrenceIssue.AMBIGUOUS_INSTITUTION, GrscicollInterpreter.getInstitutionMatchNoneIssue(Status.AMBIGUOUS)); assertEquals( OccurrenceIssue... |
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.INSTITUT... | @Test public void getCollectionMatchNoneIssuesTest() { assertEquals( OccurrenceIssue.COLLECTION_MATCH_NONE, GrscicollInterpreter.getCollectionMatchNoneIssue(null)); assertEquals( OccurrenceIssue.AMBIGUOUS_COLLECTION, GrscicollInterpreter.getCollectionMatchNoneIssue(Status.AMBIGUOUS)); assertEquals( OccurrenceIssue.AMBI... |
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 bod... | @Test(expected = IllegalArgumentException.class) public void createClientFromEmptyHostsTest() { EsClient.from(EsConfig.from()); }
@Test(expected = NullPointerException.class) public void createClientFromNullConfigTest() { EsClient.from(null); } |
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(mat... | @Test public void checkFuzzyPositiveTest() { SpeciesMatchRequest matchRequest = SpeciesMatchRequest.builder() .withKingdom("") .withPhylum("") .withClazz("") .withOrder("") .withFamily("") .withGenus("something") .build(); NameUsageMatch usageMatch = new NameUsageMatch(); Diagnostics diagnostics = new Diagnostics(); di... |
GbifJsonConverter { public static String toStringPartialJson(SpecificRecordBase... records) { return toPartialJson(records).toString(); } static ObjectNode toJson(SpecificRecordBase... records); static ObjectNode toPartialJson(SpecificRecordBase... records); static String toStringJson(SpecificRecordBase... records); s... | @Test public void taxonRecordUsageTest() { String expected = "{" + "\"id\":\"777\"," + "\"all\":[\"T1\",\"Name\"]," + "\"verbatim\":{\"core\":{\"http: + "\"http: + "\"extensions\":{}}," + "\"gbifClassification\":{\"taxonID\":\"T1\"," + "\"verbatimScientificName\":\"Name\"," + "\"usage\":{\"key\":1," + "\"name\":\"n\","... |
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(); } | @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")); } |
MultimediaConverter { public static MultimediaRecord merge( @NonNull MultimediaRecord mr, @NonNull ImageRecord ir, @NonNull AudubonRecord ar) { MultimediaRecord record = MultimediaRecord.newBuilder().setId(mr.getId()).setCreated(mr.getCreated()).build(); boolean isMrEmpty = mr.getMultimediaItems() == null && mr.getIssu... | @Test(expected = NullPointerException.class) public void nullMergeTest() { MultimediaConverter.merge(null, null, null); }
@Test public void emptyMergeTest() { MultimediaRecord mr = MultimediaRecord.newBuilder().setId("777").build(); ImageRecord ir = ImageRecord.newBuilder().setId("777").build(); AudubonRecord ar = Audu... |
OccurrenceHdfsRecordConverter { private static BiConsumer<OccurrenceHdfsRecord, SpecificRecordBase> extendedRecordMapper() { return (hr, sr) -> { ExtendedRecord er = (ExtendedRecord) sr; er.getCoreTerms() .forEach( (k, v) -> Optional.ofNullable(TERM_FACTORY.findTerm(k)) .ifPresent( term -> { if (TermUtils.verbatimTerms... | @Test public void extendedRecordMapperTest() { Map<String, String> coreTerms = new HashMap<>(); coreTerms.put(DwcTerm.verbatimDepth.simpleName(), "1.0"); coreTerms.put(DwcTerm.collectionCode.simpleName(), "C1"); coreTerms.put(DwcTerm.institutionCode.simpleName(), "I1"); coreTerms.put(DwcTerm.catalogNumber.simpleName(),... |
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... | @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"); multimediaRec... |
OccurrenceHdfsRecordConverter { private static BiConsumer<OccurrenceHdfsRecord, SpecificRecordBase> basicRecordMapper() { return (hr, sr) -> { BasicRecord br = (BasicRecord) sr; if (Objects.nonNull(br.getGbifId())) { hr.setGbifid(br.getGbifId()); } hr.setBasisofrecord(br.getBasisOfRecord()); hr.setEstablishmentmeans(br... | @Test public void basicRecordMapperTest() { long now = new Date().getTime(); BasicRecord basicRecord = new BasicRecord(); basicRecord.setBasisOfRecord(BasisOfRecord.HUMAN_OBSERVATION.name()); basicRecord.setSex(Sex.HERMAPHRODITE.name()); basicRecord.setIndividualCount(99); basicRecord.setLifeStage(LifeStage.GAMETE.name... |
OccurrenceHdfsRecordConverter { private static BiConsumer<OccurrenceHdfsRecord, SpecificRecordBase> taxonMapper() { return (hr, sr) -> { TaxonRecord tr = (TaxonRecord) sr; Optional.ofNullable(tr.getUsage()).ifPresent(x -> hr.setTaxonkey(x.getKey())); if (Objects.nonNull(tr.getClassification())) { tr.getClassification()... | @Test public void taxonMapperTest() { List<RankedName> classification = new ArrayList<>(); classification.add( RankedName.newBuilder().setKey(2).setRank(Rank.KINGDOM).setName("Archaea").build()); classification.add( RankedName.newBuilder().setKey(79).setRank(Rank.PHYLUM).setName("Crenarchaeota").build()); classificatio... |
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.ofNulla... | @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) .setEventDa... |
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.get... | @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().to... |
OccurrenceHdfsRecordConverter { private static BiConsumer<OccurrenceHdfsRecord, SpecificRecordBase> locationMapper() { return (hr, sr) -> { LocationRecord lr = (LocationRecord) sr; hr.setCountrycode(lr.getCountryCode()); hr.setContinent(lr.getContinent()); hr.setDecimallatitude(lr.getDecimalLatitude()); hr.setDecimallo... | @Test public void locationMapperTest() { LocationRecord locationRecord = LocationRecord.newBuilder() .setId("1") .setCountry(Country.COSTA_RICA.name()) .setCountryCode(Country.COSTA_RICA.getIso2LetterCode()) .setDecimalLatitude(9.934739) .setDecimalLongitude(-84.087502) .setContinent(Continent.NORTH_AMERICA.name()) .se... |
OccurrenceHdfsRecordConverter { public static OccurrenceHdfsRecord toOccurrenceHdfsRecord(SpecificRecordBase... records) { OccurrenceHdfsRecord occurrenceHdfsRecord = new OccurrenceHdfsRecord(); occurrenceHdfsRecord.setIssue(new ArrayList<>()); for (SpecificRecordBase record : records) { Optional.ofNullable(converters.... | @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) .setSta... |
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) { ... | @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 ... |
JsonConverter { @Override public String toString() { return toJson().toString(); } ObjectNode toJson(); @Override String toString(); } | @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").b... |
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... | @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 (D... |
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(); extende... | @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.qualifiedNam... |
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); } sta... | @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(); writeExtendedRecord... |
AvroReader { public static <T extends Record> Map<String, T> readUniqueRecords( String hdfsSiteConfig, String coreSiteConfig, Class<T> clazz, String path) { FileSystem fs = FsUtils.getFileSystem(hdfsSiteConfig, coreSiteConfig, path); List<Path> paths = parseWildcardPath(fs, path); return readUniqueRecords(fs, clazz, pa... | @Test public void uniqueExtendedRecordsTest() throws IOException { ExtendedRecord expectedOne = ExtendedRecord.newBuilder().setId("1").build(); ExtendedRecord expectedTwo = ExtendedRecord.newBuilder().setId("2").build(); ExtendedRecord expectedThree = ExtendedRecord.newBuilder().setId("3").build(); writeExtendedRecords... |
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 ... | @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(Temporal... |
TemporalParser implements Serializable { public OccurrenceParseResult<TemporalAccessor> parseRecordedDate( String year, String month, String day, String dateString) { boolean atomizedDateProvided = StringUtils.isNotBlank(year) || StringUtils.isNotBlank(month) || StringUtils.isNotBlank(day); boolean dateStringProvided =... | @Test public void testParseRecordedDate() { TemporalParser temporalParser = TemporalParser.create(); OccurrenceParseResult<TemporalAccessor> result; result = temporalParser.parseRecordedDate("2005", "1", "", "2005-01-01"); assertEquals(LocalDate.of(2005, 1, 1), result.getPayload()); assertEquals(0, result.getIssues().s... |
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 x... | @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 SpecificDatumRe... |
TemporalRangeParser implements Serializable { public EventRange parse(String dateRange) { return parse(null, null, null, dateRange); } @Builder(buildMethodName = "create") private TemporalRangeParser(TemporalParser temporalParser); EventRange parse(String dateRange); EventRange parse(String year, String month, String ... | @Test public void singleDateRangeTest() { TemporalRangeParser trp = TemporalRangeParser.builder() .temporalParser(TemporalParser.create(Collections.singletonList(DMY))) .create(); EventRange range = trp.parse("1930/1929"); assertEquals("1930", range.getFrom().get().toString()); assertFalse(range.getTo().isPresent()); r... |
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);... | @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(v... |
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... | @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.... |
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 ra... | @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() { Stri... |
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 s... | @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);... |
HashUtils { public static String getSha1(String... strings) { return getHash("SHA-1", strings); } static String getSha1(String... strings); } | @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-3b125dbea... |
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)... | @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> te... |
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 resolvePrioritie... | @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.C... |
IngestMetricsBuilder { public static IngestMetrics createVerbatimToInterpretedMetrics() { return IngestMetrics.create() .addMetric(BasicTransform.class, BASIC_RECORDS_COUNT) .addMetric(LocationTransform.class, LOCATION_RECORDS_COUNT) .addMetric(MetadataTransform.class, METADATA_RECORDS_COUNT) .addMetric(TaxonomyTransfo... | @Test public void createVerbatimToInterpretedMetricsTest() { IngestMetrics metrics = IngestMetricsBuilder.createVerbatimToInterpretedMetrics(); metrics.incMetric(BASIC_RECORDS_COUNT); metrics.incMetric(LOCATION_RECORDS_COUNT); metrics.incMetric(METADATA_RECORDS_COUNT); metrics.incMetric(TAXON_RECORDS_COUNT); metrics.in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.