method2testcases
stringlengths 118
6.63k
|
---|
### Question:
SuppressingCloser extends AbstractCloser<SuppressingCloser, Exception> { public SuppressingCloser push(AutoCloseable closeable) { return push( AutoCloseable::close, closeable ); } SuppressingCloser(Throwable mainThrowable); SuppressingCloser push(AutoCloseable closeable); SuppressingCloser pushAll(AutoCloseable ... closeables); SuppressingCloser pushAll(Iterable<? extends AutoCloseable> closeables); }### Answer:
@Test public void someNonFailingCloseables() { Throwable mainException = new Exception(); RuntimeException exception1 = new RuntimeException(); RuntimeException exception2 = new RuntimeException(); RuntimeException exception3 = new RuntimeException(); new SuppressingCloser( mainException ) .push( () -> { } ) .push( ignored -> { throw exception1; }, new Object() ) .push( ignored -> { throw exception2; }, new Object() ) .push( () -> { } ) .push( () -> { } ) .push( ignored -> { throw exception3; }, new Object() ) .push( () -> { } ); assertThat( mainException ) .hasSuppressedException( exception1 ) .hasSuppressedException( exception2 ) .hasSuppressedException( exception3 ); }
@Test public void onlyNonFailingCloseables() { Throwable mainException = new Exception(); new SuppressingCloser( mainException ) .push( () -> { } ) .push( () -> { } ); assertThat( mainException ) .hasNoSuppressedExceptions(); }
@Test public void customCloseable() { Throwable mainException = new Exception(); MyException1 exception1 = new MyException1(); RuntimeException exception2 = new IllegalStateException(); @SuppressWarnings("resource") MyException1Closeable closeable = () -> { throw exception1; }; new SuppressingCloser( mainException ) .push( closeable ) .push( ignored -> { throw exception2; }, new Object() ); assertThat( mainException ) .hasSuppressedException( exception1 ); }
@Test public void javaIOCloseable() { Throwable mainException = new Exception(); IOException exception1 = new IOException(); RuntimeException exception2 = new IllegalStateException(); @SuppressWarnings("resource") Closeable closeable = () -> { throw exception1; }; new SuppressingCloser( mainException ) .push( closeable ) .push( ignored -> { throw exception2; }, new Object() ); assertThat( mainException ) .hasSuppressedException( exception1 ) .hasSuppressedException( exception2 ); }
@Test public void autoCloseable() { Throwable mainException = new Exception(); Exception exception1 = new Exception(); RuntimeException exception2 = new IllegalStateException(); @SuppressWarnings("resource") AutoCloseable closeable = () -> { throw exception1; }; new SuppressingCloser( mainException ) .push( closeable ) .push( ignored -> { throw exception2; }, new Object() ); assertThat( mainException ) .hasSuppressedException( exception1 ) .hasSuppressedException( exception2 ); }
@Test public void runtimeException() { Throwable mainException = new Exception(); RuntimeException exception1 = new RuntimeException(); RuntimeException exception2 = new IllegalStateException(); RuntimeException exception3 = new UnsupportedOperationException(); new SuppressingCloser( mainException ) .push( ignored -> { throw exception1; }, new Object() ) .push( ignored -> { throw exception2; }, new Object() ) .push( ignored -> { throw exception3; }, new Object() ); assertThat( mainException ) .hasSuppressedException( exception1 ) .hasSuppressedException( exception2 ) .hasSuppressedException( exception3 ); } |
### Question:
LuceneBatchedWorkProcessor implements BatchedWorkProcessor { public void forceRefresh() { indexAccessor.refresh(); } LuceneBatchedWorkProcessor(EventContext eventContext,
IndexAccessor indexAccessor); @Override void beginBatch(); @Override CompletableFuture<?> endBatch(); @Override void complete(); T submit(IndexManagementWork<T> work); T submit(IndexingWork<T> work); void forceCommit(); void forceRefresh(); }### Answer:
@Test public void forceRefresh() { processor.forceRefresh(); verify( indexAccessorMock ).refresh(); verifyNoOtherIndexInteractionsAndClear(); }
@Test public void error_forceRefresh() { RuntimeException refreshException = new RuntimeException( "Some message" ); doThrow( refreshException ).when( indexAccessorMock ).refresh(); assertThatThrownBy( () -> processor.forceRefresh() ) .isSameAs( refreshException ); verifyNoOtherIndexInteractionsAndClear(); } |
### Question:
GsonHttpEntity implements HttpEntity, HttpAsyncContentProducer { @Override public long getContentLength() { this.contentLengthWasProvided = true; return this.contentLength; } GsonHttpEntity(Gson gson, List<JsonObject> bodyParts); @Override boolean isRepeatable(); @Override boolean isChunked(); @Override long getContentLength(); @Override Header getContentType(); @Override Header getContentEncoding(); @Override InputStream getContent(); @Override void writeTo(OutputStream out); @Override boolean isStreaming(); @Override @SuppressWarnings("deprecation") // javac warns about this method being deprecated, but we have to implement it void consumeContent(); @Override void close(); @Override void produceContent(ContentEncoder encoder, IOControl ioctrl); }### Answer:
@Test public void initialContentLength() { assumeTrue( expectedContentLength < 1024 ); assertThat( gsonEntity.getContentLength() ).isEqualTo( expectedContentLength ); }
@Test public void produceContent_noPushBack() throws IOException { int pushBackPeriod = Integer.MAX_VALUE; for ( int i = 0; i < 2; i++ ) { assertThat( doProduceContent( gsonEntity, pushBackPeriod ) ) .isEqualTo( expectedPayloadString ); assertThat( gsonEntity.getContentLength() ) .isEqualTo( expectedContentLength ); } }
@Test public void produceContent_pushBack_every5Bytes() throws IOException { int pushBackPeriod = 5; for ( int i = 0; i < 2; i++ ) { assertThat( doProduceContent( gsonEntity, pushBackPeriod ) ) .isEqualTo( expectedPayloadString ); assertThat( gsonEntity.getContentLength() ) .isEqualTo( expectedContentLength ); } }
@Test public void produceContent_pushBack_every100Bytes() throws IOException { int pushBackPeriod = 100; for ( int i = 0; i < 2; i++ ) { assertThat( doProduceContent( gsonEntity, pushBackPeriod ) ) .isEqualTo( expectedPayloadString ); assertThat( gsonEntity.getContentLength() ) .isEqualTo( expectedContentLength ); } }
@Test public void produceContent_pushBack_every500Bytes() throws IOException { int pushBackPeriod = 500; for ( int i = 0; i < 2; i++ ) { assertThat( doProduceContent( gsonEntity, pushBackPeriod ) ) .isEqualTo( expectedPayloadString ); assertThat( gsonEntity.getContentLength() ) .isEqualTo( expectedContentLength ); } } |
### Question:
GsonHttpEntity implements HttpEntity, HttpAsyncContentProducer { @Override public Header getContentType() { return CONTENT_TYPE; } GsonHttpEntity(Gson gson, List<JsonObject> bodyParts); @Override boolean isRepeatable(); @Override boolean isChunked(); @Override long getContentLength(); @Override Header getContentType(); @Override Header getContentEncoding(); @Override InputStream getContent(); @Override void writeTo(OutputStream out); @Override boolean isStreaming(); @Override @SuppressWarnings("deprecation") // javac warns about this method being deprecated, but we have to implement it void consumeContent(); @Override void close(); @Override void produceContent(ContentEncoder encoder, IOControl ioctrl); }### Answer:
@Test public void contentType() { Header contentType = gsonEntity.getContentType(); assertThat( contentType.getName() ).isEqualTo( "Content-Type" ); assertThat( contentType.getValue() ).isEqualTo( "application/json; charset=UTF-8" ); } |
### Question:
GsonHttpEntity implements HttpEntity, HttpAsyncContentProducer { @Override public void writeTo(OutputStream out) throws IOException { CountingOutputStream countingStream = new CountingOutputStream( out ); Writer writer = new OutputStreamWriter( countingStream, CHARSET ); for ( JsonObject bodyPart : bodyParts ) { gson.toJson( bodyPart, writer ); writer.append( '\n' ); } writer.flush(); hintContentLength( countingStream.getBytesWritten() ); } GsonHttpEntity(Gson gson, List<JsonObject> bodyParts); @Override boolean isRepeatable(); @Override boolean isChunked(); @Override long getContentLength(); @Override Header getContentType(); @Override Header getContentEncoding(); @Override InputStream getContent(); @Override void writeTo(OutputStream out); @Override boolean isStreaming(); @Override @SuppressWarnings("deprecation") // javac warns about this method being deprecated, but we have to implement it void consumeContent(); @Override void close(); @Override void produceContent(ContentEncoder encoder, IOControl ioctrl); }### Answer:
@Test public void writeTo() throws IOException { for ( int i = 0; i < 2; i++ ) { assertThat( doWriteTo( gsonEntity ) ) .isEqualTo( expectedPayloadString ); assertThat( gsonEntity.getContentLength() ) .isEqualTo( expectedContentLength ); } } |
### Question:
GsonHttpEntity implements HttpEntity, HttpAsyncContentProducer { @Override public InputStream getContent() { return new HttpAsyncContentProducerInputStream( this, BYTE_BUFFER_PAGE_SIZE ); } GsonHttpEntity(Gson gson, List<JsonObject> bodyParts); @Override boolean isRepeatable(); @Override boolean isChunked(); @Override long getContentLength(); @Override Header getContentType(); @Override Header getContentEncoding(); @Override InputStream getContent(); @Override void writeTo(OutputStream out); @Override boolean isStreaming(); @Override @SuppressWarnings("deprecation") // javac warns about this method being deprecated, but we have to implement it void consumeContent(); @Override void close(); @Override void produceContent(ContentEncoder encoder, IOControl ioctrl); }### Answer:
@Test public void getContent() throws IOException { for ( int i = 0; i < 2; i++ ) { assertThat( doGetContent( gsonEntity ) ) .isEqualTo( expectedPayloadString ); assertThat( gsonEntity.getContentLength() ) .isEqualTo( expectedContentLength ); } } |
### Question:
SuppressingCloser extends AbstractCloser<SuppressingCloser, Exception> { public SuppressingCloser pushAll(AutoCloseable ... closeables) { return pushAll( AutoCloseable::close, closeables ); } SuppressingCloser(Throwable mainThrowable); SuppressingCloser push(AutoCloseable closeable); SuppressingCloser pushAll(AutoCloseable ... closeables); SuppressingCloser pushAll(Iterable<? extends AutoCloseable> closeables); }### Answer:
@Test public void iterable() throws IOException { Throwable mainException = new Exception(); IOException exception1 = new IOException(); RuntimeException exception2 = new IllegalStateException(); IOException exception3 = new IOException(); RuntimeException exception4 = new UnsupportedOperationException(); List<Closeable> closeables = Arrays.asList( () -> { throw exception1; }, () -> { throw exception2; }, () -> { throw exception3; }, () -> { throw exception4; } ); new SuppressingCloser( mainException ) .pushAll( closeables ); assertThat( mainException ) .hasSuppressedException( exception1 ) .hasSuppressedException( exception2 ) .hasSuppressedException( exception3 ) .hasSuppressedException( exception4 ); } |
### Question:
SerializationUtil { public static int parseIntegerParameter(String key, String value) { try { return Integer.parseInt( value ); } catch (NumberFormatException e) { throw log.unableToParseJobParameter( key, value, e ); } } private SerializationUtil(); static String serialize(Object object); static Object deserialize(String serialized); static boolean parseBooleanParameterOptional(String key, String value, boolean defaultValue); static int parseIntegerParameter(String key, String value); static Integer parseIntegerParameterOptional(String key, String value, Integer defaultValue); @SuppressWarnings("unchecked") static T parseParameter(@SuppressWarnings("unused") Class<T> type, String key, String value); static CacheMode parseCacheModeParameter(String key, String value, CacheMode defaultValue); }### Answer:
@Test public void deserializeInt_fromInt() throws Exception { int i = SerializationUtil.parseIntegerParameter( "My parameter", "1" ); assertThat( i ).isEqualTo( 1 ); }
@Test public void deserializeInt_fromDouble() throws Exception { thrown.expect( SearchException.class ); thrown.expectMessage( "HSEARCH500029: Unable to parse value '1.0' for job parameter 'My parameter'." ); SerializationUtil.parseIntegerParameter( "My parameter", "1.0" ); }
@Test public void deserializeInt_fromOther() throws Exception { thrown.expect( SearchException.class ); thrown.expectMessage( "HSEARCH500029: Unable to parse value 'foo' for job parameter 'My parameter'." ); SerializationUtil.parseIntegerParameter( "My parameter", "foo" ); }
@Test public void deserializeInt_missing() throws Exception { thrown.expect( SearchException.class ); thrown.expectMessage( "HSEARCH500029: Unable to parse value 'null' for job parameter 'My parameter'." ); SerializationUtil.parseIntegerParameter( "My parameter", null ); } |
### Question:
SerializationUtil { public static Integer parseIntegerParameterOptional(String key, String value, Integer defaultValue) { if ( value == null ) { return defaultValue; } else { return parseIntegerParameter( key, value ); } } private SerializationUtil(); static String serialize(Object object); static Object deserialize(String serialized); static boolean parseBooleanParameterOptional(String key, String value, boolean defaultValue); static int parseIntegerParameter(String key, String value); static Integer parseIntegerParameterOptional(String key, String value, Integer defaultValue); @SuppressWarnings("unchecked") static T parseParameter(@SuppressWarnings("unused") Class<T> type, String key, String value); static CacheMode parseCacheModeParameter(String key, String value, CacheMode defaultValue); }### Answer:
@Test public void deserializeInt_defaultValue() throws Exception { int i = SerializationUtil.parseIntegerParameterOptional( "My parameter", null, 1 ); assertThat( i ).isEqualTo( 1 ); } |
### Question:
SerializationUtil { public static boolean parseBooleanParameterOptional(String key, String value, boolean defaultValue) { if ( value == null ) { return defaultValue; } if ( "true".equalsIgnoreCase( value ) ) { return true; } if ( "false".equalsIgnoreCase( value ) ) { return false; } throw log.unableToParseJobParameter( key, value, null ); } private SerializationUtil(); static String serialize(Object object); static Object deserialize(String serialized); static boolean parseBooleanParameterOptional(String key, String value, boolean defaultValue); static int parseIntegerParameter(String key, String value); static Integer parseIntegerParameterOptional(String key, String value, Integer defaultValue); @SuppressWarnings("unchecked") static T parseParameter(@SuppressWarnings("unused") Class<T> type, String key, String value); static CacheMode parseCacheModeParameter(String key, String value, CacheMode defaultValue); }### Answer:
@Test public void deserializeBoolean_fromLowerCase() throws Exception { boolean t = SerializationUtil.parseBooleanParameterOptional( "My parameter 1", "true", false ); boolean f = SerializationUtil.parseBooleanParameterOptional( "My parameter 2", "false", true ); assertThat( t ).isTrue(); assertThat( f ).isFalse(); }
@Test public void deserializeBoolean_fromUpperCase() throws Exception { boolean t = SerializationUtil.parseBooleanParameterOptional( "My parameter 1", "TRUE", false ); boolean f = SerializationUtil.parseBooleanParameterOptional( "My parameter 2", "FALSE", true ); assertThat( t ).isTrue(); assertThat( f ).isFalse(); }
@Test public void deserializeBoolean_fromIrregularCase() throws Exception { boolean t = SerializationUtil.parseBooleanParameterOptional( "My parameter 1", "TruE", false ); boolean f = SerializationUtil.parseBooleanParameterOptional( "My parameter 2", "FalSe", true ); assertThat( t ).as( "Case should be ignored." ).isTrue(); assertThat( f ).as( "Case should be ignored." ).isFalse(); }
@Test public void deserializeBoolean_fromMissing() throws Exception { boolean t = SerializationUtil.parseBooleanParameterOptional( "My parameter 1", null, true ); boolean f = SerializationUtil.parseBooleanParameterOptional( "My parameter 2", null, false ); assertThat( t ).as( "Default value should be returned." ).isTrue(); assertThat( f ).as( "Default value should be returned." ).isFalse(); }
@Test public void deserializeBoolean_fromOthers() throws Exception { for ( String value : new String[] { "", "0", "1", "t", "f" } ) { try { SerializationUtil.parseBooleanParameterOptional( "My parameter", value, true ); fail(); } catch (SearchException e) { String expectedMsg = "HSEARCH500029: Unable to parse value '" + value + "' for job parameter 'My parameter'."; assertThat( e.getMessage() ).isEqualTo( expectedMsg ); } } } |
### Question:
SimpleGlobPattern { public boolean matches(String candidate) { return matches( candidate, 0 ); } private SimpleGlobPattern(); static SimpleGlobPattern compile(String patternString); boolean matches(String candidate); SimpleGlobPattern prependLiteral(String literal); SimpleGlobPattern prependMany(); Optional<String> toLiteral(); abstract String toPatternString(); }### Answer:
@Test public void matches() { assertSoftly( softly -> { for ( String candidate : expectedMatching ) { softly.assertThat( pattern.matches( candidate ) ) .as( "'" + patternString + "' matches '" + candidate + "'" ) .isTrue(); } for ( String candidate : expectedNonMatching ) { softly.assertThat( pattern.matches( candidate ) ) .as( "'" + patternString + "' matches '" + candidate + "'" ) .isFalse(); } } ); } |
### Question:
ValidationUtil { public static void validateEntityTypes( EntityManagerFactoryRegistry emfRegistry, String entityManagerFactoryScope, String entityManagerFactoryReference, String serializedEntityTypes) { EntityManagerFactory emf = JobContextUtil.getEntityManagerFactory( emfRegistry, entityManagerFactoryScope, entityManagerFactoryReference ); ExtendedSearchIntegrator searchIntegrator = ContextHelper.getSearchIntegratorBySF( emf.unwrap( SessionFactory.class ) ); Set<String> failingTypes = new HashSet<>(); IndexedTypeSet typeIds = searchIntegrator .getIndexedTypeIdentifiers(); Set<String> indexedTypes = new HashSet<>(); for ( IndexedTypeIdentifier typeId : typeIds ) { indexedTypes.add( typeId.getName() ); } for ( String type : serializedEntityTypes.split( "," ) ) { if ( !indexedTypes.contains( type ) ) { failingTypes.add( type ); } } if ( failingTypes.size() > 0 ) { throw log.failingEntityTypes( String.join( ", ", failingTypes ) ); } } private ValidationUtil(); static void validateCheckpointInterval(int checkpointInterval, int rowsPerPartition); static void validateSessionClearInterval(int sessionClearInterval, int checkpointInterval); static void validatePositive(String parameterName, int parameterValue); static void validateEntityTypes(
EntityManagerFactoryRegistry emfRegistry,
String entityManagerFactoryScope,
String entityManagerFactoryReference,
String serializedEntityTypes); }### Answer:
@Test public void validateEntityTypes_whenAllTypesAreAvailableInEMF() throws Exception { String serializedEntityTypes = Stream .of( Company.class, Person.class ) .map( Class::getName ) .collect( Collectors.joining( "," ) ); ValidationUtil.validateEntityTypes( null, EMF_SCOPE, PERSISTENCE_UNIT_NAME, serializedEntityTypes ); }
@Test public void validateEntityTypes_whenContainingNonIndexedTypes() throws Exception { String serializedEntityTypes = Stream .of( Company.class, Person.class, NotIndexed.class ) .map( Class::getName ) .collect( Collectors.joining( "," ) ); thrown.expect( SearchException.class ); thrown.expectMessage( "HSEARCH500032: The following selected entity types aren't indexable: " + NotIndexed.class .getName() + ". Please check if the annotation '@Indexed' has been added to each of them." ); ValidationUtil.validateEntityTypes( null, EMF_SCOPE, PERSISTENCE_UNIT_NAME, serializedEntityTypes ); } |
### Question:
ValidationUtil { public static void validatePositive(String parameterName, int parameterValue) { if ( parameterValue <= 0 ) { throw log.negativeValueOrZero( parameterName, parameterValue ); } } private ValidationUtil(); static void validateCheckpointInterval(int checkpointInterval, int rowsPerPartition); static void validateSessionClearInterval(int sessionClearInterval, int checkpointInterval); static void validatePositive(String parameterName, int parameterValue); static void validateEntityTypes(
EntityManagerFactoryRegistry emfRegistry,
String entityManagerFactoryScope,
String entityManagerFactoryReference,
String serializedEntityTypes); }### Answer:
@Test(expected = SearchException.class) public void validatePositive_valueIsNegative() throws Exception { ValidationUtil.validatePositive( "MyParameter", -1 ); }
@Test(expected = SearchException.class) public void validatePositive_valueIsZero() throws Exception { ValidationUtil.validatePositive( "MyParameter", 0 ); }
@Test public void validatePositive_valueIsPositive() throws Exception { ValidationUtil.validatePositive( "MyParameter", 1 ); } |
### Question:
ValidationUtil { public static void validateCheckpointInterval(int checkpointInterval, int rowsPerPartition) { if ( checkpointInterval > rowsPerPartition ) { throw log.illegalCheckpointInterval( checkpointInterval, rowsPerPartition ); } } private ValidationUtil(); static void validateCheckpointInterval(int checkpointInterval, int rowsPerPartition); static void validateSessionClearInterval(int sessionClearInterval, int checkpointInterval); static void validatePositive(String parameterName, int parameterValue); static void validateEntityTypes(
EntityManagerFactoryRegistry emfRegistry,
String entityManagerFactoryScope,
String entityManagerFactoryReference,
String serializedEntityTypes); }### Answer:
@Test public void validateCheckpointInterval_lessThanRowsPerPartition() throws Exception { ValidationUtil.validateCheckpointInterval( 99, 100 ); }
@Test public void validateCheckpointInterval_equalToRowsPerPartition() { ValidationUtil.validateCheckpointInterval( 100, 100 ); }
@Test(expected = SearchException.class) public void validateCheckpointInterval_greaterThanRowsPerPartition() throws Exception { ValidationUtil.validateCheckpointInterval( 101, 100 ); } |
### Question:
SimpleGlobPattern { public abstract String toPatternString(); private SimpleGlobPattern(); static SimpleGlobPattern compile(String patternString); boolean matches(String candidate); SimpleGlobPattern prependLiteral(String literal); SimpleGlobPattern prependMany(); Optional<String> toLiteral(); abstract String toPatternString(); }### Answer:
@Test public void toPatternString() { assertThat( pattern.toPatternString() ).isEqualTo( expectedToPatternString ); } |
### Question:
ValidationUtil { public static void validateSessionClearInterval(int sessionClearInterval, int checkpointInterval) { if ( sessionClearInterval > checkpointInterval ) { throw log.illegalSessionClearInterval( sessionClearInterval, checkpointInterval ); } } private ValidationUtil(); static void validateCheckpointInterval(int checkpointInterval, int rowsPerPartition); static void validateSessionClearInterval(int sessionClearInterval, int checkpointInterval); static void validatePositive(String parameterName, int parameterValue); static void validateEntityTypes(
EntityManagerFactoryRegistry emfRegistry,
String entityManagerFactoryScope,
String entityManagerFactoryReference,
String serializedEntityTypes); }### Answer:
@Test public void validateSessionClearInterval_lessThanCheckpointInterval() throws Exception { ValidationUtil.validateSessionClearInterval( 99, 100 ); }
@Test public void validateSessionClearInterval_equalToCheckpointInterval() { ValidationUtil.validateSessionClearInterval( 100, 100 ); }
@Test(expected = SearchException.class) public void validateSessionClearInterval_greaterThanCheckpointInterval() throws Exception { ValidationUtil.validateSessionClearInterval( 101, 100 ); } |
### Question:
TypePatternMatcherFactory { public TypePatternMatcher createExactRawTypeMatcher(Class<?> exactTypeToMatch) { PojoRawTypeModel<?> exactTypeToMatchModel = introspector.typeModel( exactTypeToMatch ); return new ExactRawTypeMatcher( exactTypeToMatchModel ); } TypePatternMatcherFactory(PojoBootstrapIntrospector introspector); TypePatternMatcher createExactRawTypeMatcher(Class<?> exactTypeToMatch); TypePatternMatcher createRawSuperTypeMatcher(Class<?> superTypeToMatch); ExtractingTypePatternMatcher createExtractingMatcher(Type typePattern, Type typeToExtract); }### Answer:
@Test public void exactType() { PojoRawTypeModel typeToMatchMock = mock( PojoRawTypeModel.class ); PojoGenericTypeModel typeToInspectMock = mock( PojoGenericTypeModel.class ); PojoRawTypeModel typeToInspectRawTypeMock = mock( PojoRawTypeModel.class ); when( introspectorMock.typeModel( String.class ) ) .thenReturn( typeToMatchMock ); TypePatternMatcher matcher = factory.createExactRawTypeMatcher( String.class ); assertThat( matcher ).isNotNull(); when( typeToMatchMock.name() ) .thenReturn( "THE_TYPE_TO_MATCH" ); assertThat( matcher.toString() ) .isEqualTo( "hasExactRawType(THE_TYPE_TO_MATCH)" ); when( typeToInspectMock.rawType() ) .thenReturn( typeToInspectRawTypeMock ); when( typeToMatchMock.isSubTypeOf( typeToInspectRawTypeMock ) ) .thenReturn( true ); when( typeToInspectRawTypeMock.isSubTypeOf( typeToMatchMock ) ) .thenReturn( true ); assertThat( matcher.matches( typeToInspectMock ) ).isTrue(); when( typeToMatchMock.isSubTypeOf( typeToInspectRawTypeMock ) ) .thenReturn( false ); when( typeToInspectRawTypeMock.isSubTypeOf( typeToMatchMock ) ) .thenReturn( true ); assertThat( matcher.matches( typeToInspectMock ) ).isFalse(); when( typeToMatchMock.isSubTypeOf( typeToInspectRawTypeMock ) ) .thenReturn( true ); when( typeToInspectRawTypeMock.isSubTypeOf( typeToMatchMock ) ) .thenReturn( false ); assertThat( matcher.matches( typeToInspectMock ) ).isFalse(); when( typeToMatchMock.isSubTypeOf( typeToInspectRawTypeMock ) ) .thenReturn( false ); when( typeToInspectRawTypeMock.isSubTypeOf( typeToMatchMock ) ) .thenReturn( false ); assertThat( matcher.matches( typeToInspectMock ) ).isFalse(); } |
### Question:
SimpleGlobPattern { public Optional<String> toLiteral() { return Optional.empty(); } private SimpleGlobPattern(); static SimpleGlobPattern compile(String patternString); boolean matches(String candidate); SimpleGlobPattern prependLiteral(String literal); SimpleGlobPattern prependMany(); Optional<String> toLiteral(); abstract String toPatternString(); }### Answer:
@Test public void toLiteral() { assertThat( pattern.toLiteral() ).isEqualTo( expectedToLiteral ); } |
### Question:
CancellableExecutionCompletableFuture extends CompletableFuture<T> { @Override public boolean cancel(boolean mayInterruptIfRunning) { super.cancel( mayInterruptIfRunning ); return future.cancel( mayInterruptIfRunning ); } CancellableExecutionCompletableFuture(Runnable runnable, ExecutorService executor); @Override boolean cancel(boolean mayInterruptIfRunning); }### Answer:
@Test public void runnable_cancel() throws InterruptedException { AtomicBoolean started = new AtomicBoolean( false ); AtomicBoolean finished = new AtomicBoolean( false ); CompletableFuture<Void> future = new CancellableExecutionCompletableFuture<>( () -> { started.set( true ); try { Thread.sleep( Long.MAX_VALUE ); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException( e ); } finally { finished.set( true ); } }, executorService ); Awaitility.await().untilTrue( started ); Awaitility.await().untilAsserted( () -> assertThat( future.cancel( true ) ).isTrue() ); Awaitility.await().until( future::isDone ); assertThatFuture( future ).isCancelled(); Awaitility.await().untilTrue( finished ); Awaitility.await().untilAsserted( () -> assertThat( Futures.getThrowableNow( future ) ) .extracting( Throwable::getSuppressed ).asInstanceOf( InstanceOfAssertFactories.ARRAY ) .hasSize( 1 ) .extracting( Function.identity() ) .first() .asInstanceOf( InstanceOfAssertFactories.THROWABLE ) .isInstanceOf( RuntimeException.class ) .hasCauseInstanceOf( InterruptedException.class ) ); } |
### Question:
PojoModelPath { public static PojoModelPathPropertyNode ofProperty(String propertyName) { return new PojoModelPathPropertyNode( null, propertyName ); } PojoModelPath(); static Builder builder(); static PojoModelPathPropertyNode ofProperty(String propertyName); static PojoModelPathValueNode ofValue(String propertyName); static PojoModelPathValueNode ofValue(String propertyName, ContainerExtractorPath extractorPath); static PojoModelPathValueNode parse(String dotSeparatedPath); @Override String toString(); final String toPathString(); abstract PojoModelPath parent(); @Deprecated PojoModelPath getParent(); }### Answer:
@Test public void ofProperty() { assertThat( PojoModelPath.ofProperty( "foo" ) ) .satisfies( isPath( "foo" ) ); assertThatThrownBy( () -> PojoModelPath.ofProperty( null ) ) .isInstanceOf( IllegalArgumentException.class ); assertThatThrownBy( () -> PojoModelPath.ofProperty( "" ) ) .isInstanceOf( IllegalArgumentException.class ); } |
### Question:
Closer extends AbstractCloser<Closer<E>, E> implements AutoCloseable { public <E2 extends Exception> Closer<E2> split() { return new Closer<>( state ); } Closer(); private Closer(CloseableState state); Closer<E2> split(); @Override void close(); }### Answer:
@Test public void split() { MyException1 exception1 = new MyException1(); MyException2 exception2 = new MyException2(); IOException exception3 = new IOException(); assertThatThrownBy( () -> { try ( Closer<IOException> closer1 = new Closer<>(); Closer<MyException1> closer2 = closer1.split(); Closer<MyException2> closer3 = closer1.split() ) { closer2.push( ignored -> { throw exception1; }, new Object() ); closer3.push( ignored -> { throw exception2; }, new Object() ); closer1.push( ignored -> { throw exception3; }, new Object() ); } } ) .isSameAs( exception1 ) .hasSuppressedException( exception2 ) .hasSuppressedException( exception3 ); }
@Test public void split_transitive() { MyException1 exception1 = new MyException1(); MyException2 exception2 = new MyException2(); IOException exception3 = new IOException(); assertThatThrownBy( () -> { try ( Closer<IOException> closer1 = new Closer<>(); Closer<MyException1> closer2 = closer1.split(); Closer<MyException2> closer3 = closer2.split() ) { closer2.push( ignored -> { throw exception1; }, new Object() ); closer3.push( ignored -> { throw exception2; }, new Object() ); closer1.push( ignored -> { throw exception3; }, new Object() ); } } ) .isSameAs( exception1 ) .hasSuppressedException( exception2 ) .hasSuppressedException( exception3 ); } |
### Question:
PojoModelPath { public static PojoModelPathValueNode ofValue(String propertyName) { return ofValue( propertyName, ContainerExtractorPath.defaultExtractors() ); } PojoModelPath(); static Builder builder(); static PojoModelPathPropertyNode ofProperty(String propertyName); static PojoModelPathValueNode ofValue(String propertyName); static PojoModelPathValueNode ofValue(String propertyName, ContainerExtractorPath extractorPath); static PojoModelPathValueNode parse(String dotSeparatedPath); @Override String toString(); final String toPathString(); abstract PojoModelPath parent(); @Deprecated PojoModelPath getParent(); }### Answer:
@Test public void ofValue_property() { assertThat( PojoModelPath.ofValue( "foo" ) ) .satisfies( isPath( "foo", ContainerExtractorPath.defaultExtractors() ) ); assertThatThrownBy( () -> PojoModelPath.ofValue( null ) ) .isInstanceOf( IllegalArgumentException.class ); assertThatThrownBy( () -> PojoModelPath.ofValue( "" ) ) .isInstanceOf( IllegalArgumentException.class ); }
@Test public void ofValue_propertyAndContainerExtractorPath() { assertThat( PojoModelPath.ofValue( "foo", ContainerExtractorPath.explicitExtractor( BuiltinContainerExtractors.MAP_KEY ) ) ) .satisfies( isPath( "foo", ContainerExtractorPath.explicitExtractor( BuiltinContainerExtractors.MAP_KEY ) ) ); assertThatThrownBy( () -> PojoModelPath.ofValue( null, ContainerExtractorPath.explicitExtractor( BuiltinContainerExtractors.MAP_KEY ) ) ) .isInstanceOf( IllegalArgumentException.class ); assertThatThrownBy( () -> PojoModelPath.ofValue( "", ContainerExtractorPath.explicitExtractor( BuiltinContainerExtractors.MAP_KEY ) ) ) .isInstanceOf( IllegalArgumentException.class ); assertThatThrownBy( () -> PojoModelPath.ofValue( "foo", null ) ) .isInstanceOf( IllegalArgumentException.class ); } |
### Question:
PojoModelPath { public static PojoModelPathValueNode parse(String dotSeparatedPath) { Contracts.assertNotNullNorEmpty( dotSeparatedPath, "dotSeparatedPath" ); Builder builder = builder(); for ( String propertyName : DOT_PATTERN.split( dotSeparatedPath, -1 ) ) { builder.property( propertyName ).valueWithDefaultExtractors(); } return builder.toValuePath(); } PojoModelPath(); static Builder builder(); static PojoModelPathPropertyNode ofProperty(String propertyName); static PojoModelPathValueNode ofValue(String propertyName); static PojoModelPathValueNode ofValue(String propertyName, ContainerExtractorPath extractorPath); static PojoModelPathValueNode parse(String dotSeparatedPath); @Override String toString(); final String toPathString(); abstract PojoModelPath parent(); @Deprecated PojoModelPath getParent(); }### Answer:
@Test public void parse() { assertThat( PojoModelPath.parse( "foo" ) ) .satisfies( isPath( "foo", ContainerExtractorPath.defaultExtractors() ) ); assertThat( PojoModelPath.parse( "foo.bar" ) ) .satisfies( isPath( "foo", ContainerExtractorPath.defaultExtractors(), "bar", ContainerExtractorPath.defaultExtractors() ) ); assertThatThrownBy( () -> PojoModelPath.parse( null ) ) .isInstanceOf( IllegalArgumentException.class ); assertThatThrownBy( () -> PojoModelPath.parse( "" ) ) .isInstanceOf( IllegalArgumentException.class ); assertThatThrownBy( () -> PojoModelPath.parse( "foo..bar" ) ) .isInstanceOf( IllegalArgumentException.class ); assertThatThrownBy( () -> PojoModelPath.parse( "foo." ) ) .isInstanceOf( IllegalArgumentException.class ); } |
### Question:
BackendSettings { public static String backendKey(String radical) { return join( ".", EngineSettings.BACKEND, radical ); } private BackendSettings(); static String backendKey(String radical); static String backendKey(String backendName, String radical); static final String TYPE; @Deprecated
static final String INDEX_DEFAULTS; static final String INDEXES; }### Answer:
@Test public void backendKey() { assertThat( BackendSettings.backendKey( "foo.bar" ) ) .isEqualTo( "hibernate.search.backend.foo.bar" ); assertThat( BackendSettings.backendKey( "myBackend", "foo.bar" ) ) .isEqualTo( "hibernate.search.backends.myBackend.foo.bar" ); assertThat( BackendSettings.backendKey( null, "foo.bar" ) ) .isEqualTo( "hibernate.search.backend.foo.bar" ); } |
### Question:
IndexSettings { public static String indexKey(String indexName, String radical) { return join( ".", EngineSettings.BACKEND, BackendSettings.INDEXES, indexName, radical ); } private IndexSettings(); @Deprecated static String indexDefaultsKey(String radical); static String indexKey(String indexName, String radical); @Deprecated static String indexDefaultsKey(String backendName, String radical); static String indexKey(String backendName, String indexName, String radical); }### Answer:
@Test public void indexKey() { assertThat( IndexSettings.indexKey( "indexName", "foo.bar" ) ) .isEqualTo( "hibernate.search.backend.indexes.indexName.foo.bar" ); assertThat( IndexSettings.indexKey( "backendName", "indexName", "foo.bar" ) ) .isEqualTo( "hibernate.search.backends.backendName.indexes.indexName.foo.bar" ); assertThat( IndexSettings.indexKey( null, "indexName", "foo.bar" ) ) .isEqualTo( "hibernate.search.backend.indexes.indexName.foo.bar" ); } |
### Question:
IndexSettings { @Deprecated public static String indexDefaultsKey(String radical) { return join( ".", EngineSettings.BACKEND, BackendSettings.INDEX_DEFAULTS, radical ); } private IndexSettings(); @Deprecated static String indexDefaultsKey(String radical); static String indexKey(String indexName, String radical); @Deprecated static String indexDefaultsKey(String backendName, String radical); static String indexKey(String backendName, String indexName, String radical); }### Answer:
@Test @SuppressWarnings("deprecation") public void indexDefaultsKey() { assertThat( IndexSettings.indexDefaultsKey( "foo.bar" ) ) .isEqualTo( "hibernate.search.backend.index_defaults.foo.bar" ); assertThat( IndexSettings.indexDefaultsKey( "backendName", "foo.bar" ) ) .isEqualTo( "hibernate.search.backends.backendName.index_defaults.foo.bar" ); assertThat( IndexSettings.indexDefaultsKey( null, "foo.bar" ) ) .isEqualTo( "hibernate.search.backend.index_defaults.foo.bar" ); } |
### Question:
ParseUtils { public static GeoPoint parseGeoPoint(String value) { String[] split = value.split( GEO_POINT_SEPARATOR ); if ( split.length != 2 ) { throw log.unableToParseGeoPoint( value ); } try { return GeoPoint.of( Double.parseDouble( split[0] ), Double.parseDouble( split[1] ) ); } catch (NumberFormatException e) { throw log.unableToParseGeoPoint( value ); } } private ParseUtils(); static String parseString(String value); static Instant parseInstant(String value); static LocalDate parseLocalDate(String value); static LocalDateTime parseLocalDateTime(String value); static LocalTime parseLocalTime(String value); static OffsetDateTime parseOffsetDateTime(String value); static OffsetTime parseOffsetTime(String value); static ZonedDateTime parseZonedDateTime(String value); static Year parseYear(String value); static YearMonth parseYearMonth(String value); static MonthDay parseMonthDay(String value); static ZoneOffset parseZoneOffset(String value); static Period parsePeriod(String value); static Duration parseDuration(String value); static GeoPoint parseGeoPoint(String value); }### Answer:
@Test public void parseGeoPoint() { GeoPoint geoPoint = ParseUtils.parseGeoPoint( "12.123, -24.234" ); assertThat( geoPoint ).isEqualTo( GeoPoint.of( 12.123, -24.234 ) ); geoPoint = ParseUtils.parseGeoPoint( "12.123,-24.234" ); assertThat( geoPoint ).isEqualTo( GeoPoint.of( 12.123, -24.234 ) ); geoPoint = ParseUtils.parseGeoPoint( "12.123, -24.234" ); assertThat( geoPoint ).isEqualTo( GeoPoint.of( 12.123, -24.234 ) ); assertThatThrownBy( () -> ParseUtils.parseGeoPoint( "12.123#-24.234" ) ) .hasMessage( "HSEARCH000564: Unable to parse the provided geo-point value: '12.123#-24.234'. The expected format is latitude, longitude." ); assertThatThrownBy( () -> ParseUtils.parseGeoPoint( "12.123" ) ) .hasMessage( "HSEARCH000564: Unable to parse the provided geo-point value: '12.123'. The expected format is latitude, longitude." ); } |
### Question:
FailSafeFailureHandlerWrapper implements FailureHandler { @Override public void handle(FailureContext context) { try { delegate.handle( context ); } catch (Throwable t) { log.failureInFailureHandler( t ); } } FailSafeFailureHandlerWrapper(FailureHandler delegate); @Override void handle(FailureContext context); @Override void handle(EntityIndexingFailureContext context); }### Answer:
@Test public void genericContext_runtimeException() { RuntimeException runtimeException = new SimulatedRuntimeException(); logged.expectEvent( Level.ERROR, sameInstance( runtimeException ), "failure handler threw an exception" ); doThrow( runtimeException ).when( failureHandlerMock ).handle( any( FailureContext.class ) ); wrapper.handle( FailureContext.builder().build() ); verifyNoMoreInteractions( failureHandlerMock ); }
@Test public void genericContext_error() { Error error = new SimulatedError(); logged.expectEvent( Level.ERROR, sameInstance( error ), "failure handler threw an exception" ); doThrow( error ).when( failureHandlerMock ).handle( any( FailureContext.class ) ); wrapper.handle( FailureContext.builder().build() ); verifyNoMoreInteractions( failureHandlerMock ); }
@Test public void entityIndexingContext_runtimeException() { RuntimeException runtimeException = new SimulatedRuntimeException(); logged.expectEvent( Level.ERROR, sameInstance( runtimeException ), "failure handler threw an exception" ); doThrow( runtimeException ).when( failureHandlerMock ).handle( any( EntityIndexingFailureContext.class ) ); wrapper.handle( EntityIndexingFailureContext.builder().build() ); verifyNoMoreInteractions( failureHandlerMock ); }
@Test public void entityIndexingContext_error() { Error error = new SimulatedError(); logged.expectEvent( Level.ERROR, sameInstance( error ), "failure handler threw an exception" ); doThrow( error ).when( failureHandlerMock ).handle( any( EntityIndexingFailureContext.class ) ); wrapper.handle( EntityIndexingFailureContext.builder().build() ); verifyNoMoreInteractions( failureHandlerMock ); } |
### Question:
IndexManagerBuildingStateHolder { void createBackends(Set<Optional<String>> backendNames) { for ( Optional<String> backendNameOptional : backendNames ) { String backendName = backendNameOptional.orElse( defaultBackendName ); EventContext eventContext = EventContexts.fromBackendName( backendName ); BackendInitialBuildState backendBuildState; try { backendBuildState = createBackend( backendNameOptional, eventContext ); } catch (RuntimeException e) { rootBuildContext.getFailureCollector().withContext( eventContext ).add( e ); continue; } backendBuildStateByName.put( backendName, backendBuildState ); } } IndexManagerBuildingStateHolder(BeanResolver beanResolver, ConfigurationPropertySource propertySource,
RootBuildContext rootBuildContext); }### Answer:
@Test public void error_missingBackendType_nullType() { String keyPrefix = "somePrefix."; ArgumentCaptor<Throwable> throwableCaptor = ArgumentCaptor.forClass( Throwable.class ); when( configurationSourceMock.get( "default_backend" ) ) .thenReturn( (Optional) Optional.empty() ); IndexManagerBuildingStateHolder holder = new IndexManagerBuildingStateHolder( beanResolverMock, configurationSourceMock, rootBuildContextMock ); verifyNoOtherBackendInteractionsAndReset(); when( configurationSourceMock.get( "backend.type" ) ) .thenReturn( Optional.empty() ); when( beanResolverMock.namedConfiguredForRole( BackendFactory.class ) ) .thenReturn( Collections.emptyMap() ); when( configurationSourceMock.resolve( "backend.type" ) ) .thenReturn( Optional.of( keyPrefix + "backend.type" ) ); when( rootBuildContextMock.getFailureCollector() ) .thenReturn( rootFailureCollectorMock ); when( rootFailureCollectorMock.withContext( EventContexts.defaultBackend() ) ) .thenReturn( backendFailureCollectorMock ); holder.createBackends( CollectionHelper.asSet( Optional.empty() ) ); verify( backendFailureCollectorMock ).add( throwableCaptor.capture() ); verifyNoOtherBackendInteractionsAndReset(); assertThat( throwableCaptor.getValue() ) .isInstanceOf( SearchException.class ) .hasMessageContainingAll( "Configuration property 'somePrefix.backend.type' is not set, and no backend was found in the classpath", "Did you forget to add the desired backend to your project's dependencies?" ); }
@Test public void error_missingBackendType_emptyType() { String keyPrefix = "somePrefix."; ArgumentCaptor<Throwable> throwableCaptor = ArgumentCaptor.forClass( Throwable.class ); when( configurationSourceMock.get( "default_backend" ) ) .thenReturn( (Optional) Optional.empty() ); IndexManagerBuildingStateHolder holder = new IndexManagerBuildingStateHolder( beanResolverMock, configurationSourceMock, rootBuildContextMock ); verifyNoOtherBackendInteractionsAndReset(); when( configurationSourceMock.get( "backend.type" ) ) .thenReturn( (Optional) Optional.of( "" ) ); when( beanResolverMock.namedConfiguredForRole( BackendFactory.class ) ) .thenReturn( Collections.emptyMap() ); when( configurationSourceMock.resolve( "backend.type" ) ) .thenReturn( Optional.of( keyPrefix + "backend.type" ) ); when( rootBuildContextMock.getFailureCollector() ) .thenReturn( rootFailureCollectorMock ); when( rootFailureCollectorMock.withContext( EventContexts.defaultBackend() ) ) .thenReturn( backendFailureCollectorMock ); holder.createBackends( CollectionHelper.asSet( Optional.empty() ) ); verify( backendFailureCollectorMock ).add( throwableCaptor.capture() ); verifyNoOtherBackendInteractionsAndReset(); assertThat( throwableCaptor.getValue() ) .isInstanceOf( SearchException.class ) .hasMessageContainingAll( "Configuration property 'somePrefix.backend.type' is not set, and no backend was found in the classpath", "Did you forget to add the desired backend to your project's dependencies?" ); } |
### Question:
AvroSchemaIterator implements Iterable<Schema>,
Iterator<Schema> { @Override public Iterator<Schema> iterator() { return this; } AvroSchemaIterator(Schema rootSchema); @Override Iterator<Schema> iterator(); @Override boolean hasNext(); @Override Schema next(); }### Answer:
@Test public void testIterator() { Schema sample = AvroSchemaGeneratorTest.getSampleSchema(); boolean baseSeen = false, recursiveSeen = false, compositeSeen = false, arraySeen = false, mapSeen = false; for (Schema schema : new AvroSchemaIterator(sample)) { if (schema.getName().equals("SampleBaseType")) { baseSeen = true; } if (schema.getName().equals("SampleRecursiveType")) { recursiveSeen = true; } if (schema.getName().equals("SampleCompositeType")) { compositeSeen = true; } } assertTrue(baseSeen); assertTrue(recursiveSeen); assertTrue(compositeSeen); } |
### Question:
CompositeKey { public static CompositeKey parseCompositeKey(final String compositeKey) { if (compositeKey == null) { return null; } if (!compositeKey.startsWith(NAMESPACE)) { throw CompositeKeyFormatException.forInputString(compositeKey, compositeKey, 0); } final String[] segments = compositeKey.split(DELIMITER, 0); return new CompositeKey(segments[1], Arrays.stream(segments).skip(2).toArray(String[]::new)); } CompositeKey(final String objectType, final String... attributes); CompositeKey(final String objectType, final List<String> attributes); String getObjectType(); List<String> getAttributes(); @Override String toString(); static CompositeKey parseCompositeKey(final String compositeKey); static void validateSimpleKeys(final String... keys); static final String NAMESPACE; }### Answer:
@Test public void testParseCompositeKey() { final CompositeKey key = CompositeKey.parseCompositeKey("\u0000abc\u0000def\u0000ghi\u0000jkl\u0000mno\u0000"); assertThat(key.getObjectType(), is(equalTo("abc"))); assertThat(key.getAttributes(), hasSize(4)); assertThat(key.getAttributes(), contains("def", "ghi", "jkl", "mno")); assertThat(key.toString(), is(equalTo("\u0000abc\u0000def\u0000ghi\u0000jkl\u0000mno\u0000"))); }
@Test(expected = CompositeKeyFormatException.class) public void testParseCompositeKeyInvalidObjectType() { CompositeKey.parseCompositeKey("ab\udbff\udfffc\u0000def\u0000ghi\u0000jkl\u0000mno\u0000"); }
@Test(expected = CompositeKeyFormatException.class) public void testParseCompositeKeyInvalidAttribute() { CompositeKey.parseCompositeKey("abc\u0000def\u0000ghi\u0000jk\udbff\udfffl\u0000mno\u0000"); } |
### Question:
StateBasedEndorsementImpl implements StateBasedEndorsement { @Override public void addOrgs(final RoleType role, final String... organizations) { MSPRoleType mspRole; if (RoleType.RoleTypeMember.equals(role)) { mspRole = MSPRoleType.MEMBER; } else { mspRole = MSPRoleType.PEER; } for (final String neworg : organizations) { orgs.put(neworg, mspRole); } } StateBasedEndorsementImpl(final byte[] ep); @Override byte[] policy(); @Override void addOrgs(final RoleType role, final String... organizations); @Override void delOrgs(final String... organizations); @Override List<String> listOrgs(); }### Answer:
@Test public void addOrgs() { final StateBasedEndorsement ep = StateBasedEndorsementFactory.getInstance().newStateBasedEndorsement(null); ep.addOrgs(RoleType.RoleTypePeer, "Org1"); final byte[] epBytes = ep.policy(); assertThat(epBytes, is(not(nullValue()))); assertTrue(epBytes.length > 0); final byte[] expectedEPBytes = StateBasedEndorsementUtils.signedByFabricEntity("Org1", MSPRoleType.PEER).toByteString().toByteArray(); assertArrayEquals(expectedEPBytes, epBytes); } |
### Question:
StateBasedEndorsementImpl implements StateBasedEndorsement { @Override public void delOrgs(final String... organizations) { for (final String delorg : organizations) { orgs.remove(delorg); } } StateBasedEndorsementImpl(final byte[] ep); @Override byte[] policy(); @Override void addOrgs(final RoleType role, final String... organizations); @Override void delOrgs(final String... organizations); @Override List<String> listOrgs(); }### Answer:
@Test public void delOrgs() { final byte[] initEPBytes = StateBasedEndorsementUtils.signedByFabricEntity("Org1", MSPRoleType.PEER).toByteString().toByteArray(); final StateBasedEndorsement ep = StateBasedEndorsementFactory.getInstance().newStateBasedEndorsement(initEPBytes); final List<String> listOrgs = ep.listOrgs(); assertThat(listOrgs, is(not(nullValue()))); assertThat(listOrgs, contains("Org1")); assertThat(listOrgs, hasSize(1)); ep.addOrgs(RoleType.RoleTypeMember, "Org2"); ep.delOrgs("Org1"); final byte[] epBytes = ep.policy(); assertThat(epBytes, is(not(nullValue()))); assertTrue(epBytes.length > 0); final byte[] expectedEPBytes = StateBasedEndorsementUtils.signedByFabricEntity("Org2", MSPRoleType.MEMBER).toByteString().toByteArray(); assertArrayEquals(expectedEPBytes, epBytes); } |
### Question:
StateBasedEndorsementImpl implements StateBasedEndorsement { @Override public List<String> listOrgs() { final List<String> res = new ArrayList<>(); res.addAll(orgs.keySet()); return res; } StateBasedEndorsementImpl(final byte[] ep); @Override byte[] policy(); @Override void addOrgs(final RoleType role, final String... organizations); @Override void delOrgs(final String... organizations); @Override List<String> listOrgs(); }### Answer:
@Test public void listOrgs() { final byte[] initEPBytes = StateBasedEndorsementUtils.signedByFabricEntity("Org1", MSPRoleType.PEER).toByteString().toByteArray(); final StateBasedEndorsement ep = StateBasedEndorsementFactory.getInstance().newStateBasedEndorsement(initEPBytes); final List<String> listOrgs = ep.listOrgs(); assertThat(listOrgs, is(not(nullValue()))); assertThat(listOrgs, hasSize(1)); assertThat(listOrgs, contains("Org1")); } |
### Question:
StateBasedEndorsementFactory { public static synchronized StateBasedEndorsementFactory getInstance() { if (instance == null) { instance = new StateBasedEndorsementFactory(); } return instance; } static synchronized StateBasedEndorsementFactory getInstance(); StateBasedEndorsement newStateBasedEndorsement(final byte[] ep); }### Answer:
@Test public void getInstance() { assertNotNull(StateBasedEndorsementFactory.getInstance()); assertTrue(StateBasedEndorsementFactory.getInstance() instanceof StateBasedEndorsementFactory); } |
### Question:
StateBasedEndorsementFactory { public StateBasedEndorsement newStateBasedEndorsement(final byte[] ep) { return new StateBasedEndorsementImpl(ep); } static synchronized StateBasedEndorsementFactory getInstance(); StateBasedEndorsement newStateBasedEndorsement(final byte[] ep); }### Answer:
@Test public void newStateBasedEndorsement() { assertNotNull(StateBasedEndorsementFactory.getInstance().newStateBasedEndorsement(new byte[] {})); thrown.expect(IllegalArgumentException.class); StateBasedEndorsementFactory.getInstance().newStateBasedEndorsement(new byte[] {0}); } |
### Question:
KeyValueImpl implements KeyValue { KeyValueImpl(final KV kv) { this.key = kv.getKey(); this.value = kv.getValue(); } KeyValueImpl(final KV kv); @Override String getKey(); @Override byte[] getValue(); @Override String getStringValue(); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer:
@Test public void testKeyValueImpl() { new KeyValueImpl(KV.newBuilder() .setKey("key") .setValue(ByteString.copyFromUtf8("value")) .build()); } |
### Question:
KeyValueImpl implements KeyValue { @Override public String getKey() { return key; } KeyValueImpl(final KV kv); @Override String getKey(); @Override byte[] getValue(); @Override String getStringValue(); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer:
@Test public void testGetKey() { final KeyValueImpl kv = new KeyValueImpl(KV.newBuilder() .setKey("key") .setValue(ByteString.copyFromUtf8("value")) .build()); assertThat(kv.getKey(), is(equalTo("key"))); } |
### Question:
MyAssetContract implements ContractInterface { @Transaction() public void deleteMyAsset(Context ctx, String myAssetId) { boolean exists = myAssetExists(ctx,myAssetId); if (!exists) { throw new RuntimeException("The asset "+myAssetId+" does not exist"); } ctx.getStub().delState(myAssetId); } MyAssetContract(); @Transaction() boolean myAssetExists(Context ctx, String myAssetId); @Transaction() void createMyAsset(Context ctx, String myAssetId, String value); @Transaction() MyAsset readMyAsset(Context ctx, String myAssetId); @Transaction() void updateMyAsset(Context ctx, String myAssetId, String newValue); @Transaction() void deleteMyAsset(Context ctx, String myAssetId); }### Answer:
@Test public void assetDelete() { MyAssetContract contract = new MyAssetContract(); Context ctx = mock(Context.class); ChaincodeStub stub = mock(ChaincodeStub.class); when(ctx.getStub()).thenReturn(stub); when(stub.getState("10001")).thenReturn(null); Exception thrown = assertThrows(RuntimeException.class, () -> { contract.deleteMyAsset(ctx, "10001"); }); assertEquals(thrown.getMessage(), "The asset 10001 does not exist"); } |
### Question:
KeyValueImpl implements KeyValue { @Override public byte[] getValue() { return value.toByteArray(); } KeyValueImpl(final KV kv); @Override String getKey(); @Override byte[] getValue(); @Override String getStringValue(); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer:
@Test public void testGetValue() { final KeyValueImpl kv = new KeyValueImpl(KV.newBuilder() .setKey("key") .setValue(ByteString.copyFromUtf8("value")) .build()); assertThat(kv.getValue(), is(equalTo("value".getBytes(UTF_8)))); } |
### Question:
KeyValueImpl implements KeyValue { @Override public String getStringValue() { return value.toStringUtf8(); } KeyValueImpl(final KV kv); @Override String getKey(); @Override byte[] getValue(); @Override String getStringValue(); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer:
@Test public void testGetStringValue() { final KeyValueImpl kv = new KeyValueImpl(KV.newBuilder() .setKey("key") .setValue(ByteString.copyFromUtf8("value")) .build()); assertThat(kv.getStringValue(), is(equalTo("value"))); } |
### Question:
KeyValueImpl implements KeyValue { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } KeyValueImpl(final KV kv); @Override String getKey(); @Override byte[] getValue(); @Override String getStringValue(); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer:
@Test public void testHashCode() { final KeyValueImpl kv = new KeyValueImpl(KV.newBuilder() .build()); int expectedHashCode = 31; expectedHashCode = expectedHashCode + "".hashCode(); expectedHashCode = expectedHashCode * 31 + ByteString.copyFromUtf8("").hashCode(); assertEquals("Wrong hashcode", expectedHashCode, kv.hashCode()); } |
### Question:
KeyValueImpl implements KeyValue { @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final KeyValueImpl other = (KeyValueImpl) obj; if (!key.equals(other.key)) { return false; } if (!value.equals(other.value)) { return false; } return true; } KeyValueImpl(final KV kv); @Override String getKey(); @Override byte[] getValue(); @Override String getStringValue(); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer:
@Test public void testEquals() { final KeyValueImpl kv1 = new KeyValueImpl(KV.newBuilder() .setKey("a") .setValue(ByteString.copyFromUtf8("valueA")) .build()); final KeyValueImpl kv2 = new KeyValueImpl(KV.newBuilder() .setKey("a") .setValue(ByteString.copyFromUtf8("valueB")) .build()); final KeyValueImpl kv3 = new KeyValueImpl(KV.newBuilder() .setKey("b") .setValue(ByteString.copyFromUtf8("valueA")) .build()); final KeyValueImpl kv4 = new KeyValueImpl(KV.newBuilder() .setKey("a") .setValue(ByteString.copyFromUtf8("valueA")) .build()); assertFalse(kv1.equals(kv2)); assertFalse(kv1.equals(kv3)); assertTrue(kv1.equals(kv4)); } |
### Question:
InvocationTaskManager { public InvocationTaskManager register() { logger.info(() -> "Registering new chaincode " + this.chaincodeId); chaincode.setState(ChaincodeBase.CCState.CREATED); this.outgoingMessage.accept(ChaincodeMessageFactory.newRegisterChaincodeMessage(this.chaincodeId)); return this; } InvocationTaskManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId); static InvocationTaskManager getManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId); void onChaincodeMessage(final ChaincodeMessage chaincodeMessage); InvocationTaskManager setResponseConsumer(final Consumer<ChaincodeMessage> outgoingMessage); InvocationTaskManager register(); void shutdown(); }### Answer:
@Test public void register() throws UnsupportedEncodingException { itm.register(); } |
### Question:
InvocationTaskManager { public void onChaincodeMessage(final ChaincodeMessage chaincodeMessage) { logger.fine(() -> String.format("[%-8.8s] %s", chaincodeMessage.getTxid(), ChaincodeBase.toJsonString(chaincodeMessage))); try { final Type msgType = chaincodeMessage.getType(); switch (chaincode.getState()) { case CREATED: if (msgType == REGISTERED) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.ESTABLISHED); logger.fine(() -> String.format("[%-8.8s] Received REGISTERED: moving to established state", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case ESTABLISHED: if (msgType == READY) { chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.READY); logger.fine(() -> String.format("[%-8.8s] Received READY: ready for invocations", chaincodeMessage.getTxid())); } else { logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType)); } break; case READY: handleMsg(chaincodeMessage, msgType); break; default: logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), chaincodeMessage.getType())); break; } } catch (final RuntimeException e) { this.shutdown(); throw e; } } InvocationTaskManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId); static InvocationTaskManager getManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId); void onChaincodeMessage(final ChaincodeMessage chaincodeMessage); InvocationTaskManager setResponseConsumer(final Consumer<ChaincodeMessage> outgoingMessage); InvocationTaskManager register(); void shutdown(); }### Answer:
@Test public void onMessageTestTx() throws UnsupportedEncodingException { final ChaincodeMessage msg = ChaincodeMessageFactory.newEventMessage(ChaincodeMessage.Type.TRANSACTION, "mychannel", "txid", ByteString.copyFrom("Hello", "UTF-8")); when(chaincode.getChaincodeConfig()).thenReturn(new Properties()); chaincode.setState(ChaincodeBase.CCState.READY); itm.onChaincodeMessage(msg); }
@Test public void onWrongCreatedState() throws UnsupportedEncodingException { perfLogger.setLevel(Level.ALL); final ChaincodeMessage msg = ChaincodeMessageFactory.newEventMessage(ChaincodeMessage.Type.TRANSACTION, "mychannel", "txid", ByteString.copyFrom("Hello", "UTF-8")); when(chaincode.getChaincodeConfig()).thenReturn(new Properties()); chaincode.setState(ChaincodeBase.CCState.CREATED); itm.onChaincodeMessage(msg); }
@Test public void onWrongEstablishedState() throws UnsupportedEncodingException { final ChaincodeMessage msg = ChaincodeMessageFactory.newEventMessage(ChaincodeMessage.Type.TRANSACTION, "mychannel", "txid", ByteString.copyFrom("Hello", "UTF-8")); when(chaincode.getChaincodeConfig()).thenReturn(new Properties()); chaincode.setState(ChaincodeBase.CCState.ESTABLISHED); itm.onChaincodeMessage(msg); }
@Test public void onErrorResponse() throws UnsupportedEncodingException { final ChaincodeMessage msg = ChaincodeMessageFactory.newEventMessage(ChaincodeMessage.Type.ERROR, "mychannel", "txid", ByteString.copyFrom("Hello", "UTF-8")); when(chaincode.getChaincodeConfig()).thenReturn(new Properties()); chaincode.setState(ChaincodeBase.CCState.READY); itm.onChaincodeMessage(msg); } |
### Question:
ChaincodeMessageFactory { protected static ChaincodeMessage newGetPrivateDataHashEventMessage(final String channelId, final String txId, final String collection, final String key) { return newEventMessage(GET_PRIVATE_DATA_HASH, channelId, txId, GetState.newBuilder().setCollection(collection).setKey(key).build().toByteString()); } private ChaincodeMessageFactory(); }### Answer:
@Test void testNewGetPrivateDataHashEventMessage() { ChaincodeMessageFactory.newGetPrivateDataHashEventMessage(channelId, txId, collection, key); } |
### Question:
MyAssetContract implements ContractInterface { @Transaction() public MyAsset readMyAsset(Context ctx, String myAssetId) { boolean exists = myAssetExists(ctx,myAssetId); if (!exists) { throw new RuntimeException("The asset "+myAssetId+" does not exist"); } MyAsset newAsset = MyAsset.fromJSONString(new String(ctx.getStub().getState(myAssetId),UTF_8)); return newAsset; } MyAssetContract(); @Transaction() boolean myAssetExists(Context ctx, String myAssetId); @Transaction() void createMyAsset(Context ctx, String myAssetId, String value); @Transaction() MyAsset readMyAsset(Context ctx, String myAssetId); @Transaction() void updateMyAsset(Context ctx, String myAssetId, String newValue); @Transaction() void deleteMyAsset(Context ctx, String myAssetId); }### Answer:
@Test public void assetRead() { MyAssetContract contract = new MyAssetContract(); Context ctx = mock(Context.class); ChaincodeStub stub = mock(ChaincodeStub.class); when(ctx.getStub()).thenReturn(stub); MyAsset asset = new MyAsset(); asset.setValue("Valuable"); String json = asset.toJSONString(); when(stub.getState("10001")).thenReturn(json.getBytes(StandardCharsets.UTF_8)); MyAsset returnedAsset = contract.readMyAsset(ctx, "10001"); assertEquals(returnedAsset.getValue(), asset.getValue()); } |
### Question:
ChaincodeMessageFactory { protected static ChaincodeMessage newGetStateEventMessage(final String channelId, final String txId, final String collection, final String key) { return newEventMessage(GET_STATE, channelId, txId, GetState.newBuilder().setCollection(collection).setKey(key).build().toByteString()); } private ChaincodeMessageFactory(); }### Answer:
@Test void testNewGetStateEventMessage() { ChaincodeMessageFactory.newGetStateEventMessage(channelId, txId, collection, key); } |
### Question:
ChaincodeMessageFactory { protected static ChaincodeMessage newGetStateMetadataEventMessage(final String channelId, final String txId, final String collection, final String key) { return newEventMessage(GET_STATE_METADATA, channelId, txId, GetStateMetadata.newBuilder().setCollection(collection).setKey(key).build().toByteString()); } private ChaincodeMessageFactory(); }### Answer:
@Test void testNewGetStateMetadataEventMessage() { ChaincodeMessageFactory.newGetStateMetadataEventMessage(channelId, txId, collection, key); } |
### Question:
ChaincodeMessageFactory { protected static ChaincodeMessage newPutStateEventMessage(final String channelId, final String txId, final String collection, final String key, final ByteString value) { return newEventMessage(PUT_STATE, channelId, txId, PutState.newBuilder().setCollection(collection).setKey(key).setValue(value).build().toByteString()); } private ChaincodeMessageFactory(); }### Answer:
@Test void testNewPutStateEventMessage() { ChaincodeMessageFactory.newPutStateEventMessage(channelId, txId, collection, key, value); } |
### Question:
ChaincodeMessageFactory { protected static ChaincodeMessage newPutStateMetadataEventMessage(final String channelId, final String txId, final String collection, final String key, final String metakey, final ByteString value) { return newEventMessage(PUT_STATE_METADATA, channelId, txId, PutStateMetadata.newBuilder().setCollection(collection).setKey(key) .setMetadata(StateMetadata.newBuilder().setMetakey(metakey).setValue(value).build()).build().toByteString()); } private ChaincodeMessageFactory(); }### Answer:
@Test void testNewPutStateMetadataEventMessage() { ChaincodeMessageFactory.newPutStateMetadataEventMessage(channelId, txId, collection, key, metakey, value); } |
### Question:
ChaincodeMessageFactory { protected static ChaincodeMessage newDeleteStateEventMessage(final String channelId, final String txId, final String collection, final String key) { return newEventMessage(DEL_STATE, channelId, txId, DelState.newBuilder().setCollection(collection).setKey(key).build().toByteString()); } private ChaincodeMessageFactory(); }### Answer:
@Test void testNewDeleteStateEventMessage() { ChaincodeMessageFactory.newDeleteStateEventMessage(channelId, txId, collection, key); } |
### Question:
ChaincodeMessageFactory { protected static ChaincodeMessage newErrorEventMessage(final String channelId, final String txId, final Throwable throwable) { return newErrorEventMessage(channelId, txId, printStackTrace(throwable)); } private ChaincodeMessageFactory(); }### Answer:
@Test void testNewErrorEventMessage() { ChaincodeMessageFactory.newErrorEventMessage(channelId, txId, message); ChaincodeMessageFactory.newErrorEventMessage(channelId, txId, throwable); ChaincodeMessageFactory.newErrorEventMessage(channelId, txId, message, event); } |
### Question:
ChaincodeMessageFactory { protected static ChaincodeMessage newCompletedEventMessage(final String channelId, final String txId, final Chaincode.Response response, final ChaincodeEvent event) { final ChaincodeMessage message = newEventMessage(COMPLETED, channelId, txId, toProtoResponse(response).toByteString(), event); return message; } private ChaincodeMessageFactory(); }### Answer:
@Test void testNewCompletedEventMessage() { ChaincodeMessageFactory.newCompletedEventMessage(channelId, txId, response, event); } |
### Question:
ChaincodeMessageFactory { protected static ChaincodeMessage newInvokeChaincodeMessage(final String channelId, final String txId, final ByteString payload) { return newEventMessage(INVOKE_CHAINCODE, channelId, txId, payload, null); } private ChaincodeMessageFactory(); }### Answer:
@Test void testNewInvokeChaincodeMessage() { ChaincodeMessageFactory.newInvokeChaincodeMessage(channelId, txId, payload); } |
### Question:
ChaincodeMessageFactory { protected static ChaincodeMessage newRegisterChaincodeMessage(final ChaincodeID chaincodeId) { return ChaincodeMessage.newBuilder().setType(REGISTER).setPayload(chaincodeId.toByteString()).build(); } private ChaincodeMessageFactory(); }### Answer:
@Test void testNewRegisterChaincodeMessage() { ChaincodeMessageFactory.newRegisterChaincodeMessage(chaincodeId); } |
### Question:
ChaincodeMessageFactory { protected static ChaincodeMessage newEventMessage(final Type type, final String channelId, final String txId, final ByteString payload) { return newEventMessage(type, channelId, txId, payload, null); } private ChaincodeMessageFactory(); }### Answer:
@Test void testNewEventMessageTypeStringStringByteString() { ChaincodeMessageFactory.newEventMessage(type, channelId, txId, payload); ChaincodeMessageFactory.newEventMessage(type, channelId, txId, payload, event); } |
### Question:
KeyModificationImpl implements KeyModification { KeyModificationImpl(final KvQueryResult.KeyModification km) { this.txId = km.getTxId(); this.value = km.getValue(); this.timestamp = Instant.ofEpochSecond(km.getTimestamp().getSeconds(), km.getTimestamp().getNanos()); this.deleted = km.getIsDelete(); } KeyModificationImpl(final KvQueryResult.KeyModification km); @Override String getTxId(); @Override byte[] getValue(); @Override String getStringValue(); @Override java.time.Instant getTimestamp(); @Override boolean isDeleted(); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer:
@Test public void testKeyModificationImpl() { new KeyModificationImpl(KvQueryResult.KeyModification.newBuilder() .setTxId("txid") .setValue(ByteString.copyFromUtf8("value")) .setTimestamp(Timestamp.newBuilder() .setSeconds(1234567890) .setNanos(123456789)) .setIsDelete(true) .build()); } |
### Question:
KeyModificationImpl implements KeyModification { @Override public String getTxId() { return txId; } KeyModificationImpl(final KvQueryResult.KeyModification km); @Override String getTxId(); @Override byte[] getValue(); @Override String getStringValue(); @Override java.time.Instant getTimestamp(); @Override boolean isDeleted(); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer:
@Test public void testGetTxId() { final KeyModification km = new KeyModificationImpl(KvQueryResult.KeyModification.newBuilder() .setTxId("txid") .build()); assertThat(km.getTxId(), is(equalTo("txid"))); } |
### Question:
KeyModificationImpl implements KeyModification { @Override public byte[] getValue() { return value.toByteArray(); } KeyModificationImpl(final KvQueryResult.KeyModification km); @Override String getTxId(); @Override byte[] getValue(); @Override String getStringValue(); @Override java.time.Instant getTimestamp(); @Override boolean isDeleted(); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer:
@Test public void testGetValue() { final KeyModification km = new KeyModificationImpl(KvQueryResult.KeyModification.newBuilder() .setValue(ByteString.copyFromUtf8("value")) .build()); assertThat(km.getValue(), is(equalTo("value".getBytes(UTF_8)))); } |
### Question:
KeyModificationImpl implements KeyModification { @Override public String getStringValue() { return value.toStringUtf8(); } KeyModificationImpl(final KvQueryResult.KeyModification km); @Override String getTxId(); @Override byte[] getValue(); @Override String getStringValue(); @Override java.time.Instant getTimestamp(); @Override boolean isDeleted(); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer:
@Test public void testGetStringValue() { final KeyModification km = new KeyModificationImpl(KvQueryResult.KeyModification.newBuilder() .setValue(ByteString.copyFromUtf8("value")) .build()); assertThat(km.getStringValue(), is(equalTo("value"))); } |
### Question:
KeyModificationImpl implements KeyModification { @Override public java.time.Instant getTimestamp() { return timestamp; } KeyModificationImpl(final KvQueryResult.KeyModification km); @Override String getTxId(); @Override byte[] getValue(); @Override String getStringValue(); @Override java.time.Instant getTimestamp(); @Override boolean isDeleted(); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer:
@Test public void testGetTimestamp() { final KeyModification km = new KeyModificationImpl(KvQueryResult.KeyModification.newBuilder() .setTimestamp(Timestamp.newBuilder() .setSeconds(1234567890L) .setNanos(123456789)) .build()); assertThat(km.getTimestamp(), hasProperty("epochSecond", equalTo(1234567890L))); assertThat(km.getTimestamp(), hasProperty("nano", equalTo(123456789))); } |
### Question:
KeyModificationImpl implements KeyModification { @Override public boolean isDeleted() { return deleted; } KeyModificationImpl(final KvQueryResult.KeyModification km); @Override String getTxId(); @Override byte[] getValue(); @Override String getStringValue(); @Override java.time.Instant getTimestamp(); @Override boolean isDeleted(); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer:
@Test public void testIsDeleted() { Stream.of(true, false) .forEach(b -> { final KeyModification km = new KeyModificationImpl(KvQueryResult.KeyModification.newBuilder() .setIsDelete(b) .build()); assertThat(km.isDeleted(), is(b)); }); } |
### Question:
KeyModificationImpl implements KeyModification { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (deleted ? 1231 : 1237); result = prime * result + ((timestamp == null) ? 0 : timestamp.hashCode()); result = prime * result + ((txId == null) ? 0 : txId.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } KeyModificationImpl(final KvQueryResult.KeyModification km); @Override String getTxId(); @Override byte[] getValue(); @Override String getStringValue(); @Override java.time.Instant getTimestamp(); @Override boolean isDeleted(); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer:
@Test public void testHashCode() { final KeyModification km = new KeyModificationImpl(KvQueryResult.KeyModification.newBuilder() .setIsDelete(false) .build()); int expectedHashCode = 31; expectedHashCode = expectedHashCode + 1237; expectedHashCode = expectedHashCode * 31 + Instant.EPOCH.hashCode(); expectedHashCode = expectedHashCode * 31 + "".hashCode(); expectedHashCode = expectedHashCode * 31 + ByteString.copyFromUtf8("").hashCode(); assertEquals("Wrong hash code", expectedHashCode, km.hashCode()); } |
### Question:
KeyModificationImpl implements KeyModification { @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final KeyModificationImpl other = (KeyModificationImpl) obj; if (deleted != other.deleted) { return false; } if (!timestamp.equals(other.timestamp)) { return false; } if (!txId.equals(other.txId)) { return false; } if (!value.equals(other.value)) { return false; } return true; } KeyModificationImpl(final KvQueryResult.KeyModification km); @Override String getTxId(); @Override byte[] getValue(); @Override String getStringValue(); @Override java.time.Instant getTimestamp(); @Override boolean isDeleted(); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer:
@Test public void testEquals() { final KeyModification km1 = new KeyModificationImpl(KvQueryResult.KeyModification.newBuilder() .setIsDelete(false) .build()); final KeyModification km2 = new KeyModificationImpl(KvQueryResult.KeyModification.newBuilder() .setIsDelete(true) .build()); final KeyModification km3 = new KeyModificationImpl(KvQueryResult.KeyModification.newBuilder() .setIsDelete(false) .build()); assertFalse(km1.equals(km2)); assertTrue(km1.equals(km3)); } |
### Question:
QueryResultsIteratorWithMetadataImpl extends QueryResultsIteratorImpl<T> implements QueryResultsIteratorWithMetadata<T> { @Override public ChaincodeShim.QueryResponseMetadata getMetadata() { return metadata; } QueryResultsIteratorWithMetadataImpl(final ChaincodeInvocationTask handler, final String channelId, final String txId,
final ByteString responseBuffer, final Function<QueryResultBytes, T> mapper); @Override ChaincodeShim.QueryResponseMetadata getMetadata(); }### Answer:
@Test public void getMetadata() { final QueryResultsIteratorWithMetadataImpl<Integer> testIter = new QueryResultsIteratorWithMetadataImpl<>(null, "", "", prepareQueryResponse().toByteString(), queryResultBytesToKv); assertThat(testIter.getMetadata().getBookmark(), is("asdf")); assertThat(testIter.getMetadata().getFetchedRecordsCount(), is(2)); } |
### Question:
ChaincodeBase implements Chaincode { @Deprecated protected static Response newSuccessResponse(final String message, final byte[] payload) { return ResponseUtils.newSuccessResponse(message, payload); } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); static final String CORE_CHAINCODE_LOGGING_SHIM; static final String CORE_CHAINCODE_LOGGING_LEVEL; static final String DEFAULT_HOST; static final int DEFAULT_PORT; }### Answer:
@Test public void testNewSuccessResponseEmpty() { final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newSuccessResponse(); assertEquals("Response status is incorrect", response.getStatus(), org.hyperledger.fabric.shim.Chaincode.Response.Status.SUCCESS); assertNull("Response message in not null", response.getMessage()); assertNull("Response payload in not null", response.getPayload()); }
@Test public void testNewSuccessResponseWithMessage() { final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newSuccessResponse("Simple message"); assertEquals("Response status is incorrect", response.getStatus(), org.hyperledger.fabric.shim.Chaincode.Response.Status.SUCCESS); assertEquals("Response message in not correct", "Simple message", response.getMessage()); assertNull("Response payload in not null", response.getPayload()); }
@Test public void testNewSuccessResponseWithPayload() { final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newSuccessResponse("Simple payload".getBytes(Charset.defaultCharset())); assertEquals("Response status is incorrect", response.getStatus(), org.hyperledger.fabric.shim.Chaincode.Response.Status.SUCCESS); assertNull("Response message in not null", response.getMessage()); assertArrayEquals("Response payload in not null", response.getPayload(), "Simple payload".getBytes(Charset.defaultCharset())); }
@Test public void testNewSuccessResponseWithMessageAndPayload() { final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newSuccessResponse("Simple message", "Simple payload".getBytes(Charset.defaultCharset())); assertEquals("Response status is incorrect", response.getStatus(), org.hyperledger.fabric.shim.Chaincode.Response.Status.SUCCESS); assertEquals("Response message in not correct", "Simple message", response.getMessage()); assertArrayEquals("Response payload in not null", response.getPayload(), "Simple payload".getBytes(Charset.defaultCharset())); } |
### Question:
Logger extends java.util.logging.Logger { protected Logger(final String name) { super(name, null); this.setParent(java.util.logging.Logger.getLogger("org.hyperledger.fabric")); } protected Logger(final String name); static Logger getLogger(final String name); void debug(final Supplier<String> msgSupplier); void debug(final String msg); static Logger getLogger(final Class<?> class1); void error(final String message); void error(final Supplier<String> msgSupplier); String formatError(final Throwable throwable); }### Answer:
@Test public void logger() { Logger.getLogger(LoggerTest.class); Logger.getLogger(LoggerTest.class.getName()); } |
### Question:
ChaincodeBase implements Chaincode { @Deprecated protected static Response newErrorResponse(final String message, final byte[] payload) { return ResponseUtils.newErrorResponse(message, payload); } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); static final String CORE_CHAINCODE_LOGGING_SHIM; static final String CORE_CHAINCODE_LOGGING_LEVEL; static final String DEFAULT_HOST; static final int DEFAULT_PORT; }### Answer:
@Test public void testNewErrorResponseEmpty() { final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newErrorResponse(); assertEquals("Response status is incorrect", response.getStatus(), org.hyperledger.fabric.shim.Chaincode.Response.Status.INTERNAL_SERVER_ERROR); assertNull("Response message in not null", response.getMessage()); assertNull("Response payload in not null", response.getPayload()); }
@Test public void testNewErrorResponseWithMessage() { final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newErrorResponse("Simple message"); assertEquals("Response status is incorrect", response.getStatus(), org.hyperledger.fabric.shim.Chaincode.Response.Status.INTERNAL_SERVER_ERROR); assertEquals("Response message in not correct", "Simple message", response.getMessage()); assertNull("Response payload in not null", response.getPayload()); }
@Test public void testNewErrorResponseWithPayload() { final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newErrorResponse("Simple payload".getBytes(Charset.defaultCharset())); assertEquals("Response status is incorrect", response.getStatus(), org.hyperledger.fabric.shim.Chaincode.Response.Status.INTERNAL_SERVER_ERROR); assertNull("Response message in not null", response.getMessage()); assertArrayEquals("Response payload in not null", response.getPayload(), "Simple payload".getBytes(Charset.defaultCharset())); }
@Test public void testNewErrorResponseWithMessageAndPayload() { final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newErrorResponse("Simple message", "Simple payload".getBytes(Charset.defaultCharset())); assertEquals("Response status is incorrect", response.getStatus(), org.hyperledger.fabric.shim.Chaincode.Response.Status.INTERNAL_SERVER_ERROR); assertEquals("Response message in not correct", "Simple message", response.getMessage()); assertArrayEquals("Response payload in not null", response.getPayload(), "Simple payload".getBytes(Charset.defaultCharset())); }
@Test public void testNewErrorResponseWithException() { final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newErrorResponse(new Exception("Simple exception")); assertEquals("Response status is incorrect", response.getStatus(), org.hyperledger.fabric.shim.Chaincode.Response.Status.INTERNAL_SERVER_ERROR); assertEquals("Response message is not correct", "Unexpected error", response.getMessage()); assertNull("Response payload is not null", response.getPayload()); }
@Test public void testNewErrorResponseWithChaincodeException() { final org.hyperledger.fabric.shim.Chaincode.Response response = ResponseUtils.newErrorResponse(new ChaincodeException("Chaincode exception")); assertEquals("Response status is incorrect", response.getStatus(), org.hyperledger.fabric.shim.Chaincode.Response.Status.INTERNAL_SERVER_ERROR); assertEquals("Response message is not correct", "Chaincode exception", response.getMessage()); assertNull("Response payload is not null", response.getPayload()); } |
### Question:
ChaincodeBase implements Chaincode { protected final void validateOptions() { if (this.id == null) { throw new IllegalArgumentException(format( "The chaincode id must be specified using either the -i or --i command line options or the %s environment variable.", CORE_CHAINCODE_ID_NAME)); } if (this.tlsEnabled) { if (tlsClientCertPath == null) { throw new IllegalArgumentException( format("Client key certificate chain (%s) was not specified.", ENV_TLS_CLIENT_CERT_PATH)); } if (tlsClientKeyPath == null) { throw new IllegalArgumentException( format("Client key (%s) was not specified.", ENV_TLS_CLIENT_KEY_PATH)); } if (tlsClientRootCertPath == null) { throw new IllegalArgumentException( format("Peer certificate trust store (%s) was not specified.", CORE_PEER_TLS_ROOTCERT_FILE)); } } } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); static final String CORE_CHAINCODE_LOGGING_SHIM; static final String CORE_CHAINCODE_LOGGING_LEVEL; static final String DEFAULT_HOST; static final int DEFAULT_PORT; }### Answer:
@Test public void testUnsetOptionId() { final ChaincodeBase cb = new EmptyChaincode(); thrown.expect(IllegalArgumentException.class); thrown.expectMessage(Matchers.containsString("The chaincode id must be specified")); cb.validateOptions(); } |
### Question:
CompositeKey { public static void validateSimpleKeys(final String... keys) { for (final String key : keys) { if (!key.isEmpty() && key.startsWith(NAMESPACE)) { throw CompositeKeyFormatException.forSimpleKey(key); } } } CompositeKey(final String objectType, final String... attributes); CompositeKey(final String objectType, final List<String> attributes); String getObjectType(); List<String> getAttributes(); @Override String toString(); static CompositeKey parseCompositeKey(final String compositeKey); static void validateSimpleKeys(final String... keys); static final String NAMESPACE; }### Answer:
@Test public void testValidateSimpleKeys() { CompositeKey.validateSimpleKeys("abc", "def", "ghi"); }
@Test(expected = CompositeKeyFormatException.class) public void testValidateSimpleKeysException() throws Exception { CompositeKey.validateSimpleKeys("\u0000abc"); } |
### Question:
ChaincodeBase implements Chaincode { @SuppressWarnings("deprecation") final ManagedChannelBuilder<?> newChannelBuilder() throws IOException { final NettyChannelBuilder builder = NettyChannelBuilder.forAddress(host, port); LOGGER.info("Configuring channel connection to peer."); if (tlsEnabled) { builder.negotiationType(NegotiationType.TLS); builder.sslContext(createSSLContext()); } else { builder.usePlaintext(); } return builder; } @Override abstract Response init(ChaincodeStub stub); @Override abstract Response invoke(ChaincodeStub stub); void start(final String[] args); Properties getChaincodeConfig(); final CCState getState(); final void setState(final CCState newState); static String toJsonString(final ChaincodeMessage message); static final String CORE_CHAINCODE_LOGGING_SHIM; static final String CORE_CHAINCODE_LOGGING_LEVEL; static final String DEFAULT_HOST; static final int DEFAULT_PORT; }### Answer:
@Test @Ignore public void testNewChannelBuilder() throws Exception { final ChaincodeBase cb = new EmptyChaincode(); environmentVariables.set("CORE_CHAINCODE_ID_NAME", "mycc"); environmentVariables.set("CORE_PEER_ADDRESS", "localhost:7052"); environmentVariables.set("CORE_PEER_TLS_ENABLED", "true"); environmentVariables.set("CORE_PEER_TLS_ROOTCERT_FILE", "src/test/resources/ca.crt"); environmentVariables.set("CORE_TLS_CLIENT_KEY_PATH", "src/test/resources/client.key.enc"); environmentVariables.set("CORE_TLS_CLIENT_CERT_PATH", "src/test/resources/client.crt.enc"); cb.processEnvironmentOptions(); cb.validateOptions(); assertTrue("Not correct builder", cb.newChannelBuilder() instanceof ManagedChannelBuilder); } |
### Question:
ContextFactory { public static synchronized ContextFactory getInstance() { if (cf == null) { cf = new ContextFactory(); } return cf; } static synchronized ContextFactory getInstance(); Context createContext(final ChaincodeStub stub); }### Answer:
@Test public void getInstance() { final ContextFactory f1 = ContextFactory.getInstance(); final ContextFactory f2 = ContextFactory.getInstance(); assertThat(f1, sameInstance(f2)); } |
### Question:
ContextFactory { public Context createContext(final ChaincodeStub stub) { final Context newContext = new Context(stub); return newContext; } static synchronized ContextFactory getInstance(); Context createContext(final ChaincodeStub stub); }### Answer:
@Test public void createContext() { final ChaincodeStub stub = new ChaincodeStubNaiveImpl(); final Context ctx = ContextFactory.getInstance().createContext(stub); assertThat(stub.getArgs(), is(equalTo(ctx.getStub().getArgs()))); assertThat(stub.getStringArgs(), is(equalTo(ctx.getStub().getStringArgs()))); assertThat(stub.getFunction(), is(equalTo(ctx.getStub().getFunction()))); assertThat(stub.getParameters(), is(equalTo(ctx.getStub().getParameters()))); assertThat(stub.getTxId(), is(equalTo(ctx.getStub().getTxId()))); assertThat(stub.getChannelId(), is(equalTo(ctx.getStub().getChannelId()))); assertThat(stub.invokeChaincode("cc", Collections.emptyList(), "ch0"), is(equalTo(ctx.getStub().invokeChaincode("cc", Collections.emptyList(), "ch0")))); assertThat(stub.getState("a"), is(equalTo(ctx.getStub().getState("a")))); ctx.getStub().putState("b", "sdfg".getBytes()); assertThat(stub.getStringState("b"), is(equalTo(ctx.getStub().getStringState("b")))); assertThat(ctx.clientIdentity.getMSPID(), is(equalTo("testMSPID"))); assertThat(ctx.clientIdentity.getId(), is(equalTo( "x509::CN=admin, OU=Fabric, O=Hyperledger, ST=North Carolina," + " C=US::CN=example.com, OU=WWW, O=Internet Widgets, L=San Francisco, ST=California, C=US"))); } |
### Question:
Context { public ChaincodeStub getStub() { return this.stub; } Context(final ChaincodeStub stub); ChaincodeStub getStub(); ClientIdentity getClientIdentity(); }### Answer:
@Test public void getInstance() { final ChaincodeStub stub = new ChaincodeStubNaiveImpl(); final Context context1 = new Context(stub); final Context context2 = new Context(stub); assertThat(context1.getStub(), sameInstance(context2.getStub())); } |
### Question:
Context { public ClientIdentity getClientIdentity() { return this.clientIdentity; } Context(final ChaincodeStub stub); ChaincodeStub getStub(); ClientIdentity getClientIdentity(); }### Answer:
@Test public void getSetClientIdentity() { final ChaincodeStub stub = new ChaincodeStubNaiveImpl(); final Context context = ContextFactory.getInstance().createContext(stub); assertThat(context.getClientIdentity(), sameInstance(context.clientIdentity)); } |
### Question:
ContractRouter extends ChaincodeBase { protected void findAllContracts() { registry.findAndSetContracts(this.typeRegistry); } ContractRouter(final String[] args); @Override Response invoke(final ChaincodeStub stub); @Override Response init(final ChaincodeStub stub); static void main(final String[] args); }### Answer:
@Test public void testCreateAndScan() { final ContractRouter r = new ContractRouter(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"}); r.findAllContracts(); final ChaincodeStub s = new ChaincodeStubNaiveImpl(); final List<String> args = new ArrayList<>(); args.add("samplecontract:t1"); args.add("asdf"); ((ChaincodeStubNaiveImpl) s).setStringArgs(args); final InvocationRequest request = ExecutionFactory.getInstance().createRequest(s); assertThat(request.getNamespace(), is(equalTo(SampleContract.class.getAnnotation(Contract.class).name()))); assertThat(request.getMethod(), is(equalTo("t1"))); assertThat(request.getRequestName(), is(equalTo("samplecontract:t1"))); assertThat(request.getArgs(), is(contains(s.getArgs().get(1)))); } |
### Question:
ContractRouter extends ChaincodeBase { @Override public Response init(final ChaincodeStub stub) { return processRequest(stub); } ContractRouter(final String[] args); @Override Response invoke(final ChaincodeStub stub); @Override Response init(final ChaincodeStub stub); static void main(final String[] args); }### Answer:
@Test public void testInit() { final ContractRouter r = new ContractRouter(new String[] {"-a", "127.0.0.1:7052", "-i", "testId"}); r.findAllContracts(); final ChaincodeStub s = new ChaincodeStubNaiveImpl(); final List<String> args = new ArrayList<>(); args.add("samplecontract:t1"); args.add("asdf"); ((ChaincodeStubNaiveImpl) s).setStringArgs(args); SampleContract.setBeforeInvoked(0); SampleContract.setAfterInvoked(0); SampleContract.setDoWorkInvoked(0); SampleContract.setT1Invoked(0); final Chaincode.Response response = r.init(s); assertThat(response, is(notNullValue())); assertThat(response.getStatus(), is(Chaincode.Response.Status.SUCCESS)); assertThat(response.getMessage(), is(nullValue())); assertThat(response.getStringPayload(), is(equalTo("asdf"))); assertThat(SampleContract.getBeforeInvoked(), is(1)); assertThat(SampleContract.getAfterInvoked(), is(1)); assertThat(SampleContract.getDoWorkInvoked(), is(1)); assertThat(SampleContract.getT1Invoked(), is(1)); } |
### Question:
TypeSchema extends HashMap<String, Object> { String putIfNotNull(final String key, final String value) { return (String) this.putInternal(key, value); } TypeSchema(); String getType(); TypeSchema getItems(); String getRef(); String getFormat(); Class<?> getTypeClass(final TypeRegistry typeRegistry); static TypeSchema typeConvert(final Class<?> clz); void validate(final JSONObject obj); }### Answer:
@Test public void putIfNotNull() { final TypeSchema ts = new TypeSchema(); System.out.println("Key - value"); ts.putIfNotNull("Key", "value"); System.out.println("Key - null"); final String nullstr = null; ts.putIfNotNull("Key", nullstr); assertThat(ts.get("Key"), equalTo("value")); System.out.println("Key - <empty>"); ts.putIfNotNull("Key", ""); assertThat(ts.get("Key"), equalTo("value")); } |
### Question:
TypeSchema extends HashMap<String, Object> { public String getType() { if (this.containsKey("schema")) { final Map<?, ?> intermediateMap = (Map<?, ?>) this.get("schema"); return (String) intermediateMap.get("type"); } return (String) this.get("type"); } TypeSchema(); String getType(); TypeSchema getItems(); String getRef(); String getFormat(); Class<?> getTypeClass(final TypeRegistry typeRegistry); static TypeSchema typeConvert(final Class<?> clz); void validate(final JSONObject obj); }### Answer:
@Test public void getType() { final TypeSchema ts = new TypeSchema(); ts.put("type", "MyType"); assertThat(ts.getType(), equalTo("MyType")); final TypeSchema wrapper = new TypeSchema(); wrapper.put("schema", ts); assertThat(wrapper.getType(), equalTo("MyType")); } |
### Question:
TypeSchema extends HashMap<String, Object> { public String getFormat() { if (this.containsKey("schema")) { final Map<?, ?> intermediateMap = (Map<?, ?>) this.get("schema"); return (String) intermediateMap.get("format"); } return (String) this.get("format"); } TypeSchema(); String getType(); TypeSchema getItems(); String getRef(); String getFormat(); Class<?> getTypeClass(final TypeRegistry typeRegistry); static TypeSchema typeConvert(final Class<?> clz); void validate(final JSONObject obj); }### Answer:
@Test public void getFormat() { final TypeSchema ts = new TypeSchema(); ts.put("format", "MyFormat"); assertThat(ts.getFormat(), equalTo("MyFormat")); final TypeSchema wrapper = new TypeSchema(); wrapper.put("schema", ts); assertThat(wrapper.getFormat(), equalTo("MyFormat")); } |
### Question:
TypeSchema extends HashMap<String, Object> { public String getRef() { if (this.containsKey("schema")) { final Map<?, ?> intermediateMap = (Map<?, ?>) this.get("schema"); return (String) intermediateMap.get("$ref"); } return (String) this.get("$ref"); } TypeSchema(); String getType(); TypeSchema getItems(); String getRef(); String getFormat(); Class<?> getTypeClass(final TypeRegistry typeRegistry); static TypeSchema typeConvert(final Class<?> clz); void validate(final JSONObject obj); }### Answer:
@Test public void getRef() { final TypeSchema ts = new TypeSchema(); ts.put("$ref", "#/ref/to/MyType"); assertThat(ts.getRef(), equalTo("#/ref/to/MyType")); final TypeSchema wrapper = new TypeSchema(); wrapper.put("schema", ts); assertThat(wrapper.getRef(), equalTo("#/ref/to/MyType")); } |
### Question:
TypeSchema extends HashMap<String, Object> { public TypeSchema getItems() { if (this.containsKey("schema")) { final Map<?, ?> intermediateMap = (Map<?, ?>) this.get("schema"); return (TypeSchema) intermediateMap.get("items"); } return (TypeSchema) this.get("items"); } TypeSchema(); String getType(); TypeSchema getItems(); String getRef(); String getFormat(); Class<?> getTypeClass(final TypeRegistry typeRegistry); static TypeSchema typeConvert(final Class<?> clz); void validate(final JSONObject obj); }### Answer:
@Test public void getItems() { final TypeSchema ts1 = new TypeSchema(); final TypeSchema ts = new TypeSchema(); ts.put("items", ts1); assertThat(ts.getItems(), equalTo(ts1)); final TypeSchema wrapper = new TypeSchema(); wrapper.put("schema", ts); assertThat(wrapper.getItems(), equalTo(ts1)); } |
### Question:
TypeSchema extends HashMap<String, Object> { public Class<?> getTypeClass(final TypeRegistry typeRegistry) { Class<?> clz = null; String type = getType(); if (type == null) { type = "object"; } if (type.contentEquals("string")) { final String format = getFormat(); if (format != null && format.contentEquals("uint16")) { clz = char.class; } else { clz = String.class; } } else if (type.contentEquals("integer")) { final String format = getFormat(); switch (format) { case "int8": clz = byte.class; break; case "int16": clz = short.class; break; case "int32": clz = int.class; break; case "int64": clz = long.class; break; default: throw new RuntimeException("Unknown format for integer of " + format); } } else if (type.contentEquals("number")) { final String format = getFormat(); switch (format) { case "double": clz = double.class; break; case "float": clz = float.class; break; default: throw new RuntimeException("Unknown format for number of " + format); } } else if (type.contentEquals("boolean")) { clz = boolean.class; } else if (type.contentEquals("object")) { final String ref = this.getRef(); final String format = ref.substring(ref.lastIndexOf("/") + 1); clz = typeRegistry.getDataType(format).getTypeClass(); } else if (type.contentEquals("array")) { final TypeSchema typdef = this.getItems(); final Class<?> arrayType = typdef.getTypeClass(typeRegistry); clz = Array.newInstance(arrayType, 0).getClass(); } return clz; } TypeSchema(); String getType(); TypeSchema getItems(); String getRef(); String getFormat(); Class<?> getTypeClass(final TypeRegistry typeRegistry); static TypeSchema typeConvert(final Class<?> clz); void validate(final JSONObject obj); }### Answer:
@Test public void getTypeClass() { final TypeSchema ts = new TypeSchema(); ts.put("type", "string"); final TypeRegistry mockRegistry = new TypeRegistryImpl(); assertThat(ts.getTypeClass(mockRegistry), equalTo(String.class)); ts.put("type", "integer"); ts.put("format", "int8"); assertThat(ts.getTypeClass(mockRegistry), equalTo(byte.class)); ts.put("type", "integer"); ts.put("format", "int16"); assertThat(ts.getTypeClass(mockRegistry), equalTo(short.class)); ts.put("type", "integer"); ts.put("format", "int32"); assertThat(ts.getTypeClass(mockRegistry), equalTo(int.class)); ts.put("type", "integer"); ts.put("format", "int64"); assertThat(ts.getTypeClass(mockRegistry), equalTo(long.class)); ts.put("type", "number"); ts.put("format", "double"); assertThat(ts.getTypeClass(mockRegistry), equalTo(double.class)); ts.put("type", "number"); ts.put("format", "float"); assertThat(ts.getTypeClass(mockRegistry), equalTo(float.class)); ts.put("type", "boolean"); assertThat(ts.getTypeClass(mockRegistry), equalTo(boolean.class)); ts.put("type", null); ts.put("$ref", "#/ref/to/MyType"); mockRegistry.addDataType(MyType.class); assertThat(ts.getTypeClass(mockRegistry), equalTo(MyType.class)); final TypeSchema array = new TypeSchema(); array.put("type", "array"); array.put("items", ts); assertThat(array.getTypeClass(mockRegistry), equalTo(MyType[].class)); }
@Test public void unknownConversions() { assertThrows(RuntimeException.class, () -> { final TypeSchema ts = new TypeSchema(); final TypeRegistry mockRegistry = new TypeRegistryImpl(); ts.put("type", "integer"); ts.put("format", "int63"); ts.getTypeClass(mockRegistry); }); assertThrows(RuntimeException.class, () -> { final TypeSchema ts = new TypeSchema(); final TypeRegistry mockRegistry = new TypeRegistryImpl(); ts.put("type", "number"); ts.put("format", "approximate"); ts.getTypeClass(mockRegistry); }); } |
### Question:
TypeSchema extends HashMap<String, Object> { public void validate(final JSONObject obj) { final JSONObject toValidate = new JSONObject(); toValidate.put("prop", obj); JSONObject schemaJSON; if (this.containsKey("schema")) { schemaJSON = new JSONObject((Map) this.get("schema")); } else { schemaJSON = new JSONObject(this); } final JSONObject rawSchema = new JSONObject(); rawSchema.put("properties", new JSONObject().put("prop", schemaJSON)); rawSchema.put("components", new JSONObject().put("schemas", MetadataBuilder.getComponents())); final Schema schema = SchemaLoader.load(rawSchema); try { schema.validate(toValidate); } catch (final ValidationException e) { final StringBuilder sb = new StringBuilder("Validation Errors::"); e.getCausingExceptions().stream().map(ValidationException::getMessage).forEach(sb::append); logger.info(sb.toString()); throw new ContractRuntimeException(sb.toString(), e); } } TypeSchema(); String getType(); TypeSchema getItems(); String getRef(); String getFormat(); Class<?> getTypeClass(final TypeRegistry typeRegistry); static TypeSchema typeConvert(final Class<?> clz); void validate(final JSONObject obj); }### Answer:
@Test public void validate() { final TypeSchema ts = TypeSchema.typeConvert(org.hyperledger.fabric.contract.MyType.class); final DataTypeDefinition dtd = new DataTypeDefinitionImpl(org.hyperledger.fabric.contract.MyType.class); MetadataBuilder.addComponent(dtd); final JSONObject json = new JSONObject(); ts.validate(json); } |
### Question:
MetadataBuilder { public static String getMetadata() { return metadata().toString(); } private MetadataBuilder(); static void validate(); static void initialize(final RoutingRegistry registry, final TypeRegistry typeRegistry); static void addComponent(final DataTypeDefinition datatype); @SuppressWarnings("serial") static String addContract(final ContractDefinition contractDefinition); static void addTransaction(final TxFunction txFunction, final String contractName); static String getMetadata(); static String debugString(); static Map<?, ?> getComponents(); }### Answer:
@Test public void systemContract() { final SystemContract system = new SystemContract(); final ChaincodeStub stub = new ChaincodeStubNaiveImpl(); system.getMetadata(new Context(stub)); } |
### Question:
JSONTransactionSerializer implements SerializerInterface { @Override public byte[] toBuffer(final Object value, final TypeSchema ts) { logger.debug(() -> "Schema to convert is " + ts); byte[] buffer = null; if (value != null) { final String type = ts.getType(); if (type != null) { switch (type) { case "array": final JSONArray array = normalizeArray(new JSONArray(value), ts); buffer = array.toString().getBytes(UTF_8); break; case "string": final String format = ts.getFormat(); if (format != null && format.contentEquals("uint16")) { buffer = Character.valueOf((char) value).toString().getBytes(UTF_8); } else { buffer = ((String) value).getBytes(UTF_8); } break; case "number": case "integer": case "boolean": default: buffer = (value).toString().getBytes(UTF_8); } } else { final DataTypeDefinition dtd = this.typeRegistry.getDataType(ts); final Set<String> keySet = dtd.getProperties().keySet(); final String[] propNames = keySet.toArray(new String[keySet.size()]); final JSONObject obj = new JSONObject(new JSONObject(value), propNames); buffer = obj.toString().getBytes(UTF_8); } } return buffer; } JSONTransactionSerializer(); @Override byte[] toBuffer(final Object value, final TypeSchema ts); @Override Object fromBuffer(final byte[] buffer, final TypeSchema ts); }### Answer:
@Test public void toBuffer() { final TypeRegistry tr = TypeRegistry.getRegistry(); tr.addDataType(MyType.class); MetadataBuilder.addComponent(tr.getDataType("MyType")); final JSONTransactionSerializer serializer = new JSONTransactionSerializer(); byte[] bytes = serializer.toBuffer("hello world", TypeSchema.typeConvert(String.class)); assertThat(new String(bytes, StandardCharsets.UTF_8), equalTo("hello world")); bytes = serializer.toBuffer(42, TypeSchema.typeConvert(Integer.class)); assertThat(new String(bytes, StandardCharsets.UTF_8), equalTo("42")); bytes = serializer.toBuffer(true, TypeSchema.typeConvert(Boolean.class)); assertThat(new String(bytes, StandardCharsets.UTF_8), equalTo("true")); bytes = serializer.toBuffer(new MyType(), TypeSchema.typeConvert(MyType.class)); assertThat(new String(bytes, StandardCharsets.UTF_8), equalTo("{}")); bytes = serializer.toBuffer(new MyType().setValue("Hello"), TypeSchema.typeConvert(MyType.class)); assertThat(new String(bytes, StandardCharsets.UTF_8), equalTo("{\"value\":\"Hello\"}")); final MyType[] array = new MyType[2]; array[0] = new MyType().setValue("hello"); array[1] = new MyType().setValue("world"); bytes = serializer.toBuffer(array, TypeSchema.typeConvert(MyType[].class)); final byte[] buffer = "[{\"value\":\"hello\"},{\"value\":\"world\"}]".getBytes(StandardCharsets.UTF_8); System.out.println(new String(buffer, StandardCharsets.UTF_8)); System.out.println(new String(bytes, StandardCharsets.UTF_8)); assertThat(bytes, equalTo(buffer)); }
@Test public void fromBufferErrors() { final TypeRegistry tr = new TypeRegistryImpl(); tr.addDataType(MyType.class); MetadataBuilder.addComponent(tr.getDataType("MyType")); final JSONTransactionSerializer serializer = new JSONTransactionSerializer(); final TypeSchema ts = TypeSchema.typeConvert(MyType[].class); serializer.toBuffer(null, ts); } |
### Question:
JSONTransactionSerializer implements SerializerInterface { @Override public Object fromBuffer(final byte[] buffer, final TypeSchema ts) { try { final String stringData = new String(buffer, StandardCharsets.UTF_8); Object value = null; value = convert(stringData, ts); return value; } catch (InstantiationException | IllegalAccessException e) { final ContractRuntimeException cre = new ContractRuntimeException(e); throw cre; } } JSONTransactionSerializer(); @Override byte[] toBuffer(final Object value, final TypeSchema ts); @Override Object fromBuffer(final byte[] buffer, final TypeSchema ts); }### Answer:
@Test public void fromBufferObject() { final byte[] buffer = "[{\"value\":\"hello\"},{\"value\":\"world\"}]".getBytes(StandardCharsets.UTF_8); final TypeRegistry tr = TypeRegistry.getRegistry(); tr.addDataType(MyType.class); MetadataBuilder.addComponent(tr.getDataType("MyType")); final JSONTransactionSerializer serializer = new JSONTransactionSerializer(); final TypeSchema ts = TypeSchema.typeConvert(MyType[].class); final MyType[] o = (MyType[]) serializer.fromBuffer(buffer, ts); assertThat(o[0].toString(), equalTo("++++ MyType: hello")); assertThat(o[1].toString(), equalTo("++++ MyType: world")); } |
### Question:
CompositeKey { public String getObjectType() { return objectType; } CompositeKey(final String objectType, final String... attributes); CompositeKey(final String objectType, final List<String> attributes); String getObjectType(); List<String> getAttributes(); @Override String toString(); static CompositeKey parseCompositeKey(final String compositeKey); static void validateSimpleKeys(final String... keys); static final String NAMESPACE; }### Answer:
@Test public void testGetObjectType() { final CompositeKey key = new CompositeKey("abc", Arrays.asList("def", "ghi", "jkl", "mno")); assertThat(key.getObjectType(), is(equalTo("abc"))); } |
### Question:
Logging { private static Level mapLevel(final String level) { if (level != null) { switch (level.toUpperCase().trim()) { case "ERROR": case "CRITICAL": return Level.SEVERE; case "WARNING": return Level.WARNING; case "INFO": return Level.INFO; case "NOTICE": return Level.CONFIG; case "DEBUG": return Level.FINEST; default: return Level.INFO; } } return Level.INFO; } private Logging(); static String formatError(final Throwable throwable); static void setLogLevel(final String newLevel); static final String PERFLOGGER; }### Answer:
@Test public void testMapLevel() { assertEquals("Error maps", Level.SEVERE, proxyMapLevel("ERROR")); assertEquals("Critical maps", Level.SEVERE, proxyMapLevel("critical")); assertEquals("Warn maps", Level.WARNING, proxyMapLevel("WARNING")); assertEquals("Info maps", Level.INFO, proxyMapLevel("INFO")); assertEquals("Config maps", Level.CONFIG, proxyMapLevel(" notice")); assertEquals("Info maps", Level.INFO, proxyMapLevel(" info")); assertEquals("Debug maps", Level.FINEST, proxyMapLevel("debug ")); assertEquals("Info maps", Level.INFO, proxyMapLevel("wibble ")); assertEquals("Info maps", Level.INFO, proxyMapLevel(new Object[] {null})); } |
### Question:
Logging { public static String formatError(final Throwable throwable) { if (throwable == null) { return null; } final StringWriter buffer = new StringWriter(); buffer.append(throwable.getMessage()).append(System.lineSeparator()); throwable.printStackTrace(new PrintWriter(buffer)); final Throwable cause = throwable.getCause(); if (cause != null) { buffer.append(".. caused by ..").append(System.lineSeparator()); buffer.append(Logging.formatError(cause)); } return buffer.toString(); } private Logging(); static String formatError(final Throwable throwable); static void setLogLevel(final String newLevel); static final String PERFLOGGER; }### Answer:
@Test public void testFormatError() { final Exception e1 = new Exception("Computer says no"); assertThat(Logging.formatError(e1), containsString("Computer says no")); final NullPointerException npe1 = new NullPointerException("Nothing here"); npe1.initCause(e1); assertThat(Logging.formatError(npe1), containsString("Computer says no")); assertThat(Logging.formatError(npe1), containsString("Nothing here")); assertThat(Logging.formatError(null), CoreMatchers.nullValue()); } |
### Question:
Logging { public static void setLogLevel(final String newLevel) { final Level l = mapLevel(newLevel); final LogManager logManager = LogManager.getLogManager(); final ArrayList<String> allLoggers = Collections.list(logManager.getLoggerNames()); allLoggers.add("org.hyperledger"); allLoggers.stream().filter(name -> name.startsWith("org.hyperledger")).map(name -> logManager.getLogger(name)).forEach(logger -> { if (logger != null) { logger.setLevel(l); } }); } private Logging(); static String formatError(final Throwable throwable); static void setLogLevel(final String newLevel); static final String PERFLOGGER; }### Answer:
@Test public void testSetLogLevel() { final java.util.logging.Logger l = java.util.logging.Logger.getLogger("org.hyperledger.fabric.test"); final java.util.logging.Logger another = java.util.logging.Logger.getLogger("acme.wibble"); final Level anotherLevel = another.getLevel(); Logging.setLogLevel("debug"); assertThat(l.getLevel(), CoreMatchers.equalTo(Level.FINEST)); assertThat(another.getLevel(), CoreMatchers.equalTo(anotherLevel)); Logging.setLogLevel("dsomethoig"); assertThat(l.getLevel(), CoreMatchers.equalTo(Level.INFO)); assertThat(another.getLevel(), CoreMatchers.equalTo(anotherLevel)); Logging.setLogLevel("ERROR"); assertThat(l.getLevel(), CoreMatchers.equalTo(Level.SEVERE)); assertThat(another.getLevel(), CoreMatchers.equalTo(anotherLevel)); Logging.setLogLevel("INFO"); } |
### Question:
CompositeKey { public List<String> getAttributes() { return attributes; } CompositeKey(final String objectType, final String... attributes); CompositeKey(final String objectType, final List<String> attributes); String getObjectType(); List<String> getAttributes(); @Override String toString(); static CompositeKey parseCompositeKey(final String compositeKey); static void validateSimpleKeys(final String... keys); static final String NAMESPACE; }### Answer:
@Test public void testGetAttributes() { final CompositeKey key = new CompositeKey("abc", Arrays.asList("def", "ghi", "jkl", "mno")); assertThat(key.getObjectType(), is(equalTo("abc"))); assertThat(key.getAttributes(), hasSize(4)); assertThat(key.getAttributes(), contains("def", "ghi", "jkl", "mno")); } |
### Question:
CompositeKey { @Override public String toString() { return compositeKey; } CompositeKey(final String objectType, final String... attributes); CompositeKey(final String objectType, final List<String> attributes); String getObjectType(); List<String> getAttributes(); @Override String toString(); static CompositeKey parseCompositeKey(final String compositeKey); static void validateSimpleKeys(final String... keys); static final String NAMESPACE; }### Answer:
@Test public void testToString() { final CompositeKey key = new CompositeKey("abc", Arrays.asList("def", "ghi", "jkl", "mno")); assertThat(key.toString(), is(equalTo("\u0000abc\u0000def\u0000ghi\u0000jkl\u0000mno\u0000"))); } |
### Question:
AutomaticPermanentBlocksCleanup implements DailyScheduledTask { @Override @Scheduled(cron = "0 0 0 * * *") @SchedulerLock(name = "AutomaticPermanentBlocksCleanup") public void run() { final LocalDate eventRemoveDate = dateTimeProvider.getCurrentDate().minusMonths(3); LOGGER.debug("Removing block events before {}", eventRemoveDate); accessControlListDao.removeBlockEventsBefore(eventRemoveDate); final LocalDate blockRemoveDate = dateTimeProvider.getCurrentDate().minusYears(1); LOGGER.debug("Removing permanent bans before {}", blockRemoveDate); accessControlListDao.removePermanentBlocksBefore(blockRemoveDate); } @Autowired AutomaticPermanentBlocksCleanup(final DateTimeProvider dateTimeProvider, final AccessControlListDao accessControlListDao); @Override @Scheduled(cron = "0 0 0 * * *") @SchedulerLock(name = "AutomaticPermanentBlocksCleanup") void run(); }### Answer:
@Test public void run() { final LocalDate now = LocalDate.now(); when(dateTimeProvider.getCurrentDate()).thenReturn(now); subject.run(); verify(accessControlListDao, times(1)).removePermanentBlocksBefore(argThat(new BaseMatcher<LocalDate>() { @Override public boolean matches(Object item) { return item.equals(now.minusYears(1)); } @Override public void describeTo(Description description) { description.appendText("Should only delete bans older than 1 year"); } })); verify(accessControlListDao, times(1)).removeBlockEventsBefore(argThat(new BaseMatcher<LocalDate>() { @Override public boolean matches(Object item) { return item.equals(now.minusMonths(3)); } @Override public void describeTo(Description description) { description.appendText("Should only delete events older than 3 months"); } })); } |
### Question:
SsoTranslator { public RpslObject translateFromCacheAuthToUuid(final UpdateContext updateContext, final RpslObject rpslObject) { return translateAuthFromCache(updateContext, rpslObject); } @Autowired SsoTranslator(final CrowdClient crowdClient); void populateCacheAuthToUsername(final UpdateContext updateContext, final RpslObject rpslObject); void populateCacheAuthToUuid(final UpdateContext updateContext, final Update update); RpslObject translateFromCacheAuthToUuid(final UpdateContext updateContext, final RpslObject rpslObject); RpslObject translateFromCacheAuthToUsername(final UpdateContext updateContext, final RpslObject rpslObject); }### Answer:
@Test public void translate_to_uuid_username_not_stored_in_context() { final RpslObject object = RpslObject.parse("mntner: TEST-MNT\nauth: SSO [email protected]"); when(updateContext.getSsoTranslationResult("[email protected]")).thenReturn("BBBB-1234-CCCC-DDDD"); final RpslObject result = subject.translateFromCacheAuthToUuid(updateContext, object); assertThat(result, is(RpslObject.parse("mntner: TEST-MNT\nauth: SSO BBBB-1234-CCCC-DDDD"))); verify(updateContext).getSsoTranslationResult("[email protected]"); }
@Test public void translate_to_username_uuid_stored_in_context_already() { final RpslObject object = RpslObject.parse("mntner: TEST-MNT\nauth: SSO aadd-2132-aaa-fff"); when(updateContext.getSsoTranslationResult("aadd-2132-aaa-fff")).thenReturn("[email protected]"); final RpslObject result = subject.translateFromCacheAuthToUuid(updateContext, object); assertThat(result, is(RpslObject.parse("mntner: TEST-MNT\nauth: SSO [email protected]"))); }
@Test public void translate_not_a_maintainer() { final RpslObject object = RpslObject.parse("person: test person\nnic-hdl: test-nic"); final RpslObject result = subject.translateFromCacheAuthToUuid(updateContext, object); verifyZeroInteractions(updateContext); assertThat(result, is(object)); } |
### Question:
SsoTranslator { public void populateCacheAuthToUuid(final UpdateContext updateContext, final Update update) { final RpslObject submittedObject = update.getSubmittedObject(); SsoHelper.translateAuth(submittedObject, new AuthTranslator() { @Override @CheckForNull public RpslAttribute translate(final String authType, final String authToken, final RpslAttribute originalAttribute) { if (authType.equals("SSO")) { if (!updateContext.hasSsoTranslationResult(authToken)) { try { final String uuid = crowdClient.getUuid(authToken); updateContext.addSsoTranslationResult(authToken, uuid); } catch (CrowdClientException e) { updateContext.addMessage(update, originalAttribute, UpdateMessages.ripeAccessAccountUnavailable(authToken)); } } } return null; } }); } @Autowired SsoTranslator(final CrowdClient crowdClient); void populateCacheAuthToUsername(final UpdateContext updateContext, final RpslObject rpslObject); void populateCacheAuthToUuid(final UpdateContext updateContext, final Update update); RpslObject translateFromCacheAuthToUuid(final UpdateContext updateContext, final RpslObject rpslObject); RpslObject translateFromCacheAuthToUsername(final UpdateContext updateContext, final RpslObject rpslObject); }### Answer:
@Test public void populate_not_maintainer_object() { final RpslObject object = RpslObject.parse("aut-num: AS1234"); when(update.getSubmittedObject()).thenReturn(object); subject.populateCacheAuthToUuid(updateContext, update); verifyZeroInteractions(updateContext); }
@Test public void populate_no_sso_auth() { final RpslObject object = RpslObject.parse("mntner: TEST-MNT\nauth: MD5-PW aaff1232431"); when(update.getSubmittedObject()).thenReturn(object); subject.populateCacheAuthToUuid(updateContext, update); verifyZeroInteractions(updateContext); }
@Test public void populate_sso_auth() { final RpslObject object = RpslObject.parse("mntner: TEST-MNT\nauth: SSO [email protected]"); when(update.getSubmittedObject()).thenReturn(object); when(updateContext.hasSsoTranslationResult("[email protected]")).thenReturn(true); subject.populateCacheAuthToUuid(updateContext, update); verify(updateContext, times(0)).addSsoTranslationResult(eq("[email protected]"), anyString()); } |
### Question:
ShortFormatTransformer implements Transformer { @Override public RpslObject transform(final RpslObject rpslObject, final Update update, final UpdateContext updateContext, final Action action) { final RpslObjectBuilder builder = new RpslObjectBuilder(rpslObject); boolean updated = false; final ListIterator<RpslAttribute> iterator = builder.getAttributes().listIterator(); while (iterator.hasNext()) { final RpslAttribute rpslAttribute = iterator.next(); if (rpslAttribute.getType() != null && !rpslAttribute.getType().getName().equals(rpslAttribute.getKey())) { iterator.set(new RpslAttribute(rpslAttribute.getType(), rpslAttribute.getValue())); updated = true; } } if (updated) { updateContext.addMessage(update, UpdateMessages.shortFormatAttributeReplaced()); return builder.get(); } return rpslObject; } @Override RpslObject transform(final RpslObject rpslObject, final Update update, final UpdateContext updateContext, final Action action); }### Answer:
@Test public void dont_transform_no_short_format_attributes() { final RpslObject mntner = RpslObject.parse( "mntner: MINE-MNT\n" + "admin-c: AA1-TEST\n" + "auth: MD5-PW $1$/7f2XnzQ$p5ddbI7SXq4z4yNrObFS/0 # emptypassword\n" + "mnt-by: MINE-MNT\n" + "source: TEST\n"); final RpslObject updatedObject = subject.transform(mntner, update, updateContext, Action.MODIFY); assertThat(updatedObject, is(mntner)); verifyNoMoreInteractions(update); verifyNoMoreInteractions(updateContext); }
@Test public void transform_short_format_attributes() { final RpslObject mntner = RpslObject.parse( "mntner: MINE-MNT\n" + "admin-c: AA1-TEST\n" + "auth: MD5-PW $1$/7f2XnzQ$p5ddbI7SXq4z4yNrObFS/0 # emptypassword\n" + "mb: MINE-MNT # mb\n" + "*mb: MINE-MNT # star mb\n" + "mnt-by: MINE-MNT\n" + "source: TEST\n"); final RpslObject updatedObject = subject.transform(mntner, update, updateContext, Action.MODIFY); assertThat(updatedObject.toString(), is( "mntner: MINE-MNT\n" + "admin-c: AA1-TEST\n" + "auth: MD5-PW $1$/7f2XnzQ$p5ddbI7SXq4z4yNrObFS/0 # emptypassword\n" + "mnt-by: MINE-MNT # mb\n" + "mnt-by: MINE-MNT # star mb\n" + "mnt-by: MINE-MNT\n" + "source: TEST\n")); verify(updateContext).addMessage(update, UpdateMessages.shortFormatAttributeReplaced()); verifyNoMoreInteractions(update); verifyNoMoreInteractions(updateContext); } |
### Question:
ResponseFactory { public String createExceptionResponse(final UpdateContext updateContext, final Origin origin) { final VelocityContext velocityContext = new VelocityContext(); return createResponse(TEMPLATE_EXCEPTION, updateContext, velocityContext, origin); } @Autowired ResponseFactory(
final DateTimeProvider dateTimeProvider,
final ApplicationVersion applicationVersion,
@Value("${whois.source}") final String source); String createExceptionResponse(final UpdateContext updateContext, final Origin origin); String createAckResponse(final UpdateContext updateContext, final Origin origin, final Ack ack); String createHelpResponse(final UpdateContext updateContext, final Origin origin); ResponseMessage createNotification(final UpdateContext updateContext, final Origin origin, final Notification notification); }### Answer:
@Test public void getException() { final String response = subject.createExceptionResponse(updateContext, origin); assertThat(response, containsString("" + "> From: Andre Kampert <[email protected]>\n" + "> Subject: delete route 194.39.132.0/24\n" + "> Date: Thu, 14 Jun 2012 10:04:42 +0200\n" + "> Reply-To: [email protected]\n" + "> Message-ID: <[email protected]>\n" + "\n" + "Internal software error\n" + "\n" + "\n" + "The RIPE Database is subject to Terms and Conditions:\n" + "http: "\n" + "For assistance or clarification please contact:\n" + "RIPE Database Administration <[email protected]>\n")); assertVersion(response); } |
### Question:
ResponseFactory { public String createHelpResponse(final UpdateContext updateContext, final Origin origin) { final VelocityContext velocityContext = new VelocityContext(); return createResponse(TEMPLATE_HELP, updateContext, velocityContext, origin); } @Autowired ResponseFactory(
final DateTimeProvider dateTimeProvider,
final ApplicationVersion applicationVersion,
@Value("${whois.source}") final String source); String createExceptionResponse(final UpdateContext updateContext, final Origin origin); String createAckResponse(final UpdateContext updateContext, final Origin origin, final Ack ack); String createHelpResponse(final UpdateContext updateContext, final Origin origin); ResponseMessage createNotification(final UpdateContext updateContext, final Origin origin, final Notification notification); }### Answer:
@Test public void createHelpResponse() { final String response = subject.createHelpResponse(updateContext, origin); assertThat(response, containsString("" + "> From: Andre Kampert <[email protected]>\n" + "> Subject: delete route 194.39.132.0/24\n" + "> Date: Thu, 14 Jun 2012 10:04:42 +0200\n" + "> Reply-To: [email protected]\n" + "> Message-ID: <[email protected]>\n" + "\n" + "You have requested Help information from the RIPE NCC Database,\n" + "therefore the body of your message has been ignored.\n" + "\n" + "RIPE Database documentation is available at\n" + "\n" + "http: "\n" + "RIPE Database FAQ is available at\n" + "\n" + "http: "\n" + "RPSL RFCs are available at\n" + "\n" + "ftp: "ftp: "ftp: "\n" + "The RIPE Database is subject to Terms and Conditions:\n" + "http: "\n" + "For assistance or clarification please contact:\n" + "RIPE Database Administration <[email protected]>\n")); assertVersion(response); } |
Subsets and Splits