method2testcases
stringlengths 118
3.08k
|
---|
### Question:
ByteMap implements Iterable<ByteMap.Entry<V>> { public void clear (int maximumCapacity) { if (capacity <= maximumCapacity) { clear(); return; } zeroValue = null; hasZeroValue = false; size = 0; resize(maximumCapacity); } ByteMap(); ByteMap(int initialCapacity); ByteMap(int initialCapacity, float loadFactor); ByteMap(ByteMap<? extends V> map); V put(byte key, V value); void putAll(ByteMap<V> map); V get(byte key); V get(byte key, V defaultValue); V remove(byte key); void shrink(int maximumCapacity); void clear(int maximumCapacity); void clear(); boolean containsValue(Object value, boolean identity); boolean containsKey(byte key); byte findKey(Object value, boolean identity, byte notFound); void ensureCapacity(int additionalCapacity); int hashCode(); boolean equals(Object obj); String toString(); Iterator<Entry<V>> iterator(); Entries<V> entries(); Values<V> values(); Keys keys(); public int size; }### Answer:
@Test public void testClear(){ testAdd(); byteMap.clear(); Assert.assertEquals(0, byteMap.size); } |
### Question:
ShortMap implements Iterable<ShortMap.Entry<V>> { public V get (short key) { return get(key, null); } ShortMap(); ShortMap(int initialCapacity); ShortMap(int initialCapacity, float loadFactor); ShortMap(ShortMap<? extends V> map); V put(short key, V value); void putAll(ShortMap<V> map); V get(short key); V get(short key, V defaultValue); V remove(short key); void shrink(int maximumCapacity); void clear(int maximumCapacity); void clear(); boolean containsValue(Object value, boolean identity); boolean containsKey(short key); short findKey(Object value, boolean identity, short notFound); void ensureCapacity(int additionalCapacity); int hashCode(); boolean equals(Object obj); String toString(); Iterator<Entry<V>> iterator(); Entries<V> entries(); Values<V> values(); Keys keys(); public int size; }### Answer:
@Test public void testGet(){ testAdd(); Assert.assertNull(shortMap.get((short) 100)); Assert.assertEquals("Example0", shortMap.get((short) 0)); Assert.assertEquals("NewExample123", shortMap.get((short) 123)); Assert.assertEquals("Example34", shortMap.get((short) 34)); Assert.assertEquals("Example34", shortMap.get((short) 34, "DefaultValue")); Assert.assertEquals("DefaultValue", shortMap.get((short) 56, "DefaultValue")); Assert.assertEquals(3, shortMap.size); } |
### Question:
ShortMap implements Iterable<ShortMap.Entry<V>> { public void clear (int maximumCapacity) { if (capacity <= maximumCapacity) { clear(); return; } zeroValue = null; hasZeroValue = false; size = 0; resize(maximumCapacity); } ShortMap(); ShortMap(int initialCapacity); ShortMap(int initialCapacity, float loadFactor); ShortMap(ShortMap<? extends V> map); V put(short key, V value); void putAll(ShortMap<V> map); V get(short key); V get(short key, V defaultValue); V remove(short key); void shrink(int maximumCapacity); void clear(int maximumCapacity); void clear(); boolean containsValue(Object value, boolean identity); boolean containsKey(short key); short findKey(Object value, boolean identity, short notFound); void ensureCapacity(int additionalCapacity); int hashCode(); boolean equals(Object obj); String toString(); Iterator<Entry<V>> iterator(); Entries<V> entries(); Values<V> values(); Keys keys(); public int size; }### Answer:
@Test public void testClear(){ testAdd(); shortMap.clear(); Assert.assertEquals(0, shortMap.size); } |
### Question:
LongQueue { public long removeLast () { if (size == 0) { throw new NoSuchElementException("Queue is empty."); } final long[] values = this.values; int tail = this.tail; tail--; if (tail == -1) { tail = values.length - 1; } final long result = values[tail]; this.tail = tail; size--; return result; } LongQueue(); LongQueue(int initialSize); void addLast(long object); void addFirst(long object); void ensureCapacity(int additional); long removeFirst(); long removeLast(); int indexOf(long value); boolean removeValue(long value); long removeIndex(int index); boolean notEmpty(); boolean isEmpty(); long first(); long last(); long get(int index); void clear(); Iterator<Long> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer:
@Test public void removeLastTest() { LongQueue queue = new LongQueue(); queue.addLast(1); queue.addLast(2); queue.addLast(3); queue.addLast(4); assertEquals(4, queue.size); assertEquals(3, queue.indexOf(4)); assertEquals(4, queue.removeLast()); assertEquals(3, queue.size); assertEquals(2, queue.indexOf(3)); assertEquals(3, queue.removeLast()); assertEquals(2, queue.size); assertEquals(1, queue.indexOf(2)); assertEquals(2, queue.removeLast()); assertEquals(1, queue.size); assertEquals(0, queue.indexOf(1)); assertEquals(1, queue.removeLast()); assertEquals(0, queue.size); } |
### Question:
LongQueue { public long removeFirst () { if (size == 0) { throw new NoSuchElementException("Queue is empty."); } final long[] values = this.values; final long result = values[head]; head++; if (head == values.length) { head = 0; } size--; return result; } LongQueue(); LongQueue(int initialSize); void addLast(long object); void addFirst(long object); void ensureCapacity(int additional); long removeFirst(); long removeLast(); int indexOf(long value); boolean removeValue(long value); long removeIndex(int index); boolean notEmpty(); boolean isEmpty(); long first(); long last(); long get(int index); void clear(); Iterator<Long> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer:
@Test public void removeFirstTest() { LongQueue queue = new LongQueue(); queue.addLast(1); queue.addLast(2); queue.addLast(3); queue.addLast(4); assertEquals(4, queue.size); assertEquals(0, queue.indexOf(1)); assertEquals(1, queue.removeFirst()); assertEquals(3, queue.size); assertEquals(0, queue.indexOf(2)); assertEquals(2, queue.removeFirst()); assertEquals(2, queue.size); assertEquals(0, queue.indexOf(3)); assertEquals(3, queue.removeFirst()); assertEquals(1, queue.size); assertEquals(0, queue.indexOf(4)); assertEquals(4, queue.removeFirst()); assertEquals(0, queue.size); } |
### Question:
LongQueue { public long get (int index) { if (index < 0) throw new IndexOutOfBoundsException("index can't be < 0: " + index); if (index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size); final long[] values = this.values; int i = head + index; if (i >= values.length) { i -= values.length; } return values[i]; } LongQueue(); LongQueue(int initialSize); void addLast(long object); void addFirst(long object); void ensureCapacity(int additional); long removeFirst(); long removeLast(); int indexOf(long value); boolean removeValue(long value); long removeIndex(int index); boolean notEmpty(); boolean isEmpty(); long first(); long last(); long get(int index); void clear(); Iterator<Long> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer:
@Test public void getTest () { final LongQueue q = new LongQueue(7); for (int i = 0; i < 5; i++) { for (int j = 0; j < 4; j++) { q.addLast(j); } assertEquals("get(0) is not equal to peek (" + i + ")", q.get(0), q.first()); assertEquals("get(size-1) is not equal to peekLast (" + i + ")", q.get(q.size - 1), q.last()); for (int j = 0; j < 4; j++) { assertEquals(q.get(j), j); } for (int j = 0; j < 4 - 1; j++) { q.removeFirst(); assertEquals("get(0) is not equal to peek (" + i + ")", q.get(0), q.first()); } q.removeFirst(); assert q.size == 0; try { q.get(0); fail("get() on empty queue did not throw"); } catch (IndexOutOfBoundsException ignore) { } } } |
### Question:
LongQueue { public int indexOf (long value) { if (size == 0) return -1; long[] values = this.values; final int head = this.head, tail = this.tail; if (head < tail) { for (int i = head; i < tail; i++) if (values[i] == value) return i - head; } else { for (int i = head, n = values.length; i < n; i++) if (values[i] == value) return i - head; for (int i = 0; i < tail; i++) if (values[i] == value) return i + values.length - head; } return -1; } LongQueue(); LongQueue(int initialSize); void addLast(long object); void addFirst(long object); void ensureCapacity(int additional); long removeFirst(); long removeLast(); int indexOf(long value); boolean removeValue(long value); long removeIndex(int index); boolean notEmpty(); boolean isEmpty(); long first(); long last(); long get(int index); void clear(); Iterator<Long> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer:
@Test public void indexOfTest () { final LongQueue q = new LongQueue(); for (int j = 0; j <= 6; j++) q.addLast(j); for (int j = 0; j <= 6; j++) assertEquals(q.indexOf(j), j); q.clear(); for (int j = 2; j >= 0; j--) q.addFirst(j); for (int j = 3; j <= 6; j++) q.addLast(j); for (int j = 0; j <= 6; j++) assertEquals(q.indexOf(j), j); } |
### Question:
LongQueue { public String toString () { if (size == 0) { return "[]"; } final long[] values = this.values; final int head = this.head; final int tail = this.tail; StringBuilder sb = new StringBuilder(64); sb.append('['); sb.append(values[head]); for (int i = (head + 1) % values.length; i != tail; i = (i + 1) % values.length) { sb.append(", ").append(values[i]); } sb.append(']'); return sb.toString(); } LongQueue(); LongQueue(int initialSize); void addLast(long object); void addFirst(long object); void ensureCapacity(int additional); long removeFirst(); long removeLast(); int indexOf(long value); boolean removeValue(long value); long removeIndex(int index); boolean notEmpty(); boolean isEmpty(); long first(); long last(); long get(int index); void clear(); Iterator<Long> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer:
@Test public void toStringTest () { LongQueue q = new LongQueue(1); assertEquals("[]", q.toString()); q.addLast(4); assertEquals("[4]", q.toString()); q.addLast(5); q.addLast(6); q.addLast(7); assertEquals("[4, 5, 6, 7]", q.toString()); } |
### Question:
ShortQueue { public short removeLast () { if (size == 0) { throw new NoSuchElementException("Queue is empty."); } final short[] values = this.values; int tail = this.tail; tail--; if (tail == -1) { tail = values.length - 1; } final short result = values[tail]; this.tail = tail; size--; return result; } ShortQueue(); ShortQueue(int initialSize); void addLast(short object); void addFirst(short object); void ensureCapacity(int additional); short removeFirst(); short removeLast(); int indexOf(short value); boolean removeValue(short value); short removeIndex(int index); boolean notEmpty(); boolean isEmpty(); short first(); short last(); short get(int index); void clear(); Iterator<Short> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer:
@Test public void removeLastTest() { ShortQueue queue = new ShortQueue(); queue.addLast((short) 1); queue.addLast((short) 2); queue.addLast((short) 3); queue.addLast((short) 4); assertEquals(4, queue.size); assertEquals(3, queue.indexOf((short) 4)); assertEquals(4, queue.removeLast()); assertEquals(3, queue.size); assertEquals(2, queue.indexOf((short) 3)); assertEquals(3, queue.removeLast()); assertEquals(2, queue.size); assertEquals(1, queue.indexOf((short) 2)); assertEquals(2, queue.removeLast()); assertEquals(1, queue.size); assertEquals(0, queue.indexOf((short) 1)); assertEquals(1, queue.removeLast()); assertEquals(0, queue.size); } |
### Question:
ShortQueue { public short removeFirst () { if (size == 0) { throw new NoSuchElementException("Queue is empty."); } final short[] values = this.values; final short result = values[head]; head++; if (head == values.length) { head = 0; } size--; return result; } ShortQueue(); ShortQueue(int initialSize); void addLast(short object); void addFirst(short object); void ensureCapacity(int additional); short removeFirst(); short removeLast(); int indexOf(short value); boolean removeValue(short value); short removeIndex(int index); boolean notEmpty(); boolean isEmpty(); short first(); short last(); short get(int index); void clear(); Iterator<Short> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer:
@Test public void removeFirstTest() { ShortQueue queue = new ShortQueue(); queue.addLast((short) 1); queue.addLast((short) 2); queue.addLast((short) 3); queue.addLast((short) 4); assertEquals(4, queue.size); assertEquals(0, queue.indexOf((short) 1)); assertEquals(1, queue.removeFirst()); assertEquals(3, queue.size); assertEquals(0, queue.indexOf((short) 2)); assertEquals(2, queue.removeFirst()); assertEquals(2, queue.size); assertEquals(0, queue.indexOf((short) 3)); assertEquals(3, queue.removeFirst()); assertEquals(1, queue.size); assertEquals(0, queue.indexOf((short) 4)); assertEquals(4, queue.removeFirst()); assertEquals(0, queue.size); } |
### Question:
ShortQueue { public short get (int index) { if (index < 0) throw new IndexOutOfBoundsException("index can't be < 0: " + index); if (index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size); final short[] values = this.values; int i = head + index; if (i >= values.length) { i -= values.length; } return values[i]; } ShortQueue(); ShortQueue(int initialSize); void addLast(short object); void addFirst(short object); void ensureCapacity(int additional); short removeFirst(); short removeLast(); int indexOf(short value); boolean removeValue(short value); short removeIndex(int index); boolean notEmpty(); boolean isEmpty(); short first(); short last(); short get(int index); void clear(); Iterator<Short> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer:
@Test public void getTest () { final ShortQueue q = new ShortQueue(7); for (int i = 0; i < 5; i++) { for (int j = 0; j < 4; j++) { q.addLast((short) j); } assertEquals("get(0) is not equal to peek (" + i + ")", q.get(0), q.first()); assertEquals("get(size-1) is not equal to peekLast (" + i + ")", q.get(q.size - 1), q.last()); for (int j = 0; j < 4; j++) { assertEquals(q.get(j), j); } for (int j = 0; j < 4 - 1; j++) { q.removeFirst(); assertEquals("get(0) is not equal to peek (" + i + ")", q.get(0), q.first()); } q.removeFirst(); assert q.size == 0; try { q.get(0); fail("get() on empty queue did not throw"); } catch (IndexOutOfBoundsException ignore) { } } } |
### Question:
ShortQueue { public int indexOf (short value) { if (size == 0) return -1; short[] values = this.values; final int head = this.head, tail = this.tail; if (head < tail) { for (int i = head; i < tail; i++) if (values[i] == value) return i - head; } else { for (int i = head, n = values.length; i < n; i++) if (values[i] == value) return i - head; for (int i = 0; i < tail; i++) if (values[i] == value) return i + values.length - head; } return -1; } ShortQueue(); ShortQueue(int initialSize); void addLast(short object); void addFirst(short object); void ensureCapacity(int additional); short removeFirst(); short removeLast(); int indexOf(short value); boolean removeValue(short value); short removeIndex(int index); boolean notEmpty(); boolean isEmpty(); short first(); short last(); short get(int index); void clear(); Iterator<Short> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer:
@Test public void indexOfTest () { final ShortQueue q = new ShortQueue(); for (int j = 0; j <= 6; j++) q.addLast((short) j); for (int j = 0; j <= 6; j++) assertEquals(q.indexOf((short) j), j); q.clear(); for (int j = 2; j >= 0; j--) q.addFirst((short) j); for (int j = 3; j <= 6; j++) q.addLast((short) j); for (int j = 0; j <= 6; j++) assertEquals(q.indexOf((short) j), j); } |
### Question:
ShortQueue { public String toString () { if (size == 0) { return "[]"; } final short[] values = this.values; final int head = this.head; final int tail = this.tail; StringBuilder sb = new StringBuilder(64); sb.append('['); sb.append(values[head]); for (int i = (head + 1) % values.length; i != tail; i = (i + 1) % values.length) { sb.append(", ").append(values[i]); } sb.append(']'); return sb.toString(); } ShortQueue(); ShortQueue(int initialSize); void addLast(short object); void addFirst(short object); void ensureCapacity(int additional); short removeFirst(); short removeLast(); int indexOf(short value); boolean removeValue(short value); short removeIndex(int index); boolean notEmpty(); boolean isEmpty(); short first(); short last(); short get(int index); void clear(); Iterator<Short> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer:
@Test public void toStringTest () { ShortQueue q = new ShortQueue(1); assertEquals("[]", q.toString()); q.addLast((short) 4); assertEquals("[4]", q.toString()); q.addLast((short) 5); q.addLast((short) 6); q.addLast((short) 7); assertEquals("[4, 5, 6, 7]", q.toString()); } |
### Question:
IntQueue { public int removeLast () { if (size == 0) { throw new NoSuchElementException("Queue is empty."); } final int[] values = this.values; int tail = this.tail; tail--; if (tail == -1) { tail = values.length - 1; } final int result = values[tail]; this.tail = tail; size--; return result; } IntQueue(); IntQueue(int initialSize); void addLast(int object); void addFirst(int object); void ensureCapacity(int additional); int removeFirst(); int removeLast(); int indexOf(int value); boolean removeValue(int value); int removeIndex(int index); boolean notEmpty(); boolean isEmpty(); int first(); int last(); int get(int index); void clear(); Iterator<Integer> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer:
@Test public void removeLastTest() { IntQueue queue = new IntQueue(); queue.addLast(1); queue.addLast(2); queue.addLast(3); queue.addLast(4); assertEquals(4, queue.size); assertEquals(3, queue.indexOf(4)); assertEquals(4, queue.removeLast()); assertEquals(3, queue.size); assertEquals(2, queue.indexOf(3)); assertEquals(3, queue.removeLast()); assertEquals(2, queue.size); assertEquals(1, queue.indexOf(2)); assertEquals(2, queue.removeLast()); assertEquals(1, queue.size); assertEquals(0, queue.indexOf(1)); assertEquals(1, queue.removeLast()); assertEquals(0, queue.size); } |
### Question:
IntQueue { public int removeFirst () { if (size == 0) { throw new NoSuchElementException("Queue is empty."); } final int[] values = this.values; final int result = values[head]; head++; if (head == values.length) { head = 0; } size--; return result; } IntQueue(); IntQueue(int initialSize); void addLast(int object); void addFirst(int object); void ensureCapacity(int additional); int removeFirst(); int removeLast(); int indexOf(int value); boolean removeValue(int value); int removeIndex(int index); boolean notEmpty(); boolean isEmpty(); int first(); int last(); int get(int index); void clear(); Iterator<Integer> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer:
@Test public void removeFirstTest() { IntQueue queue = new IntQueue(); queue.addLast(1); queue.addLast(2); queue.addLast(3); queue.addLast(4); assertEquals(4, queue.size); assertEquals(0, queue.indexOf(1)); assertEquals(1, queue.removeFirst()); assertEquals(3, queue.size); assertEquals(0, queue.indexOf(2)); assertEquals(2, queue.removeFirst()); assertEquals(2, queue.size); assertEquals(0, queue.indexOf(3)); assertEquals(3, queue.removeFirst()); assertEquals(1, queue.size); assertEquals(0, queue.indexOf(4)); assertEquals(4, queue.removeFirst()); assertEquals(0, queue.size); } |
### Question:
IntQueue { public int get (int index) { if (index < 0) throw new IndexOutOfBoundsException("index can't be < 0: " + index); if (index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size); final int[] values = this.values; int i = head + index; if (i >= values.length) { i -= values.length; } return values[i]; } IntQueue(); IntQueue(int initialSize); void addLast(int object); void addFirst(int object); void ensureCapacity(int additional); int removeFirst(); int removeLast(); int indexOf(int value); boolean removeValue(int value); int removeIndex(int index); boolean notEmpty(); boolean isEmpty(); int first(); int last(); int get(int index); void clear(); Iterator<Integer> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer:
@Test public void getTest () { final IntQueue q = new IntQueue(7); for (int i = 0; i < 5; i++) { for (int j = 0; j < 4; j++) { q.addLast(j); } assertEquals("get(0) is not equal to peek (" + i + ")", q.get(0), q.first()); assertEquals("get(size-1) is not equal to peekLast (" + i + ")", q.get(q.size - 1), q.last()); for (int j = 0; j < 4; j++) { assertEquals(q.get(j), j); } for (int j = 0; j < 4 - 1; j++) { q.removeFirst(); assertEquals("get(0) is not equal to peek (" + i + ")", q.get(0), q.first()); } q.removeFirst(); assert q.size == 0; try { q.get(0); fail("get() on empty queue did not throw"); } catch (IndexOutOfBoundsException ignore) { } } } |
### Question:
IntQueue { public int indexOf (int value) { if (size == 0) return -1; int[] values = this.values; final int head = this.head, tail = this.tail; if (head < tail) { for (int i = head; i < tail; i++) if (values[i] == value) return i - head; } else { for (int i = head, n = values.length; i < n; i++) if (values[i] == value) return i - head; for (int i = 0; i < tail; i++) if (values[i] == value) return i + values.length - head; } return -1; } IntQueue(); IntQueue(int initialSize); void addLast(int object); void addFirst(int object); void ensureCapacity(int additional); int removeFirst(); int removeLast(); int indexOf(int value); boolean removeValue(int value); int removeIndex(int index); boolean notEmpty(); boolean isEmpty(); int first(); int last(); int get(int index); void clear(); Iterator<Integer> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer:
@Test public void indexOfTest () { final IntQueue q = new IntQueue(); for (int j = 0; j <= 6; j++) q.addLast(j); for (int j = 0; j <= 6; j++) assertEquals(q.indexOf(j), j); q.clear(); for (int j = 2; j >= 0; j--) q.addFirst(j); for (int j = 3; j <= 6; j++) q.addLast(j); for (int j = 0; j <= 6; j++) assertEquals(q.indexOf(j), j); } |
### Question:
IntQueue { public String toString () { if (size == 0) { return "[]"; } final int[] values = this.values; final int head = this.head; final int tail = this.tail; StringBuilder sb = new StringBuilder(64); sb.append('['); sb.append(values[head]); for (int i = (head + 1) % values.length; i != tail; i = (i + 1) % values.length) { sb.append(", ").append(values[i]); } sb.append(']'); return sb.toString(); } IntQueue(); IntQueue(int initialSize); void addLast(int object); void addFirst(int object); void ensureCapacity(int additional); int removeFirst(); int removeLast(); int indexOf(int value); boolean removeValue(int value); int removeIndex(int index); boolean notEmpty(); boolean isEmpty(); int first(); int last(); int get(int index); void clear(); Iterator<Integer> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer:
@Test public void toStringTest () { IntQueue q = new IntQueue(1); assertEquals("[]", q.toString()); q.addLast(4); assertEquals("[4]", q.toString()); q.addLast(5); q.addLast(6); q.addLast(7); assertEquals("[4, 5, 6, 7]", q.toString()); } |
### Question:
ConcurrentIntSet extends IntSet implements ConcurrentCollection { @Override public boolean add(int key) { lock.lockWrite(); boolean b = super.add(key); lock.unlockWrite(); return b; } ConcurrentIntSet(); ConcurrentIntSet(int initialCapacity); ConcurrentIntSet(int initialCapacity, float loadFactor); ConcurrentIntSet(IntSet set); @Override boolean add(int key); @Override void addAll(IntArray array, int offset, int length); @Override void addAll(int[] array, int offset, int length); @Override void addAll(IntSet set); @Override boolean remove(int key); @Override boolean notEmpty(); @Override boolean isEmpty(); @Override void shrink(int maximumCapacity); @Override void clear(int maximumCapacity); @Override void clear(); @Override boolean contains(int key); @Override int first(); @Override void ensureCapacity(int additionalCapacity); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); @Override IntSetIterator iterator(); @Override ReadWriteLock getLock(); }### Answer:
@Test public void testAdd() { ConcurrentIntSet set = new ConcurrentIntSet(); Random r = new Random(); CountDownLatch latch = new CountDownLatch(1000); createStartAndJoinThreads(new Runnable() { @Override public void run() { latch.countDown(); try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } while (!set.add(r.nextInt())){ } } }, 1000); assertEquals(1000, set.size); } |
### Question:
MirrorFs implements se.tfiskgul.mux2fs.fs.base.FileSystem { @Override public int getattr(String path, StatFiller stat) { logger.debug(path); return tryCatchRunnable.apply(() -> stat.stat(real(path))); } MirrorFs(Path mirroredPath); @VisibleForTesting protected MirrorFs(Path mirroredPath, FileChannelCloser fileChannelCloser); @Override String getFSName(); @Override int getattr(String path, StatFiller stat); @Override int readdir(String path, DirectoryFiller filler); @Override int readLink(String path, Consumer<String> buf, int size); @Override int open(String path, FileHandleFiller filler); @Override int read(String path, Consumer<byte[]> buf, int size, long offset, int fileHandle); @Override int release(String path, int fileHandle); @Override void destroy(); }### Answer:
@Test public void testGetAttrSubDir() throws Exception { StatFiller stat = mock(StatFiller.class); Path foo = mockPath("/foo"); int result = fs.getattr("/foo", stat); assertThat(result).isEqualTo(SUCCESS); verify(stat).stat(foo); }
@Test public void testGetAttr() throws Exception { StatFiller stat = mock(StatFiller.class); when(fileSystem.getPath(mirrorRoot.toString(), "/")).thenReturn(mirrorRoot); int result = fs.getattr("/", stat); assertThat(result).isEqualTo(SUCCESS); verify(stat).stat(mirrorRoot); } |
### Question:
MirrorFs implements se.tfiskgul.mux2fs.fs.base.FileSystem { @Override public int readdir(String path, DirectoryFiller filler) { Path realPath = readdirInitial(path, filler); return tryCatch.apply(() -> { try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(realPath)) { for (Path entry : directoryStream) { if (!add(filler, entry)) { return SUCCESS; } } } return SUCCESS; }); } MirrorFs(Path mirroredPath); @VisibleForTesting protected MirrorFs(Path mirroredPath, FileChannelCloser fileChannelCloser); @Override String getFSName(); @Override int getattr(String path, StatFiller stat); @Override int readdir(String path, DirectoryFiller filler); @Override int readLink(String path, Consumer<String> buf, int size); @Override int open(String path, FileHandleFiller filler); @Override int read(String path, Consumer<byte[]> buf, int size, long offset, int fileHandle); @Override int release(String path, int fileHandle); @Override void destroy(); }### Answer:
@Test public void testReadDir() throws Exception { Path foo = mockPath("foo"); Path bar = mockPath("bar"); mockDirectoryStream(mirrorRoot, foo, bar); DirectoryFiller filler = mock(DirectoryFiller.class); int result = fs.readdir("/", filler); assertThat(result).isEqualTo(SUCCESS); verify(fileSystem.provider()).newDirectoryStream(eq(mirrorRoot), any()); verify(filler).add(".", mirrorRoot); verify(filler).add("..", mirrorRoot); verify(filler).add("foo", foo); verify(filler).add("bar", bar); verifyNoMoreInteractions(filler); } |
### Question:
MirrorFs implements se.tfiskgul.mux2fs.fs.base.FileSystem { protected Optional<String> getFileName(Path entry) { return Optional.ofNullable(entry).flatMap(notNull -> Optional.ofNullable(notNull.getFileName())).map(Object::toString); } MirrorFs(Path mirroredPath); @VisibleForTesting protected MirrorFs(Path mirroredPath, FileChannelCloser fileChannelCloser); @Override String getFSName(); @Override int getattr(String path, StatFiller stat); @Override int readdir(String path, DirectoryFiller filler); @Override int readLink(String path, Consumer<String> buf, int size); @Override int open(String path, FileHandleFiller filler); @Override int read(String path, Consumer<byte[]> buf, int size, long offset, int fileHandle); @Override int release(String path, int fileHandle); @Override void destroy(); }### Answer:
@Test public void testGetFileNameOnNullPathIsEmpty() throws Exception { assertThat(new MirrorFs(mirrorRoot).getFileName(null)).isEmpty(); }
@Test public void testGetFileNameOnNullFileNameIsEmpty() throws Exception { assertThat(new MirrorFs(mirrorRoot).getFileName(mock(Path.class))).isEmpty(); } |
### Question:
MirrorFs implements se.tfiskgul.mux2fs.fs.base.FileSystem { @Override public int release(String path, int fileHandle) { logger.info("release({}, {})", fileHandle, path); FileChannel fileChannel = openFiles.remove(fileHandle); if (fileChannel == null) { return -ErrorCodes.EBADF(); } safeClose(fileChannel); return SUCCESS; } MirrorFs(Path mirroredPath); @VisibleForTesting protected MirrorFs(Path mirroredPath, FileChannelCloser fileChannelCloser); @Override String getFSName(); @Override int getattr(String path, StatFiller stat); @Override int readdir(String path, DirectoryFiller filler); @Override int readLink(String path, Consumer<String> buf, int size); @Override int open(String path, FileHandleFiller filler); @Override int read(String path, Consumer<byte[]> buf, int size, long offset, int fileHandle); @Override int release(String path, int fileHandle); @Override void destroy(); }### Answer:
@Test public void testReleaseNegativeFileHandle() { int result = fs.release("foo.bar", -23); assertThat(result).isEqualTo(-ErrorCodes.EBADF()); }
@Test public void testReleaseNonOpenedFileHandle() { int result = fs.release("foo.bar", 23); assertThat(result).isEqualTo(-ErrorCodes.EBADF()); }
@Test public void testRelease() throws Exception { FileHandleFiller filler = mock(FileHandleFiller.class); ArgumentCaptor<Integer> handleCaptor = ArgumentCaptor.forClass(Integer.class); doNothing().when(filler).setFileHandle(handleCaptor.capture()); Path fooBar = mockPath(mirrorRoot, "foo.bar"); when(fileSystem.provider().newFileChannel(eq(fooBar), eq(set(StandardOpenOption.READ)))).thenReturn(mock(FileChannel.class)); fs.open("foo.bar", filler); int result = fs.release("foo.bar", handleCaptor.getValue()); assertThat(result).isEqualTo(SUCCESS); } |
### Question:
MirrorFs implements se.tfiskgul.mux2fs.fs.base.FileSystem { @Override public void destroy() { logger.info("Cleaning up"); openFiles.forEach((fh, channel) -> safeClose(channel)); openFiles.clear(); } MirrorFs(Path mirroredPath); @VisibleForTesting protected MirrorFs(Path mirroredPath, FileChannelCloser fileChannelCloser); @Override String getFSName(); @Override int getattr(String path, StatFiller stat); @Override int readdir(String path, DirectoryFiller filler); @Override int readLink(String path, Consumer<String> buf, int size); @Override int open(String path, FileHandleFiller filler); @Override int read(String path, Consumer<byte[]> buf, int size, long offset, int fileHandle); @Override int release(String path, int fileHandle); @Override void destroy(); }### Answer:
@Test public void testDestroy() { fs.destroy(); } |
### Question:
MirrorFs implements se.tfiskgul.mux2fs.fs.base.FileSystem { @Override public int readLink(String path, Consumer<String> buf, int size) { logger.debug(path); Path real = real(path); return tryCatch.apply(() -> { Path target = Files.readSymbolicLink(real); return getFileName(target).map(name -> { buf.accept(truncateIfNeeded(name, size)); return SUCCESS; }).orElse(-ErrorCodes.EINVAL()); }); } MirrorFs(Path mirroredPath); @VisibleForTesting protected MirrorFs(Path mirroredPath, FileChannelCloser fileChannelCloser); @Override String getFSName(); @Override int getattr(String path, StatFiller stat); @Override int readdir(String path, DirectoryFiller filler); @Override int readLink(String path, Consumer<String> buf, int size); @Override int open(String path, FileHandleFiller filler); @Override int read(String path, Consumer<byte[]> buf, int size, long offset, int fileHandle); @Override int release(String path, int fileHandle); @Override void destroy(); }### Answer:
@Test public void testReadLink() throws Exception { Path fooBar = mockPath("foo.bar"); Path target = mockPath("bar.foo"); when(fileSystem.provider().readSymbolicLink(fooBar)).thenReturn(target); int result = fs.readLink("foo.bar", (name) -> assertThat(name).isEqualTo("bar.foo"), 1024); assertThat(result).isEqualTo(SUCCESS); }
@Test public void testReadLinkLongNameIsTruncated() throws Exception { Path fooBar = mockPath("foo.bar"); Path target = mockPath("ThisIsALongName"); when(fileSystem.provider().readSymbolicLink(fooBar)).thenReturn(target); int result = fs.readLink("foo.bar", (name) -> assertThat(name).isEqualTo("ThisI"), 5); assertThat(result).isEqualTo(SUCCESS); } |
### Question:
FileInfo { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } FileInfo other = (FileInfo) obj; return Objects.equals(inode, other.inode) && Objects.equals(mtime, other.mtime) && Objects.equals(ctime, other.ctime) && Objects.equals(size, other.size); } FileInfo(long inode, FileTime mtime, FileTime ctime, long size); FileInfo(long inode, Instant mtime, Instant ctime, long size); static FileInfo of(Path path); long getInode(); FileTime getMtime(); FileTime getCtime(); long getSize(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer:
@Test public void testEquals() { long ino = 1234L; long size = 9876L; Instant modificationTime = Instant.now(); Instant inodeTime = Instant.now().plusSeconds(5); FileInfo fileInfo = new FileInfo(ino, modificationTime, inodeTime, size); assertThat(fileInfo).isEqualTo(fileInfo); assertThat(fileInfo).isNotEqualTo(null); assertThat(fileInfo).isNotEqualTo(inodeTime); } |
### Question:
Muxer { public void start() throws IOException { if (state.compareAndSet(NOT_STARTED, RUNNING)) { try { access(mkv, AccessMode.READ); access(srt, AccessMode.READ); access(tempDir, AccessMode.WRITE); output.toFile().deleteOnExit(); ProcessBuilder builder = factory.from("mkvmerge", "-o", output.toString(), mkv.toString(), srt.toString()); builder.directory(tempDir.toFile()).inheritIO(); process = builder.start(); } catch (Exception e) { state.set(FAILED); deleteWarn(output); throw e; } } } private Muxer(Path mkv, Path srt, Path tempDir, ProcessBuilderFactory factory, Sleeper sleeper); static Muxer of(Path mkv, Path srt, Path tempDir); void start(); State state(); int waitFor(); boolean waitFor(long timeout, TimeUnit unit); Optional<Path> getOutput(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); Path getMkv(); boolean waitForOutput(); }### Answer:
@Test public void testMkvMustBeReadable() throws Exception { doThrow(new NoSuchFileException(null)).when(provider).checkAccess(mkv, AccessMode.READ); exception.expect(NoSuchFileException.class); muxer.start(); }
@Test public void testSrtMustBeReadable() throws Exception { doThrow(new NoSuchFileException(null)).when(provider).checkAccess(srt, AccessMode.READ); exception.expect(NoSuchFileException.class); muxer.start(); }
@Test public void testempDirMustBeWriteable() throws Exception { doThrow(new NoSuchFileException(null)).when(provider).checkAccess(tempDir, AccessMode.WRITE); exception.expect(NoSuchFileException.class); muxer.start(); }
@Test public void testStart() throws Exception { muxer.start(); verify(muxer.getOutputForTest().toFile()).deleteOnExit(); verify(factory).from("mkvmerge", "-o", muxer.getOutput().get().toString(), mkv.toString(), srt.toString()); } |
### Question:
Muxer { public int waitFor() throws InterruptedException { switch (state()) { case NOT_STARTED: throw new IllegalStateException("Not started"); case FAILED: return process != null ? process.exitValue() : -127; case RUNNING: case SUCCESSFUL: return process.waitFor(); default: throw new IllegalStateException("BUG: Unkown state"); } } private Muxer(Path mkv, Path srt, Path tempDir, ProcessBuilderFactory factory, Sleeper sleeper); static Muxer of(Path mkv, Path srt, Path tempDir); void start(); State state(); int waitFor(); boolean waitFor(long timeout, TimeUnit unit); Optional<Path> getOutput(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); Path getMkv(); boolean waitForOutput(); }### Answer:
@Test public void testWaitForNonStartedMuxer() throws Exception { exception.expect(IllegalStateException.class); muxer.waitFor(); }
@Test public void testWaitFor50millisNonStartedMuxer() throws Exception { exception.expect(IllegalStateException.class); muxer.waitFor(50, MILLISECONDS); } |
### Question:
Muxer { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Muxer other = (Muxer) obj; return Objects.equals(mkv, other.mkv) && Objects.equals(output, other.output) && Objects.equals(srt, other.srt) && Objects.equals(tempDir, other.tempDir); } private Muxer(Path mkv, Path srt, Path tempDir, ProcessBuilderFactory factory, Sleeper sleeper); static Muxer of(Path mkv, Path srt, Path tempDir); void start(); State state(); int waitFor(); boolean waitFor(long timeout, TimeUnit unit); Optional<Path> getOutput(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); Path getMkv(); boolean waitForOutput(); }### Answer:
@Test public void testEquals() { Muxer another = Muxer.of(mkv, srt, tempDir); boolean result = muxer.equals(another); assertThat(result).isFalse(); } |
### Question:
Muxer { @Override public int hashCode() { return Objects.hash(mkv, output, srt, tempDir); } private Muxer(Path mkv, Path srt, Path tempDir, ProcessBuilderFactory factory, Sleeper sleeper); static Muxer of(Path mkv, Path srt, Path tempDir); void start(); State state(); int waitFor(); boolean waitFor(long timeout, TimeUnit unit); Optional<Path> getOutput(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); Path getMkv(); boolean waitForOutput(); }### Answer:
@Test public void testHashCode() { Muxer another = Muxer.of(mkv, srt, tempDir); int hashCode = another.hashCode(); assertThat(hashCode).isNotEqualTo(muxer.hashCode()); } |
### Question:
Muxer { public Path getMkv() { return mkv; } private Muxer(Path mkv, Path srt, Path tempDir, ProcessBuilderFactory factory, Sleeper sleeper); static Muxer of(Path mkv, Path srt, Path tempDir); void start(); State state(); int waitFor(); boolean waitFor(long timeout, TimeUnit unit); Optional<Path> getOutput(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); Path getMkv(); boolean waitForOutput(); }### Answer:
@Test public void testGetMkv() { assertThat(muxer.getMkv()).isEqualTo(mkv); } |
### Question:
MuxedFile { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } MuxedFile other = (MuxedFile) obj; return Objects.equals(info, other.info) && Objects.equals(muxer, other.muxer); } MuxedFile(FileInfo info, Muxer muxer); FileInfo getInfo(); Muxer getMuxer(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testEquals() { FileInfo info = mock(FileInfo.class); Muxer muxer = mock(Muxer.class); MuxedFile muxedFile = new MuxedFile(info, muxer); MuxedFile muxedFile2 = new MuxedFile(info, muxer); assertThat(muxedFile).isEqualTo(muxedFile); assertThat(muxedFile).isEqualTo(muxedFile2); assertThat(muxedFile).isNotEqualTo(null); assertThat(muxedFile).isNotEqualTo(info); } |
### Question:
MuxedFile { @Override public int hashCode() { return Objects.hash(info, muxer); } MuxedFile(FileInfo info, Muxer muxer); FileInfo getInfo(); Muxer getMuxer(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testHashCode() { FileInfo info = mock(FileInfo.class); Muxer muxer = mock(Muxer.class); MuxedFile muxedFile = new MuxedFile(info, muxer); MuxedFile muxedFile2 = new MuxedFile(info, muxer); assertThat(muxedFile.hashCode()).isEqualTo(muxedFile2.hashCode()); } |
### Question:
Main { public static void main(String[] args) throws IOException { try { Strict arguments = new CommandLineArguments().parse(args); if (arguments.isHelp()) { System.out.println(arguments.getHelp()); } else if (arguments.isVersion()) { System.out.println("mux2fs version " + arguments.getVersion()); } else { arguments.validate(); mount(arguments); } } catch (Exception e) { System.err.println(CommandLineArguments.getUsage()); throw e; } } static void main(String[] args); }### Answer:
@Test public void testHelp() throws Exception { Main.main(array("-h")); }
@Test public void testInvalidOptions() throws Exception { exception.expect(ParameterException.class); Main.main(array("nonse -o nse c -p ommand line")); }
@Test public void testInvalidFuseOptions() throws Exception { exception.expect(FuseException.class); Main.main(array("/", "/tmp", "-o", "tempdir=/tmp,nonsense=invalid")); }
@Test public void testVersion() throws Exception { Main.main(array("-v")); } |
### Question:
TodoService { public List<TodoEntity> getAll() { return todoDAO.findAll(); } List<TodoEntity> getAll(); boolean add(TodoEntity entity); boolean edit(TodoEntity entity); boolean delete(long id); }### Answer:
@Test public void GetAllTest_When_MethodCall_ExpectTodoEntityList(){ TodoEntity todo1 = new TodoEntity(); todo1.setId(1); todo1.setStatus(TodoStatusType.OPEN); todo1.setName("Test todo1 name"); TodoEntity todo2 = new TodoEntity(); todo1.setId(2); todo1.setStatus(TodoStatusType.CLOSED); todo1.setName("Test todo2 name"); List<TodoEntity> existingEntities = Arrays.asList(todo1, todo2); when(todoDAO.findAll()).thenReturn(existingEntities); assertThat(todoService.getAll()).hasSize(2).contains(todo1, todo2); } |
### Question:
TodoService { public boolean add(TodoEntity entity) { if(todoDAO.findByName(entity.getName())!=null) return false; entity.setStatus(TodoStatusType.OPEN); todoDAO.saveOrUpdate(entity); return true; } List<TodoEntity> getAll(); boolean add(TodoEntity entity); boolean edit(TodoEntity entity); boolean delete(long id); }### Answer:
@Test public void AddTest_When_GivenNewNotExistingBeforeTodoEntityWithNameOnly_ExpectTrue(){ TodoEntity todoToAdd = new TodoEntity(); todoToAdd.setName("Test todoToAdd name"); assertThat(todoService.add(todoToAdd)).isTrue(); }
@Test public void AddTest_When_GivenTodoEntityWithNameThatExistedBefore_ExpectFalse(){ TodoEntity alreadyExistingTodo = new TodoEntity(); alreadyExistingTodo.setId(1); alreadyExistingTodo.setStatus(TodoStatusType.OPEN); alreadyExistingTodo.setName("Test already existing name"); TodoEntity todoToAdd = new TodoEntity(); todoToAdd.setName(alreadyExistingTodo.getName()); when(todoDAO.findByName(alreadyExistingTodo.getName())).thenReturn(alreadyExistingTodo); assertThat(todoService.add(todoToAdd)).isFalse(); } |
### Question:
TodoService { public boolean delete(long id) { if(todoDAO.findById(id) == null) return false; todoDAO.delete(id); return true; } List<TodoEntity> getAll(); boolean add(TodoEntity entity); boolean edit(TodoEntity entity); boolean delete(long id); }### Answer:
@Test public void DeleteTest_When_GivenExistingTodoEntityId_ExpectTrue(){ TodoEntity alreadyExistingTodo = new TodoEntity(); alreadyExistingTodo.setId(1); alreadyExistingTodo.setStatus(TodoStatusType.OPEN); alreadyExistingTodo.setName("Test already existing name"); when(todoDAO.findById(alreadyExistingTodo.getId())).thenReturn(alreadyExistingTodo); assertThat(todoService.delete(alreadyExistingTodo.getId())).isTrue(); }
@Test public void DeleteTest_When_GivenNonExistingTodoEntityId_ExpectFalse(){ long nonExistingId = 1; when(todoDAO.findById(nonExistingId)).thenReturn(null); assertThat(todoService.delete(nonExistingId)).isFalse(); } |
### Question:
StringTokenizer { public static Set<String> tokenize(String input) { return StringUtils.isBlank(input) ? new HashSet<String>() : new HashSet<String>(Arrays.asList(input.trim().split("\\s*,\\s*"))); } private StringTokenizer(); static Set<String> tokenize(String input); }### Answer:
@Test public void shouldBeAbleToTokenizeAStringWithSpacesBetweenItems() { Set<String> set = StringTokenizer.tokenize("first, second, third"); assertThat(set).contains("first", "second", "third"); }
@Test public void shouldBeAbleToTokenizeAStringWithSpacesBeforeAndAfterAndBetweenItems() { Set<String> set = StringTokenizer.tokenize(" first, second, third "); assertThat(set).contains("first", "second", "third"); }
@Test public void shouldBeAbleToTokenizeAStringWithAdditionalCommas() { Set<String> set = StringTokenizer.tokenize("first,,,second,,third,,"); assertThat(set).contains("first", "second", "third"); }
@Test public void shouldReturnAnEmptyListIfTheStringToTokenizeIsNull() { Set<String> set = StringTokenizer.tokenize(" "); assertThat(set).isEmpty(); }
@Test public void shouldBeAbleToTokenizeAString() { Set<String> set = StringTokenizer.tokenize("first,second,third"); assertThat(set).contains("first", "second", "third"); } |
### Question:
OAuth2AuthorizationContext implements AuthorizationContextProvider { public boolean isAuthenticated() { OAuth2Authentication oauth = oauth2Authentication(); return oauth == null ? false : oauth.isAuthenticated(); } OAuth2AuthorizationContext(); boolean isAuthenticated(); Set<String> getScopes(); Set<String> getAuthorities(); Set<String> getRoles(); String getUsername(); }### Answer:
@Test public void shouldBeAuthenticatedWhenTheUnderlyingAuthenticationIsAuthenticated() { when(authentication.isAuthenticated()).thenReturn(true); OAuth2AuthorizationContext ctx = new OAuth2AuthorizationContext(); Assertions.assertThat(ctx.isAuthenticated()).isTrue(); }
@Test public void shouldNotBeAuthenticatedWhenTheUnderlyingAuthenticationIsNotAuthenticated() { when(authentication.isAuthenticated()).thenReturn(false); OAuth2AuthorizationContext ctx = new OAuth2AuthorizationContext(); assertThat(ctx.isAuthenticated()).isFalse(); }
@Test public void shouldNotBeAuthenticatedWhenTheUnderlyingAuthenticationIsNull() { when(context.getAuthentication()).thenReturn(null); SecurityContextHolder.setContext(context); OAuth2AuthorizationContext ctx = new OAuth2AuthorizationContext(); assertThat(ctx.isAuthenticated()).isFalse(); }
@Test public void shouldNotBeAuthenticatedWhenTheUnderlyingAuthenticationIsNotAnOAuth2Authentication() { when(context.getAuthentication()).thenReturn(anonymousAuthentication); SecurityContextHolder.setContext(context); OAuth2AuthorizationContext ctx = new OAuth2AuthorizationContext(); assertThat(ctx.isAuthenticated()).isFalse(); } |
### Question:
OAuth2AuthorizationContext implements AuthorizationContextProvider { public Set<String> getScopes() { OAuth2Authentication oauth = oauth2Authentication(); if (oauth == null) { return new HashSet<String>(); } Set<String> scope = oauth.getOAuth2Request().getScope(); return scope == null ? new HashSet<String>() : scope; } OAuth2AuthorizationContext(); boolean isAuthenticated(); Set<String> getScopes(); Set<String> getAuthorities(); Set<String> getRoles(); String getUsername(); }### Answer:
@Test public void shouldReturnAnEmtpySetOfScopesIfTheAuthenticationIsNotAnOAuth2Authentication() { when(context.getAuthentication()).thenReturn(testAuthentication); SecurityContextHolder.setContext(context); OAuth2AuthorizationContext ctx = new OAuth2AuthorizationContext(); assertThat(ctx.getScopes()).hasSize(0); } |
### Question:
OAuth2AuthorizationContext implements AuthorizationContextProvider { public Set<String> getAuthorities() { OAuth2Authentication oauth = oauth2Authentication(); if (oauth == null) { return new HashSet<String>(); } Collection<GrantedAuthority> authorities = oauth.getAuthorities(); return authorities == null ? new HashSet<String>() : authorities.stream().map(authority -> authority.getAuthority()).collect(Collectors.toSet()); } OAuth2AuthorizationContext(); boolean isAuthenticated(); Set<String> getScopes(); Set<String> getAuthorities(); Set<String> getRoles(); String getUsername(); }### Answer:
@Test public void shouldReturnAnEmtpySetOfAuthoritiesIfTheAuthenticationIsNotAnOAuth2Authentication() { when(context.getAuthentication()).thenReturn(testAuthentication); SecurityContextHolder.setContext(context); OAuth2AuthorizationContext ctx = new OAuth2AuthorizationContext(); assertThat(ctx.getAuthorities()).hasSize(0); } |
### Question:
AudienceConversionService { public Audience convert(AudienceRepresentation representation) { Audience audience = new Audience(representation.getName()); audience.setDescription(representation.getDescription()); return audience; } Audience convert(AudienceRepresentation representation); AudienceRepresentation convert(Audience audience); Audience convert(AudienceRepresentation representation, Audience audience); }### Answer:
@Test public void shouldBeAbleToConvertAAudienceIntoAAudienceRepresentation() { Audience audience = audience().build(); AudienceRepresentation representation = audienceConversionService.convert(audience); assertThat(representation.getId()).isEqualTo(audience.getId()); assertThat(representation.getCreated()).isEqualTo(audience.getCreated()); assertThat(representation.getUpdated()).isEqualTo(audience.getUpdated()); assertThat(representation.getName()).isEqualTo(audience.getName()); assertThat(representation.getDescription()).isEqualTo(audience.getDescription()); }
@Test public void shouldBeAbleToConvertAAudienceRepresentationIntoANewAudience() { AudienceRepresentation representation = AudienceDSL.audience().build(); Audience audience = audienceConversionService.convert(representation); assertThat(audience.getName()).isEqualTo(representation.getName()); assertThat(audience.getDescription()).isEqualTo(representation.getDescription()); }
@Test public void shouldBeAbleToConvertAAudienceRepresentationIntoAnExistingAudience() { AudienceRepresentation representation = AudienceDSL.audience().build(); Audience audience = audience().build(); Audience updated = audienceConversionService.convert(representation, audience); assertThat(updated.getId()).isEqualTo(audience.getId()); assertThat(updated.getCreated()).isEqualTo(audience.getCreated()); assertThat(updated.getUpdated()).isEqualTo(audience.getUpdated()); assertThat(updated.getName()).isEqualTo(representation.getName()); assertThat(updated.getDescription()).isEqualTo(representation.getDescription()); } |
### Question:
ScopeConversionService { public Scope convert(ScopeRepresentation representation) { Scope audience = new Scope(representation.getName()); audience.setDescription(representation.getDescription()); return audience; } Scope convert(ScopeRepresentation representation); ScopeRepresentation convert(Scope scope); Scope convert(ScopeRepresentation representation, Scope scope); }### Answer:
@Test public void shouldBeAbleToConvertAScopeIntoAScopeRepresentation() { Scope scope = scope().build(); ScopeRepresentation representation = scopeConversionService.convert(scope); assertThat(representation.getId()).isEqualTo(scope.getId()); assertThat(representation.getCreated()).isEqualTo(scope.getCreated()); assertThat(representation.getUpdated()).isEqualTo(scope.getUpdated()); assertThat(representation.getName()).isEqualTo(scope.getName()); assertThat(representation.getDescription()).isEqualTo(scope.getDescription()); }
@Test public void shouldBeAbleToConvertAScopeRepresentationIntoANewScope() { ScopeRepresentation representation = ScopeDSL.scope().build(); Scope scope = scopeConversionService.convert(representation); assertThat(scope.getName()).isEqualTo(representation.getName()); assertThat(scope.getDescription()).isEqualTo(representation.getDescription()); }
@Test public void shouldBeAbleToConvertAScopeRepresentationIntoAnExistingScope() { ScopeRepresentation representation = ScopeDSL.scope().build(); Scope scope = scope().build(); Scope updated = scopeConversionService.convert(representation, scope); assertThat(updated.getId()).isEqualTo(scope.getId()); assertThat(updated.getCreated()).isEqualTo(scope.getCreated()); assertThat(updated.getUpdated()).isEqualTo(scope.getUpdated()); assertThat(updated.getName()).isEqualTo(representation.getName()); assertThat(updated.getDescription()).isEqualTo(representation.getDescription()); } |
### Question:
AuthorityConversionService { public Authority convert(AuthorityRepresentation representation) { Authority authority = new Authority(representation.getName()); authority.setDescription(representation.getDescription()); return authority; } Authority convert(AuthorityRepresentation representation); AuthorityRepresentation convert(Authority authority); Authority convert(AuthorityRepresentation representation, Authority authority); }### Answer:
@Test public void shouldBeAbleToConvertAAuthorityIntoAAuthorityRepresentation() { Authority authority = authority().build(); AuthorityRepresentation representation = authorityConversionService.convert(authority); assertThat(representation.getId()).isEqualTo(authority.getId()); assertThat(representation.getCreated()).isEqualTo(authority.getCreated()); assertThat(representation.getUpdated()).isEqualTo(authority.getUpdated()); assertThat(representation.getName()).isEqualTo(authority.getName()); assertThat(representation.getDescription()).isEqualTo(authority.getDescription()); }
@Test public void shouldBeAbleToConvertAAuthorityRepresentationIntoANewAuthority() { AuthorityRepresentation representation = AuthorityDSL.authority().build(); Authority authority = authorityConversionService.convert(representation); assertThat(authority.getName()).isEqualTo(representation.getName()); assertThat(authority.getDescription()).isEqualTo(representation.getDescription()); }
@Test public void shouldBeAbleToConvertAAuthorityRepresentationIntoAnExistingAuthority() { AuthorityRepresentation representation = AuthorityDSL.authority().build(); Authority authority = authority().build(); Authority updated = authorityConversionService.convert(representation, authority); assertThat(updated.getId()).isEqualTo(authority.getId()); assertThat(updated.getCreated()).isEqualTo(authority.getCreated()); assertThat(updated.getUpdated()).isEqualTo(authority.getUpdated()); assertThat(updated.getName()).isEqualTo(representation.getName()); assertThat(updated.getDescription()).isEqualTo(representation.getDescription()); } |
### Question:
RoleConversionService { public Role convert(RoleRepresentation representation) { Role role = new Role(representation.getName()); role.setDescription(representation.getDescription()); return role; } Role convert(RoleRepresentation representation); RoleRepresentation convert(Role role); Role convert(RoleRepresentation representation, Role role); }### Answer:
@Test public void shouldBeAbleToConvertARoleIntoARoleRepresentation() { Role role = role().build(); RoleRepresentation representation = roleConversionService.convert(role); assertThat(representation.getId()).isEqualTo(role.getId()); assertThat(representation.getCreated()).isEqualTo(role.getCreated()); assertThat(representation.getUpdated()).isEqualTo(role.getUpdated()); assertThat(representation.getName()).isEqualTo(role.getName()); assertThat(representation.getDescription()).isEqualTo(role.getDescription()); }
@Test public void shouldBeAbleToConvertARoleRepresentationIntoANewRole() { RoleRepresentation representation = RoleDSL.role().build(); Role role = roleConversionService.convert(representation); assertThat(role.getName()).isEqualTo(representation.getName()); assertThat(role.getDescription()).isEqualTo(representation.getDescription()); }
@Test public void shouldBeAbleToConvertARoleRepresentationIntoAnExistingRole() { RoleRepresentation representation = RoleDSL.role().build(); Role role = role().build(); Role updated = roleConversionService.convert(representation, role); assertThat(updated.getId()).isEqualTo(role.getId()); assertThat(updated.getCreated()).isEqualTo(role.getCreated()); assertThat(updated.getUpdated()).isEqualTo(role.getUpdated()); assertThat(updated.getName()).isEqualTo(representation.getName()); assertThat(updated.getDescription()).isEqualTo(representation.getDescription()); } |
### Question:
PaginatedListConversionService { public <C> PaginatedListRepresentation<C> convert(PaginatedList<?> list, Class<C> type) { PaginatedListRepresentation<C> representation = new PaginatedListRepresentation<>(); representation.setCriteria(criteriaConversionService.convert(list.getCriteria())); representation.setTotal(list.getTotal()); representation.setRemaining(list.getRemainingResults()); representation.setPages(list.getTotalPages()); return representation; } @Autowired PaginatedListConversionService(CriteriaConversionService criteriaConversionService); PaginatedListRepresentation<C> convert(PaginatedList<?> list, Class<C> type); }### Answer:
@Test public void shouldBeAbleToConverAPaginatedListIntoAPaginatedListRepresentation() { Criteria criteria = Criteria.criteria().from(new Date()).to(new Date()).limit(10).page(1); PaginatedList<?> list = new PaginatedList<>(new ArrayList<>(), 100, criteria); PaginatedListRepresentation<AccountRepresentation> representation = paginatedListConversionService.convert(list, AccountRepresentation.class); assertThat(representation.getPayload()).isEmpty(); assertThat(representation.getCriteria()).isEqualToComparingFieldByField(criteriaConversionService.convert(criteria)); assertThat(representation.getPages()).isEqualTo(10); assertThat(representation.getTotal()).isEqualTo(100); assertThat(representation.getRemaining()).isEqualTo(90); } |
### Question:
CriteriaConversionService { public CriteriaRepresentation convert(Criteria criteria) { CriteriaRepresentation representation = new CriteriaRepresentation(); representation.setFrom(criteria.hasFrom() ? criteria.getFrom().getTime() : null); representation.setTo(criteria.hasTo() ? criteria.getTo().getTime() : null); representation.setPage(criteria.getPage()); representation.setLimit(criteria.getLimit()); return representation; } CriteriaRepresentation convert(Criteria criteria); }### Answer:
@Test public void shouldBeAbleToConvertCriteriaIntoACriteriaRepresentation() { Criteria criteria = Criteria.criteria().from(new Date()).to(new Date()).limit(10).page(1); CriteriaRepresentation representation = criteriaConversionService.convert(criteria); assertThat(representation.getPage()).isEqualTo(criteria.getPage()); assertThat(representation.getLimit()).isEqualTo(criteria.getLimit()); assertThat(representation.getFrom()).isNotNull(); assertThat(representation.getTo()).isNotNull(); } |
### Question:
CommonPasswordsDictionary { public static List<String> list() { return passwords; } private CommonPasswordsDictionary(); static List<String> list(); static boolean contains(String password); }### Answer:
@Test public void shouldBeAbleToListTenThousandOfTheMostCommonPasswords() { List<String> common = CommonPasswordsDictionary.list(); assertThat(common).hasSize(10000); } |
### Question:
CommonPasswordsDictionary { public static boolean contains(String password) { return StringUtils.isBlank(password) ? false : !passwords.parallelStream().filter(pw -> pw.equalsIgnoreCase(password)).collect(Collectors.toList()).isEmpty(); } private CommonPasswordsDictionary(); static List<String> list(); static boolean contains(String password); }### Answer:
@Test public void shouldBeAbleToIdentifyCommonPasswords() { assertThat(CommonPasswordsDictionary.contains("password")).isTrue(); assertThat(CommonPasswordsDictionary.contains("midnight")).isTrue(); assertThat(CommonPasswordsDictionary.contains("123456")).isTrue(); assertThat(CommonPasswordsDictionary.contains("asdfs2342o8fhshfsd")).isFalse(); }
@Test public void shouldPerformACaseInsensitiveMatchWhenIdentifyingCommonPasswords() { assertThat(CommonPasswordsDictionary.contains("password")).isTrue(); assertThat(CommonPasswordsDictionary.contains("PASSWORD")).isTrue(); assertThat(CommonPasswordsDictionary.contains("PAsswoRD")).isTrue(); }
@Test public void shouldReturnFalseIfThePasswordToCheckIsNullOrEmpty() { assertThat(CommonPasswordsDictionary.contains(null)).isFalse(); assertThat(CommonPasswordsDictionary.contains("")).isFalse(); assertThat(CommonPasswordsDictionary.contains(" ")).isFalse(); } |
### Question:
RpcStartupHookProvider implements StartupHookProvider { @Override public void onStartup() { System.out.println("Handler scanning package = " + config.getHandlerPackage()); List<String> handlers; try (ScanResult scanResult = new ClassGraph() .whitelistPackages(config.getHandlerPackage()) .enableAllInfo() .scan()) { handlers = scanResult .getClassesWithAnnotation(ServiceHandler.class.getName()) .getNames(); } System.out.println("RpcStartupHookProvider: handlers size " + handlers.size()); for(String className: handlers) { try { Class handler = Class.forName(className); ServiceHandler a = (ServiceHandler)handler.getAnnotation(ServiceHandler.class); serviceMap.put(a.id(), (Handler)handler.getConstructor().newInstance()); System.out.println("RpcStartupHookProvider add id " + a.id() + " map to " + className); if(config.isRegisterService()) Server.serviceIds.add(a.id().replace('/', '.')); } catch (Exception e) { e.printStackTrace(); } } pathResourceProviders = SingletonServiceFactory.getBeans(PathResourceProvider.class); predicatedHandlersProviders = SingletonServiceFactory.getBeans(PredicatedHandlersProvider.class); } @Override void onStartup(); }### Answer:
@Test public void testStartup() { RpcStartupHookProvider provider = new RpcStartupHookProvider(); provider.onStartup(); Map<String, Handler> servicesMap = provider.serviceMap; Assert.assertTrue(servicesMap.size() > 0); System.out.println("serviceMap size = " + servicesMap.size()); } |
### Question:
RpcRouterConfig { public boolean isRegisterService() { return registerService; } RpcRouterConfig(); String getDescription(); void setDescription(String description); String getHandlerPackage(); void setHandlerPackage(String handlerPackage); String getJsonPath(); void setJsonPath(String jsonPath); String getFormPath(); void setFormPath(String formPath); String getColferPath(); void setColferPath(String colferPath); String getResourcesBasePath(); void setResourcesBasePath(String resourcesBasePath); boolean isRegisterService(); void setRegisterService(boolean registerService); }### Answer:
@Test public void testRegisterServiceTrue() { String configName = "rpc-router-true"; RpcRouterConfig config = (RpcRouterConfig) Config.getInstance().getJsonObjectConfig(configName, RpcRouterConfig.class); Assert.assertTrue(config.isRegisterService()); }
@Test public void testRegisterServiceFalse() { String configName = "rpc-router-false-package"; RpcRouterConfig config = (RpcRouterConfig) Config.getInstance().getJsonObjectConfig(configName, RpcRouterConfig.class); Assert.assertFalse(config.isRegisterService()); }
@Test public void testRegisterServiceEmpty() { String configName = "rpc-router-empty"; RpcRouterConfig config = (RpcRouterConfig) Config.getInstance().getJsonObjectConfig(configName, RpcRouterConfig.class); Assert.assertFalse(config.isRegisterService()); } |
### Question:
RpcRouterConfig { public String getHandlerPackage() { return handlerPackage; } RpcRouterConfig(); String getDescription(); void setDescription(String description); String getHandlerPackage(); void setHandlerPackage(String handlerPackage); String getJsonPath(); void setJsonPath(String jsonPath); String getFormPath(); void setFormPath(String formPath); String getColferPath(); void setColferPath(String colferPath); String getResourcesBasePath(); void setResourcesBasePath(String resourcesBasePath); boolean isRegisterService(); void setRegisterService(boolean registerService); }### Answer:
@Test public void testHandlerPackageEmpty() { String configName = "rpc-router-empty"; RpcRouterConfig config = (RpcRouterConfig) Config.getInstance().getJsonObjectConfig(configName, RpcRouterConfig.class); List<String> handlers; try (ScanResult scanResult = new ClassGraph() .whitelistPackages(config.getHandlerPackage()) .enableAllInfo() .scan()) { handlers = scanResult .getClassesWithAnnotation(ServiceHandler.class.getName()) .getNames(); } Assert.assertTrue(handlers.size() > 0); }
@Test public void testHandlerPackageSingle() { String configName = "rpc-router-false-package"; RpcRouterConfig config = (RpcRouterConfig) Config.getInstance().getJsonObjectConfig(configName, RpcRouterConfig.class); List<String> handlers; try (ScanResult scanResult = new ClassGraph() .whitelistPackages(config.getHandlerPackage()) .enableAllInfo() .scan()) { handlers = scanResult .getClassesWithAnnotation(ServiceHandler.class.getName()) .getNames(); } Assert.assertTrue(handlers.size() > 0); } |
### Question:
StringMethods { public String checkExtension(final String path) { if (path.equals("") || path.length() < EXTENSION.length() || !path.substring(path.length() - EXTENSION.length(), path.length()).equals(EXTENSION)) { return path + EXTENSION; } return path; } private StringMethods(); static StringMethods getInstance(); String fixPath(final String path); String checkExtension(final String path); String getNameDB(final String path); static boolean containsIgnoreCase(String str, String searchStr); static final String DEFAULT_FOLDER; }### Answer:
@Test public void When_CheckExtensionIsCalled_Expect_CorrectStringReturned() { assertThat(stringMethods.checkExtension(TEST_PATH), is("/test_path/file_name.ncf")); assertThat(stringMethods.checkExtension(".ncf"), is(".ncf")); } |
### Question:
StringMethods { public String getNameDB(final String path) { if (path.length() < EXTENSION.length() || !path.substring(path.length() - EXTENSION.length(), path.length()).equals(EXTENSION)) { return path.substring(path.lastIndexOf('/') + 1, path.length()); } return path.substring(path.lastIndexOf('/') + 1, path.length() - EXTENSION.length()); } private StringMethods(); static StringMethods getInstance(); String fixPath(final String path); String checkExtension(final String path); String getNameDB(final String path); static boolean containsIgnoreCase(String str, String searchStr); static final String DEFAULT_FOLDER; }### Answer:
@Test public void When_GetNameDBIsCalled_Expect_CorrectStringReturned() { assertThat(stringMethods.getNameDB(TEST_PATH), is("file_name")); } |
### Question:
StringMethods { public static boolean containsIgnoreCase(String str, String searchStr) { if (str != null && searchStr != null) { int len = searchStr.length(); int max = str.length() - len; for (int i = 0; i <= max; ++i) { if (str.regionMatches(true, i, searchStr, 0, len)) { return true; } } return false; } else { return false; } } private StringMethods(); static StringMethods getInstance(); String fixPath(final String path); String checkExtension(final String path); String getNameDB(final String path); static boolean containsIgnoreCase(String str, String searchStr); static final String DEFAULT_FOLDER; }### Answer:
@Test public void When_ContainsIgnoreCaseIsCalled_Expect_CorrectResult() { assertThat(containsIgnoreCase("STRING1", "StRiNg1"), is(true)); assertThat(containsIgnoreCase("STRING1", "StRiNg12"), is(false)); } |
### Question:
Playlist { Playlist(final List<Track> tracks, final int version) { this.tracks = tracks; this.version = version; } Playlist(final List<Track> tracks, final int version); List<Track> getTracks(); int getVersion(); @Override String toString(); }### Answer:
@Test public void playlist() { List<Playlist.Track> tracks = new ArrayList<>(); tracks.add(new Playlist.Track()); Playlist playlist = new Playlist(tracks, TEST_VERSION); assertEquals(TEST_VERSION, playlist.getVersion()); assertEquals(tracks, playlist.getTracks()); assertEquals(1, playlist.getTracks().size()); } |
### Question:
SqlUpdGenerator implements Generator { public String getSql() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, ParseException { if (sql == null) { generate(); } return sql; } SqlUpdGenerator(); SqlUpdGenerator(Object pojo, boolean usePhysicalPk); String getSql(); Object[] getArgs(); }### Answer:
@Test public void testGetSql() throws IllegalArgumentException, SecurityException, IllegalAccessException, NoSuchFieldException, ParseException { UserPO po = new UserPO(); po.setId(1L); SqlUpdGenerator generator = new SqlUpdGenerator(po, true); System.out.println(generator.getSql()); Object[] args = generator.getArgs(); for (Object arg : args) { System.out.print(arg + ","); } } |
### Question:
ParamTransformGenerator implements Generator { public void generate() throws DataAccessException { if (oraSql == null || "".equalsIgnoreCase(oraSql.trim())) { throw new DataAccessException("SQL is null"); } List<Object> arglist = new ArrayList<Object>(); Pattern p = Pattern.compile(PATTERN); Matcher m = p.matcher(oraSql); while (m.find()) { String key = m.group(); if (!params.containsKey(key.substring(1))) { throw new DataAccessException("Params not contains key~" + key + ";"); } arglist.add(params.get(key.substring(1))); } sql = oraSql.replaceAll(PATTERN, "?"); args = arglist.toArray(); } ParamTransformGenerator(String sql, Map<String, Object> params); void generate(); String getSql(); Object[] getArgs(); }### Answer:
@Test public void testGenerate() { String sql = " select * from abc where a=:test1 and b like :test2 an p = :test1"; Map<String, Object> params = new HashMap<String, Object>(); params.put("test1", 1); params.put("test2", "%t"); ParamTransformGenerator generator = new ParamTransformGenerator(sql, params); generator.generate(); Assert.assertTrue(" select * from abc where a=? and b like ? an p = ?".equals(generator.getSql())); Assert.assertTrue(generator.getArgs().length == 3); } |
### Question:
SqlSelHashGenerator extends SqlSelGenerator implements Generator { public String[] getSqls() throws IllegalAccessException { if (sqls == null) { generateParam(); } return sqls.toArray(new String[0]); } SqlSelHashGenerator(); SqlSelHashGenerator(Class<?> pojoClazz, Map<String, Object[]> args); List<Object[]> getArgsObjs(); String[] getSqls(); }### Answer:
@Test public void testGetSqls() throws IllegalAccessException { Map<String, Object[]> args = new HashMap<String, Object[]>(); args.put("id", new Object[]{1,101,2,102,3}); args.put("cnt", new Object[]{"123"}); SqlSelHashGenerator sqlGen = new SqlSelHashGenerator(DemoHashTable.class, args); String[] sqls = sqlGen.getSqls(); List<Object[]> rArgs = sqlGen.getArgsObjs(); for (int i = 0; i < sqls.length; i++) { System.out.println(sqls[i]); System.out.println(rArgs.get(i).length); } } |
### Question:
SqlSelGenerator implements Generator { public String getSql() throws IllegalAccessException { if (sql == null) { generateParam(); } return sql; } SqlSelGenerator(); SqlSelGenerator(Class<?> pojoClazz, Map<String, Object[]> args); Object[] getArgs(); String getSql(); Class<?> getPojoClazz(); void setPojoClazz(Class<?> pojoClazz); }### Answer:
@Test public void testGetSql() throws IllegalAccessException { Map<String, Object[]> args = new HashMap<String, Object[]>(); args.put("id", new Object[]{1,2,3}); SqlSelGenerator sqlGen = new SqlSelGenerator(DemoTablePO.class, args); System.out.println(sqlGen.getSql()); System.out.println(sqlGen.getArgs().length); } |
### Question:
RedisWeakCachedCommonDao extends DefaultCommonDao { @Override public int deleteByPhysical(Object... pojos) throws DataAccessException { int r = super.deleteByPhysical(pojos); deleteCache(pojos); return r; } RedisWeakCachedCommonDao(); void setJedisPool(JedisPool jedisPool); void setCacheSeconds(int cacheSeconds); @Override int updateByLogic(Object... pojos); @Override int updateByPhysical(Object... pojos); @Override int deleteByLogic(Object... pojos); @Override int deleteByPhysical(Object... pojos); @SuppressWarnings("unchecked") @Override T queryForPojoOne(Class<T> pojoType, Map<String, Object> args); @Override List<T> queryForPojoList(Class<T> pojoType, String col, Object... args); @Override PaginationSupport<T> queryForPaginatedPojoList(
Class<T> pojoType, Map<String, Object> args,
RowSelection rowSelection); }### Answer:
@Test public void testDeleteByPhysical() { UserPO user = new UserPO(); user.setId(123L); dao.deleteByPhysical(user); } |
### Question:
GenerationCodeJDBC implements IGenerationCode { @Override public void generate(String pack, String outputFolder, boolean useDefault) { try { List<Table> tables = gainTables(); buildSource(pack, outputFolder, tables, useDefault); } catch (Exception e) { logger.error("build source error!", e); } } GenerationCodeJDBC(); @Override void generate(String pack, String outputFolder, boolean useDefault); @Override void generatePrefix(String prefix, String pack, String outputFolder, boolean useDefault); @Override void generateTable(String tableName, String pack, String outputFolder, boolean useDefault); void setDataSource(DataSource dataSource); void setXADataSource(XADataSource dataSource); void setConnection(Connection connection); }### Answer:
@Test public void testGenerate() { boolean useDefault = false; generationCodeJDBC.generate("cn.org.zeronote.modules.plugin.admin.po", "/Test/services", useDefault); }
@Test public void testGenerateUseDefault() { boolean useDefault = true; generationCodeJDBC.generate("cn.org.zeronote.modules.plugin.admin.po", "/Test/services", useDefault); } |
### Question:
GenerationCodeJDBC implements IGenerationCode { @Override public void generatePrefix(String prefix, String pack, String outputFolder, boolean useDefault) { try { List<Table> tables = gainTables(); List<Table> tabs = new ArrayList<Table>(); for (Table table : tables) { if (table.getTableName().startsWith(prefix)) { tabs.add(table); logger.info("Generat table:{}", table.getTableName()); } } if (!tabs.isEmpty()) { buildSource(pack, outputFolder, tabs, useDefault); } else { logger.warn("No table have be Generate!"); } } catch (Exception e) { logger.error("build source error!", e); } } GenerationCodeJDBC(); @Override void generate(String pack, String outputFolder, boolean useDefault); @Override void generatePrefix(String prefix, String pack, String outputFolder, boolean useDefault); @Override void generateTable(String tableName, String pack, String outputFolder, boolean useDefault); void setDataSource(DataSource dataSource); void setXADataSource(XADataSource dataSource); void setConnection(Connection connection); }### Answer:
@Test public void testGeneratePrefix() { boolean useDefault = false; generationCodeJDBC.generatePrefix("user_", "cn.org.zeronote.modules.plugin.admin.po", "/Test/services", useDefault); }
@Test public void testGeneratePrefixUseDefault() { boolean useDefault = true; generationCodeJDBC.generatePrefix("user_", "cn.org.zeronote.modules.plugin.admin.po", "/Test/services", useDefault); } |
### Question:
GenerationCodeJDBC implements IGenerationCode { @Override public void generateTable(String tableName, String pack, String outputFolder, boolean useDefault) { try { List<Table> tables = gainTables(); List<Table> tabs = new ArrayList<Table>(); for (Table table : tables) { if (table.getTableName().equals(tableName)) { tabs.add(table); logger.info("Generat table:{}", tableName); break; } } if (!tabs.isEmpty()) { buildSource(pack, outputFolder, tabs, useDefault); } else { logger.warn("No table have be Generate!"); } } catch (Exception e) { logger.error("build source error!", e); } } GenerationCodeJDBC(); @Override void generate(String pack, String outputFolder, boolean useDefault); @Override void generatePrefix(String prefix, String pack, String outputFolder, boolean useDefault); @Override void generateTable(String tableName, String pack, String outputFolder, boolean useDefault); void setDataSource(DataSource dataSource); void setXADataSource(XADataSource dataSource); void setConnection(Connection connection); }### Answer:
@Test public void testGenerateTable() { boolean useDefault = false; generationCodeJDBC.generateTable("user_notify", "cn.org.zeronote.modules.plugin.admin.po", "/Test/services", useDefault); }
@Test public void testGenerateTableUseDefault() { boolean useDefault = true; generationCodeJDBC.generateTable("user_notify", "cn.org.zeronote.modules.plugin.admin.po", "/Test/services", useDefault); } |
### Question:
KiqrCodec implements MessageCodec<T, T> { @Override public T transform(T object) { return object; } KiqrCodec(Class<T> clazz); @Override void encodeToWire(Buffer buffer, T object); @Override T decodeFromWire(int pos, Buffer buffer); @Override T transform(T object); @Override String name(); @Override byte systemCodecID(); }### Answer:
@Test public void passThrough(){ KeyBasedQuery result = uut.transform(new KeyBasedQuery("store", "key serde", "key".getBytes(), "value serde")); assertThat(result.getStoreName(), is(equalTo("store"))); assertThat(result.getKeySerde(), is(equalTo("key serde"))); assertThat(new String(result.getKey()), is(equalTo("key"))); assertThat(result.getValueSerde(), is(equalTo("value serde"))); } |
### Question:
KiqrCodec implements MessageCodec<T, T> { @Override public byte systemCodecID() { return -1; } KiqrCodec(Class<T> clazz); @Override void encodeToWire(Buffer buffer, T object); @Override T decodeFromWire(int pos, Buffer buffer); @Override T transform(T object); @Override String name(); @Override byte systemCodecID(); }### Answer:
@Test public void id(){ byte b = uut.systemCodecID(); assertThat(b, is(equalTo((byte) -1))); } |
### Question:
RuntimeVerticle extends AbstractVerticle { protected KafkaStreams createAndStartStream(){ streams = new KafkaStreams(builder, props); streams.setStateListener(((newState, oldState) -> { vertx.eventBus().publish(Config.CLUSTER_STATE_BROADCAST_ADDRESS, newState.toString()); LOG.info("State change in KafkaStreams recorded: oldstate=" + oldState + ", newstate=" + newState); if(listener != null) listener.onChange(newState, oldState); })); streams.start(); return streams; } protected RuntimeVerticle(KStreamBuilder builder, Properties props, KafkaStreams.StateListener listener); @Override void start(Future<Void> startFuture); @Override void stop(Future<Void> stopFuture); }### Answer:
@Test public void successfulStart(TestContext context){ KafkaStreams streamsMock = mock(KafkaStreams.class); KStreamBuilder builderMock = mock(KStreamBuilder.class); Properties props = new Properties(); RuntimeVerticle verticleSpy = spy(new RuntimeVerticle(builderMock, props, null)); doReturn(streamsMock).when(verticleSpy).createAndStartStream(); rule.vertx().deployVerticle(verticleSpy, context.asyncAssertSuccess(handler -> { context.assertTrue(rule.vertx().deploymentIDs().size() > 0); })); }
@Test public void failingStart(TestContext context){ KafkaStreams streamsMock = mock(KafkaStreams.class); KStreamBuilder builderMock = mock(KStreamBuilder.class); Properties props = new Properties(); RuntimeVerticle verticleSpy = spy(new RuntimeVerticle(builderMock, props, null)); doThrow(RuntimeException.class).when(verticleSpy).createAndStartStream(); rule.vertx().deployVerticle(verticleSpy, context.asyncAssertFailure()); } |
### Question:
SpecificBlockingRestKiqrClientImpl implements SpecificBlockingKiqrClient<K,V> { @Override public Optional<V> getScalarKeyValue( K key) { return genericClient.getScalarKeyValue(store, keyClass, key, valueClass, keySerde, valueSerde); } SpecificBlockingRestKiqrClientImpl(String host, int port, String store, Class<K> keyClass, Class<V> valueClass, Serde<K> keySerde, Serde<V> valueSerde); SpecificBlockingRestKiqrClientImpl(GenericBlockingKiqrClient genericClient, String store, Class<K> keyClass, Class<V> valueClass, Serde<K> keySerde, Serde<V> valueSerde); @Override Optional<V> getScalarKeyValue( K key); @Override Map<K, V> getAllKeyValues(); @Override Map<K, V> getRangeKeyValues( K from, K to); @Override Map<Long, V> getWindow( K key, long from, long to); @Override Optional<Long> count(String store); @Override Map<Window, V> getSession(K key); }### Answer:
@Test public void scalar(){ when(clientMock.getScalarKeyValue(any(), any(), any(), any(), any(), any())).thenReturn(Optional.of(6L)); Optional<Long> result = unitUnderTest.getScalarKeyValue("key1"); assertTrue(result.isPresent()); assertThat(result.get(), is(equalTo(6L))); } |
### Question:
SpecificBlockingRestKiqrClientImpl implements SpecificBlockingKiqrClient<K,V> { @Override public Map<K, V> getAllKeyValues() { return genericClient.getAllKeyValues(store, keyClass, valueClass, keySerde, valueSerde); } SpecificBlockingRestKiqrClientImpl(String host, int port, String store, Class<K> keyClass, Class<V> valueClass, Serde<K> keySerde, Serde<V> valueSerde); SpecificBlockingRestKiqrClientImpl(GenericBlockingKiqrClient genericClient, String store, Class<K> keyClass, Class<V> valueClass, Serde<K> keySerde, Serde<V> valueSerde); @Override Optional<V> getScalarKeyValue( K key); @Override Map<K, V> getAllKeyValues(); @Override Map<K, V> getRangeKeyValues( K from, K to); @Override Map<Long, V> getWindow( K key, long from, long to); @Override Optional<Long> count(String store); @Override Map<Window, V> getSession(K key); }### Answer:
@Test public void all(){ Map<String, Long> results = new HashMap<>(); results.put("key1", 6L); when(clientMock.getAllKeyValues(any(), eq(String.class), eq(Long.class), any(), any())).thenReturn(results); Map<String, Long> result = unitUnderTest.getAllKeyValues(); assertThat(result.size(), is(equalTo(1))); assertThat(result, hasEntry("key1", 6L)); } |
### Question:
SpecificBlockingRestKiqrClientImpl implements SpecificBlockingKiqrClient<K,V> { @Override public Map<K, V> getRangeKeyValues( K from, K to) { return genericClient.getRangeKeyValues(store, keyClass, valueClass, keySerde, valueSerde, from, to); } SpecificBlockingRestKiqrClientImpl(String host, int port, String store, Class<K> keyClass, Class<V> valueClass, Serde<K> keySerde, Serde<V> valueSerde); SpecificBlockingRestKiqrClientImpl(GenericBlockingKiqrClient genericClient, String store, Class<K> keyClass, Class<V> valueClass, Serde<K> keySerde, Serde<V> valueSerde); @Override Optional<V> getScalarKeyValue( K key); @Override Map<K, V> getAllKeyValues(); @Override Map<K, V> getRangeKeyValues( K from, K to); @Override Map<Long, V> getWindow( K key, long from, long to); @Override Optional<Long> count(String store); @Override Map<Window, V> getSession(K key); }### Answer:
@Test public void range(){ Map<String, Long> results = new HashMap<>(); results.put("key1", 6L); when(clientMock.getRangeKeyValues(any(), eq(String.class), eq(Long.class), any(), any(), any(), any())).thenReturn(results); Map<String, Long> result = unitUnderTest.getRangeKeyValues("key1", "key2"); assertThat(result.size(), is(equalTo(1))); assertThat(result, hasEntry("key1", 6L)); } |
### Question:
SpecificBlockingRestKiqrClientImpl implements SpecificBlockingKiqrClient<K,V> { @Override public Map<Long, V> getWindow( K key, long from, long to) { return genericClient.getWindow(store, keyClass, key, valueClass, keySerde, valueSerde, from, to); } SpecificBlockingRestKiqrClientImpl(String host, int port, String store, Class<K> keyClass, Class<V> valueClass, Serde<K> keySerde, Serde<V> valueSerde); SpecificBlockingRestKiqrClientImpl(GenericBlockingKiqrClient genericClient, String store, Class<K> keyClass, Class<V> valueClass, Serde<K> keySerde, Serde<V> valueSerde); @Override Optional<V> getScalarKeyValue( K key); @Override Map<K, V> getAllKeyValues(); @Override Map<K, V> getRangeKeyValues( K from, K to); @Override Map<Long, V> getWindow( K key, long from, long to); @Override Optional<Long> count(String store); @Override Map<Window, V> getSession(K key); }### Answer:
@Test public void window(){ Map<Long, Long> results = new HashMap<>(); results.put(1L, 6L); when(clientMock.getWindow(anyString(), eq(String.class), eq("key1"), eq(Long.class), anyObject(), anyObject(), eq(0L), eq(1L))).thenReturn(results); Map<Long, Long> result = unitUnderTest.getWindow("key1", 0L, 1L); assertThat(result.size(), is(equalTo(1))); assertThat(result, hasEntry(1L, 6L)); } |
### Question:
StringJavaScriptVariable extends JavaScriptVariable { @Override public String getVariableValue() { return quote(super.getVariableValue()); } StringJavaScriptVariable(final String theVariableName,
final String theVariableValue); @Override String getVariableValue(); }### Answer:
@Test public void testGetVariableValue() throws Exception { final String variableName = "theVariableName"; final String variableValue = "theVariableValue"; final String expectedValue = "\"" + variableValue + "\""; final StringJavaScriptVariable variable = new StringJavaScriptVariable(variableName, variableValue); assertEquals(variableName, variable.getVariableName()); assertEquals(expectedValue, variable.getVariableValue()); } |
### Question:
JvmControlServiceImpl implements JvmControlService { @Override public CommandOutput executeCreateDirectoryCommand(final Jvm jvm, final String dirAbsolutePath) throws CommandFailureException { RemoteCommandReturnInfo remoteCommandReturnInfo = shellCommandFactory.executeRemoteCommand(jvm.getHostName(), Command.CREATE_DIR, dirAbsolutePath); return new CommandOutput(new ExecReturnCode(remoteCommandReturnInfo.retCode), remoteCommandReturnInfo.standardOuput, remoteCommandReturnInfo.errorOupout); } JvmControlServiceImpl(final JvmPersistenceService jvmPersistenceService,
final JvmStateService jvmStateService,
final HistoryFacadeService historyFacadeService); @Override CommandOutput controlJvm(final ControlJvmRequest controlJvmRequest, final User aUser); @Override CommandOutput controlJvmSynchronously(final ControlJvmRequest controlJvmRequest, final long timeout,
final User user); @Override CommandOutput secureCopyFile(final ControlJvmRequest secureCopyRequest, final String sourcePath,
final String destPath, String userId, boolean overwrite); @Override CommandOutput executeChangeFileModeCommand(final Jvm jvm, final String modifiedPermissions, final String targetAbsoluteDir, final String targetFile); @Override CommandOutput executeCreateDirectoryCommand(final Jvm jvm, final String dirAbsolutePath); @Override CommandOutput executeCheckFileExistsCommand(final Jvm jvm, final String filename); @Override CommandOutput executeBackUpCommand(final Jvm jvm, final String filename); void setJvmCommandFactory(JvmCommandFactory jvmCommandFactory); }### Answer:
@Test public void testCreateDirectory() throws CommandFailureException { Jvm mockJvm = mock(Jvm.class); when(mockJvm.getHostName()).thenReturn("test-host"); when(Config.mockShellCommandFactory.executeRemoteCommand(anyString(), eq(Command.CREATE_DIR), anyString())).thenReturn(mock(RemoteCommandReturnInfo.class)); jvmControlService.executeCreateDirectoryCommand(mockJvm, "./target"); verify(Config.mockShellCommandFactory).executeRemoteCommand("test-host", Command.CREATE_DIR, "./target"); } |
### Question:
JvmStateServiceImpl implements JvmStateService { @Override public RemoteCommandReturnInfo getServiceStatus(final Jvm jvm) { return jvmCommandFactory.executeCommand(jvm, JvmControlOperation.CHECK_SERVICE_STATUS); } @Autowired JvmStateServiceImpl(final JvmPersistenceService jvmPersistenceService,
@Qualifier("jvmInMemoryStateManagerService")
final InMemoryStateManagerService<Identifier<Jvm>, CurrentState<Jvm, JvmState>> inMemoryStateManagerService,
final JvmStateResolverWorker jvmStateResolverWorker,
final MessagingService messagingService,
final GroupStateNotificationService groupStateNotificationService,
@Value("${jvm.state.update.interval:60000}")
final long jvmStateUpdateInterval,
final JvmCommandFactory jvmCommandFactory,
final SshConfiguration sshConfig,
@Value("${jvm.state.key.lock.timeout.millis:600000}")
final long lockTimeout,
@Value("${jvm.state.key.lock.stripe.count:120}")
final int keyLockStripeCount); @Override @Scheduled(fixedDelayString = "${ping.jvm.period.millis}") void verifyAndUpdateJvmStates(); @Override void updateNotInMemOrStaleState(final Jvm jvm, final JvmState state, final String errMsg); @Override RemoteCommandReturnInfo getServiceStatus(final Jvm jvm); @Override void updateState(Jvm jvm, final JvmState state); @Override void updateState(final Jvm jvm, final JvmState state, final String errMsg); }### Answer:
@Test public void testGetServiceStatus() { final Jvm jvm = new Jvm(new Identifier<Jvm>(1L), "some-jvm", new HashSet<Group>()); jvmStateService.getServiceStatus(jvm); verify(mockJvmCommandFactory).executeCommand(eq(jvm), eq(JvmControlOperation.CHECK_SERVICE_STATUS)); } |
### Question:
GroupJvmControlServiceImpl implements GroupJvmControlService { @Transactional @Override public void controlGroup(final ControlGroupJvmRequest controlGroupJvmRequest, final User aUser) { controlGroupJvmRequest.validate(); Group group = groupService.getGroup(controlGroupJvmRequest.getGroupId()); final Set<Jvm> jvms = group.getJvms(); if (jvms != null) { controlJvms(controlGroupJvmRequest, aUser, jvms); } } GroupJvmControlServiceImpl(final GroupService theGroupService, final JvmControlService theJvmControlService); @Transactional @Override void controlGroup(final ControlGroupJvmRequest controlGroupJvmRequest, final User aUser); @Override void controlAllJvms(final ControlGroupJvmRequest controlGroupJvmRequest, final User user); boolean checkSameState(final JvmControlOperation jvmControlOperation, final JvmState jvmState); }### Answer:
@Test public void testControlGroupWithInvalidGroup() { ControlGroupJvmRequest controlGroupJvmRequest = new ControlGroupJvmRequest(groupId, JvmControlOperation.START); cut.controlGroup(controlGroupJvmRequest, testUser); } |
### Question:
GroupWebServerControlServiceImpl implements GroupWebServerControlService { @Transactional @Override public void controlGroup(final ControlGroupWebServerRequest controlGroupWebServerRequest, final User aUser) { controlGroupWebServerRequest.validate(); Group group = groupService.getGroupWithWebServers(controlGroupWebServerRequest.getGroupId()); final Set<WebServer> webServers = group.getWebServers(); if (webServers != null) { controlWebServers(controlGroupWebServerRequest, aUser, webServers); } } GroupWebServerControlServiceImpl(final GroupService theGroupService, WebServerControlService theWebServerControlService); @Transactional @Override void controlGroup(final ControlGroupWebServerRequest controlGroupWebServerRequest, final User aUser); @Override void controlAllWebSevers(final ControlGroupWebServerRequest controlGroupWebServerRequest, final User user); boolean checkSameState(final WebServerControlOperation webServerControlOperation, final String webServerStateLabel); }### Answer:
@Test(expected = BadRequestException.class) public void testControlGroupWithInvalidGroup() { ControlGroupWebServerRequest controlGroupWebServerRequest = new ControlGroupWebServerRequest(null, WebServerControlOperation.START); cut.controlGroup(controlGroupWebServerRequest, testUser); }
@Test public void testControlGroup() { when(mockWebServer.getStateLabel()).thenReturn(WebServerReachableState.WS_REACHABLE.toStateLabel()); cut.controlGroup(controlGroupWebServerRequest, testUser); } |
### Question:
GroupControlServiceImpl implements GroupControlService { @Transactional @Override public void controlGroup(ControlGroupRequest controlGroupRequest, User aUser) { LOGGER.info("begin controlGroup operation {} for groupId {}", controlGroupRequest.getControlOperation(), controlGroupRequest.getGroupId()); controlWebServers(controlGroupRequest, aUser); controlJvms(controlGroupRequest, aUser); } GroupControlServiceImpl(
final GroupWebServerControlService theGroupWebServerControlService,
final GroupJvmControlService theGroupJvmControlService); @Transactional @Override void controlGroup(ControlGroupRequest controlGroupRequest, User aUser); @Override void controlGroups(final ControlGroupRequest controlGroupRequest, final User user); }### Answer:
@Test public void testControlGroup() { ControlGroupRequest controlGroupRequest= new ControlGroupRequest(testGroupId, GroupControlOperation.START); cut.controlGroup(controlGroupRequest, systemUser); ControlGroupWebServerRequest wsCommand = new ControlGroupWebServerRequest(testGroupId, WebServerControlOperation.START); verify(mockGroupWebServerControlService).controlGroup(wsCommand, systemUser); ControlGroupJvmRequest jvmCommand = new ControlGroupJvmRequest(testGroupId, JvmControlOperation.START); verify(mockGroupJvmControlService).controlGroup(jvmCommand, systemUser); } |
### Question:
HistoryServiceImpl implements HistoryService { @Override @Transactional(propagation = Propagation.REQUIRES_NEW) public List<JpaHistory> createHistory(final String serverName, final List<Group> groups, final String event, final EventType eventType, final String user) { final List<JpaHistory> jpaHistoryList = new ArrayList<>(); if (groups != null) { for (Group group : groups) { jpaHistoryList.add(historyCrudService.createHistory(serverName, group, event, eventType, user)); } } return jpaHistoryList; } @Autowired HistoryServiceImpl(final HistoryCrudService historyCrudService); @Override @Transactional(propagation = Propagation.REQUIRES_NEW) // Write history independent of any transaction. List<JpaHistory> createHistory(final String serverName, final List<Group> groups, final String event,
final EventType eventType, final String user); @Override @Transactional(readOnly = true) List<JpaHistory> findHistory(final String groupName, final String serverName, final Integer numOfRec); }### Answer:
@Test public void testWrite() { final List<Group> groups = new ArrayList<>(); groups.add(new Group(Identifier.<Group>id(1L), "testGroup")); historyService.createHistory("any", groups, "Testing...", EventType.USER_ACTION_INFO, "user"); verify(mockHistoryCrudService).createHistory(eq("any"), any(Group.class), eq("Testing..."), eq(EventType.USER_ACTION_INFO), eq("user")); } |
### Question:
HistoryServiceImpl implements HistoryService { @Override @Transactional(readOnly = true) public List<JpaHistory> findHistory(final String groupName, final String serverName, final Integer numOfRec) { return historyCrudService.findHistory(groupName, serverName, numOfRec); } @Autowired HistoryServiceImpl(final HistoryCrudService historyCrudService); @Override @Transactional(propagation = Propagation.REQUIRES_NEW) // Write history independent of any transaction. List<JpaHistory> createHistory(final String serverName, final List<Group> groups, final String event,
final EventType eventType, final String user); @Override @Transactional(readOnly = true) List<JpaHistory> findHistory(final String groupName, final String serverName, final Integer numOfRec); }### Answer:
@Test public void testRead() { historyService.findHistory("any", "any", null); verify(mockHistoryCrudService).findHistory(eq("any"), eq("any"), anyInt()); } |
### Question:
HistoryFacadeServiceImpl implements HistoryFacadeService { @Override public void write(final String serverName, final Collection<Group> groups, final String historyMessage, final EventType eventType, final String user) { final List<JpaHistory> jpaHistoryList = historyService.createHistory(serverName, new ArrayList<>(groups), historyMessage, eventType, user); for (JpaHistory jpaHistory : jpaHistoryList) { messagingService.send(new Message<>(Message.Type.HISTORY, jpaHistory)); } } HistoryFacadeServiceImpl(final HistoryService historyService, final MessagingService messagingService); @Override void write(final String serverName, final Collection<Group> groups, final String historyMessage, final EventType eventType,
final String user); @Override @SuppressWarnings("all") void write(final String serverName, final Group group, final String event, final EventType eventType,
final String user); }### Answer:
@Test @SuppressWarnings("all") public void testWrite() throws Exception { historyFacadeService.write("someServer", Arrays.asList(someGroup), "some event", EventType.SYSTEM_INFO, "someUser"); }
@Test public void testWrite2() throws Exception { historyFacadeService.write("someServer", someGroup, "some event", EventType.SYSTEM_INFO, "someUser"); } |
### Question:
JvmWinSvcPwdStoreServiceImpl implements ObjectStoreService<String> { @Override public void add(final String password) { copyOnWriteArraySet.add(password); } JvmWinSvcPwdStoreServiceImpl(final JvmPersistenceService jvmPersistenceService); @Override void add(final String password); @Override void remove(final String password); @Override void clear(); @Override Iterable<String> getIterable(); }### Answer:
@Test public void testAdd() throws Exception { jvmWinSvcPwdStoreService.add("@@@!!!@@@@!!=="); assertEquals(2, CollectionUtils.size(jvmWinSvcPwdStoreService.getIterable())); } |
### Question:
JvmWinSvcPwdStoreServiceImpl implements ObjectStoreService<String> { @Override public void remove(final String password) { copyOnWriteArraySet.remove(password); } JvmWinSvcPwdStoreServiceImpl(final JvmPersistenceService jvmPersistenceService); @Override void add(final String password); @Override void remove(final String password); @Override void clear(); @Override Iterable<String> getIterable(); }### Answer:
@Test public void testRemove() throws Exception { jvmWinSvcPwdStoreService.remove("$#$%#$%$#^&&=="); assertEquals(0, CollectionUtils.size(jvmWinSvcPwdStoreService.getIterable())); } |
### Question:
JvmWinSvcPwdStoreServiceImpl implements ObjectStoreService<String> { @Override public void clear() { copyOnWriteArraySet.clear(); } JvmWinSvcPwdStoreServiceImpl(final JvmPersistenceService jvmPersistenceService); @Override void add(final String password); @Override void remove(final String password); @Override void clear(); @Override Iterable<String> getIterable(); }### Answer:
@Test public void testClear() throws Exception { jvmWinSvcPwdStoreService.clear(); assertEquals(0, CollectionUtils.size(jvmWinSvcPwdStoreService.getIterable())); } |
### Question:
BalancerManagerXmlParser { String getUrlPath(final String host, final int httpsPort, final String balancerName, final String nonce) { return "https: } BalancerManagerXmlParser(JvmService jvmService); Map<String, String> getWorkers(final Manager manager, final String balancerName); Map<String, String> getJvmWorkerByName(final Manager manager, final String balancerName, final String jvmName); }### Answer:
@Test public void testBalancerManagerGetUrlPath() { final String host = "test-hostname"; final String balancerName = "test-balancer-name"; final String nonce = "test-nonce"; final int httpsPort = 444; String result = balancerManagerXmlParser.getUrlPath(host, httpsPort, balancerName, nonce); assertEquals(MessageFormat.format("https: } |
### Question:
ContextPathSource extends AbstractSingleVariableSource implements JavaScriptVariableSource { @Override protected JavaScriptVariable createSingleVariable() { return new StringJavaScriptVariable("contextPath", servletContext.getContextPath()); } ContextPathSource(final ServletContext theServletContext); }### Answer:
@Test public void testCreateSingleVariable() throws Exception { final String expectedContextPath = "myExpectedContextPathValue"; final StringJavaScriptVariable expectedVariable = new StringJavaScriptVariable("contextPath", expectedContextPath); when(context.getContextPath()).thenReturn(expectedContextPath); final JavaScriptVariable actualVariable = source.createSingleVariable(); assertEquals(expectedVariable, actualVariable); } |
### Question:
MediaServiceRestImpl implements MediaServiceRest { @Override public Response getMedia(final Long id, final String mediaName, final AuthenticatedUser aUser) { LOGGER.debug("getMedia with ID {} and name {} by user", id, mediaName, aUser.getUser().getId()); if (id == null && StringUtils.isEmpty(mediaName)) { return ResponseBuilder.ok(mediaService.findAll()); } else if (id != null) { return ResponseBuilder.ok(mediaService.find(id)); } return ResponseBuilder.ok(mediaService.find(mediaName)); } @Override Response createMedia(final List<Attachment> attachments); @Override Response updateMedia(final JpaMedia media, final AuthenticatedUser aUser); @Override Response removeMedia(final String name, String type, final AuthenticatedUser aUser); @Override Response getMedia(final Long id, final String mediaName, final AuthenticatedUser aUser); @Override Response getMediaTypes(); }### Answer:
@Test public void testGetAllMedia() { when(Config.mediaService.findAll()).thenReturn(mediaList); final Response response = mediaServiceRest.getMedia(null, "", Config.authenticatedUser); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); }
@Test public void testGetMediaById() { when(Config.mediaService.find(anyLong())).thenReturn(media); final Response response = mediaServiceRest.getMedia(1L, "jdk 1.8", Config.authenticatedUser); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); }
@Test public void testGetMediaByName() { when(Config.mediaService.find(anyString())).thenReturn(media); final Response response = mediaServiceRest.getMedia(null, "jdk 1.8", Config.authenticatedUser); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); } |
### Question:
MediaServiceRestImpl implements MediaServiceRest { @Override public Response removeMedia(final String name, String type, final AuthenticatedUser aUser) { MediaType mediaType = null; if (MediaType.JDK.getDisplayName().equals(type)) { mediaType = MediaType.JDK; } if (MediaType.APACHE.getDisplayName().equals(type)) { mediaType = MediaType.APACHE; } if (MediaType.TOMCAT.getDisplayName().equals(type)) { mediaType = MediaType.TOMCAT; } LOGGER.info("removeMedia {} by user {}", name, aUser.getUser().getId()); mediaService.remove(name, mediaType); return Response.status(Response.Status.NO_CONTENT).build(); } @Override Response createMedia(final List<Attachment> attachments); @Override Response updateMedia(final JpaMedia media, final AuthenticatedUser aUser); @Override Response removeMedia(final String name, String type, final AuthenticatedUser aUser); @Override Response getMedia(final Long id, final String mediaName, final AuthenticatedUser aUser); @Override Response getMediaTypes(); }### Answer:
@Test public void testRemoveMedia() { Response response = mediaServiceRest.removeMedia("jdk 1.8", "JDK", Config.authenticatedUser); assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); } |
### Question:
MediaServiceRestImpl implements MediaServiceRest { @Override public Response getMediaTypes() { LOGGER.debug("getMediaTypes"); return ResponseBuilder.ok(mediaService.getMediaTypes()); } @Override Response createMedia(final List<Attachment> attachments); @Override Response updateMedia(final JpaMedia media, final AuthenticatedUser aUser); @Override Response removeMedia(final String name, String type, final AuthenticatedUser aUser); @Override Response getMedia(final Long id, final String mediaName, final AuthenticatedUser aUser); @Override Response getMediaTypes(); }### Answer:
@Test public void testGetMediaTypes() { when(Config.mediaService.getMediaTypes()).thenReturn(MediaType.values()); Response response = mediaServiceRest.getMediaTypes(); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); } |
### Question:
MediaServiceRestImpl implements MediaServiceRest { @Override public Response updateMedia(final JpaMedia media, final AuthenticatedUser aUser) { LOGGER.info("updateMedia {} by user {}", media, aUser.getUser().getId()); return ResponseBuilder.ok(mediaService.update(media)); } @Override Response createMedia(final List<Attachment> attachments); @Override Response updateMedia(final JpaMedia media, final AuthenticatedUser aUser); @Override Response removeMedia(final String name, String type, final AuthenticatedUser aUser); @Override Response getMedia(final Long id, final String mediaName, final AuthenticatedUser aUser); @Override Response getMediaTypes(); }### Answer:
@Test public void testUpdateMedia() { when(Config.mediaService.update(any(JpaMedia.class))).thenReturn(media); Response response = mediaServiceRest.updateMedia(media, Config.authenticatedUser); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); } |
### Question:
ApplicationServiceRestImpl implements ApplicationServiceRest { @Override public Response getApplicationByName(final String name) { return ResponseBuilder.ok(service.getApplication(name)); } ApplicationServiceRestImpl(ApplicationService applicationService,
ResourceService resourceService,
final GroupService groupService); @Override Response getApplication(Identifier<Application> anAppId); @Override Response getApplicationByName(final String name); @Override Response getApplications(Identifier<Group> aGroupId); @Override Response findApplicationsByJvmId(Identifier<Jvm> aJvmId); @Override Response createApplication(final JsonCreateApplication anAppToCreate, final AuthenticatedUser aUser); @Override Response updateApplication(final JsonUpdateApplication anAppToUpdate, final AuthenticatedUser aUser); @Override Response removeApplication(final Identifier<Application> anAppToRemove, final AuthenticatedUser aUser); @Override Response deployWebArchive(final Identifier<Application> anAppToGet, final AuthenticatedUser aUser); @Override Response deployWebArchive(final Identifier<Application> anAppToGet, String hostName); @Override Response getResourceNames(final String appName, final String jvmName); @Override Response updateResourceTemplate(final String appName,
final String resourceTemplateName,
final String jvmName,
final String groupName,
final String content); @Override Response deployConf(final String appName, final String groupName, final String jvmName,
final String resourceTemplateName, final AuthenticatedUser authUser); @Override Response previewResourceTemplate(final String appName, final String groupName, final String jvmName,
final String fileName,
final String template); @Override Response deployConf(final String appName, final AuthenticatedUser aUser, final String hostName); @Override Response checkIfFileExists(final String filePath, final AuthenticatedUser aUser, final String hostName); }### Answer:
@Test public void testGetApplicationByName() { when(Config.service.getApplication(anyString())).thenReturn(Config.mockApplication); Response response = applicationServiceRestInterface.getApplicationByName("application"); assertEquals(response.getStatus(), 200); } |
### Question:
ParamValidator { private ParamValidator() { this.valid = true; } private ParamValidator(); static ParamValidator getNewInstance(); boolean isValid(); ParamValidator isEmpty(final String val); ParamValidator isNotEmpty(final String val); }### Answer:
@Test public void testParamValidator() { assertTrue(ParamValidator.getNewInstance().isEmpty("").isEmpty("").isNotEmpty("hey").isValid()); assertFalse(ParamValidator.getNewInstance().isEmpty("").isEmpty("").isNotEmpty("").isValid()); assertTrue(ParamValidator.getNewInstance().isEmpty("").isEmpty(null).isNotEmpty("hello").isValid()); assertTrue(ParamValidator.getNewInstance().isEmpty("").isEmpty(null).isNotEmpty("hello").isNotEmpty("hoho") .isEmpty(null).isValid()); } |
### Question:
JsonUtilJvm { static Integer stringToInteger(final String val) { try { return Integer.valueOf(val); } catch (NumberFormatException nfe) { LOGGER.info("Unable to convert String to Integer", nfe); return null; } } private JsonUtilJvm(); }### Answer:
@Test public void testStringToInteger() { assertEquals(Integer.valueOf("5"), JsonUtilJvm.stringToInteger("5")); }
@Test public void testStringToIntegerNonNumeric() { assertEquals(null, JsonUtilJvm.stringToInteger("")); assertEquals(null, JsonUtilJvm.stringToInteger(" ")); assertEquals(null, JsonUtilJvm.stringToInteger("ASD$#@")); }
@Test public void testStringToIntegerOutOfScope() { assertEquals(null, JsonUtilJvm.stringToInteger("123456676989084241314253456457568687686745345")); }
@Test public void testStringToIntegerDecimalValues() { assertEquals(null, JsonUtilJvm.stringToInteger("3.55")); } |
### Question:
CompositeJavaScriptVariableSource implements JavaScriptVariableSource { @Override public Set<JavaScriptVariable> createVariables() { final Set<JavaScriptVariable> variables = new HashSet<>(); for (final JavaScriptVariableSource source : sources) { variables.addAll(source.createVariables()); } return variables; } CompositeJavaScriptVariableSource(final JavaScriptVariableSource... theSources); @Override Set<JavaScriptVariable> createVariables(); }### Answer:
@Test public void testCreateVariables() throws Exception { final JavaScriptVariableSource[] sources = mockSources(5); final CompositeJavaScriptVariableSource compositeSource = new CompositeJavaScriptVariableSource(sources); final Set<JavaScriptVariable> actualVariables = compositeSource.createVariables(); assertEquals(sources.length, actualVariables.size()); for (final JavaScriptVariable variable : actualVariables) { assertTrue(variable.getVariableName().startsWith("key")); assertTrue(variable.getVariableValue().startsWith("value")); } } |
### Question:
AdminServiceRestImpl implements AdminServiceRest { @Override public Response reload() { ApplicationProperties.reload(); Properties copyToReturn = ApplicationProperties.getProperties(); configurer.setProperties(copyToReturn); filesConfiguration.reload(); LogManager.resetConfiguration(); DOMConfigurator.configure("../data/conf/log4j.xml"); copyToReturn.put("logging-reload-state", "Property reload complete"); return ResponseBuilder.ok(new TreeMap<>(copyToReturn)); } AdminServiceRestImpl(FilesConfiguration theFilesConfiguration, ResourceService resourceService); @Override Response reload(); @Override Response view(); @Override Response encrypt(String cleartext); @Override Response manifest(ServletContext context); @Override Response isJwalaAuthorizationEnabled(); @Override Response getAuthorizationDetails(); static final String JSON_RESPONSE_TRUE; static final String JSON_RESPONSE_FALSE; }### Answer:
@Test public void testReload() { Response response = cut.reload(); assertNotNull(response.getEntity()); System.setProperty("log4j.configuration", "testlog4j.xml"); response = cut.reload(); assertNotNull(response.getEntity()); System.setProperty("log4j.configuration", "testlog4j.properties"); response = cut.reload(); assertNotNull(response.getEntity()); System.setProperty("log4j.configuration", "testlog4j_NO_SUCH_FILE.xml"); response = cut.reload(); assertNotNull(response.getEntity()); System.clearProperty("log4j.configuration"); } |
### Question:
AdminServiceRestImpl implements AdminServiceRest { @Override public Response encrypt(String cleartext) { if (cleartext == null || cleartext.trim().length() == 0) { return Response.status(Response.Status.NO_CONTENT).build(); } else { return ResponseBuilder.ok(resourceService.encryptUsingPlatformBean(cleartext)); } } AdminServiceRestImpl(FilesConfiguration theFilesConfiguration, ResourceService resourceService); @Override Response reload(); @Override Response view(); @Override Response encrypt(String cleartext); @Override Response manifest(ServletContext context); @Override Response isJwalaAuthorizationEnabled(); @Override Response getAuthorizationDetails(); static final String JSON_RESPONSE_TRUE; static final String JSON_RESPONSE_FALSE; }### Answer:
@Test public void testEncrypt() { Response response = cut.encrypt(""); assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); response = cut.encrypt("encrypt me"); assertNotNull(response.getEntity()); } |
### Question:
AdminServiceRestImpl implements AdminServiceRest { @Override public Response manifest(ServletContext context) { Attributes attributes = null; if (context != null) { try { InputStream manifestStream = context.getResourceAsStream("META-INF/MANIFEST.MF"); Manifest manifest = new Manifest(manifestStream); attributes = manifest.getMainAttributes(); } catch (IOException e) { LOGGER.debug("Error getting manifest for " + context.getServletContextName(), e); throw new InternalErrorException(FaultType.INVALID_PATH, "Failed to read MANIFEST.MF for " + context.getServletContextName()); } } return ResponseBuilder.ok(attributes); } AdminServiceRestImpl(FilesConfiguration theFilesConfiguration, ResourceService resourceService); @Override Response reload(); @Override Response view(); @Override Response encrypt(String cleartext); @Override Response manifest(ServletContext context); @Override Response isJwalaAuthorizationEnabled(); @Override Response getAuthorizationDetails(); static final String JSON_RESPONSE_TRUE; static final String JSON_RESPONSE_FALSE; }### Answer:
@Test public void testManifest() throws IOException { final ServletContext contextMock = mock(ServletContext.class); when(contextMock.getResourceAsStream(anyString())).thenReturn(new FileInputStream(new File("./src/test/resources/META-INF/MANIFEST.MF"))); Response response = cut.manifest(contextMock); assertNotNull(response.getEntity()); InputStream mockInputStream = mock(InputStream.class); when(mockInputStream.read(any(byte[].class), anyInt(), anyInt())).thenThrow(new IOException("Test bad manifest file")); when(contextMock.getResourceAsStream(anyString())).thenReturn(mockInputStream); boolean exceptionThrown = false; try { cut.manifest(contextMock); } catch (Exception e) { exceptionThrown = true; } assertTrue(exceptionThrown); } |
### Question:
AdminServiceRestImpl implements AdminServiceRest { @Override public Response view() { return ResponseBuilder.ok(new TreeMap<>(ApplicationProperties.getProperties())); } AdminServiceRestImpl(FilesConfiguration theFilesConfiguration, ResourceService resourceService); @Override Response reload(); @Override Response view(); @Override Response encrypt(String cleartext); @Override Response manifest(ServletContext context); @Override Response isJwalaAuthorizationEnabled(); @Override Response getAuthorizationDetails(); static final String JSON_RESPONSE_TRUE; static final String JSON_RESPONSE_FALSE; }### Answer:
@Test public void testView() { Response response = cut.view(); assertNotNull(response.getEntity()); } |
### Question:
AdminServiceRestImpl implements AdminServiceRest { @Override public Response isJwalaAuthorizationEnabled() { String auth = ApplicationProperties.get(JWALA_AUTHORIZATION, "true"); if("false".equals(auth)) return ResponseBuilder.ok(JSON_RESPONSE_FALSE); else return ResponseBuilder.ok(JSON_RESPONSE_TRUE); } AdminServiceRestImpl(FilesConfiguration theFilesConfiguration, ResourceService resourceService); @Override Response reload(); @Override Response view(); @Override Response encrypt(String cleartext); @Override Response manifest(ServletContext context); @Override Response isJwalaAuthorizationEnabled(); @Override Response getAuthorizationDetails(); static final String JSON_RESPONSE_TRUE; static final String JSON_RESPONSE_FALSE; }### Answer:
@Test public void testIsJwalaAuthorizationEnabled() throws Exception { Response response = cut.isJwalaAuthorizationEnabled(); ApplicationResponse applicationResponse = (ApplicationResponse) response.getEntity(); Object content = applicationResponse.getApplicationResponseContent(); assertEquals(content, AdminServiceRestImpl.JSON_RESPONSE_TRUE); System.setProperty("jwala.authorization", "false"); } |
### Question:
AdminServiceRestImpl implements AdminServiceRest { @Override public Response getAuthorizationDetails() { return ResponseBuilder.ok(new ResponseContent() { private static final String TRUE = "true"; private final String authEnabled = ApplicationProperties.get(JWALA_AUTHORIZATION, TRUE); public String getAuthorizationEnabled() { return authEnabled; } @SuppressWarnings("unchecked") public Collection<GrantedAuthority> getUserAuthorities() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (authEnabled.equalsIgnoreCase(TRUE) && auth != null) { return (Collection<GrantedAuthority>) auth.getAuthorities(); } return null; } }); } AdminServiceRestImpl(FilesConfiguration theFilesConfiguration, ResourceService resourceService); @Override Response reload(); @Override Response view(); @Override Response encrypt(String cleartext); @Override Response manifest(ServletContext context); @Override Response isJwalaAuthorizationEnabled(); @Override Response getAuthorizationDetails(); static final String JSON_RESPONSE_TRUE; static final String JSON_RESPONSE_FALSE; }### Answer:
@Test public void testGetAuthorizationDetails() { Response response = cut.getAuthorizationDetails(); assertEquals(response.getStatus(), 200); } |
### Question:
H2TcpServerServiceImpl extends AbstractH2ServerService { @Override protected Server createServer(final String [] serverParams) throws DbServerServiceException { try { return Server.createTcpServer(serverParams); } catch (final SQLException e) { LOGGER.log(Level.SEVERE, "Failed to create H2 TCP Server!", e); throw new DbServerServiceException(e); } } H2TcpServerServiceImpl(final String tcpServerParams); }### Answer:
@Test public void testCreateServer() { String[] params = new String[0]; Server result = service.createServer(params); assertNotNull(result.getPort()); assertEquals("default status", "Not started", result.getStatus()); assertNotNull("default URL", result.getURL()); assertNotNull("default service", result.getService()); }
@Test (expected = DbServerServiceException.class) public void testCreateServerThrowsException() { String[] badParams = new String[]{"-tcpPort", "ERROR"}; service.createServer(badParams); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.