method2testcases
stringlengths
118
3.08k
### 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: 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: 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: 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: 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: 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: 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 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: 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: 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 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: 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 { public static void setMaxParallelRunningCount(int maxParallelRunningCount) { DownloadDispatcher dispatcher = OkDownload.with().downloadDispatcher(); if (dispatcher.getClass() != DownloadDispatcher.class) { throw new IllegalStateException( "The current dispatcher is " + dispatcher + " not DownloadDispatcher exactly!"); } maxParallelRunningCount = Math.max(1, maxParallelRunningCount); dispatcher.maxParallelRunningCount = maxParallelRunningCount; } 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 setMaxParallelRunningCount() { doReturn(mock(MockDownloadDispatcher.class)).when(OkDownload.with()).downloadDispatcher(); thrown.expect(IllegalStateException.class); DownloadDispatcher.setMaxParallelRunningCount(1); doReturn(dispatcher).when(OkDownload.with()).breakpointStore(); DownloadDispatcher.setMaxParallelRunningCount(0); assertThat(dispatcher.maxParallelRunningCount).isEqualTo(1); DownloadDispatcher.setMaxParallelRunningCount(2); assertThat(dispatcher.maxParallelRunningCount).isEqualTo(2); }
### Question: SpeedCalculator { public String speed() { return humanReadableSpeed(getBytesPerSecondAndFlush(), true); } synchronized void reset(); synchronized void downloading(long increaseBytes); synchronized void flush(); long getInstantBytesPerSecondAndFlush(); synchronized long getBytesPerSecondAndFlush(); synchronized long getBytesPerSecondFromBegin(); synchronized void endTask(); String instantSpeed(); String speed(); String lastSpeed(); synchronized long getInstantSpeedDurationMillis(); String getSpeedWithBinaryAndFlush(); String getSpeedWithSIAndFlush(); String averageSpeed(); String speedFromBegin(); }### Answer: @Test public void speed() { long now = 66; doReturn(now).when(calculator).nowMillis(); calculator.downloading(1000); now = 565; doReturn(now).when(calculator).nowMillis(); assertThat(calculator.speed()).isEqualTo("0 B/s"); now = 566; doReturn(now).when(calculator).nowMillis(); assertThat(calculator.speed()).isEqualTo("2.0 kB/s"); now = 1066; doReturn(now).when(calculator).nowMillis(); assertThat(calculator.speed()).isEqualTo("2.0 kB/s"); }
### Question: IdentifiedTask { public boolean compareIgnoreId(IdentifiedTask another) { if (!getUrl().equals(another.getUrl())) return false; if (getUrl().equals(EMPTY_URL) || getParentFile().equals(EMPTY_FILE)) return false; if (getProvidedPathFile().equals(another.getProvidedPathFile())) return true; if (!getParentFile().equals(another.getParentFile())) return false; final String filename = getFilename(); final String anotherFilename = another.getFilename(); return anotherFilename != null && filename != null && anotherFilename.equals(filename); } abstract int getId(); @NonNull abstract String getUrl(); @NonNull abstract File getParentFile(); @Nullable abstract String getFilename(); boolean compareIgnoreId(IdentifiedTask another); static final String EMPTY_URL; static final File EMPTY_FILE; }### Answer: @Test public void compareIgnoreId_falseEmpty() { final IdentifiedTask task = DownloadTask.mockTaskForCompare(1); final IdentifiedTask anotherTask = DownloadTask.mockTaskForCompare(2); assertThat(task.compareIgnoreId(task)).isFalse(); assertThat(task.compareIgnoreId(anotherTask)).isFalse(); }
### Question: SpeedCalculator { public String instantSpeed() { return getSpeedWithSIAndFlush(); } synchronized void reset(); synchronized void downloading(long increaseBytes); synchronized void flush(); long getInstantBytesPerSecondAndFlush(); synchronized long getBytesPerSecondAndFlush(); synchronized long getBytesPerSecondFromBegin(); synchronized void endTask(); String instantSpeed(); String speed(); String lastSpeed(); synchronized long getInstantSpeedDurationMillis(); String getSpeedWithBinaryAndFlush(); String getSpeedWithSIAndFlush(); String averageSpeed(); String speedFromBegin(); }### Answer: @Test public void instantSpeed() { doReturn("1").when(calculator).getSpeedWithSIAndFlush(); assertThat(calculator.instantSpeed()).isEqualTo("1"); }
### Question: ProcessFileStrategy { public void discardProcess(@NonNull DownloadTask task) throws IOException { final File file = task.getFile(); if (file == null) return; if (file.exists() && !file.delete()) { throw new IOException("Delete file failed!"); } } @NonNull MultiPointOutputStream createProcessStream(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull DownloadStore store); void completeProcessStream(@NonNull MultiPointOutputStream processOutputStream, @NonNull DownloadTask task); void discardProcess(@NonNull DownloadTask task); @NonNull FileLock getFileLock(); boolean isPreAllocateLength(@NonNull DownloadTask task); }### Answer: @Test public void discardProcess() throws IOException { final File existFile = new File("./exist-path"); existFile.createNewFile(); when(task.getFile()).thenReturn(existFile); strategy.discardProcess(task); assertThat(existFile.exists()).isFalse(); } @Test(expected = IOException.class) public void discardProcess_deleteFailed() throws IOException { final File file = mock(File.class); when(task.getFile()).thenReturn(file); when(file.exists()).thenReturn(true); when(file.delete()).thenReturn(false); strategy.discardProcess(task); }
### Question: ProcessFileStrategy { public boolean isPreAllocateLength(@NonNull DownloadTask task) { boolean supportSeek = OkDownload.with().outputStreamFactory().supportSeek(); if (!supportSeek) return false; if (task.getSetPreAllocateLength() != null) return task.getSetPreAllocateLength(); return true; } @NonNull MultiPointOutputStream createProcessStream(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull DownloadStore store); void completeProcessStream(@NonNull MultiPointOutputStream processOutputStream, @NonNull DownloadTask task); void discardProcess(@NonNull DownloadTask task); @NonNull FileLock getFileLock(); boolean isPreAllocateLength(@NonNull DownloadTask task); }### Answer: @Test public void isPreAllocateLength() throws IOException { mockOkDownload(); when(task.getSetPreAllocateLength()).thenReturn(null); final DownloadOutputStream.Factory factory = OkDownload.with().outputStreamFactory(); when(factory.supportSeek()).thenReturn(false); assertThat(strategy.isPreAllocateLength(task)).isFalse(); when(factory.supportSeek()).thenReturn(true); assertThat(strategy.isPreAllocateLength(task)).isTrue(); when(task.getSetPreAllocateLength()).thenReturn(false); assertThat(strategy.isPreAllocateLength(task)).isFalse(); when(task.getSetPreAllocateLength()).thenReturn(true); assertThat(strategy.isPreAllocateLength(task)).isTrue(); when(factory.supportSeek()).thenReturn(false); assertThat(strategy.isPreAllocateLength(task)).isFalse(); }
### Question: MultiPointOutputStream { public synchronized void write(int blockIndex, byte[] bytes, int length) throws IOException { if (canceled) return; outputStream(blockIndex).write(bytes, 0, length); allNoSyncLength.addAndGet(length); noSyncLengthMap.get(blockIndex).addAndGet(length); inspectAndPersist(); } MultiPointOutputStream(@NonNull final DownloadTask task, @NonNull BreakpointInfo info, @NonNull DownloadStore store, @Nullable Runnable syncRunnable); MultiPointOutputStream(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull DownloadStore store); synchronized void write(int blockIndex, byte[] bytes, int length); void cancelAsync(); synchronized void cancel(); void done(int blockIndex); void inspectComplete(int blockIndex); void setRequireStreamBlocks(List<Integer> requireStreamBlocks); void catchBlockConnectException(int blockIndex); }### Answer: @Test public void write() throws IOException { doReturn(stream0).when(multiPointOutputStream).outputStream(anyInt()); doNothing().when(multiPointOutputStream).inspectAndPersist(); multiPointOutputStream.noSyncLengthMap.put(1, new AtomicLong()); multiPointOutputStream.noSyncLengthMap.put(2, new AtomicLong()); multiPointOutputStream.write(2, bytes, 16); verify(stream0).write(eq(bytes), eq(0), eq(16)); assertThat(multiPointOutputStream.allNoSyncLength.get()).isEqualTo(16); assertThat(multiPointOutputStream.noSyncLengthMap.get(1).get()).isEqualTo(0); assertThat(multiPointOutputStream.noSyncLengthMap.get(2).get()).isEqualTo(16); verify(multiPointOutputStream).inspectAndPersist(); }
### Question: MultiPointOutputStream { public void done(int blockIndex) throws IOException { noMoreStreamList.add(blockIndex); try { if (syncException != null) throw syncException; if (syncFuture != null && !syncFuture.isDone()) { final AtomicLong noSyncLength = noSyncLengthMap.get(blockIndex); if (noSyncLength != null && noSyncLength.get() > 0) { inspectStreamState(doneState); final boolean isNoMoreStream = doneState.isNoMoreStream; ensureSync(isNoMoreStream, blockIndex); } } else { if (syncFuture == null) { Util.d(TAG, "OutputStream done but no need to ensure sync, because the " + "sync job not run yet. task[" + task.getId() + "] block[" + blockIndex + "]"); } else { Util.d(TAG, "OutputStream done but no need to ensure sync, because the " + "syncFuture.isDone[" + syncFuture.isDone() + "] task[" + task.getId() + "] block[" + blockIndex + "]"); } } } finally { close(blockIndex); } } MultiPointOutputStream(@NonNull final DownloadTask task, @NonNull BreakpointInfo info, @NonNull DownloadStore store, @Nullable Runnable syncRunnable); MultiPointOutputStream(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull DownloadStore store); synchronized void write(int blockIndex, byte[] bytes, int length); void cancelAsync(); synchronized void cancel(); void done(int blockIndex); void inspectComplete(int blockIndex); void setRequireStreamBlocks(List<Integer> requireStreamBlocks); void catchBlockConnectException(int blockIndex); }### Answer: @Test(expected = IOException.class) public void done_syncException() throws IOException { multiPointOutputStream.syncException = new IOException(); multiPointOutputStream.done(1); }
### Question: MultiPointOutputStream { void runSyncDelayException() { try { runSync(); } catch (IOException e) { syncException = e; Util.w(TAG, "Sync to breakpoint-store for task[" + task.getId() + "] " + "failed with cause: " + e); } } MultiPointOutputStream(@NonNull final DownloadTask task, @NonNull BreakpointInfo info, @NonNull DownloadStore store, @Nullable Runnable syncRunnable); MultiPointOutputStream(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull DownloadStore store); synchronized void write(int blockIndex, byte[] bytes, int length); void cancelAsync(); synchronized void cancel(); void done(int blockIndex); void inspectComplete(int blockIndex); void setRequireStreamBlocks(List<Integer> requireStreamBlocks); void catchBlockConnectException(int blockIndex); }### Answer: @Test public void runSyncDelayException() throws IOException { final IOException exception = mock(IOException.class); doThrow(exception).when(multiPointOutputStream).runSync(); multiPointOutputStream.runSyncDelayException(); assertThat(multiPointOutputStream.syncException).isEqualTo(exception); }
### Question: MultiPointOutputStream { boolean isNoNeedFlushForLength() { return allNoSyncLength.get() < syncBufferSize; } MultiPointOutputStream(@NonNull final DownloadTask task, @NonNull BreakpointInfo info, @NonNull DownloadStore store, @Nullable Runnable syncRunnable); MultiPointOutputStream(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull DownloadStore store); synchronized void write(int blockIndex, byte[] bytes, int length); void cancelAsync(); synchronized void cancel(); void done(int blockIndex); void inspectComplete(int blockIndex); void setRequireStreamBlocks(List<Integer> requireStreamBlocks); void catchBlockConnectException(int blockIndex); }### Answer: @Test public void isNoNeedFlushForLength() { multiPointOutputStream.allNoSyncLength.set(0); assertThat(multiPointOutputStream.isNoNeedFlushForLength()).isFalse(); multiPointOutputStream.allNoSyncLength.set(-1); assertThat(multiPointOutputStream.isNoNeedFlushForLength()).isTrue(); }
### Question: MultiPointOutputStream { long getNextParkMillisecond() { long farToLastSyncMills = now() - lastSyncTimestamp.get(); return syncBufferIntervalMills - farToLastSyncMills; } MultiPointOutputStream(@NonNull final DownloadTask task, @NonNull BreakpointInfo info, @NonNull DownloadStore store, @Nullable Runnable syncRunnable); MultiPointOutputStream(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull DownloadStore store); synchronized void write(int blockIndex, byte[] bytes, int length); void cancelAsync(); synchronized void cancel(); void done(int blockIndex); void inspectComplete(int blockIndex); void setRequireStreamBlocks(List<Integer> requireStreamBlocks); void catchBlockConnectException(int blockIndex); }### Answer: @Test public void getNextParkMillisecond() { when(multiPointOutputStream.now()).thenReturn(2L); multiPointOutputStream.lastSyncTimestamp.set(1L); assertThat(multiPointOutputStream.getNextParkMillisecond()).isEqualTo(-1L); }
### Question: SpeedCalculator { public String lastSpeed() { return humanReadableSpeed(bytesPerSecond, true); } synchronized void reset(); synchronized void downloading(long increaseBytes); synchronized void flush(); long getInstantBytesPerSecondAndFlush(); synchronized long getBytesPerSecondAndFlush(); synchronized long getBytesPerSecondFromBegin(); synchronized void endTask(); String instantSpeed(); String speed(); String lastSpeed(); synchronized long getInstantSpeedDurationMillis(); String getSpeedWithBinaryAndFlush(); String getSpeedWithSIAndFlush(); String averageSpeed(); String speedFromBegin(); }### Answer: @Test public void lastSpeed() { calculator.bytesPerSecond = 1; assertThat(calculator.lastSpeed()).isEqualTo("1 B/s"); }
### Question: MultiPointOutputStream { void inspectAndPersist() throws IOException { if (syncException != null) throw syncException; if (syncFuture == null) { synchronized (syncRunnable) { if (syncFuture == null) { syncFuture = executeSyncRunnableAsync(); } } } } MultiPointOutputStream(@NonNull final DownloadTask task, @NonNull BreakpointInfo info, @NonNull DownloadStore store, @Nullable Runnable syncRunnable); MultiPointOutputStream(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull DownloadStore store); synchronized void write(int blockIndex, byte[] bytes, int length); void cancelAsync(); synchronized void cancel(); void done(int blockIndex); void inspectComplete(int blockIndex); void setRequireStreamBlocks(List<Integer> requireStreamBlocks); void catchBlockConnectException(int blockIndex); }### Answer: @Test public void inspectAndPersist() throws IOException { final Future newFuture = mock(Future.class); doReturn(newFuture).when(multiPointOutputStream).executeSyncRunnableAsync(); multiPointOutputStream.syncFuture = syncFuture; multiPointOutputStream.inspectAndPersist(); assertThat(multiPointOutputStream.syncFuture).isEqualTo(syncFuture); multiPointOutputStream.syncFuture = null; multiPointOutputStream.inspectAndPersist(); assertThat(multiPointOutputStream.syncFuture).isEqualTo(newFuture); } @Test(expected = IOException.class) public void inspectAndPersist_syncException() throws IOException { multiPointOutputStream.syncException = new IOException(); multiPointOutputStream.inspectAndPersist(); } @Test(expected = IOException.class) public void inspectComplete_syncException() throws IOException { multiPointOutputStream.syncException = new IOException(); multiPointOutputStream.inspectAndPersist(); }
### Question: MultiPointOutputStream { public void inspectComplete(int blockIndex) throws IOException { final BlockInfo blockInfo = info.getBlock(blockIndex); if (!Util.isCorrectFull(blockInfo.getCurrentOffset(), blockInfo.getContentLength())) { throw new IOException("The current offset on block-info isn't update correct, " + blockInfo.getCurrentOffset() + " != " + blockInfo.getContentLength() + " on " + blockIndex); } } MultiPointOutputStream(@NonNull final DownloadTask task, @NonNull BreakpointInfo info, @NonNull DownloadStore store, @Nullable Runnable syncRunnable); MultiPointOutputStream(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull DownloadStore store); synchronized void write(int blockIndex, byte[] bytes, int length); void cancelAsync(); synchronized void cancel(); void done(int blockIndex); void inspectComplete(int blockIndex); void setRequireStreamBlocks(List<Integer> requireStreamBlocks); void catchBlockConnectException(int blockIndex); }### Answer: @Test(expected = IOException.class) public void inspectComplete_notFull() throws IOException { final BlockInfo blockInfo = mock(BlockInfo.class); when(info.getBlock(1)).thenReturn(blockInfo); when(blockInfo.getContentLength()).thenReturn(9L); when(blockInfo.getCurrentOffset()).thenReturn(10L); multiPointOutputStream.inspectComplete(1); }
### Question: MultiPointOutputStream { synchronized void close(int blockIndex) throws IOException { final DownloadOutputStream outputStream = outputStreamMap.get(blockIndex); if (outputStream != null) { outputStream.close(); outputStreamMap.remove(blockIndex); Util.d(TAG, "OutputStream close task[" + task.getId() + "] block[" + blockIndex + "]"); } } MultiPointOutputStream(@NonNull final DownloadTask task, @NonNull BreakpointInfo info, @NonNull DownloadStore store, @Nullable Runnable syncRunnable); MultiPointOutputStream(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull DownloadStore store); synchronized void write(int blockIndex, byte[] bytes, int length); void cancelAsync(); synchronized void cancel(); void done(int blockIndex); void inspectComplete(int blockIndex); void setRequireStreamBlocks(List<Integer> requireStreamBlocks); void catchBlockConnectException(int blockIndex); }### Answer: @Test public void close_noExist() throws IOException { final DownloadOutputStream stream0 = mock(DownloadOutputStream.class); final DownloadOutputStream stream1 = mock(DownloadOutputStream.class); multiPointOutputStream.outputStreamMap.put(0, stream0); multiPointOutputStream.outputStreamMap.put(1, stream1); multiPointOutputStream.close(2); verify(stream0, never()).close(); verify(stream1, never()).close(); assertThat(multiPointOutputStream.outputStreamMap.size()).isEqualTo(2); } @Test public void close() throws IOException { final DownloadOutputStream stream0 = mock(DownloadOutputStream.class); final DownloadOutputStream stream1 = mock(DownloadOutputStream.class); multiPointOutputStream.outputStreamMap.put(0, stream0); multiPointOutputStream.outputStreamMap.put(1, stream1); multiPointOutputStream.close(1); verify(stream0, never()).close(); verify(stream1).close(); assertThat(multiPointOutputStream.outputStreamMap.size()).isEqualTo(1); assertThat(multiPointOutputStream.outputStreamMap.get(0)).isEqualTo(stream0); }
### Question: MultiPointOutputStream { public void setRequireStreamBlocks(List<Integer> requireStreamBlocks) { this.requireStreamBlocks = requireStreamBlocks; } MultiPointOutputStream(@NonNull final DownloadTask task, @NonNull BreakpointInfo info, @NonNull DownloadStore store, @Nullable Runnable syncRunnable); MultiPointOutputStream(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull DownloadStore store); synchronized void write(int blockIndex, byte[] bytes, int length); void cancelAsync(); synchronized void cancel(); void done(int blockIndex); void inspectComplete(int blockIndex); void setRequireStreamBlocks(List<Integer> requireStreamBlocks); void catchBlockConnectException(int blockIndex); }### Answer: @Test public void setRequireStreamBlocks() { assertThat(multiPointOutputStream.requireStreamBlocks).isEqualTo(null); final List<Integer> requireStreamBlocks = new ArrayList<Integer>() {{ add(0); add(1); add(2); }}; multiPointOutputStream.setRequireStreamBlocks(requireStreamBlocks); assertThat(multiPointOutputStream.requireStreamBlocks).isEqualTo(requireStreamBlocks); }
### Question: SpeedCalculator { public synchronized long getInstantSpeedDurationMillis() { return nowMillis() - timestamp; } synchronized void reset(); synchronized void downloading(long increaseBytes); synchronized void flush(); long getInstantBytesPerSecondAndFlush(); synchronized long getBytesPerSecondAndFlush(); synchronized long getBytesPerSecondFromBegin(); synchronized void endTask(); String instantSpeed(); String speed(); String lastSpeed(); synchronized long getInstantSpeedDurationMillis(); String getSpeedWithBinaryAndFlush(); String getSpeedWithSIAndFlush(); String averageSpeed(); String speedFromBegin(); }### Answer: @Test public void getInstantSpeedDurationMillis() { doReturn(2L).when(calculator).nowMillis(); calculator.timestamp = 1; assertThat(calculator.getInstantSpeedDurationMillis()).isOne(); }
### Question: MultiPointOutputStream { void inspectFreeSpace(StatFs statFs, long requireSpace) throws PreAllocateException { final long freeSpace = Util.getFreeSpaceBytes(statFs); if (freeSpace < requireSpace) { throw new PreAllocateException(requireSpace, freeSpace); } } MultiPointOutputStream(@NonNull final DownloadTask task, @NonNull BreakpointInfo info, @NonNull DownloadStore store, @Nullable Runnable syncRunnable); MultiPointOutputStream(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull DownloadStore store); synchronized void write(int blockIndex, byte[] bytes, int length); void cancelAsync(); synchronized void cancel(); void done(int blockIndex); void inspectComplete(int blockIndex); void setRequireStreamBlocks(List<Integer> requireStreamBlocks); void catchBlockConnectException(int blockIndex); }### Answer: @Test public void inspectFreeSpace_freeSpaceNotEnough() throws PreAllocateException { final StatFs statFs = mock(StatFs.class); when(statFs.getAvailableBlocks()).thenReturn(1); when(statFs.getBlockSize()).thenReturn(2); thrown.expectMessage("There is Free space less than Require space: 2 < 3"); thrown.expect(PreAllocateException.class); multiPointOutputStream.inspectFreeSpace(statFs, 3); } @Test public void inspectFreeSpace() throws PreAllocateException { final StatFs statFs = mock(StatFs.class); when(statFs.getAvailableBlocks()).thenReturn(1); when(statFs.getBlockSize()).thenReturn(2); multiPointOutputStream.inspectFreeSpace(statFs, 2); }
### Question: MultiPointOutputStream { public void catchBlockConnectException(int blockIndex) { noMoreStreamList.add(blockIndex); } MultiPointOutputStream(@NonNull final DownloadTask task, @NonNull BreakpointInfo info, @NonNull DownloadStore store, @Nullable Runnable syncRunnable); MultiPointOutputStream(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull DownloadStore store); synchronized void write(int blockIndex, byte[] bytes, int length); void cancelAsync(); synchronized void cancel(); void done(int blockIndex); void inspectComplete(int blockIndex); void setRequireStreamBlocks(List<Integer> requireStreamBlocks); void catchBlockConnectException(int blockIndex); }### Answer: @Test public void catchBlockConnectException() { multiPointOutputStream.catchBlockConnectException(2); assertThat(multiPointOutputStream.noMoreStreamList).hasSize(1); assertThat(multiPointOutputStream.noMoreStreamList).containsExactly(2); }
### Question: FileLock { public void increaseLock(@NonNull String path) { AtomicInteger lockCount; synchronized (fileLockCountMap) { lockCount = fileLockCountMap.get(path); } if (lockCount == null) { lockCount = new AtomicInteger(0); synchronized (fileLockCountMap) { fileLockCountMap.put(path, lockCount); } } Util.d(TAG, "increaseLock increase lock-count to " + lockCount.incrementAndGet() + path); } FileLock(@NonNull Map<String, AtomicInteger> fileLockCountMap, @NonNull Map<String, Thread> waitThreadForFileLockMap); FileLock(); void increaseLock(@NonNull String path); void decreaseLock(@NonNull String path); void waitForRelease(@NonNull String filePath); }### Answer: @Test public void increaseLock() { fileLock.increaseLock(filePath1); assertThat(fileLockCountMap.get(filePath1).get()).isOne(); fileLock.increaseLock(filePath1); assertThat(fileLockCountMap.get(filePath1).get()).isEqualTo(2); fileLock.increaseLock(filePath2); assertThat(fileLockCountMap.get(filePath2).get()).isOne(); fileLock.increaseLock(filePath2); assertThat(fileLockCountMap.get(filePath2).get()).isEqualTo(2); }
### Question: FileLock { public void decreaseLock(@NonNull String path) { AtomicInteger lockCount; synchronized (fileLockCountMap) { lockCount = fileLockCountMap.get(path); } if (lockCount != null && lockCount.decrementAndGet() == 0) { Util.d(TAG, "decreaseLock decrease lock-count to 0 " + path); final Thread lockedThread; synchronized (waitThreadForFileLockMap) { lockedThread = waitThreadForFileLockMap.get(path); if (lockedThread != null) { waitThreadForFileLockMap.remove(path); } } if (lockedThread != null) { Util.d(TAG, "decreaseLock " + path + " unpark locked thread " + lockCount); unpark(lockedThread); } synchronized (fileLockCountMap) { fileLockCountMap.remove(path); } } } FileLock(@NonNull Map<String, AtomicInteger> fileLockCountMap, @NonNull Map<String, Thread> waitThreadForFileLockMap); FileLock(); void increaseLock(@NonNull String path); void decreaseLock(@NonNull String path); void waitForRelease(@NonNull String filePath); }### Answer: @Test public void decreaseLock() { waitThreadForFileLockMap.put(filePath1, lockedThread); fileLock.decreaseLock(filePath1); assertThat(fileLockCountMap.get(filePath1)).isNull(); fileLockCountMap.put(filePath1, new AtomicInteger(2)); fileLock.decreaseLock(filePath1); assertThat(fileLockCountMap.get(filePath1).get()).isOne(); fileLock.decreaseLock(filePath1); assertThat(fileLockCountMap.get(filePath1)).isNull(); verify(fileLock).unpark(eq(lockedThread)); assertThat(waitThreadForFileLockMap.isEmpty()).isTrue(); fileLock.decreaseLock(filePath2); assertThat(fileLockCountMap.get(filePath2)).isNull(); }
### Question: FileLock { public void waitForRelease(@NonNull String filePath) { AtomicInteger lockCount; synchronized (fileLockCountMap) { lockCount = fileLockCountMap.get(filePath); } if (lockCount == null || lockCount.get() <= 0) return; synchronized (waitThreadForFileLockMap) { waitThreadForFileLockMap.put(filePath, Thread.currentThread()); } Util.d(TAG, "waitForRelease start " + filePath); while (true) { if (isNotLocked(lockCount)) break; park(); } Util.d(TAG, "waitForRelease finish " + filePath); } FileLock(@NonNull Map<String, AtomicInteger> fileLockCountMap, @NonNull Map<String, Thread> waitThreadForFileLockMap); FileLock(); void increaseLock(@NonNull String path); void decreaseLock(@NonNull String path); void waitForRelease(@NonNull String filePath); }### Answer: @Test public void waitForRelease() { fileLock.waitForRelease(filePath1); verify(fileLock, never()).park(); assertThat(waitThreadForFileLockMap.isEmpty()).isTrue(); fileLockCountMap.put(filePath1, new AtomicInteger(1)); doReturn(false, true).when(fileLock).isNotLocked(any(AtomicInteger.class)); fileLock.waitForRelease(filePath1); assertThat(waitThreadForFileLockMap.get(filePath1)).isEqualTo(Thread.currentThread()); verify(fileLock).park(); }
### Question: DownloadUriOutputStream implements DownloadOutputStream { @Override public void write(byte[] b, int off, int len) throws IOException { out.write(b, off, len); } DownloadUriOutputStream(Context context, Uri uri, int bufferSize); DownloadUriOutputStream(@NonNull FileChannel channel, @NonNull ParcelFileDescriptor pdf, @NonNull FileOutputStream fos, @NonNull BufferedOutputStream out); @Override void write(byte[] b, int off, int len); @Override void close(); @Override void flushAndSync(); @Override void seek(long offset); @Override void setLength(long newLength); }### Answer: @Test public void write() throws Exception { byte[] bytes = new byte[2]; outputStream.write(bytes, 0, 1); verify(out).write(eq(bytes), eq(0), eq(1)); }
### Question: SpeedCalculator { public String getSpeedWithBinaryAndFlush() { return humanReadableSpeed(getInstantBytesPerSecondAndFlush(), false); } synchronized void reset(); synchronized void downloading(long increaseBytes); synchronized void flush(); long getInstantBytesPerSecondAndFlush(); synchronized long getBytesPerSecondAndFlush(); synchronized long getBytesPerSecondFromBegin(); synchronized void endTask(); String instantSpeed(); String speed(); String lastSpeed(); synchronized long getInstantSpeedDurationMillis(); String getSpeedWithBinaryAndFlush(); String getSpeedWithSIAndFlush(); String averageSpeed(); String speedFromBegin(); }### Answer: @Test public void getSpeedWithBinaryAndFlush() { doReturn(1054L).when(calculator).getInstantBytesPerSecondAndFlush(); assertThat(calculator.getSpeedWithBinaryAndFlush()).isEqualTo("1.0 KiB/s"); }
### Question: DownloadUriOutputStream implements DownloadOutputStream { @Override public void close() throws IOException { out.close(); fos.close(); pdf.close(); } DownloadUriOutputStream(Context context, Uri uri, int bufferSize); DownloadUriOutputStream(@NonNull FileChannel channel, @NonNull ParcelFileDescriptor pdf, @NonNull FileOutputStream fos, @NonNull BufferedOutputStream out); @Override void write(byte[] b, int off, int len); @Override void close(); @Override void flushAndSync(); @Override void seek(long offset); @Override void setLength(long newLength); }### Answer: @Test public void close() throws Exception { outputStream.close(); verify(out).close(); verify(fos).close(); }
### Question: DownloadUriOutputStream implements DownloadOutputStream { @Override public void flushAndSync() throws IOException { out.flush(); pdf.getFileDescriptor().sync(); } DownloadUriOutputStream(Context context, Uri uri, int bufferSize); DownloadUriOutputStream(@NonNull FileChannel channel, @NonNull ParcelFileDescriptor pdf, @NonNull FileOutputStream fos, @NonNull BufferedOutputStream out); @Override void write(byte[] b, int off, int len); @Override void close(); @Override void flushAndSync(); @Override void seek(long offset); @Override void setLength(long newLength); }### Answer: @Test public void flushAndSync() throws Exception { when(pdf.getFileDescriptor()).thenReturn(fd); thrown.expect(SyncFailedException.class); thrown.expectMessage("sync failed"); outputStream.flushAndSync(); verify(out).flush(); }
### Question: DownloadUriOutputStream implements DownloadOutputStream { @Override public void seek(long offset) throws IOException { channel.position(offset); } DownloadUriOutputStream(Context context, Uri uri, int bufferSize); DownloadUriOutputStream(@NonNull FileChannel channel, @NonNull ParcelFileDescriptor pdf, @NonNull FileOutputStream fos, @NonNull BufferedOutputStream out); @Override void write(byte[] b, int off, int len); @Override void close(); @Override void flushAndSync(); @Override void seek(long offset); @Override void setLength(long newLength); }### Answer: @Test public void seek() throws Exception { outputStream.seek(1); verify(channel).position(eq(1L)); }
### Question: DownloadUriOutputStream implements DownloadOutputStream { @Override public void setLength(long newLength) { final String tag = "DownloadUriOutputStream"; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { try { Os.posix_fallocate(pdf.getFileDescriptor(), 0, newLength); } catch (Throwable e) { if (e instanceof ErrnoException) { if (((ErrnoException) e).errno == OsConstants.ENOSYS || ((ErrnoException) e).errno == OsConstants.ENOTSUP) { Util.w(tag, "fallocate() not supported; falling back to ftruncate()"); try { Os.ftruncate(pdf.getFileDescriptor(), newLength); } catch (Throwable e1) { Util.w(tag, "It can't pre-allocate length(" + newLength + ") on the sdk" + " version(" + Build.VERSION.SDK_INT + "), because of " + e1); } } } else { Util.w(tag, "It can't pre-allocate length(" + newLength + ") on the sdk" + " version(" + Build.VERSION.SDK_INT + "), because of " + e); } } } else { Util.w(tag, "It can't pre-allocate length(" + newLength + ") on the sdk " + "version(" + Build.VERSION.SDK_INT + ")"); } } DownloadUriOutputStream(Context context, Uri uri, int bufferSize); DownloadUriOutputStream(@NonNull FileChannel channel, @NonNull ParcelFileDescriptor pdf, @NonNull FileOutputStream fos, @NonNull BufferedOutputStream out); @Override void write(byte[] b, int off, int len); @Override void close(); @Override void flushAndSync(); @Override void seek(long offset); @Override void setLength(long newLength); }### Answer: @Test public void setLength() { outputStream.setLength(1); verify(pdf).getFileDescriptor(); }
### Question: DownloadListener4 implements DownloadListener, Listener4Assist.Listener4Callback, ListenerAssist { public void setAssistExtend(@NonNull Listener4Assist.AssistExtend assistExtend) { this.assist.setAssistExtend(assistExtend); } DownloadListener4(Listener4Assist assist); DownloadListener4(); void setAssistExtend(@NonNull Listener4Assist.AssistExtend assistExtend); @Override boolean isAlwaysRecoverAssistModel(); @Override void setAlwaysRecoverAssistModel(boolean isAlwaysRecoverAssistModel); @Override void setAlwaysRecoverAssistModelIfNotSet(boolean isAlwaysRecoverAssistModel); @Override void connectTrialStart(@NonNull DownloadTask task, @NonNull Map<String, List<String>> requestHeaderFields); @Override void connectTrialEnd(@NonNull DownloadTask task, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields); @Override final void downloadFromBeginning(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull ResumeFailedCause cause); @Override final void downloadFromBreakpoint(@NonNull DownloadTask task, @NonNull BreakpointInfo info); @Override void fetchStart(@NonNull DownloadTask task, int blockIndex, long contentLength); @Override final void fetchProgress(@NonNull DownloadTask task, int blockIndex, long increaseBytes); @Override void fetchEnd(@NonNull DownloadTask task, int blockIndex, long contentLength); @Override final void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause); }### Answer: @Test public void setAssistExtend() { listener4.setAssistExtend(assistExtend); verify(assist).setAssistExtend(assistExtend); }
### Question: DownloadListener4 implements DownloadListener, Listener4Assist.Listener4Callback, ListenerAssist { @Override public final void downloadFromBeginning(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull ResumeFailedCause cause) { assist.infoReady(task, info, false); } DownloadListener4(Listener4Assist assist); DownloadListener4(); void setAssistExtend(@NonNull Listener4Assist.AssistExtend assistExtend); @Override boolean isAlwaysRecoverAssistModel(); @Override void setAlwaysRecoverAssistModel(boolean isAlwaysRecoverAssistModel); @Override void setAlwaysRecoverAssistModelIfNotSet(boolean isAlwaysRecoverAssistModel); @Override void connectTrialStart(@NonNull DownloadTask task, @NonNull Map<String, List<String>> requestHeaderFields); @Override void connectTrialEnd(@NonNull DownloadTask task, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields); @Override final void downloadFromBeginning(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull ResumeFailedCause cause); @Override final void downloadFromBreakpoint(@NonNull DownloadTask task, @NonNull BreakpointInfo info); @Override void fetchStart(@NonNull DownloadTask task, int blockIndex, long contentLength); @Override final void fetchProgress(@NonNull DownloadTask task, int blockIndex, long increaseBytes); @Override void fetchEnd(@NonNull DownloadTask task, int blockIndex, long contentLength); @Override final void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause); }### Answer: @Test public void downloadFromBeginning() { listener4.downloadFromBeginning(task, info, resumeFailedCause); verify(assist).infoReady(eq(task), eq(info), eq(false)); }
### Question: DownloadListener4 implements DownloadListener, Listener4Assist.Listener4Callback, ListenerAssist { @Override public final void downloadFromBreakpoint(@NonNull DownloadTask task, @NonNull BreakpointInfo info) { assist.infoReady(task, info, true); } DownloadListener4(Listener4Assist assist); DownloadListener4(); void setAssistExtend(@NonNull Listener4Assist.AssistExtend assistExtend); @Override boolean isAlwaysRecoverAssistModel(); @Override void setAlwaysRecoverAssistModel(boolean isAlwaysRecoverAssistModel); @Override void setAlwaysRecoverAssistModelIfNotSet(boolean isAlwaysRecoverAssistModel); @Override void connectTrialStart(@NonNull DownloadTask task, @NonNull Map<String, List<String>> requestHeaderFields); @Override void connectTrialEnd(@NonNull DownloadTask task, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields); @Override final void downloadFromBeginning(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull ResumeFailedCause cause); @Override final void downloadFromBreakpoint(@NonNull DownloadTask task, @NonNull BreakpointInfo info); @Override void fetchStart(@NonNull DownloadTask task, int blockIndex, long contentLength); @Override final void fetchProgress(@NonNull DownloadTask task, int blockIndex, long increaseBytes); @Override void fetchEnd(@NonNull DownloadTask task, int blockIndex, long contentLength); @Override final void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause); }### Answer: @Test public void downloadFromBreakpoint() { listener4.downloadFromBreakpoint(task, info); verify(assist).infoReady(eq(task), eq(info), eq(true)); }
### Question: DownloadListener4 implements DownloadListener, Listener4Assist.Listener4Callback, ListenerAssist { @Override public final void fetchProgress(@NonNull DownloadTask task, int blockIndex, long increaseBytes) { assist.fetchProgress(task, blockIndex, increaseBytes); } DownloadListener4(Listener4Assist assist); DownloadListener4(); void setAssistExtend(@NonNull Listener4Assist.AssistExtend assistExtend); @Override boolean isAlwaysRecoverAssistModel(); @Override void setAlwaysRecoverAssistModel(boolean isAlwaysRecoverAssistModel); @Override void setAlwaysRecoverAssistModelIfNotSet(boolean isAlwaysRecoverAssistModel); @Override void connectTrialStart(@NonNull DownloadTask task, @NonNull Map<String, List<String>> requestHeaderFields); @Override void connectTrialEnd(@NonNull DownloadTask task, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields); @Override final void downloadFromBeginning(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull ResumeFailedCause cause); @Override final void downloadFromBreakpoint(@NonNull DownloadTask task, @NonNull BreakpointInfo info); @Override void fetchStart(@NonNull DownloadTask task, int blockIndex, long contentLength); @Override final void fetchProgress(@NonNull DownloadTask task, int blockIndex, long increaseBytes); @Override void fetchEnd(@NonNull DownloadTask task, int blockIndex, long contentLength); @Override final void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause); }### Answer: @Test public void fetchProgress() { listener4.fetchProgress(task, 1, 2); verify(assist).fetchProgress(eq(task), eq(1), eq(2L)); }
### Question: DownloadListener4 implements DownloadListener, Listener4Assist.Listener4Callback, ListenerAssist { @Override public void fetchEnd(@NonNull DownloadTask task, int blockIndex, long contentLength) { assist.fetchEnd(task, blockIndex); } DownloadListener4(Listener4Assist assist); DownloadListener4(); void setAssistExtend(@NonNull Listener4Assist.AssistExtend assistExtend); @Override boolean isAlwaysRecoverAssistModel(); @Override void setAlwaysRecoverAssistModel(boolean isAlwaysRecoverAssistModel); @Override void setAlwaysRecoverAssistModelIfNotSet(boolean isAlwaysRecoverAssistModel); @Override void connectTrialStart(@NonNull DownloadTask task, @NonNull Map<String, List<String>> requestHeaderFields); @Override void connectTrialEnd(@NonNull DownloadTask task, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields); @Override final void downloadFromBeginning(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull ResumeFailedCause cause); @Override final void downloadFromBreakpoint(@NonNull DownloadTask task, @NonNull BreakpointInfo info); @Override void fetchStart(@NonNull DownloadTask task, int blockIndex, long contentLength); @Override final void fetchProgress(@NonNull DownloadTask task, int blockIndex, long increaseBytes); @Override void fetchEnd(@NonNull DownloadTask task, int blockIndex, long contentLength); @Override final void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause); }### Answer: @Test public void fetchEnd() { listener4.fetchEnd(task, 1, 2); verify(assist).fetchEnd(eq(task), eq(1)); }
### Question: DownloadListener4 implements DownloadListener, Listener4Assist.Listener4Callback, ListenerAssist { @Override public final void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause) { assist.taskEnd(task, cause, realCause); } DownloadListener4(Listener4Assist assist); DownloadListener4(); void setAssistExtend(@NonNull Listener4Assist.AssistExtend assistExtend); @Override boolean isAlwaysRecoverAssistModel(); @Override void setAlwaysRecoverAssistModel(boolean isAlwaysRecoverAssistModel); @Override void setAlwaysRecoverAssistModelIfNotSet(boolean isAlwaysRecoverAssistModel); @Override void connectTrialStart(@NonNull DownloadTask task, @NonNull Map<String, List<String>> requestHeaderFields); @Override void connectTrialEnd(@NonNull DownloadTask task, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields); @Override final void downloadFromBeginning(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull ResumeFailedCause cause); @Override final void downloadFromBreakpoint(@NonNull DownloadTask task, @NonNull BreakpointInfo info); @Override void fetchStart(@NonNull DownloadTask task, int blockIndex, long contentLength); @Override final void fetchProgress(@NonNull DownloadTask task, int blockIndex, long increaseBytes); @Override void fetchEnd(@NonNull DownloadTask task, int blockIndex, long contentLength); @Override final void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause); }### Answer: @Test public void taskEnd() { listener4.taskEnd(task, endCause, exception); verify(assist).taskEnd(eq(task), eq(endCause), eq(exception)); }
### Question: SpeedCalculator { public String getSpeedWithSIAndFlush() { return humanReadableSpeed(getInstantBytesPerSecondAndFlush(), true); } synchronized void reset(); synchronized void downloading(long increaseBytes); synchronized void flush(); long getInstantBytesPerSecondAndFlush(); synchronized long getBytesPerSecondAndFlush(); synchronized long getBytesPerSecondFromBegin(); synchronized void endTask(); String instantSpeed(); String speed(); String lastSpeed(); synchronized long getInstantSpeedDurationMillis(); String getSpeedWithBinaryAndFlush(); String getSpeedWithSIAndFlush(); String averageSpeed(); String speedFromBegin(); }### Answer: @Test public void getSpeedWithSIAndFlush() { doReturn(1054L).when(calculator).getInstantBytesPerSecondAndFlush(); assertThat(calculator.getSpeedWithSIAndFlush()).isEqualTo("1.1 kB/s"); }
### Question: DownloadListener4 implements DownloadListener, Listener4Assist.Listener4Callback, ListenerAssist { @Override public boolean isAlwaysRecoverAssistModel() { return assist.isAlwaysRecoverAssistModel(); } DownloadListener4(Listener4Assist assist); DownloadListener4(); void setAssistExtend(@NonNull Listener4Assist.AssistExtend assistExtend); @Override boolean isAlwaysRecoverAssistModel(); @Override void setAlwaysRecoverAssistModel(boolean isAlwaysRecoverAssistModel); @Override void setAlwaysRecoverAssistModelIfNotSet(boolean isAlwaysRecoverAssistModel); @Override void connectTrialStart(@NonNull DownloadTask task, @NonNull Map<String, List<String>> requestHeaderFields); @Override void connectTrialEnd(@NonNull DownloadTask task, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields); @Override final void downloadFromBeginning(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull ResumeFailedCause cause); @Override final void downloadFromBreakpoint(@NonNull DownloadTask task, @NonNull BreakpointInfo info); @Override void fetchStart(@NonNull DownloadTask task, int blockIndex, long contentLength); @Override final void fetchProgress(@NonNull DownloadTask task, int blockIndex, long increaseBytes); @Override void fetchEnd(@NonNull DownloadTask task, int blockIndex, long contentLength); @Override final void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause); }### Answer: @Test public void isAlwaysRecoverAssistModel() { when(assist.isAlwaysRecoverAssistModel()).thenReturn(true); assertThat(listener4.isAlwaysRecoverAssistModel()).isTrue(); when(assist.isAlwaysRecoverAssistModel()).thenReturn(false); assertThat(listener4.isAlwaysRecoverAssistModel()).isFalse(); }
### Question: DownloadListener4 implements DownloadListener, Listener4Assist.Listener4Callback, ListenerAssist { @Override public void setAlwaysRecoverAssistModel(boolean isAlwaysRecoverAssistModel) { assist.setAlwaysRecoverAssistModel(isAlwaysRecoverAssistModel); } DownloadListener4(Listener4Assist assist); DownloadListener4(); void setAssistExtend(@NonNull Listener4Assist.AssistExtend assistExtend); @Override boolean isAlwaysRecoverAssistModel(); @Override void setAlwaysRecoverAssistModel(boolean isAlwaysRecoverAssistModel); @Override void setAlwaysRecoverAssistModelIfNotSet(boolean isAlwaysRecoverAssistModel); @Override void connectTrialStart(@NonNull DownloadTask task, @NonNull Map<String, List<String>> requestHeaderFields); @Override void connectTrialEnd(@NonNull DownloadTask task, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields); @Override final void downloadFromBeginning(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull ResumeFailedCause cause); @Override final void downloadFromBreakpoint(@NonNull DownloadTask task, @NonNull BreakpointInfo info); @Override void fetchStart(@NonNull DownloadTask task, int blockIndex, long contentLength); @Override final void fetchProgress(@NonNull DownloadTask task, int blockIndex, long increaseBytes); @Override void fetchEnd(@NonNull DownloadTask task, int blockIndex, long contentLength); @Override final void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause); }### Answer: @Test public void setAlwaysRecoverAssistModel() { listener4.setAlwaysRecoverAssistModel(true); verify(assist).setAlwaysRecoverAssistModel(eq(true)); listener4.setAlwaysRecoverAssistModel(false); verify(assist).setAlwaysRecoverAssistModel(eq(false)); }
### Question: DownloadListener4 implements DownloadListener, Listener4Assist.Listener4Callback, ListenerAssist { @Override public void setAlwaysRecoverAssistModelIfNotSet(boolean isAlwaysRecoverAssistModel) { assist.setAlwaysRecoverAssistModelIfNotSet(isAlwaysRecoverAssistModel); } DownloadListener4(Listener4Assist assist); DownloadListener4(); void setAssistExtend(@NonNull Listener4Assist.AssistExtend assistExtend); @Override boolean isAlwaysRecoverAssistModel(); @Override void setAlwaysRecoverAssistModel(boolean isAlwaysRecoverAssistModel); @Override void setAlwaysRecoverAssistModelIfNotSet(boolean isAlwaysRecoverAssistModel); @Override void connectTrialStart(@NonNull DownloadTask task, @NonNull Map<String, List<String>> requestHeaderFields); @Override void connectTrialEnd(@NonNull DownloadTask task, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields); @Override final void downloadFromBeginning(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull ResumeFailedCause cause); @Override final void downloadFromBreakpoint(@NonNull DownloadTask task, @NonNull BreakpointInfo info); @Override void fetchStart(@NonNull DownloadTask task, int blockIndex, long contentLength); @Override final void fetchProgress(@NonNull DownloadTask task, int blockIndex, long increaseBytes); @Override void fetchEnd(@NonNull DownloadTask task, int blockIndex, long contentLength); @Override final void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause); }### Answer: @Test public void setAlwaysRecoverAssistModelIfNotSet() { listener4.setAlwaysRecoverAssistModelIfNotSet(true); verify(assist).setAlwaysRecoverAssistModelIfNotSet(eq(true)); listener4.setAlwaysRecoverAssistModelIfNotSet(false); verify(assist).setAlwaysRecoverAssistModelIfNotSet(eq(false)); }
### Question: Listener4SpeedAssistExtend implements Listener4Assist.AssistExtend, ListenerModelHandler.ModelCreator<Listener4SpeedAssistExtend.Listener4SpeedModel> { @Override public boolean dispatchBlockEnd(DownloadTask task, int blockIndex, Listener4Assist.Listener4Model model) { final Listener4SpeedModel speedModel = (Listener4SpeedModel) model; speedModel.blockSpeeds.get(blockIndex).endTask(); if (callback != null) { callback.blockEnd(task, blockIndex, model.info.getBlock(blockIndex), speedModel.getBlockSpeed(blockIndex)); } return true; } void setCallback(Listener4SpeedCallback callback); @Override boolean dispatchInfoReady(DownloadTask task, @NonNull BreakpointInfo info, boolean fromBreakpoint, @NonNull Listener4Assist.Listener4Model model); @Override boolean dispatchFetchProgress(@NonNull DownloadTask task, int blockIndex, long increaseBytes, @NonNull Listener4Assist.Listener4Model model); @Override boolean dispatchBlockEnd(DownloadTask task, int blockIndex, Listener4Assist.Listener4Model model); @Override boolean dispatchTaskEnd(DownloadTask task, EndCause cause, @Nullable Exception realCause, @NonNull Listener4Assist.Listener4Model model); @Override Listener4SpeedModel create(int id); }### Answer: @Test public void dispatchBlockEnd() { final boolean result = assistExtend.dispatchBlockEnd(task, 0, model); assertThat(result).isTrue(); verify(model.blockSpeeds.get(0)).endTask(); verify(callback) .blockEnd(task, eq(0), info.getBlock(0), model.getBlockSpeed(0)); }
### Question: Listener4Assist implements ListenerAssist { public void setCallback(@NonNull Listener4Callback callback) { this.callback = callback; } Listener4Assist(ListenerModelHandler<T> handler); Listener4Assist(ListenerModelHandler.ModelCreator<T> creator); void setCallback(@NonNull Listener4Callback callback); void setAssistExtend(@NonNull AssistExtend assistExtend); AssistExtend getAssistExtend(); void infoReady(DownloadTask task, BreakpointInfo info, boolean fromBreakpoint); void fetchProgress(DownloadTask task, int blockIndex, long increaseBytes); void fetchEnd(DownloadTask task, int blockIndex); synchronized void taskEnd(DownloadTask task, EndCause cause, @Nullable Exception realCause); @Override boolean isAlwaysRecoverAssistModel(); @Override void setAlwaysRecoverAssistModel(boolean isAlwaysRecoverAssistModel); @Override void setAlwaysRecoverAssistModelIfNotSet(boolean isAlwaysRecoverAssistModel); }### Answer: @Test public void setCallback() { assist.setCallback(callback); assertThat(assist.callback).isEqualTo(callback); }
### Question: Listener4Assist implements ListenerAssist { public void setAssistExtend(@NonNull AssistExtend assistExtend) { this.assistExtend = assistExtend; } Listener4Assist(ListenerModelHandler<T> handler); Listener4Assist(ListenerModelHandler.ModelCreator<T> creator); void setCallback(@NonNull Listener4Callback callback); void setAssistExtend(@NonNull AssistExtend assistExtend); AssistExtend getAssistExtend(); void infoReady(DownloadTask task, BreakpointInfo info, boolean fromBreakpoint); void fetchProgress(DownloadTask task, int blockIndex, long increaseBytes); void fetchEnd(DownloadTask task, int blockIndex); synchronized void taskEnd(DownloadTask task, EndCause cause, @Nullable Exception realCause); @Override boolean isAlwaysRecoverAssistModel(); @Override void setAlwaysRecoverAssistModel(boolean isAlwaysRecoverAssistModel); @Override void setAlwaysRecoverAssistModelIfNotSet(boolean isAlwaysRecoverAssistModel); }### Answer: @Test public void setAssistExtend() { assist.setAssistExtend(assistExtend); assertThat(assist.getAssistExtend()).isEqualTo(assistExtend); }
### Question: SpeedCalculator { public String averageSpeed() { return speedFromBegin(); } synchronized void reset(); synchronized void downloading(long increaseBytes); synchronized void flush(); long getInstantBytesPerSecondAndFlush(); synchronized long getBytesPerSecondAndFlush(); synchronized long getBytesPerSecondFromBegin(); synchronized void endTask(); String instantSpeed(); String speed(); String lastSpeed(); synchronized long getInstantSpeedDurationMillis(); String getSpeedWithBinaryAndFlush(); String getSpeedWithSIAndFlush(); String averageSpeed(); String speedFromBegin(); }### Answer: @Test public void averageSpeed() { doReturn("1").when(calculator).speedFromBegin(); assertThat(calculator.averageSpeed()).isEqualTo("1"); }
### Question: DownloadSerialQueue extends DownloadListener2 implements Runnable { public synchronized void enqueue(DownloadTask task) { taskList.add(task); Collections.sort(taskList); if (!paused && !looping) { looping = true; startNewLooper(); } } 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 enqueue() { doNothing().when(serialQueue).startNewLooper(); when(task1.compareTo(task2)).thenReturn(-1); serialQueue.enqueue(task2); serialQueue.enqueue(task1); verify(taskList).add(eq(task1)); verify(taskList).add(eq(task2)); assertThat(taskList).containsExactly(task1, task2); }
### Question: Listener4Assist implements ListenerAssist { @Override public boolean isAlwaysRecoverAssistModel() { return modelHandler.isAlwaysRecoverAssistModel(); } Listener4Assist(ListenerModelHandler<T> handler); Listener4Assist(ListenerModelHandler.ModelCreator<T> creator); void setCallback(@NonNull Listener4Callback callback); void setAssistExtend(@NonNull AssistExtend assistExtend); AssistExtend getAssistExtend(); void infoReady(DownloadTask task, BreakpointInfo info, boolean fromBreakpoint); void fetchProgress(DownloadTask task, int blockIndex, long increaseBytes); void fetchEnd(DownloadTask task, int blockIndex); synchronized void taskEnd(DownloadTask task, EndCause cause, @Nullable Exception realCause); @Override boolean isAlwaysRecoverAssistModel(); @Override void setAlwaysRecoverAssistModel(boolean isAlwaysRecoverAssistModel); @Override void setAlwaysRecoverAssistModelIfNotSet(boolean isAlwaysRecoverAssistModel); }### Answer: @Test public void isAlwaysRecoverAssistModel() { when(handler.isAlwaysRecoverAssistModel()).thenReturn(true); assertThat(assist.isAlwaysRecoverAssistModel()).isTrue(); when(handler.isAlwaysRecoverAssistModel()).thenReturn(false); assertThat(assist.isAlwaysRecoverAssistModel()).isFalse(); }
### Question: Listener4Assist implements ListenerAssist { @Override public void setAlwaysRecoverAssistModel(boolean isAlwaysRecoverAssistModel) { modelHandler.setAlwaysRecoverAssistModel(isAlwaysRecoverAssistModel); } Listener4Assist(ListenerModelHandler<T> handler); Listener4Assist(ListenerModelHandler.ModelCreator<T> creator); void setCallback(@NonNull Listener4Callback callback); void setAssistExtend(@NonNull AssistExtend assistExtend); AssistExtend getAssistExtend(); void infoReady(DownloadTask task, BreakpointInfo info, boolean fromBreakpoint); void fetchProgress(DownloadTask task, int blockIndex, long increaseBytes); void fetchEnd(DownloadTask task, int blockIndex); synchronized void taskEnd(DownloadTask task, EndCause cause, @Nullable Exception realCause); @Override boolean isAlwaysRecoverAssistModel(); @Override void setAlwaysRecoverAssistModel(boolean isAlwaysRecoverAssistModel); @Override void setAlwaysRecoverAssistModelIfNotSet(boolean isAlwaysRecoverAssistModel); }### Answer: @Test public void setAlwaysRecoverAssistModel() { assist.setAlwaysRecoverAssistModel(true); verify(handler).setAlwaysRecoverAssistModel(eq(true)); assist.setAlwaysRecoverAssistModel(false); verify(handler).setAlwaysRecoverAssistModel(eq(false)); }
### Question: SpeedCalculator { public String speedFromBegin() { return humanReadableSpeed(getBytesPerSecondFromBegin(), true); } synchronized void reset(); synchronized void downloading(long increaseBytes); synchronized void flush(); long getInstantBytesPerSecondAndFlush(); synchronized long getBytesPerSecondAndFlush(); synchronized long getBytesPerSecondFromBegin(); synchronized void endTask(); String instantSpeed(); String speed(); String lastSpeed(); synchronized long getInstantSpeedDurationMillis(); String getSpeedWithBinaryAndFlush(); String getSpeedWithSIAndFlush(); String averageSpeed(); String speedFromBegin(); }### Answer: @Test public void speedFromBegin() { doReturn(1L).when(calculator).getBytesPerSecondFromBegin(); assertThat(calculator.speedFromBegin()).isEqualTo("1 B/s"); }
### Question: Listener4Assist implements ListenerAssist { @Override public void setAlwaysRecoverAssistModelIfNotSet(boolean isAlwaysRecoverAssistModel) { modelHandler.setAlwaysRecoverAssistModelIfNotSet(isAlwaysRecoverAssistModel); } Listener4Assist(ListenerModelHandler<T> handler); Listener4Assist(ListenerModelHandler.ModelCreator<T> creator); void setCallback(@NonNull Listener4Callback callback); void setAssistExtend(@NonNull AssistExtend assistExtend); AssistExtend getAssistExtend(); void infoReady(DownloadTask task, BreakpointInfo info, boolean fromBreakpoint); void fetchProgress(DownloadTask task, int blockIndex, long increaseBytes); void fetchEnd(DownloadTask task, int blockIndex); synchronized void taskEnd(DownloadTask task, EndCause cause, @Nullable Exception realCause); @Override boolean isAlwaysRecoverAssistModel(); @Override void setAlwaysRecoverAssistModel(boolean isAlwaysRecoverAssistModel); @Override void setAlwaysRecoverAssistModelIfNotSet(boolean isAlwaysRecoverAssistModel); }### Answer: @Test public void setAlwaysRecoverAssistModelIfNotSet() { assist.setAlwaysRecoverAssistModelIfNotSet(true); verify(handler).setAlwaysRecoverAssistModelIfNotSet(eq(true)); assist.setAlwaysRecoverAssistModelIfNotSet(false); verify(handler).setAlwaysRecoverAssistModelIfNotSet(eq(false)); }
### Question: ListenerModelHandler implements ListenerAssist { @NonNull T addAndGetModel(@NonNull DownloadTask task, @Nullable BreakpointInfo info) { T model = creator.create(task.getId()); synchronized (this) { if (singleTaskModel == null) { singleTaskModel = model; } else { modelList.put(task.getId(), model); } if (info != null) { model.onInfoValid(info); } } return model; } ListenerModelHandler(ModelCreator<T> creator); boolean isAlwaysRecoverAssistModel(); void setAlwaysRecoverAssistModel(boolean isAlwaysRecoverModel); @Override void setAlwaysRecoverAssistModelIfNotSet(boolean isAlwaysRecoverAssistModel); }### Answer: @Test public void addAndGetModel_provideInfo() { final ListenerModelHandler.ListenerModel model = handler.addAndGetModel(task, info); assertThat(model).isEqualTo(this.model); verify(creator).create(anyInt()); assertThat(handler.singleTaskModel).isEqualTo(model); assertThat(handler.modelList.size()).isZero(); verify(model).onInfoValid(eq(info)); handler.addAndGetModel(task, info); assertThat(handler.modelList.size()).isOne(); } @Test public void addAndGetModel_noInfo() { final ListenerModelHandler.ListenerModel model = handler.addAndGetModel(task, null); assertThat(model).isEqualTo(this.model); verify(creator).create(anyInt()); assertThat(handler.singleTaskModel).isEqualTo(model); assertThat(handler.modelList.size()).isZero(); verify(model, never()).onInfoValid(eq(info)); }
### Question: ListenerModelHandler implements ListenerAssist { @NonNull T removeOrCreate(@NonNull DownloadTask task, @Nullable BreakpointInfo info) { final int id = task.getId(); T model; synchronized (this) { if (singleTaskModel != null && singleTaskModel.getId() == id) { model = singleTaskModel; singleTaskModel = null; } else { model = modelList.get(id); modelList.remove(id); } } if (model == null) { model = creator.create(id); if (info != null) { model.onInfoValid(info); } } return model; } ListenerModelHandler(ModelCreator<T> creator); boolean isAlwaysRecoverAssistModel(); void setAlwaysRecoverAssistModel(boolean isAlwaysRecoverModel); @Override void setAlwaysRecoverAssistModelIfNotSet(boolean isAlwaysRecoverAssistModel); }### Answer: @Test public void removeOrCreate_withInfo() { handler.singleTaskModel = model; assertThat(handler.removeOrCreate(task, info)).isEqualTo(model); verify(creator, never()).create(anyInt()); verify(model, never()).onInfoValid(eq(info)); handler.singleTaskModel = null; handler.modelList.put(task.getId(), model); assertThat(handler.removeOrCreate(task, info)).isEqualTo(model); verify(creator, never()).create(anyInt()); verify(model, never()).onInfoValid(eq(info)); handler.modelList.clear(); assertThat(handler.removeOrCreate(task, info)).isEqualTo(model); verify(creator).create(anyInt()); verify(model).onInfoValid(eq(info)); } @Test public void removeOrCreate_noInfo() { handler.modelList.clear(); assertThat(handler.removeOrCreate(task, null)).isEqualTo(model); verify(creator).create(anyInt()); verify(model, never()).onInfoValid(any(BreakpointInfo.class)); }
### Question: Listener1Assist implements ListenerAssist, ListenerModelHandler.ModelCreator<Listener1Assist.Listener1Model> { public void taskStart(DownloadTask task) { final Listener1Model model = modelHandler.addAndGetModel(task, null); if (callback != null) callback.taskStart(task, model); } Listener1Assist(); Listener1Assist(ListenerModelHandler<Listener1Model> handler); void setCallback(@NonNull Listener1Callback callback); void taskStart(DownloadTask task); void taskEnd(DownloadTask task, EndCause cause, @Nullable Exception realCause); void downloadFromBeginning(DownloadTask task, @NonNull BreakpointInfo info, ResumeFailedCause cause); void downloadFromBreakpoint(DownloadTask task, @NonNull BreakpointInfo info); void connectEnd(DownloadTask task); void fetchProgress(DownloadTask task, long increaseBytes); @Override boolean isAlwaysRecoverAssistModel(); @Override void setAlwaysRecoverAssistModel(boolean isAlwaysRecoverAssistModel); @Override void setAlwaysRecoverAssistModelIfNotSet(boolean isAlwaysRecoverAssistModel); @Override Listener1Model create(int id); }### Answer: @Test public void taskStart() { when(handler.addAndGetModel(task, null)).thenReturn(model); assist.taskStart(task); verify(callback).taskStart(eq(task), eq(model)); }
### Question: Listener1Assist implements ListenerAssist, ListenerModelHandler.ModelCreator<Listener1Assist.Listener1Model> { public void taskEnd(DownloadTask task, EndCause cause, @Nullable Exception realCause) { Listener1Model model = modelHandler.removeOrCreate(task, task.getInfo()); if (callback != null) callback.taskEnd(task, cause, realCause, model); } Listener1Assist(); Listener1Assist(ListenerModelHandler<Listener1Model> handler); void setCallback(@NonNull Listener1Callback callback); void taskStart(DownloadTask task); void taskEnd(DownloadTask task, EndCause cause, @Nullable Exception realCause); void downloadFromBeginning(DownloadTask task, @NonNull BreakpointInfo info, ResumeFailedCause cause); void downloadFromBreakpoint(DownloadTask task, @NonNull BreakpointInfo info); void connectEnd(DownloadTask task); void fetchProgress(DownloadTask task, long increaseBytes); @Override boolean isAlwaysRecoverAssistModel(); @Override void setAlwaysRecoverAssistModel(boolean isAlwaysRecoverAssistModel); @Override void setAlwaysRecoverAssistModelIfNotSet(boolean isAlwaysRecoverAssistModel); @Override Listener1Model create(int id); }### Answer: @Test public void taskEnd() { when(handler.removeOrCreate(task, info)).thenReturn(model); assist.taskEnd(task, EndCause.COMPLETED, null); verify(handler).removeOrCreate(eq(task), nullable(BreakpointInfo.class)); verify(callback).taskEnd(eq(task), eq(EndCause.COMPLETED), nullable(Exception.class), eq(model)); }
### Question: Listener1Assist implements ListenerAssist, ListenerModelHandler.ModelCreator<Listener1Assist.Listener1Model> { public void downloadFromBreakpoint(DownloadTask task, @NonNull BreakpointInfo info) { final Listener1Model model = modelHandler.getOrRecoverModel(task, info); if (model == null) return; model.onInfoValid(info); model.isStarted = true; model.isFromResumed = true; model.isFirstConnect = true; } Listener1Assist(); Listener1Assist(ListenerModelHandler<Listener1Model> handler); void setCallback(@NonNull Listener1Callback callback); void taskStart(DownloadTask task); void taskEnd(DownloadTask task, EndCause cause, @Nullable Exception realCause); void downloadFromBeginning(DownloadTask task, @NonNull BreakpointInfo info, ResumeFailedCause cause); void downloadFromBreakpoint(DownloadTask task, @NonNull BreakpointInfo info); void connectEnd(DownloadTask task); void fetchProgress(DownloadTask task, long increaseBytes); @Override boolean isAlwaysRecoverAssistModel(); @Override void setAlwaysRecoverAssistModel(boolean isAlwaysRecoverAssistModel); @Override void setAlwaysRecoverAssistModelIfNotSet(boolean isAlwaysRecoverAssistModel); @Override Listener1Model create(int id); }### Answer: @Test public void downloadFromBreakpoint() { when(handler.getOrRecoverModel(task, info)).thenReturn(null); assist.downloadFromBreakpoint(task, info); verify(model, never()).onInfoValid(eq(info)); when(handler.getOrRecoverModel(task, info)).thenReturn(model); assist.downloadFromBreakpoint(task, info); verify(model).onInfoValid(eq(info)); final Listener1Assist.Listener1Model model = new Listener1Assist.Listener1Model(1); when(handler.getOrRecoverModel(task, info)).thenReturn(model); assist.downloadFromBreakpoint(task, info); assertThat(model.isStarted).isTrue(); assertThat(model.isFromResumed).isTrue(); assertThat(model.isFirstConnect).isTrue(); }
### Question: StatusUtil { public static Status getStatus(@NonNull DownloadTask task) { final Status status = isCompletedOrUnknown(task); if (status == Status.COMPLETED) return Status.COMPLETED; final DownloadDispatcher dispatcher = OkDownload.with().downloadDispatcher(); if (dispatcher.isPending(task)) return Status.PENDING; if (dispatcher.isRunning(task)) return Status.RUNNING; return status; } static boolean isSameTaskPendingOrRunning(@NonNull DownloadTask task); static Status getStatus(@NonNull DownloadTask task); static Status getStatus(@NonNull String url, @NonNull String parentPath, @Nullable String filename); static boolean isCompleted(@NonNull DownloadTask task); static Status isCompletedOrUnknown(@NonNull DownloadTask task); static boolean isCompleted(@NonNull String url, @NonNull String parentPath, @Nullable String filename); @Nullable static BreakpointInfo getCurrentInfo(@NonNull String url, @NonNull String parentPath, @Nullable String filename); @Nullable static BreakpointInfo getCurrentInfo(@NonNull DownloadTask task); }### Answer: @Test public void getStatus() throws IOException { file.getParentFile().mkdirs(); file.createNewFile(); assertThat(file.exists()).isTrue(); StatusUtil.Status status = StatusUtil .getStatus(url, file.getParent(), file.getName()); assertThat(status).isEqualTo(COMPLETED); status = StatusUtil.getStatus(url, file.getParentFile().getPath(), null); assertThat(status).isEqualTo(UNKNOWN); final DownloadDispatcher dispatcher = OkDownload.with().downloadDispatcher(); doReturn(true).when(dispatcher).isRunning(any(DownloadTask.class)); status = StatusUtil.getStatus(url, file.getParentFile().getPath(), null); assertThat(status).isEqualTo(RUNNING); doReturn(true).when(dispatcher).isPending(any(DownloadTask.class)); status = StatusUtil.getStatus(url, file.getParentFile().getPath(), null); assertThat(status).isEqualTo(PENDING); }
### Question: Listener1Assist implements ListenerAssist, ListenerModelHandler.ModelCreator<Listener1Assist.Listener1Model> { public void fetchProgress(DownloadTask task, long increaseBytes) { final Listener1Model model = modelHandler.getOrRecoverModel(task, task.getInfo()); if (model == null) return; model.currentOffset.addAndGet(increaseBytes); if (callback != null) callback.progress(task, model.currentOffset.get(), model.totalLength); } Listener1Assist(); Listener1Assist(ListenerModelHandler<Listener1Model> handler); void setCallback(@NonNull Listener1Callback callback); void taskStart(DownloadTask task); void taskEnd(DownloadTask task, EndCause cause, @Nullable Exception realCause); void downloadFromBeginning(DownloadTask task, @NonNull BreakpointInfo info, ResumeFailedCause cause); void downloadFromBreakpoint(DownloadTask task, @NonNull BreakpointInfo info); void connectEnd(DownloadTask task); void fetchProgress(DownloadTask task, long increaseBytes); @Override boolean isAlwaysRecoverAssistModel(); @Override void setAlwaysRecoverAssistModel(boolean isAlwaysRecoverAssistModel); @Override void setAlwaysRecoverAssistModelIfNotSet(boolean isAlwaysRecoverAssistModel); @Override Listener1Model create(int id); }### Answer: @Test public void fetchProgress() { when(handler.getOrRecoverModel(task, info)).thenReturn(null); assist.fetchProgress(task, 1); verify(callback, never()).progress(eq(task), anyLong(), anyLong()); final Listener1Assist.Listener1Model model = new Listener1Assist.Listener1Model(1); model.currentOffset.set(2); model.totalLength = 3; when(handler.getOrRecoverModel(task, info)).thenReturn(model); assist.fetchProgress(task, 1); verify(callback).progress(eq(task), eq(2L + 1L), eq(3L)); }
### Question: Listener1Assist implements ListenerAssist, ListenerModelHandler.ModelCreator<Listener1Assist.Listener1Model> { @Override public boolean isAlwaysRecoverAssistModel() { return modelHandler.isAlwaysRecoverAssistModel(); } Listener1Assist(); Listener1Assist(ListenerModelHandler<Listener1Model> handler); void setCallback(@NonNull Listener1Callback callback); void taskStart(DownloadTask task); void taskEnd(DownloadTask task, EndCause cause, @Nullable Exception realCause); void downloadFromBeginning(DownloadTask task, @NonNull BreakpointInfo info, ResumeFailedCause cause); void downloadFromBreakpoint(DownloadTask task, @NonNull BreakpointInfo info); void connectEnd(DownloadTask task); void fetchProgress(DownloadTask task, long increaseBytes); @Override boolean isAlwaysRecoverAssistModel(); @Override void setAlwaysRecoverAssistModel(boolean isAlwaysRecoverAssistModel); @Override void setAlwaysRecoverAssistModelIfNotSet(boolean isAlwaysRecoverAssistModel); @Override Listener1Model create(int id); }### Answer: @Test public void isAlwaysRecoverAssistModel() { when(handler.isAlwaysRecoverAssistModel()).thenReturn(true); assertThat(assist.isAlwaysRecoverAssistModel()).isTrue(); when(handler.isAlwaysRecoverAssistModel()).thenReturn(false); assertThat(assist.isAlwaysRecoverAssistModel()).isFalse(); }
### Question: Listener1Assist implements ListenerAssist, ListenerModelHandler.ModelCreator<Listener1Assist.Listener1Model> { @Override public void setAlwaysRecoverAssistModel(boolean isAlwaysRecoverAssistModel) { modelHandler.setAlwaysRecoverAssistModel(isAlwaysRecoverAssistModel); } Listener1Assist(); Listener1Assist(ListenerModelHandler<Listener1Model> handler); void setCallback(@NonNull Listener1Callback callback); void taskStart(DownloadTask task); void taskEnd(DownloadTask task, EndCause cause, @Nullable Exception realCause); void downloadFromBeginning(DownloadTask task, @NonNull BreakpointInfo info, ResumeFailedCause cause); void downloadFromBreakpoint(DownloadTask task, @NonNull BreakpointInfo info); void connectEnd(DownloadTask task); void fetchProgress(DownloadTask task, long increaseBytes); @Override boolean isAlwaysRecoverAssistModel(); @Override void setAlwaysRecoverAssistModel(boolean isAlwaysRecoverAssistModel); @Override void setAlwaysRecoverAssistModelIfNotSet(boolean isAlwaysRecoverAssistModel); @Override Listener1Model create(int id); }### Answer: @Test public void setAlwaysRecoverAssistModel() { assist.setAlwaysRecoverAssistModel(true); verify(handler).setAlwaysRecoverAssistModel(eq(true)); assist.setAlwaysRecoverAssistModel(false); verify(handler).setAlwaysRecoverAssistModel(eq(false)); }
### Question: Listener1Assist implements ListenerAssist, ListenerModelHandler.ModelCreator<Listener1Assist.Listener1Model> { @Override public void setAlwaysRecoverAssistModelIfNotSet(boolean isAlwaysRecoverAssistModel) { modelHandler.setAlwaysRecoverAssistModelIfNotSet(isAlwaysRecoverAssistModel); } Listener1Assist(); Listener1Assist(ListenerModelHandler<Listener1Model> handler); void setCallback(@NonNull Listener1Callback callback); void taskStart(DownloadTask task); void taskEnd(DownloadTask task, EndCause cause, @Nullable Exception realCause); void downloadFromBeginning(DownloadTask task, @NonNull BreakpointInfo info, ResumeFailedCause cause); void downloadFromBreakpoint(DownloadTask task, @NonNull BreakpointInfo info); void connectEnd(DownloadTask task); void fetchProgress(DownloadTask task, long increaseBytes); @Override boolean isAlwaysRecoverAssistModel(); @Override void setAlwaysRecoverAssistModel(boolean isAlwaysRecoverAssistModel); @Override void setAlwaysRecoverAssistModelIfNotSet(boolean isAlwaysRecoverAssistModel); @Override Listener1Model create(int id); }### Answer: @Test public void setAlwaysRecoverAssistModelIfNotSet() { assist.setAlwaysRecoverAssistModelIfNotSet(true); verify(handler).setAlwaysRecoverAssistModelIfNotSet(eq(true)); assist.setAlwaysRecoverAssistModelIfNotSet(false); verify(handler).setAlwaysRecoverAssistModelIfNotSet(eq(false)); }
### Question: DownloadListener2 implements DownloadListener { @Override public void connectTrialStart(@NonNull DownloadTask task, @NonNull Map<String, List<String>> requestHeaderFields) { } @Override void connectTrialStart(@NonNull DownloadTask task, @NonNull Map<String, List<String>> requestHeaderFields); @Override void connectTrialEnd(@NonNull DownloadTask task, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields); @Override void downloadFromBeginning(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull ResumeFailedCause cause); @Override void downloadFromBreakpoint(@NonNull DownloadTask task, @NonNull BreakpointInfo info); @Override void connectStart(@NonNull DownloadTask task, int blockIndex, @NonNull Map<String, List<String>> requestHeaderFields); @Override void connectEnd(@NonNull DownloadTask task, int blockIndex, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields); @Override void fetchStart(@NonNull DownloadTask task, int blockIndex, long contentLength); @Override void fetchProgress(@NonNull DownloadTask task, int blockIndex, long increaseBytes); @Override void fetchEnd(@NonNull DownloadTask task, int blockIndex, long contentLength); }### Answer: @Test public void connectTrialStart() throws Exception { listener2.connectTrialStart(task, headerFields); }
### Question: DownloadListener2 implements DownloadListener { @Override public void connectTrialEnd(@NonNull DownloadTask task, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields) { } @Override void connectTrialStart(@NonNull DownloadTask task, @NonNull Map<String, List<String>> requestHeaderFields); @Override void connectTrialEnd(@NonNull DownloadTask task, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields); @Override void downloadFromBeginning(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull ResumeFailedCause cause); @Override void downloadFromBreakpoint(@NonNull DownloadTask task, @NonNull BreakpointInfo info); @Override void connectStart(@NonNull DownloadTask task, int blockIndex, @NonNull Map<String, List<String>> requestHeaderFields); @Override void connectEnd(@NonNull DownloadTask task, int blockIndex, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields); @Override void fetchStart(@NonNull DownloadTask task, int blockIndex, long contentLength); @Override void fetchProgress(@NonNull DownloadTask task, int blockIndex, long increaseBytes); @Override void fetchEnd(@NonNull DownloadTask task, int blockIndex, long contentLength); }### Answer: @Test public void connectTrialEnd() throws Exception { listener2.connectTrialEnd(task, 200, headerFields); }
### Question: DownloadListener2 implements DownloadListener { @Override public void downloadFromBeginning(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull ResumeFailedCause cause) { } @Override void connectTrialStart(@NonNull DownloadTask task, @NonNull Map<String, List<String>> requestHeaderFields); @Override void connectTrialEnd(@NonNull DownloadTask task, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields); @Override void downloadFromBeginning(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull ResumeFailedCause cause); @Override void downloadFromBreakpoint(@NonNull DownloadTask task, @NonNull BreakpointInfo info); @Override void connectStart(@NonNull DownloadTask task, int blockIndex, @NonNull Map<String, List<String>> requestHeaderFields); @Override void connectEnd(@NonNull DownloadTask task, int blockIndex, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields); @Override void fetchStart(@NonNull DownloadTask task, int blockIndex, long contentLength); @Override void fetchProgress(@NonNull DownloadTask task, int blockIndex, long increaseBytes); @Override void fetchEnd(@NonNull DownloadTask task, int blockIndex, long contentLength); }### Answer: @Test public void downloadFromBeginning() throws Exception { listener2.downloadFromBeginning(task, info, cause); }
### Question: DownloadListener2 implements DownloadListener { @Override public void downloadFromBreakpoint(@NonNull DownloadTask task, @NonNull BreakpointInfo info) { } @Override void connectTrialStart(@NonNull DownloadTask task, @NonNull Map<String, List<String>> requestHeaderFields); @Override void connectTrialEnd(@NonNull DownloadTask task, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields); @Override void downloadFromBeginning(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull ResumeFailedCause cause); @Override void downloadFromBreakpoint(@NonNull DownloadTask task, @NonNull BreakpointInfo info); @Override void connectStart(@NonNull DownloadTask task, int blockIndex, @NonNull Map<String, List<String>> requestHeaderFields); @Override void connectEnd(@NonNull DownloadTask task, int blockIndex, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields); @Override void fetchStart(@NonNull DownloadTask task, int blockIndex, long contentLength); @Override void fetchProgress(@NonNull DownloadTask task, int blockIndex, long increaseBytes); @Override void fetchEnd(@NonNull DownloadTask task, int blockIndex, long contentLength); }### Answer: @Test public void downloadFromBreakpoint() throws Exception { listener2.downloadFromBreakpoint(task, info); }
### Question: DownloadListener2 implements DownloadListener { @Override public void connectStart(@NonNull DownloadTask task, int blockIndex, @NonNull Map<String, List<String>> requestHeaderFields) { } @Override void connectTrialStart(@NonNull DownloadTask task, @NonNull Map<String, List<String>> requestHeaderFields); @Override void connectTrialEnd(@NonNull DownloadTask task, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields); @Override void downloadFromBeginning(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull ResumeFailedCause cause); @Override void downloadFromBreakpoint(@NonNull DownloadTask task, @NonNull BreakpointInfo info); @Override void connectStart(@NonNull DownloadTask task, int blockIndex, @NonNull Map<String, List<String>> requestHeaderFields); @Override void connectEnd(@NonNull DownloadTask task, int blockIndex, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields); @Override void fetchStart(@NonNull DownloadTask task, int blockIndex, long contentLength); @Override void fetchProgress(@NonNull DownloadTask task, int blockIndex, long increaseBytes); @Override void fetchEnd(@NonNull DownloadTask task, int blockIndex, long contentLength); }### Answer: @Test public void connectStart() throws Exception { listener2.connectStart(task, 1, headerFields); }