method2testcases
stringlengths
118
6.63k
### Question: Part7Context { @Complexity(EASY) public static Mono<String> grabDataFromTheGivenContext(Object key) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Mono<String> grabDataFromTheGivenContext(Object key); @Complexity(EASY) static Mono<String> provideCorrectContext(Mono<String> source, Object key, Object value); @Complexity(EASY) static Flux<String> provideCorrectContext( Publisher<String> sourceA, Context contextA, Publisher<String> sourceB, Context contextB); }### Answer: @Test public void grabDataFromTheGivenContextTest() { StepVerifier.create( grabDataFromTheGivenContext("Test") .subscriberContext(Context.of("Test", "Test")) ) .expectSubscription() .expectNext("Test") .verifyComplete(); }
### Question: Part7Context { @Complexity(EASY) public static Mono<String> provideCorrectContext(Mono<String> source, Object key, Object value) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Mono<String> grabDataFromTheGivenContext(Object key); @Complexity(EASY) static Mono<String> provideCorrectContext(Mono<String> source, Object key, Object value); @Complexity(EASY) static Flux<String> provideCorrectContext( Publisher<String> sourceA, Context contextA, Publisher<String> sourceB, Context contextB); }### Answer: @Test public void provideCorrectContextTest() { StepVerifier.create( provideCorrectContext(Mono.just("Test"), "Key", "Value") ) .expectSubscription() .expectAccessibleContext().contains("Key", "Value").then() .expectNext("Test") .verifyComplete(); } @Test public void provideCorrectContext1() { Mono<String> a = Mono.subscriberContext() .filter( context -> context.hasKey("a") && !context.hasKey("b")) .map(context -> context.get("a")); Mono<String> b = Mono.subscriberContext() .filter( context -> context.hasKey("b") && !context.hasKey("a")) .map(context -> context.get("b")); Flux<String> flux = provideCorrectContext(a, Context.of("a", "a"), b, Context.of("b", "b")); StepVerifier.create(flux) .expectSubscription() .expectNext("a") .expectNext("b") .verifyComplete(); }
### Question: Part3MultithreadingParallelization { @Complexity(EASY) public static Publisher<String> publishOnParallelThreadScheduler(Flux<String> source) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Publisher<String> publishOnParallelThreadScheduler(Flux<String> source); @Complexity(EASY) static Publisher<String> subscribeOnSingleThreadScheduler(Callable<String> blockingCall); @Complexity(EASY) static ParallelFlux<String> paralellizeWorkOnDifferentThreads(Flux<String> source); @Complexity(HARD) static Publisher<String> paralellizeLongRunningWorkOnUnboundedAmountOfThread(Flux<Callable<String>> streamOfLongRunningSources); }### Answer: @Test public void publishOnParallelThreadSchedulerTest() { Thread[] threads = new Thread[2]; StepVerifier .create(publishOnParallelThreadScheduler(Flux.defer(() -> { threads[0] = Thread.currentThread(); return Flux.just("Hello"); }))) .expectSubscription() .expectNext("Hello") .verifyComplete(); Assert.assertTrue( "Expected execution on different Threads", !threads[0].equals(threads[1]) ); }
### Question: Part3MultithreadingParallelization { @Complexity(EASY) public static Publisher<String> subscribeOnSingleThreadScheduler(Callable<String> blockingCall) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Publisher<String> publishOnParallelThreadScheduler(Flux<String> source); @Complexity(EASY) static Publisher<String> subscribeOnSingleThreadScheduler(Callable<String> blockingCall); @Complexity(EASY) static ParallelFlux<String> paralellizeWorkOnDifferentThreads(Flux<String> source); @Complexity(HARD) static Publisher<String> paralellizeLongRunningWorkOnUnboundedAmountOfThread(Flux<Callable<String>> streamOfLongRunningSources); }### Answer: @Test public void subscribeOnSingleThreadSchedulerTest() { Thread[] threads = new Thread[1]; StepVerifier .create(subscribeOnSingleThreadScheduler(() -> { System.out.println("Threads:" + Thread.currentThread().getName()); threads[0] = Thread.currentThread(); return "Hello"; })) .expectSubscription() .expectNext("Hello") .verifyComplete(); Assert.assertTrue( "Expected execution on different Threads", !threads[0].equals(Thread.currentThread()) ); }
### Question: Part3MultithreadingParallelization { @Complexity(EASY) public static ParallelFlux<String> paralellizeWorkOnDifferentThreads(Flux<String> source) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Publisher<String> publishOnParallelThreadScheduler(Flux<String> source); @Complexity(EASY) static Publisher<String> subscribeOnSingleThreadScheduler(Callable<String> blockingCall); @Complexity(EASY) static ParallelFlux<String> paralellizeWorkOnDifferentThreads(Flux<String> source); @Complexity(HARD) static Publisher<String> paralellizeLongRunningWorkOnUnboundedAmountOfThread(Flux<Callable<String>> streamOfLongRunningSources); }### Answer: @Test public void paralellizeWorkOnDifferentThreadsTest() { StepVerifier .create(paralellizeWorkOnDifferentThreads( Flux.just("Hello", "Hello", "Hello") )) .expectSubscription() .expectNext("Hello", "Hello", "Hello") .expectComplete() .verify(); }
### Question: Part3MultithreadingParallelization { @Complexity(HARD) public static Publisher<String> paralellizeLongRunningWorkOnUnboundedAmountOfThread(Flux<Callable<String>> streamOfLongRunningSources) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Publisher<String> publishOnParallelThreadScheduler(Flux<String> source); @Complexity(EASY) static Publisher<String> subscribeOnSingleThreadScheduler(Callable<String> blockingCall); @Complexity(EASY) static ParallelFlux<String> paralellizeWorkOnDifferentThreads(Flux<String> source); @Complexity(HARD) static Publisher<String> paralellizeLongRunningWorkOnUnboundedAmountOfThread(Flux<Callable<String>> streamOfLongRunningSources); }### Answer: @Test public void paralellizeLongRunningWorkOnUnboundedAmountOfThreadTest() { Thread[] threads = new Thread[3]; StepVerifier .create(paralellizeLongRunningWorkOnUnboundedAmountOfThread(Flux.<Callable<String>>just( () -> { threads[0] = Thread.currentThread(); Thread.sleep(300); return "Hello"; }, () -> { threads[1] = Thread.currentThread(); Thread.sleep(300); return "Hello"; }, () -> { threads[2] = Thread.currentThread(); Thread.sleep(300); return "Hello"; } ).repeat(20))) .expectSubscription() .expectNext("Hello", "Hello", "Hello") .expectNextCount(60) .expectComplete() .verify(Duration.ofMillis(600)); Assert.assertTrue( "Expected execution on different Threads", !threads[0].equals(threads[1]) ); Assert.assertTrue( "Expected execution on different Threads", !threads[1].equals(threads[2]) ); Assert.assertTrue( "Expected execution on different Threads", !threads[0].equals(threads[2]) ); }
### Question: PaymentService { public Flux<Payment> findPayments(Flux<String> userIds) { return userIds.flatMap(repository::findAllByUserId); } PaymentService(); Flux<Payment> findPayments(Flux<String> userIds); }### Answer: @Test public void findPayments() { PaymentService service = new PaymentService(); StepVerifier.create(service.findPayments(Flux.range(1, 100) .map(String::valueOf)) .then()) .expectSubscription() .verifyComplete(); }
### Question: Part5ResilienceResponsive_Optional { @Complexity(HARD) public static Publisher<Integer> provideSupportOfContinuation(Flux<Integer> values) { return values; } @Complexity(HARD) static Publisher<Integer> provideSupportOfContinuation(Flux<Integer> values); @Complexity(HARD) static Publisher<Integer> provideSupportOfContinuationWithoutErrorStrategy(Flux<Integer> values, Function<Integer, Integer> mapping); }### Answer: @Test public void provideSupportOfContinuationTest() { Flux<Integer> range = Flux.range(0, 6) .map(i -> 10 / i); StepVerifier.create(provideSupportOfContinuation(range)) .expectSubscription() .expectNextCount(5) .expectComplete() .verify(); }
### Question: Part5ResilienceResponsive_Optional { @Complexity(HARD) public static Publisher<Integer> provideSupportOfContinuationWithoutErrorStrategy(Flux<Integer> values, Function<Integer, Integer> mapping) { return values.map(mapping); } @Complexity(HARD) static Publisher<Integer> provideSupportOfContinuation(Flux<Integer> values); @Complexity(HARD) static Publisher<Integer> provideSupportOfContinuationWithoutErrorStrategy(Flux<Integer> values, Function<Integer, Integer> mapping); }### Answer: @Test public void provideSupportOfContinuationWithoutErrorStrategyTest() { Function<Integer, Integer> mapping = i -> 10 / i; Flux<Integer> range = Flux.range(0, 6); StepVerifier.create(provideSupportOfContinuationWithoutErrorStrategy(range, mapping)) .expectSubscription() .expectNextCount(5) .expectComplete() .verifyThenAssertThat() .hasNotDroppedErrors(); }
### Question: Part5ResilienceResponsive { @Complexity(EASY) public static Publisher<String> fallbackHelloOnEmpty(Flux<String> emptyPublisher) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Publisher<String> fallbackHelloOnEmpty(Flux<String> emptyPublisher); @Complexity(EASY) static Publisher<String> fallbackHelloOnError(Flux<String> failurePublisher); @Complexity(EASY) static Publisher<String> retryOnError(Mono<String> failurePublisher); @Complexity(MEDIUM) static Publisher<String> timeoutLongOperation(CompletableFuture<String> longRunningCall); @Complexity(HARD) static Publisher<String> timeoutLongOperation(Callable<String> longRunningCall); }### Answer: @Test public void fallbackHelloOnEmptyTest() { StepVerifier .create(fallbackHelloOnEmpty(Flux.empty())) .expectSubscription() .expectNext("Hello") .verifyComplete(); }
### Question: Part5ResilienceResponsive { @Complexity(EASY) public static Publisher<String> fallbackHelloOnError(Flux<String> failurePublisher) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Publisher<String> fallbackHelloOnEmpty(Flux<String> emptyPublisher); @Complexity(EASY) static Publisher<String> fallbackHelloOnError(Flux<String> failurePublisher); @Complexity(EASY) static Publisher<String> retryOnError(Mono<String> failurePublisher); @Complexity(MEDIUM) static Publisher<String> timeoutLongOperation(CompletableFuture<String> longRunningCall); @Complexity(HARD) static Publisher<String> timeoutLongOperation(Callable<String> longRunningCall); }### Answer: @Test public void fallbackHelloOnErrorTest() { StepVerifier .create(fallbackHelloOnError(Flux.error(new RuntimeException()))) .expectSubscription() .expectNext("Hello") .verifyComplete(); }
### Question: Part5ResilienceResponsive { @Complexity(EASY) public static Publisher<String> retryOnError(Mono<String> failurePublisher) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Publisher<String> fallbackHelloOnEmpty(Flux<String> emptyPublisher); @Complexity(EASY) static Publisher<String> fallbackHelloOnError(Flux<String> failurePublisher); @Complexity(EASY) static Publisher<String> retryOnError(Mono<String> failurePublisher); @Complexity(MEDIUM) static Publisher<String> timeoutLongOperation(CompletableFuture<String> longRunningCall); @Complexity(HARD) static Publisher<String> timeoutLongOperation(Callable<String> longRunningCall); }### Answer: @Test public void retryOnErrorTest() throws Exception { Callable<String> callable = Mockito.mock(Callable.class); Mockito.when(callable.call()) .thenThrow(new RuntimeException()) .thenReturn("Hello"); StepVerifier .create(retryOnError(Mono.fromCallable(callable))) .expectSubscription() .expectNext("Hello") .expectComplete() .verify(); }
### Question: DefaultPriceService implements PriceService { Flux<Map<String, Object>> selectOnlyPriceUpdateEvents(Flux<Map<String, Object>> input) { return Flux.never(); } DefaultPriceService(CryptoService cryptoService); Flux<MessageDTO<Float>> pricesStream(Flux<Long> intervalPreferencesStream); }### Answer: @Test public void verifyBuildingCurrentPriceEvents() { StepVerifier.create( new DefaultPriceService(cryptoService).selectOnlyPriceUpdateEvents( Flux.just( map().put("Invalid", "A").build(), map().put(TYPE_KEY, "1").build(), map().put(TYPE_KEY, "5").build(), map().put(TYPE_KEY, "5") .put(PRICE_KEY, 0.1F) .put(CURRENCY_KEY, "USD") .put(MARKET_KEY, "External").build() ) ) ) .expectNext( map().put(TYPE_KEY, "5") .put(PRICE_KEY, 0.1F) .put(CURRENCY_KEY, "USD") .put(MARKET_KEY, "External").build() ) .expectComplete() .verify(Duration.ofSeconds(2)); }
### Question: Part5ResilienceResponsive { @Complexity(MEDIUM) public static Publisher<String> timeoutLongOperation(CompletableFuture<String> longRunningCall) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Publisher<String> fallbackHelloOnEmpty(Flux<String> emptyPublisher); @Complexity(EASY) static Publisher<String> fallbackHelloOnError(Flux<String> failurePublisher); @Complexity(EASY) static Publisher<String> retryOnError(Mono<String> failurePublisher); @Complexity(MEDIUM) static Publisher<String> timeoutLongOperation(CompletableFuture<String> longRunningCall); @Complexity(HARD) static Publisher<String> timeoutLongOperation(Callable<String> longRunningCall); }### Answer: @Test public void timeoutLongOperationWithCompletableFutureTest() { StepVerifier .withVirtualTime(() -> timeoutLongOperation(CompletableFuture.supplyAsync(() -> { try { Thread.sleep(1000000); } catch (InterruptedException e) { return null; } return "Toooooo long"; }))) .expectSubscription() .expectNoEvent(Duration.ofSeconds(1)) .expectNext("Hello") .expectComplete() .verify(Duration.ofSeconds(1)); } @Test public void timeoutLongOperationWithCallableTest() { StepVerifier .create(timeoutLongOperation(() -> { try { Thread.sleep(1000000); } catch (InterruptedException e) { return null; } return "Toooooo long"; })) .expectSubscription() .expectNext("Hello") .expectComplete() .verify(Duration.ofSeconds(2)); }
### Question: Part4Backpressure { @Complexity(EASY) public static Flux<String> dropElementsOnBackpressure(Flux<String> upstream) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Flux<String> dropElementsOnBackpressure(Flux<String> upstream); @Complexity(MEDIUM) static Flux<List<Long>> backpressureByBatching(Flux<Long> upstream); }### Answer: @Test public void dropElementsOnBackpressureTest() { DirectProcessor<String> processor = DirectProcessor.create(); StepVerifier .create(dropElementsOnBackpressure(processor), 0) .expectSubscription() .then(() -> processor.onNext("")) .then(() -> processor.onNext("")) .thenRequest(1) .then(() -> processor.onNext("0")) .expectNext("0") .then(() -> processor.onNext("0")) .then(() -> processor.onNext("0")) .thenRequest(1) .then(() -> processor.onNext("10")) .expectNext("10") .thenRequest(1) .then(() -> processor.onNext("20")) .expectNext("20") .then(() -> processor.onNext("40")) .then(() -> processor.onNext("30")) .then(processor::onComplete) .expectComplete() .verify(); }
### Question: Part4Backpressure { @Complexity(MEDIUM) public static Flux<List<Long>> backpressureByBatching(Flux<Long> upstream) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Flux<String> dropElementsOnBackpressure(Flux<String> upstream); @Complexity(MEDIUM) static Flux<List<Long>> backpressureByBatching(Flux<Long> upstream); }### Answer: @Test public void backpressureByBatchingTest() { StepVerifier .withVirtualTime(() -> backpressureByBatching(Flux.interval(Duration.ofMillis(1))), 0) .expectSubscription() .thenRequest(1) .expectNoEvent(Duration.ofSeconds(1)) .expectNextCount(1) .thenRequest(1) .expectNoEvent(Duration.ofSeconds(1)) .expectNextCount(1) .thenCancel() .verify(); }
### Question: Part4ExtraBackpressure_Optional { @Complexity(MEDIUM) public static Publisher<String> handleBackpressureWithBuffering(StringEventPublisher stringEventPublisher) { throw new RuntimeException("Not implemented"); } @Complexity(MEDIUM) static Publisher<String> handleBackpressureWithBuffering(StringEventPublisher stringEventPublisher); @Optional @Complexity(MEDIUM) static void dynamicDemand(Flux<String> source, CountDownLatch countDownOnComplete); }### Answer: @Test public void handleBackpressureWithBufferingTest() { TestStringEventPublisher stringEmitter = new TestStringEventPublisher(); StepVerifier .create( handleBackpressureWithBuffering(stringEmitter), 0 ) .expectSubscription() .then(() -> stringEmitter.consumer.accept("A")) .then(() -> stringEmitter.consumer.accept("B")) .then(() -> stringEmitter.consumer.accept("C")) .then(() -> stringEmitter.consumer.accept("D")) .then(() -> stringEmitter.consumer.accept("E")) .then(() -> stringEmitter.consumer.accept("F")) .expectNoEvent(Duration.ofMillis(300)) .thenRequest(6) .expectNext("A", "B", "C", "D", "E", "F") .thenCancel() .verify(); }
### Question: Part4ExtraBackpressure_Optional { @Optional @Complexity(MEDIUM) public static void dynamicDemand(Flux<String> source, CountDownLatch countDownOnComplete) { throw new RuntimeException("Not implemented"); } @Complexity(MEDIUM) static Publisher<String> handleBackpressureWithBuffering(StringEventPublisher stringEventPublisher); @Optional @Complexity(MEDIUM) static void dynamicDemand(Flux<String> source, CountDownLatch countDownOnComplete); }### Answer: @Test public void dynamicDemandTest() throws InterruptedException { int size = 100000; long requests = (long) Math.ceil((Math.log(size) / Math.log(2) + 1e-10)); CountDownLatch latch = new CountDownLatch(1); AtomicInteger iterations = new AtomicInteger(); dynamicDemand( Flux.range(0, size) .map(String::valueOf) .publishOn(Schedulers.single()) .doOnRequest(r -> iterations.incrementAndGet()), latch ); latch.await(5, TimeUnit.SECONDS); assertEquals(requests, iterations.get()); }
### Question: DataUploaderService { @Optional @Complexity(HARD) public Mono<Void> upload(Flux<OrderedByteBuffer> input) { throw new RuntimeException("Not implemented"); } DataUploaderService(HttpClient client); @Optional @Complexity(HARD) Mono<Void> upload(Flux<OrderedByteBuffer> input); }### Answer: @Test public void uploadTest() { TrickyHttpClient client = new TrickyHttpClient(); DataUploaderService service = new DataUploaderService(client); StepVerifier.withVirtualTime(() -> service.upload( Flux.range(0, 1000) .map(i -> new OrderedByteBuffer(i, ByteBuffer.allocate(i))) .window(100) .delayElements(Duration.ofMillis(1500)) .flatMap(Function.identity()) )) .expectSubscription() .thenAwait(Duration.ofSeconds(1000)) .verifyComplete(); verifyOrdered(client); verifyTimeout(client); }
### Question: DefaultPriceService implements PriceService { Flux<MessageDTO<Float>> averagePrice( Flux<Long> requestedInterval, Flux<MessageDTO<Float>> priceData ) { return Flux.never(); } DefaultPriceService(CryptoService cryptoService); Flux<MessageDTO<Float>> pricesStream(Flux<Long> intervalPreferencesStream); }### Answer: @Test @SuppressWarnings("unchecked") public void verifyBuildingAveragePriceEvents() { StepVerifier.withVirtualTime(() -> new DefaultPriceService(cryptoService).averagePrice( Flux.interval(Duration.ofSeconds(0), Duration.ofSeconds(5)) .map(i -> i + 1) .doOnNext(i -> System.out.println("Interval: " + i)), Flux.interval(Duration.ofMillis(500), Duration.ofSeconds(1)) .map(p -> p + 100) .map(tick -> MessageDTO.price((float) tick, "U", "M")) .take(20) .doOnNext(p -> System.out.println("Price: " + p.getData())) .replay(1000) .autoConnect() ) .take(10) .take(Duration.ofHours(1)) .map(MessageDTO::getData) .doOnNext(a -> System.out.println("AVG: " + a)) ) .expectSubscription() .thenAwait(Duration.ofDays(1)) .expectNextMatches(expectedPrice(100.0F)) .expectNextMatches(expectedPrice(101.0F)) .expectNextMatches(expectedPrice(102.0F)) .expectNextMatches(expectedPrice(103.0F)) .expectNextMatches(expectedPrice(104.0F)) .expectNextMatches(expectedPrice(103.0F)) .expectNextMatches(expectedPrice(107.5F)) .expectNextMatches(expectedPrice(109.5F)) .expectNextMatches(expectedPrice(106.0F)) .expectNextMatches(expectedPrice(114.0F)) .verifyComplete(); }
### Question: Part1CreationTransformationTermination { @Complexity(EASY) public static Observable<String> justABC() { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Observable<String> justABC(); @Complexity(EASY) static Observable<String> fromArray(String... args); @Complexity(EASY) static Observable<String> error(Throwable t); @Complexity(EASY) static Observable<Integer> convertNullableValueToObservable(@Nullable Integer nullableElement); @Complexity(EASY) static Observable<String> deferCalculation(Func0<Observable<String>> calculation); @Complexity(EASY) static Observable<Long> interval(long interval, TimeUnit timeUnit); @Complexity(EASY) static Observable<String> mapToString(Observable<Long> input); @Complexity(EASY) static Observable<String> findAllWordsWithPrefixABC(Observable<String> input); @Complexity(MEDIUM) static Observable<String> fromFutureInIOScheduler(Future<String> future); @Complexity(MEDIUM) static void iterateNTimes(int times, AtomicInteger counter); @Complexity(MEDIUM) static Observable<Character> flatMapWordsToCharacters(Observable<String> input); }### Answer: @Test public void justABCTest() { justABC() .test() .assertValue("ABC") .assertCompleted() .awaitTerminalEvent(); }
### Question: Part1CreationTransformationTermination { @Complexity(EASY) public static Observable<String> fromArray(String... args) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Observable<String> justABC(); @Complexity(EASY) static Observable<String> fromArray(String... args); @Complexity(EASY) static Observable<String> error(Throwable t); @Complexity(EASY) static Observable<Integer> convertNullableValueToObservable(@Nullable Integer nullableElement); @Complexity(EASY) static Observable<String> deferCalculation(Func0<Observable<String>> calculation); @Complexity(EASY) static Observable<Long> interval(long interval, TimeUnit timeUnit); @Complexity(EASY) static Observable<String> mapToString(Observable<Long> input); @Complexity(EASY) static Observable<String> findAllWordsWithPrefixABC(Observable<String> input); @Complexity(MEDIUM) static Observable<String> fromFutureInIOScheduler(Future<String> future); @Complexity(MEDIUM) static void iterateNTimes(int times, AtomicInteger counter); @Complexity(MEDIUM) static Observable<Character> flatMapWordsToCharacters(Observable<String> input); }### Answer: @Test public void fromArrayOfABCTest() { fromArray("A", "B", "C") .test() .assertValues("A", "B", "C") .assertCompleted() .awaitTerminalEvent(); }
### Question: Part1CreationTransformationTermination { @Complexity(EASY) public static Observable<String> error(Throwable t) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Observable<String> justABC(); @Complexity(EASY) static Observable<String> fromArray(String... args); @Complexity(EASY) static Observable<String> error(Throwable t); @Complexity(EASY) static Observable<Integer> convertNullableValueToObservable(@Nullable Integer nullableElement); @Complexity(EASY) static Observable<String> deferCalculation(Func0<Observable<String>> calculation); @Complexity(EASY) static Observable<Long> interval(long interval, TimeUnit timeUnit); @Complexity(EASY) static Observable<String> mapToString(Observable<Long> input); @Complexity(EASY) static Observable<String> findAllWordsWithPrefixABC(Observable<String> input); @Complexity(MEDIUM) static Observable<String> fromFutureInIOScheduler(Future<String> future); @Complexity(MEDIUM) static void iterateNTimes(int times, AtomicInteger counter); @Complexity(MEDIUM) static Observable<Character> flatMapWordsToCharacters(Observable<String> input); }### Answer: @Test public void errorObservableTest() { NullPointerException testException = new NullPointerException("test"); error(testException) .test() .assertError(testException) .awaitTerminalEvent(); }
### Question: Part1CreationTransformationTermination { @Complexity(EASY) public static Observable<Integer> convertNullableValueToObservable(@Nullable Integer nullableElement) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Observable<String> justABC(); @Complexity(EASY) static Observable<String> fromArray(String... args); @Complexity(EASY) static Observable<String> error(Throwable t); @Complexity(EASY) static Observable<Integer> convertNullableValueToObservable(@Nullable Integer nullableElement); @Complexity(EASY) static Observable<String> deferCalculation(Func0<Observable<String>> calculation); @Complexity(EASY) static Observable<Long> interval(long interval, TimeUnit timeUnit); @Complexity(EASY) static Observable<String> mapToString(Observable<Long> input); @Complexity(EASY) static Observable<String> findAllWordsWithPrefixABC(Observable<String> input); @Complexity(MEDIUM) static Observable<String> fromFutureInIOScheduler(Future<String> future); @Complexity(MEDIUM) static void iterateNTimes(int times, AtomicInteger counter); @Complexity(MEDIUM) static Observable<Character> flatMapWordsToCharacters(Observable<String> input); }### Answer: @Test public void emptyObservableTest() { convertNullableValueToObservable(1) .test() .assertValue(1) .assertCompleted() .awaitTerminalEvent(); convertNullableValueToObservable(null) .test() .assertNoValues() .assertCompleted() .awaitTerminalEvent(); }
### Question: Part1CreationTransformationTermination { @Complexity(EASY) public static Observable<String> deferCalculation(Func0<Observable<String>> calculation) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Observable<String> justABC(); @Complexity(EASY) static Observable<String> fromArray(String... args); @Complexity(EASY) static Observable<String> error(Throwable t); @Complexity(EASY) static Observable<Integer> convertNullableValueToObservable(@Nullable Integer nullableElement); @Complexity(EASY) static Observable<String> deferCalculation(Func0<Observable<String>> calculation); @Complexity(EASY) static Observable<Long> interval(long interval, TimeUnit timeUnit); @Complexity(EASY) static Observable<String> mapToString(Observable<Long> input); @Complexity(EASY) static Observable<String> findAllWordsWithPrefixABC(Observable<String> input); @Complexity(MEDIUM) static Observable<String> fromFutureInIOScheduler(Future<String> future); @Complexity(MEDIUM) static void iterateNTimes(int times, AtomicInteger counter); @Complexity(MEDIUM) static Observable<Character> flatMapWordsToCharacters(Observable<String> input); }### Answer: @Test @SuppressWarnings("unchecked") public void deferCalculationObservableTest() { Func0<Observable<String>> factory = Mockito.mock(Func0.class); Mockito.when(factory.call()).thenReturn(Observable.just("Hello")).thenReturn(Observable.just("World")); Observable deferCalculation = deferCalculation(factory); Mockito.verifyZeroInteractions(factory); deferCalculation .test() .assertValue("Hello") .assertCompleted() .awaitTerminalEvent(); Mockito.verify(factory).call(); deferCalculation .test() .assertValue("World") .assertCompleted() .awaitTerminalEvent(); Mockito.verify(factory, Mockito.times(2)).call(); }
### Question: Part1CreationTransformationTermination { @Complexity(EASY) public static Observable<Long> interval(long interval, TimeUnit timeUnit) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Observable<String> justABC(); @Complexity(EASY) static Observable<String> fromArray(String... args); @Complexity(EASY) static Observable<String> error(Throwable t); @Complexity(EASY) static Observable<Integer> convertNullableValueToObservable(@Nullable Integer nullableElement); @Complexity(EASY) static Observable<String> deferCalculation(Func0<Observable<String>> calculation); @Complexity(EASY) static Observable<Long> interval(long interval, TimeUnit timeUnit); @Complexity(EASY) static Observable<String> mapToString(Observable<Long> input); @Complexity(EASY) static Observable<String> findAllWordsWithPrefixABC(Observable<String> input); @Complexity(MEDIUM) static Observable<String> fromFutureInIOScheduler(Future<String> future); @Complexity(MEDIUM) static void iterateNTimes(int times, AtomicInteger counter); @Complexity(MEDIUM) static Observable<Character> flatMapWordsToCharacters(Observable<String> input); }### Answer: @Test @SuppressWarnings("unchecked") public void intervalTest() { TestScheduler testScheduler = new TestScheduler(); RxJavaHooks.setOnIOScheduler(s -> testScheduler); RxJavaHooks.setOnComputationScheduler(s -> testScheduler); RxJavaHooks.setOnNewThreadScheduler(s -> testScheduler); interval(1, TimeUnit.MINUTES) .test() .assertNoValues() .perform(() -> testScheduler.advanceTimeBy(1, TimeUnit.MINUTES)) .assertValue(0L) .perform(() -> testScheduler.advanceTimeBy(5, TimeUnit.MINUTES)) .assertValueCount(6) .assertNotCompleted() .awaitTerminalEventAndUnsubscribeOnTimeout(1, TimeUnit.MILLISECONDS); }
### Question: Part1CreationTransformationTermination { @Complexity(EASY) public static Observable<String> mapToString(Observable<Long> input) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Observable<String> justABC(); @Complexity(EASY) static Observable<String> fromArray(String... args); @Complexity(EASY) static Observable<String> error(Throwable t); @Complexity(EASY) static Observable<Integer> convertNullableValueToObservable(@Nullable Integer nullableElement); @Complexity(EASY) static Observable<String> deferCalculation(Func0<Observable<String>> calculation); @Complexity(EASY) static Observable<Long> interval(long interval, TimeUnit timeUnit); @Complexity(EASY) static Observable<String> mapToString(Observable<Long> input); @Complexity(EASY) static Observable<String> findAllWordsWithPrefixABC(Observable<String> input); @Complexity(MEDIUM) static Observable<String> fromFutureInIOScheduler(Future<String> future); @Complexity(MEDIUM) static void iterateNTimes(int times, AtomicInteger counter); @Complexity(MEDIUM) static Observable<Character> flatMapWordsToCharacters(Observable<String> input); }### Answer: @Test public void mapToStringTest() { mapToString(Observable.just(1L, 2L, 3L, 4L)) .test() .assertValues("1", "2", "3", "4") .assertCompleted() .awaitTerminalEvent(); }
### Question: Part1CreationTransformationTermination { @Complexity(EASY) public static Observable<String> findAllWordsWithPrefixABC(Observable<String> input) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Observable<String> justABC(); @Complexity(EASY) static Observable<String> fromArray(String... args); @Complexity(EASY) static Observable<String> error(Throwable t); @Complexity(EASY) static Observable<Integer> convertNullableValueToObservable(@Nullable Integer nullableElement); @Complexity(EASY) static Observable<String> deferCalculation(Func0<Observable<String>> calculation); @Complexity(EASY) static Observable<Long> interval(long interval, TimeUnit timeUnit); @Complexity(EASY) static Observable<String> mapToString(Observable<Long> input); @Complexity(EASY) static Observable<String> findAllWordsWithPrefixABC(Observable<String> input); @Complexity(MEDIUM) static Observable<String> fromFutureInIOScheduler(Future<String> future); @Complexity(MEDIUM) static void iterateNTimes(int times, AtomicInteger counter); @Complexity(MEDIUM) static Observable<Character> flatMapWordsToCharacters(Observable<String> input); }### Answer: @Test public void filterTest() { findAllWordsWithPrefixABC(Observable.just("asdas", "gdfgsdfg", "ABCasda")) .test() .assertValue("ABCasda") .assertCompleted() .awaitTerminalEvent(); }
### Question: Part1CreationTransformationTermination { @Complexity(MEDIUM) public static Observable<String> fromFutureInIOScheduler(Future<String> future) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Observable<String> justABC(); @Complexity(EASY) static Observable<String> fromArray(String... args); @Complexity(EASY) static Observable<String> error(Throwable t); @Complexity(EASY) static Observable<Integer> convertNullableValueToObservable(@Nullable Integer nullableElement); @Complexity(EASY) static Observable<String> deferCalculation(Func0<Observable<String>> calculation); @Complexity(EASY) static Observable<Long> interval(long interval, TimeUnit timeUnit); @Complexity(EASY) static Observable<String> mapToString(Observable<Long> input); @Complexity(EASY) static Observable<String> findAllWordsWithPrefixABC(Observable<String> input); @Complexity(MEDIUM) static Observable<String> fromFutureInIOScheduler(Future<String> future); @Complexity(MEDIUM) static void iterateNTimes(int times, AtomicInteger counter); @Complexity(MEDIUM) static Observable<Character> flatMapWordsToCharacters(Observable<String> input); }### Answer: @Test public void fromFutureTest() { AssertableSubscriber<String> assertable = fromFutureInIOScheduler(CompletableFuture.completedFuture("test")) .test() .awaitValueCount(1, 10, TimeUnit.SECONDS) .assertValue("test") .assertCompleted() .awaitTerminalEvent(); Thread lastSeenThread = assertable.getLastSeenThread(); Assert.assertTrue("Expect execution on I/O thread", lastSeenThread.getName().contains("RxIoScheduler-")); }
### Question: Part1CreationTransformationTermination { @Complexity(MEDIUM) public static void iterateNTimes(int times, AtomicInteger counter) { for (int i = 0; i < times; i++) { counter.incrementAndGet(); } } @Complexity(EASY) static Observable<String> justABC(); @Complexity(EASY) static Observable<String> fromArray(String... args); @Complexity(EASY) static Observable<String> error(Throwable t); @Complexity(EASY) static Observable<Integer> convertNullableValueToObservable(@Nullable Integer nullableElement); @Complexity(EASY) static Observable<String> deferCalculation(Func0<Observable<String>> calculation); @Complexity(EASY) static Observable<Long> interval(long interval, TimeUnit timeUnit); @Complexity(EASY) static Observable<String> mapToString(Observable<Long> input); @Complexity(EASY) static Observable<String> findAllWordsWithPrefixABC(Observable<String> input); @Complexity(MEDIUM) static Observable<String> fromFutureInIOScheduler(Future<String> future); @Complexity(MEDIUM) static void iterateNTimes(int times, AtomicInteger counter); @Complexity(MEDIUM) static Observable<Character> flatMapWordsToCharacters(Observable<String> input); }### Answer: @Test public void iterate10TimesTest() throws Exception { ArgumentCaptor<Integer> captor = ArgumentCaptor.forClass(Integer.class); PowerMockito.spy(Observable.class); PowerMockito .doAnswer(InvocationOnMock::callRealMethod) .when(Observable.class, "range", anyInt(), captor.capture()); AtomicInteger counter = new AtomicInteger(); iterateNTimes(10, counter); Assert.assertEquals("Atomic counter must be increased to 10", 10, counter.get()); Assert.assertEquals("Observable#range(int, int) should be called", 1, captor.getAllValues().size()); }
### Question: DefaultTradeService implements TradeService { Flux<MessageDTO<MessageDTO.Trade>> filterAndMapTradingEvents(Flux<Map<String, Object>> input) { return Flux.never(); } DefaultTradeService(CryptoService service, TradeRepository repository); @Override Flux<MessageDTO<MessageDTO.Trade>> tradesStream(); }### Answer: @Test public void verifyTradeInfoMappingToDTO() { StepVerifier.create( new DefaultTradeService(cryptoService, tradeRepository).filterAndMapTradingEvents( Flux.just( map().put("Invalid", "A").build(), map().put(TYPE_KEY, "1").build(), map().put(TYPE_KEY, "0") .put(TIMESTAMP_KEY, 1F) .put(PRICE_KEY, 0.1F) .put(FLAGS_KEY, "1") .put(QUANTITY_KEY, 1.2F) .put(CURRENCY_KEY, "USD") .put(MARKET_KEY, "External").build() ) ) .take(Duration.ofSeconds(1)) ) .expectNext(MessageDTO.trade(1000, 0.1F, 1.2F, "USD", "External")) .verifyComplete(); }
### Question: Part1CreationTransformationTermination { @Complexity(MEDIUM) public static Observable<Character> flatMapWordsToCharacters(Observable<String> input) { throw new RuntimeException("Not implemented"); } @Complexity(EASY) static Observable<String> justABC(); @Complexity(EASY) static Observable<String> fromArray(String... args); @Complexity(EASY) static Observable<String> error(Throwable t); @Complexity(EASY) static Observable<Integer> convertNullableValueToObservable(@Nullable Integer nullableElement); @Complexity(EASY) static Observable<String> deferCalculation(Func0<Observable<String>> calculation); @Complexity(EASY) static Observable<Long> interval(long interval, TimeUnit timeUnit); @Complexity(EASY) static Observable<String> mapToString(Observable<Long> input); @Complexity(EASY) static Observable<String> findAllWordsWithPrefixABC(Observable<String> input); @Complexity(MEDIUM) static Observable<String> fromFutureInIOScheduler(Future<String> future); @Complexity(MEDIUM) static void iterateNTimes(int times, AtomicInteger counter); @Complexity(MEDIUM) static Observable<Character> flatMapWordsToCharacters(Observable<String> input); }### Answer: @Test public void flatMapWordsToCharactersTest() { flatMapWordsToCharacters(Observable.just("ABC", "DEFG", "HJKL")) .test() .assertValues('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L') .assertCompleted() .awaitTerminalEvent(); }
### Question: Part10CryptoPlatform extends LoggerConfigurationTrait { public static Flux<Long> handleRequestedAveragePriceIntervalValue(Flux<String> requestedInterval) { return Flux.never(); } static void main(String[] args); static Flux<Long> handleRequestedAveragePriceIntervalValue(Flux<String> requestedInterval); static Flux<String> handleOutgoingStreamBackpressure(Flux<String> outgoingStream); }### Answer: @Test public void verifyIncomingMessageValidation() { StepVerifier.create( Part10CryptoPlatform.handleRequestedAveragePriceIntervalValue( Flux.just("Invalid", "32", "", "-1", "1", "0", "5", "62", "5.6", "12") ).take(Duration.ofSeconds(1))) .expectNext(32L, 1L, 5L, 12L) .verifyComplete(); }
### Question: Part10CryptoPlatform extends LoggerConfigurationTrait { public static Flux<String> handleOutgoingStreamBackpressure(Flux<String> outgoingStream) { return outgoingStream; } static void main(String[] args); static Flux<Long> handleRequestedAveragePriceIntervalValue(Flux<String> requestedInterval); static Flux<String> handleOutgoingStreamBackpressure(Flux<String> outgoingStream); }### Answer: @Test public void verifyOutgoingStreamBackpressure() { DirectProcessor<String> processor = DirectProcessor.create(); StepVerifier .create( Part10CryptoPlatform.handleOutgoingStreamBackpressure(processor), 0 ) .expectSubscription() .then(() -> processor.onNext("A")) .then(() -> processor.onNext("B")) .then(() -> processor.onNext("C")) .then(() -> processor.onNext("D")) .then(() -> processor.onNext("E")) .then(() -> processor.onNext("F")) .expectNoEvent(Duration.ofMillis(300)) .thenRequest(6) .expectNext("A", "B", "C", "D", "E", "F") .thenCancel() .verify(); }
### Question: Part2ExtraExercises_Optional { @Optional @Complexity(EASY) public static String firstElementFromSource(Flux<String> source) { throw new RuntimeException("Not implemented"); } @Optional @Complexity(EASY) static String firstElementFromSource(Flux<String> source); @Optional @Complexity(EASY) static Publisher<String> mergeSeveralSourcesSequential(Publisher<String>... sources); @Optional @Complexity(EASY) static Publisher<String> concatSeveralSourcesOrdered(Publisher<String>... sources); @Optional @Complexity(HARD) static Publisher<String> readFile(String filename); }### Answer: @Test public void firstElementFromSourceTest() { String element = firstElementFromSource(Flux.just("Hello", "World")); Assert.assertEquals("Expected 'Hello' but was [" + element + "]", "Hello", element); }
### Question: Part2ExtraExercises_Optional { @Optional @Complexity(EASY) public static Publisher<String> mergeSeveralSourcesSequential(Publisher<String>... sources) { throw new RuntimeException("Not implemented"); } @Optional @Complexity(EASY) static String firstElementFromSource(Flux<String> source); @Optional @Complexity(EASY) static Publisher<String> mergeSeveralSourcesSequential(Publisher<String>... sources); @Optional @Complexity(EASY) static Publisher<String> concatSeveralSourcesOrdered(Publisher<String>... sources); @Optional @Complexity(HARD) static Publisher<String> readFile(String filename); }### Answer: @Test public void mergeSeveralSourcesSequentialTest() { PublisherProbe[] probes = new PublisherProbe[2]; StepVerifier .withVirtualTime(() -> { PublisherProbe<String> probeA = PublisherProbe.of(Mono.fromCallable(() -> "VANILLA").delaySubscription(Duration.ofSeconds(1))); PublisherProbe<String> probeB = PublisherProbe.of(Mono.fromCallable(() -> "CHOCOLATE")); probes[0] = probeA; probes[1] = probeB; return mergeSeveralSourcesSequential( probeA.mono(), probeB.mono() ); }, 0) .expectSubscription() .then(() -> probes[0].assertWasSubscribed()) .then(() -> probes[1].assertWasSubscribed()) .thenRequest(2) .expectNoEvent(Duration.ofSeconds(1)) .expectNext("VANILLA") .expectNext("CHOCOLATE") .verifyComplete(); }
### Question: AccountServiceImpl implements AccountService { @Override @Transactional(readOnly = true) public Optional<Account> getAccountByUsername(String username) { return accountDAO.findByUsername(username); } @Autowired AccountServiceImpl(AccountDAO accountDAO); @Override @Transactional(readOnly = true) Optional<Account> getAccountByUsername(String username); @Override @Transactional(readOnly = true) Collection<AccountDTO> getAccounts(); @Override @Transactional(readOnly = true) Collection<AccountDTO> getAccounts(int offset, int limit); @Override @Transactional(readOnly = true) AccountDTO getAccountById(Long id); @Override @Transactional AccountDTO updateAccount(AccountDTO accountDTO); @Override @Transactional void updatePassword(Long id, String password); @Override @Transactional(readOnly = true) long getTotalCount(); }### Answer: @Test public void shouldGetAccountByUsernameFromDao() throws Exception { String username = "john.doe"; Optional<Account> accountOptional = Optional.empty(); Mockito.when(accountDAO.findByUsername(username)).thenReturn(accountOptional); Optional<Account> result = accountService.getAccountByUsername(username); Assertions.assertThat(result).isSameAs(accountOptional); }
### Question: OrderServiceImpl implements OrderService { @Override public void removeOrderItem(int orderItemIndex) { cart.removeOrderItemById(orderItemIndex); } @Override @Transactional(readOnly = true) Collection<Crust> getCrusts(); @Override @Transactional(readOnly = true) Collection<PizzaSize> getPizzaSizes(); @Override @Transactional(readOnly = true) Collection<BakeStyle> getBakeStyles(); @Override @Transactional(readOnly = true) Collection<CutStyle> getCutStyles(); @Override @Transactional(readOnly = true) Collection<Ingredient> getIngredients(); @Override Collection<Integer> getQuantities(); @Override void addOrderItemToCart(PizzaOrderDTO pizzaOrderDTO); @Override void removeOrderItem(int orderItemIndex); @Override void emptyCart(); @Override void replaceOrderItem(int orderItemIndex, PizzaOrderDTO pizzaOrderDTO); @Override PizzaOrderDTO getPizzaOrderDTOByOrderItemId(int orderItemIndex); @Override @Transactional(readOnly = true) IngredientType getIngredientTypeByIngredientId(Long ingredientId); @Override @Transactional(readOnly = true) Ingredient getIngredientById(Long ingredientId); @Override @Transactional Order postOrder(Order order); @Override @Transactional(readOnly = true) Order getOrderByTrackingNumber(String trackingNumber); @Override @Transactional void addReviewToOrderByTrackingNumber(String trackingNumber, ReviewDTO reviewDTO); @Override @Transactional(readOnly = true) Optional<PizzaOrderDTO> getPizzaOrderDTOByOrderItemId(Long orderItemId); int getMaxQuantity(); void setMaxQuantity(int maxQuantity); int getMinQuantity(); void setMinQuantity(int minQuantity); CrustDAO getCrustDAO(); @Autowired void setCrustDAO(CrustDAO crustDAO); PizzaSizeDAO getPizzaSizeDAO(); @Autowired void setPizzaSizeDAO(PizzaSizeDAO pizzaSizeDAO); BakeStyleDAO getBakeStyleDAO(); @Autowired void setBakeStyleDAO(BakeStyleDAO bakeStyleDAO); CutStyleDAO getCutStyleDAO(); @Autowired void setCutStyleDAO(CutStyleDAO cutStyleDAO); IngredientDAO getIngredientDAO(); @Autowired void setIngredientDAO(IngredientDAO ingredientDAO); OrderDAO getOrderDAO(); @Autowired void setOrderDAO(OrderDAO orderDAO); Cart getCart(); @Autowired void setCart(Cart cart); CustomerDAO getCustomerDAO(); @Autowired void setCustomerDAO(CustomerDAO customerDAO); TrackingNumberGenerationStrategy getTrackingNumberGenerationStrategy(); @Autowired void setTrackingNumberGenerationStrategy(TrackingNumberGenerationStrategy trackingNumberGenerationStrategy); OrderItemDAO getOrderItemDAO(); @Autowired void setOrderItemDAO(OrderItemDAO orderItemDAO); }### Answer: @Test public void shouldRemoveOrderItemAtIndex() throws Exception { int index = 42; orderService.removeOrderItem(index); verify(cart).removeOrderItemById(42); }
### Question: OrderServiceImpl implements OrderService { @Override @Transactional(readOnly = true) public Ingredient getIngredientById(Long ingredientId) { return ingredientDAO.findById(ingredientId).orElseThrow(RuntimeException::new); } @Override @Transactional(readOnly = true) Collection<Crust> getCrusts(); @Override @Transactional(readOnly = true) Collection<PizzaSize> getPizzaSizes(); @Override @Transactional(readOnly = true) Collection<BakeStyle> getBakeStyles(); @Override @Transactional(readOnly = true) Collection<CutStyle> getCutStyles(); @Override @Transactional(readOnly = true) Collection<Ingredient> getIngredients(); @Override Collection<Integer> getQuantities(); @Override void addOrderItemToCart(PizzaOrderDTO pizzaOrderDTO); @Override void removeOrderItem(int orderItemIndex); @Override void emptyCart(); @Override void replaceOrderItem(int orderItemIndex, PizzaOrderDTO pizzaOrderDTO); @Override PizzaOrderDTO getPizzaOrderDTOByOrderItemId(int orderItemIndex); @Override @Transactional(readOnly = true) IngredientType getIngredientTypeByIngredientId(Long ingredientId); @Override @Transactional(readOnly = true) Ingredient getIngredientById(Long ingredientId); @Override @Transactional Order postOrder(Order order); @Override @Transactional(readOnly = true) Order getOrderByTrackingNumber(String trackingNumber); @Override @Transactional void addReviewToOrderByTrackingNumber(String trackingNumber, ReviewDTO reviewDTO); @Override @Transactional(readOnly = true) Optional<PizzaOrderDTO> getPizzaOrderDTOByOrderItemId(Long orderItemId); int getMaxQuantity(); void setMaxQuantity(int maxQuantity); int getMinQuantity(); void setMinQuantity(int minQuantity); CrustDAO getCrustDAO(); @Autowired void setCrustDAO(CrustDAO crustDAO); PizzaSizeDAO getPizzaSizeDAO(); @Autowired void setPizzaSizeDAO(PizzaSizeDAO pizzaSizeDAO); BakeStyleDAO getBakeStyleDAO(); @Autowired void setBakeStyleDAO(BakeStyleDAO bakeStyleDAO); CutStyleDAO getCutStyleDAO(); @Autowired void setCutStyleDAO(CutStyleDAO cutStyleDAO); IngredientDAO getIngredientDAO(); @Autowired void setIngredientDAO(IngredientDAO ingredientDAO); OrderDAO getOrderDAO(); @Autowired void setOrderDAO(OrderDAO orderDAO); Cart getCart(); @Autowired void setCart(Cart cart); CustomerDAO getCustomerDAO(); @Autowired void setCustomerDAO(CustomerDAO customerDAO); TrackingNumberGenerationStrategy getTrackingNumberGenerationStrategy(); @Autowired void setTrackingNumberGenerationStrategy(TrackingNumberGenerationStrategy trackingNumberGenerationStrategy); OrderItemDAO getOrderItemDAO(); @Autowired void setOrderItemDAO(OrderItemDAO orderItemDAO); }### Answer: @Test public void shouldGetIngredientById() throws Exception { Long ingredientId = 42L; Ingredient ingredient = new Ingredient(); ingredient.setId(42L); when(ingredientDAO.findById(ingredientId)).thenReturn(Optional.of(ingredient)); Ingredient result = orderService.getIngredientById(ingredientId); assertThat(result).isSameAs(ingredient); }
### Question: OrderServiceImpl implements OrderService { @Override @Transactional(readOnly = true) public IngredientType getIngredientTypeByIngredientId(Long ingredientId) { return ingredientDAO.findById(ingredientId).orElseThrow(RuntimeException::new).getIngredientType(); } @Override @Transactional(readOnly = true) Collection<Crust> getCrusts(); @Override @Transactional(readOnly = true) Collection<PizzaSize> getPizzaSizes(); @Override @Transactional(readOnly = true) Collection<BakeStyle> getBakeStyles(); @Override @Transactional(readOnly = true) Collection<CutStyle> getCutStyles(); @Override @Transactional(readOnly = true) Collection<Ingredient> getIngredients(); @Override Collection<Integer> getQuantities(); @Override void addOrderItemToCart(PizzaOrderDTO pizzaOrderDTO); @Override void removeOrderItem(int orderItemIndex); @Override void emptyCart(); @Override void replaceOrderItem(int orderItemIndex, PizzaOrderDTO pizzaOrderDTO); @Override PizzaOrderDTO getPizzaOrderDTOByOrderItemId(int orderItemIndex); @Override @Transactional(readOnly = true) IngredientType getIngredientTypeByIngredientId(Long ingredientId); @Override @Transactional(readOnly = true) Ingredient getIngredientById(Long ingredientId); @Override @Transactional Order postOrder(Order order); @Override @Transactional(readOnly = true) Order getOrderByTrackingNumber(String trackingNumber); @Override @Transactional void addReviewToOrderByTrackingNumber(String trackingNumber, ReviewDTO reviewDTO); @Override @Transactional(readOnly = true) Optional<PizzaOrderDTO> getPizzaOrderDTOByOrderItemId(Long orderItemId); int getMaxQuantity(); void setMaxQuantity(int maxQuantity); int getMinQuantity(); void setMinQuantity(int minQuantity); CrustDAO getCrustDAO(); @Autowired void setCrustDAO(CrustDAO crustDAO); PizzaSizeDAO getPizzaSizeDAO(); @Autowired void setPizzaSizeDAO(PizzaSizeDAO pizzaSizeDAO); BakeStyleDAO getBakeStyleDAO(); @Autowired void setBakeStyleDAO(BakeStyleDAO bakeStyleDAO); CutStyleDAO getCutStyleDAO(); @Autowired void setCutStyleDAO(CutStyleDAO cutStyleDAO); IngredientDAO getIngredientDAO(); @Autowired void setIngredientDAO(IngredientDAO ingredientDAO); OrderDAO getOrderDAO(); @Autowired void setOrderDAO(OrderDAO orderDAO); Cart getCart(); @Autowired void setCart(Cart cart); CustomerDAO getCustomerDAO(); @Autowired void setCustomerDAO(CustomerDAO customerDAO); TrackingNumberGenerationStrategy getTrackingNumberGenerationStrategy(); @Autowired void setTrackingNumberGenerationStrategy(TrackingNumberGenerationStrategy trackingNumberGenerationStrategy); OrderItemDAO getOrderItemDAO(); @Autowired void setOrderItemDAO(OrderItemDAO orderItemDAO); }### Answer: @Test public void shouldGetIngredientTypeByIngredientId() throws Exception { IngredientType ingredientType = new IngredientType(); Long ingredientId = 42L; Ingredient ingredient = new Ingredient(); ingredient.setId(ingredientId); ingredient.setIngredientType(ingredientType); when(ingredientDAO.findById(ingredientId)).thenReturn(Optional.of(ingredient)); IngredientType result = orderService.getIngredientTypeByIngredientId(ingredientId); assertThat(result).isSameAs(ingredientType); }
### Question: OrderServiceImpl implements OrderService { @Override @Transactional public Order postOrder(Order order) { OrderEvent orderEvent = new OrderEvent(); orderEvent.setOccurredOn(Instant.now()); orderEvent.setOrderEventType(OrderEventType.PURCHASED); order.getOrderEvents().add(orderEvent); order = orderDAO.saveOrUpdate(order); order.setTrackingNumber(trackingNumberGenerationStrategy.generatetrackingNumber(order)); return order; } @Override @Transactional(readOnly = true) Collection<Crust> getCrusts(); @Override @Transactional(readOnly = true) Collection<PizzaSize> getPizzaSizes(); @Override @Transactional(readOnly = true) Collection<BakeStyle> getBakeStyles(); @Override @Transactional(readOnly = true) Collection<CutStyle> getCutStyles(); @Override @Transactional(readOnly = true) Collection<Ingredient> getIngredients(); @Override Collection<Integer> getQuantities(); @Override void addOrderItemToCart(PizzaOrderDTO pizzaOrderDTO); @Override void removeOrderItem(int orderItemIndex); @Override void emptyCart(); @Override void replaceOrderItem(int orderItemIndex, PizzaOrderDTO pizzaOrderDTO); @Override PizzaOrderDTO getPizzaOrderDTOByOrderItemId(int orderItemIndex); @Override @Transactional(readOnly = true) IngredientType getIngredientTypeByIngredientId(Long ingredientId); @Override @Transactional(readOnly = true) Ingredient getIngredientById(Long ingredientId); @Override @Transactional Order postOrder(Order order); @Override @Transactional(readOnly = true) Order getOrderByTrackingNumber(String trackingNumber); @Override @Transactional void addReviewToOrderByTrackingNumber(String trackingNumber, ReviewDTO reviewDTO); @Override @Transactional(readOnly = true) Optional<PizzaOrderDTO> getPizzaOrderDTOByOrderItemId(Long orderItemId); int getMaxQuantity(); void setMaxQuantity(int maxQuantity); int getMinQuantity(); void setMinQuantity(int minQuantity); CrustDAO getCrustDAO(); @Autowired void setCrustDAO(CrustDAO crustDAO); PizzaSizeDAO getPizzaSizeDAO(); @Autowired void setPizzaSizeDAO(PizzaSizeDAO pizzaSizeDAO); BakeStyleDAO getBakeStyleDAO(); @Autowired void setBakeStyleDAO(BakeStyleDAO bakeStyleDAO); CutStyleDAO getCutStyleDAO(); @Autowired void setCutStyleDAO(CutStyleDAO cutStyleDAO); IngredientDAO getIngredientDAO(); @Autowired void setIngredientDAO(IngredientDAO ingredientDAO); OrderDAO getOrderDAO(); @Autowired void setOrderDAO(OrderDAO orderDAO); Cart getCart(); @Autowired void setCart(Cart cart); CustomerDAO getCustomerDAO(); @Autowired void setCustomerDAO(CustomerDAO customerDAO); TrackingNumberGenerationStrategy getTrackingNumberGenerationStrategy(); @Autowired void setTrackingNumberGenerationStrategy(TrackingNumberGenerationStrategy trackingNumberGenerationStrategy); OrderItemDAO getOrderItemDAO(); @Autowired void setOrderItemDAO(OrderItemDAO orderItemDAO); }### Answer: @Test public void shouldPostOrder() throws Exception { Order order = new Order(); String trackingNumber = "42"; Long orderId = 42L; when(trackingNumberGenerationStrategy.generatetrackingNumber(order)).thenReturn(trackingNumber); when(orderDAO.saveOrUpdate(order)).thenAnswer(invocation -> { order.setId(orderId); return order; }); Order result = orderService.postOrder(order); assertThat(result.getId()).isEqualTo(orderId); assertThat(result.getTrackingNumber()).isEqualTo(trackingNumber); Condition<OrderEvent> purchaseEvent = new Condition<>(orderEvent -> orderEvent.getOrderEventType() == OrderEventType.PURCHASED, "purchase event"); assertThat(result.getOrderEvents()).first().is(purchaseEvent); }
### Question: OrderServiceImpl implements OrderService { @Override @Transactional(readOnly = true) public Order getOrderByTrackingNumber(String trackingNumber) { return orderDAO.findByTrackingNumber(trackingNumber).orElseThrow(OrderNotFoundException::new); } @Override @Transactional(readOnly = true) Collection<Crust> getCrusts(); @Override @Transactional(readOnly = true) Collection<PizzaSize> getPizzaSizes(); @Override @Transactional(readOnly = true) Collection<BakeStyle> getBakeStyles(); @Override @Transactional(readOnly = true) Collection<CutStyle> getCutStyles(); @Override @Transactional(readOnly = true) Collection<Ingredient> getIngredients(); @Override Collection<Integer> getQuantities(); @Override void addOrderItemToCart(PizzaOrderDTO pizzaOrderDTO); @Override void removeOrderItem(int orderItemIndex); @Override void emptyCart(); @Override void replaceOrderItem(int orderItemIndex, PizzaOrderDTO pizzaOrderDTO); @Override PizzaOrderDTO getPizzaOrderDTOByOrderItemId(int orderItemIndex); @Override @Transactional(readOnly = true) IngredientType getIngredientTypeByIngredientId(Long ingredientId); @Override @Transactional(readOnly = true) Ingredient getIngredientById(Long ingredientId); @Override @Transactional Order postOrder(Order order); @Override @Transactional(readOnly = true) Order getOrderByTrackingNumber(String trackingNumber); @Override @Transactional void addReviewToOrderByTrackingNumber(String trackingNumber, ReviewDTO reviewDTO); @Override @Transactional(readOnly = true) Optional<PizzaOrderDTO> getPizzaOrderDTOByOrderItemId(Long orderItemId); int getMaxQuantity(); void setMaxQuantity(int maxQuantity); int getMinQuantity(); void setMinQuantity(int minQuantity); CrustDAO getCrustDAO(); @Autowired void setCrustDAO(CrustDAO crustDAO); PizzaSizeDAO getPizzaSizeDAO(); @Autowired void setPizzaSizeDAO(PizzaSizeDAO pizzaSizeDAO); BakeStyleDAO getBakeStyleDAO(); @Autowired void setBakeStyleDAO(BakeStyleDAO bakeStyleDAO); CutStyleDAO getCutStyleDAO(); @Autowired void setCutStyleDAO(CutStyleDAO cutStyleDAO); IngredientDAO getIngredientDAO(); @Autowired void setIngredientDAO(IngredientDAO ingredientDAO); OrderDAO getOrderDAO(); @Autowired void setOrderDAO(OrderDAO orderDAO); Cart getCart(); @Autowired void setCart(Cart cart); CustomerDAO getCustomerDAO(); @Autowired void setCustomerDAO(CustomerDAO customerDAO); TrackingNumberGenerationStrategy getTrackingNumberGenerationStrategy(); @Autowired void setTrackingNumberGenerationStrategy(TrackingNumberGenerationStrategy trackingNumberGenerationStrategy); OrderItemDAO getOrderItemDAO(); @Autowired void setOrderItemDAO(OrderItemDAO orderItemDAO); }### Answer: @Test public void shouldGetOrderByTrackingNumber() throws Exception { String trackingNumber = "ABCDEF"; Order order = new Order(); when(orderDAO.findByTrackingNumber(trackingNumber)).thenReturn(Optional.of(order)); Order result = orderService.getOrderByTrackingNumber(trackingNumber); assertThat(result).isSameAs(order); }
### Question: OrderServiceImpl implements OrderService { @Override @Transactional public void addReviewToOrderByTrackingNumber(String trackingNumber, ReviewDTO reviewDTO) { Order order = orderDAO.findByTrackingNumber(trackingNumber).orElseThrow(OrderNotFoundException::new); Review review = Optional.ofNullable(order.getReview()).orElseGet(Review::new); review.setOrder(order); review.setMessage(reviewDTO.getMessage()); review.setRating(reviewDTO.getRating()); review.setImages(reviewDTO.getFiles()); order.setReview(review); } @Override @Transactional(readOnly = true) Collection<Crust> getCrusts(); @Override @Transactional(readOnly = true) Collection<PizzaSize> getPizzaSizes(); @Override @Transactional(readOnly = true) Collection<BakeStyle> getBakeStyles(); @Override @Transactional(readOnly = true) Collection<CutStyle> getCutStyles(); @Override @Transactional(readOnly = true) Collection<Ingredient> getIngredients(); @Override Collection<Integer> getQuantities(); @Override void addOrderItemToCart(PizzaOrderDTO pizzaOrderDTO); @Override void removeOrderItem(int orderItemIndex); @Override void emptyCart(); @Override void replaceOrderItem(int orderItemIndex, PizzaOrderDTO pizzaOrderDTO); @Override PizzaOrderDTO getPizzaOrderDTOByOrderItemId(int orderItemIndex); @Override @Transactional(readOnly = true) IngredientType getIngredientTypeByIngredientId(Long ingredientId); @Override @Transactional(readOnly = true) Ingredient getIngredientById(Long ingredientId); @Override @Transactional Order postOrder(Order order); @Override @Transactional(readOnly = true) Order getOrderByTrackingNumber(String trackingNumber); @Override @Transactional void addReviewToOrderByTrackingNumber(String trackingNumber, ReviewDTO reviewDTO); @Override @Transactional(readOnly = true) Optional<PizzaOrderDTO> getPizzaOrderDTOByOrderItemId(Long orderItemId); int getMaxQuantity(); void setMaxQuantity(int maxQuantity); int getMinQuantity(); void setMinQuantity(int minQuantity); CrustDAO getCrustDAO(); @Autowired void setCrustDAO(CrustDAO crustDAO); PizzaSizeDAO getPizzaSizeDAO(); @Autowired void setPizzaSizeDAO(PizzaSizeDAO pizzaSizeDAO); BakeStyleDAO getBakeStyleDAO(); @Autowired void setBakeStyleDAO(BakeStyleDAO bakeStyleDAO); CutStyleDAO getCutStyleDAO(); @Autowired void setCutStyleDAO(CutStyleDAO cutStyleDAO); IngredientDAO getIngredientDAO(); @Autowired void setIngredientDAO(IngredientDAO ingredientDAO); OrderDAO getOrderDAO(); @Autowired void setOrderDAO(OrderDAO orderDAO); Cart getCart(); @Autowired void setCart(Cart cart); CustomerDAO getCustomerDAO(); @Autowired void setCustomerDAO(CustomerDAO customerDAO); TrackingNumberGenerationStrategy getTrackingNumberGenerationStrategy(); @Autowired void setTrackingNumberGenerationStrategy(TrackingNumberGenerationStrategy trackingNumberGenerationStrategy); OrderItemDAO getOrderItemDAO(); @Autowired void setOrderItemDAO(OrderItemDAO orderItemDAO); }### Answer: @Test public void shouldAddReviewToOrderByTrackingNumber() throws Exception { int rating = 9; String message = "a review message"; ReviewDTO reviewDTO = new ReviewDTO(); reviewDTO.setMessage(message); reviewDTO.setRating(rating); File file = new File(); file.setName("image.jpg"); file.setContentType("image/jpeg"); reviewDTO.setFiles(ImmutableList.of(file)); String trackingNumber = "ABCDEF"; Order order = new Order(); when(orderDAO.findByTrackingNumber(trackingNumber)).thenReturn(Optional.of(order)); orderService.addReviewToOrderByTrackingNumber(trackingNumber, reviewDTO); Review expected = new Review(); expected.setOrder(order); expected.setRating(rating); expected.setMessage(message); expected.setImages(ImmutableList.of(file)); assertThat(order.getReview()).isEqualToComparingFieldByField(expected); }
### Question: OrderCostCalculationServiceImpl implements OrderCostCalculationService { @Override public MonetaryAmount calculateCost(Order order) { return order.getOrderItems().stream() .map(OrderCostCalculationServiceImpl::calculateOrderItemCost) .reduce(ZERO, MonetaryAmount::add); } @Override MonetaryAmount calculateCost(Order order); }### Answer: @Test public void shouldCalculateCost() throws Exception { OrderCostCalculationServiceImpl orderCostCalculationService = new OrderCostCalculationServiceImpl(); Order order = createOrder(); MonetaryAmount result = orderCostCalculationService.calculateCost(order); Assertions.assertThat(result).isEqualTo(fromDouble(99)); }
### Question: CustomerRegistrationServiceImpl implements CustomerRegistrationService { @Override @Transactional public void processRegistration(CustomerRegistrationDTO customerRegistrationDTO) { Customer customer = createCustomerFromCustomerRegistrationDTO(customerRegistrationDTO); Account account = createAccountFromCustomerRegistrationDTO(customerRegistrationDTO); account.setUser(customer); customer.setAccount(account); accountDAO.saveOrUpdate(account); } @Autowired CustomerRegistrationServiceImpl(AccountDAO accountDAO); @Override @Transactional void processRegistration(CustomerRegistrationDTO customerRegistrationDTO); AccountDAO getAccountDAO(); void setAccountDAO(AccountDAO accountDAO); }### Answer: @Test public void shouldProcessRegistration() throws Exception { CustomerRegistrationDTO customerRegistrationDTO = createCustomerRegistrationDTO(); customerRegistrationService.processRegistration(customerRegistrationDTO); ArgumentCaptor<Account> accountArgumentCaptor = ArgumentCaptor.forClass(Account.class); verify(accountDAO).saveOrUpdate(accountArgumentCaptor.capture()); Account result = accountArgumentCaptor.getValue(); Account expected = createExpectedAccount(); assertThat(result).isEqualToComparingFieldByFieldRecursively(expected); }
### Question: FileSystemFileStorageService extends AbstractDaoFileStorageService { public String getDirectory() { return directory; } @Autowired FileSystemFileStorageService(FileDAO fileDAO); @Override InputStream getFileAsInputStream(String name); String getDirectory(); void setDirectory(String directory); }### Answer: @Test public void shouldSaveFileWithoutNameProvided() throws Exception { InputStream inputStream = new ReaderInputStream(new StringReader(CONTENT)); when(fileDAO.saveOrUpdate(ArgumentMatchers.any(File.class))).thenAnswer(invocation -> invocation.getArgument(0)); File result = fileSystemFileStorageService.saveFile(inputStream, CONTENT_TYPE); verify(fileDAO).saveOrUpdate(ArgumentMatchers.any(File.class)); assertThat(result.getName()).isNotBlank(); assertThat(result.getContentType()).isEqualTo(CONTENT_TYPE); Path savedFilePath = Paths.get(fileSystemFileStorageService.getDirectory(), result.getName()); assertThat(savedFilePath).hasContent(CONTENT); } @Test public void shouldSaveFileWithNameProvided() throws Exception { InputStream inputStream = new ReaderInputStream(new StringReader(CONTENT)); when(fileDAO.saveOrUpdate(ArgumentMatchers.any(File.class))).thenAnswer(invocation -> invocation.getArgument(0)); File result = fileSystemFileStorageService.saveFile(inputStream, FILE_NAME, CONTENT_TYPE); verify(fileDAO).saveOrUpdate(ArgumentMatchers.any(File.class)); assertThat(result.getName()).isEqualTo(FILE_NAME); assertThat(result.getContentType()).isEqualTo(CONTENT_TYPE); Path savedFilePath = Paths.get(fileSystemFileStorageService.getDirectory(), FILE_NAME); assertThat(savedFilePath).hasContent(CONTENT); }
### Question: ReviewServiceImpl implements ReviewService { @Override @Transactional(readOnly = true) public List<Review> getReviews() { return reviewDAO.findAll(); } @Autowired ReviewServiceImpl(ReviewDAO reviewDAO); @Override @Transactional(readOnly = true) List<Review> getReviews(); @Override @Transactional(readOnly = true) List<Review> getReviews(int offset, int limit); @Override @Transactional(readOnly = true) long getTotalCount(); }### Answer: @Test public void shouldGetReviews() throws Exception { ImmutableList<Review> reviews = ImmutableList.of(); Mockito.when(reviewDAO.findAll()).thenReturn(reviews); List<Review> result = reviewService.getReviews(); assertThat(result).isSameAs(reviews); }
### Question: CustomerServiceImpl implements CustomerService { @Override @Transactional(readOnly = true) public Optional<Customer> getCustomerByUsername(String username) { Optional<Account> accountOptional = accountDAO.findByUsername(username); return accountOptional.flatMap(account -> customerDAO.findById(account.getUser().getId())); } @Override @Transactional(readOnly = true) Optional<Customer> getCustomerByUsername(String username); @Override Customer createNewCustomer(); @Override @Transactional void updateCustomer(Customer customer); CustomerDAO getCustomerDAO(); @Autowired void setCustomerDAO(CustomerDAO customerDAO); AccountDAO getAccountDAO(); @Autowired void setAccountDAO(AccountDAO accountDAO); }### Answer: @Test public void shouldGetCustomerByUsername() throws Exception { String username = "john.doe"; Long customerId = 42L; Customer customer = new Customer(); customer.setId(customerId); Account account = new Account(); account.setUser(customer); Mockito.when(accountDAO.findByUsername(username)).thenReturn(Optional.of(account)); Mockito.when(customerDAO.findById(customerId)).thenReturn(Optional.of(customer)); Optional<Customer> result = userService.getCustomerByUsername(username); assertThat(result).contains(customer); } @Test public void shouldReturnEmptyOptionalWhenAccountIsNotFound() throws Exception { Mockito.when(accountDAO.findByUsername(ArgumentMatchers.anyString())).thenReturn(Optional.empty()); Optional<Customer> result = userService.getCustomerByUsername("john"); assertThat(result).isEmpty(); }
### Question: CustomerServiceImpl implements CustomerService { @Override public Customer createNewCustomer() { return new Customer(); } @Override @Transactional(readOnly = true) Optional<Customer> getCustomerByUsername(String username); @Override Customer createNewCustomer(); @Override @Transactional void updateCustomer(Customer customer); CustomerDAO getCustomerDAO(); @Autowired void setCustomerDAO(CustomerDAO customerDAO); AccountDAO getAccountDAO(); @Autowired void setAccountDAO(AccountDAO accountDAO); }### Answer: @Test public void shouldCreateNewCustomer() throws Exception { Customer result = userService.createNewCustomer(); assertThat(result).isEqualToComparingFieldByFieldRecursively(new Customer()); }
### Question: CustomerServiceImpl implements CustomerService { @Override @Transactional public void updateCustomer(Customer customer) { customerDAO.saveOrUpdate(customer); } @Override @Transactional(readOnly = true) Optional<Customer> getCustomerByUsername(String username); @Override Customer createNewCustomer(); @Override @Transactional void updateCustomer(Customer customer); CustomerDAO getCustomerDAO(); @Autowired void setCustomerDAO(CustomerDAO customerDAO); AccountDAO getAccountDAO(); @Autowired void setAccountDAO(AccountDAO accountDAO); }### Answer: @Test public void shouldUpdateCustomer() throws Exception { Customer customer = new Customer(); userService.updateCustomer(customer); ArgumentCaptor<Customer> customerArgumentCaptor = ArgumentCaptor.forClass(Customer.class); verify(customerDAO).saveOrUpdate(customerArgumentCaptor.capture()); assertThat(customerArgumentCaptor.getValue()).isSameAs(customer); }
### Question: OrderItemTemplateServiceImpl implements OrderItemTemplateService { @Override public Collection<OrderItemTemplate> getOrderItemTemplates() { return orderItemTemplateDAO.findAll(); } @Autowired OrderItemTemplateServiceImpl(OrderItemTemplateDAO orderItemTemplateDAO); @Override Collection<OrderItemTemplate> getOrderItemTemplates(); }### Answer: @Test public void shouldGetOrderItemTemplates() throws Exception { ImmutableList<OrderItemTemplate> orderItemTemplates = ImmutableList.of(); Mockito.when(orderItemTemplateDAO.findAll()).thenReturn(orderItemTemplates); Collection<OrderItemTemplate> result = orderItemTemplateService.getOrderItemTemplates(); Assertions.assertThat(result).isSameAs(orderItemTemplates); }
### Question: DeliveryCostCalculationServiceImpl implements DeliveryCostCalculationService { @Override public MonetaryAmount calculateCost(Delivery delivery) { return Optional.ofNullable(delivery).map(deliveryCostCalculationStrategy::calculateCost) .orElse(Money.of(0, "USD")); } @Autowired DeliveryCostCalculationServiceImpl(DeliveryCostCalculationStrategy deliveryCostCalculationStrategy); @Override MonetaryAmount calculateCost(Delivery delivery); }### Answer: @Test public void shouldCalculateCost() throws Exception { Delivery delivery = new Delivery(); MonetaryAmount cost = Monetary.getDefaultAmountFactory().setNumber(9.99).setCurrency("USD").create(); Mockito.when(deliveryCostCalculationStrategy.calculateCost(delivery)).thenReturn(cost); MonetaryAmount result = deliveryCostCalculationService.calculateCost(delivery); Assertions.assertThat(result).isEqualTo(cost); }
### Question: OrderServiceImpl implements OrderService { @Override @Transactional(readOnly = true) public Collection<Crust> getCrusts() { return crustDAO.findAll(); } @Override @Transactional(readOnly = true) Collection<Crust> getCrusts(); @Override @Transactional(readOnly = true) Collection<PizzaSize> getPizzaSizes(); @Override @Transactional(readOnly = true) Collection<BakeStyle> getBakeStyles(); @Override @Transactional(readOnly = true) Collection<CutStyle> getCutStyles(); @Override @Transactional(readOnly = true) Collection<Ingredient> getIngredients(); @Override Collection<Integer> getQuantities(); @Override void addOrderItemToCart(PizzaOrderDTO pizzaOrderDTO); @Override void removeOrderItem(int orderItemIndex); @Override void emptyCart(); @Override void replaceOrderItem(int orderItemIndex, PizzaOrderDTO pizzaOrderDTO); @Override PizzaOrderDTO getPizzaOrderDTOByOrderItemId(int orderItemIndex); @Override @Transactional(readOnly = true) IngredientType getIngredientTypeByIngredientId(Long ingredientId); @Override @Transactional(readOnly = true) Ingredient getIngredientById(Long ingredientId); @Override @Transactional Order postOrder(Order order); @Override @Transactional(readOnly = true) Order getOrderByTrackingNumber(String trackingNumber); @Override @Transactional void addReviewToOrderByTrackingNumber(String trackingNumber, ReviewDTO reviewDTO); @Override @Transactional(readOnly = true) Optional<PizzaOrderDTO> getPizzaOrderDTOByOrderItemId(Long orderItemId); int getMaxQuantity(); void setMaxQuantity(int maxQuantity); int getMinQuantity(); void setMinQuantity(int minQuantity); CrustDAO getCrustDAO(); @Autowired void setCrustDAO(CrustDAO crustDAO); PizzaSizeDAO getPizzaSizeDAO(); @Autowired void setPizzaSizeDAO(PizzaSizeDAO pizzaSizeDAO); BakeStyleDAO getBakeStyleDAO(); @Autowired void setBakeStyleDAO(BakeStyleDAO bakeStyleDAO); CutStyleDAO getCutStyleDAO(); @Autowired void setCutStyleDAO(CutStyleDAO cutStyleDAO); IngredientDAO getIngredientDAO(); @Autowired void setIngredientDAO(IngredientDAO ingredientDAO); OrderDAO getOrderDAO(); @Autowired void setOrderDAO(OrderDAO orderDAO); Cart getCart(); @Autowired void setCart(Cart cart); CustomerDAO getCustomerDAO(); @Autowired void setCustomerDAO(CustomerDAO customerDAO); TrackingNumberGenerationStrategy getTrackingNumberGenerationStrategy(); @Autowired void setTrackingNumberGenerationStrategy(TrackingNumberGenerationStrategy trackingNumberGenerationStrategy); OrderItemDAO getOrderItemDAO(); @Autowired void setOrderItemDAO(OrderItemDAO orderItemDAO); }### Answer: @Test public void shouldGetCrustsFromDAO() throws Exception { List<Crust> crusts = ImmutableList.of(); when(crustDAO.findAll()).thenReturn(crusts); Collection<Crust> result = orderService.getCrusts(); assertThat(result).isSameAs(crusts); }
### Question: OrderServiceImpl implements OrderService { @Override @Transactional(readOnly = true) public Collection<PizzaSize> getPizzaSizes() { return pizzaSizeDAO.findAll(); } @Override @Transactional(readOnly = true) Collection<Crust> getCrusts(); @Override @Transactional(readOnly = true) Collection<PizzaSize> getPizzaSizes(); @Override @Transactional(readOnly = true) Collection<BakeStyle> getBakeStyles(); @Override @Transactional(readOnly = true) Collection<CutStyle> getCutStyles(); @Override @Transactional(readOnly = true) Collection<Ingredient> getIngredients(); @Override Collection<Integer> getQuantities(); @Override void addOrderItemToCart(PizzaOrderDTO pizzaOrderDTO); @Override void removeOrderItem(int orderItemIndex); @Override void emptyCart(); @Override void replaceOrderItem(int orderItemIndex, PizzaOrderDTO pizzaOrderDTO); @Override PizzaOrderDTO getPizzaOrderDTOByOrderItemId(int orderItemIndex); @Override @Transactional(readOnly = true) IngredientType getIngredientTypeByIngredientId(Long ingredientId); @Override @Transactional(readOnly = true) Ingredient getIngredientById(Long ingredientId); @Override @Transactional Order postOrder(Order order); @Override @Transactional(readOnly = true) Order getOrderByTrackingNumber(String trackingNumber); @Override @Transactional void addReviewToOrderByTrackingNumber(String trackingNumber, ReviewDTO reviewDTO); @Override @Transactional(readOnly = true) Optional<PizzaOrderDTO> getPizzaOrderDTOByOrderItemId(Long orderItemId); int getMaxQuantity(); void setMaxQuantity(int maxQuantity); int getMinQuantity(); void setMinQuantity(int minQuantity); CrustDAO getCrustDAO(); @Autowired void setCrustDAO(CrustDAO crustDAO); PizzaSizeDAO getPizzaSizeDAO(); @Autowired void setPizzaSizeDAO(PizzaSizeDAO pizzaSizeDAO); BakeStyleDAO getBakeStyleDAO(); @Autowired void setBakeStyleDAO(BakeStyleDAO bakeStyleDAO); CutStyleDAO getCutStyleDAO(); @Autowired void setCutStyleDAO(CutStyleDAO cutStyleDAO); IngredientDAO getIngredientDAO(); @Autowired void setIngredientDAO(IngredientDAO ingredientDAO); OrderDAO getOrderDAO(); @Autowired void setOrderDAO(OrderDAO orderDAO); Cart getCart(); @Autowired void setCart(Cart cart); CustomerDAO getCustomerDAO(); @Autowired void setCustomerDAO(CustomerDAO customerDAO); TrackingNumberGenerationStrategy getTrackingNumberGenerationStrategy(); @Autowired void setTrackingNumberGenerationStrategy(TrackingNumberGenerationStrategy trackingNumberGenerationStrategy); OrderItemDAO getOrderItemDAO(); @Autowired void setOrderItemDAO(OrderItemDAO orderItemDAO); }### Answer: @Test public void shouldGetPizzaSizesFromDAO() throws Exception { List<PizzaSize> pizzaSizes = ImmutableList.of(); when(pizzaSizeDAO.findAll()).thenReturn(pizzaSizes); Collection<PizzaSize> result = orderService.getPizzaSizes(); assertThat(result).isSameAs(pizzaSizes); }
### Question: OrderServiceImpl implements OrderService { @Override @Transactional(readOnly = true) public Collection<BakeStyle> getBakeStyles() { return bakeStyleDAO.findAll(); } @Override @Transactional(readOnly = true) Collection<Crust> getCrusts(); @Override @Transactional(readOnly = true) Collection<PizzaSize> getPizzaSizes(); @Override @Transactional(readOnly = true) Collection<BakeStyle> getBakeStyles(); @Override @Transactional(readOnly = true) Collection<CutStyle> getCutStyles(); @Override @Transactional(readOnly = true) Collection<Ingredient> getIngredients(); @Override Collection<Integer> getQuantities(); @Override void addOrderItemToCart(PizzaOrderDTO pizzaOrderDTO); @Override void removeOrderItem(int orderItemIndex); @Override void emptyCart(); @Override void replaceOrderItem(int orderItemIndex, PizzaOrderDTO pizzaOrderDTO); @Override PizzaOrderDTO getPizzaOrderDTOByOrderItemId(int orderItemIndex); @Override @Transactional(readOnly = true) IngredientType getIngredientTypeByIngredientId(Long ingredientId); @Override @Transactional(readOnly = true) Ingredient getIngredientById(Long ingredientId); @Override @Transactional Order postOrder(Order order); @Override @Transactional(readOnly = true) Order getOrderByTrackingNumber(String trackingNumber); @Override @Transactional void addReviewToOrderByTrackingNumber(String trackingNumber, ReviewDTO reviewDTO); @Override @Transactional(readOnly = true) Optional<PizzaOrderDTO> getPizzaOrderDTOByOrderItemId(Long orderItemId); int getMaxQuantity(); void setMaxQuantity(int maxQuantity); int getMinQuantity(); void setMinQuantity(int minQuantity); CrustDAO getCrustDAO(); @Autowired void setCrustDAO(CrustDAO crustDAO); PizzaSizeDAO getPizzaSizeDAO(); @Autowired void setPizzaSizeDAO(PizzaSizeDAO pizzaSizeDAO); BakeStyleDAO getBakeStyleDAO(); @Autowired void setBakeStyleDAO(BakeStyleDAO bakeStyleDAO); CutStyleDAO getCutStyleDAO(); @Autowired void setCutStyleDAO(CutStyleDAO cutStyleDAO); IngredientDAO getIngredientDAO(); @Autowired void setIngredientDAO(IngredientDAO ingredientDAO); OrderDAO getOrderDAO(); @Autowired void setOrderDAO(OrderDAO orderDAO); Cart getCart(); @Autowired void setCart(Cart cart); CustomerDAO getCustomerDAO(); @Autowired void setCustomerDAO(CustomerDAO customerDAO); TrackingNumberGenerationStrategy getTrackingNumberGenerationStrategy(); @Autowired void setTrackingNumberGenerationStrategy(TrackingNumberGenerationStrategy trackingNumberGenerationStrategy); OrderItemDAO getOrderItemDAO(); @Autowired void setOrderItemDAO(OrderItemDAO orderItemDAO); }### Answer: @Test public void shouldGetBakeStylesFromDAO() throws Exception { List<BakeStyle> bakeStyles = ImmutableList.of(); when(bakeStyleDAO.findAll()).thenReturn(bakeStyles); Collection<BakeStyle> result = orderService.getBakeStyles(); assertThat(result).isSameAs(bakeStyles); }
### Question: OrderServiceImpl implements OrderService { @Override @Transactional(readOnly = true) public Collection<CutStyle> getCutStyles() { return cutStyleDAO.findAll(); } @Override @Transactional(readOnly = true) Collection<Crust> getCrusts(); @Override @Transactional(readOnly = true) Collection<PizzaSize> getPizzaSizes(); @Override @Transactional(readOnly = true) Collection<BakeStyle> getBakeStyles(); @Override @Transactional(readOnly = true) Collection<CutStyle> getCutStyles(); @Override @Transactional(readOnly = true) Collection<Ingredient> getIngredients(); @Override Collection<Integer> getQuantities(); @Override void addOrderItemToCart(PizzaOrderDTO pizzaOrderDTO); @Override void removeOrderItem(int orderItemIndex); @Override void emptyCart(); @Override void replaceOrderItem(int orderItemIndex, PizzaOrderDTO pizzaOrderDTO); @Override PizzaOrderDTO getPizzaOrderDTOByOrderItemId(int orderItemIndex); @Override @Transactional(readOnly = true) IngredientType getIngredientTypeByIngredientId(Long ingredientId); @Override @Transactional(readOnly = true) Ingredient getIngredientById(Long ingredientId); @Override @Transactional Order postOrder(Order order); @Override @Transactional(readOnly = true) Order getOrderByTrackingNumber(String trackingNumber); @Override @Transactional void addReviewToOrderByTrackingNumber(String trackingNumber, ReviewDTO reviewDTO); @Override @Transactional(readOnly = true) Optional<PizzaOrderDTO> getPizzaOrderDTOByOrderItemId(Long orderItemId); int getMaxQuantity(); void setMaxQuantity(int maxQuantity); int getMinQuantity(); void setMinQuantity(int minQuantity); CrustDAO getCrustDAO(); @Autowired void setCrustDAO(CrustDAO crustDAO); PizzaSizeDAO getPizzaSizeDAO(); @Autowired void setPizzaSizeDAO(PizzaSizeDAO pizzaSizeDAO); BakeStyleDAO getBakeStyleDAO(); @Autowired void setBakeStyleDAO(BakeStyleDAO bakeStyleDAO); CutStyleDAO getCutStyleDAO(); @Autowired void setCutStyleDAO(CutStyleDAO cutStyleDAO); IngredientDAO getIngredientDAO(); @Autowired void setIngredientDAO(IngredientDAO ingredientDAO); OrderDAO getOrderDAO(); @Autowired void setOrderDAO(OrderDAO orderDAO); Cart getCart(); @Autowired void setCart(Cart cart); CustomerDAO getCustomerDAO(); @Autowired void setCustomerDAO(CustomerDAO customerDAO); TrackingNumberGenerationStrategy getTrackingNumberGenerationStrategy(); @Autowired void setTrackingNumberGenerationStrategy(TrackingNumberGenerationStrategy trackingNumberGenerationStrategy); OrderItemDAO getOrderItemDAO(); @Autowired void setOrderItemDAO(OrderItemDAO orderItemDAO); }### Answer: @Test public void shouldGetCutStylesFromDAO() throws Exception { List<CutStyle> cutStyles = ImmutableList.of(); when(cutStyleDAO.findAll()).thenReturn(cutStyles); Collection<CutStyle> result = orderService.getCutStyles(); assertThat(result).isSameAs(cutStyles); }
### Question: OrderServiceImpl implements OrderService { @Override @Transactional(readOnly = true) public Collection<Ingredient> getIngredients() { return ingredientDAO.findAll(); } @Override @Transactional(readOnly = true) Collection<Crust> getCrusts(); @Override @Transactional(readOnly = true) Collection<PizzaSize> getPizzaSizes(); @Override @Transactional(readOnly = true) Collection<BakeStyle> getBakeStyles(); @Override @Transactional(readOnly = true) Collection<CutStyle> getCutStyles(); @Override @Transactional(readOnly = true) Collection<Ingredient> getIngredients(); @Override Collection<Integer> getQuantities(); @Override void addOrderItemToCart(PizzaOrderDTO pizzaOrderDTO); @Override void removeOrderItem(int orderItemIndex); @Override void emptyCart(); @Override void replaceOrderItem(int orderItemIndex, PizzaOrderDTO pizzaOrderDTO); @Override PizzaOrderDTO getPizzaOrderDTOByOrderItemId(int orderItemIndex); @Override @Transactional(readOnly = true) IngredientType getIngredientTypeByIngredientId(Long ingredientId); @Override @Transactional(readOnly = true) Ingredient getIngredientById(Long ingredientId); @Override @Transactional Order postOrder(Order order); @Override @Transactional(readOnly = true) Order getOrderByTrackingNumber(String trackingNumber); @Override @Transactional void addReviewToOrderByTrackingNumber(String trackingNumber, ReviewDTO reviewDTO); @Override @Transactional(readOnly = true) Optional<PizzaOrderDTO> getPizzaOrderDTOByOrderItemId(Long orderItemId); int getMaxQuantity(); void setMaxQuantity(int maxQuantity); int getMinQuantity(); void setMinQuantity(int minQuantity); CrustDAO getCrustDAO(); @Autowired void setCrustDAO(CrustDAO crustDAO); PizzaSizeDAO getPizzaSizeDAO(); @Autowired void setPizzaSizeDAO(PizzaSizeDAO pizzaSizeDAO); BakeStyleDAO getBakeStyleDAO(); @Autowired void setBakeStyleDAO(BakeStyleDAO bakeStyleDAO); CutStyleDAO getCutStyleDAO(); @Autowired void setCutStyleDAO(CutStyleDAO cutStyleDAO); IngredientDAO getIngredientDAO(); @Autowired void setIngredientDAO(IngredientDAO ingredientDAO); OrderDAO getOrderDAO(); @Autowired void setOrderDAO(OrderDAO orderDAO); Cart getCart(); @Autowired void setCart(Cart cart); CustomerDAO getCustomerDAO(); @Autowired void setCustomerDAO(CustomerDAO customerDAO); TrackingNumberGenerationStrategy getTrackingNumberGenerationStrategy(); @Autowired void setTrackingNumberGenerationStrategy(TrackingNumberGenerationStrategy trackingNumberGenerationStrategy); OrderItemDAO getOrderItemDAO(); @Autowired void setOrderItemDAO(OrderItemDAO orderItemDAO); }### Answer: @Test public void shouldGetIngredientsFromDAO() throws Exception { List<Ingredient> ingredients = ImmutableList.of(); when(ingredientDAO.findAll()).thenReturn(ingredients); Collection<Ingredient> result = orderService.getIngredients(); assertThat(result).isSameAs(ingredients); }
### Question: OrderServiceImpl implements OrderService { @Override public void emptyCart() { cart.reset(); } @Override @Transactional(readOnly = true) Collection<Crust> getCrusts(); @Override @Transactional(readOnly = true) Collection<PizzaSize> getPizzaSizes(); @Override @Transactional(readOnly = true) Collection<BakeStyle> getBakeStyles(); @Override @Transactional(readOnly = true) Collection<CutStyle> getCutStyles(); @Override @Transactional(readOnly = true) Collection<Ingredient> getIngredients(); @Override Collection<Integer> getQuantities(); @Override void addOrderItemToCart(PizzaOrderDTO pizzaOrderDTO); @Override void removeOrderItem(int orderItemIndex); @Override void emptyCart(); @Override void replaceOrderItem(int orderItemIndex, PizzaOrderDTO pizzaOrderDTO); @Override PizzaOrderDTO getPizzaOrderDTOByOrderItemId(int orderItemIndex); @Override @Transactional(readOnly = true) IngredientType getIngredientTypeByIngredientId(Long ingredientId); @Override @Transactional(readOnly = true) Ingredient getIngredientById(Long ingredientId); @Override @Transactional Order postOrder(Order order); @Override @Transactional(readOnly = true) Order getOrderByTrackingNumber(String trackingNumber); @Override @Transactional void addReviewToOrderByTrackingNumber(String trackingNumber, ReviewDTO reviewDTO); @Override @Transactional(readOnly = true) Optional<PizzaOrderDTO> getPizzaOrderDTOByOrderItemId(Long orderItemId); int getMaxQuantity(); void setMaxQuantity(int maxQuantity); int getMinQuantity(); void setMinQuantity(int minQuantity); CrustDAO getCrustDAO(); @Autowired void setCrustDAO(CrustDAO crustDAO); PizzaSizeDAO getPizzaSizeDAO(); @Autowired void setPizzaSizeDAO(PizzaSizeDAO pizzaSizeDAO); BakeStyleDAO getBakeStyleDAO(); @Autowired void setBakeStyleDAO(BakeStyleDAO bakeStyleDAO); CutStyleDAO getCutStyleDAO(); @Autowired void setCutStyleDAO(CutStyleDAO cutStyleDAO); IngredientDAO getIngredientDAO(); @Autowired void setIngredientDAO(IngredientDAO ingredientDAO); OrderDAO getOrderDAO(); @Autowired void setOrderDAO(OrderDAO orderDAO); Cart getCart(); @Autowired void setCart(Cart cart); CustomerDAO getCustomerDAO(); @Autowired void setCustomerDAO(CustomerDAO customerDAO); TrackingNumberGenerationStrategy getTrackingNumberGenerationStrategy(); @Autowired void setTrackingNumberGenerationStrategy(TrackingNumberGenerationStrategy trackingNumberGenerationStrategy); OrderItemDAO getOrderItemDAO(); @Autowired void setOrderItemDAO(OrderItemDAO orderItemDAO); }### Answer: @Test public void shouldEmptyCart() throws Exception { orderService.emptyCart(); verify(cart).reset(); }
### Question: ProcessRetrieveRequest { public static ProcessRetrieveResponse checkRequestParameter( HttpServletRequest request, ServletContext context) { ProcessRetrieveResponse response = new ProcessRetrieveResponse(context); Integer numItems = checkNumItems(request, response); String term = checkTerm(request, response); if (term == null) { return response; } SuggestTree index = checkIndexName(request, response, context); if (index == null) { response.addError(RetrieveStatusCodes.NO_INDEX_AVAILABLE); return response; } retrieveSuggestions(request, response, index, term, numItems); return response; } static ProcessRetrieveResponse checkRequestParameter( HttpServletRequest request, ServletContext context); }### Answer: @SuppressWarnings("unchecked") @Test public void testCheckRequestParameter() throws ServletException { HttpServletRequest request = this.initializeTest(); JSONObject jsonResponse = this.testRequest(request, "Me", "7", "generalIndex"); ArrayList<HashMap<String, String>> suggestionList = (ArrayList<HashMap<String, String>>) jsonResponse .get("suggestionList"); assertTrue(suggestionList.size() == 7); }
### Question: WriteOptimizedGraphity extends SocialGraph { @Override public void createFriendship(final Node following, final Node followed) { for (Relationship followship : following.getRelationships( SocialGraphRelationshipType.FOLLOW, Direction.OUTGOING)) { if (followship.getEndNode().equals(followed)) { return; } } following.createRelationshipTo(followed, SocialGraphRelationshipType.FOLLOW); } WriteOptimizedGraphity(final AbstractGraphDatabase graph); @Override void createFriendship(final Node following, final Node followed); @Override void createStatusUpdate(final long timestamp, final Node user, StatusUpdate content); @Override List<JSONObject> readStatusUpdates(final Node poster, final Node user, final int numItems, boolean ownUpdates); @Override boolean removeFriendship(final Node following, final Node followed); @Override boolean deleteStatusUpdate(final Node user, final Node statusUpdate); }### Answer: @Test public void testCreateFriendship_Regular() { this.algorithm.createFriendship(this.USER_A, this.USER_B); this.algorithm.createFriendship(this.USER_A, this.USER_C); this.algorithm.createFriendship(this.USER_A, this.USER_D); this.algorithm.createFriendship(this.USER_A, this.USER_E); this.algorithm.createFriendship(this.USER_B, this.USER_A); this.algorithm.createFriendship(this.USER_B, this.USER_D); this.algorithm.createFriendship(this.USER_C, this.USER_A); this.algorithm.createFriendship(this.USER_C, this.USER_E); this.algorithm.createFriendship(this.USER_D, this.USER_C); final Map<Node, int[]> sortedCounts = new HashMap<Node, int[]>(); sortedCounts.put(this.USER_A, new int[] { 4, 2 }); sortedCounts.put(this.USER_B, new int[] { 2, 1 }); sortedCounts.put(this.USER_C, new int[] { 2, 2 }); sortedCounts.put(this.USER_D, new int[] { 1, 2 }); sortedCounts.put(this.USER_E, new int[] { 0, 2 }); int[] relationshipCount; for (Node user : AlgorithmTests.USERS) { relationshipCount = sortedCounts.get(user); assertEquals(AlgorithmTest.getNumberOfRelationships(user .getRelationships(SocialGraphRelationshipType.FOLLOW, Direction.OUTGOING)), relationshipCount[0]); assertEquals(AlgorithmTest.getNumberOfRelationships(user .getRelationships(SocialGraphRelationshipType.FOLLOW, Direction.INCOMING)), relationshipCount[1]); } this.transaction.success(); }
### Question: WriteOptimizedGraphity extends SocialGraph { @Override public List<JSONObject> readStatusUpdates(final Node poster, final Node user, final int numItems, boolean ownUpdates) { if (!poster.equals(user)) { ownUpdates = true; } final List<JSONObject> statusUpdates = new LinkedList<JSONObject>(); if (!ownUpdates) { final TreeSet<StatusUpdateUser> users = new TreeSet<StatusUpdateUser>( new StatusUpdateUserComparator()); Node userNode; StatusUpdateUser crrUser; for (Relationship relationship : poster.getRelationships( SocialGraphRelationshipType.FOLLOW, Direction.OUTGOING)) { userNode = relationship.getEndNode(); crrUser = new StatusUpdateUser(userNode); if (crrUser.hasStatusUpdate()) { users.add(crrUser); } } while ((statusUpdates.size() < numItems) && !users.isEmpty()) { crrUser = users.pollLast(); statusUpdates.add(crrUser.getStatusUpdate()); if (crrUser.hasStatusUpdate()) { users.add(crrUser); } } } else { final StatusUpdateUser posterNode = new StatusUpdateUser(poster); while ((statusUpdates.size() < numItems) && posterNode.hasStatusUpdate()) { statusUpdates.add(posterNode.getStatusUpdate()); } } return statusUpdates; } WriteOptimizedGraphity(final AbstractGraphDatabase graph); @Override void createFriendship(final Node following, final Node followed); @Override void createStatusUpdate(final long timestamp, final Node user, StatusUpdate content); @Override List<JSONObject> readStatusUpdates(final Node poster, final Node user, final int numItems, boolean ownUpdates); @Override boolean removeFriendship(final Node following, final Node followed); @Override boolean deleteStatusUpdate(final Node user, final Node statusUpdate); }### Answer: @Test public void testReadStatusUpdates_Regular() { List<JSONObject> activities; activities = this.algorithm.readStatusUpdates(this.USER_A, this.USER_A, 7, false); assertNotNull(activities); AlgorithmTest.compareValues(new long[] { 13, 12, 11, 10, 8, 7, 6 }, activities); activities = this.algorithm.readStatusUpdates(this.USER_A, this.USER_A, 10, false); assertNotNull(activities); AlgorithmTest.compareValues( new long[] { 13, 12, 11, 10, 8, 7, 6, 5, 4 }, activities); activities = this.algorithm.readStatusUpdates(this.USER_A, this.USER_B, 2, false); assertNotNull(activities); AlgorithmTest.compareValues(new long[] { 17, 14 }, activities); activities = this.algorithm.readStatusUpdates(this.USER_A, this.USER_B, 2, true); assertNotNull(activities); AlgorithmTest.compareValues(new long[] { 17, 14 }, activities); activities = this.algorithm.readStatusUpdates(this.USER_C, this.USER_C, 4, false); assertNotNull(activities); AlgorithmTest.compareValues(new long[] { 17, 14, 9 }, activities); activities = this.algorithm.readStatusUpdates(this.USER_A, this.USER_C, 4, true); assertNotNull(activities); AlgorithmTest.compareValues(new long[] { 17, 14, 9 }, activities); activities = this.algorithm.readStatusUpdates(this.USER_D, this.USER_D, 2, false); assertNotNull(activities); AlgorithmTest.compareValues(new long[] { 13, 7 }, activities); activities = this.algorithm.readStatusUpdates(this.USER_D, this.USER_D, 4, false); assertNotNull(activities); AlgorithmTest.compareValues(new long[] { 13, 7, 6 }, activities); activities = this.algorithm.readStatusUpdates(this.USER_E, this.USER_E, 10, false); assertNotNull(activities); AlgorithmTest.compareValues(new long[] {}, activities); }
### Question: CollectionUtil { @SuppressWarnings({ "rawtypes", "unchecked" }) public static <T> Collection<T> substract(Collection<T> oldList, Collection<T> newList, java.util.Comparator comparator) { Collection<T> result = new ArrayList<T>(oldList); for (T oldValue : oldList) { for (T newValue : newList) { if (comparator.compare(oldValue, newValue) == 0) { result.remove(oldValue); } } } return result; } @SuppressWarnings({ "rawtypes", "unchecked" }) static Collection<Pair<T, T>> intersection( Collection<T> oldList, Collection<T> newList, java.util.Comparator comparator); @SuppressWarnings({ "rawtypes", "unchecked" }) static Collection<T> substract(Collection<T> oldList, Collection<T> newList, java.util.Comparator comparator); }### Answer: @Test(groups = { "collectionUtil" }, description = "substract") public void testSubstract() throws Exception { Collection<String> a = new ArrayList<String>(); a.add("a"); a.add("b"); a.add("c"); a.add("d"); Collection<String> b = new ArrayList<String>(); b.add("a"); b.add("D"); b.add("e"); b.add("f"); Collection<String> c = CollectionUtil.substract(a, b, new StringComparator()); Assert.assertEquals(c.size(), 2, "collection size"); Assert.assertTrue(c.contains("b"), "collection should contain value"); Assert.assertTrue(c.contains("c"), "collection should contain value"); }
### Question: ProgressionCommand implements Command, Constant, ReportConstant { public void terminate(Context context, int stepCount) { ProgressionReport report = (ProgressionReport) context.get(REPORT); report.getProgression().setCurrentStep(STEP.FINALISATION.ordinal() + 1); report.getProgression().getSteps().get(STEP.FINALISATION.ordinal()).setTotal(stepCount); saveReport(context, true); saveMainValidationReport(context, true); } void initialize(Context context, int stepCount); void start(Context context, int stepCount); void terminate(Context context, int stepCount); void dispose(Context context); void saveReport(Context context, boolean force); void saveMainValidationReport(Context context, boolean force); @Override boolean execute(Context context); static final String COMMAND; }### Answer: @Test(groups = { "progression" }, description = "terminate progression command", dependsOnMethods = { "testProgressionExecute" }) public void testProgressionTerminate() throws Exception { ValidationReport validation = new ValidationReport(); context.put(VALIDATION_REPORT, validation); ValidationReporter reporter = ValidationReporter.Factory.getInstance(); reporter.addItemToValidationReport(context, "1-TEST-1", "E"); progression.terminate(context, 2); ActionReport report = (ActionReport) context.get(REPORT); Assert.assertNotNull(report.getProgression(), "progression should be reported"); Assert.assertEquals(report.getProgression().getCurrentStep(), STEP.FINALISATION.ordinal() + 1, " progression should be on step finalisation"); Assert.assertEquals(report.getProgression().getSteps().get(2).getTotal(), 2, " total progression should be 2"); Assert.assertEquals(report.getProgression().getSteps().get(2).getRealized(), 0, " current progression should be 2"); context.remove(VALIDATION_REPORT); File validationFile = new File(d, VALIDATION_FILE); Assert.assertTrue(validationFile.exists(), VALIDATION_FILE + " should exists"); }
### Question: ProgressionCommand implements Command, Constant, ReportConstant { public void dispose(Context context) { saveReport(context, true); saveMainValidationReport(context, true); Monitor monitor = MonitorFactory.getTimeMonitor("ActionReport"); if (monitor != null) log.info(Color.LIGHT_GREEN + monitor.toString() + Color.NORMAL); monitor = MonitorFactory.getTimeMonitor("ValidationReport"); if (monitor != null) log.info(Color.LIGHT_GREEN + monitor.toString() + Color.NORMAL); } void initialize(Context context, int stepCount); void start(Context context, int stepCount); void terminate(Context context, int stepCount); void dispose(Context context); void saveReport(Context context, boolean force); void saveMainValidationReport(Context context, boolean force); @Override boolean execute(Context context); static final String COMMAND; }### Answer: @Test(groups = { "progression" }, description = "dispose progression command", dependsOnMethods = { "testProgressionTerminate" }) public void testProgressionDispose() throws Exception { progression.dispose(context); ActionReport report = (ActionReport) context.get(REPORT); Assert.assertEquals(report.getResult(), ReportConstant.STATUS_OK, " result should be ok"); }
### Question: LineRegisterCommand implements Command { protected void write(StringWriter buffer, VehicleJourney vehicleJourney, StopPoint stopPoint, VehicleJourneyAtStop vehicleJourneyAtStop) throws IOException { DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); buffer.write(vehicleJourney.getId().toString()); buffer.append(SEP); buffer.write(stopPoint.getId().toString()); buffer.append(SEP); if (vehicleJourneyAtStop.getArrivalTime() != null) buffer.write(timeFormat.format(vehicleJourneyAtStop.getArrivalTime())); else buffer.write(NULL); buffer.append(SEP); if (vehicleJourneyAtStop.getDepartureTime() != null) buffer.write(timeFormat.format(vehicleJourneyAtStop.getDepartureTime())); else buffer.write(NULL); buffer.append(SEP); buffer.write(Integer.toString(vehicleJourneyAtStop.getArrivalDayOffset())); buffer.append(SEP); buffer.write(Integer.toString(vehicleJourneyAtStop.getDepartureDayOffset())); buffer.append('\n'); } @Override @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) boolean execute(Context context); static final String COMMAND; }### Answer: @SuppressWarnings("deprecation") @Test (groups = { "write" }, description = "write command") public void testLineRegisterWrite() throws Exception { InitialContext initialContext = new InitialContext(); Context context = new Context(); context.put(INITIAL_CONTEXT, initialContext); StringWriter buffer = new StringWriter(); VehicleJourney neptuneObject = new VehicleJourney(); neptuneObject.setId(4321L); StopPoint sp = new StopPoint(); sp.setId(1001L); VehicleJourneyAtStop vjas = new VehicleJourneyAtStop(); vjas.setStopPoint(sp); vjas.setArrivalTime(new Time(23,59,0)); vjas.setDepartureTime(new Time(0,5,0)); vjas.setArrivalDayOffset(0); vjas.setDepartureDayOffset(1); lineRegister = new LineRegisterCommand(); lineRegister.write(buffer, neptuneObject, sp, vjas); Assert.assertEquals(buffer.toString(), "4321|1001|23:59:00|00:05:00|0|1\n", "Invalid data entry for buffer"); }
### Question: StepProgression extends AbstractReport { @Override public void print(PrintStream out, StringBuilder ret , int level, boolean first) { ret.setLength(0); out.print(addLevel(ret, level).append('{')); out.print(toJsonString(ret, level+1, "step", step, true)); out.print(toJsonString(ret, level+1, "total", total, false)); out.print(toJsonString(ret, level+1, "realized", realized, false)); ret.setLength(0); out.print(addLevel(ret.append('\n'), level).append('}')); } JSONObject toJson(); @Override void print(PrintStream out, StringBuilder ret , int level, boolean first); }### Answer: @Test(groups = { "JsonGeneration" }, description = "Json generated" ,priority=105 ) public void verifyJsonGeneration() throws Exception { StepProgression stepProgression = new StepProgression(STEP.INITIALISATION, 1, 0); ByteArrayOutputStream oStream = new ByteArrayOutputStream(); PrintStream stream = new PrintStream(oStream); stepProgression.print(stream, new StringBuilder(), 1, true); String text = oStream.toString(); JSONObject res = new JSONObject(text); Assert.assertEquals(res.getString("step"), "INITIALISATION", "step must be INITIALISATION"); Assert.assertEquals(res.getInt("total"), 1, "total step number must be 1"); Assert.assertEquals(res.getInt("realized"), 0, "no step has been realized yet"); }
### Question: Progression extends AbstractReport { @Override public void print(PrintStream out, StringBuilder ret , int level, boolean first) { ret.setLength(0); out.print(addLevel(ret, level).append('{')); out.print(toJsonString(ret, level+1, "current_step", currentStep, true)); out.print(toJsonString(ret, level+1, "steps_count", stepsCount, false)); if (!steps.isEmpty()) { printArray(out, ret, level + 1, "steps", steps, false); } ret.setLength(0); out.print(addLevel(ret.append('\n'), level).append('}')); } Progression(); JSONObject toJson(); @Override void print(PrintStream out, StringBuilder ret , int level, boolean first); }### Answer: @Test(groups = { "JsonGeneration" }, description = "Json generated" ,priority=105 ) public void verifyJsonGeneration() throws Exception { Progression progression = new Progression(); ByteArrayOutputStream oStream = new ByteArrayOutputStream(); PrintStream stream = new PrintStream(oStream); progression.print(stream, new StringBuilder(), 1, true); String text = oStream.toString(); JSONObject res = new JSONObject(text); Assert.assertEquals(res.getInt("current_step"), 0, "current step must be 0"); Assert.assertEquals(res.getInt("steps_count"), 3, "progression must have 3 steps"); JSONArray steps = res.getJSONArray("steps"); Assert.assertEquals(steps.length(), 3, "progression step list must have 3 steps"); }
### Question: FileError extends AbstractReport { @Override public void print(PrintStream out, StringBuilder ret , int level, boolean first) { ret.setLength(0); out.print(addLevel(ret, level).append('{')); out.print(toJsonString(ret, level+1, "code", code, true)); out.print(toJsonString(ret, level+1, "description", description, false)); ret.setLength(0); out.print(addLevel(ret.append('\n'), level).append('}')); } JSONObject toJson(); @Override void print(PrintStream out, StringBuilder ret , int level, boolean first); }### Answer: @Test(groups = { "JsonGeneration" }, description = "Json generated" ,priority=105 ) public void verifyJsonGeneration() throws Exception { FileError fileError = new FileError(FILE_ERROR_CODE.FILE_NOT_FOUND, "file_error1"); ByteArrayOutputStream oStream = new ByteArrayOutputStream(); PrintStream stream = new PrintStream(oStream); fileError.print(stream, new StringBuilder(), 1, true); String text = oStream.toString(); JSONObject res = new JSONObject(text); Assert.assertEquals(res.getString("code"), "FILE_NOT_FOUND", "wrong file error code"); Assert.assertEquals(res.getString("description"), "file_error1", "wrong file error description"); }
### Question: ObjectError extends AbstractReport { @Override public void print(PrintStream out, StringBuilder ret , int level, boolean first) { ret.setLength(0); out.print(addLevel(ret, level).append('{')); out.print(toJsonString(ret, level+1, "code", code, true)); out.print(toJsonString(ret, level+1, "description", description, false)); ret.setLength(0); out.print(addLevel(ret.append('\n'), level).append('}')); } JSONObject toJson(); @Override void print(PrintStream out, StringBuilder ret , int level, boolean first); }### Answer: @Test(groups = { "JsonGeneration" }, description = "Json generated" ,priority=105 ) public void verifyJsonGeneration() throws Exception { ObjectError objectError = new ObjectError(ERROR_CODE.INTERNAL_ERROR, "object_error1"); ByteArrayOutputStream oStream = new ByteArrayOutputStream(); PrintStream stream = new PrintStream(oStream); objectError.print(stream, new StringBuilder(), 1, true); String text = oStream.toString(); JSONObject res = new JSONObject(text); Assert.assertEquals(res.getString("code"), "INTERNAL_ERROR", "wrong object error code"); Assert.assertEquals(res.getString("description"), "object_error1", "wrong object error description"); }
### Question: ActionError extends AbstractReport { @Override public void print(PrintStream out, StringBuilder ret , int level, boolean first) { ret.setLength(0); out.print(addLevel(ret, level).append('{')); out.print(toJsonString(ret, level+1, "code", code, true)); out.print(toJsonString(ret, level+1, "description", description, false)); ret.setLength(0); out.print(addLevel(ret.append('\n'), level).append('}')); } JSONObject toJson(); @Override void print(PrintStream out, StringBuilder ret , int level, boolean first); }### Answer: @Test(groups = { "JsonGeneration" }, description = "Json generated" ,priority=105 ) public void verifyJsonGeneration() throws Exception { ActionError actionError = new ActionError(ERROR_CODE.INTERNAL_ERROR, "action_error1"); ByteArrayOutputStream oStream = new ByteArrayOutputStream(); PrintStream stream = new PrintStream(oStream); actionError.print(stream, new StringBuilder(), 1, true); String text = oStream.toString(); JSONObject res = new JSONObject(text); Assert.assertEquals(res.getString("code"), "INTERNAL_ERROR", "wrong action error code"); Assert.assertEquals(res.getString("description"), "action_error1", "wrong action error description"); }
### Question: JobServiceManager { @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public JobService create(String referential, String action, String type, Map<String, InputStream> inputStreamsByName) throws ServiceException { validateReferential(referential); synchronized (lock) { if (scheduler.getActivejobsCount() >= maxJobs) { throw new RequestServiceException(RequestExceptionCode.TOO_MANY_ACTIVE_JOBS, "" + maxJobs + " active jobs"); } JobService jobService = jobServiceManager.createJob(referential, action, type, inputStreamsByName); scheduler.schedule(referential); return jobService; } } @PostConstruct synchronized void init(); @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) JobService create(String referential, String action, String type, Map<String, InputStream> inputStreamsByName); List<Stat> getMontlyStats(); JobService createJob(String referential, String action, String type, Map<String, InputStream> inputStreamsByName); List<TestDescription> getTestList(String action, String type); JobService download(String referential, Long id, String filename); JobService getNextJob(String referential); void start(JobService jobService); JobService cancel(String referential, Long id); void remove(String referential, Long id); void drop(String referential); void terminate(JobService jobService); void abort(JobService jobService); List<JobService> findAll(); List<JobService> findAll(String referential); JobService scheduledJob(String referential, Long id); JobService terminatedJob(String referential, Long id); JobService getJobService(Long id); List<JobService> jobs(String referential, String action[], final Long version, Job.STATUS[] status); List<JobService> activeJobs(); static final String BEAN_NAME; }### Answer: @Test(groups = { "JobServiceManager" }, description = "Check wrong referential") public void createWrongJobReferential() { String referential = "toto"; String action = "action"; String type = "type"; Map<String, InputStream> inputStreamsByName = null; try { jobServiceManager.create(referential, action, type, inputStreamsByName); } catch (RequestServiceException e) { Assert.assertEquals(e.getCode(), ServiceExceptionCode.INVALID_REQUEST.name(), "code expected"); Assert.assertEquals(e.getRequestCode(), RequestExceptionCode.UNKNOWN_REFERENTIAL.name(), "request code expected"); return; } catch (Exception e) { Assert.assertTrue(false, "RequestServiceException required"); } Assert.assertTrue(false, "exception required"); } @Test(groups = { "JobServiceManager" }, description = "Check wrong action") public void createWrongJobAction() { String referential = "chouette_gui"; String action = "action"; String type = "type"; Map<String, InputStream> inputStreamsByName = new HashMap<>(); try { jobServiceManager.create(referential, action, type, inputStreamsByName); } catch (RequestServiceException e) { Assert.assertEquals(e.getCode(), ServiceExceptionCode.INVALID_REQUEST.name(), "code expected"); Assert.assertEquals(e.getRequestCode(), RequestExceptionCode.UNKNOWN_ACTION.name(), "request code expected"); return; } catch (Exception e) { Assert.assertTrue(false, "RequestServiceException required," + e.getClass().getName() + " received"); } Assert.assertTrue(false, "exception required"); }
### Question: CollectionUtil { @SuppressWarnings({ "rawtypes", "unchecked" }) public static <T> Collection<Pair<T, T>> intersection( Collection<T> oldList, Collection<T> newList, java.util.Comparator comparator) { Collection<Pair<T, T>> result = new ArrayList<Pair<T, T>>(); for (T oldValue : oldList) { for (T newValue : newList) { if (comparator.compare(oldValue, newValue) == 0) { result.add(Pair.of(oldValue, newValue)); } } } return result; } @SuppressWarnings({ "rawtypes", "unchecked" }) static Collection<Pair<T, T>> intersection( Collection<T> oldList, Collection<T> newList, java.util.Comparator comparator); @SuppressWarnings({ "rawtypes", "unchecked" }) static Collection<T> substract(Collection<T> oldList, Collection<T> newList, java.util.Comparator comparator); }### Answer: @Test(groups = { "collectionUtil" }, description = "intersect") public void testIntersect() throws Exception { Collection<String> a = new ArrayList<String>(); a.add("a"); a.add("b"); a.add("c"); a.add("d"); Collection<String> b = new ArrayList<String>(); b.add("A"); b.add("D"); b.add("E"); b.add("F"); Collection<Pair<String, String>> c = CollectionUtil.intersection(a, b, new StringComparator()); Assert.assertEquals(c.size(), 2, "collection size"); Assert.assertTrue(c.contains(new Pair<String, String>("a", "A")), "collection should contain pair"); Assert.assertTrue(c.contains(new Pair<String, String>("d", "D")), "collection should contain pair"); }
### Question: FileLocation extends AbstractReport { @Override public void print(PrintStream out, StringBuilder ret , int level, boolean first) { ret.setLength(0); out.print(addLevel(ret, level).append('{')); out.print(toJsonString(ret, level + 1, "filename", filename, true)); if (lineNumber != null) { out.print(toJsonString(ret, level + 1, "line_number", lineNumber, false)); } if (columnNumber != null) { out.print(toJsonString(ret, level + 1, "column_number", columnNumber, false)); } ret.setLength(0); out.print(addLevel(ret.append('\n'), level).append('}')); } protected FileLocation(String fileName); protected FileLocation(String fileName, int lineNumber, int columnNumber); FileLocation(DataLocation dl); @Override void print(PrintStream out, StringBuilder ret , int level, boolean first); }### Answer: @Test(groups = { "JsonGeneration" }, description = "Json generated", priority = 104) public void verifyJsonGeneration() throws Exception { { ByteArrayOutputStream oStream = new ByteArrayOutputStream(); PrintStream stream = new PrintStream(oStream); FileLocation fileLocation = new FileLocation("fileName", 0, 0); fileLocation.print(stream, new StringBuilder(), 1, true); String text = oStream.toString(); JSONObject res = new JSONObject(text); Assert.assertEquals(res.getString("filename"), "fileName", "wrong file location name"); Assert.assertEquals(res.getInt("line_number"), 0, "wrong file location line number"); Assert.assertEquals(res.getInt("column_number"), 0, "wrong file location column number"); } { ByteArrayOutputStream oStream = new ByteArrayOutputStream(); PrintStream stream = new PrintStream(oStream); FileLocation fileLocation = new FileLocation("fileName", 15, 0); fileLocation.print(stream, new StringBuilder(), 1, true); String text = oStream.toString(); JSONObject res = new JSONObject(text); Assert.assertEquals(res.getString("filename"), "fileName", "wrong file location name"); Assert.assertEquals(res.getInt("line_number"), 15, "wrong file location line number"); Assert.assertEquals(res.getInt("column_number"), 0, "wrong file location column number"); } { ByteArrayOutputStream oStream = new ByteArrayOutputStream(); PrintStream stream = new PrintStream(oStream); FileLocation fileLocation = new FileLocation("fileName", 0, 10); fileLocation.print(stream, new StringBuilder(), 1, true); String text = oStream.toString(); JSONObject res = new JSONObject(text); Assert.assertEquals(res.getString("filename"), "fileName", "wrong file location name"); Assert.assertEquals(res.getInt("line_number"), 0, "wrong file location line number"); Assert.assertEquals(res.getInt("column_number"), 10, "wrong file location column number"); } }
### Question: Location extends AbstractReport { @Override public void print(PrintStream out, StringBuilder ret, int level, boolean first) { ret.setLength(0); out.print(addLevel(ret, level).append('{')); first = true; if (file != null) { printObject(out, ret, level + 1, "file", file, first); first = false; } if (objectId != null) { out.print(toJsonString(ret, level + 1, "objectid", objectId, first)); first = false; } if (name != null) { out.print(toJsonString(ret, level + 1, "label", name, first)); first = false; } if (!objectRefs.isEmpty()) { printArray(out, ret, level + 1, "object_path", objectRefs, first); first = false; } ret.setLength(0); out.print(addLevel(ret.append('\n'), level).append('}')); } Location(DataLocation dl); Location(String fileName); Location(String fileName, String locationName); Location(String fileName, String locationName, int lineNumber, String objectId); Location(String fileName, String locationName, int lineNumber, int columnNumber, String objectId); Location(String fileName, String locationName, int lineNumber); Location(String fileName, int lineNumber, int columnNumber); Location(String fileName, int lineNumber, int columnNumber, String objectId); Location(NeptuneIdentifiedObject chouetteObject); static String buildName(NeptuneIdentifiedObject chouetteObject); @Override void print(PrintStream out, StringBuilder ret, int level, boolean first); }### Answer: @Test(groups = { "JsonGeneration" }, description = "Json generated", priority = 104) public void verifyJsonGeneration() throws Exception { { ByteArrayOutputStream oStream = new ByteArrayOutputStream(); PrintStream stream = new PrintStream(oStream); Location location = new Location("fileName", 0, 0); location.print(stream, new StringBuilder(), 1, true); String text = oStream.toString(); JSONObject res = new JSONObject(text); Assert.assertNotNull(res.getJSONObject("file") , "location file shall not be null"); } { ByteArrayOutputStream oStream = new ByteArrayOutputStream(); PrintStream stream = new PrintStream(oStream); Location location = new Location("fileName", 0, 0, "neptune"); location.print(stream, new StringBuilder(), 1, true); String text = oStream.toString(); JSONObject res = new JSONObject(text); Assert.assertEquals(res.getString("objectid") , "neptune", "wrong location object id"); } { ByteArrayOutputStream oStream = new ByteArrayOutputStream(); PrintStream stream = new PrintStream(oStream); Location location = new Location("fileName", "locationName", 0); location.print(stream, new StringBuilder(), 1, true); String text = oStream.toString(); JSONObject res = new JSONObject(text); Assert.assertEquals(res.getString("label") , "locationName", "wrong location object name"); } { ByteArrayOutputStream oStream = new ByteArrayOutputStream(); PrintStream stream = new PrintStream(oStream); JourneyPattern jp = new JourneyPattern(); Route route = new Route(); route.setObjectId("route1"); route.setName("rname"); Line line = new Line(); line.setObjectId("line1"); line.setName("lname"); route.setLine(line); jp.setRoute(route); Location location = new Location(jp); location.print(stream, new StringBuilder(), 1, true); String text = oStream.toString(); JSONObject res = new JSONObject(text); JSONArray objectRef = res.getJSONArray("object_path"); Assert.assertNotNull(objectRef.get(0), "journey pattern reference shall not be null"); } }
### Question: ValidationReport extends AbstractReport implements Report { @Override public void print(PrintStream out) { print(out, new StringBuilder(), 1, true); } CheckPointReport findCheckPointReportByName(String name); CheckPointErrorReport findCheckPointReportErrorByKey(String key); @Override void print(PrintStream out); @Override void print(PrintStream out, StringBuilder ret , int level, boolean first); @Override boolean isEmpty(); }### Answer: @Test(groups = { "JsonGeneration" }, description = "Json generated", priority = 104) public void verifyJsonGeneration() throws Exception { Context context = new Context(); context.put(VALIDATION_REPORT, new ValidationReport()); context.put(REPORT, new ActionReport()); ValidationReporter validationReporter = ValidationReporter.Factory.getInstance(); ValidationReport validationReport = (ValidationReport) context.get(VALIDATION_REPORT); { ByteArrayOutputStream oStream = new ByteArrayOutputStream(); PrintStream stream = new PrintStream(oStream); validationReport.print(stream); String text = oStream.toString(); JSONObject res = new JSONObject(text); Assert.assertEquals(res.length(), 1 , "Report must contains 1 entry"); Assert.assertTrue(res.has("validation_report"), "Report must contains entry validation_report"); JSONObject vrJson = res.getJSONObject("validation_report"); Assert.assertNotNull(vrJson, "validation_report json object must not be null"); Assert.assertEquals(vrJson.getString("result"), VALIDATION_RESULT.NO_PROCESSING.toString(), "validation_report is not empty"); } validationReporter.addItemToValidationReport(context, "Neptune-", "Checkpoint", 1, "W"); DataLocation location = new DataLocation("filename", 3, 1, "1234"); validationReporter.addCheckPointReportError(context, "Neptune-Checkpoint-1", location, "test"); { ByteArrayOutputStream oStream = new ByteArrayOutputStream(); PrintStream stream = new PrintStream(oStream); validationReport.print(stream); String text = oStream.toString(); JSONObject res = new JSONObject(text); Assert.assertEquals(res.length(), 1 , "Report must contains 1 entry"); Assert.assertTrue(res.has("validation_report"), "Report must contains entry validation_report"); JSONObject vrJson = res.getJSONObject("validation_report"); Assert.assertNotNull(vrJson, "validation_report json object must not be null"); Assert.assertEquals(vrJson.getString("result"), VALIDATION_RESULT.WARNING.toString(), "validation_report is empty"); JSONArray checkPointsJson = vrJson.getJSONArray("check_points"); Assert.assertNotNull(checkPointsJson, "checkpoint list must not be null"); Assert.assertEquals(((JSONObject)checkPointsJson.get(0)).getString("test_id"), "Neptune-Checkpoint-1", "wrong checkpoint test_id"); Assert.assertEquals(((JSONObject)checkPointsJson.get(0)).getInt("check_point_error_count"), 1, "checkpoint must have one error"); JSONArray checkPointErrorsKeyJson = ((JSONObject) checkPointsJson.get(0)).getJSONArray("errors"); Assert.assertNotNull(checkPointErrorsKeyJson, "checkpoint error key list must not be null"); Assert.assertEquals(checkPointErrorsKeyJson.length(), 1, "checkpoint must contain one error"); Assert.assertEquals(checkPointErrorsKeyJson.get(0), 0, "wrong error key"); JSONArray errorsArrayJson = vrJson.getJSONArray("errors"); Assert.assertNotNull(errorsArrayJson, "errors array must not be null"); Assert.assertEquals(((JSONObject)errorsArrayJson.get(0)).getString("test_id"), "Neptune-Checkpoint-1", "wrong error test_id"); Assert.assertEquals(((JSONObject)errorsArrayJson.get(0)).getString("error_id"), "neptune_checkpoint_1", "wrong error error_id"); } }
### Question: CompressCommand implements Command, Constant { @Override public boolean execute(Context context) throws Exception { boolean result = ERROR; Monitor monitor = MonitorFactory.start(COMMAND); try { JobData jobData = (JobData) context.get(JOB_DATA); String path = jobData.getPathName(); String file = jobData.getOutputFilename(); Path target = Paths.get(path, OUTPUT); Path filename = Paths.get(path, file); File outputFile = filename.toFile(); if (outputFile.exists()) outputFile.delete(); FileUtil.compress(target.toString(), filename.toString()); result = SUCCESS; try { FileUtils.deleteDirectory(target.toFile()); } catch (Exception e) { log.warn("cannot purge output directory " + e.getMessage()); } } catch (Exception e) { log.error(e.getMessage(), e); } finally { log.info(Color.MAGENTA + monitor.stop() + Color.NORMAL); } return result; } @Override boolean execute(Context context); static final String COMMAND; }### Answer: @Test (groups = { "compress" }, description = "compress command") public void testProgressionInitialize() throws Exception { InitialContext initialContext = new InitialContext(); Context context = new Context(); context.put(INITIAL_CONTEXT, initialContext); JobDataTest test = new JobDataTest(); context.put(JOB_DATA, test); test.setPathName("target/referential/test"); test.setOutputFilename("output.zip"); if (d.exists()) try { org.apache.commons.io.FileUtils.deleteDirectory(d); } catch (IOException e) { e.printStackTrace(); } d.mkdirs(); File source = new File("src/test/data/compressTest.zip"); File output = new File(d,OUTPUT); output.mkdir(); FileUtil.uncompress(source.getAbsolutePath(), d.getAbsolutePath()); CompressCommand command = (CompressCommand) CommandFactory .create(initialContext, CompressCommand.class.getName()); command.execute(context); File archive = new File(d,"output.zip"); Assert.assertTrue (archive.exists(), "arhive file should exists"); }
### Question: ProgressionCommand implements Command, Constant, ReportConstant { public void initialize(Context context, int stepCount) { ProgressionReport report = (ProgressionReport) context.get(REPORT); report.getProgression().setCurrentStep(STEP.INITIALISATION.ordinal() + 1); report.getProgression().getSteps().get(STEP.INITIALISATION.ordinal()).setTotal(stepCount); saveReport(context, true); saveMainValidationReport(context, true); } void initialize(Context context, int stepCount); void start(Context context, int stepCount); void terminate(Context context, int stepCount); void dispose(Context context); void saveReport(Context context, boolean force); void saveMainValidationReport(Context context, boolean force); @Override boolean execute(Context context); static final String COMMAND; }### Answer: @Test(groups = { "progression" }, description = "initialize progression command") public void testProgressionInitialize() throws Exception { InitialContext initialContext = new InitialContext(); context.put(INITIAL_CONTEXT, initialContext); JobDataTest jobData = new JobDataTest(); context.put(JOB_DATA, jobData); jobData.setPathName("target/referential/test"); context.put(REPORT, new ActionReport()); ActionReport report = (ActionReport) context.get(REPORT); context.put(VALIDATION_REPORT, new ValidationReport()); context.put(CONFIGURATION, new DummyParameter()); if (d.exists()) try { FileUtils.deleteDirectory(d); } catch (IOException e) { e.printStackTrace(); } d.mkdirs(); progression = (ProgressionCommand) CommandFactory.create(initialContext, ProgressionCommand.class.getName()); log.info(report); progression.initialize(context, 2); File reportFile = new File(d, REPORT_FILE); File validationFile = new File(d, VALIDATION_FILE); Assert.assertTrue(reportFile.exists(), REPORT_FILE + "should exists"); Assert.assertFalse(validationFile.exists(), VALIDATION_FILE + "should not exists"); Assert.assertNotNull(report.getProgression(), "progression should be reported"); Assert.assertEquals(report.getProgression().getCurrentStep(), STEP.INITIALISATION.ordinal() + 1, " progression should be on step init"); Assert.assertEquals(report.getProgression().getSteps().get(0).getTotal(), 2, " total progression should be 2"); Assert.assertEquals(report.getProgression().getSteps().get(0).getRealized(), 0, " current progression should be 0"); }
### Question: ProgressionCommand implements Command, Constant, ReportConstant { public void start(Context context, int stepCount) { ProgressionReport report = (ProgressionReport) context.get(REPORT); report.getProgression().setCurrentStep(STEP.PROCESSING.ordinal() + 1); report.getProgression().getSteps().get(STEP.PROCESSING.ordinal()).setTotal(stepCount); saveReport(context, true); saveMainValidationReport(context, true); } void initialize(Context context, int stepCount); void start(Context context, int stepCount); void terminate(Context context, int stepCount); void dispose(Context context); void saveReport(Context context, boolean force); void saveMainValidationReport(Context context, boolean force); @Override boolean execute(Context context); static final String COMMAND; }### Answer: @Test(groups = { "progression" }, description = "start progression command", dependsOnMethods = { "testProgressionInitialize" }) public void testProgressionStart() throws Exception { progression.start(context, 2); ActionReport report = (ActionReport) context.get(REPORT); Assert.assertNotNull(report.getProgression(), "progression should be reported"); Assert.assertEquals(report.getProgression().getCurrentStep(), STEP.PROCESSING.ordinal() + 1, " progression should be on step processing"); Assert.assertEquals(report.getProgression().getSteps().get(1).getTotal(), 2, " total progression should be 2"); Assert.assertEquals(report.getProgression().getSteps().get(1).getRealized(), 0, " current progression should be 0"); }
### Question: ProgressionCommand implements Command, Constant, ReportConstant { @Override public boolean execute(Context context) throws Exception { boolean result = SUCCESS; ProgressionReport report = (ProgressionReport) context.get(REPORT); StepProgression step = report.getProgression().getSteps().get(report.getProgression().getCurrentStep() - 1); step.setRealized(step.getRealized() + 1); boolean force = report.getProgression().getCurrentStep() != STEP.PROCESSING.ordinal() + 1; saveReport(context, force); if (force && context.containsKey(VALIDATION_REPORT)) { saveMainValidationReport(context, force); } if (context.containsKey(CANCEL_ASKED) || Thread.currentThread().isInterrupted()) { log.info("Command cancelled"); throw new CommandCancelledException(COMMAND_CANCELLED); } AbstractParameter params = (AbstractParameter) context.get(CONFIGURATION); if (params.isTest()) { log.info(Color.YELLOW + "Mode test on: waiting 10 s" + Color.NORMAL); Thread.sleep(10000); } return result; } void initialize(Context context, int stepCount); void start(Context context, int stepCount); void terminate(Context context, int stepCount); void dispose(Context context); void saveReport(Context context, boolean force); void saveMainValidationReport(Context context, boolean force); @Override boolean execute(Context context); static final String COMMAND; }### Answer: @Test(groups = { "progression" }, description = "execute progression command", dependsOnMethods = { "testProgressionStart" }) public void testProgressionExecute() throws Exception { progression.execute(context); ActionReport report = (ActionReport) context.get(REPORT); Assert.assertNotNull(report.getProgression(), "progression should be reported"); Assert.assertEquals(report.getProgression().getCurrentStep(), STEP.PROCESSING.ordinal() + 1, " progression should be on step processing"); Assert.assertEquals(report.getProgression().getSteps().get(1).getTotal(), 2, " total progression should be 2"); Assert.assertEquals(report.getProgression().getSteps().get(1).getRealized(), 1, " current progression should be 1"); }
### Question: DownloadSerialQueue extends DownloadListener2 implements Runnable { public void setListener(DownloadListener listener) { listenerBunch = new DownloadListenerBunch.Builder() .append(this) .append(listener).build(); } DownloadSerialQueue(); DownloadSerialQueue(DownloadListener listener, ArrayList<DownloadTask> taskList); DownloadSerialQueue(DownloadListener listener); void setListener(DownloadListener listener); synchronized void enqueue(DownloadTask task); synchronized void pause(); synchronized void resume(); int getWorkingTaskId(); int getWaitingTaskCount(); synchronized DownloadTask[] shutdown(); @Override void run(); @Override void taskStart(@NonNull DownloadTask task); @Override synchronized void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause); }### Answer: @Test public void setListener() { assertThat(serialQueue.listenerBunch.contain(listener)).isTrue(); final DownloadListener anotherListener = mock(DownloadListener.class); serialQueue.setListener(anotherListener); assertThat(serialQueue.listenerBunch.contain(listener)).isFalse(); assertThat(serialQueue.listenerBunch.contain(anotherListener)).isTrue(); }
### Question: KeyToIdMap { public void remove(int id) { final String key = idToKeyMap.get(id); if (key != null) { keyToIdMap.remove(key); idToKeyMap.remove(id); } } KeyToIdMap(); KeyToIdMap(@NonNull HashMap<String, Integer> keyToIdMap, @NonNull SparseArray<String> idToKeyMap); @Nullable Integer get(@NonNull DownloadTask task); void remove(int id); void add(@NonNull DownloadTask task, int id); }### Answer: @Test public void remove() { idToKeyMap.put(1, map.generateKey(task)); keyToIdMap.put(map.generateKey(task), 1); map.remove(1); assertThat(keyToIdMap).isEmpty(); assertThat(idToKeyMap.size()).isZero(); }
### Question: KeyToIdMap { public void add(@NonNull DownloadTask task, int id) { final String key = generateKey(task); keyToIdMap.put(key, id); idToKeyMap.put(id, key); } KeyToIdMap(); KeyToIdMap(@NonNull HashMap<String, Integer> keyToIdMap, @NonNull SparseArray<String> idToKeyMap); @Nullable Integer get(@NonNull DownloadTask task); void remove(int id); void add(@NonNull DownloadTask task, int id); }### Answer: @Test public void add() { final String key = map.generateKey(task); map.add(task, 1); assertThat(keyToIdMap).containsKeys(key); assertThat(keyToIdMap).containsValues(1); assertThat(idToKeyMap.size()).isOne(); assertThat(idToKeyMap.get(1)).isEqualTo(key); }
### Question: BreakpointInfo { @Nullable public File getFile() { final String filename = this.filenameHolder.get(); if (filename == null) return null; if (targetFile == null) targetFile = new File(parentFile, filename); return targetFile; } BreakpointInfo(int id, @NonNull String url, @NonNull File parentFile, @Nullable String filename); BreakpointInfo(int id, @NonNull String url, @NonNull File parentFile, @Nullable String filename, boolean taskOnlyProvidedParentPath); int getId(); void setChunked(boolean chunked); void addBlock(BlockInfo blockInfo); boolean isChunked(); boolean isLastBlock(int blockIndex); boolean isSingleBlock(); BlockInfo getBlock(int blockIndex); void resetInfo(); void resetBlockInfos(); int getBlockCount(); void setEtag(String etag); long getTotalOffset(); long getTotalLength(); @Nullable String getEtag(); String getUrl(); @Nullable String getFilename(); DownloadStrategy.FilenameHolder getFilenameHolder(); @Nullable File getFile(); BreakpointInfo copy(); BreakpointInfo copyWithReplaceId(int replaceId); void reuseBlocks(BreakpointInfo info); BreakpointInfo copyWithReplaceIdAndUrl(int replaceId, String newUrl); boolean isSameFrom(DownloadTask task); @Override String toString(); }### Answer: @Test public void getPath() { BreakpointInfo info = new BreakpointInfo(0, "", new File(""), null); assertThat(info.getFile()).isNull(); final String parentPath = "/sdcard"; final String filename = "abc"; info = new BreakpointInfo(0, "", new File(parentPath), filename); assertThat(info.getFile()).isEqualTo(new File(parentPath, filename)); }
### Question: BreakpointInfo { public long getTotalOffset() { long offset = 0; final Object[] blocks = blockInfoList.toArray(); if (blocks != null) { for (Object block : blocks) { if (block instanceof BlockInfo) { offset += ((BlockInfo) block).getCurrentOffset(); } } } return offset; } BreakpointInfo(int id, @NonNull String url, @NonNull File parentFile, @Nullable String filename); BreakpointInfo(int id, @NonNull String url, @NonNull File parentFile, @Nullable String filename, boolean taskOnlyProvidedParentPath); int getId(); void setChunked(boolean chunked); void addBlock(BlockInfo blockInfo); boolean isChunked(); boolean isLastBlock(int blockIndex); boolean isSingleBlock(); BlockInfo getBlock(int blockIndex); void resetInfo(); void resetBlockInfos(); int getBlockCount(); void setEtag(String etag); long getTotalOffset(); long getTotalLength(); @Nullable String getEtag(); String getUrl(); @Nullable String getFilename(); DownloadStrategy.FilenameHolder getFilenameHolder(); @Nullable File getFile(); BreakpointInfo copy(); BreakpointInfo copyWithReplaceId(int replaceId); void reuseBlocks(BreakpointInfo info); BreakpointInfo copyWithReplaceIdAndUrl(int replaceId, String newUrl); boolean isSameFrom(DownloadTask task); @Override String toString(); }### Answer: @Test public void getTotalOffset() { BreakpointInfo info = new BreakpointInfo(0, "", new File(""), null); info.addBlock(new BlockInfo(0, 10, 10)); info.addBlock(new BlockInfo(10, 18, 18)); info.addBlock(new BlockInfo(28, 66, 66)); assertThat(info.getTotalOffset()).isEqualTo(94); }
### Question: BreakpointInfo { public long getTotalLength() { if (isChunked()) return getTotalOffset(); long length = 0; final Object[] blocks = blockInfoList.toArray(); if (blocks != null) { for (Object block : blocks) { if (block instanceof BlockInfo) { length += ((BlockInfo) block).getContentLength(); } } } return length; } BreakpointInfo(int id, @NonNull String url, @NonNull File parentFile, @Nullable String filename); BreakpointInfo(int id, @NonNull String url, @NonNull File parentFile, @Nullable String filename, boolean taskOnlyProvidedParentPath); int getId(); void setChunked(boolean chunked); void addBlock(BlockInfo blockInfo); boolean isChunked(); boolean isLastBlock(int blockIndex); boolean isSingleBlock(); BlockInfo getBlock(int blockIndex); void resetInfo(); void resetBlockInfos(); int getBlockCount(); void setEtag(String etag); long getTotalOffset(); long getTotalLength(); @Nullable String getEtag(); String getUrl(); @Nullable String getFilename(); DownloadStrategy.FilenameHolder getFilenameHolder(); @Nullable File getFile(); BreakpointInfo copy(); BreakpointInfo copyWithReplaceId(int replaceId); void reuseBlocks(BreakpointInfo info); BreakpointInfo copyWithReplaceIdAndUrl(int replaceId, String newUrl); boolean isSameFrom(DownloadTask task); @Override String toString(); }### Answer: @Test public void getTotalLength() { BreakpointInfo info = new BreakpointInfo(0, "", new File(""), null); info.addBlock(new BlockInfo(0, 10)); info.addBlock(new BlockInfo(10, 18, 2)); info.addBlock(new BlockInfo(28, 66, 20)); assertThat(info.getTotalLength()).isEqualTo(94); }
### Question: BreakpointInfo { public boolean isSameFrom(DownloadTask task) { if (!parentFile.equals(task.getParentFile())) { return false; } if (!url.equals(task.getUrl())) return false; final String otherFilename = task.getFilename(); if (otherFilename != null && otherFilename.equals(filenameHolder.get())) return true; if (taskOnlyProvidedParentPath) { if (!task.isFilenameFromResponse()) return false; return otherFilename == null || otherFilename.equals(filenameHolder.get()); } return false; } BreakpointInfo(int id, @NonNull String url, @NonNull File parentFile, @Nullable String filename); BreakpointInfo(int id, @NonNull String url, @NonNull File parentFile, @Nullable String filename, boolean taskOnlyProvidedParentPath); int getId(); void setChunked(boolean chunked); void addBlock(BlockInfo blockInfo); boolean isChunked(); boolean isLastBlock(int blockIndex); boolean isSingleBlock(); BlockInfo getBlock(int blockIndex); void resetInfo(); void resetBlockInfos(); int getBlockCount(); void setEtag(String etag); long getTotalOffset(); long getTotalLength(); @Nullable String getEtag(); String getUrl(); @Nullable String getFilename(); DownloadStrategy.FilenameHolder getFilenameHolder(); @Nullable File getFile(); BreakpointInfo copy(); BreakpointInfo copyWithReplaceId(int replaceId); void reuseBlocks(BreakpointInfo info); BreakpointInfo copyWithReplaceIdAndUrl(int replaceId, String newUrl); boolean isSameFrom(DownloadTask task); @Override String toString(); }### Answer: @Test public void isSameFrom() { BreakpointInfo info = new BreakpointInfo(1, "url", new File("p-path"), "filename"); DownloadTask task = mock(DownloadTask.class); when(task.getUrl()).thenReturn("url"); when(task.getParentFile()).thenReturn(new File("p-path")); assertThat(info.isSameFrom(task)).isFalse(); when(task.getFilename()).thenReturn("filename"); assertThat(info.isSameFrom(task)).isTrue(); when(task.isFilenameFromResponse()).thenReturn(true); assertThat(info.isSameFrom(task)).isTrue(); info = new BreakpointInfo(1, "url", new File("p-path"), null); assertThat(info.isSameFrom(task)).isFalse(); when(task.isFilenameFromResponse()).thenReturn(false); assertThat(info.isSameFrom(task)).isFalse(); when(task.getFilename()).thenReturn(null); when(task.isFilenameFromResponse()).thenReturn(true); assertThat(info.isSameFrom(task)).isTrue(); when(task.getUrl()).thenReturn("not-same-url"); assertThat(info.isSameFrom(task)).isFalse(); }
### Question: BreakpointInfo { public BreakpointInfo copyWithReplaceId(int replaceId) { final BreakpointInfo info = new BreakpointInfo(replaceId, url, parentFile, filenameHolder.get(), taskOnlyProvidedParentPath); info.chunked = this.chunked; for (BlockInfo blockInfo : blockInfoList) { info.blockInfoList.add(blockInfo.copy()); } return info; } BreakpointInfo(int id, @NonNull String url, @NonNull File parentFile, @Nullable String filename); BreakpointInfo(int id, @NonNull String url, @NonNull File parentFile, @Nullable String filename, boolean taskOnlyProvidedParentPath); int getId(); void setChunked(boolean chunked); void addBlock(BlockInfo blockInfo); boolean isChunked(); boolean isLastBlock(int blockIndex); boolean isSingleBlock(); BlockInfo getBlock(int blockIndex); void resetInfo(); void resetBlockInfos(); int getBlockCount(); void setEtag(String etag); long getTotalOffset(); long getTotalLength(); @Nullable String getEtag(); String getUrl(); @Nullable String getFilename(); DownloadStrategy.FilenameHolder getFilenameHolder(); @Nullable File getFile(); BreakpointInfo copy(); BreakpointInfo copyWithReplaceId(int replaceId); void reuseBlocks(BreakpointInfo info); BreakpointInfo copyWithReplaceIdAndUrl(int replaceId, String newUrl); boolean isSameFrom(DownloadTask task); @Override String toString(); }### Answer: @Test public void copyWithReplaceId() { BreakpointInfo info = new BreakpointInfo(1, "url", new File("/p-path/"), "filename"); final BlockInfo oldBlockInfo = new BlockInfo(0, 1); info.addBlock(oldBlockInfo); info.setChunked(true); BreakpointInfo anotherInfo = info.copyWithReplaceId(2); assertThat(anotherInfo).isNotEqualTo(info); assertThat(anotherInfo.id).isEqualTo(2); assertThat(anotherInfo.getUrl()).isEqualTo("url"); assertThat(anotherInfo.getFile()).isEqualTo(new File("/p-path/filename")); assertThat(anotherInfo.getBlockCount()).isEqualTo(1); assertThat(anotherInfo.isChunked()).isTrue(); final BlockInfo newBlockInfo = anotherInfo.getBlock(0); assertThat(newBlockInfo).isNotEqualTo(oldBlockInfo); assertThat(newBlockInfo.getRangeLeft()).isEqualTo(oldBlockInfo.getRangeLeft()); assertThat(newBlockInfo.getRangeRight()).isEqualTo(oldBlockInfo.getRangeRight()); }
### Question: BreakpointInfo { public BreakpointInfo copyWithReplaceIdAndUrl(int replaceId, String newUrl) { final BreakpointInfo info = new BreakpointInfo(replaceId, newUrl, parentFile, filenameHolder.get(), taskOnlyProvidedParentPath); info.chunked = this.chunked; for (BlockInfo blockInfo : blockInfoList) { info.blockInfoList.add(blockInfo.copy()); } return info; } BreakpointInfo(int id, @NonNull String url, @NonNull File parentFile, @Nullable String filename); BreakpointInfo(int id, @NonNull String url, @NonNull File parentFile, @Nullable String filename, boolean taskOnlyProvidedParentPath); int getId(); void setChunked(boolean chunked); void addBlock(BlockInfo blockInfo); boolean isChunked(); boolean isLastBlock(int blockIndex); boolean isSingleBlock(); BlockInfo getBlock(int blockIndex); void resetInfo(); void resetBlockInfos(); int getBlockCount(); void setEtag(String etag); long getTotalOffset(); long getTotalLength(); @Nullable String getEtag(); String getUrl(); @Nullable String getFilename(); DownloadStrategy.FilenameHolder getFilenameHolder(); @Nullable File getFile(); BreakpointInfo copy(); BreakpointInfo copyWithReplaceId(int replaceId); void reuseBlocks(BreakpointInfo info); BreakpointInfo copyWithReplaceIdAndUrl(int replaceId, String newUrl); boolean isSameFrom(DownloadTask task); @Override String toString(); }### Answer: @Test public void copyWithReplaceIdAndUrl() { BreakpointInfo info = new BreakpointInfo(1, "url", new File("/p-path/"), "filename"); final BlockInfo oldBlockInfo = new BlockInfo(0, 1); info.addBlock(oldBlockInfo); info.setChunked(true); BreakpointInfo anotherInfo = info.copyWithReplaceIdAndUrl(2, "anotherUrl"); assertThat(anotherInfo).isNotEqualTo(info); assertThat(anotherInfo.id).isEqualTo(2); assertThat(anotherInfo.getUrl()).isEqualTo("anotherUrl"); assertThat(anotherInfo.getFile()).isEqualTo(new File("/p-path/filename")); assertThat(anotherInfo.getBlockCount()).isEqualTo(1); assertThat(anotherInfo.isChunked()).isTrue(); final BlockInfo newBlockInfo = anotherInfo.getBlock(0); assertThat(newBlockInfo).isNotEqualTo(oldBlockInfo); assertThat(newBlockInfo.getRangeLeft()).isEqualTo(oldBlockInfo.getRangeLeft()); assertThat(newBlockInfo.getRangeRight()).isEqualTo(oldBlockInfo.getRangeRight()); }
### Question: BlockInfo { public long getRangeRight() { return startOffset + contentLength - 1; } BlockInfo(long startOffset, long contentLength); BlockInfo(long startOffset, long contentLength, @IntRange(from = 0) long currentOffset); long getCurrentOffset(); long getStartOffset(); long getRangeLeft(); long getContentLength(); long getRangeRight(); void increaseCurrentOffset(@IntRange(from = 1) long increaseLength); void resetBlock(); BlockInfo copy(); @Override String toString(); }### Answer: @Test public void getRangeRight() { BlockInfo info = new BlockInfo(0, 3, 1); assertThat(info.getRangeRight()).isEqualTo(2); info = new BlockInfo(12, 6, 2); assertThat(info.getRangeRight()).isEqualTo(17); }
### Question: BlockInfo { public long getContentLength() { return contentLength; } BlockInfo(long startOffset, long contentLength); BlockInfo(long startOffset, long contentLength, @IntRange(from = 0) long currentOffset); long getCurrentOffset(); long getStartOffset(); long getRangeLeft(); long getContentLength(); long getRangeRight(); void increaseCurrentOffset(@IntRange(from = 1) long increaseLength); void resetBlock(); BlockInfo copy(); @Override String toString(); }### Answer: @Test public void chunked() { BlockInfo info = new BlockInfo(0, CHUNKED_CONTENT_LENGTH); assertThat(info.getContentLength()).isEqualTo(CHUNKED_CONTENT_LENGTH); }
### Question: DownloadSerialQueue extends DownloadListener2 implements Runnable { @Override public synchronized void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause) { if (cause != EndCause.CANCELED && task == runningTask) runningTask = null; } DownloadSerialQueue(); DownloadSerialQueue(DownloadListener listener, ArrayList<DownloadTask> taskList); DownloadSerialQueue(DownloadListener listener); void setListener(DownloadListener listener); synchronized void enqueue(DownloadTask task); synchronized void pause(); synchronized void resume(); int getWorkingTaskId(); int getWaitingTaskCount(); synchronized DownloadTask[] shutdown(); @Override void run(); @Override void taskStart(@NonNull DownloadTask task); @Override synchronized void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause); }### Answer: @Test public void taskEnd() { serialQueue.runningTask = task1; serialQueue.taskEnd(task1, EndCause.COMPLETED, null); assertThat(serialQueue.runningTask).isNull(); }
### Question: CallbackDispatcher { public void endTasksWithError(@NonNull final Collection<DownloadTask> errorCollection, @NonNull final Exception realCause) { if (errorCollection.size() <= 0) return; Util.d(TAG, "endTasksWithError error[" + errorCollection.size() + "] realCause: " + realCause); final Iterator<DownloadTask> iterator = errorCollection.iterator(); while (iterator.hasNext()) { final DownloadTask task = iterator.next(); if (!task.isAutoCallbackToUIThread()) { task.getListener().taskEnd(task, EndCause.ERROR, realCause); iterator.remove(); } } uiHandler.post(new Runnable() { @Override public void run() { for (DownloadTask task : errorCollection) { task.getListener().taskEnd(task, EndCause.ERROR, realCause); } } }); } CallbackDispatcher(@NonNull Handler handler, @NonNull DownloadListener transmit); CallbackDispatcher(); boolean isFetchProcessMoment(DownloadTask task); void endTasksWithError(@NonNull final Collection<DownloadTask> errorCollection, @NonNull final Exception realCause); void endTasks(@NonNull final Collection<DownloadTask> completedTaskCollection, @NonNull final Collection<DownloadTask> sameTaskConflictCollection, @NonNull final Collection<DownloadTask> fileBusyCollection); void endTasksWithCanceled(@NonNull final Collection<DownloadTask> canceledCollection); DownloadListener dispatch(); }### Answer: @Test public void endTasksWithError() { final Collection<DownloadTask> errorCollection = new ArrayList<>(); final Exception realCause = mock(Exception.class); final DownloadTask autoUiTask = mock(DownloadTask.class); final DownloadTask nonUiTask = mock(DownloadTask.class); final DownloadListener nonUiListener = mock(DownloadListener.class); final DownloadListener autoUiListener = mock(DownloadListener.class); when(autoUiTask.getListener()).thenReturn(autoUiListener); when(autoUiTask.isAutoCallbackToUIThread()).thenReturn(true); when(nonUiTask.getListener()).thenReturn(nonUiListener); when(nonUiTask.isAutoCallbackToUIThread()).thenReturn(false); errorCollection.add(autoUiTask); errorCollection.add(nonUiTask); dispatcher.endTasksWithError(errorCollection, realCause); verify(nonUiListener).taskEnd(eq(nonUiTask), eq(EndCause.ERROR), eq(realCause)); verify(handler).post(any(Runnable.class)); verify(autoUiListener).taskEnd(eq(autoUiTask), eq(EndCause.ERROR), eq(realCause)); }
### Question: CallbackDispatcher { public void endTasksWithCanceled(@NonNull final Collection<DownloadTask> canceledCollection) { if (canceledCollection.size() <= 0) return; Util.d(TAG, "endTasksWithCanceled canceled[" + canceledCollection.size() + "]"); final Iterator<DownloadTask> iterator = canceledCollection.iterator(); while (iterator.hasNext()) { final DownloadTask task = iterator.next(); if (!task.isAutoCallbackToUIThread()) { task.getListener().taskEnd(task, EndCause.CANCELED, null); iterator.remove(); } } uiHandler.post(new Runnable() { @Override public void run() { for (DownloadTask task : canceledCollection) { task.getListener().taskEnd(task, EndCause.CANCELED, null); } } }); } CallbackDispatcher(@NonNull Handler handler, @NonNull DownloadListener transmit); CallbackDispatcher(); boolean isFetchProcessMoment(DownloadTask task); void endTasksWithError(@NonNull final Collection<DownloadTask> errorCollection, @NonNull final Exception realCause); void endTasks(@NonNull final Collection<DownloadTask> completedTaskCollection, @NonNull final Collection<DownloadTask> sameTaskConflictCollection, @NonNull final Collection<DownloadTask> fileBusyCollection); void endTasksWithCanceled(@NonNull final Collection<DownloadTask> canceledCollection); DownloadListener dispatch(); }### Answer: @Test public void endTasksWithCanceled() { final Collection<DownloadTask> canceledCollection = new ArrayList<>(); final DownloadTask autoUiTask = mock(DownloadTask.class); final DownloadTask nonUiTask = mock(DownloadTask.class); final DownloadListener nonUiListener = mock(DownloadListener.class); final DownloadListener autoUiListener = mock(DownloadListener.class); when(autoUiTask.getListener()).thenReturn(autoUiListener); when(autoUiTask.isAutoCallbackToUIThread()).thenReturn(true); when(nonUiTask.getListener()).thenReturn(nonUiListener); when(nonUiTask.isAutoCallbackToUIThread()).thenReturn(false); canceledCollection.add(autoUiTask); canceledCollection.add(nonUiTask); dispatcher.endTasksWithCanceled(canceledCollection); verify(nonUiListener) .taskEnd(eq(nonUiTask), eq(EndCause.CANCELED), nullable(Exception.class)); verify(handler).post(any(Runnable.class)); verify(autoUiListener) .taskEnd(eq(autoUiTask), eq(EndCause.CANCELED), nullable(Exception.class)); }
### Question: CallbackDispatcher { public boolean isFetchProcessMoment(DownloadTask task) { final long minInterval = task.getMinIntervalMillisCallbackProcess(); final long now = SystemClock.uptimeMillis(); return minInterval <= 0 || now - DownloadTask.TaskHideWrapper .getLastCallbackProcessTs(task) >= minInterval; } CallbackDispatcher(@NonNull Handler handler, @NonNull DownloadListener transmit); CallbackDispatcher(); boolean isFetchProcessMoment(DownloadTask task); void endTasksWithError(@NonNull final Collection<DownloadTask> errorCollection, @NonNull final Exception realCause); void endTasks(@NonNull final Collection<DownloadTask> completedTaskCollection, @NonNull final Collection<DownloadTask> sameTaskConflictCollection, @NonNull final Collection<DownloadTask> fileBusyCollection); void endTasksWithCanceled(@NonNull final Collection<DownloadTask> canceledCollection); DownloadListener dispatch(); }### Answer: @Test public void isFetchProcessMoment_noMinInterval() { final DownloadTask task = mock(DownloadTask.class); when(task.getMinIntervalMillisCallbackProcess()).thenReturn(0); assertThat(dispatcher.isFetchProcessMoment(task)).isTrue(); } @Test public void isFetchProcessMoment_largeThanMinInterval() { final DownloadTask task = mock(DownloadTask.class); when(task.getMinIntervalMillisCallbackProcess()).thenReturn(1); assertThat(dispatcher.isFetchProcessMoment(task)).isTrue(); } @Test public void isFetchProcessMoment_lessThanMinInterval() { final DownloadTask task = mock(DownloadTask.class); when(task.getMinIntervalMillisCallbackProcess()).thenReturn(Integer.MAX_VALUE); assertThat(dispatcher.isFetchProcessMoment(task)).isFalse(); }
### Question: DownloadDispatcher { public void enqueue(DownloadTask[] tasks) { skipProceedCallCount.incrementAndGet(); enqueueLocked(tasks); skipProceedCallCount.decrementAndGet(); } DownloadDispatcher(); DownloadDispatcher(List<DownloadCall> readyAsyncCalls, List<DownloadCall> runningAsyncCalls, List<DownloadCall> runningSyncCalls, List<DownloadCall> finishingCalls); void setDownloadStore(@NonNull DownloadStore store); void enqueue(DownloadTask[] tasks); void enqueue(DownloadTask task); void execute(DownloadTask task); @SuppressWarnings("PMD.ForLoopsMustUseBraces") void cancelAll(); void cancel(IdentifiedTask[] tasks); boolean cancel(IdentifiedTask task); boolean cancel(int id); @Nullable synchronized DownloadTask findSameTask(DownloadTask task); synchronized boolean isRunning(DownloadTask task); synchronized boolean isPending(DownloadTask task); synchronized void flyingCanceled(DownloadCall call); synchronized void finish(DownloadCall call); synchronized boolean isFileConflictAfterRun(@NonNull DownloadTask task); static void setMaxParallelRunningCount(int maxParallelRunningCount); }### Answer: @Test public void enqueue_maxTaskCountControl() { maxRunningTask(); final DownloadTask mockTask = mockTask(); dispatcher.enqueue(mockTask); assertThat(readyAsyncCalls).hasSize(1); assertThat(readyAsyncCalls.get(0).task).isEqualTo(mockTask); assertThat(runningSyncCalls).isEmpty(); assertThat(runningAsyncCalls).hasSize(dispatcher.maxParallelRunningCount); } @Test public void enqueue_priority() { final DownloadTask mockTask1 = mockTask(); when(mockTask1.getPriority()).thenReturn(1); final DownloadTask mockTask2 = mockTask(); when(mockTask2.getPriority()).thenReturn(2); final DownloadTask mockTask3 = mockTask(); when(mockTask3.getPriority()).thenReturn(3); maxRunningTask(); dispatcher.enqueue(mockTask2); dispatcher.enqueue(mockTask1); dispatcher.enqueue(mockTask3); assertThat(readyAsyncCalls.get(0).task).isEqualTo(mockTask3); assertThat(readyAsyncCalls.get(1).task).isEqualTo(mockTask2); assertThat(readyAsyncCalls.get(2).task).isEqualTo(mockTask1); }
### Question: OkDownload { public static OkDownload with() { if (singleton == null) { synchronized (OkDownload.class) { if (singleton == null) { if (OkDownloadProvider.context == null) { throw new IllegalStateException("context == null"); } singleton = new Builder(OkDownloadProvider.context).build(); } } } return singleton; } OkDownload(Context context, DownloadDispatcher downloadDispatcher, CallbackDispatcher callbackDispatcher, DownloadStore store, DownloadConnection.Factory connectionFactory, DownloadOutputStream.Factory outputStreamFactory, ProcessFileStrategy processFileStrategy, DownloadStrategy downloadStrategy); DownloadDispatcher downloadDispatcher(); CallbackDispatcher callbackDispatcher(); BreakpointStore breakpointStore(); DownloadConnection.Factory connectionFactory(); DownloadOutputStream.Factory outputStreamFactory(); ProcessFileStrategy processFileStrategy(); DownloadStrategy downloadStrategy(); Context context(); void setMonitor(@Nullable DownloadMonitor monitor); @Nullable DownloadMonitor getMonitor(); static OkDownload with(); static void setSingletonInstance(@NonNull OkDownload okDownload); }### Answer: @Test(expected = IllegalStateException.class) public void with_noValidContext() { OkDownloadProvider.context = null; OkDownload.singleton = null; OkDownload.with(); } @Test public void with_valid() { OkDownloadProvider.context = mock(Context.class); OkDownload.singleton = null; assertThat(OkDownload.with()).isNotNull(); }
### Question: DownloadDispatcher { public void execute(DownloadTask task) { Util.d(TAG, "execute: " + task); final DownloadCall call; synchronized (this) { if (inspectCompleted(task)) return; if (inspectForConflict(task)) return; call = DownloadCall.create(task, false, store); runningSyncCalls.add(call); } syncRunCall(call); } DownloadDispatcher(); DownloadDispatcher(List<DownloadCall> readyAsyncCalls, List<DownloadCall> runningAsyncCalls, List<DownloadCall> runningSyncCalls, List<DownloadCall> finishingCalls); void setDownloadStore(@NonNull DownloadStore store); void enqueue(DownloadTask[] tasks); void enqueue(DownloadTask task); void execute(DownloadTask task); @SuppressWarnings("PMD.ForLoopsMustUseBraces") void cancelAll(); void cancel(IdentifiedTask[] tasks); boolean cancel(IdentifiedTask task); boolean cancel(int id); @Nullable synchronized DownloadTask findSameTask(DownloadTask task); synchronized boolean isRunning(DownloadTask task); synchronized boolean isPending(DownloadTask task); synchronized void flyingCanceled(DownloadCall call); synchronized void finish(DownloadCall call); synchronized boolean isFileConflictAfterRun(@NonNull DownloadTask task); static void setMaxParallelRunningCount(int maxParallelRunningCount); }### Answer: @Test public void execute() { final DownloadTask mockTask = mockTask(); dispatcher.execute(mockTask); ArgumentCaptor<DownloadCall> callCaptor = ArgumentCaptor.forClass(DownloadCall.class); verify(runningSyncCalls).add(callCaptor.capture()); final DownloadCall call = callCaptor.getValue(); assertThat(call.task).isEqualTo(mockTask); verify(dispatcher).syncRunCall(call); }
### Question: DownloadDispatcher { @SuppressWarnings("PMD.ForLoopsMustUseBraces") public void cancelAll() { skipProceedCallCount.incrementAndGet(); List<DownloadTask> taskList = new ArrayList<>(); for (DownloadCall call : readyAsyncCalls) taskList.add(call.task); for (DownloadCall call : runningAsyncCalls) taskList.add(call.task); for (DownloadCall call : runningSyncCalls) taskList.add(call.task); if (!taskList.isEmpty()) { DownloadTask[] tasks = new DownloadTask[taskList.size()]; cancelLocked(taskList.toArray(tasks)); } skipProceedCallCount.decrementAndGet(); } DownloadDispatcher(); DownloadDispatcher(List<DownloadCall> readyAsyncCalls, List<DownloadCall> runningAsyncCalls, List<DownloadCall> runningSyncCalls, List<DownloadCall> finishingCalls); void setDownloadStore(@NonNull DownloadStore store); void enqueue(DownloadTask[] tasks); void enqueue(DownloadTask task); void execute(DownloadTask task); @SuppressWarnings("PMD.ForLoopsMustUseBraces") void cancelAll(); void cancel(IdentifiedTask[] tasks); boolean cancel(IdentifiedTask task); boolean cancel(int id); @Nullable synchronized DownloadTask findSameTask(DownloadTask task); synchronized boolean isRunning(DownloadTask task); synchronized boolean isPending(DownloadTask task); synchronized void flyingCanceled(DownloadCall call); synchronized void finish(DownloadCall call); synchronized boolean isFileConflictAfterRun(@NonNull DownloadTask task); static void setMaxParallelRunningCount(int maxParallelRunningCount); }### Answer: @Test public void cancelAll() { List<DownloadCall> mockReadyAsyncCalls = new ArrayList<>(); mockReadyAsyncCalls.add(spy(DownloadCall.create(mockTask(1), true, store))); mockReadyAsyncCalls.add(spy(DownloadCall.create(mockTask(2), true, store))); mockReadyAsyncCalls.add(spy(DownloadCall.create(mockTask(3), true, store))); mockReadyAsyncCalls.add(spy(DownloadCall.create(mockTask(4), true, store))); readyAsyncCalls.addAll(mockReadyAsyncCalls); runningAsyncCalls.add(spy(DownloadCall.create(mockTask(5), true, store))); runningAsyncCalls.add(spy(DownloadCall.create(mockTask(6), true, store))); runningAsyncCalls.add(spy(DownloadCall.create(mockTask(7), true, store))); runningAsyncCalls.add(spy(DownloadCall.create(mockTask(8), true, store))); runningSyncCalls.add(spy(DownloadCall.create(mockTask(9), false, store))); runningSyncCalls.add(spy(DownloadCall.create(mockTask(10), false, store))); runningSyncCalls.add(spy(DownloadCall.create(mockTask(11), false, store))); runningSyncCalls.add(spy(DownloadCall.create(mockTask(12), false, store))); dispatcher.cancelAll(); assertThat(readyAsyncCalls).isEmpty(); final ArgumentCaptor<Collection<DownloadTask>> callCaptor = ArgumentCaptor.forClass(Collection.class); verify(OkDownload.with().callbackDispatcher()).endTasksWithCanceled(callCaptor.capture()); assertThat(callCaptor.getValue()).hasSize(12); for (DownloadCall call : mockReadyAsyncCalls) { verify(call, never()).cancel(); } assertThat(runningAsyncCalls).hasSize(4); for (DownloadCall call : runningAsyncCalls) { verify(call).cancel(); } assertThat(runningSyncCalls).hasSize(4); for (DownloadCall call : runningSyncCalls) { verify(call).cancel(); } }
### Question: DownloadDispatcher { public synchronized void finish(DownloadCall call) { final boolean asyncExecuted = call.asyncExecuted; final Collection<DownloadCall> calls; if (finishingCalls.contains(call)) { calls = finishingCalls; } else if (asyncExecuted) { calls = runningAsyncCalls; } else { calls = runningSyncCalls; } if (!calls.remove(call)) throw new AssertionError("Call wasn't in-flight!"); if (asyncExecuted && call.isCanceled()) flyingCanceledAsyncCallCount.decrementAndGet(); if (asyncExecuted) processCalls(); } DownloadDispatcher(); DownloadDispatcher(List<DownloadCall> readyAsyncCalls, List<DownloadCall> runningAsyncCalls, List<DownloadCall> runningSyncCalls, List<DownloadCall> finishingCalls); void setDownloadStore(@NonNull DownloadStore store); void enqueue(DownloadTask[] tasks); void enqueue(DownloadTask task); void execute(DownloadTask task); @SuppressWarnings("PMD.ForLoopsMustUseBraces") void cancelAll(); void cancel(IdentifiedTask[] tasks); boolean cancel(IdentifiedTask task); boolean cancel(int id); @Nullable synchronized DownloadTask findSameTask(DownloadTask task); synchronized boolean isRunning(DownloadTask task); synchronized boolean isPending(DownloadTask task); synchronized void flyingCanceled(DownloadCall call); synchronized void finish(DownloadCall call); synchronized boolean isFileConflictAfterRun(@NonNull DownloadTask task); static void setMaxParallelRunningCount(int maxParallelRunningCount); }### Answer: @Test(expected = AssertionError.class) public void finish_removeFailed_exception() { dispatcher.finish(mock(DownloadCall.class)); } @Test public void finish_removeCallFromRightList() { final DownloadCall finishingSyncCall = DownloadCall.create(mockTask(1), false, store); final DownloadCall finishingAsyncCall = DownloadCall.create(mockTask(2), true, store); final DownloadCall runningAsyncCall = DownloadCall.create(mockTask(3), true, store); final DownloadCall runningSyncCall = DownloadCall.create(mockTask(4), false, store); finishingCalls.add(finishingAsyncCall); finishingCalls.add(finishingSyncCall); runningAsyncCalls.add(runningAsyncCall); runningSyncCalls.add(runningSyncCall); dispatcher.finish(finishingAsyncCall); assertThat(finishingCalls).hasSize(1); verify(finishingCalls).remove(finishingAsyncCall); verify(runningAsyncCalls, never()).remove(any(DownloadCall.class)); verify(runningSyncCalls, never()).remove(any(DownloadCall.class)); dispatcher.finish(finishingSyncCall); assertThat(finishingCalls).hasSize(0); verify(finishingCalls).remove(finishingSyncCall); verify(runningAsyncCalls, never()).remove(any(DownloadCall.class)); verify(runningSyncCalls, never()).remove(any(DownloadCall.class)); dispatcher.finish(runningAsyncCall); verify(runningAsyncCalls).remove(runningAsyncCall); verify(runningSyncCalls, never()).remove(any(DownloadCall.class)); dispatcher.finish(runningSyncCall); verify(runningSyncCalls).remove(any(DownloadCall.class)); }
### Question: DownloadDispatcher { public synchronized boolean isFileConflictAfterRun(@NonNull DownloadTask task) { Util.d(TAG, "is file conflict after run: " + task.getId()); final File file = task.getFile(); if (file == null) return false; for (DownloadCall syncCall : runningSyncCalls) { if (syncCall.isCanceled() || syncCall.task == task) continue; final File otherFile = syncCall.task.getFile(); if (otherFile != null && file.equals(otherFile)) { return true; } } for (DownloadCall asyncCall : runningAsyncCalls) { if (asyncCall.isCanceled() || asyncCall.task == task) continue; final File otherFile = asyncCall.task.getFile(); if (otherFile != null && file.equals(otherFile)) { return true; } } return false; } DownloadDispatcher(); DownloadDispatcher(List<DownloadCall> readyAsyncCalls, List<DownloadCall> runningAsyncCalls, List<DownloadCall> runningSyncCalls, List<DownloadCall> finishingCalls); void setDownloadStore(@NonNull DownloadStore store); void enqueue(DownloadTask[] tasks); void enqueue(DownloadTask task); void execute(DownloadTask task); @SuppressWarnings("PMD.ForLoopsMustUseBraces") void cancelAll(); void cancel(IdentifiedTask[] tasks); boolean cancel(IdentifiedTask task); boolean cancel(int id); @Nullable synchronized DownloadTask findSameTask(DownloadTask task); synchronized boolean isRunning(DownloadTask task); synchronized boolean isPending(DownloadTask task); synchronized void flyingCanceled(DownloadCall call); synchronized void finish(DownloadCall call); synchronized boolean isFileConflictAfterRun(@NonNull DownloadTask task); static void setMaxParallelRunningCount(int maxParallelRunningCount); }### Answer: @Test public void isFileConflictAfterRun() { final DownloadTask mockAsyncTask = mockTask(); final DownloadTask samePathTask = mockTask(); doReturn(mockAsyncTask.getFile()).when(samePathTask).getFile(); DownloadCall call = spy(DownloadCall.create(mockAsyncTask, true, store)); runningAsyncCalls.add(call); boolean isConflict = dispatcher.isFileConflictAfterRun(samePathTask); assertThat(isConflict).isTrue(); when(call.isCanceled()).thenReturn(true); isConflict = dispatcher.isFileConflictAfterRun(samePathTask); assertThat(isConflict).isFalse(); when(call.isCanceled()).thenReturn(false); final DownloadTask mockSyncTask = mockTask(); doReturn(mockSyncTask.getFile()).when(samePathTask).getFile(); runningSyncCalls.add(DownloadCall.create(mockSyncTask, false, store)); isConflict = dispatcher.isFileConflictAfterRun(samePathTask); assertThat(isConflict).isTrue(); final DownloadTask noSamePathTask = mockTask(); isConflict = dispatcher.isFileConflictAfterRun(noSamePathTask); assertThat(isConflict).isFalse(); }