method2testcases stringlengths 118 3.08k |
|---|
### Question:
RecursionExample { public int fibonacci(int n){ if (n <=1 ){ return n; } return fibonacci(n-1) + fibonacci(n-2); } int sum(int n); int tailSum(int currentSum, int n); int iterativeSum(int n); int powerOf10(int n); int fibonacci(int n); String toBinary(int n); int calculateTreeHeight(BinaryNode root); int max(int a,int b); }### Answer:
@Test public void testFibonacci() { int n0 = recursion.fibonacci(0); int n1 = recursion.fibonacci(1); int n7 = recursion.fibonacci(7); Assert.assertEquals(0, n0); Assert.assertEquals(1, n1); Assert.assertEquals(13, n7); } |
### Question:
RecursionExample { public String toBinary(int n){ if (n <= 1 ){ return String.valueOf(n); } return toBinary(n / 2) + String.valueOf(n % 2); } int sum(int n); int tailSum(int currentSum, int n); int iterativeSum(int n); int powerOf10(int n); int fibonacci(int n); String toBinary(int n); int calculateTreeHeight(BinaryNode root); int max(int a,int b); }### Answer:
@Test public void testToBinary() { String b0 = recursion.toBinary(0); String b1 = recursion.toBinary(1); String b10 = recursion.toBinary(10); Assert.assertEquals("0", b0); Assert.assertEquals("1", b1); Assert.assertEquals("1010", b10); } |
### Question:
RecursionExample { public int calculateTreeHeight(BinaryNode root){ if (root!= null){ if (root.getLeft() != null || root.getRight() != null){ return 1 + max(calculateTreeHeight(root.left) , calculateTreeHeight(root.right)); } } return 0; } int sum(int n); int tailSum(int currentSum, int n); int iterativeSum(int n); int powerOf10(int n); int fibonacci(int n); String toBinary(int n); int calculateTreeHeight(BinaryNode root); int max(int a,int b); }### Answer:
@Test public void testCalculateTreeHeight() { BinaryNode root = new BinaryNode(1); root.setLeft(new BinaryNode(1)); root.setRight(new BinaryNode(1)); root.getLeft().setLeft(new BinaryNode(1)); root.getLeft().getLeft().setRight(new BinaryNode(1)); root.getLeft().getLeft().getRight().setLeft(new BinaryNode(1)); root.getRight().setLeft(new BinaryNode(1)); root.getRight().getLeft().setRight(new BinaryNode(1)); int height = recursion.calculateTreeHeight(root); Assert.assertEquals(4, height); } |
### Question:
ActiveJDBCApp { protected void delete() { Employee employee = Employee.findFirst("first_name = ?","Hugo"); employee.delete(); employee = Employee.findFirst("last_name = ?","Choi"); if(null == employee){ System.out.println("No such Employee found!"); } } static void main( String[] args ); }### Answer:
@Test public void ifEmployeeCreatedWithRoles_whenDeleted_thenShouldNotBeFound() { Employee employee = new Employee("Binesh", "N", "M", "BN"); employee.saveIt(); employee.add(new Role("Java Developer","BN")); employee.delete(); employee = Employee.findFirst("first_name = ?", "Binesh"); the(employee).shouldBeNull(); } |
### Question:
UserValidator { public Validation<Seq<String>, User> validateUser(String name, String email) { return Validation .combine(validateField(name, NAME_PATTERN, NAME_ERROR) ,validateField(email, EMAIL_PATTERN, EMAIL_ERROR)) .ap(User::new); } Validation<Seq<String>, User> validateUser(String name, String email); }### Answer:
@Test public void givenValidUserParams_whenValidated_thenInstanceOfValid() { UserValidator userValidator = new UserValidator(); assertThat(userValidator.validateUser("John", "john@domain.com"), instanceOf(Valid.class)); }
@Test public void givenInvalidUserParams_whenValidated_thenInstanceOfInvalid() { UserValidator userValidator = new UserValidator(); assertThat(userValidator.validateUser("John", "no-email"), instanceOf(Invalid.class)); } |
### Question:
SolrJavaIntegration { protected HttpSolrClient getSolrClient() { return solrClient; } SolrJavaIntegration(String clientUrl); void addProductBean(ProductBean pBean); void addSolrDocument(String documentId, String itemName, String itemPrice); void deleteSolrDocumentById(String documentId); void deleteSolrDocumentByQuery(String query); }### Answer:
@Test public void whenAdd_thenVerifyAddedByQueryOnId() throws SolrServerException, IOException { SolrQuery query = new SolrQuery(); query.set("q", "id:123456"); QueryResponse response = null; response = solrJavaIntegration.getSolrClient().query(query); SolrDocumentList docList = response.getResults(); assertEquals(1, docList.getNumFound()); for (SolrDocument doc : docList) { assertEquals("Kenmore Dishwasher", (String) doc.getFieldValue("name")); assertEquals((Double) 599.99, (Double) doc.getFieldValue("price")); } }
@Test public void whenAdd_thenVerifyAddedByQueryOnPrice() throws SolrServerException, IOException { SolrQuery query = new SolrQuery(); query.set("q", "price:599.99"); QueryResponse response = null; response = solrJavaIntegration.getSolrClient().query(query); SolrDocumentList docList = response.getResults(); assertEquals(1, docList.getNumFound()); for (SolrDocument doc : docList) { assertEquals("123456", (String) doc.getFieldValue("id")); assertEquals((Double) 599.99, (Double) doc.getFieldValue("price")); } }
@Test public void whenAdd_thenVerifyAddedByQuery() throws SolrServerException, IOException { SolrDocument doc = solrJavaIntegration.getSolrClient().getById("123456"); assertEquals("Kenmore Dishwasher", (String) doc.getFieldValue("name")); assertEquals((Double) 599.99, (Double) doc.getFieldValue("price")); } |
### Question:
CycleDetectionByFastAndSlowIterators { public static <T> CycleDetectionResult<T> detectCycle(Node<T> head) { if (head == null) { return new CycleDetectionResult<>(false, null); } Node<T> slow = head; Node<T> fast = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; if (slow == fast) { return new CycleDetectionResult<>(true, fast); } } return new CycleDetectionResult<>(false, null); } static CycleDetectionResult<T> detectCycle(Node<T> head); }### Answer:
@Test public void givenList_detectLoop() { Assert.assertEquals(cycleExists, CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); } |
### Question:
CycleRemovalBruteForce { public static <T> boolean detectAndRemoveCycle(Node<T> head) { CycleDetectionResult<T> result = CycleDetectionByFastAndSlowIterators.detectCycle(head); if (result.cycleExists) { removeCycle(result.node, head); } return result.cycleExists; } static boolean detectAndRemoveCycle(Node<T> head); }### Answer:
@Test public void givenList_ifLoopExists_thenDetectAndRemoveLoop() { Assert.assertEquals(cycleExists, CycleRemovalBruteForce.detectAndRemoveCycle(head)); Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); } |
### Question:
CycleRemovalByCountingLoopNodes { public static <T> boolean detectAndRemoveCycle(Node<T> head) { CycleDetectionResult<T> result = CycleDetectionByFastAndSlowIterators.detectCycle(head); if (result.cycleExists) { removeCycle(result.node, head); } return result.cycleExists; } static boolean detectAndRemoveCycle(Node<T> head); }### Answer:
@Test public void givenList_ifLoopExists_thenDetectAndRemoveLoop() { Assert.assertEquals(cycleExists, CycleRemovalByCountingLoopNodes.detectAndRemoveCycle(head)); Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); } |
### Question:
CycleRemovalWithoutCountingLoopNodes { public static <T> boolean detectAndRemoveCycle(Node<T> head) { CycleDetectionResult<T> result = CycleDetectionByFastAndSlowIterators.detectCycle(head); if (result.cycleExists) { removeCycle(result.node, head); } return result.cycleExists; } static boolean detectAndRemoveCycle(Node<T> head); }### Answer:
@Test public void givenList_ifLoopExists_thenDetectAndRemoveLoop() { Assert.assertEquals(cycleExists, CycleRemovalWithoutCountingLoopNodes.detectAndRemoveCycle(head)); Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); } |
### Question:
CycleDetectionByHashing { public static <T> CycleDetectionResult<T> detectCycle(Node<T> head) { if (head == null) { return new CycleDetectionResult<>(false, null); } Set<Node<T>> set = new HashSet<>(); Node<T> node = head; while (node != null) { if (set.contains(node)) { return new CycleDetectionResult<>(true, node); } set.add(node); node = node.next; } return new CycleDetectionResult<>(false, null); } static CycleDetectionResult<T> detectCycle(Node<T> head); }### Answer:
@Test public void givenList_detectLoop() { Assert.assertEquals(cycleExists, CycleDetectionByHashing.detectCycle(head).cycleExists); } |
### Question:
CycleDetectionBruteForce { public static <T> CycleDetectionResult<T> detectCycle(Node<T> head) { if (head == null) { return new CycleDetectionResult<>(false, null); } Node<T> it1 = head; int nodesTraversedByOuter = 0; while (it1 != null && it1.next != null) { it1 = it1.next; nodesTraversedByOuter++; int x = nodesTraversedByOuter; Node<T> it2 = head; int noOfTimesCurrentNodeVisited = 0; while (x > 0) { it2 = it2.next; if (it2 == it1) { noOfTimesCurrentNodeVisited++; } if (noOfTimesCurrentNodeVisited == 2) { return new CycleDetectionResult<>(true, it1); } x--; } } return new CycleDetectionResult<>(false, null); } static CycleDetectionResult<T> detectCycle(Node<T> head); }### Answer:
@Test public void givenList_detectLoop() { Assert.assertEquals(cycleExists, CycleDetectionBruteForce.detectCycle(head).cycleExists); } |
### Question:
BubbleSort { void bubbleSort(Integer[] arr) { int n = arr.length; IntStream.range(0, n - 1) .flatMap(i -> IntStream.range(i + 1, n - i)) .forEach(j -> { if (arr[j - 1] > arr[j]) { int temp = arr[j]; arr[j] = arr[j - 1]; arr[j - 1] = temp; } }); } }### Answer:
@Test public void givenIntegerArray_whenSortedWithBubbleSort_thenGetSortedArray() { Integer[] array = { 2, 1, 4, 6, 3, 5 }; Integer[] sortedArray = { 1, 2, 3, 4, 5, 6 }; BubbleSort bubbleSort = new BubbleSort(); bubbleSort.bubbleSort(array); assertArrayEquals(array, sortedArray); } |
### Question:
BubbleSort { void optimizedBubbleSort(Integer[] arr) { int i = 0, n = arr.length; boolean swapNeeded = true; while (i < n - 1 && swapNeeded) { swapNeeded = false; for (int j = 1; j < n - i; j++) { if (arr[j - 1] > arr[j]) { int temp = arr[j - 1]; arr[j - 1] = arr[j]; arr[j] = temp; swapNeeded = true; } } if (!swapNeeded) break; i++; } } }### Answer:
@Test public void givenIntegerArray_whenSortedWithOptimizedBubbleSort_thenGetSortedArray() { Integer[] array = { 2, 1, 4, 6, 3, 5 }; Integer[] sortedArray = { 1, 2, 3, 4, 5, 6 }; BubbleSort bubbleSort = new BubbleSort(); bubbleSort.optimizedBubbleSort(array); assertArrayEquals(array, sortedArray); } |
### Question:
PrimeGenerator { public static List<Integer> primeNumbersBruteForce(int max) { final List<Integer> primeNumbers = new LinkedList<Integer>(); for (int i = 2; i <= max; i++) { if (isPrimeBruteForce(i)) { primeNumbers.add(i); } } return primeNumbers; } static List<Integer> sieveOfEratosthenes(int n); static List<Integer> primeNumbersBruteForce(int max); static List<Integer> primeNumbersTill(int max); }### Answer:
@Test public void whenBruteForced_returnsSuccessfully() { final List<Integer> primeNumbers = primeNumbersBruteForce(20); assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); } |
### Question:
PrimeGenerator { public static List<Integer> primeNumbersTill(int max) { return IntStream.rangeClosed(2, max) .filter(x -> isPrime(x)) .boxed() .collect(Collectors.toList()); } static List<Integer> sieveOfEratosthenes(int n); static List<Integer> primeNumbersBruteForce(int max); static List<Integer> primeNumbersTill(int max); }### Answer:
@Test public void whenOptimized_returnsSuccessfully() { final List<Integer> primeNumbers = primeNumbersTill(20); assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); } |
### Question:
PrimeGenerator { public static List<Integer> sieveOfEratosthenes(int n) { final boolean prime[] = new boolean[n + 1]; Arrays.fill(prime, true); for (int p = 2; p * p <= n; p++) { if (prime[p]) { for (int i = p * 2; i <= n; i += p) prime[i] = false; } } final List<Integer> primes = new LinkedList<>(); for (int i = 2; i <= n; i++) { if (prime[i]) primes.add(i); } return primes; } static List<Integer> sieveOfEratosthenes(int n); static List<Integer> primeNumbersBruteForce(int max); static List<Integer> primeNumbersTill(int max); }### Answer:
@Test public void whenSieveOfEratosthenes_returnsSuccessfully() { final List<Integer> primeNumbers = sieveOfEratosthenes(20); assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); } |
### Question:
EmployeeServiceImpl implements EmployeeService { @Override @Transactional(rollbackFor = Exception.class) @CachePut(key = "#p0.id") public Employee update(Employee employee) { return dao.save(employee); } @Override @Cacheable(key = "#p0") Employee findOne(Long id); @Override @Transactional(rollbackFor = Exception.class) @CachePut(key = "#p0.id") Employee update(Employee employee); @Override @Transactional(rollbackFor = Exception.class) @CacheEvict(key = "#p0") void delete(Long id); }### Answer:
@Test public void testUpdate() throws Exception { } |
### Question:
LearnSort { public static int[] insertSort(int[] array) { for (int i = 1; i < array.length; i++) { int temp = array[i]; int j = i - 1; for (; j >= 0 && array[j] > temp; j--) { array[j + 1] = array[j]; } array[j + 1] = temp; } return array; } static int[] insertSort(int[] array); static int[] shellSort(int[] array); static int[] selectionSort(int[] array); static int[] heapSort(int[] array); static int[] bubbleSort(@NotNull int[] array); static int[] quickSort(@NotNull int[] array); static int[] mergingSort(int[] array); static int[] radixSort(@NotNull int[] arr); final static int[] originalArray; }### Answer:
@Test public void testInsertSort() throws Exception { Assert.assertThat(resultArray, Matchers.equalTo(LearnSort.insertSort(originalArray))); } |
### Question:
LearnSort { public static int[] shellSort(int[] array) { int len = array.length; for (int gap = len >> 1; gap != 0; gap >>= 1) { for (int i = 0; i < gap; i++) { for (int j = i + gap; j < len; j += gap) { int index = j - gap; int temp = array[j]; for (; index >= 0 && temp < array[index]; index -= gap) { array[index + gap] = array[index]; } array[index + gap] = temp; } } } return array; } static int[] insertSort(int[] array); static int[] shellSort(int[] array); static int[] selectionSort(int[] array); static int[] heapSort(int[] array); static int[] bubbleSort(@NotNull int[] array); static int[] quickSort(@NotNull int[] array); static int[] mergingSort(int[] array); static int[] radixSort(@NotNull int[] arr); final static int[] originalArray; }### Answer:
@Test public void testShellSort() throws Exception { Assert.assertThat(resultArray, Matchers.equalTo(LearnSort.shellSort(originalArray))); } |
### Question:
LearnSort { public static int[] selectionSort(int[] array) { int len = array.length; for (int i = 0; i < len; i++) { int position = i; int temp = array[i]; for (int j = i + 1; j < len; j++) { if (temp > array[j]) { temp = array[j]; position = j; } } if (position > i) { array[position] = array[i]; array[i] = temp; } } return array; } static int[] insertSort(int[] array); static int[] shellSort(int[] array); static int[] selectionSort(int[] array); static int[] heapSort(int[] array); static int[] bubbleSort(@NotNull int[] array); static int[] quickSort(@NotNull int[] array); static int[] mergingSort(int[] array); static int[] radixSort(@NotNull int[] arr); final static int[] originalArray; }### Answer:
@Test public void testSelectionSort() throws Exception { Assert.assertThat(resultArray, Matchers.equalTo(LearnSort.selectionSort(originalArray))); } |
### Question:
LearnSort { public static int[] heapSort(int[] array) { for (int i = array.length; i > 0; i--) { maxHeapify(i, array); swap(0, i - 1, array); } return array; } static int[] insertSort(int[] array); static int[] shellSort(int[] array); static int[] selectionSort(int[] array); static int[] heapSort(int[] array); static int[] bubbleSort(@NotNull int[] array); static int[] quickSort(@NotNull int[] array); static int[] mergingSort(int[] array); static int[] radixSort(@NotNull int[] arr); final static int[] originalArray; }### Answer:
@Test public void testHeapSort() throws Exception { Assert.assertThat(resultArray, Matchers.equalTo(LearnSort.heapSort(originalArray))); } |
### Question:
LearnSort { public static int[] bubbleSort(@NotNull int[] array) { int len = array.length; for (int i = 0; i < len - 1; i++) { for (int j = i + 1; j < len; j++) { if (array[i] > array[j]) { swap(i, j, array); } } } return array; } static int[] insertSort(int[] array); static int[] shellSort(int[] array); static int[] selectionSort(int[] array); static int[] heapSort(int[] array); static int[] bubbleSort(@NotNull int[] array); static int[] quickSort(@NotNull int[] array); static int[] mergingSort(int[] array); static int[] radixSort(@NotNull int[] arr); final static int[] originalArray; }### Answer:
@Test public void testBubbleSort() throws Exception { Assert.assertThat(resultArray, Matchers.equalTo(LearnSort.bubbleSort(originalArray))); } |
### Question:
LearnSort { public static int[] quickSort(@NotNull int[] array) { quickSort(array, 0, array.length - 1); return array; } static int[] insertSort(int[] array); static int[] shellSort(int[] array); static int[] selectionSort(int[] array); static int[] heapSort(int[] array); static int[] bubbleSort(@NotNull int[] array); static int[] quickSort(@NotNull int[] array); static int[] mergingSort(int[] array); static int[] radixSort(@NotNull int[] arr); final static int[] originalArray; }### Answer:
@Test public void testQuickSort() throws Exception { Assert.assertThat(resultArray, Matchers.equalTo(LearnSort.quickSort(originalArray))); } |
### Question:
LearnSort { public static int[] mergingSort(int[] array) { if (array.length <= 1) { return array; } int segmentLen = array.length >> 1; int[] leftArr = Arrays.copyOfRange(array, 0, segmentLen); int[] rightArr = Arrays.copyOfRange(array, segmentLen, array.length); return merge(mergingSort(leftArr), mergingSort(rightArr)); } static int[] insertSort(int[] array); static int[] shellSort(int[] array); static int[] selectionSort(int[] array); static int[] heapSort(int[] array); static int[] bubbleSort(@NotNull int[] array); static int[] quickSort(@NotNull int[] array); static int[] mergingSort(int[] array); static int[] radixSort(@NotNull int[] arr); final static int[] originalArray; }### Answer:
@Test public void testMergingSort() throws Exception { Assert.assertThat(resultArray, Matchers.equalTo(LearnSort.mergingSort(originalArray))); } |
### Question:
LearnSort { public static int[] radixSort(@NotNull int[] arr) { int len = arr.length; if (len <= 1) { return arr; } int max = 0; for (int anArr : arr) { if (max < anArr) { max = anArr; } } int maxDigit = 1; while (max / 10 > 0) { maxDigit++; max = max / 10; } System.out.println("maxDigit: " + maxDigit); int[][] buckets = new int[10][arr.length]; int base = 10; for (int i = 0; i < maxDigit; i++) { int[] bktLen = new int[10]; for (int j = 0; j < arr.length; j++) { int whichBucket = (arr[j] % base) / (base / 10); buckets[whichBucket][bktLen[whichBucket]] = arr[j]; bktLen[whichBucket]++; } int k = 0; for (int b = 0; b < buckets.length; b++) { for (int p = 0; p < bktLen[b]; p++) { arr[k++] = buckets[b][p]; } } base *= 10; } return arr; } static int[] insertSort(int[] array); static int[] shellSort(int[] array); static int[] selectionSort(int[] array); static int[] heapSort(int[] array); static int[] bubbleSort(@NotNull int[] array); static int[] quickSort(@NotNull int[] array); static int[] mergingSort(int[] array); static int[] radixSort(@NotNull int[] arr); final static int[] originalArray; }### Answer:
@Test public void testRadixSort() throws Exception { Assert.assertThat(resultArray, Matchers.equalTo(LearnSort.radixSort(originalArray))); } |
### Question:
LearnSort { private static void maxHeapify(int index, int[] array) { int parentIdx = index >> 1; for (; parentIdx >= 0; parentIdx--) { if (parentIdx << 1 >= index) { continue; } int left = parentIdx * 2; int right = (left + 1) >= index ? left : (left + 1); int maxChildId = array[left] >= array[right] ? left : right; if (array[maxChildId] > array[parentIdx]) { swap(maxChildId, parentIdx, array); } } } static int[] insertSort(int[] array); static int[] shellSort(int[] array); static int[] selectionSort(int[] array); static int[] heapSort(int[] array); static int[] bubbleSort(@NotNull int[] array); static int[] quickSort(@NotNull int[] array); static int[] mergingSort(int[] array); static int[] radixSort(@NotNull int[] arr); final static int[] originalArray; }### Answer:
@Test public void testMaxHeapify() throws Exception { } |
### Question:
LearnSort { private static int getPivot(@NotNull int[] array, int low, int high) { int pivotValue = array[low]; while (low < high) { while (low < high && array[high] >= pivotValue) { high--; } array[low] = array[high]; while (low < high && array[low] <= pivotValue) { low++; } array[high] = array[low]; } array[low] = pivotValue; return low; } static int[] insertSort(int[] array); static int[] shellSort(int[] array); static int[] selectionSort(int[] array); static int[] heapSort(int[] array); static int[] bubbleSort(@NotNull int[] array); static int[] quickSort(@NotNull int[] array); static int[] mergingSort(int[] array); static int[] radixSort(@NotNull int[] arr); final static int[] originalArray; }### Answer:
@Test public void testGetPivot() throws Exception { } |
### Question:
EmployeeServiceImpl implements EmployeeService { @Override @Cacheable(key = "#p0") public Employee findOne(Long id) { return dao.findOne(id); } @Override @Cacheable(key = "#p0") Employee findOne(Long id); @Override @Transactional(rollbackFor = Exception.class) @CachePut(key = "#p0.id") Employee update(Employee employee); @Override @Transactional(rollbackFor = Exception.class) @CacheEvict(key = "#p0") void delete(Long id); }### Answer:
@Test public void testFindOne() throws Exception { } |
### Question:
LearnSort { private static int[] merge(int[] arr1, int[] arr2) { int i = 0, j = 0, k = 0; int[] result = new int[arr1.length + arr2.length]; while (i < arr1.length && j < arr2.length) { if (arr1[i] <= arr2[j]) { result[k++] = arr1[i++]; } else { result[k++] = arr2[j++]; } } while (i < arr1.length) { result[k++] = arr1[i++]; } while (j < arr2.length) { result[k++] = arr2[j++]; } return result; } static int[] insertSort(int[] array); static int[] shellSort(int[] array); static int[] selectionSort(int[] array); static int[] heapSort(int[] array); static int[] bubbleSort(@NotNull int[] array); static int[] quickSort(@NotNull int[] array); static int[] mergingSort(int[] array); static int[] radixSort(@NotNull int[] arr); final static int[] originalArray; }### Answer:
@Test public void testMerge() throws Exception { } |
### Question:
LearnSort { private static void swap(int i, int j, @NotNull int[] array) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } static int[] insertSort(int[] array); static int[] shellSort(int[] array); static int[] selectionSort(int[] array); static int[] heapSort(int[] array); static int[] bubbleSort(@NotNull int[] array); static int[] quickSort(@NotNull int[] array); static int[] mergingSort(int[] array); static int[] radixSort(@NotNull int[] arr); final static int[] originalArray; }### Answer:
@Test public void testSwap() throws Exception { } |
### Question:
EmployeeServiceImpl implements EmployeeService { @Override public Page<Employee> pageBySearch(EmployeeSearch search, Pageable pageable) { return employeeDao.findAll((Specification<Employee>) (root, criteriaQuery, criteriaBuilder) -> { List<Predicate> predicates = new LinkedList<>(); Optional<EmployeeSearch> optional = Optional.ofNullable(search); optional.map(EmployeeSearch::getEmployeeId).ifPresent(id -> { predicates.add(criteriaBuilder.equal(root.get(Employee_.id), id)); }); optional.map(EmployeeSearch::getEmployeeName).ifPresent(name -> { Join<Employee, EmployeeDetail> join = root.join(Employee_.detail, JoinType.LEFT); predicates.add(criteriaBuilder.like(join.get(EmployeeDetail_.name), "%" + name + "%")); }); optional.map(EmployeeSearch::getJobName).ifPresent(name -> { Join<Employee, Job> join = root.join(Employee_.job, JoinType.LEFT); predicates.add(criteriaBuilder.equal(join.get(Job_.name), name)); }); Predicate[] array = new Predicate[predicates.size()]; return criteriaBuilder.and(predicates.toArray(array)); }, pageable); } @Override Page<Employee> pageBySearch(EmployeeSearch search, Pageable pageable); @Override void save(Employee employee); @Override List<Employee> listByAge(Integer age); @Override List<Employee> listByAge1(Integer age); @Override List<Tuple> groupByName(String name); @Override List<EmployeeResult> findEmployee(); }### Answer:
@Test public void testPageBySearch() throws Exception { EmployeeSearch employeeSearch = new EmployeeSearch(null, null, "程序猿"); Sort sort = new Sort(Sort.Direction.ASC, "id"); Page<Employee> employees = employeeService.pageBySearch(employeeSearch, new PageRequest(0, 5, sort)); Assert.assertThat("18772383543", Matchers.equalTo(employees.getContent().get(0).getDetail().getPhone())); } |
### Question:
EmployeeServiceImpl implements EmployeeService { @Override public void save(Employee employee) { employeeDao.save(employee); } @Override Page<Employee> pageBySearch(EmployeeSearch search, Pageable pageable); @Override void save(Employee employee); @Override List<Employee> listByAge(Integer age); @Override List<Employee> listByAge1(Integer age); @Override List<Tuple> groupByName(String name); @Override List<EmployeeResult> findEmployee(); }### Answer:
@Test public void testSave() { Employee employee = new Employee(); EmployeeDetail detail = new EmployeeDetail(); detail.setAge(22); detail.setName("jams"); detail.setPhone("42345"); employee.setDetail(detail); employeeService.save(employee); } |
### Question:
EmployeeServiceImpl implements EmployeeService { @Override public List<Employee> listByAge(Integer age) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Employee> query = cb.createQuery(Employee.class); Root<Employee> root = query.from(Employee.class); List<Predicate> predicates = new LinkedList<>(); Join<Employee, EmployeeDetail> join = root.join(Employee_.detail, JoinType.LEFT); predicates.add(cb.gt(join.get(EmployeeDetail_.age), age)); predicates.add(cb.equal(join.get(EmployeeDetail_.age), age)); Order order = cb.asc(root.get(Employee_.id)); query.orderBy(order); query.where(cb.or(predicates.toArray(new Predicate[predicates.size()]))); TypedQuery typedQuery = em.createQuery(query); return typedQuery.getResultList(); } @Override Page<Employee> pageBySearch(EmployeeSearch search, Pageable pageable); @Override void save(Employee employee); @Override List<Employee> listByAge(Integer age); @Override List<Employee> listByAge1(Integer age); @Override List<Tuple> groupByName(String name); @Override List<EmployeeResult> findEmployee(); }### Answer:
@Test public void testListByAge() { List<Employee> list = employeeService.listByAge(24); Assert.assertThat(1L, Matchers.equalTo(list.get(0).getId())); } |
### Question:
EmployeeServiceImpl implements EmployeeService { @Override public List<Employee> listByAge1(Integer age) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Employee> query = cb.createQuery(Employee.class); Root<Employee> root = query.from(Employee.class); ParameterExpression<Integer> ageParameter = cb.parameter(Integer.class); List<Predicate> predicates = new LinkedList<>(); Join<Employee, EmployeeDetail> join = root.join(Employee_.detail, JoinType.LEFT); predicates.add(cb.gt(join.get(EmployeeDetail_.age), ageParameter)); predicates.add(cb.equal(join.get(EmployeeDetail_.age), ageParameter)); Order order = cb.asc(root.get(Employee_.id)); query.orderBy(order); query.where(cb.or(predicates.toArray(new Predicate[predicates.size()]))); TypedQuery typedQuery = em.createQuery(query); return typedQuery.setParameter(ageParameter, age).getResultList(); } @Override Page<Employee> pageBySearch(EmployeeSearch search, Pageable pageable); @Override void save(Employee employee); @Override List<Employee> listByAge(Integer age); @Override List<Employee> listByAge1(Integer age); @Override List<Tuple> groupByName(String name); @Override List<EmployeeResult> findEmployee(); }### Answer:
@Test public void testListByAge1() { List<Employee> list = employeeService.listByAge1(24); Assert.assertThat(1L, Matchers.equalTo(list.get(0).getId())); } |
### Question:
EmployeeServiceImpl implements EmployeeService { @Override public List<Tuple> groupByName(String name) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Tuple> query = cb.createTupleQuery(); Root<Employee> root = query.from(Employee.class); Join<Employee, EmployeeDetail> join = root.join(Employee_.detail, JoinType.LEFT); query.groupBy(join.get(EmployeeDetail_.name)); if (name != null) { query.having(cb.like(join.get(EmployeeDetail_.name), "%" + name + "%")); } query.select(cb.tuple(join.get(EmployeeDetail_.name).alias("name"), cb.count(root).alias("count"))); TypedQuery<Tuple> typedQuery = em.createQuery(query); return typedQuery.getResultList(); } @Override Page<Employee> pageBySearch(EmployeeSearch search, Pageable pageable); @Override void save(Employee employee); @Override List<Employee> listByAge(Integer age); @Override List<Employee> listByAge1(Integer age); @Override List<Tuple> groupByName(String name); @Override List<EmployeeResult> findEmployee(); }### Answer:
@Test public void groupByName() { List list = employeeService.groupByName("o"); System.out.println(list); } |
### Question:
EmployeeServiceImpl implements EmployeeService { @Override public List<EmployeeResult> findEmployee() { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Employee> query = cb.createQuery(Employee.class); Root<Employee> root = query.from(Employee.class); Join<Employee, EmployeeDetail> join = root.join(Employee_.detail, JoinType.LEFT); query.select(cb.construct(EmployeeResult.class, join.get(EmployeeDetail_.name), join.get(EmployeeDetail_.age))); Order order = cb.asc(root.get(Employee_.id)); query.orderBy(order); TypedQuery typedQuery = em.createQuery(query); return typedQuery.getResultList(); } @Override Page<Employee> pageBySearch(EmployeeSearch search, Pageable pageable); @Override void save(Employee employee); @Override List<Employee> listByAge(Integer age); @Override List<Employee> listByAge1(Integer age); @Override List<Tuple> groupByName(String name); @Override List<EmployeeResult> findEmployee(); }### Answer:
@Test public void testFindEmployee() { List list = employeeService.findEmployee(); System.out.println(list); } |
### Question:
HelloServiceImpl implements HelloService { @Override public void say() { System.out.println("=====>>>> Hello."); } @Override void say(); }### Answer:
@Test public void say() { HelloService helloService = new HelloServiceImpl(); helloService.say(); } |
### Question:
EmployeeController { @GetMapping public ResponseEntity<List<EmployeeResult>> listAll() { return ResponseEntity.ok(employeeService.findEmployee()); } @Autowired EmployeeController(EmployeeService employeeService); @GetMapping ResponseEntity<List<EmployeeResult>> listAll(); }### Answer:
@Test public void listAll() throws Exception { mockMvc .perform(get("/emp") .accept(MediaType.APPLICATION_JSON_UTF8) ) .andExpect(status().isOk()) .andExpect(jsonPath("$[1].name").exists()) .andDo(print()); } |
### Question:
DefaultOAuth2HttpClient implements OAuth2HttpClient { @Override public OAuth2AccessTokenResponse post(OAuth2HttpRequest oAuth2HttpRequest) { Assert.notNull(oAuth2HttpRequest, "OAuth2HttpRequest cannot be null"); RequestEntity<?> request = convert(oAuth2HttpRequest); try { return restTemplate.exchange(request, OAuth2AccessTokenResponse.class).getBody(); } catch (HttpStatusCodeException e) { throw new OAuth2ClientException(String.format("received %s from tokenendpoint=%s with responsebody=%s", e.getStatusCode(), oAuth2HttpRequest.getTokenEndpointUrl(), e.getResponseBodyAsString()), e); } } DefaultOAuth2HttpClient(RestTemplateBuilder restTemplateBuilder); @Override OAuth2AccessTokenResponse post(OAuth2HttpRequest oAuth2HttpRequest); }### Answer:
@Test void testPostAllHeadersAndFormParametersShouldBePresent() throws InterruptedException { server.enqueue(jsonResponse(TOKEN_RESPONSE)); OAuth2HttpRequest request = OAuth2HttpRequest.builder() .tokenEndpointUrl(tokenEndpointUrl) .formParameter("param1", "value1") .formParameter("param2", "value2") .oAuth2HttpHeaders(OAuth2HttpHeaders.builder() .header("header1", "headervalue1") .header("header2", "headervalue2") .build()) .build(); client.post(request); RecordedRequest recordedRequest = server.takeRequest(); var body = recordedRequest.getBody().readUtf8(); assertThat(recordedRequest.getHeaders().get("header1")).isEqualTo("headervalue1"); assertThat(recordedRequest.getHeaders().get("header2")).isEqualTo("headervalue2"); assertThat(body).contains("param1=value1"); assertThat(body).contains("param2=value2"); } |
### Question:
JwtTokenExpiryFilter implements Filter { private boolean tokenExpiresBeforeThreshold(JwtTokenClaims jwtTokenClaims) { Date expiryDate = (Date)jwtTokenClaims.get("exp"); LocalDateTime expiry = LocalDateTime.ofInstant(expiryDate.toInstant(), ZoneId.systemDefault()); long minutesUntilExpiry = LocalDateTime.now().until(expiry, ChronoUnit.MINUTES); LOG.debug("Checking token at time {} with expirationTime {} for how many minutes until expiry: {}", LocalDateTime.now(), expiry, minutesUntilExpiry); if (minutesUntilExpiry <= expiryThresholdInMinutes) { LOG.debug("There are {} minutes until expiry which is equal to or less than the configured threshold {}", minutesUntilExpiry, expiryThresholdInMinutes); return true; } return false; } JwtTokenExpiryFilter(TokenValidationContextHolder contextHolder, long expiryThresholdInMinutes); @Override void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); @Override void destroy(); @Override void init(FilterConfig filterConfig); @Override String toString(); }### Answer:
@Test public void tokenExpiresBeforeThreshold() throws IOException, ServletException { setupMocks(LocalDateTime.now().plusMinutes(2)); JwtTokenExpiryFilter jwtTokenExpiryFilter = new JwtTokenExpiryFilter(tokenValidationContextHolder, EXPIRY_THRESHOLD); jwtTokenExpiryFilter.doFilter(servletRequest, servletResponse, filterChain); verify(servletResponse).setHeader(JwtTokenConstants.TOKEN_EXPIRES_SOON_HEADER, "true"); } |
### Question:
JwtTokenExpiryFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { addHeaderOnTokenExpiryThreshold((HttpServletResponse) response); chain.doFilter(request, response); } else { chain.doFilter(request, response); } } JwtTokenExpiryFilter(TokenValidationContextHolder contextHolder, long expiryThresholdInMinutes); @Override void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); @Override void destroy(); @Override void init(FilterConfig filterConfig); @Override String toString(); }### Answer:
@Test public void tokenExpiresAfterThreshold() throws IOException, ServletException { setupMocks(LocalDateTime.now().plusMinutes(3)); JwtTokenExpiryFilter jwtTokenExpiryFilter = new JwtTokenExpiryFilter(tokenValidationContextHolder, EXPIRY_THRESHOLD); jwtTokenExpiryFilter.doFilter(servletRequest, servletResponse, filterChain); verify(servletResponse, never()).setHeader(JwtTokenConstants.TOKEN_EXPIRES_SOON_HEADER, "true"); }
@Test public void noValidToken() throws IOException, ServletException { JwtTokenExpiryFilter jwtTokenExpiryFilter = new JwtTokenExpiryFilter(mock(TokenValidationContextHolder.class), EXPIRY_THRESHOLD); jwtTokenExpiryFilter.doFilter(servletRequest, servletResponse, filterChain); } |
### Question:
JwtTokenValidationFilter implements Filter { static HttpRequest fromHttpServletRequest(final HttpServletRequest request) { return new HttpRequest() { @Override public String getHeader(String headerName) { return request.getHeader(headerName); } @Override public NameValue[] getCookies() { if (request.getCookies() == null) { return null; } return Arrays.stream(request.getCookies()).map(cookie -> new NameValue() { @Override public String getName() { return cookie.getName(); } @Override public String getValue() { return cookie.getValue(); } }).toArray(NameValue[]::new); } }; } JwtTokenValidationFilter(JwtTokenValidationHandler jwtTokenValidationHandler, TokenValidationContextHolder contextHolder); @Override void destroy(); @Override void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); @Override void init(FilterConfig filterConfig); }### Answer:
@Test void testRequestConverterShouldHandleWhenCookiesAreNULL() { when(servletRequest.getCookies()).thenReturn(null); when(servletRequest.getHeader(JwtTokenConstants.AUTHORIZATION_HEADER)).thenReturn(null); HttpRequest req = JwtTokenValidationFilter.fromHttpServletRequest(servletRequest); assertNull(req.getCookies()); assertNull(req.getHeader(JwtTokenConstants.AUTHORIZATION_HEADER)); }
@Test void testRequestConverterShouldConvertCorrectly() { when(servletRequest.getCookies()).thenReturn(new Cookie[]{new Cookie("JSESSIONID", "ABCDEF"), new Cookie("IDTOKEN", "THETOKEN")}); when(servletRequest.getHeader(JwtTokenConstants.AUTHORIZATION_HEADER)).thenReturn("Bearer eyAAA"); HttpRequest req = JwtTokenValidationFilter.fromHttpServletRequest(servletRequest); assertEquals("JSESSIONID", req.getCookies()[0].getName()); assertEquals("ABCDEF", req.getCookies()[0].getValue()); assertEquals("IDTOKEN", req.getCookies()[1].getName()); assertEquals("THETOKEN", req.getCookies()[1].getValue()); assertEquals("Bearer eyAAA", req.getHeader(JwtTokenConstants.AUTHORIZATION_HEADER)); } |
### Question:
JwkFactory { public static RSAKey fromKeyStore(String alias, InputStream keyStoreFile, String password) { RSAKey keyFromKeyStore = (RSAKey) fromKeyStore(keyStoreFile, password).getKeyByKeyId(alias); return new RSAKey.Builder(keyFromKeyStore) .keyID(USE_CERTIFICATE_SHA1_THUMBPRINT ? getX509CertSHA1Thumbprint(keyFromKeyStore) : keyFromKeyStore.getKeyID()) .build(); } static RSAKey fromJsonFile(String filePath); static RSAKey fromJson(String jsonJwk); static RSAKey fromKeyStore(String alias, InputStream keyStoreFile, String password); }### Answer:
@Test void getKeyFromKeystore() { RSAKey rsaKey = JwkFactory.fromKeyStore( ALIAS, JwkFactoryTest.class.getResourceAsStream(KEY_STORE_FILE), "Test1234" ); assertThat(rsaKey.getKeyID()).isEqualTo(certificateThumbprintSHA1()); assertThat(rsaKey.isPrivate()).isTrue(); } |
### Question:
ConfigurableJwtTokenValidator implements JwtTokenValidator { @Override public void assertValidToken(String tokenString) throws JwtTokenValidatorException { verify(issuer, tokenString, new JWSVerificationKeySelector<>( JWSAlgorithm.RS256, remoteJWKSet ) ); } ConfigurableJwtTokenValidator(
String issuer,
List<String> optionalClaims,
RemoteJWKSet<SecurityContext> remoteJWKSet
); @Override void assertValidToken(String tokenString); }### Answer:
@Test public void assertValidToken() throws JwtTokenValidatorException { JwtTokenValidator validator = tokenValidator(ISSUER, List.of("aud", "sub")); JWT token = createSignedJWT(ISSUER, null, null); validator.assertValidToken(token.serialize()); }
@Test public void testAssertUnexpectedIssuer() throws JwtTokenValidatorException { String otherIssuer = "https: JwtTokenValidator validator = tokenValidator(otherIssuer, Collections.emptyList()); JWT token = createSignedJWT(ISSUER, null, null); assertThrows(JwtTokenValidatorException.class, () -> validator.assertValidToken(token.serialize())); } |
### Question:
DefaultJwtTokenValidator implements JwtTokenValidator { @Override public void assertValidToken(String tokenString) throws JwtTokenValidatorException { assertValidToken(tokenString, null); } DefaultJwtTokenValidator(
String issuer,
List<String> acceptedAudience,
RemoteJWKSet<SecurityContext> remoteJWKSet
); @Override void assertValidToken(String tokenString); void assertValidToken(String tokenString, String expectedNonce); }### Answer:
@Test public void testAssertValidToken() throws JwtTokenValidatorException { JwtTokenValidator validator = createOIDCTokenValidator(ISSUER, Collections.singletonList("aud1")); JWT token = createSignedJWT(ISSUER, "aud1", SUB); validator.assertValidToken(token.serialize()); }
@Test public void testAssertUnexpectedIssuer() throws JwtTokenValidatorException { JwtTokenValidator validator = createOIDCTokenValidator("https: Collections.singletonList("aud1")); JWT token = createSignedJWT(ISSUER, "aud1", SUB); assertThrows(JwtTokenValidatorException.class, () -> validator.assertValidToken(token.serialize())); }
@Test public void testAssertUnknownAudience() throws JwtTokenValidatorException { JwtTokenValidator validator = createOIDCTokenValidator(ISSUER, Collections.singletonList("aud1")); JWT token = createSignedJWT(ISSUER, "unknown", SUB); assertThrows(JwtTokenValidatorException.class, () -> validator.assertValidToken(token.serialize())); } |
### Question:
DefaultJwtTokenValidator implements JwtTokenValidator { protected IDTokenValidator get(JWT jwt) throws ParseException, JwtTokenValidatorException { List<String> tokenAud = jwt.getJWTClaimsSet().getAudience(); for (String aud : tokenAud) { if (audienceValidatorMap.containsKey(aud)) { return audienceValidatorMap.get(aud); } } LOG.warn("Could not find validator for token audience {}", tokenAud); throw new JwtTokenValidatorException( "Could not find appropriate validator to validate token. check your config."); } DefaultJwtTokenValidator(
String issuer,
List<String> acceptedAudience,
RemoteJWKSet<SecurityContext> remoteJWKSet
); @Override void assertValidToken(String tokenString); void assertValidToken(String tokenString, String expectedNonce); }### Answer:
@Test public void testGetValidator() throws ParseException, JwtTokenValidatorException { List<String> aud = new ArrayList<>(); aud.add("aud1"); aud.add("aud2"); DefaultJwtTokenValidator validator = createOIDCTokenValidator(ISSUER, aud); JWT tokenAud1 = createSignedJWT(ISSUER, "aud1", SUB); assertEquals("aud1", validator.get(tokenAud1).getClientID().getValue()); JWT tokenAud2 = createSignedJWT(ISSUER, "aud2", SUB); assertEquals("aud2", validator.get(tokenAud2).getClientID().getValue()); JWT tokenUnknownAud = createSignedJWT(ISSUER, "unknown", SUB); assertThrows(JwtTokenValidatorException.class, () -> validator.get(tokenUnknownAud)); } |
### Question:
ProxyAwareResourceRetriever extends DefaultResourceRetriever { URL urlWithPlainTextForHttps(URL url) throws IOException { try { URI uri = url.toURI(); if (!uri.getScheme().equals("https")) { return url; } int port = url.getPort() > 0 ? url.getPort() : 443; String newUrl = "http: + (uri.getQuery() != null && uri.getQuery().length() > 0 ? "?" + uri.getQuery() : ""); logger.debug("using plaintext connection for https url, new url is {}", newUrl); return URI.create(newUrl).toURL(); } catch (URISyntaxException e) { throw new IOException(e); } } ProxyAwareResourceRetriever(); ProxyAwareResourceRetriever(URL proxyUrl); ProxyAwareResourceRetriever(URL proxyUrl, boolean usePlainTextForHttps); ProxyAwareResourceRetriever(URL proxyUrl, boolean usePlainTextForHttps, int connectTimeout, int readTimeout, int sizeLimit); static final int DEFAULT_HTTP_CONNECT_TIMEOUT; static final int DEFAULT_HTTP_READ_TIMEOUT; static final int DEFAULT_HTTP_SIZE_LIMIT; }### Answer:
@Test void testUsePlainTextForHttps() throws IOException { ProxyAwareResourceRetriever resourceRetriever = new ProxyAwareResourceRetriever(null, true); String scheme = "https: String host = "host.domain.no"; String pathAndQuery = "/somepath?foo=bar&bar=foo"; URL url = URI.create(scheme + host + pathAndQuery).toURL(); assertEquals("http: resourceRetriever.urlWithPlainTextForHttps(url).toString()); } |
### Question:
IssuerConfiguration { @Override public String toString() { return getClass().getSimpleName() + " [name=" + name + ", metaData=" + metadata + ", acceptedAudience=" + acceptedAudience + ", cookieName=" + cookieName + ", tokenValidator=" + tokenValidator + ", resourceRetriever=" + resourceRetriever + "]"; } IssuerConfiguration(String name, IssuerProperties issuerProperties, ResourceRetriever resourceRetriever); String getName(); List<String> getAcceptedAudience(); JwtTokenValidator getTokenValidator(); String getCookieName(); void setCookieName(String cookieName); AuthorizationServerMetadata getMetaData(); void setMetaData(AuthorizationServerMetadata metaData); void setName(String name); ResourceRetriever getResourceRetriever(); void setResourceRetriever(ResourceRetriever resourceRetriever); @Override String toString(); }### Answer:
@Test void issuerConfigurationDiscoveryUrlNotValid() { assertThatExceptionOfType(MetaDataNotAvailableException.class).isThrownBy(() -> new IssuerConfiguration( "issuer1", new IssuerProperties(URI.create("http: new ProxyAwareResourceRetriever())); assertThatExceptionOfType(MetaDataNotAvailableException.class).isThrownBy(() -> new IssuerConfiguration( "issuer1", new IssuerProperties(URI.create("http: new ProxyAwareResourceRetriever())); assertThatExceptionOfType(MetaDataNotAvailableException.class).isThrownBy(() -> new IssuerConfiguration( "issuer1", new IssuerProperties(URI.create(issuerMockWebServer.getDiscoveryUrl().toString() + "/pathincorrect").toURL(), List.of("audience1")), new ProxyAwareResourceRetriever())); } |
### Question:
TokenValidationContext { public Optional<JwtToken> getFirstValidToken() { return issuerShortNameValidatedTokenMap.values().stream().findFirst(); } TokenValidationContext(Map<String, JwtToken> issuerShortNameValidatedTokenMap); Optional<JwtToken> getJwtTokenAsOptional(String issuerName); Optional<JwtToken> getFirstValidToken(); JwtToken getJwtToken(String issuerName); JwtTokenClaims getClaims(String issuerName); Optional<JwtTokenClaims> getAnyValidClaims(); boolean hasValidToken(); boolean hasTokenFor(String issuerName); List<String> getIssuers(); }### Answer:
@Test public void getFirstValidToken() { Map<String, JwtToken> map = new ConcurrentHashMap<>(); TokenValidationContext tokenValidationContext = new TokenValidationContext(map); assertThat(tokenValidationContext.getFirstValidToken()).isEmpty(); assertThat(tokenValidationContext.hasValidToken()).isFalse(); JwtToken jwtToken1 = jwtToken("https: JwtToken jwtToken2 = jwtToken("https: map.put("issuer2", jwtToken2); map.put("issuer1", jwtToken1); assertThat(tokenValidationContext.getFirstValidToken()).hasValueSatisfying(jwtToken -> jwtToken.getIssuer().equals(jwtToken2.getIssuer())); } |
### Question:
TranslationService { Maybe<TranslationResult> getOnlineTranslation(String question, String langFrom, String langTo) { if (appState.isOfflineMode) { return Maybe.empty(); } return seznamRetrofit.create(SeznamRestInterface.class) .doTranslate(langFrom + "_" + langTo, question) .flatMap(response -> parseTranslationJson(response, question, langFrom, langTo)) .firstElement(); } TranslationService(final DatabaseManager databaseManager,
final AppState appState,
final Retrofit seznamRetrofit,
final Retrofit seznamSuggestRetrofit,
final NetworkService networkService,
final PublishSubject<Action> executeActionSubject); Maybe<List<String>> getSuggestions(String template, String langFrom, String langTo, int limit); Maybe<TranslationResult> translate(String question, String langFrom, String langTo); }### Answer:
@Test public void testOnlineTranslation1() { TranslationResult translationResult = translationService.getOnlineTranslation("pas", "cz", "ru") .blockingGet(); assertEquals(3, translationResult.getTranslations().size()); assertEquals("pas", translationResult.getWord()); }
@Test public void testOnlineTranslation2() { final String[] A_TRANSLATIONS = new String[]{"и","да", "уж", "плюс", "плюс", "да", "и да́же", "а", "но", "да", "a to, a sice а и́менно", "да", "и (поэ́тому)", "и потому́", "а", "и"}; TranslationResult translationResult = translationService.getOnlineTranslation("a", "cz", "ru") .blockingGet(); assertEquals(A_TRANSLATIONS.length, translationResult.getTranslations().size()); assertEquals("a", translationResult.getWord()); for (int i=0; i<translationResult.getTranslations().size(); i++) { assertEquals(A_TRANSLATIONS[i], translationResult.getTranslations().get(i)); } } |
### Question:
KnowledgeHierarchyPresenter extends BasePresenter<KnowledgeHierarchyContract.View> implements KnowledgeHierarchyContract.Presenter { @Override public void getKnowledgeHierarchyData(boolean isShowError) { addSubscribe(mDataManager.getKnowledgeHierarchyData() .compose(RxUtils.rxSchedulerHelper()) .compose(RxUtils.handleResult()) .subscribeWith(new BaseObserver<List<KnowledgeHierarchyData>>(mView, WanAndroidApp.getInstance().getString(R.string.failed_to_obtain_knowledge_data), isShowError) { @Override public void onNext(List<KnowledgeHierarchyData> knowledgeHierarchyDataList) { mView.showKnowledgeHierarchyData(knowledgeHierarchyDataList); } })); } @Inject KnowledgeHierarchyPresenter(DataManager dataManager); @Override void getKnowledgeHierarchyData(boolean isShowError); }### Answer:
@Test public void getKnowledgeHierarchyData() { mKnowledgeHierarchyPresenter.getKnowledgeHierarchyData(true); Mockito.verify(mView).showKnowledgeHierarchyData(ArgumentMatchers.any()); } |
### Question:
ArticleDetailPresenter extends BasePresenter<ArticleDetailContract.View> implements ArticleDetailContract.Presenter { @Override public void addCollectArticle(int articleId) { addSubscribe(mDataManager.addCollectArticle(articleId) .compose(RxUtils.rxSchedulerHelper()) .compose(RxUtils.handleCollectResult()) .subscribeWith(new BaseObserver<FeedArticleListData>(mView, WanAndroidApp.getInstance().getString(R.string.collect_fail)) { @Override public void onNext(FeedArticleListData feedArticleListData) { mView.showCollectArticleData(feedArticleListData); } })); } @Inject ArticleDetailPresenter(DataManager dataManager); @Override boolean getAutoCacheState(); @Override boolean getNoImageState(); @Override void addCollectArticle(int articleId); @Override void cancelCollectArticle(int articleId); @Override void cancelCollectPageArticle(int articleId); @Override void shareEventPermissionVerify(RxPermissions rxPermissions); }### Answer:
@Test public void collectFail() { CookiesManager.clearAllCookies(); mArticleDetailPresenter.addCollectArticle(0); Mockito.verify(mView).showErrorMsg(mApplication.getString(R.string.collect_fail)); Mockito.verify(mView).showError(); }
@Test public void collectSuccess() { login(); mArticleDetailPresenter.addCollectArticle(0); Mockito.verify(mView).showCollectArticleData(ArgumentMatchers.any(FeedArticleListData.class)); } |
### Question:
ArticleDetailPresenter extends BasePresenter<ArticleDetailContract.View> implements ArticleDetailContract.Presenter { @Override public void cancelCollectArticle(int articleId) { addSubscribe(mDataManager.cancelCollectArticle(articleId) .compose(RxUtils.rxSchedulerHelper()) .compose(RxUtils.handleCollectResult()) .subscribeWith(new BaseObserver<FeedArticleListData>(mView, WanAndroidApp.getInstance().getString(R.string.cancel_collect_fail)) { @Override public void onNext(FeedArticleListData feedArticleListData) { mView.showCancelCollectArticleData(feedArticleListData); } })); } @Inject ArticleDetailPresenter(DataManager dataManager); @Override boolean getAutoCacheState(); @Override boolean getNoImageState(); @Override void addCollectArticle(int articleId); @Override void cancelCollectArticle(int articleId); @Override void cancelCollectPageArticle(int articleId); @Override void shareEventPermissionVerify(RxPermissions rxPermissions); }### Answer:
@Test public void unCollectFail() { CookiesManager.clearAllCookies(); mArticleDetailPresenter.cancelCollectArticle(0); Mockito.verify(mView).showErrorMsg(mApplication.getString(R.string.cancel_collect_fail)); Mockito.verify(mView).showError(); }
@Test public void unCollectSuccess() { login(); mArticleDetailPresenter.cancelCollectArticle(0); Mockito.verify(mView).showCancelCollectArticleData(ArgumentMatchers.any(FeedArticleListData.class)); } |
### Question:
ArticleDetailPresenter extends BasePresenter<ArticleDetailContract.View> implements ArticleDetailContract.Presenter { @Override public void cancelCollectPageArticle(int articleId) { addSubscribe(mDataManager.cancelCollectPageArticle(articleId) .compose(RxUtils.rxSchedulerHelper()) .compose(RxUtils.handleCollectResult()) .subscribeWith(new BaseObserver<FeedArticleListData>(mView, WanAndroidApp.getInstance().getString(R.string.cancel_collect_fail)) { @Override public void onNext(FeedArticleListData feedArticleListData) { mView.showCancelCollectArticleData(feedArticleListData); } })); } @Inject ArticleDetailPresenter(DataManager dataManager); @Override boolean getAutoCacheState(); @Override boolean getNoImageState(); @Override void addCollectArticle(int articleId); @Override void cancelCollectArticle(int articleId); @Override void cancelCollectPageArticle(int articleId); @Override void shareEventPermissionVerify(RxPermissions rxPermissions); }### Answer:
@Test public void unCollectPagerFail() { CookiesManager.clearAllCookies(); mArticleDetailPresenter.cancelCollectPageArticle(0); Mockito.verify(mView).showErrorMsg(mApplication.getString(R.string.cancel_collect_fail)); Mockito.verify(mView).showError(); }
@Test public void unCollectPagerSuccess() { login(); mArticleDetailPresenter.cancelCollectPageArticle(0); Mockito.verify(mView).showCancelCollectArticleData(ArgumentMatchers.any(FeedArticleListData.class)); } |
### Question:
LoginPresenter extends BasePresenter<LoginContract.View> implements LoginContract.Presenter { @Override public void getLoginData(String username, String password) { if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) { mView.showSnackBar(WanAndroidApp.getInstance().getString(R.string.account_password_null_tint)); return; } addSubscribe(mDataManager.getLoginData(username, password) .compose(RxUtils.rxSchedulerHelper()) .compose(RxUtils.handleResult()) .subscribeWith(new BaseObserver<LoginData>(mView, WanAndroidApp.getInstance().getString(R.string.login_fail)) { @Override public void onNext(LoginData loginData) { setLoginAccount(loginData.getUsername()); setLoginPassword(loginData.getPassword()); setLoginStatus(true); RxBus.getDefault().post(new LoginEvent(true)); mView.showLoginSuccess(); } })); } @Inject LoginPresenter(DataManager dataManager); @Override void getLoginData(String username, String password); }### Answer:
@Test public void noInputUsernameOrPassword() { mLoginPresenter.getLoginData("", ""); Mockito.verify(mView).showSnackBar(mApplication.getString(R.string.account_password_null_tint)); }
@Test public void inputErrorUserNameOrPassword() { mLoginPresenter.getLoginData("2243963927", "qaz"); Mockito.verify(mView).showErrorMsg(mApplication.getString(R.string.login_fail)); Mockito.verify(mView).showError(); } |
### Question:
CollectPresenter extends BasePresenter<CollectContract.View> implements CollectContract.Presenter { @Override public void getCollectList(int page, boolean isShowError) { addSubscribe(mDataManager.getCollectList(page) .compose(RxUtils.rxSchedulerHelper()) .compose(RxUtils.handleResult()) .subscribeWith(new BaseObserver<FeedArticleListData>(mView, WanAndroidApp.getInstance().getString(R.string.failed_to_obtain_collection_data), isShowError) { @Override public void onNext(FeedArticleListData feedArticleListData) { mView.showCollectList(feedArticleListData); } })); } @Inject CollectPresenter(DataManager dataManager); @Override void attachView(CollectContract.View view); @Override void getCollectList(int page, boolean isShowError); @Override void cancelCollectPageArticle(int position, FeedArticleData feedArticleData); }### Answer:
@Test public void getCollectListError() { CookiesManager.clearAllCookies(); mCollectPresenter.getCollectList(0, false); Mockito.verify(mView).showErrorMsg(mApplication.getString(R.string.failed_to_obtain_collection_data)); }
@Test public void getCollectListErrorShow() { CookiesManager.clearAllCookies(); mCollectPresenter.getCollectList(0, true); Mockito.verify(mView).showErrorMsg(mApplication.getString(R.string.failed_to_obtain_collection_data)); Mockito.verify(mView).showError(); }
@Test public void getCollectListSuccess() { login(); mCollectPresenter.getCollectList(0, true); Mockito.verify(mView).showCollectList(ArgumentMatchers.any(FeedArticleListData.class)); } |
### Question:
CollectPresenter extends BasePresenter<CollectContract.View> implements CollectContract.Presenter { @Override public void cancelCollectPageArticle(int position, FeedArticleData feedArticleData) { addSubscribe(mDataManager.cancelCollectPageArticle(feedArticleData.getId()) .compose(RxUtils.rxSchedulerHelper()) .compose(RxUtils.handleCollectResult()) .subscribeWith(new BaseObserver<FeedArticleListData>(mView, WanAndroidApp.getInstance().getString(R.string.cancel_collect_fail)) { @Override public void onNext(FeedArticleListData feedArticleListData) { feedArticleData.setCollect(false); mView.showCancelCollectPageArticleData(position, feedArticleData, feedArticleListData); } })); } @Inject CollectPresenter(DataManager dataManager); @Override void attachView(CollectContract.View view); @Override void getCollectList(int page, boolean isShowError); @Override void cancelCollectPageArticle(int position, FeedArticleData feedArticleData); }### Answer:
@Test public void cancelCollectFail() { CookiesManager.clearAllCookies(); FeedArticleData feedArticleData = new FeedArticleData(); feedArticleData.setCollect(true); mCollectPresenter.cancelCollectPageArticle(0, feedArticleData); Mockito.verify(mView).showErrorMsg(mApplication.getString(R.string.cancel_collect_fail)); Mockito.verify(mView).showError(); }
@Test public void cancelCollectSuccess() { login(); FeedArticleData feedArticleData = new FeedArticleData(); feedArticleData.setCollect(true); mCollectPresenter.cancelCollectPageArticle(0, feedArticleData); feedArticleData.setCollect(false); Mockito.verify(mView).showCancelCollectPageArticleData(ArgumentMatchers.eq(0), ArgumentMatchers.eq(feedArticleData), ArgumentMatchers.any(FeedArticleListData.class)); } |
### Question:
SearchPresenter extends BasePresenter<SearchContract.View> implements SearchContract.Presenter { @Override public void getTopSearchData() { addSubscribe(mDataManager.getTopSearchData() .compose(RxUtils.rxSchedulerHelper()) .compose(RxUtils.handleResult()) .subscribeWith(new BaseObserver<List<TopSearchData>>(mView, WanAndroidApp.getInstance().getString(R.string.failed_to_obtain_top_data)) { @Override public void onNext(List<TopSearchData> topSearchDataList) { mView.showTopSearchData(topSearchDataList); } })); } @Inject SearchPresenter(DataManager dataManager); @Override void attachView(SearchContract.View view); @Override List<HistoryData> loadAllHistoryData(); @Override void addHistoryData(String data); @Override void clearHistoryData(); @Override void getTopSearchData(); }### Answer:
@Test public void getTopSearchDataSuccess() { mSearchPresenter.getTopSearchData(); Mockito.verify(mView).showTopSearchData(ArgumentMatchers.any()); } |
### Question:
SearchListPresenter extends BasePresenter<SearchListContract.View> implements SearchListContract.Presenter { @Override public void getSearchList(int page, String k, boolean isShowError) { addSubscribe(mDataManager.getSearchList(page, k) .compose(RxUtils.rxSchedulerHelper()) .compose(RxUtils.handleResult()) .subscribeWith(new BaseObserver<FeedArticleListData>(mView, WanAndroidApp.getInstance().getString(R.string.failed_to_obtain_search_data_list), isShowError) { @Override public void onNext(FeedArticleListData feedArticleListData) { mView.showSearchList(feedArticleListData); } })); } @Inject SearchListPresenter(DataManager dataManager); @Override void attachView(SearchListContract.View view); @Override void getSearchList(int page, String k, boolean isShowError); @Override void addCollectArticle(int position, FeedArticleData feedArticleData); @Override void cancelCollectArticle(int position, FeedArticleData feedArticleData); @Override boolean getNightModeState(); }### Answer:
@Test public void getSearchListSuccess() { mSearchListPresenter.getSearchList(0, "单元测试", true); Mockito.verify(mView).showSearchList(ArgumentMatchers.any(FeedArticleListData.class)); } |
### Question:
MainPagerPresenter extends BasePresenter<MainPagerContract.View> implements MainPagerContract.Presenter { @Override public void getBannerData(boolean isShowError) { addSubscribe(mDataManager.getBannerData() .compose(RxUtils.rxSchedulerHelper()) .compose(RxUtils.handleResult()) .subscribeWith(new BaseObserver<List<BannerData>>(mView, WanAndroidApp.getInstance().getString(R.string.failed_to_obtain_banner_data), isShowError) { @Override public void onNext(List<BannerData> bannerDataList) { mView.showBannerData(bannerDataList); } })); } @Inject MainPagerPresenter(DataManager dataManager); @Override void attachView(MainPagerContract.View view); @Override String getLoginAccount(); @Override String getLoginPassword(); @Override void loadMainPagerData(); @Override void autoRefresh(boolean isShowError); @Override void loadMore(); @Override void getBannerData(boolean isShowError); @Override void getFeedArticleList(boolean isShowError); @Override void loadMoreData(); @Override void addCollectArticle(int position, FeedArticleData feedArticleData); @Override void cancelCollectArticle(int position, FeedArticleData feedArticleData); }### Answer:
@Test public void getBannerData() { mMainPagerPresenter.getBannerData(true); Mockito.verify(mView).showBannerData(ArgumentMatchers.any()); } |
### Question:
SearchListPresenter extends BasePresenter<SearchListContract.View> implements SearchListContract.Presenter { @Override public void addCollectArticle(int position, FeedArticleData feedArticleData) { addSubscribe(mDataManager.addCollectArticle(feedArticleData.getId()) .compose(RxUtils.rxSchedulerHelper()) .compose(RxUtils.handleCollectResult()) .subscribeWith(new BaseObserver<FeedArticleListData>(mView, WanAndroidApp.getInstance().getString(R.string.collect_fail)) { @Override public void onNext(FeedArticleListData feedArticleListData) { feedArticleData.setCollect(true); mView.showCollectArticleData(position, feedArticleData, feedArticleListData); } })); } @Inject SearchListPresenter(DataManager dataManager); @Override void attachView(SearchListContract.View view); @Override void getSearchList(int page, String k, boolean isShowError); @Override void addCollectArticle(int position, FeedArticleData feedArticleData); @Override void cancelCollectArticle(int position, FeedArticleData feedArticleData); @Override boolean getNightModeState(); }### Answer:
@Test public void addCollectFail() { CookiesManager.clearAllCookies(); FeedArticleData feedArticleData = new FeedArticleData(); feedArticleData.setCollect(false); mSearchListPresenter.addCollectArticle(0, feedArticleData); Mockito.verify(mView).showErrorMsg(mApplication.getString(R.string.collect_fail)); Mockito.verify(mView).showError(); }
@Test public void addCollectSuccess() { login(); FeedArticleData feedArticleData = new FeedArticleData(); feedArticleData.setCollect(false); mSearchListPresenter.addCollectArticle(0, feedArticleData); Mockito.verify(mView).showCollectArticleData(ArgumentMatchers.eq(0), ArgumentMatchers.eq(feedArticleData), ArgumentMatchers.any(FeedArticleListData.class)); } |
### Question:
SearchListPresenter extends BasePresenter<SearchListContract.View> implements SearchListContract.Presenter { @Override public void cancelCollectArticle(int position, FeedArticleData feedArticleData) { addSubscribe(mDataManager.cancelCollectArticle(feedArticleData.getId()) .compose(RxUtils.rxSchedulerHelper()) .compose(RxUtils.handleCollectResult()) .subscribeWith(new BaseObserver<FeedArticleListData>(mView, WanAndroidApp.getInstance().getString(R.string.cancel_collect_fail)) { @Override public void onNext(FeedArticleListData feedArticleListData) { feedArticleData.setCollect(false); mView.showCancelCollectArticleData(position, feedArticleData, feedArticleListData); } })); } @Inject SearchListPresenter(DataManager dataManager); @Override void attachView(SearchListContract.View view); @Override void getSearchList(int page, String k, boolean isShowError); @Override void addCollectArticle(int position, FeedArticleData feedArticleData); @Override void cancelCollectArticle(int position, FeedArticleData feedArticleData); @Override boolean getNightModeState(); }### Answer:
@Test public void cancelCollectFail() { FeedArticleData feedArticleData = new FeedArticleData(); feedArticleData.setCollect(true); mSearchListPresenter.cancelCollectArticle(0, feedArticleData); Mockito.verify(mView).showErrorMsg(mApplication.getString(R.string.cancel_collect_fail)); Mockito.verify(mView).showError(); }
@Test public void cancelCollectSuccess() { login(); FeedArticleData feedArticleData = new FeedArticleData(); feedArticleData.setCollect(false); mSearchListPresenter.cancelCollectArticle(0, feedArticleData); Mockito.verify(mView).showCancelCollectArticleData(ArgumentMatchers.eq(0), ArgumentMatchers.eq(feedArticleData), ArgumentMatchers.any(FeedArticleListData.class)); } |
### Question:
UsageDialogPresenter extends BasePresenter<UsageDialogContract.View> implements UsageDialogContract.Presenter { @Override public void getUsefulSites() { addSubscribe(mDataManager.getUsefulSites() .compose(RxUtils.rxSchedulerHelper()) .compose(RxUtils.handleResult()) .subscribeWith(new BaseObserver<List<UsefulSiteData>>(mView, WanAndroidApp.getInstance().getString(R.string.failed_to_obtain_useful_sites_data)) { @Override public void onNext(List<UsefulSiteData> usefulSiteDataList) { mView.showUsefulSites(usefulSiteDataList); } })); } @Inject UsageDialogPresenter(DataManager dataManager); @Override void getUsefulSites(); }### Answer:
@Test public void getUsageSites() { mUsageDialogPresenter.getUsefulSites(); Mockito.verify(mView).showUsefulSites(ArgumentMatchers.any()); } |
### Question:
ProjectPresenter extends BasePresenter<ProjectContract.View> implements ProjectContract.Presenter { @Override public void getProjectClassifyData() { addSubscribe(mDataManager.getProjectClassifyData() .compose(RxUtils.rxSchedulerHelper()) .compose(RxUtils.handleResult()) .subscribeWith(new BaseObserver<List<ProjectClassifyData>>(mView, WanAndroidApp.getInstance().getString(R.string.failed_to_obtain_project_classify_data)) { @Override public void onNext(List<ProjectClassifyData> projectClassifyDataList) { mView.showProjectClassifyData(projectClassifyDataList); } })); } @Inject ProjectPresenter(DataManager dataManager); @Override void attachView(ProjectContract.View view); @Override void getProjectClassifyData(); @Override int getProjectCurrentPage(); @Override void setProjectCurrentPage(int page); }### Answer:
@Test public void getProjectClassifyData() { mProjectPresenter.getProjectClassifyData(); Mockito.verify(mView).showProjectClassifyData(ArgumentMatchers.any()); } |
### Question:
MainPagerPresenter extends BasePresenter<MainPagerContract.View> implements MainPagerContract.Presenter { @Override public void getFeedArticleList(boolean isShowError) { addSubscribe(mDataManager.getFeedArticleList(mCurrentPage) .compose(RxUtils.rxSchedulerHelper()) .compose(RxUtils.handleResult()) .filter(feedArticleListResponse -> mView != null) .subscribeWith(new BaseObserver<FeedArticleListData>(mView, WanAndroidApp.getInstance().getString(R.string.failed_to_obtain_article_list), isShowError) { @Override public void onNext(FeedArticleListData feedArticleListData) { mView.showArticleList(feedArticleListData, isRefresh); } })); } @Inject MainPagerPresenter(DataManager dataManager); @Override void attachView(MainPagerContract.View view); @Override String getLoginAccount(); @Override String getLoginPassword(); @Override void loadMainPagerData(); @Override void autoRefresh(boolean isShowError); @Override void loadMore(); @Override void getBannerData(boolean isShowError); @Override void getFeedArticleList(boolean isShowError); @Override void loadMoreData(); @Override void addCollectArticle(int position, FeedArticleData feedArticleData); @Override void cancelCollectArticle(int position, FeedArticleData feedArticleData); }### Answer:
@Test public void getFeedArticleList() { mMainPagerPresenter.getFeedArticleList(true); Mockito.verify(mView).showArticleList(ArgumentMatchers.any(FeedArticleListData.class), ArgumentMatchers.eq(true)); } |
### Question:
ProjectListPresenter extends BasePresenter<ProjectListContract.View> implements ProjectListContract.Presenter { @Override public void getProjectListData(int page, int cid, boolean isShowError) { addSubscribe(mDataManager.getProjectListData(page, cid) .compose(RxUtils.rxSchedulerHelper()) .compose(RxUtils.handleResult()) .subscribeWith(new BaseObserver<ProjectListData>(mView, WanAndroidApp.getInstance().getString(R.string.failed_to_obtain_project_list), isShowError) { @Override public void onNext(ProjectListData projectListData) { mView.showProjectListData(projectListData); } })); } @Inject ProjectListPresenter(DataManager dataManager); @Override void attachView(ProjectListContract.View view); @Override void getProjectListData(int page, int cid, boolean isShowError); @Override void addCollectOutsideArticle(int position, FeedArticleData feedArticleData); @Override void cancelCollectArticle(int position, FeedArticleData feedArticleData); }### Answer:
@Test public void getProjectListData() { mProjectListPresenter.getProjectListData(0, 0, true); Mockito.verify(mView).showProjectListData(ArgumentMatchers.any(ProjectListData.class)); } |
### Question:
NavigationPresenter extends BasePresenter<NavigationContract.View> implements NavigationContract.Presenter { @Override public void getNavigationListData(boolean isShowError) { addSubscribe(mDataManager.getNavigationListData() .compose(RxUtils.rxSchedulerHelper()) .compose(RxUtils.handleResult()) .subscribeWith(new BaseObserver<List<NavigationListData>>(mView, WanAndroidApp.getInstance().getString(R.string.failed_to_obtain_navigation_list), isShowError) { @Override public void onNext(List<NavigationListData> navigationDataList) { mView.showNavigationListData(navigationDataList); } })); } @Inject NavigationPresenter(DataManager dataManager); @Override void attachView(NavigationContract.View view); @Override void getNavigationListData(boolean isShowError); }### Answer:
@Test public void getNavigationListData() { mNavigationPresenter.getNavigationListData(true); Mockito.verify(mView).showNavigationListData(ArgumentMatchers.any()); } |
### Question:
MainPagerPresenter extends BasePresenter<MainPagerContract.View> implements MainPagerContract.Presenter { @Override public void loadMoreData() { addSubscribe(mDataManager.getFeedArticleList(mCurrentPage) .compose(RxUtils.rxSchedulerHelper()) .compose(RxUtils.handleResult()) .filter(feedArticleListResponse -> mView != null) .subscribeWith(new BaseObserver<FeedArticleListData>(mView, WanAndroidApp.getInstance().getString(R.string.failed_to_obtain_article_list), false) { @Override public void onNext(FeedArticleListData feedArticleListData) { mView.showArticleList(feedArticleListData, isRefresh); } })); } @Inject MainPagerPresenter(DataManager dataManager); @Override void attachView(MainPagerContract.View view); @Override String getLoginAccount(); @Override String getLoginPassword(); @Override void loadMainPagerData(); @Override void autoRefresh(boolean isShowError); @Override void loadMore(); @Override void getBannerData(boolean isShowError); @Override void getFeedArticleList(boolean isShowError); @Override void loadMoreData(); @Override void addCollectArticle(int position, FeedArticleData feedArticleData); @Override void cancelCollectArticle(int position, FeedArticleData feedArticleData); }### Answer:
@Test public void loadMoreData() { mMainPagerPresenter.loadMoreData(); Mockito.verify(mView).showArticleList(ArgumentMatchers.any(FeedArticleListData.class), ArgumentMatchers.eq(true)); } |
### Question:
KnowledgeHierarchyListPresenter extends BasePresenter<KnowledgeHierarchyListContract.View> implements KnowledgeHierarchyListContract.Presenter { @Override public void getKnowledgeHierarchyDetailData(int page, int cid, boolean isShowError) { addSubscribe(mDataManager.getKnowledgeHierarchyDetailData(page, cid) .compose(RxUtils.rxSchedulerHelper()) .compose(RxUtils.handleResult()) .subscribeWith(new BaseObserver<FeedArticleListData>(mView, WanAndroidApp.getInstance().getString(R.string.failed_to_obtain_knowledge_data), isShowError) { @Override public void onNext(FeedArticleListData feedArticleListData) { mView.showKnowledgeHierarchyDetailData(feedArticleListData); } })); } @Inject KnowledgeHierarchyListPresenter(DataManager dataManager); @Override void attachView(KnowledgeHierarchyListContract.View view); @Override void getKnowledgeHierarchyDetailData(int page, int cid, boolean isShowError); @Override void addCollectArticle(int position, FeedArticleData feedArticleData); @Override void cancelCollectArticle(int position, FeedArticleData feedArticleData); }### Answer:
@Test public void getKnowledgeHierarchyDetailData() { mKnowledgeHierarchyListPresenter.getKnowledgeHierarchyDetailData(0, 1010, true); Mockito.verify(mView).showKnowledgeHierarchyDetailData(ArgumentMatchers.any(FeedArticleListData.class)); } |
### Question:
ListRule implements Rule { @Override public boolean conforms(final List<String> pMarkdownLines) { if (!ORDERED_LIST_PATTERN.matcher(pMarkdownLines.get(0)).matches() && !UNORDERED_LIST_PATTERN.matcher(pMarkdownLines.get(0)).matches()) { return false; } mLinesConsumed = 0; for (String line : pMarkdownLines) { if (isList(line)) { mLinesConsumed++; } else { return true; } } return true; } @Override boolean conforms(final List<String> pMarkdownLines); @Override int getLinesConsumed(); @Override MarkdownItem toMarkdownItem(final List<String> pMarkdownLines); }### Answer:
@Test public void shouldConformToList() { List<String> strings = new ArrayList<>(); strings.add("1. Number 1"); assertTrue(mListRule.conforms(strings)); strings.clear(); strings.add("- Number 1"); assertTrue(mListRule.conforms(strings)); }
@Test public void shouldNotConformToList() { List<String> strings = new ArrayList<>(); strings.add("#. Number 1"); assertFalse(mListRule.conforms(strings)); } |
### Question:
QuoteRule implements Rule { @Override public boolean conforms(final List<String> pMarkdownLines) { return QUOTE_PATTERN.matcher(pMarkdownLines.get(0)).matches(); } @Override boolean conforms(final List<String> pMarkdownLines); @Override int getLinesConsumed(); @Override MarkdownItem toMarkdownItem(final List<String> pMarkdownLines); }### Answer:
@Test public void shouldBeQuote() { List<String> strings = new ArrayList<>(); strings.add("> Quote"); assertTrue(mQuoteRule.conforms(strings)); }
@Test public void shouldNotBeQuote() { List<String> strings = new ArrayList<>(); strings.add("< Quote"); assertFalse(mQuoteRule.conforms(strings)); } |
### Question:
CodeBlockRule implements Rule { @Override public boolean conforms(final List<String> pMarkdownLines) { if (!CODE_PATTERN_START.matcher(pMarkdownLines.get(0)).matches()) { return false; } mLinesConsumed = 0; for (String line : pMarkdownLines) { mLinesConsumed += 1; if (mLinesConsumed == 1) { if (CODE_PATTERN_END_SINGLE_LINE.matcher(line).matches()) { return true; } } else { if (CODE_PATTERN_END.matcher(line).matches()) { return true; } } } return true; } @Override boolean conforms(final List<String> pMarkdownLines); @Override int getLinesConsumed(); @Override MarkdownItem toMarkdownItem(final List<String> pMarkdownLines); }### Answer:
@Test public void shouldConformToCodeBlock() { List<String> strings = new ArrayList<>(); strings.add("```"); strings.add("code"); strings.add("```"); assertTrue(mCodeBlockRule.conforms(strings)); }
@Test public void shouldNotConformToCodeBlock() { List<String> strings = new ArrayList<>(); strings.add("***"); strings.add("code"); strings.add("***"); assertFalse(mCodeBlockRule.conforms(strings)); } |
### Question:
MarkdownLines { void removeLinesForRule(final Rule pRule) { for (int i = 0; i < pRule.getLinesConsumed(); i++) { mLines.remove(0); } } MarkdownLines(final String pMarkdown); }### Answer:
@Test public void removeLinesForRule() { Rule rule = INSTANCE.mock(Rule.class); every(mockKMatcherScope -> rule.getLinesConsumed()) .returns(20); assertEquals(453, sot.getLines().size()); sot.removeLinesForRule(rule); assertEquals(433, sot.getLines().size()); } |
### Question:
MarkdownLines { boolean isEmpty() { return mLines.isEmpty(); } MarkdownLines(final String pMarkdown); }### Answer:
@Test public void isEmpty() { assertFalse(sot.isEmpty()); } |
### Question:
MarkdownLines { List<String> getLines() { return mLines; } MarkdownLines(final String pMarkdown); }### Answer:
@Test public void getLines() { assertEquals(453, sot.getLines().size()); }
@Test public void getLinesSubset() { assertEquals(10, sot.getLines(10).size()); } |
### Question:
Converter { @SuppressWarnings("unchecked") public final void addMapping(final DisplayItem pDisplayItem) { final Type type = pDisplayItem.getClass().getGenericInterfaces()[0]; final Class<T> tClass = (Class<T>) ((ParameterizedType) type).getActualTypeArguments()[1]; mMapping.put((Class<? extends MarkdownItem>) tClass, pDisplayItem); } @SuppressWarnings("unchecked") final void addMapping(final DisplayItem pDisplayItem); @SuppressWarnings("unchecked") List<T> convert(final List<MarkdownItem> pMarkdownItems, InlineConverter pInlineConverter); }### Answer:
@Test public void addMapping() { MockDisplayItem displayItem = new MockDisplayItem(); sut.addMapping(displayItem); } |
### Question:
StrikeRule implements InlineRule { @Override public MarkdownString toMarkdownString(final String pContent) { Matcher matcher = getRegex().matcher(pContent); String content = ""; if (matcher.find()) { content = matcher.group(1); } return new StrikeString(content, true); } @Override Pattern getRegex(); @Override MarkdownString toMarkdownString(final String pContent); }### Answer:
@Test public void shouldCreateStrikeString() { assertEquals("text", mStrikeRule.toMarkdownString("~~text~~").getContent()); }
@Test public void shouldNotCreateStrikeString() { assertNotEquals("text", mStrikeRule.toMarkdownString("$$text$$").getContent()); } |
### Question:
BoldRule implements InlineRule { @Override public MarkdownString toMarkdownString(String pContent) { Matcher matcher = getRegex().matcher(pContent); String content = ""; if (matcher.find()) { content = matcher.group(2); } return new BoldString(content, true); } BoldRule(final String pPattern); @Override Pattern getRegex(); @Override MarkdownString toMarkdownString(String pContent); final static String PATTERN_ASTERISK; final static String PATTERN_UNDERSCORE; }### Answer:
@Test public void shouldCreateBoldString() { assertEquals("text", mBoldRule.toMarkdownString("__text__").getContent()); }
@Test public void shouldNotCreateBoldString() { assertNotEquals("text", mBoldRule.toMarkdownString("$$text$$").getContent()); } |
### Question:
ItalicRule implements InlineRule { @Override public MarkdownString toMarkdownString(String pContent) { Matcher matcher = getRegex().matcher(pContent); String content = ""; if (matcher.find()) { content = matcher.group(2); } return new ItalicString(content, true); } @Override Pattern getRegex(); @Override MarkdownString toMarkdownString(String pContent); }### Answer:
@Test public void shouldCreateItalicString() { assertEquals("text", mItalicRule.toMarkdownString("*text*").getContent()); }
@Test public void shouldNotCreateItalicString() { assertNotEquals("text", mItalicRule.toMarkdownString("$$text$$").getContent()); } |
### Question:
InlineCodeRule implements InlineRule { @Override public MarkdownString toMarkdownString(final String content) { final Matcher matcher = getRegex().matcher(content); if (matcher.find()) { return new CodeString(matcher.group(1), false); } return new CodeString("", false); } @Override Pattern getRegex(); @Override MarkdownString toMarkdownString(final String content); }### Answer:
@Test public void shouldCreateInlineCodeString() { assertEquals("text", mInlineCodeRule.toMarkdownString("`text`").getContent()); }
@Test public void shouldNotCreateInlineCodeString() { assertNotEquals("text", mInlineCodeRule.toMarkdownString("$$text$$").getContent()); } |
### Question:
DemoCommand extends AbstractHealthIndicator { @ShellMethod("Echo command") public String echo(@ShellOption(valueProvider = CustomValuesProvider.class) String message) { return message; } DemoCommand(SshShellHelper helper); @ShellMethod("Echo command") String echo(@ShellOption(valueProvider = CustomValuesProvider.class) String message); @ShellMethod("Terminal size command") Size size(); @ShellMethod("Progress command") void progress(int progress); @ShellMethod("File command") void file(
@ShellOption(defaultValue = ShellOption.NULL) File file,
@ShellOption(valueProvider = ExtendedFileValueProvider.class, defaultValue = ShellOption.NULL) File extended); @ShellMethod("Interactive command") void interactive(boolean fullscreen, @ShellOption(defaultValue = "3000") long delay); @ShellMethod("Ex command") void ex(); @ShellMethod("Welcome command") String welcome(); @ShellMethod("Confirmation command") String conf(); @ShellMethod("Admin command") @ShellMethodAvailability("adminAvailability") String admin(); Availability adminAvailability(); @ShellMethod("Authentication command") SshAuthentication authentication(); @ShellMethod("Displays ssh env information") String displaySshEnv(); @ShellMethod("Displays ssh session information") String displaySshSession(); @Scheduled(initialDelay = 0, fixedDelay = 60000) void logWithDelay(); @Scheduled(initialDelay = 0, fixedRate = 60000) void logWithRate(); @Scheduled(cron = "0/60 * * * * *") void logWithCron(); }### Answer:
@Test void testCommandEcho() { assertEquals("message", cmd.echo("message")); } |
### Question:
StacktraceCommand implements Stacktrace.Command { @ShellMethod(key = {"stacktrace"}, value = "Display the full stacktrace of the last error.") public void stacktrace() { Throwable lastError = TypePostProcessorResultHandler.THREAD_CONTEXT.get(); if (lastError != null) { lastError.printStackTrace(this.terminal.writer()); } } @ShellMethod(key = {"stacktrace"}, value = "Display the full stacktrace of the last error.") void stacktrace(); @Autowired @Lazy void setTerminal(Terminal terminal); }### Answer:
@Test void stacktrace() { TypePostProcessorResultHandler.THREAD_CONTEXT.set(null); StacktraceCommand cmd = new StacktraceCommand(); Terminal terminal = Mockito.mock(Terminal.class); Mockito.when(terminal.writer()).thenReturn(new PrintWriter(new StringWriter())); cmd.setTerminal(terminal); cmd.stacktrace(); Mockito.verify(terminal, Mockito.never()).writer(); TypePostProcessorResultHandler.THREAD_CONTEXT.set(new IllegalArgumentException("[TEST]")); cmd.stacktrace(); Mockito.verify(terminal, Mockito.times(1)).writer(); } |
### Question:
SystemCommand extends AbstractCommand { @ShellMethod(key = COMMAND_SYSTEM_ENV, value = "List system environment.") @ShellMethodAvailability("jvmEnvAvailability") public Object jvmEnv(boolean simpleView) { if (simpleView) { return buildSimple(System.getenv()); } return buildTable(System.getenv()).render(helper.terminalSize().getRows()); } SystemCommand(SshShellHelper helper, SshShellProperties properties); @ShellMethod(key = COMMAND_SYSTEM_ENV, value = "List system environment.") @ShellMethodAvailability("jvmEnvAvailability") Object jvmEnv(boolean simpleView); @ShellMethod(key = COMMAND_SYSTEM_PROPERTIES, value = "List system properties.") @ShellMethodAvailability("jvmPropertiesAvailability") Object jvmProperties(boolean simpleView); @ShellMethod(key = COMMAND_SYSTEM_THREADS, value = "List jvm threads.") @ShellMethodAvailability("threadsAvailability") String threads(@ShellOption(defaultValue = "LIST") ThreadAction action,
@ShellOption(help = "Order by column. Default is: ID", defaultValue = "ID") ThreadColumn orderBy,
@ShellOption(help = "Reverse order by column. Default is: false") boolean reverseOrder,
@ShellOption(help = "Not interactive. Default is: false") boolean staticDisplay,
@ShellOption(help = "Only for DUMP action", defaultValue = ShellOption.NULL) Long threadId); static final String SPLIT_REGEX; }### Answer:
@Test void jvmEnv() { command.jvmEnv(false); command.jvmEnv(true); } |
### Question:
SystemCommand extends AbstractCommand { @ShellMethod(key = COMMAND_SYSTEM_PROPERTIES, value = "List system properties.") @ShellMethodAvailability("jvmPropertiesAvailability") public Object jvmProperties(boolean simpleView) { Map<String, String> map = System.getProperties().entrySet().stream().filter(e -> e.getKey() != null) .collect(Collectors.toMap(e -> e.getKey().toString(), e -> e.getValue() != null ? e.getValue().toString() : "")); if (simpleView) { return buildSimple(map); } return buildTable(map).render(helper.terminalSize().getRows()); } SystemCommand(SshShellHelper helper, SshShellProperties properties); @ShellMethod(key = COMMAND_SYSTEM_ENV, value = "List system environment.") @ShellMethodAvailability("jvmEnvAvailability") Object jvmEnv(boolean simpleView); @ShellMethod(key = COMMAND_SYSTEM_PROPERTIES, value = "List system properties.") @ShellMethodAvailability("jvmPropertiesAvailability") Object jvmProperties(boolean simpleView); @ShellMethod(key = COMMAND_SYSTEM_THREADS, value = "List jvm threads.") @ShellMethodAvailability("threadsAvailability") String threads(@ShellOption(defaultValue = "LIST") ThreadAction action,
@ShellOption(help = "Order by column. Default is: ID", defaultValue = "ID") ThreadColumn orderBy,
@ShellOption(help = "Reverse order by column. Default is: false") boolean reverseOrder,
@ShellOption(help = "Not interactive. Default is: false") boolean staticDisplay,
@ShellOption(help = "Only for DUMP action", defaultValue = ShellOption.NULL) Long threadId); static final String SPLIT_REGEX; }### Answer:
@Test void jvmProperties() { command.jvmProperties(false); command.jvmProperties(true); } |
### Question:
DemoCommand extends AbstractHealthIndicator { @ShellMethod("Ex command") public void ex() { throw new IllegalStateException("Test exception message"); } DemoCommand(SshShellHelper helper); @ShellMethod("Echo command") String echo(@ShellOption(valueProvider = CustomValuesProvider.class) String message); @ShellMethod("Terminal size command") Size size(); @ShellMethod("Progress command") void progress(int progress); @ShellMethod("File command") void file(
@ShellOption(defaultValue = ShellOption.NULL) File file,
@ShellOption(valueProvider = ExtendedFileValueProvider.class, defaultValue = ShellOption.NULL) File extended); @ShellMethod("Interactive command") void interactive(boolean fullscreen, @ShellOption(defaultValue = "3000") long delay); @ShellMethod("Ex command") void ex(); @ShellMethod("Welcome command") String welcome(); @ShellMethod("Confirmation command") String conf(); @ShellMethod("Admin command") @ShellMethodAvailability("adminAvailability") String admin(); Availability adminAvailability(); @ShellMethod("Authentication command") SshAuthentication authentication(); @ShellMethod("Displays ssh env information") String displaySshEnv(); @ShellMethod("Displays ssh session information") String displaySshSession(); @Scheduled(initialDelay = 0, fixedDelay = 60000) void logWithDelay(); @Scheduled(initialDelay = 0, fixedRate = 60000) void logWithRate(); @Scheduled(cron = "0/60 * * * * *") void logWithCron(); }### Answer:
@Test void testCommandEx() { IllegalStateException ex = Assertions.assertThrows(IllegalStateException.class, () -> cmd.ex()); assertEquals("Test exception message", ex.getMessage()); } |
### Question:
PostProcessorsCommand extends AbstractCommand { @ShellMethod(key = COMMAND_POST_PROCESSORS, value = "Display the available post processors") @ShellMethodAvailability("postprocessorsAvailability") public CharSequence postprocessors() { AttributedStringBuilder result = new AttributedStringBuilder(); result.append("Available Post-Processors\n\n", AttributedStyle.BOLD); for (PostProcessor postProcessor : postProcessors) { result.append("\t" + postProcessor.getName() + ": ", AttributedStyle.BOLD); Class<?> cls = ((Class) ((ParameterizedType) (postProcessor.getClass().getGenericInterfaces())[0]).getActualTypeArguments()[0]); result.append(cls.getName() + "\n", AttributedStyle.DEFAULT); } return result; } PostProcessorsCommand(SshShellHelper helper, SshShellProperties properties,
List<PostProcessor> postProcessors); @ShellMethod(key = COMMAND_POST_PROCESSORS, value = "Display the available post processors") @ShellMethodAvailability("postprocessorsAvailability") CharSequence postprocessors(); static final String GROUP; static final String COMMAND_POST_PROCESSORS; }### Answer:
@Test void postprocessors() { GrepPostProcessor grep = new GrepPostProcessor(); JsonPointerPostProcessor json = new JsonPointerPostProcessor(); String result = new PostProcessorsCommand(new SshShellHelper(), new SshShellProperties(), Arrays.asList(grep, json)).postprocessors().toString(); assertTrue(result.startsWith("Available Post-Processors")); assertTrue(result.contains(grep.getName())); assertTrue(result.contains(json.getName())); } |
### Question:
ExtendedFileValueProvider extends ValueProviderSupport { @Override public List<CompletionProposal> complete(MethodParameter parameter, CompletionContext completionContext, String[] hints) { String input = completionContext.currentWordUpToCursor(); int lastSlash = input.lastIndexOf("/"); File currentDir = lastSlash > -1 ? new File(input.substring(0, lastSlash + 1)) : new File("./"); String prefix = input.substring(lastSlash + 1); File[] files = currentDir.listFiles((dir, name) -> name.startsWith(prefix)); if (files == null || files.length == 0) { return Collections.emptyList(); } return Arrays.stream(files) .map(f -> new ExtendedCompletionProposal(path(f), f.isFile())) .collect(Collectors.toList()); } ExtendedFileValueProvider(boolean replaceAll); @Override boolean supports(MethodParameter parameter, CompletionContext completionContext); @Override List<CompletionProposal> complete(MethodParameter parameter, CompletionContext completionContext,
String[] hints); }### Answer:
@Test void complete() { ExtendedFileValueProvider provider = new ExtendedFileValueProvider(true); List<CompletionProposal> result = provider.complete(null, new CompletionContext(Arrays.asList("--file", "src"), 1, 3), null); assertNotEquals(0, result.size()); result = provider.complete(null, new CompletionContext(Arrays.asList("--file", "xxx"), 1, 3), null); assertEquals(0, result.size()); } |
### Question:
ExtendedFileValueProvider extends ValueProviderSupport { @Override public boolean supports(MethodParameter parameter, CompletionContext completionContext) { if (replaceAll) { return parameter.getParameterType().equals(File.class); } return super.supports(parameter, completionContext); } ExtendedFileValueProvider(boolean replaceAll); @Override boolean supports(MethodParameter parameter, CompletionContext completionContext); @Override List<CompletionProposal> complete(MethodParameter parameter, CompletionContext completionContext,
String[] hints); }### Answer:
@Test void testSupport() throws Exception { ExtendedFileValueProvider providerForAll = new ExtendedFileValueProvider(true); Method method = TestCommand.class.getDeclaredMethod("test", File.class, File.class, String.class); MethodParameter paramFileWithProvider = MethodParameter.forParameter(method.getParameters()[0]); MethodParameter paramWithoutProvider = MethodParameter.forParameter(method.getParameters()[1]); MethodParameter paramNotFile = MethodParameter.forParameter(method.getParameters()[2]); assertTrue(providerForAll.supports(paramFileWithProvider, null)); assertTrue(providerForAll.supports(paramWithoutProvider, null)); assertFalse(providerForAll.supports(paramNotFile, null)); ExtendedFileValueProvider providerForDeclaredOnly = new ExtendedFileValueProvider(false); assertTrue(providerForDeclaredOnly.supports(paramFileWithProvider, null)); assertFalse(providerForDeclaredOnly.supports(paramWithoutProvider, null)); assertFalse(providerForDeclaredOnly.supports(paramNotFile, null)); } |
### Question:
DemoCommand extends AbstractHealthIndicator { @ShellMethod("Terminal size command") public Size size() { return helper.terminalSize(); } DemoCommand(SshShellHelper helper); @ShellMethod("Echo command") String echo(@ShellOption(valueProvider = CustomValuesProvider.class) String message); @ShellMethod("Terminal size command") Size size(); @ShellMethod("Progress command") void progress(int progress); @ShellMethod("File command") void file(
@ShellOption(defaultValue = ShellOption.NULL) File file,
@ShellOption(valueProvider = ExtendedFileValueProvider.class, defaultValue = ShellOption.NULL) File extended); @ShellMethod("Interactive command") void interactive(boolean fullscreen, @ShellOption(defaultValue = "3000") long delay); @ShellMethod("Ex command") void ex(); @ShellMethod("Welcome command") String welcome(); @ShellMethod("Confirmation command") String conf(); @ShellMethod("Admin command") @ShellMethodAvailability("adminAvailability") String admin(); Availability adminAvailability(); @ShellMethod("Authentication command") SshAuthentication authentication(); @ShellMethod("Displays ssh env information") String displaySshEnv(); @ShellMethod("Displays ssh session information") String displaySshSession(); @Scheduled(initialDelay = 0, fixedDelay = 60000) void logWithDelay(); @Scheduled(initialDelay = 0, fixedRate = 60000) void logWithRate(); @Scheduled(cron = "0/60 * * * * *") void logWithCron(); }### Answer:
@Test void size() { assertEquals(size, cmd.size()); } |
### Question:
SshShellHelper { public SshAuthentication getAuthentication() { return SshShellCommandFactory.SSH_THREAD_CONTEXT.get().getAuthentication(); } SshShellHelper(); SshShellHelper(List<String> confirmWords); String getColored(String message, PromptColor color); static String getColoredMessage(String message, PromptColor color); String getBackgroundColored(String message, PromptColor backgroundColor); static String getBackgroundColoredMessage(String message, PromptColor backgroundColor); boolean confirm(String message, String... confirmWords); boolean confirm(String message, boolean caseSensitive, String... confirmWords); String read(); String read(String message); String getSuccess(String message); String getInfo(String message); String getWarning(String message); String getError(String message); void printSuccess(String message); void printInfo(String message); void printWarning(String message); void printError(String message); void print(String message); void print(String message, PromptColor color); String renderTable(SimpleTable simpleTable); String renderTable(Table table); Table buildTable(SimpleTable simpleTable); static CellMatcher at(final int row, final int col); SshAuthentication getAuthentication(); ServerSession getSshSession(); Environment getSshEnvironment(); boolean isLocalPrompt(); boolean checkAuthorities(List<String> authorizedRoles); boolean checkAuthorities(List<String> authorizedRoles, List<String> authorities,
boolean authorizedIfNoAuthorities); Size terminalSize(); String progress(int percentage); String progress(int current, int total); PrintWriter terminalWriter(); History getHistory(); void interactive(Interactive interactive); @Deprecated void interactive(InteractiveInput input); @Deprecated void interactive(InteractiveInput input, long delay); @Deprecated void interactive(InteractiveInput input, boolean fullScreen); @Deprecated void interactive(InteractiveInput input, long delay, boolean fullScreen); @Deprecated void interactive(InteractiveInput input, long delay, boolean fullScreen, Size size); static final String INTERACTIVE_LONG_MESSAGE; static final String INTERACTIVE_SHORT_MESSAGE; static final String EXIT; static final List<String> DEFAULT_CONFIRM_WORDS; }### Answer:
@Test void getAuthentication() { assertNotNull(h.getAuthentication()); } |
### Question:
DemoCommand extends AbstractHealthIndicator { @ShellMethod("Progress command") public void progress(int progress) { helper.printSuccess(progress + "%"); helper.print(helper.progress(progress)); } DemoCommand(SshShellHelper helper); @ShellMethod("Echo command") String echo(@ShellOption(valueProvider = CustomValuesProvider.class) String message); @ShellMethod("Terminal size command") Size size(); @ShellMethod("Progress command") void progress(int progress); @ShellMethod("File command") void file(
@ShellOption(defaultValue = ShellOption.NULL) File file,
@ShellOption(valueProvider = ExtendedFileValueProvider.class, defaultValue = ShellOption.NULL) File extended); @ShellMethod("Interactive command") void interactive(boolean fullscreen, @ShellOption(defaultValue = "3000") long delay); @ShellMethod("Ex command") void ex(); @ShellMethod("Welcome command") String welcome(); @ShellMethod("Confirmation command") String conf(); @ShellMethod("Admin command") @ShellMethodAvailability("adminAvailability") String admin(); Availability adminAvailability(); @ShellMethod("Authentication command") SshAuthentication authentication(); @ShellMethod("Displays ssh env information") String displaySshEnv(); @ShellMethod("Displays ssh session information") String displaySshSession(); @Scheduled(initialDelay = 0, fixedDelay = 60000) void logWithDelay(); @Scheduled(initialDelay = 0, fixedRate = 60000) void logWithRate(); @Scheduled(cron = "0/60 * * * * *") void logWithCron(); }### Answer:
@Test void progress() { cmd.progress(3); } |
### Question:
SshShellHelper { public PrintWriter terminalWriter() { return terminal().writer(); } SshShellHelper(); SshShellHelper(List<String> confirmWords); String getColored(String message, PromptColor color); static String getColoredMessage(String message, PromptColor color); String getBackgroundColored(String message, PromptColor backgroundColor); static String getBackgroundColoredMessage(String message, PromptColor backgroundColor); boolean confirm(String message, String... confirmWords); boolean confirm(String message, boolean caseSensitive, String... confirmWords); String read(); String read(String message); String getSuccess(String message); String getInfo(String message); String getWarning(String message); String getError(String message); void printSuccess(String message); void printInfo(String message); void printWarning(String message); void printError(String message); void print(String message); void print(String message, PromptColor color); String renderTable(SimpleTable simpleTable); String renderTable(Table table); Table buildTable(SimpleTable simpleTable); static CellMatcher at(final int row, final int col); SshAuthentication getAuthentication(); ServerSession getSshSession(); Environment getSshEnvironment(); boolean isLocalPrompt(); boolean checkAuthorities(List<String> authorizedRoles); boolean checkAuthorities(List<String> authorizedRoles, List<String> authorities,
boolean authorizedIfNoAuthorities); Size terminalSize(); String progress(int percentage); String progress(int current, int total); PrintWriter terminalWriter(); History getHistory(); void interactive(Interactive interactive); @Deprecated void interactive(InteractiveInput input); @Deprecated void interactive(InteractiveInput input, long delay); @Deprecated void interactive(InteractiveInput input, boolean fullScreen); @Deprecated void interactive(InteractiveInput input, long delay, boolean fullScreen); @Deprecated void interactive(InteractiveInput input, long delay, boolean fullScreen, Size size); static final String INTERACTIVE_LONG_MESSAGE; static final String INTERACTIVE_SHORT_MESSAGE; static final String EXIT; static final List<String> DEFAULT_CONFIRM_WORDS; }### Answer:
@Test void terminalWriter() { assertNotNull(h.terminalWriter()); } |
### Question:
SshShellHelper { public History getHistory() { return new DefaultHistory(this.reader()); } SshShellHelper(); SshShellHelper(List<String> confirmWords); String getColored(String message, PromptColor color); static String getColoredMessage(String message, PromptColor color); String getBackgroundColored(String message, PromptColor backgroundColor); static String getBackgroundColoredMessage(String message, PromptColor backgroundColor); boolean confirm(String message, String... confirmWords); boolean confirm(String message, boolean caseSensitive, String... confirmWords); String read(); String read(String message); String getSuccess(String message); String getInfo(String message); String getWarning(String message); String getError(String message); void printSuccess(String message); void printInfo(String message); void printWarning(String message); void printError(String message); void print(String message); void print(String message, PromptColor color); String renderTable(SimpleTable simpleTable); String renderTable(Table table); Table buildTable(SimpleTable simpleTable); static CellMatcher at(final int row, final int col); SshAuthentication getAuthentication(); ServerSession getSshSession(); Environment getSshEnvironment(); boolean isLocalPrompt(); boolean checkAuthorities(List<String> authorizedRoles); boolean checkAuthorities(List<String> authorizedRoles, List<String> authorities,
boolean authorizedIfNoAuthorities); Size terminalSize(); String progress(int percentage); String progress(int current, int total); PrintWriter terminalWriter(); History getHistory(); void interactive(Interactive interactive); @Deprecated void interactive(InteractiveInput input); @Deprecated void interactive(InteractiveInput input, long delay); @Deprecated void interactive(InteractiveInput input, boolean fullScreen); @Deprecated void interactive(InteractiveInput input, long delay, boolean fullScreen); @Deprecated void interactive(InteractiveInput input, long delay, boolean fullScreen, Size size); static final String INTERACTIVE_LONG_MESSAGE; static final String INTERACTIVE_SHORT_MESSAGE; static final String EXIT; static final List<String> DEFAULT_CONFIRM_WORDS; }### Answer:
@Test void testGetHistory() { assertNotNull(h.getHistory()); } |
### Question:
SshShellTerminalDelegate implements Terminal { @Override public String getName() { return delegate().getName(); } SshShellTerminalDelegate(Terminal delegate); @Override String getName(); @Override SignalHandler handle(Signal signal, SignalHandler signalHandler); @Override void raise(Signal signal); @Override NonBlockingReader reader(); @Override PrintWriter writer(); @Override InputStream input(); @Override OutputStream output(); @Override Attributes enterRawMode(); @Override boolean echo(); @Override boolean echo(boolean b); @Override Attributes getAttributes(); @Override void setAttributes(Attributes attributes); @Override Size getSize(); @Override void setSize(Size size); @Override void flush(); @Override String getType(); @Override boolean puts(InfoCmp.Capability capability, Object... objects); @Override boolean getBooleanCapability(InfoCmp.Capability capability); @Override Integer getNumericCapability(InfoCmp.Capability capability); @Override String getStringCapability(InfoCmp.Capability capability); @Override Cursor getCursorPosition(IntConsumer intConsumer); @Override boolean hasMouseSupport(); @Override boolean trackMouse(MouseTracking mouseTracking); @Override MouseEvent readMouseEvent(); @Override MouseEvent readMouseEvent(IntSupplier intSupplier); @Override void close(); }### Answer:
@Test void init() { assertThrows(IllegalStateException.class, () -> new SshShellTerminalDelegate(null).getName()); }
@Test public void getName() throws Exception { del.getName(); } |
### Question:
DemoCommand extends AbstractHealthIndicator { @ShellMethod("Authentication command") public SshAuthentication authentication() { return helper.getAuthentication(); } DemoCommand(SshShellHelper helper); @ShellMethod("Echo command") String echo(@ShellOption(valueProvider = CustomValuesProvider.class) String message); @ShellMethod("Terminal size command") Size size(); @ShellMethod("Progress command") void progress(int progress); @ShellMethod("File command") void file(
@ShellOption(defaultValue = ShellOption.NULL) File file,
@ShellOption(valueProvider = ExtendedFileValueProvider.class, defaultValue = ShellOption.NULL) File extended); @ShellMethod("Interactive command") void interactive(boolean fullscreen, @ShellOption(defaultValue = "3000") long delay); @ShellMethod("Ex command") void ex(); @ShellMethod("Welcome command") String welcome(); @ShellMethod("Confirmation command") String conf(); @ShellMethod("Admin command") @ShellMethodAvailability("adminAvailability") String admin(); Availability adminAvailability(); @ShellMethod("Authentication command") SshAuthentication authentication(); @ShellMethod("Displays ssh env information") String displaySshEnv(); @ShellMethod("Displays ssh session information") String displaySshSession(); @Scheduled(initialDelay = 0, fixedDelay = 60000) void logWithDelay(); @Scheduled(initialDelay = 0, fixedRate = 60000) void logWithRate(); @Scheduled(cron = "0/60 * * * * *") void logWithCron(); }### Answer:
@Test void auth() { assertEquals(auth, cmd.authentication()); } |
### Question:
SshShellTerminalDelegate implements Terminal { @Override public SignalHandler handle(Signal signal, SignalHandler signalHandler) { return delegate().handle(signal, signalHandler); } SshShellTerminalDelegate(Terminal delegate); @Override String getName(); @Override SignalHandler handle(Signal signal, SignalHandler signalHandler); @Override void raise(Signal signal); @Override NonBlockingReader reader(); @Override PrintWriter writer(); @Override InputStream input(); @Override OutputStream output(); @Override Attributes enterRawMode(); @Override boolean echo(); @Override boolean echo(boolean b); @Override Attributes getAttributes(); @Override void setAttributes(Attributes attributes); @Override Size getSize(); @Override void setSize(Size size); @Override void flush(); @Override String getType(); @Override boolean puts(InfoCmp.Capability capability, Object... objects); @Override boolean getBooleanCapability(InfoCmp.Capability capability); @Override Integer getNumericCapability(InfoCmp.Capability capability); @Override String getStringCapability(InfoCmp.Capability capability); @Override Cursor getCursorPosition(IntConsumer intConsumer); @Override boolean hasMouseSupport(); @Override boolean trackMouse(MouseTracking mouseTracking); @Override MouseEvent readMouseEvent(); @Override MouseEvent readMouseEvent(IntSupplier intSupplier); @Override void close(); }### Answer:
@Test public void handle() throws Exception { del.handle(null, null); } |
### Question:
SshShellTerminalDelegate implements Terminal { @Override public void raise(Signal signal) { delegate().raise(signal); } SshShellTerminalDelegate(Terminal delegate); @Override String getName(); @Override SignalHandler handle(Signal signal, SignalHandler signalHandler); @Override void raise(Signal signal); @Override NonBlockingReader reader(); @Override PrintWriter writer(); @Override InputStream input(); @Override OutputStream output(); @Override Attributes enterRawMode(); @Override boolean echo(); @Override boolean echo(boolean b); @Override Attributes getAttributes(); @Override void setAttributes(Attributes attributes); @Override Size getSize(); @Override void setSize(Size size); @Override void flush(); @Override String getType(); @Override boolean puts(InfoCmp.Capability capability, Object... objects); @Override boolean getBooleanCapability(InfoCmp.Capability capability); @Override Integer getNumericCapability(InfoCmp.Capability capability); @Override String getStringCapability(InfoCmp.Capability capability); @Override Cursor getCursorPosition(IntConsumer intConsumer); @Override boolean hasMouseSupport(); @Override boolean trackMouse(MouseTracking mouseTracking); @Override MouseEvent readMouseEvent(); @Override MouseEvent readMouseEvent(IntSupplier intSupplier); @Override void close(); }### Answer:
@Test public void raise() throws Exception { del.raise(null); } |
### Question:
SshShellTerminalDelegate implements Terminal { @Override public NonBlockingReader reader() { return delegate().reader(); } SshShellTerminalDelegate(Terminal delegate); @Override String getName(); @Override SignalHandler handle(Signal signal, SignalHandler signalHandler); @Override void raise(Signal signal); @Override NonBlockingReader reader(); @Override PrintWriter writer(); @Override InputStream input(); @Override OutputStream output(); @Override Attributes enterRawMode(); @Override boolean echo(); @Override boolean echo(boolean b); @Override Attributes getAttributes(); @Override void setAttributes(Attributes attributes); @Override Size getSize(); @Override void setSize(Size size); @Override void flush(); @Override String getType(); @Override boolean puts(InfoCmp.Capability capability, Object... objects); @Override boolean getBooleanCapability(InfoCmp.Capability capability); @Override Integer getNumericCapability(InfoCmp.Capability capability); @Override String getStringCapability(InfoCmp.Capability capability); @Override Cursor getCursorPosition(IntConsumer intConsumer); @Override boolean hasMouseSupport(); @Override boolean trackMouse(MouseTracking mouseTracking); @Override MouseEvent readMouseEvent(); @Override MouseEvent readMouseEvent(IntSupplier intSupplier); @Override void close(); }### Answer:
@Test public void reader() throws Exception { del.reader(); } |
### Question:
SshShellTerminalDelegate implements Terminal { @Override public PrintWriter writer() { return delegate().writer(); } SshShellTerminalDelegate(Terminal delegate); @Override String getName(); @Override SignalHandler handle(Signal signal, SignalHandler signalHandler); @Override void raise(Signal signal); @Override NonBlockingReader reader(); @Override PrintWriter writer(); @Override InputStream input(); @Override OutputStream output(); @Override Attributes enterRawMode(); @Override boolean echo(); @Override boolean echo(boolean b); @Override Attributes getAttributes(); @Override void setAttributes(Attributes attributes); @Override Size getSize(); @Override void setSize(Size size); @Override void flush(); @Override String getType(); @Override boolean puts(InfoCmp.Capability capability, Object... objects); @Override boolean getBooleanCapability(InfoCmp.Capability capability); @Override Integer getNumericCapability(InfoCmp.Capability capability); @Override String getStringCapability(InfoCmp.Capability capability); @Override Cursor getCursorPosition(IntConsumer intConsumer); @Override boolean hasMouseSupport(); @Override boolean trackMouse(MouseTracking mouseTracking); @Override MouseEvent readMouseEvent(); @Override MouseEvent readMouseEvent(IntSupplier intSupplier); @Override void close(); }### Answer:
@Test public void writer() throws Exception { del.writer(); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.