method2testcases
stringlengths 118
3.08k
|
---|
### Question:
CloudFoundryServiceInfoCreator implements ServiceInfoCreator<SI, Map<String, Object>> { protected boolean uriKeyMatchesScheme(Map<String, Object> serviceData) { if (uriSchemes == null) { return false; } Map<String, Object> credentials = getCredentials(serviceData); if (credentials != null) { for (String uriScheme : uriSchemes) { if (credentials.containsKey(uriScheme + "Uri") || credentials.containsKey(uriScheme + "uri") || credentials.containsKey(uriScheme + "Url") || credentials.containsKey(uriScheme + "url")) { return true; } } } return false; } CloudFoundryServiceInfoCreator(Tags tags, String... uriSchemes); boolean accept(Map<String, Object> serviceData); String[] getUriSchemes(); String getDefaultUriScheme(); }### Answer:
@Test public void uriKeyMatchesScheme() { DummyServiceInfoCreator serviceInfoCreator = new DummyServiceInfoCreator(new Tags(), "amqp", "amqps"); assertAcceptedWithCredentials(serviceInfoCreator, "amqpUri", "https: assertAcceptedWithCredentials(serviceInfoCreator, "amqpsUri", "https: assertAcceptedWithCredentials(serviceInfoCreator, "amqpUrl", "https: assertAcceptedWithCredentials(serviceInfoCreator, "amqpsUrl", "https: assertAcceptedWithCredentials(serviceInfoCreator, "amqpuri", "https: assertAcceptedWithCredentials(serviceInfoCreator, "amqpsuri", "https: assertAcceptedWithCredentials(serviceInfoCreator, "amqpurl", "https: assertAcceptedWithCredentials(serviceInfoCreator, "amqpsurl", "https: } |
### Question:
Tags { public boolean containsOne(List<String> tags) { if (tags != null) { for (String value : values) { for (String tag : tags) { if (tag.equalsIgnoreCase(value)) { return true; } } } } return false; } Tags(String... values); String[] getTags(); boolean containsOne(List<String> tags); boolean contains(String tag); boolean startsWith(String tag); }### Answer:
@Test public void containsOne() { Tags tags = new Tags("test1", "test2"); assertTrue(tags.containsOne(Arrays.asList("test1", "testx"))); assertTrue(tags.containsOne(Arrays.asList("testx", "test2"))); assertTrue(tags.containsOne(Arrays.asList("TESTX", "TEST2"))); assertFalse(tags.containsOne(Arrays.asList("testx", "testy"))); }
@Test public void containsOneWithEmptyTags() { assertFalse(EMPTY_TAGS.containsOne(Arrays.asList("test"))); } |
### Question:
Tags { public boolean contains(String tag) { if (tag != null) { for (String value : values) { if (tag.equalsIgnoreCase(value)) { return true; } } } return false; } Tags(String... values); String[] getTags(); boolean containsOne(List<String> tags); boolean contains(String tag); boolean startsWith(String tag); }### Answer:
@Test public void contains() { Tags tags = new Tags("test1", "test2"); assertTrue(tags.contains("test1")); assertTrue(tags.contains("test2")); assertTrue(tags.contains("TEST2")); assertFalse(tags.contains("testx")); }
@Test public void containsWithEmptyTags() { assertFalse(EMPTY_TAGS.contains("test")); } |
### Question:
Tags { public boolean startsWith(String tag) { if (tag != null) { for (String value : values) { if (startsWithIgnoreCase(tag, value)) { return true; } } } return false; } Tags(String... values); String[] getTags(); boolean containsOne(List<String> tags); boolean contains(String tag); boolean startsWith(String tag); }### Answer:
@Test public void startsWith() { Tags tags = new Tags("test"); assertTrue(tags.startsWith("test-123")); assertTrue(tags.startsWith("TEST-123")); assertFalse(tags.startsWith("abcd")); }
@Test public void startsWithWithEmptyTags() { assertFalse(EMPTY_TAGS.startsWith("test")); } |
### Question:
ValueBuilderTemplate { public T newInstance(Module module) { ValueBuilder<T> builder = module.newValueBuilder( type ); build( builder.prototype() ); return builder.newInstance(); } protected ValueBuilderTemplate( Class<T> type ); T newInstance(Module module); }### Answer:
@Test public void testTemplate() { new TestBuilder( "Rickard" ).newInstance( module); }
@Test public void testAnonymousTemplate() { new ValueBuilderTemplate<TestValue>(TestValue.class) { @Override protected void build( TestValue prototype ) { prototype.name().set( "Rickard" ); } }.newInstance( module ); } |
### Question:
Classes { public static String toURI( final Class clazz ) throws NullPointerException { return toURI( clazz.getName() ); } static Specification<Class<?>> isAssignableFrom( final Class clazz); static Specification<Object> instanceOf( final Class clazz); static Specification<Class<?>> hasModifier( final int classModifier ); static Function<Type, Iterable<T>> forClassHierarchy( final Function<Class<?>, Iterable<T>> function ); static Function<Type, Iterable<T>> forTypes( final Function<Type, Iterable<T>> function ); static Set<Class<?>> interfacesWithMethods( Set<Class<?>> interfaces ); static String getSimpleGenericName( Type type ); static AnnotationType getAnnotationOfTypeOrAnyOfSuperTypes( Class<?> type,
Class<AnnotationType> annotationClass
); static Specification<Member> memberNamed( final String name ); static Type resolveTypeVariable( TypeVariable name, Class declaringClass, Class topClass ); static String toURI( final Class clazz ); static String toURI( String className ); static String toClassName( String uri ); static String normalizeClassToURI( String className ); static String denormalizeURIToClass( String uriPart ); static final Function<Type, Type> WRAPPER_CLASS; static final Function<Type, Type> PRIMITIVE_CLASS; static final Function<Type, Class<?>> RAW_CLASS; static final Function<AccessibleObject, Type> TYPE_OF; static final Function<Type, Iterable<Class<?>>> CLASS_HIERARCHY; static final Function<Type, Iterable<Type>> INTERFACES_OF; static final Function<Type, Iterable<Type>> TYPES_OF; }### Answer:
@Test public void givenClassNameWhenToUriThenUriIsReturned() { assertThat( "URI is correct", Classes.toURI( A.class ), equalTo( "urn:qi4j:type:org.qi4j.api.util.ClassesTest-A" ) ); } |
### Question:
Classes { public static String toClassName( String uri ) throws NullPointerException { uri = uri.substring( "urn:qi4j:type:".length() ); uri = denormalizeURIToClass( uri ); return uri; } static Specification<Class<?>> isAssignableFrom( final Class clazz); static Specification<Object> instanceOf( final Class clazz); static Specification<Class<?>> hasModifier( final int classModifier ); static Function<Type, Iterable<T>> forClassHierarchy( final Function<Class<?>, Iterable<T>> function ); static Function<Type, Iterable<T>> forTypes( final Function<Type, Iterable<T>> function ); static Set<Class<?>> interfacesWithMethods( Set<Class<?>> interfaces ); static String getSimpleGenericName( Type type ); static AnnotationType getAnnotationOfTypeOrAnyOfSuperTypes( Class<?> type,
Class<AnnotationType> annotationClass
); static Specification<Member> memberNamed( final String name ); static Type resolveTypeVariable( TypeVariable name, Class declaringClass, Class topClass ); static String toURI( final Class clazz ); static String toURI( String className ); static String toClassName( String uri ); static String normalizeClassToURI( String className ); static String denormalizeURIToClass( String uriPart ); static final Function<Type, Type> WRAPPER_CLASS; static final Function<Type, Type> PRIMITIVE_CLASS; static final Function<Type, Class<?>> RAW_CLASS; static final Function<AccessibleObject, Type> TYPE_OF; static final Function<Type, Iterable<Class<?>>> CLASS_HIERARCHY; static final Function<Type, Iterable<Type>> INTERFACES_OF; static final Function<Type, Iterable<Type>> TYPES_OF; }### Answer:
@Test public void givenUriWhenToClassNameThenClassNameIsReturned() { assertThat( "Class name is correct", Classes.toClassName( "urn:qi4j:type:org.qi4j.api.util.ClassesTest-A" ), equalTo( "org.qi4j.api.util.ClassesTest$A" ) ); } |
### Question:
UnitOfWorkTemplate { public RESULT withModule(Module module) throws ThrowableType, UnitOfWorkCompletionException { int loop = 0; ThrowableType ex = null; do { UnitOfWork uow = module.newUnitOfWork( usecase ); try { RESULT result = withUnitOfWork( uow ); if (complete) { try { uow.complete(); return result; } catch( ConcurrentEntityModificationException e ) { ex = (ThrowableType) e; } } } catch (Throwable e) { ex = (ThrowableType) e; } finally { uow.discard(); } } while (loop++ < retries); throw ex; } protected UnitOfWorkTemplate(); protected UnitOfWorkTemplate( int retries, boolean complete ); protected UnitOfWorkTemplate( Usecase usecase, int retries, boolean complete ); RESULT withModule(Module module); }### Answer:
@Test public void testTemplate() throws UnitOfWorkCompletionException { new UnitOfWorkTemplate<Void, RuntimeException>() { @Override protected Void withUnitOfWork( UnitOfWork uow ) throws RuntimeException { new EntityBuilderTemplate<TestEntity>(TestEntity.class) { @Override protected void build( TestEntity prototype ) { prototype.name().set( "Rickard" ); } }.newInstance( module ); return null; } }.withModule( module ); } |
### Question:
QualifiedName implements Comparable<QualifiedName>, Serializable { public String type() { return typeName.normalized(); } QualifiedName( TypeName typeName, String name ); static QualifiedName fromAccessor( AccessibleObject method ); static QualifiedName fromClass( Class type, String name ); static QualifiedName fromName( String type, String name ); static QualifiedName fromQN( String qualifiedName ); String type(); String name(); String toURI(); String toNamespace(); @Override String toString(); @Override boolean equals( Object o ); @Override int hashCode(); int compareTo( QualifiedName other ); }### Answer:
@Test public void testQualifiedNameWithDollar() { assertEquals( "Name containing dollar is modified", "Test-Test", new QualifiedName( TypeName.nameOf( "Test$Test" ), "satisfiedBy" ).type() ); } |
### Question:
QualifiedName implements Comparable<QualifiedName>, Serializable { public static QualifiedName fromQN( String qualifiedName ) { NullArgumentException.validateNotEmpty( "qualifiedName", qualifiedName ); int idx = qualifiedName.lastIndexOf( ":" ); if( idx == -1 ) { throw new IllegalArgumentException( "Name '" + qualifiedName + "' is not a qualified name" ); } final String type = qualifiedName.substring( 0, idx ); final String name = qualifiedName.substring( idx + 1 ); return new QualifiedName( TypeName.nameOf( type ), name ); } QualifiedName( TypeName typeName, String name ); static QualifiedName fromAccessor( AccessibleObject method ); static QualifiedName fromClass( Class type, String name ); static QualifiedName fromName( String type, String name ); static QualifiedName fromQN( String qualifiedName ); String type(); String name(); String toURI(); String toNamespace(); @Override String toString(); @Override boolean equals( Object o ); @Override int hashCode(); int compareTo( QualifiedName other ); }### Answer:
@Test( expected = NullArgumentException.class ) public void nonNullArguments4() { QualifiedName.fromQN( null ); } |
### Question:
QualifiedName implements Comparable<QualifiedName>, Serializable { public static QualifiedName fromAccessor( AccessibleObject method ) { NullArgumentException.validateNotNull( "method", method ); return fromClass( ((Member)method).getDeclaringClass(), ((Member)method).getName() ); } QualifiedName( TypeName typeName, String name ); static QualifiedName fromAccessor( AccessibleObject method ); static QualifiedName fromClass( Class type, String name ); static QualifiedName fromName( String type, String name ); static QualifiedName fromQN( String qualifiedName ); String type(); String name(); String toURI(); String toNamespace(); @Override String toString(); @Override boolean equals( Object o ); @Override int hashCode(); int compareTo( QualifiedName other ); }### Answer:
@Test( expected = NullArgumentException.class ) public void nonNullArguments5() { QualifiedName.fromAccessor( null ); } |
### Question:
QualifiedName implements Comparable<QualifiedName>, Serializable { public static QualifiedName fromClass( Class type, String name ) { return new QualifiedName( TypeName.nameOf( type ), name ); } QualifiedName( TypeName typeName, String name ); static QualifiedName fromAccessor( AccessibleObject method ); static QualifiedName fromClass( Class type, String name ); static QualifiedName fromName( String type, String name ); static QualifiedName fromQN( String qualifiedName ); String type(); String name(); String toURI(); String toNamespace(); @Override String toString(); @Override boolean equals( Object o ); @Override int hashCode(); int compareTo( QualifiedName other ); }### Answer:
@Test( expected = NullArgumentException.class ) public void nonNullArguments6() { QualifiedName.fromClass( null, "satisfiedBy" ); }
@Test( expected = NullArgumentException.class ) public void nonNullArguments7() { QualifiedName.fromClass( null, null ); } |
### Question:
Specifications { public static <T> Specification<T> TRUE() { return new Specification<T>() { public boolean satisfiedBy( T instance ) { return true; } }; } static Specification<T> TRUE(); static Specification<T> not( final Specification<T> specification ); static AndSpecification<T> and( final Specification<T>... specifications ); static AndSpecification<T> and( final Iterable<Specification<T>> specifications ); static OrSpecification<T> or( final Specification<T>... specifications ); static OrSpecification<T> or( final Iterable<Specification<T>> specifications ); static Specification<T> in( final T... allowed ); static Specification<T> in( final Iterable<T> allowed ); static Specification<T> notNull(); static Specification<FROM> translate( final Function<FROM,TO> function, final Specification<? super TO> specification); }### Answer:
@Test public void testTRUE() { Assert.assertThat( Specifications.<Object>TRUE().satisfiedBy( new Object() ), equalTo( true ) ); } |
### Question:
Specifications { public static <T> Specification<T> not( final Specification<T> specification ) { return new Specification<T>() { public boolean satisfiedBy( T instance ) { return !specification.satisfiedBy( instance ); } }; } static Specification<T> TRUE(); static Specification<T> not( final Specification<T> specification ); static AndSpecification<T> and( final Specification<T>... specifications ); static AndSpecification<T> and( final Iterable<Specification<T>> specifications ); static OrSpecification<T> or( final Specification<T>... specifications ); static OrSpecification<T> or( final Iterable<Specification<T>> specifications ); static Specification<T> in( final T... allowed ); static Specification<T> in( final Iterable<T> allowed ); static Specification<T> notNull(); static Specification<FROM> translate( final Function<FROM,TO> function, final Specification<? super TO> specification); }### Answer:
@Test public void testNot() { Assert.assertThat( Specifications.not( Specifications.<Object>TRUE() ) .satisfiedBy( new Object() ), equalTo( false ) ); } |
### Question:
Specifications { public static <T> AndSpecification<T> and( final Specification<T>... specifications ) { return and( Iterables.iterable( specifications )); } static Specification<T> TRUE(); static Specification<T> not( final Specification<T> specification ); static AndSpecification<T> and( final Specification<T>... specifications ); static AndSpecification<T> and( final Iterable<Specification<T>> specifications ); static OrSpecification<T> or( final Specification<T>... specifications ); static OrSpecification<T> or( final Iterable<Specification<T>> specifications ); static Specification<T> in( final T... allowed ); static Specification<T> in( final Iterable<T> allowed ); static Specification<T> notNull(); static Specification<FROM> translate( final Function<FROM,TO> function, final Specification<? super TO> specification); }### Answer:
@Test public void testAnd() { Specification<Object> trueSpec = Specifications.<Object>TRUE(); Specification<Object> falseSpec = Specifications.not( Specifications.<Object>TRUE() ); Assert.assertThat( Specifications.and( falseSpec, falseSpec ).satisfiedBy( new Object() ), equalTo( false ) ); Assert.assertThat( Specifications.and( trueSpec, falseSpec ).satisfiedBy( new Object() ), equalTo( false ) ); Assert.assertThat( Specifications.and( falseSpec, trueSpec ).satisfiedBy( new Object() ), equalTo( false ) ); Assert.assertThat( Specifications.and( trueSpec, trueSpec ).satisfiedBy( new Object() ), equalTo( true ) ); } |
### Question:
Specifications { public static <T> OrSpecification<T> or( final Specification<T>... specifications ) { return or( Iterables.iterable( specifications ) ); } static Specification<T> TRUE(); static Specification<T> not( final Specification<T> specification ); static AndSpecification<T> and( final Specification<T>... specifications ); static AndSpecification<T> and( final Iterable<Specification<T>> specifications ); static OrSpecification<T> or( final Specification<T>... specifications ); static OrSpecification<T> or( final Iterable<Specification<T>> specifications ); static Specification<T> in( final T... allowed ); static Specification<T> in( final Iterable<T> allowed ); static Specification<T> notNull(); static Specification<FROM> translate( final Function<FROM,TO> function, final Specification<? super TO> specification); }### Answer:
@Test public void testOr() { Specification<Object> trueSpec = Specifications.<Object>TRUE(); Specification<Object> falseSpec = Specifications.not( Specifications.<Object>TRUE() ); Assert.assertThat( Specifications.or( falseSpec, falseSpec ).satisfiedBy( new Object() ), equalTo( false ) ); Assert.assertThat( Specifications.or( trueSpec, falseSpec ).satisfiedBy( new Object() ), equalTo( true ) ); Assert.assertThat( Specifications.or( falseSpec, trueSpec ).satisfiedBy( new Object() ), equalTo( true ) ); Assert.assertThat( Specifications.or( trueSpec, trueSpec ).satisfiedBy( new Object() ), equalTo( true ) ); } |
### Question:
Specifications { public static <T> Specification<T> in( final T... allowed ) { return in( Iterables.iterable( allowed ) ); } static Specification<T> TRUE(); static Specification<T> not( final Specification<T> specification ); static AndSpecification<T> and( final Specification<T>... specifications ); static AndSpecification<T> and( final Iterable<Specification<T>> specifications ); static OrSpecification<T> or( final Specification<T>... specifications ); static OrSpecification<T> or( final Iterable<Specification<T>> specifications ); static Specification<T> in( final T... allowed ); static Specification<T> in( final Iterable<T> allowed ); static Specification<T> notNull(); static Specification<FROM> translate( final Function<FROM,TO> function, final Specification<? super TO> specification); }### Answer:
@Test public void testIn() { Assert.assertThat( Specifications.in( "1", "2", "3" ).satisfiedBy( "2" ), equalTo( true ) ); Assert.assertThat( Specifications.in( "1", "2", "3" ).satisfiedBy( "4" ), equalTo( false ) ); } |
### Question:
Specifications { public static <FROM,TO> Specification<FROM> translate( final Function<FROM,TO> function, final Specification<? super TO> specification) { return new Specification<FROM>() { @Override public boolean satisfiedBy( FROM item ) { return specification.satisfiedBy( function.map( item ) ); } }; } static Specification<T> TRUE(); static Specification<T> not( final Specification<T> specification ); static AndSpecification<T> and( final Specification<T>... specifications ); static AndSpecification<T> and( final Iterable<Specification<T>> specifications ); static OrSpecification<T> or( final Specification<T>... specifications ); static OrSpecification<T> or( final Iterable<Specification<T>> specifications ); static Specification<T> in( final T... allowed ); static Specification<T> in( final Iterable<T> allowed ); static Specification<T> notNull(); static Specification<FROM> translate( final Function<FROM,TO> function, final Specification<? super TO> specification); }### Answer:
@Test public void testTranslate() { Function<Object, String> stringifier = new Function<Object, String>() { @Override public String map( Object s ) { return s.toString(); } }; Assert.assertTrue( Specifications.translate( stringifier, Specifications.in( "3" ) ).satisfiedBy( 3L ) ); } |
### Question:
Functions { public static <A,B,C> Function2<Function<? super B,C>,Function<A,B>, Function<A,C>> compose() { return new Function2<Function<? super B, C>, Function<A, B>, Function<A, C>>() { @Override public Function<A, C> map( Function<? super B, C> bcFunction, Function<A, B> abFunction ) { return compose( bcFunction, abFunction ); } }; } static Function2<Function<? super B,C>,Function<A,B>, Function<A,C>> compose(); static Function<FROM,TO> compose( final Function<? super MIDDLE,TO> outer, final Function<FROM,MIDDLE> inner); static Function<FROM,TO> identity(); static Function<FROM,TO> fromMap( final Map<FROM,TO> map); static Function<T,T> withDefault( final T defaultValue); static final Function<Number, Long> longSum(); static Function<Number, Integer> intSum(); static Function<T, Integer> count( final Specification<T> specification); static Function<T, Integer> indexOf( final Specification<T> specification); static int indexOf(T item, Iterable<T> iterable); static Function<T, T> filteredMap( final Specification<T> specification, final Function<T, T> function); static Comparator<T> comparator( final Function<T, Comparable> comparableFunction); }### Answer:
@Test public void testCompose() { assertThat( Functions.<Object, String, Integer>compose().map( length, stringifier ).map( 12345L ), equalTo( 5 ) ); assertThat( compose( length, stringifier ).map( 12345L ), equalTo( 5 ) ); } |
### Question:
Functions { public static <FROM,TO> Function<FROM,TO> fromMap( final Map<FROM,TO> map) { return new Function<FROM,TO>() { @Override public TO map( FROM from ) { return map.get( from ); } }; } static Function2<Function<? super B,C>,Function<A,B>, Function<A,C>> compose(); static Function<FROM,TO> compose( final Function<? super MIDDLE,TO> outer, final Function<FROM,MIDDLE> inner); static Function<FROM,TO> identity(); static Function<FROM,TO> fromMap( final Map<FROM,TO> map); static Function<T,T> withDefault( final T defaultValue); static final Function<Number, Long> longSum(); static Function<Number, Integer> intSum(); static Function<T, Integer> count( final Specification<T> specification); static Function<T, Integer> indexOf( final Specification<T> specification); static int indexOf(T item, Iterable<T> iterable); static Function<T, T> filteredMap( final Specification<T> specification, final Function<T, T> function); static Comparator<T> comparator( final Function<T, Comparable> comparableFunction); }### Answer:
@Test public void testFromMap() { Map<String,String> map = new HashMap<String, String>( ); map.put( "A","1" ); map.put( "B","2" ); map.put( "C","3" ); assertThat( Iterables.toList( Iterables.filter( Specifications.notNull(), Iterables.map( Functions.fromMap( map ), Iterables.iterable( "A", "B", "D" ) ) ) ).toString(), equalTo( "[1, 2]" )); } |
### Question:
Functions { public static <T> Function<T,T> withDefault( final T defaultValue) { return new Function<T, T>() { @Override public T map( T from ) { if (from == null) return defaultValue; else return from; } }; } static Function2<Function<? super B,C>,Function<A,B>, Function<A,C>> compose(); static Function<FROM,TO> compose( final Function<? super MIDDLE,TO> outer, final Function<FROM,MIDDLE> inner); static Function<FROM,TO> identity(); static Function<FROM,TO> fromMap( final Map<FROM,TO> map); static Function<T,T> withDefault( final T defaultValue); static final Function<Number, Long> longSum(); static Function<Number, Integer> intSum(); static Function<T, Integer> count( final Specification<T> specification); static Function<T, Integer> indexOf( final Specification<T> specification); static int indexOf(T item, Iterable<T> iterable); static Function<T, T> filteredMap( final Specification<T> specification, final Function<T, T> function); static Comparator<T> comparator( final Function<T, Comparable> comparableFunction); }### Answer:
@Test public void testWithDefault() { assertThat( Iterables.toList( Iterables.map( Functions.withDefault( "DEFAULT" ), Iterables.iterable( "123", null, "456" ) ) ).toString(), equalTo( "[123, DEFAULT, 456]" ) ); } |
### Question:
Functions { public static final Function<Number, Long> longSum() { return new Function<Number, Long>() { long sum; @Override public Long map( Number number ) { sum += number.longValue(); return sum; } }; } static Function2<Function<? super B,C>,Function<A,B>, Function<A,C>> compose(); static Function<FROM,TO> compose( final Function<? super MIDDLE,TO> outer, final Function<FROM,MIDDLE> inner); static Function<FROM,TO> identity(); static Function<FROM,TO> fromMap( final Map<FROM,TO> map); static Function<T,T> withDefault( final T defaultValue); static final Function<Number, Long> longSum(); static Function<Number, Integer> intSum(); static Function<T, Integer> count( final Specification<T> specification); static Function<T, Integer> indexOf( final Specification<T> specification); static int indexOf(T item, Iterable<T> iterable); static Function<T, T> filteredMap( final Specification<T> specification, final Function<T, T> function); static Comparator<T> comparator( final Function<T, Comparable> comparableFunction); }### Answer:
@Test public void testLongSum() { assertThat( last( map( longSum(), iterable( 1, 2L, 3F, 4D ) ) ), equalTo( 10L ) ); } |
### Question:
Functions { public static Function<Number, Integer> intSum() { return new Function<Number, Integer>() { int sum; @Override public Integer map( Number number ) { sum += number.intValue(); return sum; } }; } static Function2<Function<? super B,C>,Function<A,B>, Function<A,C>> compose(); static Function<FROM,TO> compose( final Function<? super MIDDLE,TO> outer, final Function<FROM,MIDDLE> inner); static Function<FROM,TO> identity(); static Function<FROM,TO> fromMap( final Map<FROM,TO> map); static Function<T,T> withDefault( final T defaultValue); static final Function<Number, Long> longSum(); static Function<Number, Integer> intSum(); static Function<T, Integer> count( final Specification<T> specification); static Function<T, Integer> indexOf( final Specification<T> specification); static int indexOf(T item, Iterable<T> iterable); static Function<T, T> filteredMap( final Specification<T> specification, final Function<T, T> function); static Comparator<T> comparator( final Function<T, Comparable> comparableFunction); }### Answer:
@Test public void testIntSum() { assertThat( last( map( intSum(), iterable( 1, 2L, 3F, 4D ) ) ), equalTo( 10 ) ); } |
### Question:
Functions { public static <T> Function<T, Integer> count( final Specification<T> specification) { return new Function<T, Integer>() { int count; @Override public Integer map( T item ) { if (specification.satisfiedBy( item )) count++; return count; } }; } static Function2<Function<? super B,C>,Function<A,B>, Function<A,C>> compose(); static Function<FROM,TO> compose( final Function<? super MIDDLE,TO> outer, final Function<FROM,MIDDLE> inner); static Function<FROM,TO> identity(); static Function<FROM,TO> fromMap( final Map<FROM,TO> map); static Function<T,T> withDefault( final T defaultValue); static final Function<Number, Long> longSum(); static Function<Number, Integer> intSum(); static Function<T, Integer> count( final Specification<T> specification); static Function<T, Integer> indexOf( final Specification<T> specification); static int indexOf(T item, Iterable<T> iterable); static Function<T, T> filteredMap( final Specification<T> specification, final Function<T, T> function); static Comparator<T> comparator( final Function<T, Comparable> comparableFunction); }### Answer:
@Test public void testCount() { assertThat( last( map( count( in( "X" ) ), iterable( "X","Y","X","X","Y" ) ) ), equalTo( 3 ) ); } |
### Question:
Functions { public static <T> Function<T, Integer> indexOf( final Specification<T> specification) { return new Function<T, Integer>() { int index = -1; int current = 0; @Override public Integer map( T item ) { if (index == -1 && specification.satisfiedBy( item )) index = current; current++; return index; } }; } static Function2<Function<? super B,C>,Function<A,B>, Function<A,C>> compose(); static Function<FROM,TO> compose( final Function<? super MIDDLE,TO> outer, final Function<FROM,MIDDLE> inner); static Function<FROM,TO> identity(); static Function<FROM,TO> fromMap( final Map<FROM,TO> map); static Function<T,T> withDefault( final T defaultValue); static final Function<Number, Long> longSum(); static Function<Number, Integer> intSum(); static Function<T, Integer> count( final Specification<T> specification); static Function<T, Integer> indexOf( final Specification<T> specification); static int indexOf(T item, Iterable<T> iterable); static Function<T, T> filteredMap( final Specification<T> specification, final Function<T, T> function); static Comparator<T> comparator( final Function<T, Comparable> comparableFunction); }### Answer:
@Test public void testIndexOf() { assertThat( last( map( indexOf( in( "D" ) ), iterable( "A","B","C","D","D" ) ) ), equalTo( 3 ) ); }
@Test public void testIndexOf2() { assertThat( indexOf( "D", iterable( "A","B","C","D","D" )), equalTo( 3 ) ); } |
### Question:
IterableQuerySource implements QuerySource { @Override public <T> Iterator<T> iterator( Class<T> resultType, Specification<Composite> whereClause, Iterable<OrderBy> orderBySegments, Integer firstResult, Integer maxResults, Map<String, Object> variables ) { return list(resultType, whereClause, orderBySegments, firstResult, maxResults, variables).iterator(); } IterableQuerySource( final Iterable iterable ); @Override T find( Class<T> resultType, Specification<Composite> whereClause, Iterable<OrderBy> orderBySegments, Integer firstResult, Integer maxResults, Map<String, Object> variables ); @Override long count( Class<T> resultType, Specification<Composite> whereClause, Iterable<OrderBy> orderBySegments, Integer firstResult, Integer maxResults, Map<String, Object> variables ); @Override Iterator<T> iterator( Class<T> resultType, Specification<Composite> whereClause, Iterable<OrderBy> orderBySegments, Integer firstResult, Integer maxResults, Map<String, Object> variables ); }### Answer:
@Test public void givenManyAssociationContainsQueryWhenExecutedThenReturnCorrect() throws EntityFinderException { QueryBuilder<Person> qb = qbf.newQueryBuilder( Person.class ); Person person = templateFor( Person.class ); Domain value = Network.domains().iterator().next(); Query<Person> query = qb.where( QueryExpressions.contains( person.interests(), value ) ) .newQuery( Network.persons() ); for (Person person1 : query) { System.out.println( person1.name() ); } verifyOrderedResults( query, "Joe Doe", "Vivian Smith" ); } |
### Question:
UsageGraph { public List<K> resolveOrder() throws BindingException { if( resolved == null ) { buildUsageGraph(); resolved = new LinkedList<K>(); for( K item : data ) { int pos = resolved.size(); for( K entry : resolved ) { if( transitiveUse( entry, item ) ) { pos = resolved.indexOf( entry ); break; } } resolved.add( pos, item ); } } return resolved; } UsageGraph( Collection<K> data, Use<K> use, boolean allowCyclic ); boolean transitiveUse( K source, K other ); void invalidate(); List<K> resolveOrder(); }### Answer:
@Test public void whenAskingForDependencyGivenThatGraphContainsCyclicDepThenDetectTheError() throws Exception { Thing thing1 = new Thing(); Thing thing2 = new Thing(); Thing thing3 = new Thing(); Thing thing4 = new Thing(); Thing thing5 = new Thing(); Thing thing6 = new Thing(); Thing thing7 = new Thing(); thing1.uses.add( thing3 ); thing2.uses.add( thing3 ); thing3.uses.add( thing4 ); thing4.uses.add( thing5 ); thing5.uses.add( thing1 ); thing1.uses.add( thing6 ); thing7.uses.add( thing1 ); thing7.uses.add( thing2 ); thing7.uses.add( thing4 ); List<Thing> data = new ArrayList<Thing>(); data.add( thing7 ); data.add( thing4 ); data.add( thing1 ); data.add( thing3 ); data.add( thing6 ); data.add( thing5 ); data.add( thing2 ); randomize( data ); UsageGraph<Thing> deps = new UsageGraph<Thing>( data, new Userator(), false ); try { List<Thing> resolved = deps.resolveOrder(); Assert.fail( "Cyclic Dependency Not Detected." ); } catch( BindingException e ) { } } |
### Question:
GroovyMixin implements InvocationHandler { public Object invoke( Object proxy, Method method, Object[] args ) throws Throwable { final FunctionResource groovySource = getFunctionResource( method ); if( groovySource != null ) { if( groovySource.script ) { return invokeAsObject( method, args, groovySource.url ); } return invokeAsScript( method, args, groovySource.url ); } throw new RuntimeException( "Internal error: Mixin invoked even if it does not apply" ); } GroovyMixin(); Object invoke( Object proxy, Method method, Object[] args ); }### Answer:
@Test public void testInvoke() { GroovyComposite domain1 = module.newTransient( GroovyComposite.class ); GroovyComposite domain2 = module.newTransient( GroovyComposite.class ); Assert.assertEquals( "do1() in Groovy:1", domain1.do1() ); Assert.assertEquals( "do1() in Groovy:2", domain1.do1() ); Assert.assertEquals( "do1() in Groovy:3", domain1.do1() ); Assert.assertEquals( "do1() in Groovy:4", domain1.do1() ); Assert.assertEquals( "do1() in Groovy:1", domain2.do1() ); Assert.assertEquals( "do1() in Groovy:2", domain2.do1() ); Assert.assertEquals( "do1() in Groovy:3", domain2.do1() ); Assert.assertEquals( "do1() in Groovy:4", domain2.do1() ); Assert.assertEquals( "do1() in Groovy:5", domain2.do1() ); Assert.assertEquals( "do1() in Groovy:6", domain2.do1() ); Assert.assertEquals( "do1() in Groovy:5", domain1.do1() ); } |
### Question:
JavaScriptMixin implements InvocationHandler, ScriptReloadable { public Object invoke( Object proxy, Method method, Object[] args ) throws Throwable { Context cx = Context.enter(); try { Scriptable proxyScope = Context.toObject( proxy, instanceScope ); proxyScope.setPrototype( instanceScope ); proxyScope.put( "compositeBuilderFactory", proxyScope, factory ); proxyScope.put( "This", proxyScope, me ); Function fn = getFunction( cx, proxyScope, method ); Object result = fn.call( cx, instanceScope, proxyScope, args ); if( result instanceof Undefined ) { return null; } else if( result instanceof Wrapper ) { return ( (Wrapper) result ).unwrap(); } else { return result; } } finally { Context.exit(); } } JavaScriptMixin(); Object invoke( Object proxy, Method method, Object[] args ); void reloadScripts(); }### Answer:
@Test public void testInvoke() throws Throwable { JavaScriptComposite domain = module.newTransient( JavaScriptComposite.class ); Assert.assertEquals( "do1 script \" and ' for many cases is harder.", domain.do1() ); } |
### Question:
EventRouter implements Output<DomainEventValue, T>, Receiver<UnitOfWorkDomainEventsValue, T> { public EventRouter route( Specification<DomainEventValue> specification, Receiver<DomainEventValue, T> receiver ) { routeEvent.put( specification, receiver ); return this; } EventRouter route( Specification<DomainEventValue> specification, Receiver<DomainEventValue, T> receiver ); EventRouter defaultReceiver( Receiver<DomainEventValue, T> defaultReceiver ); @Override void receiveFrom( Sender<? extends DomainEventValue, SenderThrowableType> sender ); @Override void receive( final UnitOfWorkDomainEventsValue item ); }### Answer:
@Test public void testRouter() throws IOException { final List<DomainEventValue> matched = new ArrayList<DomainEventValue>( ); EventRouter<IOException> router = new EventRouter<IOException>(); router.route( Events.withNames( "Test1", "Test2" ), new Receiver<DomainEventValue,IOException>() { @Override public void receive( DomainEventValue item ) throws IOException { matched.add(item); } }); Inputs.iterable( Events.events( list ) ).transferTo( router ); Assert.assertThat(matched.toString(), CoreMatchers.equalTo( "[{\"name\":\"Test1\",\"entityType\":\"Foo\",\"entityId\":\"123\",\"parameters\":\"{}\"}, {\"name\":\"Test2\",\"entityType\":\"Foo\",\"entityId\":\"123\",\"parameters\":\"{}\"}]" )); } |
### Question:
Events { public static Iterable<DomainEventValue> events( Iterable<UnitOfWorkDomainEventsValue> transactions ) { return Iterables.flattenIterables( Iterables.map( new Function<UnitOfWorkDomainEventsValue, Iterable<DomainEventValue>>() { @Override public Iterable<DomainEventValue> map( UnitOfWorkDomainEventsValue unitOfWorkDomainEventsValue ) { return unitOfWorkDomainEventsValue.events().get(); } }, transactions ) ); } static Iterable<DomainEventValue> events( Iterable<UnitOfWorkDomainEventsValue> transactions ); static Iterable<DomainEventValue> events( UnitOfWorkDomainEventsValue... unitOfWorkDomainValues ); static Specification<UnitOfWorkDomainEventsValue> afterDate( final Date afterDate ); static Specification<UnitOfWorkDomainEventsValue> beforeDate( final Date afterDate ); static Specification<UnitOfWorkDomainEventsValue> withUsecases( final String... names ); static Specification<UnitOfWorkDomainEventsValue> byUser( final String... by ); static Specification<DomainEventValue> withNames( final Iterable<String> names ); static Specification<DomainEventValue> withNames( final String... names ); static Specification<DomainEventValue> withNames( final Class eventClass ); static Specification<DomainEventValue> onEntities( final String... entities ); static Specification<DomainEventValue> onEntityTypes( final String... entityTypes ); static Specification<DomainEventValue> paramIs( final String name, final String value ); }### Answer:
@Test public void testIterablesEvents() { assertThat( count( events( list ) ), equalTo( 6L ) ); iterable( events( list ) ).transferTo( systemOut() ); } |
### Question:
EntityTypeSerializer { public EntityTypeSerializer() { dataTypes.put( String.class.getName(), XMLSchema.STRING ); dataTypes.put( Integer.class.getName(), XMLSchema.INT ); dataTypes.put( Boolean.class.getName(), XMLSchema.BOOLEAN ); dataTypes.put( Byte.class.getName(), XMLSchema.BYTE ); dataTypes.put( BigDecimal.class.getName(), XMLSchema.DECIMAL ); dataTypes.put( Double.class.getName(), XMLSchema.DOUBLE ); dataTypes.put( Long.class.getName(), XMLSchema.LONG ); dataTypes.put( Short.class.getName(), XMLSchema.SHORT ); dataTypes.put( Date.class.getName(), XMLSchema.DATETIME ); } EntityTypeSerializer(); Iterable<Statement> serialize( final EntityDescriptor entityDescriptor ); }### Answer:
@Test public void testEntityTypeSerializer() throws RDFHandlerException { EntityDescriptor entityDescriptor = module.entityDescriptor(TestEntity.class.getName()); Iterable<Statement> graph = serializer.serialize( entityDescriptor ); String[] prefixes = new String[]{ "rdf", "dc", " vc", "qi4j" }; String[] namespaces = new String[]{ Rdfs.RDF, DcRdf.NAMESPACE, "http: new RdfXmlSerializer().serialize( graph, new PrintWriter( System.out ), prefixes, namespaces ); } |
### Question:
ParameterizedTypes { public static <S, T extends S> ParameterizedType findParameterizedType( Class<T> type, Class<S> searchType ) { return ParameterizedTypes.findParameterizedType( (Type) type, searchType ); } private ParameterizedTypes(); static Type[] findTypeVariables( Class<T> type, Class<S> searchType ); static ParameterizedType findParameterizedType( Class<T> type, Class<S> searchType ); }### Answer:
@Test public void findParameterizedType() { assertEquals( GarbageMan.class.getGenericInterfaces()[ 0 ], ParameterizedTypes.findParameterizedType( GarbageMan.class, HandlerOf.class ) ); } |
### Question:
ParameterizedTypes { public static <S, T extends S> Type[] findTypeVariables( Class<T> type, Class<S> searchType ) { return ParameterizedTypes.findParameterizedType( type, searchType ).getActualTypeArguments(); } private ParameterizedTypes(); static Type[] findTypeVariables( Class<T> type, Class<S> searchType ); static ParameterizedType findParameterizedType( Class<T> type, Class<S> searchType ); }### Answer:
@Test public void findTypeVariables() { assertArrayEquals( ((ParameterizedType) GarbageMan.class.getGenericInterfaces()[0]).getActualTypeArguments(), ParameterizedTypes.findTypeVariables( GarbageMan.class, HandlerOf.class ) ); } |
### Question:
DBInitializer implements Serializable { public final void initialize( String schemaUrl, String dataUrl, String dbUrl, Properties connectionProperties ) throws SQLException, IOException { Connection connection1 = getSqlConnection( dbUrl, connectionProperties ); runScript( schemaUrl, connection1 ); Connection connection2 = getSqlConnection( dbUrl, connectionProperties ); runScript( dataUrl, connection2 ); } final void initialize( String schemaUrl, String dataUrl, String dbUrl, Properties connectionProperties ); }### Answer:
@Test @Ignore( "The entire QRM is buggered." ) public void testInitializer() throws Exception { final DBInitializerConfiguration info = derbyDatabaseHandler.createDbInitializerConfigMock(); final DBInitializer initializer = new DBInitializer(); Properties connectionProperties = info.connectionProperties().get(); String schemaUrl = info.schemaUrl().get(); String dataUrl = info.dataUrl().get(); String dbUrl = info.dbUrl().get(); initializer.initialize( schemaUrl, dataUrl, dbUrl, connectionProperties ); derbyDatabaseHandler.checkDataInitialization(); } |
### Question:
CapitalizingIdentifierConverter implements IdentifierConverter { public String convertIdentifier( final QualifiedName qualifiedIdentifier ) { final String name = qualifiedIdentifier.name(); if( name.equalsIgnoreCase( "identity" ) ) { return "ID"; } return name.toUpperCase(); } String convertIdentifier( final QualifiedName qualifiedIdentifier ); Object getValueFromData( final Map<String, Object> rawData, final QualifiedName qualifiedName ); Map<String, Object> convertKeys( Map<QualifiedName, Object> rawData ); }### Answer:
@Test public void convertToUpperCase() { assertEquals( "identity -> ID", "ID", converter.convertIdentifier( QualifiedName.fromQN( "abc:identity" ) ) ); assertEquals( "uppercase ABC", "ABC", converter.convertIdentifier( QualifiedName.fromQN( "abc:abc" ) ) ); assertEquals( "removed qualified prefix", "ABC", converter.convertIdentifier( QualifiedName.fromQN( "aaa:abc" ) ) ); assertEquals( "removed qualified prefixes", "ABC", converter.convertIdentifier( QualifiedName.fromQN( "aaa:bbb:abc" ) ) ); } |
### Question:
CapitalizingIdentifierConverter implements IdentifierConverter { public Object getValueFromData( final Map<String, Object> rawData, final QualifiedName qualifiedName ) { String convertedIdentifier = convertIdentifier( qualifiedName ); if( rawData.containsKey( convertedIdentifier ) ) { return rawData.remove( convertedIdentifier ); } return null; } String convertIdentifier( final QualifiedName qualifiedIdentifier ); Object getValueFromData( final Map<String, Object> rawData, final QualifiedName qualifiedName ); Map<String, Object> convertKeys( Map<QualifiedName, Object> rawData ); }### Answer:
@Test public void removeFromMap() { Map<String, Object> rawData = new HashMap<String, Object>(); rawData.put( "ABC", "test" ); assertEquals( "converted key and found value", "test", converter.getValueFromData( rawData, QualifiedName.fromQN( "aaa:abc" ) ) ); assertEquals( "entry removed", 0, rawData.size() ); }
@Test public void nullIfNotFound() { Map<String, Object> rawData = new HashMap<String, Object>(); assertEquals( "converted key and found value", null, converter.getValueFromData( rawData, QualifiedName.fromQN( "aaa:abc" ) ) ); } |
### Question:
OpenSDSInfo extends BaseArrayInfo { public OpenSDSInfo() { super(); } OpenSDSInfo(); OpenSDSInfo(String id, String hostName, String port); @Override boolean equals(Object obj); @Override int hashCode(); String getProductSN(); void setProductSN(String productSN); boolean getauthEnabled(); void setauthEnabled(boolean authEnabled); void clearAll(); @Override String getURL(); @Override String toString(); }### Answer:
@Test void testOpenSDSInfo() { OpenSDSInfo OpenSDSInfo = new OpenSDSInfo("testId", "testHostName", "testPort"); OpenSDSInfo.hashCode(); OpenSDSInfo.getHostName(); OpenSDSInfo.getURL(); OpenSDSInfo.getProductSN(); OpenSDSInfo.toString(); } |
### Question:
OpenSDSInfo extends BaseArrayInfo { @Override public boolean equals(Object obj) { if (obj instanceof OpenSDSInfo) { OpenSDSInfo openSDSInfo = (OpenSDSInfo) obj; if (openSDSInfo.getId().equals(getId())) { return true; } } return false; } OpenSDSInfo(); OpenSDSInfo(String id, String hostName, String port); @Override boolean equals(Object obj); @Override int hashCode(); String getProductSN(); void setProductSN(String productSN); boolean getauthEnabled(); void setauthEnabled(boolean authEnabled); void clearAll(); @Override String getURL(); @Override String toString(); }### Answer:
@Test void testEqualsObject() { OpenSDSInfo OpenSDSInfo = new OpenSDSInfo("testId", "testHostName", "testPort"); OpenSDSInfo obj = new OpenSDSInfo("testId", "testHostName", "testPort"); OpenSDSInfo.equals(obj); }
@Test void testNotEqualsObject() { OpenSDSInfo OpenSDSInfo = new OpenSDSInfo(); OpenSDSInfo obj = new OpenSDSInfo("testId", "testHostName", "testPort"); OpenSDSInfo.equals(obj); } |
### Question:
VolumeService { public void createVolume(OpenSDSInfo openSDSInfo, String name, String description, long capacity, String profile) throws Exception { OpenSDS opensds = new OpenSDS(); opensds.login(openSDSInfo); log.info("Logged in to OpenSDS"); VolumeMO volume = opensds.createVolume(name, description, capacity, profile); log.info("Volume " + volume.id + "is created"); } void createVolume(OpenSDSInfo openSDSInfo, String name, String description, long capacity, String profile); void deleteVolume(OpenSDSInfo openSDSInfo, String id); String createAndAttachVolume(OpenSDSInfo openSDSInfo, String name, String description, long capacity,
String profile, String hostIP, String iqn); void expandVolume(OpenSDSInfo openSDSInfo, String id, long capacity); }### Answer:
@Test void testCreateVolume() throws Exception { readDefaultConfig(); VolumeService volumeService = new VolumeService(); volumeService.createVolume(arrayInfo, "test_script_vol", "test_script_vol", 1, profileId); } |
### Question:
VolumeService { public String createAndAttachVolume(OpenSDSInfo openSDSInfo, String name, String description, long capacity, String profile, String hostIP, String iqn) throws Exception { OpenSDS opensds = new OpenSDS(); opensds.login(openSDSInfo); VolumeMO volume = opensds.createVolume(name, description, capacity, profile); TimeUnit.SECONDS.sleep(10); ConnectMO connect = new ConnectMO(hostIP, HOST_OS_TYPE.ESXI, iqn, hostIP, null, ATTACH_MODE.RW, ATTACH_PROTOCOL.ISCSI); opensds.attachVolume(volume.id, connect); String volume_wwn = opensds.getVolumeWWN(volume.id); return volume_wwn; } void createVolume(OpenSDSInfo openSDSInfo, String name, String description, long capacity, String profile); void deleteVolume(OpenSDSInfo openSDSInfo, String id); String createAndAttachVolume(OpenSDSInfo openSDSInfo, String name, String description, long capacity,
String profile, String hostIP, String iqn); void expandVolume(OpenSDSInfo openSDSInfo, String id, long capacity); }### Answer:
@Test void testcreateAndAttachVolume() throws Exception { VolumeService volumeService = new VolumeService(); readDefaultConfig(); volumeService.createAndAttachVolume(arrayInfo, "attach_vol", "attach volume test", 1, profileId, esxIP, esxIQN); } |
### Question:
VolumeService { public void deleteVolume(OpenSDSInfo openSDSInfo, String id) throws Exception { OpenSDS opensds = new OpenSDS(); opensds.login(openSDSInfo); log.info("Logged in to OpenSDS"); opensds.deleteVolume(id); log.info("Volume " + id + "is deleted"); } void createVolume(OpenSDSInfo openSDSInfo, String name, String description, long capacity, String profile); void deleteVolume(OpenSDSInfo openSDSInfo, String id); String createAndAttachVolume(OpenSDSInfo openSDSInfo, String name, String description, long capacity,
String profile, String hostIP, String iqn); void expandVolume(OpenSDSInfo openSDSInfo, String id, long capacity); }### Answer:
@Test void testDeleteVolume() throws Exception { VolumeService volumeService = new VolumeService(); readDefaultConfig(); volumeService.deleteVolume(arrayInfo, volId); } |
### Question:
VolumeService { public void expandVolume(OpenSDSInfo openSDSInfo, String id, long capacity) throws Exception { OpenSDS opensds = new OpenSDS(); opensds.login(openSDSInfo); log.info("Logged in to OpenSDS"); opensds.expandVolume(id, capacity); } void createVolume(OpenSDSInfo openSDSInfo, String name, String description, long capacity, String profile); void deleteVolume(OpenSDSInfo openSDSInfo, String id); String createAndAttachVolume(OpenSDSInfo openSDSInfo, String name, String description, long capacity,
String profile, String hostIP, String iqn); void expandVolume(OpenSDSInfo openSDSInfo, String id, long capacity); }### Answer:
@Test void testexpandVolume() throws Exception { VolumeService volumeService = new VolumeService(); readDefaultConfig(); volumeService.expandVolume(arrayInfo, volId, 2); } |
### Question:
Configuration { public void register(String arrayName, String hostname, String port, String username, String password, boolean authEnabled, String productModel) throws Exception { String uniqId = hostname + "-" + port; OpenSDSInfo arrayInfo = new OpenSDSInfo(uniqId, hostname, port); arrayInfo.setArrayName(arrayName); arrayInfo.setHostName(hostname); arrayInfo.setPort(port); arrayInfo.setUsername(username); arrayInfo.setPassword(password); arrayInfo.setauthEnabled(authEnabled); arrayInfo.setProductModel(productModel); if (LOG.isInfoEnabled()) { LOG.info("register:::" + arrayInfo); } OpenSDS opensds = new OpenSDS(); opensds.login(arrayInfo); StorageMO storage = opensds.getDeviceInfo(); arrayInfo.setProductName(storage.name); arrayInfo.setProductVersion("V1"); arrayInfo.setProductSN(storage.sn); OpenSDSStorageRepository.getUniqueInstance().updateProperties(arrayInfo, OpenSDSStorageRepository.ADD); } Configuration(String id, String name); String getId(); void setId(String id); String getName(); void setName(String name); String test(); void register(String arrayName, String hostname, String port, String username, String password,
boolean authEnabled, String productModel); void unregister(OpenSDSInfo opensdsInfo); void debugOn(); void debugOff(); List<OpenSDSInfo> getOpenSDSInfos(); }### Answer:
@Test void testRegister() throws Exception { Configuration conf = new Configuration("testID", "opensds"); conf.register("OpenSDS_Test", "127.0.0.1", "50040", "admin", "opensds@123", true, "V1"); } |
### Question:
MyWidget extends Composite { public void setName(String firstName, String lastName) { name.setText(firstName + " " + lastName); } MyWidget(); void setName(String firstName, String lastName); void updateData(); void loadDataFromRpc(); }### Answer:
@Test public void testSetName() { widget.setName("John", "Smith"); verify(widget.name).setText("John Smith"); }
@Test public void testSetNameWithFakes() { GwtMockito.useProviderForType(HasText.class, new FakeProvider<HasText>() { @Override public HasText getFake(Class<?> type) { return new HasText() { private String text; @Override public void setText(String text) { this.text = text; } @Override public String getText() { return text; } }; } }); widget = new MyWidget(); widget.setName("John", "Smith"); assertEquals("John Smith", widget.name.getText()); } |
### Question:
GwtMockito { public static <T> T getFake(Class<T> type) { T fake = getFakeFromProviderMap( type, bridge != null ? bridge.registeredProviders : DEFAULT_FAKE_PROVIDERS); if (fake == null) { throw new IllegalArgumentException("No fake provider has been registered " + "for " + type.getSimpleName() + ". Call useProviderForType to " + "register a provider before calling getFake."); } return fake; } static void initMocks(Object owner); static void tearDown(); static void useProviderForType(Class<?> type, FakeProvider<?> provider); static T getFake(Class<T> type); }### Answer:
@Test public void getFakeShouldReturnDefaultFakes() { SampleMessages messages = GwtMockito.getFake(SampleMessages.class); assertEquals("noArgs", messages.noArgs()); }
@Test public void getFakeShouldFailForUnregisteredFakes() { try { GwtMockito.getFake(SampleInterface.class); fail("Exception not thrown"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains("SampleInterface")); } } |
### Question:
MyWidget extends Composite { public void updateData() { data.setText(dataProvider.getData()); } MyWidget(); void setName(String firstName, String lastName); void updateData(); void loadDataFromRpc(); }### Answer:
@Test public void testUpdateData() { when(dataProvider.getData()).thenReturn("data"); widget.updateData(); verify(widget.data).setText("data"); } |
### Question:
MyWidget extends Composite { public void loadDataFromRpc() { MyServiceAsync service = GWT.create(MyService.class); service.getData(new AsyncCallback<String>() { @Override public void onSuccess(String result) { data.setText(result); } @Override public void onFailure(Throwable caught) {} }); } MyWidget(); void setName(String firstName, String lastName); void updateData(); void loadDataFromRpc(); }### Answer:
@Test @SuppressWarnings("unchecked") public void testMockRpcs() { doAnswer(returnSuccess("some data")).when(myService).getData(any(AsyncCallback.class)); widget.loadDataFromRpc(); verify(widget.data).setText("some data"); } |
### Question:
GwtMockito { public static void initMocks(Object owner) { bridge = new Bridge(); for (Entry<Class<?>, FakeProvider<?>> entry : DEFAULT_FAKE_PROVIDERS.entrySet()) { useProviderForType(entry.getKey(), entry.getValue()); } boolean success = false; try { setGwtBridge(bridge); registerGwtMocks(owner); MockitoAnnotations.initMocks(owner); success = true; } finally { if (!success) { tearDown(); } } } static void initMocks(Object owner); static void tearDown(); static void useProviderForType(Class<?> type, FakeProvider<?> provider); static T getFake(Class<T> type); }### Answer:
@Test(expected = IllegalArgumentException.class) public void shouldNotAllowMultipleGwtMocksForSameType() { GwtMockito.initMocks(new Object() { @GwtMock SampleInterface mock1; @GwtMock SampleInterface mock2; }); } |
### Question:
InstanceRegistry extends PeerAwareInstanceRegistryImpl implements ApplicationContextAware { @Override protected boolean internalCancel(String appName, String id, boolean isReplication) { handleCancelation(appName, id, isReplication); return super.internalCancel(appName, id, isReplication); } InstanceRegistry(EurekaServerConfig serverConfig,
EurekaClientConfig clientConfig, ServerCodecs serverCodecs,
EurekaClient eurekaClient, int expectedNumberOfRenewsPerMin,
int defaultOpenForTrafficCount); @Override void setApplicationContext(ApplicationContext context); @Override void openForTraffic(ApplicationInfoManager applicationInfoManager, int count); @Override void register(InstanceInfo info, int leaseDuration, boolean isReplication); @Override void register(final InstanceInfo info, final boolean isReplication); @Override boolean cancel(String appName, String serverId, boolean isReplication); @Override boolean renew(final String appName, final String serverId,
boolean isReplication); }### Answer:
@Test public void testInternalCancel() throws Exception { instanceRegistry.internalCancel(APP_NAME, HOST_NAME, false); assertEquals(1, this.testEvents.applicationEvents.size()); assertTrue(this.testEvents.applicationEvents.get(0) instanceof EurekaInstanceCanceledEvent); final EurekaInstanceCanceledEvent registeredEvent = (EurekaInstanceCanceledEvent) (this.testEvents.applicationEvents.get(0)); assertEquals(APP_NAME, registeredEvent.getAppName()); assertEquals(HOST_NAME, registeredEvent.getServerId()); assertEquals(instanceRegistry, registeredEvent.getSource()); assertFalse(registeredEvent.isReplication()); } |
### Question:
EurekaController { @RequestMapping(method = RequestMethod.GET) public String status(HttpServletRequest request, Map<String, Object> model) { populateBase(request, model); populateApps(model); StatusInfo statusInfo; try { statusInfo = new StatusResource().getStatusInfo(); } catch (Exception e) { statusInfo = StatusInfo.Builder.newBuilder().isHealthy(false).build(); } model.put("statusInfo", statusInfo); populateInstanceInfo(model, statusInfo); filterReplicas(model, statusInfo); return "eureka/status"; } EurekaController(ApplicationInfoManager applicationInfoManager); @RequestMapping(method = RequestMethod.GET) String status(HttpServletRequest request, Map<String, Object> model); @RequestMapping(value = "/lastn", method = RequestMethod.GET) String lastn(HttpServletRequest request, Map<String, Object> model); }### Answer:
@Test public void testStatus() throws Exception { Map<String, Object> model = new HashMap<>(); EurekaController controller = new EurekaController(infoManager); controller.status(new MockHttpServletRequest("GET", "/"), model); Map<String, Object> app = getFirst(model, "apps"); Map<String, Object> instanceInfo = getFirst(app, "instanceInfos"); Map<String, Object> instance = getFirst(instanceInfo, "instances"); assertThat("id was wrong", (String)instance.get("id"), is(equalTo("myapp:1"))); assertThat("url was not null", instance.get("url"), is(nullValue())); assertThat("isHref was wrong", (Boolean)instance.get("isHref"), is(false)); } |
### Question:
HttpClient { public Response get(String host, String endpoint) throws IOException { return performRequest("GET", host, endpoint, Collections.emptyMap(), null); } private HttpClient(); Response get(String host, String endpoint); Response post(String host, String endpoint, JSONObject entity); Response put(String host, String endpoint, JSONObject entity); Response delete(String host, String endpoint); Response head(String host, String endpoint); Response performRequest(String method, String host, String endpoint, Map<String, String> params, JSONObject entity); static HttpClient getInstance(); }### Answer:
@Test public void get() throws Exception { Response response = HttpClient.getInstance().get("http: System.out.println(response); } |
### Question:
ClassUtils { public static Set<Class<?>> getAnnotatedClasses(String packageName, Class<? extends Annotation> annotation) { Reflections reflections = new Reflections(packageName); Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(annotation); return annotated; } static Set<Class<?>> getAnnotatedClasses(String packageName, Class<? extends Annotation> annotation); }### Answer:
@Test public void getAnnotatedClasses() { ClassUtils.getAnnotatedClasses("com.timeyang.search.entity", Document.class).forEach(System.out::println); } |
### Question:
JsonUtils { public static String convertToString(JSONObject jsonObject) { try { return mapper.writeValueAsString(jsonObject); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } static String convertToString(JSONObject jsonObject); static byte[] convertToBytes(JSONObject jsonObject); static JSONObject readValue(InputStream inputStream); static T parseJsonToObject(String json, Class<T> clazz); }### Answer:
@Test public void convertToString() throws Exception { JSONObject jsonObject = new JSONObject(); jsonObject.put("settings", new JSONObject().put("index", new JSONObject().put("number_of_shards", 3) .put("number_of_replicas", 2) ) ); String settings = JsonUtils.convertToString(jsonObject); System.out.println(settings); } |
### Question:
KafkaConnectClient { public void deleteConnector(String connectorName) { if(!checkConnectorExists(connectorName)) throw new IllegalArgumentException("The specified connector[" + connectorName + "] doesn't exist"); String endpoint = "connectors/" + connectorName; try { String url = getRandomUrl(); locks.putIfAbsent(connectorName, new ReentrantLock()); try { locks.get(connectorName).lock(); HTTP_CLIENT.delete(url, endpoint); }finally { locks.get(connectorName).unlock(); } } catch (IOException e) { throw new KafkaConnectRequestException(e); } } @Inject KafkaConnectClient(JkesProperties jkesProperties, Metadata metadata); @PostConstruct void init(); JSONObject getConnectConfig(String connectorName); boolean createIndexSinkConnectorIfAbsent(Class<?> document); void updateIndexSinkConnector(Class<?> document); boolean createDeleteSinkConnectorIfAbsent(); boolean ensureEsSinkConnector(Class<?> document); void deleteConnector(String connectorName); void restartConnector(String connectorName); boolean checkConnectorExists(String connectorName); }### Answer:
@Test public void deleteConnector() throws Exception { JkesProperties jkesProperties = new DefaultJkesPropertiesImpl() { @Override public String getKafkaConnectServers() { return "http: } }; Config.setJkesProperties(jkesProperties); String connectorName = KafkaConnectUtils.getConnectorName(Person.class); new KafkaConnectClient(jkesProperties, new Metadata.MetadataBuilder(jkesProperties).build()).deleteConnector(connectorName); } |
### Question:
KafkaConnectClient { public boolean checkConnectorExists(String connectorName) { String endpoint = "connectors/" + connectorName; try { String url = getRandomUrl(); Response response; locks.putIfAbsent(connectorName, new ReentrantLock()); try { locks.get(connectorName).lock(); response = HTTP_CLIENT.get(url, endpoint); }finally { locks.get(connectorName).unlock(); } boolean contain = (response.getStatusCode() / 100) == 2; return contain; } catch (IOException e) { throw new KafkaConnectRequestException(e); } } @Inject KafkaConnectClient(JkesProperties jkesProperties, Metadata metadata); @PostConstruct void init(); JSONObject getConnectConfig(String connectorName); boolean createIndexSinkConnectorIfAbsent(Class<?> document); void updateIndexSinkConnector(Class<?> document); boolean createDeleteSinkConnectorIfAbsent(); boolean ensureEsSinkConnector(Class<?> document); void deleteConnector(String connectorName); void restartConnector(String connectorName); boolean checkConnectorExists(String connectorName); }### Answer:
@Test public void checkConnectorExists() throws Exception { JkesProperties jkesProperties = new DefaultJkesPropertiesImpl() { @Override public String getKafkaConnectServers() { return "http: } }; Config.setJkesProperties(jkesProperties); String connectorName = KafkaConnectUtils.getConnectorName(Person.class); System.out.println(new KafkaConnectClient(jkesProperties, new Metadata.MetadataBuilder(jkesProperties).build()).checkConnectorExists(connectorName)); } |
### Question:
IndicesBuilder { public JSONObject buildIndex(Class<?> clazz) { Asserts.check(clazz.isAnnotationPresent(Document.class), "The class " + clazz.getCanonicalName() + " must be annotated with " + Document.class.getCanonicalName()); JSONObject settings = new JSONObject(); settings.put("index.mapper.dynamic", false); settings.put("number_of_shards", 11); settings.put("number_of_replicas", 2); JSONObject mappings = new JSONObject(); JSONObject mapping = new MappingBuilder().buildMapping(clazz); String type = DocumentUtils.getTypeName(clazz); mappings.put(type, mapping); JSONObject aliases = new JSONObject(); aliases.put(DocumentUtils.getAlias(clazz), new JSONObject()); JSONObject indices = new JSONObject(); indices.put("settings", settings); indices.put("mappings", mappings); indices.put("aliases", aliases); return indices; } private IndicesBuilder(); JSONObject buildIndex(Class<?> clazz); static IndicesBuilder getInstance(); }### Answer:
@Test public void buildIndex() throws Exception { IndicesBuilder indicesBuilder = IndicesBuilder.getInstance(); JSONObject indices = indicesBuilder.buildIndex(PersonGroup.class); System.out.println(JsonUtils.convertToString(indices)); } |
### Question:
IndicesAdminClient { @PostConstruct public void init() { logger.info("search init begin"); Set<Class<?>> annotatedClasses = metadata.getAnnotatedDocuments(); check(annotatedClasses); for(Class clazz : annotatedClasses) { if(checkExists(DocumentUtils.getIndexName(clazz))) { updateIndex(clazz); }else { createIndex(clazz); } } logger.info("search init finished"); } @Inject IndicesAdminClient(EsRestClient esRestClient, JkesProperties jkesProperties, Metadata metadata); @PostConstruct void init(); void createIndex(Class clazz); void updateIndex(Class clazz); void deleteIndex(String index); boolean checkExists(String index); }### Answer:
@Test public void start() throws Exception { indicesAdminClient.init(); } |
### Question:
IndicesAdminClient { public void createIndex(Class clazz) { String indexName = DocumentUtils.getIndexName(clazz); JSONObject index = this.indicesBuilder.buildIndex(clazz); locks.putIfAbsent(indexName, new ReentrantLock()); locks.get(indexName).lock(); this.esRestClient.performRequest("PUT", indexName, index); locks.get(indexName).unlock(); logger.info("created index[" + indexName + "] for entity: " + clazz); } @Inject IndicesAdminClient(EsRestClient esRestClient, JkesProperties jkesProperties, Metadata metadata); @PostConstruct void init(); void createIndex(Class clazz); void updateIndex(Class clazz); void deleteIndex(String index); boolean checkExists(String index); }### Answer:
@Test public void createIndex() throws Exception { if(!indicesAdminClient.checkExists("my_index")) indicesAdminClient.createIndex(PersonGroup.class); } |
### Question:
IndicesAdminClient { public boolean checkExists(String index) { locks.putIfAbsent(index, new ReentrantLock()); locks.get(index).lock(); Response response = this.esRestClient.performRequest("HEAD", index); locks.get(index).unlock(); return response.getStatusLine().getStatusCode() == 200; } @Inject IndicesAdminClient(EsRestClient esRestClient, JkesProperties jkesProperties, Metadata metadata); @PostConstruct void init(); void createIndex(Class clazz); void updateIndex(Class clazz); void deleteIndex(String index); boolean checkExists(String index); }### Answer:
@Test public void checkExists() throws Exception { indicesAdminClient.checkExists("my_index"); } |
### Question:
MappingBuilder { public JSONObject buildMapping(Class<?> clazz) { JSONObject mapping = new JSONObject(); mapping.put("dynamic", "strict"); mapping.put(FIELD_PROPERTIES, getEntityMappingProperties(clazz)); return mapping; } JSONObject buildMapping(Class<?> clazz); }### Answer:
@Test public void buildMapping() { JSONObject mapping = new MappingBuilder().buildMapping(PersonGroup.class); System.out.println(JsonUtils.convertToString(mapping)); } |
### Question:
HttpClient { public Response post(String host, String endpoint, JSONObject entity) throws IOException { return performRequest("POST", host, endpoint, Collections.emptyMap(), entity); } private HttpClient(); Response get(String host, String endpoint); Response post(String host, String endpoint, JSONObject entity); Response put(String host, String endpoint, JSONObject entity); Response delete(String host, String endpoint); Response head(String host, String endpoint); Response performRequest(String method, String host, String endpoint, Map<String, String> params, JSONObject entity); static HttpClient getInstance(); }### Answer:
@Test public void post() throws Exception { } |
### Question:
HttpClient { static URI buildUri(String path, Map<String, String> params) { Objects.requireNonNull(path, "path must not be null"); try { URIBuilder uriBuilder = new URIBuilder(path); for (Map.Entry<String, String> param : params.entrySet()) { uriBuilder.addParameter(param.getKey(), param.getValue()); } return uriBuilder.build(); } catch(URISyntaxException e) { throw new IllegalArgumentException(e.getMessage(), e); } } private HttpClient(); Response get(String host, String endpoint); Response post(String host, String endpoint, JSONObject entity); Response put(String host, String endpoint, JSONObject entity); Response delete(String host, String endpoint); Response head(String host, String endpoint); Response performRequest(String method, String host, String endpoint, Map<String, String> params, JSONObject entity); static HttpClient getInstance(); }### Answer:
@Test public void buildUri() throws Exception { String url = "http: InetAddress address = InetAddress.getByName(new URL(url).getHost()); String ip = address.getHostAddress(); System.out.println(ip); } |
### Question:
HttpUtils { public static String parseIpFromUrl(String url) throws MalformedURLException, UnknownHostException { Asserts.notBlank(url, "url can't be null"); InetAddress address = InetAddress.getByName(new URL(url).getHost()); return address.getHostAddress(); } static String parseIpFromUrl(String url); static String[] getIpsFromUrls(String... urls); static String getIpsFromDomainName(String domainName); static String[] getIpsFromDomainNames(String... domainNames); }### Answer:
@Test public void parseIpFromUrl() throws Exception { System.out.println(HttpUtils.parseIpFromUrl("http: } |
### Question:
HttpUtils { public static String[] getIpsFromUrls(String... urls) throws MalformedURLException, UnknownHostException { if(urls == null || urls.length == 0) return null; String[] ips = new String[urls.length]; for (int i = 0, urlsLength = urls.length; i < urlsLength; i++) { String url = urls[i]; InetAddress address = InetAddress.getByName(new URL(url).getHost()); ips[i] = address.getHostAddress(); } return ips; } static String parseIpFromUrl(String url); static String[] getIpsFromUrls(String... urls); static String getIpsFromDomainName(String domainName); static String[] getIpsFromDomainNames(String... domainNames); }### Answer:
@Test public void getIpsFormUrls() throws Exception { System.out.println(Arrays.toString(HttpUtils.getIpsFromUrls("http: } |
### Question:
HttpUtils { public static String[] getIpsFromDomainNames(String... domainNames) throws UnknownHostException { if(domainNames == null || domainNames.length == 0) return null; String[] ips = new String[domainNames.length]; for (int i = 0, urlsLength = domainNames.length; i < urlsLength; i++) { String url = "http: try { InetAddress address = InetAddress.getByName(new URL(url).getHost()); ips[i] = address.getHostAddress(); } catch (MalformedURLException e) { throw new RuntimeException(e); } } return ips; } static String parseIpFromUrl(String url); static String[] getIpsFromUrls(String... urls); static String getIpsFromDomainName(String domainName); static String[] getIpsFromDomainNames(String... domainNames); }### Answer:
@Test public void getIpsFormDomainNames() throws Exception { System.out.println(Arrays.toString(HttpUtils.getIpsFromDomainNames("timeyang.com", "github.com"))); } |
### Question:
ReflectionUtils { public static List<String> getReturnTypeParameters(Method method) { List<String> typeParameters = new ArrayList<>(); Type type = method.getGenericReturnType(); String typeName = type.getTypeName(); Pattern p = Pattern.compile("<((\\S+\\.?),?\\s*)>"); Matcher m = p.matcher(typeName); while (m.find()) { typeParameters.add(m.group(2)); } return typeParameters; } static List<String> getReturnTypeParameters(Method method); static String getTypeName(Method method); static String getInnermostType(Method method); static Class<?> getInnermostTypeClass(Method method); static String getInnermostType(Field field); static Class<?> getInnermostTypeClass(Field field); static String getFieldNameForGetter(String methodName); static String getFieldNameForGetter(Method method); static Object invokeMethod(Object target, String methodName, Class<?>[] parameterTypes, Object... params); static Object getAnnotatedFieldValue(Object target, Class<? extends Annotation> annotation); static Field getAnnotatedField(Class<?> clazz, String fieldName, Class<? extends Annotation> annotation); static T getFieldAnnotation(Class<?> clazz, String fieldName, Class<T> annotationClass); static Object getAnnotatedMethodReturnValue(Object target, Class<? extends Annotation> annotation); }### Answer:
@Test public void getReturnTypeParameters() throws Exception { Method method = PersonGroup.class.getDeclaredMethod("getPersons"); ReflectionUtils.getReturnTypeParameters(method); } |
### Question:
ReflectionUtils { public static String getInnermostType(Method method) { Type type = method.getGenericReturnType(); String typeName = type.getTypeName(); String[] types = typeName.split(",\\s*|<|<|>+"); return types[types.length - 1]; } static List<String> getReturnTypeParameters(Method method); static String getTypeName(Method method); static String getInnermostType(Method method); static Class<?> getInnermostTypeClass(Method method); static String getInnermostType(Field field); static Class<?> getInnermostTypeClass(Field field); static String getFieldNameForGetter(String methodName); static String getFieldNameForGetter(Method method); static Object invokeMethod(Object target, String methodName, Class<?>[] parameterTypes, Object... params); static Object getAnnotatedFieldValue(Object target, Class<? extends Annotation> annotation); static Field getAnnotatedField(Class<?> clazz, String fieldName, Class<? extends Annotation> annotation); static T getFieldAnnotation(Class<?> clazz, String fieldName, Class<T> annotationClass); static Object getAnnotatedMethodReturnValue(Object target, Class<? extends Annotation> annotation); }### Answer:
@Test public void getActualReturnType() throws Exception { Method method1 = ComplexEntity.class.getDeclaredMethod("getCars"); System.out.println(ReflectionUtils.getInnermostType(method1)); Method method2 = ComplexEntity.class.getDeclaredMethod("getBooks"); System.out.println(ReflectionUtils.getInnermostType(method2)); } |
### Question:
SimpleClassUtils { static Class[] getClasses(String packageName) throws ClassNotFoundException, IOException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); assert classLoader != null; String path = packageName.replace('.', '/'); Enumeration<URL> resources = classLoader.getResources(path); List<File> dirs = new ArrayList<>(); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); dirs.add(new File(resource.getFile())); } ArrayList<Class> classes = new ArrayList<>(); for (File directory : dirs) { classes.addAll(findClasses(directory, packageName)); } return classes.toArray(new Class[classes.size()]); } }### Answer:
@Test public void testGetClasses() throws IOException, ClassNotFoundException { Class[] classes = SimpleClassUtils.getClasses("com.timeyang.search.entity"); for (Class c : classes) { System.out.println(c); } for (Class c : SimpleClassUtils.getClasses("com.fasterxml.jackson.databind.module")) { System.out.println(c); } } |
### Question:
ClassUtils { static Set<Class<?>> getClasses(String packageName) { List<ClassLoader> classLoadersList = new LinkedList<>(); classLoadersList.add(ClasspathHelper.contextClassLoader()); classLoadersList.add(ClasspathHelper.staticClassLoader()); Reflections reflections = new Reflections(new ConfigurationBuilder() .setScanners(new SubTypesScanner(false ), new ResourcesScanner()) .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0]))) .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(packageName)))); Set<Class<?>> classes = reflections.getSubTypesOf(Object.class); return classes; } static Set<Class<?>> getAnnotatedClasses(String packageName, Class<? extends Annotation> annotation); }### Answer:
@Test public void getCLasses() { ClassUtils.getClasses("com.timeyang.search.entity").forEach(System.out::println); ClassUtils.getClasses("com.fasterxml.jackson.databind.module").forEach(System.out::println); } |
### Question:
ExceptionStack implements Serializable { public Collection<Throwable> getCauseElements() { return Collections.unmodifiableCollection(this.causes); } ExceptionStack(); ExceptionStack(final Throwable exception); @Deprecated protected ExceptionStack(final Collection<Throwable> causeChainElements, final int currentElementIndex); Collection<Throwable> getCauseElements(); boolean isLast(); Throwable getNext(); Collection<Throwable> getRemaining(); boolean isRoot(); Throwable getCurrent(); void setCauseElements(Collection<Throwable> elements); Deque<ExceptionStackItem> getOrigExceptionStackItems(); }### Answer:
@Test public void testSQLExceptionUnwrap() { SQLTransactionRollbackException transactionRollbackException = new SQLTransactionRollbackException(); SQLRecoverableException recoverableException = new SQLRecoverableException(); SQLSyntaxErrorException syntaxErrorException = new SQLSyntaxErrorException(); recoverableException.setNextException(syntaxErrorException); transactionRollbackException.setNextException(recoverableException); Throwable e = new Exception(transactionRollbackException); ExceptionStack es = new ExceptionStack(e); assertThat(es.getCauseElements().size(), is(4)); assertThat(es.getCauseElements(), hasItems(e, transactionRollbackException, recoverableException, syntaxErrorException)); } |
### Question:
RouteService { public Schema route(String sql) { SQLStatement sqlStatement = SQLUtils.parseSingleMysqlStatement(sql); return null; } RouteService(MetadataManager metadataManager); static RouteService create(MetadataManager metadataManager); Schema route(String sql); }### Answer:
@Test public void test(){ String sql = "select 1"; String text = route(sql); Assert.assertSame(text,""); } |
### Question:
GPatternUTF8Lexer { public void init(String text) { ByteBuffer byteBuffer = StandardCharsets.UTF_8.encode(text); init(byteBuffer, 0, byteBuffer.limit()); } GPatternUTF8Lexer(GPatternIdRecorder idRecorder); void init(String text); void init(ByteBuffer buffer, int startOffset, int limit); boolean nextToken(); boolean hasChar(); int peekAsciiChar(int step); int nextChar(); String getCurTokenString(); String getString(int start, int end); boolean fastEquals(int startOffset, int endOffset, byte[] symbol); static final int DEMO; static int ignorelength; }### Answer:
@Test public void init() { GPatternIdRecorder recorder = new GPatternIdRecorderImpl(false); recorder.load(Collections.emptySet()); GPatternUTF8Lexer utf8Lexer = new GPatternUTF8Lexer(recorder); String text = "1234 abc 1a2b3c 'aεεεε1' `qac`"; utf8Lexer.init(text); Assert.assertTrue(utf8Lexer.nextToken()); Assert.assertEquals("1234", utf8Lexer.getCurTokenString()); Assert.assertTrue(utf8Lexer.nextToken()); Assert.assertEquals("abc", utf8Lexer.getCurTokenString()); Assert.assertTrue(utf8Lexer.nextToken()); Assert.assertEquals("1a2b3c", utf8Lexer.getCurTokenString()); Assert.assertTrue(utf8Lexer.nextToken()); Assert.assertEquals("'aεεεε1'", utf8Lexer.getCurTokenString()); Assert.assertTrue(utf8Lexer.nextToken()); Assert.assertEquals("`qac`", utf8Lexer.getCurTokenString()); } |
### Question:
HttpLoader { public LoadedXml load(final String url, final int timeout) { try { final InputStream stream = loadAsStream(url, timeout); final DocumentBuilder builder = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder(); final Document document = builder.parse(stream); return new LoadedXml(document); } catch (SocketTimeoutException e) { return LoadedXml.EMPTY_XML; } catch (IOException e) { log.error("Error while processing url: " + url, e); } catch (ParserConfigurationException e) { log.error("Error while processing url: " + url, e); } catch (SAXException e) { log.error("Error while processing url: " + url, e); } return LoadedXml.EMPTY_XML; } HttpLoader(); InputStream loadAsStream(final String url, final int timeout, final Map<String, List<String>> params); InputStream loadAsStream(final String url, final int timeout, final Map<String, List<String>> params, final Map<String, String> headers); HttpMethodResult loadAsStreamWithHeaders(final String url, final int timeout, final Map<String, List<String>> params); HttpMethodResult loadAsStreamWithHeaders(final String url, final int timeout, final Map<String, List<String>> params, final Map<String, String> headers); InputStream loadAsStream(final String url, final int timeout); LoadedXml load(final String url, final int timeout); }### Answer:
@Test public void testTimeout() throws Throwable { HttpLoader httpLoader = new HttpLoader(); final LoadedXml loadedXml = httpLoader.load("http: assertTrue(loadedXml.isEmpty()); }
@Test public void testNonTimeout() throws Throwable { HttpLoader httpLoader = new HttpLoader(); final LoadedXml loadedXml = httpLoader.load("http: assertFalse(loadedXml.isEmpty()); } |
### Question:
YaletProcessor { public void process(final HttpServletRequest req, final HttpServletResponse res, final String realPath) throws UnsupportedEncodingException, ServletException { req.setCharacterEncoding(encoding); res.setCharacterEncoding(encoding); log.info("Start process user request => {" + realPath + "}, remote ip => {" + req.getRemoteAddr() + "}, method=" + req.getMethod()); final long startTime = System.currentTimeMillis(); final InternalRequest internalRequest = yaletSupport.createRequest(req, realPath); final InternalResponse internalResponse = yaletSupport.createResponse(res); process(internalRequest, internalResponse, new RedirHandler(res)); log.info("Processing time for user request => {" + realPath + "} is " + (System.currentTimeMillis() - startTime) + " ms"); } @Required void setYaletSupport(final YaletSupport yaletSupport); void setEncoding(final String encoding); void process(final HttpServletRequest req,
final HttpServletResponse res,
final String realPath); }### Answer:
@Test public void testProcessFile() throws Exception { request = new SimpleInternalRequest(null, "./xfresh-core/src/test/resources/test.xml"); request.setNeedTransform(false); yaletProcessor.process(request, response, new RedirHandler(null)); assertEquals(TEST_CONTENT, new String(baos.toByteArray()).trim()); }
@Test public void testTransformFile() throws Exception { request = new SimpleInternalRequest(null, "./xfresh-core/src/test/resources/test.xml"); yaletProcessor.process(request, response, new RedirHandler(null)); assertEquals(TEST_TRANSFORMED_CONTENT.toLowerCase(), new String(baos.toByteArray()).trim().toLowerCase()); }
@Test public void testTransformXFile() throws Exception { request = new SimpleInternalRequest(null, "./xfresh-core/src/test/resources/xtest.xml"); yaletProcessor.process(request, response, new RedirHandler(null)); assertEquals(TEST_CONTENT, new String(baos.toByteArray()).trim()); } |
### Question:
DbUserService implements UserService { public long addUser(final String login, final String fio, final String passwd, final String passwdAdd) throws UserCreationException { final UserInfo user = getUser(login); if (user != null) { throw new UserCreationException(UserCreationException.Type.ALREADY_EXISTS); } try { jdbcTemplate.update( "insert into auth_user (login, fio, passwd_hash, passwd_add) " + "values (?,?,?,?)", login, fio, passwd, passwdAdd ); return getLastInsertId(); } catch (Exception e) { throw new UserCreationException(UserCreationException.Type.INTERNAL_ERROR); } } @Required void setJdbcTemplate(final SimpleJdbcTemplate jdbcTemplate); long addUser(final String login, final String fio, final String passwd, final String passwdAdd); void updateUserInfo(final UserInfo userInfo); boolean checkUser(final long userId, final String passwd); UserInfo getUser(final long userId); UserInfo getUser(final String login); }### Answer:
@Test public void testAddUser() throws Exception { final long userId = createUser(); assertEquals(1, removeUser(userId)); } |
### Question:
DbUserService implements UserService { public UserInfo getUser(final long userId) { final List<UserInfo> users = jdbcTemplate.query( "select * from auth_user where user_id = ?", USER_INFO_MAPPER, userId); if (users.isEmpty()) { return null; } return users.get(0); } @Required void setJdbcTemplate(final SimpleJdbcTemplate jdbcTemplate); long addUser(final String login, final String fio, final String passwd, final String passwdAdd); void updateUserInfo(final UserInfo userInfo); boolean checkUser(final long userId, final String passwd); UserInfo getUser(final long userId); UserInfo getUser(final String login); }### Answer:
@Test public void testGetUser() throws Exception { final long userId = createUser(); final UserInfo userInfo = dbUserService.getUser(userId); assertEquals("xxx", userInfo.getLogin()); assertEquals("x x", userInfo.getFio()); assertEquals("123", userInfo.getPasswdHash()); assertEquals("11", userInfo.getPasswdAdd()); assertEquals(1, removeUser(userId)); } |
### Question:
DbUserService implements UserService { public boolean checkUser(final long userId, final String passwd) { return 0 < jdbcTemplate.queryForInt( "select count(*) from auth_user where user_id = ? and passwd_hash = ?", userId, passwd ); } @Required void setJdbcTemplate(final SimpleJdbcTemplate jdbcTemplate); long addUser(final String login, final String fio, final String passwd, final String passwdAdd); void updateUserInfo(final UserInfo userInfo); boolean checkUser(final long userId, final String passwd); UserInfo getUser(final long userId); UserInfo getUser(final String login); }### Answer:
@Test public void testCheckUser() throws Exception { final long userId = createUser(); assertTrue(dbUserService.checkUser(userId, "123")); assertFalse(dbUserService.checkUser(userId * 2, "11")); assertFalse(dbUserService.checkUser(userId * 3, "123")); assertFalse(dbUserService.checkUser(userId, null)); assertFalse(dbUserService.checkUser(userId * 5, null)); assertEquals(1, removeUser(userId)); } |
### Question:
Minimizer implements IMinimizer { @Override public void setCacheDir(File dir) { checkInitialize_(false); cache_ = new FileCache(dir); } Minimizer(ResourceType type); @Inject Minimizer(ICompressor compressor, ResourceType type); @Override void enableDisableMinimize(boolean enable); @Override void enableDisableCompress(boolean enable); @Override void enableDisableCache(boolean enable); @Override void enableDisableInMemoryCache(boolean enable); @Override void enableDisableProcessInline(boolean enable); @Deprecated void enableDisableVerifyResource(boolean verify); @Override boolean isMinimizeEnabled(); @Override boolean isCompressEnabled(); @Override boolean isCacheEnabled(); @Override void setResourceDir(String dir); @Override void setRootDir(String dir); @Override void setUrlContextPath(String ctxPath); @Override void setCacheDir(File dir); @Override void setResourceUrlRoot(String urlRoot); @Override void setResourceUrlPath(String urlPath); @Override void setCacheUrlPath(String urlPath); @Override void clearCache(); @Override void setFileLocator(IFileLocator fileLocator); @Override void setBufferLocator(IBufferLocator bufferLocator); @Override void setRouteMapper(IRouteMapper routeMapper); @Override long getLastModified(File file); @Override void checkCache(); @Override List<String> process(List<String> resourceNames); @Override List<String> processWithoutMinimize(List<String> resourceNames); @Override String processInline(String content); @Override String processStatic(File file); IResource minimize(String resourceNames); static void copy_(Reader in, Writer out); ResourceType getType(); void setResourcesParam(String resourcesParam_); static final String SYS_PROP_LESS_ENABLED; static final String SYS_PROP_COFFEE_ENABLED; }### Answer:
@Test(expected = IllegalStateException.class) public void testInvalidSetup() { jm.setCacheDir(cacheDir); } |
### Question:
EmailSender { void sendEmail(String to, String from, String title, String content) { SimpleMailMessage mail = new SimpleMailMessage(); mail.setTo(to); mail.setFrom(from); mail.setSubject(title); mail.setText(content); javaMailSender.send(mail); } EmailSender(JavaMailSender javaMailSender); }### Answer:
@Test public void shouldSendEmail() throws Exception { String to = "test@codecouple.pl"; String from = "blog@codecouple.pl"; String title = "Title"; String content = "Content"; emailSender.sendEmail(to, from, title, content); MimeMessage[] receivedMessages = server.getReceivedMessages(); assertThat(receivedMessages.length).isEqualTo(1); MimeMessage receivedMessage = receivedMessages[0]; assertThat(receivedMessage.getAllRecipients()[0].toString()).isEqualTo(to); assertThat(receivedMessage.getFrom()[0].toString()).isEqualTo(from); assertThat(receivedMessage.getSubject()).isEqualTo(title); assertThat(receivedMessage.getContent().toString()).contains(content); assertThat(content).isEqualTo(GreenMailUtil.getBody(server.getReceivedMessages()[0])); } |
### Question:
MerlinFlowable { public static Flowable<NetworkStatus> from(Context context) { return from(context, new Merlin.Builder()); } static Flowable<NetworkStatus> from(Context context); static Flowable<NetworkStatus> from(Context context, MerlinBuilder merlinBuilder); static Flowable<NetworkStatus> from(Merlin merlin); }### Answer:
@Test public void unbindWhenDisposed() { Disposable disposable = MerlinFlowable.from(merlin) .subscribe(); disposable.dispose(); verify(merlin).unbind(); }
@Test public void notCrashWhenCreatingWithAMerlinBuilderWithoutCallbacks() { Context context = mock(Context.class); Merlin.Builder merlinBuilder = new Merlin.Builder(); MerlinFlowable.from(context, merlinBuilder).subscribe(); } |
### Question:
Registrar { void clearRegistrations() { if (connectables != null) { connectables.clear(); } if (disconnectables != null) { disconnectables.clear(); } if (bindables != null) { bindables.clear(); } } Registrar(Register<Connectable> connectables, Register<Disconnectable> disconnectables, Register<Bindable> bindables); }### Answer:
@Test public void givenMissingDisconnectables_whenClearingRegistrations_thenDoesNothing() { registrar = new Registrar(connectables, null, bindables); registrar.clearRegistrations(); verifyZeroInteractions(disconnectables); }
@Test public void givenMissingBindables_whenClearingRegistrations_thenDoesNothing() { registrar = new Registrar(connectables, disconnectables, null); registrar.clearRegistrations(); verifyZeroInteractions(bindables); }
@Test public void whenClearingRegistrations_thenDelegatesClearingToRegisters() { registrar.clearRegistrations(); verify(connectables).clear(); verify(disconnectables).clear(); verify(bindables).clear(); }
@Test public void givenMissingConnectables_whenClearingRegistrations_thenDoesNothing() { registrar = new Registrar(null, disconnectables, bindables); registrar.clearRegistrations(); verifyZeroInteractions(connectables); } |
### Question:
Ping { boolean doSynchronousPing() { Logger.d("Pinging: " + endpoint); try { return validator.isResponseCodeValid(responseCodeFetcher.from(endpoint)); } catch (RequestException e) { if (!e.causedByIO()) { Logger.e("Ping task failed due to " + e.getMessage()); } return false; } } Ping(Endpoint endpoint, EndpointPinger.ResponseCodeFetcher responseCodeFetcher, ResponseCodeValidator validator); }### Answer:
@Test public void givenSuccessfulRequest_whenSynchronouslyPinging_thenChecksResponseCodeIsValid() { given(responseCodeFetcher.from(ENDPOINT)).willReturn(RESPONSE_CODE); ping.doSynchronousPing(); verify(responseCodeValidator).isResponseCodeValid(RESPONSE_CODE); }
@Test public void givenSuccessfulRequest_whenSynchronouslyPinging_thenReturnsTrue() { given(responseCodeFetcher.from(ENDPOINT)).willReturn(RESPONSE_CODE); given(responseCodeValidator.isResponseCodeValid(RESPONSE_CODE)).willReturn(true); boolean isSuccess = ping.doSynchronousPing(); assertThat(isSuccess).isTrue(); }
@Test public void givenRequestFailsWithIOException_whenSynchronouslyPinging_thenReturnsFalse() { given(responseCodeFetcher.from(ENDPOINT)).willThrow(new RequestException(new IOException())); boolean isSuccess = ping.doSynchronousPing(); assertThat(isSuccess).isFalse(); }
@Test public void givenRequestFailsWithRuntimeException_whenSynchronouslyPinging_thenReturnsFalse() { given(responseCodeFetcher.from(ENDPOINT)).willThrow(new RequestException(new RuntimeException())); boolean isSuccess = ping.doSynchronousPing(); assertThat(isSuccess).isFalse(); } |
### Question:
Merlin { public void bind() { merlinServiceBinder.bindService(); } Merlin(MerlinServiceBinder merlinServiceBinder, Registrar registrar); void setEndpoint(Endpoint endpoint, ResponseCodeValidator validator); void bind(); void unbind(); void registerConnectable(Connectable connectable); void registerDisconnectable(Disconnectable disconnectable); void registerBindable(Bindable bindable); }### Answer:
@Test public void whenBinding_thenBindsService() { merlin.bind(); verify(serviceBinder).bindService(); } |
### Question:
Merlin { public void unbind() { merlinServiceBinder.unbind(); registrar.clearRegistrations(); } Merlin(MerlinServiceBinder merlinServiceBinder, Registrar registrar); void setEndpoint(Endpoint endpoint, ResponseCodeValidator validator); void bind(); void unbind(); void registerConnectable(Connectable connectable); void registerDisconnectable(Disconnectable disconnectable); void registerBindable(Bindable bindable); }### Answer:
@Test public void whenUnbinding_thenUnbindsService() { merlin.unbind(); verify(serviceBinder).unbind(); }
@Test public void whenUnbinding_thenClearsRegistrations() { merlin.unbind(); verify(registrar).clearRegistrations(); } |
### Question:
Merlin { public void registerConnectable(Connectable connectable) { registrar.registerConnectable(connectable); } Merlin(MerlinServiceBinder merlinServiceBinder, Registrar registrar); void setEndpoint(Endpoint endpoint, ResponseCodeValidator validator); void bind(); void unbind(); void registerConnectable(Connectable connectable); void registerDisconnectable(Disconnectable disconnectable); void registerBindable(Bindable bindable); }### Answer:
@Test public void whenRegisteringConnectable_thenRegistersConnectable() { Connectable connectable = mock(Connectable.class); merlin.registerConnectable(connectable); verify(registrar).registerConnectable(connectable); } |
### Question:
Merlin { public void registerDisconnectable(Disconnectable disconnectable) { registrar.registerDisconnectable(disconnectable); } Merlin(MerlinServiceBinder merlinServiceBinder, Registrar registrar); void setEndpoint(Endpoint endpoint, ResponseCodeValidator validator); void bind(); void unbind(); void registerConnectable(Connectable connectable); void registerDisconnectable(Disconnectable disconnectable); void registerBindable(Bindable bindable); }### Answer:
@Test public void whenRegisteringDisconnectable_thenRegistersDisconnectable() { Disconnectable disconnectable = mock(Disconnectable.class); merlin.registerDisconnectable(disconnectable); verify(registrar).registerDisconnectable(disconnectable); } |
### Question:
Merlin { public void registerBindable(Bindable bindable) { registrar.registerBindable(bindable); } Merlin(MerlinServiceBinder merlinServiceBinder, Registrar registrar); void setEndpoint(Endpoint endpoint, ResponseCodeValidator validator); void bind(); void unbind(); void registerConnectable(Connectable connectable); void registerDisconnectable(Disconnectable disconnectable); void registerBindable(Bindable bindable); }### Answer:
@Test public void whenRegisteringBindable_thenRegistersBindable() { Bindable bindable = mock(Bindable.class); merlin.registerBindable(bindable); verify(registrar).registerBindable(bindable); } |
### Question:
ConnectivityChangeEventExtractor { ConnectivityChangeEvent extractFrom(Network network) { NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network); if (null != networkInfo) { boolean connected = networkInfo.isConnected(); String reason = networkInfo.getReason(); String extraInfo = networkInfo.getExtraInfo(); return ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(connected, extraInfo, reason); } else { return ConnectivityChangeEvent.createWithoutConnection(); } } ConnectivityChangeEventExtractor(ConnectivityManager connectivityManager); }### Answer:
@Test public void givenNetworkInfo_whenExtracting_thenReturnsConnectivityChangeEvent() { given(connectivityManager.getNetworkInfo(ANY_NETWORK)).willReturn(networkInfo); ConnectivityChangeEvent connectivityChangeEvent = eventExtractor.extractFrom(ANY_NETWORK); assertThat(connectivityChangeEvent).isEqualTo(ConnectivityChangeEvent.createWithNetworkInfoChangeEvent( CONNECTED, ANY_EXTRA_INFO, ANY_REASON )); }
@Test public void givenNetworkInfoIsUnavailable_whenExtracting_thenReturnsConnectivityChangeEventWithoutConnection() { given(connectivityManager.getNetworkInfo(ANY_NETWORK)).willReturn(UNAVAILABLE_NETWORK_INFO); ConnectivityChangeEvent connectivityChangeEvent = eventExtractor.extractFrom(ANY_NETWORK); assertThat(connectivityChangeEvent).isEqualTo(ConnectivityChangeEvent.createWithoutConnection()); } |
### Question:
EndpointPinger { void ping(PingerCallback pingerCallback) { PingTask pingTask = pingTaskFactory.create(endpoint, pingerCallback); pingTask.execute(); } EndpointPinger(Endpoint endpoint, PingTaskFactory pingTaskFactory); }### Answer:
@Test public void whenPinging_thenCreatesPingTask() { endpointPinger.ping(pingerCallback); verify(pingTaskFactory).create(ENDPOINT, pingerCallback); }
@Test public void whenPinging_thenExecutesPingTask() { endpointPinger.ping(pingerCallback); verify(pingTask).execute(); } |
### Question:
EndpointPinger { void noNetworkToPing(PingerCallback pingerCallback) { pingerCallback.onFailure(); } EndpointPinger(Endpoint endpoint, PingTaskFactory pingTaskFactory); }### Answer:
@Test public void whenNoNetworkToPing_thenCallsOnFailure() { endpointPinger.noNetworkToPing(pingerCallback); verify(pingerCallback).onFailure(); } |
### Question:
Registrar { void registerConnectable(Connectable connectable) { connectables().register(connectable); } Registrar(Register<Connectable> connectables, Register<Disconnectable> disconnectables, Register<Bindable> bindables); }### Answer:
@Test(expected = IllegalStateException.class) public void givenMissingRegister_whenRegisteringConnectable_thenThrowsIllegalStateException() { registrar = new Registrar(null, null, null); Connectable connectable = mock(Connectable.class); registrar.registerConnectable(connectable); }
@Test public void givenRegister_whenRegisteringConnectable_thenRegistersConnectableWithConnector() { Connectable connectable = mock(Connectable.class); registrar.registerConnectable(connectable); verify(connectables).register(connectable); } |
### Question:
ConnectivityChangesRegister { void register(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier) { if (androidVersion.isLollipopOrHigher()) { registerNetworkCallbacks(connectivityChangesNotifier); } else { registerBroadcastReceiver(); } } ConnectivityChangesRegister(Context context,
ConnectivityManager connectivityManager,
AndroidVersion androidVersion,
ConnectivityChangeEventExtractor connectivityChangeEventExtractor); }### Answer:
@Test public void givenRegisteredBroadcastReceiver_whenBindingForASecondTime_thenOriginalBroadcastReceiverIsRegisteredAgain() { ArgumentCaptor<ConnectivityReceiver> broadcastReceiver = givenRegisteredBroadcastReceiver(); connectivityChangesRegister.register(connectivityChangesNotifier); verify(context, times(2)).registerReceiver(eq(broadcastReceiver.getValue()), refEq(new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))); }
@TargetApi(Build.VERSION_CODES.LOLLIPOP) @Test public void givenRegisteredMerlinNetworkCallbacks_whenBindingForASecondTime_thenOriginalNetworkCallbacksIsRegisteredAgain() { ArgumentCaptor<ConnectivityCallbacks> merlinNetworkCallback = givenRegisteredMerlinNetworkCallbacks(); connectivityChangesRegister.register(connectivityChangesNotifier); verify(connectivityManager, times(2)).registerNetworkCallback(refEq((new NetworkRequest.Builder()).build()), eq(merlinNetworkCallback.getValue())); } |
### Question:
ConnectivityChangesRegister { void unregister() { if (androidVersion.isLollipopOrHigher()) { unregisterNetworkCallbacks(); } else { unregisterBroadcastReceiver(); } } ConnectivityChangesRegister(Context context,
ConnectivityManager connectivityManager,
AndroidVersion androidVersion,
ConnectivityChangeEventExtractor connectivityChangeEventExtractor); }### Answer:
@Test public void givenRegisteredBroadcastReceiver_whenUnbinding_thenUnregistersOriginallyRegisteredBroadcastReceiver() { ArgumentCaptor<ConnectivityReceiver> broadcastReceiver = givenRegisteredBroadcastReceiver(); connectivityChangesRegister.unregister(); verify(context).unregisterReceiver(broadcastReceiver.getValue()); }
@TargetApi(Build.VERSION_CODES.LOLLIPOP) @Test public void givenRegisteredMerlinNetworkCallback_whenUnbinding_thenUnregistersOriginallyRegisteredNetworkCallbacks() { ArgumentCaptor<ConnectivityCallbacks> merlinNetworkCallback = givenRegisteredMerlinNetworkCallbacks(); connectivityChangesRegister.unregister(); verify(connectivityManager).unregisterNetworkCallback(merlinNetworkCallback.getValue()); } |
### Question:
BindCallbackManager extends MerlinCallbackManager<Bindable> { void onMerlinBind(NetworkStatus networkStatus) { Logger.d("onBind"); for (Bindable bindable : registerables()) { bindable.onBind(networkStatus); } } BindCallbackManager(Register<Bindable> register); }### Answer:
@Test public void givenRegisteredConnectable_whenCallingOnConnect_thenCallsConnectForConnectable() { Bindable bindable = givenRegisteredBindable(); bindCallbackManager.onMerlinBind(networkStatus); verify(bindable).onBind(networkStatus); }
@Test public void givenMultipleRegisteredConnectables_whenCallingOnConnect_thenCallsConnectForAllConnectables() { List<Bindable> bindables = givenMultipleRegisteredBindables(); bindCallbackManager.onMerlinBind(networkStatus); for (Bindable bindable : bindables) { verify(bindable).onBind(networkStatus); } } |
### Question:
Registrar { void registerDisconnectable(Disconnectable disconnectable) { disconnectables().register(disconnectable); } Registrar(Register<Connectable> connectables, Register<Disconnectable> disconnectables, Register<Bindable> bindables); }### Answer:
@Test(expected = IllegalStateException.class) public void givenMissingRegister_thenRegisteringDisconnectable_thenThrowsIllegalStateException() { registrar = new Registrar(null, null, null); Disconnectable disconnectable = mock(Disconnectable.class); registrar.registerDisconnectable(disconnectable); }
@Test public void givenRegister_whenRegisteringDisconnectable_thenRegistersDisconnectableWithDisconnector() { Disconnectable disconnectable = mock(Disconnectable.class); registrar.registerDisconnectable(disconnectable); verify(this.disconnectables).register(disconnectable); } |
### Question:
ConnectivityChangesForwarder { void forward(ConnectivityChangeEvent connectivityChangeEvent) { if (matchesPreviousEndpointPingNetworkStatus(connectivityChangeEvent)) { return; } networkStatusRetriever.fetchWithPing(endpointPinger, endpointPingerCallback); lastEndpointPingNetworkStatus = connectivityChangeEvent.asNetworkStatus(); } ConnectivityChangesForwarder(NetworkStatusRetriever networkStatusRetriever,
DisconnectCallbackManager disconnectCallbackManager,
ConnectCallbackManager connectCallbackManager,
BindCallbackManager bindCallbackManager,
EndpointPinger endpointPinger); }### Answer:
@Test public void givenConnectivityChangeEvent_whenNotifyingOfConnectivityChangeEvent_thenDelegatesRefreshingToRetriever() { ConnectivityChangeEvent connectivityChangeEvent = ConnectivityChangeEvent.createWithNetworkInfoChangeEvent(CONNECTED, ANY_INFO, ANY_REASON); connectivityChangesForwarder.forward(connectivityChangeEvent); verify(networkStatusRetriever).fetchWithPing(eq(endpointPinger), any(EndpointPinger.PingerCallback.class)); } |
### Question:
ConnectivityReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { connectivityReceiverConnectivityChangeNotifier.notify(context, intent); } ConnectivityReceiver(); ConnectivityReceiver(ConnectivityReceiverConnectivityChangeNotifier connectivityReceiverConnectivityChangeNotifier); @Override void onReceive(Context context, Intent intent); }### Answer:
@Test public void whenReceivingAnIntent_thenForwardsToConnectivityChangeNotifier() { connectivityReceiver.onReceive(context, intent); verify(notifier).notify(context, intent); } |
### Question:
NetworkStatusRetriever { void fetchWithPing(EndpointPinger endpointPinger, EndpointPinger.PingerCallback pingerCallback) { if (merlinsBeard.isConnected()) { endpointPinger.ping(pingerCallback); } else { endpointPinger.noNetworkToPing(pingerCallback); } } NetworkStatusRetriever(MerlinsBeard merlinsBeard); }### Answer:
@Test public void givenMerlinsBeardIsConnected_whenFetchingWithPing_thenPingsUsingHostPinger() { given(merlinsBeards.isConnected()).willReturn(CONNECTED); networkStatusRetriever.fetchWithPing(endpointPinger, pingerCallback); verify(endpointPinger).ping(pingerCallback); }
@Test public void givenMerlinsBeardIsDisconnected_whenFetchingWithPing_thenCallsNoNetworkToPing() { given(merlinsBeards.isConnected()).willReturn(DISCONNECTED); networkStatusRetriever.fetchWithPing(endpointPinger, pingerCallback); verify(endpointPinger).noNetworkToPing(pingerCallback); } |
### Question:
NetworkStatusRetriever { NetworkStatus retrieveNetworkStatus() { if (merlinsBeard.isConnected()) { return NetworkStatus.newAvailableInstance(); } else { return NetworkStatus.newUnavailableInstance(); } } NetworkStatusRetriever(MerlinsBeard merlinsBeard); }### Answer:
@Test public void givenMerlinsBeardIsConnected_whenGettingNetworkStatus_thenReturnsNetworkStatusAvailable() { given(merlinsBeards.isConnected()).willReturn(CONNECTED); NetworkStatus networkStatus = networkStatusRetriever.retrieveNetworkStatus(); assertThat(networkStatus).isEqualTo(NetworkStatus.newAvailableInstance()); }
@Test public void givenMerlinsBeardIsDisconnected_whenGettingNetworkStatus_thenReturnsNetworkStatusUnavailable() { given(merlinsBeards.isConnected()).willReturn(DISCONNECTED); NetworkStatus networkStatus = networkStatusRetriever.retrieveNetworkStatus(); assertThat(networkStatus).isEqualTo(NetworkStatus.newUnavailableInstance()); } |