method2testcases stringlengths 118 3.08k |
|---|
### Question:
VCatLinkProvider extends AbstractLinkProvider { @Override public String provideLink(final String title) { return this.renderUrl + "?title=" + escapeMediawikiTitleForUrl(title) + this.renderParams; } protected VCatLinkProvider(final AbstractAllParams<?> all, final String renderUrl); VCatLinkProvider(final AbstractAllParams<?> all); String getRenderUrl(); @Override String provideLink(final String title); }### Answer:
@Test public void testProvideLink() { TestAllParams params = new TestAllParams(); params.putRequestParam("category", new String[] { "category" }); params.putRequestParam("ns", new String[] { "ns" }); params.putRequestParam("title", new String[] { "title" }); params.putRequestParam("a", new String[] { "1" }); params.putRequestParam("b", new String[] { "2", "3" }); params.putRequestParam("c", new String[] { "4", null }); VCatLinkProvider underTest = new VCatLinkProvider(params, "https: assertEquals("https: + "abc:%C3%84%C3%B6%C3%BC_%C3%9F%E3%83%A1%E3%82%A4%E3%83%B3%E3%83%9A%E3%83%BC%E3%82%B8" + "&a=1&b=2&b=3&c=4&c", underTest.provideLink("abc:Äöü ßメインページ")); } |
### Question:
RenderedFileCache extends AbstractFileCache<CombinedParams<W>> { @Override protected String getCacheFilename(CombinedParams<W> key) { return super.getCacheFilename(key) + '.' + key.getGraphviz().getOutputFormat().getFileExtension(); } RenderedFileCache(final File cacheDirectory, final int maxAgeInSeconds); }### Answer:
@Test public void testgetCacheFilename() throws CacheException { VCatParams<TestWiki> vCatParams = new VCatParams<>(); GraphvizParams graphvizParams = new GraphvizParams(); graphvizParams.setOutputFormat(OutputFormat.PNG); CombinedParams<TestWiki> key = new CombinedParams<>(vCatParams, graphvizParams); final String result = underTest.getCacheFilename(key); assertTrue(result.endsWith('.' + OutputFormat.PNG.getFileExtension())); } |
### Question:
ApiClient implements ICategoryProvider<W>, IMetadataProvider { @Override public Map<String, Collection<String>> requestCategories(W wiki, List<String> fullTitles, boolean showhidden) throws ApiException { Map<String, Collection<String>> categoryMap = new HashMap<>(); String clshow = showhidden ? null : "!hidden"; this.requestCategoriesRecursive(wiki.getApiUrl(), fullTitles, categoryMap, null, clshow); return categoryMap; } ApiClient(); @Override Map<String, Collection<String>> requestCategories(W wiki, List<String> fullTitles, boolean showhidden); @Override List<String> requestCategorymembers(final W wiki, final String fullTitle); Collection<Pair<String, String>> requestLinksBetween(W wiki, List<String> fullTitles); @Override Metadata requestMetadata(final IWiki wiki); }### Answer:
@Test public void testRequestCategories() throws ApiException { final List<String> fullTitles = new ArrayList<>(); fullTitles.add(PAGE_1); fullTitles.add(PAGE_2); final Map<String, Collection<String>> result = this.client.requestCategories(wiki, fullTitles, true); assertNotNull(result); assertNotEquals(0, result.size()); } |
### Question:
ApiClient implements ICategoryProvider<W>, IMetadataProvider { @Override public List<String> requestCategorymembers(final W wiki, final String fullTitle) throws ApiException { List<String> categories = new ArrayList<>(); this.requestCategorymembersRecursive(wiki.getApiUrl(), fullTitle, categories, null); return categories; } ApiClient(); @Override Map<String, Collection<String>> requestCategories(W wiki, List<String> fullTitles, boolean showhidden); @Override List<String> requestCategorymembers(final W wiki, final String fullTitle); Collection<Pair<String, String>> requestLinksBetween(W wiki, List<String> fullTitles); @Override Metadata requestMetadata(final IWiki wiki); }### Answer:
@Test public void testRequestCategorymembers() throws ApiException { final List<String> result = this.client.requestCategorymembers(wiki, CATEGORY_1); assertNotNull(result); assertNotEquals(0, result.size()); } |
### Question:
ApiClient implements ICategoryProvider<W>, IMetadataProvider { public Collection<Pair<String, String>> requestLinksBetween(W wiki, List<String> fullTitles) throws ApiException { ArrayList<Pair<String, String>> links = new ArrayList<>(); this.requestLinksBetweenRecursive(wiki.getApiUrl(), fullTitles, links, null); return links; } ApiClient(); @Override Map<String, Collection<String>> requestCategories(W wiki, List<String> fullTitles, boolean showhidden); @Override List<String> requestCategorymembers(final W wiki, final String fullTitle); Collection<Pair<String, String>> requestLinksBetween(W wiki, List<String> fullTitles); @Override Metadata requestMetadata(final IWiki wiki); }### Answer:
@Test public void testRequestLinksBetween() throws ApiException { final List<String> fullTitles = new ArrayList<>(); fullTitles.add(PAGE_1); fullTitles.add(PAGE_2); final Collection<Pair<String, String>> result = client.requestLinksBetween(wiki, fullTitles); assertNotNull(result); assertNotEquals(0, result.size()); } |
### Question:
AbstractLinkProvider implements Serializable { protected static String escapeForUrl(final String string) { if (string == null) { return null; } try { return URLEncoder.encode(string.replace(' ', '_'), "UTF8"); } catch (UnsupportedEncodingException e) { return null; } } static AbstractLinkProvider fromParams(final AbstractAllParams<?> all); void addLinkToNode(final Node node, final String title); abstract String provideLink(final String title); }### Answer:
@Test public void testEscapeForUrl() { assertEquals("abc%3A%C3%84%C3%B6%C3%BC_%C3%9F%E3%83%A1%E3%82%A4%E3%83%B3%E3%83%9A%E3%83%BC%E3%82%B8", AbstractLinkProvider.escapeForUrl("abc:Äöü ßメインページ")); }
@Test public void testEscapeForUrlNull() { assertEquals(null, AbstractLinkProvider.escapeForUrl(null)); } |
### Question:
AbstractLinkProvider implements Serializable { protected static String escapeMediawikiTitleForUrl(final String title) { return title == null ? null : escapeForUrl(title).replace("%3A", ":"); } static AbstractLinkProvider fromParams(final AbstractAllParams<?> all); void addLinkToNode(final Node node, final String title); abstract String provideLink(final String title); }### Answer:
@Test public void testEscapeMediawikiTitleForUrl() { assertEquals("abc:%C3%84%C3%B6%C3%BC_%C3%9F%E3%83%A1%E3%82%A4%E3%83%B3%E3%83%9A%E3%83%BC%E3%82%B8", AbstractLinkProvider.escapeMediawikiTitleForUrl("abc:Äöü ßメインページ")); }
@Test public void testEscapeMediawikiTitleForUrlNull() { assertEquals(null, AbstractLinkProvider.escapeMediawikiTitleForUrl(null)); } |
### Question:
AbstractLinkProvider implements Serializable { public void addLinkToNode(final Node node, final String title) { final String href = this.provideLink(title); if (href != null && !href.isEmpty()) { node.setHref(href); } } static AbstractLinkProvider fromParams(final AbstractAllParams<?> all); void addLinkToNode(final Node node, final String title); abstract String provideLink(final String title); }### Answer:
@Test public void testAddLinkToNode() { Node node = new Node("test"); underTest.addLinkToNode(node, "linktitle"); assertEquals("link:linktitle", node.getHref()); } |
### Question:
UrgBinner implements Binner { public List<Float> getBinned() { if (last == -1) return null; return new ImmutableList.Builder<Float>().addAll(binned).build(); } UrgBinner(String channel, int bins, double fov); void setLidar(Lidar lidar); void update(); List<Float> getBinned(); urg_range_t getUrgRange(); static void main(String[] args); }### Answer:
@Test public void testBinnedSize() { for (int i = 1; i < 10; ++i) { UrgBinner ub1 = new UrgBinner("URG_RANGE", i, Math.PI); assertEquals(ub1.getBinned().size(), i); } } |
### Question:
WireSafeEnum { @Nonnull @SuppressWarnings("unchecked") public static <T extends Enum<T>> WireSafeEnum<T> of(@Nonnull T value) { checkNotNull(value, "value"); Class<T> enumType = (Class<T>) value.getClass(); ensureEnumCacheInitialized(enumType); return (WireSafeEnum<T>) ENUM_LOOKUP_CACHE.get(enumType).get(value); } private WireSafeEnum(Class<T> enumType, String jsonValue, T enumValue); private WireSafeEnum(Class<T> enumType, String jsonValue); @Nonnull @SuppressWarnings("unchecked") static WireSafeEnum<T> of(@Nonnull T value); @Nonnull @SuppressWarnings("unchecked") static WireSafeEnum<T> fromJson(
@Nonnull Class<T> enumType,
@Nonnull String jsonValue
); @Nonnull Class<T> enumType(); @Nonnull @JsonValue String asString(); @Nonnull Optional<T> asEnum(); @Nonnull T asEnumOrThrow(Supplier<? extends X> exceptionSupplier); @Nonnull T asEnumOrThrow(); boolean contains(@Nonnull T value); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void itDoesntAllowNumericJsonValues() { Throwable t = catchThrowable(() -> WireSafeEnum.of(NumericJsonEnum.ABC)); assertThat(t) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("NumericJsonEnum"); } |
### Question:
AdapterUtils { public static String withoutDecimals(String s) { Objects.requireNonNull(s); int dotIndex = s.lastIndexOf("."); return dotIndex == -1 ? s : s.substring(0, dotIndex); } private AdapterUtils(); static Boolean parseBoolean(String s); static Date parseDate(String s); static LocalDate parseLocalDate(String s); static LocalDateTime parseLocalDateTime(String s); static String withoutDecimals(String s); static Enum<?> findEnumIgnoreCase(Class<? extends Enum<?>> enumType, String name); static Class<?> uncheckedClassForName(String s); }### Answer:
@Test public void testRemoveDecimals100ShouldLeaveIntact() throws Exception { assertEquals("100", AdapterUtils.withoutDecimals("100")); }
@Test public void testRemoveDecimals100_0ShouldRemoveDecimals() throws Exception { assertEquals("100", AdapterUtils.withoutDecimals("100")); }
@Test public void testRemoveDecimals100_123ShouldRemoveDecimals() throws Exception { assertEquals("100", AdapterUtils.withoutDecimals("100.123")); }
@Test public void testRemoveDecimalsABCS_123ShouldRemoveDecimals() throws Exception { assertEquals("ABC", AdapterUtils.withoutDecimals("ABC.123")); }
@Test(expected = NullPointerException.class) public void testRemoveDecimalsNullInputShouldThrowException() throws Exception { AdapterUtils.withoutDecimals(null); } |
### Question:
AdapterUtils { public static Enum<?> findEnumIgnoreCase(Class<? extends Enum<?>> enumType, String name) { Objects.requireNonNull(enumType); Objects.requireNonNull(name); return Arrays.stream(enumType.getEnumConstants()) .filter(e -> e.name().equalsIgnoreCase(name)) .findFirst() .orElseThrow( () -> new IllegalArgumentException( "Cannot convert String \"" + name + "\" to enum of type " + enumType.getName())); } private AdapterUtils(); static Boolean parseBoolean(String s); static Date parseDate(String s); static LocalDate parseLocalDate(String s); static LocalDateTime parseLocalDateTime(String s); static String withoutDecimals(String s); static Enum<?> findEnumIgnoreCase(Class<? extends Enum<?>> enumType, String name); static Class<?> uncheckedClassForName(String s); }### Answer:
@Test public void testFindMondayInDayOfWeekShouldReturnMONDAY() throws Exception { assertEquals(DayOfWeek.MONDAY, AdapterUtils.findEnumIgnoreCase(DayOfWeek.class, "Monday")); }
@Test public void testFindMONDAYInDayOfWeekShouldReturnMONDAY() throws Exception { assertEquals(DayOfWeek.MONDAY, AdapterUtils.findEnumIgnoreCase(DayOfWeek.class, "MONDAY")); }
@Test public void testFindmondayInDayOfWeekShouldReturnMONDAY() throws Exception { assertEquals(DayOfWeek.MONDAY, AdapterUtils.findEnumIgnoreCase(DayOfWeek.class, "monday")); }
@Test(expected = IllegalArgumentException.class) public void testFindJanuaryInDayOfWeekShouldThrowException() throws Exception { AdapterUtils.findEnumIgnoreCase(DayOfWeek.class, "January"); }
@Test(expected = NullPointerException.class) public void testFindNullInDayOfWeekShouldThrowException() throws Exception { AdapterUtils.findEnumIgnoreCase(DayOfWeek.class, null); }
@Test(expected = NullPointerException.class) public void testFindMondayInNullEnumShouldThrowException() throws Exception { AdapterUtils.findEnumIgnoreCase(null, "Monday"); } |
### Question:
AdapterUtils { public static Date parseDate(String s) { Objects.requireNonNull(s); LocalDateTime ldt = parseLocalDateTime(s); return Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant()); } private AdapterUtils(); static Boolean parseBoolean(String s); static Date parseDate(String s); static LocalDate parseLocalDate(String s); static LocalDateTime parseLocalDateTime(String s); static String withoutDecimals(String s); static Enum<?> findEnumIgnoreCase(Class<? extends Enum<?>> enumType, String name); static Class<?> uncheckedClassForName(String s); }### Answer:
@Test public void testParseDate2010_06_20ShouldReturnCorrectDate() throws Exception { assertEquals(new Date(110, 5, 20), AdapterUtils.parseDate("2010-06-20")); }
@Test(expected = RuntimeException.class) public void testParseInvalidDateShouldThrowException() throws Exception { AdapterUtils.parseDate("ABC_2010-06-20"); }
@Test(expected = NullPointerException.class) public void testParseNullDateShouldThrowException() throws Exception { AdapterUtils.parseDate(null); } |
### Question:
AdapterUtils { public static LocalDate parseLocalDate(String s) { Objects.requireNonNull(s); return (s.length() > ISO_LOCAL_DATE_LENGTH) ? parseLocalDateTime(s).toLocalDate() : LocalDate.parse(s); } private AdapterUtils(); static Boolean parseBoolean(String s); static Date parseDate(String s); static LocalDate parseLocalDate(String s); static LocalDateTime parseLocalDateTime(String s); static String withoutDecimals(String s); static Enum<?> findEnumIgnoreCase(Class<? extends Enum<?>> enumType, String name); static Class<?> uncheckedClassForName(String s); }### Answer:
@Test public void testParseLocalDateFromDatetimeShouldReturnCorrectDate() throws Exception { assertEquals(LocalDate.of(2010, 6, 20), AdapterUtils.parseLocalDate("2010-06-20T12:30:00")); }
@Test public void testParseLocalDateFromDatetimeWithZShouldReturnCorrectDate() throws Exception { assertEquals(LocalDate.of(2010, 6, 20), AdapterUtils.parseLocalDate("2010-06-20T12:30:00Z")); } |
### Question:
AdapterUtils { public static LocalDateTime parseLocalDateTime(String s) { Objects.requireNonNull(s); return (s.length() > ISO_LOCAL_DATE_LENGTH) ? LocalDateTime.parse(withoutZ(s)) : LocalDateTime.of(LocalDate.parse(s), LocalTime.of(0, 0)); } private AdapterUtils(); static Boolean parseBoolean(String s); static Date parseDate(String s); static LocalDate parseLocalDate(String s); static LocalDateTime parseLocalDateTime(String s); static String withoutDecimals(String s); static Enum<?> findEnumIgnoreCase(Class<? extends Enum<?>> enumType, String name); static Class<?> uncheckedClassForName(String s); }### Answer:
@Test public void testParseLocalDateTimeWithZShouldReturnCorrectDate() throws Exception { assertEquals( LocalDateTime.of(2010, 6, 20, 12, 30), AdapterUtils.parseLocalDateTime("2010-06-20T12:30:00Z")); }
@Test public void testParseLocalDateTimeWithoutZShouldReturnCorrectDateTime() throws Exception { assertEquals( LocalDateTime.of(2010, 6, 20, 12, 30), AdapterUtils.parseLocalDateTime("2010-06-20T12:30:00")); }
@Test public void testParseLocalDateTimeWithoutTimeShouldReturnCorrectDateTime() throws Exception { assertEquals( LocalDateTime.of(2010, 6, 20, 0, 0), AdapterUtils.parseLocalDateTime("2010-06-20")); } |
### Question:
SheetConfig { public String getName() { return name; } private SheetConfig(); int getIndex(); String getName(); boolean isIndexSet(); boolean isNameSet(); static SheetConfig fromAnnotation(Sheet sheet); }### Answer:
@Test public void createSheetConfigWithOnlyNameShouldSetNameFlag() { assertEquals("Name", new SheetConfig.Builder().name("Name").build().getName()); } |
### Question:
SheetConfig { public int getIndex() { return index; } private SheetConfig(); int getIndex(); String getName(); boolean isIndexSet(); boolean isNameSet(); static SheetConfig fromAnnotation(Sheet sheet); }### Answer:
@Test public void createSheetConfigWithOnlyIndexShouldSetIndexFlag() { assertEquals(0, new SheetConfig.Builder().index(0).build().getIndex()); } |
### Question:
IntegerTime implements Time { public IntegerTime() { } IntegerTime(); IntegerTime(int time); @Override boolean equals(Time t); @Override int hashCode(); @Override boolean equals(Object obj); @Override void increment(); @Override void setTime(Time t); @Override String toString(); @Override Time clone(); @Override boolean greaterThan(Time t); @Override int intValue(); }### Answer:
@Test public void testIntegerTime() { IntegerTime t = new IntegerTime(); assertNotNull(t); IntegerTime t2 = new IntegerTime(rand.nextInt()); assertNotNull(t2); } |
### Question:
IntegerTime implements Time { @Override public void increment() { this.time++; } IntegerTime(); IntegerTime(int time); @Override boolean equals(Time t); @Override int hashCode(); @Override boolean equals(Object obj); @Override void increment(); @Override void setTime(Time t); @Override String toString(); @Override Time clone(); @Override boolean greaterThan(Time t); @Override int intValue(); }### Answer:
@Test public void testIncrement() { final int initialTime = rand.nextInt(); Time t1 = new IntegerTime(initialTime); Time t2 = new IntegerTime(initialTime); Time t3 = new IntegerTime(initialTime + 1); assertTrue(t1.equals(t2)); assertFalse(t2.equals(t3)); assertFalse(t1.equals(t3)); t2.increment(); assertFalse(t1.equals(t2)); assertTrue(t2.equals(t3)); assertFalse(t1.equals(t3)); } |
### Question:
IntegerTime implements Time { @Override public void setTime(Time t) { if (t instanceof IntegerTime) { IntegerTime it = (IntegerTime) t; this.time = it.time; } } IntegerTime(); IntegerTime(int time); @Override boolean equals(Time t); @Override int hashCode(); @Override boolean equals(Object obj); @Override void increment(); @Override void setTime(Time t); @Override String toString(); @Override Time clone(); @Override boolean greaterThan(Time t); @Override int intValue(); }### Answer:
@Test public void testSetTime() { Time t1 = new IntegerTime(rand.nextInt()); Time t2 = new IntegerTime(rand.nextInt()); assertFalse(t1.equals(t2)); t1.setTime(t2); assertTrue(t1.equals(t2)); t1.setTime(null); assertTrue(t1.equals(t2)); } |
### Question:
IntegerTime implements Time { @Override public String toString() { return Integer.valueOf(this.time).toString(); } IntegerTime(); IntegerTime(int time); @Override boolean equals(Time t); @Override int hashCode(); @Override boolean equals(Object obj); @Override void increment(); @Override void setTime(Time t); @Override String toString(); @Override Time clone(); @Override boolean greaterThan(Time t); @Override int intValue(); }### Answer:
@Test public void testToString() { Integer n = Integer.valueOf(rand.nextInt()); Time t1 = new IntegerTime(n); assertEquals(t1.toString(), n.toString()); } |
### Question:
IntegerTime implements Time { @Override public Time clone() { return new IntegerTime(this.time); } IntegerTime(); IntegerTime(int time); @Override boolean equals(Time t); @Override int hashCode(); @Override boolean equals(Object obj); @Override void increment(); @Override void setTime(Time t); @Override String toString(); @Override Time clone(); @Override boolean greaterThan(Time t); @Override int intValue(); }### Answer:
@Test public void testClone() { Time t1 = new IntegerTime(rand.nextInt()); Time t2 = t1.clone(); assertTrue("equals of cloned IntegerTime should be true", t1.equals(t2)); assertNotSame("Cloned objects should not reference the same object", t2, t1); } |
### Question:
IntegerTime implements Time { @Override public boolean greaterThan(Time t) { if (t != null) return this.time > ((IntegerTime) t).time; else return false; } IntegerTime(); IntegerTime(int time); @Override boolean equals(Time t); @Override int hashCode(); @Override boolean equals(Object obj); @Override void increment(); @Override void setTime(Time t); @Override String toString(); @Override Time clone(); @Override boolean greaterThan(Time t); @Override int intValue(); }### Answer:
@Test public void testGreaterThan() { final int lower = rand.nextInt(Integer.MAX_VALUE - 1); final int higher = rand.nextInt(Integer.MAX_VALUE - lower) + lower; assertTrue("Did not generate valid values", lower < higher); Time t1 = new IntegerTime(lower); Time t2 = new IntegerTime(lower); Time t3 = new IntegerTime(higher); assertTrue("IntegerTime(Y>X).greaterThan(X) should be true", t3.greaterThan(t1)); assertFalse("IntegerTime(Y<X).greaterThan(X) should be false", t1.greaterThan(t3)); assertFalse("IntegerTime(Y==X).greaterThan(X) should be false", t1.greaterThan(t2)); assertFalse("A.greaterThan(A) should be false", t1.greaterThan(t1)); assertFalse("A.greaterThan(null) should be false", t1.greaterThan(null)); } |
### Question:
Experiment implements Iterator<Simulation> { public abstract Experiment build() throws InvalidParametersException; protected Experiment(String name, String description); String getName(); String getDescription(); abstract Experiment build(); abstract Experiment addParameter(String name, Iterable<String> values); Experiment addArrayParameter(String name, Object... values); Experiment addArrayParameter(String name, String... values); Experiment addFixedParameter(String name, String value); Experiment addFixedParameter(String name, Object value); Experiment addRangeParameter(String name, int start, int count,
int interval); }### Answer:
@Test public void testNoParams() { try { new ParameterSweep("Test", "Test_%{p.test}", "uk.ac.imperial.TestClass", 100).build(); fail(); } catch (InvalidParametersException e) { } } |
### Question:
EventBusImpl implements EventBus { EventBusImpl() { super(); } EventBusImpl(); @Override synchronized void subscribe(final Object listener); @Override synchronized void unsubscribe(Object listener); @Override void publish(final Event event); }### Answer:
@Test public void testEventBusImpl() { Mockery context = new Mockery(); Event fakeEvent = context.mock(Event.class); MockEventListener listener = new MockEventListener(); EventBus eventBus = new EventBusImpl(); eventBus.publish(new MockEvent()); assertEquals(0, invocationCount); eventBus.subscribe(listener); eventBus.publish(new MockEvent()); assertEquals(1, invocationCount); eventBus.publish(fakeEvent); assertEquals(1, invocationCount); eventBus.unsubscribe(listener); eventBus.publish(new MockEvent()); assertEquals(1, invocationCount); eventBus.subscribe(listener); eventBus.subscribe(listener); eventBus.publish(new MockEvent()); assertEquals(2, invocationCount); } |
### Question:
NotCondition implements TransitionCondition { @Override public boolean allow(Object event, Object entity, State state) { return !(condition.allow(event, entity, state)); } NotCondition(TransitionCondition condition); @Override boolean allow(Object event, Object entity, State state); }### Answer:
@Test public void test() { final Mockery context = new Mockery(); final TransitionCondition mockCondition = context.mock(TransitionCondition.class); final State mockState = new State("test", StateType.ACTIVE); NotCondition n1 = new NotCondition(mockCondition); context.checking(new Expectations() { { oneOf(mockCondition).allow(with(event), with(entity), with(mockState)); will(returnValue(true)); } }); assertFalse(n1.allow(event, entity, mockState)); context.assertIsSatisfied(); context.checking(new Expectations() { { oneOf(mockCondition).allow(with(event), with(entity), with(mockState)); will(returnValue(false)); } }); assertTrue(n1.allow(event, entity, mockState)); context.assertIsSatisfied(); } |
### Question:
AndCondition implements TransitionCondition { @Override public boolean allow(Object event, Object entity, State state) { for (TransitionCondition condition : conditions) { if (!condition.allow(event, entity, state)) return false; } return true; } AndCondition(TransitionCondition... conditions); @Override boolean allow(Object event, Object entity, State state); }### Answer:
@Test public void test() { final Random rand = new Random(); final int conditionCount = rand.nextInt(20) + 1; final TransitionCondition[] alwaysTrue = new TransitionCondition[conditionCount]; for (int i = 0; i < alwaysTrue.length; i++) { alwaysTrue[i] = TransitionCondition.ALWAYS; } AndCondition condition = new AndCondition(alwaysTrue); assertTrue(condition.allow(null, null, null)); for (int i = 0; i < 10; i++) { TransitionCondition[] mixed = Arrays.copyOf(alwaysTrue, alwaysTrue.length); int elementsToChange = rand.nextInt(mixed.length) + 1; for (int j = 0; j < elementsToChange; j++) { mixed[rand.nextInt(mixed.length)] = NEVER; } condition = new AndCondition(mixed); assertFalse(condition.allow(null, null, null)); } final TransitionCondition[] alwaysFalse = new TransitionCondition[conditionCount]; Arrays.fill(alwaysFalse, NEVER); condition = new AndCondition(alwaysFalse); assertFalse(condition.allow(null, null, null)); } |
### Question:
EventTypeCondition implements TransitionCondition { @Override public boolean allow(Object event, Object entity, State state) { return (type.isInstance(event)); } EventTypeCondition(Class<?> type); @Override boolean allow(Object event, Object entity, State state); }### Answer:
@Test public void test() { EventTypeCondition condition = new EventTypeCondition(TestEvent.class); assertTrue(condition.allow(event, null, null)); assertFalse(condition.allow(null, null, null)); assertFalse(condition.allow(new Object(), null, null)); assertTrue(condition.allow(new OtherEvent(), null, null)); } |
### Question:
OrCondition implements TransitionCondition { @Override public boolean allow(Object event, Object entity, State state) { for (TransitionCondition condition : conditions) { if (condition.allow(event, entity, state)) return true; } return false; } OrCondition(TransitionCondition... conditions); @Override boolean allow(Object event, Object entity, State state); }### Answer:
@Test public void test() { final Random rand = new Random(); final int conditionCount = rand.nextInt(20) + 1; final Mockery context = new Mockery(); final State mockState = new State("test", StateType.ACTIVE); final TransitionCondition[] conditions = new TransitionCondition[conditionCount]; for (int i = 0; i < conditions.length; i++) { conditions[i] = context.mock(TransitionCondition.class, "condition" + i); } OrCondition condition = new OrCondition(conditions); context.checking(new Expectations() { { for (int i = 0; i < conditions.length; i++) { oneOf(conditions[i]).allow(event, entity, mockState); will(returnValue(false)); } } }); assertFalse(condition.allow(event, entity, mockState)); context.assertIsSatisfied(); context.checking(new Expectations() { { for (int i = 0; i < conditions.length; i++) { allowing(conditions[i]).allow(event, entity, mockState); will(returnValue(true)); } } }); assertTrue(condition.allow(event, entity, mockState)); context.assertIsSatisfied(); for (int i = 0; i < 10; i++) { context.checking(new Expectations() { { boolean result = false; for (int i = 0; i < conditions.length; i++) { boolean value = rand.nextBoolean(); result |= value; if (i == conditions.length - 1 && !result) value = true; allowing(conditions[i]).allow(event, entity, mockState); will(returnValue(value)); } } }); assertTrue(condition.allow(event, entity, mockState)); context.assertIsSatisfied(); } } |
### Question:
AbstractEnvironment implements EnvironmentConnector,
EnvironmentServiceProvider, TimeDriven { @SuppressWarnings("unchecked") @Override public <T extends EnvironmentService> T getEnvironmentService(Class<T> type) throws UnavailableServiceException { type.toString(); for (EnvironmentService s : this.globalEnvironmentServices) { if (type.isInstance(s)) { return (T) s; } } throw new UnavailableServiceException(type); } @Inject AbstractEnvironment(SharedStateStorage sharedState); @Inject(optional = true) void deferActions(@DeferActions boolean defer); @Inject(optional = true) void registerTimeDriven(Scenario s); @SuppressWarnings("unchecked") @Override T getEnvironmentService(Class<T> type); @Override synchronized EnvironmentRegistrationResponse register(
EnvironmentRegistrationRequest request); @Override void act(Action action, UUID actor, UUID authkey); @Override void deregister(UUID participantID, UUID authkey); @Override void incrementTime(); }### Answer:
@Test public void testHasEnvironmentMembersService() throws UnavailableServiceException { final TestAbstractEnvironment envUnderTest = new TestAbstractEnvironment(mockStorage); final EnvironmentService envService = envUnderTest .getEnvironmentService(EnvironmentMembersService.class); assertNotNull(envService); assertTrue(envService instanceof EnvironmentMembersService); }
@Test public void testGetEnvironmentServiceFailure() { final TestAbstractEnvironment envUnderTest = new TestAbstractEnvironment(mockStorage); try { @SuppressWarnings("unused") final EnvironmentService envService = envUnderTest.getEnvironmentService(null); fail("No exception thrown by AbstractEnvironment.getEnvironmentService(null), NullPointerException expected."); } catch (NullPointerException e) { } catch (UnavailableServiceException e) { fail("UnavailableServiceException exception thrown by AbstractEnvironment.getEnvironmentService(null), NullPointerException expected."); } try { @SuppressWarnings("unused") final EnvironmentService envService = envUnderTest .getEnvironmentService(MockEnvironmentService.class); fail("No exception thrown by AbstractEnvironment.getEnvironmentService(MockEnvironmentService.class), UnavailableServiceException expected."); } catch (UnavailableServiceException e) { } } |
### Question:
FSMProtocol extends Protocol { @Override public Conversation spawn() { try { return spawnAsInititor(new ConversationSpawnEvent()); } catch (FSMException e) { throw new RuntimeException(e); } } FSMProtocol(String name, FSMDescription description,
NetworkAdaptor network); @Override Conversation spawn(); @Override Conversation spawn(NetworkAddress with); @Override Conversation spawn(Set<NetworkAddress> with); @Override void spawn(Message m); @Step void incrementTime(int t); }### Answer:
@Test public void test() throws UnavailableServiceException { final ConversationalAgent p1 = new ConversationalAgent( UUID.randomUUID(), "p1", ping); final ConversationalAgent p2 = new ConversationalAgent( UUID.randomUUID(), "p2", ping); final ConversationalAgent p3 = new ConversationalAgent( UUID.randomUUID(), "p3", ping); RunnableSimulation sim = new RunnableSimulation() { @Override public void initialiseScenario(Scenario s) { addModule(new AbstractEnvironmentModule() .addParticipantEnvironmentService(BasicNetworkConnector.class)); addModule(NetworkModule.fullyConnectedNetworkModule()); s.addAgent(p1); s.addAgent(p2); s.addAgent(p3); } }; sim.initialise(); sim.step(); p1.proto.spawn(); sim.step(); assertEquals(0, responders.size()); sim.step(); sim.step(); assertEquals(2, responders.size()); sim.step(); sim.step(); sim.step(); assertEquals(2, responders.size()); } |
### Question:
LocationService extends EnvironmentService { public Location getAgentLocation(UUID participantID) { return (Location) this.sharedState.get("util.location", participantID); } @Inject LocationService(EnvironmentSharedStateAccess sharedState,
EnvironmentServiceProvider serviceProvider); @Override void registerParticipant(EnvironmentRegistrationRequest req); Location getAgentLocation(UUID participantID); void setAgentLocation(final UUID participantID, final Location l); }### Answer:
@Test public void testGetAgentLocation() throws CannotSeeAgent, UnavailableServiceException { final Mockery context = new Mockery(); final EnvironmentSharedStateAccess mockEnv = context .mock(EnvironmentSharedStateAccess.class); final EnvironmentServiceProvider mockServiceProvider = context .mock(EnvironmentServiceProvider.class); final HasArea area = context.mock(HasArea.class); final Area a = new Area(1, 1, 1); context.checking(new Expectations() { { allowing(area).getArea(); will(returnValue(a)); } }); final AreaService areaService = new AreaService(mockEnv, area); final UUID validID = Random.randomUUID(); final Location loc = new Location(0, 0); final UUID invalidID = Random.randomUUID(); context.checking(new Expectations() { { allowing(mockEnv).get("util.location", validID); will(returnValue(loc)); allowing(mockEnv).get("util.location", invalidID); will(returnValue(null)); allowing(mockServiceProvider).getEnvironmentService(AreaService.class); will(returnValue(areaService)); } }); final LocationService serviceUnderTest = new LocationService(mockEnv, mockServiceProvider); assertSame(loc, serviceUnderTest.getAgentLocation(validID)); assertNull(serviceUnderTest.getAgentLocation(invalidID)); context.assertIsSatisfied(); } |
### Question:
ImmutableList implements FuncList<DATA> { @SafeVarargs public static <T> ImmutableList<T> of(T ... data) { return new ImmutableList<>(Arrays.asList(data)); } ImmutableList(Collection<DATA> data); ImmutableList(Collection<DATA> data, boolean isLazy); @SuppressWarnings("unchecked") static final ImmutableList<T> empty(); static ImmutableList<T> from(Collection<T> data); @SafeVarargs static ImmutableList<T> of(T ... data); static ImmutableList<T> from(T[] datas); static ImmutableList<T> from(Streamable<T> streamable); static ImmutableList<T> from(Stream<T> stream); static ImmutableList<T> from(ReadOnlyList<T> readOnlyList); static ImmutableList<T> from(FuncList<T> funcList); @SafeVarargs static ImmutableList<T> listOf(T ... data); @Override StreamPlus<DATA> stream(); boolean isLazy(); boolean isEager(); FuncList<DATA> lazy(); FuncList<DATA> eager(); @Override ImmutableList<DATA> toImmutableList(); @Override int size(); @Override boolean isEmpty(); @Override TARGET[] toArray(TARGET[] seed); @Override DATA get(int index); @Override int indexOf(Object o); @Override int lastIndexOf(Object o); @Override ListIterator<DATA> listIterator(); @Override ListIterator<DATA> listIterator(int index); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testSorted() { assertEquals("[1, 2, One, Two]", "" + ImmutableList.of("1", "One", "2", "Two").sorted()); assertEquals("[1, 2, One, Two]", "" + ImmutableList.of("2", "Two", "1", "One").sorted()); } |
### Question:
RefTo extends Ref<DATA> { final Ref<DATA> whenAbsent(Func0<DATA> defaultSupplier) { return this; } RefTo(Class<DATA> dataClass); final int hashCode(); final boolean equals(Object another); static final Ref<IProvideDefault> defaultProvider; }### Answer:
@Test public void testWhenAbsent() { val r = Ref.of(Person.class) .whenAbsentUseTypeDefault() .defaultTo(new Person(new SuperCar())); assertEquals("SUPER FLASH!!!!", r.value() .zoom() .toString()); val zoom = With(r.butFrom(()->null)) .run(()->{ return r.value() .zoom(); }); assertEquals("FLASH!", zoom); } |
### Question:
Log { private Log() { } private Log(); static Func1<T, T> tab(); static Func1<T, T> tab(Object prefix); static Func1<T, T> tabf(String format); static T log(T value); static T log(Object prefix, T value); static T log(Object prefix, T value, Object suffix); @SuppressWarnings("unchecked") static FuncList<T> logEach(T ... values); static FuncList<T> logEach(String prefix, Collection<T> values); static FuncList<T> logEach(String prefix, Collection<T> values, String suffix); static T logBy(Supplier<T> supplier); static T logErr(T throwable); static T logErr(Object prefix, T throwable); static T logErr(Object prefix, T throwable, Object suffix); }### Answer:
@Test public void testLog() { val stub = new Console.Stub(); With(Env.refs.console.butWith(stub)) .run(()->{ Log.log("One"); Log.log("2: ", "Two", " --"); Log.logEach("Three", "Four"); Log.logEach("-->", listOf("Three", "Four"), "<--"); Log.logBy(()-> "42"); val outLines = StreamPlus.from(stub.outLines()).toJavaList(); assertEquals( "[" + "One, " + "2: Two --, " + "Three, Four, " + "-->Three<--, -->Four<--, " + "42" + "]", outLines.toString()); stub.clearOutLines(); }); } |
### Question:
Log { public static <T extends Throwable> T logErr(T throwable) { return Env.log().logErr(throwable); } private Log(); static Func1<T, T> tab(); static Func1<T, T> tab(Object prefix); static Func1<T, T> tabf(String format); static T log(T value); static T log(Object prefix, T value); static T log(Object prefix, T value, Object suffix); @SuppressWarnings("unchecked") static FuncList<T> logEach(T ... values); static FuncList<T> logEach(String prefix, Collection<T> values); static FuncList<T> logEach(String prefix, Collection<T> values, String suffix); static T logBy(Supplier<T> supplier); static T logErr(T throwable); static T logErr(Object prefix, T throwable); static T logErr(Object prefix, T throwable, Object suffix); }### Answer:
@Test public void testLogErr() { val stub = new Console.Stub(); With(Env.refs.console.butWith(stub)) .run(()->{ try { throw new NullPointerException("NULL!!!"); } catch (Exception e) { Log.logErr("Error!", e); } val expected = "Error!\n" + "java.lang.NullPointerException: NULL!!!"; assertEquals(expected, stub.errLines().limit(2).joinToString("\n")); }); } |
### Question:
Console { public static Console.Instance println(Object line) { return Env.console().println(line); } private Console(); static FuncUnit1<Object> printf(String format); static Console.Instance print(Object text); static Console.Instance println(Object line); static Console.Instance println(); static Console.Instance outPrint(Object text); static Console.Instance outPrintln(Object line); static Console.Instance outPrintln(); static Console.Instance errPrint(Object text); static Console.Instance errPrintln(Object line); static Console.Instance errPrintln(); static String readln(); static String pollln(); static Promise<String> inputLine(); static void stopRead(); static StubRecord<Object> useStub(RunBody<E> body); static StubRecord<D> useStub(ComputeBody<D, E> body); static StubRecord<Object> useStub(FuncUnit1<ConsoleInQueue> holder, RunBody<E> body); static StubRecord<D> useStub(FuncUnit1<ConsoleInQueue> holder, ComputeBody<D, E> body); static StubRecord<Object> useStub(Stream<String> inLines, RunBody<E> body); static StubRecord<Object> useStub(ConsoleInQueue inQueue, RunBody<E> body); static StubRecord<D> useStub(Stream<String> inLines, ComputeBody<D, E> body); static StubRecord<D> useStub(ConsoleInQueue inQueue, ComputeBody<D, E> body); static FuncUnit1<Object> print; static FuncUnit1<Object> println; }### Answer:
@Test public void testStub_out() { val stub = new Console.Stub(); With(Env.refs.console.butWith(stub)) .run(()->{ Console .println("One") .println("Two"); val outLines = StreamPlus.from(stub.outLines()).toJavaList(); assertEquals( "[One, Two]", outLines.toString()); stub.clearOutLines(); }); } |
### Question:
Console { public static Console.Instance errPrintln(Object line) { return Env.console().errPrintln(line); } private Console(); static FuncUnit1<Object> printf(String format); static Console.Instance print(Object text); static Console.Instance println(Object line); static Console.Instance println(); static Console.Instance outPrint(Object text); static Console.Instance outPrintln(Object line); static Console.Instance outPrintln(); static Console.Instance errPrint(Object text); static Console.Instance errPrintln(Object line); static Console.Instance errPrintln(); static String readln(); static String pollln(); static Promise<String> inputLine(); static void stopRead(); static StubRecord<Object> useStub(RunBody<E> body); static StubRecord<D> useStub(ComputeBody<D, E> body); static StubRecord<Object> useStub(FuncUnit1<ConsoleInQueue> holder, RunBody<E> body); static StubRecord<D> useStub(FuncUnit1<ConsoleInQueue> holder, ComputeBody<D, E> body); static StubRecord<Object> useStub(Stream<String> inLines, RunBody<E> body); static StubRecord<Object> useStub(ConsoleInQueue inQueue, RunBody<E> body); static StubRecord<D> useStub(Stream<String> inLines, ComputeBody<D, E> body); static StubRecord<D> useStub(ConsoleInQueue inQueue, ComputeBody<D, E> body); static FuncUnit1<Object> print; static FuncUnit1<Object> println; }### Answer:
@Test public void testStub_err() { val stub = new Console.Stub(); With(Env.refs.console.butWith(stub)) .run(()->{ stub.clear(); Console .errPrintln("Five") .errPrintln("Six"); val outLines = StreamPlus.from(stub.errLines()).toJavaList(); assertEquals( "[Five, Six]", outLines.toString()); stub.clear(); }); } |
### Question:
Console { public static String readln() { return Env.console().readln(); } private Console(); static FuncUnit1<Object> printf(String format); static Console.Instance print(Object text); static Console.Instance println(Object line); static Console.Instance println(); static Console.Instance outPrint(Object text); static Console.Instance outPrintln(Object line); static Console.Instance outPrintln(); static Console.Instance errPrint(Object text); static Console.Instance errPrintln(Object line); static Console.Instance errPrintln(); static String readln(); static String pollln(); static Promise<String> inputLine(); static void stopRead(); static StubRecord<Object> useStub(RunBody<E> body); static StubRecord<D> useStub(ComputeBody<D, E> body); static StubRecord<Object> useStub(FuncUnit1<ConsoleInQueue> holder, RunBody<E> body); static StubRecord<D> useStub(FuncUnit1<ConsoleInQueue> holder, ComputeBody<D, E> body); static StubRecord<Object> useStub(Stream<String> inLines, RunBody<E> body); static StubRecord<Object> useStub(ConsoleInQueue inQueue, RunBody<E> body); static StubRecord<D> useStub(Stream<String> inLines, ComputeBody<D, E> body); static StubRecord<D> useStub(ConsoleInQueue inQueue, ComputeBody<D, E> body); static FuncUnit1<Object> print; static FuncUnit1<Object> println; }### Answer:
@Test public void testStub_in() { val stub = new Console.Stub(); With(Env.refs.console.butWith(stub)) .run(()->{ stub.addInLines("One", "Two"); stub.endInStream(); assertEquals("One", Console.readln()); assertEquals("Two", Console.readln()); assertEquals(0L, stub.remainingInLines().count()); stub.clearInLines(); }); } |
### Question:
Ref { public final DATA value() { val result = getResult(); val value = result.value(); return value; } Ref(Class<DATA> dataClass, Supplier<DATA> whenAbsentSupplier); static Ref<D> to(Class<D> dataClass); static RefBuilder<D> of(Class<D> dataClass); static Ref<D> ofValue(D value); static Ref<D> dictactedTo(D value); DATA get(); final Class<DATA> getDataType(); final Result<DATA> getResult(); final Result<DATA> asResult(); final Optional<DATA> asOptional(); final Func0<DATA> valueSupplier(); final DATA value(); final DATA orElse(DATA elseValue); final DATA orGet(Supplier<DATA> elseValue); final DATA orElseGet(Supplier<DATA> elseValue); final Func0<TARGET> then(Func1<DATA, TARGET> mapper); final Ref<TARGET> map(Class<TARGET> targetClass, Func1<DATA, TARGET> mapper); final Substitution<DATA> butWith(DATA value); final Substitution<DATA> butFrom(Func0<DATA> supplier); Ref<DATA> whenAbsentUse(DATA defaultValue); Ref<DATA> whenAbsentGet(Supplier<DATA> defaultSupplier); Ref<DATA> whenAbsentUseDefault(); Ref<DATA> whenAbsentUseDefaultOrGet(Supplier<DATA> manualDefault); DictatedRef<DATA> dictate(); RetainedRef.Builder<DATA> retained(); static final FuncList<Ref<?>> getCurrentRefs(); }### Answer:
@Test public void testValue() { val ref1 = Ref.ofValue("Value"); assertEquals("Value", ref1.value()); val ref2 = Ref.ofValue(42); assertEquals(42, (int)ref2.value()); } |
### Question:
Ref { public DictatedRef<DATA> dictate() { return new DictatedRef<DATA>(this); } Ref(Class<DATA> dataClass, Supplier<DATA> whenAbsentSupplier); static Ref<D> to(Class<D> dataClass); static RefBuilder<D> of(Class<D> dataClass); static Ref<D> ofValue(D value); static Ref<D> dictactedTo(D value); DATA get(); final Class<DATA> getDataType(); final Result<DATA> getResult(); final Result<DATA> asResult(); final Optional<DATA> asOptional(); final Func0<DATA> valueSupplier(); final DATA value(); final DATA orElse(DATA elseValue); final DATA orGet(Supplier<DATA> elseValue); final DATA orElseGet(Supplier<DATA> elseValue); final Func0<TARGET> then(Func1<DATA, TARGET> mapper); final Ref<TARGET> map(Class<TARGET> targetClass, Func1<DATA, TARGET> mapper); final Substitution<DATA> butWith(DATA value); final Substitution<DATA> butFrom(Func0<DATA> supplier); Ref<DATA> whenAbsentUse(DATA defaultValue); Ref<DATA> whenAbsentGet(Supplier<DATA> defaultSupplier); Ref<DATA> whenAbsentUseDefault(); Ref<DATA> whenAbsentUseDefaultOrGet(Supplier<DATA> manualDefault); DictatedRef<DATA> dictate(); RetainedRef.Builder<DATA> retained(); static final FuncList<Ref<?>> getCurrentRefs(); }### Answer:
@Test public void testDictate() { val ref1 = Ref.ofValue("DICTATE!").dictate(); val ref2 = Ref.of(String.class).dictateTo("DICTATE!!"); assertEquals("DICTATE! DICTATE!!", ref1.value() + " " + ref2.value()); val value = With(ref1.butWith("Weak!")) .and(ref2.butWith("Weak!!")) .run(()->ref1.value() + " " + ref2.value()); assertEquals("DICTATE! DICTATE!!", value); } |
### Question:
CombineResult { DeferAction<D> getDeferAction() { return action; } CombineResult(FuncList<NamedExpression<HasPromise<Object>>> hasPromises,
Func1<FuncList<Result>, Result<D>> mergeFunc); }### Answer:
@Test public void testMerge() { val logs = new ArrayList<String>(); val action1 = DeferAction.createNew().start(); val action2 = DeferAction.createNew().start(); val action3 = DeferAction.createNew().start(); val combiner = new CombineResult<>( listOf(action1, action2, action3), l -> Result.valueOf(l.toString())); val combine = combiner.getDeferAction() .onComplete(result -> { logs.add(result.toString()); }); logs.add("Done prepare"); logs.add("About to do one: " + action1.getPromise().getStatus()); action1.complete("One"); logs.add("About to do two: " + action2.getPromise().getStatus()); action2.complete("Two"); logs.add("About to do three: " + action3.getPromise().getStatus()); action3.complete("Three"); combine.abort(); logs.add(combine.getResult().toString()); assertEquals( "Done prepare\n" + "About to do one: PENDING\n" + "About to do two: PENDING\n" + "About to do three: PENDING\n" + "Result:{ Value: [Result:{ Value: One }, Result:{ Value: Two }, Result:{ Value: Three }] }\n" + "Result:{ Value: [Result:{ Value: One }, Result:{ Value: Two }, Result:{ Value: Three }] }", logs.stream().collect(joining("\n"))); } |
### Question:
IntStep implements Streamable<Integer>, IntUnaryOperator { public static IntStep of(int size) { return new IntStep(size, 0); } private IntStep(int size, int start); static IntStep step(int size); static IntStep step(Size size); static IntStep step(Size size, From from); static IntStep step(int size, From from); static IntStep of(int size); static IntStep of(Size size); static IntStep of(Size size, From from); static IntStep of(int size, From from); static Size size(int size); static From startAt(int start); static From from(int start); IntStreamPlus intStream(); @Override StreamPlus<Integer> stream(); @Override int applyAsInt(int operand); Func1<Integer, Integer> function(); }### Answer:
@Test public void testAsStream() { assertEquals("[0, 7, 14, 21, 28, 35, 42, 49, 56, 63]", IntStep.of(7).limit(10).toList().toString()); } |
### Question:
MapTo { public static <T> Func1<T, T> only(Predicate<? super T> checker) { return input -> checker.test(input) ? input : null; } static Func1<T, T> only(Predicate<? super T> checker); static Func1<T, T> forOnly(
Predicate<? super T> checker,
Func1<? super T, ? extends T> mapper); static Func1<T, T> when(
Predicate<? super T> checker,
Function<? super T, ? extends T> mapper,
Function<? super T, ? extends T> elseMapper); static Func1<D, T> firstOf(
FuncList<Function<? super D, ? extends T>> mappers); @SafeVarargs static Func1<D, T> firstOf(
Function<? super D, ? extends T> ... mappers); static ToTuple2Func<D, T1, T2> toTuple(
Func1<? super D, ? extends T1> mapper1,
Func1<? super D, ? extends T2> mapper2); static ToMapFunc<D, K, V> toMap(
K key, Func1<? super D, ? extends V> mapper); }### Answer:
@Test public void testSelectThen() { assertEquals("Result:{ Value: null }", "" + Result.valueOf("Hello").map(only(s -> s.length() < 4))); } |
### Question:
MapTo { public static <D, T1, T2> ToTuple2Func<D, T1, T2> toTuple( Func1<? super D, ? extends T1> mapper1, Func1<? super D, ? extends T2> mapper2) { return input -> { val v1 = mapper1.apply(input); val v2 = mapper2.apply(input); return Tuple.of(v1, v2); }; } static Func1<T, T> only(Predicate<? super T> checker); static Func1<T, T> forOnly(
Predicate<? super T> checker,
Func1<? super T, ? extends T> mapper); static Func1<T, T> when(
Predicate<? super T> checker,
Function<? super T, ? extends T> mapper,
Function<? super T, ? extends T> elseMapper); static Func1<D, T> firstOf(
FuncList<Function<? super D, ? extends T>> mappers); @SafeVarargs static Func1<D, T> firstOf(
Function<? super D, ? extends T> ... mappers); static ToTuple2Func<D, T1, T2> toTuple(
Func1<? super D, ? extends T1> mapper1,
Func1<? super D, ? extends T2> mapper2); static ToMapFunc<D, K, V> toMap(
K key, Func1<? super D, ? extends V> mapper); }### Answer:
@Test public void testTuple() { val f1 = toTuple ((String s)->s, (String s) -> s.length()) .thenReduce((a,b)-> a + " - " + b); Assert.assertEquals("Result:{ Value: Hello - 5 }", "" + Result.valueOf("Hello").map(f1)); } |
### Question:
ElmChoiceBuilder implements ElmTypeDef { public ILines typeDefinition() { val definition = line("type " + spec.typeName()); val choices = spec.sourceSpec() .choices.stream() .map(toCaseTypes) .map(toLine); val lines = linesOf(choices) .containWith("=", "|", null); return definition .append(indent(lines)); } ElmChoiceBuilder(ElmChoiceSpec spec); String typeName(); String encoderName(); String decoderName(); ILines typeDefinition(); ElmFunctionBuilder encoder(); ElmFunctionBuilder decoder(); String toElmCode(); }### Answer:
@Test public void testChoiceTypeDefinition() { val builder = setupBuilder(); assertEquals( "type LoginStatus\n" + " = LoggedIn String Int (List Int) (Maybe Float) Functionalj.Types.Elm.User\n" + " | LoggedOut", builder.typeDefinition().toText()); } |
### Question:
ElmChoiceBuilder implements ElmTypeDef { public ElmFunctionBuilder encoder() { val typeName = spec.typeName(); val name = encoderName(); val params = camelName(); val declaration = typeName + " -> Json.Encode.Value"; val caseExpr = line("case " + name + " of"); val choices = linesOf( spec.sourceSpec() .choices.stream() .map(toCaseField)); val body = caseExpr.append(choices.indent(1)); return new ElmFunctionBuilder(name, declaration, params, body); } ElmChoiceBuilder(ElmChoiceSpec spec); String typeName(); String encoderName(); String decoderName(); ILines typeDefinition(); ElmFunctionBuilder encoder(); ElmFunctionBuilder decoder(); String toElmCode(); }### Answer:
@Test public void testChoiceTypeEncoder() { val builder = setupBuilder(); assertEquals( "loginStatusEncoder : LoginStatus -> Json.Encode.Value\n" + "loginStatusEncoder loginStatus = \n" + " case loginStatusEncoder of\n" + " LoggedIn name age years wealth user ->\n" + " Json.Encode.object\n" + " [ ( \"__tagged\", Json.Encode.string \"LoggedIn\" )\n" + " , ( \"name\", Json.Encode.string name )\n" + " , ( \"age\", Json.Encode.int age )\n" + " , ( \"years\", Json.Encode.list Json.Encode.int years )\n" + " , ( \"wealth\", Maybe.withDefault Json.Encode.null (Maybe.map Json.Encode.float wealth) )\n" + " , ( \"user\", userEncoder user )\n" + " ]\n" + " LoggedOut ->\n" + " Json.Encode.object\n" + " [ ( \"__tagged\", Json.Encode.string \"LoggedOut\" )\n" + " ]", builder.encoder().toText()); } |
### Question:
Store { public Store<DATA> use(FuncUnit1<DATA> consumer) { if (consumer == null) return this; val value = dataRef.get(); consumer.accept(value); return this; } Store(DATA data); Store(
DATA data,
Func2<DATA, Result<DATA>, ChangeResult<DATA>> accepter); Store(
DATA data,
Func2<DATA, Result<DATA>, ChangeResult<DATA>> accepter,
Func2<DATA, Func1<DATA, DATA>, ChangeNotAllowedException> approver); ChangeResult<DATA> change(Func1<DATA, DATA> changer); @SafeVarargs final ChangeResult<DATA> change(Func1<DATA, DATA> changer, Func1<DATA, DATA> ... moreChangers); Store<DATA> use(FuncUnit1<DATA> consumer); DATA value(); Result<DATA> extract(); @Override String toString(); }### Answer:
@Test public void testUse() { val log = new ArrayList<String>(); val store = new Store<>(0); assertEquals("Store [data=0]", store.toString()); store .change(theInteger.add(1)) .store().use (value -> log.add("" + value)); assertEquals("Store [data=1]", store.toString()); } |
### Question:
Utils { public static String toCamelCase(String str) { if (str.equals(str.toUpperCase())) return str.toLowerCase(); if (str.length() <= 2) return str.toLowerCase(); val firstTwo = str.substring(0, 2); if (firstTwo.equals(firstTwo.toUpperCase())) { val first = str.replaceAll("^([A-Z]+)([A-Z][^A-Z]*)$", "$1"); val rest = str.substring(first.length()); return first.toLowerCase() + rest; } else { val first = str.replaceAll("^([A-Z]+[^A-Z])(.*)$", "$1"); val rest = str.substring(first.length()); return first.toLowerCase() + rest; } } static String templateRange(int fromInclusive, int toExclusive, String delimiter); static String toTitleCase(String str); static String toCamelCase(String str); static String switchClassName(String targetName, List<Case> choices); static String switchClassName(String targetName, List<Case> choices, int skip); static String toListCode(List<D> list, Function<D, String> toCode); static String toStringLiteral(String str); }### Answer:
@Test public void testCamelCase() { assertEquals("repeatAll", toCamelCase("RepeatAll")); assertEquals("rgbColor", toCamelCase("RGBColor")); assertEquals("rgb", toCamelCase("RGB")); assertEquals("repeat", toCamelCase("repeat")); assertEquals("repeat", toCamelCase("Repeat")); assertEquals("repeat", toCamelCase("REPEAT")); } |
### Question:
Utils { public static String toStringLiteral(String str) { if (str == null) return "null"; if (str.isEmpty()) return "\"\""; val matcher = pattern.matcher(str); val buffer = new StringBuffer(); while (matcher.find()) { val original = matcher.group(); if(original.length() == 0) continue; val replacement = findReplacement(original); matcher.appendReplacement(buffer, replacement); } matcher.appendTail(buffer); return "\"" + buffer.toString() + "\""; } static String templateRange(int fromInclusive, int toExclusive, String delimiter); static String toTitleCase(String str); static String toCamelCase(String str); static String switchClassName(String targetName, List<Case> choices); static String switchClassName(String targetName, List<Case> choices, int skip); static String toListCode(List<D> list, Function<D, String> toCode); static String toStringLiteral(String str); }### Answer:
@Test public void testStringLiteral() { assertEquals("\"-\\n-\\r-\\'-\\\"-\\\\\"-\"", toStringLiteral("-\n-\r-\'-\"-\\\"-")); } |
### Question:
KoanComparator implements Comparator<KoanMethod> { public int compare(KoanMethod arg0, KoanMethod arg1) { Class<?> declaringClass0 = arg0.getMethod().getDeclaringClass(); Class<?> declaringClass1 = arg1.getMethod().getDeclaringClass(); if(declaringClass0 != declaringClass1){ Logger.getAnonymousLogger().severe("no idea how to handle comparing the classes: " + declaringClass0 + " and: "+declaringClass1); return 0; } String contentsOfOriginalJavaFile = FileCompiler.getContentsOfJavaFile(DirectoryManager.getSourceDir(), declaringClass0.getName()); String pattern = ".*\\s%s(\\(|\\s*\\))"; Integer index0 = indexOfMatch(contentsOfOriginalJavaFile, String.format(pattern, arg0.getMethod().getName())); Integer index1 = indexOfMatch(contentsOfOriginalJavaFile, String.format(pattern, arg1.getMethod().getName())); return index0.compareTo(index1); } int compare(KoanMethod arg0, KoanMethod arg1); }### Answer:
@Test public void testThatKomparatorBombsWhenNotFound() throws Exception { Method m = new Object(){ @Koan public void someMethod(){} }.getClass().getDeclaredMethod("someMethod"); KoanComparator comparator = new KoanComparator(); try{ comparator.compare(KoanMethod.getInstance("2",m), KoanMethod.getInstance("1",m)); }catch(RuntimeException fileNotFound){} } |
### Question:
Strings { public static String getMessage(String key) { try { return MESSAGES_BUNDLE.getString(key); } catch (MissingResourceException e) { return new StringBuilder(UNFOUND_PROP_VALUE_STRING).append(key).append(UNFOUND_PROP_VALUE_STRING).toString(); } } private Strings(); static String getMessage(String key); static String getMessage(Class<?> clazz, String key); static String[] getMessages(Class<?> clazz, String key); static boolean wasNotFound(String lesson); }### Answer:
@Test public void testFallsBackToEnglishXmlWhenNoXmlForLocaleIsFound_eventIsLogged(){ Locale.setDefault(Locale.CHINA); assertLogged(Strings.class.getName(), new RBSensitiveLoggerExpectation(){ @Override protected void logCalled(LogRecord record) { assertEquals(Level.INFO, record.getLevel()); String expectation0 = "Your default language is not supported yet. "; String msg = record.getMessage(); assertTrue(msg.startsWith(expectation0)); assertTrue(msg.contains("messages_zh.properties")); } }); } |
### Question:
Strings { static ResourceBundle createResourceBundle() { ResourceBundle temp = null; try { temp = new PropertyResourceBundle(new FileInputStream( DirectoryManager.injectFileSystemSeparators( DirectoryManager.getProjectI18nDir(), new StringBuilder("messages_").append( Locale.getDefault().getLanguage()).append( ".properties").toString()))); } catch(FileNotFoundException x) { try { Logger.getLogger(Strings.class.getName()).log(Level.INFO, "Your default language is not supported yet. "+x.getLocalizedMessage()); temp = new PropertyResourceBundle(new FileInputStream( DirectoryManager.injectFileSystemSeparators( DirectoryManager.getProjectI18nDir(), "messages_en.properties"))); } catch (Exception e) { throw new RuntimeException(e); } } catch (Exception e) { throw new RuntimeException(e); } return temp; } private Strings(); static String getMessage(String key); static String getMessage(Class<?> clazz, String key); static String[] getMessages(Class<?> clazz, String key); static boolean wasNotFound(String lesson); }### Answer:
@Test public void testStringsBundleInitializationWithDefaultLocale() throws Exception { Locale.setDefault(Locale.US); assertNotNull(Strings.createResourceBundle()); }
@Test public void testStringsBundleInitializationWithNonDefaultLocale() throws Exception { Locale.setDefault(Locale.CHINA); assertNotNull(Strings.createResourceBundle()); } |
### Question:
PathToEnlightenment { static XmlToPathTransformer getXmlToPathTransformer(){ if(xmlToPathTransformer == null){ try { String filename = DirectoryManager.injectFileSystemSeparators( DirectoryManager.getConfigDir(), ApplicationSettings.getPathXmlFileName()); File file = new File(filename); if(!file.exists()){ throw new RuntimeException("No "+filename+" was found at: "+file.getAbsolutePath()); } xmlToPathTransformer = new XmlToPathTransformerImpl(filename, suiteName, koanMethod); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } return xmlToPathTransformer; } private PathToEnlightenment(); static void filterBySuite(String suite); static void filterByKoan(String koan); static Path getPathToEnlightenment(); }### Answer:
@Test public void testFallsBackToEnglishXmlWhenNoXmlForLocaleIsFound(){ Locale.setDefault(Locale.CHINA); PathToEnlightenment.xmlToPathTransformer = null; assertNotNull(PathToEnlightenment.getXmlToPathTransformer()); }
@Test public void testEnglishXmlWhenXmlForLocaleIsFound(){ Locale.setDefault(Locale.US); PathToEnlightenment.xmlToPathTransformer = null; assertNotNull(PathToEnlightenment.getXmlToPathTransformer()); } |
### Question:
RemoteMusicDatabaseServiceMusicBrainz implements
RemoteMusicDatabaseService { public StringBuffer appendDate(Date startDate, Date endDate, StringBuffer stringBuffer) { if (startDate == null && endDate == null) { return stringBuffer; } stringBuffer.append(SEARCH_DATE_BASE); if (startDate != null) { stringBuffer.append(dateFormat.format(startDate)); } else { stringBuffer.append("0"); } stringBuffer.append(SEARCH_DATE_TO); if (endDate != null) { stringBuffer.append(dateFormat.format(endDate)); } else { stringBuffer.append(SEARCH_DATE_OPEN_END); } stringBuffer.append(SEARCH_DATE_FINAL); return stringBuffer; } @Inject RemoteMusicDatabaseServiceMusicBrainz(
@ApplicationName String appName,
@ApplicationVersion String appVersion,
@ApplicationContact String appContact); @Override Artist findReleases(Artist artist, Date fromDate, Date endDate); StringBuffer appendDate(Date startDate, Date endDate,
StringBuffer stringBuffer); }### Answer:
@Test public void testAppendDate() { StringBuffer actual = new StringBuffer(); remoteMusicDatabaseServiceMusicBrainz.appendDate(null, expectedToDate, actual); assertEquals("Unexpected result for open start date", EXPECTED_STRING_OPEN_BEGINNING, actual.toString()); actual = new StringBuffer(); remoteMusicDatabaseServiceMusicBrainz.appendDate(expectedFromDate, null, actual); assertEquals("Unexpected result for open end date", EXPECTED_STRING_OPEN_END, actual.toString()); actual = new StringBuffer(); remoteMusicDatabaseServiceMusicBrainz.appendDate(null, null, actual); assertEquals("Unexpected result for open end date", EXPECTED_STRING_NO_DATES, actual.toString()); actual = new StringBuffer(); remoteMusicDatabaseServiceMusicBrainz.appendDate(expectedFromDate, expectedToDate, actual); assertEquals("Unexpected result for open end date", EXPECTED_STRING_REGULAR_DATES, actual.toString()); } |
### Question:
SqliteUtil { public static Integer toInteger(Boolean boolValue) { if (boolValue == null) { return null; } if (Boolean.FALSE.equals(boolValue)) { return FALSE; } return TRUE; } private SqliteUtil(); static void putIfNotNull(ContentValues values, String column,
Object value); static Date loadDate(Cursor cursor, int index); static Boolean loadBoolean(Cursor cursor, int index); static Boolean toBoolean(Integer intValue); static ContentValues toContentValues(Map<String, Object> input); static Integer toInteger(Boolean boolValue); static Integer loadInteger(Cursor cursor, int index); static Long loadLong(Cursor cursor, int index); static final Integer FALSE; static final Integer TRUE; }### Answer:
@Test public void testToIntegerFalse() { assertEquals(Integer.valueOf(0), SqliteUtil.toInteger(Boolean.FALSE)); }
@Test public void testToIntegerTrue() { assertEquals(Integer.valueOf(1), SqliteUtil.toInteger(Boolean.TRUE)); }
@Test public void testToIntegerNull() { assertNull(SqliteUtil.toInteger(null)); } |
### Question:
SqliteUtil { public static ContentValues toContentValues(Map<String, Object> input) { if (input == null) { return null; } Parcel parcel = Parcel.obtain(); parcel.writeMap(input); parcel.setDataPosition(0); return ContentValues.CREATOR.createFromParcel(parcel); } private SqliteUtil(); static void putIfNotNull(ContentValues values, String column,
Object value); static Date loadDate(Cursor cursor, int index); static Boolean loadBoolean(Cursor cursor, int index); static Boolean toBoolean(Integer intValue); static ContentValues toContentValues(Map<String, Object> input); static Integer toInteger(Boolean boolValue); static Integer loadInteger(Cursor cursor, int index); static Long loadLong(Cursor cursor, int index); static final Integer FALSE; static final Integer TRUE; }### Answer:
@Test public void testToContentValues() { Map<String, Object> expected = new HashMap<String, Object>(); expected.put("key1", Integer.valueOf(42)); expected.put("KEY2", "value2"); ContentValues actual = SqliteUtil.toContentValues(expected); assertEquals("ContentValues contans unexpected amount of values", expected.size(), actual.keySet().size()); for (Entry<String, Object> expectedEntry : expected.entrySet()) { assertEquals("ContentValue returns different value for key " + expectedEntry.getKey(), expectedEntry.getValue(), actual.get(expectedEntry.getKey())); } }
@Test public void testToContentValuesNull() { assertNull(SqliteUtil.toContentValues(null)); }
@Test public void testToContentValuesEmpty() { ContentValues actual = SqliteUtil .toContentValues(new HashMap<String, Object>()); assertEquals("ContentValues contans unexpected amount of values", 0, actual.keySet().size()); } |
### Question:
NusicWebViewActivity extends RoboActionBarActivity { @VisibleForTesting Intent createShareIntent() { return new Intent(Intent.ACTION_SEND) .setType("text/plain") .putExtra(Intent.EXTRA_SUBJECT, getExtraOrEmpty(EXTRA_SUBJECT)) .putExtra(Intent.EXTRA_TEXT, createShareText()); } @Override boolean onCreateOptionsMenu(Menu menu); @Override boolean onOptionsItemSelected(MenuItem item); static final String EXTRA_URL; static final String EXTRA_SUBJECT; }### Answer:
@Test public void createShareIntent() throws Exception { Intent intent = new Intent() .putExtra(NusicWebViewActivity.EXTRA_URL, expectedUrl) .putExtra(NusicWebViewActivity.EXTRA_SUBJECT, expectedSubject); NusicWebViewActivity activity = Robolectric.buildActivity(NusicWebViewActivity.class, intent).create().get(); Intent shareIntent = activity.createShareIntent(); Assert.assertEquals("subject", expectedSubject, shareIntent.getStringExtra(Intent.EXTRA_SUBJECT)); Assert.assertEquals("url", expectedUrl + "\n" + RuntimeEnvironment.application.getString(R.string.NusicWebViewActivity_sharedViaNusic), shareIntent.getStringExtra(Intent.EXTRA_TEXT)); }
@Test public void createShareIntentNoExtras() throws Exception { NusicWebViewActivity activity = Robolectric.setupActivity(NusicWebViewActivity.class); Intent shareIntent = activity.createShareIntent(); Assert.assertEquals("subject", "", shareIntent.getStringExtra(Intent.EXTRA_SUBJECT)); Assert.assertEquals("url", "", shareIntent.getStringExtra(Intent.EXTRA_TEXT)); } |
### Question:
DateUtil { public static Date addMinutes(int minutes) { return new Date(System.currentTimeMillis() + minutes * MILLIS_TO_MINUTES); } private DateUtil(); static Long toLong(Date date); static Date toDate(Long date); static Date addMinutes(int minutes); static long midnightUtc(Calendar cal); static long tomorrowMidnightUtc(); static long todayMidnightUtc(); static final int MILLIS_TO_MINUTES; }### Answer:
@Test public void testAddMinutes() { long testStartMillis = new Date().getTime(); long actualTime = DateUtil.addMinutes(ADD_MINUTES).getTime(); long expectedTime = testStartMillis + (ADD_MINUTES * MILLIS_TO_MINUTES); assertTrue("Added time amount is not great enough", actualTime >= expectedTime); } |
### Question:
DateUtil { public static long midnightUtc(Calendar cal) { int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(0); cal.set(year, month, day, 0, 0, 0); return cal.getTimeInMillis(); } private DateUtil(); static Long toLong(Date date); static Date toDate(Long date); static Date addMinutes(int minutes); static long midnightUtc(Calendar cal); static long tomorrowMidnightUtc(); static long todayMidnightUtc(); static final int MILLIS_TO_MINUTES; }### Answer:
@Test public void testMidnightUtcPlus() { Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC+2")); cal.set(2014, Calendar.JULY, 22, 1, 44, 55); long expected = 1405987200000l; long actual = DateUtil.midnightUtc(cal); assertEquals("Unexpected date returned", expected, actual); }
@Test public void testMidnightUtcMinus() { Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC-2")); cal.set(2014, Calendar.JULY, 22, 23, 44, 55); long expected = 1405987200000l; long actual = DateUtil.midnightUtc(cal); assertEquals("Unexpected date returned", expected, actual); } |
### Question:
NusicDatabaseSqlite extends SQLiteOpenHelper { static String createTable(String tableName, String... columnsAndTypeTuples) { StringBuffer sql = new StringBuffer(DATABASE_TABLE_CREATE).append( tableName).append("("); int index = 0; sql.append(columnsAndTypeTuples[index++]).append(" ") .append(columnsAndTypeTuples[index++]); while (index < columnsAndTypeTuples.length) { sql.append(", "); sql.append(columnsAndTypeTuples[index++]).append(" ") .append(columnsAndTypeTuples[index++]); } sql.append(");"); return sql.toString(); } NusicDatabaseSqlite(); @Override synchronized void close(); @Override void onCreate(SQLiteDatabase db); @Override void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion); }### Answer:
@Test public void testCreateTable() { String expected = "CREATE TABLE testdb(id INTEGER PRIMARY KEY AUTOINCREMENT, someText TEXT NOT NULL);"; String actual = NusicDatabaseSqlite.createTable("testdb", "id", "INTEGER PRIMARY KEY AUTOINCREMENT", "someText", "TEXT NOT NULL"); assertEquals("Unexpected sql query returned", expected, actual); } |
### Question:
SqliteUtil { public static Boolean toBoolean(Integer intValue) { if (intValue == null) { return null; } if (FALSE.equals(intValue)) { return Boolean.FALSE; } return Boolean.TRUE; } private SqliteUtil(); static void putIfNotNull(ContentValues values, String column,
Object value); static Date loadDate(Cursor cursor, int index); static Boolean loadBoolean(Cursor cursor, int index); static Boolean toBoolean(Integer intValue); static ContentValues toContentValues(Map<String, Object> input); static Integer toInteger(Boolean boolValue); static Integer loadInteger(Cursor cursor, int index); static Long loadLong(Cursor cursor, int index); static final Integer FALSE; static final Integer TRUE; }### Answer:
@Test public void testToBoolean0() { assertEquals(Boolean.FALSE, SqliteUtil.toBoolean(0)); }
@Test public void testToBoolean1() { assertEquals(Boolean.TRUE, SqliteUtil.toBoolean(1)); }
@Test public void testToBooleanGt1() { assertEquals(Boolean.TRUE, SqliteUtil.toBoolean(10000000)); }
@Test public void testToBooleanLt0() { assertEquals(Boolean.TRUE, SqliteUtil.toBoolean(-1)); }
@Test public void testToBooleanNull() { assertNull(SqliteUtil.toBoolean(null)); } |
### Question:
VersionsCommand extends DefaultCommand { @Override public void run() throws CLIException { new Versions() .run(); } @Override void run(); }### Answer:
@Test public void shouldPrintTheVersions() { command.run(); } |
### Question:
ES4X extends Launcher { public static void main(String... args) { final ES4X launcher = new ES4X(); if (args.length == 1) { boolean isFileOrDir; try { isFileOrDir = new File(args[0]).exists(); } catch (SecurityException e) { isFileOrDir = false; } if (isFileOrDir) { launcher.execute("run", args); return; } } launcher.dispatch(args); } @Override void beforeStartingVertx(VertxOptions options); static void main(String... args); }### Answer:
@Test public void testRun() throws IOException { File script = new File("unittest.js"); script.deleteOnExit(); try(OutputStream out = new FileOutputStream(script)) { out.write("console.log('Hello from unittest!');".getBytes()); } ES4X.main("run", script.getAbsolutePath()); }
@Test public void testLauncher() { ES4X.main("--help"); } |
### Question:
DockerfileCommand extends DefaultCommand { @Override public void run() throws CLIException { File dockerfile = new File(getCwd(), "Dockerfile"); if (dockerfile.exists()) { fatal("Dockerfile already exists."); } try (InputStream in = DockerfileCommand.class.getClassLoader().getResourceAsStream("META-INF/es4x-commands/Dockerfile")) { if (in == null) { fatal("Cannot load Dockerfile template."); } else { Files.copy(in, dockerfile.toPath()); } } catch (IOException e) { fatal(e.getMessage()); } File dockerignore = new File(getCwd(), ".dockerignore"); if (!dockerignore.exists()) { try (InputStream in = DockerfileCommand.class.getClassLoader().getResourceAsStream("META-INF/es4x-commands/.dockerignore")) { if (in == null) { fatal("Cannot load .dockerignore template."); } else { Files.copy(in, dockerignore.toPath()); } } catch (IOException e) { fatal(e.getMessage()); } } } @Override void run(); }### Answer:
@Test public void shouldCreateADockerFile() { command.setCwd(IOUtils.mkTempDir()); File file = new File(command.getCwd(), "Dockerfile"); file.deleteOnExit(); assertFalse(file.exists()); command.run(); assertTrue(file.exists()); } |
### Question:
InstallCommand extends DefaultCommand { @Override public void run() throws CLIException { command .setCwd(getCwd()) .run(); } @Option(longName = "vendor", shortName = "v") @Description("Comma separated list of vendor jars.") void setVendor(String vendor); @Option(longName = "link", shortName = "l", flag = true) @Description("Symlink jars instead of copy.") void setLink(boolean link); @Override void run(); }### Answer:
@Test public void shouldDownloadDependencies() throws IOException { command.setCwd(IOUtils.mkTempDir()); File packageJson = new File(command.getCwd(), "package.json"); packageJson.deleteOnExit(); assertFalse(packageJson.exists()); Map json = new HashMap(); json.put("name", "empty"); Map dependencies = new HashMap(); dependencies.put("@vertx/core", "3.6.3"); json.put("dependencies", dependencies); Map devDependencies = new HashMap(); devDependencies.put("@vertx/unit", "3.6.3"); json.put("devDependencies", devDependencies); List mvnDependencies = new ArrayList(); mvnDependencies.add("io.reactiverse:es4x:0.7.2"); mvnDependencies.add("io.vertx:vertx-core:3.6.3"); mvnDependencies.add("io.vertx:vertx-unit:3.6.3"); json.put("mvnDependencies", mvnDependencies); JSON.encode(packageJson, json); command.run(); } |
### Question:
ProjectCommand extends DefaultCommand { @Override public void run() throws CLIException { new Project() .setCwd(getCwd()) .run(); } @Option(longName = "ts", shortName = "t", flag = true) @Description("Init a TypeScript project.") void setForce(boolean force); @Override void run(); }### Answer:
@Test public void shouldCreateAnEmptyProject() throws IOException { command.setCwd(IOUtils.mkTempDir()); String projectName = command.getCwd().getName(); File packageJson = new File(command.getCwd(), "package.json"); packageJson.deleteOnExit(); assertFalse(packageJson.exists()); command.run(); assertTrue(packageJson.exists()); Map json = JSON.parse(packageJson); assertEquals(projectName, json.get("name")); } |
### Question:
Util { public static void generateLicense(PrintWriter writer) { writer.println(""); writer.println(); } private Util(); static boolean isOptionalModule(String name); static boolean isBlacklistedClass(String name); static List<?> jvmClasses(); static String genType(TypeInfo type); static String genType(TypeInfo type, boolean parameter); static String genGeneric(List<? extends TypeParamInfo> params); static boolean isImported(TypeInfo ref, Map<String, Object> session); static String getNPMScope(ModuleInfo module); static String includeFileIfPresent(String file); static void generateLicense(PrintWriter writer); static String cleanReserved(String value); static String getOverrideArgs(String type, String method); static String getOverrideReturn(String type, String method); static boolean isBlacklisted(String type, String method, Object params); static void generateDoc(PrintWriter writer, Doc doc, String margin); static void registerJvmClasses(); static void unregisterJvmClasses(); static CharSequence genType(String name); }### Answer:
@Test public void generateLicenseInputNullOutputNullPointerException() { final PrintWriter writer = null; thrown.expect(NullPointerException.class); Util.generateLicense(writer); } |
### Question:
Util { public static String genGeneric(List<? extends TypeParamInfo> params) { StringBuilder sb = new StringBuilder(); if (params.size() > 0) { sb.append("<"); boolean firstParam = true; for (TypeParamInfo p : params) { if (!firstParam) { sb.append(", "); } sb.append(p.getName()); firstParam = false; } sb.append(">"); } return sb.toString(); } private Util(); static boolean isOptionalModule(String name); static boolean isBlacklistedClass(String name); static List<?> jvmClasses(); static String genType(TypeInfo type); static String genType(TypeInfo type, boolean parameter); static String genGeneric(List<? extends TypeParamInfo> params); static boolean isImported(TypeInfo ref, Map<String, Object> session); static String getNPMScope(ModuleInfo module); static String includeFileIfPresent(String file); static void generateLicense(PrintWriter writer); static String cleanReserved(String value); static String getOverrideArgs(String type, String method); static String getOverrideReturn(String type, String method); static boolean isBlacklisted(String type, String method, Object params); static void generateDoc(PrintWriter writer, Doc doc, String margin); static void registerJvmClasses(); static void unregisterJvmClasses(); static CharSequence genType(String name); }### Answer:
@Test public void genGenericInput0OutputNotNull() { final ArrayList params = new ArrayList(); final String actual = Util.genGeneric(params); Assert.assertEquals("", actual); }
@Test public void genGenericInput1OutputClassCastException() { final ArrayList params = new ArrayList(); params.add(0); thrown.expect(ClassCastException.class); Util.genGeneric(params); }
@Test public void genGenericInput1OutputNullPointerException() { final ArrayList params = new ArrayList(); params.add(null); thrown.expect(NullPointerException.class); Util.genGeneric(params); } |
### Question:
TagGenerator { public String generate(final String artifactId, final String projectVersion) { return String.join(HYPHEN_DELIMITER, artifactId, projectVersion, Long.toString(currentTimeSource.get())); } @Inject TagGenerator(final CurrentTimeSource currentTimeSource); String generate(final String artifactId, final String projectVersion); }### Answer:
@Test public void testGenerate() { when(currentTimeSource.get()).thenReturn(CURRENT_TIME); String expected = String.join(HYPHEN_DELIMITER, ARTIFACT_ID, PROJECT_VERSION, Long.toString(CURRENT_TIME)); assertThat(tagGenerator.generate(ARTIFACT_ID, PROJECT_VERSION), equalTo(expected)); } |
### Question:
StagingMoveMojo extends StagingActionMojo { @Override public void execute() throws MojoFailureException { RepositoryManagerV3Client client = getRepositoryManagerV3Client(); failIfOffline(); if (destinationRepository == null || destinationRepository.isEmpty()) { throw new MojoFailureException("'destinationRepository' is required but was not found"); } try { tag = getTag(); sourceRepository = getSourceRepository(); getLog().info(format("Moving artifacts with tag '%s' from '%s' to '%s'", tag, sourceRepository, destinationRepository)); client.move(destinationRepository, createSearchCriteria(sourceRepository, tag)); } catch (RepositoryManagerException e) { String reason = format("%s. Reason: %s", e.getMessage(), e.getResponseMessage().isPresent() ? e.getResponseMessage().get() : e.getCause().getMessage()); throw new MojoFailureException(reason, e); } catch (Exception e) { throw new MojoFailureException(e.getMessage(), e); } } @Override void execute(); }### Answer:
@Test(expected = MojoFailureException.class) public void testFailsWhenOffline() throws Exception { underTest.setOffline(true); underTest.execute(); }
@Test(expected = MojoFailureException.class) public void testFailWhenTagIsNull() throws Exception { underTest.setTag(null); underTest.execute(); }
@Test(expected = MojoFailureException.class) public void testFailWhenTagIsNotFound() throws Exception { setupPropertiesFile(EMPTY); underTest.setTag(null); underTest.execute(); }
@Test public void testMove() throws Exception { underTest.execute(); Map<String, String> searchCriteria = ImmutableMap.of("repository", SOURCE_REPOSITORY, "tag", TAG); verify(client).move(eq(DESTINATION_REPOSITORY), eq(searchCriteria)); } |
### Question:
StagingMoveMojo extends StagingActionMojo { @VisibleForTesting Map<String, String> createSearchCriteria(final String repository, final String tag) { return SearchBuilder.create().withRepository(repository).withTag(tag).build(); } @Override void execute(); }### Answer:
@Test public void testGetSearchCriteria() throws Exception { Map<String, String> expectedCriteria = ImmutableMap.of("repository", "foo", "tag", "bah"); assertThat(underTest.createSearchCriteria("foo", "bah"), equalTo(expectedCriteria)); } |
### Question:
Nxrm3ClientFactory { public RepositoryManagerV3Client build(final ServerConfig serverConfig) { return RepositoryManagerV3ClientBuilder.create().withServerConfig(serverConfig).build(); } RepositoryManagerV3Client build(final ServerConfig serverConfig); }### Answer:
@Test public void buildClient() throws Exception { RepositoryManagerV3Client client = new Nxrm3ClientFactory().build(serverConfig); assertThat(client, is(notNullValue())); } |
### Question:
PBKDF2PasswordHash { public static String createHash(String password) throws NoSuchAlgorithmException, InvalidKeySpecException { return createHash(password.toCharArray()); } private PBKDF2PasswordHash(); static String createHash(String password); static String createHash(char[] password); static boolean validatePassword(String password, String goodHash); static boolean validatePassword(char[] password, String goodHash); static final String PBKDF2_ALGORITHM; static final int SALT_BYTES; static final int HASH_BYTES; static final int PBKDF2_ITERATIONS; static final int ITERATION_INDEX; static final int SALT_INDEX; static final int PBKDF2_INDEX; }### Answer:
@Test public void testCreate() throws InvalidKeySpecException, NoSuchAlgorithmException { String hash = createHash("password10"); Assert.assertNotNull(hash); } |
### Question:
DateUtil { @Nonnull public static LocalDate parseStringToDateOrReturnNow(@Nullable String stringDate) { LocalDate date = LocalDate.now(); if (stringDate != null && !stringDate.isEmpty()) { date = parseStringToDate(stringDate); } return date; } private DateUtil(); @Nonnull static LocalDate parseStringToDateNullSafe(@Nonnull String stringDate); @Nonnull static LocalDate parseStringToDateOrReturnNow(@Nullable String stringDate); @Nonnull static LocalDate parseStringToDate(@Nonnull String stringDate); @Nonnull static LocalDateTime parseStringToDateTimeOrReturnNow(@Nonnull String stringDateTime); static boolean isWeekend(@Nonnull LocalDate date); static boolean isHoliday(@Nonnull LocalDate date); static LocalDate getMax(@Nonnull LocalDate date1, @Nonnull LocalDate date2); static LocalDate getMin(@Nonnull LocalDate date1, @Nonnull LocalDate date2); }### Answer:
@Test public void parseStringToDateOrReturnNowTestNullString() { final LocalDate now = LocalDate.now(); final LocalDate returnedDate = DateUtil.parseStringToDateOrReturnNow(null); Assert.assertNotNull(returnedDate); Assert.assertTrue(now.isEqual(returnedDate)); }
@Test public void parseStringToDateOrReturnNowTestEmptyString() { final LocalDate now = LocalDate.now(); final LocalDate returnedDate = DateUtil.parseStringToDateOrReturnNow(""); Assert.assertNotNull(returnedDate); Assert.assertTrue(now.isEqual(returnedDate)); }
@Test public void parseStringToDateOrReturnNowTest() { final LocalDate now = LocalDate.now(); final LocalDate returnedDate = DateUtil.parseStringToDateOrReturnNow("2015-12-31"); Assert.assertNotNull(returnedDate); Assert.assertEquals(2015, returnedDate.getYear()); Assert.assertEquals(12, returnedDate.getMonthValue()); Assert.assertEquals(31, returnedDate.getDayOfMonth()); } |
### Question:
InvestorServicesFetchOperations { public List<Investor> fetchAllInvestors() { return InvestorService.investorsList; } List<Investor> fetchAllInvestors(); Investor fetchInvestorById(String investorId); List<Stock> fetchStocksByInvestorId(String investorId, int offset, int limit); Stock fetchSingleStockByInvestorIdAndStockSymbol(String investorId, String symbol); }### Answer:
@Test public void testFetchAllInvestors() { int expectedSize = 2; int actualListSize = new InvestorServicesFetchOperations().fetchAllInvestors().size(); assertEquals(expectedSize, actualListSize); } |
### Question:
InvestorServicesFetchOperations { public Investor fetchInvestorById(String investorId) { return InvestorService.investorsList.stream() .filter(investors -> investorId.equalsIgnoreCase(investors.getId())).findAny().orElse(null); } List<Investor> fetchAllInvestors(); Investor fetchInvestorById(String investorId); List<Stock> fetchStocksByInvestorId(String investorId, int offset, int limit); Stock fetchSingleStockByInvestorIdAndStockSymbol(String investorId, String symbol); }### Answer:
@Test public void testFetchInvestorById() { Investor actualInvestor = getInvestorServiceForTest().fetchInvestorById("invr_1"); Investor expectedInvestor = new Investor("INVR_1", "Investor ONE", "conservative investor", getStocksSetOne()); assertEquals(actualInvestor.getId(), expectedInvestor.getId()); actualInvestor = getInvestorServiceForTest().fetchInvestorById("invr_2"); expectedInvestor = new Investor("INVR_2", "Investor TWO", "Moderate Risk investor", getStocksSetTwo()); assertEquals(expectedInvestor.getId(), actualInvestor.getId()); } |
### Question:
InvestorService { public Investor fetchInvestorById(String investorId) { return investorsList.stream().filter(investors -> investorId.equalsIgnoreCase(investors.getId())).findAny() .orElse(null); } List<Investor> fetchAllInvestors(); Investor fetchInvestorById(String investorId); List<Stock> fetchStocksByInvestorId(String investorId, int offset, int limit); Stock fetchSingleStockByInvestorIdAndStockSymbol(String investorId, String symbol); Stock addNewStockToTheInvestorPortfolio(String investorId, Stock newStock); boolean deleteStockFromTheInvestorPortfolio(String investorId, String stockTobeDeletedSymbol); Stock updateAStockByInvestorIdAndStock(String investorId, Stock stockTobeUpdated); Stock updateAStockByInvestorIdAndStock(String investorId, String symbol, Stock stockTobeUpdated); }### Answer:
@Test public void testFetchInvestorById() { Investor actualInvestor = getInvestorServiceForTest().fetchInvestorById("invr_1"); Investor expectedInvestor = new Investor("INVR_1", "Investor ONE", "conservative investor", getStocksSetOne()); assertEquals(actualInvestor.getId(), expectedInvestor.getId()); actualInvestor = getInvestorServiceForTest().fetchInvestorById("invr_2"); expectedInvestor = new Investor("INVR_2", "Investor TWO", "Moderate Risk investor", getStocksSetTwo()); assertEquals(expectedInvestor.getId(), actualInvestor.getId()); } |
### Question:
InvestorServicesFetchOperations { public List<Stock> fetchStocksByInvestorId(String investorId, int offset, int limit) { Investor investor = fetchInvestorById(investorId); return investor.getStocks().subList(getStartFrom(offset, investor), getToIndex(offset, limit, investor)); } List<Investor> fetchAllInvestors(); Investor fetchInvestorById(String investorId); List<Stock> fetchStocksByInvestorId(String investorId, int offset, int limit); Stock fetchSingleStockByInvestorIdAndStockSymbol(String investorId, String symbol); }### Answer:
@Test public void testFetchStocksByInvestorId() { Investor expectedInvestor = getInvestorServiceForTest().fetchInvestorById("invr_1"); String expectedStockSymbol = "EXB"; assertEquals(4,expectedInvestor.getStocks().size()); Stock expectedStock = expectedInvestor.getStocks().stream() .filter(stock -> expectedStockSymbol.equalsIgnoreCase(stock.getSymbol())).findAny().orElse(null); assertNotNull(expectedStock); } |
### Question:
InvestorServicesFetchOperations { public Stock fetchSingleStockByInvestorIdAndStockSymbol(String investorId, String symbol) { Investor investor = fetchInvestorById(investorId); return investor.getStocks().stream().filter(stock -> symbol.equalsIgnoreCase(stock.getSymbol())).findAny() .orElse(null); } List<Investor> fetchAllInvestors(); Investor fetchInvestorById(String investorId); List<Stock> fetchStocksByInvestorId(String investorId, int offset, int limit); Stock fetchSingleStockByInvestorIdAndStockSymbol(String investorId, String symbol); }### Answer:
@Test public void testFetchSingleStockByInvestorIdAndStockSymbol() { String investorId = "Invr_1"; String expectedSymbol = "EXA"; String actualSymbol = (getInvestorServiceForTest() .fetchSingleStockByInvestorIdAndStockSymbol(investorId, expectedSymbol).getSymbol()); assertEquals(expectedSymbol, actualSymbol); } |
### Question:
InvestorService { public boolean deleteAStockFromTheInvestorPortfolio(String investorId, String stockTobeDeletedSymbol) { return deleteServiceFacade.deleteAStock(investorId, stockTobeDeletedSymbol); } Stock addNewStockToTheInvestorPortfolio(String investorId, Stock newStock); boolean deleteAStockFromTheInvestorPortfolio(String investorId, String stockTobeDeletedSymbol); Stock updateAStockByInvestorIdAndStock(String investorId, Stock stockTobeUpdated); Stock updateAStockByInvestorIdAndStock(String investorId, String symbol, Stock stockTobeUpdated); List<Stock> bulkUpdateOfStocksByInvestorId(String investorId, List<Stock> stocksTobeUpdated); }### Answer:
@Test public void testDeleteAStockToTheInvestorPortfolio() { Stock actualStock = new Stock("EXA", 150, 18.5); getInvestorServiceForTest().deleteAStockFromTheInvestorPortfolio("invr_1", actualStock.getSymbol()); Stock expectedStock = getInvestorServiceFetchOperationsForTest() .fetchSingleStockByInvestorIdAndStockSymbol("invr_1", "EXa"); assertNull(expectedStock); } |
### Question:
InvestorService { public List<Investor> fetchAllInvestors() { return investorsList; } List<Investor> fetchAllInvestors(); Investor fetchInvestorById(String investorId); List<Stock> fetchStocksByInvestorId(String investorId, int offset, int limit); Stock fetchSingleStockByInvestorIdAndStockSymbol(String investorId, String symbol); String welcomePage(); }### Answer:
@Test public void testFetchAllInvestors() { int expectedSize = 2; int actualListSize = getInvestorServiceForTest().fetchAllInvestors().size(); assertEquals(expectedSize, actualListSize); } |
### Question:
InvestorService { public Investor fetchInvestorById(String investorId) { return investorsList.stream().filter(investors -> investorId.equalsIgnoreCase(investors.getId())).findAny() .orElse(null); } List<Investor> fetchAllInvestors(); Investor fetchInvestorById(String investorId); List<Stock> fetchStocksByInvestorId(String investorId, int offset, int limit); Stock fetchSingleStockByInvestorIdAndStockSymbol(String investorId, String symbol); String welcomePage(); }### Answer:
@Test public void testFetchInvestorById() { Investor actualInvestor = getInvestorServiceForTest().fetchInvestorById("invr_1"); Investor expectedInvestor = new Investor("INVR_1", "Investor ONE", "conservative investor", getStocksSetOne()); assertEquals(actualInvestor.getId(), expectedInvestor.getId()); actualInvestor = getInvestorServiceForTest().fetchInvestorById("invr_2"); expectedInvestor = new Investor("INVR_2", "Investor TWO", "Moderate Risk investor", getStocksSetTwo()); assertEquals(expectedInvestor.getId(), actualInvestor.getId()); } |
### Question:
InvestorService { public List<Stock> fetchStocksByInvestorId(String investorId, int offset, int limit) { Investor investor = fetchInvestorById(investorId); return investor.getStocks().subList(getStartFrom(offset, investor), getToIndex(offset, limit, investor)); } List<Investor> fetchAllInvestors(); Investor fetchInvestorById(String investorId); List<Stock> fetchStocksByInvestorId(String investorId, int offset, int limit); Stock fetchSingleStockByInvestorIdAndStockSymbol(String investorId, String symbol); Stock addNewStockToTheInvestorPortfolio(String investorId, Stock newStock); boolean deleteStockFromTheInvestorPortfolio(String investorId, String stockTobeDeletedSymbol); Stock updateAStockByInvestorIdAndStock(String investorId, Stock stockTobeUpdated); Stock updateAStockByInvestorIdAndStock(String investorId, String symbol, Stock stockTobeUpdated); }### Answer:
@Test public void testFetchStocksByInvestorId() { Investor expectedInvestor = getInvestorServiceForTest().fetchInvestorById("invr_1"); String expectedStockSymbol = "EXB"; assertEquals(expectedInvestor.getStocks().size(), 4); Stock expectedStock = expectedInvestor.getStocks().stream() .filter(stock -> expectedStockSymbol.equalsIgnoreCase(stock.getSymbol())).findAny().orElse(null); assertNotNull(expectedStock); } |
### Question:
InvestorService { public List<Stock> fetchStocksByInvestorId(String investorId, int offset, int limit) { Investor investor = fetchInvestorById(investorId); return investor.getStocks().subList(getStartFrom(offset, investor), getToIndex(offset, limit, investor)); } List<Investor> fetchAllInvestors(); Investor fetchInvestorById(String investorId); List<Stock> fetchStocksByInvestorId(String investorId, int offset, int limit); Stock fetchSingleStockByInvestorIdAndStockSymbol(String investorId, String symbol); String welcomePage(); }### Answer:
@Test public void testFetchStocksByInvestorId() { Investor expectedInvestor = getInvestorServiceForTest().fetchInvestorById("invr_1"); String expectedStockSymbol = "EXB"; assertEquals(expectedInvestor.getStocks().size(), 4); Stock expectedStock = expectedInvestor.getStocks().stream() .filter(stock -> expectedStockSymbol.equalsIgnoreCase(stock.getSymbol())).findAny().orElse(null); assertNotNull(expectedStock); } |
### Question:
InvestorService { public Stock fetchSingleStockByInvestorIdAndStockSymbol(String investorId, String symbol) { Investor investor = fetchInvestorById(investorId); return investor.getStocks().stream().filter(stock -> symbol.equalsIgnoreCase(stock.getSymbol())).findAny() .orElse(null); } List<Investor> fetchAllInvestors(); Investor fetchInvestorById(String investorId); List<Stock> fetchStocksByInvestorId(String investorId, int offset, int limit); Stock fetchSingleStockByInvestorIdAndStockSymbol(String investorId, String symbol); String welcomePage(); }### Answer:
@Test public void testFetchSingleStockByInvestorIdAndStockSymbol() { String investorId = "Invr_1"; String expectedSymbol = "EXA"; String actualSymbol = (getInvestorServiceForTest() .fetchSingleStockByInvestorIdAndStockSymbol(investorId, expectedSymbol).getSymbol()); assertEquals(expectedSymbol, actualSymbol); } |
### Question:
InvestorService { public List<Investor> fetchAllInvestors() { return investorsList; } List<Investor> fetchAllInvestors(); Investor fetchInvestorById(String investorId); List<Stock> fetchStocksByInvestorId(String investorId, int offset, int limit); Stock fetchSingleStockByInvestorIdAndStockSymbol(String investorId, String symbol); @HystrixCommand(fallbackMethod="welcomeUrlFailureFallback") String circuitBreakerImplWelcome(); String welcomeUrlFailureFallback(); }### Answer:
@Test public void testFetchAllInvestors() { int expectedSize = 2; int actualListSize = getInvestorServiceForTest().fetchAllInvestors().size(); assertEquals(expectedSize, actualListSize); } |
### Question:
InvestorService { public Investor fetchInvestorById(String investorId) { return investorsList.stream().filter(investors -> investorId.equalsIgnoreCase(investors.getId())).findAny() .orElse(null); } List<Investor> fetchAllInvestors(); Investor fetchInvestorById(String investorId); List<Stock> fetchStocksByInvestorId(String investorId, int offset, int limit); Stock fetchSingleStockByInvestorIdAndStockSymbol(String investorId, String symbol); @HystrixCommand(fallbackMethod="welcomeUrlFailureFallback") String circuitBreakerImplWelcome(); String welcomeUrlFailureFallback(); }### Answer:
@Test public void testFetchInvestorById() { Investor actualInvestor = getInvestorServiceForTest().fetchInvestorById("invr_1"); Investor expectedInvestor = new Investor("INVR_1", "Investor ONE", "conservative investor", getStocksSetOne()); assertEquals(actualInvestor.getId(), expectedInvestor.getId()); actualInvestor = getInvestorServiceForTest().fetchInvestorById("invr_2"); expectedInvestor = new Investor("INVR_2", "Investor TWO", "Moderate Risk investor", getStocksSetTwo()); assertEquals(expectedInvestor.getId(), actualInvestor.getId()); } |
### Question:
InvestorService { public List<Stock> fetchStocksByInvestorId(String investorId, int offset, int limit) { Investor investor = fetchInvestorById(investorId); return investor.getStocks().subList(getStartFrom(offset, investor), getToIndex(offset, limit, investor)); } List<Investor> fetchAllInvestors(); Investor fetchInvestorById(String investorId); List<Stock> fetchStocksByInvestorId(String investorId, int offset, int limit); Stock fetchSingleStockByInvestorIdAndStockSymbol(String investorId, String symbol); @HystrixCommand(fallbackMethod="welcomeUrlFailureFallback") String circuitBreakerImplWelcome(); String welcomeUrlFailureFallback(); }### Answer:
@Test public void testFetchStocksByInvestorId() { Investor expectedInvestor = getInvestorServiceForTest().fetchInvestorById("invr_1"); String expectedStockSymbol = "EXB"; assertEquals(expectedInvestor.getStocks().size(), 4); Stock expectedStock = expectedInvestor.getStocks().stream() .filter(stock -> expectedStockSymbol.equalsIgnoreCase(stock.getSymbol())).findAny().orElse(null); assertNotNull(expectedStock); } |
### Question:
InvestorService { public Stock fetchSingleStockByInvestorIdAndStockSymbol(String investorId, String symbol) { Investor investor = fetchInvestorById(investorId); return investor.getStocks().stream().filter(stock -> symbol.equalsIgnoreCase(stock.getSymbol())).findAny() .orElse(null); } List<Investor> fetchAllInvestors(); Investor fetchInvestorById(String investorId); List<Stock> fetchStocksByInvestorId(String investorId, int offset, int limit); Stock fetchSingleStockByInvestorIdAndStockSymbol(String investorId, String symbol); @HystrixCommand(fallbackMethod="welcomeUrlFailureFallback") String circuitBreakerImplWelcome(); String welcomeUrlFailureFallback(); }### Answer:
@Test public void testFetchSingleStockByInvestorIdAndStockSymbol() { String investorId = "Invr_1"; String expectedSymbol = "EXA"; String actualSymbol = (getInvestorServiceForTest() .fetchSingleStockByInvestorIdAndStockSymbol(investorId, expectedSymbol).getSymbol()); assertEquals(expectedSymbol, actualSymbol); } |
### Question:
InvestorService { public Stock fetchSingleStockByInvestorIdAndStockSymbol(String investorId, String symbol) { Investor investor = fetchInvestorById(investorId); return investor.getStocks().stream().filter(stock -> symbol.equalsIgnoreCase(stock.getSymbol())).findAny() .orElse(null); } List<Investor> fetchAllInvestors(); Investor fetchInvestorById(String investorId); List<Stock> fetchStocksByInvestorId(String investorId, int offset, int limit); Stock fetchSingleStockByInvestorIdAndStockSymbol(String investorId, String symbol); Stock addNewStockToTheInvestorPortfolio(String investorId, Stock newStock); boolean deleteStockFromTheInvestorPortfolio(String investorId, String stockTobeDeletedSymbol); Stock updateAStockByInvestorIdAndStock(String investorId, Stock stockTobeUpdated); Stock updateAStockByInvestorIdAndStock(String investorId, String symbol, Stock stockTobeUpdated); }### Answer:
@Test public void testFetchSingleStockByInvestorIdAndStockSymbol() { String investorId = "Invr_1"; String expectedSymbol = "EXA"; String actualSymbol = (getInvestorServiceForTest() .fetchSingleStockByInvestorIdAndStockSymbol(investorId, expectedSymbol).getSymbol()); assertEquals(expectedSymbol, actualSymbol); } |
### Question:
InvestorService { public boolean deleteStockFromTheInvestorPortfolio(String investorId, String stockTobeDeletedSymbol) { boolean deletedStatus = false; Stock stockTobeDeleted = investorServicesFetchOperations.fetchSingleStockByInvestorIdAndStockSymbol(investorId, stockTobeDeletedSymbol); if (stockTobeDeleted != null) { Investor investor = investorServicesFetchOperations.fetchInvestorById(investorId); deletedStatus = investor.getStocks().remove(stockTobeDeleted); } designForIntentCascadePortfolioDelete(investorId, deletedStatus); return deletedStatus; } Stock addNewStockToTheInvestorPortfolio(String investorId, Stock newStock); boolean deleteStockFromTheInvestorPortfolio(String investorId, String stockTobeDeletedSymbol); Stock updateAStockByInvestorIdAndStock(String investorId, Stock stockTobeUpdated); Stock updateAStockByInvestorIdAndStock(String investorId, String symbol, Stock stockTobeUpdated); List<Stock> bulkUpdateOfStocksByInvestorId(String investorId, List<Stock> stocksTobeUpdated); }### Answer:
@Test public void testDeleteAStockToTheInvestorPortfolio() { Stock actualStock = new Stock("EXA", 150, 18.5); getInvestorServiceForTest().deleteStockFromTheInvestorPortfolio("invr_1", actualStock.getSymbol()); Stock expectedStock = getInvestorServiceFetchOperationsForTest() .fetchSingleStockByInvestorIdAndStockSymbol("invr_1", "EXa"); assertNull(expectedStock); } |
### Question:
InvestorService { public Stock addNewStockToTheInvestorPortfolio(String investorId, Stock newStock) { if (isPreConditionSuccess(investorId, newStock) && isNewStockInsertSucess(investorId, newStock)) { designForIntentCascadePortfolioAdd(investorId); return fetchSingleStockByInvestorIdAndStockSymbol(investorId, newStock.getSymbol()); } return null; } List<Investor> fetchAllInvestors(); Investor fetchInvestorById(String investorId); List<Stock> fetchStocksByInvestorId(String investorId, int offset, int limit); Stock fetchSingleStockByInvestorIdAndStockSymbol(String investorId, String symbol); Stock addNewStockToTheInvestorPortfolio(String investorId, Stock newStock); boolean deleteStockFromTheInvestorPortfolio(String investorId, String stockTobeDeletedSymbol); Stock updateAStockByInvestorIdAndStock(String investorId, Stock stockTobeUpdated); Stock updateAStockByInvestorIdAndStock(String investorId, String symbol, Stock stockTobeUpdated); }### Answer:
@Test public void testAddNewStocksToTheInvestorPortfolioFailsWhenTryInsertingDuplicate() { String investorId = "invr_1"; String actualStockSymbol = "EXe"; Stock actualStock = new Stock(actualStockSymbol, 150, 18.5); InvestorService localInvestorService = getInvestorServiceForTest(); assertNotNull(localInvestorService.addNewStockToTheInvestorPortfolio(investorId, actualStock)); assertNull(localInvestorService.addNewStockToTheInvestorPortfolio(investorId, actualStock)); } |
### Question:
InvestorService { public List<Investor> fetchAllInvestors() { return investorsList; } List<Investor> fetchAllInvestors(); Investor fetchInvestorById(String investorId); List<Stock> fetchStocksByInvestorId(String investorId, int offset, int limit); Stock fetchSingleStockByInvestorIdAndStockSymbol(String investorId, String symbol); Stock addNewStockToTheInvestorPortfolio(String investorId, Stock newStock); boolean deleteStockFromTheInvestorPortfolio(String investorId, String stockTobeDeletedSymbol); Stock updateAStockByInvestorIdAndStock(String investorId, Stock stockTobeUpdated); Stock updateAStockByInvestorIdAndStock(String investorId, String symbol, Stock stockTobeUpdated); }### Answer:
@Test public void testFetchAllInvestors() { int expectedSize = 2; int actualListSize = getInvestorServiceForTest().fetchAllInvestors().size(); assertEquals(expectedSize, actualListSize); } |
### Question:
User implements Serializable { public void setName(String name) { this.name = name; } User(); User(String name, String email); Integer getId(); void setId(Integer id); String getName(); void setName(String name); String getEmail(); void setEmail(String email); @Override int hashCode(); @Override boolean equals(Object object); @Override String toString(); }### Answer:
@Test public void update() { User user = new User("User", "user@test.com"); user = userBean.add(user); user.setName("User1"); userBean.update(user); Assert.assertNotNull(userBean.findByName("User1")); } |
### Question:
MeliSpinner extends FrameLayout { @Deprecated public final MeliSpinner setSpinnerMode(final SpinnerMode mode) { size = mode == SpinnerMode.BIG_WHITE || mode == SpinnerMode.BIG_YELLOW ? LARGE : SMALL; configureSpinner(mode.primaryColor, mode.secondaryColor); return this; } MeliSpinner(final Context context); MeliSpinner(final Context context, final AttributeSet attrs); @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") MeliSpinner(final Context context, final AttributeSet attrs, final int defStyleAttr); void setSize(@SpinnerSize final int size); void setPrimaryColor(@ColorRes final int primaryColor); void setSecondaryColor(@ColorRes final int secondaryColor); MeliSpinner setText(final CharSequence text); @Deprecated final MeliSpinner setSpinnerMode(final SpinnerMode mode); @Deprecated void start(); @Deprecated void stop(); }### Answer:
@Test public void testDefaultInitialization() { spinner.setSpinnerMode(MeliSpinner.SpinnerMode.BIG_YELLOW); final TextView textView = getTextView(spinner); Assert.assertNotNull(textView); Assert.assertEquals(View.GONE, textView.getVisibility()); final LoadingSpinner loadingSpinner = getLoadingSpinner(spinner); Assert.assertNotNull(loadingSpinner); Assert.assertEquals(View.VISIBLE, loadingSpinner.getVisibility()); } |
### Question:
ErrorView extends LinearLayout { public void setImage(@DrawableRes final int drawable) { setImage(drawable, null); } ErrorView(final Context context); ErrorView(final Context context, final AttributeSet attrs); ErrorView(final Context context, final AttributeSet attrs, final int defStyleAttr); @TargetApi(Build.VERSION_CODES.LOLLIPOP) ErrorView(final Context context, final AttributeSet attrs, final int defStyleAttr, final int defStyleRes); void setImage(@DrawableRes final int drawable); void setImage(@DrawableRes final int drawable, @Nullable final String contentDescription); void setTitle(@Nullable final String titleText); void setTitle(@StringRes final int resId); void setSubtitle(@Nullable final String subtitleText); void setSubtitle(@StringRes final int resId); void setButton(@Nullable final String buttonLabel, @Nullable final OnClickListener onClickListener); void setButton(@StringRes final int resId, @Nullable final OnClickListener onClickListener); @Override String toString(); }### Answer:
@Test public void testCustomImage() { assertEquals("The ErrorView image should be gone", View.GONE, image.getVisibility()); errorView.setImage(0); assertEquals("The ErrorView image should be gone", View.GONE, image.getVisibility()); errorView.setImage(R.drawable.ui_button_style_primary); assertEquals("The ErrorView image should be visible", View.VISIBLE, image.getVisibility()); } |
### Question:
ErrorView extends LinearLayout { public void setTitle(@Nullable final String titleText) { if (titleText == null) { title.setText(null); title.setVisibility(GONE); } else { title.setText(titleText); title.setVisibility(VISIBLE); } } ErrorView(final Context context); ErrorView(final Context context, final AttributeSet attrs); ErrorView(final Context context, final AttributeSet attrs, final int defStyleAttr); @TargetApi(Build.VERSION_CODES.LOLLIPOP) ErrorView(final Context context, final AttributeSet attrs, final int defStyleAttr, final int defStyleRes); void setImage(@DrawableRes final int drawable); void setImage(@DrawableRes final int drawable, @Nullable final String contentDescription); void setTitle(@Nullable final String titleText); void setTitle(@StringRes final int resId); void setSubtitle(@Nullable final String subtitleText); void setSubtitle(@StringRes final int resId); void setButton(@Nullable final String buttonLabel, @Nullable final OnClickListener onClickListener); void setButton(@StringRes final int resId, @Nullable final OnClickListener onClickListener); @Override String toString(); }### Answer:
@Test public void testCustomTitle() { assertEquals("The ErrorView title should be gone", View.GONE, title.getVisibility()); errorView.setTitle(null); assertEquals("The ErrorView title should be gone", View.GONE, title.getVisibility()); errorView.setTitle(TEST_TEXT); assertEquals("The ErrorView title should be visible", View.VISIBLE, title.getVisibility()); } |
### Question:
ErrorView extends LinearLayout { public void setSubtitle(@Nullable final String subtitleText) { if (subtitleText == null) { subtitle.setText(null); subtitle.setVisibility(GONE); } else { subtitle.setText(subtitleText); subtitle.setVisibility(VISIBLE); } } ErrorView(final Context context); ErrorView(final Context context, final AttributeSet attrs); ErrorView(final Context context, final AttributeSet attrs, final int defStyleAttr); @TargetApi(Build.VERSION_CODES.LOLLIPOP) ErrorView(final Context context, final AttributeSet attrs, final int defStyleAttr, final int defStyleRes); void setImage(@DrawableRes final int drawable); void setImage(@DrawableRes final int drawable, @Nullable final String contentDescription); void setTitle(@Nullable final String titleText); void setTitle(@StringRes final int resId); void setSubtitle(@Nullable final String subtitleText); void setSubtitle(@StringRes final int resId); void setButton(@Nullable final String buttonLabel, @Nullable final OnClickListener onClickListener); void setButton(@StringRes final int resId, @Nullable final OnClickListener onClickListener); @Override String toString(); }### Answer:
@Test public void testCustomSubtitle() { assertEquals("The ErrorView subtitle should be gone", View.GONE, subtitle.getVisibility()); errorView.setSubtitle(null); assertEquals("The ErrorView subtitle should be gone", View.GONE, subtitle.getVisibility()); errorView.setSubtitle(TEST_TEXT); assertEquals("The ErrorView subtitle should be visible", View.VISIBLE, subtitle.getVisibility()); } |
### Question:
ErrorView extends LinearLayout { public void setButton(@Nullable final String buttonLabel, @Nullable final OnClickListener onClickListener) { if (buttonLabel == null || onClickListener == null) { button.setText(null); button.setVisibility(GONE); } else { button.setText(buttonLabel); button.setOnClickListener(onClickListener); button.setVisibility(VISIBLE); } buttonClickListener = onClickListener; } ErrorView(final Context context); ErrorView(final Context context, final AttributeSet attrs); ErrorView(final Context context, final AttributeSet attrs, final int defStyleAttr); @TargetApi(Build.VERSION_CODES.LOLLIPOP) ErrorView(final Context context, final AttributeSet attrs, final int defStyleAttr, final int defStyleRes); void setImage(@DrawableRes final int drawable); void setImage(@DrawableRes final int drawable, @Nullable final String contentDescription); void setTitle(@Nullable final String titleText); void setTitle(@StringRes final int resId); void setSubtitle(@Nullable final String subtitleText); void setSubtitle(@StringRes final int resId); void setButton(@Nullable final String buttonLabel, @Nullable final OnClickListener onClickListener); void setButton(@StringRes final int resId, @Nullable final OnClickListener onClickListener); @Override String toString(); }### Answer:
@Test public void testCustomButton() { assertEquals("The ErrorView button should be gone", View.GONE, button.getVisibility()); errorView.setButton(null, null); assertEquals("The ErrorView button should be gone", View.GONE, button.getVisibility()); errorView.setButton(TEST_TEXT, mock(View.OnClickListener.class)); assertEquals("The ErrorView button should be visible", View.VISIBLE, button.getVisibility()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.