method2testcases stringlengths 118 3.08k |
|---|
### Question:
TypeInsnNode extends AbstractInsnNode { @Override public int getType() { return TYPE_INSN; } TypeInsnNode(final int opcode, final String descriptor); void setOpcode(final int opcode); @Override int getType(); @Override void accept(final MethodVisitor methodVisitor); @Override AbstractInsnNode clone(final Map<LabelNode, LabelNode> clonedLabels); public String desc; }### Answer:
@Test public void testConstructor() { TypeInsnNode typeInsnNode = new TypeInsnNode(Opcodes.NEW, "java/lang/Object"); assertEquals(Opcodes.NEW, typeInsnNode.getOpcode()); assertEquals(AbstractInsnNode.TYPE_INSN, typeInsnNode.getType()); assertEquals("java/lang/Object", typeInsnNode.desc); } |
### Question:
TypeInsnNode extends AbstractInsnNode { public void setOpcode(final int opcode) { this.opcode = opcode; } TypeInsnNode(final int opcode, final String descriptor); void setOpcode(final int opcode); @Override int getType(); @Override void accept(final MethodVisitor methodVisitor); @Override AbstractInsnNode clone(final Map<LabelNode, LabelNode> clonedLabels); public String desc; }### Answer:
@Test public void testSetOpcode() { TypeInsnNode typeInsnNode = new TypeInsnNode(Opcodes.NEW, "java/lang/Object"); typeInsnNode.setOpcode(Opcodes.CHECKCAST); assertEquals(Opcodes.CHECKCAST, typeInsnNode.getOpcode()); } |
### Question:
IntInsnNode extends AbstractInsnNode { @Override public int getType() { return INT_INSN; } IntInsnNode(final int opcode, final int operand); void setOpcode(final int opcode); @Override int getType(); @Override void accept(final MethodVisitor methodVisitor); @Override AbstractInsnNode clone(final Map<LabelNode, LabelNode> clonedLabels); public int operand; }### Answer:
@Test public void testConstructor() { IntInsnNode intInsnNode = new IntInsnNode(Opcodes.BIPUSH, 0); assertEquals(Opcodes.BIPUSH, intInsnNode.getOpcode()); assertEquals(AbstractInsnNode.INT_INSN, intInsnNode.getType()); } |
### Question:
IntInsnNode extends AbstractInsnNode { public void setOpcode(final int opcode) { this.opcode = opcode; } IntInsnNode(final int opcode, final int operand); void setOpcode(final int opcode); @Override int getType(); @Override void accept(final MethodVisitor methodVisitor); @Override AbstractInsnNode clone(final Map<LabelNode, LabelNode> clonedLabels); public int operand; }### Answer:
@Test public void testSetOpcode() { IntInsnNode intInsnNode = new IntInsnNode(Opcodes.BIPUSH, 0); intInsnNode.setOpcode(Opcodes.SIPUSH); assertEquals(Opcodes.SIPUSH, intInsnNode.getOpcode()); } |
### Question:
SourceValue implements Value { @Override public boolean equals(final Object value) { if (!(value instanceof SourceValue)) { return false; } SourceValue sourceValue = (SourceValue) value; return size == sourceValue.size && insns.equals(sourceValue.insns); } SourceValue(final int size); SourceValue(final int size, final AbstractInsnNode insnNode); SourceValue(final int size, final Set<AbstractInsnNode> insnSet); @Override int getSize(); @Override boolean equals(final Object value); @Override int hashCode(); final int size; final Set<AbstractInsnNode> insns; }### Answer:
@Test public void testEquals() { SourceValue nullValue = null; boolean equalsSame = new SourceValue(1).equals(new SourceValue(1)); boolean equalsValueWithDifferentSource = new SourceValue(1).equals(new SourceValue(1, new InsnNode(Opcodes.NOP))); boolean equalsValueWithDifferentValue = new SourceValue(1).equals(new SourceValue(2)); boolean equalsNull = new SourceValue(1).equals(nullValue); assertTrue(equalsSame); assertFalse(equalsValueWithDifferentSource); assertFalse(equalsValueWithDifferentValue); assertFalse(equalsNull); }
@Test public void testEquals() { assertEquals(new SourceValue(1), new SourceValue(1)); assertNotEquals(new SourceValue(1), new SourceValue(1, new InsnNode(Opcodes.NOP))); assertNotEquals(new SourceValue(1), new SourceValue(2)); assertNotEquals(new SourceValue(1), null); } |
### Question:
BasicValue implements Value { @Override public int hashCode() { return type == null ? 0 : type.hashCode(); } BasicValue(final Type type); Type getType(); @Override int getSize(); boolean isReference(); @Override boolean equals(final Object value); @Override int hashCode(); @Override String toString(); static final BasicValue UNINITIALIZED_VALUE; static final BasicValue INT_VALUE; static final BasicValue FLOAT_VALUE; static final BasicValue LONG_VALUE; static final BasicValue DOUBLE_VALUE; static final BasicValue REFERENCE_VALUE; static final BasicValue RETURNADDRESS_VALUE; }### Answer:
@Test public void testHashCode() { assertEquals(0, BasicValue.UNINITIALIZED_VALUE.hashCode()); assertNotEquals(0, BasicValue.INT_VALUE.hashCode()); } |
### Question:
LineNumberNode extends AbstractInsnNode { @Override public int getType() { return LINE; } LineNumberNode(final int line, final LabelNode start); @Override int getType(); @Override void accept(final MethodVisitor methodVisitor); @Override AbstractInsnNode clone(final Map<LabelNode, LabelNode> clonedLabels); public int line; public LabelNode start; }### Answer:
@Test public void testConstructor() { LabelNode labelNode = new LabelNode(); LineNumberNode lineNumberNode = new LineNumberNode(42, labelNode); assertEquals(42, lineNumberNode.line); assertEquals(labelNode, lineNumberNode.start); assertEquals(AbstractInsnNode.LINE, lineNumberNode.getType()); } |
### Question:
IincInsnNode extends AbstractInsnNode { @Override public int getType() { return IINC_INSN; } IincInsnNode(final int var, final int incr); @Override int getType(); @Override void accept(final MethodVisitor methodVisitor); @Override AbstractInsnNode clone(final Map<LabelNode, LabelNode> clonedLabels); public int var; public int incr; }### Answer:
@Test public void testConstructor() { IincInsnNode iincnInsnNode = new IincInsnNode(1, 2); assertEquals(AbstractInsnNode.IINC_INSN, iincnInsnNode.getType()); assertEquals(1, iincnInsnNode.var); assertEquals(2, iincnInsnNode.incr); } |
### Question:
JumpInsnNode extends AbstractInsnNode { @Override public int getType() { return JUMP_INSN; } JumpInsnNode(final int opcode, final LabelNode label); void setOpcode(final int opcode); @Override int getType(); @Override void accept(final MethodVisitor methodVisitor); @Override AbstractInsnNode clone(final Map<LabelNode, LabelNode> clonedLabels); public LabelNode label; }### Answer:
@Test public void testConstructor() { LabelNode labelNode = new LabelNode(); JumpInsnNode jumpInsnNode = new JumpInsnNode(Opcodes.GOTO, labelNode); assertEquals(Opcodes.GOTO, jumpInsnNode.getOpcode()); assertEquals(AbstractInsnNode.JUMP_INSN, jumpInsnNode.getType()); assertEquals(labelNode, jumpInsnNode.label); } |
### Question:
JumpInsnNode extends AbstractInsnNode { public void setOpcode(final int opcode) { this.opcode = opcode; } JumpInsnNode(final int opcode, final LabelNode label); void setOpcode(final int opcode); @Override int getType(); @Override void accept(final MethodVisitor methodVisitor); @Override AbstractInsnNode clone(final Map<LabelNode, LabelNode> clonedLabels); public LabelNode label; }### Answer:
@Test public void testSetOpcode() { JumpInsnNode jumpInsnNode = new JumpInsnNode(Opcodes.GOTO, new LabelNode()); jumpInsnNode.setOpcode(Opcodes.IFEQ); assertEquals(Opcodes.IFEQ, jumpInsnNode.getOpcode()); } |
### Question:
LdcInsnNode extends AbstractInsnNode { @Override public int getType() { return LDC_INSN; } LdcInsnNode(final Object value); @Override int getType(); @Override void accept(final MethodVisitor methodVisitor); @Override AbstractInsnNode clone(final Map<LabelNode, LabelNode> clonedLabels); public Object cst; }### Answer:
@Test public void testConstructor() { LdcInsnNode ldcInsnNode = new LdcInsnNode("s"); assertEquals(AbstractInsnNode.LDC_INSN, ldcInsnNode.getType()); assertEquals("s", ldcInsnNode.cst); } |
### Question:
InsnNode extends AbstractInsnNode { @Override public int getType() { return INSN; } InsnNode(final int opcode); @Override int getType(); @Override void accept(final MethodVisitor methodVisitor); @Override AbstractInsnNode clone(final Map<LabelNode, LabelNode> clonedLabels); }### Answer:
@Test public void testConstructor() { InsnNode insnNode = new InsnNode(Opcodes.ACONST_NULL); assertEquals(AbstractInsnNode.INSN, insnNode.getType()); assertEquals(insnNode.getOpcode(), Opcodes.ACONST_NULL); } |
### Question:
VarInsnNode extends AbstractInsnNode { @Override public int getType() { return VAR_INSN; } VarInsnNode(final int opcode, final int var); void setOpcode(final int opcode); @Override int getType(); @Override void accept(final MethodVisitor methodVisitor); @Override AbstractInsnNode clone(final Map<LabelNode, LabelNode> clonedLabels); public int var; }### Answer:
@Test public void testConstructor() { VarInsnNode varInsnNode = new VarInsnNode(Opcodes.ALOAD, 123); assertEquals(Opcodes.ALOAD, varInsnNode.getOpcode()); assertEquals(AbstractInsnNode.VAR_INSN, varInsnNode.getType()); assertEquals(123, varInsnNode.var); } |
### Question:
VarInsnNode extends AbstractInsnNode { public void setOpcode(final int opcode) { this.opcode = opcode; } VarInsnNode(final int opcode, final int var); void setOpcode(final int opcode); @Override int getType(); @Override void accept(final MethodVisitor methodVisitor); @Override AbstractInsnNode clone(final Map<LabelNode, LabelNode> clonedLabels); public int var; }### Answer:
@Test public void testSetOpcode() { VarInsnNode varInsnNode = new VarInsnNode(Opcodes.ALOAD, 123); varInsnNode.setOpcode(Opcodes.ASTORE); assertEquals(Opcodes.ASTORE, varInsnNode.getOpcode()); } |
### Question:
InsnList implements Iterable<AbstractInsnNode> { public int size() { return size; } int size(); AbstractInsnNode getFirst(); AbstractInsnNode getLast(); AbstractInsnNode get(final int index); boolean contains(final AbstractInsnNode insnNode); int indexOf(final AbstractInsnNode insnNode); void accept(final MethodVisitor methodVisitor); @Override ListIterator<AbstractInsnNode> iterator(); @SuppressWarnings("unchecked") ListIterator<AbstractInsnNode> iterator(final int index); AbstractInsnNode[] toArray(); void set(final AbstractInsnNode oldInsnNode, final AbstractInsnNode newInsnNode); void add(final AbstractInsnNode insnNode); void add(final InsnList insnList); void insert(final AbstractInsnNode insnNode); void insert(final InsnList insnList); void insert(final AbstractInsnNode previousInsn, final AbstractInsnNode insnNode); void insert(final AbstractInsnNode previousInsn, final InsnList insnList); void insertBefore(final AbstractInsnNode nextInsn, final AbstractInsnNode insnNode); void insertBefore(final AbstractInsnNode nextInsn, final InsnList insnList); void remove(final AbstractInsnNode insnNode); void clear(); void resetLabels(); }### Answer:
@Test public void testSize_emptyList() { assertEquals(0, newInsnList().size()); } |
### Question:
SourceValue implements Value { @Override public int hashCode() { return insns.hashCode(); } SourceValue(final int size); SourceValue(final int size, final AbstractInsnNode insnNode); SourceValue(final int size, final Set<AbstractInsnNode> insnSet); @Override int getSize(); @Override boolean equals(final Object value); @Override int hashCode(); final int size; final Set<AbstractInsnNode> insns; }### Answer:
@Test public void testHashcode() { assertEquals(0, new SourceValue(1).hashCode()); assertNotEquals(0, new SourceValue(1, new InsnNode(Opcodes.NOP)).hashCode()); } |
### Question:
InsnList implements Iterable<AbstractInsnNode> { public AbstractInsnNode getFirst() { return firstInsn; } int size(); AbstractInsnNode getFirst(); AbstractInsnNode getLast(); AbstractInsnNode get(final int index); boolean contains(final AbstractInsnNode insnNode); int indexOf(final AbstractInsnNode insnNode); void accept(final MethodVisitor methodVisitor); @Override ListIterator<AbstractInsnNode> iterator(); @SuppressWarnings("unchecked") ListIterator<AbstractInsnNode> iterator(final int index); AbstractInsnNode[] toArray(); void set(final AbstractInsnNode oldInsnNode, final AbstractInsnNode newInsnNode); void add(final AbstractInsnNode insnNode); void add(final InsnList insnList); void insert(final AbstractInsnNode insnNode); void insert(final InsnList insnList); void insert(final AbstractInsnNode previousInsn, final AbstractInsnNode insnNode); void insert(final AbstractInsnNode previousInsn, final InsnList insnList); void insertBefore(final AbstractInsnNode nextInsn, final AbstractInsnNode insnNode); void insertBefore(final AbstractInsnNode nextInsn, final InsnList insnList); void remove(final AbstractInsnNode insnNode); void clear(); void resetLabels(); }### Answer:
@Test public void testGetFirst_emptyList() { assertEquals(null, newInsnList().getFirst()); } |
### Question:
InsnList implements Iterable<AbstractInsnNode> { public AbstractInsnNode getLast() { return lastInsn; } int size(); AbstractInsnNode getFirst(); AbstractInsnNode getLast(); AbstractInsnNode get(final int index); boolean contains(final AbstractInsnNode insnNode); int indexOf(final AbstractInsnNode insnNode); void accept(final MethodVisitor methodVisitor); @Override ListIterator<AbstractInsnNode> iterator(); @SuppressWarnings("unchecked") ListIterator<AbstractInsnNode> iterator(final int index); AbstractInsnNode[] toArray(); void set(final AbstractInsnNode oldInsnNode, final AbstractInsnNode newInsnNode); void add(final AbstractInsnNode insnNode); void add(final InsnList insnList); void insert(final AbstractInsnNode insnNode); void insert(final InsnList insnList); void insert(final AbstractInsnNode previousInsn, final AbstractInsnNode insnNode); void insert(final AbstractInsnNode previousInsn, final InsnList insnList); void insertBefore(final AbstractInsnNode nextInsn, final AbstractInsnNode insnNode); void insertBefore(final AbstractInsnNode nextInsn, final InsnList insnList); void remove(final AbstractInsnNode insnNode); void clear(); void resetLabels(); }### Answer:
@Test public void testGetLast_emptyList() { assertEquals(null, newInsnList().getLast()); } |
### Question:
InsnList implements Iterable<AbstractInsnNode> { public AbstractInsnNode get(final int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(); } if (cache == null) { cache = toArray(); } return cache[index]; } int size(); AbstractInsnNode getFirst(); AbstractInsnNode getLast(); AbstractInsnNode get(final int index); boolean contains(final AbstractInsnNode insnNode); int indexOf(final AbstractInsnNode insnNode); void accept(final MethodVisitor methodVisitor); @Override ListIterator<AbstractInsnNode> iterator(); @SuppressWarnings("unchecked") ListIterator<AbstractInsnNode> iterator(final int index); AbstractInsnNode[] toArray(); void set(final AbstractInsnNode oldInsnNode, final AbstractInsnNode newInsnNode); void add(final AbstractInsnNode insnNode); void add(final InsnList insnList); void insert(final AbstractInsnNode insnNode); void insert(final InsnList insnList); void insert(final AbstractInsnNode previousInsn, final AbstractInsnNode insnNode); void insert(final AbstractInsnNode previousInsn, final InsnList insnList); void insertBefore(final AbstractInsnNode nextInsn, final AbstractInsnNode insnNode); void insertBefore(final AbstractInsnNode nextInsn, final InsnList insnList); void remove(final AbstractInsnNode insnNode); void clear(); void resetLabels(); }### Answer:
@Test public void testGet_outOfBounds() { Executable get = () -> newInsnList().get(0); assertThrows(IndexOutOfBoundsException.class, get); } |
### Question:
InsnList implements Iterable<AbstractInsnNode> { public boolean contains(final AbstractInsnNode insnNode) { AbstractInsnNode currentInsn = firstInsn; while (currentInsn != null && currentInsn != insnNode) { currentInsn = currentInsn.nextInsn; } return currentInsn != null; } int size(); AbstractInsnNode getFirst(); AbstractInsnNode getLast(); AbstractInsnNode get(final int index); boolean contains(final AbstractInsnNode insnNode); int indexOf(final AbstractInsnNode insnNode); void accept(final MethodVisitor methodVisitor); @Override ListIterator<AbstractInsnNode> iterator(); @SuppressWarnings("unchecked") ListIterator<AbstractInsnNode> iterator(final int index); AbstractInsnNode[] toArray(); void set(final AbstractInsnNode oldInsnNode, final AbstractInsnNode newInsnNode); void add(final AbstractInsnNode insnNode); void add(final InsnList insnList); void insert(final AbstractInsnNode insnNode); void insert(final InsnList insnList); void insert(final AbstractInsnNode previousInsn, final AbstractInsnNode insnNode); void insert(final AbstractInsnNode previousInsn, final InsnList insnList); void insertBefore(final AbstractInsnNode nextInsn, final AbstractInsnNode insnNode); void insertBefore(final AbstractInsnNode nextInsn, final InsnList insnList); void remove(final AbstractInsnNode insnNode); void clear(); void resetLabels(); }### Answer:
@Test public void testContains() { assertFalse(newInsnList().contains(new InsnNode(0))); } |
### Question:
InsnList implements Iterable<AbstractInsnNode> { public int indexOf(final AbstractInsnNode insnNode) { if (cache == null) { cache = toArray(); } return insnNode.index; } int size(); AbstractInsnNode getFirst(); AbstractInsnNode getLast(); AbstractInsnNode get(final int index); boolean contains(final AbstractInsnNode insnNode); int indexOf(final AbstractInsnNode insnNode); void accept(final MethodVisitor methodVisitor); @Override ListIterator<AbstractInsnNode> iterator(); @SuppressWarnings("unchecked") ListIterator<AbstractInsnNode> iterator(final int index); AbstractInsnNode[] toArray(); void set(final AbstractInsnNode oldInsnNode, final AbstractInsnNode newInsnNode); void add(final AbstractInsnNode insnNode); void add(final InsnList insnList); void insert(final AbstractInsnNode insnNode); void insert(final InsnList insnList); void insert(final AbstractInsnNode previousInsn, final AbstractInsnNode insnNode); void insert(final AbstractInsnNode previousInsn, final InsnList insnList); void insertBefore(final AbstractInsnNode nextInsn, final AbstractInsnNode insnNode); void insertBefore(final AbstractInsnNode nextInsn, final InsnList insnList); void remove(final AbstractInsnNode insnNode); void clear(); void resetLabels(); }### Answer:
@Test public void testIndexOf_noSuchElement() { InsnList insnList = newInsnList(); Executable indexOf = () -> insnList.indexOf(new InsnNode(0)); assertThrows(NoSuchElementException.class, indexOf); }
@Test public void testIndexOf() { InsnList insnList = newInsnList(insn1, insn2); int index1 = insnList.indexOf(insn1); int index2 = insnList.indexOf(insn2); assertEquals(0, index1); assertEquals(1, index2); } |
### Question:
InsnList implements Iterable<AbstractInsnNode> { public AbstractInsnNode[] toArray() { int currentInsnIndex = 0; AbstractInsnNode currentInsn = firstInsn; AbstractInsnNode[] insnNodeArray = new AbstractInsnNode[size]; while (currentInsn != null) { insnNodeArray[currentInsnIndex] = currentInsn; currentInsn.index = currentInsnIndex++; currentInsn = currentInsn.nextInsn; } return insnNodeArray; } int size(); AbstractInsnNode getFirst(); AbstractInsnNode getLast(); AbstractInsnNode get(final int index); boolean contains(final AbstractInsnNode insnNode); int indexOf(final AbstractInsnNode insnNode); void accept(final MethodVisitor methodVisitor); @Override ListIterator<AbstractInsnNode> iterator(); @SuppressWarnings("unchecked") ListIterator<AbstractInsnNode> iterator(final int index); AbstractInsnNode[] toArray(); void set(final AbstractInsnNode oldInsnNode, final AbstractInsnNode newInsnNode); void add(final AbstractInsnNode insnNode); void add(final InsnList insnList); void insert(final AbstractInsnNode insnNode); void insert(final InsnList insnList); void insert(final AbstractInsnNode previousInsn, final AbstractInsnNode insnNode); void insert(final AbstractInsnNode previousInsn, final InsnList insnList); void insertBefore(final AbstractInsnNode nextInsn, final AbstractInsnNode insnNode); void insertBefore(final AbstractInsnNode nextInsn, final InsnList insnList); void remove(final AbstractInsnNode insnNode); void clear(); void resetLabels(); }### Answer:
@Test public void testToArray_emptyList() { assertEquals(0, newInsnList().toArray().length); }
@Test public void testToArray_nonEmptyList() { InsnList insnList = newInsnList(insn1, insn2); AbstractInsnNode[] insnArray = insnList.toArray(); assertArrayEquals(new AbstractInsnNode[] {insn1, insn2}, insnArray); } |
### Question:
InsnList implements Iterable<AbstractInsnNode> { public void add(final AbstractInsnNode insnNode) { ++size; if (lastInsn == null) { firstInsn = insnNode; lastInsn = insnNode; } else { lastInsn.nextInsn = insnNode; insnNode.previousInsn = lastInsn; } lastInsn = insnNode; cache = null; insnNode.index = 0; } int size(); AbstractInsnNode getFirst(); AbstractInsnNode getLast(); AbstractInsnNode get(final int index); boolean contains(final AbstractInsnNode insnNode); int indexOf(final AbstractInsnNode insnNode); void accept(final MethodVisitor methodVisitor); @Override ListIterator<AbstractInsnNode> iterator(); @SuppressWarnings("unchecked") ListIterator<AbstractInsnNode> iterator(final int index); AbstractInsnNode[] toArray(); void set(final AbstractInsnNode oldInsnNode, final AbstractInsnNode newInsnNode); void add(final AbstractInsnNode insnNode); void add(final InsnList insnList); void insert(final AbstractInsnNode insnNode); void insert(final InsnList insnList); void insert(final AbstractInsnNode previousInsn, final AbstractInsnNode insnNode); void insert(final AbstractInsnNode previousInsn, final InsnList insnList); void insertBefore(final AbstractInsnNode nextInsn, final AbstractInsnNode insnNode); void insertBefore(final AbstractInsnNode nextInsn, final InsnList insnList); void remove(final AbstractInsnNode insnNode); void clear(); void resetLabels(); }### Answer:
@Test public void testAdd_illegalArgument() { InsnList insnList = newInsnList(); newInsnList(insn1, insn2); Executable add = () -> insnList.add(insn1); assertThrows(IllegalArgumentException.class, add); }
@Test public void testAddList_illegalArgument() { InsnList insnList = newInsnList(); Executable add = () -> insnList.add(insnList); assertThrows(IllegalArgumentException.class, add); } |
### Question:
InsnList implements Iterable<AbstractInsnNode> { public void clear() { removeAll(false); } int size(); AbstractInsnNode getFirst(); AbstractInsnNode getLast(); AbstractInsnNode get(final int index); boolean contains(final AbstractInsnNode insnNode); int indexOf(final AbstractInsnNode insnNode); void accept(final MethodVisitor methodVisitor); @Override ListIterator<AbstractInsnNode> iterator(); @SuppressWarnings("unchecked") ListIterator<AbstractInsnNode> iterator(final int index); AbstractInsnNode[] toArray(); void set(final AbstractInsnNode oldInsnNode, final AbstractInsnNode newInsnNode); void add(final AbstractInsnNode insnNode); void add(final InsnList insnList); void insert(final AbstractInsnNode insnNode); void insert(final InsnList insnList); void insert(final AbstractInsnNode previousInsn, final AbstractInsnNode insnNode); void insert(final AbstractInsnNode previousInsn, final InsnList insnList); void insertBefore(final AbstractInsnNode nextInsn, final AbstractInsnNode insnNode); void insertBefore(final AbstractInsnNode nextInsn, final InsnList insnList); void remove(final AbstractInsnNode insnNode); void clear(); void resetLabels(); }### Answer:
@Test public void testClear() { InsnList insnList = newInsnList(); InsnNode insn = new InsnNode(0); insnList.add(new InsnNode(0)); insnList.add(insn); insnList.add(new InsnNode(0)); insnList.clear(); assertEquals(0, insnList.size()); assertEquals(null, insnList.getFirst()); assertEquals(null, insnList.getLast()); assertFalse(insnList.contains(insn)); assertArrayEquals(new AbstractInsnNode[0], insnList.toArray()); assertEquals(null, insn.getPrevious()); assertEquals(null, insn.getNext()); } |
### Question:
InsnList implements Iterable<AbstractInsnNode> { public void resetLabels() { AbstractInsnNode currentInsn = firstInsn; while (currentInsn != null) { if (currentInsn instanceof LabelNode) { ((LabelNode) currentInsn).resetLabel(); } currentInsn = currentInsn.nextInsn; } } int size(); AbstractInsnNode getFirst(); AbstractInsnNode getLast(); AbstractInsnNode get(final int index); boolean contains(final AbstractInsnNode insnNode); int indexOf(final AbstractInsnNode insnNode); void accept(final MethodVisitor methodVisitor); @Override ListIterator<AbstractInsnNode> iterator(); @SuppressWarnings("unchecked") ListIterator<AbstractInsnNode> iterator(final int index); AbstractInsnNode[] toArray(); void set(final AbstractInsnNode oldInsnNode, final AbstractInsnNode newInsnNode); void add(final AbstractInsnNode insnNode); void add(final InsnList insnList); void insert(final AbstractInsnNode insnNode); void insert(final InsnList insnList); void insert(final AbstractInsnNode previousInsn, final AbstractInsnNode insnNode); void insert(final AbstractInsnNode previousInsn, final InsnList insnList); void insertBefore(final AbstractInsnNode nextInsn, final AbstractInsnNode insnNode); void insertBefore(final AbstractInsnNode nextInsn, final InsnList insnList); void remove(final AbstractInsnNode insnNode); void clear(); void resetLabels(); }### Answer:
@Test public void testResetLabels() { InsnList insnList = newInsnList(); LabelNode labelNode = new LabelNode(); insnList.add(new InsnNode(55)); insnList.add(labelNode); insnList.add(new InsnNode(77)); Label label = labelNode.getLabel(); insnList.resetLabels(); assertNotNull(label); assertNotSame(label, labelNode.getLabel()); } |
### Question:
SmallSet extends AbstractSet<T> { @Override public Iterator<T> iterator() { return new IteratorImpl<>(element1, element2); } SmallSet(); SmallSet(final T element); private SmallSet(final T element1, final T element2); @Override Iterator<T> iterator(); @Override int size(); }### Answer:
@Test public void testIterator_next_firstElement() { Iterator<Object> iterator = newSmallSet(ELEMENT1, ELEMENT2).iterator(); Object element = iterator.next(); assertEquals(ELEMENT1, element); assertTrue(iterator.hasNext()); }
@Test public void testIterator_next_secondElement() { Iterator<Object> iterator = newSmallSet(ELEMENT1, ELEMENT2).iterator(); iterator.next(); Object element = iterator.next(); assertEquals(ELEMENT2, element); assertFalse(iterator.hasNext()); }
@Test public void testIterator_next_noSuchElement() { Iterator<Object> iterator = newSmallSet(ELEMENT1, ELEMENT2).iterator(); iterator.next(); iterator.next(); Executable next = () -> iterator.next(); assertThrows(NoSuchElementException.class, next); }
@Test public void testIterator_remove() { Iterator<Object> iterator = newSmallSet(ELEMENT1, ELEMENT2).iterator(); iterator.next(); assertThrows(UnsupportedOperationException.class, () -> iterator.remove()); } |
### Question:
BasicValue implements Value { @Override public String toString() { if (this == UNINITIALIZED_VALUE) { return "."; } else if (this == RETURNADDRESS_VALUE) { return "A"; } else if (this == REFERENCE_VALUE) { return "R"; } else { return type.getDescriptor(); } } BasicValue(final Type type); Type getType(); @Override int getSize(); boolean isReference(); @Override boolean equals(final Object value); @Override int hashCode(); @Override String toString(); static final BasicValue UNINITIALIZED_VALUE; static final BasicValue INT_VALUE; static final BasicValue FLOAT_VALUE; static final BasicValue LONG_VALUE; static final BasicValue DOUBLE_VALUE; static final BasicValue REFERENCE_VALUE; static final BasicValue RETURNADDRESS_VALUE; }### Answer:
@Test public void testToString() { assertEquals(".", BasicValue.UNINITIALIZED_VALUE.toString()); assertEquals("A", BasicValue.RETURNADDRESS_VALUE.toString()); assertEquals("R", BasicValue.REFERENCE_VALUE.toString()); assertEquals("LI;", new BasicValue(Type.getObjectType("I")).toString()); } |
### Question:
CheckRecordComponentAdapter extends RecordComponentVisitor { @Override public AnnotationVisitor visitTypeAnnotation( final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) { checkVisitEndNotCalled(); int sort = new TypeReference(typeRef).getSort(); if (sort != TypeReference.FIELD) { throw new IllegalArgumentException( "Invalid type reference sort 0x" + Integer.toHexString(sort)); } CheckClassAdapter.checkTypeRef(typeRef); CheckMethodAdapter.checkDescriptor(Opcodes.V1_5, descriptor, false); return new CheckAnnotationAdapter( super.visitTypeAnnotation(typeRef, typePath, descriptor, visible)); } CheckRecordComponentAdapter(final RecordComponentVisitor recordComponentVisitor); protected CheckRecordComponentAdapter(
final int api, final RecordComponentVisitor recordComponentVisitor); @Override AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible); @Override AnnotationVisitor visitTypeAnnotation(
final int typeRef, final TypePath typePath, final String descriptor, final boolean visible); @Override void visitAttribute(final Attribute attribute); @Override void visitEnd(); }### Answer:
@Test public void testVisitTypeAnnotation_illegalTypeAnnotation() { CheckRecordComponentAdapter checkRecordComponentAdapter = new CheckRecordComponentAdapter(null); Executable visitTypeAnnotation = () -> checkRecordComponentAdapter.visitTypeAnnotation( TypeReference.newFormalParameterReference(0).getValue(), null, "LA;", true); Exception exception = assertThrows(IllegalArgumentException.class, visitTypeAnnotation); assertEquals("Invalid type reference sort 0x16", exception.getMessage()); } |
### Question:
CheckRecordComponentAdapter extends RecordComponentVisitor { @Override public void visitAttribute(final Attribute attribute) { checkVisitEndNotCalled(); if (attribute == null) { throw new IllegalArgumentException("Invalid attribute (must not be null)"); } super.visitAttribute(attribute); } CheckRecordComponentAdapter(final RecordComponentVisitor recordComponentVisitor); protected CheckRecordComponentAdapter(
final int api, final RecordComponentVisitor recordComponentVisitor); @Override AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible); @Override AnnotationVisitor visitTypeAnnotation(
final int typeRef, final TypePath typePath, final String descriptor, final boolean visible); @Override void visitAttribute(final Attribute attribute); @Override void visitEnd(); }### Answer:
@Test public void testVisitAttribute_illegalAttribute() { CheckRecordComponentAdapter checkRecordComponentAdapter = new CheckRecordComponentAdapter(null); Executable visitAttribute = () -> checkRecordComponentAdapter.visitAttribute(null); Exception exception = assertThrows(IllegalArgumentException.class, visitAttribute); assertEquals("Invalid attribute (must not be null)", exception.getMessage()); } |
### Question:
CheckAnnotationAdapter extends AnnotationVisitor { @Override public void visit(final String name, final Object value) { checkVisitEndNotCalled(); checkName(name); if (!(value instanceof Byte || value instanceof Boolean || value instanceof Character || value instanceof Short || value instanceof Integer || value instanceof Long || value instanceof Float || value instanceof Double || value instanceof String || value instanceof Type || value instanceof byte[] || value instanceof boolean[] || value instanceof char[] || value instanceof short[] || value instanceof int[] || value instanceof long[] || value instanceof float[] || value instanceof double[])) { throw new IllegalArgumentException("Invalid annotation value"); } if (value instanceof Type && ((Type) value).getSort() == Type.METHOD) { throw new IllegalArgumentException("Invalid annotation value"); } super.visit(name, value); } CheckAnnotationAdapter(final AnnotationVisitor annotationVisitor); CheckAnnotationAdapter(final AnnotationVisitor annotationVisitor, final boolean useNamedValues); @Override void visit(final String name, final Object value); @Override void visitEnum(final String name, final String descriptor, final String value); @Override AnnotationVisitor visitAnnotation(final String name, final String descriptor); @Override AnnotationVisitor visitArray(final String name); @Override void visitEnd(); }### Answer:
@Test public void testVisit_illegalAnnotationName() { CheckAnnotationAdapter checkAnnotationAdapter = new CheckAnnotationAdapter(null); Executable visit = () -> checkAnnotationAdapter.visit(null, Integer.valueOf(0)); Exception exception = assertThrows(IllegalArgumentException.class, visit); assertEquals("Annotation value name must not be null", exception.getMessage()); }
@Test public void testVisit_illegalAnnotationValue1() { CheckAnnotationAdapter checkAnnotationAdapter = new CheckAnnotationAdapter(null); Executable visit = () -> checkAnnotationAdapter.visit("name", new Object()); Exception exception = assertThrows(IllegalArgumentException.class, visit); assertEquals("Invalid annotation value", exception.getMessage()); }
@Test public void testVisit_illegalAnnotationValue2() { CheckAnnotationAdapter checkAnnotationAdapter = new CheckAnnotationAdapter(null); Executable visit = () -> checkAnnotationAdapter.visit("name", Type.getMethodType("()V")); Exception exception = assertThrows(IllegalArgumentException.class, visit); assertEquals("Invalid annotation value", exception.getMessage()); } |
### Question:
CheckAnnotationAdapter extends AnnotationVisitor { @Override public void visitEnum(final String name, final String descriptor, final String value) { checkVisitEndNotCalled(); checkName(name); CheckMethodAdapter.checkDescriptor(Opcodes.V1_5, descriptor, false); if (value == null) { throw new IllegalArgumentException("Invalid enum value"); } super.visitEnum(name, descriptor, value); } CheckAnnotationAdapter(final AnnotationVisitor annotationVisitor); CheckAnnotationAdapter(final AnnotationVisitor annotationVisitor, final boolean useNamedValues); @Override void visit(final String name, final Object value); @Override void visitEnum(final String name, final String descriptor, final String value); @Override AnnotationVisitor visitAnnotation(final String name, final String descriptor); @Override AnnotationVisitor visitArray(final String name); @Override void visitEnd(); }### Answer:
@Test public void testVisitEnum_illegalAnnotationEnumValue() { CheckAnnotationAdapter checkAnnotationAdapter = new CheckAnnotationAdapter(null); Executable visitEnum = () -> checkAnnotationAdapter.visitEnum("name", "Lpkg/Enum;", null); Exception exception = assertThrows(IllegalArgumentException.class, visitEnum); assertEquals("Invalid enum value", exception.getMessage()); } |
### Question:
TraceSignatureVisitor extends SignatureVisitor { @Override public void visitBaseType(final char descriptor) { String baseType = BASE_TYPES.get(descriptor); if (baseType == null) { throw new IllegalArgumentException(); } declaration.append(baseType); endType(); } TraceSignatureVisitor(final int accessFlags); private TraceSignatureVisitor(final StringBuilder stringBuilder); @Override void visitFormalTypeParameter(final String name); @Override SignatureVisitor visitClassBound(); @Override SignatureVisitor visitInterfaceBound(); @Override SignatureVisitor visitSuperclass(); @Override SignatureVisitor visitInterface(); @Override SignatureVisitor visitParameterType(); @Override SignatureVisitor visitReturnType(); @Override SignatureVisitor visitExceptionType(); @Override void visitBaseType(final char descriptor); @Override void visitTypeVariable(final String name); @Override SignatureVisitor visitArrayType(); @Override void visitClassType(final String name); @Override void visitInnerClassType(final String name); @Override void visitTypeArgument(); @Override SignatureVisitor visitTypeArgument(final char tag); @Override void visitEnd(); String getDeclaration(); String getReturnType(); String getExceptions(); }### Answer:
@Test public void testVisitBaseType_invalidSignature() { TraceSignatureVisitor traceSignatureVisitor = new TraceSignatureVisitor(0); Executable visitBaseType = () -> traceSignatureVisitor.visitBaseType('-'); assertThrows(IllegalArgumentException.class, visitBaseType); } |
### Question:
CheckModuleAdapter extends ModuleVisitor { @Override public void visitExport(final String packaze, final int access, final String... modules) { checkVisitEndNotCalled(); CheckMethodAdapter.checkInternalName(Opcodes.V9, packaze, "package name"); exportedPackages.checkNameNotAlreadyDeclared(packaze); CheckClassAdapter.checkAccess(access, Opcodes.ACC_SYNTHETIC | Opcodes.ACC_MANDATED); if (modules != null) { for (String module : modules) { CheckClassAdapter.checkFullyQualifiedName(Opcodes.V9, module, "module export to"); } } super.visitExport(packaze, access, modules); } CheckModuleAdapter(final ModuleVisitor moduleVisitor, final boolean isOpen); protected CheckModuleAdapter(
final int api, final ModuleVisitor moduleVisitor, final boolean isOpen); @Override void visitMainClass(final String mainClass); @Override void visitPackage(final String packaze); @Override void visitRequire(final String module, final int access, final String version); @Override void visitExport(final String packaze, final int access, final String... modules); @Override void visitOpen(final String packaze, final int access, final String... modules); @Override void visitUse(final String service); @Override void visitProvide(final String service, final String... providers); @Override void visitEnd(); }### Answer:
@Test public void testVisitExport_nullArray() { CheckModuleAdapter checkModuleAdapter = new CheckModuleAdapter(null, false); Executable visitExport = () -> checkModuleAdapter.visitExport("package", 0, (String[]) null); assertDoesNotThrow(visitExport); } |
### Question:
CheckModuleAdapter extends ModuleVisitor { @Override public void visitOpen(final String packaze, final int access, final String... modules) { checkVisitEndNotCalled(); if (isOpen) { throw new UnsupportedOperationException("An open module can not use open directive"); } CheckMethodAdapter.checkInternalName(Opcodes.V9, packaze, "package name"); openedPackages.checkNameNotAlreadyDeclared(packaze); CheckClassAdapter.checkAccess(access, Opcodes.ACC_SYNTHETIC | Opcodes.ACC_MANDATED); if (modules != null) { for (String module : modules) { CheckClassAdapter.checkFullyQualifiedName(Opcodes.V9, module, "module open to"); } } super.visitOpen(packaze, access, modules); } CheckModuleAdapter(final ModuleVisitor moduleVisitor, final boolean isOpen); protected CheckModuleAdapter(
final int api, final ModuleVisitor moduleVisitor, final boolean isOpen); @Override void visitMainClass(final String mainClass); @Override void visitPackage(final String packaze); @Override void visitRequire(final String module, final int access, final String version); @Override void visitExport(final String packaze, final int access, final String... modules); @Override void visitOpen(final String packaze, final int access, final String... modules); @Override void visitUse(final String service); @Override void visitProvide(final String service, final String... providers); @Override void visitEnd(); }### Answer:
@Test public void testVisitOpen_nullArray() { CheckModuleAdapter checkModuleAdapter = new CheckModuleAdapter(null, false); Executable visitOpen = () -> checkModuleAdapter.visitOpen("package", 0, (String[]) null); assertDoesNotThrow(visitOpen); }
@Test public void testVisitOpen_openModule() { CheckModuleAdapter checkModuleAdapter = new CheckModuleAdapter(null, true); Executable visitOpen = () -> checkModuleAdapter.visitOpen("package", 0, (String[]) null); Exception exception = assertThrows(UnsupportedOperationException.class, visitOpen); assertEquals("An open module can not use open directive", exception.getMessage()); } |
### Question:
CheckModuleAdapter extends ModuleVisitor { @Override public void visitUse(final String service) { checkVisitEndNotCalled(); CheckMethodAdapter.checkInternalName(Opcodes.V9, service, "service"); usedServices.checkNameNotAlreadyDeclared(service); super.visitUse(service); } CheckModuleAdapter(final ModuleVisitor moduleVisitor, final boolean isOpen); protected CheckModuleAdapter(
final int api, final ModuleVisitor moduleVisitor, final boolean isOpen); @Override void visitMainClass(final String mainClass); @Override void visitPackage(final String packaze); @Override void visitRequire(final String module, final int access, final String version); @Override void visitExport(final String packaze, final int access, final String... modules); @Override void visitOpen(final String packaze, final int access, final String... modules); @Override void visitUse(final String service); @Override void visitProvide(final String service, final String... providers); @Override void visitEnd(); }### Answer:
@Test public void testVisitUse_nameAlreadyDeclared() { CheckModuleAdapter checkModuleAdapter = new CheckModuleAdapter(null, false); checkModuleAdapter.visitUse("service"); Executable visitUse = () -> checkModuleAdapter.visitUse("service"); Exception exception = assertThrows(IllegalArgumentException.class, visitUse); assertEquals("Module uses 'service' already declared", exception.getMessage()); } |
### Question:
CheckModuleAdapter extends ModuleVisitor { @Override public void visitProvide(final String service, final String... providers) { checkVisitEndNotCalled(); CheckMethodAdapter.checkInternalName(Opcodes.V9, service, "service"); providedServices.checkNameNotAlreadyDeclared(service); if (providers == null || providers.length == 0) { throw new IllegalArgumentException("Providers cannot be null or empty"); } for (String provider : providers) { CheckMethodAdapter.checkInternalName(Opcodes.V9, provider, "provider"); } super.visitProvide(service, providers); } CheckModuleAdapter(final ModuleVisitor moduleVisitor, final boolean isOpen); protected CheckModuleAdapter(
final int api, final ModuleVisitor moduleVisitor, final boolean isOpen); @Override void visitMainClass(final String mainClass); @Override void visitPackage(final String packaze); @Override void visitRequire(final String module, final int access, final String version); @Override void visitExport(final String packaze, final int access, final String... modules); @Override void visitOpen(final String packaze, final int access, final String... modules); @Override void visitUse(final String service); @Override void visitProvide(final String service, final String... providers); @Override void visitEnd(); }### Answer:
@Test public void testVisitProvide_nullProviderList() { CheckModuleAdapter checkModuleAdapter = new CheckModuleAdapter(null, false); Executable visitProvide = () -> checkModuleAdapter.visitProvide("service2", (String[]) null); Exception exception = assertThrows(IllegalArgumentException.class, visitProvide); assertEquals("Providers cannot be null or empty", exception.getMessage()); }
@Test public void testVisitProvide_emptyProviderList() { CheckModuleAdapter checkModuleAdapter = new CheckModuleAdapter(null, false); Executable visitProvide = () -> checkModuleAdapter.visitProvide("service1"); Exception exception = assertThrows(IllegalArgumentException.class, visitProvide); assertEquals("Providers cannot be null or empty", exception.getMessage()); } |
### Question:
Lib1 { public String hello(String who) { return "Hello " + new Lib2().awesome(who) + "!"; } String hello(String who); }### Answer:
@Test public void testHello() { final Lib1 underTest = new Lib1(); Assert.assertEquals("Hello Awesome! menny!", underTest.hello("menny")); } |
### Question:
BazelCleanTask extends BazelExecTaskBase { @Override public void setBazelConfig(BazelLeafConfig.Decorated config) { super.setBazelConfig(config); setDescription("Cleans Bazel workspace"); setGroup(BasePlugin.BUILD_GROUP); } @Inject BazelCleanTask(); @VisibleForTesting BazelCleanTask(BazelExecHelper bazelExecHelper); @Override void setBazelConfig(BazelLeafConfig.Decorated config); }### Answer:
@Test public void testTask() throws Exception { Project project = TestUtils.createConfiguredAppliedProject(); TestableBazelCleanTask bazelClean = project.getTasks().create("bazelClean", TestableBazelCleanTask.class); BazelLeafConfig.Decorated config = new BazelLeafConfig.Decorated( "bazelBin", "targetPath", "targetName", "testTargetName", new File("workspaceDir"), "outputDir" ); bazelClean.setBazelConfig(config); bazelClean.bazelExec(); verify(bazelClean.getMockBazelExecHelper()).createBazelRun(true, config, "", "clean"); verify(bazelClean.mockBazelExec).start(); assertThat(bazelClean.getDescription(), IsEqual .equalTo("Cleans Bazel workspace")); assertThat(bazelClean.getGroup(), IsEqual.equalTo(BasePlugin.BUILD_GROUP)); } |
### Question:
SystemEnvironment { public static OsType getOsType() { final String osName = System.getProperty("os.name", "none").toLowerCase(Locale.US); if (osName.contains("mac") || osName.contains("darwin")) { return OsType.macOs; } else if (osName.contains("win")) { return OsType.Windows; } else { return OsType.Linux; } } private SystemEnvironment(); static OsType getOsType(); }### Answer:
@Test public void testDarwin() { System.setProperty("os.name", "darwin"); SystemEnvironment.OsType osType = SystemEnvironment.getOsType(); assertThat(osType, IsEqual.equalTo(SystemEnvironment.OsType.macOs)); }
@Test public void testMac() { System.setProperty("os.name", "mac"); SystemEnvironment.OsType osType = SystemEnvironment.getOsType(); assertThat(osType, IsEqual.equalTo(SystemEnvironment.OsType.macOs)); }
@Test public void testWindows() { System.setProperty("os.name", "WINDOWS"); SystemEnvironment.OsType osType = SystemEnvironment.getOsType(); assertThat(osType, IsEqual.equalTo(SystemEnvironment.OsType.Windows)); }
@Test public void testLinux() { System.setProperty("os.name", "NOTSOMEEXPECTEDVALUE"); SystemEnvironment.OsType osType = SystemEnvironment.getOsType(); assertThat(osType, IsEqual.equalTo(SystemEnvironment.OsType.Linux)); } |
### Question:
AndroidLibraryStrategy extends PlainBuildStrategy { @Override public Task createBazelExecTask(Project project) { final BazelBuildTask bazelBuildTask = (BazelBuildTask) super.createBazelExecTask(project); bazelBuildTask.setBazelConfig(new BazelLeafConfig.Decorated( mConfig.bazelBin, mConfig.targetPath, mConfig.targetName + ".aar", mConfig.testTargetName, mConfig.workspaceRootFolder, mConfig.buildOutputDir)); return bazelBuildTask; } AndroidLibraryStrategy(BazelLeafConfig.Decorated config); @Override Task createBazelExecTask(Project project); @Override List<BazelPublishArtifact> getBazelArtifacts(AspectRunner aspectRunner, Project project, Task bazelExecTask); }### Answer:
@Test public void testConfiguration() { Project project = TestUtils.createConfiguredAppliedProject(); BazelLeafConfig.Decorated decoratedConfig = new BazelLeafConfig.Decorated( "bazelBin", "targetPath", "targetName", "testTargetName", new File("workspaceDir"), "outputDir" ); AndroidLibraryStrategy androidLibraryStrategy = new AndroidLibraryStrategy(decoratedConfig); BazelBuildTask createdTask = (BazelBuildTask) androidLibraryStrategy.createBazelExecTask(project); assertThat(createdTask, IsNull.notNullValue()); assertThat(createdTask.getDescription(), IsEqual .equalTo(String.format("Compiles Bazel target %s:%s", "targetPath", "targetName.aar"))); } |
### Question:
Lib2 { public String awesome(String who) { return "Awesome! " + checkNotNull(who); } String awesome(String who); }### Answer:
@Test public void testAwesome() { final Lib2 underTest = new Lib2(); Assert.assertEquals("Awesome! menny", underTest.awesome("menny")); }
@Test(expected = NullPointerException.class) public void testNPE() { final Lib2 underTest = new Lib2(); underTest.awesome(null); } |
### Question:
BazelExpungeTask extends BazelExecTaskBase { @Override public void setBazelConfig(BazelLeafConfig.Decorated config) { super.setBazelConfig(config); setDescription("Cleans and expunges Bazel workspace"); setGroup(BasePlugin.BUILD_GROUP); } @Inject BazelExpungeTask(); @VisibleForTesting BazelExpungeTask(BazelExecHelper bazelExecHelper); @Override void setBazelConfig(BazelLeafConfig.Decorated config); }### Answer:
@Test public void testTask() throws Exception { Project project = TestUtils.createConfiguredAppliedProject(); TestableBazelExpungeTask bazelExpunge = project.getTasks().create("bazelExpunge", TestableBazelExpungeTask.class); BazelLeafConfig.Decorated config = new BazelLeafConfig.Decorated( "bazelBin", "targetPath", "targetName", "testTargetName", new File("workspaceDir"), "outputDir" ); bazelExpunge.setBazelConfig(config); bazelExpunge.bazelExec(); verify(bazelExpunge.getMockBazelExecHelper()).createBazelRun(true, config, "", "clean", "--expunge"); verify(bazelExpunge.mockBazelExec).start(); assertThat(bazelExpunge.getDescription(), IsEqual .equalTo("Cleans and expunges Bazel workspace")); assertThat(bazelExpunge.getGroup(), IsEqual.equalTo(BasePlugin.BUILD_GROUP)); } |
### Question:
DownloadBazelTask extends DefaultTask { @TaskAction public void download() throws IOException { if (mTargetFile == null) { throw new NullPointerException("targetFile needs to be set!"); } if (mDownloadUrl == null) { throw new NullPointerException("downloadUrl needs to be set!"); } File canonicalFileTargetFile = mTargetFile.getCanonicalFile(); if (canonicalFileTargetFile.getParentFile() == null || ( !canonicalFileTargetFile.getParentFile().exists() && !canonicalFileTargetFile .getParentFile().mkdirs())) { throw new IOException( "Failed to create parent folder for " + canonicalFileTargetFile.getAbsolutePath()); } try { final Download downloader = new Download( new DownloadProgressLogger(mDownloadUrl, canonicalFileTargetFile.getAbsolutePath()), "bazel-leaf", "0.0.1"); downloader.download(URI.create(mDownloadUrl), canonicalFileTargetFile); getAnt().invokeMethod("chmod", map( "file", canonicalFileTargetFile, "perm", "+x")); } catch (Exception e) { throw new RuntimeException("Failed to download Bazel to " + canonicalFileTargetFile + "! This could be a target path issue.", e); } } static DownloadBazelTask injectDownloadTask(Project project, String pathToBazelBin); @Input File getTargetFile(); void setTargetFile(File targetFile); @Input String getDownloadUrl(); void setDownloadUrl(String downloadUrl); @TaskAction void download(); }### Answer:
@Test public void testMissingTargetFileArgument() throws Exception { Project project = TestUtils.createConfiguredAppliedProject(); DownloadBazelTask downloadBazel = project.getTasks().create("downloadBazel", DownloadBazelTask.class); try { downloadBazel.download(); fail(); } catch (NullPointerException e) { assertThat(e.getMessage(), IsEqual.equalTo("targetFile needs to be set!")); } } |
### Question:
DownloadBazelTask extends DefaultTask { public static DownloadBazelTask injectDownloadTask(Project project, String pathToBazelBin) { Project rootProject = project.getRootProject(); if (rootProject.getTasks().findByName(DOWNLOAD_TASK_NAME) == null) { final Object urlPropertyName; switch (SystemEnvironment.getOsType()) { case macOs: urlPropertyName = rootProject.getProperties().get("bazel.bin.url.macos"); break; case Windows: urlPropertyName = rootProject.getProperties().get("bazel.bin.url.windows"); break; default: urlPropertyName = rootProject.getProperties().get("bazel.bin.url.linux"); } return injectTask(rootProject, urlPropertyName, pathToBazelBin); } return null; } static DownloadBazelTask injectDownloadTask(Project project, String pathToBazelBin); @Input File getTargetFile(); void setTargetFile(File targetFile); @Input String getDownloadUrl(); void setDownloadUrl(String downloadUrl); @TaskAction void download(); }### Answer:
@Test public void testDownloadUrlDoesntExistsForOs() throws Exception { Project project = TestUtils.createConfiguredAppliedProject(); System.setProperty("os.name", "mac"); project.getExtensions().getExtraProperties().set("bazel.bin.url.macos", null); Exception caughtException = null; try { DownloadBazelTask.injectDownloadTask(project, "bazelBin"); } catch (Exception e) { caughtException = e; } assertNotNull(caughtException); assertTrue(caughtException instanceof IllegalArgumentException); assertTrue(caughtException.getMessage().contains("The URL property to download Bazel is invalid")); } |
### Question:
MacroIfLogic { private static boolean include(Object value, String valueStr, String compare, String type) { if (value == null) { return false; } String compareLow = compare.toLowerCase(); if (value instanceof String) { return valueStr.toLowerCase().contains(compareLow); } if (value.getClass().isArray()) { Object[] values = CollectionUtil.convertArray(value); for (Object var : values) { if (compareLow.equals((var == null) ? null : var.toString().toLowerCase())) { return true; } } } if (value instanceof Collection) { Iterator iter = ((Collection) value).iterator(); Object var; while (iter.hasNext()) { var = iter.next(); if (compareLow.equals((var == null) ? null : var.toString().toLowerCase())) { return true; } } } return false; } static boolean evalLogic(String sql, List paramValues, int preCount, int logicParamCnt); }### Answer:
@Test public void testInclude() { String sql="size(:statusAry) >=4"; List params=new ArrayList(); params.add(new Object[] {1,2}); boolean result=MacroIfLogic.evalLogic(sql, params, 0, 1); assertEquals(result,true); } |
### Question:
AsmUtil { static String getDescriptor(final Constructor c) { StringBuilder buf = new StringBuilder(); buf.append('('); for (Class<?> paramType : c.getParameterTypes()) { buf.append(getDescriptor(paramType)); } return buf.append(")V").toString(); } private AsmUtil(); }### Answer:
@Test void getDescriptor() { assertEquals("I", AsmUtil.getDescriptor(int.class)); assertEquals("J", AsmUtil.getDescriptor(long.class)); assertEquals("Z", AsmUtil.getDescriptor(boolean.class)); assertEquals("B", AsmUtil.getDescriptor(byte.class)); assertEquals("C", AsmUtil.getDescriptor(char.class)); assertEquals("Ljava/lang/Integer;", AsmUtil.getDescriptor(Integer.class)); assertEquals("Ljava/lang/String;", AsmUtil.getDescriptor(String.class)); assertEquals("Ljava/util/Map;", AsmUtil.getDescriptor(Map.class)); assertEquals("[I", AsmUtil.getDescriptor(int[].class)); assertEquals("[[I", AsmUtil.getDescriptor(int[][].class)); assertEquals("[[[I", AsmUtil.getDescriptor(int[][][].class)); assertEquals("[Ljava/lang/Integer;", AsmUtil.getDescriptor(Integer[].class)); assertEquals("[[Ljava/lang/Integer;", AsmUtil.getDescriptor(Integer[][].class)); assertEquals("[[[Ljava/lang/Integer;", AsmUtil.getDescriptor(Integer[][][].class)); } |
### Question:
FieldInfoResolver { static String cutFieldName(final String string, final int from) { final int nextIndex = from + 1; final int len = string.length(); if (len > nextIndex) { char c = string.charAt(nextIndex); if (c >= 'A' && c <= 'Z') { return string.substring(from); } } char[] buffer = new char[len - from]; string.getChars(from, len, buffer, 0); char c = buffer[0]; if (c >= 'A' && c <= 'Z') { buffer[0] = (char) (c + 0x20); } return new String(buffer); } private FieldInfoResolver(Class<?> beanClass); static Stream<FieldInfo> resolve(Class<?> beanClass); }### Answer:
@Test void cutFieldNameTest() { assertEquals("a", FieldInfoResolver.cutFieldName("getA", 3)); assertEquals("ab", FieldInfoResolver.cutFieldName("getAb", 3)); assertEquals("AB", FieldInfoResolver.cutFieldName("getAB", 3)); assertEquals("ABc", FieldInfoResolver.cutFieldName("getABc", 3)); assertEquals("ABC", FieldInfoResolver.cutFieldName("getABC", 3)); assertEquals("aB", FieldInfoResolver.cutFieldName("getaB", 3)); } |
### Question:
AsmUtil { static String getInternalName(String className) { int i = className.indexOf('.'); if (i < 0) { return className; } char[] str = className.toCharArray(); int len = str.length; for (; i < len; i++) { if (str[i] == '.') { str[i] = '/'; } } return new String(str); } private AsmUtil(); }### Answer:
@Test void getInternalName() { assertEquals("java/lang/Integer", getInternalName(Integer.class)); assertEquals("java/lang/String", getInternalName(String.class)); assertEquals("java/util/Map", getInternalName(Map.class)); assertEquals("int", getInternalName(int.class)); assertEquals("boolean", getInternalName(boolean.class)); assertEquals("void", getInternalName(Void.TYPE)); assertEquals("java/lang/Void", getInternalName(Void.class)); assertEquals("[I", getInternalName(int[].class)); assertEquals("[[I", getInternalName(int[][].class)); assertEquals("[[[I", getInternalName(int[][][].class)); assertEquals("[Ljava/lang/Integer;", getInternalName(Integer[].class)); assertEquals("[[Ljava/lang/Integer;", getInternalName(Integer[][].class)); assertEquals("[[[Ljava/lang/Integer;", getInternalName(Integer[][][].class)); } |
### Question:
AsmUtil { static String getBoxedInternalName(Class<?> type) { return getInternalName(type.isPrimitive() ? ClassUtil.getBoxedPrimitiveClass(type).getName() : type.getName()); } private AsmUtil(); }### Answer:
@Test void test_getBoxedInternalName() { assertEquals("java/lang/Integer", AsmUtil.getBoxedInternalName(Integer.class)); assertEquals("java/lang/String", AsmUtil.getBoxedInternalName(String.class)); assertEquals("java/util/Map", AsmUtil.getBoxedInternalName(Map.class)); assertEquals("java/lang/Integer", AsmUtil.getBoxedInternalName(int.class)); assertEquals("java/lang/Boolean", AsmUtil.getBoxedInternalName(boolean.class)); assertEquals("java/lang/Void", AsmUtil.getBoxedInternalName(Void.TYPE)); assertEquals("java/lang/Void", AsmUtil.getBoxedInternalName(Void.class)); assertEquals("[I", AsmUtil.getBoxedInternalName(int[].class)); assertEquals("[[I", AsmUtil.getBoxedInternalName(int[][].class)); assertEquals("[[[I", AsmUtil.getBoxedInternalName(int[][][].class)); } |
### Question:
WorkerService implements WorkerServiceI { @Override public Worker findWorkerByLogin(String login) throws BaseException { Worker worker = workerRepository.findWorkerByLogin(login); if (worker == null) { throw new WorkerDontExistsException("Issued worker dont exists"); } return worker; } @Inject WorkerService(WorkerRepositoryI workerRepository); @Override Worker createWorker(Worker worker); @Override Worker editWorker(String login, Worker editedWorker); @Override Worker deleteWorker(String login); @Override Worker findWorkerByLogin(String login); }### Answer:
@Test public void findWorker_Success() { try { Worker result = workerService.findWorkerByLogin(EXISTING_LOGIN); assertEquals(EXISTING_LOGIN, result.getLogin()); assertEquals(NAME, result.getName()); assertEquals(SURNAME, result.getSurname()); assertEquals(EMAIL, result.getEmail()); } catch (Exception e) { fail(String.format("Error in deleting worker: %s", e.getMessage())); } }
@Test(expected = WorkerDontExistsException.class) public void findWorker_WorkerDontExist() throws BaseException { workerService.findWorkerByLogin(NON_EXISTING_LOGIN); } |
### Question:
WorkLogService implements WorkLogServiceI { @Override public WorkLog deleteWorkLog(Long workLogId) throws BaseException { WorkLog workLog = workLogRepository.findWorkLogById(workLogId); if (workLog == null) { throw new WorkLogDontExistException("Deleting work log dont exists"); } return workLogRepository.deleteWorkLog(workLog); } @Inject WorkLogService(WorkLogRepositoryI workLogRepository, WorkerRepositoryI workerRepository); @Override WorkLog logWork(WorkLog workLog); @Override WorkLog editWorkLog(Long id, WorkLog workLog); @Override WorkLog deleteWorkLog(Long workLogId); @Override List<WorkLog> reportWorkerWork(Worker worker); @Override WorkLog findWorkLogById(Long id); }### Answer:
@Test public void deleteWorkLog_Success() throws BaseException { WorkLog existingWorkLog = getWorkLogRepositoryStub().getWorkLogList().stream().findAny().get(); WorkLog result = workLogService.deleteWorkLog(1l); assertEquals(existingWorkLog.getWorkLogId(), result.getWorkLogId()); assertEquals(existingWorkLog.getDescription(), result.getDescription()); assertEquals(existingWorkLog.getStartDate(), result.getStartDate()); assertEquals(existingWorkLog.getTimeSpentInSeconds(), result.getTimeSpentInSeconds()); assertEquals(existingWorkLog.getAssociatedWorker().getLogin(), result.getAssociatedWorker().getLogin()); assertTrue(getWorkLogRepositoryStub().getWorkLogList().isEmpty()); }
@Test(expected = WorkLogDontExistException.class) public void deleteWorkLog_WorkLogDontExist() throws BaseException { workLogService.deleteWorkLog(2l); } |
### Question:
WorkLogService implements WorkLogServiceI { @Override public WorkLog findWorkLogById(Long id) throws BaseException { WorkLog workLog = workLogRepository.findWorkLogById(id); if (workLog == null) { throw new WorkLogDontExistException("Deleting work log dont exists"); } return workLog; } @Inject WorkLogService(WorkLogRepositoryI workLogRepository, WorkerRepositoryI workerRepository); @Override WorkLog logWork(WorkLog workLog); @Override WorkLog editWorkLog(Long id, WorkLog workLog); @Override WorkLog deleteWorkLog(Long workLogId); @Override List<WorkLog> reportWorkerWork(Worker worker); @Override WorkLog findWorkLogById(Long id); }### Answer:
@Test public void findWorkLogById_Success() throws BaseException { WorkLog existingWorkLog = getWorkLogRepositoryStub().getWorkLogList().stream().findAny().get(); WorkLog result = workLogService.findWorkLogById(1l); assertEquals(existingWorkLog.getWorkLogId(), result.getWorkLogId()); assertEquals(existingWorkLog.getDescription(), result.getDescription()); assertEquals(existingWorkLog.getStartDate(), result.getStartDate()); assertEquals(existingWorkLog.getTimeSpentInSeconds(), result.getTimeSpentInSeconds()); assertEquals(existingWorkLog.getAssociatedWorker().getLogin(), result.getAssociatedWorker().getLogin()); assertEquals(1, getWorkLogRepositoryStub().getWorkLogList().size()); }
@Test(expected = WorkLogDontExistException.class) public void findWorkLogById_WorkLogDontExist() throws BaseException { workLogService.findWorkLogById(2l); } |
### Question:
WorkLogService implements WorkLogServiceI { @Override public List<WorkLog> reportWorkerWork(Worker worker) { return workLogRepository.findWorkLogsByWorker(worker); } @Inject WorkLogService(WorkLogRepositoryI workLogRepository, WorkerRepositoryI workerRepository); @Override WorkLog logWork(WorkLog workLog); @Override WorkLog editWorkLog(Long id, WorkLog workLog); @Override WorkLog deleteWorkLog(Long workLogId); @Override List<WorkLog> reportWorkerWork(Worker worker); @Override WorkLog findWorkLogById(Long id); }### Answer:
@Test public void reportWorkerWorkLogs_Success() throws BaseException { WorkLog existingWorkLog = getWorkLogRepositoryStub().getWorkLogList().stream().findAny().get(); List<WorkLog> resultList = workLogService.reportWorkerWork(exisitngWorker()); assertEquals(1, resultList.size()); WorkLog result = resultList.get(0); assertEquals(existingWorkLog.getWorkLogId(), result.getWorkLogId()); assertEquals(existingWorkLog.getDescription(), result.getDescription()); assertEquals(existingWorkLog.getStartDate(), result.getStartDate()); assertEquals(existingWorkLog.getTimeSpentInSeconds(), result.getTimeSpentInSeconds()); assertEquals(existingWorkLog.getAssociatedWorker().getLogin(), result.getAssociatedWorker().getLogin()); assertEquals(1, getWorkLogRepositoryStub().getWorkLogList().size()); }
@Test public void reportWorkerWorkLogs_NoWorkLogs() throws BaseException { List<WorkLog> resultList = workLogService.reportWorkerWork(nonExisitngWorker()); assertTrue(resultList.isEmpty()); } |
### Question:
WorkerService implements WorkerServiceI { @Override public Worker createWorker(Worker worker) throws BaseException { if (workerRepository.findWorkerByLogin(worker.getLogin()) != null) { throw new WorkerExistsException("Worker already exists"); } return workerRepository.saveWorker(worker); } @Inject WorkerService(WorkerRepositoryI workerRepository); @Override Worker createWorker(Worker worker); @Override Worker editWorker(String login, Worker editedWorker); @Override Worker deleteWorker(String login); @Override Worker findWorkerByLogin(String login); }### Answer:
@Test public void createWorker_Success() { try { Worker newWorker = nonExisitngWorker(); Worker result = workerService.createWorker(newWorker); assertEquals(newWorker.getLogin(), result.getLogin()); assertEquals(newWorker.getName(), result.getName()); assertEquals(newWorker.getSurname(), result.getSurname()); assertEquals(newWorker.getEmail(), result.getEmail()); assertEquals(2, getWorkerRepositoryStub().getWorkerList().size()); } catch (Exception e) { fail(String.format("Error in creating worker: %s", e.getMessage())); } }
@Test(expected = WorkerExistsException.class) public void createWorker_WorkerExist() throws BaseException { workerService.createWorker(exisitngWorker()); } |
### Question:
WorkerService implements WorkerServiceI { @Override public Worker editWorker(String login, Worker editedWorker) throws BaseException { Worker worker = workerRepository.findWorkerByLogin(login); if (worker == null) { throw new WorkerDontExistsException("Edited worker dont exists"); } return workerRepository.updateWorker(new Worker(login, editedWorker.getName(), editedWorker.getSurname(), editedWorker.getEmail())); } @Inject WorkerService(WorkerRepositoryI workerRepository); @Override Worker createWorker(Worker worker); @Override Worker editWorker(String login, Worker editedWorker); @Override Worker deleteWorker(String login); @Override Worker findWorkerByLogin(String login); }### Answer:
@Test public void editWorker_Success() { try { Worker editedWorker = nonExisitngWorker(); Worker result = workerService.editWorker(EXISTING_LOGIN, editedWorker); assertEquals(EXISTING_LOGIN, result.getLogin()); assertEquals(OTHER_NAME, result.getName()); assertEquals(OTHER_SURNAME, result.getSurname()); assertEquals(OTHER_EMAIL, result.getEmail()); assertEquals(1, getWorkerRepositoryStub().getWorkerList().size()); } catch (Exception e) { fail(String.format("Error in editing worker: %s", e.getMessage())); } }
@Test(expected = WorkerDontExistsException.class) public void editWorker_WorkerDontExist() throws BaseException { workerService.editWorker(NON_EXISTING_LOGIN, null); } |
### Question:
WorkerService implements WorkerServiceI { @Override public Worker deleteWorker(String login) throws BaseException { Worker worker = workerRepository.findWorkerByLogin(login); if (worker == null) { throw new WorkerDontExistsException("Issued worker dont exists"); } return workerRepository.deleteWorker(worker); } @Inject WorkerService(WorkerRepositoryI workerRepository); @Override Worker createWorker(Worker worker); @Override Worker editWorker(String login, Worker editedWorker); @Override Worker deleteWorker(String login); @Override Worker findWorkerByLogin(String login); }### Answer:
@Test public void deleteWorker_Success() { try { Worker result = workerService.deleteWorker(EXISTING_LOGIN); assertEquals(EXISTING_LOGIN, result.getLogin()); assertEquals(NAME, result.getName()); assertEquals(SURNAME, result.getSurname()); assertEquals(EMAIL, result.getEmail()); assertTrue(getWorkerRepositoryStub().getWorkerList().isEmpty()); } catch (Exception e) { fail(String.format("Error in deleting worker: %s", e.getMessage())); } }
@Test(expected = WorkerDontExistsException.class) public void deleteWorker_WorkerDontExist() throws BaseException { workerService.deleteWorker(NON_EXISTING_LOGIN); } |
### Question:
RetryStrategy implements Function<Flowable<Throwable>, Flowable<?>> { public static Builder onlyIf(Predicate<Throwable> predicate) { return new Builder(predicate); } RetryStrategy(Builder builder); @Override Flowable<?> apply(Flowable<Throwable> errors); static Builder always(); @SafeVarargs @SuppressWarnings("varargs") static Builder ifInstanceOf(Class<? extends Throwable>... classes); static Builder onlyIf(Predicate<Throwable> predicate); }### Answer:
@Test void testOnlyIf() throws Exception { errorSource(2) .retryWhen( RetryStrategy.onlyIf( e -> e instanceof RuntimeException && "Error #1".equals(e.getMessage())) .build()) .test() .await() .assertError(RuntimeException.class) .assertErrorMessage("Error #2"); errorSource(1) .retryWhen(RetryStrategy.onlyIf(e -> e instanceof Error).build()) .test() .await() .assertError(RuntimeException.class) .assertErrorMessage("Error #1"); } |
### Question:
DistroProperties extends BaseSdkProperties { public void resolvePlaceholders(Properties projectProperties){ for(Map.Entry<Object, Object> property: properties.entrySet()){ if(hasPlaceholder(property.getValue())){ try{ Object placeholderValue = projectProperties.get(getPlaceholderKey((String)property.getValue())); if(placeholderValue == null){ throw new IllegalArgumentException("Failed to resolve property placeholders in distro file, no property for key: "+property.getKey()); } else { property.setValue(putInPlaceholder((String)property.getValue(), (String)placeholderValue)); } } catch(ClassCastException e){ throw new IllegalArgumentException("Property with key "+property.getKey()+" and value "+property.getValue()+"is not placeholder."); } } } } DistroProperties(String version); DistroProperties(String name, String version); DistroProperties(Properties properties); DistroProperties(File file); boolean isH2Supported(); void setH2Support(boolean supported); String getSqlScriptPath(); String getPropertyPromt(String propertyName); String getPropertyDefault(String propertyName); String getPropertyValue(String propertyName); Set<String> getPropertiesNames(); Artifact getDistroArtifact(); List<Artifact> getModuleArtifacts(DistroHelper distroHelper, File directory); List<Artifact> getOwaArtifacts(DistroHelper distroHelper, File directory); List<Artifact> getWarArtifacts(DistroHelper distroHelper, File directory); String getPlatformVersion(DistroHelper distroHelper, File directory); void saveTo(File path); void resolvePlaceholders(Properties projectProperties); static final String PROPERTY_PROMPT_KEY; static final String DISTRO_FILE_NAME; static final String PROPERTY_DEFAULT_VALUE_KEY; static final String PROPERTY_KEY; }### Answer:
@Test(expected = IllegalArgumentException.class) public void resolvePlaceholders_shouldFailIfNoPropertyForPlaceholderFound(){ Properties properties = new Properties(); properties.setProperty("omod.fails", "${failsVersion}"); DistroProperties distro = new DistroProperties(properties); distro.resolvePlaceholders(getProjectProperties()); } |
### Question:
VersionsHelper { public String getLatestReleasedVersion(Artifact artifact){ return getLatestReleasedVersion(getVersions(artifact)); } VersionsHelper(ArtifactFactory artifactFactory, MavenProject mavenProject, MavenSession mavenSession, ArtifactMetadataSource artifactMetadataSource); String getLatestReleasedVersion(Artifact artifact); String getLatestSnapshotVersion(Artifact artifact); String getLatestSnapshotVersion(List<ArtifactVersion> versions); String getLatestReleasedVersion(List<ArtifactVersion> versions); List<String> getVersionAdvice(Artifact artifact, int maxReleases); List<String> getVersionAdvice(List<ArtifactVersion> allVersions, int maxSize); }### Answer:
@Test public void getLatestReleasedVersion_shouldNotIncludeSnapshots(){ String res = helper.getLatestReleasedVersion( createTestVersions("1.8.8", "1.8.3", "1.8.10-SNAPSHOT", "1.8.9-alpha")); assertThat(res, is(equalTo("1.8.8"))); } |
### Question:
VersionsHelper { public String getLatestSnapshotVersion(Artifact artifact) { return getLatestSnapshotVersion(getVersions(artifact)); } VersionsHelper(ArtifactFactory artifactFactory, MavenProject mavenProject, MavenSession mavenSession, ArtifactMetadataSource artifactMetadataSource); String getLatestReleasedVersion(Artifact artifact); String getLatestSnapshotVersion(Artifact artifact); String getLatestSnapshotVersion(List<ArtifactVersion> versions); String getLatestReleasedVersion(List<ArtifactVersion> versions); List<String> getVersionAdvice(Artifact artifact, int maxReleases); List<String> getVersionAdvice(List<ArtifactVersion> allVersions, int maxSize); }### Answer:
@Test public void getLatestSnapshotVersion_shouldReturnLatestSnapshot(){ String res = helper.getLatestSnapshotVersion( createTestVersions("1.8.8", "1.8.3", "1.8.10-SNAPSHOT", "1.8.9-alpha")); assertThat(res, is(equalTo("1.8.10-SNAPSHOT"))); } |
### Question:
ExchangeBasedCurrencyValue extends CurrencyValue { static public CurrencyValue fromValue(CurrencyValue currencyValue, String targetCurrency, ExchangeRateProvider exchangeRateManager) { if (currencyValue instanceof ExchangeBasedCurrencyValue) { return fromValue((ExchangeBasedCurrencyValue) currencyValue, targetCurrency, exchangeRateManager); } else if (currencyValue instanceof ExactCurrencyValue) { return fromValue((ExactCurrencyValue) currencyValue, targetCurrency, exchangeRateManager); } else { throw new RuntimeException("Unable to convert from currency value " + currencyValue.getClass().toString()); } } protected ExchangeBasedCurrencyValue(String currency, ExactCurrencyValue basedOnExactValue); static CurrencyValue fromValue(CurrencyValue currencyValue, String targetCurrency, ExchangeRateProvider exchangeRateManager); static CurrencyValue fromValue(ExchangeBasedCurrencyValue currencyValue, String targetCurrency, ExchangeRateProvider exchangeRateManager); static CurrencyValue fromValue(ExactCurrencyValue currencyValue, String targetCurrency, ExchangeRateProvider exchangeRateManager); static CurrencyValue from(BigDecimal value, String currency); static CurrencyValue convertFromValue(ExchangeBasedCurrencyValue value, String targetCurrency, ExchangeRateProvider exchangeRateManager); static CurrencyValue fromExactValue(ExactCurrencyValue exactValue, String targetCurrency, ExchangeRateProvider exchangeRateManager); @Override String getCurrency(); @Override boolean hasExactValue(); @Override ExactCurrencyValue getExactValue(); }### Answer:
@Test public void testFromValue() throws Exception { } |
### Question:
ExchangeBasedCurrencyValue extends CurrencyValue { static public CurrencyValue from(BigDecimal value, String currency) { if (currency.equals(CurrencyValue.BTC)) { return new ExchangeBasedBitcoinValue(currency, value); } else { return new ExchangeBasedFiatValue(currency, value); } } protected ExchangeBasedCurrencyValue(String currency, ExactCurrencyValue basedOnExactValue); static CurrencyValue fromValue(CurrencyValue currencyValue, String targetCurrency, ExchangeRateProvider exchangeRateManager); static CurrencyValue fromValue(ExchangeBasedCurrencyValue currencyValue, String targetCurrency, ExchangeRateProvider exchangeRateManager); static CurrencyValue fromValue(ExactCurrencyValue currencyValue, String targetCurrency, ExchangeRateProvider exchangeRateManager); static CurrencyValue from(BigDecimal value, String currency); static CurrencyValue convertFromValue(ExchangeBasedCurrencyValue value, String targetCurrency, ExchangeRateProvider exchangeRateManager); static CurrencyValue fromExactValue(ExactCurrencyValue exactValue, String targetCurrency, ExchangeRateProvider exchangeRateManager); @Override String getCurrency(); @Override boolean hasExactValue(); @Override ExactCurrencyValue getExactValue(); }### Answer:
@Test public void testFrom() throws Exception { } |
### Question:
GoogleMapsGeocoder extends Geocoder { @Override public GeocodeResponse query(String address, int maxResults) throws RemoteGeocodeException { final String encodedAddress; try { encodedAddress = URLEncoder.encode(address, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } String transportAgnosticUrl = "maps.googleapis.com/maps/api/geocode/json?address=" + encodedAddress + "&sensor=true&language=" + language; InputStream inputData = openStream(transportAgnosticUrl); GeocodeResponse res = null; try { res = response2Graph(inputData); } catch (RemoteGeocodeException e) { throw new RemoteGeocodeException(transportAgnosticUrl, e.status); } if (maxResults == -1) { return res; } else { return sizeLimited(res, maxResults); } } GoogleMapsGeocoder(String language); GoogleMapsGeocoder(String language, boolean forceHttps); @Override GeocodeResponse query(String address, int maxResults); @Override GeocodeResponse getFromLocation(double latitude, double longitude); GeocodeResponse response2Graph(InputStream apply); }### Answer:
@Test @Ignore public void testRemoteCoding() throws IOException, RemoteGeocodeException { GeocodeResponse response = new GoogleMapsGeocoder("en").query("Ungargasse 6 1030 Wien", -1); assertEquals("Ungargasse 6, 1030 Wien, Austria", response.results.get(0).formattedAddress); }
@Test @Ignore public void testRemoteCodingGerman() throws IOException, RemoteGeocodeException { GeocodeResponse response = new GoogleMapsGeocoder("de").query("Ungargasse 6 1030 Wien", -1); assertEquals("Ungargasse 6, 1030 Wien, Österreich", response.results.get(0).formattedAddress); } |
### Question:
GoogleMapsGeocoder extends Geocoder { public GeocodeResponse response2Graph(InputStream apply) throws RemoteGeocodeException { ObjectMapper mapper = new ObjectMapper(); mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); final GeocodeResponse graph; try { graph = Preconditions.checkNotNull(mapper.readValue(apply, GeocodeResponse.class)); apply.close(); } catch (IOException e) { throw new RuntimeException("error parsing response from ", e); } if (!isValidStatus(graph.status)) { throw new RemoteGeocodeException("an error occurred while querying", graph.status, graph.errorMessage); } return graph; } GoogleMapsGeocoder(String language); GoogleMapsGeocoder(String language, boolean forceHttps); @Override GeocodeResponse query(String address, int maxResults); @Override GeocodeResponse getFromLocation(double latitude, double longitude); GeocodeResponse response2Graph(InputStream apply); }### Answer:
@Test public void testCoding() throws IOException, RemoteGeocodeException { final InputStream stream = Preconditions.checkNotNull(getClass().getResourceAsStream("/ungargasse.json")); GeocodeResponse response = new GoogleMapsGeocoder("en").response2Graph(stream); assertEquals("Ungargasse 6, 1030 Vienna, Austria", response.results.get(0).formattedAddress); }
@Test public void testPostcode() throws IOException, RemoteGeocodeException { final InputStream stream = Preconditions.checkNotNull(getClass().getResourceAsStream("/exampleWithPostcode.json")); new GoogleMapsGeocoder("en").response2Graph(stream); } |
### Question:
Hmac { public static byte[] hmacSha512(byte[] key, byte[] message) { MessageDigest digest; try { digest = MessageDigest.getInstance(SHA512); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } return hmac(digest, SHA512_BLOCK_SIZE, key, message); } static byte[] hmacSha256(byte[] key, byte[] message); static byte[] hmacSha512(byte[] key, byte[] message); static boolean testTestVectors(); }### Answer:
@Test public void hmacSha512Test() throws InterruptedException { assertTrue(Arrays.equals(TEST_1_RESULT, Hmac.hmacSha512(TEST_1_KEY, TEST_1_DATA))); assertTrue(Arrays.equals(TEST_2_RESULT, Hmac.hmacSha512(TEST_2_KEY, TEST_2_DATA))); assertTrue(Arrays.equals(TEST_3_RESULT, Hmac.hmacSha512(TEST_3_KEY, TEST_3_DATA))); } |
### Question:
Ecdh { public static byte[] calculateSharedSecret(PublicKey foreignPublicKey, InMemoryPrivateKey privateKey) { Point P = calculateSharedSecretPoint(foreignPublicKey, privateKey); BigInteger Px = P.getX().toBigInteger(); byte[] bytes = EcTools.integerToBytes(Px, SECRET_LENGTH); return HashUtils.sha256(bytes).getBytes(); } static byte[] calculateSharedSecret(PublicKey foreignPublicKey, InMemoryPrivateKey privateKey); static final int SECRET_LENGTH; }### Answer:
@Test public void sharedSecretTest() { InMemoryPrivateKey myPrv = new InMemoryPrivateKey(PRIVATE_KEY_1, NetworkParameters.productionNetwork); InMemoryPrivateKey foreignPrv = new InMemoryPrivateKey(PRIVATE_KEY_2, NetworkParameters.productionNetwork); byte[] mySecret = Ecdh.calculateSharedSecret(foreignPrv.getPublicKey(), myPrv); byte[] foreignerSecret = Ecdh.calculateSharedSecret(myPrv.getPublicKey(), foreignPrv); assertTrue(BitUtils.areEqual(mySecret, foreignerSecret)); assertEquals(HexUtils.toHex(mySecret), SECRET); } |
### Question:
Address implements Serializable, Comparable<Address> { @Override public String toString() { if (_address == null) { byte[] addressBytes = new byte[1 + 20 + 4]; addressBytes[0] = _bytes[0]; System.arraycopy(_bytes, 0, addressBytes, 0, NUM_ADDRESS_BYTES); Sha256Hash checkSum = HashUtils.doubleSha256(addressBytes, 0, NUM_ADDRESS_BYTES); System.arraycopy(checkSum.getBytes(), 0, addressBytes, NUM_ADDRESS_BYTES, 4); _address = Base58.encode(addressBytes); } return _address; } Address(byte[] bytes); Address(byte[] bytes, String stringAddress); static Collection<Address> fromStrings(Collection<String> addresses, NetworkParameters network); static Address[] fromStrings(String[] addressStrings); static String[] toStrings(Address[] addresses); static Address fromString(String address, NetworkParameters network); static Address fromString(String address); static Address fromP2SHBytes(byte[] bytes, NetworkParameters network); static Address fromStandardBytes(byte[] bytes, NetworkParameters network); boolean isValidAddress(NetworkParameters network); boolean isMultisig(NetworkParameters network); byte getVersion(); byte[] getAllAddressBytes(); byte[] getTypeSpecificBytes(); @Override String toString(); String getShortAddress(); String getShortAddress(int showChars); @Override int hashCode(); @Override boolean equals(Object obj); static Address getNullAddress(NetworkParameters network); @Override int compareTo(Address other); String toMultiLineString(); String toDoubleLineString(); NetworkParameters getNetwork(); static final int NUM_ADDRESS_BYTES; static final Function<? super String,Address> FROM_STRING; }### Answer:
@Test public void toStringTest() { InMemoryPrivateKey priv = new InMemoryPrivateKey(RANDOM_SOURCE); PublicKey pub = priv.getPublicKey(); Address addr = pub.toAddress(NetworkParameters.productionNetwork); System.out.println(addr.toString()); } |
### Question:
ScriptOutputOpReturn extends ScriptOutput implements Serializable { protected static boolean isScriptOutputOpReturn(byte[][] chunks) { return chunks.length == 2 && Script.isOP(chunks[0], OP_RETURN) && chunks[1] != null && chunks[1].length > 0; } protected ScriptOutputOpReturn(byte[][] chunks, byte[] scriptBytes); byte[] getDataBytes(); @Override Address getAddress(NetworkParameters network); }### Answer:
@Test public void isScriptOutputOpReturnTest() throws Exception { byte[][] chunks = new byte[2][]; chunks[0]=new byte[]{OP_RETURN}; assertFalse(isScriptOutputOpReturn(chunks)); assertTrue(isScriptOutputOpReturn(new byte[][]{{OP_RETURN}, "Hallotest".getBytes()})); assertFalse(isScriptOutputOpReturn(new byte[][]{{OP_RETURN}, null})); assertFalse(isScriptOutputOpReturn(new byte[][]{{OP_RETURN}, "".getBytes()})); assertFalse(isScriptOutputOpReturn(new byte[][]{null, "Hallo".getBytes()})); } |
### Question:
StandardTransactionBuilder { public static List<byte[]> generateSignatures(SigningRequest[] requests, IPrivateKeyRing keyRing) { List<byte[]> signatures = new LinkedList<>(); for (SigningRequest request : requests) { BitcoinSigner signer = keyRing.findSignerByPublicKey(request.publicKey); if (signer == null) { throw new RuntimeException("Private key not found"); } byte[] signature = signer.makeStandardBitcoinSignature(request.toSign); signatures.add(signature); } return signatures; } StandardTransactionBuilder(NetworkParameters network); void addOutput(Address sendTo, long value); void addOutput(TransactionOutput output); void addOutputs(OutputList outputs); static TransactionOutput createOutput(Address sendTo, long value, NetworkParameters network); static List<byte[]> generateSignatures(SigningRequest[] requests, IPrivateKeyRing keyRing); UnsignedTransaction createUnsignedTransaction(Collection<UnspentTransactionOutput> inventory,
Address changeAddress, IPublicKeyRing keyRing,
NetworkParameters network, long minerFeeToUse); static Transaction finalizeTransaction(UnsignedTransaction unsigned, List<byte[]> signatures); static int estimateTransactionSize(int inputs, int outputs); static long estimateFee(int inputs, int outputs, long minerFeePerKb); static final int MAX_INPUT_SIZE; }### Answer:
@Test(timeout=500) @Ignore("This is not really a requirement but was meant to show the supperior performance of bitcoinJ") public void generateSignaturesBitlib() throws Exception { List<SigningRequest> requests = new ArrayList<>(); for(int i = 0; i<30; i++) { requests.add(new SigningRequest(PUBLIC_KEYS[i % COUNT], HashUtils.sha256(("bla" + i).getBytes()))); } StandardTransactionBuilder.generateSignatures(requests.toArray(new SigningRequest[]{}), PRIVATE_KEY_RING); } |
### Question:
ColuTransferInstructionsParser { static int getAmountTotalBytesSFFC(byte flagByte) { for(byte ssfcFlagByte : SFFC_FLAG_BYTES_MAP.keySet()) { if(flagByte == ssfcFlagByte) { return SFFC_FLAG_BYTES_MAP.get(ssfcFlagByte); } } return 1; } ColuTransferInstructionsParser(WapiLogger logger); boolean isValidColuScript(byte []scriptBytes); List<Integer> retrieveOutputIndexesFromScript(byte []scriptBytes); static final int SCRIPTBYTES_MIN_SIZE; }### Answer:
@Test public void getAmountTotalBytesSFFC() throws Exception { for (byte b: ColuTransferInstructionsParser.SFFC_FLAG_BYTES_MAP.keySet()) { assertEquals((int)ColuTransferInstructionsParser.SFFC_FLAG_BYTES_MAP.get(b), ColuTransferInstructionsParser.getAmountTotalBytesSFFC(b)); } } |
### Question:
CurrencySum { public synchronized CurrencyValue getSumAsCurrency(String targetCurrency, ExchangeRateProvider exchangeRateProvider) { CurrencyValue sum = ExactCurrencyValue.from(BigDecimal.ZERO, targetCurrency); for (Map.Entry<String, CurrencyValue> value : buckets.entrySet()) { if (value.getValue() != null) { CurrencyValue sumLocal = sum.add(value.getValue(), exchangeRateProvider); if(sumLocal.getValue() != null) { sum = sumLocal; } } } return sum; } synchronized void add(CurrencyValue valueToAdd); synchronized void add(CurrencySum sumToAdd); synchronized Map<String, CurrencyValue> getAllValues(); synchronized CurrencyValue getSumAsCurrency(String targetCurrency, ExchangeRateProvider exchangeRateProvider); }### Answer:
@Test public void testGetSumAsCurrency() throws Exception { ExactCurrencyValue b1 = ExactCurrencyValue.from(BigDecimal.ONE, CurrencyValue.BTC); ExactCurrencyValue b2 = ExactCurrencyValue.from(BigDecimal.valueOf(2L), CurrencyValue.BTC); ExactCurrencyValue f1 = ExactFiatValue.from(BigDecimal.valueOf(3L), "USD"); ExactCurrencyValue f2 = ExactFiatValue.from(BigDecimal.valueOf(4L), "USD"); ExactCurrencyValue f3 = ExactFiatValue.from(BigDecimal.valueOf(5L), "EUR"); CurrencySum currencySum = new CurrencySum(); currencySum.add(b1); currencySum.add(b2); currencySum.add(f1); currencySum.add(f2); currencySum.add(f3); CurrencyValue sumAsCurrency = currencySum.getSumAsCurrency(CurrencyValue.BTC, fx); AssertHelper.assertRoundedEqualValue(BigDecimal.valueOf(5), sumAsCurrency.getValue(), 8); assertEquals(sumAsCurrency.getCurrency(), "BTC"); CurrencyValue sumAsCurrencyUSD = currencySum.getSumAsCurrency("USD", fx); AssertHelper.assertRoundedEqualValue(BigDecimal.valueOf(35), sumAsCurrencyUSD.getValue(), 8); assertEquals("USD", sumAsCurrencyUSD.getCurrency()); } |
### Question:
CurrencyValue implements Serializable { public static boolean isNullOrZero(CurrencyValue value) { return value == null || value.getValue() == null || value.isZero(); } abstract String getCurrency(); abstract BigDecimal getValue(); boolean isZero(); @Override String toString(); static CurrencyValue fromValue(CurrencyValue currencyValue, String targetCurrency, ExchangeRateProvider exchangeRateManager); static CurrencyValue fromValue(ExchangeBasedCurrencyValue value, String targetCurrency, ExchangeRateProvider exchangeRateManager); static CurrencyValue fromValue(ExactCurrencyValue value, String targetCurrency, ExchangeRateProvider exchangeRateManager); static boolean isNullOrZero(CurrencyValue value); boolean isBtc(); boolean isFiat(); BitcoinValue getBitcoinValue(ExchangeRateProvider exchangeRateManager); CurrencyValue add(CurrencyValue other, ExchangeRateProvider exchangeRateProvider); Bitcoins getAsBitcoin(ExchangeRateProvider exchangeRateManager); abstract ExactCurrencyValue getExactValue(); CurrencyValue getExactValueIfPossible(); @Override boolean equals(Object o); @Override int hashCode(); static Optional<ExactCurrencyValue> checkCurrencyAmount(CurrencyValue amount, String currency); static final String BTC; }### Answer:
@Test public void testIsNullOrZero() throws Exception { assertFalse(CurrencyValue.isNullOrZero(ExactBitcoinValue.from(BigDecimal.ONE))); assertFalse(CurrencyValue.isNullOrZero(ExactCurrencyValue.from(BigDecimal.ONE, "EUR"))); assertTrue(CurrencyValue.isNullOrZero(null)); assertTrue(CurrencyValue.isNullOrZero(ExactCurrencyValue.from(null, "EUR"))); assertTrue(CurrencyValue.isNullOrZero(ExactBitcoinValue.from(0L))); assertTrue(CurrencyValue.isNullOrZero(ExactBitcoinValue.ZERO)); } |
### Question:
TrustAddressGenerator { public static String getTrustAddress(String contractAddress, String digest) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException { return preimageToAddress((contractAddress + "TRUST" + digest).getBytes()); } static String getTrustAddress(String contractAddress, String digest); static String getRevokeAddress(String contractAddress, String digest); static String preimageToAddress(byte[] preimage); static void main(String args[]); Response DeriveTrustAddress(Request req); static final byte[] masterPubKey; }### Answer:
@Test public void generateTrustAddress() throws Exception { System.out.println("digest:" + digest); String trustAddress = TrustAddressGenerator.getTrustAddress("0x63cCEF733a093E5Bd773b41C96D3eCE361464942", digest); assert(trustAddress.equals("0x2e02934b4ed1bee0defa7a58061dd8ee9440094c")); } |
### Question:
TrustAddressGenerator { public static String getRevokeAddress(String contractAddress, String digest) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException { return preimageToAddress((contractAddress + "REVOKE" + digest).getBytes()); } static String getTrustAddress(String contractAddress, String digest); static String getRevokeAddress(String contractAddress, String digest); static String preimageToAddress(byte[] preimage); static void main(String args[]); Response DeriveTrustAddress(Request req); static final byte[] masterPubKey; }### Answer:
@Test public void generateRevokeAddress() throws Exception { String revokeAddress = TrustAddressGenerator.getRevokeAddress("0x63cCEF733a093E5Bd773b41C96D3eCE361464942", digest); assert(revokeAddress.equals("0x6b4c50938caef365fa3e04bfe5a25da518dba447")); } |
### Question:
StringUtil { public boolean isValidPassword(String password) { Pattern p = Pattern.compile("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=\\S+$).{8,}$"); Matcher m = p.matcher(password); if (m.find()) return true; return false; } boolean isValidPassword(String password); }### Answer:
@Test public void it_should_validate_passwords() { String validPassword = "As1asd1sdas21"; String invalidPassword = "asd123"; assertTrue(stringUtil.isValidPassword(validPassword)); assertFalse(stringUtil.isValidPassword(invalidPassword)); } |
### Question:
FeignContext extends NamedContextFactory<FeignClientSpecification> { @Nullable public <T> T getInstanceWithoutAncestors(String name, Class<T> type) { try { return BeanFactoryUtils.beanOfType(getContext(name), type); } catch (BeansException ex) { return null; } } FeignContext(); @Nullable T getInstanceWithoutAncestors(String name, Class<T> type); @Nullable Map<String, T> getInstancesWithoutAncestors(String name, Class<T> type); }### Answer:
@Test public void getInstanceWithoutAncestors_verifyNullForMissing() { AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext(); parent.refresh(); FeignContext feignContext = new FeignContext(); feignContext.setApplicationContext(parent); feignContext.setConfigurations(Lists.newArrayList(getSpec("empty", EmptyConfiguration.class))); Logger.Level level = feignContext.getInstanceWithoutAncestors("empty", Logger.Level.class); assertThat(level).as("Logger was not null").isNull(); }
@Test public void getInstanceWithoutAncestors() { AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext(); parent.refresh(); FeignContext feignContext = new FeignContext(); feignContext.setApplicationContext(parent); feignContext.setConfigurations(Lists.newArrayList(getSpec("demo", DemoConfiguration.class))); Logger.Level level = feignContext.getInstanceWithoutAncestors("demo", Logger.Level.class); assertThat(level).isEqualTo(Logger.Level.FULL); } |
### Question:
FeignContext extends NamedContextFactory<FeignClientSpecification> { @Nullable public <T> Map<String, T> getInstancesWithoutAncestors(String name, Class<T> type) { return getContext(name).getBeansOfType(type); } FeignContext(); @Nullable T getInstanceWithoutAncestors(String name, Class<T> type); @Nullable Map<String, T> getInstancesWithoutAncestors(String name, Class<T> type); }### Answer:
@Test public void getInstancesWithoutAncestors_verifyEmptyForMissing() { AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext(); parent.refresh(); FeignContext feignContext = new FeignContext(); feignContext.setApplicationContext(parent); feignContext.setConfigurations(Lists.newArrayList(getSpec("empty", EmptyConfiguration.class))); Collection<RequestInterceptor> interceptors = feignContext .getInstancesWithoutAncestors("empty", RequestInterceptor.class).values(); assertThat(interceptors).as("Interceptors is not empty").isEmpty(); }
@Test public void getInstancesWithoutAncestors() { AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext(); parent.refresh(); FeignContext feignContext = new FeignContext(); feignContext.setApplicationContext(parent); feignContext.setConfigurations(Lists.newArrayList(getSpec("demo", DemoConfiguration.class))); Collection<RequestInterceptor> interceptors = feignContext .getInstancesWithoutAncestors("demo", RequestInterceptor.class).values(); assertThat(interceptors.size()).isEqualTo(1); } |
### Question:
ArrayParser implements Parser<String[][]> { @Override public void parse(String data, ParseCallback<String[][]> parseResult) { rows = null; titleRow = null; totalColumns = 0; Row[] lines; try { lines = getRows(data); } catch (ColumnsLengthException e) { parseResult.onParsingFailure(e); return; } String[][] result = new String[lines.length][getTotalColumns(getTitles(data))]; for (int i = 0; i < lines.length; i++) { for (int j = 0; j < getTotalColumns(getTitles(data)); j++) { result[i][j] = lines[i].getEntries()[j]; } } parseResult.onParsingSuccess(result); } @Override void parse(String data, ParseCallback<String[][]> parseResult); @Override Row[] getRows(String data); @Override String[] getWords(String rowAsString); @Override Row getTitles(String data); @Override int getTotalColumns(Row titles); }### Answer:
@Test public void parserTestSimpleData() throws ColumnsLengthException { System.out.println("\n\n---------Test Simple Characters Data---------"); parser.parse(simpleData, callback); }
@Test public void parserTestSpecialData() throws ColumnsLengthException { System.out.println("\n\n---------Test Special Character Data---------"); parser.parse(specialCharsData, callback); } |
### Question:
ProductCategoryEnricher { public Tuple enrichEvent(Tuple event) { if ("PRODUCT".equals(event.getString("type"))) { List<String> names = new ArrayList<>(event.getFieldNames()); List<Object> values = new ArrayList(event.getValues()); names.add("category"); values.add(getCategory(event.getString("product"))); return TupleBuilder.tuple().ofNamesAndValues(names, values); } else { return null; } } ProductCategoryEnricher(RedisTemplate<String, String> redisTemplate); Tuple enrichEvent(Tuple event); }### Answer:
@Test @Ignore public void testEnrichProductWithCategory() { String event = "{\"user\":\"60571253-8315-40ff-8142-f8d68f9d35f0\",\"product\":\"15\",\"type\":\"PRODUCT\"}"; Tuple enrichedEvent = productCategoryEnricher.enrichEvent(TupleBuilder.fromString(event)); assertEquals("Covers", enrichedEvent.getString("category")); } |
### Question:
MovingAverage implements Processor<Tuple, Tuple> { @Override public Stream<Tuple> process(Stream<Tuple> inputStream) { return inputStream.map(tuple -> { return tuple.getDouble("measurement"); }) .buffer(5) .map(data -> tuple().of("average", avg(data))); } @Override Stream<Tuple> process(Stream<Tuple> inputStream); }### Answer:
@Test public void simple() { Environment.initializeIfEmpty(); final Broadcaster<Object> broadcaster = SerializedBroadcaster.create(); Processor processor = new MovingAverage(); Stream<?> outputStream = processor.process(broadcaster); outputStream.consume(new Consumer<Object>() { @Override public void accept(Object o) { System.out.println("processed : " + o); } }); List<Tuple> inputData = new ArrayList<Tuple>(); for (int i = 0; i < 10; i++) { inputData.add(TupleBuilder.tuple().of("id", i, "measurement", new Double(i+10))); } for (Tuple tuple: inputData) { broadcaster.onNext(tuple); } } |
### Question:
DepartmentsSort { public Set<String> naturalOrderSort(String[] departments) { TreeSet<String> sortedDepartments = new TreeSet<>(); for (String fullString : departments) { StringBuilder department = new StringBuilder(); for (String splitString : fullString.split("\\\\")) { department.append(splitString); sortedDepartments.add(department.toString()); department.append("\\"); } } return sortedDepartments; } Set<String> naturalOrderSort(String[] departments); TreeSet<String> reverseOrderSort(String[] departments); }### Answer:
@Test public void ifArrayNaturalOrderSortingThenResultIsNaturalOrderSortingExpect() { DepartmentsSort testSort = new DepartmentsSort(); Set<String> result = testSort.naturalOrderSort(arrayForSorting); assertThat(result, is(new LinkedHashSet<>(asList(naturalOrderSortingExpect)))); } |
### Question:
DbStore implements Store, UserAddressStore { @Override public List<User> findAll() { List<User> resultList = new ArrayList<>(); try (Connection con = SOURCE.getConnection(); Statement st = con.createStatement(); ResultSet rst = st.executeQuery(PROPS.getProperty("findAll"))) { while (rst.next()) { resultList.add(this.createUserFromRstSet(rst)); } } catch (SQLException e) { LOG.error(e.getMessage(), e); } return resultList; } private DbStore(); static DbStore getInstance(); @Override User findByLogin(String login); @Override void add(User user); @Override void update(User newUser); @Override void delete(int userId); @Override List<User> findAll(); @Override User findById(int id); List<String> findAllCountries(); List<String> findCitiesByCountry(String name); }### Answer:
@Test public void findAll() { this.testStore.add(first); this.testStore.add(second); try (Statement st = this.connect.createStatement(); ResultSet rstSet = st.executeQuery("SELECT id FROM users WHERE name = 'test'")) { rstSet.next(); this.first.setId(rstSet.getInt("id")); rstSet.next(); this.second.setId(rstSet.getInt("id")); } catch (SQLException e) { e.printStackTrace(); } List<User> result = this.testStore.findAll(); List<User> expect = new ArrayList<>(asList(first, second)); assertThat(result.containsAll(expect), is(true)); } |
### Question:
DbStore implements Store, UserAddressStore { @Override public User findById(int id) { User user = null; try (Connection con = SOURCE.getConnection(); PreparedStatement st = con.prepareStatement(PROPS.getProperty("findById"))) { st.setInt(1, id); try (ResultSet rstSet = st.executeQuery()) { if (rstSet.next()) { user = this.createUserFromRstSet(rstSet); } } } catch (SQLException e) { LOG.error(e.getMessage(), e); } return user; } private DbStore(); static DbStore getInstance(); @Override User findByLogin(String login); @Override void add(User user); @Override void update(User newUser); @Override void delete(int userId); @Override List<User> findAll(); @Override User findById(int id); List<String> findAllCountries(); List<String> findCitiesByCountry(String name); }### Answer:
@Test public void findById() { this.testStore.add(first); try (Statement st = this.connect.createStatement(); ResultSet rstSet = st.executeQuery("SELECT id FROM users WHERE name = 'test'")) { rstSet.next(); this.first.setId(rstSet.getInt("id")); } catch (SQLException e) { e.printStackTrace(); } assertThat(this.testStore.findById(this.first.getId()), is(this.first)); } |
### Question:
DbStore implements Store, UserAddressStore { public List<String> findAllCountries() { List<String> resultList = new ArrayList<>(); try (Connection con = SOURCE.getConnection(); Statement st = con.createStatement(); ResultSet rst = st.executeQuery(PROPS.getProperty("getAllCountries"))) { while (rst.next()) { resultList.add(rst.getString("name")); } } catch (SQLException e) { LOG.error(e.getMessage(), e); } return resultList; } private DbStore(); static DbStore getInstance(); @Override User findByLogin(String login); @Override void add(User user); @Override void update(User newUser); @Override void delete(int userId); @Override List<User> findAll(); @Override User findById(int id); List<String> findAllCountries(); List<String> findCitiesByCountry(String name); }### Answer:
@Test public void findAllCountriesTest() { assertTrue(this.testStore.findAllCountries().containsAll(asList("Russia", "USA"))); } |
### Question:
DbStore implements Store, UserAddressStore { public List<String> findCitiesByCountry(String name) { List<String> resultList = new ArrayList<>(); try (Connection con = SOURCE.getConnection(); PreparedStatement st = con.prepareStatement(PROPS.getProperty("getCitiesByCountry"))) { st.setString(1, name); try (ResultSet rstSet = st.executeQuery()) { while (rstSet.next()) { resultList.add(rstSet.getString("name")); } } } catch (SQLException e) { LOG.error(e.getMessage(), e); } return resultList; } private DbStore(); static DbStore getInstance(); @Override User findByLogin(String login); @Override void add(User user); @Override void update(User newUser); @Override void delete(int userId); @Override List<User> findAll(); @Override User findById(int id); List<String> findAllCountries(); List<String> findCitiesByCountry(String name); }### Answer:
@Test public void findCitiesByCountry() { assertTrue(this.testStore.findCitiesByCountry("Russia").containsAll( asList("Moscow", "Saint Petersburg", "Ekaterinburg")) ); } |
### Question:
ValidateService { public static ValidateService getInstance() { return INSTANCE; } private ValidateService(); static ValidateService getInstance(); boolean add(final User newUser); boolean update(final User newUser); boolean delete(final int id); List<User> findAll(); User findById(final int id); User findByLogin(final String login); }### Answer:
@Test public void getInstanceForAllTimeShouldBeReturnSomeObject() { ValidateService secondTestValidator = ValidateService.getInstance(); assertThat(this.testValidator, is(secondTestValidator)); } |
### Question:
MemoryStore implements Store { public static MemoryStore getInstance() { return INSTANCE; } private MemoryStore(); static MemoryStore getInstance(); @Override void add(final User newUser); @Override void update(final User newUser); @Override void delete(final int userId); @Override List<User> findAll(); @Override User findById(final int id); @Override User findByLogin(String login); }### Answer:
@Test public void ifGetTwoInstanceThenTheyShouldBeOneObject() { MemoryStore secondTestStore = MemoryStore.getInstance(); assertThat(this.testStore, is(secondTestStore)); } |
### Question:
TaskStore { public void add(Task task) { this.tx(session -> { session.save(task); return null; }); } boolean delete(final int id); void add(Task task); void update(Task task); List<Task> findAll(); Task findById(int id); }### Answer:
@Test public void add() { this.test.add(this.first); assertTrue(this.test.findAll().contains(this.first)); } |
### Question:
TaskStore { public void update(Task task) { this.tx(session -> { session.update(task); return null; }); } boolean delete(final int id); void add(Task task); void update(Task task); List<Task> findAll(); Task findById(int id); }### Answer:
@Test public void update() { this.test.add(this.second); int taskId = this.findTaskId(this.second); Task updatedTask = this.first; this.first.setId(taskId); this.test.update(updatedTask); assertThat(this.test.findById(taskId), is(this.first)); } |
### Question:
ConvertList { public int[][] toArray(List<Integer> list, int rows) { int rowLength = (int) Math.ceil(list.size() / (double) rows); int[][] result = new int[rows][rowLength]; int rowsNumber = 0; int rowsPosition = 0; for (int element : list) { if (rowsPosition < rowLength) { result[rowsNumber][rowsPosition++] = element; } else if (rowsNumber < rows - 1) { rowsPosition = 0; result[++rowsNumber][rowsPosition++] = element; } } if (list.size() % rows != 0) { while (rowsPosition < rowLength) { result[rows - 1][rowsPosition++] = 0; } } return result; } List<Integer> toList(int[][] array); int[][] toArray(List<Integer> list, int rows); List<Integer> convert(List<int[]> list); }### Answer:
@Test public void convertArrayListToTwoDimensionalArray() { ConvertList testConvert = new ConvertList(); int[][] result = testConvert.toArray(new ArrayList<>(asList(1, 2, 3, 4, 5, 6, 7)), 3); int[][] expect = new int[][]{ {1, 2, 3}, {4, 5, 6}, {7, 0, 0} }; assertThat(result, is(expect)); } |
### Question:
TaskStore { public boolean delete(final int id) { boolean result = false; try { this.tx( session -> { session.delete(new Task(id)); return null; } ); result = true; } catch (Exception e) { LOG.error(e.getMessage(), e); } return result; } boolean delete(final int id); void add(Task task); void update(Task task); List<Task> findAll(); Task findById(int id); }### Answer:
@Test public void delete() { this.test.add(this.first); int taskId = this.findTaskId(this.first); assertTrue(this.test.delete(taskId)); assertFalse(this.test.delete(taskId)); assertFalse(this.test.findAll().contains(this.first)); } |
### Question:
Counter { public int add(int start, int finish) { int count = 0; for (int i = start; i <= finish; i++) { if (i % 2 == 0) { count += i; } } return count; } int add(int start, int finish); }### Answer:
@Test public void whenSumEvenNumbersFromOneToTenThenThirty() { Counter sumSquares = new Counter(); int result = sumSquares.add(1, 10); assertThat(result, is(30)); } |
### Question:
Board { public String paint(int width, int height) { StringBuilder screen = new StringBuilder(); String ln = System.lineSeparator(); for (int currentHeight = 0; currentHeight < height; currentHeight++) { for (int currentWidth = 0; currentWidth < width; currentWidth++) { if ((currentWidth + currentHeight) % 2 == 0) { screen.append("x"); } else { screen.append(" "); } } screen.append(ln); } return screen.toString(); } String paint(int width, int height); }### Answer:
@Test public void whenPaintBoardWithWidthThreeAndHeightThreeThenStringWithThreeColsAndThreeRows() { Board board = new Board(); String result = board.paint(3, 3); final String line = System.getProperty("line.separator"); String expected = String.format("x x%s x %sx x%s", line, line, line); assertThat(result, is(expected)); }
@Test public void whenPaintBoardWithWidthFiveAndHeightFiveThenStringWithFiveColsAndFiveRows() { Board board = new Board(); String result = board.paint(5, 5); final String line = System.getProperty("line.separator"); String expected = String.format("x x x%s x x %sx x x%s x x %sx x x%s", line, line, line, line, line); assertThat(result, is(expected)); } |
### Question:
Paint { public String rightTrl(int height) { return this.loopBy( height, height, (row, column) -> row >= column ); } String rightTrl(int height); String leftTrl(int height); String pyramid(int height); }### Answer:
@Test public void whenPyramid4Right() { Paint paint = new Paint(); String rst = paint.rightTrl(4); System.out.println(rst); assertThat(rst, is( new StringJoiner(System.lineSeparator(), "", System.lineSeparator()) .add("^ ") .add("^^ ") .add("^^^ ") .add("^^^^") .toString() ) ); } |
### Question:
Paint { public String leftTrl(int height) { return this.loopBy( height, height, (row, column) -> row >= height - column - 1 ); } String rightTrl(int height); String leftTrl(int height); String pyramid(int height); }### Answer:
@Test public void whenPyramid4Left() { Paint paint = new Paint(); String rst = paint.leftTrl(4); System.out.println(rst); assertThat(rst, is( new StringJoiner(System.lineSeparator(), "", System.lineSeparator()) .add(" ^") .add(" ^^") .add(" ^^^") .add("^^^^") .toString() ) ); } |
### Question:
Paint { public String pyramid(int height) { return this.loopBy( height, 2 * height - 1, (row, column) -> row >= height - column - 1 && row + height - 1 >= column ); } String rightTrl(int height); String leftTrl(int height); String pyramid(int height); }### Answer:
@Test public void whenPyramidFive() { Paint paint = new Paint(); String rst = paint.pyramid(5); System.out.println(rst); assertThat(rst, is( new StringJoiner(System.lineSeparator(), "", System.lineSeparator()) .add(" ^ ") .add(" ^^^ ") .add(" ^^^^^ ") .add(" ^^^^^^^ ") .add("^^^^^^^^^") .toString() ) ); } |
### Question:
Factorial { public int calc(int n) { int factorial = 1; for (int i = 1; i <= n; i++) { factorial *= i; } return factorial; } int calc(int n); }### Answer:
@Test public void factorialOfNumberFive() { Factorial factor = new Factorial(); int result = factor.calc(5); assertThat(result, is(120)); }
@Test public void factorialOfNumberOne() { Factorial factor = new Factorial(); int result = factor.calc(1); assertThat(result, is(1)); } |
### Question:
DummyBot { public String answer(String question) { String answer = "Это ставит меня в тупик. Спросите другой вопрос."; if ("Привет, Бот.".equals(question)) { answer = "Привет, умник."; } else if ("Пока.".equals(question)) { answer = "До скорой встречи."; } return answer; } String answer(String question); }### Answer:
@Test public void whenGreetBot() { DummyBot bot = new DummyBot(); assertThat( bot.answer("Привет, Бот."), is("Привет, умник.") ); }
@Test public void whenByuBot() { DummyBot bot = new DummyBot(); assertThat( bot.answer("Пока."), is("До скорой встречи.") ); }
@Test public void whenUnknownBot() { DummyBot bot = new DummyBot(); assertThat( bot.answer("Сколько будет 2 + 2?"), is("Это ставит меня в тупик. Спросите другой вопрос.") ); } |
### Question:
ConvertList { public List<Integer> convert(List<int[]> list) { List<Integer> result = new ArrayList<>(); for (int[] array : list) { for (int element : array) { result.add(element); } } return result; } List<Integer> toList(int[][] array); int[][] toArray(List<Integer> list, int rows); List<Integer> convert(List<int[]> list); }### Answer:
@Test public void convertListOfArraysToList() { List<int[]> list = new ArrayList<>(); list.add(new int[]{1, 2}); list.add(new int[]{3, 4, 5, 6}); ConvertList testConvert = new ConvertList(); List<Integer> result = testConvert.convert(list); assertThat(result, is(new ArrayList<>(asList(1, 2, 3, 4, 5, 6)))); } |
### Question:
Triangle { public double area() { double area = -1; double ab = this.a.distanceTo(this.b); double ac = this.a.distanceTo(this.c); double bc = this.b.distanceTo(this.c); double p = this.period(ab, ac, bc); if (this.exist(ab, ac, bc)) { area = Math.sqrt(p * (p - ab) * (p - ac) * (p - bc)); } return area; } Triangle(Point a, Point b, Point c); double period(double ab, double ac, double bc); double area(); }### Answer:
@Test public void whenAreaSetThreePointsThenTreangleArea() { Point a = new Point(0, 0); Point b = new Point(0, 2); Point c = new Point(2, 0); Triangle triangle = new Triangle(a, b, c); double result = triangle.area(); double expected = 2D; assertThat(result, closeTo(expected, 0.1)); }
@Test public void whenExistFalse() { Point a = new Point(0, 0); Point b = new Point(0, 0); Point c = new Point(0, 1); Triangle triangle = new Triangle(a, b, c); double result = triangle.area(); double expected = -1D; assertThat(result, is(expected)); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.