src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
LegacyMasterProcessChannelEncoder implements MasterProcessChannelEncoder { @Override public void consoleErrorLog( String message ) { consoleErrorLog( message, null ); } LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out ); protected LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out, @Nonnull RunMode runMode ); @Override MasterProcessChannelEncoder asRerunMode(); @Override MasterProcessChannelEncoder asNormalMode(); @Override boolean checkError(); @Override void onJvmExit(); @Override void sendSystemProperties( Map<String, String> sysProps ); @Override void testSetStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSetCompleted( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSucceeded( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testFailed( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSkipped( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testError( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testAssumptionFailure( ReportEntry reportEntry, boolean trimStackTraces ); @Override void stdOut( String msg, boolean newLine ); @Override void stdErr( String msg, boolean newLine ); @Override void consoleInfoLog( String message ); @Override void consoleErrorLog( String message ); @Override void consoleErrorLog( Throwable t ); @Override void consoleErrorLog( String message, Throwable t ); @Override void consoleErrorLog( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); @Override void consoleDebugLog( String message ); @Override void consoleWarningLog( String message ); @Override void bye(); @Override void stopOnNextTest(); @Override void acquireNextTest(); @Override void sendExitError( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); }
@Test public void testConsoleError() { Stream out = Stream.newStream(); LegacyMasterProcessChannelEncoder encoder = new LegacyMasterProcessChannelEncoder( newBufferedChannel( out ) ); encoder.consoleErrorLog( "msg" ); String encoded = new String( out.toByteArray(), UTF_8 ); String expected = ":maven-surefire-event:\u0011:console-error-log:\u0005:UTF-8:" + "\u0000\u0000\u0000\u0003:msg:" + "\u0000\u0000\u0000\u0001:\u0000:" + "\u0000\u0000\u0000\u0001:\u0000:"; assertThat( encoded ) .isEqualTo( expected ); } @Test public void testConsoleErrorLog1() throws IOException { Stream out = Stream.newStream(); LegacyMasterProcessChannelEncoder encoder = new LegacyMasterProcessChannelEncoder( newBufferedChannel( out ) ); Exception e = new Exception( "msg" ); encoder.consoleErrorLog( e ); String stackTrace = ConsoleLoggerUtils.toString( e ); ByteArrayOutputStream expectedFrame = new ByteArrayOutputStream(); expectedFrame.write( ":maven-surefire-event:\u0011:console-error-log:\u0005:UTF-8:".getBytes( UTF_8 ) ); expectedFrame.write( 0 ); expectedFrame.write( 0 ); expectedFrame.write( 0 ); expectedFrame.write( 3 ); expectedFrame.write( ':' ); expectedFrame.write( "msg".getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( 0 ); expectedFrame.write( 0 ); expectedFrame.write( 0 ); expectedFrame.write( 1 ); expectedFrame.write( ':' ); expectedFrame.write( 0 ); expectedFrame.write( ':' ); byte[] stackTraceBytes = stackTrace.getBytes( UTF_8 ); int[] stackTraceLength = toBytes( stackTraceBytes.length ); expectedFrame.write( stackTraceLength[0] ); expectedFrame.write( stackTraceLength[1] ); expectedFrame.write( stackTraceLength[2] ); expectedFrame.write( stackTraceLength[3] ); expectedFrame.write( ':' ); expectedFrame.write( stackTraceBytes ); expectedFrame.write( ':' ); assertThat( out.toByteArray() ) .isEqualTo( expectedFrame.toByteArray() ); } @Test public void testConsoleErrorLog2() throws IOException { Stream out = Stream.newStream(); LegacyMasterProcessChannelEncoder encoder = new LegacyMasterProcessChannelEncoder( newBufferedChannel( out ) ); Exception e = new Exception( "msg" ); encoder.consoleErrorLog( "msg2", e ); String stackTrace = ConsoleLoggerUtils.toString( e ); ByteArrayOutputStream expectedFrame = new ByteArrayOutputStream(); expectedFrame.write( ":maven-surefire-event:\u0011:console-error-log:\u0005:UTF-8:".getBytes( UTF_8 ) ); expectedFrame.write( 0 ); expectedFrame.write( 0 ); expectedFrame.write( 0 ); expectedFrame.write( 4 ); expectedFrame.write( ':' ); expectedFrame.write( "msg2".getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( 0 ); expectedFrame.write( 0 ); expectedFrame.write( 0 ); expectedFrame.write( 1 ); expectedFrame.write( ':' ); expectedFrame.write( 0 ); expectedFrame.write( ':' ); byte[] stackTraceBytes = stackTrace.getBytes( UTF_8 ); int[] stackTraceLength = toBytes( stackTraceBytes.length ); expectedFrame.write( stackTraceLength[0] ); expectedFrame.write( stackTraceLength[1] ); expectedFrame.write( stackTraceLength[2] ); expectedFrame.write( stackTraceLength[3] ); expectedFrame.write( ':' ); expectedFrame.write( stackTraceBytes ); expectedFrame.write( ':' ); assertThat( out.toByteArray() ) .isEqualTo( expectedFrame.toByteArray() ); } @Test public void testConsoleErrorLog3() { Stream out = Stream.newStream(); LegacyMasterProcessChannelEncoder encoder = new LegacyMasterProcessChannelEncoder( newBufferedChannel( out ) ); StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); when( stackTraceWriter.getThrowable() ).thenReturn( new SafeThrowable( "1" ) ); when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( "2" ); when( stackTraceWriter.writeTraceToString() ).thenReturn( "3" ); when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( "4" ); encoder.consoleErrorLog( stackTraceWriter, true ); String encoded = new String( out.toByteArray(), UTF_8 ); assertThat( encoded ) .startsWith( ":maven-surefire-event:\u0011:console-error-log:\u0005:UTF-8:\u0000\u0000\u0000\u0001:1:\u0000\u0000\u0000\u0001:2:\u0000\u0000\u0000\u0001:4:" ); }
LegacyMasterProcessChannelEncoder implements MasterProcessChannelEncoder { @Override public void consoleDebugLog( String message ) { ByteBuffer result = encodeMessage( BOOTERCODE_CONSOLE_DEBUG, null, message ); encodeAndPrintEvent( result, true ); } LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out ); protected LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out, @Nonnull RunMode runMode ); @Override MasterProcessChannelEncoder asRerunMode(); @Override MasterProcessChannelEncoder asNormalMode(); @Override boolean checkError(); @Override void onJvmExit(); @Override void sendSystemProperties( Map<String, String> sysProps ); @Override void testSetStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSetCompleted( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSucceeded( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testFailed( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSkipped( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testError( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testAssumptionFailure( ReportEntry reportEntry, boolean trimStackTraces ); @Override void stdOut( String msg, boolean newLine ); @Override void stdErr( String msg, boolean newLine ); @Override void consoleInfoLog( String message ); @Override void consoleErrorLog( String message ); @Override void consoleErrorLog( Throwable t ); @Override void consoleErrorLog( String message, Throwable t ); @Override void consoleErrorLog( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); @Override void consoleDebugLog( String message ); @Override void consoleWarningLog( String message ); @Override void bye(); @Override void stopOnNextTest(); @Override void acquireNextTest(); @Override void sendExitError( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); }
@Test public void testConsoleDebug() { Stream out = Stream.newStream(); LegacyMasterProcessChannelEncoder encoder = new LegacyMasterProcessChannelEncoder( newBufferedChannel( out ) ); encoder.consoleDebugLog( "msg" ); String encoded = new String( out.toByteArray(), UTF_8 ); String expected = ":maven-surefire-event:\u0011:console-debug-log:\u0005:UTF-8:\u0000\u0000\u0000\u0003:msg:"; assertThat( encoded ) .isEqualTo( expected ); }
LegacyMasterProcessChannelEncoder implements MasterProcessChannelEncoder { @Override public void consoleWarningLog( String message ) { ByteBuffer result = encodeMessage( BOOTERCODE_CONSOLE_WARNING, null, message ); encodeAndPrintEvent( result, true ); } LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out ); protected LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out, @Nonnull RunMode runMode ); @Override MasterProcessChannelEncoder asRerunMode(); @Override MasterProcessChannelEncoder asNormalMode(); @Override boolean checkError(); @Override void onJvmExit(); @Override void sendSystemProperties( Map<String, String> sysProps ); @Override void testSetStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSetCompleted( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSucceeded( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testFailed( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSkipped( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testError( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testAssumptionFailure( ReportEntry reportEntry, boolean trimStackTraces ); @Override void stdOut( String msg, boolean newLine ); @Override void stdErr( String msg, boolean newLine ); @Override void consoleInfoLog( String message ); @Override void consoleErrorLog( String message ); @Override void consoleErrorLog( Throwable t ); @Override void consoleErrorLog( String message, Throwable t ); @Override void consoleErrorLog( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); @Override void consoleDebugLog( String message ); @Override void consoleWarningLog( String message ); @Override void bye(); @Override void stopOnNextTest(); @Override void acquireNextTest(); @Override void sendExitError( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); }
@Test public void testConsoleWarning() { Stream out = Stream.newStream(); LegacyMasterProcessChannelEncoder encoder = new LegacyMasterProcessChannelEncoder( newBufferedChannel( out ) ); encoder.consoleWarningLog( "msg" ); String encoded = new String( out.toByteArray(), UTF_8 ); String expected = ":maven-surefire-event:\u0013:console-warning-log:\u0005:UTF-8:\u0000\u0000\u0000\u0003:msg:"; assertThat( encoded ) .isEqualTo( expected ); }
LegacyMasterProcessChannelEncoder implements MasterProcessChannelEncoder { @Override public void stdOut( String msg, boolean newLine ) { ForkedProcessEventType event = newLine ? BOOTERCODE_STDOUT_NEW_LINE : BOOTERCODE_STDOUT; setOutErr( event, msg ); } LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out ); protected LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out, @Nonnull RunMode runMode ); @Override MasterProcessChannelEncoder asRerunMode(); @Override MasterProcessChannelEncoder asNormalMode(); @Override boolean checkError(); @Override void onJvmExit(); @Override void sendSystemProperties( Map<String, String> sysProps ); @Override void testSetStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSetCompleted( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSucceeded( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testFailed( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSkipped( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testError( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testAssumptionFailure( ReportEntry reportEntry, boolean trimStackTraces ); @Override void stdOut( String msg, boolean newLine ); @Override void stdErr( String msg, boolean newLine ); @Override void consoleInfoLog( String message ); @Override void consoleErrorLog( String message ); @Override void consoleErrorLog( Throwable t ); @Override void consoleErrorLog( String message, Throwable t ); @Override void consoleErrorLog( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); @Override void consoleDebugLog( String message ); @Override void consoleWarningLog( String message ); @Override void bye(); @Override void stopOnNextTest(); @Override void acquireNextTest(); @Override void sendExitError( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); }
@Test public void testStdOutStream() throws IOException { Stream out = Stream.newStream(); WritableBufferedByteChannel channel = newBufferedChannel( out ); LegacyMasterProcessChannelEncoder encoder = new LegacyMasterProcessChannelEncoder( channel ); encoder.stdOut( "msg", false ); channel.close(); String expected = ":maven-surefire-event:\u000e:std-out-stream:" + (char) 10 + ":normal-run:\u0005:UTF-8:\u0000\u0000\u0000\u0003:msg:"; assertThat( new String( out.toByteArray(), UTF_8 ) ) .isEqualTo( expected ); } @Test public void testStdOutStreamLn() throws IOException { Stream out = Stream.newStream(); WritableBufferedByteChannel channel = newBufferedChannel( out ); LegacyMasterProcessChannelEncoder encoder = new LegacyMasterProcessChannelEncoder( channel ); encoder.stdOut( "msg", true ); channel.close(); String expected = ":maven-surefire-event:\u0017:std-out-stream-new-line:" + (char) 10 + ":normal-run:\u0005:UTF-8:\u0000\u0000\u0000\u0003:msg:"; assertThat( new String( out.toByteArray(), UTF_8 ) ) .isEqualTo( expected ); } @Test public void testInterruptHandling() throws IOException { Stream out = Stream.newStream(); WritableBufferedByteChannel channel = newBufferedChannel( out ); LegacyMasterProcessChannelEncoder encoder = new LegacyMasterProcessChannelEncoder( channel ); Thread.currentThread().interrupt(); try { encoder.stdOut( "msg", false ); channel.close(); } finally { assertThat( Thread.interrupted() ) .isTrue(); } assertThat( new String( out.toByteArray(), UTF_8 ) ) .isEqualTo( ":maven-surefire-event:\u000e:std-out-stream:" + (char) 10 + ":normal-run:\u0005:UTF-8:\u0000\u0000\u0000\u0003:msg:" ); }
LegacyMasterProcessChannelEncoder implements MasterProcessChannelEncoder { @Override public void stdErr( String msg, boolean newLine ) { ForkedProcessEventType event = newLine ? BOOTERCODE_STDERR_NEW_LINE : BOOTERCODE_STDERR; setOutErr( event, msg ); } LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out ); protected LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out, @Nonnull RunMode runMode ); @Override MasterProcessChannelEncoder asRerunMode(); @Override MasterProcessChannelEncoder asNormalMode(); @Override boolean checkError(); @Override void onJvmExit(); @Override void sendSystemProperties( Map<String, String> sysProps ); @Override void testSetStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSetCompleted( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSucceeded( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testFailed( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSkipped( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testError( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testAssumptionFailure( ReportEntry reportEntry, boolean trimStackTraces ); @Override void stdOut( String msg, boolean newLine ); @Override void stdErr( String msg, boolean newLine ); @Override void consoleInfoLog( String message ); @Override void consoleErrorLog( String message ); @Override void consoleErrorLog( Throwable t ); @Override void consoleErrorLog( String message, Throwable t ); @Override void consoleErrorLog( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); @Override void consoleDebugLog( String message ); @Override void consoleWarningLog( String message ); @Override void bye(); @Override void stopOnNextTest(); @Override void acquireNextTest(); @Override void sendExitError( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); }
@Test public void testStdErrStream() throws IOException { Stream out = Stream.newStream(); WritableBufferedByteChannel channel = newBufferedChannel( out ); LegacyMasterProcessChannelEncoder encoder = new LegacyMasterProcessChannelEncoder( channel ); encoder.stdErr( "msg", false ); channel.close(); String expected = ":maven-surefire-event:\u000e:std-err-stream:" + (char) 10 + ":normal-run:\u0005:UTF-8:\u0000\u0000\u0000\u0003:msg:"; assertThat( new String( out.toByteArray(), UTF_8 ) ) .isEqualTo( expected ); } @Test public void testStdErrStreamLn() throws IOException { Stream out = Stream.newStream(); WritableBufferedByteChannel channel = newBufferedChannel( out ); LegacyMasterProcessChannelEncoder encoder = new LegacyMasterProcessChannelEncoder( channel ); encoder.stdErr( "msg", true ); channel.close(); String expected = ":maven-surefire-event:\u0017:std-err-stream-new-line:" + (char) 10 + ":normal-run:\u0005:UTF-8:\u0000\u0000\u0000\u0003:msg:"; assertThat( new String( out.toByteArray(), UTF_8 ) ) .isEqualTo( expected ); }
LegacyMasterProcessChannelEncoder implements MasterProcessChannelEncoder { @Override public void sendSystemProperties( Map<String, String> sysProps ) { CharsetEncoder encoder = DEFAULT_STREAM_ENCODING.newEncoder(); ByteBuffer result = null; for ( Iterator<Entry<String, String>> it = sysProps.entrySet().iterator(); it.hasNext(); ) { Entry<String, String> entry = it.next(); String key = entry.getKey(); String value = entry.getValue(); int bufferLength = estimateBufferLength( BOOTERCODE_SYSPROPS, runMode, encoder, 0, key, value ); result = result != null && result.capacity() >= bufferLength ? result : ByteBuffer.allocate( bufferLength ); result.clear(); encode( encoder, result, BOOTERCODE_SYSPROPS, runMode, key, value ); boolean sendImmediately = !it.hasNext(); encodeAndPrintEvent( result, sendImmediately ); } } LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out ); protected LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out, @Nonnull RunMode runMode ); @Override MasterProcessChannelEncoder asRerunMode(); @Override MasterProcessChannelEncoder asNormalMode(); @Override boolean checkError(); @Override void onJvmExit(); @Override void sendSystemProperties( Map<String, String> sysProps ); @Override void testSetStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSetCompleted( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSucceeded( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testFailed( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSkipped( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testError( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testAssumptionFailure( ReportEntry reportEntry, boolean trimStackTraces ); @Override void stdOut( String msg, boolean newLine ); @Override void stdErr( String msg, boolean newLine ); @Override void consoleInfoLog( String message ); @Override void consoleErrorLog( String message ); @Override void consoleErrorLog( Throwable t ); @Override void consoleErrorLog( String message, Throwable t ); @Override void consoleErrorLog( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); @Override void consoleDebugLog( String message ); @Override void consoleWarningLog( String message ); @Override void bye(); @Override void stopOnNextTest(); @Override void acquireNextTest(); @Override void sendExitError( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); }
@Test @SuppressWarnings( "checkstyle:innerassignment" ) public void shouldCountSameNumberOfSystemProperties() throws IOException { Stream stream = Stream.newStream(); WritableBufferedByteChannel channel = newBufferedChannel( stream ); LegacyMasterProcessChannelEncoder encoder = new LegacyMasterProcessChannelEncoder( channel ); Map<String, String> sysProps = ObjectUtils.systemProps(); encoder.sendSystemProperties( sysProps ); channel.close(); for ( Entry<String, String> entry : sysProps.entrySet() ) { int[] k = toBytes( entry.getKey().length() ); int[] v = toBytes( entry.getValue() == null ? 1 : entry.getValue().getBytes( UTF_8 ).length ); ByteArrayOutputStream expectedFrame = new ByteArrayOutputStream(); expectedFrame.write( ":maven-surefire-event:sys-prop:normal-run:UTF-8:".getBytes( UTF_8 ) ); expectedFrame.write( k[0] ); expectedFrame.write( k[1] ); expectedFrame.write( k[2] ); expectedFrame.write( k[3] ); expectedFrame.write( ':' ); expectedFrame.write( v[0] ); expectedFrame.write( v[1] ); expectedFrame.write( v[2] ); expectedFrame.write( v[3] ); expectedFrame.write( ':' ); expectedFrame.write( ( entry.getValue() == null ? "\u0000" : entry.getValue() ).getBytes( UTF_8 ) ); expectedFrame.write( ':' ); assertThat( stream.toByteArray() ) .contains( expectedFrame.toByteArray() ); } }
LegacyMasterProcessChannelEncoder implements MasterProcessChannelEncoder { @Override public void sendExitError( StackTraceWriter stackTraceWriter, boolean trimStackTraces ) { error( stackTraceWriter, trimStackTraces, BOOTERCODE_JVM_EXIT_ERROR, true ); } LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out ); protected LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out, @Nonnull RunMode runMode ); @Override MasterProcessChannelEncoder asRerunMode(); @Override MasterProcessChannelEncoder asNormalMode(); @Override boolean checkError(); @Override void onJvmExit(); @Override void sendSystemProperties( Map<String, String> sysProps ); @Override void testSetStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSetCompleted( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSucceeded( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testFailed( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSkipped( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testError( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testAssumptionFailure( ReportEntry reportEntry, boolean trimStackTraces ); @Override void stdOut( String msg, boolean newLine ); @Override void stdErr( String msg, boolean newLine ); @Override void consoleInfoLog( String message ); @Override void consoleErrorLog( String message ); @Override void consoleErrorLog( Throwable t ); @Override void consoleErrorLog( String message, Throwable t ); @Override void consoleErrorLog( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); @Override void consoleDebugLog( String message ); @Override void consoleWarningLog( String message ); @Override void bye(); @Override void stopOnNextTest(); @Override void acquireNextTest(); @Override void sendExitError( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); }
@Test public void shouldHandleExit() { Stream out = Stream.newStream(); LegacyMasterProcessChannelEncoder encoder = new LegacyMasterProcessChannelEncoder( newBufferedChannel( out ) ); StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); when( stackTraceWriter.getThrowable() ).thenReturn( new SafeThrowable( "1" ) ); when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( "2" ); when( stackTraceWriter.writeTraceToString() ).thenReturn( "3" ); when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( "4" ); encoder.sendExitError( stackTraceWriter, false ); assertThat( new String( out.toByteArray(), UTF_8 ) ) .startsWith( ":maven-surefire-event:\u000e:jvm-exit-error:\u0005:UTF-8:\u0000\u0000\u0000\u0001:1:\u0000\u0000\u0000\u0001:2:\u0000\u0000\u0000\u0001:3:" ); } @Test public void shouldHandleExitWithTrimmedTrace() { Stream out = Stream.newStream(); LegacyMasterProcessChannelEncoder encoder = new LegacyMasterProcessChannelEncoder( newBufferedChannel( out ) ); StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); when( stackTraceWriter.getThrowable() ).thenReturn( new SafeThrowable( "1" ) ); when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( "2" ); when( stackTraceWriter.writeTraceToString() ).thenReturn( "3" ); when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( "4" ); encoder.sendExitError( stackTraceWriter, true ); assertThat( new String( out.toByteArray(), UTF_8 ) ) .startsWith( ":maven-surefire-event:\u000e:jvm-exit-error:\u0005:UTF-8:\u0000\u0000\u0000\u0001:1:\u0000\u0000\u0000\u0001:2:\u0000\u0000\u0000\u0001:4:" ); }
AbstractSurefireMojo extends AbstractMojo implements SurefireExecutionParameters { boolean verifyParameters() throws MojoFailureException, MojoExecutionException { setProperties( new SurefireProperties( getProperties() ) ); if ( isSkipExecution() ) { getConsoleLogger().info( "Tests are skipped." ); return false; } String jvmToUse = getJvm(); if ( toolchain != null ) { getConsoleLogger().info( "Toolchain in maven-" + getPluginName() + "-plugin: " + toolchain ); if ( jvmToUse != null ) { getConsoleLogger().warning( "Toolchains are ignored, 'jvm' parameter is set to " + jvmToUse ); } } if ( !getTestClassesDirectory().exists() && ( getDependenciesToScan() == null || getDependenciesToScan().length == 0 ) ) { if ( TRUE.equals( getFailIfNoTests() ) ) { throw new MojoFailureException( "No tests to run!" ); } getConsoleLogger().info( "No tests to run." ); } else { ensureEnableProcessChecker(); convertDeprecatedForkMode(); ensureWorkingDirectoryExists(); ensureParallelRunningCompatibility(); ensureThreadCountWithPerThread(); warnIfUselessUseSystemClassLoaderParameter(); warnIfDefunctGroupsCombinations(); warnIfRerunClashes(); warnIfWrongShutdownValue(); warnIfNotApplicableSkipAfterFailureCount(); warnIfIllegalTempDir(); warnIfForkCountIsZero(); printDefaultSeedIfNecessary(); } return true; } @Override abstract List<String> getIncludes(); abstract File getIncludesFile(); @Override abstract void setIncludes( List<String> includes ); abstract File getExcludesFile(); abstract File[] getSuiteXmlFiles(); abstract void setSuiteXmlFiles( File[] suiteXmlFiles ); abstract String getRunOrder(); abstract void setRunOrder( String runOrder ); abstract Long getRunOrderRandomSeed(); abstract void setRunOrderRandomSeed( Long runOrderRandomSeed ); @Override void execute(); static SurefireProperties createCopyAndReplaceForkNumPlaceholder( SurefireProperties effectiveSystemProperties, int threadNumber ); RepositorySystem getRepositorySystem(); void setRepositorySystem( RepositorySystem repositorySystem ); DependencyResolver getDependencyResolver(); void setDependencyResolver( DependencyResolver dependencyResolver ); TestListResolver getSpecificTests(); @Override List<String> getExcludes(); @Override void setExcludes( List<String> excludes ); @Override ArtifactRepository getLocalRepository(); @Override void setLocalRepository( ArtifactRepository localRepository ); Properties getSystemProperties(); @SuppressWarnings( "UnusedDeclaration" ) void setSystemProperties( Properties systemProperties ); Map<String, String> getSystemPropertyVariables(); @SuppressWarnings( "UnusedDeclaration" ) void setSystemPropertyVariables( Map<String, String> systemPropertyVariables ); abstract File getSystemPropertiesFile(); @SuppressWarnings( "UnusedDeclaration" ) abstract void setSystemPropertiesFile( File systemPropertiesFile ); void setProperties( Properties properties ); Map<String, Artifact> getPluginArtifactMap(); @SuppressWarnings( "UnusedDeclaration" ) void setPluginArtifactMap( Map<String, Artifact> pluginArtifactMap ); Map<String, Artifact> getProjectArtifactMap(); @SuppressWarnings( "UnusedDeclaration" ) void setProjectArtifactMap( Map<String, Artifact> projectArtifactMap ); String getReportNameSuffix(); @SuppressWarnings( "UnusedDeclaration" ) void setReportNameSuffix( String reportNameSuffix ); boolean isRedirectTestOutputToFile(); @SuppressWarnings( "UnusedDeclaration" ) void setRedirectTestOutputToFile( boolean redirectTestOutputToFile ); Boolean getFailIfNoTests(); void setFailIfNoTests( boolean failIfNoTests ); String getForkMode(); @SuppressWarnings( "UnusedDeclaration" ) void setForkMode( String forkMode ); String getJvm(); String getArgLine(); @SuppressWarnings( "UnusedDeclaration" ) void setArgLine( String argLine ); Map<String, String> getEnvironmentVariables(); @SuppressWarnings( "UnusedDeclaration" ) void setEnvironmentVariables( Map<String, String> environmentVariables ); File getWorkingDirectory(); @SuppressWarnings( "UnusedDeclaration" ) void setWorkingDirectory( File workingDirectory ); boolean isChildDelegation(); @SuppressWarnings( "UnusedDeclaration" ) void setChildDelegation( boolean childDelegation ); String getGroups(); @SuppressWarnings( "UnusedDeclaration" ) void setGroups( String groups ); String getExcludedGroups(); @SuppressWarnings( "UnusedDeclaration" ) void setExcludedGroups( String excludedGroups ); String getJunitArtifactName(); @SuppressWarnings( "UnusedDeclaration" ) void setJunitArtifactName( String junitArtifactName ); String getTestNGArtifactName(); @SuppressWarnings( "UnusedDeclaration" ) void setTestNGArtifactName( String testNGArtifactName ); int getThreadCount(); @SuppressWarnings( "UnusedDeclaration" ) void setThreadCount( int threadCount ); boolean getPerCoreThreadCount(); @SuppressWarnings( "UnusedDeclaration" ) void setPerCoreThreadCount( boolean perCoreThreadCount ); boolean getUseUnlimitedThreads(); @SuppressWarnings( "UnusedDeclaration" ) void setUseUnlimitedThreads( boolean useUnlimitedThreads ); String getParallel(); @SuppressWarnings( "UnusedDeclaration" ) void setParallel( String parallel ); boolean isParallelOptimized(); @SuppressWarnings( "UnusedDeclaration" ) void setParallelOptimized( boolean parallelOptimized ); int getThreadCountSuites(); void setThreadCountSuites( int threadCountSuites ); int getThreadCountClasses(); void setThreadCountClasses( int threadCountClasses ); int getThreadCountMethods(); void setThreadCountMethods( int threadCountMethods ); boolean isTrimStackTrace(); @SuppressWarnings( "UnusedDeclaration" ) void setTrimStackTrace( boolean trimStackTrace ); List<ArtifactRepository> getProjectRemoteRepositories(); @SuppressWarnings( "UnusedDeclaration" ) void setProjectRemoteRepositories( List<ArtifactRepository> projectRemoteRepositories ); List<ArtifactRepository> getRemoteRepositories(); @SuppressWarnings( "UnusedDeclaration" ) void setRemoteRepositories( List<ArtifactRepository> remoteRepositories ); boolean isDisableXmlReport(); @SuppressWarnings( "UnusedDeclaration" ) void setDisableXmlReport( boolean disableXmlReport ); boolean isEnableAssertions(); boolean effectiveIsEnableAssertions(); @SuppressWarnings( "UnusedDeclaration" ) void setEnableAssertions( boolean enableAssertions ); MavenSession getSession(); @SuppressWarnings( "UnusedDeclaration" ) void setSession( MavenSession session ); String getObjectFactory(); @SuppressWarnings( "UnusedDeclaration" ) void setObjectFactory( String objectFactory ); ToolchainManager getToolchainManager(); @SuppressWarnings( "UnusedDeclaration" ) void setToolchainManager( ToolchainManager toolchainManager ); boolean isMavenParallel(); String[] getDependenciesToScan(); void setDependenciesToScan( String[] dependenciesToScan ); PluginDescriptor getPluginDescriptor(); MavenProject getProject(); @SuppressWarnings( "UnusedDeclaration" ) void setProject( MavenProject project ); @Override File getTestSourceDirectory(); @Override void setTestSourceDirectory( File testSourceDirectory ); String getForkCount(); boolean isReuseForks(); String[] getAdditionalClasspathElements(); void setAdditionalClasspathElements( String[] additionalClasspathElements ); String[] getClasspathDependencyExcludes(); void setClasspathDependencyExcludes( String[] classpathDependencyExcludes ); String getClasspathDependencyScopeExclude(); void setClasspathDependencyScopeExclude( String classpathDependencyScopeExclude ); File getProjectBuildDirectory(); void setProjectBuildDirectory( File projectBuildDirectory ); Map<String, String> getJdkToolchain(); void setJdkToolchain( Map<String, String> jdkToolchain ); String getTempDir(); void setTempDir( String tempDir ); }
@Test public void shouldVerifyConfigParameters() throws Exception { Mojo mojo = new Mojo() { @Override public File getTestClassesDirectory() { return new File( System.getProperty( "user.dir" ), "target/test-classes" ); } @Override protected String getEnableProcessChecker() { return "fake"; } }; e.expect( MojoFailureException.class ); e.expectMessage( "Unexpected value 'fake' in the configuration parameter 'enableProcessChecker'." ); mojo.verifyParameters(); }
PpidChecker { static boolean canExecuteUnixPs() { return canExecuteLocalUnixPs() || canExecuteStandardUnixPs(); } PpidChecker( @Nonnull String ppid ); void stop(); @Override String toString(); }
@Test public void canExecuteUnixPs() { assumeTrue( IS_OS_UNIX ); assertThat( PpidChecker.canExecuteUnixPs() ) .as( "Surefire should be tested on real box OS, e.g. Ubuntu or FreeBSD." ) .isTrue(); }
EventConsumerThread extends CloseableDaemonThread { private static String toString( List<String> strings ) { if ( strings.size() == 1 ) { return strings.get( 0 ); } StringBuilder concatenated = new StringBuilder( strings.size() * BUFFER_SIZE ); for ( String s : strings ) { concatenated.append( s ); } return concatenated.toString(); } EventConsumerThread( @Nonnull String threadName, @Nonnull ReadableByteChannel channel, @Nonnull EventHandler<Event> eventHandler, @Nonnull CountdownCloseable countdownCloseable, @Nonnull ForkNodeArguments arguments ); @Override void run(); @Override void disable(); @Override void close(); }
@Test public void shouldDecodeHappyCase() throws Exception { CharsetDecoder decoder = UTF_8.newDecoder() .onMalformedInput( REPLACE ) .onUnmappableCharacter( REPLACE ); ByteBuffer input = ByteBuffer.allocate( 1024 ); input.put( PATTERN2_BYTES ) .flip(); int bytesToDecode = PATTERN2_BYTES.length; CharBuffer output = CharBuffer.allocate( 1024 ); int readBytes = invokeMethod( EventConsumerThread.class, "decodeString", decoder, input, output, bytesToDecode, true, 0 ); assertThat( readBytes ) .isEqualTo( bytesToDecode ); assertThat( output.flip().toString() ) .isEqualTo( PATTERN2 ); } @Test public void shouldDecodeShifted() throws Exception { CharsetDecoder decoder = UTF_8.newDecoder() .onMalformedInput( REPLACE ) .onUnmappableCharacter( REPLACE ); ByteBuffer input = ByteBuffer.allocate( 1024 ); input.put( PATTERN1.getBytes( UTF_8 ) ) .put( 90, (byte) 'A' ) .put( 91, (byte) 'B' ) .put( 92, (byte) 'C' ) .position( 90 ); CharBuffer output = CharBuffer.allocate( 1024 ); int readBytes = invokeMethod( EventConsumerThread.class, "decodeString", decoder, input, output, 2, true, 0 ); assertThat( readBytes ) .isEqualTo( 2 ); assertThat( output.flip().toString() ) .isEqualTo( "AB" ); }
EventConsumerThread extends CloseableDaemonThread { protected int readInt( Memento memento ) throws IOException, MalformedFrameException { read( memento, INT_LENGTH + DELIMITER_LENGTH ); int i = memento.bb.getInt(); checkDelimiter( memento ); return i; } EventConsumerThread( @Nonnull String threadName, @Nonnull ReadableByteChannel channel, @Nonnull EventHandler<Event> eventHandler, @Nonnull CountdownCloseable countdownCloseable, @Nonnull ForkNodeArguments arguments ); @Override void run(); @Override void disable(); @Override void close(); }
@Test public void shouldReadInt() throws Exception { Channel channel = new Channel( new byte[] {0x01, 0x02, 0x03, 0x04, ':'}, 1 ); EventConsumerThread thread = new EventConsumerThread( "t", channel, new MockEventHandler<Event>(), COUNTDOWN_CLOSEABLE, new MockForkNodeArguments() ); Memento memento = thread.new Memento(); memento.bb.position( 0 ).limit( 0 ); assertThat( thread.readInt( memento ) ) .isEqualTo( new BigInteger( new byte[] {0x01, 0x02, 0x03, 0x04} ).intValue() ); }
EventConsumerThread extends CloseableDaemonThread { protected Integer readInteger( Memento memento ) throws IOException, MalformedFrameException { read( memento, BYTE_LENGTH ); boolean isNullObject = memento.bb.get() == 0; if ( isNullObject ) { read( memento, DELIMITER_LENGTH ); checkDelimiter( memento ); return null; } return readInt( memento ); } EventConsumerThread( @Nonnull String threadName, @Nonnull ReadableByteChannel channel, @Nonnull EventHandler<Event> eventHandler, @Nonnull CountdownCloseable countdownCloseable, @Nonnull ForkNodeArguments arguments ); @Override void run(); @Override void disable(); @Override void close(); }
@Test public void shouldReadInteger() throws Exception { Channel channel = new Channel( new byte[] {(byte) 0xff, 0x01, 0x02, 0x03, 0x04, ':'}, 1 ); EventConsumerThread thread = new EventConsumerThread( "t", channel, new MockEventHandler<Event>(), COUNTDOWN_CLOSEABLE, new MockForkNodeArguments() ); Memento memento = thread.new Memento(); memento.bb.position( 0 ).limit( 0 ); assertThat( thread.readInteger( memento ) ) .isEqualTo( new BigInteger( new byte[] {0x01, 0x02, 0x03, 0x04} ).intValue() ); } @Test public void shouldReadNullInteger() throws Exception { Channel channel = new Channel( new byte[] {(byte) 0x00, ':'}, 1 ); EventConsumerThread thread = new EventConsumerThread( "t", channel, new MockEventHandler<Event>(), COUNTDOWN_CLOSEABLE, new MockForkNodeArguments() ); Memento memento = thread.new Memento(); memento.bb.position( 0 ).limit( 0 ); assertThat( thread.readInteger( memento ) ) .isNull(); }
EventConsumerThread extends CloseableDaemonThread { protected String readString( Memento memento ) throws IOException, MalformedFrameException { memento.cb.clear(); int readCount = readInt( memento ); read( memento, readCount + DELIMITER_LENGTH ); final String string; if ( readCount == 0 ) { string = ""; } else if ( readCount == 1 ) { read( memento, 1 ); byte oneChar = memento.bb.get(); string = oneChar == 0 ? null : String.valueOf( (char) oneChar ); } else { string = readString( memento, readCount ); } checkDelimiter( memento ); return string; } EventConsumerThread( @Nonnull String threadName, @Nonnull ReadableByteChannel channel, @Nonnull EventHandler<Event> eventHandler, @Nonnull CountdownCloseable countdownCloseable, @Nonnull ForkNodeArguments arguments ); @Override void run(); @Override void disable(); @Override void close(); }
@Test public void shouldReadString() throws Exception { Channel channel = new Channel( PATTERN1.getBytes(), PATTERN1.length() ); EventConsumerThread thread = new EventConsumerThread( "t", channel, new MockEventHandler<Event>(), COUNTDOWN_CLOSEABLE, new MockForkNodeArguments() ); Memento memento = thread.new Memento(); memento.bb.position( 0 ).limit( 0 ); String s = thread.readString( memento, 10 ); assertThat( s ) .isEqualTo( "0123456789" ); } @Test public void shouldDecode3BytesEncodedSymbol() throws Exception { byte[] encodedSymbol = new byte[] {(byte) -30, (byte) -126, (byte) -84}; int countSymbols = 1024; byte[] input = new byte[encodedSymbol.length * countSymbols]; for ( int i = 0; i < countSymbols; i++ ) { System.arraycopy( encodedSymbol, 0, input, encodedSymbol.length * i, encodedSymbol.length ); } Channel channel = new Channel( input, 2 ); EventConsumerThread thread = new EventConsumerThread( "t", channel, new MockEventHandler<Event>(), COUNTDOWN_CLOSEABLE, new MockForkNodeArguments() ); Memento memento = thread.new Memento(); memento.bb.position( 0 ).limit( 0 ); String decodedOutput = thread.readString( memento, input.length ); assertThat( decodedOutput ) .isEqualTo( new String( input, 0, input.length, UTF_8 ) ); } @Test public void shouldReadEmptyString() throws Exception { byte[] stream = "\u0000\u0000\u0000\u0000::".getBytes( UTF_8 ); Channel channel = new Channel( stream, 1 ); EventConsumerThread thread = new EventConsumerThread( "t", channel, new MockEventHandler<Event>(), COUNTDOWN_CLOSEABLE, new MockForkNodeArguments() ); Memento memento = thread.new Memento(); memento.bb.position( 0 ).limit( 0 ); memento.setCharset( UTF_8 ); assertThat( thread.readString( memento ) ) .isEmpty(); } @Test public void shouldReadNullString() throws Exception { byte[] stream = "\u0000\u0000\u0000\u0001:\u0000:".getBytes( UTF_8 ); Channel channel = new Channel( stream, 1 ); EventConsumerThread thread = new EventConsumerThread( "t", channel, new MockEventHandler<Event>(), COUNTDOWN_CLOSEABLE, new MockForkNodeArguments() ); Memento memento = thread.new Memento(); memento.bb.position( 0 ).limit( 0 ); memento.setCharset( UTF_8 ); assertThat( thread.readString( memento ) ) .isNull(); } @Test public void shouldReadSingleCharString() throws Exception { byte[] stream = "\u0000\u0000\u0000\u0001:A:".getBytes( UTF_8 ); Channel channel = new Channel( stream, 1 ); EventConsumerThread thread = new EventConsumerThread( "t", channel, new MockEventHandler<Event>(), COUNTDOWN_CLOSEABLE, new MockForkNodeArguments() ); Memento memento = thread.new Memento(); memento.bb.position( 0 ).limit( 0 ); memento.setCharset( UTF_8 ); assertThat( thread.readString( memento ) ) .isEqualTo( "A" ); } @Test public void shouldReadThreeCharactersString() throws Exception { byte[] stream = "\u0000\u0000\u0000\u0003:ABC:".getBytes( UTF_8 ); Channel channel = new Channel( stream, 1 ); EventConsumerThread thread = new EventConsumerThread( "t", channel, new MockEventHandler<Event>(), COUNTDOWN_CLOSEABLE, new MockForkNodeArguments() ); Memento memento = thread.new Memento(); memento.bb.position( 0 ).limit( 0 ); memento.setCharset( UTF_8 ); assertThat( thread.readString( memento ) ) .isEqualTo( "ABC" ); }
ScannerUtil { public static boolean isJavaClassFile( String file ) { return file.endsWith( ".class" ); } private ScannerUtil(); @Nonnull static String convertJarFileResourceToJavaClassName( @Nonnull String test ); static boolean isJavaClassFile( String file ); @Deprecated @Nonnull static String convertSlashToSystemFileSeparator( @Nonnull String path ); }
@Test public void shouldBeClassFile() { assertThat( ScannerUtil.isJavaClassFile( "META-INF/MANIFEST.MF" ) ) .isFalse(); assertThat( ScannerUtil.isJavaClassFile( "org/apache/pkg/MyService.class" ) ) .isTrue(); }
EventConsumerThread extends CloseableDaemonThread { protected StreamReadStatus read( Memento memento, int recommendedCount ) throws IOException { ByteBuffer buffer = memento.bb; if ( buffer.remaining() >= recommendedCount && buffer.position() != 0 ) { return OVERFLOW; } else { if ( buffer.position() != 0 && recommendedCount > buffer.capacity() - buffer.position() ) { buffer.compact().flip(); memento.line.positionByteBuffer = 0; } int mark = buffer.position(); buffer.position( buffer.limit() ); buffer.limit( buffer.capacity() ); boolean isEnd = false; while ( !isEnd && buffer.position() - mark < recommendedCount && buffer.position() != buffer.limit() ) { isEnd = channel.read( buffer ) == -1; } buffer.limit( buffer.position() ); buffer.position( mark ); int readBytes = buffer.remaining(); if ( isEnd && readBytes < recommendedCount ) { throw new EOFException(); } else { return readBytes >= recommendedCount ? OVERFLOW : UNDERFLOW; } } } EventConsumerThread( @Nonnull String threadName, @Nonnull ReadableByteChannel channel, @Nonnull EventHandler<Event> eventHandler, @Nonnull CountdownCloseable countdownCloseable, @Nonnull ForkNodeArguments arguments ); @Override void run(); @Override void disable(); @Override void close(); }
@Test( timeout = 60_000L ) public void performanceTest() throws Exception { final long[] staredAt = {0}; final long[] finishedAt = {0}; final AtomicInteger calls = new AtomicInteger(); final int totalCalls = 1_000_000; EventHandler<Event> handler = new EventHandler<Event>() { @Override public void handleEvent( @Nonnull Event event ) { if ( staredAt[0] == 0 ) { staredAt[0] = System.currentTimeMillis(); } if ( calls.incrementAndGet() == totalCalls ) { finishedAt[0] = System.currentTimeMillis(); } } }; final ByteBuffer event = ByteBuffer.allocate( 192 ); event.put( ":maven-surefire-event:".getBytes( UTF_8 ) ); event.put( (byte) 14 ); event.put( ":std-out-stream:".getBytes( UTF_8 ) ); event.put( (byte) 10 ); event.put( ":normal-run:".getBytes( UTF_8 ) ); event.put( (byte) 5 ); event.put( ":UTF-8:".getBytes( UTF_8 ) ); event.putInt( 100 ); event.put( ":0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789:" .getBytes( UTF_8 ) ); event.flip(); byte[] frame = copyOfRange( event.array(), event.arrayOffset(), event.arrayOffset() + event.remaining() ); ReadableByteChannel channel = new Channel( frame, 1024 ) { private int countRounds; @Override public int read( ByteBuffer dst ) { int length = super.read( dst ); if ( length == -1 && countRounds < totalCalls ) { i = 0; length = super.read( dst ); countRounds++; } return length; } }; EventConsumerThread thread = new EventConsumerThread( "t", channel, handler, new CountdownCloseable( new MockCloseable(), 1 ), new MockForkNodeArguments() ); TimeUnit.SECONDS.sleep( 2 ); System.gc(); TimeUnit.SECONDS.sleep( 5 ); System.out.println( "Staring the event thread..." ); thread.start(); thread.join(); long execTime = finishedAt[0] - staredAt[0]; System.out.println( execTime ); assertThat( execTime ) .describedAs( "The performance test should assert 1.0s of read time. " + "The limit 3.6s guarantees that the read time does not exceed this limit on overloaded CPU." ) .isPositive() .isLessThanOrEqualTo( 3_600L ); }
EventConsumerThread extends CloseableDaemonThread { static Map<Segment, RunMode> mapRunModes() { Map<Segment, RunMode> map = new HashMap<>(); for ( RunMode e : RunMode.values() ) { byte[] array = e.geRunmode().getBytes( US_ASCII ); map.put( new Segment( array, 0, array.length ), e ); } return map; } EventConsumerThread( @Nonnull String threadName, @Nonnull ReadableByteChannel channel, @Nonnull EventHandler<Event> eventHandler, @Nonnull CountdownCloseable countdownCloseable, @Nonnull ForkNodeArguments arguments ); @Override void run(); @Override void disable(); @Override void close(); }
@Test public void shouldMapSegmentToEventType() { Map<Segment, RunMode> map = mapRunModes(); assertThat( map ) .hasSize( 2 ); byte[] stream = "normal-run".getBytes( US_ASCII ); Segment segment = new Segment( stream, 0, stream.length ); assertThat( map.get( segment ) ) .isEqualTo( NORMAL_RUN ); stream = "rerun-test-after-failure".getBytes( US_ASCII ); segment = new Segment( stream, 0, stream.length ); assertThat( map.get( segment ) ) .isEqualTo( RERUN_TEST_AFTER_FAILURE ); }
EventConsumerThread extends CloseableDaemonThread { @Nonnull @SuppressWarnings( "checkstyle:magicnumber" ) protected Charset readCharset( Memento memento ) throws IOException, MalformedFrameException { int length = readByte( memento ) & 0xff; read( memento, length + DELIMITER_LENGTH ); ByteBuffer bb = memento.bb; byte[] array = bb.array(); int offset = bb.arrayOffset() + bb.position(); bb.position( bb.position() + length ); boolean isDefaultEncoding = false; if ( length == DEFAULT_STREAM_ENCODING_BYTES.length ) { isDefaultEncoding = true; for ( int i = 0; i < length; i++ ) { isDefaultEncoding &= DEFAULT_STREAM_ENCODING_BYTES[i] == array[offset + i]; } } try { Charset charset = isDefaultEncoding ? DEFAULT_STREAM_ENCODING : Charset.forName( new String( array, offset, length, US_ASCII ) ); checkDelimiter( memento ); return charset; } catch ( IllegalArgumentException e ) { throw new MalformedFrameException( memento.line.positionByteBuffer, bb.position() ); } } EventConsumerThread( @Nonnull String threadName, @Nonnull ReadableByteChannel channel, @Nonnull EventHandler<Event> eventHandler, @Nonnull CountdownCloseable countdownCloseable, @Nonnull ForkNodeArguments arguments ); @Override void run(); @Override void disable(); @Override void close(); }
@Test public void shouldReadDefaultCharset() throws Exception { byte[] stream = "\u0005:UTF-8:".getBytes( US_ASCII ); Channel channel = new Channel( stream, 1 ); EventConsumerThread thread = new EventConsumerThread( "t", channel, new MockEventHandler<Event>(), COUNTDOWN_CLOSEABLE, new MockForkNodeArguments() ); Memento memento = thread.new Memento(); memento.bb.position( 0 ).limit( 0 ); memento.setCharset( UTF_8 ); assertThat( thread.readCharset( memento ) ) .isNotNull() .isEqualTo( UTF_8 ); } @Test public void shouldReadNonDefaultCharset() throws Exception { byte[] stream = ( (char) 10 + ":ISO_8859_1:" ).getBytes( US_ASCII ); Channel channel = new Channel( stream, 1 ); EventConsumerThread thread = new EventConsumerThread( "t", channel, new MockEventHandler<Event>(), COUNTDOWN_CLOSEABLE, new MockForkNodeArguments() ); Memento memento = thread.new Memento(); memento.bb.position( 0 ).limit( 0 ); memento.setCharset( UTF_8 ); assertThat( thread.readCharset( memento ) ) .isNotNull() .isEqualTo( ISO_8859_1 ); } @Test( expected = EventConsumerThread.MalformedFrameException.class ) public void malformedCharset() throws Exception { byte[] stream = ( (char) 8 + ":ISO_8859:" ).getBytes( US_ASCII ); Channel channel = new Channel( stream, 1 ); EventConsumerThread thread = new EventConsumerThread( "t", channel, new MockEventHandler<Event>(), COUNTDOWN_CLOSEABLE, new MockForkNodeArguments() ); Memento memento = thread.new Memento(); memento.bb.position( 0 ).limit( 0 ); memento.setCharset( UTF_8 ); thread.readCharset( memento ); }
EventConsumerThread extends CloseableDaemonThread { static SegmentType[] nextSegmentType( ForkedProcessEventType eventType ) { switch ( eventType ) { case BOOTERCODE_BYE: case BOOTERCODE_STOP_ON_NEXT_TEST: case BOOTERCODE_NEXT_TEST: return EVENT_WITHOUT_DATA; case BOOTERCODE_CONSOLE_ERROR: case BOOTERCODE_JVM_EXIT_ERROR: return EVENT_WITH_ERROR_TRACE; case BOOTERCODE_CONSOLE_INFO: case BOOTERCODE_CONSOLE_DEBUG: case BOOTERCODE_CONSOLE_WARNING: return EVENT_WITH_ONE_STRING; case BOOTERCODE_STDOUT: case BOOTERCODE_STDOUT_NEW_LINE: case BOOTERCODE_STDERR: case BOOTERCODE_STDERR_NEW_LINE: return EVENT_WITH_RUNMODE_AND_ONE_STRING; case BOOTERCODE_SYSPROPS: return EVENT_WITH_RUNMODE_AND_TWO_STRINGS; case BOOTERCODE_TESTSET_STARTING: case BOOTERCODE_TESTSET_COMPLETED: case BOOTERCODE_TEST_STARTING: case BOOTERCODE_TEST_SUCCEEDED: case BOOTERCODE_TEST_FAILED: case BOOTERCODE_TEST_SKIPPED: case BOOTERCODE_TEST_ERROR: case BOOTERCODE_TEST_ASSUMPTIONFAILURE: return EVENT_TEST_CONTROL; default: throw new IllegalArgumentException( "Unknown enum " + eventType ); } } EventConsumerThread( @Nonnull String threadName, @Nonnull ReadableByteChannel channel, @Nonnull EventHandler<Event> eventHandler, @Nonnull CountdownCloseable countdownCloseable, @Nonnull ForkNodeArguments arguments ); @Override void run(); @Override void disable(); @Override void close(); }
@Test public void shouldMapEventTypeToSegmentType() { SegmentType[] segmentTypes = nextSegmentType( BOOTERCODE_BYE ); assertThat( segmentTypes ) .hasSize( 1 ) .containsOnly( END_OF_FRAME ); segmentTypes = nextSegmentType( BOOTERCODE_STOP_ON_NEXT_TEST ); assertThat( segmentTypes ) .hasSize( 1 ) .containsOnly( END_OF_FRAME ); segmentTypes = nextSegmentType( BOOTERCODE_NEXT_TEST ); assertThat( segmentTypes ) .hasSize( 1 ) .containsOnly( END_OF_FRAME ); segmentTypes = nextSegmentType( BOOTERCODE_CONSOLE_ERROR ); assertThat( segmentTypes ) .hasSize( 5 ) .satisfies( new InOrder( STRING_ENCODING, DATA_STRING, DATA_STRING, DATA_STRING, END_OF_FRAME ) ); segmentTypes = nextSegmentType( ForkedProcessEventType.BOOTERCODE_JVM_EXIT_ERROR ); assertThat( segmentTypes ) .hasSize( 5 ) .satisfies( new InOrder( STRING_ENCODING, DATA_STRING, DATA_STRING, DATA_STRING, END_OF_FRAME ) ); segmentTypes = nextSegmentType( BOOTERCODE_CONSOLE_INFO ); assertThat( segmentTypes ) .hasSize( 3 ) .satisfies( new InOrder( STRING_ENCODING, DATA_STRING, END_OF_FRAME ) ); segmentTypes = nextSegmentType( ForkedProcessEventType.BOOTERCODE_CONSOLE_DEBUG ); assertThat( segmentTypes ) .hasSize( 3 ) .satisfies( new InOrder( STRING_ENCODING, DATA_STRING, END_OF_FRAME ) ); segmentTypes = nextSegmentType( ForkedProcessEventType.BOOTERCODE_CONSOLE_WARNING ); assertThat( segmentTypes ) .hasSize( 3 ) .satisfies( new InOrder( STRING_ENCODING, DATA_STRING, END_OF_FRAME ) ); segmentTypes = nextSegmentType( BOOTERCODE_STDOUT ); assertThat( segmentTypes ) .hasSize( 4 ) .satisfies( new InOrder( RUN_MODE, STRING_ENCODING, DATA_STRING, END_OF_FRAME ) ); segmentTypes = nextSegmentType( ForkedProcessEventType.BOOTERCODE_STDOUT_NEW_LINE ); assertThat( segmentTypes ) .hasSize( 4 ) .satisfies( new InOrder( RUN_MODE, STRING_ENCODING, DATA_STRING, END_OF_FRAME ) ); segmentTypes = nextSegmentType( ForkedProcessEventType.BOOTERCODE_STDERR ); assertThat( segmentTypes ) .hasSize( 4 ) .satisfies( new InOrder( RUN_MODE, STRING_ENCODING, DATA_STRING, END_OF_FRAME ) ); segmentTypes = nextSegmentType( ForkedProcessEventType.BOOTERCODE_STDERR_NEW_LINE ); assertThat( segmentTypes ) .hasSize( 4 ) .satisfies( new InOrder( RUN_MODE, STRING_ENCODING, DATA_STRING, END_OF_FRAME ) ); segmentTypes = nextSegmentType( BOOTERCODE_SYSPROPS ); assertThat( segmentTypes ) .hasSize( 5 ) .satisfies( new InOrder( RUN_MODE, STRING_ENCODING, DATA_STRING, DATA_STRING, END_OF_FRAME ) ); segmentTypes = nextSegmentType( BOOTERCODE_TESTSET_STARTING ); assertThat( segmentTypes ) .hasSize( 13 ) .satisfies( new InOrder( RUN_MODE, STRING_ENCODING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_INT, DATA_STRING, DATA_STRING, DATA_STRING, END_OF_FRAME ) ); segmentTypes = nextSegmentType( ForkedProcessEventType.BOOTERCODE_TESTSET_COMPLETED ); assertThat( segmentTypes ) .hasSize( 13 ) .satisfies( new InOrder( RUN_MODE, STRING_ENCODING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_INT, DATA_STRING, DATA_STRING, DATA_STRING, END_OF_FRAME ) ); segmentTypes = nextSegmentType( ForkedProcessEventType.BOOTERCODE_TEST_STARTING ); assertThat( segmentTypes ) .hasSize( 13 ) .satisfies( new InOrder( RUN_MODE, STRING_ENCODING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_INT, DATA_STRING, DATA_STRING, DATA_STRING, END_OF_FRAME ) ); segmentTypes = nextSegmentType( BOOTERCODE_TEST_SUCCEEDED ); assertThat( segmentTypes ) .hasSize( 13 ) .satisfies( new InOrder( RUN_MODE, STRING_ENCODING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_INT, DATA_STRING, DATA_STRING, DATA_STRING, END_OF_FRAME ) ); segmentTypes = nextSegmentType( BOOTERCODE_TEST_FAILED ); assertThat( segmentTypes ) .hasSize( 13 ) .satisfies( new InOrder( RUN_MODE, STRING_ENCODING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_INT, DATA_STRING, DATA_STRING, DATA_STRING, END_OF_FRAME ) ); segmentTypes = nextSegmentType( ForkedProcessEventType.BOOTERCODE_TEST_SKIPPED ); assertThat( segmentTypes ) .hasSize( 13 ) .satisfies( new InOrder( RUN_MODE, STRING_ENCODING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_INT, DATA_STRING, DATA_STRING, DATA_STRING, END_OF_FRAME ) ); segmentTypes = nextSegmentType( ForkedProcessEventType.BOOTERCODE_TEST_ERROR ); assertThat( segmentTypes ) .hasSize( 13 ) .satisfies( new InOrder( RUN_MODE, STRING_ENCODING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_INT, DATA_STRING, DATA_STRING, DATA_STRING, END_OF_FRAME ) ); segmentTypes = nextSegmentType( ForkedProcessEventType.BOOTERCODE_TEST_ASSUMPTIONFAILURE ); assertThat( segmentTypes ) .hasSize( 13 ) .satisfies( new InOrder( RUN_MODE, STRING_ENCODING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_INT, DATA_STRING, DATA_STRING, DATA_STRING, END_OF_FRAME ) ); }
SurefireHelper { public static File replaceForkThreadsInPath( File path, int replacement ) { Deque<String> dirs = new LinkedList<>(); File root = path; while ( !root.exists() ) { dirs.addFirst( replaceThreadNumberPlaceholders( root.getName(), replacement ) ); root = root.getParentFile(); } File replacedPath = root; for ( String dir : dirs ) { replacedPath = new File( replacedPath, dir ); } return replacedPath; } private SurefireHelper(); @Nonnull static String replaceThreadNumberPlaceholders( @Nonnull String argLine, int threadNumber ); static File replaceForkThreadsInPath( File path, int replacement ); static String[] getDumpFilesToPrint(); static void reportExecution( SurefireReportParameters reportParameters, RunResult result, PluginConsoleLogger log, Exception firstForkException ); static List<CommandLineOption> commandLineOptions( MavenSession session, PluginConsoleLogger log ); static void logDebugOrCliShowErrors( String s, PluginConsoleLogger log, Collection<CommandLineOption> cli ); static String escapeToPlatformPath( String path ); static final String DUMP_FILE_PREFIX; static final String DUMP_FILENAME_FORMATTER; static final String DUMPSTREAM_FILENAME_FORMATTER; static final String DUMPSTREAM_FILENAME; static final String DUMP_FILENAME; }
@Test public void shouldReplaceForkNumberPath() { File root = new File( System.getProperty( "user.dir", "" ) ); File pathWithPlaceholder = new File( root, "${surefire.forkNumber}" ); File changed = SurefireHelper.replaceForkThreadsInPath( pathWithPlaceholder, 5 ); assertThat( changed.getPath() ) .isEqualTo( new File( root, "5" ).getPath() ); } @Test public void shouldReplaceLongForkNumberPath() { File root = new File( System.getProperty( "user.dir", "" ) ); File subDir = new File( root, "reports-${surefire.forkNumber}" ); File pathWithPlaceholder = new File( subDir, "subfolder" ); File changed = SurefireHelper.replaceForkThreadsInPath( pathWithPlaceholder, 5 ); assertThat( changed.getPath() ) .isEqualTo( new File( new File( root, "reports-5" ), "subfolder" ).getPath() ); }
EventConsumerThread extends CloseableDaemonThread { static Event toEvent( ForkedProcessEventType eventType, RunMode runMode, List<Object> args ) { switch ( eventType ) { case BOOTERCODE_BYE: return new ControlByeEvent(); case BOOTERCODE_STOP_ON_NEXT_TEST: return new ControlStopOnNextTestEvent(); case BOOTERCODE_NEXT_TEST: return new ControlNextTestEvent(); case BOOTERCODE_CONSOLE_ERROR: return new ConsoleErrorEvent( toStackTraceWriter( args ) ); case BOOTERCODE_JVM_EXIT_ERROR: return new JvmExitErrorEvent( toStackTraceWriter( args ) ); case BOOTERCODE_CONSOLE_INFO: return new ConsoleInfoEvent( (String) args.get( 0 ) ); case BOOTERCODE_CONSOLE_DEBUG: return new ConsoleDebugEvent( (String) args.get( 0 ) ); case BOOTERCODE_CONSOLE_WARNING: return new ConsoleWarningEvent( (String) args.get( 0 ) ); case BOOTERCODE_STDOUT: return new StandardStreamOutEvent( runMode, (String) args.get( 0 ) ); case BOOTERCODE_STDOUT_NEW_LINE: return new StandardStreamOutWithNewLineEvent( runMode, (String) args.get( 0 ) ); case BOOTERCODE_STDERR: return new StandardStreamErrEvent( runMode, (String) args.get( 0 ) ); case BOOTERCODE_STDERR_NEW_LINE: return new StandardStreamErrWithNewLineEvent( runMode, (String) args.get( 0 ) ); case BOOTERCODE_SYSPROPS: String key = (String) args.get( 0 ); String value = (String) args.get( 1 ); return new SystemPropertyEvent( runMode, key, value ); case BOOTERCODE_TESTSET_STARTING: return new TestsetStartingEvent( runMode, toReportEntry( args ) ); case BOOTERCODE_TESTSET_COMPLETED: return new TestsetCompletedEvent( runMode, toReportEntry( args ) ); case BOOTERCODE_TEST_STARTING: return new TestStartingEvent( runMode, toReportEntry( args ) ); case BOOTERCODE_TEST_SUCCEEDED: return new TestSucceededEvent( runMode, toReportEntry( args ) ); case BOOTERCODE_TEST_FAILED: return new TestFailedEvent( runMode, toReportEntry( args ) ); case BOOTERCODE_TEST_SKIPPED: return new TestSkippedEvent( runMode, toReportEntry( args ) ); case BOOTERCODE_TEST_ERROR: return new TestErrorEvent( runMode, toReportEntry( args ) ); case BOOTERCODE_TEST_ASSUMPTIONFAILURE: return new TestAssumptionFailureEvent( runMode, toReportEntry( args ) ); default: throw new IllegalArgumentException( "Missing a branch for the event type " + eventType ); } } EventConsumerThread( @Nonnull String threadName, @Nonnull ReadableByteChannel channel, @Nonnull EventHandler<Event> eventHandler, @Nonnull CountdownCloseable countdownCloseable, @Nonnull ForkNodeArguments arguments ); @Override void run(); @Override void disable(); @Override void close(); }
@Test public void shouldCreateEvent() { Event event = toEvent( BOOTERCODE_BYE, NORMAL_RUN, emptyList() ); assertThat( event ) .isInstanceOf( ControlByeEvent.class ); event = toEvent( BOOTERCODE_STOP_ON_NEXT_TEST, NORMAL_RUN, emptyList() ); assertThat( event ) .isInstanceOf( ControlStopOnNextTestEvent.class ); event = toEvent( BOOTERCODE_NEXT_TEST, NORMAL_RUN, emptyList() ); assertThat( event ) .isInstanceOf( ControlNextTestEvent.class ); List data = asList( "1", "2", "3" ); event = toEvent( BOOTERCODE_CONSOLE_ERROR, NORMAL_RUN, data ); assertThat( event ) .isInstanceOf( ConsoleErrorEvent.class ); ConsoleErrorEvent consoleErrorEvent = (ConsoleErrorEvent) event; assertThat( consoleErrorEvent.getStackTraceWriter().getThrowable().getLocalizedMessage() ) .isEqualTo( "1" ); assertThat( consoleErrorEvent.getStackTraceWriter().smartTrimmedStackTrace() ) .isEqualTo( "2" ); assertThat( consoleErrorEvent.getStackTraceWriter().writeTraceToString() ) .isEqualTo( "3" ); data = asList( null, null, null ); event = toEvent( BOOTERCODE_CONSOLE_ERROR, NORMAL_RUN, data ); assertThat( event ) .isInstanceOf( ConsoleErrorEvent.class ); consoleErrorEvent = (ConsoleErrorEvent) event; assertThat( consoleErrorEvent.getStackTraceWriter() ) .isNull(); data = asList( "1", "2", "3" ); event = toEvent( BOOTERCODE_JVM_EXIT_ERROR, NORMAL_RUN, data ); assertThat( event ) .isInstanceOf( JvmExitErrorEvent.class ); JvmExitErrorEvent jvmExitErrorEvent = (JvmExitErrorEvent) event; assertThat( jvmExitErrorEvent.getStackTraceWriter().getThrowable().getLocalizedMessage() ) .isEqualTo( "1" ); assertThat( jvmExitErrorEvent.getStackTraceWriter().smartTrimmedStackTrace() ) .isEqualTo( "2" ); assertThat( jvmExitErrorEvent.getStackTraceWriter().writeTraceToString() ) .isEqualTo( "3" ); data = asList( null, null, null ); event = toEvent( BOOTERCODE_JVM_EXIT_ERROR, NORMAL_RUN, data ); assertThat( event ) .isInstanceOf( JvmExitErrorEvent.class ); jvmExitErrorEvent = (JvmExitErrorEvent) event; assertThat( jvmExitErrorEvent.getStackTraceWriter() ) .isNull(); data = singletonList( "m" ); event = toEvent( BOOTERCODE_CONSOLE_INFO, NORMAL_RUN, data ); assertThat( event ).isInstanceOf( ConsoleInfoEvent.class ); assertThat( ( (ConsoleInfoEvent) event ).getMessage() ).isEqualTo( "m" ); data = singletonList( "" ); event = toEvent( BOOTERCODE_CONSOLE_WARNING, NORMAL_RUN, data ); assertThat( event ).isInstanceOf( ConsoleWarningEvent.class ); assertThat( ( (ConsoleWarningEvent) event ).getMessage() ).isEmpty(); data = singletonList( null ); event = toEvent( BOOTERCODE_CONSOLE_DEBUG, NORMAL_RUN, data ); assertThat( event ).isInstanceOf( ConsoleDebugEvent.class ); assertThat( ( (ConsoleDebugEvent) event ).getMessage() ).isNull(); data = singletonList( "m" ); event = toEvent( BOOTERCODE_STDOUT, NORMAL_RUN, data ); assertThat( event ).isInstanceOf( StandardStreamOutEvent.class ); assertThat( ( (StandardStreamOutEvent) event ).getMessage() ).isEqualTo( "m" ); assertThat( ( (StandardStreamOutEvent) event ).getRunMode() ).isEqualTo( NORMAL_RUN ); data = singletonList( null ); event = toEvent( BOOTERCODE_STDOUT_NEW_LINE, RERUN_TEST_AFTER_FAILURE, data ); assertThat( event ).isInstanceOf( StandardStreamOutWithNewLineEvent.class ); assertThat( ( (StandardStreamOutWithNewLineEvent) event ).getMessage() ).isNull(); assertThat( ( (StandardStreamOutWithNewLineEvent) event ).getRunMode() ).isEqualTo( RERUN_TEST_AFTER_FAILURE ); data = singletonList( null ); event = toEvent( BOOTERCODE_STDERR, RERUN_TEST_AFTER_FAILURE, data ); assertThat( event ).isInstanceOf( StandardStreamErrEvent.class ); assertThat( ( (StandardStreamErrEvent) event ).getMessage() ).isNull(); assertThat( ( (StandardStreamErrEvent) event ).getRunMode() ).isEqualTo( RERUN_TEST_AFTER_FAILURE ); data = singletonList( "abc" ); event = toEvent( BOOTERCODE_STDERR_NEW_LINE, NORMAL_RUN, data ); assertThat( event ).isInstanceOf( StandardStreamErrWithNewLineEvent.class ); assertThat( ( (StandardStreamErrWithNewLineEvent) event ).getMessage() ).isEqualTo( "abc" ); assertThat( ( (StandardStreamErrWithNewLineEvent) event ).getRunMode() ).isEqualTo( NORMAL_RUN ); data = asList( "key", "value" ); event = toEvent( BOOTERCODE_SYSPROPS, NORMAL_RUN, data ); assertThat( event ).isInstanceOf( SystemPropertyEvent.class ); assertThat( ( (SystemPropertyEvent) event ).getKey() ).isEqualTo( "key" ); assertThat( ( (SystemPropertyEvent) event ).getValue() ).isEqualTo( "value" ); assertThat( ( (SystemPropertyEvent) event ).getRunMode() ).isEqualTo( NORMAL_RUN ); data = asList( "source", "sourceText", "name", "nameText", "group", "message", 5, "traceMessage", "smartTrimmedStackTrace", "stackTrace" ); event = toEvent( BOOTERCODE_TESTSET_STARTING, NORMAL_RUN, data ); assertThat( event ).isInstanceOf( TestsetStartingEvent.class ); assertThat( ( (TestsetStartingEvent) event ).getRunMode() ).isEqualTo( NORMAL_RUN ); assertThat( ( (TestsetStartingEvent) event ).getReportEntry().getSourceName() ).isEqualTo( "source" ); assertThat( ( (TestsetStartingEvent) event ).getReportEntry().getSourceText() ).isEqualTo( "sourceText" ); assertThat( ( (TestsetStartingEvent) event ).getReportEntry().getName() ).isEqualTo( "name" ); assertThat( ( (TestsetStartingEvent) event ).getReportEntry().getNameText() ).isEqualTo( "nameText" ); assertThat( ( (TestsetStartingEvent) event ).getReportEntry().getGroup() ).isEqualTo( "group" ); assertThat( ( (TestsetStartingEvent) event ).getReportEntry().getMessage() ).isEqualTo( "message" ); assertThat( ( (TestsetStartingEvent) event ).getReportEntry().getElapsed() ).isEqualTo( 5 ); assertThat( ( (TestsetStartingEvent) event ) .getReportEntry().getStackTraceWriter().getThrowable().getLocalizedMessage() ) .isEqualTo( "traceMessage" ); assertThat( ( (TestsetStartingEvent) event ).getReportEntry().getStackTraceWriter().smartTrimmedStackTrace() ) .isEqualTo( "smartTrimmedStackTrace" ); assertThat( ( (TestsetStartingEvent) event ).getReportEntry().getStackTraceWriter().writeTraceToString() ) .isEqualTo( "stackTrace" ); data = asList( "source", "sourceText", "name", "nameText", "group", null, 5, "traceMessage", "smartTrimmedStackTrace", "stackTrace" ); event = toEvent( BOOTERCODE_TESTSET_COMPLETED, NORMAL_RUN, data ); assertThat( event ).isInstanceOf( TestsetCompletedEvent.class ); assertThat( ( (TestsetCompletedEvent) event ).getRunMode() ).isEqualTo( NORMAL_RUN ); assertThat( ( (TestsetCompletedEvent) event ).getReportEntry().getSourceName() ).isEqualTo( "source" ); assertThat( ( (TestsetCompletedEvent) event ).getReportEntry().getSourceText() ).isEqualTo( "sourceText" ); assertThat( ( (TestsetCompletedEvent) event ).getReportEntry().getName() ).isEqualTo( "name" ); assertThat( ( (TestsetCompletedEvent) event ).getReportEntry().getNameText() ).isEqualTo( "nameText" ); assertThat( ( (TestsetCompletedEvent) event ).getReportEntry().getGroup() ).isEqualTo( "group" ); assertThat( ( (TestsetCompletedEvent) event ).getReportEntry().getMessage() ).isNull(); assertThat( ( (TestsetCompletedEvent) event ).getReportEntry().getElapsed() ).isEqualTo( 5 ); assertThat( ( (TestsetCompletedEvent) event ) .getReportEntry().getStackTraceWriter().getThrowable().getLocalizedMessage() ) .isEqualTo( "traceMessage" ); assertThat( ( (TestsetCompletedEvent) event ).getReportEntry().getStackTraceWriter().smartTrimmedStackTrace() ) .isEqualTo( "smartTrimmedStackTrace" ); assertThat( ( (TestsetCompletedEvent) event ).getReportEntry().getStackTraceWriter().writeTraceToString() ) .isEqualTo( "stackTrace" ); data = asList( "source", "sourceText", "name", "nameText", "group", "message", 5, null, "smartTrimmedStackTrace", "stackTrace" ); event = toEvent( BOOTERCODE_TEST_STARTING, NORMAL_RUN, data ); assertThat( event ).isInstanceOf( TestStartingEvent.class ); assertThat( ( (TestStartingEvent) event ).getRunMode() ).isEqualTo( NORMAL_RUN ); assertThat( ( (TestStartingEvent) event ).getReportEntry().getSourceName() ).isEqualTo( "source" ); assertThat( ( (TestStartingEvent) event ).getReportEntry().getSourceText() ).isEqualTo( "sourceText" ); assertThat( ( (TestStartingEvent) event ).getReportEntry().getName() ).isEqualTo( "name" ); assertThat( ( (TestStartingEvent) event ).getReportEntry().getNameText() ).isEqualTo( "nameText" ); assertThat( ( (TestStartingEvent) event ).getReportEntry().getGroup() ).isEqualTo( "group" ); assertThat( ( (TestStartingEvent) event ).getReportEntry().getMessage() ).isEqualTo( "message" ); assertThat( ( (TestStartingEvent) event ).getReportEntry().getElapsed() ).isEqualTo( 5 ); assertThat( ( (TestStartingEvent) event ) .getReportEntry().getStackTraceWriter().getThrowable().getLocalizedMessage() ) .isNull(); assertThat( ( (TestStartingEvent) event ).getReportEntry().getStackTraceWriter().smartTrimmedStackTrace() ) .isEqualTo( "smartTrimmedStackTrace" ); assertThat( ( (TestStartingEvent) event ).getReportEntry().getStackTraceWriter().writeTraceToString() ) .isEqualTo( "stackTrace" ); data = asList( "source", "sourceText", "name", "nameText", "group", "message", 5, null, null, null ); event = toEvent( BOOTERCODE_TEST_SUCCEEDED, NORMAL_RUN, data ); assertThat( event ).isInstanceOf( TestSucceededEvent.class ); assertThat( ( (TestSucceededEvent) event ).getRunMode() ).isEqualTo( NORMAL_RUN ); assertThat( ( (TestSucceededEvent) event ).getReportEntry().getSourceName() ).isEqualTo( "source" ); assertThat( ( (TestSucceededEvent) event ).getReportEntry().getSourceText() ).isEqualTo( "sourceText" ); assertThat( ( (TestSucceededEvent) event ).getReportEntry().getName() ).isEqualTo( "name" ); assertThat( ( (TestSucceededEvent) event ).getReportEntry().getNameText() ).isEqualTo( "nameText" ); assertThat( ( (TestSucceededEvent) event ).getReportEntry().getGroup() ).isEqualTo( "group" ); assertThat( ( (TestSucceededEvent) event ).getReportEntry().getMessage() ).isEqualTo( "message" ); assertThat( ( (TestSucceededEvent) event ).getReportEntry().getElapsed() ).isEqualTo( 5 ); assertThat( ( (TestSucceededEvent) event ).getReportEntry().getStackTraceWriter() ).isNull(); data = asList( "source", null, "name", null, "group", null, 5, "traceMessage", "smartTrimmedStackTrace", "stackTrace" ); event = toEvent( BOOTERCODE_TEST_FAILED, RERUN_TEST_AFTER_FAILURE, data ); assertThat( event ).isInstanceOf( TestFailedEvent.class ); assertThat( ( (TestFailedEvent) event ).getRunMode() ).isEqualTo( RERUN_TEST_AFTER_FAILURE ); assertThat( ( (TestFailedEvent) event ).getReportEntry().getSourceName() ).isEqualTo( "source" ); assertThat( ( (TestFailedEvent) event ).getReportEntry().getSourceText() ).isNull(); assertThat( ( (TestFailedEvent) event ).getReportEntry().getName() ).isEqualTo( "name" ); assertThat( ( (TestFailedEvent) event ).getReportEntry().getNameText() ).isNull(); assertThat( ( (TestFailedEvent) event ).getReportEntry().getGroup() ).isEqualTo( "group" ); assertThat( ( (TestFailedEvent) event ).getReportEntry().getMessage() ).isNull(); assertThat( ( (TestFailedEvent) event ).getReportEntry().getElapsed() ).isEqualTo( 5 ); assertThat( ( (TestFailedEvent) event ) .getReportEntry().getStackTraceWriter().getThrowable().getLocalizedMessage() ) .isEqualTo( "traceMessage" ); assertThat( ( (TestFailedEvent) event ).getReportEntry().getStackTraceWriter().smartTrimmedStackTrace() ) .isEqualTo( "smartTrimmedStackTrace" ); assertThat( ( (TestFailedEvent) event ).getReportEntry().getStackTraceWriter().writeTraceToString() ) .isEqualTo( "stackTrace" ); data = asList( "source", null, "name", null, null, null, 5, null, null, "stackTrace" ); event = toEvent( BOOTERCODE_TEST_SKIPPED, NORMAL_RUN, data ); assertThat( event ).isInstanceOf( TestSkippedEvent.class ); assertThat( ( (TestSkippedEvent) event ).getRunMode() ).isEqualTo( NORMAL_RUN ); assertThat( ( (TestSkippedEvent) event ).getReportEntry().getSourceName() ).isEqualTo( "source" ); assertThat( ( (TestSkippedEvent) event ).getReportEntry().getSourceText() ).isNull(); assertThat( ( (TestSkippedEvent) event ).getReportEntry().getName() ).isEqualTo( "name" ); assertThat( ( (TestSkippedEvent) event ).getReportEntry().getNameText() ).isNull(); assertThat( ( (TestSkippedEvent) event ).getReportEntry().getGroup() ).isNull(); assertThat( ( (TestSkippedEvent) event ).getReportEntry().getMessage() ).isNull(); assertThat( ( (TestSkippedEvent) event ).getReportEntry().getElapsed() ).isEqualTo( 5 ); assertThat( ( (TestSkippedEvent) event ) .getReportEntry().getStackTraceWriter().getThrowable().getLocalizedMessage() ) .isNull(); assertThat( ( (TestSkippedEvent) event ) .getReportEntry().getStackTraceWriter().smartTrimmedStackTrace() ) .isNull(); assertThat( ( (TestSkippedEvent) event ) .getReportEntry().getStackTraceWriter().writeTraceToString() ) .isEqualTo( "stackTrace" ); data = asList( "source", null, "name", "nameText", null, null, 0, null, null, "stackTrace" ); event = toEvent( BOOTERCODE_TEST_ERROR, NORMAL_RUN, data ); assertThat( event ).isInstanceOf( TestErrorEvent.class ); assertThat( ( (TestErrorEvent) event ).getRunMode() ).isEqualTo( NORMAL_RUN ); assertThat( ( (TestErrorEvent) event ).getReportEntry().getSourceName() ).isEqualTo( "source" ); assertThat( ( (TestErrorEvent) event ).getReportEntry().getSourceText() ).isNull(); assertThat( ( (TestErrorEvent) event ).getReportEntry().getName() ).isEqualTo( "name" ); assertThat( ( (TestErrorEvent) event ).getReportEntry().getNameText() ).isEqualTo( "nameText" ); assertThat( ( (TestErrorEvent) event ).getReportEntry().getGroup() ).isNull(); assertThat( ( (TestErrorEvent) event ).getReportEntry().getMessage() ).isNull(); assertThat( ( (TestErrorEvent) event ).getReportEntry().getElapsed() ).isZero(); assertThat( ( (TestErrorEvent) event ) .getReportEntry().getStackTraceWriter().getThrowable().getLocalizedMessage() ) .isNull(); assertThat( ( (TestErrorEvent) event ) .getReportEntry().getStackTraceWriter().smartTrimmedStackTrace() ) .isNull(); assertThat( ( (TestErrorEvent) event ) .getReportEntry().getStackTraceWriter().writeTraceToString() ) .isEqualTo( "stackTrace" ); data = asList( "source", null, "name", null, "group", null, 5, null, null, "stackTrace" ); event = toEvent( BOOTERCODE_TEST_ASSUMPTIONFAILURE, NORMAL_RUN, data ); assertThat( event ).isInstanceOf( TestAssumptionFailureEvent.class ); assertThat( ( (TestAssumptionFailureEvent) event ).getRunMode() ).isEqualTo( NORMAL_RUN ); assertThat( ( (TestAssumptionFailureEvent) event ).getReportEntry().getSourceName() ).isEqualTo( "source" ); assertThat( ( (TestAssumptionFailureEvent) event ).getReportEntry().getSourceText() ).isNull(); assertThat( ( (TestAssumptionFailureEvent) event ).getReportEntry().getName() ).isEqualTo( "name" ); assertThat( ( (TestAssumptionFailureEvent) event ).getReportEntry().getNameText() ).isNull(); assertThat( ( (TestAssumptionFailureEvent) event ).getReportEntry().getGroup() ).isEqualTo( "group" ); assertThat( ( (TestAssumptionFailureEvent) event ).getReportEntry().getMessage() ).isNull(); assertThat( ( (TestAssumptionFailureEvent) event ).getReportEntry().getElapsed() ).isEqualTo( 5 ); assertThat( ( (TestAssumptionFailureEvent) event ) .getReportEntry().getStackTraceWriter().getThrowable().getLocalizedMessage() ) .isNull(); assertThat( ( (TestAssumptionFailureEvent) event ) .getReportEntry().getStackTraceWriter().smartTrimmedStackTrace() ) .isNull(); assertThat( ( (TestAssumptionFailureEvent) event ) .getReportEntry().getStackTraceWriter().writeTraceToString() ) .isEqualTo( "stackTrace" ); }
StreamFeeder extends CloseableDaemonThread { public static byte[] encode( MasterProcessCommand cmdType, String data ) { if ( !cmdType.hasDataType() ) { throw new IllegalArgumentException( "cannot use data without data type" ); } if ( cmdType.getDataType() != String.class ) { throw new IllegalArgumentException( "Data type can be only " + String.class ); } return encode( COMMAND_OPCODES.get( cmdType ), data ) .toString() .getBytes( US_ASCII ); } StreamFeeder( @Nonnull String threadName, @Nonnull WritableByteChannel channel, @Nonnull CommandReader commandReader, @Nonnull ConsoleLogger logger ); @Override @SuppressWarnings( "checkstyle:innerassignment" ) void run(); void disable(); Throwable getException(); @Override void close(); static byte[] encode( MasterProcessCommand cmdType, String data ); static byte[] encode( MasterProcessCommand cmdType ); }
@Test( expected = IllegalArgumentException.class ) public void shouldFailWithoutData() { StreamFeeder.encode( RUN_CLASS ); } @Test( expected = IllegalArgumentException.class ) public void shouldFailWithData() { StreamFeeder.encode( NOOP, "" ); }
ForkConfiguration { @Nonnull public abstract OutputStreamFlushableCommandline createCommandLine( @Nonnull StartupConfiguration config, int forkNumber, @Nonnull File dumpLogDirectory ) throws SurefireBooterForkException; @Nonnull abstract ForkNodeFactory getForkNodeFactory(); @Nonnull abstract File getTempDirectory(); @Nonnull abstract OutputStreamFlushableCommandline createCommandLine( @Nonnull StartupConfiguration config, int forkNumber, @Nonnull File dumpLogDirectory ); }
@Test @SuppressWarnings( { "checkstyle:methodname", "checkstyle:magicnumber" } ) public void testCreateCommandLine_UseSystemClassLoaderForkOnce_ShouldConstructManifestOnlyJar() throws IOException, SurefireBooterForkException { ForkConfiguration config = getForkConfiguration( basedir, null ); File cpElement = getTempClasspathFile(); List<String> cp = singletonList( cpElement.getAbsolutePath() ); ClasspathConfiguration cpConfig = new ClasspathConfiguration( new Classpath( cp ), emptyClasspath(), emptyClasspath(), true, true ); ClassLoaderConfiguration clc = new ClassLoaderConfiguration( true, true ); StartupConfiguration startup = new StartupConfiguration( "", cpConfig, clc, ALL, Collections.<String[]>emptyList() ); Commandline cli = config.createCommandLine( startup, 1, temporaryFolder() ); String line = StringUtils.join( cli.getCommandline(), " " ); assertTrue( line.contains( "-jar" ) ); } @Test public void testArglineWithNewline() throws IOException, SurefireBooterForkException { ForkConfiguration config = getForkConfiguration( basedir, "abc\ndef" ); File cpElement = getTempClasspathFile(); List<String> cp = singletonList( cpElement.getAbsolutePath() ); ClasspathConfiguration cpConfig = new ClasspathConfiguration( new Classpath( cp ), emptyClasspath(), emptyClasspath(), true, true ); ClassLoaderConfiguration clc = new ClassLoaderConfiguration( true, true ); StartupConfiguration startup = new StartupConfiguration( "", cpConfig, clc, ALL, Collections.<String[]>emptyList() ); Commandline commandLine = config.createCommandLine( startup, 1, temporaryFolder() ); assertTrue( commandLine.toString().contains( "abc def" ) ); } @Test public void testExceptionWhenCurrentDirectoryIsNotRealDirectory() throws IOException { File cwd = new File( basedir, "cwd.txt" ); FileUtils.touch( cwd ); try { ForkConfiguration config = getForkConfiguration( cwd.getCanonicalFile() ); config.createCommandLine( STARTUP_CONFIG, 1, temporaryFolder() ); } catch ( SurefireBooterForkException e ) { String absolutePath = cwd.getCanonicalPath(); assertEquals( "WorkingDirectory " + absolutePath + " exists and is not a directory", e.getMessage() ); return; } finally { assertTrue( cwd.delete() ); } fail(); } @Test public void testExceptionWhenCurrentDirectoryCannotBeCreated() throws IOException { File cwd = new File( basedir, "?\u0000InvalidDirectoryName" ); try { ForkConfiguration config = getForkConfiguration( cwd.getAbsoluteFile() ); config.createCommandLine( STARTUP_CONFIG, 1, temporaryFolder() ); } catch ( SurefireBooterForkException sbfe ) { assertEquals( "Cannot create workingDirectory " + cwd.getAbsolutePath(), sbfe.getMessage() ); return; } finally { FileUtils.deleteDirectory( cwd ); } if ( SystemUtils.IS_OS_WINDOWS || isJavaVersionAtLeast7u60() ) { fail(); } }
JarManifestForkConfiguration extends AbstractClasspathForkConfiguration { static String escapeUri( String input, Charset encoding ) { try { String uriFormEncoded = URLEncoder.encode( input, encoding.name() ); String uriPathEncoded = uriFormEncoded.replaceAll( "\\+", "%20" ); uriPathEncoded = uriPathEncoded.replaceAll( "%2F|%5C", "/" ); return uriPathEncoded; } catch ( UnsupportedEncodingException e ) { throw new IllegalStateException( "avoided by using Charset" ); } } @SuppressWarnings( "checkstyle:parameternumber" ) JarManifestForkConfiguration( @Nonnull Classpath bootClasspath, @Nonnull File tempDirectory, @Nullable String debugLine, @Nonnull File workingDirectory, @Nonnull Properties modelProperties, @Nullable String argLine, @Nonnull Map<String, String> environmentVariables, @Nonnull String[] excludedEnvironmentVariables, boolean debug, int forkCount, boolean reuseForks, @Nonnull Platform pluginPlatform, @Nonnull ConsoleLogger log, @Nonnull ForkNodeFactory forkNodeFactory ); }
@Test @SuppressWarnings( "checkstyle:magicnumber" ) public void shouldEscapeUri() throws Exception { assertThat( escapeUri( "a", UTF_8 ) ).isEqualTo( "a" ); assertThat( escapeUri( " ", UTF_8 ) ).isEqualTo( "%20" ); assertThat( escapeUri( "%", UTF_8 ) ).isEqualTo( "%25" ); assertThat( escapeUri( "+", UTF_8 ) ).isEqualTo( "%2B" ); assertThat( escapeUri( ",", UTF_8 ) ).isEqualTo( "%2C" ); assertThat( escapeUri( "/", UTF_8 ) ).isEqualTo( "/" ); assertThat( escapeUri( "7", UTF_8 ) ).isEqualTo( "7" ); assertThat( escapeUri( ":", UTF_8 ) ).isEqualTo( "%3A" ); assertThat( escapeUri( "@", UTF_8 ) ).isEqualTo( "%40" ); assertThat( escapeUri( "A", UTF_8 ) ).isEqualTo( "A" ); assertThat( escapeUri( "[", UTF_8 ) ).isEqualTo( "%5B" ); assertThat( escapeUri( "\\", UTF_8 ) ).isEqualTo( "/" ); assertThat( escapeUri( "]", UTF_8 ) ).isEqualTo( "%5D" ); assertThat( escapeUri( "`", UTF_8 ) ).isEqualTo( "%60" ); assertThat( escapeUri( "a", UTF_8 ) ).isEqualTo( "a" ); assertThat( escapeUri( "{", UTF_8 ) ).isEqualTo( "%7B" ); assertThat( escapeUri( "" + (char) 0xFF, UTF_8 ) ).isEqualTo( "%C3%BF" ); assertThat( escapeUri( "..\\..\\..\\Test : User\\me\\.m2\\repository\\grp\\art\\1.0\\art-1.0.jar", UTF_8 ) ) .isEqualTo( "../../../Test%20%3A%20User/me/.m2/repository/grp/art/1.0/art-1.0.jar" ); assertThat( escapeUri( "..\\..\\..\\Test : User\\me\\.m2\\repository\\grp\\art\\1.0\\art-1.0.jar", Charset.defaultCharset() ) ) .isEqualTo( "../../../Test%20%3A%20User/me/.m2/repository/grp/art/1.0/art-1.0.jar" ); assertThat( escapeUri( "../../surefire-its/target/junit-pathWithÜmlaut_1/target/surefire", UTF_8 ) ) .isEqualTo( "../../surefire-its/target/junit-pathWith%C3%9Cmlaut_1/target/surefire" ); String source = "../../surefire-its/target/junit-pathWithÜmlaut_1/target/surefire"; String encoded = escapeUri( "../../surefire-its/target/junit-pathWithÜmlaut_1/target/surefire", UTF_8 ); String decoded = URLDecoder.decode( encoded, UTF_8.name() ); assertThat( decoded ) .isEqualTo( source ); }
JarManifestForkConfiguration extends AbstractClasspathForkConfiguration { static String relativize( @Nonnull Path parent, @Nonnull Path child ) throws IllegalArgumentException { return parent.relativize( child ) .toString(); } @SuppressWarnings( "checkstyle:parameternumber" ) JarManifestForkConfiguration( @Nonnull Classpath bootClasspath, @Nonnull File tempDirectory, @Nullable String debugLine, @Nonnull File workingDirectory, @Nonnull Properties modelProperties, @Nullable String argLine, @Nonnull Map<String, String> environmentVariables, @Nonnull String[] excludedEnvironmentVariables, boolean debug, int forkCount, boolean reuseForks, @Nonnull Platform pluginPlatform, @Nonnull ConsoleLogger log, @Nonnull ForkNodeFactory forkNodeFactory ); }
@Test public void shouldRelativizeOnRealPlatform() { Path parentDir = new File( TMP, "test-parent-1" ) .toPath(); Path testDir = new File( TMP, "@1 test with white spaces" ) .toPath(); String relativeTestDir = relativize( parentDir, testDir ); assertThat( relativeTestDir ) .isEqualTo( ".." + File.separator + "@1 test with white spaces" ); }
JarManifestForkConfiguration extends AbstractClasspathForkConfiguration { static String toAbsoluteUri( @Nonnull Path absolutePath ) { return absolutePath.toUri() .toASCIIString(); } @SuppressWarnings( "checkstyle:parameternumber" ) JarManifestForkConfiguration( @Nonnull Classpath bootClasspath, @Nonnull File tempDirectory, @Nullable String debugLine, @Nonnull File workingDirectory, @Nonnull Properties modelProperties, @Nullable String argLine, @Nonnull Map<String, String> environmentVariables, @Nonnull String[] excludedEnvironmentVariables, boolean debug, int forkCount, boolean reuseForks, @Nonnull Platform pluginPlatform, @Nonnull ConsoleLogger log, @Nonnull ForkNodeFactory forkNodeFactory ); }
@Test public void shouldMakeAbsoluteUriOnRealPlatform() throws Exception { Path testDir = new File( TMP, "@2 test with white spaces" ) .toPath(); URI testDirUri = new URI( toAbsoluteUri( testDir ) ); assertThat( testDirUri.getScheme() ) .isEqualTo( "file" ); assertThat( testDirUri.getRawPath() ) .isEqualTo( testDir.toUri().getRawPath() ); }
JarManifestForkConfiguration extends AbstractClasspathForkConfiguration { static ClasspathElementUri toClasspathElementUri( @Nonnull Path parent, @Nonnull Path classPathElement, @Nonnull File dumpLogDirectory, boolean dumpError ) { try { String relativePath = relativize( parent, classPathElement ); return relative( escapeUri( relativePath, UTF_8 ) ); } catch ( IllegalArgumentException e ) { if ( dumpError ) { String error = "Boot Manifest-JAR contains absolute paths in classpath '" + classPathElement + "'" + NL + "Hint: <argLine>-Djdk.net.URLClassPath.disableClassPathURLCheck=true</argLine>"; InPluginProcessDumpSingleton.getSingleton() .dumpStreamText( error, dumpLogDirectory ); } return absolute( toAbsoluteUri( classPathElement ) ); } } @SuppressWarnings( "checkstyle:parameternumber" ) JarManifestForkConfiguration( @Nonnull Classpath bootClasspath, @Nonnull File tempDirectory, @Nullable String debugLine, @Nonnull File workingDirectory, @Nonnull Properties modelProperties, @Nullable String argLine, @Nonnull Map<String, String> environmentVariables, @Nonnull String[] excludedEnvironmentVariables, boolean debug, int forkCount, boolean reuseForks, @Nonnull Platform pluginPlatform, @Nonnull ConsoleLogger log, @Nonnull ForkNodeFactory forkNodeFactory ); }
@Test public void shouldMakeRelativeUriOnRealPlatform() throws Exception { Path parentDir = new File( TMP, "test-parent-2" ) .toPath(); Path testDir = new File( TMP, "@3 test with white spaces" ) .toPath(); ClasspathElementUri testDirUriPath = toClasspathElementUri( parentDir, testDir, dumpDirectory, true ); assertThat( testDirUriPath.uri ) .isEqualTo( "../%403%20test%20with%20white%20spaces" ); }
ForkClient implements EventHandler<Event> { @Override public final void handleEvent( @Nonnull Event event ) { notifier.notifyEvent( event ); } ForkClient( DefaultReporterFactory defaultReporterFactory, NotifiableTestStream notifiableTestStream, int forkNumber ); void kill(); final void tryToTimeout( long currentTimeMillis, int forkedProcessTimeoutInSeconds ); final DefaultReporterFactory getDefaultReporterFactory(); @Override final void handleEvent( @Nonnull Event event ); final boolean hadTimeout(); final Map<String, String> getTestVmSystemProperties(); final RunListener getReporter(); void close( boolean hadTimeout ); final boolean isSaidGoodBye(); final StackTraceWriter getErrorInFork(); final boolean isErrorInFork(); Set<String> testsInProgress(); boolean hasTestsInProgress(); }
@Test( expected = NullPointerException.class ) public void shouldFailOnNPE() { String cwd = System.getProperty( "user.dir" ); File target = new File( cwd, "target" ); DefaultReporterFactory factory = mock( DefaultReporterFactory.class ); when( factory.getReportsDirectory() ) .thenReturn( new File( target, "surefire-reports" ) ); ForkClient client = new ForkClient( factory, null, 0 ); client.handleEvent( null ); }
ForkClient implements EventHandler<Event> { public void kill() { if ( !saidGoodBye ) { notifiableTestStream.shutdown( KILL ); } } ForkClient( DefaultReporterFactory defaultReporterFactory, NotifiableTestStream notifiableTestStream, int forkNumber ); void kill(); final void tryToTimeout( long currentTimeMillis, int forkedProcessTimeoutInSeconds ); final DefaultReporterFactory getDefaultReporterFactory(); @Override final void handleEvent( @Nonnull Event event ); final boolean hadTimeout(); final Map<String, String> getTestVmSystemProperties(); final RunListener getReporter(); void close( boolean hadTimeout ); final boolean isSaidGoodBye(); final StackTraceWriter getErrorInFork(); final boolean isErrorInFork(); Set<String> testsInProgress(); boolean hasTestsInProgress(); }
@Test public void shouldBePossibleToKill() { NotifiableTestStream notifiableTestStream = mock( NotifiableTestStream.class ); ForkClient client = new ForkClient( null, notifiableTestStream, 0 ); client.kill(); verify( notifiableTestStream, times( 1 ) ) .shutdown( eq( Shutdown.KILL ) ); }
ThreadedStreamConsumer implements EventHandler<Event>, Closeable { public ThreadedStreamConsumer( EventHandler<Event> target ) { pumper = new Pumper( target ); Thread thread = newDaemonThread( pumper, "ThreadedStreamConsumer" ); thread.start(); } ThreadedStreamConsumer( EventHandler<Event> target ); @Override void handleEvent( @Nonnull Event event ); @Override void close(); }
@Test public void testThreadedStreamConsumer() throws Exception { final CountDownLatch countDown = new CountDownLatch( 5_000_000 ); EventHandler<Event> handler = new EventHandler<Event>() { @Override public void handleEvent( @Nonnull Event event ) { countDown.countDown(); } }; ThreadedStreamConsumer streamConsumer = new ThreadedStreamConsumer( handler ); SECONDS.sleep( 1 ); System.gc(); SECONDS.sleep( 2 ); long t1 = System.currentTimeMillis(); Event event = new StandardStreamOutWithNewLineEvent( NORMAL_RUN, "" ); for ( int i = 0; i < 5_000_000; i++ ) { streamConsumer.handleEvent( event ); } assertThat( countDown.await( 3L, SECONDS ) ) .isTrue(); long t2 = System.currentTimeMillis(); System.out.println( ( t2 - t1 ) + " millis in testThreadedStreamConsumer()" ); streamConsumer.close(); }
CommonReflector { public Object createReportingReporterFactory( @Nonnull StartupReportConfiguration startupReportConfiguration, @Nonnull ConsoleLogger consoleLogger ) { Class<?>[] args = { this.startupReportConfiguration, this.consoleLogger }; Object src = createStartupReportConfiguration( startupReportConfiguration ); Object logger = createConsoleLogger( consoleLogger, surefireClassLoader ); Object[] params = { src, logger }; return instantiateObject( DefaultReporterFactory.class.getName(), args, params, surefireClassLoader ); } CommonReflector( @Nonnull ClassLoader surefireClassLoader ); Object createReportingReporterFactory( @Nonnull StartupReportConfiguration startupReportConfiguration, @Nonnull ConsoleLogger consoleLogger ); }
@Test public void createReportingReporterFactory() { CommonReflector reflector = new CommonReflector( Thread.currentThread().getContextClassLoader() ); DefaultReporterFactory factory = (DefaultReporterFactory) reflector.createReportingReporterFactory( startupReportConfiguration, consoleLogger ); assertThat( factory ) .isNotNull(); StartupReportConfiguration reportConfiguration = getInternalState( factory, "reportConfiguration" ); assertThat( reportConfiguration ) .isNotSameAs( startupReportConfiguration ); assertThat( reportConfiguration.isUseFile() ).isTrue(); assertThat( reportConfiguration.isPrintSummary() ).isTrue(); assertThat( reportConfiguration.getReportFormat() ).isEqualTo( "PLAIN" ); assertThat( reportConfiguration.isRedirectTestOutputToFile() ).isFalse(); assertThat( reportConfiguration.getReportsDirectory() ).isSameAs( reportsDirectory ); assertThat( reportConfiguration.isTrimStackTrace() ).isFalse(); assertThat( reportConfiguration.getReportNameSuffix() ).isNull(); assertThat( reportConfiguration.getStatisticsFile() ).isSameAs( statistics ); assertThat( reportConfiguration.isRequiresRunHistory() ).isFalse(); assertThat( reportConfiguration.getRerunFailingTestsCount() ).isEqualTo( 1 ); assertThat( reportConfiguration.getXsdSchemaLocation() ).isNull(); assertThat( reportConfiguration.getEncoding() ).isEqualTo( UTF_8 ); assertThat( reportConfiguration.isForkMode() ).isFalse(); assertThat( reportConfiguration.getXmlReporter().toString() ) .isEqualTo( xmlReporter.toString() ); assertThat( reportConfiguration.getTestsetReporter().toString() ) .isEqualTo( infoReporter.toString() ); assertThat( reportConfiguration.getConsoleOutputReporter().toString() ) .isEqualTo( consoleOutputReporter.toString() ); }
CommonReflector { static Object createConsoleLogger( ConsoleLogger consoleLogger, ClassLoader cl ) { try { Class<?> decoratorClass = cl.loadClass( ConsoleLoggerDecorator.class.getName() ); return getConstructor( decoratorClass, Object.class ).newInstance( consoleLogger ); } catch ( Exception e ) { throw new SurefireReflectionException( e ); } } CommonReflector( @Nonnull ClassLoader surefireClassLoader ); Object createReportingReporterFactory( @Nonnull StartupReportConfiguration startupReportConfiguration, @Nonnull ConsoleLogger consoleLogger ); }
@Test public void shouldProxyConsoleLogger() { ClassLoader cl = Thread.currentThread().getContextClassLoader(); ConsoleLogger logger = spy( new PrintStreamLogger( System.out ) ); Object mirror = CommonReflector.createConsoleLogger( logger, cl ); MatcherAssert.assertThat( mirror, is( notNullValue() ) ); MatcherAssert.assertThat( mirror.getClass().getInterfaces()[0].getName(), is( ConsoleLogger.class.getName() ) ); MatcherAssert.assertThat( mirror, is( not( sameInstance( (Object) logger ) ) ) ); MatcherAssert.assertThat( mirror, is( instanceOf( ConsoleLoggerDecorator.class ) ) ); invokeMethodWithArray( mirror, getMethod( mirror, "info", String.class ), "Hi There!" ); verify( logger, times( 1 ) ).info( "Hi There!" ); } @Test public void testCreateConsoleLogger() { ClassLoader cl = Thread.currentThread().getContextClassLoader(); ConsoleLogger consoleLogger = mock( ConsoleLogger.class ); ConsoleLogger decorator = (ConsoleLogger) CommonReflector.createConsoleLogger( consoleLogger, cl ); assertThat( decorator ) .isNotSameAs( consoleLogger ); assertThat( decorator.isDebugEnabled() ).isFalse(); when( consoleLogger.isDebugEnabled() ).thenReturn( true ); assertThat( decorator.isDebugEnabled() ).isTrue(); verify( consoleLogger, times( 2 ) ).isDebugEnabled(); decorator.info( "msg" ); ArgumentCaptor<String> argumentMsg = ArgumentCaptor.forClass( String.class ); verify( consoleLogger, times( 1 ) ).info( argumentMsg.capture() ); assertThat( argumentMsg.getAllValues() ).hasSize( 1 ); assertThat( argumentMsg.getAllValues().get( 0 ) ).isEqualTo( "msg" ); }
ConsoleLoggerUtils { public static String toString( Throwable t ) { return toString( null, t ); } private ConsoleLoggerUtils(); static String toString( Throwable t ); static String toString( String message, Throwable t ); }
@Test public void shouldPrintStacktraceAsString() { Exception e = new IllegalArgumentException( "wrong param" ); String msg = ConsoleLoggerUtils.toString( e ); StringWriter text = new StringWriter(); PrintWriter writer = new PrintWriter( text ); e.printStackTrace( writer ); String s = text.toString(); assertThat( msg ) .isEqualTo( s ); } @Test public void shouldPrintStacktracWithMessageAsString() { Exception e = new IllegalArgumentException( "wrong param" ); String msg = ConsoleLoggerUtils.toString( "issue", e ); StringWriter text = new StringWriter(); PrintWriter writer = new PrintWriter( text ); writer.println( "issue" ); e.printStackTrace( writer ); String s = text.toString(); assertThat( msg ) .isEqualTo( s ); }
ReflectionUtils { public static Class<?> reloadClass( ClassLoader classLoader, Object source ) throws ReflectiveOperationException { return classLoader.loadClass( source.getClass().getName() ); } private ReflectionUtils(); static Method getMethod( Object instance, String methodName, Class<?>... parameters ); static Method getMethod( Class<?> clazz, String methodName, Class<?>... parameters ); static Method tryGetMethod( Class<?> clazz, String methodName, Class<?>... parameters ); static Object invokeGetter( Object instance, String methodName ); static Object invokeGetter( Class<?> instanceType, Object instance, String methodName ); static Constructor<?> getConstructor( Class<?> clazz, Class<?>... arguments ); static Object newInstance( Constructor<?> constructor, Object... params ); static T instantiate( ClassLoader classLoader, String classname, Class<T> returnType ); static Object instantiateOneArg( ClassLoader classLoader, String className, Class<?> param1Class, Object param1 ); static void invokeSetter( Object o, String name, Class<?> value1clazz, Object value ); static Object invokeSetter( Object target, Method method, Object value ); static Object invokeMethodWithArray( Object target, Method method, Object... args ); static Object invokeMethodWithArray2( Object target, Method method, Object... args ); static Object instantiateObject( String className, Class<?>[] types, Object[] params, ClassLoader cl ); @SuppressWarnings( "checkstyle:emptyblock" ) static Class<?> tryLoadClass( ClassLoader classLoader, String className ); static Class<?> loadClass( ClassLoader classLoader, String className ); static Class<?> reloadClass( ClassLoader classLoader, Object source ); static Object invokeStaticMethod( Class<?> clazz, String methodName, Class<?>[] parameterTypes, Object[] parameters ); static Object invokeMethodChain( Class<?>[] classesChain, String[] noArgMethodNames, Object fallback ); }
@Test public void shouldReloadClass() throws Exception { ClassLoader cl = Thread.currentThread().getContextClassLoader(); assertThat( ReflectionUtils.reloadClass( cl, new B() ) ) .isEqualTo( B.class ); }
SurefireHelper { public static String[] getDumpFilesToPrint() { return DUMP_FILES_PRINT.clone(); } private SurefireHelper(); @Nonnull static String replaceThreadNumberPlaceholders( @Nonnull String argLine, int threadNumber ); static File replaceForkThreadsInPath( File path, int replacement ); static String[] getDumpFilesToPrint(); static void reportExecution( SurefireReportParameters reportParameters, RunResult result, PluginConsoleLogger log, Exception firstForkException ); static List<CommandLineOption> commandLineOptions( MavenSession session, PluginConsoleLogger log ); static void logDebugOrCliShowErrors( String s, PluginConsoleLogger log, Collection<CommandLineOption> cli ); static String escapeToPlatformPath( String path ); static final String DUMP_FILE_PREFIX; static final String DUMP_FILENAME_FORMATTER; static final String DUMPSTREAM_FILENAME_FORMATTER; static final String DUMPSTREAM_FILENAME; static final String DUMP_FILENAME; }
@Test public void shouldBeThreeDumpFiles() { String[] dumps = SurefireHelper.getDumpFilesToPrint(); assertThat( dumps ).hasSize( 4 ); assertThat( dumps ).doesNotHaveDuplicates(); List<String> onlyStrings = new ArrayList<>(); addAll( onlyStrings, dumps ); onlyStrings.removeAll( singleton( (String) null ) ); assertThat( onlyStrings ).hasSize( 4 ); } @Test public void shouldCloneDumpFiles() { String[] dumps1 = SurefireHelper.getDumpFilesToPrint(); String[] dumps2 = SurefireHelper.getDumpFilesToPrint(); assertThat( dumps1 ).isNotSameAs( dumps2 ); }
ReflectionUtils { public static Object invokeStaticMethod( Class<?> clazz, String methodName, Class<?>[] parameterTypes, Object[] parameters ) { if ( parameterTypes.length != parameters.length ) { throw new IllegalArgumentException( "arguments length do not match" ); } Method method = getMethod( clazz, methodName, parameterTypes ); return invokeMethodWithArray( null, method, parameters ); } private ReflectionUtils(); static Method getMethod( Object instance, String methodName, Class<?>... parameters ); static Method getMethod( Class<?> clazz, String methodName, Class<?>... parameters ); static Method tryGetMethod( Class<?> clazz, String methodName, Class<?>... parameters ); static Object invokeGetter( Object instance, String methodName ); static Object invokeGetter( Class<?> instanceType, Object instance, String methodName ); static Constructor<?> getConstructor( Class<?> clazz, Class<?>... arguments ); static Object newInstance( Constructor<?> constructor, Object... params ); static T instantiate( ClassLoader classLoader, String classname, Class<T> returnType ); static Object instantiateOneArg( ClassLoader classLoader, String className, Class<?> param1Class, Object param1 ); static void invokeSetter( Object o, String name, Class<?> value1clazz, Object value ); static Object invokeSetter( Object target, Method method, Object value ); static Object invokeMethodWithArray( Object target, Method method, Object... args ); static Object invokeMethodWithArray2( Object target, Method method, Object... args ); static Object instantiateObject( String className, Class<?>[] types, Object[] params, ClassLoader cl ); @SuppressWarnings( "checkstyle:emptyblock" ) static Class<?> tryLoadClass( ClassLoader classLoader, String className ); static Class<?> loadClass( ClassLoader classLoader, String className ); static Class<?> reloadClass( ClassLoader classLoader, Object source ); static Object invokeStaticMethod( Class<?> clazz, String methodName, Class<?>[] parameterTypes, Object[] parameters ); static Object invokeMethodChain( Class<?>[] classesChain, String[] noArgMethodNames, Object fallback ); }
@Test( expected = RuntimeException.class ) public void shouldNotInvokeStaticMethod() { ReflectionUtils.invokeStaticMethod( ReflectionUtilsTest.class, "notCallable", new Class<?>[0], new Object[0] ); } @Test public void shouldInvokeStaticMethod() { Object o = ReflectionUtils.invokeStaticMethod( ReflectionUtilsTest.class, "callable", new Class<?>[0], new Object[0] ); assertThat( o ) .isEqualTo( 3L ); }
ReflectionUtils { public static Object invokeMethodChain( Class<?>[] classesChain, String[] noArgMethodNames, Object fallback ) { if ( classesChain.length != noArgMethodNames.length ) { throw new IllegalArgumentException( "arrays must have the same length" ); } Object obj = null; try { for ( int i = 0, len = noArgMethodNames.length; i < len; i++ ) { if ( i == 0 ) { obj = invokeStaticMethod( classesChain[i], noArgMethodNames[i], EMPTY_CLASS_ARRAY, EMPTY_OBJECT_ARRAY ); } else { Method method = getMethod( classesChain[i], noArgMethodNames[i] ); obj = invokeMethodWithArray( obj, method ); } } return obj; } catch ( RuntimeException e ) { return fallback; } } private ReflectionUtils(); static Method getMethod( Object instance, String methodName, Class<?>... parameters ); static Method getMethod( Class<?> clazz, String methodName, Class<?>... parameters ); static Method tryGetMethod( Class<?> clazz, String methodName, Class<?>... parameters ); static Object invokeGetter( Object instance, String methodName ); static Object invokeGetter( Class<?> instanceType, Object instance, String methodName ); static Constructor<?> getConstructor( Class<?> clazz, Class<?>... arguments ); static Object newInstance( Constructor<?> constructor, Object... params ); static T instantiate( ClassLoader classLoader, String classname, Class<T> returnType ); static Object instantiateOneArg( ClassLoader classLoader, String className, Class<?> param1Class, Object param1 ); static void invokeSetter( Object o, String name, Class<?> value1clazz, Object value ); static Object invokeSetter( Object target, Method method, Object value ); static Object invokeMethodWithArray( Object target, Method method, Object... args ); static Object invokeMethodWithArray2( Object target, Method method, Object... args ); static Object instantiateObject( String className, Class<?>[] types, Object[] params, ClassLoader cl ); @SuppressWarnings( "checkstyle:emptyblock" ) static Class<?> tryLoadClass( ClassLoader classLoader, String className ); static Class<?> loadClass( ClassLoader classLoader, String className ); static Class<?> reloadClass( ClassLoader classLoader, Object source ); static Object invokeStaticMethod( Class<?> clazz, String methodName, Class<?>[] parameterTypes, Object[] parameters ); static Object invokeMethodChain( Class<?>[] classesChain, String[] noArgMethodNames, Object fallback ); }
@Test public void shouldInvokeMethodChain() { Class<?>[] classes1 = { A.class, A.class }; String[] chain = { "current", "pid" }; Object o = ReflectionUtils.invokeMethodChain( classes1, chain, null ); assertThat( o ) .isEqualTo( 3L ); Class<?>[] classes2 = { A.class, A.class, B.class }; String[] longChain = { "current", "createB", "pid" }; o = ReflectionUtils.invokeMethodChain( classes2, longChain, null ); assertThat( o ) .isEqualTo( 1L ); } @Test public void shouldInvokeFallbackOnMethodChain() { Class<?>[] classes1 = { A.class, A.class }; String[] chain = { "current", "abc" }; Object o = ReflectionUtils.invokeMethodChain( classes1, chain, 5L ); assertThat( o ) .isEqualTo( 5L ); Class<?>[] classes2 = { A.class, B.class, B.class }; String[] longChain = { "current", "createB", "abc" }; o = ReflectionUtils.invokeMethodChain( classes2, longChain, 6L ); assertThat( o ) .isEqualTo( 6L ); }
ConcurrencyUtils { @SuppressWarnings( "checkstyle:emptyforiteratorpad" ) public static boolean countDownToZero( AtomicInteger counter ) { for (;;) { int c = counter.get(); if ( c > 0 ) { int newCounter = c - 1; if ( counter.compareAndSet( c, newCounter ) ) { return newCounter == 0; } } else { return false; } } } private ConcurrencyUtils(); @SuppressWarnings( "checkstyle:emptyforiteratorpad" ) static boolean countDownToZero( AtomicInteger counter ); }
@Test public void countDownShouldBeUnchangedAsZeroNegativeTest() { AtomicInteger atomicCounter = new AtomicInteger( 0 ); assertFalse( countDownToZero( atomicCounter ) ); assertThat( atomicCounter.get(), is( 0 ) ); } @Test public void countDownShouldBeUnchangedAsNegativeNegativeTest() { AtomicInteger atomicCounter = new AtomicInteger( -1 ); assertFalse( countDownToZero( atomicCounter ) ); assertThat( atomicCounter.get(), is( -1 ) ); } @Test public void countDownShouldBeDecreasedByOneThreadModification() { AtomicInteger atomicCounter = new AtomicInteger( 10 ); assertFalse( countDownToZero( atomicCounter ) ); assertThat( atomicCounter.get(), is( 9 ) ); } @Test public void countDownToZeroShouldBeDecreasedByOneThreadModification() { AtomicInteger atomicCounter = new AtomicInteger( 1 ); assertTrue( countDownToZero( atomicCounter ) ); assertThat( atomicCounter.get(), is( 0 ) ); } @Test public void countDownShouldBeDecreasedByTwoThreadsModification() throws ExecutionException, InterruptedException { final AtomicInteger atomicCounter = new AtomicInteger( 3 ); FutureTask<Boolean> task = new FutureTask<Boolean>( new Callable<Boolean>() { @Override public Boolean call() throws Exception { return countDownToZero( atomicCounter ); } } ); Thread t = new Thread( task ); t.start(); assertFalse( countDownToZero( atomicCounter ) ); assertFalse( task.get() ); assertThat( atomicCounter.get(), is( 1 ) ); assertTrue( countDownToZero( atomicCounter ) ); assertThat( atomicCounter.get(), is( 0 ) ); }
ImmutableMap extends AbstractMap<K, V> { @Override public Set<Entry<K, V>> entrySet() { Set<Entry<K, V>> entries = new LinkedHashSet<>(); Node<K, V> node = first; while ( node != null ) { entries.add( node ); node = node.next; } return unmodifiableSet( entries ); } ImmutableMap( Map<K, V> map ); @Override Set<Entry<K, V>> entrySet(); }
@Test public void testEntrySet() { Set<Entry<String, String>> entries = map.entrySet(); assertThat( entries, hasSize( 6 ) ); assertThat( entries, hasItem( new Node<>( "a", "1" ) ) ); assertThat( entries, hasItem( new Node<>( "x", (String) null ) ) ); assertThat( entries, hasItem( new Node<>( "b", "2" ) ) ); assertThat( entries, hasItem( new Node<>( "c", "3" ) ) ); assertThat( entries, hasItem( new Node<>( "", "" ) ) ); assertThat( entries, hasItem( new Node<>( (String) null, "1" ) ) ); } @Test( expected = UnsupportedOperationException.class ) public void shouldNotModifyEntries() { map.entrySet().clear(); } @Test public void shouldSafelyEnumerateEntries() { Iterator<Entry<String, String>> it = map.entrySet().iterator(); assertThat( it.hasNext(), is( true ) ); Entry<String, String> val = it.next(); assertThat( val.getKey(), is( "a" ) ); assertThat( val.getValue(), is( "1" ) ); assertThat( it.hasNext(), is( true ) ); val = it.next(); assertThat( val.getKey(), is( "x" ) ); assertThat( val.getValue(), is( nullValue() ) ); assertThat( it.hasNext(), is( true ) ); val = it.next(); assertThat( val.getKey(), is( "b" ) ); assertThat( val.getValue(), is( "2" ) ); assertThat( it.hasNext(), is( true ) ); val = it.next(); assertThat( val.getKey(), is( "c" ) ); assertThat( val.getValue(), is( "3" ) ); assertThat( it.hasNext(), is( true ) ); val = it.next(); assertThat( val.getKey(), is( "" ) ); assertThat( val.getValue(), is( "" ) ); assertThat( it.hasNext(), is( true ) ); val = it.next(); assertThat( val.getKey(), is( nullValue() ) ); assertThat( val.getValue(), is( "1" ) ); assertThat( it.hasNext(), is( false ) ); } @Test( expected = UnsupportedOperationException.class ) public void shouldNotSetEntries() { map.entrySet().iterator().next().setValue( "" ); } @Test public void shouldNotHaveEqualEntry() { Map<String, String> map = new ImmutableMap<>( Collections.singletonMap( "k", "v" ) ); Entry<String, String> e = map.entrySet().iterator().next(); assertThat( e, is( not( (Entry<String, String>) null ) ) ); assertThat( e, is( not( new Object() ) ) ); } @Test public void shouldHaveEqualEntry() { Map<String, String> map = new ImmutableMap<>( Collections.singletonMap( "k", "v" ) ); Entry<String, String> e = map.entrySet().iterator().next(); assertThat( e, is( e ) ); assertThat( e, is( (Entry<String, String>) new Node<>( "k", "v" ) ) ); }
GroupMatcherCategoryFilter extends Filter { @Override public boolean shouldRun( Description description ) { if ( invalidTestClass( description ) ) { return shouldRun( description, null, null ); } if ( describesTestClass( description ) ) { Class<?> testClass = description.getTestClass(); return shouldRun( description, null, testClass ); } else { Class<?> testClass = description.getTestClass(); return shouldRun( description, createSuiteDescription( testClass ), testClass ); } } GroupMatcherCategoryFilter( GroupMatcher included, GroupMatcher excluded ); @Override boolean shouldRun( Description description ); @Override String describe(); }
@Test public void shouldMatchIncludedCategoryInSelf() { GroupMatcher included = new SingleGroupMatcher( "org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryB" ); GroupMatcher excluded = null; cut = new GroupMatcherCategoryFilter( included, excluded ); assertTrue( cut.shouldRun( createSuiteDescription( BTest.class ) ) ); } @Test public void shouldMatchIncludedCategoryInParent() { GroupMatcher included = new SingleGroupMatcher( "org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryB" ); GroupMatcher excluded = null; cut = new GroupMatcherCategoryFilter( included, excluded ); assertTrue( cut.shouldRun( createSuiteDescription( BCTest.class ) ) ); assertFalse( cut.shouldRun( createSuiteDescription( ATest.class ) ) ); } @Test public void shouldMatchIncludedCategoryInHierarchy() { GroupMatcher included = new SingleGroupMatcher( "org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryC" ); GroupMatcher excluded = null; cut = new GroupMatcherCategoryFilter( included, excluded ); assertTrue( cut.shouldRun( createSuiteDescription( ABCTest.class ) ) ); assertTrue( cut.shouldRun( createSuiteDescription( BCTest.class ) ) ); assertFalse( cut.shouldRun( createSuiteDescription( ATest.class ) ) ); } @Test public void shouldMatchIncludedCategoryInParentWhenSelfHasAnother() { GroupMatcher included = new SingleGroupMatcher( "org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryB" ); GroupMatcher excluded = null; cut = new GroupMatcherCategoryFilter( included, excluded ); assertTrue( cut.shouldRun( createSuiteDescription( ABCTest.class ) ) ); assertTrue( cut.shouldRun( createTestDescription( ABCTest.class, "abc" ) ) ); assertTrue( cut.shouldRun( createSuiteDescription( ABCParameterizedTest.class ) ) ); assertTrue( cut.shouldRun( createTestDescription( ABCParameterizedTest.class, "abc" ) ) ); } @Test public void shouldNotMatchIncludedCategoryInParentWhenSelfHasExcludedCategory() { GroupMatcher included = new SingleGroupMatcher( "org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryB" ); GroupMatcher excluded = new SingleGroupMatcher( "org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryA" ); cut = new GroupMatcherCategoryFilter( included, excluded ); assertFalse( cut.shouldRun( createSuiteDescription( ABCTest.class ) ) ); assertTrue( cut.shouldRun( createSuiteDescription( BBCTest.class ) ) ); assertTrue( cut.shouldRun( createSuiteDescription( BTest.class ) ) ); } @Test public void shouldMatchExcludedCategoryInSelf() { GroupMatcher included = null; GroupMatcher excluded = new SingleGroupMatcher( "org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryA" ); cut = new GroupMatcherCategoryFilter( included, excluded ); assertFalse( cut.shouldRun( createSuiteDescription( ATest.class ) ) ); assertTrue( cut.shouldRun( createSuiteDescription( BTest.class ) ) ); assertTrue( cut.shouldRun( createSuiteDescription( BBCTest.class ) ) ); }
SurefireHelper { public static String escapeToPlatformPath( String path ) { if ( IS_OS_WINDOWS && path.length() > MAX_PATH_LENGTH_WINDOWS ) { path = path.startsWith( "\\\\" ) ? "\\\\?\\UNC\\" + path.substring( 2 ) : "\\\\?\\" + path; } return path; } private SurefireHelper(); @Nonnull static String replaceThreadNumberPlaceholders( @Nonnull String argLine, int threadNumber ); static File replaceForkThreadsInPath( File path, int replacement ); static String[] getDumpFilesToPrint(); static void reportExecution( SurefireReportParameters reportParameters, RunResult result, PluginConsoleLogger log, Exception firstForkException ); static List<CommandLineOption> commandLineOptions( MavenSession session, PluginConsoleLogger log ); static void logDebugOrCliShowErrors( String s, PluginConsoleLogger log, Collection<CommandLineOption> cli ); static String escapeToPlatformPath( String path ); static final String DUMP_FILE_PREFIX; static final String DUMP_FILENAME_FORMATTER; static final String DUMPSTREAM_FILENAME_FORMATTER; static final String DUMPSTREAM_FILENAME; static final String DUMP_FILENAME; }
@Test public void shouldEscapeWindowsPath() { assumeTrue( IS_OS_WINDOWS ); String root = "X:\\path\\to\\project\\"; String pathToJar = "target\\surefire\\surefirebooter4942721306300108667.jar"; @SuppressWarnings( "checkstyle:magicnumber" ) int projectNameLength = 247 - root.length() - pathToJar.length(); StringBuilder projectFolder = new StringBuilder(); for ( int i = 0; i < projectNameLength; i++ ) { projectFolder.append( 'x' ); } String path = root + projectFolder + "\\" + pathToJar; String escaped = escapeToPlatformPath( path ); assertThat( escaped ).isEqualTo( "\\\\?\\" + path ); path = root + "\\" + pathToJar; escaped = escapeToPlatformPath( path ); assertThat( escaped ).isEqualTo( root + "\\" + pathToJar ); }
SurefireHelper { public static void reportExecution( SurefireReportParameters reportParameters, RunResult result, PluginConsoleLogger log, Exception firstForkException ) throws MojoFailureException, MojoExecutionException { if ( firstForkException == null && !result.isTimeout() && result.isErrorFree() ) { if ( result.getCompletedCount() == 0 && failIfNoTests( reportParameters ) ) { throw new MojoFailureException( "No tests were executed! " + "(Set -DfailIfNoTests=false to ignore this error.)" ); } return; } if ( reportParameters.isTestFailureIgnore() ) { log.error( createErrorMessage( reportParameters, result, firstForkException ) ); } else { throwException( reportParameters, result, firstForkException ); } } private SurefireHelper(); @Nonnull static String replaceThreadNumberPlaceholders( @Nonnull String argLine, int threadNumber ); static File replaceForkThreadsInPath( File path, int replacement ); static String[] getDumpFilesToPrint(); static void reportExecution( SurefireReportParameters reportParameters, RunResult result, PluginConsoleLogger log, Exception firstForkException ); static List<CommandLineOption> commandLineOptions( MavenSession session, PluginConsoleLogger log ); static void logDebugOrCliShowErrors( String s, PluginConsoleLogger log, Collection<CommandLineOption> cli ); static String escapeToPlatformPath( String path ); static final String DUMP_FILE_PREFIX; static final String DUMP_FILENAME_FORMATTER; static final String DUMPSTREAM_FILENAME_FORMATTER; static final String DUMPSTREAM_FILENAME; static final String DUMP_FILENAME; }
@Test public void shouldHandleFailIfNoTests() throws Exception { RunResult summary = new RunResult( 0, 0, 0, 0 ); try { Mojo plugin = new Mojo(); plugin.setFailIfNoTests( true ); reportExecution( plugin, summary, null, null ); } catch ( MojoFailureException e ) { assertThat( e.getLocalizedMessage() ) .isEqualTo( "No tests were executed! (Set -DfailIfNoTests=false to ignore this error.)" ); return; } fail( "Expected MojoFailureException with message " + "'No tests were executed! (Set -DfailIfNoTests=false to ignore this error.)'" ); } @Test public void shouldHandleTestFailure() throws Exception { RunResult summary = new RunResult( 1, 0, 1, 0 ); try { reportExecution( new Mojo(), summary, null, null ); } catch ( MojoFailureException e ) { assertThat( e.getLocalizedMessage() ) .isEqualTo( "There are test failures.\n\nPlease refer to null " + "for the individual test results.\nPlease refer to dump files (if any exist) " + "[date].dump, [date]-jvmRun[N].dump and [date].dumpstream." ); return; } fail( "Expected MojoFailureException with message " + "'There are test failures.\n\nPlease refer to null " + "for the individual test results.\nPlease refer to dump files (if any exist) " + "[date].dump, [date]-jvmRun[N].dump and [date].dumpstream.'" ); }
ConsumerGatewayUtil { protected static boolean setConsumerMember(ConsumerEndpoint endpoint) { ConsumerMember consumer = ConfigurationHelper.parseConsumerMember(endpoint.getClientId()); if (consumer == null) { log.warn("ConsumerMember not found."); return false; } endpoint.setConsumer(consumer); log.debug("ConsumerMember id : \"{}\".", consumer.toString()); return true; } private ConsumerGatewayUtil(); static Map<String, ConsumerEndpoint> extractConsumers(Properties endpoints, Properties gatewayProperties); static void extractEndpoints(String key, Properties endpoints, ConsumerEndpoint endpoint); static ConsumerEndpoint findMatch(String serviceId, Map<String, ConsumerEndpoint> endpoints); static String rewriteUrl(String servletUrl, String pathToResource, String responseStr); static ConsumerEndpoint createUnconfiguredEndpoint(Properties props, String pathToResource); static String removeResponseTag(String message); static boolean checkEncryptionProperties(Properties props, Map<String, ConsumerEndpoint> endpoints, Map<String, Encrypter> asymmetricEncrypterCache); }
@Test public void testParseConsumer1() throws XRd4JException { String clientId = "FI_PILOT.GOV.0245437-2"; ConsumerEndpoint consumerEndpoint = new ConsumerEndpoint(null, clientId, null); assertEquals(true, ConsumerGatewayUtil.setConsumerMember(consumerEndpoint)); assertEquals(clientId, consumerEndpoint.getConsumer().toString()); assertEquals("FI_PILOT", consumerEndpoint.getConsumer().getXRoadInstance()); assertEquals("GOV", consumerEndpoint.getConsumer().getMemberClass()); assertEquals("0245437-2", consumerEndpoint.getConsumer().getMemberCode()); assertEquals(null, consumerEndpoint.getConsumer().getSubsystemCode()); clientId = "FI_PILOT.GOV.0245437-2.ConsumerService"; consumerEndpoint = new ConsumerEndpoint(null, clientId, null); assertEquals(true, ConsumerGatewayUtil.setConsumerMember(consumerEndpoint)); assertEquals(clientId, consumerEndpoint.getConsumer().toString()); assertEquals("FI_PILOT", consumerEndpoint.getConsumer().getXRoadInstance()); assertEquals("GOV", consumerEndpoint.getConsumer().getMemberClass()); assertEquals("0245437-2", consumerEndpoint.getConsumer().getMemberCode()); assertEquals("ConsumerService", consumerEndpoint.getConsumer().getSubsystemCode()); clientId = "FI_PILOT.GOV.0245437-2.ConsumerService.getOrganizationList"; consumerEndpoint = new ConsumerEndpoint(null, clientId, null); assertEquals(false, ConsumerGatewayUtil.setConsumerMember(consumerEndpoint)); clientId = "FI_PILOT.GOV.0245437-2.ConsumerService.getOrganizationList.v1"; consumerEndpoint = new ConsumerEndpoint(null, clientId, null); assertEquals(false, ConsumerGatewayUtil.setConsumerMember(consumerEndpoint)); clientId = "FI_PILOT.GOV"; consumerEndpoint = new ConsumerEndpoint(null, clientId, null); assertEquals(false, ConsumerGatewayUtil.setConsumerMember(consumerEndpoint)); }
ConsumerGatewayUtil { public static String rewriteUrl(String servletUrl, String pathToResource, String responseStr) { log.debug("Rewrite URLs in the response to point Consumer Gateway."); log.debug("Consumer Gateway URL : \"{}\".", servletUrl); try { String resourcePath = pathToResource.substring(1, pathToResource.length() - 1).replaceAll("/\\{" + Constants.PARAM_RESOURCE_ID + "\\}", ""); log.debug("Resourse URL that's replaced with Consumer Gateway URL : \"http(s): log.debug("New resource URL : \"{}{}\".", servletUrl, resourcePath); return responseStr.replaceAll("http(s|):\\/\\/" + resourcePath, servletUrl + resourcePath); } catch (Exception ex) { log.error("Rewriting the URLs failed!"); log.error(ex.getMessage(), ex); return responseStr; } } private ConsumerGatewayUtil(); static Map<String, ConsumerEndpoint> extractConsumers(Properties endpoints, Properties gatewayProperties); static void extractEndpoints(String key, Properties endpoints, ConsumerEndpoint endpoint); static ConsumerEndpoint findMatch(String serviceId, Map<String, ConsumerEndpoint> endpoints); static String rewriteUrl(String servletUrl, String pathToResource, String responseStr); static ConsumerEndpoint createUnconfiguredEndpoint(Properties props, String pathToResource); static String removeResponseTag(String message); static boolean checkEncryptionProperties(Properties props, Map<String, ConsumerEndpoint> endpoints, Map<String, Encrypter> asymmetricEncrypterCache); }
@Test public void testModifyUrl5() { String responseCorrect = "<urls><url>http: String resourcePath = "/example.com/second/"; String responseStr = "<urls><url>http: responseStr = ConsumerGatewayUtil.rewriteUrl(servletUrl, resourcePath, responseStr); assertEquals(responseCorrect, responseStr); } @Test public void testModifyUrl6() { String responseCorrect = "<urls><url>http: String resourcePath = "/example.com/second/{resourceId}/"; String responseStr = "<urls><url>http: responseStr = ConsumerGatewayUtil.rewriteUrl(servletUrl, resourcePath, responseStr); assertEquals(responseCorrect, responseStr); } @Test public void testModifyUrl7() { String responseCorrect = "<urls><url>https: String resourcePath = "/example.com/second/"; String responseStr = "<urls><url>https: this.servletUrl = this.servletUrl.replace("http", "https"); responseStr = ConsumerGatewayUtil.rewriteUrl(servletUrl, resourcePath, responseStr); assertEquals(responseCorrect, responseStr); } @Test public void testModifyUrl8() { String responseCorrect = "<urls><url>https: String resourcePath = "/example.com/second/{resourceId}/"; String responseStr = "<urls><url>https: this.servletUrl = this.servletUrl.replace("http", "https"); responseStr = ConsumerGatewayUtil.rewriteUrl(servletUrl, resourcePath, responseStr); assertEquals(responseCorrect, responseStr); } @Test public void testModifyUrl1() { String responseCorrect = "{\"urls\":[\"http: String resourcePath = "/example.com/second/"; String responseStr = "{\"urls\":[\"http: responseStr = ConsumerGatewayUtil.rewriteUrl(servletUrl, resourcePath, responseStr); assertEquals(responseCorrect, responseStr); } @Test public void testModifyUrl2() { String responseCorrect = "{\"urls\":[\"http: String resourcePath = "/example.com/second/{resourceId}/"; String responseStr = "{\"urls\":[\"http: responseStr = ConsumerGatewayUtil.rewriteUrl(servletUrl, resourcePath, responseStr); assertEquals(responseCorrect, responseStr); } @Test public void testModifyUrl3() { String responseCorrect = "{\"urls\":[\"https: String resourcePath = "/example.com/second/"; String responseStr = "{\"urls\":[\"https: this.servletUrl = this.servletUrl.replace("http", "https"); responseStr = ConsumerGatewayUtil.rewriteUrl(servletUrl, resourcePath, responseStr); assertEquals(responseCorrect, responseStr); } @Test public void testModifyUrl4() { String responseCorrect = "{\"urls\":[\"https: String resourcePath = "/example.com/second/{resourceId}/"; String responseStr = "{\"urls\":[\"https: this.servletUrl = this.servletUrl.replace("http", "https"); responseStr = ConsumerGatewayUtil.rewriteUrl(servletUrl, resourcePath, responseStr); assertEquals(responseCorrect, responseStr); }
ConsumerGatewayUtil { public static String removeResponseTag(String message) { String responsePrefix = ""; String regex = ".*<(\\w+:)*(\\w+R|r)esponse.*?>.*"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(message); if (matcher.find()) { if (matcher.group(1) != null) { responsePrefix = matcher.group(1); log.debug("Response tag's prefix is \"{}\".", responsePrefix); } else { log.debug("No namespace prefix was found for response tag."); } } String response = message.replaceAll("<(/)*" + responsePrefix + "(\\w+R|r)esponse.*?>", ""); if (!responsePrefix.isEmpty()) { response = response.replaceAll("(</{0,1})" + responsePrefix, "$1"); } return response; } private ConsumerGatewayUtil(); static Map<String, ConsumerEndpoint> extractConsumers(Properties endpoints, Properties gatewayProperties); static void extractEndpoints(String key, Properties endpoints, ConsumerEndpoint endpoint); static ConsumerEndpoint findMatch(String serviceId, Map<String, ConsumerEndpoint> endpoints); static String rewriteUrl(String servletUrl, String pathToResource, String responseStr); static ConsumerEndpoint createUnconfiguredEndpoint(Properties props, String pathToResource); static String removeResponseTag(String message); static boolean checkEncryptionProperties(Properties props, Map<String, ConsumerEndpoint> endpoints, Map<String, Encrypter> asymmetricEncrypterCache); }
@Test public void testRemoveResponseTag1() { String source = "<response><param1>value1</param1><param2>value2</param2></response>"; String result = "<param1>value1</param1><param2>value2</param2>"; assertEquals(result, ConsumerGatewayUtil.removeResponseTag(source)); assertEquals(null, SOAPHelper.xmlStrToSOAPElement(result)); } @Test public void testRemoveResponseTag2() { String source = "<response xmlns:ts1=\"http: String result = "<param1>value1</param1><param2>value2</param2>"; assertEquals(result, ConsumerGatewayUtil.removeResponseTag(source)); assertEquals(null, SOAPHelper.xmlStrToSOAPElement(result)); } @Test public void testRemoveResponseTag3() { String source = "<ts1:response xmlns:ts1=\"http: String result = "<param1>value1</param1><param2>value2</param2>"; assertEquals(result, ConsumerGatewayUtil.removeResponseTag(source)); assertEquals(null, SOAPHelper.xmlStrToSOAPElement(result)); } @Test public void testRemoveResponseTag4() { String source = "<ts1:response xmlns:ts1=\"http: String result = "<param1>value1</param1><param2>value2</param2>"; assertEquals(result, ConsumerGatewayUtil.removeResponseTag(source)); assertEquals(null, SOAPHelper.xmlStrToSOAPElement(result)); } @Test public void testRemoveResponseTag5() { String source = "<ts1:response xmlns:ts1=\"http: String result = "<param1>value1</param1><param2>value2</param2>"; assertEquals(result, ConsumerGatewayUtil.removeResponseTag(source)); assertEquals(null, SOAPHelper.xmlStrToSOAPElement(result)); } @Test public void testRemoveResponseTag6() { String source = "<ts1:response xmlns:ts1=\"http: String result = "<ts2:param1 xmlns:ts2=\"http: assertEquals(result, ConsumerGatewayUtil.removeResponseTag(source)); assertEquals(null, SOAPHelper.xmlStrToSOAPElement(result)); } @Test public void testRemoveResponseTag7() { String source = "<ts1:response xmlns:ts1=\"http: String result = "<ts2:param1 xmlns:ts2=\"http: assertEquals(result, ConsumerGatewayUtil.removeResponseTag(source)); assertEquals(null, SOAPHelper.xmlStrToSOAPElement(result)); } @Test public void testRemoveResponseTag8() { String source = "<response><ts2:param1 xmlns:ts2=\"http: String result = "<ts2:param1 xmlns:ts2=\"http: assertEquals(result, ConsumerGatewayUtil.removeResponseTag(source)); assertEquals(null, SOAPHelper.xmlStrToSOAPElement(result)); } @Test public void testRemoveResponseTag9() { String source = "<response><ts2:param1 xmlns:ts2=\"http: String result = "<ts2:param1 xmlns:ts2=\"http: assertEquals(result, ConsumerGatewayUtil.removeResponseTag(source)); if (SOAPHelper.xmlStrToSOAPElement(result) == null) { fail("Response can't be null"); } } @Test public void testRemoveResponseTag10() { String source = "<ts1:response xmlns:ts1=\"http: String result = "<ts2:param1 xmlns:ts2=\"http: assertEquals(result, ConsumerGatewayUtil.removeResponseTag(source)); if (SOAPHelper.xmlStrToSOAPElement(result) == null) { fail("Response can't be null"); } } @Test public void testRemoveResponseTag11() { String source = "<response xmlns=\"http: String result = "<ts2:param1 xmlns:ts2=\"http: assertEquals(result, ConsumerGatewayUtil.removeResponseTag(source)); if (SOAPHelper.xmlStrToSOAPElement(result) == null) { fail("Response can't be null"); } } @Test public void testRemoveResponseTag12() throws UnsupportedEncodingException { String source = new String("<response><wrapper><param1>value1</param1><param2>ÄÖÅäöå</param2></wrapper></response>".getBytes(), "ISO-8859-1"); String result = new String("<wrapper><param1>value1</param1><param2>ÄÖÅäöå</param2></wrapper>".getBytes(), "ISO-8859-1"); assertEquals(result, ConsumerGatewayUtil.removeResponseTag(source)); if (SOAPHelper.xmlStrToSOAPElement(result) == null) { fail("Response can't be null"); } } @Test public void testRemoveResponseTag13() { String source = "<testServiceResponse><wrapper><param1>value1</param1><param2>value2</param2></wrapper></testServiceResponse>"; String result = "<wrapper><param1>value1</param1><param2>value2</param2></wrapper>"; assertEquals(result, ConsumerGatewayUtil.removeResponseTag(source)); if (SOAPHelper.xmlStrToSOAPElement(result) == null) { fail("Response can't be null"); } } @Test public void testRemoveResponseTag14() { String source = "<testServiceResponse xmlns=\"http: String result = "<ts1:wrapper xmlns:ts1=\"http: assertEquals(result, ConsumerGatewayUtil.removeResponseTag(source)); if (SOAPHelper.xmlStrToSOAPElement(result) == null) { fail("Response can't be null"); } } @Test public void testRemoveResponseTag15() { String source = "<ts0:testServiceResponse xmlns:ts0=\"http: String result = "<ts1:wrapper xmlns:ts1=\"http: assertEquals(result, ConsumerGatewayUtil.removeResponseTag(source)); if (SOAPHelper.xmlStrToSOAPElement(result) == null) { fail("Response can't be null"); } } @Test public void testRemoveResponseTag16() { String source = "<ts0:testServiceResponse xmlns:ts0=\"http: String result = "<wrapper><param1>value1</param1><param2>value2</param2></wrapper>"; assertEquals(result, ConsumerGatewayUtil.removeResponseTag(source)); if (SOAPHelper.xmlStrToSOAPElement(result) == null) { fail("Response can't be null"); } }
ConsumerGatewayUtil { protected static boolean setProducerMember(ConsumerEndpoint endpoint) { ProducerMember producer = ConfigurationHelper.parseProducerMember(endpoint.getServiceId()); if (producer == null) { log.warn("ProducerMember not found."); return false; } endpoint.setProducer(producer); log.debug("ProducerMember id : \"{}\".", producer.toString()); return true; } private ConsumerGatewayUtil(); static Map<String, ConsumerEndpoint> extractConsumers(Properties endpoints, Properties gatewayProperties); static void extractEndpoints(String key, Properties endpoints, ConsumerEndpoint endpoint); static ConsumerEndpoint findMatch(String serviceId, Map<String, ConsumerEndpoint> endpoints); static String rewriteUrl(String servletUrl, String pathToResource, String responseStr); static ConsumerEndpoint createUnconfiguredEndpoint(Properties props, String pathToResource); static String removeResponseTag(String message); static boolean checkEncryptionProperties(Properties props, Map<String, ConsumerEndpoint> endpoints, Map<String, Encrypter> asymmetricEncrypterCache); }
@Test public void testParseProducer1() throws XRd4JException { String serviceId = "FI_PILOT.GOV.0245437-2.ConsumerService.getOrganizationList.v1"; ConsumerEndpoint consumerEndpoint = new ConsumerEndpoint(serviceId, null, null); assertEquals(true, ConsumerGatewayUtil.setProducerMember(consumerEndpoint)); assertEquals(serviceId, consumerEndpoint.getProducer().toString()); assertEquals("FI_PILOT", consumerEndpoint.getProducer().getXRoadInstance()); assertEquals("GOV", consumerEndpoint.getProducer().getMemberClass()); assertEquals("0245437-2", consumerEndpoint.getProducer().getMemberCode()); assertEquals("ConsumerService", consumerEndpoint.getProducer().getSubsystemCode()); assertEquals("getOrganizationList", consumerEndpoint.getProducer().getServiceCode()); assertEquals("v1", consumerEndpoint.getProducer().getServiceVersion()); serviceId = "FI_PILOT.GOV.0245437-2.ConsumerService2.getOrganizationList.V1"; consumerEndpoint = new ConsumerEndpoint(serviceId, null, null); assertEquals(true, ConsumerGatewayUtil.setProducerMember(consumerEndpoint)); assertEquals(serviceId, consumerEndpoint.getProducer().toString()); assertEquals("FI_PILOT", consumerEndpoint.getProducer().getXRoadInstance()); assertEquals("GOV", consumerEndpoint.getProducer().getMemberClass()); assertEquals("0245437-2", consumerEndpoint.getProducer().getMemberCode()); assertEquals("ConsumerService2", consumerEndpoint.getProducer().getSubsystemCode()); assertEquals("getOrganizationList", consumerEndpoint.getProducer().getServiceCode()); assertEquals("V1", consumerEndpoint.getProducer().getServiceVersion()); serviceId = "FI_PILOT.GOV.0245437-2.ConsumerService2.getOrganizationList.V1_0"; consumerEndpoint = new ConsumerEndpoint(serviceId, null, null); assertEquals(true, ConsumerGatewayUtil.setProducerMember(consumerEndpoint)); assertEquals(serviceId, consumerEndpoint.getProducer().toString()); assertEquals("FI_PILOT", consumerEndpoint.getProducer().getXRoadInstance()); assertEquals("GOV", consumerEndpoint.getProducer().getMemberClass()); assertEquals("0245437-2", consumerEndpoint.getProducer().getMemberCode()); assertEquals("ConsumerService2", consumerEndpoint.getProducer().getSubsystemCode()); assertEquals("getOrganizationList", consumerEndpoint.getProducer().getServiceCode()); assertEquals("V1_0", consumerEndpoint.getProducer().getServiceVersion()); serviceId = "FI_PILOT.GOV.0245437-2.ConsumerService.getOrganizationList1"; consumerEndpoint = new ConsumerEndpoint(serviceId, null, null); assertEquals(true, ConsumerGatewayUtil.setProducerMember(consumerEndpoint)); assertEquals(serviceId, consumerEndpoint.getProducer().toString()); assertEquals("FI_PILOT", consumerEndpoint.getProducer().getXRoadInstance()); assertEquals("GOV", consumerEndpoint.getProducer().getMemberClass()); assertEquals("0245437-2", consumerEndpoint.getProducer().getMemberCode()); assertEquals("ConsumerService", consumerEndpoint.getProducer().getSubsystemCode()); assertEquals("getOrganizationList1", consumerEndpoint.getProducer().getServiceCode()); assertEquals(null, consumerEndpoint.getProducer().getServiceVersion()); serviceId = "FI_PILOT.GOV.0245437-2.getOrganizationList2"; consumerEndpoint = new ConsumerEndpoint(serviceId, null, null); assertEquals(true, ConsumerGatewayUtil.setProducerMember(consumerEndpoint)); assertEquals(serviceId, consumerEndpoint.getProducer().toString()); assertEquals("FI_PILOT", consumerEndpoint.getProducer().getXRoadInstance()); assertEquals("GOV", consumerEndpoint.getProducer().getMemberClass()); assertEquals("0245437-2", consumerEndpoint.getProducer().getMemberCode()); assertEquals(null, consumerEndpoint.getProducer().getSubsystemCode()); assertEquals("getOrganizationList2", consumerEndpoint.getProducer().getServiceCode()); assertEquals(null, consumerEndpoint.getProducer().getServiceVersion()); serviceId = "FI_PILOT.GOV.0245437-2.getOrganizationList.v1"; consumerEndpoint = new ConsumerEndpoint(serviceId, null, null); assertEquals(true, ConsumerGatewayUtil.setProducerMember(consumerEndpoint)); assertEquals(serviceId, consumerEndpoint.getProducer().toString()); assertEquals("FI_PILOT", consumerEndpoint.getProducer().getXRoadInstance()); assertEquals("GOV", consumerEndpoint.getProducer().getMemberClass()); assertEquals("0245437-2", consumerEndpoint.getProducer().getMemberCode()); assertEquals(null, consumerEndpoint.getProducer().getSubsystemCode()); assertEquals("getOrganizationList", consumerEndpoint.getProducer().getServiceCode()); assertEquals("v1", consumerEndpoint.getProducer().getServiceVersion()); serviceId = "FI_PILOT.GOV.0245437-2.getOrganizationList.V11"; consumerEndpoint = new ConsumerEndpoint(serviceId, null, null); assertEquals(true, ConsumerGatewayUtil.setProducerMember(consumerEndpoint)); assertEquals(serviceId, consumerEndpoint.getProducer().toString()); assertEquals("FI_PILOT", consumerEndpoint.getProducer().getXRoadInstance()); assertEquals("GOV", consumerEndpoint.getProducer().getMemberClass()); assertEquals("0245437-2", consumerEndpoint.getProducer().getMemberCode()); assertEquals(null, consumerEndpoint.getProducer().getSubsystemCode()); assertEquals("getOrganizationList", consumerEndpoint.getProducer().getServiceCode()); assertEquals("V11", consumerEndpoint.getProducer().getServiceVersion()); serviceId = "FI_PILOT.GOV.0245437-2.getOrganizationList.1"; consumerEndpoint = new ConsumerEndpoint(serviceId, null, null); assertEquals(true, ConsumerGatewayUtil.setProducerMember(consumerEndpoint)); assertEquals(serviceId, consumerEndpoint.getProducer().toString()); assertEquals("FI_PILOT", consumerEndpoint.getProducer().getXRoadInstance()); assertEquals("GOV", consumerEndpoint.getProducer().getMemberClass()); assertEquals("0245437-2", consumerEndpoint.getProducer().getMemberCode()); assertEquals(null, consumerEndpoint.getProducer().getSubsystemCode()); assertEquals("getOrganizationList", consumerEndpoint.getProducer().getServiceCode()); assertEquals("1", consumerEndpoint.getProducer().getServiceVersion()); serviceId = "FI_PILOT.GOV.0245437-2.getOrganizationList.1_0"; consumerEndpoint = new ConsumerEndpoint(serviceId, null, null); assertEquals(true, ConsumerGatewayUtil.setProducerMember(consumerEndpoint)); assertEquals(serviceId, consumerEndpoint.getProducer().toString()); assertEquals("FI_PILOT", consumerEndpoint.getProducer().getXRoadInstance()); assertEquals("GOV", consumerEndpoint.getProducer().getMemberClass()); assertEquals("0245437-2", consumerEndpoint.getProducer().getMemberCode()); assertEquals(null, consumerEndpoint.getProducer().getSubsystemCode()); assertEquals("getOrganizationList", consumerEndpoint.getProducer().getServiceCode()); assertEquals("1_0", consumerEndpoint.getProducer().getServiceVersion()); serviceId = "FI_PILOT.GOV.0245437-2.getOrganizationList.1-0"; consumerEndpoint = new ConsumerEndpoint(serviceId, null, null); assertEquals(true, ConsumerGatewayUtil.setProducerMember(consumerEndpoint)); assertEquals(serviceId, consumerEndpoint.getProducer().toString()); assertEquals("FI_PILOT", consumerEndpoint.getProducer().getXRoadInstance()); assertEquals("GOV", consumerEndpoint.getProducer().getMemberClass()); assertEquals("0245437-2", consumerEndpoint.getProducer().getMemberCode()); assertEquals(null, consumerEndpoint.getProducer().getSubsystemCode()); assertEquals("getOrganizationList", consumerEndpoint.getProducer().getServiceCode()); assertEquals("1-0", consumerEndpoint.getProducer().getServiceVersion()); serviceId = "FI_PILOT.GOV.0245437-2.getOrganizationList.ve1"; consumerEndpoint = new ConsumerEndpoint(serviceId, null, null); assertEquals(true, ConsumerGatewayUtil.setProducerMember(consumerEndpoint)); assertEquals(serviceId, consumerEndpoint.getProducer().toString()); assertEquals("FI_PILOT", consumerEndpoint.getProducer().getXRoadInstance()); assertEquals("GOV", consumerEndpoint.getProducer().getMemberClass()); assertEquals("0245437-2", consumerEndpoint.getProducer().getMemberCode()); assertEquals("getOrganizationList", consumerEndpoint.getProducer().getSubsystemCode()); assertEquals("ve1", consumerEndpoint.getProducer().getServiceCode()); assertEquals(null, consumerEndpoint.getProducer().getServiceVersion()); serviceId = "FI_PILOT.GOV"; consumerEndpoint = new ConsumerEndpoint(serviceId, null, null); assertEquals(false, ConsumerGatewayUtil.setProducerMember(consumerEndpoint)); serviceId = "FI_PILOT.GOV.0245437-2"; consumerEndpoint = new ConsumerEndpoint(serviceId, null, null); assertEquals(false, ConsumerGatewayUtil.setProducerMember(consumerEndpoint)); serviceId = "FI_PILOT.GOV.0245437-2.subsystem.service.v1.0"; consumerEndpoint = new ConsumerEndpoint(serviceId, null, null); assertEquals(false, ConsumerGatewayUtil.setProducerMember(consumerEndpoint)); }
ConsumerGatewayUtil { public static ConsumerEndpoint findMatch(String serviceId, Map<String, ConsumerEndpoint> endpoints) { if (endpoints.containsKey(serviceId)) { log.debug("Found match by service id : \"{}\".", serviceId); return endpoints.get(serviceId); } for (Map.Entry<String, ConsumerEndpoint> entry : endpoints.entrySet()) { String key = entry.getKey(); String keyMod = key.replaceAll("\\{" + Constants.PARAM_RESOURCE_ID + "\\}", "([\\\\w\\\\-]+?)"); log.trace("Modified key used for comparison : \"{}\".", keyMod); if (serviceId.matches(keyMod)) { log.debug("Found partial match by service id. Request value : \"{}\", matching value : \"{}\".", serviceId, key); ConsumerEndpoint endpoint = entry.getValue(); parseResourceId(key, endpoint, serviceId); return endpoint; } } log.debug("No match by service id was found. Service id : \"{}\".", serviceId); return null; } private ConsumerGatewayUtil(); static Map<String, ConsumerEndpoint> extractConsumers(Properties endpoints, Properties gatewayProperties); static void extractEndpoints(String key, Properties endpoints, ConsumerEndpoint endpoint); static ConsumerEndpoint findMatch(String serviceId, Map<String, ConsumerEndpoint> endpoints); static String rewriteUrl(String servletUrl, String pathToResource, String responseStr); static ConsumerEndpoint createUnconfiguredEndpoint(Properties props, String pathToResource); static String removeResponseTag(String message); static boolean checkEncryptionProperties(Properties props, Map<String, ConsumerEndpoint> endpoints, Map<String, Encrypter> asymmetricEncrypterCache); }
@Test public void testExtractConsumer0() throws XRd4JException { ConsumerEndpoint temp = ConsumerGatewayUtil.findMatch("GET /www.hel.fi/palvelukarttaws/rest/v2/organization/", map); assertEquals(false, temp == null); assertEquals("FI_PILOT.GOV.0245437-2.ConsumerService", temp.getClientId()); assertEquals("FI_PILOT.GOV.1019125-0.Demo2Service.getOrganizationList.v1", temp.getServiceId()); assertEquals("/www.hel.fi/palvelukarttaws/rest/v2/organization/", temp.getResourcePath()); assertEquals(null, temp.getResourceId()); assertEquals(false, temp.isModifyUrl()); assertEquals("http: assertEquals("ts1", temp.getPrefix()); assertEquals("http: assertEquals(false, temp.isRequestEncrypted()); assertEquals(false, temp.isResponseEncrypted()); assertEquals(new ConsumerMember("FI_PILOT", "GOV", "0245437-2", "ConsumerService").toString(), temp.getConsumer().toString()); assertEquals(new ProducerMember("FI_PILOT", "GOV", "1019125-0", "Demo2Service", "getOrganizationList", "v1").toString(), temp.getProducer().toString()); } @Test public void testExtractConsumer1() throws XRd4JException { ConsumerEndpoint temp = ConsumerGatewayUtil.findMatch("GET /www.hel.fi/palvelukarttaws/rest/v2/organization/49/", map); assertEquals(false, temp == null); assertEquals("FI_PILOT.GOV.0245437-2.TestService", temp.getClientId()); assertEquals("FI_PILOT.GOV.1019125-0.Demo2Service.getOrganization.v1", temp.getServiceId()); assertEquals("/www.hel.fi/palvelukarttaws/rest/v2/organization/{resourceId}/", temp.getResourcePath()); assertEquals("49", temp.getResourceId()); assertEquals(false, temp.isModifyUrl()); assertEquals("http: assertEquals("test", temp.getPrefix()); assertEquals("http: assertEquals(false, temp.isRequestEncrypted()); assertEquals(false, temp.isResponseEncrypted()); assertEquals(new ConsumerMember("FI_PILOT", "GOV", "0245437-2", "TestService").toString(), temp.getConsumer().toString()); assertEquals(new ProducerMember("FI_PILOT", "GOV", "1019125-0", "Demo2Service", "getOrganization", "v1").toString(), temp.getProducer().toString()); } @Test public void testExtractConsumer4() throws XRd4JException { ConsumerEndpoint temp = ConsumerGatewayUtil.findMatch("GET /test.com/api/", map); assertEquals(false, temp == null); assertEquals("FI_PILOT.GOV.0245437-2.ConsumerService", temp.getClientId()); assertEquals("FI_PILOT.GOV.1019125-0.testApi.v1", temp.getServiceId()); assertEquals("/test.com/api/", temp.getResourcePath()); assertEquals(null, temp.getResourceId()); assertEquals(false, temp.isModifyUrl()); assertEquals("http: assertEquals("ts1", temp.getPrefix()); assertEquals("http: assertEquals(false, temp.isRequestEncrypted()); assertEquals(false, temp.isResponseEncrypted()); assertEquals(new ConsumerMember("FI_PILOT", "GOV", "0245437-2", "ConsumerService").toString(), temp.getConsumer().toString()); ProducerMember producer = new ProducerMember("FI_PILOT", "GOV", "1019125-0", "null", "testApi", "v1"); producer.setSubsystemCode(null); assertEquals(producer.toString(), temp.getProducer().toString()); } @Test public void testExtractConsumer5() throws XRd4JException { ConsumerEndpoint temp = ConsumerGatewayUtil.findMatch("GET /example.com/api/", map); assertEquals(true, temp == null); }
RESTGatewayUtil { public static boolean isXml(String contentType) { return contentType != null && (contentType.startsWith(Constants.TEXT_XML) || contentType.startsWith(Constants.APPLICATION_XML)); } private RESTGatewayUtil(); static boolean isXml(String contentType); static boolean isValidContentType(String contentType); static void extractEndpoints(String key, Properties endpoints, AbstractEndpoint endpoint); static boolean isNullOrEmpty(String value); static Decrypter checkPrivateKey(Properties props); static Decrypter getDecrypter(String privateKeyFile, String privateKeyFilePassword, String privateKeyAlias, String privateKeyPassword); static Encrypter checkPublicKey(Properties props, String serviceId); static Encrypter getEncrypter(String publicKeyFile, String publicKeyFilePassword, String serviceId); static int getKeyLength(Properties props); static Encrypter createSymmetricEncrypter(int keyLength); static Decrypter getSymmetricDecrypter(Decrypter asymmetricDecrypter, String encryptedKey, String encodedIV); static void buildEncryptedBody(Encrypter symmetricEncrypter, Encrypter asymmetricEncrypter, SOAPElement msg, String encryptedData); static String getPropertiesDirectory(); static final int DEFAULT_KEY_LENGTH; }
@Test public void testIsXml1() { assertEquals(false, RESTGatewayUtil.isXml(null)); } @Test public void testIsXml2() { assertEquals(false, RESTGatewayUtil.isXml("")); } @Test public void testIsXml3() { assertEquals(true, RESTGatewayUtil.isXml("text/xml")); } @Test public void testIsXml4() { assertEquals(false, RESTGatewayUtil.isXml("application/json")); } @Test public void testIsXml5() { assertEquals(false, RESTGatewayUtil.isXml("application/XML")); } @Test public void testIsXml6() { assertEquals(false, RESTGatewayUtil.isXml("text/html")); }
ProviderGatewayUtil { public static Map<String, String> generateHttpHeaders(ServiceRequest request, ProviderEndpoint endpoint) { log.info("Generate HTTP headers."); Map<String, String> headers = new HashMap<>(); if (endpoint.isSendXrdHeaders()) { log.debug("Generate X-Road specific headers."); headers.put(Constants.XRD_HEADER_CLIENT, request.getConsumer().toString()); headers.put(Constants.XRD_HEADER_SERVICE, request.getProducer().toString()); headers.put(Constants.XRD_HEADER_MESSAGE_ID, request.getId()); log.debug(Constants.LOG_STRING_FOR_HEADERS, Constants.XRD_HEADER_CLIENT, request.getConsumer().toString()); log.debug(Constants.LOG_STRING_FOR_HEADERS, Constants.XRD_HEADER_SERVICE, request.getProducer().toString()); log.debug(Constants.LOG_STRING_FOR_HEADERS, Constants.XRD_HEADER_MESSAGE_ID, request.getId()); if (request.getUserId() != null && !request.getUserId().isEmpty()) { log.debug(Constants.LOG_STRING_FOR_HEADERS, Constants.XRD_HEADER_USER_ID, request.getUserId()); headers.put(Constants.XRD_HEADER_USER_ID, request.getUserId()); } } else { log.debug("Generation of X-Road specific headers is disabled."); } if (endpoint.getContentType() != null && !endpoint.getContentType().isEmpty()) { log.debug(Constants.LOG_STRING_FOR_HEADERS, Constants.HTTP_HEADER_CONTENT_TYPE, endpoint.getContentType()); headers.put(Constants.HTTP_HEADER_CONTENT_TYPE, endpoint.getContentType()); } if (endpoint.getAccept() != null && !endpoint.getAccept().isEmpty()) { log.debug(Constants.LOG_STRING_FOR_HEADERS, Constants.HTTP_HEADER_ACCEPT, endpoint.getAccept()); headers.put(Constants.HTTP_HEADER_ACCEPT, endpoint.getAccept()); } log.info("HTTP headers were succesfully generated."); return headers; } private ProviderGatewayUtil(); static Map<String, ProviderEndpoint> extractProviders(Properties endpoints, Properties gatewayProperties); static void extractEndpoints(String key, Properties endpoints, ProviderEndpoint endpoint); static Map<String, String> generateHttpHeaders(ServiceRequest request, ProviderEndpoint endpoint); static String fromJSONToXML(String data); static String getRequestBody(Map<String, List<String>> params); static void filterRequestParameters(ServiceRequest request, ProviderEndpoint endpoint); static boolean checkPrivateKeyProperties(Properties props, Map<String, ProviderEndpoint> endpoints); }
@Test public void testGenerateHtmlHeaders1() throws XRd4JException { ConsumerMember consumer = new ConsumerMember("FI_PILOT", "GOV", "0245437-2", "ConsumerService"); ProducerMember producer = new ProducerMember("FI_PILOT", "GOV", "1019125-0", "Demo2Service", "getOrganizationList", "v1"); ServiceRequest request = new ServiceRequest(consumer, producer, "12345"); request.setUserId("test-user"); Map<String, String> headers = ProviderGatewayUtil.generateHttpHeaders(request, this.map.get("FI_PILOT.GOV.1019125-0.Demo2Service.getOrganizationList.v1")); assertEquals("FI_PILOT.GOV.0245437-2.ConsumerService", headers.get(Constants.XRD_HEADER_CLIENT)); assertEquals("FI_PILOT.GOV.1019125-0.Demo2Service.getOrganizationList.v1", headers.get(Constants.XRD_HEADER_SERVICE)); assertEquals("12345", headers.get(Constants.XRD_HEADER_MESSAGE_ID)); assertEquals("test-user", headers.get(Constants.XRD_HEADER_USER_ID)); assertEquals(null, headers.get(Constants.HTTP_HEADER_CONTENT_TYPE)); assertEquals(null, headers.get(Constants.HTTP_HEADER_ACCEPT)); } @Test public void testGenerateHtmlHeaders2() throws XRd4JException { ConsumerMember consumer = new ConsumerMember("FI_PILOT", "GOV", "0245437-2", "ConsumerService"); ProducerMember producer = new ProducerMember("FI_PILOT", "GOV", "1019125-0", "Demo2Service", "getWeather", "v1"); ServiceRequest request = new ServiceRequest(consumer, producer, "12345"); request.setUserId("test-user"); Map<String, String> headers = ProviderGatewayUtil.generateHttpHeaders(request, this.map.get("FI_PILOT.GOV.1019125-0.Demo2Service.getWeather.v1")); assertEquals(null, headers.get(Constants.XRD_HEADER_CLIENT)); assertEquals(null, headers.get(Constants.XRD_HEADER_SERVICE)); assertEquals(null, headers.get(Constants.XRD_HEADER_MESSAGE_ID)); assertEquals(null, headers.get(Constants.XRD_HEADER_USER_ID)); assertEquals(Constants.APPLICATION_JSON, headers.get(Constants.HTTP_HEADER_CONTENT_TYPE)); assertEquals(Constants.APPLICATION_JSON, headers.get(Constants.HTTP_HEADER_ACCEPT)); }
SkippableLogRecord implements WritableComparable<SkippableLogRecord> { public boolean isSkipped() { return jvm.toString() == null || jvm.toString().isEmpty(); } SkippableLogRecord(); SkippableLogRecord(Text line); Text getJvm(); IntWritable getDay(); IntWritable getMonth(); IntWritable getYear(); Text getRoot(); Text getFilename(); Text getPath(); IntWritable getStatus(); LongWritable getSize(); boolean isSkipped(); @Override void readFields(DataInput in); @Override void write(DataOutput out); @Override int compareTo(SkippableLogRecord other); @Override int hashCode(); @Override boolean equals(Object obj); }
@Test public void testReadLineForOtherApp() { String line = "https-other aac.alliedinsurance.com 0 155.188.183.17 - - [27/Feb/2015:07:18:04 -0600] " + "\"GET /download/IT%20Tech%20Writing%20Only/PL%20NB%20Billing%20Changes%20Feb%202015%20TipSheet.pdf " + "HTTP/1.1\" 200 207773 \"https: + "(compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; " + ".NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET CLR 1.1.4322; .NET4.0C; " + ".NET4.0E; InfoPath.2)\""; SkippableLogRecord rec = new SkippableLogRecord(new Text(line)); assertTrue(rec.isSkipped()); }
Trie { public String longestPrefix(String inputWord) { if (inputWord == null || inputWord.isEmpty()) { return null; } Node node = root; Node child = null; char ch = '\u0000'; final int len = inputWord.length(); StringBuilder runningPrefix = new StringBuilder(); String longestPrefix = null; for (int idx = 0; idx < len; idx++) { ch = inputWord.charAt(idx); child = node.getChild(ch); if (node.isEndOfWord) { longestPrefix = runningPrefix.toString(); } if (child != null) { runningPrefix.append(ch); node = child; } else { break; } } if (node.isEndOfWord && node.getChild(ch) == null && ch == node.value) { longestPrefix = runningPrefix.toString(); } return longestPrefix; } Trie(String[] words); String longestPrefix(String inputWord); }
@Test public void testLongestPrefix1() { trie = new Trie(new String[] { "abc", "abcd", "abcdde" }); Assert.assertEquals("abcd", trie.longestPrefix("abcdd")); } @Test public void testLongestPrefix2() { trie = new Trie(new String[] { "are", "area", "base", "cat", "cater", "basement" }); Assert.assertEquals("cater", trie.longestPrefix("caterer")); Assert.assertEquals("basement", trie.longestPrefix("basement")); Assert.assertEquals("are", trie.longestPrefix("are")); Assert.assertEquals("are", trie.longestPrefix("arex")); Assert.assertEquals("base", trie.longestPrefix("basemexz")); Assert.assertNull(trie.longestPrefix("xyz")); Assert.assertNull(trie.longestPrefix("")); Assert.assertNull(trie.longestPrefix(null)); Assert.assertNull(trie.longestPrefix(" ")); }
PracticeQuestionsCh11 { public static int firstOccurrence(final int[] arr, final int key) { int index = -1; int left = 0; int right = arr.length - 1; if (right < 0 || arr[right] <= key) { return index; } int mid = left + ((right - left) >>> 1); for (; left <= right; mid = left + ((right - left) >>> 1)) { if (arr[mid] > key) { index = mid; right = mid - 1; } else { left = mid + 1; } } return index; } static int firstOccurrence(final int[] arr, final int key); static final Logger LOGGER; }
@Test public void testFirstOccurance() { final int[] arr = { -1, -10, 2, 108, 108, 243, 285, 285, 285, 401 }; Assert.assertEquals(-1, firstOccurrence(arr, 500)); Assert.assertEquals(3, firstOccurrence(arr, 101)); }
PracticeQuestionsCh13 { public static Integer[] intersection(final int[] a, final int[] b) { Integer[] intersection = null; if (a.length < b.length) { intersection = findIntersection(a, b); } else { intersection = findIntersection(b, a); } return intersection; } static Integer[] intersection(final int[] a, final int[] b); static final Logger LOGGER; }
@Test public void testIntersection() { int[] a = { -2, -1, 5, 7, 11 }; int[] b = { 0, 1, 5, 7, 13 }; Assert.assertArrayEquals(new Integer[] { 5, 7 }, intersection(a, b)); }
PracticeQuestionsCh10 { public static int[] kSort(Integer[] arr, int k) { final int size = Math.min(2 * k, arr.length); MinHeap<Integer> minHeap = new MinHeap<Integer>(Arrays.copyOf(arr, size)); int[] sorted = new int[arr.length]; int i = 0; for (int j = size + i; j < arr.length; ++i, ++j) { sorted[i] = minHeap.delete(); minHeap.insert(arr[j]); } for (; minHeap.size() > 0; ++i) { sorted[i] = minHeap.delete(); } return sorted; } static int[] kSort(Integer[] arr, int k); static int[] runningMedian(int[] elements); static final Logger LOGGER; }
@Test public void testKSort() { final Integer[] arr = { 3, 1, 7, 4, 10 }; final int[] expected = { 1, 3, 4, 7, 10 }; int[] actual = kSort(arr, 2); Assert.assertArrayEquals(expected, actual); actual = kSort(arr, 4); Assert.assertArrayEquals(expected, actual); }
PracticeQuestionsCh10 { public static int[] runningMedian(int[] elements) { final MinHeap<Integer> minHeap = new MinHeap<Integer>(new Integer[] {}); final MaxHeap<Integer> maxHeap = new MaxHeap<Integer>(new Integer[] {}); final int[] medians = new int[elements.length]; int median = 0; int element = 0; boolean isElementLessThanMedian = false; Heap<Integer> heapWhereElementToBeInserted = null; Heap<Integer> otherHeap = null; for (int i = 0; i < elements.length; ++i) { element = elements[i]; isElementLessThanMedian = element < median; heapWhereElementToBeInserted = heapWhereElementToBeInserted(isElementLessThanMedian, minHeap, maxHeap); otherHeap = heapWhereElementToBeInserted == minHeap ? maxHeap : minHeap; transferTopItemIfRequired(heapWhereElementToBeInserted, otherHeap); heapWhereElementToBeInserted.insert(element); if (isTheSizeOfBothHeapsEqual(minHeap, maxHeap)) { median = average(minHeap.root(), maxHeap.root()); } else { median = heapWhereElementToBeInserted.root(); } medians[i] = median; } return medians; } static int[] kSort(Integer[] arr, int k); static int[] runningMedian(int[] elements); static final Logger LOGGER; }
@Test public void testRunningMedian() { int[] elements = { 5, 15, 1, 3, 2, 8, 7 }; int[] expected = { 5, 10, 5, 4, 3, 4, 5 }; int[] actual = runningMedian(elements); Assert.assertArrayEquals(expected, actual); }
PracticeQuestionsCh5 { public static long[] computeParities(final long[] input) { final int numInput = input == null || input.length == 0 ? 0 : input.length; if (numInput == 0) { return input; } final int storage = (int) (numInput >> 6) + 1; final long[] parities = new long[storage]; if (isOddParity(input[0])) { parities[0] ^= 1; } for (int i = 1; i < numInput; i++) { final int section = i >> 6; final int currentIdx = i % 64 - 1; if (isOddParity(input[i])) { parities[section] ^= 1 << currentIdx; } } return parities; } static long[] computeParities(final long[] input); static long swapBits(final long x, final int i, final int j); static void powerSet(Set<Integer> set); static int stringToInt(String s); static String changeBase(String s, int b1, int b2); static final Logger LOGGER; }
@Test public void testComputeParities() { long[] input = null; Assert.assertNull(computeParities(input)); long[] parities = computeParities(new long[87]); Assert.assertEquals(2, parities.length); input = new long[2]; input[0] = 8L; input[1] = 9L; parities = computeParities(input); Assert.assertEquals(1, parities.length); Assert.assertEquals(1, parities[0]); }
PracticeQuestionsCh5 { public static long swapBits(final long x, final int i, final int j) { if (j <= i || i < 0 || j > 63) { return x; } final long mask1 = 1L << i; final long mask2 = 1L << j; final long mask = mask1 | mask2; return x ^ mask; } static long[] computeParities(final long[] input); static long swapBits(final long x, final int i, final int j); static void powerSet(Set<Integer> set); static int stringToInt(String s); static String changeBase(String s, int b1, int b2); static final Logger LOGGER; }
@Test public void testSwapBits() { Assert.assertEquals(2, swapBits(2, 1, 1)); Assert.assertEquals(2, swapBits(2, -1, 1)); Assert.assertEquals(2, swapBits(2, 1, 65)); Assert.assertEquals(1, swapBits(2, 0, 1)); Assert.assertEquals(14, swapBits(7, 0, 3)); }
PracticeQuestionsCh5 { public static void powerSet(Set<Integer> set) { if (set == null) { LOGGER.info("Null input."); return; } LOGGER.info("{}.", set.toString()); LOGGER.info("{" + "Ø" + "}"); final Integer[] elements = set.toArray(new Integer[] {}); final int numElements = elements.length; final StringBuilder identitySet = new StringBuilder(); for (int currentIdx = 0; currentIdx < numElements; currentIdx++) { int currentElement = elements[currentIdx]; identitySet.append(currentElement); if (currentIdx != numElements - 1) { identitySet.append(", "); } for (int lookAheadIdx = currentIdx + 1; lookAheadIdx < numElements; lookAheadIdx++) { int lookAheadElement = elements[lookAheadIdx]; LOGGER.info("{" + "{}, {}" + "}.", currentElement, lookAheadElement); } } LOGGER.info("{" + "{}" + "}.", identitySet.toString()); } static long[] computeParities(final long[] input); static long swapBits(final long x, final int i, final int j); static void powerSet(Set<Integer> set); static int stringToInt(String s); static String changeBase(String s, int b1, int b2); static final Logger LOGGER; }
@SuppressWarnings("unchecked") @Test public void testPowerSet() { powerSet(null); powerSet(Collections.EMPTY_SET); Set<Integer> set = new HashSet<>(); set.add(1); set.add(2); set.add(3); powerSet(set); }
PracticeQuestionsCh5 { public static int stringToInt(String s) { final String regex = "^-?\\d+"; if (s == null || !s.matches(regex)) { throw new NumberFormatException(s + " is not a valid integer encoding."); } return parseInt(s, 10, s.length() - 1); } static long[] computeParities(final long[] input); static long swapBits(final long x, final int i, final int j); static void powerSet(Set<Integer> set); static int stringToInt(String s); static String changeBase(String s, int b1, int b2); static final Logger LOGGER; }
@Test public void testStringToInt() { try { stringToInt(null); Assert.fail(); } catch (NumberFormatException iae) { } try { stringToInt("123abc"); Assert.fail(); } catch (NumberFormatException iae) { } int result = stringToInt("-123"); Assert.assertEquals(-123, result); result = stringToInt("123"); Assert.assertEquals(123, result); }
XMLSigner { public void sign(String inputFile, String outputFile, String referenceURI) throws Exception { File ipFile = new File(inputFile); File opFile = new File(outputFile); SecurityUtil.print(ipFile); KeyPair keyPair = KeyStoreManager.getKeyPair(XMLSigner.class .getResource("/" + KEYSTORE).getPath(), STORE_PASSWORD, KEY_PASSWORD, ALIAS); SignatureManager sigMgr = new SignatureManager(keyPair, XMLSigner.class .getResource("/" + CERTIFICATE).getPath(), referenceURI); sigMgr.sign(ipFile, opFile); SecurityUtil.print(opFile); } void sign(String inputFile, String outputFile, String referenceURI); void validate(String inputFile); }
@Test public void testSign() { String inputFile = XMLSignerTest.class.getResource("/" + INPUT_FILE) .getPath(); String outputFile = new File(inputFile).getParent() + File.separator + OUTPUT_FILE; try { XMLSigner.sign(inputFile, outputFile, REFERENCE_URI); } catch (Exception e) { e.printStackTrace(); Assert.fail("Shouldn't be here."); } }
PracticeQuestionsCh5 { private static StringBuilder convertToBase(int x, int b) { StringBuilder buffer = new StringBuilder(); buffer.insert(0, encode(x % b)); if (x >= b) { buffer.insert(0, convertToBase(x / b, b)); } return buffer; } static long[] computeParities(final long[] input); static long swapBits(final long x, final int i, final int j); static void powerSet(Set<Integer> set); static int stringToInt(String s); static String changeBase(String s, int b1, int b2); static final Logger LOGGER; }
@Test public void testConvertToBase() { Assert.assertNull(changeBase(null, 10, 2)); Assert.assertEquals("", changeBase("", 10, 2)); Assert.assertEquals("1001", changeBase("9", 10, 2)); Assert.assertEquals("1F", changeBase("31", 10, 16)); }
CircularQueue { public int enqueue(int element) { if (isCapacityFull()) { resize(); } queue[++end] = element; return element; } CircularQueue(); CircularQueue(final int capacity); int size(); int capacity(); int enqueue(int element); int dequeue(); boolean isEmpty(); static final Logger LOGGER; static final int DEFAULT_CAPACITY; }
@Test public void testEnqueue() { queue.enqueue(11); Assert.assertEquals(CircularQueue.DEFAULT_CAPACITY, queue.capacity()); Assert.assertEquals(1, queue.size()); }
CircularQueue { public int dequeue() { if (isEmpty()) { throw new NoSuchElementException("Cannot dequeue from an empty queue."); } return queue[begin++]; } CircularQueue(); CircularQueue(final int capacity); int size(); int capacity(); int enqueue(int element); int dequeue(); boolean isEmpty(); static final Logger LOGGER; static final int DEFAULT_CAPACITY; }
@Test public void testDequeue() { queue.enqueue(11); queue.enqueue(12); queue.enqueue(13); Assert.assertEquals(11, queue.dequeue()); Assert.assertEquals(CircularQueue.DEFAULT_CAPACITY, queue.capacity()); Assert.assertEquals(2, queue.size()); } @Test(expected = NoSuchElementException.class) public void testDequeueWhenEmpty() { queue.dequeue(); }
CircularQueue { public int capacity() { return capacity; } CircularQueue(); CircularQueue(final int capacity); int size(); int capacity(); int enqueue(int element); int dequeue(); boolean isEmpty(); static final Logger LOGGER; static final int DEFAULT_CAPACITY; }
@Test public void testCapacity() { CircularQueue cq = new CircularQueue(1); Assert.assertEquals(1, cq.capacity()); Assert.assertEquals(0, cq.size()); }
CircularQueue { private void resize() { LOGGER.debug("Resizing queue from {} to {}.", capacity, capacity * 2); queue = Arrays.copyOf(queue, capacity *= 2); } CircularQueue(); CircularQueue(final int capacity); int size(); int capacity(); int enqueue(int element); int dequeue(); boolean isEmpty(); static final Logger LOGGER; static final int DEFAULT_CAPACITY; }
@Test public void testResize() { CircularQueue cq = new CircularQueue(1); Assert.assertEquals(1, cq.capacity()); Assert.assertEquals(0, cq.size()); cq.enqueue(1); cq.enqueue(2); Assert.assertEquals(2, cq.capacity()); Assert.assertEquals(2, cq.size()); }
MaxStack { public int push(int element) { if (maxStack.isEmpty()) { maxStack.add(element); } else { maxStack.add(0, Math.max(element, maxStack.peek().intValue())); } stack.add(0, element); return element; } int push(int element); int pop(); int max(); int size(); }
@Test public void testPush() { MaxStack maxStack = new MaxStack(); maxStack.push(1); maxStack.push(3); maxStack.push(2); Assert.assertEquals(3, maxStack.size()); }
MaxStack { public int pop() { maxStack.remove(0); return stack.remove(0); } int push(int element); int pop(); int max(); int size(); }
@Test public void testPop() { MaxStack maxStack = new MaxStack(); maxStack.push(1); maxStack.push(3); maxStack.push(2); Assert.assertEquals(2, maxStack.pop()); Assert.assertEquals(3, maxStack.pop()); Assert.assertEquals(1, maxStack.pop()); } @Test(expected = NoSuchElementException.class) public void testPopWhenEmpty() { new MaxStack().pop(); }
MaxStack { public int max() { return maxStack.peek(); } int push(int element); int pop(); int max(); int size(); }
@Test public void testMax() { MaxStack maxStack = new MaxStack(); maxStack.push(1); maxStack.push(3); maxStack.push(2); Assert.assertEquals(3, maxStack.max()); }
XMLSigner { public void validate(String inputFile) throws Exception { File signedFile = new File(inputFile); KeyPair keyPair = KeyStoreManager.getKeyPair(XMLSigner.class .getResource("/" + KEYSTORE).getPath(), STORE_PASSWORD, KEY_PASSWORD, ALIAS); SignatureManager sigMan = new SignatureManager(keyPair, XMLSigner.class .getResource("/" + CERTIFICATE).getPath(), null); sigMan.validate(signedFile); } void sign(String inputFile, String outputFile, String referenceURI); void validate(String inputFile); }
@Test public void testValidate() { String inputFile = XMLSignerTest.class.getResource("/" + INPUT_FILE) .getPath(); String outputFile = new File(inputFile).getParent() + File.separator + OUTPUT_FILE; try { XMLSigner.validate(outputFile); } catch (Exception e) { e.printStackTrace(); Assert.fail("Shouldn't be here."); } }
PracticeQuestionsCh8 { public static int evalRpn(String expr) { final String basicRpnPattern = "-?\\d+"; if (expr != null && expr.matches(basicRpnPattern)) { return Integer.valueOf(expr); } Stack<String> rpnStack = new Stack<String>(); String[] tokens = expr.split(","); int value = 0; for (String token : tokens) { if (token.matches(basicRpnPattern)) { rpnStack.push(token); } else { int operand2 = Integer.valueOf(rpnStack.pop()); int operand1 = Integer.valueOf(rpnStack.pop()); value = eval(operand1, operand2, token); rpnStack.push(String.valueOf(value)); } } value = Integer.valueOf(rpnStack.pop()); LOGGER.info("Expression \"{}\" evaluated to {}.", expr, value); return value; } static int evalRpn(String expr); static final Logger LOGGER; }
@Test public void testEvalRpn() { Assert.assertEquals(123, evalRpn("123")); Assert.assertEquals(3, evalRpn("1,2,+")); Assert.assertEquals(60, evalRpn("1,2,+,4,5,x,x")); Assert.assertEquals(-4, evalRpn("1,1,+,-2,x")); Assert.assertEquals(0, evalRpn("4,6,/,2,/")); }
PracticeQuestionsCh9 { public static BinaryTreeNode<Integer> lowestCommonAncestor(BinaryTreeNode<Integer> root, BinaryTreeNode<Integer> n1, BinaryTreeNode<Integer> n2) { if (root == null || root == n1 || root == n2) { return root; } BinaryTreeNode<Integer> left = lowestCommonAncestor(root.leftChild(), n1, n2); BinaryTreeNode<Integer> right = lowestCommonAncestor(root.rightChild(), n1, n2); if (left != null && right != null) { return root; } return left != null ? left : right; } static BinaryTreeNode<Integer> lowestCommonAncestor(BinaryTreeNode<Integer> root, BinaryTreeNode<Integer> n1, BinaryTreeNode<Integer> n2); static final Logger LOGGER; }
@Test public void testLowestCommonAncestor() { BinaryTreeNode<Integer> lca = lowestCommonAncestor(root, three, five); Assert.assertEquals(4, lca.data().intValue()); lca = lowestCommonAncestor(root, one, three); Assert.assertEquals(2, lca.data().intValue()); lca = lowestCommonAncestor(root, three, eight); Assert.assertEquals(6, lca.data().intValue()); }
PracticeQuestionsCh12 { @SuppressWarnings("unchecked") public static List<List<String>> anagrams(final List<String> dictionary) { final MultiMap<Integer, Integer> anagramMap = new MultiValueMap<Integer, Integer>(); char[] arr = null; int hashCode = -1; for (int i = 0; i < dictionary.size(); ++i) { arr = dictionary.get(i).toCharArray(); Arrays.sort(arr); hashCode = String.valueOf(arr).hashCode(); anagramMap.put(hashCode, i); } final List<List<String>> anagrams = new ArrayList<>(); final Set<Entry<Integer, Object>> anagramIndices = anagramMap.entrySet(); List<Integer> aSet = null; for (final Object o : anagramIndices) { aSet = (List<Integer>) ((Entry<Integer, Object>) o).getValue(); if (aSet.size() > 1) { final List<String> an = new ArrayList<>(); for (final int i : aSet) { an.add(dictionary.get(i)); } anagrams.add(an); } } return anagrams; } @SuppressWarnings("unchecked") static List<List<String>> anagrams(final List<String> dictionary); static final Logger LOGGER; }
@Test public void testAnagrams() { List<String> dictionary = new ArrayList<>(); dictionary.add("urn"); dictionary.add("won"); dictionary.add("bear"); dictionary.add("bare"); dictionary.add("run"); dictionary.add("cafe"); dictionary.add("now"); List<List<String>> anagrams = anagrams(dictionary); Assert.assertEquals(3, anagrams.size()); Assert.assertTrue(anagrams.contains(Arrays.asList(new String[] { "urn", "run" }))); Assert.assertTrue(anagrams.contains(Arrays.asList(new String[] { "won", "now" }))); Assert.assertTrue(anagrams.contains(Arrays.asList(new String[] { "bear", "bare" }))); }
PracticeQuestionsCh7 { public static LinkedListNode<Integer> mergeLists(LinkedList<Integer> l, LinkedList<Integer> f) { final String newline = System.getProperty("line.separator"); LinkedListNode<Integer> currentHead = l.head(); LinkedListNode<Integer> bigger = currentHead.successor(); LinkedListNode<Integer> otherHead = f.head(); LinkedListNode<Integer> smallest = currentHead.successor(); while (otherHead.successor().data() != null) { LOGGER.info("{}", newline); LOGGER.info("Current head: {}.", currentHead); LOGGER.info("Current: {}.", bigger); LOGGER.info("Other head: {}.", otherHead); LOGGER.info("Smallest: {}.", smallest); if (bigger.data() < otherHead.successor().data()) { LOGGER.info("Setting current head successor to: {}.", bigger.successor()); currentHead.setSuccessor(bigger.successor()); LOGGER.info("Setting bigger successor to: {}.", otherHead.successor()); bigger.setSuccessor(otherHead.successor()); LOGGER.info("Setting bigger to: {}.", otherHead.successor()); bigger = otherHead.successor(); LOGGER.info("Setting other head successor to: {}.", smallest); otherHead.setSuccessor(smallest); LOGGER.info("Swapping heads."); LinkedListNode<Integer> tempHead = currentHead; currentHead = otherHead; otherHead = tempHead; } else { LinkedListNode<Integer> predecessor = predecessor(currentHead, bigger); LOGGER.info("Predecessor to {} is {}.", bigger, predecessor); LinkedListNode<Integer> temp = otherHead.successor(); LOGGER.info("Setting predecessor successor to: {}.", temp); predecessor.setSuccessor(temp); LOGGER.info("Setting smallest to: {}.", currentHead.successor()); smallest = currentHead.successor(); LOGGER.info("Setting other head successor to: {}.", temp.successor()); otherHead.setSuccessor(temp.successor()); LOGGER.info("Setting temp successor to: {}.", bigger); temp.setSuccessor(bigger); } } return currentHead; } static LinkedListNode<Integer> mergeLists(LinkedList<Integer> l, LinkedList<Integer> f); static LinkedListNode<Integer> startOfLoop(LinkedList<Integer> l); static LinkedListNode<Integer> intersection(LinkedList<Integer> l1, LinkedList<Integer> l2); static void evenOddMerge(LinkedList<Integer> l); static void reverse(LinkedList<Integer> l); static final Logger LOGGER; }
@Test public void testMergeLists() { LinkedList<Integer> l = newLinkedList(2, 5, 7); LinkedList<Integer> f = newLinkedList(3, 11); int[] merged = new int[] { 2, 3, 5, 7, 11 }; LinkedListNode<Integer> runningNode = mergeLists(l, f); assertArrayEqualsList(merged, runningNode); l = newLinkedList(3, 11); f = newLinkedList(2, 5, 7); runningNode = mergeLists(l, f); assertArrayEqualsList(merged, runningNode); }
PracticeQuestionsCh7 { public static LinkedListNode<Integer> startOfLoop(LinkedList<Integer> l) { LinkedListNode<Integer> tortoise = l.head(); LinkedListNode<Integer> hare = l.head(); do { if (tortoise != l.tail()) { tortoise = tortoise.successor(); LOGGER.info("Tortoise was here: {}.", tortoise); } if (hare.successor() != l.tail()) { hare = hare.successor().successor(); LOGGER.info("Hare was here: {}.", hare); } if (tortoise == l.tail() || hare == l.tail()) { LOGGER.info("No loop found."); return null; } } while (!tortoise.equals(hare)); LOGGER.info("Loop found. Tortoise is here: {}, hare is here: {}.", tortoise, hare); for (tortoise = l.head(); !tortoise.equals(hare); tortoise = tortoise.successor(), hare = hare.successor()) ; LOGGER.info("Found start of loop at: {}.", tortoise); return tortoise; } static LinkedListNode<Integer> mergeLists(LinkedList<Integer> l, LinkedList<Integer> f); static LinkedListNode<Integer> startOfLoop(LinkedList<Integer> l); static LinkedListNode<Integer> intersection(LinkedList<Integer> l1, LinkedList<Integer> l2); static void evenOddMerge(LinkedList<Integer> l); static void reverse(LinkedList<Integer> l); static final Logger LOGGER; }
@Test public void testStartOfLoop() { LinkedList<Integer> l = newLinkedList(2, 5, 7); LinkedListNode<Integer> startOfLoop = startOfLoop(l); Assert.assertNull(startOfLoop); LinkedListNode<Integer> runningNode = l.head(); for (; runningNode.successor() != null; runningNode = runningNode.successor()) { if (runningNode.successor().data() == 7) { runningNode.successor().setSuccessor(runningNode); break; } } startOfLoop = startOfLoop(l); Assert.assertNotNull(startOfLoop); Assert.assertEquals(5, startOfLoop.data().intValue()); }
PracticeQuestionsCh7 { public static LinkedListNode<Integer> intersection(LinkedList<Integer> l1, LinkedList<Integer> l2) { final int sizeL1 = l1.size(); final int sizeL2 = l2.size(); LOGGER.info("List 1 size: {}.", sizeL1); LOGGER.info("List 2 size: {}.", sizeL2); int diff = sizeL1 - sizeL2; LinkedListNode<Integer> l1Pointer = l1.head(); LinkedListNode<Integer> l2Pointer = l2.head(); if (diff < 0) { for (; diff > 0; l2Pointer = l2Pointer.successor(), --diff) ; } else { for (; diff > 0; l1Pointer = l1Pointer.successor(), --diff) ; } while (l1Pointer != l1.tail() && l2Pointer != l2.tail()) { LOGGER.info("List 1 pointer is at: {}.", l1Pointer); LOGGER.info("List 2 pointer is at: {}.", l2Pointer); if (l1Pointer.equals(l2Pointer)) { return l1Pointer; } l1Pointer = l1Pointer.successor(); l2Pointer = l2Pointer.successor(); } return null; } static LinkedListNode<Integer> mergeLists(LinkedList<Integer> l, LinkedList<Integer> f); static LinkedListNode<Integer> startOfLoop(LinkedList<Integer> l); static LinkedListNode<Integer> intersection(LinkedList<Integer> l1, LinkedList<Integer> l2); static void evenOddMerge(LinkedList<Integer> l); static void reverse(LinkedList<Integer> l); static final Logger LOGGER; }
@Test public void testIntersection() { LinkedList<Integer> l1 = newLinkedList(2, 3, 5, 7); LinkedList<Integer> l2 = newLinkedList(1, 5, 7); LinkedListNode<Integer> intersection = intersection(l1, l2); Assert.assertNotNull(intersection); Assert.assertEquals(5, intersection.data().intValue()); }
PracticeQuestionsCh7 { public static void evenOddMerge(LinkedList<Integer> l) { LinkedListNode<Integer> evenPointer = l.head(); LinkedListNode<Integer> oddPointer = l.head(); LinkedListNode<Integer> oddHead = null; while (evenPointer.successor() != l.tail()) { oddPointer = evenPointer.successor().successor(); LOGGER.info("Odd pointer is at: {}.", oddPointer); if (oddHead == null) { oddHead = oddPointer; } evenPointer = evenPointer.successor(); LOGGER.info("Even pointer is at: {}.", evenPointer); if (oddPointer.successor() != null) { LOGGER.info("Setting even pointer successor to: {}.", oddPointer.successor()); evenPointer.setSuccessor(oddPointer.successor()); } if (evenPointer.successor() != l.tail()) { LOGGER.info("Setting odd pointer successor to: {}.", evenPointer.successor()); oddPointer.setSuccessor(evenPointer.successor().successor()); } } evenPointer.setSuccessor(oddHead); } static LinkedListNode<Integer> mergeLists(LinkedList<Integer> l, LinkedList<Integer> f); static LinkedListNode<Integer> startOfLoop(LinkedList<Integer> l); static LinkedListNode<Integer> intersection(LinkedList<Integer> l1, LinkedList<Integer> l2); static void evenOddMerge(LinkedList<Integer> l); static void reverse(LinkedList<Integer> l); static final Logger LOGGER; }
@Test public void testEvenOddMerge() { LinkedList<Integer> l = newLinkedList(1, 2, 3, 4, 5); evenOddMerge(l); LinkedListNode<Integer> runningNode = l.head(); int[] merged = new int[] { 1, 3, 5, 2, 4 }; assertArrayEqualsList(merged, runningNode); l = newLinkedList(1, 2, 3, 4, 5, 6); evenOddMerge(l); runningNode = l.head(); merged = new int[] { 1, 3, 5, 2, 4, 6 }; assertArrayEqualsList(merged, runningNode); }
PracticeQuestionsCh7 { public static void reverse(LinkedList<Integer> l) { LinkedListNode<Integer> previous = l.head(); LinkedListNode<Integer> current = previous.successor(); LinkedListNode<Integer> next = current.successor(); while (next != l.tail()) { LOGGER.info("Previous: {}, current: {}, next: {}.", previous, current, next); current.setSuccessor(previous); previous = current; current = next; next = next.successor(); } LOGGER.info("Swapping head and tail."); LOGGER.info("Previous: {}, current: {}, next: {}.", previous, current, next); current.setSuccessor(previous); previous = l.head().successor(); l.head().setSuccessor(current); next.setSuccessor(previous); } static LinkedListNode<Integer> mergeLists(LinkedList<Integer> l, LinkedList<Integer> f); static LinkedListNode<Integer> startOfLoop(LinkedList<Integer> l); static LinkedListNode<Integer> intersection(LinkedList<Integer> l1, LinkedList<Integer> l2); static void evenOddMerge(LinkedList<Integer> l); static void reverse(LinkedList<Integer> l); static final Logger LOGGER; }
@Test public void testReverse() { LinkedList<Integer> l = newLinkedList(1, 2, 3, 4, 5); reverse(l); LinkedListNode<Integer> runningNode = l.head(); int[] reversed = new int[] { 5, 4, 3, 2, 1 }; assertArrayEqualsList(reversed, runningNode); }
PracticeQuestionsCh6 { public static List<String> keypadPermutation(int num) { final List<String> perms = new ArrayList<>(); final String numSeq = String.valueOf(num); return permute(numSeq, 0, perms); } static List<String> keypadPermutation(int num); static final Logger LOGGER; }
@Test public void testKeypadPermutation() { List<String> expected = new ArrayList<>(); expected.add("AD"); expected.add("AE"); expected.add("AF"); expected.add("BD"); expected.add("BE"); expected.add("BF"); expected.add("CD"); expected.add("CE"); expected.add("CF"); Assert.assertEquals(expected, keypadPermutation(23)); expected.clear(); expected.add("A"); expected.add("B"); expected.add("C"); Assert.assertEquals(expected, keypadPermutation(12)); }
BingoNumberCaller { public String callBingoNumber() throws NoMoreBingoNumbersException { if (numbersCalled.size() == LARGEST_NUMBER) { throw new NoMoreBingoNumbersException( "All possible Bingo numbers have been called."); } final int randomBingoNumberIndex = generator.nextInt(LARGEST_NUMBER); final String bingoNumber = BINGO_NUMBER_POOL[randomBingoNumberIndex % BUCKET_SIZE][randomBingoNumberIndex / BUCKET_SIZE]; if (numbersCalled.add(bingoNumber)) { return bingoNumber; } return callBingoNumber(); } String callBingoNumber(); Set<String> getNumbersCalled(); boolean isCalled(String bingoNumber); static final String[][] BINGO_NUMBER_POOL; }
@Test public void testGenerateBingoNumber() { for (int i = 1; i <= LARGEST_NUMBER; i++) { try { String result = generator.callBingoNumber(); assertNotNull(result); assertTrue(BINGO.contains(String.valueOf(result.charAt(0)))); assertTrue(Integer.parseInt(result.substring(1)) <= LARGEST_NUMBER); } catch (NoMoreBingoNumbersException ex) { assertEquals(LARGEST_NUMBER, i); } } }
BinaryTreeWalker { public static <E> List<E> iterativeInorder(BinaryTreeNode<E> root) { BinaryTreeNode<E> current = root; BinaryTreeNode<E> previous = null; List<E> visited = new ArrayList<>(); while (current != null) { if (previous == current.parent()) { LOGGER.debug("(p = c.parent) Previous {} is parent of current {}.", previous, current); LOGGER.debug("(p = c.parent) Setting previous {} to current {}.", previous, current); previous = current; if (current.leftChild() != null) { LOGGER.debug("(p = c.parent) Setting current {} to current -> left {}.", current, current.leftChild()); current = current.leftChild(); } else { LOGGER.debug("(p = c.parent) Added current {} to visited.", current); visited.add(current.data()); if (current.rightChild() != null) { LOGGER.debug("(p = c.parent) Setting current {} to current -> right {}.", current, current.rightChild()); current = current.rightChild(); } else { LOGGER.debug("(p = c.parent) Setting current {} to current -> parent {}.", current, current.parent()); current = current.parent(); } } } else if (previous == current.leftChild()) { LOGGER.debug("(p = c.left) Previous {} is left child of current {}.", previous, current); LOGGER.debug("(p = c.left) Setting previous {} to current {}.", previous, current); previous = current; LOGGER.debug("(p = c.left) Added current {} to visited.", current); visited.add(current.data()); if (current.rightChild() != null) { LOGGER.debug("(p = c.left) Setting current {} to current -> right {}.", current, current.rightChild()); current = current.rightChild(); } else { LOGGER.debug("(p = c.left) Setting current {} to current -> parent {}.", current, current.parent()); current = current.parent(); } } else if (previous == current.rightChild()) { LOGGER.debug("(p = c.right) Previous {} is right child of current {}.", previous, current); LOGGER.debug("(p = c.left) Setting previous {} to current {}.", previous, current); LOGGER.debug("(p = c.right) Setting current {} to current -> parent {}.", current, current.parent()); previous = current; current = current.parent(); } } return visited; } static List<E> iterativeInorder(BinaryTreeNode<E> root); static List<E> recursiveInorder(BinaryTreeNode<E> root); static final Logger LOGGER; }
@Test public void testIterativeInorder() { assertInorder(iterativeInorder(root)); }
PracticeQuestionsCh5 { public static int insertMIntoN(int N, int M, int i, int j) { LOGGER.debug("N = {}, M = {}, i = {}, j = {}.", N, M, i, j); final int mask1 = ~0 << (j + 1); final int mask2 = (1 << i) - 1; final int mask = mask1 | mask2; final int maskAndN = mask & N; final int leftShiftedM = M << i; LOGGER.debug("mask 1 = {}, mask 2 = {}.", mask1, mask2); LOGGER.debug("mask = {}.", mask); LOGGER.debug("maskAndN = {}.", maskAndN); LOGGER.debug("leftShiftedM = {}.", leftShiftedM); return maskAndN | leftShiftedM; } static int insertMIntoN(int N, int M, int i, int j); static final Logger LOGGER; }
@Test public void testInsertMIntoN() { Assert.assertEquals(2124, PracticeQuestionsCh5.insertMIntoN(2048, 19, 2, 6)); }
StackWithMin extends Stack<E> { public E min() { return this.min; } @Override E push(E element); @Override E pop(); E min(); }
@Test public void testMin() { assertEquals(Integer.valueOf(1), stack.min()); }
SetOfStacks { public boolean isEmpty() { return stacks.isEmpty() || stacks.getFirst().isEmpty(); } SetOfStacks(); SetOfStacks(int capacity); E push(E element); E pop(); E peek(); boolean isEmpty(); int size(); int numElements(); }
@Test public void testIsEmpty() { assertTrue(stacks.isEmpty()); }
SetOfStacks { public E push(E element) { if (isFull()) { stacks.addFirst(new ArrayDeque<E>()); } stacks.getFirst().addFirst(element); return element; } SetOfStacks(); SetOfStacks(int capacity); E push(E element); E pop(); E peek(); boolean isEmpty(); int size(); int numElements(); }
@Test public void testPush() { stacks.push(1); stacks.push(2); assertEquals(2, stacks.size()); assertEquals(2, stacks.numElements()); }
SetOfStacks { public E pop() { final E element = stacks.getFirst().remove(); if (stacks.getFirst().isEmpty() && stacks.size() != 1) { stacks.remove(); } return element; } SetOfStacks(); SetOfStacks(int capacity); E push(E element); E pop(); E peek(); boolean isEmpty(); int size(); int numElements(); }
@Test public void testPop() { stacks.push(1); stacks.push(2); int e = stacks.pop(); assertEquals(2, e); assertEquals(1, stacks.size()); assertEquals(1, stacks.numElements()); }
SetOfStacks { public E peek() { return stacks.getFirst().getFirst(); } SetOfStacks(); SetOfStacks(int capacity); E push(E element); E pop(); E peek(); boolean isEmpty(); int size(); int numElements(); }
@Test public void testPeek() { stacks.push(1); stacks.push(2); int e = stacks.peek(); assertEquals(2, e); assertEquals(2, stacks.size()); assertEquals(2, stacks.numElements()); }
PracticeQuestionsCh2 { public static <E> void removeDupes(LinkedList<E> linkedList) { Set<E> dupes = new HashSet<E>(); LinkedListNode<E> current = linkedList.head().successor(); E data = null; for (int idx = 0; idx < linkedList.size(); idx++) { data = current.data(); current = current.successor(); if (dupes.contains(data)) { linkedList.remove(idx); } else { dupes.add(data); } } } static void removeDupes(LinkedList<E> linkedList); static void partition(LinkedList<E> linkedList, E pivot); static boolean isPalindrome(LinkedList<E> linkedList); static boolean isPalindromeVariant(LinkedList<E> linkedList); }
@Test public void testRemoveDupes() { LinkedList<Integer> linkedList = new LinkedList<Integer>(); linkedList.add(1); linkedList.add(2); linkedList.add(1); removeDupes(linkedList); assertEquals(2, linkedList.size()); assertEquals(Integer.valueOf(1), linkedList.remove()); assertEquals(Integer.valueOf(2), linkedList.remove()); assertEquals(0, linkedList.size()); }
PracticeQuestionsCh2 { public static <E extends Comparable<E>> void partition(LinkedList<E> linkedList, E pivot) { int lastIdx = linkedList.size() - 1; int pivotIdx = linkedList.indexOf(pivot); if (pivotIdx != linkedList.lastIndexOf(pivot)) { throw new IllegalArgumentException("Can't handle dupes in input list."); } swap(linkedList, pivotIdx, lastIdx); int storeIdx = 0; for (int runningIdx = 0; runningIdx < lastIdx; runningIdx++) { if (linkedList.get(runningIdx).compareTo(pivot) <= 0) { swap(linkedList, runningIdx, storeIdx); storeIdx++; } } swap(linkedList, storeIdx, lastIdx); } static void removeDupes(LinkedList<E> linkedList); static void partition(LinkedList<E> linkedList, E pivot); static boolean isPalindrome(LinkedList<E> linkedList); static boolean isPalindromeVariant(LinkedList<E> linkedList); }
@Test public void testPartition() { LinkedList<Integer> linkedList = new LinkedList<Integer>(); linkedList.add(2); linkedList.add(4); linkedList.add(5); linkedList.add(1); partition(linkedList, 4); assertEquals(4, linkedList.size()); assertEquals(Integer.valueOf(2), linkedList.get(0)); assertEquals(Integer.valueOf(1), linkedList.get(1)); assertEquals(Integer.valueOf(4), linkedList.get(2)); assertEquals(Integer.valueOf(5), linkedList.get(3)); }
PracticeQuestionsCh2 { public static <E> boolean isPalindrome(LinkedList<E> linkedList) { int lastIdx = linkedList.size() - 1; for (int runningIdx = 0; runningIdx < lastIdx; runningIdx++, lastIdx--) { if (!linkedList.get(runningIdx).equals(linkedList.get(lastIdx))) { return false; } } return true; } static void removeDupes(LinkedList<E> linkedList); static void partition(LinkedList<E> linkedList, E pivot); static boolean isPalindrome(LinkedList<E> linkedList); static boolean isPalindromeVariant(LinkedList<E> linkedList); }
@Test public void testIsPalindrome() { LinkedList<Character> linkedList = new LinkedList<Character>(); linkedList.add('c'); linkedList.add('i'); linkedList.add('v'); linkedList.add('i'); linkedList.add('c'); assertTrue(isPalindrome(linkedList)); linkedList = new LinkedList<Character>(); linkedList.add('a'); linkedList.add('n'); linkedList.add('n'); linkedList.add('a'); assertTrue(isPalindrome(linkedList)); linkedList = new LinkedList<Character>(); linkedList.add('a'); linkedList.add('n'); linkedList.add('m'); linkedList.add('a'); assertFalse(isPalindrome(linkedList)); }
PracticeQuestionsCh2 { public static <E> boolean isPalindromeVariant(LinkedList<E> linkedList) { LinkedListNode<E> slow = linkedList.head().successor(); LinkedListNode<E> fast = slow; Stack<E> stack = new Stack<E>(); while (fast != linkedList.tail() && fast.successor() != linkedList.tail()) { stack.push(slow.data()); slow = slow.successor(); fast = fast.successor().successor(); } if (fast == linkedList.tail() && !slow.data().equals(stack.pop())) { return false; } do { slow = slow.successor(); if (!slow.data().equals(stack.pop())) { return false; } } while (slow.successor() != linkedList.tail()); return true; } static void removeDupes(LinkedList<E> linkedList); static void partition(LinkedList<E> linkedList, E pivot); static boolean isPalindrome(LinkedList<E> linkedList); static boolean isPalindromeVariant(LinkedList<E> linkedList); }
@Test public void testIsPalindromeVariant() { LinkedList<Character> linkedList = new LinkedList<Character>(); linkedList.add('c'); linkedList.add('i'); linkedList.add('v'); linkedList.add('i'); linkedList.add('c'); assertTrue(isPalindromeVariant(linkedList)); linkedList = new LinkedList<Character>(); linkedList.add('a'); linkedList.add('n'); linkedList.add('n'); linkedList.add('a'); assertTrue(isPalindromeVariant(linkedList)); linkedList = new LinkedList<Character>(); linkedList.add('a'); linkedList.add('n'); linkedList.add('m'); linkedList.add('a'); assertFalse(isPalindromeVariant(linkedList)); }
BinaryTreeWalker { public static <E> List<E> recursiveInorder(BinaryTreeNode<E> root) { List<E> visited = new ArrayList<>(); if (root.leftChild() != null) { visited.addAll(recursiveInorder(root.leftChild())); } visited.add(root.data()); if (root.rightChild() != null) { visited.addAll(recursiveInorder(root.rightChild())); } return visited; } static List<E> iterativeInorder(BinaryTreeNode<E> root); static List<E> recursiveInorder(BinaryTreeNode<E> root); static final Logger LOGGER; }
@Test public void testRecursiveInorder() { assertInorder(recursiveInorder(root)); }
PracticeQuestionsCh1 { public static boolean isUnique(String s) { int[] arr = new int[3]; int len = s.length(); int ch = -1; final int numASCIICtrlChars = 32; for (int i = 0; i < len; i++) { ch = s.charAt(i) - numASCIICtrlChars; int bitmask = ch & 0x1f; int bitVectorIdx = ch >> 5; ch = arr[bitVectorIdx] & bitmask; if (ch == 1) { return false; } arr[bitVectorIdx] |= bitmask; } return true; } static boolean isUnique(String s); static boolean isPermutation(String s1, String s2); static String encodeRepeatedChars(final String str); static void fillIfZero(int[][] matrix); static boolean isRotation(String s1, String s2); static final Logger LOGGER; }
@Test public void testIsUnique() { assertTrue(isUnique("abc")); assertFalse(isUnique("aba")); }
PracticeQuestionsCh1 { public static boolean isPermutation(String s1, String s2) { int len = s1.length(); if (s2.length() != len) { return false; } char[] charArr1 = s1.toCharArray(); char[] charArr2 = s2.toCharArray(); short sum1 = 0; short sum2 = 0; for (short i = 0; i < len; i++) { sum1 += ((short) charArr1[i]); sum2 += ((short) charArr2[i]); } return sum1 == sum2; } static boolean isUnique(String s); static boolean isPermutation(String s1, String s2); static String encodeRepeatedChars(final String str); static void fillIfZero(int[][] matrix); static boolean isRotation(String s1, String s2); static final Logger LOGGER; }
@Test public void testIsPermutation() { assertTrue(isPermutation("abc", "cba")); assertTrue(isPermutation("aBc", "acB")); assertFalse(isPermutation("abc", "c")); assertFalse(isPermutation("abc", "def")); }
PracticeQuestionsCh1 { public static String encodeRepeatedChars(final String str) { final AtomicInteger repeatCount = new AtomicInteger(1); final StringBuilder previousChar = new StringBuilder(" "); final StringBuilder buffer = new StringBuilder(); final int len = str.length() - 1; IntStream.range(0, str.length()).forEach(idx -> { if (str.charAt(idx) == previousChar.charAt(0)) { repeatCount.incrementAndGet(); } else { if (idx != 0) { buffer.append(previousChar.charAt(0)).append(repeatCount.get()); } repeatCount.set(1); previousChar.setCharAt(0, str.charAt(idx)); } if (idx == len) { buffer.append(str.charAt(idx)).append(repeatCount.get()); } }); return buffer.length() < str.length() ? buffer.toString() : str; } static boolean isUnique(String s); static boolean isPermutation(String s1, String s2); static String encodeRepeatedChars(final String str); static void fillIfZero(int[][] matrix); static boolean isRotation(String s1, String s2); static final Logger LOGGER; }
@Test public void testEncodeRepeatedChars() { assertEquals("a3b2", encodeRepeatedChars("aaabb")); assertEquals("abc", encodeRepeatedChars("abc")); assertEquals("a3b3a1", encodeRepeatedChars("aaabbba")); assertEquals("a1b3c3", encodeRepeatedChars("abbbccc")); }
PracticeQuestionsCh1 { public static void fillIfZero(int[][] matrix) { int numRows = matrix.length; int numCols = matrix[0].length; int rowWhereZeroFound = -1; int colWhereZeroFound = -1; for (int rowNum = 0; rowNum < numRows; rowNum++) { boolean isZeroFound = false; for (int colNum = 0; colNum < numCols; colNum++) { isZeroFound = (matrix[rowNum][colNum] == 0) | isZeroFound; if (isZeroFound) { LOGGER.debug("Zero found at [{},{}].", rowNum, colNum); colWhereZeroFound = colNum; rowWhereZeroFound = rowNum; break; } } if (isZeroFound) { LOGGER.debug("Setting to zero [{},{}].", rowNum, colWhereZeroFound); matrix[rowNum][colWhereZeroFound] = 0; } } LOGGER.debug("Setting to zero [{}].", rowWhereZeroFound); Arrays.fill(matrix[rowWhereZeroFound], 0); for (int rowNum = 0; rowNum < rowWhereZeroFound; rowNum++) { LOGGER.debug("Setting to zero [{},{}].", rowNum, colWhereZeroFound); matrix[rowNum][colWhereZeroFound] = 0; } } static boolean isUnique(String s); static boolean isPermutation(String s1, String s2); static String encodeRepeatedChars(final String str); static void fillIfZero(int[][] matrix); static boolean isRotation(String s1, String s2); static final Logger LOGGER; }
@Test public void testFillIfZero() { int[][] matrix = new int[][] { { 1, 2 }, { 3, 4 }, { 5, 0 } }; fillIfZero(matrix); assertEquals(0, matrix[0][1]); assertEquals(0, matrix[1][1]); assertEquals(0, matrix[2][0]); assertEquals(0, matrix[2][1]); assertEquals(1, matrix[0][0]); assertEquals(3, matrix[1][0]); }
PracticeQuestionsCh1 { public static boolean isRotation(String s1, String s2) { int len = s1.length(); if (s2.length() != len) { return false; } char[] charArr1 = s1.toCharArray(); char[] charArr2 = s2.toCharArray(); int j = 0; for (int i = 0; i < len && j < len; i++) { if (charArr1[i] == charArr2[j]) { j++; } } return isSubstring(s1, String.valueOf(Arrays.copyOfRange(charArr2, j, len))); } static boolean isUnique(String s); static boolean isPermutation(String s1, String s2); static String encodeRepeatedChars(final String str); static void fillIfZero(int[][] matrix); static boolean isRotation(String s1, String s2); static final Logger LOGGER; }
@Test public void testIsRotation() { assertTrue(isRotation("erbottlewat", "waterbottle")); assertFalse(isRotation("erbottlewat", "waterbottel")); }
DeckOfCards extends AbstractList<Card> { public DeckOfCards() { Suit[] suits = Suit.values(); Rank[] ranks = Rank.values(); int numCard = 0; for (Suit aSuit : suits) { for (Rank aRank : ranks) { Card newCard = new Card(aSuit, aRank); cards[numCard++] = newCard; } } } DeckOfCards(); @Override Card get(int index); Card set(int index, Card card); @Override int size(); static final int NUM_CARDS; }
@Test public void testDeckOfCards() { Assert.assertEquals(deck.get(0).getSuit(), deck.get(12).getSuit()); Assert.assertEquals(deck.get(13).getSuit(), deck.get(25).getSuit()); Assert.assertEquals(deck.get(26).getSuit(), deck.get(38).getSuit()); Assert.assertEquals(deck.get(39).getSuit(), deck.get(51).getSuit()); Assert.assertEquals(deck.get(0).getRank(), deck.get(13).getRank()); Assert.assertEquals(deck.get(0).getRank(), deck.get(26).getRank()); Assert.assertEquals(deck.get(0).getRank(), deck.get(39).getRank()); }
JigsawPuzzle { public boolean solve() { Piece aPiece = null; Piece anotherPiece = null; Stack<Piece> stackOfPieces = stackOfPieces(); while (stackOfPieces.size() > 1) { aPiece = stackOfPieces.pop(); while (!stackOfPieces.isEmpty()) { anotherPiece = stackOfPieces.pop(); if (aPiece.fitsWith(anotherPiece)) { Piece bigPiece = aPiece.joinWith(anotherPiece); stackOfPieces.push(bigPiece); break; } } } return stackOfPieces.size() == 1; } JigsawPuzzle(Piece[] pieces); Piece[] piecesOfPuzzle(); boolean solve(); public Piece[] piecesOfPuzzle; }
@Test public void testSolve() { Piece[] pieces = new Piece[5]; Piece first = new Piece(0); Piece second = new Piece(1); Piece third = new Piece(1); Piece fourth = new Piece(2); Piece fifth = new Piece(3); pieces[0] = first; pieces[1] = second; pieces[2] = third; pieces[3] = fourth; pieces[4] = fifth; JigsawPuzzle puzzle = new JigsawPuzzle(pieces); Assert.assertTrue(puzzle.solve()); } @Test public void testCannotSolve() { Piece[] pieces = new Piece[5]; Piece first = new Piece(0); Piece second = new Piece(1); Piece third = new Piece(1); Piece fourth = new Piece(2); Piece fifth = new Piece(6); pieces[0] = first; pieces[1] = second; pieces[2] = third; pieces[3] = fourth; pieces[4] = fifth; JigsawPuzzle puzzle = new JigsawPuzzle(pieces); Assert.assertFalse(puzzle.solve()); }
PracticeQuestionsCh9 { public static int magicIndex(int[] array, int startIndex, int endIndex) { if (startIndex >= endIndex) { return -1; } long avg = startIndex + endIndex >> 1; if (avg >= Integer.MAX_VALUE) { return -1; } int midIdx = (int) avg; int val = array[midIdx]; if (val == midIdx) { LOGGER.debug("Found magic index{}.%n", midIdx); return midIdx; } LOGGER.debug("Start index = {}, end index = {}, middle index = {}.%n", startIndex, endIndex, midIdx); LOGGER.debug("val = {}.%n", val); if (midIdx < val) { return magicIndex(array, startIndex, --midIdx); } return magicIndex(array, ++midIdx, endIndex); } static int magicIndex(int[] array, int startIndex, int endIndex); static Set<String> perm(String s); static final Logger LOGGER; }
@Test public void testMagicIndex() { int[] array = new int[] { -1, 0, 2 }; assertEquals(2, magicIndex(array, 0, array.length)); array = new int[] { 1, 2, 3 }; assertEquals(-1, PracticeQuestionsCh9.magicIndex(array, 0, array.length)); }
PracticeQuestionsCh9 { public static Set<String> perm(String s) { Set<String> perms = new HashSet<String>(); recursivePerm(s, s.length() - 1, perms); return perms; } static int magicIndex(int[] array, int startIndex, int endIndex); static Set<String> perm(String s); static final Logger LOGGER; }
@Test public void testPerm() { String s = "abc"; String[] expected = new String[] { "cab", "abc", "bac", "acb" }; Set<String> allPerms = perm(s); assertEquals(expected.length, allPerms.size()); stream(expected).forEach(aPerm -> assertTrue(allPerms.contains(aPerm))); }
LinkedList { public boolean add(E e) { return add(size, e); } LinkedList(); LinkedList(Collection<E> elements); boolean add(E e); boolean add(int index, E e); boolean addAll(Collection<E> elements); E remove(); E remove(int index); E peek(); int size(); boolean isEmpty(); void reverse(); LinkedListNode<E> head(); LinkedListNode<E> tail(); E get(int index); void set(int index, E element); int indexOf(E element); int lastIndexOf(E element); @Override String toString(); }
@Test public void testAdd() { Assert.assertEquals(3, linkedList.size()); Assert.assertTrue(linkedList.add(4)); Assert.assertEquals(4, linkedList.size()); Assert.assertTrue(linkedList.add(linkedList.size(), 0)); Assert.assertEquals(5, linkedList.size()); Assert.assertEquals(Integer.valueOf(4), linkedList.remove(3)); Assert.assertEquals(Integer.valueOf(1), linkedList.remove()); } @Test(expected = IndexOutOfBoundsException.class) public void testInvalidIndexOperation() { linkedList.add(10, 1); }