method2testcases
stringlengths
118
3.08k
### Question: Statistics { public Vector getValues() { return (Vector)v.clone(); } Statistics(); Statistics(Iterable<Double> values); void clearAll(); int count(); double max(); double min(); double mean(); double median(); double mode(); int modeOccurrenceCount(); double range(); double standardDeviation(); Vector getValues(); void addValue(Double double1); void addValue(double d); void setValues(Iterable<Double> vals); void setValues(Calculable[] calcs); void removeValues(double d, boolean removeAll); void removeValues(Double double1, boolean removeAll); void removeValue(int location); void removeValues(Double low, Double high); void removeValues(double low, double high); double sum(); }### Answer: @Test public void testGetValues() { Statistics stat = new Statistics(); Assert.assertEquals(new Vector(), stat.getValues()); for (int i = 0; i < 10; i++) { Vector<Double> v = new Vector<>(); int count = (int) (Math.random() * 1000); for (int j = 0; j < count; j++) { double d = Math.random(); stat.addValue(d); v.add(d); } Assert.assertEquals(v, stat.getValues()); stat.clearAll(); Assert.assertEquals(new Vector(), stat.getValues()); } Vector<Double> v = new Vector<>(); stat.setValues(v); Assert.assertEquals(v, stat.getValues()); Assert.assertNotSame(v, stat.getValues()); }
### Question: WatchDataSourceImpl implements WatchDataSource, ServerProxyTrust { public ThresholdValues getThresholdValues() { ThresholdValues thresholdValues; if(thresholdManager!=null) thresholdValues = thresholdManager.getThresholdValues(); else thresholdValues = new ThresholdValues(); return thresholdValues; } WatchDataSourceImpl(); WatchDataSourceImpl(String id, Configuration config); void initialize(); WatchDataSource export(); WatchDataSource getProxy(); void setConfiguration(Configuration config); void unexport(boolean force); String getID(); void setID(String id); void setMaxSize(int size); void clear(); int getMaxSize(); int getCurrentSize(); @SuppressWarnings("unchecked") void addCalculable(Calculable calculable); Calculable[] getCalculable(); Calculable[] getCalculable(String id); Calculable[] getCalculable(long from, long to); Calculable getLastCalculable(); ThresholdValues getThresholdValues(); void setThresholdValues(ThresholdValues tValues); void close(); void setView(String viewClass); String getView(); TrustVerifier getProxyVerifier(); boolean addWatchDataReplicator(WatchDataReplicator replicator); boolean removeWatchDataReplicator(WatchDataReplicator replicator); WatchDataReplicator[] getWatchDataReplicators(); final static int DEFAULT_COLLECTION_SIZE; final static int MAX_COLLECTION_SIZE; }### Answer: @Test public void testGetThresholdValues() throws Exception { WatchDataSourceImpl impl = new WatchDataSourceImpl(); impl.setThresholdManager(new BoundedThresholdManager("watch")); impl.setID("watch"); impl.setConfiguration(EmptyConfiguration.INSTANCE); ThresholdValues tv = impl.getThresholdValues(); Assert.assertNotNull(tv); tv = new ThresholdValues(); impl.setThresholdValues(tv); Assert.assertSame(tv, impl.getThresholdValues()); impl.close(); }
### Question: WatchDataSourceImpl implements WatchDataSource, ServerProxyTrust { public void setThresholdValues(ThresholdValues tValues) { if(thresholdManager!=null) thresholdManager.setThresholdValues(tValues); } WatchDataSourceImpl(); WatchDataSourceImpl(String id, Configuration config); void initialize(); WatchDataSource export(); WatchDataSource getProxy(); void setConfiguration(Configuration config); void unexport(boolean force); String getID(); void setID(String id); void setMaxSize(int size); void clear(); int getMaxSize(); int getCurrentSize(); @SuppressWarnings("unchecked") void addCalculable(Calculable calculable); Calculable[] getCalculable(); Calculable[] getCalculable(String id); Calculable[] getCalculable(long from, long to); Calculable getLastCalculable(); ThresholdValues getThresholdValues(); void setThresholdValues(ThresholdValues tValues); void close(); void setView(String viewClass); String getView(); TrustVerifier getProxyVerifier(); boolean addWatchDataReplicator(WatchDataReplicator replicator); boolean removeWatchDataReplicator(WatchDataReplicator replicator); WatchDataReplicator[] getWatchDataReplicators(); final static int DEFAULT_COLLECTION_SIZE; final static int MAX_COLLECTION_SIZE; }### Answer: @Test public void testSetThresholdValues() throws Exception { WatchDataSourceImpl impl = new WatchDataSourceImpl(); impl.setID("watch"); impl.setThresholdManager(new BoundedThresholdManager("watch")); impl.setConfiguration(EmptyConfiguration.INSTANCE); ThresholdValues tv = new ThresholdValues(); impl.setThresholdValues(tv); Assert.assertSame(tv, impl.getThresholdValues()); impl.setThresholdValues(null); Assert.assertSame(tv, impl.getThresholdValues()); impl.close(); }
### Question: WatchDataSourceImpl implements WatchDataSource, ServerProxyTrust { public String getView() { return (viewClass); } WatchDataSourceImpl(); WatchDataSourceImpl(String id, Configuration config); void initialize(); WatchDataSource export(); WatchDataSource getProxy(); void setConfiguration(Configuration config); void unexport(boolean force); String getID(); void setID(String id); void setMaxSize(int size); void clear(); int getMaxSize(); int getCurrentSize(); @SuppressWarnings("unchecked") void addCalculable(Calculable calculable); Calculable[] getCalculable(); Calculable[] getCalculable(String id); Calculable[] getCalculable(long from, long to); Calculable getLastCalculable(); ThresholdValues getThresholdValues(); void setThresholdValues(ThresholdValues tValues); void close(); void setView(String viewClass); String getView(); TrustVerifier getProxyVerifier(); boolean addWatchDataReplicator(WatchDataReplicator replicator); boolean removeWatchDataReplicator(WatchDataReplicator replicator); WatchDataReplicator[] getWatchDataReplicators(); final static int DEFAULT_COLLECTION_SIZE; final static int MAX_COLLECTION_SIZE; }### Answer: @Test public void testGetView() throws Exception { WatchDataSourceImpl impl = new WatchDataSourceImpl(); impl.setID("watch"); impl.setConfiguration(EmptyConfiguration.INSTANCE); Assert.assertEquals(null, impl.getView()); impl.setView("abcd"); Assert.assertEquals("abcd", impl.getView()); impl.close(); }
### Question: WatchDataSourceImpl implements WatchDataSource, ServerProxyTrust { public void setView(String viewClass) { this.viewClass = viewClass; } WatchDataSourceImpl(); WatchDataSourceImpl(String id, Configuration config); void initialize(); WatchDataSource export(); WatchDataSource getProxy(); void setConfiguration(Configuration config); void unexport(boolean force); String getID(); void setID(String id); void setMaxSize(int size); void clear(); int getMaxSize(); int getCurrentSize(); @SuppressWarnings("unchecked") void addCalculable(Calculable calculable); Calculable[] getCalculable(); Calculable[] getCalculable(String id); Calculable[] getCalculable(long from, long to); Calculable getLastCalculable(); ThresholdValues getThresholdValues(); void setThresholdValues(ThresholdValues tValues); void close(); void setView(String viewClass); String getView(); TrustVerifier getProxyVerifier(); boolean addWatchDataReplicator(WatchDataReplicator replicator); boolean removeWatchDataReplicator(WatchDataReplicator replicator); WatchDataReplicator[] getWatchDataReplicators(); final static int DEFAULT_COLLECTION_SIZE; final static int MAX_COLLECTION_SIZE; }### Answer: @Test public void testSetView() throws Exception { WatchDataSourceImpl impl = new WatchDataSourceImpl(); impl.setID("watch"); impl.setConfiguration(EmptyConfiguration.INSTANCE); impl.setView("abcd"); Assert.assertEquals("abcd", impl.getView()); impl.setView(""); Assert.assertEquals("", impl.getView()); impl.setView(null); Assert.assertEquals(null, impl.getView()); impl.close(); }
### Question: PeriodicWatch extends ThresholdWatch implements PeriodicWatchMBean { public long getPeriod() { return (period); } PeriodicWatch(String id); PeriodicWatch(String id, Configuration config); PeriodicWatch(WatchDataSource watchDataSource, String id); void start(); void stop(); long getPeriod(); void setPeriod(long newPeriod); static final long DEFAULT_PERIOD; }### Answer: @Test public void testGetPeriod() { MyPeriodicWatch watch = new MyPeriodicWatch("watch"); Assert.assertEquals(PeriodicWatch.DEFAULT_PERIOD, watch.getPeriod()); for (int i = 0; i < 10; i++) { long value = Math.round(Math.random() * 100) + 1; watch.setPeriod(value); Assert.assertEquals(value, watch.getPeriod()); } Utils.close(watch.getWatchDataSource()); }
### Question: PeriodicWatch extends ThresholdWatch implements PeriodicWatchMBean { public void start() { long now = System.currentTimeMillis(); stop(); watchTimer = new Timer(true); watchTimer.schedule(new PeriodicTask(), new Date(now+period), period); } PeriodicWatch(String id); PeriodicWatch(String id, Configuration config); PeriodicWatch(WatchDataSource watchDataSource, String id); void start(); void stop(); long getPeriod(); void setPeriod(long newPeriod); static final long DEFAULT_PERIOD; }### Answer: @Test public void testStart() { MyPeriodicWatch watch = new MyPeriodicWatch("watch"); watch.setPeriod(500); watch.stop(); watch.start(); Utils.sleep(5000); watch.stop(); Assert.assertTrue(watch.log().length() >= 8); Assert.assertTrue(watch.log().length() <= 12); watch.log().delete(0, watch.log().length()); watch.start(); watch.stop(); Utils.sleep(5000); Assert.assertTrue(watch.log().length() == 0); watch.start(); Utils.sleep(5000); watch.stop(); Assert.assertTrue(watch.log().length() >= 8); Assert.assertTrue(watch.log().length() <= 12); watch.log().delete(0, watch.log().length()); for (int i = 0; i < 1000; i++) { watch.start(); } for (int i = 0; i < 50; i++) { watch.start(); Utils.sleep(100); } Assert.assertTrue(watch.log().length() == 0); Utils.sleep(5000); watch.stop(); Assert.assertTrue(watch.log().length() >= 8); Assert.assertTrue(watch.log().length() <= 12); watch.log().delete(0, watch.log().length()); Utils.close(watch.getWatchDataSource()); }
### Question: PeriodicWatch extends ThresholdWatch implements PeriodicWatchMBean { public void stop() { if(watchTimer != null) watchTimer.cancel(); } PeriodicWatch(String id); PeriodicWatch(String id, Configuration config); PeriodicWatch(WatchDataSource watchDataSource, String id); void start(); void stop(); long getPeriod(); void setPeriod(long newPeriod); static final long DEFAULT_PERIOD; }### Answer: @Test public void testStop() { MyPeriodicWatch watch = new MyPeriodicWatch("watch"); watch.start(); watch.setPeriod(500); Utils.sleep(5000); watch.stop(); Assert.assertTrue(watch.log().length() >= 8); Assert.assertTrue(watch.log().length() <= 12); watch.log().delete(0, watch.log().length()); Utils.sleep(2000); Assert.assertTrue(watch.log().length() == 0); watch.stop(); Utils.sleep(2000); Assert.assertTrue(watch.log().length() == 0); watch.start(); Utils.sleep(5000); for (int i = 0; i < 100; i++) { watch.stop(); } Assert.assertTrue(watch.log().length() >= 8); Assert.assertTrue(watch.log().length() <= 12); watch.log().delete(0, watch.log().length()); for (int i = 0; i < 1000; i++) { watch.stop(); } Utils.close(watch.getWatchDataSource()); }
### Question: Statistics { public void setValues(Iterable<Double> vals) { if(vals==null) throw new IllegalArgumentException("vector is null"); v.clear(); for(Double d : vals) v.add(d); } Statistics(); Statistics(Iterable<Double> values); void clearAll(); int count(); double max(); double min(); double mean(); double median(); double mode(); int modeOccurrenceCount(); double range(); double standardDeviation(); Vector getValues(); void addValue(Double double1); void addValue(double d); void setValues(Iterable<Double> vals); void setValues(Calculable[] calcs); void removeValues(double d, boolean removeAll); void removeValues(Double double1, boolean removeAll); void removeValue(int location); void removeValues(Double low, Double high); void removeValues(double low, double high); double sum(); }### Answer: @Test public void testSetValues() { Statistics stat = new Statistics(); for (int i = 0; i < 10; i++) { Vector<Double> v = new Vector<>(); int count = (int) (Math.random() * 100); for (int j = 0; j < count; j++) { v.add(Math.random()); stat.setValues(v); Assert.assertEquals(v, stat.getValues()); Assert.assertNotSame(v, stat.getValues()); } } List<Double> v = new ArrayList<>(); stat.setValues(v); Assert.assertEquals(0, stat.count()); v.add((double) 0); Assert.assertEquals(0, stat.count()); try { stat.setValues((List<Double>)null); Assert.fail("IllegalArgumentException expected but not thrown"); } catch (IllegalArgumentException e) { } }
### Question: WatchDataSourceRegistry implements WatchRegistry { public void closeAll() { Watch[] watches = watchRegistry.toArray(new Watch[0]); for(Watch w : watches) { if(w instanceof PeriodicWatch) ((PeriodicWatch)w).stop(); try { WatchDataSource wd = w.getWatchDataSource(); if (wd != null) wd.close(); watchRegistry.remove(w); } catch (Exception e) { logger.warn("Closing WatchDataSource", e); } } } void deregister(Watch... watches); void closeAll(); void register(Watch... watches); void addThresholdListener(String id, ThresholdListener thresholdListener); void removeThresholdListener(String id, ThresholdListener thresholdListener); Watch findWatch(String id); WatchDataSource[] fetch(); WatchDataSource fetch(String id); void setServiceBeanContext(ServiceBeanContext context); }### Answer: @Test public void testCloseAll() { WatchDataSourceRegistry registry = new WatchDataSourceRegistry(); int[] counts = new int[] {0, 1, 10, 100}; for (int count : counts) { Collection<Watch> watches = new ArrayList<Watch>(); for (int j = 0; j < count; j++) { String id = "watch" + j; LoggingWatchDataSource ds = new LoggingWatchDataSource( id, EmptyConfiguration.INSTANCE); Watch watch = new GaugeWatch(ds, id); watches.add(watch); } for (Watch watch : watches) { registry.register(watch); } registry.closeAll(); for (Watch watch : watches) { LoggingWatchDataSource ds = (LoggingWatchDataSource) watch.getWatchDataSource(); checkLog(ds.log(), "close()"); } for (Watch watch : watches) { registry.deregister(watch); LoggingWatchDataSource ds = (LoggingWatchDataSource) watch.getWatchDataSource(); checkLog(ds.log(), "close()"); } registry.closeAll(); for (Watch watch : watches) { LoggingWatchDataSource ds = (LoggingWatchDataSource) watch.getWatchDataSource(); checkLog(ds.log(), ""); } } }
### Question: WatchDataSourceRegistry implements WatchRegistry { public Watch findWatch(String id) { if(id == null) throw new IllegalArgumentException("id is null"); Watch watch = null; for(Watch w : watchRegistry) { if(id.equals(w.getId())) { watch = w; break; } } return watch; } void deregister(Watch... watches); void closeAll(); void register(Watch... watches); void addThresholdListener(String id, ThresholdListener thresholdListener); void removeThresholdListener(String id, ThresholdListener thresholdListener); Watch findWatch(String id); WatchDataSource[] fetch(); WatchDataSource fetch(String id); void setServiceBeanContext(ServiceBeanContext context); }### Answer: @Test public void testFindWatch() { WatchDataSourceRegistry registry = new WatchDataSourceRegistry(); int[] counts = new int[] {0, 1, 10, 100}; for (int count : counts) { Collection<Watch> watches = new ArrayList<Watch>(); for (int k = 0; k < count; k++) { String id = "watch" + k; if (k == 1) { id = ""; } WatchDataSource ds = new WatchDataSourceImpl( id, EmptyConfiguration.INSTANCE); watches.add(new GaugeWatch(ds, id)); } for (int j = 0; j < 5; j++) { for (Watch watch : watches) { String id = watch.getId(); Watch res = registry.findWatch(id); Assert.assertNull(res); } for (Watch watch : watches) { registry.register(watch); } for (Watch watch : watches) { String id = watch.getId(); Watch res = registry.findWatch(id); Assert.assertNotNull(res); Assert.assertSame(watch, res); } Assert.assertNull(registry.findWatch("aaa")); for (Watch watch : watches) { registry.deregister(watch); } for (Watch watch : watches) { String id = watch.getId(); Watch res = registry.findWatch(id); Assert.assertNull(res); } } } try { registry.findWatch(null); Assert.fail("IllegalArgumentException expected but not thrown"); } catch (IllegalArgumentException e) { } }
### Question: ConfigHelper { public static String[] getConfigArgs(final ServiceElement service) throws IOException { return getConfigArgs(service, Thread.currentThread().getContextClassLoader()); } static String[] getConfigArgs(final ServiceElement service); static String[] getConfigArgs(final ServiceElement service, final ClassLoader cl); static final String CLASSPATH_RESOURCE; static final String FILE_RESOURCE; }### Answer: @Test(expected = IllegalArgumentException.class) public void testGetConfigArgsNoCLassLoader() throws IOException { ConfigHelper.getConfigArgs(new ServiceElement(), null); } @Test public void testUsingConfig() throws IOException { ServiceElement service = new ServiceElement(); service.getServiceBeanConfig().setConfigArgs(getConfig()); String[] args = ConfigHelper.getConfigArgs(service); Assert.assertNotNull(args); Assert.assertEquals(1, args.length); File file = new File(args[0]); Assert.assertTrue(file.exists()); Configuration configuration = new GroovyConfig(args, Thread.currentThread().getContextClassLoader()); Assert.assertNotNull(configuration); } @Test public void testUsingGroovyConfig() throws IOException { ServiceElement service = new ServiceElement(); service.getServiceBeanConfig().setConfigArgs(getGroovyConfig()); String[] args = ConfigHelper.getConfigArgs(service); Assert.assertNotNull(args); Assert.assertEquals(1, args.length); File file = new File(args[0]); Assert.assertFalse(file.exists()); Configuration configuration = new GroovyConfig(args, Thread.currentThread().getContextClassLoader()); Assert.assertNotNull(configuration); } @Test(expected = FileNotFoundException.class) public void testUsingMissingGroovyFile() throws IOException { ServiceElement service = new ServiceElement(); service.getServiceBeanConfig().setConfigArgs("file:foo"); String[] args = ConfigHelper.getConfigArgs(service); Assert.assertNotNull(args); Configuration configuration = new GroovyConfig(args, Thread.currentThread().getContextClassLoader()); Assert.assertNotNull(configuration); }
### Question: ClassBundleLoader { public static Class<?> loadClass(ClassBundle bundle) throws ClassNotFoundException, MalformedURLException { Class<?> theClass; final Thread currentThread = Thread.currentThread(); final ClassLoader cCL = AccessController.doPrivileged( (PrivilegedAction<ClassLoader>) currentThread::getContextClassLoader); try { theClass = loadClass(cCL, bundle); } finally { AccessController.doPrivileged((PrivilegedAction<ClassLoader>) () -> { currentThread.setContextClassLoader(cCL); return (null); }); } return theClass; } static Class<?> loadClass(ClassBundle bundle); static Class<?> loadClass(final ClassLoader parent, ClassBundle bundle); }### Answer: @Test public void testLoadClass() throws Exception { ClassBundle classBundle = new ClassBundle(JustForTesting.class.getName()); classBundle.setCodebase(System.getProperty("user.dir")+File.separator+ "target"+File.separator+ "test-classes"+File.separator); Class testClass = ClassBundleLoader.loadClass(classBundle); Assert.assertNotNull(testClass); }
### Question: Statistics { public void removeValue(int location) { if(location < v.size() && location >= 0) v.removeElementAt(location); } Statistics(); Statistics(Iterable<Double> values); void clearAll(); int count(); double max(); double min(); double mean(); double median(); double mode(); int modeOccurrenceCount(); double range(); double standardDeviation(); Vector getValues(); void addValue(Double double1); void addValue(double d); void setValues(Iterable<Double> vals); void setValues(Calculable[] calcs); void removeValues(double d, boolean removeAll); void removeValues(Double double1, boolean removeAll); void removeValue(int location); void removeValues(Double low, Double high); void removeValues(double low, double high); double sum(); }### Answer: @Test public void testRemoveValue() { List<Double> v = asList(new double[]{ 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); Statistics stat = new Statistics(v); while (stat.count() > 0) { int i = (int) (Math.random() * stat.count()); stat.removeValue(i); v.remove(i); Assert.assertEquals(v, stat.getValues()); } assertClean(stat); v = asList(new double[]{1, 2, 3, 4, 5}); stat.setValues(v); stat.removeValue(-1); stat.removeValue(5); Assert.assertEquals(v, stat.getValues()); }
### Question: AssociationInjector implements AssociationListener<T> { public void setBackend(Object target) { this.target = target; } AssociationInjector(Object target); void setBackend(Object target); void setCallerClassLoader(ClassLoader callerCL); void terminate(); Map<AssociationDescriptor, Long> getInvocationMap(); void injectEmpty(Association<T> association); void discovered(Association<T> association, T service); void changed(Association<T> association, T service); void broken(Association<T> association, T service); }### Answer: @Test public void testEagerInjection() { DefaultAssociationManagement aMgr = new DefaultAssociationManagement(); Target5 target = new Target5(); aMgr.setBackend(target); AssociationDescriptor descriptor = createAssociationDescriptor(); descriptor.setLazyInject(false); Association<Dummy> a = aMgr.addAssociationDescriptor(descriptor); Assert.assertTrue(target.injectedCount==1); Assert.assertNotNull(target.dummy); Assert.assertEquals(Association.State.PENDING, target.dummy.getState()); }
### Question: AssociationProxyUtil { public static <T> Association<T> getAssociation(T proxy) { Association<T> association = null; if(proxy instanceof AssociationProxy) { association = ((AssociationProxy<T>)proxy).getAssociation(); } return association; } static T getService(T proxy); static T regenProxy(T proxy); static T getFirst(T proxy); static Association<T> getAssociation(T proxy); }### Answer: @Test public void testGetAssociationFromProxy() { Association<Dummy> association = AssociationProxyUtil.getAssociation(t.getDummy()); Assert.assertNotNull(association); }
### Question: AssociationProxyUtil { public static <T> T regenProxy(T proxy) throws ClassNotFoundException, InstantiationException, IllegalAccessException { T newProxy = null; if(proxy instanceof AssociationProxy) { AssociationProxy<T> aProxy = (AssociationProxy)proxy; Association<T> association = aProxy.getAssociation(); String proxyClass = association.getAssociationDescriptor().getProxyClass(); proxyClass = (proxyClass==null? AssociationProxySupport.class.getName() : proxyClass); String strategyClass = aProxy.getServiceSelectionStrategy().getClass().getName(); newProxy = (T) AssociationProxyFactory.createProxy(proxyClass, strategyClass, association, aProxy.getClass().getClassLoader()); aProxy.terminate(); } return newProxy==null?proxy:newProxy; } static T getService(T proxy); static T regenProxy(T proxy); static T getFirst(T proxy); static Association<T> getAssociation(T proxy); }### Answer: @Test public void testRegen() throws ClassNotFoundException, IllegalAccessException, InstantiationException { Dummy d = t.getDummy(); int index = d.getIndex(); Dummy d1 = AssociationProxyUtil.regenProxy(t.getDummy()); Assert.assertEquals(index, d1.getIndex()); }
### Question: ComputeResourceAccessor { public static ComputeResource getComputeResource() { if(computeResource==null) { try { computeResource = new ComputeResource(); computeResource.boot(); } catch (ConfigurationException | UnknownHostException e) { logger.error("Unable to create default ComputeResource", e); } } return computeResource; } static ComputeResource getComputeResource(); }### Answer: @Test public void getComputeResource() throws Exception { ComputeResource computeResource = ComputeResourceAccessor.getComputeResource(); ComputeResourceUtilization cru = computeResource.getComputeResourceUtilization(); assertNotNull(cru); String systemCPUPercent = formatPercent(cru.getCpuUtilization().getValue()); assertNotNull(systemCPUPercent); String processCPUUtilization = formatPercent(getMeasuredValue(SystemWatchID.PROC_CPU, cru)); assertNotNull(processCPUUtilization); String systemMemoryTotal = format(cru.getSystemMemoryUtilization().getTotal(), "MB"); assertNotNull(systemMemoryTotal); String systemMemoryUtilPercent = formatPercent(cru.getSystemMemoryUtilization().getValue()); assertNotNull(systemMemoryUtilPercent); String processMemoryTotal = format(cru.getProcessMemoryUtilization().getUsedHeap()," MB"); assertNotNull(processMemoryTotal); String processMemoryUtilPercent = formatPercent(getMeasuredValue(SystemWatchID.JVM_MEMORY, cru)); assertNotNull(processMemoryUtilPercent); }
### Question: Jetty implements WebsterService { public int getPort() { if (server == null) { return port; } return ((ServerConnector)server.getConnectors()[0]).getLocalPort(); } Jetty(); Jetty(File jettyConfig); Jetty(Configuration config); Jetty setRoots(String... roots); Jetty setPort(int port); Jetty setMinThreads(int minThreads); Jetty setMaxThreads(int maxThreads); Jetty setPutDir(String putDir); @Override void start(); @Override void startSecure(); @Override void terminate(); @Override URI getURI(); int getPort(); String getAddress(); void join(); static void main(String[] args); }### Answer: @Test public void testStartWithConfig() throws Exception { DynamicConfiguration config = new DynamicConfiguration(); config.setEntry(Jetty.COMPONENT,"port", int.class,9020); config.setEntry(Jetty.COMPONENT,"roots", String[].class, new String[]{ System.getProperty("user.dir") + "/build/classes", System.getProperty("user.dir") + "/build/libs" }); Jetty jetty = new Jetty(config); assertEquals(9020, jetty.getPort()); } @Test public void testStartWithGroovyConfig() throws Exception { String projectDir = System.getProperty("projectDir"); String resources = new File(projectDir+"/src/test/resources").getPath(); File config = new File(resources +"/jetty.groovy"); Jetty jetty = new Jetty(config); assertEquals(9029, jetty.getPort()); }
### Question: GenericCostModel implements ResourceCostModel { public GenericCostModel(double value) { this(value, null, DEFAULT_DESCRIPTION); } GenericCostModel(double value); GenericCostModel(double value, TimeBoundary[] timeBoundaries); GenericCostModel(double value, TimeBoundary[] timeBoundaries, String description); double getCostPerUnit(long duration); void addTimeBoundary(TimeBoundary timeBoundary); String getDescription(); }### Answer: @Test public void testGenericCostModel() { GenericCostModel gcm = new GenericCostModel(0.01); gcm.addTimeBoundary(new ResourceCostModel.TimeBoundary(5, 10, ResourceCostModel.TimeBoundary.SECONDS)); gcm.addTimeBoundary(new ResourceCostModel.TimeBoundary(5, 100, ResourceCostModel.TimeBoundary.MINUTES)); System.out.println("Testing " + gcm.getClass().getName() + "\n"); System.out.println(gcm.getDescription()); Assert.assertTrue("Cost per unit for 2 seconds should be 0.01", gcm.getCostPerUnit(twoSeconds)==0.01); Assert.assertTrue("Cost per unit for 6 minutes should be 1.0", gcm.getCostPerUnit(sixMinutes) == 1.0); Assert.assertTrue("Cost per unit for 2 hours should be 1.0", gcm.getCostPerUnit(twoHours) == 1.0); }
### Question: Version { public boolean isRange() { return version.contains(","); } Version(final String version); boolean isRange(); String getVersion(); String getStartRange(); String getEndRange(); boolean minorVersionSupport(); boolean majorVersionSupport(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testIsRange() throws Exception { Version v = new Version("1,2"); Assert.assertTrue(v.isRange()); Version v1 = new Version("1.2"); Assert.assertFalse(v1.isRange()); }
### Question: Version { public String getVersion() { if (minorVersionSupport() || majorVersionSupport()) { return version.substring(0, version.length()-1).trim(); } return version.trim(); } Version(final String version); boolean isRange(); String getVersion(); String getStartRange(); String getEndRange(); boolean minorVersionSupport(); boolean majorVersionSupport(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testGetVersion() throws Exception { Version v = new Version("1,2"); Assert.assertNotNull(v.getVersion()); }
### Question: Version { public String getStartRange() { String[] parts = version.split(",", 2); return parts[0].trim(); } Version(final String version); boolean isRange(); String getVersion(); String getStartRange(); String getEndRange(); boolean minorVersionSupport(); boolean majorVersionSupport(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testGetStartRange() throws Exception { Version v = new Version("1,2"); Assert.assertNotNull(v.getStartRange()); Assert.assertEquals("1", v.getStartRange()); Version v1 = new Version("1.2"); Assert.assertNotNull(v1.getStartRange()); }
### Question: Version { public String getEndRange() { if (!isRange()) return getVersion(); String[] parts = version.split(",", 2); return parts[1].trim(); } Version(final String version); boolean isRange(); String getVersion(); String getStartRange(); String getEndRange(); boolean minorVersionSupport(); boolean majorVersionSupport(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testGetEndRange() throws Exception { Version v = new Version("1,2"); Assert.assertNotNull(v.getEndRange()); Assert.assertEquals("2", v.getEndRange()); Version v1 = new Version("1.2"); Assert.assertNotNull(v1.getEndRange()); }
### Question: Version { public boolean minorVersionSupport() { return version.endsWith("*"); } Version(final String version); boolean isRange(); String getVersion(); String getStartRange(); String getEndRange(); boolean minorVersionSupport(); boolean majorVersionSupport(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testMinorVersionSupport() throws Exception { Version v = new Version("1.1*"); Assert.assertTrue(v.minorVersionSupport()); Version v1 = new Version("1.2"); Assert.assertFalse(v1.minorVersionSupport()); }
### Question: Version { public boolean majorVersionSupport() { return version.endsWith("+"); } Version(final String version); boolean isRange(); String getVersion(); String getStartRange(); String getEndRange(); boolean minorVersionSupport(); boolean majorVersionSupport(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testMajorVersionSupport() throws Exception { Version v = new Version("1+"); Assert.assertTrue(v.majorVersionSupport()); Version v1 = new Version("1.2"); Assert.assertFalse(v1.majorVersionSupport()); }
### Question: Version { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Version version1 = (Version) o; return version.equals(version1.version); } Version(final String version); boolean isRange(); String getVersion(); String getStartRange(); String getEndRange(); boolean minorVersionSupport(); boolean majorVersionSupport(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testEquals() throws Exception { Version v = new Version("1.2"); Version v1 = new Version("1.2"); Assert.assertTrue(v.equals(v1)); }
### Question: RioProperties { public static void load() { File rioEnv; String rioEnvFileName = System.getProperty(Constants.ENV_PROPERTY_NAME, System.getenv(Constants.ENV_PROPERTY_NAME)); if(rioEnvFileName==null) { File rioRoot = new File(System.getProperty("user.home"), ".rio"); rioEnv = new File(rioRoot, "rio.env"); if(rioEnv.exists()) { loadAndSetProperties(rioEnv); } else { String rioHome = System.getProperty("rio.home", System.getenv("RIO_HOME")); if(rioHome!=null) { rioEnv = new File(rioHome, "config/rio.env"); if(rioEnv.exists()) { loadAndSetProperties(rioEnv); } else { System.err.println(rioEnv.getPath()+" not found, skipping"); } } else { System.err.println("RIO_HOME environment not set"); } } } else { rioEnv = new File(rioEnvFileName); if(rioEnv.exists()) { loadAndSetProperties(rioEnv); } } } private RioProperties(); static void load(); }### Answer: @Test public void testLoadFromEnv() { try { System.setProperty(Constants.ENV_PROPERTY_NAME, System.getProperty("user.dir") + "/src/test/resources/config/rio.env"); RioProperties.load(); String locators = System.getProperty(Constants.LOCATOR_PROPERTY_NAME); Assert.assertNotNull(locators); } finally { System.clearProperty(Constants.ENV_PROPERTY_NAME); } } @Test public void testLoadFromRioHome() { String oldRioHome = System.getProperty("rio.home"); try { System.setProperty("rio.home", System.getProperty("user.dir") + "/src/test/resources"); RioProperties.load(); String locators = System.getProperty(Constants.LOCATOR_PROPERTY_NAME); Assert.assertNotNull(locators); } finally { if (oldRioHome == null) System.clearProperty("RIO_HOME"); else System.setProperty("rio.home", oldRioHome); } }
### Question: SettingsUtil { public static Settings getSettings() throws SettingsBuildingException { DefaultSettingsBuilder defaultSettingsBuilder = new DefaultSettingsBuilder(); DefaultSettingsBuildingRequest request = new DefaultSettingsBuildingRequest(); File userSettingsFile = new File(System.getProperty("user.home"), ".m2" + File.separator + "settings.xml"); request.setUserSettingsFile(userSettingsFile); defaultSettingsBuilder.setSettingsWriter(new DefaultSettingsWriter()); defaultSettingsBuilder.setSettingsReader(new DefaultSettingsReader()); defaultSettingsBuilder.setSettingsValidator(new DefaultSettingsValidator()); SettingsBuildingResult build = defaultSettingsBuilder.build(request); return build.getEffectiveSettings(); } private SettingsUtil(); static Settings getSettings(); static String getLocalRepositoryLocation(final Settings settings); }### Answer: @Test public void testGetSettings() throws Exception { Settings settings = SettingsUtil.getSettings(); Assert.assertNotNull(settings); }
### Question: NettyAllocatorMetricSet implements MetricSet { @Override public Map<String, Metric> getMetrics() { Map<String, Metric> gauges = new HashMap<>(); gauges.put(name(namespace, "usedDirectMemory"), (Gauge<Long>) metric::usedDirectMemory); gauges.put(name(namespace, "usedHeapMemory"), (Gauge<Long>) metric::usedHeapMemory); return copyOf(gauges); } NettyAllocatorMetricSet(String namespace, ByteBufAllocatorMetric metric); @Override Map<String, Metric> getMetrics(); }### Answer: @Test public void gaugeReportsDirectMemoryUsageValue() throws Exception { when(metricUnderTest.usedDirectMemory()).thenReturn(1L); NettyAllocatorMetricSet metricSet = new NettyAllocatorMetricSet("test-metric", metricUnderTest); Gauge<Long> metric = (Gauge<Long>) metricSet.getMetrics().get("test-metric.usedDirectMemory"); assertThat(metric.getValue(), is(1L)); } @Test public void gaugeReportsHeapMemoryUsageValue() throws Exception { when(metricUnderTest.usedHeapMemory()).thenReturn(1L); NettyAllocatorMetricSet metricSet = new NettyAllocatorMetricSet("test-metric", metricUnderTest); Gauge<Long> metric = (Gauge<Long>) metricSet.getMetrics().get("test-metric.usedHeapMemory"); assertThat(metric.getValue(), is(1L)); }
### Question: StartupConfig { public static StartupConfig load() { String styxHome = System.getProperty(STYX_HOME_VAR_NAME); checkArgument(styxHome != null, "No system property %s has been defined.", STYX_HOME_VAR_NAME); checkArgument(isReadable(Paths.get(styxHome)), "%s=%s is not a readable configuration path.", STYX_HOME_VAR_NAME, styxHome); String configFileLocation = System.getProperty(CONFIG_FILE_LOCATION_VAR_NAME); if (configFileLocation == null) { configFileLocation = Paths.get(styxHome).resolve("conf/default.yml").toString(); } String logbackConfigLocation = System.getProperty(LOGBACK_CONFIG_LOCATION_VAR_NAME); if (logbackConfigLocation == null) { logbackConfigLocation = Paths.get(styxHome).resolve("conf/logback.xml").toString(); } return new Builder() .styxHome(styxHome) .configFileLocation(configFileLocation) .logbackConfigLocation(logbackConfigLocation) .build(); } private StartupConfig(Builder builder); static StartupConfig load(); static Builder newStartupConfigBuilder(); Path styxHome(); Resource logConfigLocation(); Resource configFileLocation(); @Override String toString(); }### Answer: @Test public void configurationLoadingFailsIfStyxHomeIsNotSpecified() { Exception e = assertThrows(IllegalArgumentException.class, () -> StartupConfig.load()); assertEquals("No system property STYX_HOME has been defined.", e.getMessage()); } @Test public void configurationLoadingFailsIfStyxHomeDoesNotPointToReadableLocation() { setProperty(STYX_HOME_VAR_NAME, "/undefined"); Exception e = assertThrows(IllegalArgumentException.class, () -> StartupConfig.load()); assertEquals("STYX_HOME=/undefined is not a readable configuration path.", e.getMessage()); }
### Question: YamlConfigurationFormat implements ConfigurationFormat<YamlConfiguration> { @Override public String resolvePlaceholdersInText(String text, Map<String, String> overrides) { List<PlaceholderResolver.Placeholder> placeholders = extractPlaceholders(text); String resolvedText = text; for (PlaceholderResolver.Placeholder placeholder : placeholders) { resolvedText = resolvePlaceholderInText(resolvedText, placeholder, overrides); } return resolvedText; } private YamlConfigurationFormat(); @Override YamlConfiguration deserialise(String string); @Override YamlConfiguration deserialise(Resource resource); @Override String resolvePlaceholdersInText(String text, Map<String, String> overrides); @Override String toString(); static final YamlConfigurationFormat YAML; }### Answer: @Test public void canResolvePlaceholdersInInclude() throws IOException { Map<String, String> overrides = ImmutableMap.of("CONFIG_LOCATION", "some_location"); String yaml = "${CONFIG_LOCATION:classpath:}/conf/environment/default.yaml"; String resolved = YamlConfigurationFormat.YAML.resolvePlaceholdersInText(yaml, overrides); assertThat(resolved, is("some_location/conf/environment/default.yaml")); }
### Question: PlaceholderResolver { @VisibleForTesting static List<String> extractPlaceholderStrings(String value) { Matcher matcher = PLACEHOLDER_REGEX_CAPTURE_ALL.matcher(value); List<String> placeholders = new ArrayList<>(); while (matcher.find()) { placeholders.add(matcher.group()); } return placeholders; } PlaceholderResolver(ObjectNode rootNode, Map<String, String> externalProperties); static Collection<UnresolvedPlaceholder> resolvePlaceholders(JsonNode rootNode, Map<String, String> externalProperties); static Collection<UnresolvedPlaceholder> resolvePlaceholders(JsonNode rootNode, Properties properties); Collection<UnresolvedPlaceholder> resolve(); @VisibleForTesting static String replacePlaceholder(String originalString, String placeholderName, String placeholderValue); @VisibleForTesting static List<Placeholder> extractPlaceholders(String value); }### Answer: @Test public void extractsPlaceholders() { String valueWithPlaceholders = "foo ${with.default:defaultValue} bar ${without.default} ${configLocation:classpath:}foo"; List<String> placeholders = PlaceholderResolver.extractPlaceholderStrings(valueWithPlaceholders); assertThat(placeholders, contains("${with.default:defaultValue}", "${without.default}", "${configLocation:classpath:}")); } @Test public void extractsPlaceholdersWithEmptyDefaults() { String valueWithPlaceholders = "foo: \"${FOO:}\""; List<String> placeholders = PlaceholderResolver.extractPlaceholderStrings(valueWithPlaceholders); assertThat(placeholders, contains("${FOO:}")); }
### Question: PlaceholderResolver { @VisibleForTesting public static List<Placeholder> extractPlaceholders(String value) { List<Placeholder> namesAndDefaults = new ArrayList<>(); for (String placeholder : extractPlaceholderStrings(value)) { Matcher placeholderMatcher = PLACEHOLDER_REGEX_CAPTURE_NAME_AND_DEFAULT.matcher(placeholder); if (placeholderMatcher.matches()) { namesAndDefaults.add(new Placeholder(placeholderMatcher.group(1), placeholderMatcher.group(2))); } } return namesAndDefaults; } PlaceholderResolver(ObjectNode rootNode, Map<String, String> externalProperties); static Collection<UnresolvedPlaceholder> resolvePlaceholders(JsonNode rootNode, Map<String, String> externalProperties); static Collection<UnresolvedPlaceholder> resolvePlaceholders(JsonNode rootNode, Properties properties); Collection<UnresolvedPlaceholder> resolve(); @VisibleForTesting static String replacePlaceholder(String originalString, String placeholderName, String placeholderValue); @VisibleForTesting static List<Placeholder> extractPlaceholders(String value); }### Answer: @Test public void extractsPlaceholderNamesAndDefaults() { String valueWithPlaceholders = "foo ${with.default:defaultValue} bar ${without.default} ${configLocation:classpath:}foo"; List<Placeholder> placeholders = PlaceholderResolver.extractPlaceholders(valueWithPlaceholders); List<Placeholder> expected = ImmutableList.of( new Placeholder("with.default", "defaultValue"), new Placeholder("without.default"), new Placeholder("configLocation", "classpath:")); assertThat(placeholders, is(expected)); } @Test public void extractsPlaceholderNamesAndEmptyDefaults() { String valueWithPlaceholders = "${FOO:}"; List<Placeholder> placeholders = PlaceholderResolver.extractPlaceholders(valueWithPlaceholders); assertThat(placeholders, is(singletonList(new Placeholder("FOO", "")))); }
### Question: PlaceholderResolver { @VisibleForTesting public static String replacePlaceholder(String originalString, String placeholderName, String placeholderValue) { return originalString.replaceAll("\\$\\{" + quote(placeholderName) + "(?:\\:[^\\}]*?)?\\}", placeholderValue); } PlaceholderResolver(ObjectNode rootNode, Map<String, String> externalProperties); static Collection<UnresolvedPlaceholder> resolvePlaceholders(JsonNode rootNode, Map<String, String> externalProperties); static Collection<UnresolvedPlaceholder> resolvePlaceholders(JsonNode rootNode, Properties properties); Collection<UnresolvedPlaceholder> resolve(); @VisibleForTesting static String replacePlaceholder(String originalString, String placeholderName, String placeholderValue); @VisibleForTesting static List<Placeholder> extractPlaceholders(String value); }### Answer: @Test public void replacesPlaceholder() { String original = "foo ${with.default:defaultValue} bar ${without.default}"; assertThat(PlaceholderResolver.replacePlaceholder(original, "with.default", "replacement"), is("foo replacement bar ${without.default}")); assertThat(PlaceholderResolver.replacePlaceholder(original, "without.default", "replacement"), is("foo ${with.default:defaultValue} bar replacement")); }
### Question: NodePath { public Optional<JsonNode> findMatchingDescendant(JsonNode rootNode) { JsonNode current = rootNode; for (PathElement element : elements) { current = element.child(current); if (current == null) { return Optional.empty(); } } return Optional.ofNullable(current); } NodePath(String path); NodePath(List<PathElement> elements); List<PathElement> elements(); PathElement lastElement(); Optional<JsonNode> findMatchingDescendant(JsonNode rootNode); boolean override(JsonNode rootNode, JsonNode leaf); boolean override(JsonNode rootNode, String value); @Override String toString(); }### Answer: @Test public void canGetTopLevelProperty() { assertThat(new NodePath("text").findMatchingDescendant(root), matches(isTextNode("abc"))); } @Test public void canGetArrayElements() { assertThat(new NodePath("array[0]").findMatchingDescendant(root), matches(isTextNode("alpha"))); assertThat(new NodePath("array[1]").findMatchingDescendant(root), matches(isTextNode("beta"))); assertThat(new NodePath("array[2]").findMatchingDescendant(root), matches(isTextNode("gamma"))); } @Test public void canGetObjectField() { assertThat(new NodePath("object.field1").findMatchingDescendant(root), matches(isTextNode("foo"))); assertThat(new NodePath("object.field2").findMatchingDescendant(root), matches(isTextNode("bar"))); } @Test public void canGetFieldsWithinArrayElementObjects() { assertThat(new NodePath("array2[0].arrayObjectField1").findMatchingDescendant(root), matches(isTextNode("abc"))); assertThat(new NodePath("array2[0].arrayObjectField2").findMatchingDescendant(root), matches(isTextNode("def"))); }
### Question: JsonNodeConfig implements Configuration { @Override public Optional<String> get(String key) { return get(key, String.class); } JsonNodeConfig(JsonNode rootNode); protected JsonNodeConfig(JsonNode rootNode, ObjectMapper mapper); @Override Optional<String> get(String key); @Override Optional<T> get(String property, Class<T> tClass); @Override X as(Class<X> type); @Override String toString(); }### Answer: @Test public void extractsDefaultStringTypeConfigurationFromJsonNode() { JsonNode rootNode = jsonNode("{\"text\":\"foo\"}"); JsonNodeConfig config = new JsonNodeConfig(rootNode); assertThat(config.get("text"), isValue("foo")); assertThat(config.get("nonExistent"), isAbsent()); } @Test public void extractsSpecifiedTypeConfigurationFromJsonNode() { JsonNode rootNode = jsonNode("{\"text\":\"foo\",\"number\":123}"); JsonNodeConfig config = new JsonNodeConfig(rootNode); assertThat(config.get("text", String.class), isValue("foo")); assertThat(config.get("nonExistent", String.class), isAbsent()); assertThat(config.get("number", Integer.class), isValue(123)); assertThat(config.get("nonExistent", Integer.class), isAbsent()); }
### Question: GraphiteReporter extends ScheduledReporter { @VisibleForTesting void initConnection() { tryTimes( MAX_RETRIES, graphite::connect, (e) -> attemptErrorHandling(graphite::close) ); } private GraphiteReporter(MetricRegistry registry, GraphiteSender graphite, Clock clock, String prefix, TimeUnit rateUnit, TimeUnit durationUnit, MetricFilter filter); static Builder forRegistry(MetricRegistry registry); @Override void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters, SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers); @Override void stop(); }### Answer: @Test public void initConnectionRetriesOnFailure() throws Exception { doThrow(new UnknownHostException("UNKNOWN-HOST")).when(graphite).connect(); try { reporter.initConnection(); fail("Should have thrown an exception"); } catch (UncheckedIOException e) { verify(graphite, times(MAX_RETRIES)).connect(); } }
### Question: MemoryBackedRegistry extends AbstractRegistry<T> { public void add(T t) { resources.put(t.id(), t); if (autoReload) { reload(); } } MemoryBackedRegistry(); private MemoryBackedRegistry(boolean autoReload); void add(T t); void removeById(Id id); void reset(); @Override CompletableFuture<ReloadResult> reload(); }### Answer: @Test public void addsResources() { BackendService landing = backendService("landing", 9091); BackendService shopping = backendService("shopping", 9090); MemoryBackedRegistry<BackendService> registry = new MemoryBackedRegistry<>(); registry.add(landing); registry.addListener(listener); registry.add(shopping); assertThat(registry.get(), containsInAnyOrder(landing, shopping)); verify(listener).onChange(eq(added(shopping))); } @Test public void updatesResources() { BackendService landing = backendService("landing", 9091); MemoryBackedRegistry<BackendService> registry = new MemoryBackedRegistry<>(); registry.add(backendService("shopping", 9090)); registry.add(landing); registry.addListener(listener); BackendService shopping = backendService("shopping", 9091); registry.add(shopping); assertThat(registry.get(), containsInAnyOrder(landing, shopping)); verify(listener).onChange(eq(updated(shopping))); }
### Question: ExceptionConverter extends ClassicConverter { @Override public String convert(final ILoggingEvent loggingEvent) { return Optional.ofNullable(loggingEvent) .map(this::getExceptionData) .orElse(NO_MSG); } @Override String convert(final ILoggingEvent loggingEvent); static final String TARGET_CLASSES_PROPERTY_NAME; }### Answer: @Test public void extractsTheExceptionClassMethodAndCreatesAUniqueExceptionId() throws Exception { ExceptionConverter converter = newExceptionConverter(); assertThat(converter.convert(loggingEvent).trim(), endsWith("[exceptionClass=com.hotels.styx.infrastructure.logging.ExceptionConverterTest, exceptionMethod=<init>, exceptionID=10d7182c]")); } @Test public void gracefullyHandlesExceptionInstancesWithoutStackTrace() throws Exception { ExceptionConverter converter = newExceptionConverter(); ILoggingEvent errorEvent = newErrorLoggingEvent(new NoStackException()); assertThat(converter.convert(errorEvent), endsWith("")); } @Test public void prioritizeTargetClassStackTraceElementsOverTheRootOnes() throws Exception { ExceptionConverter converter = newExceptionConverter(); converter.getContext() .putProperty(TARGET_CLASSES_PROPERTY_NAME, "TargetClass"); ILoggingEvent loggingEvent = newErrorLoggingEvent(new TargetClass().blow()); assertThat(converter.convert(loggingEvent).trim(), endsWith("[exceptionClass=com.hotels.styx.infrastructure.logging.ExceptionConverterTest$TargetClass, exceptionMethod=blow, exceptionID=8b93d529]")); } @Test public void errorsIfTargetClassPropertyIsEmpty() throws Exception { ContextBase contextBase = new ContextBase(); StatusManager statusManager = mock(StatusManager.class); contextBase.setStatusManager(statusManager); ExceptionConverter converter = newExceptionConverter(contextBase); converter.getContext() .putProperty(TARGET_CLASSES_PROPERTY_NAME, ""); ILoggingEvent loggingEvent = newErrorLoggingEvent(new TargetClass().blow()); converter.convert(loggingEvent); verify(statusManager).add(any(ErrorStatus.class)); }
### Question: LOGBackConfigurer { public static void initLogging(String logConfigLocation, boolean installJULBridge) { try { String location = resolvePlaceholders(logConfigLocation); if (location.indexOf("${") >= 0) { throw new IllegalStateException("unable to resolve certain placeholders: " + sanitise(location)); } location = location.replaceAll("\\\\", "/"); String notice = "If you are watching the console output, it may stop after this point, if configured to only write to file."; Logger.getLogger(LOGBackConfigurer.class.getName()).info("Initializing LOGBack from [" + sanitise(location) + "]. " + notice); initLogging(getURL(location), installJULBridge); } catch (FileNotFoundException ex) { throw new IllegalArgumentException("invalid '" + sanitise(logConfigLocation) + "' parameter: " + ex.getMessage()); } } private LOGBackConfigurer(); static void initLogging(String logConfigLocation, boolean installJULBridge); static void initLogging(URL url, boolean installJULBridge); static void shutdownLogging(boolean uninstallJULBridge); }### Answer: @Test public void canConfigureLoggingFromClasspath() { initLogging("classpath:conf/logback.xml", false); } @Test public void canConfigureLoggingFromURL() { initLogging(LOGBackConfigurerTest.class.getResource("/conf/logback.xml"), false); } @Test public void resolvesPlaceholdersBeforeInitializing() { System.setProperty("CONFIG_LOCATION", "classpath:"); initLogging("${CONFIG_LOCATION}conf/logback.xml", false); } @Test public void failsForInvalidLogbackPath() { assertThrows(IllegalArgumentException.class, () -> initLogging(NON_EXISTENT_LOGBACK, false)); }
### Question: StyxConfig implements Configuration { public ProxyServerConfig proxyServerConfig() { return proxyServerConfig; } StyxConfig(); StyxConfig(Configuration configuration); @Override Optional<T> get(String key, Class<T> tClass); @Override X as(Class<X> type); @Override Optional<String> get(String key); StyxHeaderConfig styxHeaderConfig(); ProxyServerConfig proxyServerConfig(); AdminServerConfig adminServerConfig(); int port(); Optional<String> applicationsConfigurationPath(); Iterable<Resource> versionFiles(StartupConfig startupConfig); static StyxConfig fromYaml(String yamlText); static StyxConfig fromYaml(String yamlText, boolean validateConfiguration); static StyxConfig defaultConfig(); @Override String toString(); static final String NO_JVM_ROUTE_SET; }### Answer: @Test public void readsTheDefaultValueForBossThreadsCountIfNotConfigured() { assertThat(styxConfig.proxyServerConfig().bossThreadsCount(), is(HALF_OF_AVAILABLE_PROCESSORS)); } @Test public void readsTheDefaultValueForClientWorkerThreadsCountIfNotConfigured() { assertThat(styxConfig.proxyServerConfig().clientWorkerThreadsCount(), is(HALF_OF_AVAILABLE_PROCESSORS)); }
### Question: ServiceProvision { public static <E extends RetryPolicy> Optional<E> loadRetryPolicy( Configuration configuration, Environment environment, String key, Class<? extends E> serviceClass) { return configuration .get(key, ServiceFactoryConfig.class) .map(factoryConfig -> { RetryPolicyFactory factory = newInstance(factoryConfig.factory(), RetryPolicyFactory.class); JsonNodeConfig config = factoryConfig.config(); return serviceClass.cast(factory.create(environment, config)); }); } private ServiceProvision(); static Optional<E> loadLoadBalancer( Configuration configuration, Environment environment, String key, Class<? extends E> serviceClass, ActiveOrigins activeOrigins); static Optional<E> loadRetryPolicy( Configuration configuration, Environment environment, String key, Class<? extends E> serviceClass); static Map<String, T> loadServices(Configuration configuration, Environment environment, String key, Class<? extends T> serviceClass); }### Answer: @Test public void serviceReturnsCorrectlyFromCall() { assertThat(loadRetryPolicy(environment.configuration(), environment, "myRetry.factory", RetryPolicy.class).get(), is(instanceOf(RetryPolicy.class))); } @Test public void serviceReturnsEmptyWhenFactoryKeyDoesNotExist() { assertThat(loadRetryPolicy(environment.configuration(), environment, "invalid.key", RetryPolicy.class), isAbsent()); } @Test public void throwsExceptionWhenClassDoesNotExist() { Exception e = assertThrows(Exception.class, () -> loadRetryPolicy(environment.configuration(), environment, "not.real", RetryPolicy.class)); assertThat(e.getMessage(), matchesPattern("(?s).*No such class 'my.FakeClass'.*")); }
### Question: StyxServer extends AbstractService { public InetSocketAddress proxyHttpAddress() { return Optional.ofNullable(httpServer) .map(InetServer::inetAddress) .orElse(null); } StyxServer(StyxServerComponents config); StyxServer(StyxServerComponents components, Stopwatch stopwatch); static void main(String[] args); InetSocketAddress serverAddress(String name); InetSocketAddress proxyHttpAddress(); InetSocketAddress proxyHttpsAddress(); InetSocketAddress adminHttpAddress(); }### Answer: @Test public void serverDoesNotStartUntilPluginsAreStarted() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); StyxServer styxServer = styxServerWithPlugins(ImmutableMap.of( "slowlyStartingPlugin", new Plugin() { @Override public void styxStarting() { try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request1, Chain chain) { return Eventual.of(response(OK).build()); } } )); try { styxServer.startAsync(); Thread.sleep(10); assertThat(styxServer.proxyHttpAddress(), nullValue()); latch.countDown(); eventually(() -> assertThat(styxServer.proxyHttpAddress().getPort(), is(greaterThan(0)))); } finally { stopIfRunning(styxServer); } }
### Question: StyxServer extends AbstractService { public static void main(String[] args) { try { StyxServer styxServer = createStyxServer(args); getRuntime().addShutdownHook(new Thread(() -> styxServer.stopAsync().awaitTerminated())); styxServer.startAsync().awaitRunning(); } catch (SchemaValidationException cause) { LOG.error(cause.getMessage()); System.exit(2); } catch (Throwable cause) { LOG.error("Error in Styx server startup.", cause); System.exit(1); } } StyxServer(StyxServerComponents config); StyxServer(StyxServerComponents components, Stopwatch stopwatch); static void main(String[] args); InetSocketAddress serverAddress(String name); InetSocketAddress proxyHttpAddress(); InetSocketAddress proxyHttpsAddress(); InetSocketAddress adminHttpAddress(); }### Answer: @Test public void startsFromMain() { try { setProperty("STYX_HOME", fixturesHome()); StyxServer.main(new String[0]); eventually(() -> assertThat(log.log(), hasItem(loggingEvent(INFO, "Started Styx server in \\d+ ms")))); } finally { clearProperty("STYX_HOME"); } }
### Question: ResponseInfoFormat { public String format(LiveHttpRequest request) { return String.format(format, request == null ? "" : request.id()); } ResponseInfoFormat(Environment environment); String format(LiveHttpRequest request); }### Answer: @Test public void defaultFormatDoesNotIncludeVersion() { String info = new ResponseInfoFormat(defaultEnvironment()).format(request); assertThat(info, is("noJvmRouteSet;" + request.id())); } @Test public void canConfigureCustomHeaderFormatWithVersion() { StyxHeaderConfig styxHeaderConfig = new StyxHeaderConfig( new StyxHeaderConfig.StyxHeader( null, "{VERSION};{REQUEST_ID};{INSTANCE}"), null, null); Environment environment = environment(new MapBackedConfiguration() .set("styxHeaders", styxHeaderConfig)); String info = new ResponseInfoFormat(environment).format(request); assertThat(info, is("STYX-dev.0.0;" + request.id() + ";noJvmRouteSet")); }
### Question: SpiExtension { public JsonNode config() { return config; } @JsonCreator SpiExtension(@JsonProperty("factory") SpiExtensionFactory factory, @JsonProperty("config") JsonNode config, @JsonProperty("enabled") Boolean enabled); SpiExtensionFactory factory(); JsonNode config(); boolean enabled(); T config(Class<T> configClass); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer: @Test public void getsConfigAsClass() throws IOException { JsonNode configNode = MAPPER.readTree("foo: bar"); SpiExtension metadata = new SpiExtension(new SpiExtensionFactory("factoryClass", "classPath"), configNode, null); TestObject config = metadata.config(TestObject.class); assertThat(config.foo, is("bar")); }
### Question: ExtensionObjectFactory { public <T> T newInstance(SpiExtensionFactory extensionFactory, Class<T> type) throws ExtensionLoadingException { try { Class<?> extensionClass = loadClass(extensionFactory); Object instance = extensionClass.newInstance(); return type.cast(instance); } catch (ExtensionLoadingException e) { throw e; } catch (Exception e) { throw new ExtensionLoadingException("error instantiating class=" + extensionFactory.factoryClass(), e); } } private ExtensionObjectFactory(); @VisibleForTesting ExtensionObjectFactory(Function<SpiExtensionFactory, ClassSource> extensionLocator); T newInstance(SpiExtensionFactory extensionFactory, Class<T> type); static final ExtensionObjectFactory EXTENSION_OBJECT_FACTORY; }### Answer: @Test public void throwsAppropriateExceptionIfClassNotFound() { ExtensionObjectFactory factory = new ExtensionObjectFactory(extensionFactory -> name -> { throw new ClassNotFoundException(); }); Exception e = assertThrows(ExtensionLoadingException.class, () -> factory.newInstance(new SpiExtensionFactory("some.FakeClass", "/fake/class/path"), Object.class)); assertEquals("no class=some.FakeClass is found in the specified classpath=/fake/class/path", e.getMessage()); } @Test public void throwsAppropriateExceptionIfObjectCannotBeInstantiated() { ExtensionObjectFactory factory = new ExtensionObjectFactory(extensionFactory -> DEFAULT_CLASS_LOADER); String className = CannotInstantiate.class.getName(); try { factory.newInstance(new SpiExtensionFactory(className, "/fake/class/path"), Object.class); fail("No exception thrown"); } catch (ExtensionLoadingException e) { assertThat(e.getMessage(), is("error instantiating class=" + className)); assertThat(e.getCause(), is(instanceOf(IllegalAccessException.class))); } } @Test public void instantiatesObjects() { ExtensionObjectFactory factory = new ExtensionObjectFactory(extensionFactory -> DEFAULT_CLASS_LOADER); String className = String.class.getName(); Object object = factory.newInstance(new SpiExtensionFactory(className, "/fake/class/path"), Object.class); assertThat(object, is(instanceOf(String.class))); }
### Question: LoggingConfigurationHandler implements WebServiceHandler { @Override public Eventual<HttpResponse> handle(HttpRequest request, HttpInterceptor.Context context) { return Eventual.of(generateResponse()); } LoggingConfigurationHandler(Resource logConfigLocation); @Override Eventual<HttpResponse> handle(HttpRequest request, HttpInterceptor.Context context); }### Answer: @Test public void showsErrorMessageInContentIfLogConfigFileDoesNotExist() { StartupConfig startupConfig = newStartupConfigBuilder() .logbackConfigLocation("/foo/bar") .build(); LoggingConfigurationHandler handler = new LoggingConfigurationHandler(startupConfig.logConfigLocation()); HttpResponse response = Mono.from(handler.handle(get("/").build(), requestContext())).block(); assertThat(response.status(), is(OK)); assertThat(response.bodyAs(UTF_8), matchesRegex("Could not load resource=.*foo[\\\\/]bar'")); } @Test public void showsLogConfigContent() throws IOException { StartupConfig startupConfig = newStartupConfigBuilder() .logbackConfigLocation(fixturesHome() + "/conf/environment/styx-config-test.yml") .build(); LoggingConfigurationHandler handler = new LoggingConfigurationHandler(startupConfig.logConfigLocation()); HttpResponse response = Mono.from(handler.handle(get("/").build(), requestContext())).block(); String expected = Resources.load(new ClasspathResource("conf/environment/styx-config-test.yml", LoggingConfigurationHandlerTest.class)); assertThat(response.status(), is(OK)); assertThat(response.bodyAs(UTF_8), is(expected)); }
### Question: DashboardData { @JsonProperty("server") public Server server() { return server; } DashboardData(MetricRegistry metrics, Registry<BackendService> backendServicesRegistry, String serverId, Version version, EventBus eventBus); @JsonProperty("server") Server server(); @JsonProperty("downstream") Downstream downstream(); @JsonProperty("publishTime") long publishTime(); }### Answer: @Test public void providesServerId() { DashboardData dashboardData = newDashboardData("styx-prod1-presentation-01", "releaseTag", backendServicesRegistry); assertThat(dashboardData.server().id(), is("styx-prod1-presentation-01")); } @Test public void providesVersion() { DashboardData dashboardData = newDashboardData("serverId", "STYX.0.4.283", backendServicesRegistry); assertThat(dashboardData.server().version(), is("0.4.283")); } @Test public void providesUptime() { metricRegistry.register("jvm.uptime.formatted", gauge("1d 3h 2m")); assertThat(newDashboardData().server().uptime(), is("1d 3h 2m")); } @Test public void providesStyxErrorResponseCodes() { metricRegistry.counter("styx.response.status.500").inc(111); metricRegistry.counter("styx.response.status.502").inc(222); Map<String, Integer> responses = newDashboardData().server().responses(); assertThat(responses.get("500"), is(111)); assertThat(responses.get("502"), is(222)); assertThat(responses.get("5xx"), is(333)); }
### Question: DashboardData { void unregister() { this.downstream.unregister(); } DashboardData(MetricRegistry metrics, Registry<BackendService> backendServicesRegistry, String serverId, Version version, EventBus eventBus); @JsonProperty("server") Server server(); @JsonProperty("downstream") Downstream downstream(); @JsonProperty("publishTime") long publishTime(); }### Answer: @Test public void unsubscribesFromEventBus() { EventBus eventBus = mock(EventBus.class); MemoryBackedRegistry<BackendService> backendServicesRegistry = new MemoryBackedRegistry<>(); backendServicesRegistry.add(application("app", origin("app-01", "localhost", 9090))); backendServicesRegistry.add(application("test", origin("test-01", "localhost", 9090))); DashboardData dashbaord = new DashboardData(metricRegistry, backendServicesRegistry, "styx-prod1-presentation-01", new Version("releaseTag"), eventBus); verify(eventBus, times(4)).register(any(DashboardData.Origin.class)); dashbaord.unregister(); verify(eventBus, times(4)).unregister(any(DashboardData.Origin.class)); }
### Question: SimpleConverter implements Converter { @Override public <T> T convert(Object source, Class<T> targetType) { if (source == null) { return null; } if (targetType == Boolean.class || targetType == Boolean.TYPE) { @SuppressWarnings("unchecked") T t = (T) Boolean.valueOf(source.toString()); return t; } @SuppressWarnings("unchecked") T t = (T) parse(source.toString(), targetType); return t; } @Override T convert(Object source, Class<T> targetType); }### Answer: @Test public void convertsBooleanValue() { assertThat(converter.convert("true", Boolean.TYPE), is(true)); assertThat(converter.convert("false", Boolean.TYPE), is(false)); } @Test public void convertsIntegerValues() { assertThat(converter.convert("9000", Integer.TYPE), is(9000)); } @Test public void convertsStringValue() { assertThat(converter.convert("9000", String.class), is("9000")); } @Test public void convertsEnumValues() { assertThat(converter.convert("CLOSE", Status.class), is(Status.CLOSE)); assertThat(converter.convert("OPEN", Status.class), is(Status.OPEN)); } @Test public void convertsArrayOfPrimitives() { String[] locales = converter.convert("UK,US,IT", String[].class); assertThat(asList(locales), contains("UK", "US", "IT")); } @Test public void failsForUndefinedEnumValue() { assertThrows(ConversionException.class, () -> converter.convert("UDEFINED", Status.class)); } @Test public void failsForUndefinedObject() { assertThrows(ConversionException.class, () -> converter.convert("UDEFINED", ConfigurationValue.class)); }
### Question: HttpHeaders implements Iterable<HttpHeader> { public Set<String> names() { return ImmutableSet.copyOf(nettyHeaders.names()); } private HttpHeaders(Builder builder); Set<String> names(); Optional<String> get(CharSequence name); List<String> getAll(CharSequence name); boolean contains(CharSequence name); @Override Iterator<HttpHeader> iterator(); void forEach(BiConsumer<String, String> consumer); Builder newBuilder(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void emptyHeadersHasEmptyNames() { HttpHeaders httpHeaders = new HttpHeaders.Builder().build(); assertThat(httpHeaders.names(), is(emptyIterable())); }
### Question: HttpHeaders implements Iterable<HttpHeader> { public boolean contains(CharSequence name) { return nettyHeaders.contains(name); } private HttpHeaders(Builder builder); Set<String> names(); Optional<String> get(CharSequence name); List<String> getAll(CharSequence name); boolean contains(CharSequence name); @Override Iterator<HttpHeader> iterator(); void forEach(BiConsumer<String, String> consumer); Builder newBuilder(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void checksWhetherHeadersExist() { assertThat(headers.contains("header1"), is(true)); assertThat(headers.contains("header2"), is(true)); assertThat(headers.contains("nonExistent"), is(false)); } @Test public void setsHeaders() { HttpHeaders newHeaders = new HttpHeaders.Builder() .add("foo", "bar") .build(); HttpHeaders headers = new HttpHeaders.Builder(newHeaders) .build(); assertThat(headers, contains(header("foo", "bar"))); } @Test public void removesNullValues() { HttpHeaders headers = new Builder() .add("header1", asList("val1", null, "val2")) .build(); assertThat(headers, contains(header("header1", "val1"), header("header1", "val2"))); }
### Question: HttpHeaders implements Iterable<HttpHeader> { public Optional<String> get(CharSequence name) { return Optional.ofNullable(nettyHeaders.get(name)); } private HttpHeaders(Builder builder); Set<String> names(); Optional<String> get(CharSequence name); List<String> getAll(CharSequence name); boolean contains(CharSequence name); @Override Iterator<HttpHeader> iterator(); void forEach(BiConsumer<String, String> consumer); Builder newBuilder(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void providesSingleHeaderValue() { assertThat(headers.get("header1").get(), is("val1")); } @Test public void providesFirstHeaderValueWhenSeveralExist() { assertThat(headers.get("header2").get(), is("val2a")); } @Test public void providesOptionalAbsentWhenNoSuchHeaderExists() { assertThat(headers.get("nonExistent"), isAbsent()); } @Test public void setsDateHeaders() { Instant time = ZonedDateTime.of(2015, 9, 10, 12, 2, 28, 0, UTC).toInstant(); HttpHeaders headers = new HttpHeaders.Builder() .set("foo", time) .build(); assertThat(headers.get("foo"), isValue("Thu, 10 Sep 2015 12:02:28 GMT")); }
### Question: HttpHeaders implements Iterable<HttpHeader> { @Override public String toString() { return Iterables.toString(nettyHeaders); } private HttpHeaders(Builder builder); Set<String> names(); Optional<String> get(CharSequence name); List<String> getAll(CharSequence name); boolean contains(CharSequence name); @Override Iterator<HttpHeader> iterator(); void forEach(BiConsumer<String, String> consumer); Builder newBuilder(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void convertsHeadersToString() { assertThat(headers.toString(), is("[header1=val1, header2=val2a, header2=val2b]")); }
### Question: ServerCookieEncoder extends CookieEncoder { String encode(String name, String value) { return encode(new DefaultCookie(name, value)); } private ServerCookieEncoder(boolean strict); }### Answer: @Test public void removesMaxAgeInFavourOfExpireIfDateIsInThePast() { String cookieValue = "hp_pos=\"\"; Domain=.dev-hotels.com; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/"; Cookie cookie = ClientCookieDecoder.LAX.decode(cookieValue); String encodedCookieValue = ServerCookieEncoder.LAX.encode(cookie); assertThat(encodedCookieValue, not(containsString("Max-Age=0"))); assertThat(encodedCookieValue, containsString("Expires=Thu, 01 Jan 1970 00:00")); } @Test public void willNotModifyMaxAgeIfPositive() { String cookieValue = "hp_pos=\"\"; Domain=.dev-hotels.com; Max-Age=50; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/"; Cookie cookie = ClientCookieDecoder.LAX.decode(cookieValue); assertThat(cookie.maxAge(), is(50L)); assertThat(ServerCookieEncoder.LAX.encode(cookie), containsString("Max-Age=50")); } @Test public void setValidSameSite() { DefaultCookie cookie = new DefaultCookie("key", "value"); cookie.setSameSite(SameSite.Lax); cookie.setDomain(".domain.com"); cookie.setMaxAge(50); assertThat(ServerCookieEncoder.LAX.encode(cookie), containsString("Lax")); }
### Question: ResponseCookie { private ResponseCookie(Builder builder) { if (builder.name == null || builder.name.isEmpty()) { throw new IllegalArgumentException(); } this.name = builder.name; this.value = builder.value; this.domain = builder.domain; this.maxAge = builder.maxAge; this.path = builder.path; this.httpOnly = builder.httpOnly; this.secure = builder.secure; this.sameSite = builder.sameSite; this.hashCode = hash(name, value, domain, maxAge, path, secure, httpOnly, sameSite); } private ResponseCookie(Builder builder); static ResponseCookie.Builder responseCookie(String name, String value); static Set<ResponseCookie> decode(List<String> headerValues); String name(); String value(); Optional<Long> maxAge(); Optional<String> path(); boolean httpOnly(); Optional<String> domain(); boolean secure(); Optional<SameSite> sameSite(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void acceptsOnlyNonEmptyName() { assertThrows(IllegalArgumentException.class, () -> responseCookie("", "value").build()); } @Test public void acceptsOnlyNonNullName() { assertThrows(NullPointerException.class, () -> responseCookie(null, "value").build()); } @Test public void acceptsOnlyNonNullValue() { assertThrows(NullPointerException.class, () -> responseCookie("name", null).build()); }
### Question: HttpHeader { public static HttpHeader header(String name, String... values) { if (values.length <= 0) { throw new IllegalArgumentException("must give at least one value"); } return new HttpHeader(requireNonNull(name), ImmutableList.copyOf(values)); } private HttpHeader(String name, List<String> values); static HttpHeader header(String name, String... values); String name(); String value(); Iterable<String> values(); @Override int hashCode(); @Override boolean equals(Object o); @Override String toString(); }### Answer: @Test public void rejectsEmptyValuesList() { assertThrows(IllegalArgumentException.class, () -> header("name", new String[0])); } @Test public void valuesCannotBeNull() { assertThrows(NullPointerException.class, () -> header("name", "value1", null, "value2")); }
### Question: Eventual implements Publisher<T> { public static <T> Eventual<T> from(CompletionStage<T> completionStage) { return fromMono(Mono.fromCompletionStage(completionStage)); } Eventual(Publisher<T> publisher); static Eventual<T> of(T value); static Eventual<T> from(CompletionStage<T> completionStage); static Eventual<T> error(Throwable error); Eventual<R> map(Function<? super T, ? extends R> transformation); Eventual<R> flatMap(Function<? super T, ? extends Eventual<? extends R>> transformation); Eventual<T> onError(Function<Throwable, ? extends Eventual<? extends T>> errorHandler); @Override void subscribe(Subscriber<? super T> subscriber); }### Answer: @Test public void createFromPublisher() { String value = Mono.from(new Eventual<>(Flux.just("hello"))).block(); assertEquals(value, "hello"); } @Test public void createFromCompletionStage() { CompletableFuture<String> future = new CompletableFuture<>(); Eventual<String> eventual = Eventual.from(future); StepVerifier.create(eventual) .thenRequest(1) .expectNextCount(0) .then(() -> future.complete("hello")) .expectNext("hello") .verifyComplete(); }
### Question: Eventual implements Publisher<T> { public static <T> Eventual<T> of(T value) { return fromMono(Mono.just(value)); } Eventual(Publisher<T> publisher); static Eventual<T> of(T value); static Eventual<T> from(CompletionStage<T> completionStage); static Eventual<T> error(Throwable error); Eventual<R> map(Function<? super T, ? extends R> transformation); Eventual<R> flatMap(Function<? super T, ? extends Eventual<? extends R>> transformation); Eventual<T> onError(Function<Throwable, ? extends Eventual<? extends T>> errorHandler); @Override void subscribe(Subscriber<? super T> subscriber); }### Answer: @Test public void createFromValue() { StepVerifier.create(Eventual.of("x")) .expectNext("x") .verifyComplete(); }
### Question: Eventual implements Publisher<T> { public static <T> Eventual<T> error(Throwable error) { return fromMono(Mono.error(error)); } Eventual(Publisher<T> publisher); static Eventual<T> of(T value); static Eventual<T> from(CompletionStage<T> completionStage); static Eventual<T> error(Throwable error); Eventual<R> map(Function<? super T, ? extends R> transformation); Eventual<R> flatMap(Function<? super T, ? extends Eventual<? extends R>> transformation); Eventual<T> onError(Function<Throwable, ? extends Eventual<? extends T>> errorHandler); @Override void subscribe(Subscriber<? super T> subscriber); }### Answer: @Test public void createFromError() { Eventual<String> eventual = Eventual.error(new JustATestException()); StepVerifier.create(eventual) .expectError(RuntimeException.class) .verify(); }
### Question: Eventual implements Publisher<T> { public <R> Eventual<R> map(Function<? super T, ? extends R> transformation) { return fromMono(Mono.from(publisher).map(transformation)); } Eventual(Publisher<T> publisher); static Eventual<T> of(T value); static Eventual<T> from(CompletionStage<T> completionStage); static Eventual<T> error(Throwable error); Eventual<R> map(Function<? super T, ? extends R> transformation); Eventual<R> flatMap(Function<? super T, ? extends Eventual<? extends R>> transformation); Eventual<T> onError(Function<Throwable, ? extends Eventual<? extends T>> errorHandler); @Override void subscribe(Subscriber<? super T> subscriber); }### Answer: @Test public void mapsValues() { StepVerifier.create(new Eventual<>(Flux.just("hello")).map(String::toUpperCase)) .expectNext("HELLO") .verifyComplete(); }
### Question: HttpMessageSupport { public static boolean chunked(HttpHeaders headers) { for (String value : headers.getAll(TRANSFER_ENCODING)) { if (value.equalsIgnoreCase(CHUNKED.toString())) { return true; } } return false; } private HttpMessageSupport(); static boolean chunked(HttpHeaders headers); static boolean keepAlive(HttpHeaders headers, HttpVersion version); }### Answer: @Test public void chunkedReturnsTrueWhenChunkedTransferEncodingIsSet() { HttpHeaders headers = requestBuilder() .header(TRANSFER_ENCODING, CHUNKED) .build() .headers(); assertThat(chunked(headers), is(true)); HttpHeaders headers2 = requestBuilder() .header(TRANSFER_ENCODING, "foo") .addHeader(TRANSFER_ENCODING, CHUNKED) .addHeader(TRANSFER_ENCODING, "bar") .build() .headers(); assertThat(chunked(headers2), is(true)); } @Test public void chunkedReturnsFalseWhenChunkedTransferEncodingIsNotSet() { HttpHeaders headers = requestBuilder() .header(TRANSFER_ENCODING, "foo") .build() .headers(); assertThat(chunked(headers), is(false)); } @Test public void chunkedReturnsTrueWhenChunkedTransferEncodingIsAbsent() { HttpHeaders headers = requestBuilder().build().headers(); assertThat(chunked(headers), is(false)); }
### Question: HttpMessageSupport { public static boolean keepAlive(HttpHeaders headers, HttpVersion version) { Optional<String> connection = headers.get(CONNECTION); if (connection.isPresent()) { if (CLOSE.toString().equalsIgnoreCase(connection.get())) { return false; } if (KEEP_ALIVE.toString().equalsIgnoreCase(connection.get())) { return true; } } return version.isKeepAliveDefault(); } private HttpMessageSupport(); static boolean chunked(HttpHeaders headers); static boolean keepAlive(HttpHeaders headers, HttpVersion version); }### Answer: @Test public void keepAliveReturnsTrueWhenHttpConnectionMustBeKeptAlive() { HttpHeaders connectionHeaderAbsent = requestBuilder().build().headers(); HttpHeaders connectionHeaderClose = requestBuilder() .header(CONNECTION, CLOSE) .build() .headers(); HttpHeaders connectionHeaderKeepAlive = requestBuilder() .header(CONNECTION, KEEP_ALIVE) .build() .headers(); assertThat(keepAlive(connectionHeaderAbsent, HTTP_1_0), is(false)); assertThat(keepAlive(connectionHeaderAbsent, HTTP_1_1), is(true)); assertThat(keepAlive(connectionHeaderClose, HTTP_1_0), is(false)); assertThat(keepAlive(connectionHeaderClose, HTTP_1_1), is(false)); assertThat(keepAlive(connectionHeaderKeepAlive, HTTP_1_0), is(true)); assertThat(keepAlive(connectionHeaderKeepAlive, HTTP_1_1), is(true)); }
### Question: LiveHttpRequest implements LiveHttpMessage { public static Builder get(String uri) { return new Builder(GET, uri); } LiveHttpRequest(Builder builder); static Builder get(String uri); static Builder head(String uri); static Builder post(String uri); static Builder delete(String uri); static Builder put(String uri); static Builder patch(String uri); static Builder post(String uri, ByteStream body); static Builder put(String uri, ByteStream body); static Builder patch(String uri, ByteStream body); @Override HttpVersion version(); @Override HttpHeaders headers(); @Override List<String> headers(CharSequence name); @Override ByteStream body(); Object id(); HttpMethod method(); Url url(); String path(); boolean keepAlive(); Optional<String> queryParam(String name); Iterable<String> queryParams(String name); Map<String, List<String>> queryParams(); Iterable<String> queryParamNames(); Transformer newBuilder(); Eventual<HttpRequest> aggregate(int maxContentBytes); Set<RequestCookie> cookies(); Optional<RequestCookie> cookie(String name); @Override String toString(); }### Answer: @Test public void rejectsMultipleContentLengthInSingleHeader() { assertThrows(IllegalArgumentException.class, () -> get("/foo") .addHeader(CONTENT_LENGTH, "15, 16") .build()); } @Test public void rejectsMultipleContentLengthHeaders() { assertThrows(IllegalArgumentException.class, () -> get("/foo") .addHeader(CONTENT_LENGTH, "15") .addHeader(CONTENT_LENGTH, "16") .build()); } @Test public void rejectsInvalidContentLength() { assertThrows(IllegalArgumentException.class, () -> get("/foo") .addHeader(CONTENT_LENGTH, "foo") .build()); } @Test public void setsHostHeaderFromAuthorityIfSet() { LiveHttpRequest request = get("http: assertThat(request.header(HOST), isValue("www.hotels.com")); }
### Question: LiveHttpRequest implements LiveHttpMessage { public static Builder post(String uri) { return new Builder(POST, uri); } LiveHttpRequest(Builder builder); static Builder get(String uri); static Builder head(String uri); static Builder post(String uri); static Builder delete(String uri); static Builder put(String uri); static Builder patch(String uri); static Builder post(String uri, ByteStream body); static Builder put(String uri, ByteStream body); static Builder patch(String uri, ByteStream body); @Override HttpVersion version(); @Override HttpHeaders headers(); @Override List<String> headers(CharSequence name); @Override ByteStream body(); Object id(); HttpMethod method(); Url url(); String path(); boolean keepAlive(); Optional<String> queryParam(String name); Iterable<String> queryParams(String name); Map<String, List<String>> queryParams(); Iterable<String> queryParamNames(); Transformer newBuilder(); Eventual<HttpRequest> aggregate(int maxContentBytes); Set<RequestCookie> cookies(); Optional<RequestCookie> cookie(String name); @Override String toString(); }### Answer: @Test public void ensuresContentLengthIsPositive() { Exception e = assertThrows(IllegalArgumentException.class, () -> LiveHttpRequest.post("/y") .header("Content-Length", -3) .build()); assertEquals("Invalid Content-Length found. -3", e.getMessage()); }
### Question: HttpRequest implements HttpMessage { public static Builder get(String uri) { return new Builder(GET, uri); } HttpRequest(Builder builder); static Builder get(String uri); static Builder head(String uri); static Builder post(String uri); static Builder delete(String uri); static Builder put(String uri); static Builder patch(String uri); @Override HttpVersion version(); @Override HttpHeaders headers(); @Override List<String> headers(CharSequence name); @Override byte[] body(); @Override String bodyAs(Charset charset); Object id(); HttpMethod method(); Url url(); String path(); boolean keepAlive(); Optional<String> queryParam(String name); Iterable<String> queryParams(String name); Map<String, List<String>> queryParams(); Iterable<String> queryParamNames(); Builder newBuilder(); LiveHttpRequest stream(); Set<RequestCookie> cookies(); Optional<RequestCookie> cookie(String name); @Override String toString(); }### Answer: @Test public void rejectsMultipleContentLengthInSingleHeader() { assertThrows(IllegalArgumentException.class, () -> get("/foo") .addHeader(CONTENT_LENGTH, "15, 16") .build()); } @Test public void rejectsMultipleContentLengthHeaders() { assertThrows(IllegalArgumentException.class, () -> get("/foo") .addHeader(CONTENT_LENGTH, "15") .addHeader(CONTENT_LENGTH, "16") .build()); } @Test public void rejectsInvalidContentLength() { assertThrows(IllegalArgumentException.class, () -> get("/foo") .addHeader(CONTENT_LENGTH, "foo") .build()); } @Test public void setsHostHeaderFromAuthorityIfSet() { HttpRequest request = get("http: assertThat(request.header(HOST), isValue("www.hotels.com")); }
### Question: HttpRequest implements HttpMessage { public static Builder post(String uri) { return new Builder(POST, uri); } HttpRequest(Builder builder); static Builder get(String uri); static Builder head(String uri); static Builder post(String uri); static Builder delete(String uri); static Builder put(String uri); static Builder patch(String uri); @Override HttpVersion version(); @Override HttpHeaders headers(); @Override List<String> headers(CharSequence name); @Override byte[] body(); @Override String bodyAs(Charset charset); Object id(); HttpMethod method(); Url url(); String path(); boolean keepAlive(); Optional<String> queryParam(String name); Iterable<String> queryParams(String name); Map<String, List<String>> queryParams(); Iterable<String> queryParamNames(); Builder newBuilder(); LiveHttpRequest stream(); Set<RequestCookie> cookies(); Optional<RequestCookie> cookie(String name); @Override String toString(); }### Answer: @Test public void ensuresContentLengthIsPositive() { Exception e = assertThrows(IllegalArgumentException.class, () -> HttpRequest.post("/y") .header("Content-Length", -3) .build()); assertEquals("Invalid Content-Length found. -3", e.getMessage()); }
### Question: RewriteConfig implements RewriteRule { @Override public Optional<String> rewrite(String originalUri) { Matcher matcher = compiledUrlPattern.matcher(originalUri); if (matcher.matches()) { return Optional.of(preprocessedReplacement.substitute(matcher)); } return Optional.empty(); } RewriteConfig(String urlPattern, String replacement); String urlPattern(); String replacement(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override Optional<String> rewrite(String originalUri); }### Answer: @Test public void testSubstitutions() { String urlPattern = "\\/foo\\/(a|b|c)(\\/.*)?"; RewriteConfig config = new RewriteConfig(urlPattern, "/bar/$1$2"); assertThat(config.rewrite("/foo/b/something").get(), CoreMatchers.equalTo("/bar/b/something")); config = new RewriteConfig(urlPattern, "/bar/$1/x$2"); assertThat(config.rewrite("/foo/b/something").get(), CoreMatchers.equalTo("/bar/b/x/something")); config = new RewriteConfig(urlPattern, "/bar/$1/x$2/y"); assertThat(config.rewrite("/foo/b/something").get(), CoreMatchers.equalTo("/bar/b/x/something/y")); config = new RewriteConfig(urlPattern, "$1/x$2/y"); assertThat(config.rewrite("/foo/b/something").get(), CoreMatchers.equalTo("b/x/something/y")); config = new RewriteConfig(urlPattern, "$1$2/y"); assertThat(config.rewrite("/foo/b/something").get(), CoreMatchers.equalTo("b/something/y")); config = new RewriteConfig(urlPattern, "$1$2"); assertThat(config.rewrite("/foo/b/something").get(), CoreMatchers.equalTo("b/something")); }
### Question: AbstractStyxService implements StyxService { @Override public Map<String, HttpHandler> adminInterfaceHandlers() { return ImmutableMap.of("status", (request, context) -> Eventual.of( response(OK) .addHeader(CONTENT_TYPE, APPLICATION_JSON) .body(format("{ name: \"%s\" status: \"%s\" }", name, status), UTF_8) .build() .stream())); } AbstractStyxService(String name); StyxServiceStatus status(); @Override CompletableFuture<Void> start(); @Override CompletableFuture<Void> stop(); @Override Map<String, HttpHandler> adminInterfaceHandlers(); String serviceName(); }### Answer: @Test public void exposesNameAndStatusViaAdminInterface() throws ExecutionException, InterruptedException { DerivedStyxService service = new DerivedStyxService("derived-service", new CompletableFuture<>()); HttpResponse response = Mono.from(service.adminInterfaceHandlers().get("status").handle(get, MOCK_CONTEXT) .flatMap(r -> r.aggregate(1024))).block(); assertThat(response.bodyAs(UTF_8), is("{ name: \"derived-service\" status: \"CREATED\" }")); }
### Question: HttpResponse implements HttpMessage { public static Builder response() { return new Builder(); } private HttpResponse(Builder builder); static Builder response(); static Builder response(HttpResponseStatus status); @Override Optional<String> header(CharSequence name); @Override List<String> headers(CharSequence name); @Override HttpHeaders headers(); @Override byte[] body(); @Override String bodyAs(Charset charset); @Override HttpVersion version(); Builder newBuilder(); HttpResponseStatus status(); boolean isRedirect(); LiveHttpResponse stream(); Set<ResponseCookie> cookies(); Optional<ResponseCookie> cookie(String name); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void shouldCreateAChunkedResponse() { assertThat(HttpResponse.response().build().chunked(), is(false)); assertThat(HttpResponse.response().setChunked().build().chunked(), is(true)); } @Test public void rejectsMultipleContentLengthInSingleHeader() { assertThrows(IllegalArgumentException.class, () -> HttpResponse.response() .addHeader(CONTENT_LENGTH, "15, 16") .ensureContentLengthIsValid() .build()); } @Test public void rejectsMultipleContentLength() { assertThrows(IllegalArgumentException.class, () -> HttpResponse.response() .addHeader(CONTENT_LENGTH, "15") .addHeader(CONTENT_LENGTH, "16") .ensureContentLengthIsValid() .build()); } @Test public void rejectsInvalidContentLength() { assertThrows(IllegalArgumentException.class, () -> HttpResponse.response() .addHeader(CONTENT_LENGTH, "foo") .ensureContentLengthIsValid() .build()); }
### Question: GraphiteReporter extends ScheduledReporter { @Override public void stop() { try { super.stop(); } finally { try { graphite.close(); } catch (IOException e) { LOGGER.debug("Error disconnecting from Graphite", e); } } } private GraphiteReporter(MetricRegistry registry, GraphiteSender graphite, Clock clock, String prefix, TimeUnit rateUnit, TimeUnit durationUnit, MetricFilter filter); static Builder forRegistry(MetricRegistry registry); @Override void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters, SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers); @Override void stop(); }### Answer: @Test public void closesConnectionOnReporterStop() throws Exception { reporter.stop(); verify(graphite).close(); verifyNoMoreInteractions(graphite); }
### Question: UrlQuery { String encodedQuery() { return encodedQuery; } private UrlQuery(List<Parameter> parameters); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void providesEncodedQuery() { assertThat(query.encodedQuery(), is("foo=alpha&bar=beta&foo=gamma")); }
### Question: UrlQuery { Iterable<String> parameterNames() { return parameters().stream().map(Parameter::key).distinct().collect(toList()); } private UrlQuery(List<Parameter> parameters); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void providesParameterNames() { assertThat(query.parameterNames(), contains("foo", "bar")); }
### Question: UrlQuery { Optional<String> parameterValue(String name) { return stream(parameterValues(name).spliterator(), false).findFirst(); } private UrlQuery(List<Parameter> parameters); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void providesValueByKey() { assertThat(query.parameterValue("foo"), isValue("alpha")); assertThat(query.parameterValue("bar"), isValue("beta")); assertThat(query.parameterValue("no_such_key"), isAbsent()); }
### Question: UrlQuery { Iterable<String> parameterValues(String name) { return parameters().stream() .filter(parameter -> parameter.key.equals(name)) .map(Parameter::value) .collect(toList()); } private UrlQuery(List<Parameter> parameters); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void providesValuesByKey() { assertThat(query.parameterValues("foo"), contains("alpha", "gamma")); assertThat(query.parameterValues("bar"), contains("beta")); assertThat(query.parameterValues("no_such_key"), is(emptyIterable())); }
### Question: UrlQuery { List<Parameter> parameters() { return parameters; } private UrlQuery(List<Parameter> parameters); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void providesFullParameters() { assertThat(query.parameters(), contains( new Parameter("foo", "alpha"), new Parameter("bar", "beta"), new Parameter("foo", "gamma") )); }
### Question: UrlQuery { Builder newBuilder() { return new Builder(this); } private UrlQuery(List<Parameter> parameters); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void buildsNewQueryFromExistingQuery() { assertThat(query.newBuilder().build(), equalTo(query)); }
### Question: RequestCookie { private RequestCookie(String name, String value) { if (name == null || name.isEmpty()) { throw new IllegalArgumentException("name cannot be null or empty"); } requireNonNull(value, "value cannot be null"); this.name = name; this.value = value; this.hashCode = Objects.hash(name, value); } private RequestCookie(String name, String value); static RequestCookie requestCookie(String name, String value); static Set<RequestCookie> decode(String headerValue); static String encode(Collection<RequestCookie> cookies); String name(); String value(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer: @Test public void acceptsOnlyNonEmptyName() { assertThrows(IllegalArgumentException.class, () -> requestCookie("", "value")); } @Test public void acceptsOnlyNonNullName() { assertThrows(IllegalArgumentException.class, () -> requestCookie(null, "value")); } @Test public void acceptsOnlyNonNullValue() { assertThrows(NullPointerException.class, () -> requestCookie("name", null)); }
### Question: RouteHandlerAdapter implements RoutingObject { @Override public Eventual<LiveHttpResponse> handle(LiveHttpRequest request, HttpInterceptor.Context context) { return router.route(request, context) .map(handler -> handler.handle(request, context)) .orElseGet(() -> Eventual.error(new NoServiceConfiguredException(request.path()))); } RouteHandlerAdapter(HttpRouter router); @Override Eventual<LiveHttpResponse> handle(LiveHttpRequest request, HttpInterceptor.Context context); }### Answer: @Test public void injectsToPipelineWhenRouteFound() { HttpHandler pipeline = mock(HttpHandler.class); when(pipeline.handle(any(LiveHttpRequest.class), any(HttpInterceptor.Context.class))).thenReturn(Eventual.of(respOk)); HttpRouter router = mock(HttpRouter.class); when(router.route(any(LiveHttpRequest.class), any(HttpInterceptor.Context.class))).thenReturn(Optional.of(pipeline)); LiveHttpResponse response = Mono.from(new RouteHandlerAdapter(router).handle(request, requestContext())).block(); assertThat(response.status(), is(OK)); }
### Question: Url implements Comparable<Url> { private Url(Builder builder) { this.scheme = builder.scheme; this.authority = builder.authority; this.path = builder.path; this.query = Optional.ofNullable(builder.queryBuilder).map(UrlQuery.Builder::build); this.fragment = builder.fragment; } private Url(Builder builder); String scheme(); String path(); Optional<String> fragment(); Optional<Authority> authority(); Optional<String> host(); boolean isSecure(); boolean isFullyQualified(); boolean isAbsolute(); boolean isRelative(); URL toURL(); URI toURI(); Optional<String> queryParam(String name); Iterable<String> queryParams(String name); Map<String, List<String>> queryParams(); Iterable<String> queryParamNames(); String encodedUri(); @Override String toString(); @Override int compareTo(Url other); @Override int hashCode(); @Override boolean equals(Object obj); Builder newBuilder(); }### Answer: @Test public void unwiseCharsAreNotAccepted() throws Exception { String urlWithUnwiseChars = "/search.do?foo={&srsReport=Landing|AutoS|HOTEL|Hotel%20Il%20Duca%20D%27Este|0|0|0|2|1|2|284128&srsr=Landing|AutoS|HOTEL|Hotel%20Il%20Duca%20D%27Este|0|0|0|2|1|2|284128"; assertThrows(IllegalArgumentException.class, () -> url(urlWithUnwiseChars).build()); }
### Question: PluginsMetadata implements Iterable<SpiExtension> { public List<Pair<String, SpiExtension>> activePlugins() { return activePluginsNames.stream() .map(name -> pair(name, plugins.get(name))) .collect(toList()); } PluginsMetadata(@JsonProperty("active") String active, @JsonProperty("all") Map<String, SpiExtension> plugins); List<Pair<String, SpiExtension>> plugins(); List<Pair<String, SpiExtension>> activePlugins(); @Override String toString(); @Override Iterator<SpiExtension> iterator(); }### Answer: @Test public void pluginsAreProvidedInOrderSpecifiedByActivePluginsCommaSeparatedList() { Map<String, SpiExtension> plugins = new LinkedHashMap<>(); Stream.of("two", "four", "three", "one") .forEach(key -> plugins.put(key, pluginMetadata())); PluginsMetadata pluginsMetadata = new PluginsMetadata("one,two,three,four", plugins); List<String> activePlugins = pluginsMetadata.activePlugins().stream() .map(Pair::key) .collect(toList()); assertThat(activePlugins, contains("one", "two", "three", "four")); }
### Question: SlidingWindowHistogram { public synchronized void recordValue(long msValue) { checkArgument(msValue >= 0, "Recorded value must be a positive number."); long currentTime = clock.tickMillis(); purgeOldHistograms(currentTime); int bucket = bucketFromTime(currentTime); window[bucket].recordValue(msValue); lastUpdateTime = currentTime; } private SlidingWindowHistogram(Builder builder); synchronized void recordValue(long msValue); synchronized double getMean(); synchronized double getValueAtPercentile(double percentile); synchronized double getStdDeviation(); synchronized Histogram copy(); int windowSize(); long timeIntervalMs(); }### Answer: @Test public void doesNotAcceptNegativeValues() { assertThrows(IllegalArgumentException.class, () -> newHistogram(2, 2).recordValue(-1)); }
### Question: SlidingWindowHistogramReservoir implements Reservoir { @Override public synchronized Snapshot getSnapshot() { if (updated || snapshotExpired(clock.tickMillis())) { snapshot = new HistogramSnapshot(histogram); updated = false; snapshotCreationTime = clock.tickMillis(); } return snapshot; } SlidingWindowHistogramReservoir(); SlidingWindowHistogramReservoir(SlidingWindowHistogram histogram); SlidingWindowHistogramReservoir(SlidingWindowHistogram histogram, Clock clock); @Override int size(); @Override synchronized void update(long value); @Override synchronized Snapshot getSnapshot(); }### Answer: @Test public void snapshotComputesPercentiles() { SlidingWindowHistogramReservoir reservoir = reservoirWithSamples(1, 100); assertThat(reservoir.getSnapshot().getMin(), is(1L)); assertThat(reservoir.getSnapshot().getMax(), is(100L)); assertThat(reservoir.getSnapshot().getMean(), is(closeTo(50.5, 1))); assertThat(reservoir.getSnapshot().get75thPercentile(), is(closeTo(75, 0.5))); assertThat(reservoir.getSnapshot().get95thPercentile(), is(closeTo(95, 0.5))); assertThat(reservoir.getSnapshot().get98thPercentile(), is(closeTo(98, 0.5))); assertThat(reservoir.getSnapshot().get99thPercentile(), is(closeTo(99, 0.5))); assertThat(reservoir.getSnapshot().getMedian(), is(closeTo(50L, 1))); } @Test public void snapshotExposesSamplesAsArray() { SlidingWindowHistogramReservoir reservoir = reservoirWithSamples(1, 100); assertThat(reservoir.getSnapshot().getValues(), is(toArray(Range.closed(1L, 100L)))); }
### Question: Announcer { public static <T extends EventListener> Announcer<T> to(Class<? extends T> listenerType) { return new Announcer<>(listenerType); } Announcer(Class<? extends T> listenerType); static Announcer<T> to(Class<? extends T> listenerType); void addListener(T listener); void removeListener(T listener); T announce(); List<T> listeners(); }### Answer: @Test public void createsAnnouncerForType() { Announcer<AnnouncerTestListener> announcer = Announcer.to(AnnouncerTestListener.class); assertThat(announcer, is(notNullValue())); }
### Question: DocumentFormat { public static Builder newDocument() { return new Builder(); } private DocumentFormat(Builder builder); void validateObject(JsonNode tree); static Builder newDocument(); }### Answer: @Test public void discriminatedUnionSelectorMustBeString() { Exception e = assertThrows(InvalidSchemaException.class, () -> newDocument() .rootSchema(object( field("httpPipeline", object( field("type", integer()), field("config", union("type")) )) ) ).build()); assertThat(e.getMessage(), matchesPattern("Discriminator attribute 'type' must be a string \\(but it is not\\)")); }
### Question: FileSystemPluginFactoryLoader implements PluginFactoryLoader { @Override public PluginFactory load(SpiExtension spiExtension) { return newPluginFactory(spiExtension); } @Override PluginFactory load(SpiExtension spiExtension); }### Answer: @Test public void pluginLoaderLoadsPluginFromJarFile() { SpiExtensionFactory factory = new SpiExtensionFactory("testgrp.TestPluginModule", pluginsPath.toString()); PluginFactory plugin = pluginFactoryLoader.load(new SpiExtension(factory, config, null)); assertThat(plugin, is(not(nullValue()))); assertThat(plugin.getClass().getName(), is("testgrp.TestPluginModule")); } @Test public void providesMeaningfulErrorMessageWhenConfiguredFactoryClassCannotBeLoaded() { String jarFile = "/plugins/oneplugin/testPluginA-1.0-SNAPSHOT.jar"; Path pluginsPath = fixturesHome(FileSystemPluginFactoryLoader.class, jarFile); SpiExtensionFactory factory = new SpiExtensionFactory("incorrect.plugin.class.name.TestPluginModule", pluginsPath.toString()); SpiExtension spiExtension = new SpiExtension(factory, config, null); Exception e = assertThrows(ConfigurationException.class, () -> new FileSystemPluginFactoryLoader().load(spiExtension)); assertThat(e.getMessage(), matchesPattern("Could not load a plugin factory for configuration=SpiExtension\\{" + "factory=SpiExtensionFactory\\{" + "class=incorrect.plugin.class.name.TestPluginModule, " + "classPath=.*[\\\\/]components[\\\\/]proxy[\\\\/]target[\\\\/]test-classes[\\\\/]plugins[\\\\/]oneplugin[\\\\/]testPluginA-1.0-SNAPSHOT.jar" + "\\}\\}")); }
### Question: Schema { private Schema(Builder builder) { this.fieldNames = builder.fields.stream().map(Field::name).collect(toList()); this.fields = ImmutableList.copyOf(builder.fields); this.optionalFields = ImmutableSet.copyOf(builder.optionalFields); this.constraints = ImmutableList.copyOf(builder.constraints); this.ignore = builder.pass; this.name = builder.name.length() > 0 ? builder.name : String.join(", ", this.fieldNames); } private Schema(Builder builder); Set<String> optionalFields(); List<String> fieldNames(); List<Field> fields(); List<Constraint> constraints(); String name(); boolean ignore(); Builder newBuilder(); }### Answer: @Test public void list_checksThatSubobjectUnionDiscriminatorAttributeExists() throws Exception { Exception e = assertThrows(InvalidSchemaException.class, () -> schema(field("name", string()), field("config", union("type")) )); assertEquals("Discriminator attribute 'type' not present.", e.getMessage()); } @Test public void checksThatSubobjectUnionDiscriminatorAttributeIsString() throws Exception { Exception e = assertThrows(InvalidSchemaException.class, () -> schema(field("name", string()), field("type", integer()), field("config", union("type")) )); assertThat(e.getMessage(), matchesPattern("Discriminator attribute 'type' must be a string \\(but it is not\\)")); }
### Question: AtLeastOneFieldPresenceConstraint implements Constraint { @Override public String describe() { return description; } AtLeastOneFieldPresenceConstraint(String... fieldNames); @Override boolean evaluate(Schema schema, JsonNode node); @Override String describe(); }### Answer: @Test public void describesItsBehaviour() { AtLeastOneFieldPresenceConstraint constraint = new AtLeastOneFieldPresenceConstraint("http", "https"); assertThat(constraint.describe(), is("At least one of ('http', 'https') must be present.")); }
### Question: AtLeastOneFieldPresenceConstraint implements Constraint { @Override public boolean evaluate(Schema schema, JsonNode node) { long fieldsPresent = ImmutableList.copyOf(node.fieldNames()) .stream() .filter(fieldNames::contains) .count(); return fieldsPresent >= 1; } AtLeastOneFieldPresenceConstraint(String... fieldNames); @Override boolean evaluate(Schema schema, JsonNode node); @Override String describe(); }### Answer: @Test public void passesWhenOneRequiredFieldIsPresent() throws IOException { AtLeastOneFieldPresenceConstraint constraint = new AtLeastOneFieldPresenceConstraint("http", "https"); boolean result = constraint.evaluate( schema( field("x", integer()), field("http", integer()), field("https", integer()), atLeastOne("http", "https")), jsonNode( " http: 8080\n" )); assertThat(result, is(true)); } @Test public void allowsSeveralFieldsToBePresent() throws IOException { AtLeastOneFieldPresenceConstraint constraint = new AtLeastOneFieldPresenceConstraint("http", "https"); boolean result = constraint.evaluate( schema( field("x", integer()), field("http", integer()), field("https", integer()), atLeastOne("http", "https")), jsonNode( " https: 8443\n" + " http: 8080\n" )); assertThat(result, is(true)); } @Test public void throwsExceptionWhenNoneRequiredFieldsArePresent() throws IOException { AtLeastOneFieldPresenceConstraint constraint = new AtLeastOneFieldPresenceConstraint("http", "https"); boolean result = constraint.evaluate( schema( field("x", integer()), field("http", integer()), field("https", integer()), atLeastOne("http", "https")), jsonNode( " x: 43\n" )); assertThat(result, is(false)); }
### Question: HttpAggregator implements HttpHandler { @Override public Eventual<LiveHttpResponse> handle(LiveHttpRequest request, HttpInterceptor.Context context) { return request.aggregate(bytes) .flatMap(aggregated -> this.delegate.handle(aggregated, context)) .map(HttpResponse::stream); } HttpAggregator(int bytes, WebServiceHandler delegate); HttpAggregator(WebServiceHandler delegate); @Override Eventual<LiveHttpResponse> handle(LiveHttpRequest request, HttpInterceptor.Context context); }### Answer: @Test public void aggregatesRequestAndStreamsResponses() { AtomicReference<String> result = new AtomicReference<>(); WebServiceHandler webServiceHandler = (request, ctx) -> { result.set(request.bodyAs(UTF_8)); return Eventual.of(response(OK) .body("abcdef", UTF_8) .build()); }; LiveHttpResponse response = Mono.from( new HttpAggregator(500, webServiceHandler) .handle(LiveHttpRequest.post("/") .body(ByteStream.from("ABCDEF", UTF_8)) .build(), requestContext())) .block(); assertThat(result.get(), is("ABCDEF")); assertThat(Mono.from(response.aggregate(500)).block().bodyAs(UTF_8), is("abcdef")); }
### Question: HttpStreamer implements WebServiceHandler { @Override public Eventual<HttpResponse> handle(HttpRequest request, HttpInterceptor.Context context) { return delegate.handle(request.stream(), context) .flatMap(live -> live.aggregate(maxContentBytes)); } HttpStreamer(int maxContentBytes, HttpHandler delegate); HttpStreamer(HttpHandler delegate); @Override Eventual<HttpResponse> handle(HttpRequest request, HttpInterceptor.Context context); }### Answer: @Test public void streamsRequestAndAggregatesResponses() { HttpHandler httpHandler = (request, ctx) -> Eventual.of( LiveHttpResponse.response(OK) .body(ByteStream.from("abcdef", UTF_8)) .build()); HttpResponse response = Mono.from( new HttpStreamer(500, httpHandler) .handle(HttpRequest.post("/") .body("ABCDEF", UTF_8) .build(), requestContext())) .block(); assertThat(response.bodyAs(UTF_8), is("abcdef")); }
### Question: HttpMethodFilteringHandler implements WebServiceHandler { @Override public Eventual<HttpResponse> handle(HttpRequest request, HttpInterceptor.Context context) { if (!method.equals(request.method())) { return Eventual.of( HttpResponse.response(METHOD_NOT_ALLOWED) .body(errorBody, StandardCharsets.UTF_8) .build() ); } return httpHandler.handle(request, context); } HttpMethodFilteringHandler(HttpMethod method, WebServiceHandler httpHandler); @Override Eventual<HttpResponse> handle(HttpRequest request, HttpInterceptor.Context context); }### Answer: @Test public void delegatesTheRequestIfRequestMethodIsSupported() { WebServiceHandler handler = mock(WebServiceHandler.class); HttpMethodFilteringHandler post = new HttpMethodFilteringHandler(POST, handler); HttpRequest request = post("/some-uri").build(); post.handle(request, mock(HttpInterceptor.Context.class)); verify(handler).handle(eq(request), any(HttpInterceptor.Context.class)); } @Test public void failsIfRequestMethodIsNotSupported() throws Exception { WebServiceHandler handler = mock(WebServiceHandler.class); HttpMethodFilteringHandler post = new HttpMethodFilteringHandler(GET, handler); HttpRequest request = post("/some-uri").build(); HttpResponse response = Mono.from(post.handle(request, requestContext())).block(); assertThat(response.status(), is(METHOD_NOT_ALLOWED)); }
### Question: FsmEventProcessor implements EventProcessor { @Override public void submit(Object event) { requireNonNull(event); try { stateMachine.handle(event, loggingPrefix); } catch (Throwable cause) { String eventName = event.getClass().getSimpleName(); LOGGER.error("{} {} -> ???: Exception occurred while processing event={}. Cause=\"{}\"", new Object[]{loggingPrefix, stateMachine.currentState(), eventName, cause}); errorHandler.accept(cause, stateMachine.currentState()); } } FsmEventProcessor(StateMachine<S> stateMachine, BiConsumer<Throwable, S> errorHandler, String loggingPrefix); @Override void submit(Object event); }### Answer: @Test public void throwsNullPointerExceptionForNullEvents() { FsmEventProcessor<String> processor = new FsmEventProcessor<>(stateMachine, errorHandler, "prefix"); assertThrows(NullPointerException.class, () -> processor.submit(null)); } @Test public void propagatesEventToFsm() { FsmEventProcessor<String> processor = new FsmEventProcessor<>(stateMachine, errorHandler, "prefix"); processor.submit(new TestEventOk()); assertThat(stateMachine.currentState(), is("end")); } @Test public void handlesStateMachineExceptions() { FsmEventProcessor<String> processor = new FsmEventProcessor<>(stateMachine, errorHandler, "prefix"); processor.submit(new TestEventError()); verify(errorHandler).accept(any(RuntimeException.class), eq("start")); assertThat(logger.lastMessage(), is( loggingEvent( ERROR, "prefix start -> \\?\\?\\?: Exception occurred while processing event=TestEventError. Cause=.*", RuntimeException.class, "Test exception message"))); }
### Question: FileResourceIndex implements ResourceIndex { @Override public Iterable<Resource> list(String path, String suffix) { ArrayList<Resource> list = new ArrayList<>(); new FileResourceIterator(new File(path), new File(path), suffix).forEachRemaining(list::add); return list; } @Override Iterable<Resource> list(String path, String suffix); }### Answer: @Test public void listsResourcesFromFileSystemDirectory() { Iterable<Resource> jars = resourceIndex.list(PLUGINS_FIXTURE_PATH.toString(), ".jar"); assertThat(jars, contains(resourceWithPath("oneplugin/url-rewrite-1.0-SNAPSHOT.jar"))); } @Test public void listsResourcesFromFileSystemFile() { File file = new File(PLUGINS_FIXTURE_PATH.toFile(), "groovy/UrlRewrite.groovy"); Iterable<Resource> files = resourceIndex.list(file.getPath(), ".anything"); assertThat(files, contains(resourceWithPath( PLUGINS_FIXTURE_PATH.resolve("groovy/UrlRewrite.groovy").toString()))); }
### Question: ClasspathResourceIndex implements ResourceIndex { @Override public Iterable<Resource> list(String path, String suffix) { String classpath = path.replace("classpath:", ""); ResourceIteratorFactory resourceIteratorFactory = new DelegatingResourceIteratorFactory(); try { Enumeration<URL> resources = classLoader.getResources(classpath); return enumerationStream(resources) .map(url -> resourceIteratorFactory.createIterator(url, classpath, suffix)) .flatMap(ClasspathResourceIndex::iteratorStream) .collect(toList()); } catch (IOException e) { throw new RuntimeException(e); } } ClasspathResourceIndex(ClassLoader classLoader); @Override Iterable<Resource> list(String path, String suffix); }### Answer: @Test public void listsByPathAndSuffix() { ClassLoader classLoader = ClasspathResourceIndexTest.class.getClassLoader(); ClasspathResourceIndex index = new ClasspathResourceIndex(classLoader); Iterable<Resource> resources = index.list("com/hotels/styx/common/io", ".txt"); assertThat(resources, containsInAnyOrder( resourceWithPath("resource.txt"), resourceWithPath("subdirectory/subdir-resource.txt") )); }
### Question: FileResource implements Resource { @Override public InputStream inputStream() throws IOException { return new FileInputStream(file); } FileResource(File file); FileResource(File root, File file); FileResource(String path); @Override String path(); @Override URL url(); @Override String absolutePath(); @Override InputStream inputStream(); @Override ClassLoader classLoader(); File getFile(); @Override String toString(); static final String FILE_SCHEME; }### Answer: @Test public void nonExistentResourceThrowsExceptionWhenTryingToGetInputStream() throws IOException { FileResource resource = new FileResource("foobar"); Exception e = assertThrows(FileNotFoundException.class, () -> resource.inputStream()); assertThat(e.getMessage(), matchesPattern("foobar.*")); }
### Question: ClasspathResource implements Resource { @Override public URL url() { URL url = this.classLoader.getResource(this.path); if (url == null) { throw new RuntimeException(new FileNotFoundException(this.path)); } return url; } ClasspathResource(String path, Class<?> clazz); ClasspathResource(String path, ClassLoader classLoader); @Override String path(); @Override URL url(); @Override String absolutePath(); @Override InputStream inputStream(); @Override ClassLoader classLoader(); @Override String toString(); static final String CLASSPATH_SCHEME; }### Answer: @Test public void nonExistentResourceThrowsExceptionWhenTryingToGetURL() { ClasspathResource resource = new ClasspathResource("foobar", ClasspathResourceTest.class); Exception e = assertThrows(RuntimeException.class, () -> resource.url()); assertEquals("java.io.FileNotFoundException: foobar", e.getMessage()); }
### Question: ClasspathResource implements Resource { @Override public InputStream inputStream() throws FileNotFoundException { InputStream stream = classLoader.getResourceAsStream(this.path); if (stream == null) { throw new FileNotFoundException(CLASSPATH_SCHEME + path); } return stream; } ClasspathResource(String path, Class<?> clazz); ClasspathResource(String path, ClassLoader classLoader); @Override String path(); @Override URL url(); @Override String absolutePath(); @Override InputStream inputStream(); @Override ClassLoader classLoader(); @Override String toString(); static final String CLASSPATH_SCHEME; }### Answer: @Test public void nonExistentResourceThrowsExceptionWhenTryingToGetInputStream() { ClasspathResource resource = new ClasspathResource("foobar", ClasspathResourceTest.class); Exception e = assertThrows(FileNotFoundException.class, () -> resource.inputStream()); assertEquals("classpath:foobar", e.getMessage()); }