method2testcases
stringlengths
118
3.08k
### Question: SystemMetrics extends AbstractLifecycleListener { public SystemMetrics() { this(new File("/proc/meminfo")); } SystemMetrics(); SystemMetrics(File memInfoFile); @Override void start(ElasticApmTracer tracer); }### Answer: @Test @DisabledOnOs(OS.MAC) void testSystemMetrics() throws InterruptedException { systemMetrics.bindTo(metricRegistry); consumeCpu(); Thread.sleep(1000); assertThat(metricRegistry.getGaugeValue("system.cpu.total.norm.pct", Labels.EMPTY)).isBetween(0.0, 1.0); assertThat(metricRegistry.getGaugeValue("system.process.cpu.total.norm.pct", Labels.EMPTY)).isBetween(0.0, 1.0); assertThat(metricRegistry.getGaugeValue("system.memory.total", Labels.EMPTY)).isGreaterThan(0.0); assertThat(metricRegistry.getGaugeValue("system.memory.actual.free", Labels.EMPTY)).isGreaterThan(0.0); assertThat(metricRegistry.getGaugeValue("system.process.memory.size", Labels.EMPTY)).isGreaterThan(0.0); }
### Question: RangeValidator implements ConfigurationOption.Validator<T> { public static <T extends Comparable> RangeValidator<T> max(T max) { return new RangeValidator<>(null, max, true); } private RangeValidator(@Nullable T min, @Nullable T max, boolean mustBeInRange); static RangeValidator<T> isInRange(T min, T max); static RangeValidator<T> isNotInRange(T min, T max); static RangeValidator<T> min(T min); static RangeValidator<T> max(T max); @Override void assertValid(@Nullable T value); }### Answer: @Test void testMax() { final RangeValidator<Integer> validator = RangeValidator.max(3); validator.assertValid(1); validator.assertValid(2); validator.assertValid(3); assertThatThrownBy(() -> validator.assertValid(4)).isInstanceOf(IllegalArgumentException.class); }
### Question: JvmGcMetrics extends AbstractLifecycleListener { void bindTo(final MetricRegistry registry) { for (final GarbageCollectorMXBean garbageCollectorMXBean : garbageCollectorMXBeans) { final Labels tags = Labels.Mutable.of("name", garbageCollectorMXBean.getName()); registry.addUnlessNegative("jvm.gc.count", tags, new DoubleSupplier() { @Override public double get() { return garbageCollectorMXBean.getCollectionCount(); } }); registry.addUnlessNegative("jvm.gc.time", tags, new DoubleSupplier() { @Override public double get() { return garbageCollectorMXBean.getCollectionTime(); } }); } try { final Class<?> sunBeanClass = Class.forName("com.sun.management.ThreadMXBean"); if (sunBeanClass.isInstance(ManagementFactory.getThreadMXBean())) { registry.add("jvm.gc.alloc", Labels.EMPTY, (DoubleSupplier) Class.forName(getClass().getName() + "$HotspotAllocationSupplier").getEnumConstants()[0]); } } catch (ClassNotFoundException ignore) { } } @Override void start(ElasticApmTracer tracer); }### Answer: @Test void testGcMetrics() { jvmGcMetrics.bindTo(registry); verify(registry, atLeastOnce()).addUnlessNegative(eq("jvm.gc.count"), any(), any()); verify(registry, atLeastOnce()).addUnlessNegative(eq("jvm.gc.time"), any(), any()); verify(registry, atLeastOnce()).add(eq("jvm.gc.alloc"), any(), any()); }
### Question: HelperClassManager { @Nullable protected abstract T doGetForClassLoaderOfClass(Class<?> classOfTargetClassLoader) throws Exception; protected HelperClassManager(ElasticApmTracer tracer, String implementation, String[] additionalHelpers); @Nullable T getForClassLoaderOfClass(Class<?> classOfTargetClassLoader); }### Answer: @Test void testFailOnlyOnceAnyClassLoader() throws ClassNotFoundException { final HelperClassManager<Object> helperClassManager = HelperClassManager.ForAnyClassLoader.of(mock(ElasticApmTracer.class), "co.elastic.apm.agent.bci.NonExistingHelperClass"); URL[] urls = {getClass().getProtectionDomain().getCodeSource().getLocation()}; ClassLoader targetClassLoader1 = new URLClassLoader(urls, getClass().getClassLoader().getParent()); Class libClass1 = targetClassLoader1.loadClass("co.elastic.apm.agent.bci.HelperClassManagerTest$InnerTestClass$LibClass"); assertFailLoadingOnlyOnce(helperClassManager, libClass1); ClassLoader targetClassLoader2 = new URLClassLoader(urls, getClass().getClassLoader().getParent()); Class libClass2 = targetClassLoader2.loadClass("co.elastic.apm.agent.bci.HelperClassManagerTest$InnerTestClass$LibClass"); assertFailLoadingOnlyOnce(helperClassManager, libClass2); assertThatCode(() -> helperClassManager.doGetForClassLoaderOfClass(libClass1)).doesNotThrowAnyException(); }
### Question: AgentMain { static boolean isJavaVersionSupported(String version, String vmName, @Nullable String vmVersion) { int major; if (version.startsWith("1.")) { major = Character.digit(version.charAt(2), 10); } else { String majorAsString = version.split("\\.")[0]; int indexOfDash = majorAsString.indexOf('-'); if (indexOfDash > 0) { majorAsString = majorAsString.substring(0, indexOfDash); } major = Integer.parseInt(majorAsString); } boolean isHotSpot = vmName.contains("HotSpot(TM)") || vmName.contains("OpenJDK"); boolean isIbmJ9 = vmName.contains("IBM J9"); if (major < 7) { return false; } if (isHotSpot) { return isHotSpotVersionSupported(version, major); } else if (isIbmJ9) { return isIbmJ9VersionSupported(vmVersion, major); } return true; } static void premain(String agentArguments, Instrumentation instrumentation); @SuppressWarnings("unused") static void agentmain(String agentArguments, Instrumentation instrumentation); synchronized static void init(String agentArguments, Instrumentation instrumentation, boolean premain); }### Answer: @Test void testIbmJava8SupportedAfterBuild2_8() { assertThat(AgentMain.isJavaVersionSupported("1.8.0", "IBM J9 VM", "2.8")).isFalse(); assertThat(AgentMain.isJavaVersionSupported("1.8.0", "IBM J9 VM", "2.9")).isTrue(); }
### Question: MethodHierarchyMatcher extends ElementMatcher.Junction.AbstractBase<MethodDescription> { @Override public boolean matches(MethodDescription targetMethod) { return declaresInHierarchy(targetMethod, targetMethod.getDeclaringType().asErasure()); } MethodHierarchyMatcher(ElementMatcher<? super MethodDescription> extraMethodMatcher); private MethodHierarchyMatcher(ElementMatcher<? super MethodDescription> extraMethodMatcher, ElementMatcher<? super TypeDescription> superClassMatcher); ElementMatcher<MethodDescription> onSuperClassesThat(ElementMatcher<? super TypeDescription> superClassMatcher); @Override boolean matches(MethodDescription targetMethod); }### Answer: @Test void testMatchInSameClass() throws Exception { assertThat(CustomElementMatchers.overridesOrImplementsMethodThat(isAnnotatedWith(FindMe.class)) .matches(new MethodDescription.ForLoadedMethod(TestClass.class.getDeclaredMethod("findInSameClass")))) .isTrue(); } @Test void testMatchInInterfaceOfSuperClass() throws Exception { assertThat(CustomElementMatchers.overridesOrImplementsMethodThat(isAnnotatedWith(FindMe.class)) .matches(new MethodDescription.ForLoadedMethod(TestClass.class.getDeclaredMethod("findInInterfaceOfSuperClass")))) .isTrue(); } @Test void testMatchInSuperInterface() throws Exception { assertThat(CustomElementMatchers.overridesOrImplementsMethodThat(isAnnotatedWith(FindMe.class)) .matches(new MethodDescription.ForLoadedMethod(TestClass.class.getDeclaredMethod("findInSuperInterface")))) .isTrue(); } @Test void testMatchInInterface() throws Exception { assertThat(CustomElementMatchers.overridesOrImplementsMethodThat(isAnnotatedWith(FindMe.class)) .matches(new MethodDescription.ForLoadedMethod(TestClass.class.getDeclaredMethod("findInInterface")))) .isTrue(); }
### Question: RegexValidator implements ConfigurationOption.Validator<String> { private RegexValidator(String regex, String errorMessagePattern) { pattern = Pattern.compile(regex); this.errorMessagePattern = errorMessagePattern; } private RegexValidator(String regex, String errorMessagePattern); static RegexValidator of(String regex); static RegexValidator of(String regex, String errorMessagePattern); @Override void assertValid(@Nullable String value); }### Answer: @Test void testRegexValidator() { SoftAssertions.assertSoftly(softly -> { softly.assertThatCode(() -> RegexValidator.of("foo").assertValid("foo")).doesNotThrowAnyException(); softly.assertThatCode(() -> RegexValidator.of("foo").assertValid(null)).doesNotThrowAnyException(); softly.assertThatCode(() -> RegexValidator.of("foo").assertValid("bar")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Value \"bar\" does not match regex foo"); softly.assertThatCode(() -> RegexValidator.of("foo", "{0} is not {1}").assertValid("bar")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("bar is not foo"); }); }
### Question: CustomElementMatchers { public static ElementMatcher.Junction<ClassLoader> classLoaderCanLoadClass(final String className) { return new ElementMatcher.Junction.AbstractBase<ClassLoader>() { private final boolean loadableByBootstrapClassLoader = canLoadClass(null, className); private final WeakConcurrentMap<ClassLoader, Boolean> cache = WeakMapSupplier.createMap(); @Override public boolean matches(@Nullable ClassLoader target) { if (target == null) { return loadableByBootstrapClassLoader; } Boolean result = cache.get(target); if (result == null) { result = canLoadClass(target, className); cache.put(target, result); } return result; } }; } static ElementMatcher.Junction<NamedElement> isInAnyPackage(Collection<String> includedPackages, ElementMatcher.Junction<NamedElement> defaultIfEmpty); static ElementMatcher.Junction<ClassLoader> classLoaderCanLoadClass(final String className); static ElementMatcher.Junction<ProtectionDomain> implementationVersionLte(final String version); static MethodHierarchyMatcher overridesOrImplementsMethodThat(ElementMatcher<? super MethodDescription> methodElementMatcher); static ElementMatcher.Junction<NamedElement> matches(final WildcardMatcher matcher); static ElementMatcher.Junction<NamedElement> anyMatch(final List<WildcardMatcher> matchers); static ElementMatcher.Junction<AnnotationSource> annotationMatches(final String annotationWildcard); static ElementMatcher.Junction<T> isProxy(); }### Answer: @Test void testClassLoaderCanLoadClass() { assertThat(classLoaderCanLoadClass(Object.class.getName()).matches(ClassLoader.getSystemClassLoader())).isTrue(); assertThat(classLoaderCanLoadClass(Object.class.getName()).matches(null)).isTrue(); assertThat(classLoaderCanLoadClass("not.Here").matches(ClassLoader.getSystemClassLoader())).isFalse(); }
### Question: VersionUtils { @Nullable static String getVersionFromPackage(Class<?> clazz) { Package pkg = clazz.getPackage(); if (pkg != null) { return pkg.getImplementationVersion(); } return null; } private VersionUtils(); @Nullable static String getAgentVersion(); @Nullable static String getVersion(Class<?> clazz, String groupId, String artifactId); @Nullable static String getManifestEntry(@Nullable File jarFile, String manifestAttribute); }### Answer: @Test void testGetVersionFromPackage() { assertThat(VersionUtils.getVersionFromPackage(Test.class)).isNotEmpty(); assertThat(VersionUtils.getVersionFromPackage(Test.class)) .isEqualTo(VersionUtils.getVersion(Test.class, "org.junit.jupiter", "junit-jupiter-api")); assertThat(VersionUtils.getManifestEntry(new File(Test.class.getProtectionDomain().getCodeSource().getLocation().getFile()), "Implementation-Version")) .isEqualTo(VersionUtils.getVersionFromPackage(Test.class)); assertThat(VersionUtils.getVersion(Test.class, "org.junit.jupiter", "junit-jupiter-api")) .isSameAs(VersionUtils.getVersion(Test.class, "org.junit.jupiter", "junit-jupiter-api")); }
### Question: VersionUtils { @Nullable static String getVersionFromPomProperties(Class<?> clazz, String groupId, String artifactId) { final String classpathLocation = "/META-INF/maven/" + groupId + "/" + artifactId + "/pom.properties"; final Properties pomProperties = getFromClasspath(classpathLocation, clazz); if (pomProperties != null) { return pomProperties.getProperty("version"); } return null; } private VersionUtils(); @Nullable static String getAgentVersion(); @Nullable static String getVersion(Class<?> clazz, String groupId, String artifactId); @Nullable static String getManifestEntry(@Nullable File jarFile, String manifestAttribute); }### Answer: @Test void getVersionFromPomProperties() { assertThat(VersionUtils.getVersionFromPomProperties(Assertions.class, "org.assertj", "assertj-core")).isNotEmpty(); assertThat(VersionUtils.getVersionFromPomProperties(Assertions.class, "org.assertj", "assertj-core")) .isEqualTo(VersionUtils.getVersion(Assertions.class, "org.assertj", "assertj-core")); assertThat(VersionUtils.getVersion(Assertions.class, "org.assertj", "assertj-core")) .isSameAs(VersionUtils.getVersion(Assertions.class, "org.assertj", "assertj-core")); }
### Question: ThreadUtils { public static String addElasticApmThreadPrefix(String purpose) { return ELASTIC_APM_THREAD_PREFIX + purpose; } private ThreadUtils(); static String addElasticApmThreadPrefix(String purpose); static final String ELASTIC_APM_THREAD_PREFIX; }### Answer: @Test public void testAddElasticApmThreadPrefix() { String purpose = RandomStringUtils.randomAlphanumeric(10); String prefixedThreadName = ThreadUtils.addElasticApmThreadPrefix(purpose); assertThat(prefixedThreadName).isEqualTo("elastic-apm-"+purpose); }
### Question: BinaryHeaderMap implements Recyclable, Iterable<BinaryHeaderMap.Entry> { public void copyFrom(BinaryHeaderMap other) { resetState(); keys.addAll(other.keys); ((Buffer) other.valueBuffer).flip(); if (valueBuffer.capacity() < other.valueBuffer.remaining()) { valueBuffer = CharBuffer.allocate(other.valueBuffer.remaining()); } valueBuffer.put(other.valueBuffer); if (this.valueLengths.length < other.valueLengths.length) { this.valueLengths = new int[other.valueLengths.length]; } System.arraycopy(other.valueLengths, 0, this.valueLengths, 0, other.valueLengths.length); } BinaryHeaderMap(); int size(); boolean isEmpty(); boolean add(String key, byte[] value); @Override void resetState(); @Override Iterator<Entry> iterator(); void copyFrom(BinaryHeaderMap other); static final int MAXIMUM_HEADER_BUFFER_SIZE; }### Answer: @Test void testCopyFrom() { headerMap.add(String.valueOf(0), "value0".getBytes()); headerMap.add(String.valueOf(1), "value1".getBytes()); BinaryHeaderMap copy = new BinaryHeaderMap(); copy.add("foo", "bar".getBytes()); copy.copyFrom(headerMap); int index = 0; int numElements = 0; for (BinaryHeaderMap.Entry entry : copy) { numElements++; String indexS = String.valueOf(index++); assertThat(entry.getKey()).isEqualTo(indexS); assertThat(entry.getValue().toString()).isEqualTo("value" + indexS); } assertThat(numElements).isEqualTo(2); }
### Question: PackageScanner { public static List<String> getClassNames(final String basePackage, ClassLoader classLoader) throws IOException, URISyntaxException { String baseFolderResource = basePackage.replace('.', '/'); final List<String> classNames = new ArrayList<>(); Enumeration<URL> resources = classLoader.getResources(baseFolderResource); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); URI uri = resource.toURI(); List<String> result; if (uri.getScheme().equals("jar")) { synchronized (PackageScanner.class) { try (FileSystem fileSystem = FileSystems.newFileSystem(uri, Collections.<String, Object>emptyMap())) { final Path basePath = fileSystem.getPath(baseFolderResource).toAbsolutePath(); result = listClassNames(basePackage, basePath); } } } else { result = listClassNames(basePackage, Paths.get(uri)); } classNames.addAll(result); } return classNames; } static List<String> getClassNames(final String basePackage, ClassLoader classLoader); }### Answer: @Test void getClassNames() throws Exception { assertThat(PackageScanner.getClassNames(getClass().getPackageName(), ElasticApmAgent.getAgentClassLoader())) .contains(PackageScanner.class.getName()); } @Test void testScanJar() throws Exception { assertThat(PackageScanner.getClassNames(ByteBuddy.class.getPackageName(), ElasticApmAgent.getAgentClassLoader())) .contains(ByteBuddy.class.getName()); assertThat(PackageScanner.getClassNames(ByteBuddy.class.getPackageName(), ElasticApmAgent.getAgentClassLoader())) .contains(ByteBuddy.class.getName()); } @Test void getClassNamesOfNonExistentPackage() throws Exception { assertThat(PackageScanner.getClassNames("foo.bar", ElasticApmAgent.getAgentClassLoader())).isEmpty(); }
### Question: PotentiallyMultiValuedMap implements Recyclable { public void set(String key, String[] values) { if (values.length > 0) { if (values.length == 1) { keys.add(key); this.values.add(values[0]); } else { keys.add(key); this.values.add(Arrays.asList(values)); } } } void add(String key, String value); void set(String key, String[] values); @Nullable String getFirst(String key); @Nullable Object get(String key); List<String> getAll(String key); boolean isEmpty(); @Override void resetState(); String getKey(int i); Object getValue(int i); int size(); void copyFrom(PotentiallyMultiValuedMap other); void removeIgnoreCase(String key); void set(int index, String value); boolean containsIgnoreCase(String key); }### Answer: @Test void testSet() { map.add("foo", "bar"); map.set(0, "foo"); assertThat(map.get("foo")).isEqualTo("foo"); }
### Question: MathUtils { public static int getNextPowerOf2(int i) { return Math.max(2, Integer.highestOneBit(i - 1) << 1); } static int getNextPowerOf2(int i); }### Answer: @Test void getNextPowerOf2() { assertSoftly(softly -> { softly.assertThat(MathUtils.getNextPowerOf2(-1)).isEqualTo(2); softly.assertThat(MathUtils.getNextPowerOf2(0)).isEqualTo(2); softly.assertThat(MathUtils.getNextPowerOf2(1)).isEqualTo(2); softly.assertThat(MathUtils.getNextPowerOf2(2)).isEqualTo(2); softly.assertThat(MathUtils.getNextPowerOf2(3)).isEqualTo(4); softly.assertThat(MathUtils.getNextPowerOf2(234234)).isEqualTo(262144); }); }
### Question: Version implements Comparable<Version> { private Version(String version) { final String[] parts = version.split("\\-")[0].split("\\."); numbers = new int[parts.length]; for (int i = 0; i < parts.length; i++) { numbers[i] = Integer.valueOf(parts[i]); } } private Version(String version); static Version of(String version); @Override int compareTo(Version another); static final Version UNKNOWN_VERSION; }### Answer: @Test void testVersion() { assertThat(Version.of("1.2.3")).isGreaterThan(Version.of("1.2.2")); assertThat(Version.of("1.2.3-SNAPSHOT")).isGreaterThan(Version.of("1.2.2")); }
### Question: DependencyInjectingServiceLoader { public static <T> List<T> load(Class<T> clazz, Object... constructorArguments) { return new DependencyInjectingServiceLoader<>(clazz, constructorArguments).instances; } private DependencyInjectingServiceLoader(Class<T> clazz, Object... constructorArguments); private DependencyInjectingServiceLoader(Class<T> clazz, List<ClassLoader> classLoaders, Object... constructorArguments); static List<T> load(Class<T> clazz, Object... constructorArguments); static List<T> load(Class<T> clazz, List<ClassLoader> classLoaders, Object... constructorArguments); }### Answer: @Test void testServiceWithConstructorArgument() { final List<Service> serviceImplementations = DependencyInjectingServiceLoader.load(Service.class, "foo"); assertThat(serviceImplementations).hasSize(2); assertThat(serviceImplementations.get(0).getString()).isEqualTo("foo"); assertThat(serviceImplementations.get(0)).isInstanceOf(ServiceImpl.class); assertThat(serviceImplementations.get(1).getString()).isEqualTo("foo"); assertThat(serviceImplementations.get(1)).isInstanceOf(ServiceImpl2.class); } @Test void testServiceWithoutConstructorArgument() { final List<Service> serviceImplementations = DependencyInjectingServiceLoader.load(Service.class); assertThat(serviceImplementations).hasSize(2); assertThat(serviceImplementations.get(0).getString()).isEqualTo("bar"); assertThat(serviceImplementations.get(0)).isInstanceOf(ServiceImpl.class); assertThat(serviceImplementations.get(1).getString()).isEqualTo("bar"); assertThat(serviceImplementations.get(1)).isInstanceOf(ServiceImpl2.class); }
### Question: ByteUtils { public static void putLong(byte[] buffer, int offset, long l) { buffer[offset++] = (byte) (l >> 56); buffer[offset++] = (byte) (l >> 48); buffer[offset++] = (byte) (l >> 40); buffer[offset++] = (byte) (l >> 32); buffer[offset++] = (byte) (l >> 24); buffer[offset++] = (byte) (l >> 16); buffer[offset++] = (byte) (l >> 8); buffer[offset] = (byte) l; } static void putLong(byte[] buffer, int offset, long l); static long getLong(byte[] buffer, int offset); }### Answer: @Test public void putLong() { byte[] array = new byte[8]; ByteBuffer buffer = ByteBuffer.wrap(array); ByteUtils.putLong(array, 0, 42); assertThat(buffer.getLong()).isEqualTo(42); }
### Question: ByteUtils { public static long getLong(byte[] buffer, int offset) { return ((long) buffer[offset] << 56) | ((long) buffer[offset + 1] & 0xff) << 48 | ((long) buffer[offset + 2] & 0xff) << 40 | ((long) buffer[offset + 3] & 0xff) << 32 | ((long) buffer[offset + 4] & 0xff) << 24 | ((long) buffer[offset + 5] & 0xff) << 16 | ((long) buffer[offset + 6] & 0xff) << 8 | ((long) buffer[offset + 7] & 0xff); } static void putLong(byte[] buffer, int offset, long l); static long getLong(byte[] buffer, int offset); }### Answer: @Test public void getLong() { byte[] array = new byte[8]; ByteBuffer buffer = ByteBuffer.wrap(array); buffer.putLong(42); assertThat(ByteUtils.getLong(array, 0)).isEqualTo(42); }
### Question: IOUtils { @VisibleForAdvice public static CoderResult decodeUtf8Byte(final byte b, final CharBuffer charBuffer) { final ByteBuffer buffer = threadLocalByteBuffer.get(); buffer.put(b); ((Buffer) buffer).position(0); ((Buffer) buffer).limit(1); return decode(charBuffer, buffer); } @VisibleForAdvice static boolean readUtf8Stream(final InputStream is, final CharBuffer charBuffer); @VisibleForAdvice static CoderResult decodeUtf8Bytes(final byte[] bytes, final CharBuffer charBuffer); @VisibleForAdvice static CoderResult decodeUtf8Bytes(final byte[] bytes, final int offset, final int length, final CharBuffer charBuffer); @VisibleForAdvice static CoderResult decodeUtf8Byte(final byte b, final CharBuffer charBuffer); static synchronized File exportResourceToDirectory(String resource, String parentDirectory, String tempFileNamePrefix, String tempFileNameExtension); static String md5Hash(InputStream resourceAsStream); }### Answer: @Test void readUtf8Byte() { final CharBuffer charBuffer = CharBuffer.allocate(8); for (byte b : "{foo}".getBytes(UTF_8)) { assertThat(IOUtils.decodeUtf8Byte(b, charBuffer).isError()).isFalse(); } charBuffer.flip(); assertThat(charBuffer.toString()).isEqualTo("{foo}"); }
### Question: HexUtils { public static byte getNextByte(String hexEncodedString, int offset) { final int hi = hexCharToBinary(hexEncodedString.charAt(offset)); final int lo = hexCharToBinary(hexEncodedString.charAt(offset + 1)); if (hi == -1 || lo == -1) { throw new IllegalArgumentException("Not a hex encoded string: " + hexEncodedString + " at offset " + offset); } return (byte) ((hi << 4) + lo); } private HexUtils(); static String bytesToHex(byte[] bytes); static void writeBytesAsHex(byte[] bytes, JsonWriter jw); static void writeBytesAsHex(byte[] bytes, StringBuilder sb); static void writeBytesAsHex(byte[] bytes, int offset, int length, StringBuilder sb); static void writeByteAsHex(byte b, StringBuilder sb); static byte getNextByte(String hexEncodedString, int offset); static void nextBytes(String hexEncodedString, int offset, byte[] bytes); static void decode(String hexEncodedString, int srcOffset, int srcLength, byte[] bytes, int destOffset); static void writeAsHex(long l, JsonWriter jw); }### Answer: @Test void testInvalidHex() { assertThatThrownBy(() -> HexUtils.getNextByte("0$", 0)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Not a hex encoded string: 0$ at offset 0"); }
### Question: HexUtils { public static void nextBytes(String hexEncodedString, int offset, byte[] bytes) { final int charsToRead = bytes.length * 2; if (hexEncodedString.length() < offset + charsToRead) { throw new IllegalArgumentException(String.format("Can't read %d bytes from string %s with offset %d", bytes.length, hexEncodedString, offset)); } for (int i = 0; i < charsToRead; i += 2) { bytes[i / 2] = getNextByte(hexEncodedString, offset + i); } } private HexUtils(); static String bytesToHex(byte[] bytes); static void writeBytesAsHex(byte[] bytes, JsonWriter jw); static void writeBytesAsHex(byte[] bytes, StringBuilder sb); static void writeBytesAsHex(byte[] bytes, int offset, int length, StringBuilder sb); static void writeByteAsHex(byte b, StringBuilder sb); static byte getNextByte(String hexEncodedString, int offset); static void nextBytes(String hexEncodedString, int offset, byte[] bytes); static void decode(String hexEncodedString, int srcOffset, int srcLength, byte[] bytes, int destOffset); static void writeAsHex(long l, JsonWriter jw); }### Answer: @Test void testStringTooSmall() { assertThatThrownBy(() -> HexUtils.nextBytes("00", 0, new byte[2])) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Can't read 2 bytes from string 00 with offset 0"); } @Test void testUnevenLength() { final byte[] bytes = new byte[1]; HexUtils.nextBytes("0a0", 0, bytes); assertThat(bytes).isEqualTo(new byte[]{10}); }
### Question: NoRandomAccessMap implements Recyclable, Iterable<NoRandomAccessMap.Entry<K, V>> { public void add(K key, @Nullable V value) throws NullPointerException { if (key == null) { throw new NullPointerException("This map doesn't support null keys"); } keys.add(key); values.add(value); } void add(K key, @Nullable V value); int size(); boolean isEmpty(); @Override void resetState(); @Override java.util.Iterator<NoRandomAccessMap.Entry<K, V>> iterator(); void copyFrom(NoRandomAccessMap<K, V> other); }### Answer: @Test void testOneEntry() { map.add("foo", "bar"); int numElements = 0; for (NoRandomAccessMap.Entry entry : map) { numElements++; assertThat(entry.getKey()).isEqualTo("foo"); assertThat(entry.getValue()).isEqualTo("bar"); } assertThat(numElements).isEqualTo(1); } @Test void testNullValue() { map.add("foo", null); int numElements = 0; for (NoRandomAccessMap.Entry entry : map) { numElements++; assertThat(entry.getKey()).isEqualTo("foo"); assertThat(entry.getValue()).isNull(); } assertThat(numElements).isEqualTo(1); } @Test void testTwoEntries() { map.add(String.valueOf(0), "value"); map.add(String.valueOf(1), "value"); int index = 0; int numElements = 0; for (NoRandomAccessMap.Entry entry : map) { numElements++; assertThat(entry.getKey()).isEqualTo(String.valueOf(index++)); assertThat(entry.getValue()).isEqualTo("value"); } assertThat(numElements).isEqualTo(2); } @Test void testTwoIterations() { map.add(String.valueOf(0), "value"); map.add(String.valueOf(1), "value"); int numElements = 0; for (NoRandomAccessMap.Entry entry : map) { numElements++; break; } for (NoRandomAccessMap.Entry entry : map) { numElements++; } assertThat(numElements).isEqualTo(3); }
### Question: StartupInfo extends AbstractLifecycleListener { void logConfiguration(ConfigurationRegistry configurationRegistry, Logger logger) { final String serviceName = configurationRegistry.getConfig(CoreConfiguration.class).getServiceName(); logger.info("Starting Elastic APM {} as {} on {}", elasticApmVersion, serviceName, getJvmAndOsVersionString()); for (List<ConfigurationOption<?>> options : configurationRegistry.getConfigurationOptionsByCategory().values()) { for (ConfigurationOption<?> option : options) { if (!option.isDefault()) { logConfigWithNonDefaultValue(logger, option); } } } if (configurationRegistry.getConfig(StacktraceConfiguration.class).getApplicationPackages().isEmpty()) { logger.warn("To enable all features and decrease startup time, please configure {}", StacktraceConfiguration.APPLICATION_PACKAGES); } } StartupInfo(); @Override void init(ElasticApmTracer tracer); }### Answer: @Test void testLogDeprecatedKey() throws Exception { configurationRegistry.save("test_alias", "0.5", SimpleSource.NAME); startupInfo.logConfiguration(configurationRegistry, logger); verify(logger).warn("Detected usage of an old configuration key: '{}'. Please use '{}' instead.", "test_alias", "test"); } @Test void testLogDeprecationWarningWhenNotSpecifyingTimeUnit() throws Exception { assertThat(config.duration.get().getMillis()).isEqualTo(1); assertThat(config.duration.getValueAsString()).isEqualTo("1"); startupInfo.logConfiguration(configurationRegistry, logger); verify(logger).warn("DEPRECATION WARNING: {}: '{}' (source: {}) is not using a time unit. Please use one of 'ms', 's' or 'm'.", "duration", "1", SimpleSource.NAME); }
### Question: NoRandomAccessMap implements Recyclable, Iterable<NoRandomAccessMap.Entry<K, V>> { public void copyFrom(NoRandomAccessMap<K, V> other) { resetState(); for (Entry<K, V> entry : other) { this.add(entry.getKey(), entry.getValue()); } } void add(K key, @Nullable V value); int size(); boolean isEmpty(); @Override void resetState(); @Override java.util.Iterator<NoRandomAccessMap.Entry<K, V>> iterator(); void copyFrom(NoRandomAccessMap<K, V> other); }### Answer: @Test void testCopyFrom() { map.add(String.valueOf(0), "value"); map.add(String.valueOf(1), "value"); NoRandomAccessMap<String, String> copy = new NoRandomAccessMap<>(); copy.add("foo", "bar"); copy.copyFrom(map); int index = 0; int numElements = 0; for (NoRandomAccessMap.Entry entry : copy) { numElements++; assertThat(entry.getKey()).isEqualTo(String.valueOf(index++)); assertThat(entry.getValue()).isEqualTo("value"); } assertThat(numElements).isEqualTo(2); }
### Question: LongList { public void add(long l) { ensureCapacity(size + 1); longs[size++] = l; } LongList(); LongList(int initialCapacity); static LongList of(long... values); void add(long l); void addAll(LongList other); int getSize(); long get(int i); boolean contains(long l); boolean remove(long l); long remove(int i); void clear(); @Override String toString(); long[] toArray(); boolean isEmpty(); }### Answer: @Test void testAdd() { assertThat(longList.isEmpty()).isTrue(); longList.add(42); assertThat(longList.isEmpty()).isFalse(); assertThat(longList.getSize()).isEqualTo(1); assertThat(longList.get(0)).isEqualTo(42); }
### Question: LongList { public boolean contains(long l) { for (int i = 0; i < size; i++) { if (longs[i] == l) { return true; } } return false; } LongList(); LongList(int initialCapacity); static LongList of(long... values); void add(long l); void addAll(LongList other); int getSize(); long get(int i); boolean contains(long l); boolean remove(long l); long remove(int i); void clear(); @Override String toString(); long[] toArray(); boolean isEmpty(); }### Answer: @Test void testContains() { longList.add(42); assertThat(longList.contains(42)).isTrue(); assertThat(longList.contains(0)).isFalse(); }
### Question: LongList { public void addAll(LongList other) { ensureCapacity(size + other.size); System.arraycopy(other.longs, 0, longs, size, other.size); size += other.size; } LongList(); LongList(int initialCapacity); static LongList of(long... values); void add(long l); void addAll(LongList other); int getSize(); long get(int i); boolean contains(long l); boolean remove(long l); long remove(int i); void clear(); @Override String toString(); long[] toArray(); boolean isEmpty(); }### Answer: @Test void testAddAll() { longList.add(42); LongList list2 = new LongList(); list2.add(43); list2.add(44); longList.addAll(list2); assertThat(this.longList.getSize()).isEqualTo(3); assertThat(this.longList.get(0)).isEqualTo(42); assertThat(this.longList.get(1)).isEqualTo(43); assertThat(this.longList.get(2)).isEqualTo(44); }
### Question: LongList { static int newCapacity(long minCapacity, long oldCapacity) { long growBy50Percent = oldCapacity + (oldCapacity >> 1); if (minCapacity <= growBy50Percent) { return (int) growBy50Percent; } else if (minCapacity <= MAX_ARRAY_SIZE) { return (int) minCapacity; } else { throw new OutOfMemoryError(); } } LongList(); LongList(int initialCapacity); static LongList of(long... values); void add(long l); void addAll(LongList other); int getSize(); long get(int i); boolean contains(long l); boolean remove(long l); long remove(int i); void clear(); @Override String toString(); long[] toArray(); boolean isEmpty(); }### Answer: @Test void testNewCapacity() { assertThat(LongList.newCapacity(1, 0)).isEqualTo(1); assertThat(LongList.newCapacity(42, 4)).isEqualTo(42); assertThat(LongList.newCapacity(5, 4)).isEqualTo(6); assertThatThrownBy(() -> LongList.newCapacity(Integer.MAX_VALUE, 4)).isInstanceOf(OutOfMemoryError.class); }
### Question: LongList { public long get(int i) { if (i >= size) { throw new IndexOutOfBoundsException(); } return longs[i]; } LongList(); LongList(int initialCapacity); static LongList of(long... values); void add(long l); void addAll(LongList other); int getSize(); long get(int i); boolean contains(long l); boolean remove(long l); long remove(int i); void clear(); @Override String toString(); long[] toArray(); boolean isEmpty(); }### Answer: @Test void testOutOfBounds() { assertThatThrownBy(() -> longList.get(0)).isInstanceOf(IndexOutOfBoundsException.class); }
### Question: ReporterFactory { public Reporter createReporter(ConfigurationRegistry configurationRegistry, ApmServerClient apmServerClient, MetaData metaData) { ReporterConfiguration reporterConfiguration = configurationRegistry.getConfig(ReporterConfiguration.class); ReportingEventHandler reportingEventHandler = getReportingEventHandler(configurationRegistry, reporterConfiguration, metaData, apmServerClient); return new ApmServerReporter(true, reporterConfiguration, reportingEventHandler); } Reporter createReporter(ConfigurationRegistry configurationRegistry, ApmServerClient apmServerClient, MetaData metaData); }### Answer: @Test void testNotValidatingSslCertificate() throws Exception { when(reporterConfiguration.isVerifyServerCert()).thenReturn(false); ApmServerClient apmServerClient = new ApmServerClient(reporterConfiguration); apmServerClient.start(); final Reporter reporter = reporterFactory.createReporter(configuration, apmServerClient, MetaData.create(configuration, null)); reporter.start(); reporter.report(new Transaction(MockTracer.create())); reporter.flush().get(); assertThat(requestHandled) .describedAs("request should ignore certificate validation and properly execute") .isTrue(); } @Test void testValidatingSslCertificate() throws Exception { when(reporterConfiguration.isVerifyServerCert()).thenReturn(true); ApmServerClient apmServerClient = new ApmServerClient(reporterConfiguration); apmServerClient.start(); final Reporter reporter = reporterFactory.createReporter(configuration, apmServerClient, MetaData.create(configuration, null)); reporter.start(); reporter.report(new Transaction(MockTracer.create())); reporter.flush().get(); assertThat(requestHandled) .describedAs("request should have produced a certificate validation error") .isFalse(); }
### Question: ApmServerClient { List<URL> getServerUrls() { if (serverUrls == null) { throw new IllegalStateException("APM Server client not yet initialized"); } return serverUrls; } ApmServerClient(ReporterConfiguration reporterConfiguration); void start(); void start(List<URL> shuffledUrls); @Nullable V execute(String path, ConnectionHandler<V> connectionHandler); List<T> executeForAllUrls(String path, ConnectionHandler<T> connectionHandler); boolean supportsNonStringLabels(); boolean supportsLogsEndpoint(); boolean isAtLeast(Version apmServerVersion); }### Answer: @Test public void testGetServerUrlsVerifyThatServerUrlsWillBeReloaded() throws IOException { URL tempUrl = new URL("http", "localhost", 9999, ""); config.save("server_urls", tempUrl.toString(), SpyConfiguration.CONFIG_SOURCE_NAME); List<URL> updatedServerUrls = apmServerClient.getServerUrls(); assertThat(updatedServerUrls).isEqualTo(List.of(tempUrl)); }
### Question: AgentArgumentsConfigurationSource extends AbstractConfigurationSource { public static AgentArgumentsConfigurationSource parse(String agentAgruments) { final Map<String, String> configs = new HashMap<>(); for (String config : StringUtils.split(agentAgruments, ';')) { final int indexOfEquals = config.indexOf('='); if (indexOfEquals < 1) { throw new IllegalArgumentException(String.format("%s is not a '=' separated key/value pair", config)); } configs.put(config.substring(0, indexOfEquals).trim(), config.substring(indexOfEquals + 1).trim()); } return new AgentArgumentsConfigurationSource(configs); } private AgentArgumentsConfigurationSource(Map<String, String> config); static AgentArgumentsConfigurationSource parse(String agentAgruments); @Override @Nullable String getValue(String key); @Override String getName(); }### Answer: @Test void testParse() { assertThat(AgentArgumentsConfigurationSource.parse("foo=bar").getValue("foo")).isEqualTo("bar"); assertThat(AgentArgumentsConfigurationSource.parse("foo = bar ; baz =qux, quux ").getConfig()) .containsEntry("foo", "bar") .containsEntry("baz", "qux, quux"); assertThat(AgentArgumentsConfigurationSource.parse("foo = bar ; baz =qux=quux,foo=bar ").getConfig()) .containsEntry("foo", "bar") .containsEntry("baz", "qux=quux,foo=bar"); assertThatThrownBy(() -> AgentArgumentsConfigurationSource.parse("foo")).isInstanceOf(IllegalArgumentException.class); }
### Question: TimeDuration implements Comparable<TimeDuration> { public static TimeDuration of(String durationString) { Matcher matcher = DURATION_PATTERN.matcher(durationString); if (matcher.matches()) { long duration = Long.parseLong(matcher.group(2)); if (matcher.group(1) != null) { duration = duration * -1; } return new TimeDuration(durationString, duration * getDurationMultiplier(matcher.group(3))); } else { throw new IllegalArgumentException("Invalid duration '" + durationString + "'"); } } private TimeDuration(String durationString, long durationMs); static TimeDuration of(String durationString); long getMillis(); @Override String toString(); @Override int compareTo(TimeDuration o); static final Pattern DURATION_PATTERN; }### Answer: @Test void testParseUnitInvalid() { for (String invalid : List.of(" 1s", "1 s", "1s ", "1h")) { assertThatCode(() -> TimeDuration.of(invalid)).isInstanceOf(IllegalArgumentException.class); } }
### Question: ThreadPool { public static void runSingleThreadServer() throws IOException { ServerSocket socket = new ServerSocket(10080); while (true) { final Socket connetion = socket.accept(); handleConnection(connetion); connetion.close(); } } static void runSingleThreadServer(); static void handleConnection(Socket connection); static void runMuiltThreadServerWithThreadPool_Future(); static void runMuiltThreadServerWithThreadPool(); }### Answer: @Ignore @Test public void runSingleThreadServerTest() throws Exception { ThreadPool.runSingleThreadServer(); }
### Question: BinarySearchTree { public boolean isEmpty() { return Objects.isNull(root); } BinarySearchTree(); BinaryNode getRoot(); boolean contains(Integer data); static BinarySearchTree build(Integer[] sourceDatas); void insert(Integer data, BinaryNode node); boolean remove(Integer data); BinaryNode remove(Integer data, BinaryNode node); void preOrderTraversal(BinaryNode node, List<Integer> list); List<Integer> preOrderTraversal(); void inOrderTraversal(BinaryNode node, List<Integer> list); List<Integer> inOrderTraversal(); void postOrderTraversal(BinaryNode node, List<Integer> list); List<Integer> postOrderTraversal(); boolean isEmpty(); Integer getMin(); Integer getMax(); Integer getMax(BinaryNode node); }### Answer: @Test public void isEmpty() throws Exception { dataList = new ArrayList<>(); datas = dataList.toArray(new Integer[dataList.size()]); tree = BinarySearchTree.build(datas); assertThat(tree.isEmpty(), is(true)); dataList = Arrays.asList(6, 4, 9, 3, 8, 5, 10); datas = dataList.toArray(new Integer[dataList.size()]); BinarySearchTree tree = BinarySearchTree.build(datas); assertThat(tree.isEmpty(), is(false)); }
### Question: BinarySearchTree { public boolean contains(Integer data) { return Objects.nonNull(data) && contains(data, root); } BinarySearchTree(); BinaryNode getRoot(); boolean contains(Integer data); static BinarySearchTree build(Integer[] sourceDatas); void insert(Integer data, BinaryNode node); boolean remove(Integer data); BinaryNode remove(Integer data, BinaryNode node); void preOrderTraversal(BinaryNode node, List<Integer> list); List<Integer> preOrderTraversal(); void inOrderTraversal(BinaryNode node, List<Integer> list); List<Integer> inOrderTraversal(); void postOrderTraversal(BinaryNode node, List<Integer> list); List<Integer> postOrderTraversal(); boolean isEmpty(); Integer getMin(); Integer getMax(); Integer getMax(BinaryNode node); }### Answer: @Test public void containsTest() throws Exception { dataList = Arrays.asList(6, 4, 9, 3, 8, 5, 10); datas = dataList.toArray(new Integer[dataList.size()]); tree = BinarySearchTree.build(datas); assertThat(tree.contains(5), is(true)); assertThat(tree.contains(0), is(false)); assertThat(tree.contains(null), is(false)); }
### Question: SelectionSort { public static int[] sort(int[] sourceDatas) { int[] datas = IntStream.of(sourceDatas).distinct().toArray(), result = new int[datas.length]; int data, size = datas.length; for (int i = 0; i < size; i++) { data = getSmallestData(datas); result[i] = data; datas = removeData(data, datas); } return result; } static int[] sort(int[] sourceDatas); }### Answer: @Test public void sort() throws Exception { int[] datas = { 1, 8, 7, 20, 9, 10 }; int[] result = { 1, 7, 8, 9, 10, 20 }; assertArrayEquals(SelectionSort.sort(datas), result); } @Test public void sort_When_Has_Same_Data() throws Exception { int[] datas = { 1, 7, 7, 20, 9, 10 }; int[] result = { 1, 7, 9, 10, 20 }; assertArrayEquals(SelectionSort.sort(datas), result); }
### Question: Stack { T pop() { if (storage.isEmpty()) { throw new RuntimeException("stack has no value"); } return storage.remove(topIndex()); } Stack(); }### Answer: @Test(expected = RuntimeException.class) public void whenExceptionThrown() throws Exception { Stack stack = new Stack(); stack.pop(); }
### Question: ThreadPool { public static void runMuiltThreadServerWithThreadPool() throws IOException { ServerSocket socket = new ServerSocket(10080); while (true) { final Socket connection = socket.accept(); executor.execute(() -> handleConnection(connection)); } } static void runSingleThreadServer(); static void handleConnection(Socket connection); static void runMuiltThreadServerWithThreadPool_Future(); static void runMuiltThreadServerWithThreadPool(); }### Answer: @Ignore @Test public void runMultiThreadServerTest() throws Exception { ThreadPool.runMuiltThreadServerWithThreadPool(); }
### Question: BinarySearch { public static boolean find(int[] datas, int dataToFind) { int leftIndex = 0, rightIndex = datas.length - 1, index = datas.length / 2; while(rightIndex - leftIndex >= 0) { if (leftIndex == rightIndex) { return dataToFind == datas[index]; } if (dataToFind == datas[index]) { return true; } if (dataToFind < datas[index]) { rightIndex = index - 1; } else { leftIndex = index + 1; } index = (leftIndex + rightIndex + 1) / 2; } return false; } static boolean find(int[] datas, int dataToFind); }### Answer: @Test public void find() throws Exception { int[] datas = setIntSortedArrays(1000); assertTrue(BinarySearch.find(datas, 60)); assertTrue(BinarySearch.find(datas, 0)); assertFalse(BinarySearch.find(datas, 1001)); } @Test public void find_Complicated_Case() throws Exception { int[] datas = { 1, 3, 5, 8, 9, 10 }; assertTrue(BinarySearch.find(datas, 5)); assertFalse(BinarySearch.find(datas, 7)); assertFalse(BinarySearch.find(datas, 90)); }
### Question: ThreadPool { public static void runMuiltThreadServerWithThreadPool_Future() throws IOException, InterruptedException, ExecutionException { ServerSocket socket = new ServerSocket(10080); while (true) { final Socket connection = socket.accept(); Future a = executorFuture.submit(() -> handleConnection(connection)); System.out.println(a.get()); System.out.println(a.isDone()); } } static void runSingleThreadServer(); static void handleConnection(Socket connection); static void runMuiltThreadServerWithThreadPool_Future(); static void runMuiltThreadServerWithThreadPool(); }### Answer: @Ignore @Test public void runMultiThreadServerTest_Future() throws Exception { ThreadPool.runMuiltThreadServerWithThreadPool_Future(); }
### Question: SqlRunner { public Result<Record> run(String sql) { try { Statement statement = connection.createStatement(); return DSL.using(new DefaultConfiguration()).fetch(statement.executeQuery(sql)); } catch (SQLException ex) { ex.printStackTrace(); throw new RuntimeException(); } } SqlRunner(String databaseName, Object sourceData); Result<Record> run(String sql); }### Answer: @Test public void run() throws Exception { sqlRunner = new SqlRunner("merchant_system", database); sql = "SELECT \n" + "\"products\".\"id\", \"sellers\".\"name\" \n" + "FROM \"merchant_system\".\"products\" \n" + "INNER JOIN \"merchant_system\".\"sellers\" \n" + "ON \"merchant_system\".\"sellers\".\"id\" = \"merchant_system\".\"products\".\"sellerId\" \n" + "WHERE \"sellers\".\"name\" = 'dengqinghua'"; Result<Record> result = sqlRunner.run(sql); assertThat(result.format(), is( "+----+-----------+" + "\n" + "| id|name |" + "\n" + "+----+-----------+" + "\n" + "|1024|dengqinghua|" + "\n" + "+----+-----------+" )); }
### Question: Salary { public long calculateYearSalary() { return this.monthSalary * 12 + bonus; } Salary(int monthSalary, int bonus); long calculateYearSalary(); }### Answer: @Test public void calculateYearSalary() { Salary salary = new Salary(10_000, 20_000); assertEquals(salary.calculateYearSalary(), 140_000); } @Test public void calculateYearSalary2() { Salary salary = new Salary(10_000, 20_000); assertEquals(salary.calculateYearSalary(), 140_000); }
### Question: WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); initMetrics(servletContext, disps); log.info("Web application fully configured"); } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(WebServerFactory server); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); }### Answer: @Test public void testStartUpProdServletContext() throws ServletException { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); webConfigurer.onStartup(servletContext); assertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry); assertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry); verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.class)); verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.class)); } @Test public void testStartUpDevServletContext() throws ServletException { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT); webConfigurer.onStartup(servletContext); assertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry); assertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry); verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.class)); verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.class)); }
### Question: CursorPoint { public double getDistanceFromOrigin() { return Math.hypot(this.x, this.y); } CursorPoint(int x, int y, int delay); double getDistanceFromOrigin(); double getThetaFromOrigin(); CursorPoint getCursorPointTranslatedBy(CursorPoint startingCursorPoint); CursorPoint getCursorPointScaledBy(double scaleFactor); CursorPoint getCursorPointRotatedBy(double angleOfRotation); CursorPoint getCursorPointTransformedByParabola(double[] parabolaEquation); CursorPoint getCursorPointWithNewDelay(int delay); void display(); public int x; public int y; public int delay; }### Answer: @Test void testDistanceFromOrigin() { CursorPoint a = new CursorPoint(0, 0, 0); CursorPoint b = new CursorPoint(3, 4, 0); CursorPoint c = new CursorPoint(500, 750, 0); CursorPoint d = new CursorPoint(284, 848, 0); assertEquals(0, a.getDistanceFromOrigin()); assertEquals(894.293016857, d.getDistanceFromOrigin(), 0.0001); assertEquals(5, b.getDistanceFromOrigin(), 0.0001); }
### Question: CursorPoint { public double getThetaFromOrigin() { return Math.atan2(this.x, this.y); } CursorPoint(int x, int y, int delay); double getDistanceFromOrigin(); double getThetaFromOrigin(); CursorPoint getCursorPointTranslatedBy(CursorPoint startingCursorPoint); CursorPoint getCursorPointScaledBy(double scaleFactor); CursorPoint getCursorPointRotatedBy(double angleOfRotation); CursorPoint getCursorPointTransformedByParabola(double[] parabolaEquation); CursorPoint getCursorPointWithNewDelay(int delay); void display(); public int x; public int y; public int delay; }### Answer: @Test void testThetaFromOrigin() { CursorPoint a = new CursorPoint(0, 0, 0); CursorPoint b = new CursorPoint(3, 4, 0); CursorPoint c = new CursorPoint(500, 750, 0); CursorPoint d = new CursorPoint(284, 848, 0); CursorPoint e = new CursorPoint(10, 0, 0); CursorPoint f = new CursorPoint(0, 10, 0); assertEquals(0, a.getThetaFromOrigin()); assertEquals(0.6435011087932844, b.getThetaFromOrigin()); assertEquals(0.5880026035475675, c.getThetaFromOrigin()); assertEquals(0.32316498061040844, d.getThetaFromOrigin()); assertEquals(1.5707963267948966, e.getThetaFromOrigin()); assertEquals(0.0, f.getThetaFromOrigin()); }
### Question: CursorPoint { public CursorPoint getCursorPointRotatedBy(double angleOfRotation) { int rotatedX = (int) (Math.cos(angleOfRotation) * this.x - Math.sin(angleOfRotation) * this.y); int rotatedY = (int) (Math.sin(angleOfRotation) * this.x + Math.cos(angleOfRotation) * this.y); return (new CursorPoint(rotatedX, rotatedY, delay)); } CursorPoint(int x, int y, int delay); double getDistanceFromOrigin(); double getThetaFromOrigin(); CursorPoint getCursorPointTranslatedBy(CursorPoint startingCursorPoint); CursorPoint getCursorPointScaledBy(double scaleFactor); CursorPoint getCursorPointRotatedBy(double angleOfRotation); CursorPoint getCursorPointTransformedByParabola(double[] parabolaEquation); CursorPoint getCursorPointWithNewDelay(int delay); void display(); public int x; public int y; public int delay; }### Answer: @Test void testCursorPointRotation() { CursorPoint a = new CursorPoint(0, 0, 0); CursorPoint b = new CursorPoint(10, 0, 0); CursorPoint c = new CursorPoint(10, 20, 0); CursorPoint d = a.getCursorPointRotatedBy(Math.PI / 4); CursorPoint e = b.getCursorPointRotatedBy(Math.PI / 3); CursorPoint f = c.getCursorPointRotatedBy(-Math.PI / 6); CursorPoint g = b.getCursorPointRotatedBy(-Math.PI / 6); assertTrue(d.x == 0 && d.y == 0); assertTrue(e.x == 5 && e.y == 8); assertTrue(f.x == 18 && f.y == 12); assertTrue(g.x == 8 && g.y == -4); }
### Question: CursorPoint { public CursorPoint getCursorPointScaledBy(double scaleFactor) { return (new CursorPoint((int) (this.x * scaleFactor), (int) (this.y * scaleFactor), (int) (delay * scaleFactor))); } CursorPoint(int x, int y, int delay); double getDistanceFromOrigin(); double getThetaFromOrigin(); CursorPoint getCursorPointTranslatedBy(CursorPoint startingCursorPoint); CursorPoint getCursorPointScaledBy(double scaleFactor); CursorPoint getCursorPointRotatedBy(double angleOfRotation); CursorPoint getCursorPointTransformedByParabola(double[] parabolaEquation); CursorPoint getCursorPointWithNewDelay(int delay); void display(); public int x; public int y; public int delay; }### Answer: @Test void testCursorPointScaling() { CursorPoint a = new CursorPoint(0, 0, 0); CursorPoint b = new CursorPoint(100, 0, 0); CursorPoint c = new CursorPoint(100, 200, 0); CursorPoint d = new CursorPoint(-400, -300, 0); CursorPoint e = a.getCursorPointScaledBy(1.1); CursorPoint f = b.getCursorPointScaledBy(0.95); CursorPoint g = c.getCursorPointScaledBy(1.23); CursorPoint h = d.getCursorPointScaledBy(1.07); assertTrue(e.x == 0 && e.y == 0); assertTrue(f.x == 95 && f.y == 0); assertTrue(g.x == 123 && g.y == 246); assertTrue(h.x == -428 && h.y == -321); }
### Question: InventoryItems { public String getNameOfItemFromImage(BufferedImage inputImage) { for (String itemName : items.keySet()) { if (getItemByName(itemName).itemMatchesImage(inputImage)) { return itemName; } } return "empty"; } InventoryItems(String itemDirectoryPath); File[] getListOfFilesFromItemDirectory(String itemDirectoryPath); String getItemNameFromFile(String fileName); boolean isImageThisItem(BufferedImage itemImage, String itemName); String getNameOfItemFromImage(BufferedImage inputImage); }### Answer: @Test public void testGetNameOfItemFromImage() throws IOException { initialize(); for (File itemFile : items.getListOfFilesFromItemDirectory(Paths.INVENTORY_ITEMS_TEST_DIRECTORY_PATH)) { if (itemFile.isFile()) { BufferedImage itemImage = ImageIO.read(itemFile); String expectedItemName = getItemNameForTest(itemFile.getName()); assertEquals(expectedItemName, items.getNameOfItemFromImage(itemImage)); } } }
### Question: InventoryItems { public boolean isImageThisItem(BufferedImage itemImage, String itemName) { if (items.containsKey(itemName)) { return getItemByName(itemName).itemMatchesImage(itemImage); } return false; } InventoryItems(String itemDirectoryPath); File[] getListOfFilesFromItemDirectory(String itemDirectoryPath); String getItemNameFromFile(String fileName); boolean isImageThisItem(BufferedImage itemImage, String itemName); String getNameOfItemFromImage(BufferedImage inputImage); }### Answer: @Test public void testIsImageThisItem() throws IOException { initialize(); for (File itemFile : items.getListOfFilesFromItemDirectory(Paths.INVENTORY_ITEMS_TEST_DIRECTORY_PATH)) { if (itemFile.isFile()) { BufferedImage itemImage = ImageIO.read(itemFile); String expectedItemName = getItemNameForTest(itemFile.getName()); if (expectedItemName.equals("empty")) { continue; } assertTrue(items.isImageThisItem(itemImage, expectedItemName)); } } }
### Question: Cursors { public static <T> FluentIterable<T> toFluentIterable(Cursor cursor, Function<? super Cursor, T> singleRowTransform) { List<T> transformed = Lists.newArrayList(); if (cursor != null) { for (int i = 0; cursor.moveToPosition(i); i++) { transformed.add(singleRowTransform.apply(cursor)); } } return FluentIterable.from(transformed); } private Cursors(); static FluentIterable<T> toFluentIterable(Cursor cursor, Function<? super Cursor, T> singleRowTransform); static void closeQuietly(Cursor cursor); static Cursor returnSameOrEmptyIfNull(Cursor cursor); }### Answer: @Test public void shouldSurviveNullPassedToFluentIterable() throws Exception { final Cursor cursor = null; final FluentIterable<Object> objects = Cursors.toFluentIterable(cursor, new Function<Cursor, Object>() { @Override public Object apply(Cursor cursor) { return null; } }); assertThat(objects).isEmpty(); }
### Question: FluentCursor extends CrossProcessCursorWrapper { public int toRowCount() { try { return getCount(); } finally { close(); } } FluentCursor(Cursor cursor); FluentIterable<T> toFluentIterable(Function<? super Cursor, T> singleRowTransform); LazyCursorList<T> toLazyCursorList(Function<? super Cursor, T> singleRowTransform); LinkedHashMultimap<TKey, TValue> toMultimap(Function<? super Cursor, TKey> keyTransform, Function<? super Cursor, TValue> valueTransform); LinkedHashMap<TKey, TValue> toMap(Function<? super Cursor, TKey> keyTransform, Function<? super Cursor, TValue> valueTransform); T toOnlyElement(Function<? super Cursor, T> singleRowTransform); T toOnlyElement(Function<? super Cursor, T> singleRowTransform, T defaultValue); int toRowCount(); FluentCursor withNotificationUri(ContentResolver resolver, Uri uri); }### Answer: @Test public void shouldCloseCursorWhenGettingRowCount() throws Exception { Cursor mock = mock(Cursor.class); new FluentCursor(mock).toRowCount(); verify(mock).close(); } @Test public void shouldConvertToCorrectRowCount() throws Exception { Cursor mock = mock(Cursor.class); when(mock.getCount()).thenReturn(42); assertThat(new FluentCursor(mock).toRowCount()).isEqualTo(42); } @Test public void shouldNotIterateOverCursorWhenTransformingCursorToRowCount() throws Exception { Cursor mock = mock(Cursor.class); new FluentCursor(mock).toRowCount(); verify(mock, never()).moveToFirst(); verify(mock, never()).moveToNext(); verify(mock, never()).moveToLast(); verify(mock, never()).moveToPrevious(); verify(mock, never()).moveToPosition(anyInt()); }
### Question: Cursors { public static void closeQuietly(Cursor cursor) { if (cursor != null && !cursor.isClosed()) { cursor.close(); } } private Cursors(); static FluentIterable<T> toFluentIterable(Cursor cursor, Function<? super Cursor, T> singleRowTransform); static void closeQuietly(Cursor cursor); static Cursor returnSameOrEmptyIfNull(Cursor cursor); }### Answer: @Test public void shouldCloseCursorProperly() throws Exception { final MatrixCursor cursor = new MatrixCursor(new String[] { "column1" }); Cursors.closeQuietly(cursor); assertThat(cursor.isClosed()).isTrue(); } @Test public void shouldSurviveNullPassedToCloseQuietly() throws Exception { Cursors.closeQuietly(null); } @Test public void shouldNotTryToCloseAlreadyClosedCursor() throws Exception { Cursor cursor = mock(Cursor.class); when(cursor.isClosed()).thenReturn(true); Cursors.closeQuietly(cursor); verify(cursor, never()).close(); }
### Question: ViewActions { public static ViewSelector<ViewSelectStatementChooser> create() { return new CreateViewAction(); } private ViewActions(); static ViewSelector<ViewSelectStatementChooser> create(); static ViewSelector<ViewAction> dropIfExists(); }### Answer: @Test public void shouldCreateViewFromProvidedQuery() throws Exception { ViewActions .create() .view("view_a") .as(select().from("table_a").build()) .perform(db); Mockito.verify(db).execSQL("CREATE VIEW view_a AS SELECT * FROM table_a"); } @Test(expected = IllegalArgumentException.class) public void shouldNotAllowUsingQueryWithBoundArgs() throws Exception { ViewActions .create() .view("view_a") .as( select() .from("table_a") .where(column("col_a").eq().arg(), "test") .build() ); }
### Question: ViewActions { public static ViewSelector<ViewAction> dropIfExists() { return new DropViewAction(); } private ViewActions(); static ViewSelector<ViewSelectStatementChooser> create(); static ViewSelector<ViewAction> dropIfExists(); }### Answer: @Test public void shouldDropSpecifiedView() throws Exception { ViewActions .dropIfExists() .view("view_a") .perform(db); Mockito.verify(db).execSQL("DROP VIEW IF EXISTS view_a"); }
### Question: Insert implements InsertValuesBuilder { private Insert(String table, ContentValues values) { mTable = table; mValues = values; } private Insert(String table, ContentValues values); static InsertTableSelector insert(); long perform(SQLiteDatabase db); long performOrThrow(SQLiteDatabase db); @Override Insert values(ContentValues values); @Override Insert value(String column, Object value); }### Answer: @Test public void shouldUseTableSpecifiedInIntoStepInInsertForDefaultValues() throws Exception { DefaultValuesInsert insert = insert().into("A").defaultValues("nullable_col"); assertThat(insert.mTable).isEqualTo("A"); } @Test public void shouldBuildTheInsertForDefaultValues() throws Exception { DefaultValuesInsert insert = insert().into("A").defaultValues("nullable_col"); assertThat(insert.mNullColumnHack).isEqualTo("nullable_col"); }
### Question: Expressions { public static ExpressionCombiner coalesce(Expression... expressions) { return new Builder().coalesce(expressions); } private Expressions(); static ExpressionCore not(); static ExpressionCombiner column(String col); static ExpressionCombiner column(String table, String col); static ExpressionCombiner arg(); static ExpressionCombiner nul(); static ExpressionCombiner literal(Number number); static ExpressionCombiner literal(Object object); @SafeVarargs static Expression[] literals(T... objects); static Expression[] literals(Number... numbers); static ExpressionCombiner sum(Expression e); static ExpressionCombiner count(Expression e); static ExpressionCombiner count(); static ExpressionCombiner max(Expression e); static ExpressionCombiner min(Expression e); static ExpressionCombiner ifNull(Expression left, Expression right); static ExpressionCombiner nullIf(Expression left, Expression right); static ExpressionCombiner coalesce(Expression... expressions); static ExpressionCombiner length(Expression e); static ExpressionCombiner concat(Expression... e); static ExpressionCombiner expr(String expression); static ExpressionCombiner expr(Expression expression); static ExpressionCombiner join(String on, Expression... e); static CaseCondition cases(); static CaseCondition cases(Expression e); static final Function<Query, Iterable<String>> GET_TABLES; }### Answer: @Test(expected = IllegalArgumentException.class) public void shouldRejectCoalesceWithNoArguments() throws Exception { coalesce(); }
### Question: Expressions { @SafeVarargs public static <T> Expression[] literals(T... objects) { Preconditions.checkNotNull(objects); Expression[] result = new Expression[objects.length]; for (int i = 0; i < objects.length; i++) { result[i] = literal(objects[i]); } return result; } private Expressions(); static ExpressionCore not(); static ExpressionCombiner column(String col); static ExpressionCombiner column(String table, String col); static ExpressionCombiner arg(); static ExpressionCombiner nul(); static ExpressionCombiner literal(Number number); static ExpressionCombiner literal(Object object); @SafeVarargs static Expression[] literals(T... objects); static Expression[] literals(Number... numbers); static ExpressionCombiner sum(Expression e); static ExpressionCombiner count(Expression e); static ExpressionCombiner count(); static ExpressionCombiner max(Expression e); static ExpressionCombiner min(Expression e); static ExpressionCombiner ifNull(Expression left, Expression right); static ExpressionCombiner nullIf(Expression left, Expression right); static ExpressionCombiner coalesce(Expression... expressions); static ExpressionCombiner length(Expression e); static ExpressionCombiner concat(Expression... e); static ExpressionCombiner expr(String expression); static ExpressionCombiner expr(Expression expression); static ExpressionCombiner join(String on, Expression... e); static CaseCondition cases(); static CaseCondition cases(Expression e); static final Function<Query, Iterable<String>> GET_TABLES; }### Answer: @Test(expected = NullPointerException.class) public void shouldFailToConvertNullNumbersArrayIntoExpressions() throws Exception { literals((Number[]) null); } @Test(expected = NullPointerException.class) public void shouldFailToConvertNullObjectsArrayIntoExpressions() throws Exception { literals((Number[]) null); }
### Question: Utils { public static Object escapeSqlArg(Object arg) { if (arg == null) { return null; } if (arg instanceof Boolean) { return (Boolean) arg ? 1 : 0; } if(arg instanceof Number) { return arg; } return DatabaseUtils.sqlEscapeString(arg.toString()); } private Utils(); static void addToContentValues(String key, Object value, ContentValues contentValues); static void bindContentValueArg(SQLiteStatement statement, int index, Object value); static Object escapeSqlArg(Object arg); static Function<T, Object> toEscapedSqlFunction(); static final UriDecorator DUMMY_URI_DECORATOR; }### Answer: @Test public void shouldReturnNull() throws Exception { assertThat(Utils.escapeSqlArg(null)).isNull(); } @Test public void shouldReturnSqlBoolean() throws Exception { assertThat(Utils.escapeSqlArg(true)).isEqualTo(1); } @Test public void shouldReturnNumber() throws Exception { assertThat(Utils.escapeSqlArg(1L)).isEqualTo(1L); } @Test public void shouldReturnEscapedString() throws Exception { assertThat(Utils.escapeSqlArg("test")).isEqualTo("'test'"); }
### Question: LazyCursorList extends AbstractList<T> implements RandomAccess, Closeable { @Override public T get(int i) { return cache.get(i); } LazyCursorList(final Cursor cursor, final Function<? super Cursor, T> function); @Override T get(int i); @Override int size(); @Override void close(); }### Answer: @Test public void shouldAccessProperRow() throws Exception { final MatrixCursor cursor = new MatrixCursor(new String[] { "name" }); for (int i = 0; i < 10; i++) { cursor.addRow(new Object[] { "Name" + i }); } final LazyCursorList<String> list = new LazyCursorList<String>(cursor, new Function<Cursor, String>() { @Override public String apply(Cursor cursor) { return cursor.getString(0); } }); assertThat(list.get(5)).isEqualTo("Name" + 5); }
### Question: LazyCursorList extends AbstractList<T> implements RandomAccess, Closeable { @Override public int size() { return cursor.getCount(); } LazyCursorList(final Cursor cursor, final Function<? super Cursor, T> function); @Override T get(int i); @Override int size(); @Override void close(); }### Answer: @Test public void shouldContainProperSize() throws Exception { final MatrixCursor cursor = new MatrixCursor(new String[] { "name" }); for (int i = 0; i < 10; i++) { cursor.addRow(new Object[] { "Name" + i }); } final LazyCursorList<String> list = new LazyCursorList<String>(cursor, new Function<Cursor, String>() { @Override public String apply(Cursor cursor) { return null; } }); assertThat(list.size()).isEqualTo(cursor.getCount()); }
### Question: ProductService { @RequestMapping(value="/product/{id}", method = RequestMethod.GET ) Product getProduct(@PathVariable("id") int id) { Product prod = prodRepo.findOne(id); if (prod == null) throw new RuntimeException("No product for id " + id); else return prod ; } }### Answer: @Test public void getProduct() { ResponseEntity<Product> response = restTemplate.getForEntity("/product/1", Product.class); assertEquals(HttpStatus.OK, response.getStatusCode()); assertEquals("Apples", response.getBody().getName()); }
### Question: ProductService { @RequestMapping("/products") List<Product> getProductsForCategory(@RequestParam("id") int id) { return prodRepo.findByCatId(id); } }### Answer: @Test public void getProductsForCategory() { ResponseEntity<Object[]> response = restTemplate.getForEntity("/products?id=1", Object[].class); assertEquals(HttpStatus.OK, response.getStatusCode()); assertFalse(response.getBody().length == 0); }
### Question: HelloHandler implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> { @Override public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent request, Context context) { String who = "World"; if ( request.getPathParameters() != null ) { String name = request.getPathParameters().get("name"); if ( name != null && !"".equals(name.trim()) ) { who = name; } } return new APIGatewayProxyResponseEvent().withStatusCode(HttpURLConnection.HTTP_OK).withBody(String.format("Hello %s!", who)); } @Override APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent request, Context context); }### Answer: @Test public void handleRequest() { APIGatewayProxyResponseEvent res = handler.handleRequest(input, null); assertNotNull(res); assertEquals("Hello Universe!", res.getBody()); } @Test public void handleEmptyRequest() { input.withPathParamters(Collections.emptyMap()); APIGatewayProxyResponseEvent res = handler.handleRequest(input, null); assertNotNull(res); assertEquals("Hello World!", res.getBody()); }
### Question: Function { @FunctionName("hello") public HttpResponseMessage<String> hello( @HttpTrigger(name = "req", methods = { "get", "post" }, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request, final ExecutionContext context) { context.getLogger().info("Java HTTP trigger processed a request."); String query = request.getQueryParameters().get("name"); String name = request.getBody().orElse(query); if (name == null) { return request.createResponse(400, "Please pass a name on the query string or in the request body"); } else { return request.createResponse(200, "Hello, " + name); } } @FunctionName("hello") HttpResponseMessage<String> hello( @HttpTrigger(name = "req", methods = { "get", "post" }, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request, final ExecutionContext context); }### Answer: @Test public void testHello() throws Exception { final HttpRequestMessage<Optional<String>> req = mock(HttpRequestMessage.class); final Map<String, String> queryParams = new HashMap<>(); queryParams.put("name", "Azure"); doReturn(queryParams).when(req).getQueryParameters(); final Optional<String> queryBody = Optional.empty(); doReturn(queryBody).when(req).getBody(); final HttpResponseMessage res = mock(HttpResponseMessage.class); doReturn(res).when(req).createResponse(anyInt(), anyString()); final ExecutionContext context = mock(ExecutionContext.class); doReturn(Logger.getGlobal()).when(context).getLogger(); final HttpResponseMessage ret = new Function().hello(req, context); assertSame(res, ret); }
### Question: GroupId implements Comparable<GroupId> { public static GroupId ofString(String str) { Matcher matcher = VERSION_PATTERN.matcher(str); if (matcher.matches()) { MatchResult result = matcher.toMatchResult(); return GroupId.of( result.group(1), Optional.ofNullable(result.group(2)).map(Integer::parseInt) ); } else { return GroupId.of( str, Optional.empty() ); } } static GroupId of(String name, int version); static GroupId of(String name, Optional<Integer> version); static GroupId ofString(String str); String asString(); @Override int compareTo(GroupId other); static final Comparator<GroupId> COMPARATOR; static final String VERSION_SEPARATOR; static final Pattern VERSION_PATTERN; }### Answer: @Test public void testParsing() { assertThat(GroupId.ofString(string)).isEqualTo(object); }
### Question: GroupId implements Comparable<GroupId> { public String asString() { return name + version.map(it -> VERSION_SEPARATOR + it).orElse(""); } static GroupId of(String name, int version); static GroupId of(String name, Optional<Integer> version); static GroupId ofString(String str); String asString(); @Override int compareTo(GroupId other); static final Comparator<GroupId> COMPARATOR; static final String VERSION_SEPARATOR; static final Pattern VERSION_PATTERN; }### Answer: @Test public void testStringRepresentation() { assertThat(object.asString()).isEqualTo(string); }
### Question: StaticRSAKeyProvider implements RSAKeyProvider { @SneakyThrows(NoSuchAlgorithmException.class) static RSAPublicKey parsePubKey(String key) throws InvalidKeySpecException { String keyContent = key.replaceAll("\\n", "") .replace("-----BEGIN PUBLIC KEY-----", "") .replace("-----END PUBLIC KEY-----", ""); byte[] byteKey = Base64.getDecoder().decode(keyContent); var x509EncodedKeySpec = new X509EncodedKeySpec(byteKey); return (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(x509EncodedKeySpec); } StaticRSAKeyProvider(Map<String, String> keys); @Override RSAPublicKey getPublicKeyById(String keyId); @Override RSAPrivateKey getPrivateKey(); @Override String getPrivateKeyId(); }### Answer: @Test void shouldThrowExceptionOnInvalid() { assertThatThrownBy(() -> StaticRSAKeyProvider.parsePubKey("")).isInstanceOf(InvalidKeySpecException.class); }
### Question: StaticRSAKeyProvider implements RSAKeyProvider { @Override public RSAPublicKey getPublicKeyById(String keyId) { if (!keys.containsKey(keyId)) { throw new NoSuchElementException(String.format("KeyId %s is not defined to authorize GRPC requests", keyId)); } return keys.get(keyId); } StaticRSAKeyProvider(Map<String, String> keys); @Override RSAPublicKey getPublicKeyById(String keyId); @Override RSAPrivateKey getPrivateKey(); @Override String getPrivateKeyId(); }### Answer: @Test void shouldComplainOnNotFoundKey() { assertThatThrownBy(() -> new StaticRSAKeyProvider(Map.of( "valid", STRIPPED_4096 )).getPublicKeyById("unknown")) .isInstanceOf(NoSuchElementException.class); }
### Question: FixLengthDecoder extends ByteToMessageDecoder { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { while (in.readableBytes() >= length){ ByteBuf byt = in.readBytes(length) ; out.add(byt) ; } } FixLengthDecoder(int length); }### Answer: @Test public void decode() throws Exception { ByteBuf buf = Unpooled.buffer(); for (int i = 0; i < 9; i++) { buf.writeByte(i); } ByteBuf duplicate = buf.duplicate(); EmbeddedChannel channel = new EmbeddedChannel(new FixLengthDecoder(3)); channel.writeInbound(buf.retain()); channel.finish(); ByteBuf read = channel.readInbound(); Assert.assertEquals(duplicate.readSlice(3), read); read = channel.readInbound(); Assert.assertEquals(duplicate.readSlice(3), read); read = channel.readInbound(); Assert.assertEquals(duplicate.readSlice(3), read); read.release(); }
### Question: EdgeMetadata { public Iterable<String> toIterable(CSVRecord record) { return () -> new Iterator<String>() { int currentColumnIndex = firstColumnIndex - 1; @Override public boolean hasNext() { return currentColumnIndex < record.size(); } @Override public String next() { if (currentColumnIndex < firstColumnIndex) { currentColumnIndex++; return idGenerator.get(); } else { int headerIndex = currentColumnIndex - firstColumnIndex + 1; Header header = headers.get(headerIndex); PropertyValue propertyValue = propertyValueParser.parse(record.get(currentColumnIndex)); header.updateDataType(propertyValue.dataType()); currentColumnIndex++; return propertyValue.value(); } } }; } private EdgeMetadata(Headers headers, int firstColumnIndex, Supplier<String> idGenerator, PropertyValueParser parser); static EdgeMetadata parse(CSVRecord record, PropertyValueParser parser); List<String> headers(); boolean isEdge(CSVRecord record); Iterable<String> toIterable(CSVRecord record); }### Answer: @Test public void shouldWrapRecordWithEdgeSpecificIterable() { String columnHeaders = "\"_id\",\"_labels\",\"address\",\"name\",\"index\",\"txid\",\"_start\",\"_end\",\"_type\",\"strength\",\"timestamp\""; EdgeMetadata edgeMetadata = createEdgeMetadata(columnHeaders); CSVRecord record = CSVUtils.firstRecord(",,,,,,\"1\",\"2\",\"KNOWS\",\"10\",\"12345\""); Iterable<String> edge = edgeMetadata.toIterable(record); String expected = "edge-id,1,2,KNOWS,10,12345"; assertEquals(expected, String.join(",", edge)); }
### Question: Range { public boolean isAll(){ return start == 0 && end == -1; } Range(long start, long end); GraphTraversal<? extends Element, ?> applyRange(GraphTraversal<? extends Element, ?> traversal); long difference(); boolean isEmpty(); boolean isAll(); @Override String toString(); boolean sizeExceeds(long value); static final Range ALL; }### Answer: @Test public void shouldIndicateThatRangeCoversAll(){ assertTrue(new Range(0, -1).isAll()); assertFalse(new Range(0, 1).isAll()); assertFalse(new Range(-1, -1).isAll()); }
### Question: Range { public boolean isEmpty() { return start == -1 && end == -1; } Range(long start, long end); GraphTraversal<? extends Element, ?> applyRange(GraphTraversal<? extends Element, ?> traversal); long difference(); boolean isEmpty(); boolean isAll(); @Override String toString(); boolean sizeExceeds(long value); static final Range ALL; }### Answer: @Test public void shouldIndicateIfEmpty(){ assertTrue(new Range(-1, -1).isEmpty()); assertFalse(new Range(0, 1).isEmpty()); assertFalse(new Range(0, -1).isEmpty()); }
### Question: Range { public boolean sizeExceeds(long value) { if (isEmpty()){ return false; } if (isAll()){ return true; } return value < (end - start); } Range(long start, long end); GraphTraversal<? extends Element, ?> applyRange(GraphTraversal<? extends Element, ?> traversal); long difference(); boolean isEmpty(); boolean isAll(); @Override String toString(); boolean sizeExceeds(long value); static final Range ALL; }### Answer: @Test public void shouldIndicateIfSizeBiggerThanSuupliedValue(){ assertTrue(new Range(0, -1).sizeExceeds(100)); assertTrue(new Range(0, 200).sizeExceeds(100)); assertFalse(new Range(0, 100).sizeExceeds(100)); assertFalse(new Range(0, 100).sizeExceeds(200)); assertFalse(new Range(-1, -1).sizeExceeds(1)); }
### Question: S3ObjectInfo { public String bucket() { return bucket; } S3ObjectInfo(String s3Uri); String bucket(); String key(); File createDownloadFile(String parent); S3ObjectInfo withNewKeySuffix(String suffix); S3ObjectInfo replaceOrAppendKey(String placeholder, String ifPresent, String ifAbsent); S3ObjectInfo replaceOrAppendKey(String placeholder, String ifPresent); @Override String toString(); }### Answer: @Test public void canParseBucketFromURI(){ String s3Uri = "s3: S3ObjectInfo s3ObjectInfo = new S3ObjectInfo(s3Uri); assertEquals("my-bucket", s3ObjectInfo.bucket()); }
### Question: S3ObjectInfo { public String key() { return key; } S3ObjectInfo(String s3Uri); String bucket(); String key(); File createDownloadFile(String parent); S3ObjectInfo withNewKeySuffix(String suffix); S3ObjectInfo replaceOrAppendKey(String placeholder, String ifPresent, String ifAbsent); S3ObjectInfo replaceOrAppendKey(String placeholder, String ifPresent); @Override String toString(); }### Answer: @Test public void canParseKeyWithoutTrailingSlashFromURI(){ String s3Uri = "s3: S3ObjectInfo s3ObjectInfo = new S3ObjectInfo(s3Uri); assertEquals("a/b/c", s3ObjectInfo.key()); } @Test public void canParseKeyWithTrainlingSlashFromURI(){ String s3Uri = "s3: S3ObjectInfo s3ObjectInfo = new S3ObjectInfo(s3Uri); assertEquals("a/b/c/", s3ObjectInfo.key()); }
### Question: S3ObjectInfo { public File createDownloadFile(String parent) { return new File(parent, fileName); } S3ObjectInfo(String s3Uri); String bucket(); String key(); File createDownloadFile(String parent); S3ObjectInfo withNewKeySuffix(String suffix); S3ObjectInfo replaceOrAppendKey(String placeholder, String ifPresent, String ifAbsent); S3ObjectInfo replaceOrAppendKey(String placeholder, String ifPresent); @Override String toString(); }### Answer: @Test public void canCreateDownloadFileForKeyWithoutTrailingSlash(){ String s3Uri = "s3: S3ObjectInfo s3ObjectInfo = new S3ObjectInfo(s3Uri); assertEquals("/temp/c.txt", s3ObjectInfo.createDownloadFile("/temp").getAbsolutePath()); } @Test public void canCreateDownloadFileForKeyWithTrailingSlash(){ String s3Uri = "s3: S3ObjectInfo s3ObjectInfo = new S3ObjectInfo(s3Uri); assertEquals("/temp/c", s3ObjectInfo.createDownloadFile("/temp").getAbsolutePath()); }
### Question: Args { @Override public String toString() { return String.join(" ", args); } Args(String cmd); void removeOptions(String... options); void removeFlags(String... flags); void addOption(String option, String value); boolean contains(String name); String[] values(); @Override String toString(); }### Answer: @Test public void shouldFormatAsString() throws Exception { Args args = new Args("-e endpoint -c config"); assertEquals("-e endpoint -c config", args.toString()); }
### Question: VertexMetadata { public boolean isVertex(CSVRecord record) { return !record.get(0).isEmpty(); } private VertexMetadata(Headers headers, int lastColumnIndex, PropertyValueParser parser); static VertexMetadata parse(CSVRecord record, PropertyValueParser parser); List<String> headers(); boolean isVertex(CSVRecord record); Iterable<String> toIterable(CSVRecord record); }### Answer: @Test public void shouldIndicateWhetherARecordContainsAVertex() { String columnHeaders = "\"_id\",\"_labels\",\"address\",\"name\",\"index\",\"txid\",\"_start\",\"_end\",\"_type\",\"strength\",\"timestamp\""; VertexMetadata vertexMetadata = createVertexMetadata(columnHeaders); CSVRecord vertexRecord = CSVUtils.firstRecord("\"1\",\"Person\",\"address\",\"name\",\"1\",\"1\",,,,,"); CSVRecord edgeRecord = CSVUtils.firstRecord(",,,,,,\"1\",\"2\",\"KNOWS\",\"10\",\"12345\""); assertTrue(vertexMetadata.isVertex(vertexRecord)); assertFalse(vertexMetadata.isVertex(edgeRecord)); }
### Question: EdgeMetadata { public boolean isEdge(CSVRecord record) { return (!record.get(firstColumnIndex).isEmpty()) && (!record.get(firstColumnIndex + 1).isEmpty()) && (!record.get(firstColumnIndex + 2).isEmpty()); } private EdgeMetadata(Headers headers, int firstColumnIndex, Supplier<String> idGenerator, PropertyValueParser parser); static EdgeMetadata parse(CSVRecord record, PropertyValueParser parser); List<String> headers(); boolean isEdge(CSVRecord record); Iterable<String> toIterable(CSVRecord record); }### Answer: @Test public void shouldIndicateWhetherARecordContainsAnEdge() { String columnHeaders = "\"_id\",\"_labels\",\"address\",\"name\",\"index\",\"txid\",\"_start\",\"_end\",\"_type\",\"strength\",\"timestamp\""; EdgeMetadata edgeMetadata = createEdgeMetadata(columnHeaders); CSVRecord vertexRecord = CSVUtils.firstRecord("\"1\",\"Person\",\"address\",\"name\",\"1\",\"1\",,,,,"); CSVRecord edgeRecord = CSVUtils.firstRecord(",,,,,,\"1\",\"2\",\"KNOWS\",\"10\",\"12345\""); assertFalse(edgeMetadata.isEdge(vertexRecord)); assertTrue(edgeMetadata.isEdge(edgeRecord)); }
### Question: BaseStageModel { protected final void sendEmptyResponse() { doSendResponse(EMPTY_DATA); } protected BaseStageModel(AndroidComponentDelegate androidComponentDelegate); protected BaseStageModel(@Nullable Activity activity); protected BaseStageModel(@NonNull ClientCommunicator clientCommunicator, InternalData senderInternalData); String getFlowInitiatorPackage(); Observable<FlowEvent> getEvents(); @NonNull abstract String getRequestJson(); @NonNull ObservableActivityHelper<AppMessage> processInActivity(Context context, Class<? extends Activity> activityClass); @NonNull ObservableActivityHelper<AppMessage> processInActivity(Context context, Intent activityIntent, String requestJson); void addAuditEntry(AuditEntry.AuditSeverity auditSeverity, String message, Object... parameters); void sendEvent(FlowEvent flowEvent); }### Answer: @Test(expected = IllegalStateException.class) public void shouldOnlyAllowResponseSentOnce() throws Exception { testModel.sendEmptyResponse(); testModel.sendEmptyResponse(); }
### Question: BaseApiClient { protected InternalData getInternalData() { return internalData; } protected BaseApiClient(String apiVersion, Context context); @NonNull Completable initiateRequest(final Request request); Completable sendEvent(final FlowEvent flowEvent); @NonNull Observable<Response> queryResponses(@NonNull ResponseQuery responseQuery); @NonNull Single<List<Device>> getDevices(); @NonNull Observable<FlowEvent> subscribeToSystemEvents(); static boolean isProcessingServiceInstalled(Context context); @NonNull static String getProcessingServiceVersion(Context context); static final String FLOW_PROCESSING_SERVICE; }### Answer: @Test public void shouldParsePropertiesFileAndSetVersion() throws Exception { assertThat(apiBase.getInternalData().getSenderApiVersion()).isEqualTo("1.2.3"); }
### Question: BaseApiClient { public static boolean isProcessingServiceInstalled(Context context) { PackageManager packageManager = context.getPackageManager(); List<ResolveInfo> resolveInfo = packageManager .queryIntentServices(getIntent(FLOW_PROCESSING_SERVICE_COMPONENT), PackageManager.MATCH_DEFAULT_ONLY); return resolveInfo.size() == 1 && resolveInfo.get(0).serviceInfo != null; } protected BaseApiClient(String apiVersion, Context context); @NonNull Completable initiateRequest(final Request request); Completable sendEvent(final FlowEvent flowEvent); @NonNull Observable<Response> queryResponses(@NonNull ResponseQuery responseQuery); @NonNull Single<List<Device>> getDevices(); @NonNull Observable<FlowEvent> subscribeToSystemEvents(); static boolean isProcessingServiceInstalled(Context context); @NonNull static String getProcessingServiceVersion(Context context); static final String FLOW_PROCESSING_SERVICE; }### Answer: @Test public void callIsProcessingServiceInstalledShouldReturnFalse() throws Exception { assertThat(BaseApiClient.isProcessingServiceInstalled(RuntimeEnvironment.application)).isFalse(); } @Test public void callIsProcessingServiceInstalledShouldReturnTrueIfPackageManagerThinksSo() throws Exception { pretendServiceIsInstalled(BaseApiClient.FLOW_PROCESSING_SERVICE_COMPONENT); assertThat(BaseApiClient.isProcessingServiceInstalled(RuntimeEnvironment.application)).isTrue(); }
### Question: BaseApiClient { @NonNull public Single<List<Device>> getDevices() { if (!isProcessingServiceInstalled(context)) { return Single.error(NO_FPS_EXCEPTION); } final ChannelClient deviceMessenger = getMessengerClient(INFO_PROVIDER_SERVICE_COMPONENT); AppMessage appMessage = new AppMessage(DEVICE_INFO_REQUEST, getInternalData()); return deviceMessenger .sendMessage(appMessage.toJson()) .map(Device::fromJson) .toList() .doFinally(deviceMessenger::closeConnection) .onErrorResumeNext(throwable -> Single.error(createFlowException(throwable))); } protected BaseApiClient(String apiVersion, Context context); @NonNull Completable initiateRequest(final Request request); Completable sendEvent(final FlowEvent flowEvent); @NonNull Observable<Response> queryResponses(@NonNull ResponseQuery responseQuery); @NonNull Single<List<Device>> getDevices(); @NonNull Observable<FlowEvent> subscribeToSystemEvents(); static boolean isProcessingServiceInstalled(Context context); @NonNull static String getProcessingServiceVersion(Context context); static final String FLOW_PROCESSING_SERVICE; }### Answer: @Test public void getDevicesShouldSendCorrectMessage() throws Exception { pretendServiceIsInstalled(BaseApiClient.FLOW_PROCESSING_SERVICE_COMPONENT); apiBase.getDevices().test(); AppMessage appMessage = callSendAndCaptureMessage(); assertThat(appMessage).isNotNull(); verify(messengerClient).closeConnection(); } @Test public void getDevicesShouldErrorIfNoFps() throws Exception { TestObserver<List<Device>> testObserver = apiBase.getDevices().test(); assertThat(testObserver.assertError(BaseApiClient.NO_FPS_EXCEPTION)); }
### Question: BasketItemModifierBuilder { @NonNull public BasketItemModifier build() { checkNotEmpty(name, "Name must be set"); checkNotEmpty(type, "Type must be set"); checkArgument(amount != null || percentage != null, "Either amount or percentage must be set"); return new BasketItemModifier(id, name, type, amount, percentage); } BasketItemModifierBuilder(@NonNull String name, @NonNull String type); @NonNull BasketItemModifierBuilder withId(String id); @NonNull BasketItemModifierBuilder withFractionalAmount(float amount); BasketItemModifierBuilder withAmount(long amount); BasketItemModifierBuilder withPercentage(float percentage); @NonNull BasketItemModifier build(); }### Answer: @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionIfNoAmountOrPercentage() throws Exception { new BasketItemModifierBuilder("bananas", "type") .build(); }
### Question: PaymentFlowServices implements Jsonable { public int getNumberOfFlowServices() { return paymentFlowServiceInfoList.size(); } PaymentFlowServices(Collection<PaymentFlowServiceInfo> paymentFlowServiceInfoList); int getNumberOfFlowServices(); @NonNull List<PaymentFlowServiceInfo> getAll(); @NonNull Observable<PaymentFlowServiceInfo> stream(); @Nullable PaymentFlowServiceInfo getFlowServiceFromId(String id); boolean isCustomRequestTypeSupported(String requestType); @NonNull Set<String> getAllCustomRequestTypes(); boolean isCurrencySupported(String currency); @NonNull Set<String> getAllSupportedCurrencies(); @NonNull Set<String> getAllSupportedPaymentMethods(); boolean isDataKeySupported(String dataKey); @NonNull Set<String> getAllSupportedDataKeys(); @Override String toJson(); static PaymentFlowServices fromJson(String json); }### Answer: @Test public void shouldContainListOfTwoEntries() throws Exception { assertThat(paymentFlowServices.getNumberOfFlowServices()).isEqualTo(2); }
### Question: PaymentFlowServices implements Jsonable { @NonNull public Set<String> getAllSupportedPaymentMethods() { return supportedPaymentMethods; } PaymentFlowServices(Collection<PaymentFlowServiceInfo> paymentFlowServiceInfoList); int getNumberOfFlowServices(); @NonNull List<PaymentFlowServiceInfo> getAll(); @NonNull Observable<PaymentFlowServiceInfo> stream(); @Nullable PaymentFlowServiceInfo getFlowServiceFromId(String id); boolean isCustomRequestTypeSupported(String requestType); @NonNull Set<String> getAllCustomRequestTypes(); boolean isCurrencySupported(String currency); @NonNull Set<String> getAllSupportedCurrencies(); @NonNull Set<String> getAllSupportedPaymentMethods(); boolean isDataKeySupported(String dataKey); @NonNull Set<String> getAllSupportedDataKeys(); @Override String toJson(); static PaymentFlowServices fromJson(String json); }### Answer: @Test public void shouldCollatePaymentMethodsCorrectly() throws Exception { Set<String> allSupportedPaymentMethods = paymentFlowServices.getAllSupportedPaymentMethods(); assertThat(allSupportedPaymentMethods).hasSize(3); assertThat(allSupportedPaymentMethods).containsOnly("pigeon", "yak", "horse"); }
### Question: ActivityComponentDelegate extends AndroidComponentDelegate { @Override void sendMessage(AppMessage appMessage) { appMessage.updateInternalData(responseInternalData); Activity activity = getActivity(); if (activity != null) { try { ObservableActivityHelper<AppMessage> helper = getHelperFromActivity(activity); helper.sendMessageToClient(appMessage); } catch (NoSuchInstanceException e) { Log.e(TAG, "Failed to retrieve ObservableActivityHelper - was the activity started correctly?"); } } else { Log.e(TAG, "Activity reference no longer available to send message via"); } } ActivityComponentDelegate(Activity activity); }### Answer: @Test public void sendMessageShouldSendViaHelper() throws Exception { AppMessage appMessage = new AppMessage("hello"); activityComponentDelegate.sendMessage(appMessage); verify(helper).sendMessageToClient(appMessage); }
### Question: PaymentFlowServices implements Jsonable { @NonNull public Set<String> getAllSupportedDataKeys() { return supportedDataKeys; } PaymentFlowServices(Collection<PaymentFlowServiceInfo> paymentFlowServiceInfoList); int getNumberOfFlowServices(); @NonNull List<PaymentFlowServiceInfo> getAll(); @NonNull Observable<PaymentFlowServiceInfo> stream(); @Nullable PaymentFlowServiceInfo getFlowServiceFromId(String id); boolean isCustomRequestTypeSupported(String requestType); @NonNull Set<String> getAllCustomRequestTypes(); boolean isCurrencySupported(String currency); @NonNull Set<String> getAllSupportedCurrencies(); @NonNull Set<String> getAllSupportedPaymentMethods(); boolean isDataKeySupported(String dataKey); @NonNull Set<String> getAllSupportedDataKeys(); @Override String toJson(); static PaymentFlowServices fromJson(String json); }### Answer: @Test public void shouldCollateDataKeysCorrectly() throws Exception { Set<String> allSupportedDataKeys = paymentFlowServices.getAllSupportedDataKeys(); assertThat(allSupportedDataKeys).hasSize(3); assertThat(allSupportedDataKeys).containsOnly("dataOne", "dataTwo", "dataThree"); }
### Question: PaymentFlowServices implements Jsonable { public boolean isDataKeySupported(String dataKey) { return ComparisonUtil.stringCollectionContainsIgnoreCase(supportedDataKeys, dataKey); } PaymentFlowServices(Collection<PaymentFlowServiceInfo> paymentFlowServiceInfoList); int getNumberOfFlowServices(); @NonNull List<PaymentFlowServiceInfo> getAll(); @NonNull Observable<PaymentFlowServiceInfo> stream(); @Nullable PaymentFlowServiceInfo getFlowServiceFromId(String id); boolean isCustomRequestTypeSupported(String requestType); @NonNull Set<String> getAllCustomRequestTypes(); boolean isCurrencySupported(String currency); @NonNull Set<String> getAllSupportedCurrencies(); @NonNull Set<String> getAllSupportedPaymentMethods(); boolean isDataKeySupported(String dataKey); @NonNull Set<String> getAllSupportedDataKeys(); @Override String toJson(); static PaymentFlowServices fromJson(String json); }### Answer: @Test public void shouldCheckDataKeySupportedCorrectly() throws Exception { assertThat(paymentFlowServices.isDataKeySupported("dataOne")).isTrue(); assertThat(paymentFlowServices.isDataKeySupported("dataTwo")).isTrue(); assertThat(paymentFlowServices.isDataKeySupported("banana")).isFalse(); }
### Question: PaymentFlowServices implements Jsonable { @NonNull public Set<String> getAllCustomRequestTypes() { return supportedRequestTypes; } PaymentFlowServices(Collection<PaymentFlowServiceInfo> paymentFlowServiceInfoList); int getNumberOfFlowServices(); @NonNull List<PaymentFlowServiceInfo> getAll(); @NonNull Observable<PaymentFlowServiceInfo> stream(); @Nullable PaymentFlowServiceInfo getFlowServiceFromId(String id); boolean isCustomRequestTypeSupported(String requestType); @NonNull Set<String> getAllCustomRequestTypes(); boolean isCurrencySupported(String currency); @NonNull Set<String> getAllSupportedCurrencies(); @NonNull Set<String> getAllSupportedPaymentMethods(); boolean isDataKeySupported(String dataKey); @NonNull Set<String> getAllSupportedDataKeys(); @Override String toJson(); static PaymentFlowServices fromJson(String json); }### Answer: @Test public void shouldCollateRequestTypesCorrectly() throws Exception { Set<String> allSupportedRequestTypes = paymentFlowServices.getAllCustomRequestTypes(); assertThat(allSupportedRequestTypes).hasSize(3).containsOnly("reqOne", "reqTwo", "reqThree"); }
### Question: PaymentFlowServices implements Jsonable { public boolean isCurrencySupported(String currency) { return ComparisonUtil.stringCollectionContainsIgnoreCase(supportedCurrencies, currency); } PaymentFlowServices(Collection<PaymentFlowServiceInfo> paymentFlowServiceInfoList); int getNumberOfFlowServices(); @NonNull List<PaymentFlowServiceInfo> getAll(); @NonNull Observable<PaymentFlowServiceInfo> stream(); @Nullable PaymentFlowServiceInfo getFlowServiceFromId(String id); boolean isCustomRequestTypeSupported(String requestType); @NonNull Set<String> getAllCustomRequestTypes(); boolean isCurrencySupported(String currency); @NonNull Set<String> getAllSupportedCurrencies(); @NonNull Set<String> getAllSupportedPaymentMethods(); boolean isDataKeySupported(String dataKey); @NonNull Set<String> getAllSupportedDataKeys(); @Override String toJson(); static PaymentFlowServices fromJson(String json); }### Answer: @Test public void isCurrencySupportedShouldMatchCorrectly() throws Exception { assertThat(paymentFlowServices.isCurrencySupported("AUD")).isTrue(); assertThat(paymentFlowServices.isCurrencySupported("GBP")).isTrue(); assertThat(paymentFlowServices.isCurrencySupported("USD")).isTrue(); assertThat(paymentFlowServices.isCurrencySupported("SEK")).isFalse(); assertThat(paymentFlowServices.isCurrencySupported("EUR")).isFalse(); }
### Question: PaymentFlowServices implements Jsonable { @NonNull public Set<String> getAllSupportedCurrencies() { return supportedCurrencies; } PaymentFlowServices(Collection<PaymentFlowServiceInfo> paymentFlowServiceInfoList); int getNumberOfFlowServices(); @NonNull List<PaymentFlowServiceInfo> getAll(); @NonNull Observable<PaymentFlowServiceInfo> stream(); @Nullable PaymentFlowServiceInfo getFlowServiceFromId(String id); boolean isCustomRequestTypeSupported(String requestType); @NonNull Set<String> getAllCustomRequestTypes(); boolean isCurrencySupported(String currency); @NonNull Set<String> getAllSupportedCurrencies(); @NonNull Set<String> getAllSupportedPaymentMethods(); boolean isDataKeySupported(String dataKey); @NonNull Set<String> getAllSupportedDataKeys(); @Override String toJson(); static PaymentFlowServices fromJson(String json); }### Answer: @Test public void shouldCollateSupportedCurrenciesCorrectly() throws Exception { Set<String> allSupportedCurrencies = paymentFlowServices.getAllSupportedCurrencies(); assertThat(allSupportedCurrencies).hasSize(3).containsOnly("GBP", "AUD", "USD"); }
### Question: Amounts implements Jsonable { @NonNull public String getCurrency() { return currency; } Amounts(); Amounts(long baseAmount, String currency); Amounts(Amounts from); Amounts(long baseAmount, String currency, Map<String, Long> additionalAmounts); void addAdditionalAmount(String identifier, long amount); void addAdditionalAmountAsBaseFraction(String identifier, float fraction); @NonNull String getCurrency(); long getBaseAmountValue(); @NonNull Amount getBaseAmount(); boolean hasAdditionalAmount(String identifier); long getAdditionalAmountValue(String identifier); @NonNull Amount getAdditionalAmount(String identifier); @NonNull Map<String, Long> getAdditionalAmounts(); @JsonConverter.ExposeMethod(value = "totalAmount") long getTotalAmountValue(); long getTotalExcludingAmounts(String... amountIdentifiers); @NonNull Amount getTotalAmount(); double getCurrencyExchangeRate(); @NonNull String getOriginalCurrency(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @NonNull static Amounts addAmounts(Amounts a1, Amounts a2); @NonNull static Amounts subtractAmounts(Amounts a1, Amounts a2, boolean keepZeroAmountAdditionals); @Override String toJson(); }### Answer: @Test public void checkCurrencyIsCorrect() { Amounts amounts = new Amounts(1000L, "GBP"); assertThat(amounts.getCurrency()).isEqualTo("GBP"); }
### Question: Amounts implements Jsonable { public void addAdditionalAmountAsBaseFraction(String identifier, float fraction) { if (fraction < 0.0f || fraction > 1.0f) { throw new IllegalArgumentException("Fraction must be between 0.0 and 1.0"); } addAdditionalAmount(identifier, (long) (baseAmount * fraction)); } Amounts(); Amounts(long baseAmount, String currency); Amounts(Amounts from); Amounts(long baseAmount, String currency, Map<String, Long> additionalAmounts); void addAdditionalAmount(String identifier, long amount); void addAdditionalAmountAsBaseFraction(String identifier, float fraction); @NonNull String getCurrency(); long getBaseAmountValue(); @NonNull Amount getBaseAmount(); boolean hasAdditionalAmount(String identifier); long getAdditionalAmountValue(String identifier); @NonNull Amount getAdditionalAmount(String identifier); @NonNull Map<String, Long> getAdditionalAmounts(); @JsonConverter.ExposeMethod(value = "totalAmount") long getTotalAmountValue(); long getTotalExcludingAmounts(String... amountIdentifiers); @NonNull Amount getTotalAmount(); double getCurrencyExchangeRate(); @NonNull String getOriginalCurrency(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @NonNull static Amounts addAmounts(Amounts a1, Amounts a2); @NonNull static Amounts subtractAmounts(Amounts a1, Amounts a2, boolean keepZeroAmountAdditionals); @Override String toJson(); }### Answer: @Test(expected = IllegalArgumentException.class) public void checkCantUseNegativePercentage() throws Exception { Amounts amounts = new Amounts(1000L, "GBP"); amounts.addAdditionalAmountAsBaseFraction("charity", -0.5f); } @Test(expected = IllegalArgumentException.class) public void checkCantAddMoreThan100Percent() throws Exception { Amounts amounts = new Amounts(1000L, "GBP"); amounts.addAdditionalAmountAsBaseFraction("charity", 1.5f); }
### Question: FlowEvent implements Jsonable { public <T> T getEventData(Class<T> classType) { return this.data.getValue(type, classType); } FlowEvent(String type); FlowEvent(String type, AdditionalData data); FlowEvent(String type, AdditionalData data, String eventTrigger); @SuppressWarnings("unchecked") <T> FlowEvent(String type, T eventData); @NonNull String getType(); @NonNull AdditionalData getData(); T getEventData(Class<T> classType); boolean hasEventData(); void setEventTrigger(String eventTrigger); @Nullable String getEventTrigger(); @Nullable String getOriginatingRequestId(); void setOriginatingRequestId(String originatingRequestId); @Nullable String getTarget(); void setTarget(String target); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override String toJson(); static FlowEvent fromJson(String json); }### Answer: @Test public void canSetAndGetDomainEventData() { TestEventObjectData data = new TestEventObjectData(); FlowEvent fe = new FlowEvent("blah", data); assertThat(fe.getEventData(TestEventObjectData.class)).isNotNull(); assertThat(fe.getEventData(TestEventObjectData.class)).isEqualTo(data); } @Test public void shouldReturnNullIfWrongTypeUsed() { TestEventObjectData data = new TestEventObjectData(); FlowEvent fe = new FlowEvent("blah", data); assertThat(fe.getEventData(FlowEvent.class)).isNull(); }
### Question: Amounts implements Jsonable { @NonNull public Amount getBaseAmount() { return new Amount(baseAmount, currency); } Amounts(); Amounts(long baseAmount, String currency); Amounts(Amounts from); Amounts(long baseAmount, String currency, Map<String, Long> additionalAmounts); void addAdditionalAmount(String identifier, long amount); void addAdditionalAmountAsBaseFraction(String identifier, float fraction); @NonNull String getCurrency(); long getBaseAmountValue(); @NonNull Amount getBaseAmount(); boolean hasAdditionalAmount(String identifier); long getAdditionalAmountValue(String identifier); @NonNull Amount getAdditionalAmount(String identifier); @NonNull Map<String, Long> getAdditionalAmounts(); @JsonConverter.ExposeMethod(value = "totalAmount") long getTotalAmountValue(); long getTotalExcludingAmounts(String... amountIdentifiers); @NonNull Amount getTotalAmount(); double getCurrencyExchangeRate(); @NonNull String getOriginalCurrency(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @NonNull static Amounts addAmounts(Amounts a1, Amounts a2); @NonNull static Amounts subtractAmounts(Amounts a1, Amounts a2, boolean keepZeroAmountAdditionals); @Override String toJson(); }### Answer: @Test public void checkCanGetAmountForZeroAmounts() { Amounts amounts = new Amounts(0, "GBP"); Amount amount = amounts.getBaseAmount(); assertThat(amount.getValue()).isEqualTo(0L); }
### Question: Card implements Jsonable { @Nullable public String getMaskedPan() { return maskedPan; } Card(); Card(String maskedPan, String cardholderName, String expiryDate, Token token, AdditionalData additionalData); static Card getEmptyCard(); @Nullable String getMaskedPan(); @Nullable String getCardholderName(); @Nullable String getExpiryDate(); @Nullable String getFormattedExpiryDate(String pattern); @Nullable Token getCardToken(); @NonNull AdditionalData getAdditionalData(); boolean isEmpty(); @Override String toJson(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void shouldAllowPanWithLessThan10Digits() throws Exception { Card card = new Card("123456789XXXXXX", "Mr T", "0102", null, null); assertThat(card.getMaskedPan()).isEqualTo("123456789XXXXXX"); }
### Question: Card implements Jsonable { @Nullable public String getFormattedExpiryDate(String pattern) { if (expiryDate == null || pattern == null) { return null; } SimpleDateFormat inputFormat = new SimpleDateFormat("yyMM", Locale.getDefault()); SimpleDateFormat outputFormat = new SimpleDateFormat(pattern, Locale.getDefault()); try { return outputFormat.format(inputFormat.parse(expiryDate)); } catch (ParseException e) { return null; } } Card(); Card(String maskedPan, String cardholderName, String expiryDate, Token token, AdditionalData additionalData); static Card getEmptyCard(); @Nullable String getMaskedPan(); @Nullable String getCardholderName(); @Nullable String getExpiryDate(); @Nullable String getFormattedExpiryDate(String pattern); @Nullable Token getCardToken(); @NonNull AdditionalData getAdditionalData(); boolean isEmpty(); @Override String toJson(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void shouldFormatExpiryDateCorrectly() throws Exception { Card card = new Card("123456789XXXXXX", "Mr T", "2010", null, null); assertThat(card.getFormattedExpiryDate("MM/yyyy")).isEqualTo("10/2020"); }