method2testcases
stringlengths
118
3.08k
### Question: ClickatellGatewayManagerImpl implements GatewayManager { public MStatus mapMessageStatus(GatewayResponse response) { return messageHandler.parseMessageStatus(response.getResponseText()); } ClickatellGatewayManagerImpl(); Set<GatewayResponse> sendMessage(GatewayRequest messageDetails); String getMessageStatus(GatewayResponse response); MStatus mapMessageStatus(GatewayResponse response); GatewayMessageHandler getMessageHandler(); void setMessageHandler(GatewayMessageHandler messageHandler); String getApiId(); void setApiId(String apiId); String getUser(); void setUser(String user); String getPassword(); void setPassword(String password); String getSender(); void setSender(String sender); String getDeliveryAcknowledge(); void setDeliveryAcknowledge(String deliveryAcknowledge); String getCallback(); void setCallback(String callback); void setBaseUrl(String baseUrl); }### Answer: @Test public void testMapMessageStatus() { System.out.println("mapMessageStatus"); GatewayResponseImpl response = new GatewayResponseImpl(); response.setResponseText("Some gateway response message"); expect( mockHandler.parseMessageStatus((String) anyObject()) ).andReturn(MStatus.DELIVERED); replay(mockHandler); MStatus result = instance.mapMessageStatus(response); assertEquals(result, MStatus.DELIVERED); verify(mockHandler); }
### Question: IMPManagerImpl implements ApplicationContextAware, IMPManager { public IncomingMessageFormValidator createIncomingMessageFormValidator(){ return (IncomingMessageFormValidator)context.getBean("imFormValidator"); } IMPService createIMPService(); IncomingMessageParser createIncomingMessageParser(); IncomingMessageXMLParser createIncomingMessageXMLParser(); IncomingMessageFormValidator createIncomingMessageFormValidator(); CommandAction createCommandAction(); void setApplicationContext(ApplicationContext applicationContext); }### Answer: @Test public void testCreateIncomingMessageFormValidator() { System.out.println("createIncomingMessageFormValidator"); IncomingMessageFormValidator result = impManager.createIncomingMessageFormValidator(); assertNotNull(result); }
### Question: Instantiators { public static <T> Converter<T> createConverter( Class<T> klass, InstantiatorModule... modules) { return createConverterForType(klass, modules); } private Instantiators(); static Instantiator<T> createInstantiator( Class<T> klass, InstantiatorModule... modules); @SuppressWarnings({ "unchecked", "rawtypes" }) static Option<Instantiator<T>> createInstantiator( Errors errors, Class<T> klass, InstantiatorModule... modules); static Converter<T> createConverter( Class<T> klass, InstantiatorModule... modules); static Converter<T> createConverter( TypeLiteral<T> typeLiteral, InstantiatorModule... modules); }### Answer: @Test public void createUriConverter() throws URISyntaxException { assertEquals( new URI("www.kaching.com"), createConverter(URI.class).fromString("www.kaching.com")); } @Test public void createConverterPairConverter() throws URISyntaxException { Converter<ConvertedPair> converter = createConverter(ConvertedPair.class); assertEquals( "1:2", converter.toString(converter.fromString("1:2"))); }
### Question: StringConstructorConverter implements Converter<T> { @Override @SuppressWarnings("unchecked") public T fromString(String representation) { try { constructor.setAccessible(true); return (T) constructor.newInstance(representation); } catch (IllegalArgumentException e) { throw new IllegalStateException( "unreachable since we check the number of arguments the " + "constructor takes when building this converter", e); } catch (InstantiationException e) { throw new IllegalStateException( "unreachable since we check that the class is not abstract", e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { try { throw e.getTargetException(); } catch (RuntimeException targetException) { throw targetException; } catch (Throwable targetException) { throw new RuntimeException(e); } } } StringConstructorConverter(Constructor<?> constructor); @Override String toString(T value); @Override @SuppressWarnings("unchecked") T fromString(String representation); }### Answer: @Test public void properlyBubblesException() { try { converter(TakesSingleStringAndThrows.class).fromString(null); fail(); } catch (RuntimeException e) { assertEquals(PrivateLocalRuntimException.class, e.getClass()); } }
### Question: InstantiatorImpl implements Instantiator<T> { @Override public T newInstance(String... values) { return newInstance(Arrays.asList(values)); } InstantiatorImpl( Constructor<T> constructor, Converter<?>[] converters, Field[] fields, BitSet optionality, BitSet wrapInOption, String[] defaultValues, Object[] defaultConstants, String[] parameterNames); @Override T newInstance(String... values); @Override T newInstance(Map<String, String> namedValues); @Override T newInstance(Iterable<String> values); @SuppressWarnings("unchecked") List<String> fromInstance(T instance); @Override Constructor<T> getConstructor(); @Override String toString(); }### Answer: @Test public void newInstanceHasEnum() { assertEquals( IsEnum.FOO, createFactory(new Errors(), HasEnum.class).build().getOrThrow() .newInstance("FOO") .value); } @Test(expected = UnsupportedOperationException.class) public void fromInstanceByNameThrowsIfNoParamaterNames() throws Exception { InstantiatorImpl<String> instantiator = new InstantiatorImpl<String>( null, null, null, null, null, null, null, null); instantiator.newInstance((Map<String, String>) null); }
### Question: InstantiatorImpl implements Instantiator<T> { @Override public Constructor<T> getConstructor() { return constructor; } InstantiatorImpl( Constructor<T> constructor, Converter<?>[] converters, Field[] fields, BitSet optionality, BitSet wrapInOption, String[] defaultValues, Object[] defaultConstants, String[] parameterNames); @Override T newInstance(String... values); @Override T newInstance(Map<String, String> namedValues); @Override T newInstance(Iterable<String> values); @SuppressWarnings("unchecked") List<String> fromInstance(T instance); @Override Constructor<T> getConstructor(); @Override String toString(); }### Answer: @Test public void getConstructor() throws Exception { Constructor<Object> constructor = Object.class.getConstructor(); InstantiatorImpl<Object> instantiator = new InstantiatorImpl<Object>( constructor, null, null, new BitSet(), new BitSet(), null, null, null); assertTrue(constructor == instantiator.getConstructor()); }
### Question: CollectionOfElementsConverter implements Converter<T> { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public T fromString(String representation) { if (representation == null) { return null; } else { Collection collection = collectionProvider.get(); if (!representation.isEmpty()) { for (String part : representation.split(",")) { collection.add(elementConverter.fromString(part)); } } return (T) collection; } } CollectionOfElementsConverter( Type kindOfCollection, Converter<?> elementConverter); @Override String toString(T value); @Override @SuppressWarnings({ "unchecked", "rawtypes" }) T fromString(String representation); }### Answer: @Test @SuppressWarnings({ "unchecked", "rawtypes" }) public void createsRightKindOfCollection() { assertEquals( HashSet.class, new CollectionOfElementsConverter(Set.class, C_BOOLEAN).fromString("").getClass()); }
### Question: ConstructorAnalysis { static AnalysisResult analyse( Class<?> klass, Constructor<?> constructor) throws IOException { Class<?>[] parameterTypes = constructor.getParameterTypes(); InputStream in = klass.getResourceAsStream("/" + klass.getName().replace('.', '/') + ".class"); if (in == null) { throw new IllegalArgumentException(format("can not find bytecode for %s", klass)); } return analyse(in, klass.getName().replace('.', '/'), klass.getSuperclass().getName().replace('.', '/'), parameterTypes); } }### Answer: @Test public void regression1() throws IOException { InputStream classInputStream = this.getClass().getResourceAsStream("example_scala_class01.bin"); assertNotNull(classInputStream); Map<String, FormalParameter> assignements = analyse(classInputStream, "com/kaching/trading/rules/formula/FormulaValue", "java/lang/Object", int.class).assignments; assertMapEqualAsString(ImmutableMap.of("number", "p0"), assignements); } @Test public void regression2() throws IOException { InputStream classInputStream = this.getClass().getResourceAsStream("example_scala_class02.bin"); assertNotNull(classInputStream); Map<String, FormalParameter> assignements = analyse(classInputStream, "com/kaching/user/GetAllModels", "com/kaching/platform/queryengine/AbstractQuery", Boolean.class).assignments; assertMapEqualAsString(ImmutableMap.of("com$kaching$user$GetAllModels$$withHistory", "p0"), assignements); }
### Question: NullHandlingConverter implements Converter<T> { public T fromString(String representation) { return representation == null ? null : fromNonNullableString(representation); } T fromString(String representation); String toString(T value); }### Answer: @Test public void fromNullString() throws Exception { Converter<Boolean> converter = new NullHandlingConverter<Boolean>() { @Override protected Boolean fromNonNullableString(String representation) { throw new UnsupportedOperationException(); } @Override protected String nonNullableToString(Boolean value) { throw new UnsupportedOperationException(); } }; assertNull(converter.fromString(null)); } @Test public void fromNotNullString() throws Exception { Converter<Boolean> converter = new NullHandlingConverter<Boolean>() { @Override protected Boolean fromNonNullableString(String representation) { return true; } @Override protected String nonNullableToString(Boolean value) { throw new UnsupportedOperationException(); } }; assertTrue(converter.fromString("")); }
### Question: NullHandlingConverter implements Converter<T> { public String toString(T value) { return value == null ? null : nonNullableToString(value); } T fromString(String representation); String toString(T value); }### Answer: @Test public void nullToString() throws Exception { Converter<Boolean> converter = new NullHandlingConverter<Boolean>() { @Override protected Boolean fromNonNullableString(String representation) { throw new UnsupportedOperationException(); } @Override protected String nonNullableToString(Boolean value) { throw new UnsupportedOperationException(); } }; assertNull(converter.toString(null)); } @Test public void notNullToString() throws Exception { Converter<Boolean> converter = new NullHandlingConverter<Boolean>() { @Override protected Boolean fromNonNullableString(String representation) { throw new UnsupportedOperationException(); } @Override protected String nonNullableToString(Boolean value) { return ""; } }; assertEquals("", converter.toString(true)); }
### Question: InstantiatorErrors { @SuppressWarnings("rawtypes") static Errors incorrectBoundForConverter( Errors errors, Type targetType, Class<? extends Converter> converterClass, Type producedType) { return errors.addMessage( "the converter %2$s, mentioned on %1$s using @%4$s, does not produce " + "instances of %1$s. It produces %3$s.", targetType, converterClass, producedType, ConvertedBy.class.getSimpleName()); } }### Answer: @Test public void incorrectBoundForConverter() { check( "the converter interface com.kaching.platform.converters.Converter, " + "mentioned on class java.lang.String using @ConvertedBy, " + "does not produce instances of class java.lang.String. It produces " + "class java.lang.Integer.", InstantiatorErrors.incorrectBoundForConverter( new Errors(), String.class, Converter.class, Integer.class)); }
### Question: InstantiatorErrors { static Errors incorrectDefaultValue(Errors errors, String value, RuntimeException e) { return errors.addMessage( "%s: For default value \"%s\"", e.getClass().getName(), value); } }### Answer: @Test public void incorrectDefaultValue() { check( "java.lang.NumberFormatException: For default value \"90z\"", InstantiatorErrors.incorrectDefaultValue( new Errors(), "90z", new NumberFormatException("the message"))); }
### Question: InstantiatorErrors { static Errors illegalConstructor(Errors errors, Class<?> klass, String message) { return errors.addMessage( "%s has an illegal constructor%s", klass, message == null ? "" : ": " + message); } }### Answer: @Test public void illegalConstructor1() { check( "class java.lang.String has an illegal constructor: hello", InstantiatorErrors.illegalConstructor( new Errors(), String.class, "hello")); } @Test public void illegalConstructor2() { check( "class java.lang.String has an illegal constructor", InstantiatorErrors.illegalConstructor( new Errors(), String.class, null)); }
### Question: InstantiatorErrors { static Errors enumHasAmbiguousNames(Errors errors, Class<? extends Enum<?>> clazz) { return errors.addMessage( "enum %s has ambiguous names", clazz.getName()); } }### Answer: @Test public void enumHasAmbiguousNames() { check( "enum com.kaching.platform.converters.InstantiatorErrorsTest$AmbiguousEnum has ambiguous names", InstantiatorErrors.enumHasAmbiguousNames( new Errors(), AmbiguousEnum.class)); }
### Question: InstantiatorErrors { static Errors moreThanOneMatchingFunction(Errors errors, Type type) { return errors.addMessage( "%s has more than one matching function", type); } }### Answer: @Test public void moreThanOneMatchingFunction() { check( "class com.kaching.platform.converters.InstantiatorErrorsTest$AmbiguousEnum has more than one matching function", InstantiatorErrors.moreThanOneMatchingFunction( new Errors(), AmbiguousEnum.class)); }
### Question: InstantiatorErrors { static Errors noConverterForType(Errors errors, Type type) { return errors.addMessage( "no converter for %s", type); } }### Answer: @Test public void noConverterForType() { check( "no converter for java.util.List<java.lang.String>", InstantiatorErrors.noConverterForType( new Errors(), new TypeLiteral<List<String>>() {}.getType())); }
### Question: InstantiatorErrors { static Errors noSuchField(Errors errors, String fieldName) { return errors.addMessage( "no such field %s", fieldName); } }### Answer: @Test public void addinTwiceTheSameMessageDoesNotDuplicateTheError() { check( "no such field a", noSuchField(noSuchField(new Errors(), "a"), "a")); }
### Question: InstantiatorErrors { static Errors cannotSpecifyDefaultValueAndConstant(Errors errors, Optional annotation) { return errors.addMessage( "cannot specify both a default constant and a default value %s", annotation.toString().replaceFirst(Optional.class.getName(), Optional.class.getSimpleName())); } }### Answer: @Test public void cannotSpecifyDefaultValueAndConstant() throws Exception { check( "cannot specify both a default constant and a default value " + "@Optional(constant=FOO, value=4)", InstantiatorErrors.cannotSpecifyDefaultValueAndConstant( new Errors(), inspectMeCannotSpecifyDefaultValueAndConstant(8))); }
### Question: InstantiatorErrors { static Errors unableToResolveConstant(Errors errors, Class<?> container, String constant) { return unableToResolveFullyQualifiedConstant( errors, localConstantQualifier(container, constant)); } }### Answer: @Test public void unableToResolveLocalConstant() throws Exception { check( "unable to resolve constant com.kaching.platform.converters.InstantiatorErrorsTest#MY_CONSTANT", InstantiatorErrors.unableToResolveConstant( new Errors(), InstantiatorErrorsTest.class, "MY_CONSTANT")); }
### Question: AbstractImmutableType extends AbstractType { public Object assemble( Serializable cached, SessionImplementor session, Object owner) throws HibernateException { return cached; } final Object deepCopy(Object value); final boolean isMutable(); final Serializable disassemble(Object value); Serializable disassemble(Object value, SessionImplementor session); Object assemble( Serializable cached, SessionImplementor session, Object owner); final Object assemble(Serializable cached, Object owner); final Object replace(Object original, Object target, Object owner); Object replace(Object original, Object target, SessionImplementor session, Object owner); void nullSafeSet(PreparedStatement st, Object value, int index); void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session); void setPropertyValue(Object component, int property, Object value); }### Answer: @Test public void assemble() { assertEquals(serializable, type.assemble(serializable, null)); assertEquals(serializable, type.assemble(serializable, null, null)); }
### Question: AbstractImmutableType extends AbstractType { public final Object deepCopy(Object value) { return value; } final Object deepCopy(Object value); final boolean isMutable(); final Serializable disassemble(Object value); Serializable disassemble(Object value, SessionImplementor session); Object assemble( Serializable cached, SessionImplementor session, Object owner); final Object assemble(Serializable cached, Object owner); final Object replace(Object original, Object target, Object owner); Object replace(Object original, Object target, SessionImplementor session, Object owner); void nullSafeSet(PreparedStatement st, Object value, int index); void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session); void setPropertyValue(Object component, int property, Object value); }### Answer: @Test public void deepCopy() { assertEquals(serializable, type.deepCopy(serializable)); }
### Question: AbstractImmutableType extends AbstractType { public final Serializable disassemble(Object value) throws HibernateException { return (Serializable) value; } final Object deepCopy(Object value); final boolean isMutable(); final Serializable disassemble(Object value); Serializable disassemble(Object value, SessionImplementor session); Object assemble( Serializable cached, SessionImplementor session, Object owner); final Object assemble(Serializable cached, Object owner); final Object replace(Object original, Object target, Object owner); Object replace(Object original, Object target, SessionImplementor session, Object owner); void nullSafeSet(PreparedStatement st, Object value, int index); void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session); void setPropertyValue(Object component, int property, Object value); }### Answer: @Test public void disassemble() { assertEquals(serializable, type.disassemble(serializable)); assertEquals(serializable, type.disassemble(serializable, null)); }
### Question: AbstractImmutableType extends AbstractType { public final boolean isMutable() { return false; } final Object deepCopy(Object value); final boolean isMutable(); final Serializable disassemble(Object value); Serializable disassemble(Object value, SessionImplementor session); Object assemble( Serializable cached, SessionImplementor session, Object owner); final Object assemble(Serializable cached, Object owner); final Object replace(Object original, Object target, Object owner); Object replace(Object original, Object target, SessionImplementor session, Object owner); void nullSafeSet(PreparedStatement st, Object value, int index); void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session); void setPropertyValue(Object component, int property, Object value); }### Answer: @Test public void isMutable() { assertFalse(type.isMutable()); }
### Question: AbstractType { public final boolean equals(Object x, Object y) throws HibernateException { if (x == y) { return true; } else if (x == null || y == null) { return false; } else { return x.equals(y); } } final boolean equals(Object x, Object y); final int hashCode(Object value); }### Answer: @Test public void equality() { assertTrue(type.equals(null, null)); assertFalse(type.equals(serializable, null)); assertFalse(type.equals(null, serializable)); assertTrue(type.equals(serializable, serializable)); }
### Question: AbstractType { public final int hashCode(Object value) throws HibernateException { return value.hashCode(); } final boolean equals(Object x, Object y); final int hashCode(Object value); }### Answer: @Test public void hashing() { assertEquals(serializable.hashCode(), type.hashCode(serializable)); }
### Question: AbstractStringImmutableType extends AbstractImmutableType implements UserType { public final T nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException { String representation = rs.getString(names[0]); if (rs.wasNull() || representation == null) { return null; } else { return converter().fromString(representation); } } final T nullSafeGet(ResultSet rs, String[] names, Object owner); @SuppressWarnings("unchecked") @Override final void nullSafeSet(PreparedStatement st, Object value, int index); final int[] sqlTypes(); }### Answer: @Test public void getButWasNull() throws Exception { final ResultSet rs = mockery.mock(ResultSet.class); final Sequence execution = mockery.sequence("execution"); mockery.checking(new Expectations() {{ one(rs).getString(with(equal("name0here"))); inSequence(execution); will(returnValue("78")); one(rs).wasNull(); inSequence(execution); will(returnValue(true)); }}); assertNull(type.nullSafeGet(rs, new String[] { "name0here" }, null)); mockery.assertIsSatisfied(); } @Test public void getHadData() throws Exception { final ResultSet rs = mockery.mock(ResultSet.class); final Sequence execution = mockery.sequence("execution"); mockery.checking(new Expectations() {{ one(rs).getString(with(equal("name0here"))); inSequence(execution); will(returnValue("98")); one(rs).wasNull(); inSequence(execution); will(returnValue(false)); }}); Object value = type.nullSafeGet(rs, new String[] { "name0here" }, null); assertNotNull(value); assertEquals(98, value); mockery.assertIsSatisfied(); }
### Question: ResultsMatcher extends TypeSafeDiagnosingMatcher<RecurrenceRule> { public static Matcher<RecurrenceRule> results(DateTime start, Matcher<Integer> count) { return new ResultsMatcher(start, is(count)); } ResultsMatcher(DateTime start, Matcher<Integer> countMatcher); static Matcher<RecurrenceRule> results(DateTime start, Matcher<Integer> count); static Matcher<RecurrenceRule> results(DateTime start, int count); @Override void describeTo(Description description); }### Answer: @Test public void test() throws Exception { assertThat(results(DateTime.parse("20180101"), 10), AllOf.<Matcher<RecurrenceRule>>allOf( matches(new RecurrenceRule("FREQ=DAILY;COUNT=10")), mismatches(new RecurrenceRule("FREQ=DAILY;COUNT=9"), "number of instances was <9>"), mismatches(new RecurrenceRule("FREQ=DAILY;COUNT=12"), "number of instances was <12>"), describesAs("number of instances is <10>") )); assertThat(results(DateTime.parse("20180101"), lessThan(20)), AllOf.<Matcher<RecurrenceRule>>allOf( matches(new RecurrenceRule("FREQ=DAILY;COUNT=1")), matches(new RecurrenceRule("FREQ=DAILY;COUNT=19")), mismatches(new RecurrenceRule("FREQ=DAILY;COUNT=20"), "number of instances <20> was equal to <20>"), mismatches(new RecurrenceRule("FREQ=DAILY;COUNT=21"), "number of instances <21> was greater than <20>"), describesAs("number of instances is a value less than <20>") )); }
### Question: DayOfMonthMatcher extends FeatureMatcher<DateTime, Integer> { public static Matcher<DateTime> onDayOfMonth(Matcher<Integer> dayMatcher) { return new DayOfMonthMatcher(dayMatcher); } DayOfMonthMatcher(Matcher<Integer> subMatcher); static Matcher<DateTime> onDayOfMonth(Matcher<Integer> dayMatcher); static Matcher<DateTime> onDayOfMonth(Integer... days); }### Answer: @Test public void test() throws Exception { assertThat(onDayOfMonth(10), AllOf.<Matcher<DateTime>>allOf( matches(DateTime.parse("20180710T010001Z")), mismatches(DateTime.parse("20181001T005959Z"), "day of month was <1>"), mismatches(DateTime.parse("20181011T010000Z"), "day of month was <11>"), describesAs("day of month (<10>)") )); assertThat(onDayOfMonth(6, 8, 10), AllOf.<Matcher<DateTime>>allOf( matches(DateTime.parse("20180706T010001Z")), matches(DateTime.parse("20180708T010002Z")), matches(DateTime.parse("20180710T010003Z")), mismatches(DateTime.parse("20180605T005959Z"), "day of month was <5>"), mismatches(DateTime.parse("20180811T005958Z"), "day of month was <11>"), mismatches(DateTime.parse("20181009T005957Z"), "day of month was <9>"), mismatches(DateTime.parse("20180907T010000Z"), "day of month was <7>"), describesAs("day of month (<6> or <8> or <10>)") )); }
### Question: MonthMatcher extends FeatureMatcher<DateTime, Integer> { public static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher) { return new MonthMatcher(monthMatcher); } MonthMatcher(Matcher<Integer> subMatcher); static Matcher<DateTime> inMonth(Matcher<Integer> monthMatcher); static Matcher<DateTime> inMonth(Integer... months); }### Answer: @Test public void test() throws Exception { assertThat(inMonth(10), AllOf.<Matcher<DateTime>>allOf( matches(DateTime.parse("20181001T010001Z")), mismatches(DateTime.parse("20180901T005959Z"), "month was <9>"), mismatches(DateTime.parse("20181101T010000Z"), "month was <11>"), describesAs("month (<10>)") )); assertThat(inMonth(6, 8, 10), AllOf.<Matcher<DateTime>>allOf( matches(DateTime.parse("20181001T010001Z")), matches(DateTime.parse("20180801T010002Z")), matches(DateTime.parse("20180601T010003Z")), mismatches(DateTime.parse("20180501T005959Z"), "month was <5>"), mismatches(DateTime.parse("20180701T005958Z"), "month was <7>"), mismatches(DateTime.parse("20180901T005957Z"), "month was <9>"), mismatches(DateTime.parse("20181101T010000Z"), "month was <11>"), describesAs("month (<6> or <8> or <10>)") )); }
### Question: AfterMatcher extends TypeSafeDiagnosingMatcher<DateTime> { public static Matcher<DateTime> after(String dateTime) { return after(DateTime.parse(dateTime)); } AfterMatcher(DateTime referenceDate); static Matcher<DateTime> after(String dateTime); static Matcher<DateTime> after(DateTime dateTime); @Override void describeTo(Description description); }### Answer: @Test public void test() throws Exception { assertThat(after(DateTime.parse("20180101T010000Z")), AllOf.<Matcher<DateTime>>allOf( matches(DateTime.parse("20180101T010001Z")), mismatches(DateTime.parse("20180101T005959Z"), "not after 20180101T010000Z"), mismatches(DateTime.parse("20180101T010000Z"), "not after 20180101T010000Z"), describesAs("after 20180101T010000Z") )); assertThat(after("20180101T010000Z"), AllOf.<Matcher<DateTime>>allOf( matches(DateTime.parse("20180101T010001Z")), mismatches(DateTime.parse("20180101T005959Z"), "not after 20180101T010000Z"), mismatches(DateTime.parse("20180101T010000Z"), "not after 20180101T010000Z"), describesAs("after 20180101T010000Z") )); }
### Question: WeekDayMatcher extends FeatureMatcher<DateTime, Weekday> { public static Matcher<DateTime> onWeekDay(Matcher<Weekday> weekdayMatcher) { return new WeekDayMatcher(weekdayMatcher); } WeekDayMatcher(Matcher<Weekday> subMatcher); static Matcher<DateTime> onWeekDay(Matcher<Weekday> weekdayMatcher); static Matcher<DateTime> onWeekDay(Weekday... weekdays); }### Answer: @Test public void test() throws Exception { assertThat(onWeekDay(Weekday.WE), AllOf.<Matcher<DateTime>>allOf( matches(DateTime.parse("20180808T010001Z")), mismatches(DateTime.parse("20180809T005959Z"), "weekday was <TH>"), mismatches(DateTime.parse("20180807T010000Z"), "weekday was <TU>"), describesAs("weekday (<WE>)") )); assertThat(onWeekDay(Weekday.MO, Weekday.WE, Weekday.FR), AllOf.<Matcher<DateTime>>allOf( matches(DateTime.parse("20180808T010001Z")), matches(DateTime.parse("20180806T010002Z")), matches(DateTime.parse("20180810T010003Z")), mismatches(DateTime.parse("20180805T005959Z"), "weekday was <SU>"), mismatches(DateTime.parse("20180804T005958Z"), "weekday was <SA>"), mismatches(DateTime.parse("20180814T005957Z"), "weekday was <TU>"), mismatches(DateTime.parse("20180816T010000Z"), "weekday was <TH>"), describesAs("weekday (<MO> or <WE> or <FR>)") )); }
### Question: BeforeMatcher extends TypeSafeDiagnosingMatcher<DateTime> { public static Matcher<DateTime> before(String dateTime) { return before(DateTime.parse(dateTime)); } BeforeMatcher(DateTime referenceDate); static Matcher<DateTime> before(String dateTime); static Matcher<DateTime> before(DateTime dateTime); @Override void describeTo(Description description); }### Answer: @Test public void test() throws Exception { assertThat(before(DateTime.parse("20180101T010000Z")), AllOf.<Matcher<DateTime>>allOf( matches(DateTime.parse("20180101T000059Z")), mismatches(DateTime.parse("20180101T010001Z"), "not before 20180101T010000Z"), mismatches(DateTime.parse("20180101T010000Z"), "not before 20180101T010000Z"), describesAs("before 20180101T010000Z") )); assertThat(before("20180101T010000Z"), AllOf.<Matcher<DateTime>>allOf( matches(DateTime.parse("20180101T000059Z")), mismatches(DateTime.parse("20180101T010001Z"), "not before 20180101T010000Z"), mismatches(DateTime.parse("20180101T010000Z"), "not before 20180101T010000Z"), describesAs("before 20180101T010000Z") )); }
### Question: YearMatcher extends FeatureMatcher<DateTime, Integer> { public static Matcher<DateTime> inYear(Matcher<Integer> yearMatcher) { return new YearMatcher(yearMatcher); } YearMatcher(Matcher<Integer> subMatcher); static Matcher<DateTime> inYear(Matcher<Integer> yearMatcher); static Matcher<DateTime> inYear(Integer... years); }### Answer: @Test public void test() throws Exception { assertThat(inYear(2018), AllOf.<Matcher<DateTime>>allOf( matches(DateTime.parse("20181001T010001Z")), mismatches(DateTime.parse("20210901T005959Z"), "year was <2021>"), mismatches(DateTime.parse("20171101T010000Z"), "year was <2017>"), describesAs("year (<2018>)") )); assertThat(inYear(2018, 2019, 2020), AllOf.<Matcher<DateTime>>allOf( matches(DateTime.parse("20181001T010001Z")), matches(DateTime.parse("20190801T010002Z")), matches(DateTime.parse("20200601T010003Z")), mismatches(DateTime.parse("20110501T005959Z"), "year was <2011>"), mismatches(DateTime.parse("20170701T005958Z"), "year was <2017>"), mismatches(DateTime.parse("20210901T005957Z"), "year was <2021>"), mismatches(DateTime.parse("20301101T010000Z"), "year was <2030>"), describesAs("year (<2018> or <2019> or <2020>)") )); }
### Question: HugeHashMap extends AbstractMap<K, V> implements HugeMap<K, V> { @Override public V remove(Object key) { long hash = hasher.hash(key); int segment = hasher.getSegment(hash); int segmentHash = hasher.segmentHash(hash); segments[segment].remove(segmentHash, (K) key); return null; } HugeHashMap(); HugeHashMap(HugeConfig config, Class<K> kClass, Class<V> vClass); @Override V put(K key, V value); @Override V get(Object key); @Override V get(K key, V value); @Override V remove(Object key); @Override boolean containsKey(Object key); @NotNull @Override Set<Entry<K, V>> entrySet(); @Override V putIfAbsent(@NotNull K key, V value); @Override boolean remove(@NotNull Object key, Object value); @Override boolean replace(@NotNull K key, @NotNull V oldValue, @NotNull V newValue); @Override V replace(@NotNull K key, @NotNull V value); @Override boolean isEmpty(); @Override int size(); @Override long offHeapUsed(); @Override void clear(); }### Answer: @Test public void clearMapViaKeyIteratorRemoves() { int noOfElements = 16 * 1024; HugeHashMap<Integer, String> map = getViewTestMap(noOfElements); int sum = 0; for (Iterator it = map.keySet().iterator(); it.hasNext(); ) { it.next(); it.remove(); ++sum; } assertEquals(noOfElements, sum); } @Test public void clearMapViaValueIteratorRemoves() { int noOfElements = 16 * 1024; HugeHashMap<Integer, String> map = getViewTestMap(noOfElements); int sum = 0; for (Iterator it = map.values().iterator(); it.hasNext(); ) { it.next(); it.remove(); ++sum; } assertEquals(noOfElements, sum); }
### Question: VanillaSharedReplicatedHashMap extends AbstractVanillaSharedHashMap<K, V> implements SharedHashMap<K, V>, ReplicaExternalizable<K, V>, EntryResolver<K, V>, Closeable { @Override public V put(K key, V value) { return put0(key, value, true, localIdentifier, timeProvider.currentTimeMillis()); } VanillaSharedReplicatedHashMap(@NotNull SharedHashMapBuilder builder, @NotNull Class<K> kClass, @NotNull Class<V> vClass); @Override long lastModificationTime(byte remoteIdentifier); @Override V put(K key, V value); @Override V putIfAbsent(@net.openhft.lang.model.constraints.NotNull K key, V value); @Override V remove(final Object key); @Override void close(); @Override byte identifier(); @Override Replica.ModificationIterator acquireModificationIterator(short remoteIdentifier, @NotNull final ModificationNotifier modificationNotifier); @Override boolean remove(@net.openhft.lang.model.constraints.NotNull final Object key, final Object value); @Override void writeExternalEntry(@NotNull AbstractBytes entry, @NotNull Bytes destination, int chronicleId); @Override void readExternalEntry(@NotNull Bytes source); @NotNull @Override Set<Entry<K, V>> entrySet(); @Override K key(@NotNull AbstractBytes entry, K usingKey); @Override V value(@NotNull AbstractBytes entry, V usingValue); @Override boolean wasRemoved(@NotNull AbstractBytes entry); static final int RESERVED_MOD_ITER; }### Answer: @Test public void testPut1_NullPointerException() throws IOException { try { SharedHashMap c = newShmIntString(5); c.put(null, "whatever"); shouldThrow(); } catch (NullPointerException success) { } } @Test public void testPut2_NullPointerException() throws IOException { try { SharedHashMap c = newShmIntString(5); c.put(JSR166TestCase.notPresent, null); shouldThrow(); } catch (NullPointerException success) { } }
### Question: OperationHandler { public boolean execute() { boolean isExecutionOk = true; if (!fieldsToCheck.containsKey(JSON_ELEM_ACTUAL_VALUE) || !fieldsToCheck.containsKey(JSON_ELEM_EXPECTED_VALUE)) { throw new HeatException("json input format not supported! '" + fieldsToCheck.toString() + "'"); } if (isComparingBlock()) { isExecutionOk &= multipleModeOperationExecution(); } else { isExecutionOk &= singleModeOperationExecution(); } return isExecutionOk; } OperationHandler(Map fieldsToCheck, Object response); boolean execute(); void setOperationBlocking(boolean isBlocking); void setFlowOutputParameters(Map<Integer, Map<String, String>> retrievedParameters); LoggingUtils getLogUtils(); static final String OPERATION_JSON_ELEMENT; static final String FORMAT_OF_TYPE_CHECK_JSON_ELEMENT; static final String JSON_ELEM_DESCRIPTION; static final String JSON_ELEM_EXPECTED_VALUE; static final String JSON_ELEM_ACTUAL_VALUE; static final String JSON_ELEM_REFERRING_OBJECT; }### Answer: @Test (enabled = true) public void testCompareEqualsFields() { underTest = new OperationHandler(getEqualsFieldsToCheck(), buildResponses()); boolean execution = underTest.execute(); Assert.assertTrue(execution); } @Test(enabled = true, expectedExceptions = HeatException.class) public void testCompareDifferentFields() { underTest = new OperationHandler(getDifferentFieldsToCheck(), buildResponses()); underTest.execute(); }
### Question: MotechUserRepository { public MotechUserTypes userTypes() { return motechUsers.types(); } MotechUserRepository(IdentifierGenerator identifierGenerator, UserService userService, PersonService personService, MotechUsers motechUsers); User newUser(WebStaff webStaff); User updateUser(User staff, WebStaff webStaff); MotechUserTypes userTypes(); }### Answer: @Test public void shouldRetrieveUserTypes() { MotechUserRepository repository = new MotechUserRepository(null, null, null, motechUsers); MotechUserTypes userTypes = repository.userTypes(); assertTrue(userTypes.hasTypes(2)); assertTrue(userTypes.hasType("CHO")); assertTrue(userTypes.hasType("CHN")); }
### Question: DemoPatientController extends BasePatientController { @ModelAttribute("regions") public List<String> getRegions() { return JSONLocationSerializer.getAllRegions(); } @Autowired void setContextService(ContextService contextService); void setRegistrarBean(RegistrarBean registrarBean); void setWebModelConverter(WebModelConverter webModelConverter); @InitBinder void initBinder(WebDataBinder binder); @ModelAttribute("regions") List<String> getRegions(); @ModelAttribute("districts") List<String> getDistricts(); @ModelAttribute("communities") List<Community> getCommunities(); @RequestMapping(method = RequestMethod.GET) void viewForm(@RequestParam(required = false) Integer id,ModelMap model); @ModelAttribute("patient") WebPatient getWebPatient(@RequestParam(required = false) Integer id); @RequestMapping(method = RequestMethod.POST) String submitForm(@ModelAttribute("patient") WebPatient patient, Errors errors, ModelMap model, SessionStatus status, HttpSession session); }### Answer: @Test public void testGetRegions() throws Exception { ContextService contextService = createMock(ContextService.class); MotechService motechService = createMock(MotechService.class); JSONLocationSerializer JSONLocationSerializer = new JSONLocationSerializer(); JSONLocationSerializer.setContextService(contextService); demoPatientController.setContextService(contextService); demoPatientController.setJSONLocationSerializer(JSONLocationSerializer); expect(contextService.getMotechService()).andReturn(motechService); expect(motechService.getAllRegions()).andReturn(Collections.<String>emptyList()).once(); replay(contextService, motechService); demoPatientController.getRegions(); verify(contextService, motechService); }
### Question: DemoPatientController extends BasePatientController { @ModelAttribute("districts") public List<String> getDistricts() { return JSONLocationSerializer.getAllDistricts(); } @Autowired void setContextService(ContextService contextService); void setRegistrarBean(RegistrarBean registrarBean); void setWebModelConverter(WebModelConverter webModelConverter); @InitBinder void initBinder(WebDataBinder binder); @ModelAttribute("regions") List<String> getRegions(); @ModelAttribute("districts") List<String> getDistricts(); @ModelAttribute("communities") List<Community> getCommunities(); @RequestMapping(method = RequestMethod.GET) void viewForm(@RequestParam(required = false) Integer id,ModelMap model); @ModelAttribute("patient") WebPatient getWebPatient(@RequestParam(required = false) Integer id); @RequestMapping(method = RequestMethod.POST) String submitForm(@ModelAttribute("patient") WebPatient patient, Errors errors, ModelMap model, SessionStatus status, HttpSession session); }### Answer: @Test public void testGetDistricts() throws Exception { ContextService contextService = createMock(ContextService.class); MotechService motechService = createMock(MotechService.class); JSONLocationSerializer JSONLocationSerializer = new JSONLocationSerializer(); JSONLocationSerializer.setContextService(contextService); demoPatientController.setContextService(contextService); demoPatientController.setJSONLocationSerializer(JSONLocationSerializer); expect(contextService.getMotechService()).andReturn(motechService); expect(motechService.getAllDistricts()).andReturn(Collections.<String>emptyList()).once(); replay(contextService, motechService); demoPatientController.getDistricts(); verify(contextService, motechService); }
### Question: DemoPatientController extends BasePatientController { @ModelAttribute("communities") public List<Community> getCommunities() { return JSONLocationSerializer.getAllCommunities(false); } @Autowired void setContextService(ContextService contextService); void setRegistrarBean(RegistrarBean registrarBean); void setWebModelConverter(WebModelConverter webModelConverter); @InitBinder void initBinder(WebDataBinder binder); @ModelAttribute("regions") List<String> getRegions(); @ModelAttribute("districts") List<String> getDistricts(); @ModelAttribute("communities") List<Community> getCommunities(); @RequestMapping(method = RequestMethod.GET) void viewForm(@RequestParam(required = false) Integer id,ModelMap model); @ModelAttribute("patient") WebPatient getWebPatient(@RequestParam(required = false) Integer id); @RequestMapping(method = RequestMethod.POST) String submitForm(@ModelAttribute("patient") WebPatient patient, Errors errors, ModelMap model, SessionStatus status, HttpSession session); }### Answer: @Test public void testGetCommunities() throws Exception { ContextService contextService = createMock(ContextService.class); MotechService motechService = createMock(MotechService.class); JSONLocationSerializer JSONLocationSerializer = new JSONLocationSerializer(); JSONLocationSerializer.setContextService(contextService); demoPatientController.setContextService(contextService); demoPatientController.setJSONLocationSerializer(JSONLocationSerializer); expect(contextService.getMotechService()).andReturn(motechService); expect(motechService.getAllCommunities(false)).andReturn(Collections.<Community>emptyList()).once(); replay(contextService, motechService); demoPatientController.getCommunities(); verify(contextService, motechService); }
### Question: SMSController { @RequestMapping(value = VIEW, method = RequestMethod.GET) public ModelAndView render() { ModelAndView modelAndView = new ModelAndView(VIEW, "bulkMessage", new WebBulkMessage()); locationSerializer.populateJavascriptMaps(modelAndView.getModelMap()); return modelAndView; } @RequestMapping(value = VIEW, method = RequestMethod.GET) ModelAndView render(); void setLocationSerializer(JSONLocationSerializer locationSerializer); @RequestMapping(value = VIEW, method = RequestMethod.POST) ModelAndView send(@ModelAttribute WebBulkMessage bulkMessage); void setMessageService(MessageService messageService); }### Answer: @Test public void shouldRenderTheCorrectPage() { expect(contextService.getMotechService()).andReturn(motechService); expect(motechService.getAllFacilities()).andReturn(Collections.<Facility>emptyList()); expect(motechService.getAllLanguages()).andReturn(Collections.<MessageLanguage>emptyList()); replay(contextService, motechService); ModelAndView modelAndView = controller.render(); verify(contextService, motechService); assertNotNull(modelAndView); assertEquals("/module/motechmodule/sms", modelAndView.getViewName()); WebBulkMessage message = (WebBulkMessage) modelAndView.getModelMap().get("bulkMessage"); assertNotNull(message); assertNotNull(modelAndView.getModel().get("regionMap")); assertNotNull(modelAndView.getModel().get("districtMap")); assertNotNull(modelAndView.getModel().get("facilities")); }
### Question: AuthenticationServiceImpl implements AuthenticationService { public User getAuthenticatedUser() { return contextService.getAuthenticatedUser(); } AuthenticationServiceImpl(ContextService contextService); User getAuthenticatedUser(); }### Answer: @Test public void shouldDelegateCallToContextService(){ AuthenticationServiceImpl service = new AuthenticationServiceImpl(contextService); User user = new User(); when(contextService.getAuthenticatedUser()).thenReturn(user); User authenticatedUser = service.getAuthenticatedUser(); verify(contextService).getAuthenticatedUser(); assertSame(user,authenticatedUser); }
### Question: SupportCaseExtractionStrategy implements MessageContentExtractionStrategy { public SupportCase extractFrom(IncomingMessage message) { try { String dateRaisedOn = message.extractDateWith(this); String phoneNumber = message.extractPhoneNumberWith(this); String sender = message.extractSenderWith(this); String description = message.extractDescriptionWith(this); return new SupportCase(sender,phoneNumber,dateRaisedOn,description); } catch (Exception ex){ return new SupportCase(); } } SupportCase extractFrom(IncomingMessage message); String extractDateFrom(String time); String extractPhoneNumberFrom(String phoneNumber); String extractSenderFrom(String text); String extractDescriptionFrom(String text); }### Answer: @Test public void shouldExtractMessageContent() throws ParseException, MessageContentExtractionException { SupportCaseExtractionStrategy strategy = new SupportCaseExtractionStrategy(); IncomingMessage message = new IncomingMessage(); message.setKey(" SUPPORT"); message.setTime("2011-06-25 09:30:29 "); message.setText("SUPPORT 123 Cannot Upload Forms "); message.setNumber("+233123456789 "); SupportCase supportCase = strategy.extractFrom(message); assertEquals("123",supportCase.getRaisedBy()); assertEquals("+233123456789",supportCase.getPhoneNumber()); assertEquals("2011-06-25 09:30:29",supportCase.getDateRaisedOn()); assertEquals("Cannot Upload Forms",supportCase.getDescription()); }
### Question: Password { public String create(){ StringBuilder sb = new StringBuilder(); for (int i = 0; i < length ; i++) { int charIndex = (int) (Math.random() * PASSCHARS.length); sb.append(PASSCHARS[charIndex]); } return sb.toString(); } Password(Integer length); String create(); }### Answer: @Test public void createPasswordWithSpecifiedLength(){ String password = new Password(10).create(); assertNotNull(password); assertEquals(10,password.length()); }
### Question: DateUtil { public boolean isSameMonth(Date date, Date otherDate) { Calendar calendar = calendarFor(date); Calendar otherCalendar = calendarFor(otherDate); return calendar.get(Calendar.MONTH) == otherCalendar.get(Calendar.MONTH); } boolean isSameMonth(Date date, Date otherDate); boolean isSameYear(Date date, Date otherDate); Calendar calendarFor(Date date); Date dateFor(int day, int month, int year); Calendar getCalendarWithTime(int hourOfTheDay, int minutes, int seconds); }### Answer: @Test public void isSameMonth() { assertTrue(dateUtil.isSameMonth(new Date(), new Date())); } @Test public void isNotSameMonth() { assertFalse(dateUtil.isSameMonth(new Date(), DateUtils.addMonths(new Date(), -1))); }
### Question: DateUtil { public boolean isSameYear(Date date, Date otherDate) { Calendar calendar = calendarFor(date); Calendar otherCalendar = calendarFor(otherDate); return calendar.get(Calendar.YEAR) == otherCalendar.get(Calendar.YEAR); } boolean isSameMonth(Date date, Date otherDate); boolean isSameYear(Date date, Date otherDate); Calendar calendarFor(Date date); Date dateFor(int day, int month, int year); Calendar getCalendarWithTime(int hourOfTheDay, int minutes, int seconds); }### Answer: @Test public void isSameYear() { assertTrue(dateUtil.isSameYear(new Date(), new Date())); } @Test public void isNotSameYear() { assertFalse(dateUtil.isSameYear(new Date(), DateUtils.addYears(new Date(), -1))); }
### Question: DateUtil { public Calendar getCalendarWithTime(int hourOfTheDay, int minutes, int seconds) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, hourOfTheDay); calendar.set(Calendar.MINUTE, minutes); calendar.set(Calendar.SECOND, seconds); return calendar; } boolean isSameMonth(Date date, Date otherDate); boolean isSameYear(Date date, Date otherDate); Calendar calendarFor(Date date); Date dateFor(int day, int month, int year); Calendar getCalendarWithTime(int hourOfTheDay, int minutes, int seconds); }### Answer: @Test public void shouldReturnCalendarWithGivenTime() { Calendar calendar = dateUtil.getCalendarWithTime(10, 50, 20); assertNotNull(calendar); assertEquals(10, calendar.get(Calendar.HOUR_OF_DAY)); assertEquals(50, calendar.get(Calendar.MINUTE)); assertEquals(20, calendar.get(Calendar.SECOND)); }
### Question: CareConfiguration { public Boolean canAlertBeSent(Integer alertCount) { return alertCount < maxAlertsToBeSent ; } CareConfiguration(); CareConfiguration(Long id, String name, Integer maxAlertsToBeSent); Boolean canAlertBeSent(Integer alertCount); }### Answer: @Test public void shouldCheckWhetherMaximumAlertsHaveBeenSent() { CareConfiguration careConfiguration = new CareConfiguration(1L, "ANC", 4); assertTrue(careConfiguration.canAlertBeSent(1)); assertTrue(careConfiguration.canAlertBeSent(2)); assertFalse(careConfiguration.canAlertBeSent(4)); assertFalse(careConfiguration.canAlertBeSent(5)); }
### Question: HttpClient implements WebClient { public Response get(String fromUrl) { DefaultHttpClient client = new DefaultHttpClient(); try { HttpResponse httpResponse = client.execute(new HttpGet(fromUrl)); return new WebResponse(httpResponse).read(); } catch (IOException e) { return new Response(MailingConstants.MESSAGE_PROCESSING_FAILED); } } Response get(String fromUrl); }### Answer: @Ignore("Should be an integration test") @Test public void shouldMakeAHttpGetRequest() { HttpClient client = new HttpClient(); Response response = client.get("http: "text=support+465+Connection+Broken&number=%2B233123456789" + "&key=support&code=1982&time=2011-01-01+10:10:10"); assertEquals("Welcome to MOTECH. Your message has been submitted to the support team" ,response.getContent()); }
### Question: MailingServiceImpl implements MailingService { public void send(Email mail) { SimpleMailMessage mailMessage = new SimpleMailMessage(); mailMessage.setTo(mail.to()); mailMessage.setFrom(mail.from()); mailMessage.setSubject(mail.subject()); mailMessage.setText(mail.text()); mailSenderFactory.mailSender().send(mailMessage); } MailingServiceImpl(MailSenderFactory mailSenderFactory); void send(Email mail); }### Answer: @Test public void shouldEmail() { MailSenderFactory mailSenderFactory = createMock(MailSenderFactory.class); JavaMailSender sender = createMock(JavaMailSender.class); expect(mailSenderFactory.mailSender()).andReturn(sender); sender.send(equalsMessage(expectedMessage())); expectLastCall(); Email mail = new Email("[email protected]", "[email protected]", "Hi", "Hello World"); replay(mailSenderFactory,sender); new MailingServiceImpl(mailSenderFactory).send(mail); verify(mailSenderFactory,sender); }
### Question: PatientBuilder { public Patient build() { if (registrantType == RegistrantType.CHILD_UNDER_FIVE) { return buildChild(); } else { return buildPatient(); } } PatientBuilder(PersonService personService, MotechService motechService, IdentifierGenerator idGenerator, RegistrantType registrantType, PatientService patientService, LocationService locationService); PatientBuilder setMotechId(Integer motechId); PatientBuilder setName(String fistName, String middleName, String lastName); PatientBuilder setAddress1(String address1); PatientBuilder setPreferredName(String preferredName); PatientBuilder setGender(Gender gender); PatientBuilder setBirthDate(Date birthDate); PatientBuilder setBirthDateEstimated(boolean birthDateEstimated); PatientBuilder setParent(Patient parent); PatientBuilder addAttribute(PersonAttributeTypeEnum patientAttributeType, Object originalValue, String methodName); PatientBuilder addAttribute(PersonAttributeTypeEnum patientAttributeType, Object originalValue, Object invocationTarget, String methodName); Patient build(); }### Answer: @Test public void shouldNotAddPatientToCommunityWhenCommunityIsNotSet() { Community community = mock(Community.class); Patient patient = builder.build(); verify(community, never()).add(patient); }
### Question: TokenReloadCrumbExclusion extends CrumbExclusion { @Override public boolean process(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { if (TokenReloadAction.tokenReloadEnabled()) { String pathInfo = request.getPathInfo(); if (pathInfo != null && pathInfo.equals("/" + TokenReloadAction.URL_NAME + "/")) { chain.doFilter(request, response); return true; } } return false; } @Override boolean process(HttpServletRequest request, HttpServletResponse response, FilterChain chain); }### Answer: @Test public void crumbExclusionIsDisabledByDefault() throws Exception { System.clearProperty("casc.reload.token"); TokenReloadCrumbExclusion crumbExclusion = new TokenReloadCrumbExclusion(); assertFalse(crumbExclusion.process(newRequestWithPath("/reload-configuration-as-code/"), null, null)); } @Test public void crumbExclusionChecksRequestPath() throws Exception { System.setProperty("casc.reload.token", "someSecretValue"); TokenReloadCrumbExclusion crumbExclusion = new TokenReloadCrumbExclusion(); assertFalse(crumbExclusion.process(newRequestWithPath("/reload-configuration-as-code/2"), null, null)); } @Test public void crumbExclustionAllowsReloadIfEnabledAndRequestPathMatch() throws Exception { System.setProperty("casc.reload.token", "someSecretValue"); TokenReloadCrumbExclusion crumbExclusion = new TokenReloadCrumbExclusion(); AtomicBoolean callProcessed = new AtomicBoolean(false); assertTrue(crumbExclusion.process(newRequestWithPath("/reload-configuration-as-code/"), null, (request, response) -> callProcessed.set(true))); assertTrue(callProcessed.get()); }
### Question: StaticFieldExporter { @Deprecated public static void export(Module module, List<Class<?>> classesToConvert) { new StaticFieldExporter(module, null).export(classesToConvert); } StaticFieldExporter(Module module, Configuration conf); @Deprecated static void export(Module module, List<Class<?>> classesToConvert); void export(List<Class<?>> classesToConvert); }### Answer: @Test public void testTypeScriptDefinition() throws IOException, IllegalArgumentException { Writer out = new StringWriter(); ArrayList<Class<?>> classesToConvert = new ArrayList<Class<?>>(); classesToConvert.add(TestClass.class); Module module = new Module("mod"); new StaticFieldExporter(module, null).export(classesToConvert); module.write(out); out.close(); final String result = out.toString(); System.out.println(result); assertTrue(result.contains("export class TestClassStatic")); assertTrue(result.contains("export enum ChangedEnumName")); assertTrue(result.contains("static MY_CONSTANT_STRING: string = 'Test';")); assertTrue(result .contains("static MY_CONSTANT_ENUM_ARRAY_2: ChangedEnumName[] = [ ChangedEnumName.VAL1, ChangedEnumName.VAL2 ];")); assertFalse(result.contains("doNotExportAsStatic")); }
### Question: SQLFile { public static List<String> statementsFrom(Reader reader) throws IOException { SQLFile file = new SQLFile(); file.parse(reader); return file.getStatements(); } void parse(Reader in); List<String> getStatements(); static List<String> statementsFrom(Reader reader); static List<String> statementsFrom(File sqlfile); }### Answer: @Test public void testReadMultiLineCommand() throws IOException { String firstLine = "CREATE TABLE 'testTable'"; String secondLine = "_id INTEGER PRIMARY KEY AUTOINCREMENT;"; String singleLineCommand = firstLine + " " + secondLine; String multiLineCommand = firstLine + "\n" + secondLine; List<String> statementsFromMultiline = SQLFile.statementsFrom(new StringReader(multiLineCommand)); assertEquals(singleLineCommand, statementsFromMultiline.get(0)); } @Test public void testSkippingTrailingComments() throws IOException { String rawLine = "CREATE TABLE 'testTable'"; String comment = "-- adding some comment that should get stripped off"; String nextLine = "_id INTEGER PRIMARY KEY AUTOINCREMENT;"; String lineCommand = rawLine + comment + "\n" + nextLine; List<String> statements = SQLFile.statementsFrom(new StringReader(lineCommand)); assertEquals(rawLine + " " + nextLine, statements.get(0)); }
### Question: AllDateTypes { public LocalDate getLocalDate() { return localDate; } AllDateTypes(); Date getDate(); void setDate(Date date); LocalDate getLocalDate(); void setLocalDate(LocalDate localDate); LocalDateTime getLocalDateTime(); void setLocalDateTime(LocalDateTime localDateTime); DayOfWeek getDayOfWeek(); void setDayOfWeek(DayOfWeek dayOfWeek); LocalTime getSixThirty(); void setSixThirty(LocalTime sixThirty); ZoneId getZoneId(); void setZoneId(ZoneId zoneId); ZonedDateTime getZonedDateTime(); void setZonedDateTime(ZonedDateTime zonedDateTime); ZoneOffset getOffset(); void setOffset(ZoneOffset offset); OffsetDateTime getOffsetDateTime(); void setOffsetDateTime(OffsetDateTime offsetDateTime); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void givenLocalDate_shouldSerialize() throws ParseException { String expectedJson = "{\"year\":2017,\"month\":12,\"day\":25}"; String actualJson = new GsonBuilder().create().toJson(new AllDateTypes().getLocalDate()); assertThat(actualJson).isEqualTo(expectedJson); }
### Question: RuntimeSampler { public static GsonBuilder gsonBuilder() { return new GsonBuilder() .serializeNulls() .setExclusionStrategies(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes fieldAttributes) { return false; } @Override public boolean shouldSkipClass(Class<?> aClass) { return false; } }) .excludeFieldsWithModifiers(Modifier.PROTECTED) .excludeFieldsWithoutExposeAnnotation() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .setFieldNamingStrategy((field) -> field.getName().toLowerCase()) .setDateFormat("MM/dd/yyyy") .setPrettyPrinting(); } static GsonBuilder gsonBuilder(); }### Answer: @Test public void test_using_gsonBuilder() { String expectedJson = "{\n" + " \"byteprimitive\": 0,\n" + " \"shortprimitive\": 0,\n" + " \"charprimitive\": \"\\u0000\",\n" + " \"intprimitive\": 0,\n" + " \"longprimitive\": 0,\n" + " \"floatprimitive\": 0.0,\n" + " \"doubleprimitive\": 0.0,\n" + " \"aboolean\": false,\n" + " \"bytewrapper\": 0,\n" + " \"shortwrapper\": 0,\n" + " \"charwrapper\": \"\\u0000\",\n" + " \"intwrapper\": 0,\n" + " \"longwrapper\": 0,\n" + " \"floatwrapper\": 0.0,\n" + " \"doublewrapper\": 0.0,\n" + " \"booleanwrapper\": false,\n" + " \"string\": \"Hello World\"\n" + "}"; String actualJson = RuntimeSampler.gsonBuilder().create().toJson(new AllBasicTypes()); String cc = RuntimeSampler.gsonBuilder().create().fromJson("", String.class); assertThat(actualJson).isEqualTo(expectedJson); }
### Question: RuntimeSampler { public static JsonbConfig jsonbConfig() { return new JsonbConfig() .withNullValues(true) .withPropertyVisibilityStrategy(new PropertyVisibilityStrategy() { @Override public boolean isVisible(Field field) { return false; } @Override public boolean isVisible(Method method) { return false; } }) .withPropertyNamingStrategy(PropertyNamingStrategy.CASE_INSENSITIVE) .withPropertyOrderStrategy(PropertyOrderStrategy.REVERSE) .withAdapters(new ClassAdapter()) .withDeserializers(new CustomDeserializer()) .withSerializers(new CustomSerializer()) .withBinaryDataStrategy(BinaryDataStrategy.BASE_64_URL) .withDateFormat("MM/dd/yyyy", Locale.ENGLISH) .withLocale(Locale.CANADA) .withEncoding("UTF-8") .withStrictIJSON(true) .withFormatting(true); } static JsonbConfig jsonbConfig(); }### Answer: @Test public void test_using_jsonbConfig() { String expectedJson = "\n" + "{\n" + " \"string\": null,\n" + " \"shortWrapper\": null,\n" + " \"shortPrimitive\": null,\n" + " \"longWrapper\": null,\n" + " \"longPrimitive\": null,\n" + " \"intWrapper\": null,\n" + " \"intPrimitive\": null,\n" + " \"floatWrapper\": null,\n" + " \"floatPrimitive\": null,\n" + " \"doubleWrapper\": null,\n" + " \"doublePrimitive\": null,\n" + " \"charWrapper\": null,\n" + " \"charPrimitive\": null,\n" + " \"byteWrapper\": null,\n" + " \"bytePrimitive\": null,\n" + " \"booleanWrapper\": null,\n" + " \"aBoolean\": null\n" + "}"; String actualJson = JsonbBuilder.create(RuntimeSampler.jsonbConfig()).toJson(new AllBasicTypes()); assertThat(actualJson).isEqualTo(expectedJson); }
### Question: AllDateTypes { public Date getDate() { return date; } AllDateTypes(); Date getDate(); void setDate(Date date); LocalDate getLocalDate(); void setLocalDate(LocalDate localDate); LocalDateTime getLocalDateTime(); void setLocalDateTime(LocalDateTime localDateTime); DayOfWeek getDayOfWeek(); void setDayOfWeek(DayOfWeek dayOfWeek); LocalTime getLocalTime(); void setLocalTime(LocalTime localTime); ZoneId getZoneId(); void setZoneId(ZoneId zoneId); ZonedDateTime getZonedDateTime(); void setZonedDateTime(ZonedDateTime zonedDateTime); ZoneOffset getOffset(); void setOffset(ZoneOffset offset); OffsetDateTime getOffsetDateTime(); void setOffsetDateTime(OffsetDateTime offsetDateTime); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void givenDate_shouldSerialize() throws ParseException, JsonProcessingException { String expectedJson = "1514160000000"; String actualJson = new ObjectMapper().writeValueAsString(new AllDateTypes().getDate()); assertThat(actualJson).isEqualTo(expectedJson); }
### Question: AllDateTypes { public LocalDate getLocalDate() { return localDate; } AllDateTypes(); Date getDate(); void setDate(Date date); LocalDate getLocalDate(); void setLocalDate(LocalDate localDate); LocalDateTime getLocalDateTime(); void setLocalDateTime(LocalDateTime localDateTime); DayOfWeek getDayOfWeek(); void setDayOfWeek(DayOfWeek dayOfWeek); LocalTime getLocalTime(); void setLocalTime(LocalTime localTime); ZoneId getZoneId(); void setZoneId(ZoneId zoneId); ZonedDateTime getZonedDateTime(); void setZonedDateTime(ZonedDateTime zonedDateTime); ZoneOffset getOffset(); void setOffset(ZoneOffset offset); OffsetDateTime getOffsetDateTime(); void setOffsetDateTime(OffsetDateTime offsetDateTime); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void givenLocalDate_shouldSerialize() throws ParseException, JsonProcessingException { String expectedJson = "{\"year\":2017,\"month\":\"DECEMBER\",\"chronology\":{\"id\":\"ISO\",\"calendarType\":\"iso8601\"},\"dayOfMonth\":25,\"dayOfWeek\":\"MONDAY\",\"dayOfYear\":359,\"leapYear\":false,\"monthValue\":12,\"era\":\"CE\"}"; String actualJson = new ObjectMapper().writeValueAsString(new AllDateTypes().getLocalDate()); assertThat(actualJson).isEqualTo(expectedJson); }
### Question: AllDateTypes { public LocalDateTime getLocalDateTime() { return localDateTime; } AllDateTypes(); Date getDate(); void setDate(Date date); LocalDate getLocalDate(); void setLocalDate(LocalDate localDate); LocalDateTime getLocalDateTime(); void setLocalDateTime(LocalDateTime localDateTime); DayOfWeek getDayOfWeek(); void setDayOfWeek(DayOfWeek dayOfWeek); LocalTime getLocalTime(); void setLocalTime(LocalTime localTime); ZoneId getZoneId(); void setZoneId(ZoneId zoneId); ZonedDateTime getZonedDateTime(); void setZonedDateTime(ZonedDateTime zonedDateTime); ZoneOffset getOffset(); void setOffset(ZoneOffset offset); OffsetDateTime getOffsetDateTime(); void setOffsetDateTime(OffsetDateTime offsetDateTime); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void givenLocalDateTime_shouldSerialize() throws ParseException, JsonProcessingException { String expectedJson = "{\"hour\":0,\"minute\":0,\"nano\":0,\"second\":0,\"dayOfMonth\":25,\"dayOfWeek\":\"MONDAY\",\"dayOfYear\":359,\"month\":\"DECEMBER\",\"monthValue\":12,\"year\":2017,\"chronology\":{\"id\":\"ISO\",\"calendarType\":\"iso8601\"}}"; String actualJson = new ObjectMapper().writeValueAsString(new AllDateTypes().getLocalDateTime()); assertThat(actualJson).isEqualTo(expectedJson); }
### Question: AllDateTypes { public LocalTime getLocalTime() { return localTime; } AllDateTypes(); Date getDate(); void setDate(Date date); LocalDate getLocalDate(); void setLocalDate(LocalDate localDate); LocalDateTime getLocalDateTime(); void setLocalDateTime(LocalDateTime localDateTime); DayOfWeek getDayOfWeek(); void setDayOfWeek(DayOfWeek dayOfWeek); LocalTime getLocalTime(); void setLocalTime(LocalTime localTime); ZoneId getZoneId(); void setZoneId(ZoneId zoneId); ZonedDateTime getZonedDateTime(); void setZonedDateTime(ZonedDateTime zonedDateTime); ZoneOffset getOffset(); void setOffset(ZoneOffset offset); OffsetDateTime getOffsetDateTime(); void setOffsetDateTime(OffsetDateTime offsetDateTime); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void givenLocalTime_shouldSerialize() throws ParseException, JsonProcessingException { String expectedJson = "{\"hour\":23,\"minute\":0,\"second\":0,\"nano\":0}"; String actualJson = new ObjectMapper().writeValueAsString(new AllDateTypes().getLocalTime()); assertThat(actualJson).isEqualTo(expectedJson); }
### Question: RuntimeSampler { public static ObjectMapper objectMapper() { return new ObjectMapper() .setDefaultPropertyInclusion(JsonInclude.Include.ALWAYS) .setDefaultVisibility(JsonAutoDetect.Value.construct(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.PROTECTED_AND_PUBLIC)) .configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true) .setSerializationInclusion(JsonInclude.Include.NON_NULL) .configure(SerializationFeature.WRITE_NULL_MAP_VALUES, true) .setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE) .setDateFormat(new SimpleDateFormat("MM/dd/yyyy")) .setDefaultPrettyPrinter(new DefaultPrettyPrinter()) .setLocale(Locale.CANADA); } static ObjectMapper objectMapper(); }### Answer: @Test public void test_using_customised_objectMapper() throws IOException { String expectedJson = "{\"aBoolean\":false,\"booleanWrapper\":false,\"bytePrimitive\":0,\"byteWrapper\":0,\"charPrimitive\":\"\\u0000\",\"charWrapper\":\"\\u0000\",\"doublePrimitive\":0.0,\"doubleWrapper\":0.0,\"floatPrimitive\":0.0,\"floatWrapper\":0.0,\"intPrimitive\":0,\"intWrapper\":0,\"longPrimitive\":0,\"longWrapper\":0,\"shortPrimitive\":0,\"shortWrapper\":0,\"string\":\"Hello World\"}"; String actualJson = RuntimeSampler.objectMapper().writeValueAsString(new AllBasicTypes()); assertThat(actualJson).isEqualTo(expectedJson); }
### Question: MatrixChecker { static void verifyArrays(@NonNull double[][] arrays) { checkNotNull(arrays); final int m = arrays.length; checkExpression(m > 0, "Row should be positive"); final int n = arrays[0].length; for (int i = 1; i < m; ++i) { checkExpression(arrays[i].length == n, "All rows must have the same length"); } } }### Answer: @Test public void testVerifyArrays() { final double[][] arrays = new double[][]{ new double[]{1, 2, 3}, new double[]{4, 5, 6} }; MatrixChecker.verifyArrays(arrays); } @Test(expected = IllegalArgumentException.class) public void testVerifyArrays2() { MatrixChecker.verifyArrays(new double[0][0]); } @Test(expected = IllegalArgumentException.class) public void testVerifyArrays3() { final double[][] arrays = new double[][]{ new double[]{1, 2, 3}, new double[]{4, 5, 6, 4} }; MatrixChecker.verifyArrays(arrays); }
### Question: Matrix implements Serializable { public Matrix copy() { final double[] array = mArray.clone(); return Matrix.array(array, mRow); } private Matrix(double[] array, int row, int col); int[] shape(); double[] getArray(); double[][] getArrays(); Matrix copy(); int getRow(); int getCol(); double get(int i, int j); void set(int i, int j, double value); Matrix times(@NonNull Matrix matrix); Matrix times(double num); Matrix timesTo(double num); Matrix timesTo(@NonNull Matrix matrix); Matrix plus(@NonNull Matrix matrix); Matrix plusTo(@NonNull Matrix matrix); Matrix minus(@NonNull Matrix matrix); Matrix minusTo(@NonNull Matrix matrix); Matrix dot(@NonNull Matrix matrix); Matrix transpose(); static Matrix array(@NonNull double[][] arrays); static Matrix array(@NonNull double[] array, int row); static Matrix randn(int row, int col); static Matrix plus(@NonNull Matrix a, @NonNull Matrix b); static Matrix plusTo(@NonNull Matrix a,@NonNull Matrix b); static Matrix minus(@NonNull Matrix a,@NonNull Matrix b); static Matrix minusTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix dot(@NonNull Matrix a, @NonNull Matrix b); static Matrix transpose(@NonNull Matrix a); static Matrix zeroLike(Matrix matrix); static Matrix zeros(@NonNull int... shape); }### Answer: @Test public void testCopy() { final Matrix a = Matrix.array(new double[]{ 1, 2, 3, 4, 5, 6 }, 2); final Matrix b = a.copy(); assertNotSame(a, b); assertNotSame(a.getArray(), b.getArray()); assertEquals(b.getRow(), 2); assertEquals(b.getCol(), 3); assertArrayEquals(b.getArray(), new double[]{ 1, 2, 3, 4, 5, 6 }, 0); }
### Question: Matrix implements Serializable { public static Matrix zeros(@NonNull int... shape) { checkNotNull(shape); checkExpression( shape.length == 2, "Shape is incorrect"); return new Matrix(new double[shape[0] * shape[1]], shape[0], shape[1]); } private Matrix(double[] array, int row, int col); int[] shape(); double[] getArray(); double[][] getArrays(); Matrix copy(); int getRow(); int getCol(); double get(int i, int j); void set(int i, int j, double value); Matrix times(@NonNull Matrix matrix); Matrix times(double num); Matrix timesTo(double num); Matrix timesTo(@NonNull Matrix matrix); Matrix plus(@NonNull Matrix matrix); Matrix plusTo(@NonNull Matrix matrix); Matrix minus(@NonNull Matrix matrix); Matrix minusTo(@NonNull Matrix matrix); Matrix dot(@NonNull Matrix matrix); Matrix transpose(); static Matrix array(@NonNull double[][] arrays); static Matrix array(@NonNull double[] array, int row); static Matrix randn(int row, int col); static Matrix plus(@NonNull Matrix a, @NonNull Matrix b); static Matrix plusTo(@NonNull Matrix a,@NonNull Matrix b); static Matrix minus(@NonNull Matrix a,@NonNull Matrix b); static Matrix minusTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix dot(@NonNull Matrix a, @NonNull Matrix b); static Matrix transpose(@NonNull Matrix a); static Matrix zeroLike(Matrix matrix); static Matrix zeros(@NonNull int... shape); }### Answer: @Test public void testZeros() { final Matrix matrix = Matrix.zeros(2, 3); assertEquals(matrix.getRow(), 2); assertEquals(matrix.getCol(), 3); assertArrayEquals(matrix.getArray(), new double[]{ 0D, 0D, 0D, 0D, 0D, 0D }, 0); }
### Question: Matrix implements Serializable { public static Matrix randn(int row, int col) { checkDimensions(row, col); final Matrix matrix = Matrix.zeros(row, col); final double[] array = matrix.getArray(); final Random random = new Random(System.currentTimeMillis()); for (int i = 0, len = array.length; i < len; ++i) { array[i] = random.nextGaussian(); } return matrix; } private Matrix(double[] array, int row, int col); int[] shape(); double[] getArray(); double[][] getArrays(); Matrix copy(); int getRow(); int getCol(); double get(int i, int j); void set(int i, int j, double value); Matrix times(@NonNull Matrix matrix); Matrix times(double num); Matrix timesTo(double num); Matrix timesTo(@NonNull Matrix matrix); Matrix plus(@NonNull Matrix matrix); Matrix plusTo(@NonNull Matrix matrix); Matrix minus(@NonNull Matrix matrix); Matrix minusTo(@NonNull Matrix matrix); Matrix dot(@NonNull Matrix matrix); Matrix transpose(); static Matrix array(@NonNull double[][] arrays); static Matrix array(@NonNull double[] array, int row); static Matrix randn(int row, int col); static Matrix plus(@NonNull Matrix a, @NonNull Matrix b); static Matrix plusTo(@NonNull Matrix a,@NonNull Matrix b); static Matrix minus(@NonNull Matrix a,@NonNull Matrix b); static Matrix minusTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix dot(@NonNull Matrix a, @NonNull Matrix b); static Matrix transpose(@NonNull Matrix a); static Matrix zeroLike(Matrix matrix); static Matrix zeros(@NonNull int... shape); }### Answer: @Test public void testRandn() { final Matrix a = Matrix.randn(2, 3); assertEquals(a.getRow(), 2); assertEquals(a.getCol(), 3); }
### Question: Matrix implements Serializable { public Matrix transpose() { return Matrix.transpose(this); } private Matrix(double[] array, int row, int col); int[] shape(); double[] getArray(); double[][] getArrays(); Matrix copy(); int getRow(); int getCol(); double get(int i, int j); void set(int i, int j, double value); Matrix times(@NonNull Matrix matrix); Matrix times(double num); Matrix timesTo(double num); Matrix timesTo(@NonNull Matrix matrix); Matrix plus(@NonNull Matrix matrix); Matrix plusTo(@NonNull Matrix matrix); Matrix minus(@NonNull Matrix matrix); Matrix minusTo(@NonNull Matrix matrix); Matrix dot(@NonNull Matrix matrix); Matrix transpose(); static Matrix array(@NonNull double[][] arrays); static Matrix array(@NonNull double[] array, int row); static Matrix randn(int row, int col); static Matrix plus(@NonNull Matrix a, @NonNull Matrix b); static Matrix plusTo(@NonNull Matrix a,@NonNull Matrix b); static Matrix minus(@NonNull Matrix a,@NonNull Matrix b); static Matrix minusTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix dot(@NonNull Matrix a, @NonNull Matrix b); static Matrix transpose(@NonNull Matrix a); static Matrix zeroLike(Matrix matrix); static Matrix zeros(@NonNull int... shape); }### Answer: @Test public void testTranspose() { final Matrix a = Matrix.array(new double[]{ 1, 2, 3, 4, 5, 6 }, 2); final Matrix b = a.transpose(); assertEquals(b.getRow(), 3); assertEquals(b.getCol(), 2); assertArrayEquals(b.getArray(), new double[]{ 1, 4, 2, 5, 3, 6 }, 0); }
### Question: Matrix implements Serializable { public Matrix plus(@NonNull Matrix matrix) { checkNotNull(matrix); return Matrix.plus(this, matrix); } private Matrix(double[] array, int row, int col); int[] shape(); double[] getArray(); double[][] getArrays(); Matrix copy(); int getRow(); int getCol(); double get(int i, int j); void set(int i, int j, double value); Matrix times(@NonNull Matrix matrix); Matrix times(double num); Matrix timesTo(double num); Matrix timesTo(@NonNull Matrix matrix); Matrix plus(@NonNull Matrix matrix); Matrix plusTo(@NonNull Matrix matrix); Matrix minus(@NonNull Matrix matrix); Matrix minusTo(@NonNull Matrix matrix); Matrix dot(@NonNull Matrix matrix); Matrix transpose(); static Matrix array(@NonNull double[][] arrays); static Matrix array(@NonNull double[] array, int row); static Matrix randn(int row, int col); static Matrix plus(@NonNull Matrix a, @NonNull Matrix b); static Matrix plusTo(@NonNull Matrix a,@NonNull Matrix b); static Matrix minus(@NonNull Matrix a,@NonNull Matrix b); static Matrix minusTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix dot(@NonNull Matrix a, @NonNull Matrix b); static Matrix transpose(@NonNull Matrix a); static Matrix zeroLike(Matrix matrix); static Matrix zeros(@NonNull int... shape); }### Answer: @Test public void testPlus() { final Matrix a = Matrix.array(new double[]{ 1, 2, 3, 4, 5, 6 }, 3); final Matrix b = Matrix.array(new double[]{ 6, 5, 4, 3, 2, 1 }, 3); final Matrix c = a.plus(b); assertNotSame(c, a); assertEquals(c.getRow(), 3); assertEquals(c.getCol(), 2); assertArrayEquals(c.getArray(), new double[]{ 7, 7, 7, 7, 7, 7 }, 0); }
### Question: Matrix implements Serializable { public Matrix plusTo(@NonNull Matrix matrix) { checkNotNull(matrix); return Matrix.plusTo(this, matrix); } private Matrix(double[] array, int row, int col); int[] shape(); double[] getArray(); double[][] getArrays(); Matrix copy(); int getRow(); int getCol(); double get(int i, int j); void set(int i, int j, double value); Matrix times(@NonNull Matrix matrix); Matrix times(double num); Matrix timesTo(double num); Matrix timesTo(@NonNull Matrix matrix); Matrix plus(@NonNull Matrix matrix); Matrix plusTo(@NonNull Matrix matrix); Matrix minus(@NonNull Matrix matrix); Matrix minusTo(@NonNull Matrix matrix); Matrix dot(@NonNull Matrix matrix); Matrix transpose(); static Matrix array(@NonNull double[][] arrays); static Matrix array(@NonNull double[] array, int row); static Matrix randn(int row, int col); static Matrix plus(@NonNull Matrix a, @NonNull Matrix b); static Matrix plusTo(@NonNull Matrix a,@NonNull Matrix b); static Matrix minus(@NonNull Matrix a,@NonNull Matrix b); static Matrix minusTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix dot(@NonNull Matrix a, @NonNull Matrix b); static Matrix transpose(@NonNull Matrix a); static Matrix zeroLike(Matrix matrix); static Matrix zeros(@NonNull int... shape); }### Answer: @Test public void testPlusTo() { final Matrix a = Matrix.array(new double[]{ 1, 2, 3, 4, 5, 6 }, 3); final Matrix b = Matrix.array(new double[]{ 6, 5, 4, 3, 2, 1 }, 3); final Matrix c = a.plusTo(b); assertSame(c, a); assertArrayEquals(a.getArray(), new double[]{ 7, 7, 7, 7, 7, 7 }, 0); }
### Question: Matrix implements Serializable { public Matrix minus(@NonNull Matrix matrix) { checkNotNull(matrix); return Matrix.minus(this, matrix); } private Matrix(double[] array, int row, int col); int[] shape(); double[] getArray(); double[][] getArrays(); Matrix copy(); int getRow(); int getCol(); double get(int i, int j); void set(int i, int j, double value); Matrix times(@NonNull Matrix matrix); Matrix times(double num); Matrix timesTo(double num); Matrix timesTo(@NonNull Matrix matrix); Matrix plus(@NonNull Matrix matrix); Matrix plusTo(@NonNull Matrix matrix); Matrix minus(@NonNull Matrix matrix); Matrix minusTo(@NonNull Matrix matrix); Matrix dot(@NonNull Matrix matrix); Matrix transpose(); static Matrix array(@NonNull double[][] arrays); static Matrix array(@NonNull double[] array, int row); static Matrix randn(int row, int col); static Matrix plus(@NonNull Matrix a, @NonNull Matrix b); static Matrix plusTo(@NonNull Matrix a,@NonNull Matrix b); static Matrix minus(@NonNull Matrix a,@NonNull Matrix b); static Matrix minusTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix dot(@NonNull Matrix a, @NonNull Matrix b); static Matrix transpose(@NonNull Matrix a); static Matrix zeroLike(Matrix matrix); static Matrix zeros(@NonNull int... shape); }### Answer: @Test public void testMinus() { final Matrix a = Matrix.array(new double[]{ 6, 6, 6, 6, 6, 6 }, 2); final Matrix b = Matrix.array(new double[]{ 1, 2, 3, 4, 5, 6 }, 2); final Matrix c = a.minus(b); assertNotSame(a, c); assertEquals(c.getRow(), 2); assertEquals(c.getCol(), 3); assertArrayEquals(c.getArray(), new double[]{ 5, 4, 3, 2, 1, 0 }, 0); }
### Question: Matrix implements Serializable { public Matrix minusTo(@NonNull Matrix matrix) { checkNotNull(matrix); return Matrix.minusTo(this, matrix); } private Matrix(double[] array, int row, int col); int[] shape(); double[] getArray(); double[][] getArrays(); Matrix copy(); int getRow(); int getCol(); double get(int i, int j); void set(int i, int j, double value); Matrix times(@NonNull Matrix matrix); Matrix times(double num); Matrix timesTo(double num); Matrix timesTo(@NonNull Matrix matrix); Matrix plus(@NonNull Matrix matrix); Matrix plusTo(@NonNull Matrix matrix); Matrix minus(@NonNull Matrix matrix); Matrix minusTo(@NonNull Matrix matrix); Matrix dot(@NonNull Matrix matrix); Matrix transpose(); static Matrix array(@NonNull double[][] arrays); static Matrix array(@NonNull double[] array, int row); static Matrix randn(int row, int col); static Matrix plus(@NonNull Matrix a, @NonNull Matrix b); static Matrix plusTo(@NonNull Matrix a,@NonNull Matrix b); static Matrix minus(@NonNull Matrix a,@NonNull Matrix b); static Matrix minusTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix dot(@NonNull Matrix a, @NonNull Matrix b); static Matrix transpose(@NonNull Matrix a); static Matrix zeroLike(Matrix matrix); static Matrix zeros(@NonNull int... shape); }### Answer: @Test public void testMinusTo() { final Matrix a = Matrix.array(new double[]{ 6, 6, 6, 6, 6, 6 }, 2); final Matrix b = Matrix.array(new double[]{ 1, 2, 3, 4, 5, 6 }, 2); final Matrix c = a.minusTo(b); assertSame(c, a); assertArrayEquals(a.getArray(), new double[]{ 5, 4, 3, 2, 1, 0 }, 0); }
### Question: Matrix implements Serializable { public Matrix times(@NonNull Matrix matrix) { checkNotNull(matrix); return Matrix.times(this, matrix); } private Matrix(double[] array, int row, int col); int[] shape(); double[] getArray(); double[][] getArrays(); Matrix copy(); int getRow(); int getCol(); double get(int i, int j); void set(int i, int j, double value); Matrix times(@NonNull Matrix matrix); Matrix times(double num); Matrix timesTo(double num); Matrix timesTo(@NonNull Matrix matrix); Matrix plus(@NonNull Matrix matrix); Matrix plusTo(@NonNull Matrix matrix); Matrix minus(@NonNull Matrix matrix); Matrix minusTo(@NonNull Matrix matrix); Matrix dot(@NonNull Matrix matrix); Matrix transpose(); static Matrix array(@NonNull double[][] arrays); static Matrix array(@NonNull double[] array, int row); static Matrix randn(int row, int col); static Matrix plus(@NonNull Matrix a, @NonNull Matrix b); static Matrix plusTo(@NonNull Matrix a,@NonNull Matrix b); static Matrix minus(@NonNull Matrix a,@NonNull Matrix b); static Matrix minusTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix dot(@NonNull Matrix a, @NonNull Matrix b); static Matrix transpose(@NonNull Matrix a); static Matrix zeroLike(Matrix matrix); static Matrix zeros(@NonNull int... shape); }### Answer: @Test public void testTimes() { final Matrix a = Matrix.array(new double[]{ 1, 2, 3, 4, 5, 6 }, 3); final Matrix b = Matrix.array(new double[]{ 1, 2, 3, 4, 5, 6 }, 3); final Matrix c = a.times(b); assertNotSame(c, a); assertEquals(c.getRow(), 3); assertEquals(c.getCol(), 2); assertArrayEquals(c.getArray(), new double[]{ 1, 4, 9, 16, 25, 36 }, 0); }
### Question: Matrix implements Serializable { public Matrix timesTo(double num) { return Matrix.timesTo(this, num); } private Matrix(double[] array, int row, int col); int[] shape(); double[] getArray(); double[][] getArrays(); Matrix copy(); int getRow(); int getCol(); double get(int i, int j); void set(int i, int j, double value); Matrix times(@NonNull Matrix matrix); Matrix times(double num); Matrix timesTo(double num); Matrix timesTo(@NonNull Matrix matrix); Matrix plus(@NonNull Matrix matrix); Matrix plusTo(@NonNull Matrix matrix); Matrix minus(@NonNull Matrix matrix); Matrix minusTo(@NonNull Matrix matrix); Matrix dot(@NonNull Matrix matrix); Matrix transpose(); static Matrix array(@NonNull double[][] arrays); static Matrix array(@NonNull double[] array, int row); static Matrix randn(int row, int col); static Matrix plus(@NonNull Matrix a, @NonNull Matrix b); static Matrix plusTo(@NonNull Matrix a,@NonNull Matrix b); static Matrix minus(@NonNull Matrix a,@NonNull Matrix b); static Matrix minusTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix dot(@NonNull Matrix a, @NonNull Matrix b); static Matrix transpose(@NonNull Matrix a); static Matrix zeroLike(Matrix matrix); static Matrix zeros(@NonNull int... shape); }### Answer: @Test public void testTimesTo() { final Matrix a = Matrix.array(new double[]{ 1, 2, 3, 4, 5, 6 }, 3); final Matrix b = Matrix.array(new double[]{ 1, 2, 3, 4, 5, 6 }, 3); final Matrix c = a.timesTo(b); assertSame(c, a); assertArrayEquals(a.getArray(), new double[]{ 1, 4, 9, 16, 25, 36 }, 0); }
### Question: Matrix implements Serializable { public double get(int i, int j) { checkExpression(i >= 0 && i < mRow && j >= 0 && j < mCol, "Row or col is out of bounds"); return mArray[i * mCol + j]; } private Matrix(double[] array, int row, int col); int[] shape(); double[] getArray(); double[][] getArrays(); Matrix copy(); int getRow(); int getCol(); double get(int i, int j); void set(int i, int j, double value); Matrix times(@NonNull Matrix matrix); Matrix times(double num); Matrix timesTo(double num); Matrix timesTo(@NonNull Matrix matrix); Matrix plus(@NonNull Matrix matrix); Matrix plusTo(@NonNull Matrix matrix); Matrix minus(@NonNull Matrix matrix); Matrix minusTo(@NonNull Matrix matrix); Matrix dot(@NonNull Matrix matrix); Matrix transpose(); static Matrix array(@NonNull double[][] arrays); static Matrix array(@NonNull double[] array, int row); static Matrix randn(int row, int col); static Matrix plus(@NonNull Matrix a, @NonNull Matrix b); static Matrix plusTo(@NonNull Matrix a,@NonNull Matrix b); static Matrix minus(@NonNull Matrix a,@NonNull Matrix b); static Matrix minusTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix dot(@NonNull Matrix a, @NonNull Matrix b); static Matrix transpose(@NonNull Matrix a); static Matrix zeroLike(Matrix matrix); static Matrix zeros(@NonNull int... shape); }### Answer: @Test public void testGet() { final Matrix a = Matrix.array(new double[]{ 1, 2, 3, 4, 5, 6 }, 3); assertEquals(a.get(2,1), 6, 0); }
### Question: Matrix implements Serializable { public void set(int i, int j, double value) { checkExpression(i >= 0 && i < mRow && j >= 0 && j < mCol, "Row or col is out of bounds"); mArray[i * mCol + j] = value; } private Matrix(double[] array, int row, int col); int[] shape(); double[] getArray(); double[][] getArrays(); Matrix copy(); int getRow(); int getCol(); double get(int i, int j); void set(int i, int j, double value); Matrix times(@NonNull Matrix matrix); Matrix times(double num); Matrix timesTo(double num); Matrix timesTo(@NonNull Matrix matrix); Matrix plus(@NonNull Matrix matrix); Matrix plusTo(@NonNull Matrix matrix); Matrix minus(@NonNull Matrix matrix); Matrix minusTo(@NonNull Matrix matrix); Matrix dot(@NonNull Matrix matrix); Matrix transpose(); static Matrix array(@NonNull double[][] arrays); static Matrix array(@NonNull double[] array, int row); static Matrix randn(int row, int col); static Matrix plus(@NonNull Matrix a, @NonNull Matrix b); static Matrix plusTo(@NonNull Matrix a,@NonNull Matrix b); static Matrix minus(@NonNull Matrix a,@NonNull Matrix b); static Matrix minusTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix dot(@NonNull Matrix a, @NonNull Matrix b); static Matrix transpose(@NonNull Matrix a); static Matrix zeroLike(Matrix matrix); static Matrix zeros(@NonNull int... shape); }### Answer: @Test public void testSet() { final Matrix a = Matrix.array(new double[]{ 1, 2, 3, 4, 5, 6 }, 3); a.set(1, 1, 666); assertEquals(a.get(1, 1), 666, 0); }
### Question: Matrix implements Serializable { public Matrix dot(@NonNull Matrix matrix) { checkNotNull(matrix); return Matrix.dot(this, matrix); } private Matrix(double[] array, int row, int col); int[] shape(); double[] getArray(); double[][] getArrays(); Matrix copy(); int getRow(); int getCol(); double get(int i, int j); void set(int i, int j, double value); Matrix times(@NonNull Matrix matrix); Matrix times(double num); Matrix timesTo(double num); Matrix timesTo(@NonNull Matrix matrix); Matrix plus(@NonNull Matrix matrix); Matrix plusTo(@NonNull Matrix matrix); Matrix minus(@NonNull Matrix matrix); Matrix minusTo(@NonNull Matrix matrix); Matrix dot(@NonNull Matrix matrix); Matrix transpose(); static Matrix array(@NonNull double[][] arrays); static Matrix array(@NonNull double[] array, int row); static Matrix randn(int row, int col); static Matrix plus(@NonNull Matrix a, @NonNull Matrix b); static Matrix plusTo(@NonNull Matrix a,@NonNull Matrix b); static Matrix minus(@NonNull Matrix a,@NonNull Matrix b); static Matrix minusTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix dot(@NonNull Matrix a, @NonNull Matrix b); static Matrix transpose(@NonNull Matrix a); static Matrix zeroLike(Matrix matrix); static Matrix zeros(@NonNull int... shape); }### Answer: @Test public void testDot() { final Matrix a = Matrix.array(new double[]{ 1, 2, 3, 4, 5, 6 }, 2); final Matrix b = Matrix.array(new double[]{ 1, 2, 9, 4, 5, 7 }, 3); final Matrix c = a.dot(b); assertEquals(c.getRow(), 2); assertEquals(c.getCol(), 2); assertArrayEquals(c.getArray(), new double[]{ 34, 31, 79, 70 }, 0); }
### Question: MatrixChecker { static void checkDimensions(int row, int col) { checkExpression(row > 0 && col > 0, "Row and column should be positive"); } }### Answer: @Test(expected = IllegalArgumentException.class) public void testCheckDimensions() { MatrixChecker.checkDimensions(-1, 0); } @Test public void testCheckDimensions1() { MatrixChecker.checkDimensions( 2, 3); } @Test public void testCheckDimensions2() { final Matrix a = Matrix.zeros(2, 3); final Matrix b = a.copy(); MatrixChecker.checkDimensions(a, b); } @Test(expected = IllegalArgumentException.class) public void testCheckDimensions3() { final Matrix a = Matrix.zeros(2, 3); final Matrix b = Matrix.zeros(3, 3); MatrixChecker.checkDimensions(a, b); }
### Question: MatrixChecker { static void checkInnerDimensions(@NonNull Matrix a, @NonNull Matrix b) { checkExpression(a.getCol() == b.getRow(), "Matrix inner dimensions must agree"); } }### Answer: @Test public void testCheckInnerDimension() { final Matrix a = Matrix.zeros(2, 3); final Matrix b = Matrix.zeros(3, 2); MatrixChecker.checkInnerDimensions(a, b); } @Test(expected = IllegalArgumentException.class) public void testCheckInnerDimension2() { final Matrix a = Matrix.zeros(2, 3); final Matrix b = Matrix.zeros(3, 3); MatrixChecker.checkInnerDimensions(b, a); }
### Question: Matrix implements Serializable { public int[] shape() { return new int[]{mRow, mCol}; } private Matrix(double[] array, int row, int col); int[] shape(); double[] getArray(); double[][] getArrays(); Matrix copy(); int getRow(); int getCol(); double get(int i, int j); void set(int i, int j, double value); Matrix times(@NonNull Matrix matrix); Matrix times(double num); Matrix timesTo(double num); Matrix timesTo(@NonNull Matrix matrix); Matrix plus(@NonNull Matrix matrix); Matrix plusTo(@NonNull Matrix matrix); Matrix minus(@NonNull Matrix matrix); Matrix minusTo(@NonNull Matrix matrix); Matrix dot(@NonNull Matrix matrix); Matrix transpose(); static Matrix array(@NonNull double[][] arrays); static Matrix array(@NonNull double[] array, int row); static Matrix randn(int row, int col); static Matrix plus(@NonNull Matrix a, @NonNull Matrix b); static Matrix plusTo(@NonNull Matrix a,@NonNull Matrix b); static Matrix minus(@NonNull Matrix a,@NonNull Matrix b); static Matrix minusTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix dot(@NonNull Matrix a, @NonNull Matrix b); static Matrix transpose(@NonNull Matrix a); static Matrix zeroLike(Matrix matrix); static Matrix zeros(@NonNull int... shape); }### Answer: @Test public void testShape() { final Matrix a = Matrix.array(new double[]{ 1, 2, 3, 4, 5, 6 }, 3); assertArrayEquals(a.shape(), new int[]{ 3, 2 }); }
### Question: IpBlockFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { initializeReloadCommandParamName(filterConfig); createIpBlocker(filterConfig); } @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); @Override void destroy(); static final String RELOAD_COMMAND_PARAM_NAME_CONFIG_NAME; static final String DEFAULT_RELOAD_COMMAND_PARAM_NAME_VALUE; }### Answer: @Test public void filterInit() throws ServletException, IOException { assertFalse(FakeIpBlocker.created); filter.init(mockFilterConfig); assertTrue(FakeIpBlocker.created); }
### Question: ConfigIpFilter implements IpFilter { @Override public boolean accept(String ip) { if (allowFirst) return accepAllowFirst(ip); else return acceptDenyFirst(ip); } ConfigIpFilter(Config config); @Override boolean accept(String ip); }### Answer: @Test public void shouldReturnTrueDupIpInAllowAndDenyListWhenAllowFirst() { Config config = new Config(); config.setAllowFirst(true); config.allow("1.2.3.4"); config.deny("1.2.3.4"); IpFilter ipFilter = new ConfigIpFilter(config); assertTrue(ipFilter.accept("1.2.3.4")); } @Test public void shouldReturnFalseDupIpInAllowAndDenyListWhenDenyFirst() { Config config = new Config(); config.setAllowFirst(false); config.allow("1.2.3.4"); config.deny("1.2.3.4"); IpFilter ipFilter = new ConfigIpFilter(config); assertFalse(ipFilter.accept("1.2.3.4")); }
### Question: IpFilters { public static IpFilter create(Config config) { return new ConfigIpFilter(config); } static IpFilter create(Config config); static IpFilter createCached(Config config); }### Answer: @Test public void createIpFilterWithConfig() { IpFilter filter = IpFilters.create(createConfig()); assertTrue(filter instanceof ConfigIpFilter); }
### Question: IpFilters { public static IpFilter createCached(Config config) { return new CachedIpFilter(create(config)); } static IpFilter create(Config config); static IpFilter createCached(Config config); }### Answer: @Test public void createCachedIpFilterWithConfig() { IpFilter filter = IpFilters.createCached(createConfig()); assertTrue(filter instanceof CachedIpFilter); }
### Question: NumberNode { public boolean isSimpleNumber() { return isSimpleNumber; } NumberNode(String number); NumberNode createOrGetChildNumber(String numberPattern); NumberNode findMatchingChild(String number); boolean isMatch(String number); boolean isSimpleNumber(); boolean isAllAccept(); }### Answer: @Test public void createSimpleNode() { NumberNode node = new NumberNode("10"); assertTrue(node.isSimpleNumber()); } @Test public void createPatternNodeWith128_25() { NumberNode node = new NumberNode("128/25"); assertFalse(node.isSimpleNumber()); assertNodeMatch(node, 128, 255, true); assertNodeMatch(node, 0, 127, false); } @Test public void createPatternNodeWith8_30() { NumberNode node = new NumberNode("8/30"); assertFalse(node.isSimpleNumber()); assertNodeMatch(node, 8, 11, true); assertNodeMatch(node, 0, 7, false); assertNodeMatch(node, 12, 255, false); }
### Question: IpBlockFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (ipBlocker.accept(request.getRemoteAddr())) processDoFilter(request, response, chain); else sendNotFoundResponse((HttpServletResponse) response); } @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); @Override void destroy(); static final String RELOAD_COMMAND_PARAM_NAME_CONFIG_NAME; static final String DEFAULT_RELOAD_COMMAND_PARAM_NAME_VALUE; }### Answer: @Test public void shouldRunChainWhenIpIsNotBlocked() throws ServletException, IOException { filterInit(); when(mockRequest.getRemoteAddr()).thenReturn(FakeIpBlocker.ALLOW_IP); filter.doFilter(mockRequest, mockResponse, mockFilterChain); verify(mockFilterChain, only()).doFilter(mockRequest, mockResponse); } @Test public void shouldResponse404WhenIpIsBlocked() throws ServletException, IOException { filterInit(); when(mockRequest.getRemoteAddr()).thenReturn(DENY_IP); filter.doFilter(mockRequest, mockResponse, mockFilterChain); verify(mockFilterChain, never()).doFilter(mockRequest, mockResponse); verify(mockResponse, only()).sendError(HttpServletResponse.SC_NOT_FOUND); } @Test public void shouldReloadWhenRequestHasReloadParameter() throws ServletException, IOException { filterInit(); when(mockRequest.getRemoteAddr()).thenReturn(FakeIpBlocker.ALLOW_IP); filter.doFilter(mockRequest, mockResponse, mockFilterChain); assertFalse(FakeIpBlocker.reloaded); when(mockRequest.getParameter("IBFRM")).thenReturn("true"); filter.doFilter(mockRequest, mockResponse, mockFilterChain); assertTrue(FakeIpBlocker.reloaded); }
### Question: ConfigFactory { public static ConfigFactory getInstance(String type) { if (type.equals("text")) return new TextConfigFactory(); if (type.equals("file")) return new FileConfigFactory(); if (type.equals("classpath")) return new ClasspathConfigFactory(); return null; } static ConfigFactory getInstance(String type); abstract Config create(String value); abstract boolean isReloadSupported(); }### Answer: @Test public void getFileConfigFactory() { ConfigFactory factory = ConfigFactory.getInstance("file"); assertTrue(factory instanceof FileConfigFactory); } @Test public void getClasspathConfigFactory() { ConfigFactory factory = ConfigFactory.getInstance("classpath"); assertTrue(factory instanceof ClasspathConfigFactory); } @Test public void getTextConfigFactory() { ConfigFactory factory = ConfigFactory.getInstance("text"); assertTrue(factory instanceof TextConfigFactory); }
### Question: IpBlockerFactoryImpl extends IpBlockerFactory { @Override public IpBlocker create(Map<String, String> config) { try { IpBlockerImpl ipBlocker = new IpBlockerImpl(); ipBlocker.init(config); return ipBlocker; } catch (Exception ex) { throw new IpBlockerCreationException(ex); } } @Override IpBlocker create(Map<String, String> config); }### Answer: @Test public void shouldCreateIpBlockerImplInstance() { IpBlocker ipBlocker = new IpBlockerFactoryImpl().create(ConfigMapUtil.getTextConfigMap()); assertTrue(ipBlocker instanceof IpBlockerImpl); }
### Question: CachedIpFilter implements IpFilter { @Override public boolean accept(String ip) { if (cachedMap.containsKey(ip)) return cachedMap.get(ip); Boolean result = delegate.accept(ip); cachedMap.put(ip, result); return result; } CachedIpFilter(IpFilter delegate); @Override boolean accept(String ip); }### Answer: @Test public void shouldCacheDupIp() { IpFilter mockFilter = mock(IpFilter.class); String ip = "1.2.3.4"; when(mockFilter.accept(ip)).thenReturn(true); CachedIpFilter filter = new CachedIpFilter(mockFilter); filter.accept(ip); verify(mockFilter, only()).accept(ip); filter.accept(ip); verify(mockFilter, only()).accept(ip); }
### Question: IpTree { public void add(String ip) { String[] ipNumbers = ip.split("\\."); NumberNode node = root; for (String number : ipNumbers) node = node.createOrGetChildNumber(number); } void add(String ip); boolean containsIp(String ip); }### Answer: @Test public void level4StarIpTree() { ipTree.add("10.20.30.*"); assertIpTreeContainsIp(ipTree, "10.20.30", 0, 255, true); }
### Question: Store { List<String> read(String name) { final List<String> allKeys = new ArrayList<>(sharedPreferences.getAll().keySet()); Collections.sort(allKeys); final Pattern pattern = Pattern.compile("^[0-9]+" + Pattern.quote("_" + name) + "$"); final List<String> result = new ArrayList<>(); for (String key : allKeys) { if (pattern.matcher(key).matches()) { result.add(sharedPreferences.getString(key, AutoFiller.EMPTY_FIELD)); } } return result; } Store(SharedPreferences sharedPreferences); }### Answer: @Test public void read_without_saves_returns_empty_list() throws Exception { assertEquals(Collections.emptyList(), store.read("t")); }
### Question: Phial { public static void setKey(String key, String value) { DEFAULT_CATEGORY.setKey(key, value); } static void setKey(String key, String value); static void setKey(@NonNull String key, @Nullable Object value); static void removeKey(String key); static Category category(String name); static void removeCategory(String name); static void addSaver(Saver saver); static void removeSaver(Saver saver); }### Answer: @Test public void setKey_call_setKey_for_all_savers() throws Exception { Phial.setKey("key", "value"); savers.forEach(saver -> verify(saver).save(anyString(), eq("key"), eq("value")) ); }
### Question: Phial { public static void removeKey(String key) { DEFAULT_CATEGORY.removeKey(key); } static void setKey(String key, String value); static void setKey(@NonNull String key, @Nullable Object value); static void removeKey(String key); static Category category(String name); static void removeCategory(String name); static void addSaver(Saver saver); static void removeSaver(Saver saver); }### Answer: @Test public void removeKey_call_removeKey_for_all_savers() throws Exception { Phial.removeKey("key"); savers.forEach(saver -> verify(saver).remove(anyString(), eq("key")) ); }
### Question: Phial { public static void removeSaver(Saver saver) { SAVERS.remove(saver); } static void setKey(String key, String value); static void setKey(@NonNull String key, @Nullable Object value); static void removeKey(String key); static Category category(String name); static void removeCategory(String name); static void addSaver(Saver saver); static void removeSaver(Saver saver); }### Answer: @Test public void removeSaver() { savers.forEach(Phial::removeSaver); Phial.setKey("key", "value"); Phial.removeKey("key"); Phial.category("category").setKey("key", "value"); Phial.category("category").removeKey("key"); savers.forEach(Mockito::verifyZeroInteractions); }
### Question: FileUtil { public static void write(String text, File target) throws IOException { BufferedWriter bw = null; FileWriter fw = null; try { fw = new FileWriter(target); bw = new BufferedWriter(fw); bw.write(text); } finally { if (bw != null) { bw.close(); } if (fw != null) { fw.close(); } } } private FileUtil(); static void write(String text, File target); static Uri getUri(Context context, String authority, File file); static void saveBitmap(Bitmap bitmap, File targetFile, int quality); static void saveBitmap(Bitmap bitmap, File targetFile, Bitmap.CompressFormat format, int quality); static void zip(List<File> sources, File target); static List<File> walk(File source); static List<File> walk(List<File> sources); static String uniqueName(File source, Set<String> taken); static String getFileExtension(File file); static String getFileNameWithoutExtention(File file); }### Answer: @Test public void write() throws Exception { FileUtil.write("test text", file); Assert.assertEquals( "test text", Files.lines(Paths.get(FILE_NAME)).reduce("", (l, r) -> l + r) ); }
### Question: FileUtil { public static void saveBitmap(Bitmap bitmap, File targetFile, int quality) throws IOException { saveBitmap(bitmap, targetFile, Bitmap.CompressFormat.JPEG, quality); } private FileUtil(); static void write(String text, File target); static Uri getUri(Context context, String authority, File file); static void saveBitmap(Bitmap bitmap, File targetFile, int quality); static void saveBitmap(Bitmap bitmap, File targetFile, Bitmap.CompressFormat format, int quality); static void zip(List<File> sources, File target); static List<File> walk(File source); static List<File> walk(List<File> sources); static String uniqueName(File source, Set<String> taken); static String getFileExtension(File file); static String getFileNameWithoutExtention(File file); }### Answer: @Test public void saveBitmap() throws Exception { final Bitmap bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.RGB_565); FileUtil.saveBitmap(bitmap, file, 100); final Bitmap result = BitmapFactory.decodeFile(FILE_NAME); Assert.assertEquals(100, result.getHeight()); Assert.assertEquals(100, result.getWidth()); } @Test public void saveBitmapWithConfig() throws Exception { final Bitmap bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.RGB_565); FileUtil.saveBitmap(bitmap, file, Bitmap.CompressFormat.PNG, 100); final BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inPreferredConfig = Bitmap.Config.RGB_565; final Bitmap result = BitmapFactory.decodeFile(FILE_NAME, opts); Assert.assertEquals(100, result.getHeight()); Assert.assertEquals(100, result.getWidth()); Assert.assertEquals(bitmap.getPixel(0, 0), result.getPixel(0, 0)); }
### Question: FileUtil { public static List<File> walk(File source) { if (!source.isDirectory()) { return Collections.singletonList(source); } final File[] files = source.listFiles(); return walk(Arrays.asList(files)); } private FileUtil(); static void write(String text, File target); static Uri getUri(Context context, String authority, File file); static void saveBitmap(Bitmap bitmap, File targetFile, int quality); static void saveBitmap(Bitmap bitmap, File targetFile, Bitmap.CompressFormat format, int quality); static void zip(List<File> sources, File target); static List<File> walk(File source); static List<File> walk(List<File> sources); static String uniqueName(File source, Set<String> taken); static String getFileExtension(File file); static String getFileNameWithoutExtention(File file); }### Answer: @Test public void walk() { final File dir1 = createDirectories("dir1"); final File dir12 = createDirectories("dir1", "dir2"); final File dir2 = createDirectories("dir2"); final File dir3 = createDirectories("dir3"); createFiles(dir1, "f1.txt", "f2.txt", "f3.txt"); createFiles(dir12, "f1.txt", "f4.txt"); createFiles(dir2); createFiles(dir3, "f1.txt"); Assert.assertEquals(CollectionUtils.asSet( new File(dir1, "f1.txt"), new File(dir1, "f2.txt"), new File(dir1, "f3.txt"), new File(dir12, "f1.txt"), new File(dir12, "f4.txt"), new File(dir3, "f1.txt")), new HashSet<>(FileUtil.walk(file)) ); }
### Question: FileUtil { public static String uniqueName(File source, Set<String> taken) { String name = source.getName(); for (int i = 1; taken.contains(name); i++) { name = getFileNameWithoutExtention(source) + "_" + i; final String extension = getFileExtension(source); if (!extension.isEmpty()) { name += "." + extension; } } return name; } private FileUtil(); static void write(String text, File target); static Uri getUri(Context context, String authority, File file); static void saveBitmap(Bitmap bitmap, File targetFile, int quality); static void saveBitmap(Bitmap bitmap, File targetFile, Bitmap.CompressFormat format, int quality); static void zip(List<File> sources, File target); static List<File> walk(File source); static List<File> walk(List<File> sources); static String uniqueName(File source, Set<String> taken); static String getFileExtension(File file); static String getFileNameWithoutExtention(File file); }### Answer: @Test public void uniqueName_returns_same_if_not_taken() { final File file = new File("f.txt"); Assert.assertEquals("f.txt", FileUtil.uniqueName(file, new HashSet<>())); } @Test public void uniqueName_returns_new_name_if_taken() { final File file = new File("f.txt"); Assert.assertEquals("f_2.txt", FileUtil.uniqueName(file, CollectionUtils.asSet("f.txt", "f_1.txt"))); } @Test public void uniqueName_returns_new_name_if_taken_file_without_extension() { final File file = new File("f"); Assert.assertEquals("f_2", FileUtil.uniqueName(file, CollectionUtils.asSet("f", "f_1"))); } @Test public void uniqueName_returns_new_name_if_taken_file_starts_with_dot() { final File file = new File(".ignore"); Assert.assertEquals(".ignore_2", FileUtil.uniqueName(file, CollectionUtils.asSet(".ignore", ".ignore_1"))); }
### Question: ConfigManager { List<FillOption> getOptions() { final List<FillOption> savedOptions = readConfigsFromStore(); final List<FillOption> result = new ArrayList<>(fillConfig.getOptions().size() + savedOptions.size()); result.addAll(savedOptions); result.addAll(fillConfig.getOptions()); return result; } ConfigManager(FillConfig fillConfig, Store store); }### Answer: @Test public void getOptions_returns_all_options() throws Exception { when(store.read(eq(ConfigManager.ORDER))).thenReturn(Collections.singletonList("n1")); when(store.read(eq(ConfigManager.KEY_PREFIX + "n1"))).thenReturn(Arrays.asList("v1", "v2")); final List<FillOption> expected = new ArrayList<>(); expected.add(new FillOption("n1", Arrays.asList("v1", "v2"))); expected.addAll(simpleOptions("opt1", "opt2")); assertEquals(expected, configManager.getOptions()); } @Test public void getOptions_not_include_options_with_bad_size() throws Exception { when(store.read(eq(ConfigManager.ORDER))).thenReturn(Arrays.asList("n1", "n2")); when(store.read(eq(ConfigManager.KEY_PREFIX + "n1"))).thenReturn(Collections.singletonList("v1")); when(store.read(eq(ConfigManager.KEY_PREFIX + "n1"))).thenReturn(Arrays.asList("v1", "v2", "v3")); assertEquals(simpleOptions("opt1", "opt2"), configManager.getOptions()); } @Test public void getOptions_with_empty_custom_options_returns_options_from_config_only() throws Exception { when(store.read(eq(ConfigManager.ORDER))).thenReturn(Collections.emptyList()); assertEquals(simpleOptions("opt1", "opt2"), configManager.getOptions()); verify(store, times(1)).read(anyString()); }
### Question: CurrentActivityProvider extends SimpleActivityLifecycleCallbacks { public Activity getActivity() { return activity; } @Override void onActivityResumed(Activity activity); @Override void onActivityPaused(Activity activity); Activity getActivity(); void addListener(AppStateListener listener); void removeListener(AppStateListener listener); }### Answer: @Test public void getActivity_returns_null_at_start() throws Exception { assertNull(provider.getActivity()); }
### Question: AnimatorFactory { static int calcRadius(int width, int height) { return (int) Math.round(Math.sqrt((float) width * width + height * height)); } AnimatorFactory(View startView); static AnimatorFactory createFactory(View startView); abstract Animator createAppearAnimator(View targetView); abstract Animator createDisappearAnimator(View targetView); }### Answer: @Test public void calRadius_returns_correct_radius() throws Exception { final int radius = AnimatorFactory.calcRadius(3, 4); assertEquals(5, radius); }