method2testcases
stringlengths
118
3.08k
### Question: NamingUtils { public static String getPartitionAddress(String address, int partition) { Objects.requireNonNull(address); return String.format("%s-%d", address, partition); } static String getPartitionAddress(String address, int partition); static String getQueueName(String address, String group); static String getAnonymousGroupName(); }### Answer: @Test public void shouldGetPartitionAddress() { assertThat(NamingUtils.getPartitionAddress("testAddress", 0)).isEqualTo("testAddress-0"); } @Test(expected = NullPointerException.class) public void shouldNotAcceptNullAddressToGetPartitionAddress() { NamingUtils.getPartitionAddress(null, 0); }
### Question: ArtemisProducerDestination implements ProducerDestination { @Override public String getNameForPartition(int i) { return getPartitionAddress(name, i); } ArtemisProducerDestination(String name); @Override String getName(); @Override String getNameForPartition(int i); @Override String toString(); }### Answer: @Test public void shouldGetNameForPartition() { String name = "test-name"; ArtemisProducerDestination destination = new ArtemisProducerDestination(name); assertThat(destination.getNameForPartition(0)).isEqualTo(getPartitionAddress(name, 0)); }
### Question: ArtemisConsumerDestination implements ConsumerDestination { @Override public String getName() { return name; } ArtemisConsumerDestination(String name); @Override String getName(); @Override String toString(); }### Answer: @Test public void shouldGetName() { String name = "test-name"; ArtemisConsumerDestination destination = new ArtemisConsumerDestination(name); assertThat(destination.getName()).isEqualTo(name); }
### Question: ArtemisProvisioningProvider implements ProvisioningProvider< ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties) throws ProvisioningException { ArtemisConsumerDestination destination; if (properties.isPartitioned()) { logger.debug("Provisioning partitioned consumer destination with address '{}' and instance index '{}'", address, properties.getInstanceIndex()); destination = new ArtemisConsumerDestination(getPartitionAddress(address, properties.getInstanceIndex())); } else { logger.debug("Provisioning unpartitioned consumer destination with address '{}'", address); destination = new ArtemisConsumerDestination(address); } artemisBrokerManager.createAddress(destination.getName(), properties.getExtension()); return destination; } ArtemisProvisioningProvider(ArtemisBrokerManager artemisBrokerManager); @Override ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties); @Override ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties); }### Answer: @Test public void shouldProvisionUnpartitionedConsumer() { ConsumerDestination destination = provider.provisionConsumerDestination(address, null, mockConsumerProperties); assertThat(destination).isInstanceOf(ArtemisConsumerDestination.class); assertThat(destination.getName()).isEqualTo(address); verify(mockArtemisBrokerManager).createAddress(address, mockArtemisConsumerProperties); } @Test public void shouldProvisionPartitionedConsumer() { given(mockConsumerProperties.isPartitioned()).willReturn(true); given(mockConsumerProperties.getInstanceIndex()).willReturn(0); ConsumerDestination destination = provider.provisionConsumerDestination(address, null, mockConsumerProperties); String partitionedAddress = String.format("%s-0", address); assertThat(destination).isInstanceOf(ArtemisConsumerDestination.class); assertThat(destination.getName()).isEqualTo(partitionedAddress); verify(mockArtemisBrokerManager).createAddress(partitionedAddress, mockArtemisConsumerProperties); }
### Question: ListenerContainerFactory { public AbstractMessageListenerContainer getListenerContainer(String topic, String subscriptionName) { DefaultMessageListenerContainer listenerContainer = new DefaultMessageListenerContainer(); listenerContainer.setConnectionFactory(connectionFactory); listenerContainer.setPubSubDomain(true); listenerContainer.setDestinationName(topic); listenerContainer.setSubscriptionName(subscriptionName); listenerContainer.setSessionTransacted(true); listenerContainer.setSubscriptionDurable(true); listenerContainer.setSubscriptionShared(true); return listenerContainer; } ListenerContainerFactory(ConnectionFactory connectionFactory); AbstractMessageListenerContainer getListenerContainer(String topic, String subscriptionName); }### Answer: @Test public void shouldGetListenerContainer() { ListenerContainerFactory factory = new ListenerContainerFactory(mockConnectionFactory); AbstractMessageListenerContainer container = factory.getListenerContainer("testTopic", "testSubscription"); assertThat(container.getConnectionFactory()).isEqualTo(mockConnectionFactory); assertThat(container.getDestinationName()).isEqualTo("testTopic"); assertThat(container.isPubSubDomain()).isTrue(); assertThat(container.getSubscriptionName()).isEqualTo("testSubscription"); assertThat(container.isSessionTransacted()).isTrue(); assertThat(container.isSubscriptionDurable()).isTrue(); assertThat(container.isSubscriptionShared()).isTrue(); }
### Question: NamingUtils { public static String getQueueName(String address, String group) { Objects.requireNonNull(address); Objects.requireNonNull(group); return String.format("%s-%s", address, group); } static String getPartitionAddress(String address, int partition); static String getQueueName(String address, String group); static String getAnonymousGroupName(); }### Answer: @Test public void shouldGetQueueName() { assertThat(NamingUtils.getQueueName("testAddress", "testGroup")).isEqualTo("testAddress-testGroup"); } @Test(expected = NullPointerException.class) public void shouldNotAcceptNullAddressToGetQueueName() { NamingUtils.getQueueName(null, "testGroup"); } @Test(expected = NullPointerException.class) public void shouldNotAcceptNullGroupToGetQueueName() { NamingUtils.getQueueName("testAddress", null); }
### Question: NamingUtils { public static String getAnonymousGroupName() { UUID uuid = UUID.randomUUID(); ByteBuffer buffer = ByteBuffer.wrap(new byte[16]); buffer.putLong(uuid.getMostSignificantBits()) .putLong(uuid.getLeastSignificantBits()); return "anonymous-" + Base64Utils.encodeToUrlSafeString(buffer.array()) .replaceAll("=", ""); } static String getPartitionAddress(String address, int partition); static String getQueueName(String address, String group); static String getAnonymousGroupName(); }### Answer: @Test public void shouldGetAnonymousQueueName() { assertThat(NamingUtils.getAnonymousGroupName()).hasSize(32) .startsWith("anonymous-"); }
### Question: ArtemisMessageChannelBinder extends AbstractMessageChannelBinder<ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>, ArtemisProvisioningProvider> implements ExtendedPropertiesBinder<MessageChannel, ArtemisConsumerProperties, ArtemisProducerProperties> { @Override protected MessageHandler createProducerMessageHandler(ProducerDestination destination, ExtendedProducerProperties<ArtemisProducerProperties> properties, MessageChannel errorChannel) { logger.debug("Creating producer message handler for '" + destination + "'"); JmsSendingMessageHandler handler = Jms.outboundAdapter(connectionFactory) .destination(message -> getMessageDestination(message, destination)) .configureJmsTemplate(templateSpec -> templateSpec.pubSubDomain(true)) .get(); handler.setApplicationContext(getApplicationContext()); handler.setBeanFactory(getBeanFactory()); return handler; } ArtemisMessageChannelBinder(ArtemisProvisioningProvider provisioningProvider, ConnectionFactory connectionFactory, ArtemisExtendedBindingProperties bindingProperties); @Override ArtemisConsumerProperties getExtendedConsumerProperties(String channelName); @Override ArtemisProducerProperties getExtendedProducerProperties(String channelName); @Override String getDefaultsPrefix(); @Override Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass(); }### Answer: @Test public void shouldCreateProducerMessageHandler() { MessageHandler handler = binder.createProducerMessageHandler(null, null, null); assertThat(handler).isInstanceOf(JmsSendingMessageHandler.class); }
### Question: ArtemisProducerDestination implements ProducerDestination { @Override public String getName() { return name; } ArtemisProducerDestination(String name); @Override String getName(); @Override String getNameForPartition(int i); @Override String toString(); }### Answer: @Test public void shouldGetName() { String name = "test-name"; ArtemisProducerDestination destination = new ArtemisProducerDestination(name); assertThat(destination.getName()).isEqualTo(name); }
### Question: GrobidResponseStaxHandler implements StaxParserContentHandler { public GrobidResponse getResponse() { return response; } @Override void onStartDocument(XMLStreamReader2 reader); @Override void onEndDocument(XMLStreamReader2 reader); @Override void onStartElement(XMLStreamReader2 reader); @Override void onEndElement(XMLStreamReader2 reader); @Override void onCharacter(XMLStreamReader2 reader); GrobidResponse getResponse(); }### Answer: @Test public void testParsingPublication_shouldWork() throws Exception { InputStream inputStream = this.getClass().getResourceAsStream("/sample.grobid.xml"); XMLStreamReader2 reader = (XMLStreamReader2) inputFactory.createXMLStreamReader(inputStream); StaxUtils.traverse(reader, target); GrobidResponseStaxHandler.GrobidResponse structures = target.getResponse(); assertThat(structures.getAtitle(), is("This si the end of the world")); assertThat(structures.getFirstAuthor(), is("Foppiano")); } @Test public void testParsingPublication2_shouldWork() throws Exception { InputStream inputStream = this.getClass().getResourceAsStream("/sample.grobid-2.xml"); XMLStreamReader2 reader = (XMLStreamReader2) inputFactory.createXMLStreamReader(inputStream); StaxUtils.traverse(reader, target); GrobidResponseStaxHandler.GrobidResponse structures = target.getResponse(); assertThat(structures.getFirstAuthorMonograph(), is("Gupta")); } @Test public void testParsingPublication3_shouldWork() throws Exception { InputStream inputStream = this.getClass().getResourceAsStream("/sample.grobid-3.xml"); XMLStreamReader2 reader = (XMLStreamReader2) inputFactory.createXMLStreamReader(inputStream); StaxUtils.traverse(reader, target); GrobidResponseStaxHandler.GrobidResponse structures = target.getResponse(); assertThat(structures.getAtitle(), is("This si the end of the world")); assertThat(structures.getFirstAuthor(), is("Foppiano")); }
### Question: IstexIdsReader { public void load(String input, Consumer<IstexData> closure) { try (Stream<String> stream = Files.lines(Paths.get(input))) { stream.forEach(line -> closure.accept(fromJson(line))); } catch (IOException e) { LOGGER.error("Some serious error when processing the input Istex ID file.", e); } } void load(String input, Consumer<IstexData> closure); void load(InputStream input, Consumer<IstexData> closure); IstexData fromJson(String inputLine); }### Answer: @Test public void test3() throws Exception { target.load( new GZIPInputStream(this.getClass().getResourceAsStream("/sample-istex-ids.json.gz")), unpaidWallMetadata -> System.out.println(unpaidWallMetadata.getDoi() )); }
### Question: PmidReader { public PmidData fromCSV(String inputLine) { final String[] split = StringUtils.splitPreserveAllTokens(inputLine, ","); if (split.length > 0 && split.length <= 3) { return new PmidData(split[0], split[1], replaceAll(split[2], "\"", "")); } return null; } void load(String input, Consumer<PmidData> closure); void load(InputStream input, Consumer<PmidData> closure); PmidData fromCSV(String inputLine); }### Answer: @Test public void test() throws Exception { PmidData metadata = target.fromCSV("9999996,,\"https: assertThat(metadata, is(not(nullValue()))); assertThat(metadata.getDoi(), is ("10.1103/physrevb.44.3678")); assertThat(metadata.getPmid(), is ("9999996")); assertThat(metadata.getPmcid(), is ("")); }
### Question: SupplyLocationBulkUploadController { public List<SupplyLocation> uploadFitleredLocations(List<SupplyLocation> locations) { return this.service.saveSupplyLocationsZipContains504(locations); } @Autowired SupplyLocationBulkUploadController(SupplyLocationRepository repository); @Autowired SupplyLocationBulkUploadController(SupplyLocationRepository repository, SupplyLocationService service); @RequestMapping(value = "/bulk/supplyLocations", method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) void upload(@RequestBody List<SupplyLocation> locations); @RequestMapping(value = "/purge", method = RequestMethod.POST) void purge(); List<SupplyLocation> uploadFitleredLocations(List<SupplyLocation> locations); }### Answer: @Test public void whenListFiltered_returnSavedList() { List<SupplyLocation> locations = new ArrayList<>(); locations.add(generateSupplyLocations(4, 4, "504")); when(service.saveSupplyLocationsZipContains504(inputLocations)).thenReturn(locations); assertThat(controller.uploadFitleredLocations(inputLocations)).size().isEqualTo(1); assertThat(controller.uploadFitleredLocations(inputLocations).get(0).getZip()).isEqualTo("504"); }
### Question: HashtableGenerator extends MapGenerator<Hashtable> { @Override protected boolean okToAdd(Object key, Object value) { return key != null && value != null; } HashtableGenerator(); @Override void addComponentGenerators(List<Generator<?>> newComponents); }### Answer: @Test public void disallowsNullKeyAndNullValue() { assertFalse(generator.okToAdd(null, null)); } @Test public void disallowsNullKey() { assertFalse(generator.okToAdd(null, new Object())); } @Test public void disallowsNullValue() { assertFalse(generator.okToAdd(new Object(), null)); } @Test public void allowsKeyAndValueWhenNeitherIsNull() { assertTrue(generator.okToAdd(new Object(), new Object())); }
### Question: Items { @SuppressWarnings("unchecked") public static <T> T choose(Collection<T> items, SourceOfRandomness random) { int size = items.size(); if (size == 0) { throw new IllegalArgumentException( "Collection is empty, can't pick an element from it"); } if (items instanceof RandomAccess && items instanceof List<?>) { List<T> list = (List<T>) items; return size == 1 ? list.get(0) : list.get(random.nextInt(size)); } if (size == 1) { return items.iterator().next(); } Object[] array = items.toArray(new Object[0]); return (T) array[random.nextInt(array.length)]; } private Items(); @SuppressWarnings("unchecked") static T choose(Collection<T> items, SourceOfRandomness random); static T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random); }### Answer: @Test public void choosingFromEmptyCollection() { thrown.expect(IllegalArgumentException.class); Items.choose(emptyList(), random); } @Test public void choosingFromSet() { Set<String> names = new LinkedHashSet<>(asList("alpha", "bravo", "charlie", "delta")); when(random.nextInt(names.size())).thenReturn(2); assertEquals("charlie", Items.choose(names, random)); }
### Question: Lists { public static <T> List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink) { if (target.isEmpty()) return new ArrayList<>(); T head = target.get(0); List<T> tail = target.subList(1, target.size()); List<List<T>> shrinks = new ArrayList<>(); shrinks.addAll( shrink.shrink(random, head) .stream() .map(i -> { List<T> items = new ArrayList<>(); items.add(i); items.addAll(tail); return items; }) .collect(toList())); shrinks.addAll( shrinksOfOneItem(random, tail, shrink) .stream() .map(s -> { List<T> items = new ArrayList<>(); items.add(head); items.addAll(s); return items; }) .collect(toList())); return shrinks; } private Lists(); static List<List<T>> removeFrom(List<T> target, int howMany); static List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink); static boolean isDistinct(List<T> target); }### Answer: @Test public void shrinksOfEmptyList() { assertEquals(emptyList(), Lists.shrinksOfOneItem(random, emptyList(), null)); } @Test public void shrinksOfNonEmptyList() { List<List<Integer>> shrinks = Lists.shrinksOfOneItem( random, newArrayList(1, 2, 3), (r, i) -> { assumeThat(r, sameInstance(random)); return newArrayList(4, 5); }); assertEquals( newArrayList( newArrayList(4, 2, 3), newArrayList(5, 2, 3), newArrayList(1, 4, 3), newArrayList(1, 5, 3), newArrayList(1, 2, 4), newArrayList(1, 2, 5) ), shrinks); }
### Question: Lambdas { public static <T, U> T makeLambda( Class<T> lambdaType, Generator<U> returnValueGenerator, GenerationStatus status) { if (singleAbstractMethodOf(lambdaType) == null) { throw new IllegalArgumentException( lambdaType + " is not a functional interface type"); } return lambdaType.cast( newProxyInstance( lambdaType.getClassLoader(), new Class<?>[] { lambdaType }, new LambdaInvocationHandler<>( lambdaType, returnValueGenerator, status.attempts()))); } private Lambdas(); static T makeLambda( Class<T> lambdaType, Generator<U> returnValueGenerator, GenerationStatus status); }### Answer: @Test public void rejectsNonFunctionalInterface() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(Cloneable.class + " is not a functional interface"); makeLambda(Cloneable.class, new AnInt(), status); } @Test public void invokingDefaultMethodOnFunctionalInterface() { System.out.println(System.getProperty("java.version")); @SuppressWarnings("unchecked") Predicate<Integer> another = makeLambda(Predicate.class, returnValueGenerator, status); boolean firstResult = predicate.test(4); boolean secondResult = another.test(4); assertEquals(firstResult || secondResult, predicate.or(another).test(4)); } @Test public void equalsBasedOnIdentity() { Predicate<?> duplicate = makeLambda(Predicate.class, returnValueGenerator, status); assertEquals(predicate, predicate); assertEquals(duplicate, duplicate); assertNotEquals(predicate, duplicate); assertNotEquals(duplicate, predicate); }
### Question: Pair { @Override public String toString() { return String.format("[%s = %s]", first, second); } Pair(F first, S second); @Override int hashCode(); @Override boolean equals(Object o); @Override String toString(); final F first; final S second; }### Answer: @Test public void stringifying() { assertEquals("[1 = 2]", new Pair<>(1, 2).toString()); }
### Question: Sequences { public static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start) { return () -> new BigIntegerHalvingIterator(start, max); } private Sequences(); static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start); static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start); static Iterable<Integer> halving(int start); }### Answer: @Test public void halvingBigIntegers() { assertEquals( newArrayList( BigInteger.valueOf(5), BigInteger.valueOf(7), BigInteger.valueOf(8), BigInteger.valueOf(9)), newArrayList(Sequences.halvingIntegral(BigInteger.TEN, BigInteger.ZERO))); } @Test public void halvingNegativeBigIntegers() { assertEquals( newArrayList( BigInteger.valueOf(-5), BigInteger.valueOf(-7), BigInteger.valueOf(-8), BigInteger.valueOf(-9)), newArrayList(Sequences.halvingIntegral(BigInteger.TEN.negate(), BigInteger.ZERO))); } @Test public void callingNextOutOfSequenceOnHalvingBigIntegers() { Iterator<BigInteger> i = Sequences.halvingIntegral(BigInteger.ZERO, BigInteger.ZERO).iterator(); i.next(); thrown.expect(NoSuchElementException.class); i.next(); }
### Question: Sequences { public static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start) { return () -> new BigDecimalHalvingIterator(start, max); } private Sequences(); static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start); static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start); static Iterable<Integer> halving(int start); }### Answer: @Test public void halvingBigDecimals() { assertEquals( newArrayList( BigDecimal.valueOf(5), BigDecimal.valueOf(8), BigDecimal.valueOf(9), BigDecimal.TEN), newArrayList(Sequences.halvingDecimal(BigDecimal.TEN, BigDecimal.ZERO))); } @Test public void halvingNegativeBigDecimals() { assertEquals( newArrayList( BigDecimal.valueOf(-5), BigDecimal.valueOf(-8), BigDecimal.valueOf(-9), BigDecimal.TEN.negate()), newArrayList(Sequences.halvingDecimal(BigDecimal.TEN.negate(), BigDecimal.ZERO))); } @Test public void callingNextOutOfSequenceOnHalvingBigDecimals() { Iterator<BigDecimal> i = Sequences.halvingDecimal(BigDecimal.ZERO, BigDecimal.ZERO).iterator(); i.next(); thrown.expect(NoSuchElementException.class); i.next(); }
### Question: Sequences { public static Iterable<Integer> halving(int start) { return () -> new IntegerHalvingIterator(start); } private Sequences(); static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start); static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start); static Iterable<Integer> halving(int start); }### Answer: @Test public void halvingInts() { assertEquals( newArrayList(27, 13, 6, 3, 1), newArrayList(Sequences.halving(27))); } @Test public void callingNextOutOfSequenceOnHalvingInts() { Iterator<Integer> i = Sequences.halving(0).iterator(); i.next(); thrown.expect(NoSuchElementException.class); i.next(); }
### Question: EnumGenerator extends Generator<Enum> { @Override public boolean canShrink(Object larger) { return enumType.isInstance(larger); } EnumGenerator(Class<?> enumType); @Override Enum<?> generate( SourceOfRandomness random, GenerationStatus status); @Override boolean canShrink(Object larger); }### Answer: @Test public void capabilityOfShrinkingNonEnum() { assertFalse(generator.canShrink(new Object())); } @Test public void capabilityOfShrinkingEnumOfDesiredType() { assertTrue(generator.canShrink(ElementType.METHOD)); } @Test public void capabilityOfShrinkingEnumOfOtherType() { assertFalse(generator.canShrink(RetentionPolicy.SOURCE)); }
### Question: CompositeGenerator extends Generator<Object> { @Override public boolean canShrink(Object larger) { return composed.stream() .map(w -> w.item) .anyMatch(g -> g.canShrink(larger)); } CompositeGenerator(List<Weighted<Generator<?>>> composed); @Override Object generate(SourceOfRandomness random, GenerationStatus status); @Override boolean canShrink(Object larger); @Override List<Object> doShrink(SourceOfRandomness random, Object larger); Generator<?> composed(int index); int numberOfComposedGenerators(); @Override void provide(Generators provided); @Override BigDecimal magnitude(Object value); @Override void configure(AnnotatedType annotatedType); @Override void configure(AnnotatedElement element); @Override void addComponentGenerators(List<Generator<?>> newComponents); }### Answer: @Test public void capabilityOfShrinkingDependsOnComponents() { when(first.canShrink(9)).thenReturn(true); when(second.canShrink(9)).thenReturn(false); when(third.canShrink(9)).thenReturn(true); assertTrue(composite.canShrink(9)); } @Test public void capabilityOfShrinkingFalseIfNoComponentsCanShrinkAValue() { when(first.canShrink(8)).thenReturn(false); when(second.canShrink(8)).thenReturn(false); when(third.canShrink(8)).thenReturn(false); assertFalse(composite.canShrink(8)); }
### Question: ArrayGenerator extends Generator<Object> { @Override public boolean canShrink(Object larger) { return larger.getClass().getComponentType() == componentType; } ArrayGenerator(Class<?> componentType, Generator<?> component); void configure(Size size); void configure(Distinct distinct); @Override Object generate( SourceOfRandomness random, GenerationStatus status); @Override boolean canShrink(Object larger); @Override List<Object> doShrink(SourceOfRandomness random, Object larger); @Override void provide(Generators provided); @Override BigDecimal magnitude(Object value); @Override void configure(AnnotatedType annotatedType); }### Answer: @Test public void capabilityOfShrinkingNonArray() { assertFalse(intArrayGenerator.canShrink(3)); } @Test public void capabilityOfShrinkingArrayOfIdenticalComponentType() { assertTrue(intArrayGenerator.canShrink(new int[0])); } @Test public void capabilityOfShrinkingArrayOfEquivalentWrapperComponentType() { assertFalse(intArrayGenerator.canShrink(new Integer[0])); }
### Question: Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } private Comparables(); static Predicate<T> inRange( T min, T max); static T leastMagnitude( T min, T max, T zero); }### Answer: @Test public void leastMagnitudeUnbounded() { assertEquals(Integer.valueOf(0), Comparables.leastMagnitude(null, null, 0)); } @Test public void leastMagnitudeNegativeMinOnly() { assertEquals(Integer.valueOf(0), Comparables.leastMagnitude(-3, null, 0)); } @Test public void leastMagnitudePositiveMinOnly() { assertEquals(Integer.valueOf(4), Comparables.leastMagnitude(4, null, 0)); } @Test public void leastMagnitudeNegativeMaxOnly() { assertEquals(Integer.valueOf(-2), Comparables.leastMagnitude(null, -2, 0)); } @Test public void leastMagnitudePositiveMaxOnly() { assertEquals(Integer.valueOf(0), Comparables.leastMagnitude(null, 5, 0)); } @Test public void leastMagnitudeBothLessThanZero() { assertEquals(Integer.valueOf(-1), Comparables.leastMagnitude(-4, -1, 0)); } @Test public void leastMagnitudeBothGreaterThanZero() { assertEquals(Integer.valueOf(5), Comparables.leastMagnitude(5, 7, 0)); } @Test public void leastMagnitudeStraddlingZero() { assertEquals(Integer.valueOf(0), Comparables.leastMagnitude(-2, 4, 0)); }
### Question: GeometricDistribution { int sample(double p, SourceOfRandomness random) { ensureProbability(p); if (p == 1) return 0; double uniform = random.nextDouble(); return (int) ceil(log(1 - uniform) / log(1 - p)); } int sampleWithMean(double mean, SourceOfRandomness random); }### Answer: @Test public void negativeProbability() { thrown.expect(IllegalArgumentException.class); distro.sample(-ulp(0), random); } @Test public void zeroProbability() { thrown.expect(IllegalArgumentException.class); distro.sample(0, random); } @Test public void greaterThanOneProbability() { thrown.expect(IllegalArgumentException.class); distro.sample(1 + ulp(1), random); } @Test public void sampleWithCertainProbability() { assertEquals(0, distro.sample(1, random)); } @Test public void sampleWithNonCertainProbability() { when(random.nextDouble()).thenReturn(0.88); assertEquals(10, distro.sample(0.2, random)); }
### Question: GeometricDistribution { double probabilityOfMean(double mean) { if (mean <= 0) throw new IllegalArgumentException("Need a positive mean, got " + mean); return 1 / mean; } int sampleWithMean(double mean, SourceOfRandomness random); }### Answer: @Test public void negativeMeanProbability() { thrown.expect(IllegalArgumentException.class); distro.probabilityOfMean(-ulp(0)); } @Test public void zeroMeanProbability() { thrown.expect(IllegalArgumentException.class); distro.probabilityOfMean(0); } @Test public void nonZeroMeanProbability() { assertEquals(1 / 6D, distro.probabilityOfMean(6), 0); }
### Question: GeometricDistribution { public int sampleWithMean(double mean, SourceOfRandomness random) { return sample(probabilityOfMean(mean), random); } int sampleWithMean(double mean, SourceOfRandomness random); }### Answer: @Test public void sampleWithMean() { when(random.nextDouble()).thenReturn(0.76); assertEquals(8, distro.sampleWithMean(6, random)); }
### Question: CodePoints { public static CodePoints forCharset(Charset c) { if (ENCODABLES.containsKey(c)) return ENCODABLES.get(c); CodePoints points = load(c); ENCODABLES.put(c, points); return points; } CodePoints(); int at(int index); int size(); boolean contains(int codePoint); static CodePoints forCharset(Charset c); }### Answer: @Test public void versusCharsetThatDoesNotSupportEncoding() { Charset noEncoding; try { noEncoding = Charset.forName("ISO-2022-CN"); } catch (UnsupportedCharsetException testNotValid) { return; } thrown.expect(IllegalArgumentException.class); CodePoints.forCharset(noEncoding); }
### Question: Reflection { public static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes) { try { return target.getMethod(methodName, argTypes); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }### Answer: @Test public void findingNonExistentMethodQuietlyWrapsNoSuchMethodException() { thrown.expect(ReflectionException.class); thrown.expectMessage(NoSuchMethodException.class.getName()); findMethod(getClass(), "foo"); }
### Question: CodePoints { public int at(int index) { if (index < 0) throw new IndexOutOfBoundsException("illegal negative index: " + index); int min = 0; int max = ranges.size() - 1; while (min <= max) { int midpoint = min + ((max - min) / 2); CodePointRange current = ranges.get(midpoint); if (index >= current.previousCount && index < current.previousCount + current.size()) return current.low + index - current.previousCount; else if (index < current.previousCount) max = midpoint - 1; else min = midpoint + 1; } throw new IndexOutOfBoundsException(String.valueOf(index)); } CodePoints(); int at(int index); int size(); boolean contains(int codePoint); static CodePoints forCharset(Charset c); }### Answer: @Test public void lowIndex() { thrown.expect(IndexOutOfBoundsException.class); new CodePoints().at(-1); } @Test public void highIndex() { thrown.expect(IndexOutOfBoundsException.class); new CodePoints().at(0); }
### Question: Reflection { public static Object invoke(Method method, Object target, Object... args) { try { return method.invoke(target, args); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }### Answer: @Test public void invokingMethodQuietlyWrapsIllegalAccessException() throws Exception { Method method = ZeroArgIllegalAccessProblematic.class.getDeclaredMethod("foo"); thrown.expect(ReflectionException.class); thrown.expectMessage(IllegalAccessException.class.getName()); invoke(method, new ZeroArgIllegalAccessProblematic(0)); }
### Question: Reflection { public static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute) { try { return annotationType.getMethod(attribute).getDefaultValue(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }### Answer: @Test public void findingDefaultValueOfAnnotationAttribute() throws Exception { assertEquals("baz", defaultValueOf(Foo.class, "bar")); } @Test public void missingAnnotationAttribute() throws Exception { thrown.expect(ReflectionException.class); thrown.expectMessage(NoSuchMethodException.class.getName()); defaultValueOf(Foo.class, "noneSuch"); }
### Question: CodePoints { public int size() { if (ranges.isEmpty()) return 0; CodePointRange last = ranges.get(ranges.size() - 1); return last.previousCount + last.size(); } CodePoints(); int at(int index); int size(); boolean contains(int codePoint); static CodePoints forCharset(Charset c); }### Answer: @Test public void sizeOfEmpty() { assertEquals(0, new CodePoints().size()); }
### Question: VoidGenerator extends Generator<Void> { @Override public Void generate(SourceOfRandomness random, GenerationStatus status) { return null; } @SuppressWarnings("unchecked") VoidGenerator(); @Override Void generate(SourceOfRandomness random, GenerationStatus status); @Override boolean canRegisterAsType(Class<?> type); }### Answer: @Test public void canOnlyGenerateNull() { VoidGenerator generator = new VoidGenerator(); Void value = generator.generate(null, null); assertNull(value); }
### Question: Reflection { public static Field findField(Class<?> type, String fieldName) { try { return type.getDeclaredField(fieldName); } catch (NoSuchFieldException ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }### Answer: @Test public void findingField() { Field i = findField(Parent.class, "i"); assertEquals(int.class, i.getType()); } @Test public void findingNonExistentField() { thrown.expect(ReflectionException.class); thrown.expectMessage(NoSuchFieldException.class.getName()); findField(Parent.class, "missing"); }
### Question: Ranges { static long findNextPowerOfTwoLong(long positiveLong) { return isPowerOfTwoLong(positiveLong) ? positiveLong : ((long) 1) << (64 - Long.numberOfLeadingZeros(positiveLong)); } private Ranges(); static int checkRange( Type type, T min, T max); static BigInteger choose( SourceOfRandomness random, BigInteger min, BigInteger max); static long choose(SourceOfRandomness random, long min, long max); }### Answer: @Test public void checkFindNextPowerOfTwoLong() { assertEquals(1, findNextPowerOfTwoLong(1)); assertEquals(2, findNextPowerOfTwoLong(2)); assertEquals(4, findNextPowerOfTwoLong(3)); assertEquals(4, findNextPowerOfTwoLong(4)); assertEquals(8, findNextPowerOfTwoLong(5)); assertEquals((long) 1 << 61, findNextPowerOfTwoLong((long) 1 << 61)); assertEquals((long) 1 << 62, findNextPowerOfTwoLong(1 + (long) 1 << 61)); }
### Question: Ranges { public static BigInteger choose( SourceOfRandomness random, BigInteger min, BigInteger max) { BigInteger range = max.subtract(min).add(BigInteger.ONE); BigInteger generated; do { generated = random.nextBigInteger(range.bitLength()); } while (generated.compareTo(range) >= 0); return generated.add(min); } private Ranges(); static int checkRange( Type type, T min, T max); static BigInteger choose( SourceOfRandomness random, BigInteger min, BigInteger max); static long choose(SourceOfRandomness random, long min, long max); }### Answer: @Test public void weakSanityCheckForDistributionOfChooseLongs() { boolean[] hits = new boolean[5]; SourceOfRandomness random = new SourceOfRandomness(new Random(0)); for (int i = 0; i < 100; i++) { hits[(int) Ranges.choose(random, 0, (long) hits.length - 1)] = true; } for (boolean hit : hits) { assertTrue(hit); } }
### Question: FieldPropertyScanner implements PropertyScanner { @Override public List<Property> getProperties(Type type) { Class<?> clazz = extractClass(type); return getAllFields(clazz).stream() .filter(FieldPropertyScanner::isRelevantWhenSerialized) .map(FieldPropertyScanner::toProperty) .collect(toList()); } @Override List<Property> getProperties(Type type); }### Answer: @Test public void getFieldTypes_primitive() { List<Property> props = scanner.getProperties(int.class); assertTrue(props.isEmpty()); } @Test public void getFieldTypes_excludesTransient() throws NoSuchFieldException { Set<Property> props = new HashSet<>(); props.add(createFieldProperty("stringField", String.class, CustomObject.class)); props.add(createFieldProperty("intField", int.class, CustomObject.class)); props.add(createFieldProperty("objField", Object.class, CustomObject.class)); props.add(new Property("genericField", List.class, new TypeToken<List<Integer>>() {}.getType(), CustomObject.class.getDeclaredField("genericField"))); assertEquals(props, new HashSet<>(scanner.getProperties(CustomObject.class))); } @Test public void getFieldTypes_inheritedFields() throws NoSuchFieldException { Set<Property> props = new HashSet<>(); props.add(createFieldProperty("parentField", Float.class, Parent.class)); props.add(createFieldProperty("childField", Double.class, Child.class)); assertEquals(props, new HashSet<>(scanner.getProperties(Child.class))); } @Test public void getFieldTypes_enum() throws NoSuchFieldException { Set<Property> props = new HashSet<>(); props.add(createFieldProperty("name", String.class, Enum.class)); props.add(createFieldProperty("ordinal", int.class, Enum.class)); props.add(createFieldProperty("intField", int.class, MyEnum.class)); props.add(createFieldProperty("doubleField", Double.class, MyEnum.class)); assertEquals(props, new HashSet<>(scanner.getProperties(MyEnum.class))); }
### Question: RecursivePropertyTypeScanner implements TypeScanner { @Override public Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes) { Set<Class<?>> allTypes = new HashSet<>(); rootTypes.forEach(type -> exploreType(type, allTypes)); return allTypes; } RecursivePropertyTypeScanner(PropertyScanner scanner); Predicate<? super Class<?>> getTypeFilter(); void setTypeFilter(Predicate<? super Class<?>> typeFilter); Predicate<? super Class<?>> getTypeInspectionFilter(); void setTypeInspectionFilter(Predicate<? super Class<?>> typeInspectionFilter); Function<Class<?>, Set<Class<?>>> getTypeMapper(); void setTypeMapper(Function<Class<?>, Set<Class<?>>> mapper); @Override Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes); }### Answer: @Test public void findTypes_simpleString() { Set<Type> rootTypes = Collections.singleton(String.class); assertSetEquals(explorer.findTypesToDocument(rootTypes), String.class); } @Test public void findTypes_simpleCharacter() { Set<Type> rootTypes = Collections.singleton(Character.class); assertSetEquals(explorer.findTypesToDocument(rootTypes), Character.class); } @Test public void findTypes_customType() { Set<Type> rootTypes = Collections.singleton(Custom.class); assertSetEquals(explorer.findTypesToDocument(rootTypes), Custom.class, Long.class); } @Test public void findTypes_inheritedFields() { Set<Type> rootTypes = Collections.singleton(Child.class); assertSetEquals(explorer.findTypesToDocument(rootTypes), Child.class, Double.class, Long.class); } @Test public void findTypes_complexHierarchy() { Set<Type> rootTypes = Collections.singleton(TestRoot.class); assertSetEquals(explorer.findTypesToDocument(rootTypes), TestRoot.class, WithCustomObject.class, WithPrimitives.class, Custom.class, Long.class, String.class, int.class); }
### Question: ConcreteSubtypesMapper implements Function<Class<?>, Set<Class<?>>> { @Override public Set<Class<?>> apply(Class<?> type) { if (isAbstract(type)) { return getImplementationsOf(type); } return Collections.singleton(type); } ConcreteSubtypesMapper(Reflections reflections); @Override Set<Class<?>> apply(Class<?> type); }### Answer: @Test public void apply_concreteClass() { assertEquals(mapper.apply(SimpleAImpl.class), SimpleAImpl.class); assertEquals(mapper.apply(ConcreteAImpl.class), ConcreteAImpl.class); assertEquals(mapper.apply(BImpl.class), BImpl.class); } @Test public void apply_abstractClass() { assertEquals(mapper.apply(AbstractA.class), ConcreteAImpl.class); } @Test public void apply_interface() { assertEquals(mapper.apply(B.class), BImpl.class); assertEquals(mapper.apply(A.class), SimpleAImpl.class, ConcreteAImpl.class, BImpl.class); }
### Question: Defaults { public static Object defaultValueFor(@Nullable Class<?> type) { if (type == null) { return null; } return primitiveDefaults.get(type); } static Object defaultValueFor(@Nullable Class<?> type); }### Answer: @Test public void defaultValueFor_primitives() { assertEquals(0, Defaults.defaultValueFor(byte.class)); assertEquals(0, Defaults.defaultValueFor(short.class)); assertEquals(0, Defaults.defaultValueFor(int.class)); assertEquals(0L, Defaults.defaultValueFor(long.class)); assertEquals(0f, Defaults.defaultValueFor(float.class)); assertEquals(0.0, Defaults.defaultValueFor(double.class)); assertEquals(false, Defaults.defaultValueFor(boolean.class)); assertEquals('\0', Defaults.defaultValueFor(char.class)); } @Test public void defaultValueFor_objects() { assertNull(Defaults.defaultValueFor(Integer.class)); assertNull(Defaults.defaultValueFor(Double.class)); assertNull(Defaults.defaultValueFor(Boolean.class)); assertNull(Defaults.defaultValueFor(String.class)); }
### Question: JavadocTypeDocReader implements TypeDocReader { @NotNull @Override public Optional<TypeDoc> buildTypeDocBase(@NotNull Class<?> clazz, @NotNull TypeReferenceProvider typeReferenceProvider, @NotNull TemplateProvider templateProvider) { TypeDoc doc = new TypeDoc(clazz); doc.setName(clazz.getSimpleName()); doc.setDescription(JavadocHelper.getJavadocDescription(clazz).orElse(null)); return Optional.of(doc); } @NotNull @Override Optional<TypeDoc> buildTypeDocBase(@NotNull Class<?> clazz, @NotNull TypeReferenceProvider typeReferenceProvider, @NotNull TemplateProvider templateProvider); @NotNull @Override Optional<PropertyDoc> buildPropertyDoc(Property property, TypeDoc parentDoc, TypeReferenceProvider typeReferenceProvider); }### Answer: @Test public void buildTypeDocBase() { Optional<TypeDoc> doc = reader.buildTypeDocBase(Person.class, typeReferenceProvider, c -> null); assertTrue(doc.isPresent()); TypeDoc typeDoc = doc.get(); assertEquals("Person", typeDoc.getName()); assertEquals("Represents a person.", typeDoc.getDescription()); }
### Question: JacksonPropertyScanner implements PropertyScanner { @Override public List<Property> getProperties(Type type) { return getJacksonProperties(type).stream() .filter(JacksonPropertyScanner::isReadable) .map(this::convertProp) .collect(toList()); } JacksonPropertyScanner(ObjectMapper mapper); @Override List<Property> getProperties(Type type); }### Answer: @Test public void getProperties_primitive() { assertTrue(scanner.getProperties(int.class).isEmpty()); }
### Question: RestUserDetailsService implements UserDetailsManager { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return restTemplate.getForObject("/{0}", User.class, username); } RestUserDetailsService(RestTemplateBuilder builder, @Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); }### Answer: @Test public void testLoadUserByUsername() { server.expect(requestTo("/" + USERNAME)).andExpect(method(GET)) .andRespond(withHalJsonResponse("/user_jbloggs_GET.txt")); UserDetails userDetails = service.loadUserByUsername(USERNAME); assertNotNull(userDetails); }
### Question: SpannersService { public void create(Spanner spanner) { restTemplate.postForObject("/", spanner, Spanner.class); } SpannersService(RestTemplateBuilder builder, @Value("${app.service.url.spanners}") String rootUri); Collection<Spanner> findAll(); Spanner findOne(Long id); @PreAuthorize("hasPermission(#spanner, 'owner')") void delete(Spanner spanner); void create(Spanner spanner); @PreAuthorize("hasPermission(#spanner, 'owner')") void update(Spanner spanner); }### Answer: @Test public void testCreate() throws Exception { server.expect(requestTo("/")).andExpect(method(POST)) .andRespond(withStatus(HttpStatus.CREATED)); Spanner newSpanner = aSpanner().withId(null).build(); service.create(newSpanner); server.verify(); }
### Question: SpannersService { @PreAuthorize("hasPermission(#spanner, 'owner')") public void update(Spanner spanner) { restTemplate.put("/{0}", spanner, spanner.getId()); } SpannersService(RestTemplateBuilder builder, @Value("${app.service.url.spanners}") String rootUri); Collection<Spanner> findAll(); Spanner findOne(Long id); @PreAuthorize("hasPermission(#spanner, 'owner')") void delete(Spanner spanner); void create(Spanner spanner); @PreAuthorize("hasPermission(#spanner, 'owner')") void update(Spanner spanner); }### Answer: @Test public void testUpdate() throws Exception { server.expect(requestTo("/1")).andExpect(method(PUT)) .andRespond(withStatus(HttpStatus.OK)); Spanner update = aSpanner().withId(1L).build(); service.update(update); server.verify(); }
### Question: AddSpannerController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public ModelAndView displayPage() { SpannerForm newSpanner = new SpannerForm(); return new ModelAndView(VIEW_ADD_SPANNER, MODEL_SPANNER, newSpanner); } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) ModelAndView displayPage(); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) ModelAndView addSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult, Principal principal); static final String CONTROLLER_URL; static final String VIEW_ADD_SPANNER; static final String VIEW_SUCCESS; static final String VIEW_VALIDATION_FAIL; static final String MODEL_SPANNER; }### Answer: @Test public void testPageDisplay() { ModelAndView response = controller.displayPage(); assertNotNull("no response", response); assertEquals("view", VIEW_ADD_SPANNER, response.getViewName()); }
### Question: DetailSpannerController { @RequestMapping(value = "/detailSpanner", method = RequestMethod.GET) public ModelAndView displayDetail(@RequestParam Long id) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } return new ModelAndView(VIEW_DETAIL_SPANNER, MODEL_SPANNER, spanner); } @RequestMapping(value = "/detailSpanner", method = RequestMethod.GET) ModelAndView displayDetail(@RequestParam Long id); static final String VIEW_DETAIL_SPANNER; static final String MODEL_SPANNER; }### Answer: @Test public void testDisplayPage() throws Exception { when(spannersService.findOne(SPANNER_ID)).thenReturn(SPANNER); ModelAndView response = controller.displayDetail(SPANNER_ID); assertNotNull("no response", response); assertEquals(VIEW_DETAIL_SPANNER, response.getViewName()); Spanner spannerInModel = (Spanner)response.getModelMap().get(MODEL_SPANNER); assertSpannerEquals(SPANNER, spannerInModel); } @Test public void testSpannerNotFound() throws Exception { when(spannersService.findOne(SPANNER_ID)).thenReturn(null); try { controller.displayDetail(SPANNER_ID); fail("Expected: SpannerNotFoundException"); } catch(SpannerNotFoundException notFoundEx) { assertEquals("Exception spanner id", SPANNER_ID, notFoundEx.getSpannerId()); } }
### Question: HomeController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String index() { return VIEW_NOT_SIGNED_IN; } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) String index(); static final String CONTROLLER_URL; static final String VIEW_NOT_SIGNED_IN; }### Answer: @Test public void testHomePage() { String response = controller.index(); assertEquals("view name", VIEW_NOT_SIGNED_IN, response); }
### Question: RestUserDetailsService implements UserDetailsManager { @Override public void createUser(UserDetails userDetails) { restTemplate.postForLocation("/", userDetails); } RestUserDetailsService(RestTemplateBuilder builder, @Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); }### Answer: @Test public void testCreateUser() throws Exception { server.expect(requestTo("/")).andExpect(method(POST)) .andRespond(withStatus(HttpStatus.CREATED)); UserDetails user = new User(USERNAME, PASSWORD, ENABLED); service.createUser(user); server.verify(); }
### Question: DisplaySpannersController { @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) public String deleteSpanner(@RequestParam Long id, ModelMap model) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } spannersService.delete(spanner); return displaySpanners(model); } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) String displaySpanners(ModelMap model); @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) String deleteSpanner(@RequestParam Long id, ModelMap model); }### Answer: @Test public void testDeleteSpanner() throws Exception { when(spannersService.findOne(SPANNER_ID)).thenReturn(SPANNER); ModelMap model = new ModelMap(); String view = controller.deleteSpanner(SPANNER_ID, model); verify(spannersService).delete(SPANNER); assertEquals("view name", VIEW_DISPLAY_SPANNERS, view); } @Test public void testDeleteSpannerNotFound() { when(spannersService.findOne(SPANNER_ID)).thenReturn(null); try { controller.deleteSpanner(SPANNER_ID, new ModelMap()); fail("Expected: SpannerNotFoundException"); } catch(SpannerNotFoundException notFoundEx) { assertEquals("Exception spanner id", SPANNER_ID, notFoundEx.getSpannerId()); } }
### Question: EditSpannerController implements ApplicationEventPublisherAware { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public ModelAndView displayPage(@RequestParam Long id) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } SpannerForm initializedForm = new SpannerForm(spanner); return new ModelAndView(VIEW_EDIT_SPANNER, MODEL_SPANNER, initializedForm); } @Override void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) ModelAndView displayPage(@RequestParam Long id); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) ModelAndView updateSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult); static final String VIEW_EDIT_SPANNER; static final String VIEW_UPDATE_SUCCESS; static final String VIEW_VALIDATION_ERRORS; static final String MODEL_SPANNER; static final String CONTROLLER_URL; }### Answer: @Test public void testDisplayPage() throws Exception { when(spannersService.findOne(SPANNER_ID)).thenReturn(SPANNER); ModelAndView response = controller.displayPage(SPANNER_ID); assertNotNull("no response", response); assertEquals("view", VIEW_EDIT_SPANNER, response.getViewName()); SpannerForm spannerFormData = (SpannerForm)response.getModelMap().get(MODEL_SPANNER); assertSpannerEquals(SPANNER, spannerFormData); } @Test public void testSpannerNotFound() { when(spannersService.findOne(SPANNER_ID)).thenReturn(null); try { controller.displayPage(SPANNER_ID); fail("Expected: SpannerNotFoundException"); } catch(SpannerNotFoundException notFoundEx) { assertEquals("Exception spanner id", SPANNER_ID, notFoundEx.getSpannerId()); } }
### Question: RestUserDetailsService implements UserDetailsManager { @Override public void updateUser(UserDetails userDetails) { restTemplate.put("/{0}", userDetails, userDetails.getUsername()); } RestUserDetailsService(RestTemplateBuilder builder, @Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); }### Answer: @Test public void testUpdateUser() throws Exception { server.expect(requestTo("/" + USERNAME)).andExpect(method(PUT)) .andRespond(withStatus(HttpStatus.OK)); UserDetails user = new User(USERNAME, PASSWORD, ENABLED); service.updateUser(user); server.verify(); }
### Question: RestUserDetailsService implements UserDetailsManager { @Override public void deleteUser(String username) { restTemplate.delete("/{0}", username); } RestUserDetailsService(RestTemplateBuilder builder, @Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); }### Answer: @Test public void testDeleteUser() throws Exception { server.expect(requestTo("/" + USERNAME)).andExpect(method(DELETE)) .andRespond(withStatus(HttpStatus.OK)); service.deleteUser(USERNAME); server.verify(); }
### Question: RestUserDetailsService implements UserDetailsManager { @Override public boolean userExists(String username) { try { ResponseEntity<User> responseEntity = restTemplate.getForEntity("/{0}", User.class, username); return HttpStatus.OK.equals(responseEntity.getStatusCode()); } catch (HttpClientErrorException e) { return false; } } RestUserDetailsService(RestTemplateBuilder builder, @Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); }### Answer: @Test public void testUserExists() throws Exception { server.expect(requestTo("/" + USERNAME)).andExpect(method(GET)) .andRespond(withHalJsonResponse("/user_jbloggs_GET.txt")); boolean userExists = service.userExists(USERNAME); assertTrue(userExists); } @Test public void testUserNotExists() throws Exception { server.expect(requestTo("/" + USERNAME)).andExpect(method(GET)) .andRespond(withStatus(HttpStatus.NOT_FOUND)); boolean userExists = service.userExists(USERNAME); assertFalse(userExists); }
### Question: RestUserDetailsService implements UserDetailsManager { @Override public void changePassword(String username, String password) { User user = new User(); user.setUsername(username); user.setPassword(password); HttpEntity<User> requestEntity = new HttpEntity<>(user); restTemplate.exchange("/{0}", HttpMethod.PATCH, requestEntity, Void.class, username); } RestUserDetailsService(RestTemplateBuilder builder, @Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); }### Answer: @Test public void changePassword() throws Exception { server.expect(requestTo("/" + USERNAME)).andExpect(method(PATCH)) .andRespond(withStatus(HttpStatus.OK)); service.changePassword(USERNAME, PASSWORD); server.verify(); }
### Question: SpannersService { public Collection<Spanner> findAll() { ResponseEntity<PagedResources<Spanner>> response = restTemplate.exchange("/", HttpMethod.GET, null, new ParameterizedTypeReference<PagedResources<Spanner>>(){}); PagedResources<Spanner> pages = response.getBody(); return pages.getContent(); } SpannersService(RestTemplateBuilder builder, @Value("${app.service.url.spanners}") String rootUri); Collection<Spanner> findAll(); Spanner findOne(Long id); @PreAuthorize("hasPermission(#spanner, 'owner')") void delete(Spanner spanner); void create(Spanner spanner); @PreAuthorize("hasPermission(#spanner, 'owner')") void update(Spanner spanner); }### Answer: @Test public void testFindAll() throws Exception { server.expect(requestTo("/")).andExpect(method(GET)) .andRespond(withHalJsonResponse("/spannersGET.txt")); Collection<Spanner> spanners = service.findAll(); assertThat(spanners, hasSize(2)); }
### Question: SpannersService { public Spanner findOne(Long id) { return restTemplate.getForObject("/{0}", Spanner.class, id); } SpannersService(RestTemplateBuilder builder, @Value("${app.service.url.spanners}") String rootUri); Collection<Spanner> findAll(); Spanner findOne(Long id); @PreAuthorize("hasPermission(#spanner, 'owner')") void delete(Spanner spanner); void create(Spanner spanner); @PreAuthorize("hasPermission(#spanner, 'owner')") void update(Spanner spanner); }### Answer: @Test public void testFindOne() throws Exception { server.expect(requestTo("/1")).andExpect(method(GET)) .andRespond(withHalJsonResponse("/spanner1GET.txt")); Spanner spanner = service.findOne(1L); assertSpanner("Belinda", 10, "jones", spanner); }
### Question: SpannersService { @PreAuthorize("hasPermission(#spanner, 'owner')") public void delete(Spanner spanner) { restTemplate.delete("/{0}", spanner.getId()); } SpannersService(RestTemplateBuilder builder, @Value("${app.service.url.spanners}") String rootUri); Collection<Spanner> findAll(); Spanner findOne(Long id); @PreAuthorize("hasPermission(#spanner, 'owner')") void delete(Spanner spanner); void create(Spanner spanner); @PreAuthorize("hasPermission(#spanner, 'owner')") void update(Spanner spanner); }### Answer: @Test public void testDelete() throws Exception { server.expect(requestTo("/1")).andExpect(method(DELETE)) .andRespond(withStatus(HttpStatus.NO_CONTENT)); Spanner susan = aSpanner().withId(1L).named("Susan").build(); service.delete(susan); server.verify(); }
### Question: MongoDbController { @GetMapping("/mongo/findAll") public List<Book> findAll() { return mongoDbService.findAll(); } @PostMapping("/mongo/save") String saveObj(@RequestBody Book book); @GetMapping("/mongo/findAll") List<Book> findAll(); @GetMapping("/mongo/findOne") Book findOne(@RequestParam String id); @GetMapping("/mongo/findOneByName") Book findOneByName(@RequestParam String name); @PostMapping("/mongo/update") String update(@RequestBody Book book); @PostMapping("/mongo/delOne") String delOne(@RequestBody Book book); @GetMapping("/mongo/delById") String delById(@RequestParam String id); @GetMapping("/mongo/findLikes") List<Book> findByLikes(@RequestParam String search); }### Answer: @Test public void findAllTest() throws Exception{ MockUtils.mockGetTest("/mongo/findAll",mockMvc); }
### Question: MongoDbController { @PostMapping("/mongo/update") public String update(@RequestBody Book book) { return mongoDbService.updateBook(book); } @PostMapping("/mongo/save") String saveObj(@RequestBody Book book); @GetMapping("/mongo/findAll") List<Book> findAll(); @GetMapping("/mongo/findOne") Book findOne(@RequestParam String id); @GetMapping("/mongo/findOneByName") Book findOneByName(@RequestParam String name); @PostMapping("/mongo/update") String update(@RequestBody Book book); @PostMapping("/mongo/delOne") String delOne(@RequestBody Book book); @GetMapping("/mongo/delById") String delById(@RequestParam String id); @GetMapping("/mongo/findLikes") List<Book> findByLikes(@RequestParam String search); }### Answer: @Test public void updateTest() throws Exception{ Book book = new Book(); book.setId("4"); book.setPrice(130); book.setName("VUE从入门到放弃"); book.setInfo("前端框架--更新"); Gson gson = new Gson(); String params = gson.toJson(book); MvcResult mvcResult = MockUtils.mockPostTest("/mongo/delOne",params,mockMvc); String result = mvcResult.getResponse().getContentAsString(); System.out.println("更新对象-->" + result); }
### Question: MongoDbController { @GetMapping("/mongo/findLikes") public List<Book> findByLikes(@RequestParam String search) { return mongoDbService.findByLikes(search); } @PostMapping("/mongo/save") String saveObj(@RequestBody Book book); @GetMapping("/mongo/findAll") List<Book> findAll(); @GetMapping("/mongo/findOne") Book findOne(@RequestParam String id); @GetMapping("/mongo/findOneByName") Book findOneByName(@RequestParam String name); @PostMapping("/mongo/update") String update(@RequestBody Book book); @PostMapping("/mongo/delOne") String delOne(@RequestBody Book book); @GetMapping("/mongo/delById") String delById(@RequestParam String id); @GetMapping("/mongo/findLikes") List<Book> findByLikes(@RequestParam String search); }### Answer: @Test public void findByLikesTest() throws Exception{ MockUtils.mockGetTest("/mongo/findLikes?search=从",mockMvc); }
### Question: MyRingArrayQueue implements MyQueue<T> { @Override public T peek() { if(isEmpty()){ throw new RuntimeException(); } return (T) data[head]; } MyRingArrayQueue(); MyRingArrayQueue(int capacity); @Override void enqueue(T value); @Override T dequeue(); @Override T peek(); @Override int size(); }### Answer: @Test public void testFailToPeekOnEmpty(){ assertThrows(RuntimeException.class, () -> queue.peek()); }
### Question: CopyExample { public static String[] copyWrong(String[] input){ if(input == null){ return null; } String[] output = input; return output; } static String[] copyWrong(String[] input); static String[] copy(String[] input); static String[][] copyWrong(String[][] input); static String[][] copy(String[][] input); }### Answer: @Test public void testCopyArrayWrong(){ String[] foo = {"hello", "there", "!"}; String[] copy = CopyExample.copyWrong(foo); checkSameData(foo, copy); String WRONG = "WRONG"; copy[0] = WRONG; assertEquals(WRONG, foo[0]); } @Test public void testCopyMatrixWrong(){ String[][] foo = new String[2][]; foo[0] = new String[]{"Hi", "first row"}; foo[1] = new String[]{"Hello", "second row", "rows do not have to have same length"}; String[][] copy = CopyExample.copyWrong(foo); checkSameData(foo, copy); String WRONG = "WRONG"; copy[0] = new String[]{WRONG}; assertEquals(2, foo[0].length); assertNotEquals(WRONG, foo[0][0]); assertEquals("Hi", foo[0][0]); copy[1][0] = WRONG; assertEquals(WRONG, foo[1][0]); }
### Question: CopyExample { public static String[] copy(String[] input){ if(input == null){ return null; } String[] output = new String[input.length]; for(int i=0; i<output.length; i++){ output[i] = input[i]; } return output; } static String[] copyWrong(String[] input); static String[] copy(String[] input); static String[][] copyWrong(String[][] input); static String[][] copy(String[][] input); }### Answer: @Test public void testCopyArray(){ String[] foo = {"hello", "there", "!"}; String[] copy = CopyExample.copy(foo); checkSameData(foo, copy); String ORIGINAL = foo[0]; String WRONG = "WRONG"; copy[0] = WRONG; assertNotEquals(WRONG, foo[0]); assertEquals(ORIGINAL, foo[0]); } @Test public void testCopyMatrix(){ String[][] foo = new String[2][]; foo[0] = new String[]{"Hi", "first row"}; foo[1] = new String[]{"Hello", "second row", "raws do not have to have same length"}; String[][] copy = CopyExample.copy(foo); checkSameData(foo, copy); String WRONG = "WRONG"; copy[0] = new String[]{WRONG}; assertEquals(2, foo[0].length); assertNotEquals(WRONG, foo[0][0]); assertEquals("Hi", foo[0][0]); copy[1][0] = WRONG; assertNotEquals(WRONG, foo[1][0]); assertEquals("Hello", foo[1][0]); }
### Question: User { public void setName(String name) { this.name = name; } User(String name, String surname, int id); @Override boolean equals(Object o); @Override int hashCode(); String getName(); void setName(String name); String getSurname(); void setSurname(String surname); int getId(); void setId(int id); }### Answer: @Test public void testMutabilityProblem(){ User foo = new User("foo", "bar", 0); MySet<User> users = new MySetHashMap<>(); users.add(foo); assertEquals(1, users.size()); assertTrue(users.isPresent(foo)); foo.setName("changed"); assertEquals(1, users.size()); assertFalse(users.isPresent(foo)); User copy = new User("foo", "bar", 0); assertFalse(users.isPresent(copy)); User changedCopy = new User("changed", "bar", 0); assertEquals(foo, changedCopy); assertFalse(users.isPresent(changedCopy)); foo.setName("foo"); assertTrue(users.isPresent(copy)); }
### Question: MySetHashMap implements MySet<E> { @Override public int size() { return map.size(); } @Override void add(E element); @Override void remove(E element); @Override boolean isPresent(E element); @Override int size(); }### Answer: @Test public void testEmpty() { assertEquals(0, set.size()); assertTrue(set.isEmpty()); }
### Question: MySetHashMap implements MySet<E> { @Override public void remove(E element) { map.delete(element); } @Override void add(E element); @Override void remove(E element); @Override boolean isPresent(E element); @Override int size(); }### Answer: @Test public void testRemove() { int n = set.size(); String element = "foo"; set.add(element); assertTrue(set.isPresent(element)); assertEquals(n + 1, set.size()); set.remove(element); assertFalse(set.isPresent(element)); assertEquals(n, set.size()); }
### Question: HashFunctions { public static int hashLongToInt(long x) { return (int) x; } static int nonUniformHash(int x); static int identityHash(int x); static int shiftedHash(int x); static int hashLongToInt(long x); static int hashLongToIntRevised(long x); static int hashStringSum(String x); static int hashStringSumRevised(String x); }### Answer: @Test public void testHashLongToInt(){ assertEquals(0, HashFunctions.hashLongToInt(0)); assertEquals(42, HashFunctions.hashLongToInt(42)); assertEquals(0, HashFunctions.hashLongToInt(0x1_00_00_00_00L)); assertEquals(5, HashFunctions.hashLongToInt(0x7_00_00_00_05L)); assertEquals(0, HashFunctions.hashLongToInt(0xFF_FF_00_00_00_00L)); } @Test public void testHashLongToIntNegative(){ long one32times = 0xFF_FF_FF_FFL; assertTrue(one32times > 2_000_000_000); assertEquals(-1, HashFunctions.hashLongToInt(one32times)); long singleOne = 0x80_00_00_00L; assertTrue(singleOne > 2_000_000_000); int hashed = HashFunctions.hashLongToInt(singleOne); assertTrue(hashed < -2_000_000_000); assertEquals(Integer.MIN_VALUE, hashed); }
### Question: HashFunctions { public static int hashLongToIntRevised(long x) { return (int) (x ^ (x >>> 32)); } static int nonUniformHash(int x); static int identityHash(int x); static int shiftedHash(int x); static int hashLongToInt(long x); static int hashLongToIntRevised(long x); static int hashStringSum(String x); static int hashStringSumRevised(String x); }### Answer: @Test public void testHashLongToIntRevised(){ long x = 0b0001_0000_0000_0000_0000_0000_0000_0000_____0000_0000_0000_0000_0000_0000_0000_0000L; long w = 0b0001_0000_0000_0000_0000_0000_0000_0000_____0000_0000_0000_0000_0000_0000_0001_0000L; long z = 0b0001_0001_0000_0000_0000_0000_0000_0000_____0000_0000_0000_0000_0000_0000_0000_0000L; assertNotEquals(HashFunctions.hashLongToInt(x), HashFunctions.hashLongToInt(w)); assertEquals(HashFunctions.hashLongToInt(x), HashFunctions.hashLongToInt(z)); assertNotEquals(HashFunctions.hashLongToIntRevised(x), HashFunctions.hashLongToIntRevised(w)); assertNotEquals(HashFunctions.hashLongToIntRevised(x), HashFunctions.hashLongToIntRevised(z)); }
### Question: UndirectedGraph implements Graph<V> { @Override public List<V> findPathDFS(V start, V end) { if(! graph.containsKey(start) || ! graph.containsKey(end)){ return null; } if(start.equals(end)){ throw new IllegalArgumentException(); } Set<V> alreadyVisited = new HashSet<>(); Deque<V> stack = new ArrayDeque<>(); dfs(alreadyVisited, stack, start, end); if(isPathTo(stack, end)){ List<V> path = new ArrayList<>(stack); Collections.reverse(path); return path; } return null; } @Override void addVertex(V vertex); @Override void addEdge(V from, V to); @Override int getNumberOfVertices(); @Override int getNumberOfEdges(); @Override void removeEdge(V from, V to); @Override void removeVertex(V vertex); @Override Collection<V> getAdjacents(V vertex); @Override List<V> findPathDFS(V start, V end); @Override List<V> findPathBFS(V start, V end); @Override Set<V> findConnected(V vertex); @Override Set<V> findConnected(Iterable<V> vertices); }### Answer: @Test public void testNoPathDFS(){ Graph<Integer> graph = createGraph(); List<Integer> path = graph.findPathDFS(10, 4); assertNull(path); }
### Question: UndirectedGraph implements Graph<V> { @Override public Set<V> findConnected(V vertex) { if(! graph.containsKey(vertex)){ return null; } Set<V> connected = new HashSet<>(); findConnected(connected, vertex); return connected; } @Override void addVertex(V vertex); @Override void addEdge(V from, V to); @Override int getNumberOfVertices(); @Override int getNumberOfEdges(); @Override void removeEdge(V from, V to); @Override void removeVertex(V vertex); @Override Collection<V> getAdjacents(V vertex); @Override List<V> findPathDFS(V start, V end); @Override List<V> findPathBFS(V start, V end); @Override Set<V> findConnected(V vertex); @Override Set<V> findConnected(Iterable<V> vertices); }### Answer: @Test public void testConnected(){ Graph<Integer> graph = createGraph(); Set<Integer> left = graph.findConnected(3); Set<Integer> right = graph.findConnected(10); assertEquals(8, left.size()); assertEquals(2, right.size()); }
### Question: GenericExample { public <Z> MyPair<T,Z> createPair(T t, Z z){ MyPair<T, Z> pair = new MyPair<>(t, z); return pair; } Object identityObject(Object x); T identityGeneric(T x); Z identityGenericOnMethod(T t, Z z); MyPair<T,Z> createPair(T t, Z z); Comparable max(Comparable x, Comparable y); Z maxWithGenerics(Z x, Z y); }### Answer: @Test public void testMultiGenerics(){ GenericExample<String> example = new GenericExample<>(); GenericExample.MyPair<String, Integer> pair = example.createPair("foo", 5); assertNotNull(pair); assertEquals("foo", pair.x); assertEquals((Integer)5, pair.y); GenericExample.MyPair<String, String> other = example.createPair("foo", "bar"); assertNotNull(other); assertEquals("foo", other.x); assertEquals("bar", other.y); }
### Question: ArrayExample { public static int sum(int[] array){ if(array == null){ return 0; } int sum = 0; for(int i=0; i< array.length; i++){ sum += array[i]; } return sum; } static int sum(int[] array); }### Answer: @Test public void testBase(){ int[] array = {1, 2, 3}; int res = ArrayExample.sum(array); assertEquals(6, res); } @Test public void testNegative(){ int[] array = new int[3]; array[0] = -2; array[1] = -1; int res = ArrayExample.sum(array); assertEquals(-3, res); } @Test public void testLarge(){ int x = 1_000_000_000; int[] array = {x, x, x}; int res = ArrayExample.sum(array); assertTrue(res < 0); }
### Question: GreedyForKnapsack { public static boolean[] solveByHeavierFirst(KnapsackProblem problem){ List<KnapsackProblem.Item> items = problem.getCopyOfItems(); items.sort((a,b) -> { double diff = a.getWeight() - b.getWeight(); if(diff < 0){ return 1; } else if(diff > 0){ return -1; } else { return 0; } }); return solve(problem, items); } static boolean[] solveByHeavierFirst(KnapsackProblem problem); static boolean[] solveByLighterFirst(KnapsackProblem problem); static boolean[] solveByBestRatioFirst(KnapsackProblem problem); }### Answer: @Test public void testSolveByHeavierFirst(){ KnapsackInstanceWithSolution p = KnapsackInstanceWithSolution.problemP05(); boolean[] res = GreedyForKnapsack.solveByHeavierFirst(p.getProblem()); double fitness = p.getProblem().evaluate(res); assertEquals(47d, fitness, 0.001); double best = p.getBestFitness(); assertNotEquals(best, fitness); assertTrue(best > fitness); }
### Question: GreedyForKnapsack { public static boolean[] solveByLighterFirst(KnapsackProblem problem){ List<KnapsackProblem.Item> items = problem.getCopyOfItems(); items.sort((a,b) -> { double diff = a.getWeight() - b.getWeight(); if(diff > 0){ return 1; } else if(diff < 0){ return -1; } else { return 0; } }); return solve(problem, items); } static boolean[] solveByHeavierFirst(KnapsackProblem problem); static boolean[] solveByLighterFirst(KnapsackProblem problem); static boolean[] solveByBestRatioFirst(KnapsackProblem problem); }### Answer: @Test public void testSolveByLighterFirst(){ KnapsackInstanceWithSolution p = KnapsackInstanceWithSolution.problemP05(); boolean[] res = GreedyForKnapsack.solveByLighterFirst(p.getProblem()); double fitness = p.getProblem().evaluate(res); assertEquals(44d, fitness, 0.001); double best = p.getBestFitness(); assertNotEquals(best, fitness); assertTrue(best > fitness); }
### Question: GreedyForKnapsack { public static boolean[] solveByBestRatioFirst(KnapsackProblem problem){ List<KnapsackProblem.Item> items = problem.getCopyOfItems(); items.sort((a,b) -> { if(a.getWeight() == 0){ return -1; } if(b.getWeight() == 0){ return 1; } double ra = a.getValue() / a.getWeight(); double rb = b.getValue() / b.getWeight(); double diff = ra - rb; if(diff < 0){ return 1; } else if(diff > 0){ return -1; } else { return 0; } }); return solve(problem, items); } static boolean[] solveByHeavierFirst(KnapsackProblem problem); static boolean[] solveByLighterFirst(KnapsackProblem problem); static boolean[] solveByBestRatioFirst(KnapsackProblem problem); }### Answer: @Test public void testSolveByBestRatioFirst(){ KnapsackInstanceWithSolution p = KnapsackInstanceWithSolution.problemP05(); boolean[] heavier = GreedyForKnapsack.solveByHeavierFirst(p.getProblem()); boolean[] ratio = GreedyForKnapsack.solveByBestRatioFirst(p.getProblem()); assertArrayEquals(heavier, ratio); }
### Question: DnaCompressor { public static byte[] compress(String dna){ BitWriter writer = new BitWriter(); writer.write(dna.length()); for(int i=0; i<dna.length(); i++){ char c = dna.charAt(i); if(c== 'A'){ writer.write(true); writer.write(true); } else if(c== 'C'){ writer.write(true); writer.write(false); }else if(c== 'G'){ writer.write(false); writer.write(true); }else if(c== 'T'){ writer.write(false); writer.write(false); } else { throw new IllegalArgumentException("Unrecognized character: " + c); } } return writer.extract(); } static byte[] compress(String dna); static String decompress(byte[] data); }### Answer: @Test public void testDecreaseSize(){ String dna = "AAAGTACCTGAGTAAAGTACCTGAGTAAAGTACCTGAGTTTTGCTGCTGCTGCTGCTGCTGCTGCTGCTGCTTTTTTT"; checkPreserveInformation(dna); int nonCompressedSize = dna.getBytes(StandardCharsets.UTF_8).length; byte[] compressed = DnaCompressor.compress(dna); assertTrue(compressed.length < nonCompressedSize); double ratio = (double) compressed.length / (double) nonCompressedSize; assertTrue(ratio < 0.33); assertTrue(ratio >= 0.25); } @Test public void testIncreaseSize(){ String dna = "A"; checkPreserveInformation(dna); int nonCompressedSize = dna.getBytes(StandardCharsets.UTF_8).length; byte[] compressed = DnaCompressor.compress(dna); assertTrue(compressed.length > nonCompressedSize); }
### Question: BitReader { public byte readByte(){ if(bits % 8 == 0){ int i = bits / 8; bits += 8; return data[i]; } byte tmp = 0; for(int j=0; j<8; j++){ tmp = (byte) (tmp << 1); boolean k = readBoolean(); if(k){ tmp |= 1; } } return tmp; } BitReader(byte[] data); byte readByte(); boolean readBoolean(); int readInt(); int readInt(int nbits); char readChar(); }### Answer: @Test public void testByte(){ byte val = 5; BitReader reader = new BitReader(new byte[]{val}); byte res = reader.readByte(); assertEquals(val, res); } @Test public void testNegativeByte(){ byte val = -125; BitReader reader = new BitReader(new byte[]{val}); byte res = reader.readByte(); assertEquals(val, res); }
### Question: BitReader { public boolean readBoolean(){ int i = bits / 8; if(i >= data.length){ throw new IllegalStateException("No more data to read"); } byte b = data[i]; int k = bits % 8; bits++; return ((b >>> (8 - k - 1)) & 1) == 1; } BitReader(byte[] data); byte readByte(); boolean readBoolean(); int readInt(); int readInt(int nbits); char readChar(); }### Answer: @Test public void testBoolean(){ byte val = (byte)0b1000_0000; BitReader reader = new BitReader(new byte[]{val}); boolean b = reader.readBoolean(); assertTrue(b); } @Test public void testTrueFalseTrue(){ byte val = (byte)0b1010_0000; BitReader reader = new BitReader(new byte[]{val}); assertTrue(reader.readBoolean()); assertFalse(reader.readBoolean()); assertTrue(reader.readBoolean()); }
### Question: BitReader { public int readInt(){ int x; byte a = readByte(); x = a & 0xFF; byte b = readByte(); x = x << 8; x |= (b & 0xFF); byte c = readByte(); x = x << 8; x |= (c & 0xFF); byte d = readByte(); x = x << 8; x |= (d & 0xFF); return x; } BitReader(byte[] data); byte readByte(); boolean readBoolean(); int readInt(); int readInt(int nbits); char readChar(); }### Answer: @Test public void testSmallInt(){ int val = 5; BitWriter writer = new BitWriter(); writer.write(val); BitReader reader = new BitReader(writer.extract()); int res = reader.readInt(); assertEquals(val, res); } @Test public void testIntWithNegativeBytes(){ int val = 0b1000_0000_1000_0000; BitWriter writer = new BitWriter(); writer.write(val); BitReader reader = new BitReader(writer.extract()); int res = reader.readInt(); assertEquals(val, res); }
### Question: BitReader { public char readChar(){ int x; byte a = readByte(); x = a & 0xFF; byte b = readByte(); x = x << 8; x |= (b & 0xFF); return (char) x; } BitReader(byte[] data); byte readByte(); boolean readBoolean(); int readInt(); int readInt(int nbits); char readChar(); }### Answer: @Test public void testStringChar(){ String val = "abc"; BitWriter writer = new BitWriter(); writer.write(val); BitReader reader = new BitReader(writer.extract()); char a = reader.readChar(); char b = reader.readChar(); char c = reader.readChar(); assertEquals('a', a); assertEquals('b', b); assertEquals('c', c); }
### Question: MyMapBinarySearchTree implements MyMapTreeBased<K, V> { @Override public int getMaxTreeDepth() { if (root == null) { return 0; } return depth(root); } @Override void put(K key, V value); @Override void delete(K key); @Override V get(K key); @Override int size(); @Override int getMaxTreeDepth(); }### Answer: @Test public void testDepthZero() { assertEquals(0, map.getMaxTreeDepth()); }
### Question: LambdaExamples { public static void useRunnable(Runnable runnable){ System.out.println("Before runnable"); runnable.run(); System.out.println("After runnable"); } static void useRunnable(Runnable runnable); static void useConsumer(Consumer<String> consumer); static String usePredicate(Predicate<String> predicate); static int useFunction(Function<String, Integer> function); }### Answer: @Test public void testRunnable() { Runnable anonymousClass = new Runnable() { @Override public void run() { System.out.println("Executing method run()"); } }; Runnable lambda = () -> System.out.println("Executing method run()"); LambdaExamples.useRunnable(anonymousClass); LambdaExamples.useRunnable(lambda); LambdaExamples.useRunnable(() -> System.out.println("Executing method run()")); }
### Question: LambdaExamples { public static void useConsumer(Consumer<String> consumer){ String foo = "foo"; System.out.println("Before consumer"); consumer.accept(foo); System.out.println("After consumer"); } static void useRunnable(Runnable runnable); static void useConsumer(Consumer<String> consumer); static String usePredicate(Predicate<String> predicate); static int useFunction(Function<String, Integer> function); }### Answer: @Test public void testConsumer() { Consumer<String> anonymousClass = new Consumer<String>() { @Override public void accept(String s) { System.out.println(s.toUpperCase()); } }; Consumer<String> lambda = s -> System.out.println(s.toUpperCase()); LambdaExamples.useConsumer(anonymousClass); LambdaExamples.useConsumer(lambda); LambdaExamples.useConsumer(s -> System.out.println(s.toUpperCase())); }
### Question: LambdaExamples { public static String usePredicate(Predicate<String> predicate){ String foo = "foo"; if(predicate.test(foo)){ return foo; } else { return null; } } static void useRunnable(Runnable runnable); static void useConsumer(Consumer<String> consumer); static String usePredicate(Predicate<String> predicate); static int useFunction(Function<String, Integer> function); }### Answer: @Test public void testPredicate() { Predicate<String> anonymousClass = new Predicate<String>() { @Override public boolean test(String s) { return s.length() > 5; } }; Predicate<String> lambda = s -> s.toUpperCase().equals("FOO"); assertNull(LambdaExamples.usePredicate(anonymousClass)); assertNotNull(LambdaExamples.usePredicate(lambda)); assertNotNull(LambdaExamples.usePredicate(s -> { int length = s.length(); return length == 3; } )); }
### Question: LambdaExamples { public static int useFunction(Function<String, Integer> function){ String input = "foo"; return function.apply(input); } static void useRunnable(Runnable runnable); static void useConsumer(Consumer<String> consumer); static String usePredicate(Predicate<String> predicate); static int useFunction(Function<String, Integer> function); }### Answer: @Test public void testFunction(){ Function<String, Integer> anonymousClass = new Function<String, Integer>() { @Override public Integer apply(String s) { return s.length(); } }; Function<String, Integer> lambda = s -> 5; assertEquals(3, LambdaExamples.useFunction(anonymousClass)); assertEquals(5, LambdaExamples.useFunction(lambda)); assertEquals(6, LambdaExamples.useFunction(s -> s.length() * 2)); }
### Question: MyIterableLinkedList implements Iterable<T> { public void add(T value) { ListNode node = new ListNode(); node.value = value; size++; modificationCounter++; if (head == null) { head = node; tail = node; return; } tail.next = node; tail = node; } @Override Iterator<T> iterator(); void delete(int index); T get(int index); void add(T value); int size(); boolean isEmpty(); boolean contains(T value); }### Answer: @Test public void testIterable(){ MyIterableLinkedList<String> data = new MyIterableLinkedList<>(); data.add("a"); data.add("b"); data.add("c"); String buffer = ""; for(String value : data){ buffer += value; } assertEquals("abc", buffer); }
### Question: MyIterableLinkedList implements Iterable<T> { public int size() { return size; } @Override Iterator<T> iterator(); void delete(int index); T get(int index); void add(T value); int size(); boolean isEmpty(); boolean contains(T value); }### Answer: @Test public void testEmpty(){ MyIterableLinkedList<Integer> data = new MyIterableLinkedList<>(); assertEquals(0, data.size()); }
### Question: AllPathsGraph extends UndirectedGraph<V> { public List<List<V>> findAllPaths(V start, V end) { if (!graph.containsKey(start) && !graph.containsKey(end)) { return Collections.emptyList(); } if (start.equals(end)) { throw new IllegalArgumentException(); } Deque<V> stack = new ArrayDeque<>(); List<List<V>> paths = new ArrayList<>(); dfs(paths, stack, start, end); return paths; } List<List<V>> findAllPaths(V start, V end); }### Answer: @Test public void test(){ AllPathsGraph<String> graph = new AllPathsGraph<>(); graph.addEdge("0","X"); graph.addEdge("X","1"); graph.addEdge("X","Y"); graph.addEdge("1","2"); graph.addEdge("2","Y"); graph.addEdge("1","3"); graph.addEdge("3","4"); graph.addEdge("3","5"); graph.addEdge("4","5"); List<List<String>> paths = graph.findAllPaths("X","5"); assertEquals(4, paths.size()); assertTrue(paths.stream().anyMatch(p -> p.size() == 4)); assertTrue(paths.stream().anyMatch(p -> p.size() == 5)); assertTrue(paths.stream().anyMatch(p -> p.size() == 6)); assertTrue(paths.stream().anyMatch(p -> p.size() == 7)); }
### Question: MyIterableLinkedList implements Iterable<T> { public T get(int index) { if (index < 0 || index >= size()) { throw new IndexOutOfBoundsException(); } ListNode current = head; int counter = 0; while (current != null) { if (counter == index) { return current.value; } current = current.next; counter++; } assert false; return null; } @Override Iterator<T> iterator(); void delete(int index); T get(int index); void add(T value); int size(); boolean isEmpty(); boolean contains(T value); }### Answer: @Test public void testOutOfIndex(){ MyIterableLinkedList<String> data = new MyIterableLinkedList<>(); assertThrows(IndexOutOfBoundsException.class, () -> data.get(-5)); assertThrows(IndexOutOfBoundsException.class, () -> data.get(42)); }
### Question: MyIterableHashMap implements MyHashMap<K,V>, Iterable<V> { @Override public void put(K key, V value) { modificationCounter++; int i = index(key); if(data[i] == null){ data[i] = new ArrayList<>(); } List<Entry> list = data[i]; for(int j=0; j<list.size(); j++){ Entry entry = list.get(j); if(key.equals(entry.key)){ entry.value = value; return; } } list.add(new Entry(key, value)); } MyIterableHashMap(); MyIterableHashMap(int capacity); @Override Iterator<V> iterator(); @Override void put(K key, V value); @Override void delete(K key); @Override V get(K key); @Override int size(); }### Answer: @Test public void testIterable(){ MyIterableHashMap<Integer, String> map = new MyIterableHashMap<>(); map.put(0, "a"); map.put(1, "b"); map.put(2, "c"); String buffer = ""; for(String value : map){ buffer += value; } assertEquals(3, buffer.length()); assertTrue(buffer.contains("a")); assertTrue(buffer.contains("b")); assertTrue(buffer.contains("c")); }
### Question: MyIterableHashMap implements MyHashMap<K,V>, Iterable<V> { @Override public int size() { int size = 0; for(int i=0; i<data.length; i++){ if(data[i] != null){ size += data[i].size(); } } return size; } MyIterableHashMap(); MyIterableHashMap(int capacity); @Override Iterator<V> iterator(); @Override void put(K key, V value); @Override void delete(K key); @Override V get(K key); @Override int size(); }### Answer: @Test public void testEmpty() { MyIterableHashMap<String, Integer> map = new MyIterableHashMap<>(); assertEquals(0, map.size()); assertTrue(map.isEmpty()); }
### Question: MyIterableHashMap implements MyHashMap<K,V>, Iterable<V> { @Override public void delete(K key) { int i = index(key); if(data[i] == null){ return; } List<Entry> list = data[i]; for(int j=0; j<list.size(); j++){ Entry entry = list.get(j); if(key.equals(entry.key)){ list.remove(j); modificationCounter++; return; } } } MyIterableHashMap(); MyIterableHashMap(int capacity); @Override Iterator<V> iterator(); @Override void put(K key, V value); @Override void delete(K key); @Override V get(K key); @Override int size(); }### Answer: @Test public void testDelete() { MyIterableHashMap<String, Integer> map = new MyIterableHashMap<>(); int n = map.size(); String key = "foo"; int x = 42; map.put(key, x); assertEquals(x, map.get(key).intValue()); assertEquals(n + 1, map.size()); map.delete(key); assertNull(map.get(key)); assertEquals(n, map.size()); }
### Question: TernaryTreeMap implements MyMapTreeBased<K, V> { @Override public int getMaxTreeDepth() { if (root == null) { return 0; } return depth(root); } @Override void put(K key, V value); @Override void delete(K key); @Override V get(K key); @Override int size(); @Override int getMaxTreeDepth(); }### Answer: @Test public void testDepthZero() { assertEquals(0, map.getMaxTreeDepth()); }
### Question: MyArrayListInteger { public int size() { return size; } MyArrayListInteger(); MyArrayListInteger(int maxSize); Integer get(int index); void add(Integer value); int size(); }### Answer: @Test public void testEmpty(){ assertEquals(0, data.size()); }
### Question: MyArrayListInteger { public Integer get(int index) { if(index < 0 || index >= size){ return null; } return data[index]; } MyArrayListInteger(); MyArrayListInteger(int maxSize); Integer get(int index); void add(Integer value); int size(); }### Answer: @Test public void testOutOfIndex(){ assertNull(data.get(-5)); assertNull(data.get(42)); }
### Question: AxonDBEventStore extends AbstractEventStore { @Override public TrackingEventStream openStream(TrackingToken trackingToken) { return storageEngine().openStream(trackingToken); } AxonDBEventStore(AxonDBConfiguration configuration, Serializer serializer); AxonDBEventStore(AxonDBConfiguration configuration, Serializer serializer, EventUpcaster upcasterChain); AxonDBEventStore(AxonDBConfiguration configuration, Serializer snapshotSerializer, Serializer eventSerializer, EventUpcaster upcasterChain); @Override TrackingEventStream openStream(TrackingToken trackingToken); QueryResultStream query(String query, boolean liveUpdates); }### Answer: @Test public void testPublishAndConsumeEvents() throws Exception { UnitOfWork<Message<?>> uow = DefaultUnitOfWork.startAndGet(null); testSubject.publish(GenericEventMessage.asEventMessage("Test1"), GenericEventMessage.asEventMessage("Test2"), GenericEventMessage.asEventMessage("Test3")); uow.commit(); TrackingEventStream stream = testSubject.openStream(null); List<String> received = new ArrayList<>(); while(stream.hasNextAvailable(100, TimeUnit.MILLISECONDS)) { received.add(stream.nextAvailable().getPayload().toString()); } stream.close(); assertEquals(Arrays.asList("Test1", "Test2", "Test3"), received); }
### Question: IdGenerator { public static long newRandomId(@Nullable Set<Long> existingIds) { while (true) { long candidateId = ThreadLocalRandom.current().nextLong(); if (MIN <= candidateId && candidateId <= MAX) { if (existingIds == null) { return candidateId; } if (!existingIds.contains(candidateId)) { return candidateId; } } } } static long newRandomId(@Nullable Set<Long> existingIds); static long newLinearId(AtomicLong longValue); static final long MIN; static final long MAX; }### Answer: @Test public void testNewRandomId() { assertThat(IdGenerator.newRandomId(null)).isBetween(IdGenerator.MIN, IdGenerator.MAX); Set<Long> ids = new HashSet<>(); ids.add(1L); assertThat(IdGenerator.newRandomId(ids)).isBetween(IdGenerator.MIN, IdGenerator.MAX); }
README.md exists but content is empty.
Downloads last month
31