method2testcases
stringlengths 118
3.08k
|
---|
### 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:
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 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:
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:
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:
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:
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:
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:
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:
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 { 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:
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:
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:
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)); } |
### Question:
IngestMetricsBuilder { public static IngestMetrics createInterpretedToHdfsViewMetrics() { return IngestMetrics.create() .addMetric(OccurrenceHdfsRecordConverterTransform.class, AVRO_TO_HDFS_COUNT); } static IngestMetrics createVerbatimToInterpretedMetrics(); static IngestMetrics createInterpretedToEsIndexMetrics(); static IngestMetrics createInterpretedToHdfsViewMetrics(); }### Answer:
@Test public void createInterpretedToHdfsViewMetricsTest() { IngestMetrics metrics = IngestMetricsBuilder.createInterpretedToHdfsViewMetrics(); metrics.incMetric(AVRO_TO_HDFS_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_HDFS_COUNT)); } |
### Question:
Columns { public static String column(Term term) { if (term instanceof GbifInternalTerm || TermUtils.isOccurrenceJavaProperty(term) || GbifTerm.mediaType == term) { return column(term, ""); } else if (TermUtils.isInterpretedSourceTerm(term)) { throw new IllegalArgumentException( "The term " + term + " is interpreted and only relevant for verbatim values"); } else { return verbatimColumn(term); } } static String column(Term term); static String verbatimColumn(Term term); static final String OCCURRENCE_COLUMN_FAMILY; static final byte[] CF; static final String COUNTER_COLUMN; static final String LOOKUP_KEY_COLUMN; static final String LOOKUP_LOCK_COLUMN; static final String LOOKUP_STATUS_COLUMN; }### Answer:
@Test public void testGetColumn() { assertEquals("scientificName", Columns.column(DwcTerm.scientificName)); assertEquals("countryCode", Columns.column(DwcTerm.countryCode)); assertEquals("v_catalogNumber", Columns.column(DwcTerm.catalogNumber)); assertEquals("class", Columns.column(DwcTerm.class_)); assertEquals("order", Columns.column(DwcTerm.order)); assertEquals("kingdomKey", Columns.column(GbifTerm.kingdomKey)); assertEquals("taxonKey", Columns.column(GbifTerm.taxonKey)); assertEquals("v_occurrenceID", Columns.column(DwcTerm.occurrenceID)); assertEquals("v_taxonID", Columns.column(DwcTerm.taxonID)); assertEquals("basisOfRecord", Columns.column(DwcTerm.basisOfRecord)); assertEquals("taxonKey", Columns.column(GbifTerm.taxonKey)); }
@Test(expected = IllegalArgumentException.class) public void testGetColumnIllegal3() { Columns.column(DwcTerm.country); } |
### Question:
Columns { public static String verbatimColumn(Term term) { if (term instanceof GbifInternalTerm) { throw new IllegalArgumentException( "Internal terms (like the tried [" + term.simpleName() + "]) do not exist as verbatim columns"); } return column(term, VERBATIM_TERM_PREFIX); } static String column(Term term); static String verbatimColumn(Term term); static final String OCCURRENCE_COLUMN_FAMILY; static final byte[] CF; static final String COUNTER_COLUMN; static final String LOOKUP_KEY_COLUMN; static final String LOOKUP_LOCK_COLUMN; static final String LOOKUP_STATUS_COLUMN; }### Answer:
@Test(expected = IllegalArgumentException.class) public void testGetVerbatimColumnIllegal() { Columns.verbatimColumn(GbifInternalTerm.crawlId); }
@Test public void testGetVerbatimColumn() { assertEquals("v_basisOfRecord", Columns.verbatimColumn(DwcTerm.basisOfRecord)); } |
### Question:
XmlFragmentParser { public static List<RawOccurrenceRecord> parseRecord(RawXmlOccurrence xmlRecord) { return parseRecord(xmlRecord.getXml(), xmlRecord.getSchemaType()); } private XmlFragmentParser(); static List<RawOccurrenceRecord> parseRecord(RawXmlOccurrence xmlRecord); static List<RawOccurrenceRecord> parseRecord(String xml, OccurrenceSchemaType schemaType); static List<RawOccurrenceRecord> parseRecord(byte[] xml, OccurrenceSchemaType schemaType); static RawOccurrenceRecord parseRecord(
byte[] xml, OccurrenceSchemaType schemaType, String unitQualifier); static Set<IdentifierExtractionResult> extractIdentifiers(
UUID datasetKey,
byte[] xml,
OccurrenceSchemaType schemaType,
boolean useTriplet,
boolean useOccurrenceId); }### Answer:
@Test public void testUtf8a() throws IOException { String xml = Resources.toString( Resources.getResource("id_extraction/abcd1_umlaut.xml"), StandardCharsets.UTF_8); RawXmlOccurrence rawRecord = createFakeOcc(xml); List<RawOccurrenceRecord> results = XmlFragmentParser.parseRecord(rawRecord); assertEquals(1, results.size()); assertEquals("Oschütz", results.get(0).getCollectorName()); } |
### Question:
HttpResponseParser { static Set<String> parseIndexesInAliasResponse(HttpEntity entity) { return JsonHandler.readValue(entity).keySet(); } }### Answer:
@Test public void parseIndexesTest() { String path = "/responses/alias-indexes.json"; Set<String> indexes = HttpResponseParser.parseIndexesInAliasResponse(getEntityFromResponse(path)); assertEquals(2, indexes.size()); assertTrue(indexes.contains("idx1")); assertTrue(indexes.contains("idx2")); } |
### Question:
HashIdTransform extends DoFn<ExtendedRecord, ExtendedRecord> { public static SingleOutput<ExtendedRecord, ExtendedRecord> create(String datasetId) { return ParDo.of(new HashIdTransform(datasetId)); } static SingleOutput<ExtendedRecord, ExtendedRecord> create(String datasetId); @ProcessElement void processElement(@Element ExtendedRecord er, OutputReceiver<ExtendedRecord> out); }### Answer:
@Test public void hashIdTest() { final String datasetId = "f349d447-1c92-4637-ab32-8ae559497032"; final List<ExtendedRecord> input = createCollection("0001_1", "0002_2", "0003_3"); final List<ExtendedRecord> expected = createCollection( "20d8ab138ab4c919cbf32f5d9e667812077a0ee4_1", "1122dc31ba32e386e3a36719699fdb5fb1d2912f_2", "f2b1c436ad680263d74bf1498bf7433d9bb4b31a_3"); PCollection<ExtendedRecord> result = p.apply(Create.of(input)).apply(HashIdTransform.create(datasetId)); PAssert.that(result).containsInAnyOrder(expected); p.run(); } |
### Question:
MetadataServiceClientFactory { public static SerializableSupplier<MetadataServiceClient> getInstanceSupplier( PipelinesConfig config) { return () -> getInstance(config); } @SneakyThrows private MetadataServiceClientFactory(PipelinesConfig config); static MetadataServiceClient getInstance(PipelinesConfig config); static SerializableSupplier<MetadataServiceClient> createSupplier(PipelinesConfig config); static SerializableSupplier<MetadataServiceClient> getInstanceSupplier(
PipelinesConfig config); }### Answer:
@Test public void sameLinkToObjectTest() { PipelinesConfig pc = new PipelinesConfig(); WsConfig wc = new WsConfig(); wc.setWsUrl("https: pc.setGbifApi(wc); SerializableSupplier<MetadataServiceClient> supplierOne = MetadataServiceClientFactory.getInstanceSupplier(pc); SerializableSupplier<MetadataServiceClient> supplierTwo = MetadataServiceClientFactory.getInstanceSupplier(pc); Assert.assertSame(supplierOne.get(), supplierTwo.get()); } |
### Question:
MetadataServiceClientFactory { public static SerializableSupplier<MetadataServiceClient> createSupplier(PipelinesConfig config) { return () -> new MetadataServiceClientFactory(config).client; } @SneakyThrows private MetadataServiceClientFactory(PipelinesConfig config); static MetadataServiceClient getInstance(PipelinesConfig config); static SerializableSupplier<MetadataServiceClient> createSupplier(PipelinesConfig config); static SerializableSupplier<MetadataServiceClient> getInstanceSupplier(
PipelinesConfig config); }### Answer:
@Test public void newObjectTest() { PipelinesConfig pc = new PipelinesConfig(); WsConfig wc = new WsConfig(); wc.setWsUrl("https: pc.setGbifApi(wc); SerializableSupplier<MetadataServiceClient> supplierOne = MetadataServiceClientFactory.createSupplier(pc); SerializableSupplier<MetadataServiceClient> supplierTwo = MetadataServiceClientFactory.createSupplier(pc); Assert.assertNotSame(supplierOne.get(), supplierTwo.get()); } |
### Question:
LocationFeatureInterpreter { public static BiConsumer<LocationRecord, LocationFeatureRecord> interpret( KeyValueStore<LatLng, String> kvStore) { return (lr, asr) -> { if (kvStore != null) { try { String json = kvStore.get(new LatLng(lr.getDecimalLatitude(), lr.getDecimalLongitude())); if (!Strings.isNullOrEmpty(json)) { json = json.substring(11, json.length() - 1); ObjectMapper objectMapper = new ObjectMapper(); Map<String, String> map = objectMapper.readValue(json, new TypeReference<HashMap<String, String>>() {}); asr.setItems(map); } } catch (NoSuchElementException | NullPointerException | IOException ex) { log.error(ex.getMessage(), ex); } } }; } static BiConsumer<LocationRecord, LocationFeatureRecord> interpret(
KeyValueStore<LatLng, String> kvStore); }### Answer:
@Test public void locationFeaturesInterpreterTest() { LocationRecord locationRecord = LocationRecord.newBuilder().setId("777").build(); LocationFeatureRecord record = LocationFeatureRecord.newBuilder().setId("777").build(); KeyValueStore<LatLng, String> kvStore = new KeyValueStore<LatLng, String>() { @Override public String get(LatLng latLng) { return "{\"layers: \"{\"cb1\":\"1\",\"cb2\":\"2\",\"cb3\":\"3\"}}"; } @Override public void close() { } }; Map<String, String> resultMap = new HashMap<>(); resultMap.put("cb1", "1"); resultMap.put("cb2", "2"); resultMap.put("cb3", "3"); LocationFeatureRecord result = LocationFeatureRecord.newBuilder().setId("777").setItems(resultMap).build(); LocationFeatureInterpreter.interpret(kvStore).accept(locationRecord, record); Assert.assertEquals(result, record); } |
### Question:
EsIndex { public static long countDocuments(EsConfig config, String index) { Preconditions.checkArgument(!Strings.isNullOrEmpty(index), "index is required"); log.info("Counting documents from index {}", index); try (EsClient esClient = EsClient.from(config)) { return EsService.countIndexDocuments(esClient, index); } } static String createIndex(EsConfig config, IndexParams indexParams); static Optional<String> createIndexIfNotExists(EsConfig config, IndexParams indexParams); static void swapIndexInAliases(EsConfig config, Set<String> aliases, String index); static void swapIndexInAliases(
EsConfig config,
Set<String> aliases,
String index,
Set<String> extraIdxToRemove,
Map<String, String> settings); static long countDocuments(EsConfig config, String index); static Set<String> deleteRecordsByDatasetId(
EsConfig config,
String[] aliases,
String datasetKey,
Predicate<String> indexesToDelete,
int timeoutSec,
int attempts); static Set<String> findDatasetIndexesInAliases(
EsConfig config, String[] aliases, String datasetKey); }### Answer:
@Test(expected = IllegalArgumentException.class) public void countIndexDocumentsNullIndexTest() { EsIndex.countDocuments(EsConfig.from(DUMMY_HOST), null); thrown.expectMessage("index is required"); }
@Test(expected = IllegalArgumentException.class) public void countIndexDocumentsEmptyIndexTest() { EsIndex.countDocuments(EsConfig.from(DUMMY_HOST), ""); thrown.expectMessage("index is required"); } |
### Question:
ISwitchImpl implements ISwitch { @Override public void modState(SwitchChangeType state) throws SimulatorException { this.state = state; switch (state) { case ADDED: break; case ACTIVATED: activate(); break; case DEACTIVATED: case REMOVED: deactivate(); break; case CHANGED: throw new SimulatorException("Received modState of CHANGED, no idea why"); default: throw new SimulatorException(String.format("Unknown state %s", state)); } } ISwitchImpl(); ISwitchImpl(SwitchId dpid); ISwitchImpl(SwitchId dpid, int numOfPorts, PortStateType portState); @Override void modState(SwitchChangeType state); @Override void activate(); @Override void deactivate(); @Override boolean isActive(); @Override int getControlPlaneLatency(); @Override void setControlPlaneLatency(int controlPlaneLatency); @Override DatapathId getDpid(); @Override String getDpidAsString(); @Override void setDpid(DatapathId dpid); @Override void setDpid(SwitchId dpid); @Override List<IPortImpl> getPorts(); @Override IPortImpl getPort(int portNum); @Override int addPort(IPortImpl port); @Override int getMaxPorts(); @Override void setMaxPorts(int maxPorts); @Override Map<Long, IFlow> getFlows(); @Override IFlow getFlow(long cookie); @Override void addFlow(IFlow flow); @Override void modFlow(IFlow flow); @Override void delFlow(long cookie); @Override List<PortStatsEntry> getPortStats(); @Override PortStatsEntry getPortStats(int portNum); }### Answer:
@Test public void modState() throws Exception { sw.modState(SwitchChangeType.ACTIVATED); assertTrue(sw.isActive()); sw.modState(SwitchChangeType.DEACTIVATED); assertFalse(sw.isActive()); } |
### Question:
ISwitchImpl implements ISwitch { @Override public void setDpid(DatapathId dpid) { this.dpid = dpid; } ISwitchImpl(); ISwitchImpl(SwitchId dpid); ISwitchImpl(SwitchId dpid, int numOfPorts, PortStateType portState); @Override void modState(SwitchChangeType state); @Override void activate(); @Override void deactivate(); @Override boolean isActive(); @Override int getControlPlaneLatency(); @Override void setControlPlaneLatency(int controlPlaneLatency); @Override DatapathId getDpid(); @Override String getDpidAsString(); @Override void setDpid(DatapathId dpid); @Override void setDpid(SwitchId dpid); @Override List<IPortImpl> getPorts(); @Override IPortImpl getPort(int portNum); @Override int addPort(IPortImpl port); @Override int getMaxPorts(); @Override void setMaxPorts(int maxPorts); @Override Map<Long, IFlow> getFlows(); @Override IFlow getFlow(long cookie); @Override void addFlow(IFlow flow); @Override void modFlow(IFlow flow); @Override void delFlow(long cookie); @Override List<PortStatsEntry> getPortStats(); @Override PortStatsEntry getPortStats(int portNum); }### Answer:
@Test public void testSetDpid() { SwitchId newDpid = new SwitchId("01:02:03:04:05:06"); sw.setDpid(newDpid); assertEquals(newDpid.toString(), sw.getDpidAsString()); assertEquals(DatapathId.of(newDpid.toString()), sw.getDpid()); DatapathId dpid = sw.getDpid(); sw.setDpid(dpid); assertEquals(dpid, sw.getDpid()); } |
### Question:
ISwitchImpl implements ISwitch { @Override public int addPort(IPortImpl port) throws SimulatorException { if (ports.size() < maxPorts) { ports.add(port); } else { throw new SimulatorException(String.format("Switch already has reached maxPorts of %d" + "", maxPorts)); } return port.getNumber(); } ISwitchImpl(); ISwitchImpl(SwitchId dpid); ISwitchImpl(SwitchId dpid, int numOfPorts, PortStateType portState); @Override void modState(SwitchChangeType state); @Override void activate(); @Override void deactivate(); @Override boolean isActive(); @Override int getControlPlaneLatency(); @Override void setControlPlaneLatency(int controlPlaneLatency); @Override DatapathId getDpid(); @Override String getDpidAsString(); @Override void setDpid(DatapathId dpid); @Override void setDpid(SwitchId dpid); @Override List<IPortImpl> getPorts(); @Override IPortImpl getPort(int portNum); @Override int addPort(IPortImpl port); @Override int getMaxPorts(); @Override void setMaxPorts(int maxPorts); @Override Map<Long, IFlow> getFlows(); @Override IFlow getFlow(long cookie); @Override void addFlow(IFlow flow); @Override void modFlow(IFlow flow); @Override void delFlow(long cookie); @Override List<PortStatsEntry> getPortStats(); @Override PortStatsEntry getPortStats(int portNum); }### Answer:
@Test public void addPort() throws Exception { int portNum = sw.getPorts().size(); IPortImpl port = new IPortImpl(sw, PortStateType.UP, portNum); thrown.expect(SimulatorException.class); thrown.expectMessage("Switch already has reached maxPorts"); sw.addPort(port); } |
### Question:
ISwitchImpl implements ISwitch { @Override public IPortImpl getPort(int portNum) throws SimulatorException { try { return ports.get(portNum); } catch (IndexOutOfBoundsException e) { throw new SimulatorException(String.format("Port %d is not defined on %s", portNum, getDpidAsString())); } } ISwitchImpl(); ISwitchImpl(SwitchId dpid); ISwitchImpl(SwitchId dpid, int numOfPorts, PortStateType portState); @Override void modState(SwitchChangeType state); @Override void activate(); @Override void deactivate(); @Override boolean isActive(); @Override int getControlPlaneLatency(); @Override void setControlPlaneLatency(int controlPlaneLatency); @Override DatapathId getDpid(); @Override String getDpidAsString(); @Override void setDpid(DatapathId dpid); @Override void setDpid(SwitchId dpid); @Override List<IPortImpl> getPorts(); @Override IPortImpl getPort(int portNum); @Override int addPort(IPortImpl port); @Override int getMaxPorts(); @Override void setMaxPorts(int maxPorts); @Override Map<Long, IFlow> getFlows(); @Override IFlow getFlow(long cookie); @Override void addFlow(IFlow flow); @Override void modFlow(IFlow flow); @Override void delFlow(long cookie); @Override List<PortStatsEntry> getPortStats(); @Override PortStatsEntry getPortStats(int portNum); }### Answer:
@Test public void getPort() throws Exception { int numOfPorts = sw.getPorts().size(); assertEquals(1, sw.getPort(1).getNumber()); thrown.expect(SimulatorException.class); thrown.expectMessage(String.format("Port %d is not defined on %s", numOfPorts, sw.getDpidAsString())); sw.getPort(numOfPorts); } |
### Question:
ISwitchImpl implements ISwitch { @Override public IFlow getFlow(long cookie) throws SimulatorException { try { return flows.get(cookie); } catch (IndexOutOfBoundsException e) { throw new SimulatorException(String.format("Flow %d could not be found.", cookie)); } } ISwitchImpl(); ISwitchImpl(SwitchId dpid); ISwitchImpl(SwitchId dpid, int numOfPorts, PortStateType portState); @Override void modState(SwitchChangeType state); @Override void activate(); @Override void deactivate(); @Override boolean isActive(); @Override int getControlPlaneLatency(); @Override void setControlPlaneLatency(int controlPlaneLatency); @Override DatapathId getDpid(); @Override String getDpidAsString(); @Override void setDpid(DatapathId dpid); @Override void setDpid(SwitchId dpid); @Override List<IPortImpl> getPorts(); @Override IPortImpl getPort(int portNum); @Override int addPort(IPortImpl port); @Override int getMaxPorts(); @Override void setMaxPorts(int maxPorts); @Override Map<Long, IFlow> getFlows(); @Override IFlow getFlow(long cookie); @Override void addFlow(IFlow flow); @Override void modFlow(IFlow flow); @Override void delFlow(long cookie); @Override List<PortStatsEntry> getPortStats(); @Override PortStatsEntry getPortStats(int portNum); }### Answer:
@Test public void getFlow() { } |
### Question:
ISwitchImpl implements ISwitch { @Override public void addFlow(IFlow flow) throws SimulatorException { if (flows.containsKey(flow.getCookie())) { throw new SimulatorException(String.format("Flow %s already exists.", flow.toString())); } flows.put(flow.getCookie(), flow); } ISwitchImpl(); ISwitchImpl(SwitchId dpid); ISwitchImpl(SwitchId dpid, int numOfPorts, PortStateType portState); @Override void modState(SwitchChangeType state); @Override void activate(); @Override void deactivate(); @Override boolean isActive(); @Override int getControlPlaneLatency(); @Override void setControlPlaneLatency(int controlPlaneLatency); @Override DatapathId getDpid(); @Override String getDpidAsString(); @Override void setDpid(DatapathId dpid); @Override void setDpid(SwitchId dpid); @Override List<IPortImpl> getPorts(); @Override IPortImpl getPort(int portNum); @Override int addPort(IPortImpl port); @Override int getMaxPorts(); @Override void setMaxPorts(int maxPorts); @Override Map<Long, IFlow> getFlows(); @Override IFlow getFlow(long cookie); @Override void addFlow(IFlow flow); @Override void modFlow(IFlow flow); @Override void delFlow(long cookie); @Override List<PortStatsEntry> getPortStats(); @Override PortStatsEntry getPortStats(int portNum); }### Answer:
@Test public void addFlow() { } |
### Question:
ISwitchImpl implements ISwitch { @Override public void modFlow(IFlow flow) throws SimulatorException { delFlow(flow.getCookie()); addFlow(flow); } ISwitchImpl(); ISwitchImpl(SwitchId dpid); ISwitchImpl(SwitchId dpid, int numOfPorts, PortStateType portState); @Override void modState(SwitchChangeType state); @Override void activate(); @Override void deactivate(); @Override boolean isActive(); @Override int getControlPlaneLatency(); @Override void setControlPlaneLatency(int controlPlaneLatency); @Override DatapathId getDpid(); @Override String getDpidAsString(); @Override void setDpid(DatapathId dpid); @Override void setDpid(SwitchId dpid); @Override List<IPortImpl> getPorts(); @Override IPortImpl getPort(int portNum); @Override int addPort(IPortImpl port); @Override int getMaxPorts(); @Override void setMaxPorts(int maxPorts); @Override Map<Long, IFlow> getFlows(); @Override IFlow getFlow(long cookie); @Override void addFlow(IFlow flow); @Override void modFlow(IFlow flow); @Override void delFlow(long cookie); @Override List<PortStatsEntry> getPortStats(); @Override PortStatsEntry getPortStats(int portNum); }### Answer:
@Test public void modFlow() { } |
### Question:
ISwitchImpl implements ISwitch { @Override public void delFlow(long cookie) { flows.remove(cookie); } ISwitchImpl(); ISwitchImpl(SwitchId dpid); ISwitchImpl(SwitchId dpid, int numOfPorts, PortStateType portState); @Override void modState(SwitchChangeType state); @Override void activate(); @Override void deactivate(); @Override boolean isActive(); @Override int getControlPlaneLatency(); @Override void setControlPlaneLatency(int controlPlaneLatency); @Override DatapathId getDpid(); @Override String getDpidAsString(); @Override void setDpid(DatapathId dpid); @Override void setDpid(SwitchId dpid); @Override List<IPortImpl> getPorts(); @Override IPortImpl getPort(int portNum); @Override int addPort(IPortImpl port); @Override int getMaxPorts(); @Override void setMaxPorts(int maxPorts); @Override Map<Long, IFlow> getFlows(); @Override IFlow getFlow(long cookie); @Override void addFlow(IFlow flow); @Override void modFlow(IFlow flow); @Override void delFlow(long cookie); @Override List<PortStatsEntry> getPortStats(); @Override PortStatsEntry getPortStats(int portNum); }### Answer:
@Test public void delFlow() { } |
### Question:
ISwitchImpl implements ISwitch { @Override public List<PortStatsEntry> getPortStats() { return null; } ISwitchImpl(); ISwitchImpl(SwitchId dpid); ISwitchImpl(SwitchId dpid, int numOfPorts, PortStateType portState); @Override void modState(SwitchChangeType state); @Override void activate(); @Override void deactivate(); @Override boolean isActive(); @Override int getControlPlaneLatency(); @Override void setControlPlaneLatency(int controlPlaneLatency); @Override DatapathId getDpid(); @Override String getDpidAsString(); @Override void setDpid(DatapathId dpid); @Override void setDpid(SwitchId dpid); @Override List<IPortImpl> getPorts(); @Override IPortImpl getPort(int portNum); @Override int addPort(IPortImpl port); @Override int getMaxPorts(); @Override void setMaxPorts(int maxPorts); @Override Map<Long, IFlow> getFlows(); @Override IFlow getFlow(long cookie); @Override void addFlow(IFlow flow); @Override void modFlow(IFlow flow); @Override void delFlow(long cookie); @Override List<PortStatsEntry> getPortStats(); @Override PortStatsEntry getPortStats(int portNum); }### Answer:
@Test public void getPortStats() { } |
### Question:
IPortImpl implements IPort { @Override public boolean isActiveIsl() { return (peerSwitch != null && peerPortNum >= 0 && isActive && isForwarding); } IPortImpl(ISwitchImpl sw, PortStateType state, int portNumber); InfoMessage makePorChangetMessage(); @Override void enable(); @Override void disable(); @Override void block(); @Override void unblock(); void modPort(PortModMessage message); @Override boolean isActive(); @Override boolean isForwarding(); @Override int getNumber(); @Override void setLatency(int latency); @Override int getLatency(); @Override String getPeerSwitch(); @Override void setPeerSwitch(String peerSwitch); @Override void setPeerPortNum(int peerPortNum); @Override int getPeerPortNum(); @Override void setIsl(DatapathId peerSwitch, int peerPortNum); ISwitchImpl getSw(); void setSw(ISwitchImpl sw); @Override boolean isActiveIsl(); @Override PortStatsEntry getStats(); }### Answer:
@Test public void isActiveIsl() throws Exception { port.enable(); port.setPeerSwitch("00:00:00:00:00:01"); port.setPeerPortNum(10); assertTrue(port.isActiveIsl()); port.disable(); assertFalse(port.isActiveIsl()); port.enable(); port.block(); assertFalse(port.isActiveIsl()); port.unblock(); assertTrue(port.isActiveIsl()); port.disable(); port.unblock(); assertFalse(port.isActiveIsl()); } |
### Question:
IPortImpl implements IPort { @Override public PortStatsEntry getStats() { if (isForwarding && isActive) { this.rxPackets += rand.nextInt(MAX_LARGE); this.txPackets += rand.nextInt(MAX_LARGE); this.rxBytes += rand.nextInt(MAX_LARGE); this.txBytes += rand.nextInt(MAX_LARGE); this.rxDropped += rand.nextInt(MAX_SMALL); this.txDropped += rand.nextInt(MAX_SMALL); this.rxErrors += rand.nextInt(MAX_SMALL); this.txErrors += rand.nextInt(MAX_SMALL); this.rxFrameErr += rand.nextInt(MAX_SMALL); this.rxOverErr += rand.nextInt(MAX_SMALL); this.rxCrcErr += rand.nextInt(MAX_SMALL); this.collisions += rand.nextInt(MAX_SMALL); } return new PortStatsEntry(this.number, this.rxPackets, this.txPackets, this.rxBytes, this.txBytes, this.rxDropped, this.txDropped, this.rxErrors, this.txErrors, this.rxFrameErr, this.rxOverErr, this.rxCrcErr, this.collisions); } IPortImpl(ISwitchImpl sw, PortStateType state, int portNumber); InfoMessage makePorChangetMessage(); @Override void enable(); @Override void disable(); @Override void block(); @Override void unblock(); void modPort(PortModMessage message); @Override boolean isActive(); @Override boolean isForwarding(); @Override int getNumber(); @Override void setLatency(int latency); @Override int getLatency(); @Override String getPeerSwitch(); @Override void setPeerSwitch(String peerSwitch); @Override void setPeerPortNum(int peerPortNum); @Override int getPeerPortNum(); @Override void setIsl(DatapathId peerSwitch, int peerPortNum); ISwitchImpl getSw(); void setSw(ISwitchImpl sw); @Override boolean isActiveIsl(); @Override PortStatsEntry getStats(); }### Answer:
@Test public void getStats() throws Exception { } |
### Question:
SwitchValidateServiceImpl implements SwitchValidateService { @Override public void handleFlowEntriesResponse(String key, SwitchFlowEntries data) { handle(key, SwitchValidateEvent.RULES_RECEIVED, SwitchValidateContext.builder().flowEntries(data.getFlowEntries()).build()); } SwitchValidateServiceImpl(
SwitchManagerCarrier carrier, PersistenceManager persistenceManager, ValidationService validationService); @Override void handleSwitchValidateRequest(String key, SwitchValidateRequest request); @Override void handleFlowEntriesResponse(String key, SwitchFlowEntries data); @Override void handleGroupEntriesResponse(String key, SwitchGroupEntries data); @Override void handleExpectedDefaultFlowEntriesResponse(String key, SwitchExpectedDefaultFlowEntries data); @Override void handleExpectedDefaultMeterEntriesResponse(String key, SwitchExpectedDefaultMeterEntries data); @Override void handleMeterEntriesResponse(String key, SwitchMeterEntries data); @Override void handleMetersUnsupportedResponse(String key); @Override void handleTaskError(String key, ErrorMessage message); @Override void handleTaskTimeout(String key); }### Answer:
@Test public void receiveOnlyRules() { handleRequestAndInitDataReceive(); service.handleFlowEntriesResponse(KEY, new SwitchFlowEntries(SWITCH_ID, singletonList(flowEntry))); verifyNoMoreInteractions(carrier); verifyNoMoreInteractions(validationService); }
@Test public void doNothingWhenFsmNotFound() { service.handleFlowEntriesResponse(KEY, new SwitchFlowEntries(SWITCH_ID, singletonList(flowEntry))); verifyZeroInteractions(carrier); verifyZeroInteractions(validationService); } |
### Question:
SwitchValidateServiceImpl implements SwitchValidateService { @Override public void handleSwitchValidateRequest(String key, SwitchValidateRequest request) { SwitchValidateFsm fsm = builder.newStateMachine( SwitchValidateState.START, carrier, key, request, validationService, repositoryFactory); fsms.put(key, fsm); fsm.start(); handle(fsm, SwitchValidateEvent.NEXT, SwitchValidateContext.builder().build()); } SwitchValidateServiceImpl(
SwitchManagerCarrier carrier, PersistenceManager persistenceManager, ValidationService validationService); @Override void handleSwitchValidateRequest(String key, SwitchValidateRequest request); @Override void handleFlowEntriesResponse(String key, SwitchFlowEntries data); @Override void handleGroupEntriesResponse(String key, SwitchGroupEntries data); @Override void handleExpectedDefaultFlowEntriesResponse(String key, SwitchExpectedDefaultFlowEntries data); @Override void handleExpectedDefaultMeterEntriesResponse(String key, SwitchExpectedDefaultMeterEntries data); @Override void handleMeterEntriesResponse(String key, SwitchMeterEntries data); @Override void handleMetersUnsupportedResponse(String key); @Override void handleTaskError(String key, ErrorMessage message); @Override void handleTaskTimeout(String key); }### Answer:
@Test public void errorResponseOnSwitchNotFound() { request = SwitchValidateRequest .builder().switchId(SWITCH_ID_MISSING).performSync(true).processMeters(true).build(); service.handleSwitchValidateRequest(KEY, request); verify(carrier).cancelTimeoutCallback(eq(KEY)); verify(carrier).errorResponse( eq(KEY), eq(ErrorType.NOT_FOUND), eq(String.format("Switch '%s' not found", request.getSwitchId()))); verifyNoMoreInteractions(carrier); verifyNoMoreInteractions(validationService); } |
### Question:
SwitchSyncServiceImpl implements SwitchSyncService { @Override public void handleInstallRulesResponse(String key) { SwitchSyncFsm fsm = fsms.get(key); if (fsm == null) { logFsmNotFound(key); return; } fsm.fire(SwitchSyncEvent.RULES_INSTALLED); process(fsm); } SwitchSyncServiceImpl(SwitchManagerCarrier carrier, PersistenceManager persistenceManager,
FlowResourcesConfig flowResourcesConfig); @Override void handleSwitchSync(String key, SwitchValidateRequest request, ValidationResult validationResult); @Override void handleInstallRulesResponse(String key); @Override void handleRemoveRulesResponse(String key); @Override void handleReinstallDefaultRulesResponse(String key, FlowReinstallResponse response); @Override void handleRemoveMetersResponse(String key); @Override void handleTaskTimeout(String key); @Override void handleTaskError(String key, ErrorMessage message); }### Answer:
@Test public void doNothingWhenFsmNotFound() { service.handleInstallRulesResponse(KEY); verifyZeroInteractions(carrier); verifyZeroInteractions(commandBuilder); } |
### Question:
FlowPathStatusConverter implements AttributeConverter<FlowPathStatus, String> { @Override public String toGraphProperty(FlowPathStatus value) { if (value == null) { return null; } return value.name().toLowerCase(); } @Override String toGraphProperty(FlowPathStatus value); @Override FlowPathStatus toEntityAttribute(String value); }### Answer:
@Test public void shouldConvertToGraphProperty() { FlowPathStatusConverter converter = new FlowPathStatusConverter(); assertEquals("active", converter.toGraphProperty(FlowPathStatus.ACTIVE)); assertEquals("inactive", converter.toGraphProperty(FlowPathStatus.INACTIVE)); assertEquals("in_progress", converter.toGraphProperty(FlowPathStatus.IN_PROGRESS)); } |
### Question:
FlowPathStatusConverter implements AttributeConverter<FlowPathStatus, String> { @Override public FlowPathStatus toEntityAttribute(String value) { if (value == null || value.trim().isEmpty()) { return null; } return FlowPathStatus.valueOf(value.toUpperCase()); } @Override String toGraphProperty(FlowPathStatus value); @Override FlowPathStatus toEntityAttribute(String value); }### Answer:
@Test public void shouldConvertToEntity() { FlowPathStatusConverter converter = new FlowPathStatusConverter(); assertEquals(FlowPathStatus.ACTIVE, converter.toEntityAttribute("ACTIVE")); assertEquals(FlowPathStatus.ACTIVE, converter.toEntityAttribute("active")); assertEquals(FlowPathStatus.IN_PROGRESS, converter.toEntityAttribute("In_Progress")); } |
### Question:
PathIdConverter implements AttributeConverter<PathId, String> { @Override public String toGraphProperty(PathId value) { if (value == null) { return null; } return value.getId(); } @Override String toGraphProperty(PathId value); @Override PathId toEntityAttribute(String value); static final PathIdConverter INSTANCE; }### Answer:
@Test public void shouldConvertIdToString() { PathId pathId = new PathId("test_path_id"); String graphObject = PathIdConverter.INSTANCE.toGraphProperty(pathId); assertEquals(pathId.getId(), graphObject); } |
### Question:
PathIdConverter implements AttributeConverter<PathId, String> { @Override public PathId toEntityAttribute(String value) { if (value == null || value.trim().isEmpty()) { return null; } return new PathId(value); } @Override String toGraphProperty(PathId value); @Override PathId toEntityAttribute(String value); static final PathIdConverter INSTANCE; }### Answer:
@Test public void shouldConvertStringToId() { PathId pathId = new PathId("test_path_id"); PathId actualEntity = PathIdConverter.INSTANCE.toEntityAttribute(pathId.getId()); assertEquals(pathId, actualEntity); } |
### Question:
SwitchIdConverter implements AttributeConverter<SwitchId, String> { @Override public String toGraphProperty(SwitchId value) { if (value == null) { return null; } return value.toString(); } @Override String toGraphProperty(SwitchId value); @Override SwitchId toEntityAttribute(String value); static final SwitchIdConverter INSTANCE; }### Answer:
@Test public void shouldConvertIdToString() { SwitchId switchId = new SwitchId((long) 0x123); String graphObject = SwitchIdConverter.INSTANCE.toGraphProperty(switchId); assertEquals(switchId.toString(), graphObject); } |
### Question:
SwitchIdConverter implements AttributeConverter<SwitchId, String> { @Override public SwitchId toEntityAttribute(String value) { if (value == null || value.trim().isEmpty()) { return null; } return new SwitchId(value); } @Override String toGraphProperty(SwitchId value); @Override SwitchId toEntityAttribute(String value); static final SwitchIdConverter INSTANCE; }### Answer:
@Test public void shouldConvertStringToId() { SwitchId switchId = new SwitchId((long) 0x123); SwitchId actualEntity = SwitchIdConverter.INSTANCE.toEntityAttribute(switchId.toString()); assertEquals(switchId, actualEntity); } |
### Question:
FlowStatusConverter implements AttributeConverter<FlowStatus, String> { @Override public String toGraphProperty(FlowStatus value) { if (value == null) { return null; } return value.name().toLowerCase(); } @Override String toGraphProperty(FlowStatus value); @Override FlowStatus toEntityAttribute(String value); static final FlowStatusConverter INSTANCE; }### Answer:
@Test public void shouldConvertToGraphProperty() { FlowStatusConverter converter = FlowStatusConverter.INSTANCE; assertEquals("up", converter.toGraphProperty(FlowStatus.UP)); assertEquals("down", converter.toGraphProperty(FlowStatus.DOWN)); assertEquals("in_progress", converter.toGraphProperty(FlowStatus.IN_PROGRESS)); } |
### Question:
FlowStatusConverter implements AttributeConverter<FlowStatus, String> { @Override public FlowStatus toEntityAttribute(String value) { if (value == null || value.trim().isEmpty()) { return FlowStatus.UP; } return FlowStatus.valueOf(value.toUpperCase()); } @Override String toGraphProperty(FlowStatus value); @Override FlowStatus toEntityAttribute(String value); static final FlowStatusConverter INSTANCE; }### Answer:
@Test public void shouldConvertToEntity() { FlowStatusConverter converter = FlowStatusConverter.INSTANCE; assertEquals(FlowStatus.UP, converter.toEntityAttribute("UP")); assertEquals(FlowStatus.UP, converter.toEntityAttribute("up")); assertEquals(FlowStatus.IN_PROGRESS, converter.toEntityAttribute("In_Progress")); } |
### Question:
ExclusionCookieConverter implements AttributeConverter<ExclusionCookie, Long> { @Override public Long toGraphProperty(ExclusionCookie value) { if (value == null) { return null; } return value.getValue(); } @Override Long toGraphProperty(ExclusionCookie value); @Override ExclusionCookie toEntityAttribute(Long value); static final ExclusionCookieConverter INSTANCE; }### Answer:
@Test public void shouldConvertIdToLong() { ExclusionCookie cookie = new ExclusionCookie((long) 0x123); Long graphObject = new ExclusionCookieConverter().toGraphProperty(cookie); assertEquals(cookie.getValue(), (long) graphObject); } |
### Question:
ExclusionCookieConverter implements AttributeConverter<ExclusionCookie, Long> { @Override public ExclusionCookie toEntityAttribute(Long value) { if (value == null) { return null; } return new ExclusionCookie(value); } @Override Long toGraphProperty(ExclusionCookie value); @Override ExclusionCookie toEntityAttribute(Long value); static final ExclusionCookieConverter INSTANCE; }### Answer:
@Test public void shouldConvertLongToId() { ExclusionCookie cookie = new ExclusionCookie((long) 0x123); Cookie actualEntity = new ExclusionCookieConverter().toEntityAttribute(cookie.getValue()); assertEquals(cookie, actualEntity); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.