method2testcases
stringlengths
118
3.08k
### Question: LuceneBatchedWorkProcessor implements BatchedWorkProcessor { public void forceCommit() { try { indexAccessor.commit(); } catch (RuntimeException e) { indexAccessor.cleanUpAfterFailure( e, "Commit after a set of index works" ); throw e; } } 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 forceCommit() { processor.forceCommit(); verify( indexAccessorMock ).commit(); verifyNoOtherIndexInteractionsAndClear(); }
### 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 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: 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 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: 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: 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: 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: 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: 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: 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 { 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 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 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: 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: SetNotReferencedValidator implements BusinessRuleValidator { @Override public ImmutableList<Action> getActions() { return ACTIONS; } @Autowired SetNotReferencedValidator(final RpslObjectDao objectDao); @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }### Answer: @Test public void testGetActions() { assertThat(subject.getActions(), containsInAnyOrder(Action.DELETE)); }
### Question: SetNotReferencedValidator implements BusinessRuleValidator { @Override public ImmutableList<ObjectType> getTypes() { return TYPES; } @Autowired SetNotReferencedValidator(final RpslObjectDao objectDao); @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }### Answer: @Test public void testGetTypes() { assertThat(subject.getTypes(), containsInAnyOrder(ObjectType.AS_SET, ObjectType.ROUTE_SET, ObjectType.RTR_SET)); }
### Question: SetNotReferencedValidator implements BusinessRuleValidator { @Override public void validate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject updatedObject = update.getUpdatedObject(); final List<RpslObjectInfo> incomingReferences = objectDao.findMemberOfByObjectTypeWithoutMbrsByRef(updatedObject.getType(), updatedObject.getKey().toString()); if (!incomingReferences.isEmpty()) { updateContext.addMessage(update, UpdateMessages.objectInUse(updatedObject)); } } @Autowired SetNotReferencedValidator(final RpslObjectDao objectDao); @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }### Answer: @Test public void set_that_has_incoming_references() { final RpslObject routeSet = RpslObject.parse("route-set: rs-AH"); when(update.getUpdatedObject()).thenReturn(routeSet); when(objectDao.findMemberOfByObjectTypeWithoutMbrsByRef(ObjectType.ROUTE_SET, "rs-AH")).thenReturn(Lists.newArrayList(new RpslObjectInfo(1, ObjectType.ROUTE, "192.168.0.1/32"))); subject.validate(update, updateContext); verify(updateContext).addMessage(update, UpdateMessages.objectInUse(routeSet)); } @Test public void set_that_has_no_incoming_references() { final RpslObject asSet = RpslObject.parse("as-set: AS1325:AS-lopp"); when(update.getUpdatedObject()).thenReturn(asSet); when(objectDao.findMemberOfByObjectTypeWithoutMbrsByRef(ObjectType.AS_SET, "rs-AH")).thenReturn(Lists.<RpslObjectInfo>newArrayList()); subject.validate(update, updateContext); verify(updateContext, never()).addMessage(update, UpdateMessages.objectInUse(asSet)); }
### Question: PeeringSetAttributeMustBePresent implements BusinessRuleValidator { @Override public ImmutableList<Action> getActions() { return ACTIONS; } PeeringSetAttributeMustBePresent(); @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }### Answer: @Test public void testGetActions() { assertThat(subject.getActions(), containsInAnyOrder(Action.CREATE, Action.MODIFY)); }
### Question: PeeringSetAttributeMustBePresent implements BusinessRuleValidator { @Override public ImmutableList<ObjectType> getTypes() { return TYPES; } PeeringSetAttributeMustBePresent(); @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }### Answer: @Test public void testGetTypes() { assertThat(subject.getTypes(), Matchers.contains(ObjectType.PEERING_SET, ObjectType.FILTER_SET)); }
### Question: SetnameMustExistValidator implements BusinessRuleValidator { @Override public ImmutableList<Action> getActions() { return ACTIONS; } @Autowired SetnameMustExistValidator(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }### Answer: @Test public void getActions() { assertThat(subject.getActions(), containsInAnyOrder(Action.CREATE)); }
### Question: SetnameMustExistValidator implements BusinessRuleValidator { @Override public ImmutableList<ObjectType> getTypes() { return TYPES; } @Autowired SetnameMustExistValidator(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }### Answer: @Test public void getTypes() { assertThat(subject.getTypes(), containsInAnyOrder(ObjectType.AS_SET, ObjectType.FILTER_SET, ObjectType.PEERING_SET, ObjectType.ROUTE_SET, ObjectType.RTR_SET)); }
### Question: OrganisationTypeValidator implements BusinessRuleValidator { @Override public ImmutableList<Action> getActions() { return ACTIONS; } @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }### Answer: @Test public void getActions() { assertThat(subject.getActions().size(), is(2)); assertThat(subject.getActions().contains(Action.MODIFY), is(true)); assertThat(subject.getActions().contains(Action.CREATE), is(true)); }
### Question: OrganisationTypeValidator implements BusinessRuleValidator { @Override public ImmutableList<ObjectType> getTypes() { return TYPES; } @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }### Answer: @Test public void getTypes() { assertThat(subject.getTypes().size(), is(1)); assertThat(subject.getTypes().get(0), is(ObjectType.ORGANISATION)); }
### Question: OrgNameNotChangedValidator implements BusinessRuleValidator { @Override public ImmutableList<Action> getActions() { return ACTIONS; } @Autowired OrgNameNotChangedValidator(final RpslObjectUpdateDao objectUpdateDao, final RpslObjectDao objectDao, final Maintainers maintainers); @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }### Answer: @Test public void getActions() { assertThat(subject.getActions(), contains(Action.MODIFY)); }
### Question: OrgNameNotChangedValidator implements BusinessRuleValidator { @Override public ImmutableList<ObjectType> getTypes() { return TYPES; } @Autowired OrgNameNotChangedValidator(final RpslObjectUpdateDao objectUpdateDao, final RpslObjectDao objectDao, final Maintainers maintainers); @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }### Answer: @Test public void getTypes() { assertThat(subject.getTypes(), contains(ObjectType.ORGANISATION)); }
### Question: LirUserMaintainedAttributesValidator implements BusinessRuleValidator { @Override public ImmutableList<Action> getActions() { return ACTIONS; } @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }### Answer: @Test public void getActions() { assertThat(subject.getActions().size(), is(1)); assertTrue(subject.getActions().contains(Action.MODIFY)); }
### Question: LirUserMaintainedAttributesValidator implements BusinessRuleValidator { @Override public ImmutableList<ObjectType> getTypes() { return TYPES; } @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }### Answer: @Test public void getTypes() { assertThat(subject.getTypes().size(), is(1)); assertTrue(subject.getTypes().contains(ObjectType.ORGANISATION)); }
### Question: AbuseCNoLimitWarningValidator implements BusinessRuleValidator { @Override public ImmutableList<Action> getActions() { return ACTIONS; } @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }### Answer: @Test public void getActions() { assertThat(subject.getActions(), containsInAnyOrder(Action.CREATE, Action.MODIFY)); }
### Question: AbuseCNoLimitWarningValidator implements BusinessRuleValidator { @Override public ImmutableList<ObjectType> getTypes() { return TYPES; } @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }### Answer: @Test public void getTypes() { assertThat(subject.getTypes(), containsInAnyOrder(ObjectType.ROLE)); }
### Question: LirMntByAttributeCountValidator implements BusinessRuleValidator { @Override public ImmutableList<Action> getActions() { return ACTIONS; } @Autowired LirMntByAttributeCountValidator(final Maintainers maintainers); @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }### Answer: @Test public void getActions() { assertThat(subject.getActions().size(), is(2)); assertTrue(subject.getActions().contains(Action.CREATE)); assertTrue(subject.getActions().contains(Action.MODIFY)); }