method2testcases
stringlengths
118
3.08k
### Question: ClojureScriptEngineService implements ScriptEngineService { @Override public ScriptEngine createScriptEngine(ScriptLocation script) throws EngineException { if (m_cljFileMatcher.accept(script.getFile())) { try { return new ClojureScriptEngine(script); } catch (LinkageError e) { throw new EngineException("Clojure is not on the classpath", e); } } return null; } @Override ScriptEngine createScriptEngine(ScriptLocation script); @Override List<? extends Instrumenter> createInstrumenters(); }### Answer: @Test public void testCreateScriptEngineWrongType() throws Exception { final ScriptLocation someScript = new ScriptLocation(new File("some.thing")); final ScriptEngine result = new ClojureScriptEngineService().createScriptEngine(someScript); assertNull(result); } @Test public void testCreateScriptEngine() throws Exception { final ScriptLocation script = new ScriptLocation(new Directory(getDirectory()), new File("my.clj")); createFile(script.getFile(), "(fn [] (fn [] ()))"); final ScriptEngine result = new ClojureScriptEngineService().createScriptEngine(script); assertContains(result.getDescription(), "Clojure"); } @Test public void testCreateScriptEngineNoClojure() throws Exception { final ScriptLocation script = new ScriptLocation(new Directory(getDirectory()), new File("my.clj")); final ClassLoader blockingLoader = new BlockingClassLoader(singleton("clojure.*"), singleton("net.grinder.scriptengine.clojure.*"), Collections.<String>emptySet(), false); final ScriptEngineService service = (ScriptEngineService) blockingLoader.loadClass( ClojureScriptEngineService.class.getName()).newInstance(); try { service.createScriptEngine(script); fail("Expected EngineException"); } catch (EngineException e) { assertContains(e.getMessage(), "classpath"); } }
### Question: FileStore { public Directory getDirectory() throws FileStoreException { try { synchronized (m_incomingDirectory) { if (m_incomingDirectory.getFile().exists()) { m_incomingDirectory.copyTo(m_currentDirectory, m_incremental); } m_incremental = true; } return m_currentDirectory; } catch (IOException e) { UncheckedInterruptedException.ioException(e); throw new FileStoreException("Could not create file store directory", e); } } FileStore(File directory, Logger logger); Directory getDirectory(); CacheHighWaterMark getCacheHighWaterMark(); void registerMessageHandlers( MessageDispatchRegistry messageDispatcher); }### Answer: @Test public void testConstruction() throws Exception { File.createTempFile("file", "", getDirectory()); assertEquals(1, getDirectory().list().length); final FileStore fileStore = new FileStore(getDirectory(), null); final File currentDirectory = fileStore.getDirectory().getFile(); assertNotNull(currentDirectory); assertTrue( currentDirectory.getPath().startsWith(getDirectory().getPath())); assertEquals(1, getDirectory().list().length); assertTrue(!currentDirectory.exists()); final File file1 = File.createTempFile("file", "", getDirectory()); try { new FileStore(file1, null); fail("Expected FileStoreException"); } catch (FileStore.FileStoreException e) { } assertTrue(file1.delete()); assertTrue(file1.mkdir()); assertTrue(new File(file1, "current").createNewFile()); try { new FileStore(file1, null); fail("Expected FileStoreException"); } catch (FileStore.FileStoreException e) { } final File readOnlyDirectory = new File(getDirectory(), "directory"); assertTrue(readOnlyDirectory.mkdir()); readOnlyDirectory.setWritable(false); try { new FileStore(readOnlyDirectory, null); if (!System.getProperty("os.name").startsWith("Win")) { fail("Expected FileStoreException"); } } catch (FileStore.FileStoreException e) { } final File notThere = new File(getDirectory(), "notThere"); new FileStore(notThere, null); }
### Question: WorkerProcessCommandLine implements CommandLine { static boolean isAgentJar(final String name) { final Matcher matcher = AGENT_JAR_FILENAME_PATTERN.matcher(name); if (matcher.matches()) { final String maybeSnapshot = matcher.group(2); return maybeSnapshot == null || "-SNAPSHOT".equals(maybeSnapshot); } return false; } WorkerProcessCommandLine(final GrinderProperties properties, final Properties systemProperties, final String jvmArguments, final Directory workingDirectory); @Override Directory getWorkingDirectory(); @Override List<String> getCommandList(); @Override String toString(); }### Answer: @Test public void testIsAgentJarValidNames() { for (final String s : asList("grinder-dcr-agent-1.jar", "grinder-dcr-agent-"+ GrinderBuild.getVersionString() + ".jar")) { assertTrue(s, WorkerProcessCommandLine.isAgentJar(s)); } } @Test public void testIsAgentJarInvalidNames() { for (final String s : asList("grinder-dcr-agent.jar", "grinder-dcr-agent-"+ GrinderBuild.getVersionString() + ".jar.asc", "grinder-dcr-agent-" + GrinderBuild.getVersionString() + "-sources.jar", "xgrinder-dcr-agent-" + GrinderBuild.getVersionString() + ".jar")) { assertFalse(s, WorkerProcessCommandLine.isAgentJar(s)); } }
### Question: WorkerProcessCommandLine implements CommandLine { static File findAgentJarFile(final List<File> systemClasspath) { for (final File pathEntry : systemClasspath) { final File f = pathEntry.getParentFile(); final File parentFile = f != null ? f : new File("."); final File[] children = parentFile.listFiles(); if (children != null) { for (final File candidate : children) { if (isAgentJar(candidate.getName())) { return candidate; } } } } return null; } WorkerProcessCommandLine(final GrinderProperties properties, final Properties systemProperties, final String jvmArguments, final Directory workingDirectory); @Override Directory getWorkingDirectory(); @Override List<String> getCommandList(); @Override String toString(); }### Answer: @Test public void testFindAgentJarFile() throws Exception { assertNull(WorkerProcessCommandLine.findAgentJarFile(path("foo.jar"))); assertNull(WorkerProcessCommandLine.findAgentJarFile(path("/foo.jar"))); assertNull( WorkerProcessCommandLine.findAgentJarFile(path("/notthere/foo.jar"))); assertNull( WorkerProcessCommandLine.findAgentJarFile( path("somewhere ", "somewhereelse"))); final File directories = new File(getDirectory(), "a/b"); directories.mkdirs(); assertNull( WorkerProcessCommandLine.findAgentJarFile(path(directories.getPath() + "/c.jar"))); final File f = new File(directories, "grinder-dcr-agent-1.20.jar"); f.createNewFile(); assertNotNull( WorkerProcessCommandLine.findAgentJarFile(path(f.getAbsolutePath()))); assertNull( WorkerProcessCommandLine.findAgentJarFile( asList(new File(getDirectory().getAbsoluteFile(), "c.jar")))); }
### Question: AgentImplementation implements Agent { @Override public void shutdown() { m_timer.cancel(); m_fanOutStreamSender.shutdown(); m_consoleListener.shutdown(); m_logger.info("finished"); } AgentImplementation(Logger logger, File alternateFile, boolean proceedWithoutConsole); @Override void run(); @Override void shutdown(); }### Answer: @Test public void testConstruction() throws Exception { final File propertyFile = new File(getDirectory(), "properties"); final Agent agent = new AgentImplementation(m_logger, propertyFile, true); agent.shutdown(); verify(m_logger).info("finished"); verifyNoMoreInteractions(m_logger); }
### Question: DebugThreadWorker implements Worker { public DebugThreadWorker(WorkerIdentity workerIdentity, final IsolateGrinderProcessRunner runner) { m_workerIdentity = workerIdentity; m_communicationStream = new PipedOutputStream(); final InputStream inputStream; try { inputStream = new PipedInputStream(m_communicationStream); } catch (IOException e) { throw new AssertionError(e); } m_thread = new Thread(workerIdentity.getName()) { public void run() { m_result = runner.run(inputStream); } }; m_thread.setDaemon(true); } DebugThreadWorker(WorkerIdentity workerIdentity, final IsolateGrinderProcessRunner runner); void start(); WorkerIdentity getIdentity(); OutputStream getCommunicationStream(); int waitFor(); void destroy(); }### Answer: @Test public void testDebugThreadWorker() throws Exception { final DelegatingStubFactory<IsolatedGrinderProcessRunner> isolateGrinderProcessRunnerStubFactory = DelegatingStubFactory.create(new IsolatedGrinderProcessRunner()); final DebugThreadWorker worker = new DebugThreadWorker(m_workerIdentity, isolateGrinderProcessRunnerStubFactory.getStub()); assertEquals(m_workerIdentity, worker.getIdentity()); assertNotNull(worker.getCommunicationStream()); worker.start(); final int[] resultHolder = { -1 }; final Thread waitThread = new Thread() { public void run() { resultHolder[0] = worker.waitFor(); } }; waitThread.start(); assertEquals(-1, resultHolder[0]); assertTrue(waitThread.isAlive()); final RedirectStandardStreams streams = new RedirectStandardStreams() { protected void runWithRedirectedStreams() throws Exception { new StreamSender(worker.getCommunicationStream()).shutdown(); waitThread.join(); } }; streams.run(); isolateGrinderProcessRunnerStubFactory.assertSuccess( "run", InputStream.class); assertEquals(-2, resultHolder[0]); final String output = new String(streams.getStderrBytes()); assertTrue(output.indexOf("No control stream from agent") > 0); worker.destroy(); }
### Question: AgentDaemon implements Agent { public void shutdown() { m_sleeper.shutdown(); m_delegateAgent.shutdown(); } AgentDaemon(Logger logger, long sleepTime, Agent agent); AgentDaemon(Logger logger, long sleepTime, Agent agent, Sleeper sleeper); void run(); void shutdown(); }### Answer: @Test public void testConstruction() throws Exception { final File propertyFile = new File(getDirectory(), "properties"); final Agent agent = new AgentImplementation(m_logger, propertyFile, false); final AgentDaemon daemon = new AgentDaemon(m_logger, 1000, agent); daemon.shutdown(); verify(m_logger).info(contains("finished")); verifyNoMoreInteractions(m_logger); }
### Question: EchoFilter implements TCPProxyFilter { @Override public void connectionOpened(ConnectionDetails connectionDetails) { m_out.println("--- " + connectionDetails + " opened --"); } EchoFilter(PrintWriter output); @Override byte[] handle(ConnectionDetails connectionDetails, byte[] buffer, int bytesRead); @Override void connectionOpened(ConnectionDetails connectionDetails); @Override void connectionClosed(ConnectionDetails connectionDetails); }### Answer: @Test public void testConnectionOpened() throws Exception { final EchoFilter echoFilter = new EchoFilter(m_out); echoFilter.connectionOpened(m_connectionDetails); final String output = m_outString.toString(); assertContains(output, m_connectionDetails.toString()); assertContains(output, "opened"); }
### Question: AgentDaemon implements Agent { public void run() throws GrinderException { Runtime.getRuntime().addShutdownHook(m_shutdownHook); try { while (true) { m_delegateAgent.run(); m_logger.info("agent finished"); m_sleeper.sleepNormal(m_sleepTime); } } catch (ShutdownException e) { } } AgentDaemon(Logger logger, long sleepTime, Agent agent); AgentDaemon(Logger logger, long sleepTime, Agent agent, Sleeper sleeper); void run(); void shutdown(); }### Answer: @Test public void testRun() throws Exception { final ActionListSleeperStubFactory sleeperStubFactory = new ActionListSleeperStubFactory( new SleepAction[] { new SleepAction() { public void sleep(long time) throws ShutdownException { assertEquals(1000, time); } }, new SleepAction() { public void sleep(long time) throws ShutdownException { assertEquals(1000, time); throw new ShutdownException(""); } } } ); final AgentDaemon agentDaemon = new AgentDaemon(m_logger, 1000, m_agent, sleeperStubFactory.getStub()); agentDaemon.run(); sleeperStubFactory.assertFinished(); }
### Question: WorkerLauncher { public void startAllWorkers() throws EngineException { startSomeWorkers(m_workers.length - m_nextWorkerIndex); } WorkerLauncher(int numberOfWorkers, WorkerFactory workerFactory, Condition notifyOnFinish, Logger logger); WorkerLauncher(ExecutorService executor, int numberOfWorkers, WorkerFactory workerFactory, Condition notifyOnFinish, Logger logger); void startAllWorkers(); boolean startSomeWorkers(int numberOfWorkers); boolean allFinished(); void shutdown(); void dontStartAnyMore(); void destroyAllWorkers(); }### Answer: @Test public void testInteruptedWaitFor() throws Exception { final WorkerIdentity workerIdentity = new AgentIdentityImplementation("test").createWorkerIdentity(); final WorkerFactory workerFactory = mock(WorkerFactory.class); final Worker worker = mock(Worker.class); when(worker.getIdentity()).thenReturn(workerIdentity); when(workerFactory.create(isA(OutputStream.class), isA(OutputStream.class))).thenReturn(worker); final WorkerLauncher workerLauncher = new WorkerLauncher(1, workerFactory, m_condition, m_logger); doThrow(new UncheckedInterruptedException(new InterruptedException())) .when(worker).waitFor(); workerLauncher.startAllWorkers(); verify(worker).getIdentity(); verify(worker, timeout(1000)).waitFor(); verify(worker, timeout(1000)).destroy(); verifyNoMoreInteractions(worker); }
### Question: ProcessWorker implements Worker { public void destroy() { try { Thread.sleep(100); } catch (InterruptedException e) { throw new UncheckedInterruptedException(e); } m_process.destroy(); } ProcessWorker(WorkerIdentity workerIdentity, CommandLine commandLine, OutputStream outputStream, OutputStream errorStream); WorkerIdentity getIdentity(); OutputStream getCommunicationStream(); int waitFor(); void destroy(); }### Answer: @Test public void testDestroy() throws Exception { final CommandLine commandLine = new MyCommandLine("java", "-classpath", s_testClasspath, EchoClass.class.getName()); final ProcessWorker childProcess = new ProcessWorker(m_agentIdentity.createWorkerIdentity(), commandLine, m_outputStream, m_errorStream); childProcess.destroy(); childProcess.waitFor(); }
### Question: ThreadContextImplementation implements ThreadContext { @Override public Marker getLogMarker() { return m_threadMarker; } ThreadContextImplementation(GrinderProperties properties, StatisticsServices statisticsServices, int threadNumber, Logger dataLogger); int getThreadNumber(); int getRunNumber(); @Override void setCurrentRunNumber(int run); SSLContextFactory getThreadSSLContextFactory(); void setThreadSSLContextFactory(SSLContextFactory sslContextFactory); DispatchResultReporter getDispatchResultReporter(); void registerThreadLifeCycleListener( ThreadLifeCycleListener listener); void removeThreadLifeCycleListener(ThreadLifeCycleListener listener); void fireBeginThreadEvent(); void fireBeginRunEvent(); void fireEndRunEvent(); void fireBeginShutdownEvent(); void fireEndThreadEvent(); void pushDispatchContext(DispatchContext dispatchContext); void popDispatchContext(); StatisticsForTest getStatisticsForCurrentTest(); StatisticsForTest getStatisticsForLastTest(); void setDelayReports(boolean b); void reportPendingDispatchContext(); void pauseClock(); void resumeClock(); void shutdown(); @Override Marker getLogMarker(); }### Answer: @Test public void testGetLogMarker() throws Exception { final ThreadContext threadContext = new ThreadContextImplementation(m_properties, m_statisticsServices, 2, null); final Marker marker = threadContext.getLogMarker(); assertEquals("thread-2", marker.getName()); assertFalse(marker.hasReferences()); }
### Question: ScriptEngineContainer { public Instrumenter createInstrumenter() throws EngineException { final List<Instrumenter> instrumenters = new ArrayList<Instrumenter>(); for (ScriptEngineService service : m_container.getComponents(ScriptEngineService.class)) { for (Instrumenter instrumenter : service.createInstrumenters()) { instrumenters.add(instrumenter); } } return new MasterInstrumenter(instrumenters); } ScriptEngineContainer(GrinderProperties properties, Logger logger, DCRContext dcrContext, ScriptLocation scriptLocation); ScriptEngine getScriptEngine(ScriptLocation script); Instrumenter createInstrumenter(); }### Answer: @Test public void testStandardInstrumentationNoDCR() throws Exception { final ScriptEngineContainer container = new ScriptEngineContainer(m_properties, m_logger, null, m_pyScript); final Instrumenter instrumenter = container.createInstrumenter(); assertEquals("NO INSTRUMENTER COULD BE LOADED", instrumenter.getDescription()); } @Test public void testStandardInstrumentationDCR() throws Exception { final ScriptEngineContainer container = new ScriptEngineContainer(m_properties, m_logger, m_dcrContext, m_pyScript); final Instrumenter instrumenter = container.createInstrumenter(); assertEquals("byte code transforming instrumenter for Jython 2.5; " + "byte code transforming instrumenter for Java", instrumenter.getDescription()); }
### Question: ScriptEngineContainer { public ScriptEngine getScriptEngine(ScriptLocation script) throws EngineException { for (ScriptEngineService service : m_container.getComponents(ScriptEngineService.class)) { final ScriptEngine engine = service.createScriptEngine(script); if (engine != null) { return engine; } } throw new EngineException("No suitable script engine installed for '" + script + "'"); } ScriptEngineContainer(GrinderProperties properties, Logger logger, DCRContext dcrContext, ScriptLocation scriptLocation); ScriptEngine getScriptEngine(ScriptLocation script); Instrumenter createInstrumenter(); }### Answer: @Test public void testUnknownScriptType() throws Exception { final ScriptEngineContainer container = new ScriptEngineContainer(m_properties, m_logger, m_dcrContext, m_pyScript); try { container.getScriptEngine(new ScriptLocation(new File("foo.xxx"))); fail("Expected EngineException"); } catch (EngineException e) { assertContains(e.getMessage(), "No suitable script engine"); } } @Test public void testJythonScript() throws Exception { final ScriptLocation pyScript = new ScriptLocation(new Directory(getDirectory()), new File("my.py")); createFile(pyScript.getFile(), "class TestRunner: pass"); final ScriptEngineContainer container = new ScriptEngineContainer(m_properties, m_logger, m_dcrContext, m_pyScript); final ScriptEngine scriptEngine = container.getScriptEngine(pyScript); assertContains(scriptEngine.getDescription(), "Jython"); }
### Question: ScriptContextImplementation implements InternalScriptContext { public void sleep(long meanTime) throws GrinderException { m_sleeper.sleepNormal(meanTime); } ScriptContextImplementation( WorkerIdentity workerIdentity, WorkerIdentity firstWorkerIdentity, ThreadContextLocator threadContextLocator, GrinderProperties properties, Logger logger, Sleeper sleeper, SSLControl sslControl, Statistics scriptStatistics, TestRegistry testRegistry, ThreadStarter threadStarter, ThreadStopper threadStopper, BarrierGroups barrierGroups, BarrierIdentity.Factory barrierIdentityFactory); int getAgentNumber(); String getProcessName(); int getProcessNumber(); int getFirstProcessNumber(); int getThreadNumber(); int getRunNumber(); Logger getLogger(); void sleep(long meanTime); void sleep(long meanTime, long sigma); int startWorkerThread(); int startWorkerThread(Object testRunner); void stopThisWorkerThread(); boolean stopWorkerThread(int threadNumber); GrinderProperties getProperties(); Statistics getStatistics(); SSLControl getSSLControl(); TestRegistry getTestRegistry(); Barrier barrier(String name); }### Answer: @Test public void testSleep() throws Exception { final Sleeper sleeper = new SleeperImplementation(new StandardTimeAuthority(), m_logger, 1, 0); final ScriptContextImplementation scriptContext = new ScriptContextImplementation( null, null, null, null, null, sleeper, null, null, null, null, null, null, null); assertTrue( new Time(50, 70) { public void doIt() throws Exception { scriptContext.sleep(50); } }.run()); assertTrue( new Time(40, 70) { public void doIt() throws Exception { scriptContext.sleep(50, 5); } }.run()); }
### Question: ScriptContextImplementation implements InternalScriptContext { public void stopThisWorkerThread() throws InvalidContextException { if (m_threadContextLocator.get() != null) { throw new ShutdownException("Thread has been shut down"); } else { throw new InvalidContextException( "stopThisWorkerThread() must be called from a worker thread"); } } ScriptContextImplementation( WorkerIdentity workerIdentity, WorkerIdentity firstWorkerIdentity, ThreadContextLocator threadContextLocator, GrinderProperties properties, Logger logger, Sleeper sleeper, SSLControl sslControl, Statistics scriptStatistics, TestRegistry testRegistry, ThreadStarter threadStarter, ThreadStopper threadStopper, BarrierGroups barrierGroups, BarrierIdentity.Factory barrierIdentityFactory); int getAgentNumber(); String getProcessName(); int getProcessNumber(); int getFirstProcessNumber(); int getThreadNumber(); int getRunNumber(); Logger getLogger(); void sleep(long meanTime); void sleep(long meanTime, long sigma); int startWorkerThread(); int startWorkerThread(Object testRunner); void stopThisWorkerThread(); boolean stopWorkerThread(int threadNumber); GrinderProperties getProperties(); Statistics getStatistics(); SSLControl getSSLControl(); TestRegistry getTestRegistry(); Barrier barrier(String name); }### Answer: @Test public void testStopThisWorkerThread() throws Exception { final StubThreadContextLocator threadContextLocator = new StubThreadContextLocator(); final ScriptContextImplementation scriptContext = new ScriptContextImplementation( null, null, threadContextLocator, null, null, null, null, null, null, null, null, null, null); try { scriptContext.stopThisWorkerThread(); fail("Expected InvalidContextException"); } catch (InvalidContextException e) { } threadContextLocator.set(m_threadContext); try { scriptContext.stopThisWorkerThread(); fail("Expected ShutdownException"); } catch (ShutdownException e) { } }
### Question: ScriptContextImplementation implements InternalScriptContext { public Barrier barrier(String name) throws CommunicationException { return new BarrierImplementation(m_barrierGroups.getGroup(name), m_barrierIdentityFactory); } ScriptContextImplementation( WorkerIdentity workerIdentity, WorkerIdentity firstWorkerIdentity, ThreadContextLocator threadContextLocator, GrinderProperties properties, Logger logger, Sleeper sleeper, SSLControl sslControl, Statistics scriptStatistics, TestRegistry testRegistry, ThreadStarter threadStarter, ThreadStopper threadStopper, BarrierGroups barrierGroups, BarrierIdentity.Factory barrierIdentityFactory); int getAgentNumber(); String getProcessName(); int getProcessNumber(); int getFirstProcessNumber(); int getThreadNumber(); int getRunNumber(); Logger getLogger(); void sleep(long meanTime); void sleep(long meanTime, long sigma); int startWorkerThread(); int startWorkerThread(Object testRunner); void stopThisWorkerThread(); boolean stopWorkerThread(int threadNumber); GrinderProperties getProperties(); Statistics getStatistics(); SSLControl getSSLControl(); TestRegistry getTestRegistry(); Barrier barrier(String name); }### Answer: @Test public void testBarrier() throws Exception { final ScriptContextImplementation scriptContext = new ScriptContextImplementation( null, null, null, null, null, null, null, null, null, null, null, m_barrierGroups, m_identityGenerator); final Barrier globalBarrier = scriptContext.barrier("MyBarrierGroup"); assertEquals("MyBarrierGroup", globalBarrier.getName()); verify(m_identityGenerator).next(); }
### Question: MasterInstrumenter extends CompositeInstrumenter { @Override public String getDescription() { final String result = super.getDescription(); if (result.length() == 0) { return "NO INSTRUMENTER COULD BE LOADED"; } return result.toString(); } MasterInstrumenter(List<Instrumenter> instrumenters); @Override Object createInstrumentedProxy(Test test, Recorder recorder, Object target); @Override boolean instrument(Test test, Recorder recorder, Object target, InstrumentationFilter filter); @Override String getDescription(); }### Answer: @Test public void testGetDescription() throws Exception { when(m_instrumenter1.getDescription()).thenReturn("I1"); when(m_instrumenter2.getDescription()).thenReturn("I2"); final Instrumenter instrumenter = new MasterInstrumenter(asList(m_instrumenter1, m_instrumenter2)); assertEquals("I1; I2", instrumenter.getDescription()); final Instrumenter instrumenter2 = new MasterInstrumenter(asList(m_instrumenter1)); assertEquals("I1", instrumenter2.getDescription()); final List<Instrumenter> e = emptyList(); assertEquals("NO INSTRUMENTER COULD BE LOADED", new MasterInstrumenter(e).getDescription()); }
### Question: ExternalLogger extends MarkerIgnoringBase { @Override public boolean isTraceEnabled() { return m_delegate.isTraceEnabled(getMarker()); } ExternalLogger(Logger processLogger, ThreadContextLocator threadContextLocator); @Override String getName(); @Override boolean isTraceEnabled(); @Override void trace(String msg); @Override void trace(String format, Object arg); @Override void trace(String format, Object arg1, Object arg2); @Override void trace(String format, Object[] argArray); @Override void trace(String msg, Throwable t); @Override boolean isDebugEnabled(); @Override void debug(String msg); @Override void debug(String format, Object arg); @Override void debug(String format, Object arg1, Object arg2); @Override void debug(String format, Object[] argArray); @Override void debug(String msg, Throwable t); @Override boolean isInfoEnabled(); @Override void info(String msg); @Override void info(String format, Object arg); @Override void info(String format, Object arg1, Object arg2); @Override void info(String format, Object[] argArray); @Override void info(String msg, Throwable t); @Override boolean isWarnEnabled(); @Override void warn(String msg); @Override void warn(String format, Object arg); @Override void warn(String format, Object arg1, Object arg2); @Override void warn(String format, Object[] argArray); @Override void warn(String msg, Throwable t); @Override boolean isErrorEnabled(); @Override void error(String msg); @Override void error(String format, Object arg); @Override void error(String format, Object arg1, Object arg2); @Override void error(String format, Object[] argArray); @Override void error(String msg, Throwable t); }### Answer: @Test public void testGetMarkerNullContext() { final Logger logger = new ExternalLogger(m_delegate, m_threadContextLocator); logger.isTraceEnabled(); verify(m_delegate).isTraceEnabled(null); }
### Question: ConsoleListener { public void registerMessageHandlers( MessageDispatchRegistry messageDispatcher) { messageDispatcher.set( StartGrinderMessage.class, new AbstractMessageHandler<StartGrinderMessage>() { public void handle(StartGrinderMessage message) { m_logger.info("received a start message"); m_lastStartGrinderMessage = message; setReceived(START); } }); messageDispatcher.set( StopGrinderMessage.class, new AbstractMessageHandler<StopGrinderMessage>() { public void handle(StopGrinderMessage message) { m_logger.info("received a stop message"); setReceived(STOP); } }); messageDispatcher.set( ResetGrinderMessage.class, new AbstractMessageHandler<ResetGrinderMessage>() { public void handle(ResetGrinderMessage message) { m_logger.info("received a reset message"); setReceived(RESET); } }); } ConsoleListener(Condition notifyOnMessage, Logger logger); void shutdown(); void waitForMessage(); boolean checkForMessage(int mask); void discardMessages(int mask); synchronized boolean received(int mask); void registerMessageHandlers( MessageDispatchRegistry messageDispatcher); StartGrinderMessage getLastStartGrinderMessage(); static final int START; static final int RESET; static final int STOP; static final int SHUTDOWN; static final int ANY; }### Answer: @Test public void testSendNotification() throws Exception { final Condition myCondition = new Condition(); final ConsoleListener listener = new ConsoleListener(myCondition, m_logger); final MessageDispatchSender messageDispatcher = new MessageDispatchSender(); listener.registerMessageHandlers(messageDispatcher); final WaitForNotification notified = new WaitForNotification(myCondition); messageDispatcher.send(new StopGrinderMessage()); assertTrue(notified.wasNotified()); }
### Question: ConsoleListener { public void waitForMessage() { while (!checkForMessage(ConsoleListener.ANY)) { synchronized (m_notifyOnMessage) { m_notifyOnMessage.waitNoInterrruptException(); } } } ConsoleListener(Condition notifyOnMessage, Logger logger); void shutdown(); void waitForMessage(); boolean checkForMessage(int mask); void discardMessages(int mask); synchronized boolean received(int mask); void registerMessageHandlers( MessageDispatchRegistry messageDispatcher); StartGrinderMessage getLastStartGrinderMessage(); static final int START; static final int RESET; static final int STOP; static final int SHUTDOWN; static final int ANY; }### Answer: @Test public void testWaitForMessage() throws Exception { final Condition myCondition = new Condition(); final ConsoleListener listener = new ConsoleListener(myCondition, m_logger); final MessageDispatchSender messageDispatcher = new MessageDispatchSender(); listener.registerMessageHandlers(messageDispatcher); final Thread t = new Thread() { public void run() { synchronized (myCondition) { try { messageDispatcher.send( new StartGrinderMessage(new GrinderProperties(), -1)); } catch (CommunicationException e) { e.printStackTrace(); } } } }; synchronized (myCondition) { t.start(); listener.waitForMessage(); } assertTrue(listener.received(ConsoleListener.START)); }
### Question: ConsoleListener { public void shutdown() { setReceived(SHUTDOWN); } ConsoleListener(Condition notifyOnMessage, Logger logger); void shutdown(); void waitForMessage(); boolean checkForMessage(int mask); void discardMessages(int mask); synchronized boolean received(int mask); void registerMessageHandlers( MessageDispatchRegistry messageDispatcher); StartGrinderMessage getLastStartGrinderMessage(); static final int START; static final int RESET; static final int STOP; static final int SHUTDOWN; static final int ANY; }### Answer: @Test public void testShutdown() throws Exception { final Condition myCondition = new Condition(); final ConsoleListener listener = new ConsoleListener(myCondition, m_logger); final WaitForNotification notified = new WaitForNotification(myCondition); listener.shutdown(); assertTrue(notified.wasNotified()); verifyNoMoreInteractions(m_logger); assertFalse(listener.checkForMessage(ConsoleListener.ANY ^ ConsoleListener.SHUTDOWN)); assertTrue(listener.checkForMessage(ConsoleListener.SHUTDOWN)); assertTrue(listener.received(ConsoleListener.SHUTDOWN)); assertFalse(listener.checkForMessage(ConsoleListener.SHUTDOWN)); assertFalse(listener.received(ConsoleListener.SHUTDOWN)); }
### Question: ConsoleListener { public StartGrinderMessage getLastStartGrinderMessage() { return m_lastStartGrinderMessage; } ConsoleListener(Condition notifyOnMessage, Logger logger); void shutdown(); void waitForMessage(); boolean checkForMessage(int mask); void discardMessages(int mask); synchronized boolean received(int mask); void registerMessageHandlers( MessageDispatchRegistry messageDispatcher); StartGrinderMessage getLastStartGrinderMessage(); static final int START; static final int RESET; static final int STOP; static final int SHUTDOWN; static final int ANY; }### Answer: @Test public void testGetLastStartGrinderMessage() throws Exception { final ConsoleListener listener = new ConsoleListener(new Condition(), m_logger); final Message m1 = new StartGrinderMessage(new GrinderProperties(), -1); final Message m2 = new StartGrinderMessage(new GrinderProperties(), -1); final Message m3 = new MyMessage(); final MessageDispatchSender messageDispatcher = new MessageDispatchSender(); listener.registerMessageHandlers(messageDispatcher); assertNull(listener.getLastStartGrinderMessage()); messageDispatcher.send(m1); assertEquals(m1, listener.getLastStartGrinderMessage()); messageDispatcher.send(m3); assertEquals(m1, listener.getLastStartGrinderMessage()); messageDispatcher.send(m2); assertEquals(m2, listener.getLastStartGrinderMessage()); }
### Question: GrinderProperties extends Properties { public final boolean getBoolean(String propertyName, boolean defaultValue) { final String s = getProperty(propertyName); if (s != null) { return Boolean.valueOf(s).booleanValue(); } return defaultValue; } GrinderProperties(); GrinderProperties(File file); final File getAssociatedFile(); final void setAssociatedFile(File file); final void save(); final void saveSingleProperty(String name); final void setErrorWriter(PrintWriter writer); final synchronized GrinderProperties getPropertySubset(String prefix); final int getInt(String propertyName, int defaultValue); final void setInt(String propertyName, int value); final long getLong(String propertyName, long defaultValue); final void setLong(String propertyName, long value); final short getShort(String propertyName, short defaultValue); final void setShort(String propertyName, short value); final double getDouble(String propertyName, double defaultValue); final void setDouble(String propertyName, double value); final boolean getBoolean(String propertyName, boolean defaultValue); final void setBoolean(String propertyName, boolean value); final File getFile(String propertyName, File defaultValue); final File resolveRelativeFile(File file); final void setFile(String propertyName, File value); static final String SCRIPT; static final String LOG_DIRECTORY; static final String CONSOLE_HOST; static final String CONSOLE_PORT; static final File DEFAULT_PROPERTIES; static final File DEFAULT_SCRIPT; }### Answer: @Test public void testGetBoolean() throws Exception { assertTrue(m_grinderProperties.getBoolean("Not there", true)); assertTrue(!m_grinderProperties.getBoolean("Not there", false)); (new IterateOverProperties(m_booleanSet) { void match(String key, String value) throws Exception { assertTrue(!(Boolean.valueOf(value).booleanValue() ^ m_grinderProperties.getBoolean(key, false))); } } ).run(); (new IterateOverProperties(m_brokenBooleanSet) { void match(String key, String value) { assertTrue(!m_grinderProperties.getBoolean(key, false)); } } ).run(); }
### Question: GrinderProperties extends Properties { public final File getFile(String propertyName, File defaultValue) { final String s = getProperty(propertyName); if (s != null) { return new File(s); } return defaultValue; } GrinderProperties(); GrinderProperties(File file); final File getAssociatedFile(); final void setAssociatedFile(File file); final void save(); final void saveSingleProperty(String name); final void setErrorWriter(PrintWriter writer); final synchronized GrinderProperties getPropertySubset(String prefix); final int getInt(String propertyName, int defaultValue); final void setInt(String propertyName, int value); final long getLong(String propertyName, long defaultValue); final void setLong(String propertyName, long value); final short getShort(String propertyName, short defaultValue); final void setShort(String propertyName, short value); final double getDouble(String propertyName, double defaultValue); final void setDouble(String propertyName, double value); final boolean getBoolean(String propertyName, boolean defaultValue); final void setBoolean(String propertyName, boolean value); final File getFile(String propertyName, File defaultValue); final File resolveRelativeFile(File file); final void setFile(String propertyName, File value); static final String SCRIPT; static final String LOG_DIRECTORY; static final String CONSOLE_HOST; static final String CONSOLE_PORT; static final File DEFAULT_PROPERTIES; static final File DEFAULT_SCRIPT; }### Answer: @Test public void testGetFile() throws Exception { final File f = new File("foo"); assertEquals(f, m_grinderProperties.getFile("Not there", f)); (new IterateOverProperties(m_fileSet) { void match(String key, String value) throws Exception { assertEquals(new File(value), m_grinderProperties.getFile(key, null)); } } ).run(); }
### Question: GrinderProperties extends Properties { public final void setInt(String propertyName, int value) { setProperty(propertyName, Integer.toString(value)); } GrinderProperties(); GrinderProperties(File file); final File getAssociatedFile(); final void setAssociatedFile(File file); final void save(); final void saveSingleProperty(String name); final void setErrorWriter(PrintWriter writer); final synchronized GrinderProperties getPropertySubset(String prefix); final int getInt(String propertyName, int defaultValue); final void setInt(String propertyName, int value); final long getLong(String propertyName, long defaultValue); final void setLong(String propertyName, long value); final short getShort(String propertyName, short defaultValue); final void setShort(String propertyName, short value); final double getDouble(String propertyName, double defaultValue); final void setDouble(String propertyName, double value); final boolean getBoolean(String propertyName, boolean defaultValue); final void setBoolean(String propertyName, boolean value); final File getFile(String propertyName, File defaultValue); final File resolveRelativeFile(File file); final void setFile(String propertyName, File value); static final String SCRIPT; static final String LOG_DIRECTORY; static final String CONSOLE_HOST; static final String CONSOLE_PORT; static final File DEFAULT_PROPERTIES; static final File DEFAULT_SCRIPT; }### Answer: @Test public void testSetInt() throws Exception { final GrinderProperties properties = new GrinderProperties(); (new IterateOverProperties(m_intSet) { void match(String key, String value) throws Exception { properties.setInt(key, Integer.parseInt(value.trim())); assertEquals(value.trim(), properties.getProperty(key, null)); } } ).run(); }
### Question: GrinderProperties extends Properties { public final void setLong(String propertyName, long value) { setProperty(propertyName, Long.toString(value)); } GrinderProperties(); GrinderProperties(File file); final File getAssociatedFile(); final void setAssociatedFile(File file); final void save(); final void saveSingleProperty(String name); final void setErrorWriter(PrintWriter writer); final synchronized GrinderProperties getPropertySubset(String prefix); final int getInt(String propertyName, int defaultValue); final void setInt(String propertyName, int value); final long getLong(String propertyName, long defaultValue); final void setLong(String propertyName, long value); final short getShort(String propertyName, short defaultValue); final void setShort(String propertyName, short value); final double getDouble(String propertyName, double defaultValue); final void setDouble(String propertyName, double value); final boolean getBoolean(String propertyName, boolean defaultValue); final void setBoolean(String propertyName, boolean value); final File getFile(String propertyName, File defaultValue); final File resolveRelativeFile(File file); final void setFile(String propertyName, File value); static final String SCRIPT; static final String LOG_DIRECTORY; static final String CONSOLE_HOST; static final String CONSOLE_PORT; static final File DEFAULT_PROPERTIES; static final File DEFAULT_SCRIPT; }### Answer: @Test public void testSetLong() throws Exception { final GrinderProperties properties = new GrinderProperties(); (new IterateOverProperties(m_longSet) { void match(String key, String value) throws Exception { properties.setLong(key, Long.parseLong(value.trim())); assertEquals(value.trim(), properties.getProperty(key, null)); } } ).run(); }
### Question: GrinderProperties extends Properties { public final void setShort(String propertyName, short value) { setProperty(propertyName, Short.toString(value)); } GrinderProperties(); GrinderProperties(File file); final File getAssociatedFile(); final void setAssociatedFile(File file); final void save(); final void saveSingleProperty(String name); final void setErrorWriter(PrintWriter writer); final synchronized GrinderProperties getPropertySubset(String prefix); final int getInt(String propertyName, int defaultValue); final void setInt(String propertyName, int value); final long getLong(String propertyName, long defaultValue); final void setLong(String propertyName, long value); final short getShort(String propertyName, short defaultValue); final void setShort(String propertyName, short value); final double getDouble(String propertyName, double defaultValue); final void setDouble(String propertyName, double value); final boolean getBoolean(String propertyName, boolean defaultValue); final void setBoolean(String propertyName, boolean value); final File getFile(String propertyName, File defaultValue); final File resolveRelativeFile(File file); final void setFile(String propertyName, File value); static final String SCRIPT; static final String LOG_DIRECTORY; static final String CONSOLE_HOST; static final String CONSOLE_PORT; static final File DEFAULT_PROPERTIES; static final File DEFAULT_SCRIPT; }### Answer: @Test public void testSetShort() throws Exception { final GrinderProperties properties = new GrinderProperties(); (new IterateOverProperties(m_shortSet) { void match(String key, String value) throws Exception { properties.setShort(key, Short.parseShort(value.trim())); assertEquals(value.trim(), properties.getProperty(key, null)); } } ).run(); }
### Question: GrinderProperties extends Properties { public final void setDouble(String propertyName, double value) { setProperty(propertyName, Double.toString(value)); } GrinderProperties(); GrinderProperties(File file); final File getAssociatedFile(); final void setAssociatedFile(File file); final void save(); final void saveSingleProperty(String name); final void setErrorWriter(PrintWriter writer); final synchronized GrinderProperties getPropertySubset(String prefix); final int getInt(String propertyName, int defaultValue); final void setInt(String propertyName, int value); final long getLong(String propertyName, long defaultValue); final void setLong(String propertyName, long value); final short getShort(String propertyName, short defaultValue); final void setShort(String propertyName, short value); final double getDouble(String propertyName, double defaultValue); final void setDouble(String propertyName, double value); final boolean getBoolean(String propertyName, boolean defaultValue); final void setBoolean(String propertyName, boolean value); final File getFile(String propertyName, File defaultValue); final File resolveRelativeFile(File file); final void setFile(String propertyName, File value); static final String SCRIPT; static final String LOG_DIRECTORY; static final String CONSOLE_HOST; static final String CONSOLE_PORT; static final File DEFAULT_PROPERTIES; static final File DEFAULT_SCRIPT; }### Answer: @Test public void testSetDouble() throws Exception { final GrinderProperties properties = new GrinderProperties(); (new IterateOverProperties(m_doubleSet) { void match(String key, String value) throws Exception { properties.setDouble(key, Double.parseDouble(value)); assertEquals(Double.parseDouble(value), Double.parseDouble( properties.getProperty(key, null)), 0); } } ).run(); }
### Question: GrinderProperties extends Properties { public final void setBoolean(String propertyName, boolean value) { setProperty(propertyName, String.valueOf(value)); } GrinderProperties(); GrinderProperties(File file); final File getAssociatedFile(); final void setAssociatedFile(File file); final void save(); final void saveSingleProperty(String name); final void setErrorWriter(PrintWriter writer); final synchronized GrinderProperties getPropertySubset(String prefix); final int getInt(String propertyName, int defaultValue); final void setInt(String propertyName, int value); final long getLong(String propertyName, long defaultValue); final void setLong(String propertyName, long value); final short getShort(String propertyName, short defaultValue); final void setShort(String propertyName, short value); final double getDouble(String propertyName, double defaultValue); final void setDouble(String propertyName, double value); final boolean getBoolean(String propertyName, boolean defaultValue); final void setBoolean(String propertyName, boolean value); final File getFile(String propertyName, File defaultValue); final File resolveRelativeFile(File file); final void setFile(String propertyName, File value); static final String SCRIPT; static final String LOG_DIRECTORY; static final String CONSOLE_HOST; static final String CONSOLE_PORT; static final File DEFAULT_PROPERTIES; static final File DEFAULT_SCRIPT; }### Answer: @Test public void testSetBoolean() throws Exception { final GrinderProperties properties = new GrinderProperties(); (new IterateOverProperties(m_booleanSet) { void match(String key, String value) throws Exception { properties.setBoolean(key, Boolean.valueOf(value). booleanValue()); assertEquals(Boolean.valueOf(value).toString(), properties.getProperty(key, null)); } } ).run(); }
### Question: GrinderProperties extends Properties { public final void setFile(String propertyName, File value) { setProperty(propertyName, value.getPath()); } GrinderProperties(); GrinderProperties(File file); final File getAssociatedFile(); final void setAssociatedFile(File file); final void save(); final void saveSingleProperty(String name); final void setErrorWriter(PrintWriter writer); final synchronized GrinderProperties getPropertySubset(String prefix); final int getInt(String propertyName, int defaultValue); final void setInt(String propertyName, int value); final long getLong(String propertyName, long defaultValue); final void setLong(String propertyName, long value); final short getShort(String propertyName, short defaultValue); final void setShort(String propertyName, short value); final double getDouble(String propertyName, double defaultValue); final void setDouble(String propertyName, double value); final boolean getBoolean(String propertyName, boolean defaultValue); final void setBoolean(String propertyName, boolean value); final File getFile(String propertyName, File defaultValue); final File resolveRelativeFile(File file); final void setFile(String propertyName, File value); static final String SCRIPT; static final String LOG_DIRECTORY; static final String CONSOLE_HOST; static final String CONSOLE_PORT; static final File DEFAULT_PROPERTIES; static final File DEFAULT_SCRIPT; }### Answer: @Test public void testSetFile() throws Exception { final GrinderProperties properties = new GrinderProperties(); (new IterateOverProperties(m_fileSet) { void match(String key, String value) throws Exception { properties.setFile(key, new File(value)); assertEquals(new File(value).getPath(), properties.getProperty(key, null)); } } ).run(); }
### Question: Closer { Closer() { throw new UnsupportedOperationException(); } Closer(); static void close(Reader reader); static void close(Writer writer); static void close(InputStream inputStream); static void close(OutputStream outputStream); static void close(Socket socket); }### Answer: @Test public void testCloser() throws Exception { Closer.close((Socket)null); final Socket socket = new Socket() { public synchronized void close() throws IOException { TestCloser.this.close(); } }; Closer.close(socket); m_ioexception[0] = new IOException(); Closer.close(socket); m_ioexception[0] = new InterruptedIOException(); try { Closer.close(socket); fail("Expected UncheckedInterruptedException"); } catch (UncheckedInterruptedException e) { assertSame(m_ioexception[0], e.getCause()); } }
### Question: GrinderBuild { public static String getName() { return "The Grinder " + getVersionString(); } GrinderBuild(); static String getName(); static String getVersionString(); }### Answer: @Test public void testGrinderBuildExceptions() throws Exception { final ClassLoader blockingLoader = new BlockingClassLoader(Collections.<String>emptySet(), singleton(GrinderBuild.class.getName()), Collections.<String>emptySet(), false) { @Override public URL getResource(String name) { return null; } }; try { Class.forName(GrinderBuild.class.getName(), true, blockingLoader); fail("Expected ExceptionInInitializerError"); } catch (ExceptionInInitializerError e) { assertTrue(e.getCause().toString(), e.getCause() instanceof IOException); } }
### Question: HTTPUtilitiesImplementation implements HTTPUtilities { public NVPair basicAuthorizationHeader(String userID, String password) { return new NVPair("Authorization", "Basic " + Codecs.base64Encode(userID + ":" + password)); } HTTPUtilitiesImplementation(PluginProcessContext processContext); NVPair basicAuthorizationHeader(String userID, String password); HTTPResponse getLastResponse(); String valueFromLocationURI(final String tokenName); String valueFromBodyInput(final String tokenName); String valueFromBodyInput(String tokenName, String afterText); List<String> valuesFromBodyInput(final String tokenName); List<String> valuesFromBodyInput(String tokenName, String afterText); String valueFromHiddenInput(final String tokenName); String valueFromHiddenInput(String tokenName, String afterText); List<String> valuesFromHiddenInput(final String tokenName); List<String> valuesFromHiddenInput(String tokenName, String afterText); String valueFromBodyURI(final String tokenName); String valueFromBodyURI(final String tokenName, String afterText); List<String> valuesFromBodyURI(final String tokenName); List<String> valuesFromBodyURI(final String tokenName, String afterText); }### Answer: @Test public void testBasicAuthorizationHeader() throws Exception { final HTTPUtilities httpUtilities = new HTTPUtilitiesImplementation(m_pluginProcessContext); final NVPair pair = httpUtilities.basicAuthorizationHeader("foo", "secret"); assertEquals("Authorization", pair.getName()); assertEquals("Basic Zm9vOnNlY3JldA==", pair.getValue()); final NVPair pair2 = httpUtilities.basicAuthorizationHeader("", ""); assertEquals("Authorization", pair2.getName()); assertEquals("Basic Og==", pair2.getValue()); }
### Question: Connector { static ConnectDetails read(InputStream in) throws CommunicationException { try { final ObjectInputStream objectInputStream = new ObjectInputStream(in); final ConnectionType type = (ConnectionType) objectInputStream.readObject(); final Address address = (Address) objectInputStream.readObject(); return new ConnectDetails(type, address); } catch (IOException e) { throw new CommunicationException("Could not read address details", e); } catch (ClassNotFoundException e) { throw new CommunicationException("Could not read address details", e); } } Connector(String hostString, int port, ConnectionType connectionType); @Override int hashCode(); @Override boolean equals(Object o); String getEndpointAsString(); }### Answer: @Test public void testBadRead() throws Exception { final PipedOutputStream out = new PipedOutputStream(); final PipedInputStream in = new PipedInputStream(out); for (int x = 0; x < 100; ++x) { out.write(99); } try { Connector.read(in); fail("Expected CommunicationException"); } catch (CommunicationException e) { } final ObjectOutputStream objectStream = new ObjectOutputStream(out); objectStream.writeObject(ConnectionType.WORKER); objectStream.write(99); objectStream.writeObject(null); try { Connector.read(in); fail("Expected CommunicationException"); } catch (CommunicationException e) { } while (in.available() > 0) { in.read(); } objectStream.writeObject(ConnectionType.WORKER); objectStream.writeObject(IsolatedObjectFactory.getIsolatedObject()); try { Connector.read(in); fail("Expected CommunicationException"); } catch (CommunicationException e) { } }
### Question: Connector { @Override public int hashCode() { return m_hostString.hashCode() ^ m_port ^ m_connectionType.hashCode(); } Connector(String hostString, int port, ConnectionType connectionType); @Override int hashCode(); @Override boolean equals(Object o); String getEndpointAsString(); }### Answer: @Test public void testEquality() throws Exception { final Connector connector = new Connector("a", 1234, ConnectionType.WORKER); assertEquals(connector.hashCode(), connector.hashCode()); assertEquals(connector, connector); assertNotEquals(connector, null); assertNotEquals(connector, this); final Connector[] equal = { new Connector("a", 1234, ConnectionType.WORKER), }; final Connector[] notEqual = { new Connector("a", 6423, ConnectionType.WORKER), new Connector("b", 1234, ConnectionType.WORKER), new Connector("a", 1234, ConnectionType.AGENT), }; for (int i = 0; i < equal.length; ++i) { assertEquals(connector.hashCode(), equal[i].hashCode()); assertEquals(connector, equal[i]); } for (int i = 0; i < notEqual.length; ++i) { assertNotEquals(connector, notEqual[i]); } }
### Question: Connector { public String getEndpointAsString() { String host; try { host = InetAddress.getByName(m_hostString).toString(); } catch (UnknownHostException e) { host = m_hostString; } return host + ":" + m_port; } Connector(String hostString, int port, ConnectionType connectionType); @Override int hashCode(); @Override boolean equals(Object o); String getEndpointAsString(); }### Answer: @Test public void testGetEndpointAsString() throws Exception { assertEquals( "a:1234", new Connector("a", 1234, ConnectionType.WORKER).getEndpointAsString()); final String description = new Connector("", 1234, ConnectionType.WORKER).getEndpointAsString(); assertContains(description, "localhost"); assertContains(description, "1234"); }
### Question: Acceptor { public void shutdown() throws CommunicationException { synchronized (m_socketSets) { if (m_isShutdown) { return; } m_isShutdown = true; } try { m_serverSocket.close(); } catch (IOException e) { UncheckedInterruptedException.ioException(e); throw new CommunicationException("Error closing socket", e); } finally { m_executor.shutdownNow(); final ResourcePool[] socketSets = cloneListOfSocketSets(); for (int i = 0; i < socketSets.length; ++i) { socketSets[i].closeCurrentResources(); } m_exceptionQueue.clear(); } } Acceptor(String addressString, int port, int numberOfThreads, TimeAuthority timeAuthority); void shutdown(); int getPort(); Exception getPendingException(); int getNumberOfConnections(); void addListener(ConnectionType connectionType, Listener listener); }### Answer: @Test public void testShutdown() throws Exception { final Acceptor acceptor = createAcceptor(3); final ResourcePool socketSet = acceptor.getSocketSet(ConnectionType.AGENT); final Connector connector = new Connector("localhost", acceptor.getPort(), ConnectionType.AGENT); connector.connect(); for (int i = 0; socketSet.countActive() != 1 && i < 10; ++i) { Thread.sleep(i * i * 10); } assertNull(acceptor.peekPendingException()); acceptor.shutdown(); try { acceptor.getSocketSet(ConnectionType.AGENT); fail("Expected Acceptor.ShutdownException"); } catch (Acceptor.ShutdownException e) { } assertTrue(socketSet.reserveNext().isSentinel()); }
### Question: Acceptor { public Exception getPendingException() { synchronized (m_socketSets) { if (m_isShutdown) { return null; } } try { return m_exceptionQueue.take(); } catch (InterruptedException e) { throw new UncheckedInterruptedException(e); } } Acceptor(String addressString, int port, int numberOfThreads, TimeAuthority timeAuthority); void shutdown(); int getPort(); Exception getPendingException(); int getNumberOfConnections(); void addListener(ConnectionType connectionType, Listener listener); }### Answer: @Test public void testGetPendingException() throws Exception { final Acceptor acceptor = createAcceptor(3); assertNull(acceptor.peekPendingException()); final Socket socket = new Socket("localhost", acceptor.getPort()); for (int i = 0; i < 10; ++i) { socket.getOutputStream().write(99); } socket.getOutputStream().flush(); final Socket socket2 = new Socket("localhost", acceptor.getPort()); for (int i = 0; i < 10; ++i) { socket2.getOutputStream().write(99); } socket2.getOutputStream().flush(); assertTrue(acceptor.getPendingException() instanceof CommunicationException); assertTrue(acceptor.getPendingException() instanceof CommunicationException); assertNull(acceptor.peekPendingException()); acceptor.shutdown(); assertNull(acceptor.getPendingException()); } @Test public void testGetPendingExceptionInterrupted() throws Exception { final Acceptor acceptor = createAcceptor(3); Thread.currentThread().interrupt(); try { acceptor.getPendingException(); fail("Expected UncheckedInterruptedException"); } catch (UncheckedInterruptedException e) { } }
### Question: HTTPUtilitiesImplementation implements HTTPUtilities { public HTTPResponse getLastResponse() throws GrinderException { final HTTPPluginThreadState threadState = (HTTPPluginThreadState)m_processContext.getPluginThreadListener(); return threadState.getLastResponse(); } HTTPUtilitiesImplementation(PluginProcessContext processContext); NVPair basicAuthorizationHeader(String userID, String password); HTTPResponse getLastResponse(); String valueFromLocationURI(final String tokenName); String valueFromBodyInput(final String tokenName); String valueFromBodyInput(String tokenName, String afterText); List<String> valuesFromBodyInput(final String tokenName); List<String> valuesFromBodyInput(String tokenName, String afterText); String valueFromHiddenInput(final String tokenName); String valueFromHiddenInput(String tokenName, String afterText); List<String> valuesFromHiddenInput(final String tokenName); List<String> valuesFromHiddenInput(String tokenName, String afterText); String valueFromBodyURI(final String tokenName); String valueFromBodyURI(final String tokenName, String afterText); List<String> valuesFromBodyURI(final String tokenName); List<String> valuesFromBodyURI(final String tokenName, String afterText); }### Answer: @Test public void testGetLastResponse() throws Exception { final HTTPUtilities httpUtilities = new HTTPUtilitiesImplementation(m_pluginProcessContext); assertEquals(null, httpUtilities.getLastResponse()); final HTTPRequestHandler handler = new HTTPRequestHandler(); handler.start(); final HTTPRequest request = new HTTPRequest(); final HTTPResponse httpResponse = request.GET(handler.getURL()); assertSame(httpResponse, httpUtilities.getLastResponse()); handler.shutdown(); }
### Question: QueuedSenderDecorator implements QueuedSender { public void send(Message message) throws CommunicationException { m_messageQueue.queue(message); } QueuedSenderDecorator(Sender delegate); void send(Message message); @Override void flush(); void shutdown(); }### Answer: @Test public void testSend() throws Exception { final StubSender sender = new StubSender(); final QueuedSender queuedSender = new QueuedSenderDecorator(sender); final Message message1 = new SimpleMessage(); final Message message2 = new SimpleMessage(); queuedSender.send(message1); queuedSender.send(message2); queuedSender.flush(); final Message[] messagesReceived = sender.getMessagesReceived(); assertEquals(2, messagesReceived.length); assertSame(message1, messagesReceived[0]); assertSame(message2, messagesReceived[1]); }
### Question: QueuedSenderDecorator implements QueuedSender { public void shutdown() { m_messageQueue.shutdown(); m_delegate.shutdown(); } QueuedSenderDecorator(Sender delegate); void send(Message message); @Override void flush(); void shutdown(); }### Answer: @Test public void testShutdown() throws Exception { final StubSender sender = new StubSender(); final QueuedSender queuedSender = new QueuedSenderDecorator(sender); assertTrue(!sender.getIsShutdown()); queuedSender.shutdown(); assertTrue(sender.getIsShutdown()); try { queuedSender.send(new SimpleMessage()); fail("Expected CommunicationException"); } catch (CommunicationException e) { } try { queuedSender.flush(); fail("Expected CommunicationException"); } catch (CommunicationException e) { } }
### Question: MessageQueue { public void queue(Message message) throws ShutdownException { checkIfShutdown(); m_queue.add(message); } MessageQueue(boolean passExceptions); void queue(Message message); void queue(Exception exception); Message dequeue(boolean block); void shutdown(); void checkIfShutdown(); List<Message> drainMessages(); }### Answer: @Test public void testWithActiveDequeuer() throws Exception { final Message[] messages = { new SimpleMessage(10), new SimpleMessage(0), new SimpleMessage(999), }; final DequeuerThread dequeuerThread = new DequeuerThread(messages.length); dequeuerThread.start(); for (int i=0; i<messages.length; ++i) { m_queue.queue(messages[i]); } dequeuerThread.join(); final List<Message> receivedMessages = dequeuerThread.getMessages(); assertEquals(messages.length, receivedMessages.size()); for (int i=0; i<messages.length; ++i) { assertSame(messages[i], receivedMessages.get(i)); } }
### Question: ClientSender extends StreamSender implements BlockingSender { public static ClientSender connect(Connector connector, Address address) throws CommunicationException { return new ClientSender(new SocketWrapper(connector.connect(address))); } private ClientSender(SocketWrapper socketWrapper); static ClientSender connect(Connector connector, Address address); static ClientSender connect(ClientReceiver clientReceiver); @Override void shutdown(); Message blockingSend(Message message); void sendKeepAlive(); }### Answer: @Test public void testSend() throws Exception { final SocketAcceptorThread socketAcceptor = SocketAcceptorThread.create(); final Connector connector = new Connector(socketAcceptor.getHostName(), socketAcceptor.getPort(), ConnectionType.AGENT); final Sender clientSender = ClientSender.connect(connector, null); socketAcceptor.join(); final SimpleMessage message1 = new SimpleMessage(); final SimpleMessage message2 = new SimpleMessage(); clientSender.send(message1); clientSender.send(message2); final InputStream socketInput = socketAcceptor.getAcceptedSocket().getInputStream(); assertEquals(ConnectionType.AGENT, Connector.read(socketInput).getConnectionType()); final ObjectInputStream inputStream1 = new ObjectInputStream(socketInput); final Object o1 = inputStream1.readObject(); final ObjectInputStream inputStream2 = new ObjectInputStream(socketInput); final Object o2 = inputStream2.readObject(); assertEquals(message1, o1); assertEquals(message2, o2); assertEquals(0, socketInput.available()); socketAcceptor.close(); try { ClientReceiver.connect(connector, new StubAddress()); fail("Expected CommunicationException"); } catch (CommunicationException e) { } }
### Question: ClientSender extends StreamSender implements BlockingSender { @Override public void shutdown() { m_socketWrapper.close(); super.shutdown(); } private ClientSender(SocketWrapper socketWrapper); static ClientSender connect(Connector connector, Address address); static ClientSender connect(ClientReceiver clientReceiver); @Override void shutdown(); Message blockingSend(Message message); void sendKeepAlive(); }### Answer: @Test public void testShutdown() throws Exception { final SocketAcceptorThread socketAcceptor = SocketAcceptorThread.create(); final Connector connector = new Connector(socketAcceptor.getHostName(), socketAcceptor.getPort(), ConnectionType.AGENT); final Sender clientSender = ClientSender.connect(connector, null); socketAcceptor.join(); final Message message = new SimpleMessage(); clientSender.send(message); clientSender.shutdown(); try { clientSender.send(message); fail("Expected CommunicationException"); } catch (CommunicationException e) { } final InputStream socketInput = socketAcceptor.getAcceptedSocket().getInputStream(); assertEquals(ConnectionType.AGENT, Connector.read(socketInput).getConnectionType()); final ObjectInputStream inputStream1 = new ObjectInputStream(socketInput); final Object o1 = inputStream1.readObject(); assertNotNull(o1); final ObjectInputStream inputStream2 = new ObjectInputStream(socketInput); final Object o2 = inputStream2.readObject(); assertTrue(o2 instanceof CloseCommunicationMessage); socketAcceptor.close(); }
### Question: ClientSender extends StreamSender implements BlockingSender { public Message blockingSend(Message message) throws CommunicationException { final MessageRequiringResponse messageRequiringResponse = new MessageRequiringResponse(message); final Message result; synchronized (m_socketWrapper) { send(messageRequiringResponse); final Receiver receiver = new StreamReceiver(m_socketWrapper.getInputStream()); result = receiver.waitForMessage(); } if (result == null) { throw new CommunicationException("Shut down"); } else if (result instanceof NoResponseMessage) { throw new NoResponseException("Server did not respond"); } return result; } private ClientSender(SocketWrapper socketWrapper); static ClientSender connect(Connector connector, Address address); static ClientSender connect(ClientReceiver clientReceiver); @Override void shutdown(); Message blockingSend(Message message); void sendKeepAlive(); }### Answer: @Test public void testBlockingSend() throws Exception { final SocketAcceptorThread socketAcceptor = SocketAcceptorThread.create(); final Connector connector = new Connector(socketAcceptor.getHostName(), socketAcceptor.getPort(), ConnectionType.AGENT); final BlockingSender clientSender = ClientSender.connect(connector, null); socketAcceptor.join(); final Socket acceptedSocket = socketAcceptor.getAcceptedSocket(); final InputStream socketInput = acceptedSocket.getInputStream(); final OutputStream socketOutput = acceptedSocket.getOutputStream(); assertEquals(ConnectionType.AGENT, Connector.read(socketInput).getConnectionType()); final SimpleMessage message1 = new SimpleMessage(); final ReceiveOneMessageAndReply receiver1 = new ReceiveOneMessageAndReply(socketInput, socketOutput); receiver1.start(); final Object received1 = clientSender.blockingSend(message1); assertEquals(message1, received1); receiver1.join(); assertNull(receiver1.getException()); final NoResponseMessage message2 = new NoResponseMessage(); final ReceiveOneMessageAndReply receiver2 = new ReceiveOneMessageAndReply(socketInput, socketOutput); receiver2.start(); try { clientSender.blockingSend(message2); fail("Expected NoResponseException"); } catch (NoResponseException e) { } receiver2.join(); assertNull(receiver2.getException()); socketAcceptor.close(); }
### Question: MessageDispatchSender implements Sender, MessageDispatchRegistry { public void shutdown() { final List<Handler<? extends Message>> handlers; synchronized (m_handlers) { handlers = new ArrayList<Handler<? extends Message>>(m_handlers.values()); } for (Handler<? extends Message> handler : handlers) { handler.shutdown(); } final List<BlockingHandler<? extends Message>> responders; synchronized (m_responders) { responders = new ArrayList<BlockingHandler<? extends Message>>( m_responders.values()); } for (BlockingHandler<? extends Message> responder : responders) { responder.shutdown(); } m_fallbackHandlers.apply(new ListenerSupport.Informer<Handler<Message>>() { public void inform(Handler<Message> handler) { handler.shutdown(); } }); } @SuppressWarnings("unchecked") @Override Handler<T> set(Class<S> messageType, Handler<T> messageHandler); @SuppressWarnings("unchecked") @Override BlockingHandler<T> set(Class<S> messageType, BlockingHandler<T> responder); void addFallback(Handler<Message> messageHandler); void send(final Message message); void shutdown(); }### Answer: @Test public void testShutdown() throws Exception { final MessageDispatchSender messageDispatchSender = new MessageDispatchSender(); messageDispatchSender.shutdown(); messageDispatchSender.set(SimpleMessage.class, m_handler); messageDispatchSender.shutdown(); verify(m_handler).shutdown(); messageDispatchSender.addFallback(m_handler2); messageDispatchSender.addFallback(m_handler2); messageDispatchSender.set(OtherMessage.class, m_responder); final BlockingHandler<Message> blockingHandler2 = new AbstractBlockingHandler<Message>() { public Message blockingSend(Message message) throws CommunicationException { return null; }}; messageDispatchSender.set(Message.class, blockingHandler2); messageDispatchSender.shutdown(); verify(m_handler, times(2)).shutdown(); verify(m_handler2, times(2)).shutdown(); verify(m_responder).shutdown(); verifyNoMoreInteractions(m_handler, m_handler2, m_responder); }
### Question: SocketWrapper implements ResourcePool.Resource { public void close() { if (!m_socket.isClosed()) { synchronized (m_outputStream) { new StreamSender(m_outputStream).shutdown(); } Closer.close(m_socket); m_closedListeners.apply(m_closedInformer); } } SocketWrapper(Socket socket); void close(); boolean isClosed(); ConnectionIdentity getConnectionIdentity(); InputStream getInputStream(); OutputStream getOutputStream(); void addClosedListener(ClosedListener listener); void setAddress(Address address); Address getAddress(); }### Answer: @Test(expected=CommunicationException.class) public void testConstructionWithBadSocket() throws Exception { m_socket.close(); new SocketWrapper(m_socket); }
### Question: EchoFilter implements TCPProxyFilter { @Override public void connectionClosed(ConnectionDetails connectionDetails) { m_out.println("--- " + connectionDetails + " closed --"); } EchoFilter(PrintWriter output); @Override byte[] handle(ConnectionDetails connectionDetails, byte[] buffer, int bytesRead); @Override void connectionOpened(ConnectionDetails connectionDetails); @Override void connectionClosed(ConnectionDetails connectionDetails); }### Answer: @Test public void testConnectionClosed() throws Exception { final EchoFilter echoFilter = new EchoFilter(m_out); echoFilter.connectionClosed(m_connectionDetails); final String output = m_outString.toString(); assertContains(output, m_connectionDetails.toString()); assertContains(output, "closed"); }
### Question: ClientReceiver extends StreamReceiver { @Override public void shutdown() { m_socketWrapper.close(); super.shutdown(); } private ClientReceiver(SocketWrapper socketWrapper); static ClientReceiver connect(Connector connector, Address address); @Override void shutdown(); }### Answer: @Test public void testShutdown() throws Exception { final SocketAcceptorThread socketAcceptor = SocketAcceptorThread.create(); final Connector connector = new Connector(socketAcceptor.getHostName(), socketAcceptor.getPort(), ConnectionType.AGENT); final Address address = new StubAddress(); final Receiver clientReceiver = ClientReceiver.connect(connector, address); socketAcceptor.join(); final Socket acceptedSocket = socketAcceptor.getAcceptedSocket(); assertConnection( acceptedSocket.getInputStream(), ConnectionType.AGENT, address); final OutputStream socketOutput = acceptedSocket.getOutputStream(); final SimpleMessage message1 = new SimpleMessage(); final ObjectOutputStream objectStream1 = new ObjectOutputStream(socketOutput); objectStream1.writeObject(message1); objectStream1.flush(); final Message receivedMessage = clientReceiver.waitForMessage(); assertNotNull(receivedMessage); clientReceiver.shutdown(); assertNull(clientReceiver.waitForMessage()); socketAcceptor.close(); }
### Question: MessagePump { public void shutdown() { if (!m_shutdownTriggered) { m_shutdownTriggered = true; m_receiver.shutdown(); m_sender.shutdown(); m_executor.shutdownNow(); } } MessagePump(Receiver receiver, Sender sender, int numberOfThreads); void start(); void shutdown(); }### Answer: @Test public void testShutdownIfReceiverShutdown() throws Exception { m_sender.shutdown(); assertEquals(null, m_intermediateReceiver.waitForMessage()); assertEquals(null, m_receiver.waitForMessage()); }
### Question: ServerReceiver implements Receiver { public synchronized void shutdown() { m_messageQueue.shutdown(); m_executor.shutdownNow(); } void receiveFrom(Acceptor acceptor, ConnectionType[] connectionTypes, int numberOfThreads, final long idleThreadPollDelay, final long inactiveClientTimeOut); Message waitForMessage(); synchronized void shutdown(); }### Answer: @Test public void testShutdown() throws Exception { final Acceptor acceptor = new Acceptor("localhost", 0, 1, m_timeAuthority); final ServerReceiver serverReceiver = new ServerReceiver(); serverReceiver.receiveFrom( acceptor, new ConnectionType[] { ConnectionType.AGENT }, 3, 10, 100); final Socket socket = new Connector(InetAddress.getByName(null).getHostName(), acceptor.getPort(), ConnectionType.AGENT) .connect(); final ResourcePool socketSet = acceptor.getSocketSet(ConnectionType.AGENT); for (int i=0; socketSet.countActive() != 1 && i<10; ++i) { Thread.sleep(i * i * 10); } final SimpleMessage message = new SimpleMessage(); final ObjectOutputStream objectStream = new ObjectOutputStream(socket.getOutputStream()); objectStream.writeObject(message); objectStream.flush(); final Message receivedMessage = serverReceiver.waitForMessage(); assertNotNull(receivedMessage); serverReceiver.shutdown(); try { serverReceiver.receiveFrom( acceptor, new ConnectionType[] { ConnectionType.AGENT }, 3, 10, 100); fail("Expected a CommunicationException"); } catch (CommunicationException e) { } assertNull(serverReceiver.waitForMessage()); acceptor.shutdown(); }
### Question: IdleAwareSocketWrapper extends SocketWrapper { public boolean hasData(long inactiveClientTimeOut) throws IOException { if (isClosed()) { throw new IOException("Socket is closed"); } final InputStream inputStream = getInputStream(); synchronized (inputStream) { if (inputStream.available() > 0) { m_idleStart = -1; return true; } final long now = m_timeAuthority.getTimeInMilliseconds(); if (m_idleStart == -1) { m_idleStart = now; } else if (m_idleStart + inactiveClientTimeOut < now) { close(); } return false; } } IdleAwareSocketWrapper(Socket socket, TimeAuthority timeAuthority); boolean hasData(long inactiveClientTimeOut); }### Answer: @Test public void testHasDataNoData() throws Exception { final IdleAwareSocketWrapper socketWrapper = new IdleAwareSocketWrapper(m_socket, m_timeAuthority); assertFalse(socketWrapper.hasData(99)); } @Test(expected = IOException.class) public void testHasDataSocketClosed() throws Exception { final IdleAwareSocketWrapper socketWrapper = new IdleAwareSocketWrapper(m_socket, m_timeAuthority); socketWrapper.close(); socketWrapper.hasData(99); } @Test public void testHasDataTimeOut() throws Exception { final IdleAwareSocketWrapper socketWrapper = new IdleAwareSocketWrapper(m_socket, m_timeAuthority); when(m_timeAuthority.getTimeInMilliseconds()) .thenReturn(1000L) .thenReturn(2000L); assertFalse(socketWrapper.hasData(123)); assertFalse(m_socket.isClosed()); assertFalse(socketWrapper.hasData(123)); assertTrue(m_socket.isClosed()); }
### Question: BarrierIdentityGenerator implements BarrierIdentity.Factory { @Override public BarrierIdentity next() { return new BarrierIdentityImplementation(m_scope, m_next.getAndIncrement()); } BarrierIdentityGenerator(Serializable scope); @Override BarrierIdentity next(); }### Answer: @Test public void testIdentityGeneration() { final BarrierIdentityGenerator generator = new BarrierIdentityGenerator(new Integer(1)); final BarrierIdentity one = generator.next(); final BarrierIdentity two = generator.next(); assertNotEquals(one, two); } @Test public void testIdentityIsSerializable() throws Exception { final BarrierIdentityGenerator generator = new BarrierIdentityGenerator(new Integer(1)); final BarrierIdentity id = generator.next(); final BarrierIdentity serializedID = serialize(id); assertEquals(id, serializedID); } @Test public void testIdentityEquality() throws Exception { final BarrierIdentityGenerator generator = new BarrierIdentityGenerator(new Integer(1)); final BarrierIdentity one = generator.next(); final BarrierIdentity two = generator.next(); assertEquals(one, one); assertEquals(one.hashCode(), one.hashCode()); assertNotEquals(one, two); assertNotEquals(one, this); assertNotEquals(one, null); }
### Question: BarrierImplementation implements Barrier, BarrierGroup.Listener { @Override public String getName() { return m_barrierGroup.getName(); } BarrierImplementation(BarrierGroup group, BarrierIdentity.Factory identityFactory); @Override void await(); @Override boolean await(long timeout, TimeUnit unit); @Override boolean await(long timeout); @Override void awaken(Set<BarrierIdentity> waiters); @Override void cancel(); @Override String getName(); }### Answer: @Test public void testGetGroupName() throws Exception { final BarrierImplementation b = new BarrierImplementation(m_barrierGroup, m_identityFactory); when(m_barrierGroup.getName()).thenReturn("mygroup"); assertEquals("mygroup", b.getName()); }
### Question: BarrierImplementation implements Barrier, BarrierGroup.Listener { @Override public void cancel() throws CommunicationException { synchronized (m_condition) { m_state.cancel(this); } } BarrierImplementation(BarrierGroup group, BarrierIdentity.Factory identityFactory); @Override void await(); @Override boolean await(long timeout, TimeUnit unit); @Override boolean await(long timeout); @Override void awaken(Set<BarrierIdentity> waiters); @Override void cancel(); @Override String getName(); }### Answer: @Test public void testCancelVirginBarrier() throws Exception { final BarrierImplementation b = new BarrierImplementation(m_barrierGroup, m_identityFactory); reset(m_barrierGroup); b.cancel(); verify(m_barrierGroup).cancelWaiter(ID1); verify(m_barrierGroup).removeBarriers(1); verify(m_barrierGroup).removeListener(b); verifyNoMoreInteractions(m_barrierGroup); b.cancel(); verifyNoMoreInteractions(m_barrierGroup); }
### Question: XSLTHelper { public static String formatTime(String iso8601) throws ParseException { final Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(iso8601); return DateFormat.getDateTimeInstance().format(date); } XSLTHelper(); static String formatTime(String iso8601); static String quoteForPython(String value); static String quoteEOLEscapedStringForPython(String value); static String quoteForClojure(String value); static String quoteEOLEscapedStringForClojure(String value); static String summariseAsLine(String value, int maximumCharacters); static String escape(String value); static String indent(); static String newLine(); static String newLineAndIndent(); static String changeIndent(int indentChange); static String resetIndent(); static String base64ToPython(String base64String); static String base64ToClojure(String base64String); static void setIndentString(String indentString); }### Answer: @Test public void testFormatTime() throws Exception { try { XSLTHelper.formatTime("abc"); fail("Expected ParseException"); } catch (ParseException e) { } final String s = XSLTHelper.formatTime("2005-01-04T18:30:00"); assertNotNull(s); }
### Question: XSLTHelper { public static String quoteForPython(String value) { if (value == null) { return "None"; } final StringBuilder result = new StringBuilder(); final String quotes = pythonQuotes(value); result.append(quotes).append(escape(value, false)).append(quotes); return result.toString(); } XSLTHelper(); static String formatTime(String iso8601); static String quoteForPython(String value); static String quoteEOLEscapedStringForPython(String value); static String quoteForClojure(String value); static String quoteEOLEscapedStringForClojure(String value); static String summariseAsLine(String value, int maximumCharacters); static String escape(String value); static String indent(); static String newLine(); static String newLineAndIndent(); static String changeIndent(int indentChange); static String resetIndent(); static String base64ToPython(String base64String); static String base64ToClojure(String base64String); static void setIndentString(String indentString); }### Answer: @Test public void testQuoteForPython() throws Exception { assertEquals("None", XSLTHelper.quoteForPython(null)); assertEquals("''", XSLTHelper.quoteForPython("")); assertEquals("\'\\\"\'", XSLTHelper.quoteForPython("\"")); assertEquals("'foo'", XSLTHelper.quoteForPython("foo")); assertEquals("'foo\\''", XSLTHelper.quoteForPython("foo'")); assertEquals("' \\\\ '", XSLTHelper.quoteForPython(" \\ ")); assertEquals("'''foo \n bah'''", XSLTHelper.quoteForPython("foo \n bah")); assertEquals("'''foo \\r bah'''", XSLTHelper.quoteForPython("foo \r bah")); assertEquals("'foo \\\\n bah'", XSLTHelper.quoteForPython("foo \\n bah")); }
### Question: XSLTHelper { public static String quoteEOLEscapedStringForPython(String value) { if (value == null) { return "None"; } final StringBuilder result = new StringBuilder(); final String quotes = pythonQuotes(value); result.append(quotes).append(escape(value, true)).append(quotes); return result.toString(); } XSLTHelper(); static String formatTime(String iso8601); static String quoteForPython(String value); static String quoteEOLEscapedStringForPython(String value); static String quoteForClojure(String value); static String quoteEOLEscapedStringForClojure(String value); static String summariseAsLine(String value, int maximumCharacters); static String escape(String value); static String indent(); static String newLine(); static String newLineAndIndent(); static String changeIndent(int indentChange); static String resetIndent(); static String base64ToPython(String base64String); static String base64ToClojure(String base64String); static void setIndentString(String indentString); }### Answer: @Test public void testQuoteEOLEscapedStringForPython() throws Exception { assertEquals("None", XSLTHelper.quoteEOLEscapedStringForPython(null)); assertEquals("''", XSLTHelper.quoteEOLEscapedStringForPython("")); assertEquals("\'\\\"\'", XSLTHelper.quoteEOLEscapedStringForPython("\"")); assertEquals("'foo'", XSLTHelper.quoteEOLEscapedStringForPython("foo")); assertEquals("'foo\\''", XSLTHelper.quoteEOLEscapedStringForPython("foo'")); assertEquals("' \\\\ '", XSLTHelper.quoteEOLEscapedStringForPython(" \\ ")); assertEquals("'''foo bah'''", XSLTHelper.quoteEOLEscapedStringForPython("foo \n \r bah")); assertEquals("'foo \\n bah\\\\'", XSLTHelper.quoteEOLEscapedStringForPython("foo \\n bah\\")); }
### Question: XSLTHelper { public static String quoteForClojure(String value) { if (value == null) { return "nil"; } final StringBuilder result = new StringBuilder(); result.append('"').append(escape(value, false)).append('"'); return result.toString(); } XSLTHelper(); static String formatTime(String iso8601); static String quoteForPython(String value); static String quoteEOLEscapedStringForPython(String value); static String quoteForClojure(String value); static String quoteEOLEscapedStringForClojure(String value); static String summariseAsLine(String value, int maximumCharacters); static String escape(String value); static String indent(); static String newLine(); static String newLineAndIndent(); static String changeIndent(int indentChange); static String resetIndent(); static String base64ToPython(String base64String); static String base64ToClojure(String base64String); static void setIndentString(String indentString); }### Answer: @Test public void testQuoteForClojure() throws Exception { assertEquals("nil", XSLTHelper.quoteForClojure(null)); assertEquals("\"\"", XSLTHelper.quoteForClojure("")); assertEquals("\"\\\"\"", XSLTHelper.quoteForClojure("\"")); assertEquals("\"\\\"\"", XSLTHelper.quoteForClojure("\"")); assertEquals("\"foo\"", XSLTHelper.quoteForClojure("foo")); assertEquals("\"foo\\'\"", XSLTHelper.quoteForClojure("foo'")); assertEquals("\" \\\\ \"", XSLTHelper.quoteForClojure(" \\ ")); assertEquals("\"foo \n bah\"", XSLTHelper.quoteForClojure("foo \n bah")); assertEquals("\"foo \\r bah\"", XSLTHelper.quoteForClojure("foo \r bah")); assertEquals("\"foo \\\\n bah\"", XSLTHelper.quoteForClojure("foo \\n bah")); }
### Question: XSLTHelper { public static String quoteEOLEscapedStringForClojure(String value) { if (value == null) { return "nil"; } final StringBuilder result = new StringBuilder(); result.append('"').append(escape(value, true)).append('"'); return result.toString(); } XSLTHelper(); static String formatTime(String iso8601); static String quoteForPython(String value); static String quoteEOLEscapedStringForPython(String value); static String quoteForClojure(String value); static String quoteEOLEscapedStringForClojure(String value); static String summariseAsLine(String value, int maximumCharacters); static String escape(String value); static String indent(); static String newLine(); static String newLineAndIndent(); static String changeIndent(int indentChange); static String resetIndent(); static String base64ToPython(String base64String); static String base64ToClojure(String base64String); static void setIndentString(String indentString); }### Answer: @Test public void testQuoteEOLEscapedStringForClojure() throws Exception { assertEquals("nil", XSLTHelper.quoteEOLEscapedStringForClojure(null)); assertEquals("\"\"", XSLTHelper.quoteEOLEscapedStringForClojure("")); assertEquals("\"\\\"\"", XSLTHelper.quoteEOLEscapedStringForClojure("\"")); assertEquals("\"foo\"", XSLTHelper.quoteEOLEscapedStringForClojure("foo")); assertEquals("\"foo\\'\"", XSLTHelper.quoteEOLEscapedStringForClojure("foo'")); }
### Question: XSLTHelper { public static String escape(String value) { return escape(value, false); } XSLTHelper(); static String formatTime(String iso8601); static String quoteForPython(String value); static String quoteEOLEscapedStringForPython(String value); static String quoteForClojure(String value); static String quoteEOLEscapedStringForClojure(String value); static String summariseAsLine(String value, int maximumCharacters); static String escape(String value); static String indent(); static String newLine(); static String newLineAndIndent(); static String changeIndent(int indentChange); static String resetIndent(); static String base64ToPython(String base64String); static String base64ToClojure(String base64String); static void setIndentString(String indentString); }### Answer: @Test public void testEscape() throws Exception { assertEquals("", XSLTHelper.escape("")); assertEquals("\\'", XSLTHelper.escape("'")); assertEquals("\\\"", XSLTHelper.escape("\"")); assertEquals("\\\\", XSLTHelper.escape("\\")); assertEquals("Hello \\'quoted\\\" \\\\world", XSLTHelper.escape("Hello 'quoted\" \\world")); }
### Question: XSLTHelper { public static String indent() { final StringBuilder result = new StringBuilder(Math.max(0, s_indentString.length() * s_indentLevel)); for (int i = 0; i < s_indentLevel; ++i) { result.append(s_indentString); } return result.toString(); } XSLTHelper(); static String formatTime(String iso8601); static String quoteForPython(String value); static String quoteEOLEscapedStringForPython(String value); static String quoteForClojure(String value); static String quoteEOLEscapedStringForClojure(String value); static String summariseAsLine(String value, int maximumCharacters); static String escape(String value); static String indent(); static String newLine(); static String newLineAndIndent(); static String changeIndent(int indentChange); static String resetIndent(); static String base64ToPython(String base64String); static String base64ToClojure(String base64String); static void setIndentString(String indentString); }### Answer: @Test public void testIndent() throws Exception { assertEquals("", XSLTHelper.indent()); XSLTHelper.changeIndent(2); assertEquals(" ", XSLTHelper.indent()); XSLTHelper.setIndentString("\t"); assertEquals("\t\t", XSLTHelper.indent()); }
### Question: ParametersFromProperties implements HTTPRecordingParameters { @Override public boolean isCommonHeader(String headerName) { return m_commonHeaders.contains(headerName); } ParametersFromProperties(); @Override int getTestNumberOffset(); @Override boolean isCommonHeader(String headerName); @Override boolean isMirroredHeader(String headerName); }### Answer: @Test public void testIsCommonHeader() { final HTTPRecordingParameters parameters = new ParametersFromProperties(); assertTrue(parameters.isCommonHeader("Accept")); assertTrue(parameters.isCommonHeader("User-Agent")); assertTrue(parameters.isCommonHeader("faces-request")); assertFalse(parameters.isCommonHeader("If-None-Match")); assertFalse(parameters.isCommonHeader("Content-Type")); assertFalse(parameters.isCommonHeader("Bar")); }
### Question: ParametersFromProperties implements HTTPRecordingParameters { @Override public boolean isMirroredHeader(String headerName) { return m_mirroredHeaders.contains(headerName); } ParametersFromProperties(); @Override int getTestNumberOffset(); @Override boolean isCommonHeader(String headerName); @Override boolean isMirroredHeader(String headerName); }### Answer: @Test public void testIsMirroredHeader() { final HTTPRecordingParameters parameters = new ParametersFromProperties(); assertTrue(parameters.isMirroredHeader("Accept")); assertTrue(parameters.isMirroredHeader("User-Agent")); assertTrue(parameters.isMirroredHeader("If-None-Match")); }
### Question: HTTPRecordingImplementation implements HTTPRecording, Disposable { @Override public File createBodyDataFileName() { return new File("http-data-" + m_bodyFileIDGenerator.next() + ".dat"); } HTTPRecordingImplementation( HTTPRecordingParameters parameters, HTTPRecordingResultProcessor resultProcessor, Logger logger, RegularExpressions regularExpressions, URIParser uriParser); @Override HTTPRecordingParameters getParameters(); @Override RequestType addRequest( ConnectionDetails connectionDetails, String method, String relativeURI); @Override void markLastResponseTime(); @Override void setTokenReference( String name, String value, TokenReferenceType tokenReference); @Override String getLastValueForToken(String name); @Override boolean tokenReferenceExists(String name, String source); @Override File createBodyDataFileName(); void dispose(); }### Answer: @Test public void testCreateBodyDataFileName() throws Exception { final File file1 = m_httpRecording.createBodyDataFileName(); final File file2 = m_httpRecording.createBodyDataFileName(); assertTrue(!file1.equals(file2)); }
### Question: ConnectionHandlerFactoryImplementation implements ConnectionHandlerFactory { public ConnectionHandler create(ConnectionDetails connectionDetails) { return new ConnectionHandlerImplementation(m_httpRecording, m_logger, m_regularExpressions, m_uriParser, m_attributeStringParser, m_postBodyStringEscaper, m_commentSource, connectionDetails); } ConnectionHandlerFactoryImplementation( HTTPRecording httpRecording, Logger logger, RegularExpressions regularExpressions, URIParser uriParser, AttributeStringParser attributeStringParser, StringEscaper postBodyStringEscaper, CommentSource commentSource); ConnectionHandler create(ConnectionDetails connectionDetails); }### Answer: @Test public void testFactory() { final ConnectionHandlerFactory factory = new ConnectionHandlerFactoryImplementation(m_httpRecording, m_logger, m_regularExpressions, m_uriParser, m_attributeStringParser, null, m_commentSource); final ConnectionHandler handler1 = factory.create(m_connectionDetails); final ConnectionHandler handler2 = factory.create(m_connectionDetails); assertNotSame(handler1, handler2); verifyNoMoreInteractions(m_httpRecording, m_logger, m_regularExpressions, m_uriParser, m_attributeStringParser); }
### Question: HTTPPluginThreadState extends SkeletonThreadLifeCycleListener implements PluginThreadListener { HTTPPluginThreadState(final PluginThreadContext threadContext, final SSLContextFactory sslContextFactory, final Sleeper slowClientSleeper, final TimeAuthority timeAuthority) throws PluginException { m_threadContext = threadContext; m_sslContextFactory = sslContextFactory; m_slowClientSleeper = slowClientSleeper; m_timeAuthority = new TimeAuthorityAdapter(timeAuthority); } HTTPPluginThreadState(final PluginThreadContext threadContext, final SSLContextFactory sslContextFactory, final Sleeper slowClientSleeper, final TimeAuthority timeAuthority); PluginThreadContext getThreadContext(); HTTPConnectionWrapper getConnectionWrapper(final URI uri); @Override void beginRun(); void setLastResponse(final HTTPResponse lastResponse); HTTPResponse getLastResponse(); }### Answer: @Test public void testHTTPPluginThreadState() throws Exception { final HTTPPluginThreadState pluginThreadState = new HTTPPluginThreadState(m_threadContext, m_sslContextFactory, m_sleeper, null); assertSame(m_threadContext, pluginThreadState.getThreadContext()); pluginThreadState.beginThread(); pluginThreadState.beginRun(); pluginThreadState.endRun(); pluginThreadState.beginRun(); final HTTPConnectionWrapper wrapper1 = pluginThreadState.getConnectionWrapper(new URI("http: assertNotNull(wrapper1); assertNotNull(m_sslContextFactory.getSSLContext().getSocketFactory()); final HTTPConnectionWrapper wrapper2 = pluginThreadState.getConnectionWrapper(new URI("https: assertNotNull(wrapper2); final HTTPConnectionWrapper wrapper3 = pluginThreadState.getConnectionWrapper(new URI("http: assertSame(wrapper1, wrapper3); assertNotSame(wrapper2, wrapper3); pluginThreadState.endRun(); pluginThreadState.beginRun(); final HTTPConnectionWrapper wrapper4 = pluginThreadState.getConnectionWrapper(new URI("http: assertNotSame(wrapper1, wrapper4); pluginThreadState.endRun(); pluginThreadState.endThread(); pluginThreadState.beginShutdown(); }
### Question: StatisticsTable { public StatisticsTable(final StatisticsView statisticsView, final StatisticsIndexMap statisticsIndexMap, final TestStatisticsMap testStatisticsMap) { m_statisticsView = statisticsView; m_testStatisticsMap = testStatisticsMap; m_periodIndex = statisticsIndexMap.getLongIndex("period"); } StatisticsTable(final StatisticsView statisticsView, final StatisticsIndexMap statisticsIndexMap, final TestStatisticsMap testStatisticsMap); final void print(final PrintWriter out, final long elapsedTime); }### Answer: @Test public void testStatisticsTable() throws Exception { final StringWriter expected = new StringWriter(); final PrintWriter in = new PrintWriter(expected); in.println(" A B A plus B A divided by "); in.println(" B "); in.println(); in.println("Test 3 1 2 3 0.50 "); in.println("Test 9 0 1 1 0.00 \"Test 9\""); in.println("Test 113 0 0 0 - \"Another test\""); in.println("Test 12345678 3 4 7 0.75 \"A test with a long name\""); in.println(); in.println("Totals 4 7 11 0.57 "); in.close(); final StatisticsTable table = new StatisticsTable(m_statisticsView, m_indexMap, m_testStatisticsMap); final StringWriter output = new StringWriter(); final PrintWriter out = new PrintWriter(output); table.print(out, 1234); out.close(); AssertUtilities.assertContains( output.getBuffer().toString(), expected.getBuffer().toString()); }
### Question: RollOnStartUp extends TriggeringPolicyBase<E> { @Override public boolean isTriggeringEvent(File activeFile, E event) { if (!m_firstTime) { return false; } m_firstTime = false; return activeFile.exists() && activeFile.length() > 0; } @Override boolean isTriggeringEvent(File activeFile, E event); }### Answer: @Test public void testRollOnStartUp() throws IOException { final File f = new File(getDirectory(), "foo"); final FileWriter out = new FileWriter(f); out.write("foo"); out.close(); final RollOnStartUp<Object> r1 = new RollOnStartUp<Object>(); assertTrue(r1.isTriggeringEvent(f, null)); assertFalse(r1.isTriggeringEvent(f, null)); assertFalse(r1.isTriggeringEvent(f, null)); assertTrue(new RollOnStartUp<Object>().isTriggeringEvent(f, null)); assertFalse(r1.isTriggeringEvent(f, null)); } @Test public void testRollOnStartUpNoFile() throws IOException { final File f = new File(getDirectory(), "foo"); final RollOnStartUp<Object> r1 = new RollOnStartUp<Object>(); assertFalse(r1.isTriggeringEvent(f, null)); } @Test public void testRollOnStartUpEmptyFile() throws IOException { final File f = new File(getDirectory(), "foo"); f.createNewFile(); final RollOnStartUp<Object> r1 = new RollOnStartUp<Object>(); assertFalse(r1.isTriggeringEvent(f, null)); }
### Question: BufferedEchoMessageEncoder extends EchoEncoder<ILoggingEvent> { @Override public void doEncode(ILoggingEvent event) throws IOException { outputStream.write(event.getMessage().getBytes()); outputStream.write(LINE_SEPARATOR_BYTES); } @Override void init(OutputStream os); @Override void doEncode(ILoggingEvent event); @Override void close(); int getBufferSize(); void setBufferSize(int bufferSize); }### Answer: @Test public void testDoEncode() throws Exception { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); m_encoder.init(baos); m_encoder.start(); when(m_event.getMessage()).thenReturn("hello"); m_encoder.doEncode(m_event); when(m_event.getMessage()).thenReturn("world"); m_encoder.doEncode(m_event); m_encoder.close(); assertEquals("hello" + CoreConstants.LINE_SEPARATOR + "world" + CoreConstants.LINE_SEPARATOR, baos.toString()); }
### Question: PortForwarderTCPProxyEngine extends AbstractTCPProxyEngine { public void run() { while (true) { final Socket localSocket; try { localSocket = accept(); } catch (IOException e) { UncheckedInterruptedException.ioException(e); logIOException(e); return; } final EndPoint sourceEndPoint = EndPoint.clientEndPoint(localSocket); final EndPoint targetEndPoint = m_connectionDetails.getRemoteEndPoint(); try { final Socket remoteSocket = getSocketFactory().createClientSocket(targetEndPoint); launchThreadPair(localSocket, remoteSocket, sourceEndPoint, targetEndPoint, m_connectionDetails.isSecure()); } catch (IOException e) { UncheckedInterruptedException.ioException(e); logIOException(e); try { localSocket.close(); } catch (IOException closeException) { throw new AssertionError(closeException); } } } } PortForwarderTCPProxyEngine(TCPProxyFilter requestFilter, TCPProxyFilter responseFilter, PrintWriter output, Logger logger, ConnectionDetails connectionDetails, boolean useColour, int timeout); PortForwarderTCPProxyEngine(TCPProxySocketFactory socketFactory, TCPProxyFilter requestFilter, TCPProxyFilter responseFilter, PrintWriter output, Logger logger, ConnectionDetails connectionDetails, boolean useColour, int timeout); void run(); }### Answer: @Test public void testTimeOut() throws Exception { final ConnectionDetails connectionDetails = new ConnectionDetails(new EndPoint("localhost", m_localPort), new EndPoint("wherever", 9999), false); final TCPProxyEngine engine = new PortForwarderTCPProxyEngine(m_requestFilter, m_responseFilter, m_out, m_logger, connectionDetails, false, 10); resetLogger(); engine.run(); verify(m_logger).error("Listen time out"); verifyNoMoreInteractions(m_logger); }
### Question: AbstractMainClass { protected AbstractMainClass(Logger logger, String usage) throws GrinderException { m_usage = new FixedWidthFormatter(FixedWidthFormatter.Align.LEFT, FixedWidthFormatter.Flow.WORD_WRAP, 80).format(usage); m_logger = logger; if (!JVM.getInstance().haveRequisites(m_logger)) { throw new LoggedInitialisationException("Unsupported JVM"); } } protected AbstractMainClass(Logger logger, String usage); }### Answer: @Test public void testAbstractMainClass() throws Exception { final Logger logger = mock(Logger.class); final String myUsage = "do some stuff"; final MyMainClass mainClass = new MyMainClass(logger, myUsage); assertSame(logger, mainClass.getLogger()); final String javaVersion = System.getProperty("java.version"); try { try { System.setProperty("java.version", "whatever"); new MyMainClass(logger, myUsage); fail("Expected VersionException"); } catch (VersionException e) { } try { System.setProperty("java.version", "1.3"); new MyMainClass(logger, myUsage); fail("Expected LoggedInitialisationException"); } catch (LoggedInitialisationException e) { AssertUtilities.assertContains(e.getMessage(), "Unsupported"); verify(logger).error(contains("incompatible version"), isA(JVM.class), isA(String.class)); } } finally { System.setProperty("java.version", javaVersion); } final LoggedInitialisationException barfError = mainClass.barfError("foo"); assertEquals("foo", barfError.getMessage()); verify(logger).error(contains("foo")); final LoggedInitialisationException barfUsage = mainClass.barfUsage(); AssertUtilities.assertContains(barfUsage.getMessage(), myUsage); verify(logger).error(contains(myUsage)); verifyNoMoreInteractions(logger); }
### Question: RegistryServerSync implements InitializingBean, DisposableBean, NotifyListener { public ConcurrentMap<String, ConcurrentMap<String, Map<String, URL>>> getRegistryCache() { return registryCache; } ConcurrentMap<String, ConcurrentMap<String, Map<String, URL>>> getRegistryCache(); @Override void afterPropertiesSet(); @Override void destroy(); @Override void notify(List<URL> urls); }### Answer: @Test public void testGetRegistryCache() { registryServerSync.getRegistryCache(); }
### Question: LoadBalanceController { @RequestMapping(value = "/{id}", method = RequestMethod.GET) public BalancingDTO detailLoadBalance(@PathVariable String id, @PathVariable String env) throws ParamValidationException { id = id.replace(Constants.ANY_VALUE, Constants.PATH_SEPARATOR); BalancingDTO balancingDTO = overrideService.findBalance(id); if (balancingDTO == null) { throw new ResourceNotFoundException("Unknown ID!"); } return balancingDTO; } @Autowired LoadBalanceController(OverrideService overrideService, ProviderService providerService); @RequestMapping(method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) boolean createLoadbalance(@RequestBody BalancingDTO balancingDTO, @PathVariable String env); @RequestMapping(value = "/{id}", method = RequestMethod.PUT) boolean updateLoadbalance(@PathVariable String id, @RequestBody BalancingDTO balancingDTO, @PathVariable String env); @RequestMapping(method = RequestMethod.GET) List<BalancingDTO> searchLoadbalances(@RequestParam(required = false) String service, @RequestParam(required = false) String application, @PathVariable String env); @RequestMapping(value = "/{id}", method = RequestMethod.GET) BalancingDTO detailLoadBalance(@PathVariable String id, @PathVariable String env); @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) boolean deleteLoadBalance(@PathVariable String id, @PathVariable String env); }### Answer: @Test public void detailLoadBalance() throws IOException { String id = "1"; ResponseEntity<String> response; response = restTemplate.getForEntity(url("/api/{env}/rules/balancing/{id}"), String.class, env, id); assertFalse("should return a fail response, when id is null", (Boolean) objectMapper.readValue(response.getBody(), Map.class).get("success")); BalancingDTO balancingDTO = new BalancingDTO(); when(overrideService.findBalance(id)).thenReturn(balancingDTO); response = restTemplate.getForEntity(url("/api/{env}/rules/balancing/{id}"), String.class, env, id); assertEquals(HttpStatus.OK, response.getStatusCode()); }
### Question: LoadBalanceController { @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) public boolean deleteLoadBalance(@PathVariable String id, @PathVariable String env) { if (id == null) { throw new IllegalArgumentException("Argument of id is null!"); } id = id.replace(Constants.ANY_VALUE, Constants.PATH_SEPARATOR); overrideService.deleteBalance(id); return true; } @Autowired LoadBalanceController(OverrideService overrideService, ProviderService providerService); @RequestMapping(method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) boolean createLoadbalance(@RequestBody BalancingDTO balancingDTO, @PathVariable String env); @RequestMapping(value = "/{id}", method = RequestMethod.PUT) boolean updateLoadbalance(@PathVariable String id, @RequestBody BalancingDTO balancingDTO, @PathVariable String env); @RequestMapping(method = RequestMethod.GET) List<BalancingDTO> searchLoadbalances(@RequestParam(required = false) String service, @RequestParam(required = false) String application, @PathVariable String env); @RequestMapping(value = "/{id}", method = RequestMethod.GET) BalancingDTO detailLoadBalance(@PathVariable String id, @PathVariable String env); @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) boolean deleteLoadBalance(@PathVariable String id, @PathVariable String env); }### Answer: @Test public void deleteLoadBalance() { String id = "1"; URI uri; ResponseEntity<String> response; response = restTemplate.exchange(url("/api/{env}/rules/balancing/{id}"), HttpMethod.DELETE, new HttpEntity<>(null), String.class, env, id); assertEquals(HttpStatus.OK, response.getStatusCode()); assertTrue(Boolean.valueOf(response.getBody())); }
### Question: AccessesController { @RequestMapping(value = "/{id}", method = RequestMethod.GET) public AccessDTO detailAccess(@PathVariable String id, @PathVariable String env) { id = id.replace(Constants.ANY_VALUE, Constants.PATH_SEPARATOR); AccessDTO accessDTO = routeService.findAccess(id); return accessDTO; } @Autowired AccessesController(RouteService routeService, ProviderService providerService); @RequestMapping(method = RequestMethod.GET) List<AccessDTO> searchAccess(@RequestParam(required = false) String service, @RequestParam(required = false) String application, @PathVariable String env); @RequestMapping(value = "/{id}", method = RequestMethod.GET) AccessDTO detailAccess(@PathVariable String id, @PathVariable String env); @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) void deleteAccess(@PathVariable String id, @PathVariable String env); @RequestMapping(method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) void createAccess(@RequestBody AccessDTO accessDTO, @PathVariable String env); @RequestMapping(value = "/{id}", method = RequestMethod.PUT) void updateAccess(@PathVariable String id, @RequestBody AccessDTO accessDTO, @PathVariable String env); }### Answer: @Test public void detailAccess() throws JsonProcessingException { String id = "1"; AccessDTO accessDTO = new AccessDTO(); when(routeService.findAccess(id)).thenReturn(accessDTO); ResponseEntity<String> response = restTemplate.getForEntity(url("/api/{env}/rules/access/{id}"), String.class, env, id); String exceptResponseBody = objectMapper.writeValueAsString(accessDTO); assertEquals(exceptResponseBody, response.getBody()); }
### Question: AccessesController { @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) public void deleteAccess(@PathVariable String id, @PathVariable String env) { id = id.replace(Constants.ANY_VALUE, Constants.PATH_SEPARATOR); routeService.deleteAccess(id); } @Autowired AccessesController(RouteService routeService, ProviderService providerService); @RequestMapping(method = RequestMethod.GET) List<AccessDTO> searchAccess(@RequestParam(required = false) String service, @RequestParam(required = false) String application, @PathVariable String env); @RequestMapping(value = "/{id}", method = RequestMethod.GET) AccessDTO detailAccess(@PathVariable String id, @PathVariable String env); @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) void deleteAccess(@PathVariable String id, @PathVariable String env); @RequestMapping(method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) void createAccess(@RequestBody AccessDTO accessDTO, @PathVariable String env); @RequestMapping(value = "/{id}", method = RequestMethod.PUT) void updateAccess(@PathVariable String id, @RequestBody AccessDTO accessDTO, @PathVariable String env); }### Answer: @Test public void deleteAccess() { String id = "1"; restTemplate.delete(url("/api/{env}/rules/access/{id}"), env, id); verify(routeService).deleteAccess(id); }
### Question: RegistryServerSync implements InitializingBean, DisposableBean, NotifyListener { @Override public void afterPropertiesSet() throws Exception { logger.info("Init Dubbo Admin Sync Cache..."); registry.subscribe(SUBSCRIBE, this); } ConcurrentMap<String, ConcurrentMap<String, Map<String, URL>>> getRegistryCache(); @Override void afterPropertiesSet(); @Override void destroy(); @Override void notify(List<URL> urls); }### Answer: @Test public void testAfterPropertiesSet() throws Exception { registryServerSync.afterPropertiesSet(); verify(registry).subscribe(any(URL.class), any(RegistryServerSync.class)); }
### Question: AccessesController { @RequestMapping(value = "/{id}", method = RequestMethod.PUT) public void updateAccess(@PathVariable String id, @RequestBody AccessDTO accessDTO, @PathVariable String env) { id = id.replace(Constants.ANY_VALUE, Constants.PATH_SEPARATOR); ConditionRouteDTO route = routeService.findConditionRoute(id); if (Objects.isNull(route)) { throw new ResourceNotFoundException("Unknown ID!"); } routeService.updateAccess(accessDTO); } @Autowired AccessesController(RouteService routeService, ProviderService providerService); @RequestMapping(method = RequestMethod.GET) List<AccessDTO> searchAccess(@RequestParam(required = false) String service, @RequestParam(required = false) String application, @PathVariable String env); @RequestMapping(value = "/{id}", method = RequestMethod.GET) AccessDTO detailAccess(@PathVariable String id, @PathVariable String env); @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) void deleteAccess(@PathVariable String id, @PathVariable String env); @RequestMapping(method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) void createAccess(@RequestBody AccessDTO accessDTO, @PathVariable String env); @RequestMapping(value = "/{id}", method = RequestMethod.PUT) void updateAccess(@PathVariable String id, @RequestBody AccessDTO accessDTO, @PathVariable String env); }### Answer: @Test public void updateAccess() throws IOException { AccessDTO accessDTO = new AccessDTO(); String id = "1"; restTemplate.put(url("/api/{env}/rules/access/{id}"), accessDTO, env, id); verify(routeService).findConditionRoute(id); ConditionRouteDTO conditionRouteDTO = mock(ConditionRouteDTO.class); when(routeService.findConditionRoute(id)).thenReturn(conditionRouteDTO); restTemplate.put(url("/api/{env}/rules/access/{id}"), accessDTO, env, id); verify(routeService).updateAccess(any(AccessDTO.class)); }
### Question: ConfigCenter { @Bean @DependsOn("governanceConfiguration") Registry getRegistry() { Registry registry = null; if (registryUrl == null) { if (StringUtils.isBlank(registryAddress)) { throw new ConfigurationException("Either config center or registry address is needed, please refer to https: } registryUrl = formUrl(registryAddress, registryGroup, username, password); } RegistryFactory registryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.class).getAdaptiveExtension(); registry = registryFactory.getRegistry(registryUrl); return registry; } }### Answer: @Test public void testGetRegistry() throws Exception { try { configCenter.getRegistry(); fail("should throw exception when registryAddress is blank"); } catch (ConfigurationException e) { } assertNull(ReflectionTestUtils.getField(configCenter, "registryUrl")); ReflectionTestUtils.setField(configCenter, "registryAddress", zkAddress); ReflectionTestUtils.setField(configCenter, "registryGroup", "dubbo"); ReflectionTestUtils.setField(configCenter, "username", "username"); ReflectionTestUtils.setField(configCenter, "password", "password"); configCenter.getRegistry(); Object registryUrl = ReflectionTestUtils.getField(configCenter, "registryUrl"); assertNotNull(registryUrl); assertEquals("127.0.0.1", ((URL) registryUrl).getHost()); }
### Question: ConfigCenter { @Bean @DependsOn("governanceConfiguration") MetaDataCollector getMetadataCollector() { MetaDataCollector metaDataCollector = new NoOpMetadataCollector(); if (metadataUrl == null) { if (StringUtils.isNotEmpty(metadataAddress)) { metadataUrl = formUrl(metadataAddress, metadataGroup, username, password); metadataUrl = metadataUrl.addParameter(CLUSTER_KEY, cluster); } } if (metadataUrl != null) { metaDataCollector = ExtensionLoader.getExtensionLoader(MetaDataCollector.class).getExtension(metadataUrl.getProtocol()); metaDataCollector.setUrl(metadataUrl); metaDataCollector.init(); } else { logger.warn("you are using dubbo.registry.address, which is not recommend, please refer to: https: } return metaDataCollector; } }### Answer: @Test public void testGetMetadataCollector() throws Exception { ReflectionTestUtils.setField(configCenter, "metadataAddress", ""); configCenter.getMetadataCollector(); assertNull(ReflectionTestUtils.getField(configCenter, "metadataUrl")); ReflectionTestUtils.setField(configCenter, "metadataAddress", zkAddress); ReflectionTestUtils.setField(configCenter, "metadataGroup", "dubbo"); ReflectionTestUtils.setField(configCenter, "username", "username"); ReflectionTestUtils.setField(configCenter, "password", "password"); configCenter.getMetadataCollector(); Object metadataUrl = ReflectionTestUtils.getField(configCenter, "metadataUrl"); assertNotNull(metadataUrl); assertEquals("127.0.0.1", ((URL) metadataUrl).getHost()); }
### Question: YamlParser { public static <T> T loadObject(String content, Class<T> type) { return yaml.loadAs(content, type); } static String dumpObject(Object object); static T loadObject(String content, Class<T> type); }### Answer: @Test public void parseLoadBalanceTest() throws IOException { try (InputStream yamlStream = this.getClass().getResourceAsStream("/LoadBalance.yml")) { DynamicConfigDTO overrideDTO = YamlParser.loadObject(streamToString(yamlStream), DynamicConfigDTO.class); assertEquals("v2.7", overrideDTO.getConfigVersion()); assertEquals(false, overrideDTO.isEnabled()); List<OverrideConfig> configs = overrideDTO.getConfigs(); assertEquals(2, configs.size()); OverrideConfig first = configs.get(0); assertEquals("0.0.0.0:20880", first.getAddresses().get(0)); assertEquals("provider", first.getSide()); Map<String, Object> parameters = first.getParameters(); assertEquals(1, parameters.size()); assertEquals(2000, parameters.get("timeout")); OverrideConfig second = configs.get(1); assertEquals("balancing", second.getType()); assertEquals(true, second.isEnabled()); parameters = second.getParameters(); assertEquals(2, parameters.size()); assertEquals("*", parameters.get("method")); assertEquals("random", parameters.get("strategy")); } }
### Question: CoderUtil { public static String MD5_16bit(String input) { String hash = MD5_32bit(input); if (hash == null) { return null; } return hash.substring(8, 24); } static String MD5_16bit(String input); static String MD5_32bit(String input); static String MD5_32bit(byte[] input); static String decodeBase64(String source); }### Answer: @Test public void MD5_16bit() { assertNull(CoderUtil.MD5_16bit(null)); String input = "dubbo"; String output = "2CC9DEED96FE012E"; assertEquals(output, CoderUtil.MD5_16bit(input)); }
### Question: CoderUtil { public static String MD5_32bit(String input) { if (input == null || input.length() == 0) { return null; } md.update(input.getBytes()); byte[] digest = md.digest(); String hash = convertToString(digest); return hash; } static String MD5_16bit(String input); static String MD5_32bit(String input); static String MD5_32bit(byte[] input); static String decodeBase64(String source); }### Answer: @Test public void MD5_32bit() { String input = null; assertNull(CoderUtil.MD5_32bit(input)); input = "dubbo"; String output = "AA4E1B8C2CC9DEED96FE012EF2E0752A"; assertEquals(output, CoderUtil.MD5_32bit(input)); } @Test public void MD5_32bit1() { byte[] input = null; assertNull(CoderUtil.MD5_32bit(input)); input = "dubbo".getBytes(); String output = "AA4E1B8C2CC9DEED96FE012EF2E0752A"; assertEquals(output, CoderUtil.MD5_32bit(input)); }
### Question: CoderUtil { public static String decodeBase64(String source) { return new String(Bytes.base642bytes(source)); } static String MD5_16bit(String input); static String MD5_32bit(String input); static String MD5_32bit(byte[] input); static String decodeBase64(String source); }### Answer: @Test public void decodeBase64() { try { CoderUtil.decodeBase64(null); fail("when param is null, this should throw exception"); } catch (Exception e) { } String input = "ZHViYm8="; String output = "dubbo"; assertEquals(output, CoderUtil.decodeBase64(input)); }
### Question: RegistryServerSync implements InitializingBean, DisposableBean, NotifyListener { @Override public void destroy() throws Exception { registry.unsubscribe(SUBSCRIBE, this); } ConcurrentMap<String, ConcurrentMap<String, Map<String, URL>>> getRegistryCache(); @Override void afterPropertiesSet(); @Override void destroy(); @Override void notify(List<URL> urls); }### Answer: @Test public void testDestroy() throws Exception { registryServerSync.destroy(); verify(registry).unsubscribe(any(URL.class), any(RegistryServerSync.class)); }
### Question: UrlUtils { public static String paramsMapToString(Map<String, String[]> params) { StringBuilder paramsString = new StringBuilder(); for (Entry<String, String[]> param : params.entrySet()) { if (paramsString != null) { paramsString.append("&"); } paramsString.append(param.getKey()); paramsString.append("="); for (int i = 0; i < param.getValue().length; i++) { if (i == 0) { paramsString.append(param.getValue()[i]); } else { paramsString.append(","); paramsString.append(param.getValue()[i]); } } } return paramsString.toString(); } static String paramsMapToString(Map<String, String[]> params); static String arrayToString(String[] values); }### Answer: @Test public void testParamsMapToString() { Map<String, String[]> params = new HashMap<>(); params.put("a", new String[]{"1", "2", "3"}); params.put("b", new String[]{"8", "7", "6"}); String result = UrlUtils.paramsMapToString(params); Assert.assertEquals(result, "&a=1,2,3&b=8,7,6"); }
### Question: UrlUtils { public static String arrayToString(String[] values) { StringBuilder paramsString = new StringBuilder(); for (int i = 0; i < values.length; i++) { if (i == 0) { paramsString.append(values[i]); } else { paramsString.append(","); paramsString.append(values[i]); } } return paramsString.toString(); } static String paramsMapToString(Map<String, String[]> params); static String arrayToString(String[] values); }### Answer: @Test public void testArrayToString() { String[] strArr = {"1", "2", "3"}; String result = UrlUtils.arrayToString(strArr); Assert.assertEquals(result, "1,2,3"); }
### Question: ConsulMetaDataCollector implements MetaDataCollector { @Override public String getConsumerMetaData(MetadataIdentifier key) { return doGetMetaData(key); } @Override URL getUrl(); @Override void setUrl(URL url); @Override void init(); @Override String getProviderMetaData(MetadataIdentifier key); @Override String getConsumerMetaData(MetadataIdentifier key); }### Answer: @Test public void testGetConsumerMetaData() { MetadataIdentifier identifier = buildIdentifier(false); Map<String, String> consumerParams = new HashMap<>(); consumerParams.put("k1", "v1"); consumerParams.put("k2", "1"); consumerParams.put("k3", "true"); String metadata = gson.toJson(consumerParams); consulMetaDataCollector.getClient().setKVValue(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), metadata); String consumerMetaData = consulMetaDataCollector.getConsumerMetaData(identifier); Map<String, String> retParams = gson.fromJson(consumerMetaData, new TypeToken<Map<String, String>>() { }.getType()); Assert.assertEquals(consumerParams, retParams); } @Test public void testGetConsumerMetaData() { MetadataIdentifier identifier = buildIdentifier(false); Map<String, String> consumerParams = new HashMap<>(); consumerParams.put("k1", "v1"); consumerParams.put("k2", "1"); consumerParams.put("k3", "true"); String metadata = gson.toJson(consumerParams); consulMetaDataCollector.getClient().setKVValue(identifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY), metadata); String consumerMetaData = consulMetaDataCollector.getConsumerMetaData(identifier); Map<String, String> retParams = gson.fromJson(consumerMetaData, new TypeToken<Map<String, String>>() { }.getType()); Assert.assertEquals(consumerParams, retParams); }
### Question: ZookeeperConfiguration implements GovernanceConfiguration { @Override public boolean deleteConfig(String key) { return deleteConfig(null, key); } @Override void setUrl(URL url); @Override URL getUrl(); @Override void init(); @Override String setConfig(String key, String value); @Override String getConfig(String key); @Override boolean deleteConfig(String key); @Override String setConfig(String group, String key, String value); @Override String getConfig(String group, String key); @Override boolean deleteConfig(String group, String key); @Override String getPath(String key); @Override String getPath(String group, String key); }### Answer: @Test public void testDeleteConfig() { assertEquals(false, configuration.deleteConfig("not_exist_key")); configuration.setConfig("test_delete", "test_value"); assertEquals("test_value", configuration.getConfig("test_delete")); configuration.deleteConfig("test_delete"); assertEquals(null, configuration.getConfig("test_delete")); assertEquals(false, configuration.deleteConfig("test_group", "not_exist_key")); configuration.setConfig("test_group", "test_delete", "test_value"); assertEquals("test_value", configuration.getConfig("test_group", "test_delete")); configuration.deleteConfig("test_group", "test_delete"); assertEquals(null, configuration.getConfig("test_group", "test_delete")); try { configuration.deleteConfig(null); fail("should throw IllegalArgumentException for null key"); } catch (IllegalArgumentException e) { } }
### Question: ZookeeperConfiguration implements GovernanceConfiguration { @Override public String getPath(String key) { return getNodePath(key, null); } @Override void setUrl(URL url); @Override URL getUrl(); @Override void init(); @Override String setConfig(String key, String value); @Override String getConfig(String key); @Override boolean deleteConfig(String key); @Override String setConfig(String group, String key, String value); @Override String getConfig(String group, String key); @Override boolean deleteConfig(String group, String key); @Override String getPath(String key); @Override String getPath(String group, String key); }### Answer: @Test public void testGetPath() { assertEquals(Constants.PATH_SEPARATOR + Constants.DEFAULT_ROOT + Constants.PATH_SEPARATOR + "test_key", configuration.getPath("test_key")); try { configuration.getPath(null); fail("should throw IllegalArgumentException for null path"); } catch (IllegalArgumentException e) { } }
### Question: JSPackagerClient implements ReconnectingWebSocket.MessageCallback { public void close() { mWebSocket.closeQuietly(); } JSPackagerClient(String clientId, PackagerConnectionSettings settings, Map<String, RequestHandler> requestHandlers); JSPackagerClient( String clientId, PackagerConnectionSettings settings, Map<String, RequestHandler> requestHandlers, @Nullable ReconnectingWebSocket.ConnectionCallback connectionCallback); void init(); void close(); @Override void onMessage(String text); @Override void onMessage(ByteString bytes); }### Answer: @Test public void test_onDisconnection_ShouldTriggerDisconnectionCallback() throws IOException { ConnectionCallback connectionHandler = mock(ConnectionCallback.class); RequestHandler handler = mock(RequestHandler.class); final JSPackagerClient client = new JSPackagerClient("test_client", mSettings, new HashMap<String,RequestHandler>(), connectionHandler); client.close(); verify(connectionHandler, never()).onConnected(); verify(connectionHandler, times(1)).onDisconnected(); verify(handler, never()).onNotification(any()); verify(handler, never()).onRequest(any(), any(Responder.class)); }
### Question: UsersService { public void add(@Valid User newUser) { em.persist(newUser); } User isValid(String username, String password); Set<User> getAll(); void add(@Valid User newUser); boolean update(User updated); void remove(Long id); Optional<User> get(Long id); List<String> getNames(); }### Answer: @Test public void testCreateUser(@ArquillianResource URL resource) throws Exception { URL apiUrl = new URL(resource, "resources/users"); JsonObject user = Json.createObjectBuilder() .add("name", "Marcus") .add("email", "marcus_1982@jee8ng.org") .add("credential", credential("marcus", "1234")) .build(); Response initiallyCreated = ClientBuilder.newClient().target(apiUrl.toURI()) .request(MediaType.APPLICATION_JSON) .post(Entity.json(user)); assertThat(initiallyCreated.getStatus(), is(201)); String location = initiallyCreated.getHeaderString("Location"); assertNotNull(location); }
### Question: UsersService { public Optional<User> get(Long id) { User found = em.find(User.class, id); return found != null ? Optional.of(found) : Optional.empty(); } User isValid(String username, String password); Set<User> getAll(); void add(@Valid User newUser); boolean update(User updated); void remove(Long id); Optional<User> get(Long id); List<String> getNames(); }### Answer: @Test public void testGetUsers(@ArquillianResource URL resource) throws Exception { URL obj = new URL(resource, "resources/users"); when().get(obj.toURI()).then() .statusCode(200); }
### Question: AmazonSnsPushMessageSubscriber implements PushMessageSubscriber { @Override public String refreshDeviceEndpointArn(final String existingDeviceEndpointArn, final String userDeviceToken, final String applicationArn) { Assert.hasText(existingDeviceEndpointArn, "Null or empty text was passed as an argument for parameter 'existingDeviceEndpointArn'."); assertValidDeviceTokenAndAplicationArn(userDeviceToken, applicationArn); return refreshDeviceEndpointArnInternal(existingDeviceEndpointArn, userDeviceToken, applicationArn); } AmazonSnsPushMessageSubscriber(final AmazonSnsApiCommunicator amazonSnsApiCommunicator); @Override String refreshDeviceEndpointArn(final String existingDeviceEndpointArn, final String userDeviceToken, final String applicationArn); @Override String registerDeviceEndpointArn(final String userDeviceToken, final String applicationArn); }### Answer: @Test public void testRefreshDeviceEndpointArnWithInvalidArguments() { Assertions.assertThatThrownBy(() -> messageSubscriber.refreshDeviceEndpointArn(null, uuid(), uuid())) .isInstanceOf(IllegalArgumentException.class); Assertions.assertThatThrownBy(() -> messageSubscriber.refreshDeviceEndpointArn(uuid(), null, uuid())) .isInstanceOf(IllegalArgumentException.class); Assertions.assertThatThrownBy(() -> messageSubscriber.refreshDeviceEndpointArn(uuid(), uuid(), null)) .isInstanceOf(IllegalArgumentException.class); } @Test public void testRefreshDeviceEndpointArnExistingTokenValid() { final String existingDeviceEndpointArn = uuid(); final String userDeviceToken = uuid(); final String applicationArn = uuid(); final GetDeviceEndpointAttributesRequest request = new GetDeviceEndpointAttributesRequest(existingDeviceEndpointArn); final GetDeviceEndpointAttributesResponse response = new GetDeviceEndpointAttributesResponse(existingDeviceEndpointArn,userDeviceToken,true,true); when(amazonSnsApiCommunicator.getDeviceEndpointAttributes(request)).thenReturn(response); assertThat( messageSubscriber.refreshDeviceEndpointArn(existingDeviceEndpointArn, userDeviceToken, applicationArn)).isEqualTo(existingDeviceEndpointArn); verify(amazonSnsApiCommunicator).getDeviceEndpointAttributes(request); }
### Question: DefaultSmsSenderProvider implements SmsSenderProvider { @Override public Optional<SimpleSmsSender> lookupSimpleSmsMessageSenderFor(final String providerType) { assertValidProviderTypeArgument(providerType); return Optional.ofNullable(registeredSimpleSmsSenders.get(providerType)); } DefaultSmsSenderProvider(final List<SimpleSmsSenderRegistry> simpleSmsSenderRegistries, final List<TemplatedSmsSenderRegistry> templatedSmsSenderRegistries); @Override Optional<SimpleSmsSender> lookupSimpleSmsMessageSenderFor(final String providerType); @Override Optional<TemplatedSmsSender> lookupTemplatedSmsMessageSenderFor(final String providerType); }### Answer: @Test public void testLookupSimpleSmsMessageSenderFor() { assertThatThrownBy(() -> smsSenderProvider.lookupSimpleSmsMessageSenderFor(null)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> smsSenderProvider.lookupSimpleSmsMessageSenderFor("")) .isInstanceOf(IllegalArgumentException.class); } @Test public void testLookupSimpleSmsMessageSenderForMissing() { assertThat(smsSenderProvider.lookupSimpleSmsMessageSenderFor(simpleSmsSenderRegistry.name() + "_test")) .isEmpty(); } @Test public void testLookupSimpleSmsMessageSenderForPresent() { assertThat(smsSenderProvider.lookupSimpleSmsMessageSenderFor(simpleSmsSenderRegistry.name())) .isPresent() .contains(simpleSmsSenderRegistry.sender()); }
### Question: DefaultSmsSenderProvider implements SmsSenderProvider { @Override public Optional<TemplatedSmsSender> lookupTemplatedSmsMessageSenderFor(final String providerType) { assertValidProviderTypeArgument(providerType); return Optional.ofNullable(registeredTemplatedSmsSender.get(providerType)); } DefaultSmsSenderProvider(final List<SimpleSmsSenderRegistry> simpleSmsSenderRegistries, final List<TemplatedSmsSenderRegistry> templatedSmsSenderRegistries); @Override Optional<SimpleSmsSender> lookupSimpleSmsMessageSenderFor(final String providerType); @Override Optional<TemplatedSmsSender> lookupTemplatedSmsMessageSenderFor(final String providerType); }### Answer: @Test public void testLookupTemplatedSmsMessageSenderFor() { assertThatThrownBy(() -> smsSenderProvider.lookupTemplatedSmsMessageSenderFor(null)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> smsSenderProvider.lookupTemplatedSmsMessageSenderFor("")) .isInstanceOf(IllegalArgumentException.class); } @Test public void testLookupTemplatedSmsMessageSenderForrMissing() { assertThat(smsSenderProvider.lookupTemplatedSmsMessageSenderFor(templatedSmsSenderRegistry.name() + "_test")) .isEmpty(); } @Test public void testLookupTemplatedSmsMessageSenderForPresent() { assertThat(smsSenderProvider.lookupTemplatedSmsMessageSenderFor(templatedSmsSenderRegistry.name())) .isPresent() .contains(templatedSmsSenderRegistry.sender()); }
### Question: SmsNotificationServiceImpl extends AbstractNotificationServiceImpl<SmsNotification> implements SmsNotificationService { @Transactional @Nonnull @Override public SmsNotification createSmsNotification(@Nonnull final SmsNotificationDto smsNotificationDto) { assertSmsNotificationDto(smsNotificationDto); LOGGER.debug("Creating SMS notification for DTO - {}", smsNotificationDto); SmsNotification smsNotification = new SmsNotification(true); smsNotificationDto.updateDomainEntityProperties(smsNotification); smsNotification = smsNotificationRepository.save(smsNotification); LOGGER.debug("Successfully created SMS notification with id - {}, notification - {}", smsNotification.getId(), smsNotification); return smsNotification; } SmsNotificationServiceImpl(); @Transactional @Nonnull @Override SmsNotification createSmsNotification(@Nonnull final SmsNotificationDto smsNotificationDto); @Override SmsNotification getSmsNotificationForProcessing(final Long notificationId); SmsNotificationRepository getSmsNotificationRepository(); void setSmsNotificationRepository(final SmsNotificationRepository smsNotificationRepository); }### Answer: @Test public void testCreateEmailNotificationWithInvalidArguments() { final SmsNotificationDto smsNotificationDto = getServicesImplTestHelper().createSmsNotificationDto(); resetAll(); replayAll(); try { smsNotificationService.createSmsNotification(null); fail("Exception should be thrown"); } catch (final IllegalArgumentException ex) { } try { smsNotificationService.createSmsNotification(new SmsNotificationDto(null, smsNotificationDto.getContent(), smsNotificationDto.getClientIpAddress(), NotificationProviderType.TWILLIO) ); fail("Exception should be thrown"); } catch (final IllegalArgumentException ex) { } verifyAll(); } @Test public void testCreateEmailNotification() { final SmsNotificationDto notificationDto = getServicesImplTestHelper().createSmsNotificationDto(); resetAll(); expect(smsNotificationRepository.save(isA(SmsNotification.class))).andAnswer(() -> (SmsNotification) getCurrentArguments()[0]).once(); replayAll(); final SmsNotification notification = smsNotificationService.createSmsNotification(notificationDto); getServicesImplTestHelper().assertSmsNotification(notification, notificationDto); }
### Question: EmailNotificationServiceImpl extends AbstractNotificationServiceImpl<EmailNotification> implements EmailNotificationService { @Transactional @Nonnull @Override public EmailNotification createEmailNotification(@Nonnull final EmailNotificationDto emailNotificationDto) { assertEmailNotificationDto(emailNotificationDto); LOGGER.debug("Creating email notification for DTO - {} and property dtos - {}", emailNotificationDto, emailNotificationDto.getProperties()); EmailNotification emailNotification = new EmailNotification(true); emailNotification.setFileAttachments(emailNotificationDto.getFileAttachments()); emailNotificationDto.updateDomainEntityProperties(emailNotification); emailNotification = emailNotificationRepository.save(emailNotification); associateNotificationWithUser(emailNotificationDto, emailNotification); LOGGER.debug("Successfully created email notification with id - {}, email notification - {}", emailNotification.getId(), emailNotification); return emailNotification; } EmailNotificationServiceImpl(); @Transactional @Nonnull @Override EmailNotification createEmailNotification(@Nonnull final EmailNotificationDto emailNotificationDto); @Override EmailNotification getEmailNotificationForProcessing(final Long notificationId); void setEmailNotificationRepository(final EmailNotificationRepository emailNotificationRepository); }### Answer: @Test public void testCreateEmailNotificationWithInvalidArguments() { final EmailNotificationDto emailNotificationDto = getServicesImplTestHelper().createEmailNotificationDto(); final List<NotificationPropertyDto> properties = getServicesImplTestHelper().createNotificationPropertyDtos(2); resetAll(); replayAll(); try { emailNotificationService.createEmailNotification(null); fail("Exception should be thrown"); } catch (final IllegalArgumentException ex) { } } @Test public void testCreateEmailNotification_WhenUserUuidNull() { final EmailNotificationDto emailNotificationDto = getServicesImplTestHelper().createEmailNotificationDto(); final EmailNotification emailNotification = getServicesImplTestHelper().createEmailNotification(); emailNotification.setId(1L); resetAll(); expect(emailNotificationRepository.save(isA(EmailNotification.class))).andReturn(emailNotification); applicationEventDistributionService.publishAsynchronousEvent(new StartSendingNotificationEvent(emailNotification.getId(), emailNotificationDto.getProperties())); replayAll(); final EmailNotification result = emailNotificationService.createEmailNotification(emailNotificationDto); getServicesImplTestHelper().assertEmailNotification(result, emailNotificationDto); }