method2testcases
stringlengths
118
3.08k
### Question: NameUtilities { public static String getFullName(Class c) { if (c == null) { throw new IllegalArgumentException("class cannot be null"); } StringBuilder name = new StringBuilder(); name.append(c.getPackage().getName()).append("."); Class klaus = c; List<Class> enclosingClasses = new ArrayList<Class>(); while ((klaus = klaus.getEnclosingClass()) != null) { enclosingClasses.add(klaus); } for (int i = enclosingClasses.size() - 1; i >= 0; i--) { name.append(enclosingClasses.get(i).getSimpleName()).append("."); } name.append(c.getSimpleName()); return name.toString(); } static String getFullName(Class c); }### Answer: @Test public void testInnerClassNaming() { String expected = NameUtilitiesTest.class.getPackage().getName()+"." + NameUtilitiesTest.class.getSimpleName()+"." + "Inner" ; String name = NameUtilities.getFullName(Inner.class); Assert.assertEquals(expected, name); }
### Question: UriUtils { public static String replaceNamespace(String base, String replacement) { Matcher m = replaceNamespacePattern.matcher(base); String result = m.replaceAll(replacement); return result; } static Map<String, String> createMapFromUriQueryString(URI uri); static String getNameSpace(String s); static String getLocalName(String s); static String replaceNamespace(String base, String replacement); static Multimap<String, String> parseQueryString(String queryString); static Multimap<String, String> parseQueryStringEx(String queryString); static final Pattern replaceNamespacePattern; }### Answer: @Test public void test() { String r = UriUtils.replaceNamespace("http: Assert.assertEquals("http: }
### Question: JSONReader { public Attributes readDataset(Attributes attrs) { boolean wrappedInArray = next() == Event.START_ARRAY; if (wrappedInArray) next(); expect(Event.START_OBJECT); if (attrs == null) { attrs = new Attributes(); } fmi = null; next(); doReadDataset(attrs); if (wrappedInArray) next(); return attrs; } JSONReader(JsonParser parser); boolean isSkipBulkDataURI(); void setSkipBulkDataURI(boolean skipBulkDataURI); Attributes getFileMetaInformation(); Attributes readDataset(Attributes attrs); void readDatasets(Callback callback); }### Answer: @Test public void test() { StringReader reader = new StringReader(JSON); JsonParser parser = Json.createParser(reader); Attributes dataset = new JSONReader(parser).readDataset(null); assertArrayEquals(IS, dataset.getStrings(Tag.SelectorISValue)); assertArrayEquals(DS, dataset.getStrings(Tag.SelectorDSValue)); assertInfinityAndNaN(dataset.getDoubles(Tag.SelectorFDValue)); assertInfinityAndNaN(dataset.getFloats(Tag.SelectorFLValue)); }
### Question: DicomOutputStream extends FilterOutputStream { public void writeCommand(Attributes cmd) throws IOException { if (explicitVR || bigEndian) throw new IllegalStateException("explicitVR=" + explicitVR + ", bigEndian=" + bigEndian); cmd.writeGroupTo(this, Tag.CommandGroupLength); } DicomOutputStream(OutputStream out, String tsuid); DicomOutputStream(File file); final void setPreamble(byte[] preamble); final boolean isExplicitVR(); final boolean isBigEndian(); final DicomEncodingOptions getEncodingOptions(); final void setEncodingOptions(DicomEncodingOptions encOpts); @Override void write(byte[] b, int off, int len); void writeCommand(Attributes cmd); void writeFileMetaInformation(Attributes fmi); void writeDataset(Attributes fmi, Attributes dataset); void switchTransferSyntax(String tsuid); void writeHeader(int tag, VR vr, int len); void writeAttribute(int tag, VR vr, Object value, SpecificCharacterSet cs); void writeAttribute(int tag, VR vr, byte[] val); void writeAttribute(int tag, VR vr, Value val); void writeGroupLength(int tag, int len); void finish(); void close(); }### Answer: @Test public void testWriteCommand() throws IOException { DicomOutputStream out = new DicomOutputStream( new FileOutputStream(file), UID.ImplicitVRLittleEndian); try { out.writeCommand(cechorq()); } finally { out.close(); } assertEquals(4, readAttributes().size()); }
### Question: AttributeSelector implements Serializable { public boolean matches(List<ItemPointer> itemPointers, String privateCreator, int tag) { int level; if (tag != this.tag || !Objects.equals(privateCreator, this.privateCreator) || (itemPointers.size() != (level = level()))) { return false; } for (int i = 0; i < level; i++) { ItemPointer itemPointer = itemPointers.get(i); ItemPointer other = itemPointer(i); if (!(itemPointer.itemIndex < 0 || other.itemIndex < 0 ? itemPointer.equalsIgnoreItemIndex(other) : itemPointer.equals(other))) { return false; } } return true; } AttributeSelector(int tag); AttributeSelector(int tag, String privateCreator); AttributeSelector(int tag, String privateCreator, ItemPointer... itemPointers); AttributeSelector(int tag, String privateCreator, List<ItemPointer> itemPointers); int tag(); String privateCreator(); int level(); ItemPointer itemPointer(int index); String selectStringValue(Attributes attrs, int valueIndex, String defVal); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static AttributeSelector valueOf(String s); boolean matches(List<ItemPointer> itemPointers, String privateCreator, int tag); }### Answer: @Test public void testMatches() { ItemPointer ip = new ItemPointer(Tag.RequestAttributesSequence); AttributeSelector selector = new AttributeSelector(Tag.StudyInstanceUID, null, ip); assertTrue(selector.matches(Collections.singletonList(ip), null, Tag.StudyInstanceUID)); }
### Question: DicomOutputStream extends FilterOutputStream { public void writeDataset(Attributes fmi, Attributes dataset) throws IOException { if (fmi != null) { writeFileMetaInformation(fmi); switchTransferSyntax(fmi.getString(Tag.TransferSyntaxUID, null)); } if (dataset.bigEndian() != bigEndian || encOpts.groupLength || !encOpts.undefSequenceLength || !encOpts.undefItemLength) dataset = new Attributes(dataset, bigEndian); if (encOpts.groupLength) dataset.calcLength(encOpts, explicitVR); dataset.writeTo(this); } DicomOutputStream(OutputStream out, String tsuid); DicomOutputStream(File file); final void setPreamble(byte[] preamble); final boolean isExplicitVR(); final boolean isBigEndian(); final DicomEncodingOptions getEncodingOptions(); final void setEncodingOptions(DicomEncodingOptions encOpts); @Override void write(byte[] b, int off, int len); void writeCommand(Attributes cmd); void writeFileMetaInformation(Attributes fmi); void writeDataset(Attributes fmi, Attributes dataset); void switchTransferSyntax(String tsuid); void writeHeader(int tag, VR vr, int len); void writeAttribute(int tag, VR vr, Object value, SpecificCharacterSet cs); void writeAttribute(int tag, VR vr, byte[] val); void writeAttribute(int tag, VR vr, Value val); void writeGroupLength(int tag, int len); void finish(); void close(); }### Answer: @Test public void testWriteDataset() throws IOException { DicomOutputStream out = new DicomOutputStream(file); } @Test public void testWriteDeflatedEvenLength() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try (DicomOutputStream dos = new DicomOutputStream( out, UID.DeflatedExplicitVRLittleEndian)) { Attributes attrs = new Attributes(); attrs.setString(Tag.SOPClassUID, VR.UI, UID.CTImageStorage); dos.writeDataset(null, attrs); } assertEquals("odd number of bytes", 0, out.size() & 1); }
### Question: DicomOutputStream extends FilterOutputStream { public final void setEncodingOptions(DicomEncodingOptions encOpts) { if (encOpts == null) throw new NullPointerException(); this.encOpts = encOpts; } DicomOutputStream(OutputStream out, String tsuid); DicomOutputStream(File file); final void setPreamble(byte[] preamble); final boolean isExplicitVR(); final boolean isBigEndian(); final DicomEncodingOptions getEncodingOptions(); final void setEncodingOptions(DicomEncodingOptions encOpts); @Override void write(byte[] b, int off, int len); void writeCommand(Attributes cmd); void writeFileMetaInformation(Attributes fmi); void writeDataset(Attributes fmi, Attributes dataset); void switchTransferSyntax(String tsuid); void writeHeader(int tag, VR vr, int len); void writeAttribute(int tag, VR vr, Object value, SpecificCharacterSet cs); void writeAttribute(int tag, VR vr, byte[] val); void writeAttribute(int tag, VR vr, Value val); void writeGroupLength(int tag, int len); void finish(); void close(); }### Answer: @Test public void testWriteDatasetWithGroupLength() throws IOException { DicomOutputStream out = new DicomOutputStream(file); out.setEncodingOptions( new DicomEncodingOptions(true, true, false, true, false)); testWriteDataset(out, UID.ExplicitVRLittleEndian); } @Test public void testWriteDatasetWithoutUndefLength() throws IOException { DicomOutputStream out = new DicomOutputStream(file); out.setEncodingOptions( new DicomEncodingOptions(false, false, false, false, false)); testWriteDataset(out, UID.ExplicitVRLittleEndian); } @Test public void testWriteDatasetWithUndefEmptyLength() throws IOException { DicomOutputStream out = new DicomOutputStream(file); out.setEncodingOptions( new DicomEncodingOptions(false, true, true, true, true)); testWriteDataset(out, UID.ExplicitVRLittleEndian); }
### Question: DicomOutputStream extends FilterOutputStream { public void close() throws IOException { try { finish(); } catch (IOException ignored) { } super.close(); } DicomOutputStream(OutputStream out, String tsuid); DicomOutputStream(File file); final void setPreamble(byte[] preamble); final boolean isExplicitVR(); final boolean isBigEndian(); final DicomEncodingOptions getEncodingOptions(); final void setEncodingOptions(DicomEncodingOptions encOpts); @Override void write(byte[] b, int off, int len); void writeCommand(Attributes cmd); void writeFileMetaInformation(Attributes fmi); void writeDataset(Attributes fmi, Attributes dataset); void switchTransferSyntax(String tsuid); void writeHeader(int tag, VR vr, int len); void writeAttribute(int tag, VR vr, Object value, SpecificCharacterSet cs); void writeAttribute(int tag, VR vr, byte[] val); void writeAttribute(int tag, VR vr, Value val); void writeGroupLength(int tag, int len); void finish(); void close(); }### Answer: @Test public void testSerializeDataset() throws Exception { ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream(file)); try { out.writeObject(dataset()); out.writeUTF("END"); } finally { out.close(); } deserializeAttributes(); }
### Question: DicomOutputStream extends FilterOutputStream { public void writeFileMetaInformation(Attributes fmi) throws IOException { if (!explicitVR || bigEndian || countingOutputStream != null) throw new IllegalStateException("explicitVR=" + explicitVR + ", bigEndian=" + bigEndian + ", deflated=" + (countingOutputStream != null)); write(preamble); write(DICM); fmi.writeGroupTo(this, Tag.FileMetaInformationGroupLength); } DicomOutputStream(OutputStream out, String tsuid); DicomOutputStream(File file); final void setPreamble(byte[] preamble); final boolean isExplicitVR(); final boolean isBigEndian(); final DicomEncodingOptions getEncodingOptions(); final void setEncodingOptions(DicomEncodingOptions encOpts); @Override void write(byte[] b, int off, int len); void writeCommand(Attributes cmd); void writeFileMetaInformation(Attributes fmi); void writeDataset(Attributes fmi, Attributes dataset); void switchTransferSyntax(String tsuid); void writeHeader(int tag, VR vr, int len); void writeAttribute(int tag, VR vr, Object value, SpecificCharacterSet cs); void writeAttribute(int tag, VR vr, byte[] val); void writeAttribute(int tag, VR vr, Value val); void writeGroupLength(int tag, int len); void finish(); void close(); }### Answer: @Test(expected = IllegalStateException.class) public void testWriteFMIDeflated() throws IOException { try (DicomOutputStream out = new DicomOutputStream( new ByteArrayOutputStream(), UID.DeflatedExplicitVRLittleEndian)) { out.writeFileMetaInformation( Attributes.createFileMetaInformation(UIDUtils.createUID(), UID.CTImageStorage, UID.DeflatedExplicitVRLittleEndian)); } }
### Question: RecordFactory { public RecordType getRecordType(String cuid) { if (cuid == null) throw new NullPointerException(); lazyLoadDefaultConfiguration(); RecordType recordType = recordTypes.get(cuid); return recordType != null ? recordType : RecordType.PRIVATE; } void loadDefaultConfiguration(); void loadConfiguration(String uri); RecordType getRecordType(String cuid); RecordType setRecordType(String cuid, RecordType type); void setRecordKeys(RecordType type, int[] keys); int[] getRecordKeys(RecordType type); String getPrivateRecordUID(String cuid); String setPrivateRecordUID(String cuid, String uid); int[] setPrivateRecordKeys(String uid, int[] keys); Attributes createRecord(Attributes dataset, Attributes fmi, String[] fileIDs); Attributes createRecord(RecordType type, String privRecUID, Attributes dataset, Attributes fmi, String[] fileIDs); }### Answer: @Test public void testGetRecordType() { RecordFactory f = new RecordFactory(); assertEquals(RecordType.IMAGE, f.getRecordType(UID.SecondaryCaptureImageStorage)); }
### Question: FindSCU { static void mergeKeys(Attributes attrs, Attributes keys) { try { attrs.accept(new MergeNested(keys), false); } catch (Exception e) { throw new RuntimeException(e); } attrs.addAll(keys); } FindSCU(); final void setPriority(int priority); final void setInformationModel(InformationModel model, String[] tss, EnumSet<QueryOption> queryOptions); void addLevel(String s); final void setCancelAfter(int cancelAfter); final void setOutputDirectory(File outDir); final void setOutputFileFormat(String outFileFormat); final void setXSLT(File xsltFile); final void setXML(boolean xml); final void setXMLIndent(boolean indent); final void setXMLIncludeKeyword(boolean includeKeyword); final void setXMLIncludeNamespaceDeclaration( boolean includeNamespaceDeclaration); final void setConcatenateOutputFiles(boolean catOut); final void setInputFilter(int[] inFilter); ApplicationEntity getApplicationEntity(); Connection getRemoteConnection(); AAssociateRQ getAAssociateRQ(); Association getAssociation(); Device getDevice(); Attributes getKeys(); @SuppressWarnings("unchecked") static void main(String[] args); void open(); void close(); void query(File f); void query(); void query( DimseRSPHandler rspHandler); }### Answer: @Test public void mergeNestedKeys() throws Exception { Attributes attrs = withSSA(returnKeys()); FindSCU.mergeKeys(attrs, withSSA(matchingKeys())); assertEquals(mergedKeys(), attrs.getNestedDataset(Tag.ScheduledStepAttributesSequence)); }
### Question: LdapHL7Configuration extends LdapDicomConfigurationExtension implements HL7Configuration { @Override public HL7Application findHL7Application(String name) throws ConfigurationException { Device device = config.findDevice( "(&(objectclass=hl7Application)(hl7ApplicationName=" + name + "))", name); HL7DeviceExtension hl7Ext = device.getDeviceExtension(HL7DeviceExtension.class); return hl7Ext.getHL7Application(name); } void addHL7ConfigurationExtension(LdapHL7ConfigurationExtension ext); boolean removeHL7ConfigurationExtension( LdapHL7ConfigurationExtension ext); @Override boolean registerHL7Application(String name); @Override void unregisterHL7Application(String name); @Override String[] listRegisteredHL7ApplicationNames(); @Override HL7Application findHL7Application(String name); @Override synchronized HL7ApplicationInfo[] listHL7AppInfos(HL7ApplicationInfo keys); }### Answer: @Test public void testPersist() throws Exception { try { config.removeDevice("Test-Device-1", null); } catch (ConfigurationNotFoundException e) {} Device device = createDevice("Test-Device-1", "TEST1^DCM4CHE"); config.persist(device, null); HL7Application app = hl7Ext.findHL7Application("TEST1^DCM4CHE"); assertEquals(2575, app.getConnections().get(0).getPort()); assertEquals("TEST2^DCM4CHE", app.getAcceptedSendingApplications()[0]); assertEquals(7, app.getAcceptedMessageTypes().length); config.removeDevice("Test-Device-1", null); }
### Question: IOD extends ArrayList<IOD.DataElement> { public static IOD load(String uri) throws IOException { if (uri.startsWith("resource:")) { try { uri = ResourceLocator.getResource(uri.substring(9), IOD.class); } catch (NullPointerException npe) { throw new FileNotFoundException(uri); } } else if (uri.indexOf(':') < 2) { uri = new File(uri).toURI().toString(); } IOD iod = new IOD(); iod.parse(uri); iod.trimToSize(); return iod; } void setType(DataElementType type); DataElementType getType(); void setCondition(Condition condition); Condition getCondition(); int getLineNumber(); void setLineNumber(int lineNumber); void parse(String uri); static IOD load(String uri); static IOD valueOf(Code code); }### Answer: @Test public void testValidateDICOMDIR() throws Exception { IOD iod = IOD.load("resource:dicomdir-iod.xml"); Attributes attrs = readDataset("DICOMDIR"); ValidationResult result = attrs.validate(iod); assertTrue(result.isValid()); } @Test public void testValidateCode() throws Exception { IOD iod = IOD.load("resource:code-iod.xml"); Attributes attrs = new Attributes(2); attrs.newSequence(Tag.ConceptNameCodeSequence, 1).add( new Code("CV-9991", "99DCM4CHE", null, "CM-9991").toItem()); Attributes contentNode = new Attributes(2); contentNode.newSequence(Tag.ConceptNameCodeSequence, 1).add( new Code("CV-9992", "99DCM4CHE", null, "CM-9992").toItem()); contentNode.newSequence(Tag.ConceptCodeSequence, 1).add( new Code("CV-9993", "99DCM4CHE", null, "CM-9993").toItem()); attrs.newSequence(Tag.ContentSequence, 1).add(contentNode); ValidationResult result = attrs.validate(iod); assertTrue(result.isValid()); }
### Question: PersonName { public String get(Component c) { return get(Group.Alphabetic, c); } PersonName(); PersonName(String s); PersonName(String s, boolean lenient); String toString(); String toString(Group g, boolean trim); String get(Component c); String get(Group g, Component c); void set(Component c, String s); void set(Group g, Component c, String s); boolean isEmpty(); boolean contains(Group g); boolean contains(Group g, Component c); boolean contains(Component c); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testValueOf() { PersonName pn = new PersonName( "Adams^John Robert Quincy^^Rev.^B.A. M.Div."); assertEquals("Adams", pn.get(PersonName.Component.FamilyName)); assertEquals("John Robert Quincy", pn.get(PersonName.Component.GivenName)); assertEquals("Rev.", pn.get(PersonName.Component.NamePrefix)); assertEquals("B.A. M.Div.", pn.get(PersonName.Component.NameSuffix)); } @Test public void testValueOf2() { PersonName pn = new PersonName("Hong^Gildong=洪^吉洞=홍^길동"); assertEquals("Hong", pn.get(PersonName.Group.Alphabetic, PersonName.Component.FamilyName)); assertEquals("Gildong", pn.get(PersonName.Group.Alphabetic, PersonName.Component.GivenName)); assertEquals("洪", pn.get(PersonName.Group.Ideographic, PersonName.Component.FamilyName)); assertEquals("吉洞", pn.get(PersonName.Group.Ideographic, PersonName.Component.GivenName)); assertEquals("홍", pn.get(PersonName.Group.Phonetic, PersonName.Component.FamilyName)); assertEquals("길동", pn.get(PersonName.Group.Phonetic, PersonName.Component.GivenName)); }
### Question: PersonName { public String toString() { int totLen = 0; Group lastGroup = Group.Alphabetic; for (Group g : Group.values()) { Component lastCompOfGroup = Component.FamilyName; for (Component c : Component.values()) { String s = get(g, c); if (s != null) { totLen += s.length(); lastGroup = g; lastCompOfGroup = c; } } totLen += lastCompOfGroup.ordinal(); } totLen += lastGroup.ordinal(); char[] ch = new char[totLen]; int wpos = 0; for (Group g : Group.values()) { Component lastCompOfGroup = Component.FamilyName; for (Component c : Component.values()) { String s = get(g, c); if (s != null) { int d = c.ordinal() - lastCompOfGroup.ordinal(); while (d-- > 0) ch[wpos++] = '^'; d = s.length(); s.getChars(0, d, ch, wpos); wpos += d; lastCompOfGroup = c; } } if (g == lastGroup) break; ch[wpos++] = '='; } return new String(ch); } PersonName(); PersonName(String s); PersonName(String s, boolean lenient); String toString(); String toString(Group g, boolean trim); String get(Component c); String get(Group g, Component c); void set(Component c, String s); void set(Group g, Component c, String s); boolean isEmpty(); boolean contains(Group g); boolean contains(Group g, Component c); boolean contains(Component c); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testToString() { PersonName pn = new PersonName(); pn.set(PersonName.Component.FamilyName, "Morrison-Jones"); pn.set(PersonName.Component.GivenName, "Susan"); pn.set(PersonName.Component.NameSuffix, "Ph.D., Chief Executive Officer"); assertEquals("Morrison-Jones^Susan^^^Ph.D., Chief Executive Officer", pn.toString()); }
### Question: ValueSelector implements Serializable { @Override public String toString() { if (str == null) str = attributeSelector.toStringBuilder() .append("/Value[@number=\"") .append(valueIndex + 1) .append("\"]") .toString(); return str; } ValueSelector(int tag, String privateCreator, int index, ItemPointer... itemPointers); ValueSelector(AttributeSelector attributeSelector, int index); int tag(); String privateCreator(); int level(); ItemPointer itemPointer(int index); int valueIndex(); String selectStringValue(Attributes attrs, String defVal); @Override String toString(); static ValueSelector valueOf(String s); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testToString() { ItemPointer ip = new ItemPointer(Tag.RequestAttributesSequence, 0); ValueSelector vs = new ValueSelector(Tag.StudyInstanceUID, null, 0, ip); assertEquals(XPATH, vs.toString()); }
### Question: ValueSelector implements Serializable { public static ValueSelector valueOf(String s) { int fromIndex = s.lastIndexOf("DicomAttribute"); try { return new ValueSelector(AttributeSelector.valueOf(s), AttributeSelector.selectNumber(s, fromIndex) - 1); } catch (Exception e) { throw new IllegalArgumentException(s); } } ValueSelector(int tag, String privateCreator, int index, ItemPointer... itemPointers); ValueSelector(AttributeSelector attributeSelector, int index); int tag(); String privateCreator(); int level(); ItemPointer itemPointer(int index); int valueIndex(); String selectStringValue(Attributes attrs, String defVal); @Override String toString(); static ValueSelector valueOf(String s); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testValueOf() { ValueSelector vs = ValueSelector.valueOf(XPATH); assertEquals(Tag.StudyInstanceUID, vs.tag()); assertNull(vs.privateCreator()); assertEquals(0, vs.valueIndex()); assertEquals(1, vs.level()); ItemPointer ip = vs.itemPointer(0); assertEquals(Tag.RequestAttributesSequence, ip.sequenceTag); assertNull(ip.privateCreator); assertEquals(0, ip.itemIndex); }
### Question: ElementDictionary { public static VR vrOf(int tag, String privateCreator) { return getElementDictionary(privateCreator).vrOf(tag); } protected ElementDictionary(String privateCreator, Class<?> tagClass); static ElementDictionary getStandardElementDictionary(); static ElementDictionary getElementDictionary(String privateCreator); static void reload(); static VR vrOf(int tag, String privateCreator); static String keywordOf(int tag, String privateCreator); static int tagForKeyword(String keyword, String privateCreatorID); final String getPrivateCreator(); abstract VR vrOf(int tag); abstract String keywordOf(int tag); int tmTagOf(int daTag); int daTagOf(int tmTag); int tagForKeyword(String keyword); }### Answer: @Test public void testVrOf() { for (int i = 0; i < TAGS.length; i++) assertEquals(VRS[i], ElementDictionary.vrOf(TAGS[i], null)); } @Test public void testPrivateVrOf() { for (int i = 0; i < SIEMENS_CSA_HEADER_TAGS.length; i++) assertEquals(SIEMENS_CSA_HEADER_VRS[i], ElementDictionary.vrOf(SIEMENS_CSA_HEADER_TAGS[i], SIEMENS_CSA_HEADER)); for (int i = 0; i < SIEMENS_CSA_NON_IMAGE_TAGS.length; i++) assertEquals(SIEMENS_CSA_NON_IMAGE_VRS[i], ElementDictionary.vrOf(SIEMENS_CSA_NON_IMAGE_TAGS[i], SIEMENS_CSA_NON_IMAGE)); }
### Question: ElementDictionary { public static String keywordOf(int tag, String privateCreator) { return getElementDictionary(privateCreator).keywordOf(tag); } protected ElementDictionary(String privateCreator, Class<?> tagClass); static ElementDictionary getStandardElementDictionary(); static ElementDictionary getElementDictionary(String privateCreator); static void reload(); static VR vrOf(int tag, String privateCreator); static String keywordOf(int tag, String privateCreator); static int tagForKeyword(String keyword, String privateCreatorID); final String getPrivateCreator(); abstract VR vrOf(int tag); abstract String keywordOf(int tag); int tmTagOf(int daTag); int daTagOf(int tmTag); int tagForKeyword(String keyword); }### Answer: @Test public void testKeywordOf() { for (int i = 0; i < TAGS.length; i++) assertEquals(KEYWORDS[i], ElementDictionary.keywordOf(TAGS[i], null)); } @Test public void testPrivateKeywordOf() { for (int i = 0; i < SIEMENS_CSA_HEADER_TAGS.length; i++) assertEquals(SIEMENS_CSA_HEADER_KEYWORDS[i], ElementDictionary.keywordOf( SIEMENS_CSA_HEADER_TAGS[i], SIEMENS_CSA_HEADER)); for (int i = 0; i < SIEMENS_CSA_NON_IMAGE_TAGS.length; i++) assertEquals(SIEMENS_CSA_NON_IMAGE_KEYWORDS[i], ElementDictionary.keywordOf( SIEMENS_CSA_NON_IMAGE_TAGS[i], SIEMENS_CSA_NON_IMAGE)); }
### Question: ElementDictionary { public static int tagForKeyword(String keyword, String privateCreatorID) { return getElementDictionary(privateCreatorID).tagForKeyword(keyword); } protected ElementDictionary(String privateCreator, Class<?> tagClass); static ElementDictionary getStandardElementDictionary(); static ElementDictionary getElementDictionary(String privateCreator); static void reload(); static VR vrOf(int tag, String privateCreator); static String keywordOf(int tag, String privateCreator); static int tagForKeyword(String keyword, String privateCreatorID); final String getPrivateCreator(); abstract VR vrOf(int tag); abstract String keywordOf(int tag); int tmTagOf(int daTag); int daTagOf(int tmTag); int tagForKeyword(String keyword); }### Answer: @Test public void tagForKeyword() { for (int i = 0; i < KEYWORDS.length-1; i++) assertEquals(TAGS[i], ElementDictionary.tagForKeyword(KEYWORDS[i], null)); } @Test public void tagPrivateForKeyword() { for (int i = 0; i < SIEMENS_CSA_HEADER_KEYWORDS.length; i++) assertEquals(SIEMENS_CSA_HEADER_TAGS[i], ElementDictionary.tagForKeyword( SIEMENS_CSA_HEADER_KEYWORDS[i], SIEMENS_CSA_HEADER)); for (int i = 0; i < SIEMENS_CSA_NON_IMAGE_KEYWORDS.length; i++) assertEquals(SIEMENS_CSA_NON_IMAGE_TAGS[i], ElementDictionary.tagForKeyword( SIEMENS_CSA_NON_IMAGE_KEYWORDS[i], SIEMENS_CSA_NON_IMAGE)); }
### Question: DateUtils { public static String formatDA(TimeZone tz, Date date) { return formatDA(tz, date, new StringBuilder(8)).toString(); } static String formatDA(TimeZone tz, Date date); static StringBuilder formatDA(TimeZone tz, Date date, StringBuilder toAppendTo); static String formatTM(TimeZone tz, Date date); static String formatTM(TimeZone tz, Date date, DatePrecision precision); static String formatDT(TimeZone tz, Date date); static String formatDT(TimeZone tz, Date date, DatePrecision precision); static StringBuilder formatDT(TimeZone tz, Date date, StringBuilder toAppendTo, DatePrecision precision); static String formatTimezoneOffsetFromUTC(TimeZone tz); static String formatTimezoneOffsetFromUTC(TimeZone tz, Date date); static Date parseDA(TimeZone tz, String s); static Date parseDA(TimeZone tz, String s, boolean ceil); static Date parseTM(TimeZone tz, String s, DatePrecision precision); static Date parseTM(TimeZone tz, String s, boolean ceil, DatePrecision precision); static Date parseDT(TimeZone tz, String s, DatePrecision precision); static TimeZone timeZone(String s); static Date parseDT(TimeZone tz, String s, boolean ceil, DatePrecision precision); static final Date[] EMPTY_DATES; }### Answer: @Test public void testFormatDA() { assertEquals("19700101", DateUtils.formatDA(tz, new Date(0))); }
### Question: DateUtils { public static String formatTM(TimeZone tz, Date date) { return formatTM(tz, date, new DatePrecision()); } static String formatDA(TimeZone tz, Date date); static StringBuilder formatDA(TimeZone tz, Date date, StringBuilder toAppendTo); static String formatTM(TimeZone tz, Date date); static String formatTM(TimeZone tz, Date date, DatePrecision precision); static String formatDT(TimeZone tz, Date date); static String formatDT(TimeZone tz, Date date, DatePrecision precision); static StringBuilder formatDT(TimeZone tz, Date date, StringBuilder toAppendTo, DatePrecision precision); static String formatTimezoneOffsetFromUTC(TimeZone tz); static String formatTimezoneOffsetFromUTC(TimeZone tz, Date date); static Date parseDA(TimeZone tz, String s); static Date parseDA(TimeZone tz, String s, boolean ceil); static Date parseTM(TimeZone tz, String s, DatePrecision precision); static Date parseTM(TimeZone tz, String s, boolean ceil, DatePrecision precision); static Date parseDT(TimeZone tz, String s, DatePrecision precision); static TimeZone timeZone(String s); static Date parseDT(TimeZone tz, String s, boolean ceil, DatePrecision precision); static final Date[] EMPTY_DATES; }### Answer: @Test public void testFormatTM() { assertEquals("020000.000", DateUtils.formatTM(tz, new Date(0))); }
### Question: DateUtils { public static String formatDT(TimeZone tz, Date date) { return formatDT(tz, date, new DatePrecision()); } static String formatDA(TimeZone tz, Date date); static StringBuilder formatDA(TimeZone tz, Date date, StringBuilder toAppendTo); static String formatTM(TimeZone tz, Date date); static String formatTM(TimeZone tz, Date date, DatePrecision precision); static String formatDT(TimeZone tz, Date date); static String formatDT(TimeZone tz, Date date, DatePrecision precision); static StringBuilder formatDT(TimeZone tz, Date date, StringBuilder toAppendTo, DatePrecision precision); static String formatTimezoneOffsetFromUTC(TimeZone tz); static String formatTimezoneOffsetFromUTC(TimeZone tz, Date date); static Date parseDA(TimeZone tz, String s); static Date parseDA(TimeZone tz, String s, boolean ceil); static Date parseTM(TimeZone tz, String s, DatePrecision precision); static Date parseTM(TimeZone tz, String s, boolean ceil, DatePrecision precision); static Date parseDT(TimeZone tz, String s, DatePrecision precision); static TimeZone timeZone(String s); static Date parseDT(TimeZone tz, String s, boolean ceil, DatePrecision precision); static final Date[] EMPTY_DATES; }### Answer: @Test public void testFormatDT() { assertEquals("19700101020000.000", DateUtils.formatDT(tz, new Date(0))); } @Test public void testFormatDTwithTZ() { assertEquals("19700101020000.000+0200", DateUtils.formatDT(tz, new Date(0), new DatePrecision(Calendar.MILLISECOND, true))); }
### Question: DateUtils { public static Date parseDA(TimeZone tz, String s) { return parseDA(tz, s, false); } static String formatDA(TimeZone tz, Date date); static StringBuilder formatDA(TimeZone tz, Date date, StringBuilder toAppendTo); static String formatTM(TimeZone tz, Date date); static String formatTM(TimeZone tz, Date date, DatePrecision precision); static String formatDT(TimeZone tz, Date date); static String formatDT(TimeZone tz, Date date, DatePrecision precision); static StringBuilder formatDT(TimeZone tz, Date date, StringBuilder toAppendTo, DatePrecision precision); static String formatTimezoneOffsetFromUTC(TimeZone tz); static String formatTimezoneOffsetFromUTC(TimeZone tz, Date date); static Date parseDA(TimeZone tz, String s); static Date parseDA(TimeZone tz, String s, boolean ceil); static Date parseTM(TimeZone tz, String s, DatePrecision precision); static Date parseTM(TimeZone tz, String s, boolean ceil, DatePrecision precision); static Date parseDT(TimeZone tz, String s, DatePrecision precision); static TimeZone timeZone(String s); static Date parseDT(TimeZone tz, String s, boolean ceil, DatePrecision precision); static final Date[] EMPTY_DATES; }### Answer: @Test public void testParseDA() { assertEquals(-2 * HOUR, DateUtils.parseDA(tz, "19700101").getTime()); } @Test public void testParseDAacrnema() { assertEquals(-2 * HOUR, DateUtils.parseDA(tz, "1970.01.01").getTime()); } @Test public void testParseDAceil() { assertEquals(DAY - 2 * HOUR - 1, DateUtils.parseDA(tz, "19700101", true).getTime()); }
### Question: IntHashMap implements Cloneable, java.io.Serializable { public int size() { return size; } IntHashMap(); IntHashMap(int expectedMaxSize); int size(); boolean isEmpty(); @SuppressWarnings("unchecked") V get(int key); boolean containsKey(int key); @SuppressWarnings("unchecked") V put(int key, V value); void trimToSize(); void rehash(); @SuppressWarnings("unchecked") V remove(int key); void clear(); @SuppressWarnings("unchecked") Object clone(); @SuppressWarnings("unchecked") boolean accept(Visitor<V> visitor); }### Answer: @Test public void testSize() { assertEquals(15, map.size()); removeOdd(); assertEquals(7, map.size()); }
### Question: IntHashMap implements Cloneable, java.io.Serializable { @SuppressWarnings("unchecked") public V get(int key) { byte[] states = this.states; int[] keys = this.keys; int mask = keys.length - 1; int i = key & mask; while (states[i] != FREE) { if (keys[i] == key) return (V) values[i]; i = (i + 1) & mask; } return null; } IntHashMap(); IntHashMap(int expectedMaxSize); int size(); boolean isEmpty(); @SuppressWarnings("unchecked") V get(int key); boolean containsKey(int key); @SuppressWarnings("unchecked") V put(int key, V value); void trimToSize(); void rehash(); @SuppressWarnings("unchecked") V remove(int key); void clear(); @SuppressWarnings("unchecked") Object clone(); @SuppressWarnings("unchecked") boolean accept(Visitor<V> visitor); }### Answer: @Test public void testGet() { removeOdd(); testGet(map); }
### Question: IntHashMap implements Cloneable, java.io.Serializable { @SuppressWarnings("unchecked") public V put(int key, V value) { byte[] states = this.states; int[] keys = this.keys; int mask = keys.length - 1; int i = key & mask; while (states[i] > FREE) { if (keys[i] == key) { V oldValue = (V) values[i]; values[i] = value; return oldValue; } i = (i + 1) & mask; } byte oldState = states[i]; states[i] = FULL; keys[i] = key; values[i] = value; ++size; if (oldState == FREE && --free < 0) resize(Math.max(capacity(size), keys.length)); return null; } IntHashMap(); IntHashMap(int expectedMaxSize); int size(); boolean isEmpty(); @SuppressWarnings("unchecked") V get(int key); boolean containsKey(int key); @SuppressWarnings("unchecked") V put(int key, V value); void trimToSize(); void rehash(); @SuppressWarnings("unchecked") V remove(int key); void clear(); @SuppressWarnings("unchecked") Object clone(); @SuppressWarnings("unchecked") boolean accept(Visitor<V> visitor); }### Answer: @Test public void testPut() { removeOdd(); for (int i = 0; i < 45; i++) map.put(i, Integer.valueOf(i)); assertEquals(45, map.size()); for (int i = 0; i < 45; i++) assertEquals(Integer.valueOf(i), map.get(i)); }
### Question: IntHashMap implements Cloneable, java.io.Serializable { public boolean containsKey(int key) { byte[] states = this.states; int[] keys = this.keys; int mask = keys.length - 1; int i = key & mask; while (states[i] != FREE) { if (keys[i] == key) return states[i] > FREE; i = (i + 1) & mask; } return false; } IntHashMap(); IntHashMap(int expectedMaxSize); int size(); boolean isEmpty(); @SuppressWarnings("unchecked") V get(int key); boolean containsKey(int key); @SuppressWarnings("unchecked") V put(int key, V value); void trimToSize(); void rehash(); @SuppressWarnings("unchecked") V remove(int key); void clear(); @SuppressWarnings("unchecked") Object clone(); @SuppressWarnings("unchecked") boolean accept(Visitor<V> visitor); }### Answer: @Test public void testContainsKey() { removeOdd(); for (int i = 1; i < 45; i++) assertEquals((i & 1) == 0 && (i % 3) == 1, map.containsKey(i)); }
### Question: IntHashMap implements Cloneable, java.io.Serializable { public void rehash() { resize(keys.length); } IntHashMap(); IntHashMap(int expectedMaxSize); int size(); boolean isEmpty(); @SuppressWarnings("unchecked") V get(int key); boolean containsKey(int key); @SuppressWarnings("unchecked") V put(int key, V value); void trimToSize(); void rehash(); @SuppressWarnings("unchecked") V remove(int key); void clear(); @SuppressWarnings("unchecked") Object clone(); @SuppressWarnings("unchecked") boolean accept(Visitor<V> visitor); }### Answer: @Test public void testRehash() { removeOdd(); map.trimToSize(); testGet(map); }
### Question: IntHashMap implements Cloneable, java.io.Serializable { @SuppressWarnings("unchecked") public V remove(int key) { byte[] states = this.states; int[] keys = this.keys; int mask = keys.length - 1; int i = key & mask; while (states[i] != FREE) { if (keys[i] == key) { if (states[i] < FREE) return null; states[i] = REMOVED; V oldValue = (V) values[i]; values[i] = null; size--; return oldValue; } i = (i + 1) & mask; } return null; } IntHashMap(); IntHashMap(int expectedMaxSize); int size(); boolean isEmpty(); @SuppressWarnings("unchecked") V get(int key); boolean containsKey(int key); @SuppressWarnings("unchecked") V put(int key, V value); void trimToSize(); void rehash(); @SuppressWarnings("unchecked") V remove(int key); void clear(); @SuppressWarnings("unchecked") Object clone(); @SuppressWarnings("unchecked") boolean accept(Visitor<V> visitor); }### Answer: @Test public void testRemove() { for (int i = 1; i < 45; i += 2) if ((i % 3) == 1) assertEquals(Integer.valueOf(i), map.remove(i)); else assertNull(map.remove(i)); }
### Question: IntHashMap implements Cloneable, java.io.Serializable { public void clear() { Arrays.fill(values, null); Arrays.fill(states, FREE); size = 0; free = keys.length >>> 1; } IntHashMap(); IntHashMap(int expectedMaxSize); int size(); boolean isEmpty(); @SuppressWarnings("unchecked") V get(int key); boolean containsKey(int key); @SuppressWarnings("unchecked") V put(int key, V value); void trimToSize(); void rehash(); @SuppressWarnings("unchecked") V remove(int key); void clear(); @SuppressWarnings("unchecked") Object clone(); @SuppressWarnings("unchecked") boolean accept(Visitor<V> visitor); }### Answer: @Test public void testClear() { assertFalse(map.isEmpty()); map.clear(); assertTrue(map.isEmpty()); }
### Question: IntHashMap implements Cloneable, java.io.Serializable { @SuppressWarnings("unchecked") public Object clone() { try { IntHashMap<V> m = (IntHashMap<V>) super.clone(); m.states = states.clone(); m.keys = keys.clone(); m.values = values.clone(); return m; } catch (CloneNotSupportedException e) { throw new InternalError(); } } IntHashMap(); IntHashMap(int expectedMaxSize); int size(); boolean isEmpty(); @SuppressWarnings("unchecked") V get(int key); boolean containsKey(int key); @SuppressWarnings("unchecked") V put(int key, V value); void trimToSize(); void rehash(); @SuppressWarnings("unchecked") V remove(int key); void clear(); @SuppressWarnings("unchecked") Object clone(); @SuppressWarnings("unchecked") boolean accept(Visitor<V> visitor); }### Answer: @SuppressWarnings("unchecked") @Test public void testClone() { removeOdd(); IntHashMap<Integer> clone = (IntHashMap<Integer>) map.clone(); map.clear(); testGet(clone); }
### Question: AttributeSelector implements Serializable { @Override public String toString() { if (str == null) str = toStringBuilder().toString(); return str; } AttributeSelector(int tag); AttributeSelector(int tag, String privateCreator); AttributeSelector(int tag, String privateCreator, ItemPointer... itemPointers); AttributeSelector(int tag, String privateCreator, List<ItemPointer> itemPointers); int tag(); String privateCreator(); int level(); ItemPointer itemPointer(int index); String selectStringValue(Attributes attrs, int valueIndex, String defVal); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static AttributeSelector valueOf(String s); boolean matches(List<ItemPointer> itemPointers, String privateCreator, int tag); }### Answer: @Test public void testToString() { ItemPointer ip = new ItemPointer(Tag.RequestAttributesSequence); AttributeSelector selector = new AttributeSelector(Tag.StudyInstanceUID, null, ip); assertEquals(XPATH, selector.toString()); }
### Question: AttributeSelector implements Serializable { public static AttributeSelector valueOf(String s) { int fromIndex = s.lastIndexOf("DicomAttribute"); try { return new AttributeSelector( selectTag(s, fromIndex), selectPrivateCreator(s, fromIndex), itemPointersOf(s, fromIndex)); } catch (Exception e) { throw new IllegalArgumentException(s); } } AttributeSelector(int tag); AttributeSelector(int tag, String privateCreator); AttributeSelector(int tag, String privateCreator, ItemPointer... itemPointers); AttributeSelector(int tag, String privateCreator, List<ItemPointer> itemPointers); int tag(); String privateCreator(); int level(); ItemPointer itemPointer(int index); String selectStringValue(Attributes attrs, int valueIndex, String defVal); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static AttributeSelector valueOf(String s); boolean matches(List<ItemPointer> itemPointers, String privateCreator, int tag); }### Answer: @Test public void testValueOf() { AttributeSelector selector = AttributeSelector.valueOf(XPATH); assertEquals(Tag.StudyInstanceUID, selector.tag()); assertNull(selector.privateCreator()); assertEquals(1, selector.level()); ItemPointer ip = selector.itemPointer(0); assertEquals(Tag.RequestAttributesSequence, ip.sequenceTag); assertNull(ip.privateCreator); assertEquals(-1, ip.itemIndex); }
### Question: Post extends AuditableEntity { @PrePersist public void slugify(){ this.slug = new Slugify().slugify(this.title); } @PrePersist void slugify(); }### Answer: @Test public void testSlug() { System.out.println("getSlug"); Post instance = new Post(); instance.setTitle("test post 1"); instance.slugify(); assertEquals("test-post-1", instance.getSlug()); }
### Question: PostService { public Post createPost(PostForm form) { Post _post = Post.builder() .title(form.getTitle()) .content(form.getContent()) .build(); Post saved = this.postRepository.save(_post); return saved; } Post createPost(PostForm form); Post updatePost(String slug, PostForm form); void deletePost(String slug); }### Answer: @Test public void createPost() { final String TITLE = "test post title"; final String CONTENT = "test post content"; final PostForm input = PostForm.builder().title(TITLE).content(CONTENT).build(); Post expected = Post.builder().title(TITLE).content(CONTENT).build(); expected.setId(1L); given(posts.save(Post.builder().title(input.getTitle()).content(input.getContent()).build())) .willReturn(expected); Post returned = postService.createPost(input); assertTrue(returned == expected); verify(posts, times(1)).save(any(Post.class)); verifyNoMoreInteractions(posts); }
### Question: UserServiceClient { public User findByUsername(String username) { try { ResponseEntity<User> response = this.restTemplate.getForEntity(userServiceUrl + "/users/{username}", User.class, username); return response.getBody(); } catch (HttpClientErrorException e) { if (e.getStatusCode() == NOT_FOUND) { return null; } } return null; } UserServiceClient(RestTemplateBuilder builder, ObjectMapper objectMapper); void handleSignup(SignupForm form); User findByUsername(String username); }### Answer: @Test public void testFindbyUsername() { this.server.expect(requestTo(userServiceUrl + "/users/user")) .andRespond(withSuccess(new ClassPathResource("/find-user-by-username.json"), MediaType.APPLICATION_JSON_UTF8)); User user = this.client.findByUsername("user"); assertNotNull(user); assertEquals("user", user.getUsername()); this.server.verify(); } @Test public void testFindbyUsername_notFound() { this.server.expect(requestTo(userServiceUrl + "/users/user1")) .andRespond(withStatus(NOT_FOUND)); User user = this.client.findByUsername("user1"); assertNull(user); this.server.verify(); }
### Question: GraphUIController { public void refresh() { if (dfa == null) { throw new IllegalStateException("Graph has not been built using start() yet."); } panel.renderGraph(dfa); if (!panel.isJumpToActionEnabled()) { updateStatePanel(); } } GraphUIController(VisualGraphPanel panel); void start(final DFAExecution<? extends LatticeElement> dfa); void setStatePanel(StatePanelOpen statePanel); void refresh(); void stop(); }### Answer: @Test(expected = IllegalStateException.class) public void refreshShouldNotBePossibleBeforeStart() { controller.refresh(); }
### Question: Tracing extends org.apache.cassandra.tracing.Tracing { Span spanFromPayload(Tracer tracer, @Nullable Map<String, ByteBuffer> payload) { ByteBuffer b3 = payload != null ? payload.get("b3") : null; if (b3 == null) return tracer.nextSpan(); TraceContextOrSamplingFlags extracted = B3SingleFormat.parseB3SingleFormat(UTF_8.decode(b3)); if (extracted == null) return tracer.nextSpan(); return tracer.nextSpan(extracted); } Tracing(brave.Tracing tracing); Tracing(); @Override final TraceState begin( String request, InetAddress client, Map<String, String> parameters); @Override final void trace(ByteBuffer sessionId, String message, int ttl); }### Answer: @Test public void spanFromPayload_startsTraceOnNullPayload() { assertThat(cassandraTracing.spanFromPayload(tracing.tracer(), null)) .isNotNull(); } @Test public void spanFromPayload_startsTraceOnAbsentB3SingleEntry() { assertThat(cassandraTracing.spanFromPayload(tracing.tracer(), Collections.emptyMap())) .isNotNull(); } @Test public void spanFromPayload_resumesTraceOnB3SingleEntry() { assertThat(cassandraTracing.spanFromPayload(tracing.tracer(), Collections.singletonMap("b3", ByteBuffer.wrap(new byte[] {'0'})))) .extracting(b -> b.isNoop()) .isEqualTo(Boolean.TRUE); }
### Question: HashTableHipsterDirectedGraph extends HashTableHipsterGraph<V,E> implements HipsterDirectedGraph<V,E> { @Override public GraphEdge<V,E> connect(V v1, V v2, E value){ Preconditions.checkArgument(v1 != null && v2 != null, "Vertices cannot be null"); GraphEdge<V,E> edge = new DirectedEdge<V, E>(v1, v2, value); graphTable.put(v1, v2, edge); disconnected.remove(v1); disconnected.remove(v2); return edge; } @Override GraphEdge<V,E> connect(V v1, V v2, E value); @Override Iterable<GraphEdge<V, E>> outgoingEdgesOf(V vertex); @Override Iterable<GraphEdge<V, E>> incomingEdgesOf(V vertex); static HashTableHipsterDirectedGraph<V, E> create(); }### Answer: @Test public void testConnect() throws Exception { directedGraph.connect("F", "G", 1d); assertEquals("F", directedGraph.incomingEdgesOf("G").iterator().next().getVertex1()); }
### Question: HashBasedHipsterGraph implements HipsterMutableGraph<V,E> { @Override public boolean add(V v){ if(!connected.containsKey(v)){ connected.put(v, new LinkedHashSet<GraphEdge<V, E>>()); return true; } return false; } HashBasedHipsterGraph(); @Override boolean add(V v); @Override Set<V> add(V... vertices); @Override boolean remove(V v); @Override Set<V> remove(V... vertices); @Override GraphEdge<V,E> connect(V v1, V v2, E value); GraphEdge<V,E> buildEdge(V v1, V v2, E value); @Override Iterable<GraphEdge<V, E>> edges(); @Override Iterable<V> vertices(); @Override Iterable<GraphEdge<V, E>> edgesOf(V vertex); HashMap<V, Set<GraphEdge<V, E>>> getConnected(); void setConnected(HashMap<V, Set<GraphEdge<V, E>>> connected); static HashBasedHipsterGraph<V, E> create(); }### Answer: @Test public void testEdgesWithDisconnectedVertices() throws Exception { graph.add("X"); graph.add("Y"); testGraphEdges(); } @Test public void testAdd() throws Exception { graph.add("X"); Set vertices = Sets.newHashSet(graph.vertices()); assertTrue(vertices.contains("X")); assertTrue(vertices.size()==size+1); }
### Question: HashBasedHipsterGraph implements HipsterMutableGraph<V,E> { @Override public boolean remove(V v){ Set<GraphEdge<V, E>> edges = this.connected.get(v); if (edges == null) return false; for(Iterator<GraphEdge<V,E>> it = edges.iterator(); it.hasNext(); ){ GraphEdge<V,E> edge = it.next(); it.remove(); V v2 = edge.getVertex1().equals(v) ? edge.getVertex2() : edge.getVertex1(); for(Iterator<GraphEdge<V,E>> it2 = this.connected.get(v2).iterator(); it2.hasNext();){ GraphEdge<V,E> edge2 = it2.next(); if (edge2.getVertex1().equals(v) || edge2.getVertex2().equals(v)){ it2.remove(); } } } this.connected.remove(v); return true; } HashBasedHipsterGraph(); @Override boolean add(V v); @Override Set<V> add(V... vertices); @Override boolean remove(V v); @Override Set<V> remove(V... vertices); @Override GraphEdge<V,E> connect(V v1, V v2, E value); GraphEdge<V,E> buildEdge(V v1, V v2, E value); @Override Iterable<GraphEdge<V, E>> edges(); @Override Iterable<V> vertices(); @Override Iterable<GraphEdge<V, E>> edgesOf(V vertex); HashMap<V, Set<GraphEdge<V, E>>> getConnected(); void setConnected(HashMap<V, Set<GraphEdge<V, E>>> connected); static HashBasedHipsterGraph<V, E> create(); }### Answer: @Test public void testRemove() throws Exception { graph.remove("v1"); assertFalse(Sets.newHashSet(graph.vertices()).contains("v1")); }
### Question: HashBasedHipsterGraph implements HipsterMutableGraph<V,E> { @Override public GraphEdge<V,E> connect(V v1, V v2, E value){ if(v1 == null || v2 == null) throw new IllegalArgumentException("Invalid vertices. A vertex cannot be null"); if (!connected.containsKey(v1)) throw new IllegalArgumentException(v1 + " is not a vertex of the graph"); if (!connected.containsKey(v2)) throw new IllegalArgumentException(v2 + " is not a vertex of the graph"); GraphEdge<V,E> edge = buildEdge(v1, v2, value); connected.get(v1).add(edge); connected.get(v2).add(edge); return edge; } HashBasedHipsterGraph(); @Override boolean add(V v); @Override Set<V> add(V... vertices); @Override boolean remove(V v); @Override Set<V> remove(V... vertices); @Override GraphEdge<V,E> connect(V v1, V v2, E value); GraphEdge<V,E> buildEdge(V v1, V v2, E value); @Override Iterable<GraphEdge<V, E>> edges(); @Override Iterable<V> vertices(); @Override Iterable<GraphEdge<V, E>> edgesOf(V vertex); HashMap<V, Set<GraphEdge<V, E>>> getConnected(); void setConnected(HashMap<V, Set<GraphEdge<V, E>>> connected); static HashBasedHipsterGraph<V, E> create(); }### Answer: @Test public void testConnect() throws Exception { graph.add("X"); graph.add("Y"); graph.connect("X","Y",1.0d); assertTrue(Sets.newHashSet(graph.vertices()).contains("X")); assertTrue(Sets.newHashSet(graph.vertices()).contains("Y")); }
### Question: HashBasedHipsterGraph implements HipsterMutableGraph<V,E> { @Override public Iterable<V> vertices() { return connected.keySet(); } HashBasedHipsterGraph(); @Override boolean add(V v); @Override Set<V> add(V... vertices); @Override boolean remove(V v); @Override Set<V> remove(V... vertices); @Override GraphEdge<V,E> connect(V v1, V v2, E value); GraphEdge<V,E> buildEdge(V v1, V v2, E value); @Override Iterable<GraphEdge<V, E>> edges(); @Override Iterable<V> vertices(); @Override Iterable<GraphEdge<V, E>> edgesOf(V vertex); HashMap<V, Set<GraphEdge<V, E>>> getConnected(); void setConnected(HashMap<V, Set<GraphEdge<V, E>>> connected); static HashBasedHipsterGraph<V, E> create(); }### Answer: @Test public void testVertices() throws Exception { Set vertices = Sets.newHashSet(graph.vertices()); assertEquals(size, vertices.size()); }
### Question: HashBasedHipsterGraph implements HipsterMutableGraph<V,E> { @Override public Iterable<GraphEdge<V, E>> edgesOf(V vertex) { Set<GraphEdge<V, E>> set = connected.get(vertex); if (set == null) set = Collections.emptySet(); return set; } HashBasedHipsterGraph(); @Override boolean add(V v); @Override Set<V> add(V... vertices); @Override boolean remove(V v); @Override Set<V> remove(V... vertices); @Override GraphEdge<V,E> connect(V v1, V v2, E value); GraphEdge<V,E> buildEdge(V v1, V v2, E value); @Override Iterable<GraphEdge<V, E>> edges(); @Override Iterable<V> vertices(); @Override Iterable<GraphEdge<V, E>> edgesOf(V vertex); HashMap<V, Set<GraphEdge<V, E>>> getConnected(); void setConnected(HashMap<V, Set<GraphEdge<V, E>>> connected); static HashBasedHipsterGraph<V, E> create(); }### Answer: @Test public void testEdgesOf() throws Exception { Set edges = Sets.newHashSet(graph.edgesOf("v1")); assertEquals(size-1, edges.size()); }
### Question: HashBasedHipsterDirectedGraph extends HashBasedHipsterGraph<V, E> implements HipsterMutableGraph<V, E>, HipsterDirectedGraph<V, E> { @Override public Iterable<GraphEdge<V, E>> outgoingEdgesOf(final V vertex) { return F.filter(edgesOf(vertex), new Function<GraphEdge<V, E>, Boolean>() { @Override public Boolean apply(GraphEdge<V, E> edge) { return edge.getVertex1().equals(vertex); } }); } @Override GraphEdge<V, E> buildEdge(V v1, V v2, E value); @Override Iterable<GraphEdge<V, E>> outgoingEdgesOf(final V vertex); @Override Iterable<GraphEdge<V, E>> incomingEdgesOf(final V vertex); @Override Iterable<GraphEdge<V, E>> edges(); static HashBasedHipsterDirectedGraph<V, E> create(); }### Answer: @Test public void testOutgoingEdgesOf() throws Exception { for(int i=0; i<size; i++) { Set edges = Sets.newHashSet(graph.outgoingEdgesOf("v"+i)); assertEquals(size-(i+1), edges.size()); } }
### Question: HashBasedHipsterDirectedGraph extends HashBasedHipsterGraph<V, E> implements HipsterMutableGraph<V, E>, HipsterDirectedGraph<V, E> { @Override public Iterable<GraphEdge<V, E>> incomingEdgesOf(final V vertex) { return F.filter(edgesOf(vertex), new Function<GraphEdge<V, E>, Boolean>() { @Override public Boolean apply(GraphEdge<V, E> edge) { return edge.getVertex2().equals(vertex); } }); } @Override GraphEdge<V, E> buildEdge(V v1, V v2, E value); @Override Iterable<GraphEdge<V, E>> outgoingEdgesOf(final V vertex); @Override Iterable<GraphEdge<V, E>> incomingEdgesOf(final V vertex); @Override Iterable<GraphEdge<V, E>> edges(); static HashBasedHipsterDirectedGraph<V, E> create(); }### Answer: @Test public void testIncomingEdgesOf() throws Exception { for(int i=0; i<size; i++) { Set edges = Sets.newHashSet(graph.incomingEdgesOf("v"+i)); assertEquals(i, edges.size()); } }
### Question: HashBasedHipsterDirectedGraph extends HashBasedHipsterGraph<V, E> implements HipsterMutableGraph<V, E>, HipsterDirectedGraph<V, E> { @Override public Iterable<GraphEdge<V, E>> edges() { return F.map( F.filter(HashBasedHipsterDirectedGraph.super.vedges(), new Function<Map.Entry<V, GraphEdge<V, E>>, Boolean>() { @Override public Boolean apply(Map.Entry<V, GraphEdge<V, E>> input) { return input.getKey().equals(input.getValue().getVertex1()); } }), new Function<Map.Entry<V, GraphEdge<V, E>>, GraphEdge<V, E>>() { @Override public GraphEdge<V, E> apply(Map.Entry<V, GraphEdge<V, E>> input) { return input.getValue(); } }); } @Override GraphEdge<V, E> buildEdge(V v1, V v2, E value); @Override Iterable<GraphEdge<V, E>> outgoingEdgesOf(final V vertex); @Override Iterable<GraphEdge<V, E>> incomingEdgesOf(final V vertex); @Override Iterable<GraphEdge<V, E>> edges(); static HashBasedHipsterDirectedGraph<V, E> create(); }### Answer: @Test public void testEdges() throws Exception { Set edges = Sets.newHashSet(graph.edges()); assertEquals(size*(size-1)/2, edges.size()); }
### Question: HashTableHipsterDirectedGraph extends HashTableHipsterGraph<V,E> implements HipsterDirectedGraph<V,E> { @Override public Iterable<GraphEdge<V, E>> outgoingEdgesOf(V vertex) { return graphTable.row(vertex).values(); } @Override GraphEdge<V,E> connect(V v1, V v2, E value); @Override Iterable<GraphEdge<V, E>> outgoingEdgesOf(V vertex); @Override Iterable<GraphEdge<V, E>> incomingEdgesOf(V vertex); static HashTableHipsterDirectedGraph<V, E> create(); }### Answer: @Test public void testOutgoingEdgesOf() throws Exception { Set<DirectedEdge<String, Double>> expected = new HashSet<DirectedEdge<String, Double>>(); expected.add(new DirectedEdge<String, Double>("B", "C", 5d)); expected.add(new DirectedEdge<String, Double>("B", "D", 10d)); assertEquals(expected, Sets.newHashSet(directedGraph.outgoingEdgesOf("B"))); }
### Question: HashTableHipsterDirectedGraph extends HashTableHipsterGraph<V,E> implements HipsterDirectedGraph<V,E> { @Override public Iterable<GraphEdge<V, E>> incomingEdgesOf(V vertex) { return graphTable.column(vertex).values(); } @Override GraphEdge<V,E> connect(V v1, V v2, E value); @Override Iterable<GraphEdge<V, E>> outgoingEdgesOf(V vertex); @Override Iterable<GraphEdge<V, E>> incomingEdgesOf(V vertex); static HashTableHipsterDirectedGraph<V, E> create(); }### Answer: @Test public void testIncomingEdgesOf() throws Exception { Set<DirectedEdge<String, Double>> expected = new HashSet<DirectedEdge<String, Double>>(); expected.add(new DirectedEdge<String, Double>("B", "C", 5d)); expected.add(new DirectedEdge<String, Double>("A", "C", 2d)); assertEquals(expected, Sets.newHashSet(directedGraph.incomingEdgesOf("C"))); }
### Question: HashTableHipsterGraph implements HipsterGraph<V,E> { public void add(V v){ if (!graphTable.containsColumn(v) && !graphTable.containsRow(v)){ disconnected.add(v); } } void add(V v); void remove(V v); void remove(V v, GraphEdge<V,E> edge); GraphEdge<V,E> connect(V v1, V v2, E value); @Override Iterable<GraphEdge<V, E>> edges(); @Override Iterable<V> vertices(); @Override Iterable<GraphEdge<V, E>> edgesOf(V vertex); static HashTableHipsterGraph<V, E> create(); }### Answer: @Test public void testAdd() throws Exception { graph.add("G"); assertTrue(Sets.newHashSet(graph.vertices()).contains("G")); }
### Question: HashTableHipsterGraph implements HipsterGraph<V,E> { public void remove(V v){ for(GraphEdge<V,E> edge : edgesOf(v)){ V connectedVertex = edge.getVertex1().equals(v) ? edge.getVertex2() : edge.getVertex1(); if (!greaterThan(1, edgesOf(connectedVertex))){ disconnected.add(connectedVertex); } } if (graphTable.containsRow(v)){ graphTable.row(v).clear(); } if (graphTable.containsColumn(v)){ graphTable.column(v).clear(); } disconnected.remove(v); } void add(V v); void remove(V v); void remove(V v, GraphEdge<V,E> edge); GraphEdge<V,E> connect(V v1, V v2, E value); @Override Iterable<GraphEdge<V, E>> edges(); @Override Iterable<V> vertices(); @Override Iterable<GraphEdge<V, E>> edgesOf(V vertex); static HashTableHipsterGraph<V, E> create(); }### Answer: @Test public void testRemove() throws Exception { graph.remove("B"); assertFalse(Sets.newHashSet(graph.vertices()).contains("B")); }
### Question: HashTableHipsterGraph implements HipsterGraph<V,E> { public GraphEdge<V,E> connect(V v1, V v2, E value){ Preconditions.checkArgument(v1 != null && v2 != null, "Vertices cannot be null"); GraphEdge<V,E> edge = new UndirectedEdge<V, E>(v1, v2, value); graphTable.put(v1, v2, edge); graphTable.put(v2, v1, edge); disconnected.remove(v1); disconnected.remove(v2); return edge; } void add(V v); void remove(V v); void remove(V v, GraphEdge<V,E> edge); GraphEdge<V,E> connect(V v1, V v2, E value); @Override Iterable<GraphEdge<V, E>> edges(); @Override Iterable<V> vertices(); @Override Iterable<GraphEdge<V, E>> edgesOf(V vertex); static HashTableHipsterGraph<V, E> create(); }### Answer: @Test public void testConnect() throws Exception { graph.connect("X","Y",1.0d); assertTrue(Sets.newHashSet(graph.vertices()).contains("X")); assertTrue(Sets.newHashSet(graph.vertices()).contains("Y")); }
### Question: HashTableHipsterGraph implements HipsterGraph<V,E> { @Override public Iterable<GraphEdge<V, E>> edges() { return graphTable.values(); } void add(V v); void remove(V v); void remove(V v, GraphEdge<V,E> edge); GraphEdge<V,E> connect(V v1, V v2, E value); @Override Iterable<GraphEdge<V, E>> edges(); @Override Iterable<V> vertices(); @Override Iterable<GraphEdge<V, E>> edgesOf(V vertex); static HashTableHipsterGraph<V, E> create(); }### Answer: @Test public void testEdges() throws Exception { Set<GraphEdge<String,Double>> expected = new HashSet<GraphEdge<String, Double>>(); expected.add(new UndirectedEdge<String, Double>("A","B",4d)); expected.add(new UndirectedEdge<String, Double>("A","C",2d)); expected.add(new UndirectedEdge<String, Double>("B","C",5d)); expected.add(new UndirectedEdge<String, Double>("B","D",10d)); expected.add(new UndirectedEdge<String, Double>("C","E",3d)); expected.add(new UndirectedEdge<String, Double>("D","F",11d)); expected.add(new UndirectedEdge<String, Double>("E","D",4d)); assertEquals(expected, Sets.newHashSet(graph.edges())); }
### Question: HashTableHipsterGraph implements HipsterGraph<V,E> { @Override public Iterable<V> vertices() { return Sets.union(Sets.union(graphTable.rowKeySet(), graphTable.columnKeySet()), disconnected); } void add(V v); void remove(V v); void remove(V v, GraphEdge<V,E> edge); GraphEdge<V,E> connect(V v1, V v2, E value); @Override Iterable<GraphEdge<V, E>> edges(); @Override Iterable<V> vertices(); @Override Iterable<GraphEdge<V, E>> edgesOf(V vertex); static HashTableHipsterGraph<V, E> create(); }### Answer: @Test public void testVertices() throws Exception { Set<String> expected = Sets.newHashSet("A","B","C","D","E","F"); assertEquals(expected, graph.vertices()); }
### Question: HashTableHipsterGraph implements HipsterGraph<V,E> { @Override public Iterable<GraphEdge<V, E>> edgesOf(V vertex) { return Sets.union(Sets.newHashSet(graphTable.row(vertex).values()), Sets.newHashSet(graphTable.column(vertex).values())); } void add(V v); void remove(V v); void remove(V v, GraphEdge<V,E> edge); GraphEdge<V,E> connect(V v1, V v2, E value); @Override Iterable<GraphEdge<V, E>> edges(); @Override Iterable<V> vertices(); @Override Iterable<GraphEdge<V, E>> edgesOf(V vertex); static HashTableHipsterGraph<V, E> create(); }### Answer: @Test public void testEdgesOf() throws Exception { Set<GraphEdge<String,Double>> expected = new HashSet<GraphEdge<String, Double>>(); expected.add(new UndirectedEdge<String, Double>("B","D",10d)); expected.add(new UndirectedEdge<String, Double>("A","B",4d)); expected.add(new UndirectedEdge<String, Double>("B","C",5d)); assertEquals(expected, graph.edgesOf("B")); }
### Question: HashBasedHipsterGraph implements HipsterMutableGraph<V,E> { @Override public Iterable<GraphEdge<V, E>> edges() { return F.map(vedges(), new Function<Map.Entry<V, GraphEdge<V, E>>, GraphEdge<V, E>>() { @Override public GraphEdge<V, E> apply(Map.Entry<V, GraphEdge<V, E>> entry) { return entry.getValue(); } }); } HashBasedHipsterGraph(); @Override boolean add(V v); @Override Set<V> add(V... vertices); @Override boolean remove(V v); @Override Set<V> remove(V... vertices); @Override GraphEdge<V,E> connect(V v1, V v2, E value); GraphEdge<V,E> buildEdge(V v1, V v2, E value); @Override Iterable<GraphEdge<V, E>> edges(); @Override Iterable<V> vertices(); @Override Iterable<GraphEdge<V, E>> edgesOf(V vertex); HashMap<V, Set<GraphEdge<V, E>>> getConnected(); void setConnected(HashMap<V, Set<GraphEdge<V, E>>> connected); static HashBasedHipsterGraph<V, E> create(); }### Answer: @Test public void testEdges() throws Exception { testGraphEdges(); }
### Question: CallArgumentsToByteArray { public byte[] getGasPrice() { byte[] gasPrice = new byte[] {0}; if (args.gasPrice != null && args.gasPrice.length() != 0) { gasPrice = stringHexToByteArray(args.gasPrice); } return gasPrice; } CallArgumentsToByteArray(Web3.CallArguments args); byte[] getGasPrice(); byte[] getGasLimit(); byte[] getToAddress(); byte[] getValue(); byte[] getData(); RskAddress getFromAddress(); }### Answer: @Test public void getGasPriceWhenValueIsNull() throws Exception { Web3.CallArguments args = new Web3.CallArguments(); CallArgumentsToByteArray byteArrayArgs = new CallArgumentsToByteArray(args); Assert.assertArrayEquals(new byte[] {0}, byteArrayArgs.getGasPrice()); } @Test public void getGasPriceWhenValueIsEmpty() throws Exception { Web3.CallArguments args = new Web3.CallArguments(); args.gasPrice = ""; CallArgumentsToByteArray byteArrayArgs = new CallArgumentsToByteArray(args); Assert.assertArrayEquals(new byte[] {0}, byteArrayArgs.getGasPrice()); }
### Question: Value { public boolean isEmpty() { if (isNull()) { return true; } if (isBytes() && asBytes().length == 0) { return true; } if (isList() && asList().isEmpty()) { return true; } if (isString() && asString().equals("")) { return true; } return false; } Value(); Value(Object obj); static Value fromRlpEncoded(byte[] data); void init(byte[] rlp); Object asObj(); List<Object> asList(); int asInt(); long asLong(); BigInteger asBigInt(); String asString(); byte[] asBytes(); String getHex(); byte[] getData(); int[] asSlice(); Value get(int index); byte[] encode(); byte[] hash(); boolean isList(); boolean isString(); boolean isInt(); boolean isLong(); boolean isBigInt(); boolean isBytes(); boolean isReadableString(); boolean isHexString(); boolean isHashCode(); boolean isNull(); boolean isEmpty(); int length(); String toString(); }### Answer: @Test public void isEmpty_Array() { Value val = new Value(new String[0]); assertTrue(val.isEmpty()); } @Test public void isEmpty_Null() { Value val = new Value(null); assertTrue(val.isEmpty()); } @Test public void isEmpty_EmptyString() { Value val = new Value(""); assertTrue(val.isEmpty()); } @Test public void isEmpty_Bytes() { Value val = new Value(new byte[0]); assertTrue(val.isEmpty()); }
### Question: LockWhitelist { public Integer getSize() { return whitelistedAddresses.size(); } LockWhitelist(Map<Address, LockWhitelistEntry> whitelistedAddresses); LockWhitelist(Map<Address, LockWhitelistEntry> whitelistedAddresses, int disableBlockHeight); boolean isWhitelisted(Address address); boolean isWhitelisted(byte[] address); boolean isWhitelistedFor(Address address, Coin amount, int height); Integer getSize(); List<Address> getAddresses(); List<T> getAll(Class<T> type); List<LockWhitelistEntry> getAll(); LockWhitelistEntry get(Address address); boolean put(Address address, LockWhitelistEntry entry); boolean remove(Address address); void consume(Address address); int getDisableBlockHeight(); void setDisableBlockHeight(int disableBlockHeight); boolean isDisableBlockSet(); }### Answer: @Test public void getSize() { Assert.assertEquals(4, whitelist.getSize().intValue()); }
### Question: LockWhitelist { public List<Address> getAddresses() { return new ArrayList<>(whitelistedAddresses.keySet()); } LockWhitelist(Map<Address, LockWhitelistEntry> whitelistedAddresses); LockWhitelist(Map<Address, LockWhitelistEntry> whitelistedAddresses, int disableBlockHeight); boolean isWhitelisted(Address address); boolean isWhitelisted(byte[] address); boolean isWhitelistedFor(Address address, Coin amount, int height); Integer getSize(); List<Address> getAddresses(); List<T> getAll(Class<T> type); List<LockWhitelistEntry> getAll(); LockWhitelistEntry get(Address address); boolean put(Address address, LockWhitelistEntry entry); boolean remove(Address address); void consume(Address address); int getDisableBlockHeight(); void setDisableBlockHeight(int disableBlockHeight); boolean isDisableBlockSet(); }### Answer: @Test public void getAddresses() { Assert.assertNotSame(whitelist.getAddresses(), addresses); Assert.assertThat(whitelist.getAddresses(), containsInAnyOrder(addresses.keySet().toArray())); }
### Question: LockWhitelist { public boolean isWhitelisted(Address address) { return whitelistedAddresses.containsKey(address); } LockWhitelist(Map<Address, LockWhitelistEntry> whitelistedAddresses); LockWhitelist(Map<Address, LockWhitelistEntry> whitelistedAddresses, int disableBlockHeight); boolean isWhitelisted(Address address); boolean isWhitelisted(byte[] address); boolean isWhitelistedFor(Address address, Coin amount, int height); Integer getSize(); List<Address> getAddresses(); List<T> getAll(Class<T> type); List<LockWhitelistEntry> getAll(); LockWhitelistEntry get(Address address); boolean put(Address address, LockWhitelistEntry entry); boolean remove(Address address); void consume(Address address); int getDisableBlockHeight(); void setDisableBlockHeight(int disableBlockHeight); boolean isDisableBlockSet(); }### Answer: @Test public void isWhitelisted() { for (Address address : addresses.keySet()) { assertExistance(address, true); } Address randomAddress = Address.fromBase58( NetworkParameters.fromID(NetworkParameters.ID_REGTEST), "n3PLxDiwWqa5uH7fSbHCxS6VAjD9Y7Rwkj" ); assertExistance(randomAddress, false); }
### Question: LockWhitelist { public boolean remove(Address address) { return whitelistedAddresses.remove(address) != null; } LockWhitelist(Map<Address, LockWhitelistEntry> whitelistedAddresses); LockWhitelist(Map<Address, LockWhitelistEntry> whitelistedAddresses, int disableBlockHeight); boolean isWhitelisted(Address address); boolean isWhitelisted(byte[] address); boolean isWhitelistedFor(Address address, Coin amount, int height); Integer getSize(); List<Address> getAddresses(); List<T> getAll(Class<T> type); List<LockWhitelistEntry> getAll(); LockWhitelistEntry get(Address address); boolean put(Address address, LockWhitelistEntry entry); boolean remove(Address address); void consume(Address address); int getDisableBlockHeight(); void setDisableBlockHeight(int disableBlockHeight); boolean isDisableBlockSet(); }### Answer: @Test public void remove() { Assert.assertTrue(whitelist.isWhitelisted(existingAddress)); Assert.assertTrue(whitelist.isWhitelisted(existingAddress.getHash160())); Assert.assertTrue(whitelist.remove(existingAddress)); Assert.assertFalse(whitelist.isWhitelisted(existingAddress)); Assert.assertFalse(whitelist.isWhitelisted(existingAddress.getHash160())); Assert.assertFalse(whitelist.remove(existingAddress)); }
### Question: LockWhitelist { public <T extends LockWhitelistEntry> List<T> getAll(Class<T> type) { return whitelistedAddresses.values().stream() .filter(e -> e.getClass() == type) .map(type::cast) .collect(Collectors.toList()); } LockWhitelist(Map<Address, LockWhitelistEntry> whitelistedAddresses); LockWhitelist(Map<Address, LockWhitelistEntry> whitelistedAddresses, int disableBlockHeight); boolean isWhitelisted(Address address); boolean isWhitelisted(byte[] address); boolean isWhitelistedFor(Address address, Coin amount, int height); Integer getSize(); List<Address> getAddresses(); List<T> getAll(Class<T> type); List<LockWhitelistEntry> getAll(); LockWhitelistEntry get(Address address); boolean put(Address address, LockWhitelistEntry entry); boolean remove(Address address); void consume(Address address); int getDisableBlockHeight(); void setDisableBlockHeight(int disableBlockHeight); boolean isDisableBlockSet(); }### Answer: @Test public void getAllByType() { Assert.assertArrayEquals( addresses.values().stream().filter(e -> e.getClass() == OneOffWhiteListEntry.class).map(e-> e.address()).sorted().toArray(), whitelist.getAll(OneOffWhiteListEntry.class).stream().map(e-> e.address()).toArray() ); Assert.assertArrayEquals( addresses.values().stream().filter(e -> e.getClass() == UnlimitedWhiteListEntry.class).map(e-> e.address()).sorted().toArray(), whitelist.getAll(UnlimitedWhiteListEntry.class).stream().map(e-> e.address()).toArray() ); } @Test public void getAll() { Assert.assertEquals(addresses.size(), whitelist.getAll().size()); }
### Question: CoinbaseInformation { public Sha256Hash getWitnessMerkleRoot() { return witnessMerkleRoot; } CoinbaseInformation(Sha256Hash witnessMerkleRoot); Sha256Hash getWitnessMerkleRoot(); }### Answer: @Test public void getWitnessMerkleRoot() { Sha256Hash secondHashTx = Sha256Hash.wrap(Hex.decode("e3d0840a0825fb7d880e5cb8306745352920a8c7e8a30fac882b275e26c6bb65")); Sha256Hash witnessRoot = MerkleTreeUtils.combineLeftRight(Sha256Hash.ZERO_HASH, secondHashTx); CoinbaseInformation instance = new CoinbaseInformation(witnessRoot); Sha256Hash expectedHash = new Sha256Hash(Hex.decode("613cb22535df8d9443fe94b66d807cd60312f982e305e25e825b00e6f429799f")); Assert.assertEquals(expectedHash, instance.getWitnessMerkleRoot()); }
### Question: Federation { public List<FederationMember> getMembers() { return members; } Federation(List<FederationMember> members, Instant creationTime, long creationBlockNumber, NetworkParameters btcParams); List<FederationMember> getMembers(); List<BtcECKey> getBtcPublicKeys(); int getNumberOfSignaturesRequired(); Instant getCreationTime(); NetworkParameters getBtcParams(); long getCreationBlockNumber(); Script getRedeemScript(); Script getP2SHScript(); Address getAddress(); int getSize(); Integer getBtcPublicKeyIndex(BtcECKey key); boolean hasBtcPublicKey(BtcECKey key); boolean hasMemberWithRskAddress(byte[] address); boolean isMember(FederationMember federationMember); @Override String toString(); @Override boolean equals(Object other); @Override int hashCode(); }### Answer: @Test public void membersImmutable() { boolean exception = false; try { federation.getMembers().add(new FederationMember(new BtcECKey(), new ECKey(), new ECKey())); } catch (Exception e) { exception = true; } Assert.assertTrue(exception); exception = false; try { federation.getMembers().remove(0); } catch (Exception e) { exception = true; } Assert.assertTrue(exception); }
### Question: Federation { public Integer getBtcPublicKeyIndex(BtcECKey key) { for (int i = 0; i < members.size(); i++) { if (Arrays.equals(key.getPubKey(), members.get(i).getBtcPublicKey().getPubKey())) { return i; } } return null; } Federation(List<FederationMember> members, Instant creationTime, long creationBlockNumber, NetworkParameters btcParams); List<FederationMember> getMembers(); List<BtcECKey> getBtcPublicKeys(); int getNumberOfSignaturesRequired(); Instant getCreationTime(); NetworkParameters getBtcParams(); long getCreationBlockNumber(); Script getRedeemScript(); Script getP2SHScript(); Address getAddress(); int getSize(); Integer getBtcPublicKeyIndex(BtcECKey key); boolean hasBtcPublicKey(BtcECKey key); boolean hasMemberWithRskAddress(byte[] address); boolean isMember(FederationMember federationMember); @Override String toString(); @Override boolean equals(Object other); @Override int hashCode(); }### Answer: @Test public void getBtcPublicKeyIndex() { for (int i = 0; i < federation.getBtcPublicKeys().size(); i++) { Assert.assertEquals(i, federation.getBtcPublicKeyIndex(sortedPublicKeys.get(i)).intValue()); } Assert.assertNull(federation.getBtcPublicKeyIndex(BtcECKey.fromPrivate(BigInteger.valueOf(1234)))); }
### Question: Federation { public boolean hasBtcPublicKey(BtcECKey key) { return getBtcPublicKeyIndex(key) != null; } Federation(List<FederationMember> members, Instant creationTime, long creationBlockNumber, NetworkParameters btcParams); List<FederationMember> getMembers(); List<BtcECKey> getBtcPublicKeys(); int getNumberOfSignaturesRequired(); Instant getCreationTime(); NetworkParameters getBtcParams(); long getCreationBlockNumber(); Script getRedeemScript(); Script getP2SHScript(); Address getAddress(); int getSize(); Integer getBtcPublicKeyIndex(BtcECKey key); boolean hasBtcPublicKey(BtcECKey key); boolean hasMemberWithRskAddress(byte[] address); boolean isMember(FederationMember federationMember); @Override String toString(); @Override boolean equals(Object other); @Override int hashCode(); }### Answer: @Test public void hasBtcPublicKey() { for (int i = 0; i < federation.getBtcPublicKeys().size(); i++) { Assert.assertTrue(federation.hasBtcPublicKey(sortedPublicKeys.get(i))); } Assert.assertFalse(federation.hasBtcPublicKey(BtcECKey.fromPrivate(BigInteger.valueOf(1234)))); }
### Question: Federation { public boolean hasMemberWithRskAddress(byte[] address) { return members.stream() .anyMatch(m -> Arrays.equals(m.getRskPublicKey().getAddress(), address)); } Federation(List<FederationMember> members, Instant creationTime, long creationBlockNumber, NetworkParameters btcParams); List<FederationMember> getMembers(); List<BtcECKey> getBtcPublicKeys(); int getNumberOfSignaturesRequired(); Instant getCreationTime(); NetworkParameters getBtcParams(); long getCreationBlockNumber(); Script getRedeemScript(); Script getP2SHScript(); Address getAddress(); int getSize(); Integer getBtcPublicKeyIndex(BtcECKey key); boolean hasBtcPublicKey(BtcECKey key); boolean hasMemberWithRskAddress(byte[] address); boolean isMember(FederationMember federationMember); @Override String toString(); @Override boolean equals(Object other); @Override int hashCode(); }### Answer: @Test public void hasMemberWithRskAddress() { for (int i = 0; i < federation.getBtcPublicKeys().size(); i++) { Assert.assertTrue(federation.hasMemberWithRskAddress(rskAddresses.get(i))); } byte[] nonFederateRskAddress = ECKey.fromPrivate(BigInteger.valueOf(1234)).getAddress(); Assert.assertFalse(federation.hasMemberWithRskAddress(nonFederateRskAddress)); }
### Question: Federation { @Override public String toString() { return String.format("%d of %d signatures federation", getNumberOfSignaturesRequired(), members.size()); } Federation(List<FederationMember> members, Instant creationTime, long creationBlockNumber, NetworkParameters btcParams); List<FederationMember> getMembers(); List<BtcECKey> getBtcPublicKeys(); int getNumberOfSignaturesRequired(); Instant getCreationTime(); NetworkParameters getBtcParams(); long getCreationBlockNumber(); Script getRedeemScript(); Script getP2SHScript(); Address getAddress(); int getSize(); Integer getBtcPublicKeyIndex(BtcECKey key); boolean hasBtcPublicKey(BtcECKey key); boolean hasMemberWithRskAddress(byte[] address); boolean isMember(FederationMember federationMember); @Override String toString(); @Override boolean equals(Object other); @Override int hashCode(); }### Answer: @Test public void testToString() { Assert.assertEquals("4 of 6 signatures federation", federation.toString()); }
### Question: Federation { public boolean isMember(FederationMember federationMember){ return this.members.contains(federationMember); } Federation(List<FederationMember> members, Instant creationTime, long creationBlockNumber, NetworkParameters btcParams); List<FederationMember> getMembers(); List<BtcECKey> getBtcPublicKeys(); int getNumberOfSignaturesRequired(); Instant getCreationTime(); NetworkParameters getBtcParams(); long getCreationBlockNumber(); Script getRedeemScript(); Script getP2SHScript(); Address getAddress(); int getSize(); Integer getBtcPublicKeyIndex(BtcECKey key); boolean hasBtcPublicKey(BtcECKey key); boolean hasMemberWithRskAddress(byte[] address); boolean isMember(FederationMember federationMember); @Override String toString(); @Override boolean equals(Object other); @Override int hashCode(); }### Answer: @Test public void isMember(){ FederationMember federationMember = federation.getMembers().get(0); Assert.assertTrue(federation.isMember(federationMember)); byte[] b = new byte[20]; new Random().nextBytes(b); ECKey invalidRskKey = ECKey.fromPrivate(b); BtcECKey invalidBtcKey = BtcECKey.fromPrivate(b); FederationMember invalidRskPubKey = new FederationMember(federationMember.getBtcPublicKey(), invalidRskKey, federationMember.getMstPublicKey()); Assert.assertFalse(federation.isMember(invalidRskPubKey)); FederationMember invalidBtcPubKey = new FederationMember(invalidBtcKey, federationMember.getRskPublicKey(), federationMember.getMstPublicKey()); Assert.assertFalse(federation.isMember(invalidBtcPubKey)); FederationMember invalidMstPubKey = new FederationMember(federationMember.getBtcPublicKey(), federationMember.getRskPublicKey(), invalidRskKey); Assert.assertFalse(federation.isMember(invalidMstPubKey)); FederationMember invalidPubKeys = new FederationMember(invalidBtcKey, invalidRskKey, invalidRskKey); Assert.assertFalse(federation.isMember(invalidPubKeys)); }
### Question: PartialMerkleTreeFormatUtils { public static VarInt getHashesCount(byte[] pmtSerialized) { return new VarInt(pmtSerialized, BLOCK_TRANSACTION_COUNT_LENGTH); } static VarInt getHashesCount(byte[] pmtSerialized); static VarInt getFlagBitsCount(byte[] pmtSerialized); static boolean hasExpectedSize(byte[] pmtSerialized); static Stream<Sha256Hash> streamIntermediateHashes(byte[] pmtSerialized); }### Answer: @Test public void getHashesCount() { String pmtSerializedEncoded = "030000000279e7c0da739df8a00f12c0bff55e5438f530aa5859ff9874258cd7bad3fe709746aff89" + "7e6a851faa80120d6ae99db30883699ac0428fc7192d6c3fec0ca6409010d"; byte[] pmtSerialized = Hex.decode(pmtSerializedEncoded); Assert.assertThat(PartialMerkleTreeFormatUtils.getHashesCount(pmtSerialized).value, is(2L)); }
### Question: ReleaseRequestQueue { public void add(Address destination, Coin amount, Keccak256 rskTxHash) { entries.add(new Entry(destination, amount, rskTxHash)); } ReleaseRequestQueue(List<Entry> entries); List<Entry> getEntriesWithoutHash(); List<Entry> getEntriesWithHash(); List<Entry> getEntries(); void add(Address destination, Coin amount, Keccak256 rskTxHash); void add(Address destination, Coin amount); void process(int maxIterations, Processor processor); }### Answer: @Test public void add() { Assert.assertFalse(queue.getEntries().contains(new ReleaseRequestQueue.Entry(mockAddress(10), Coin.valueOf(10)))); queue.add(mockAddress(10), Coin.valueOf(10), null); Assert.assertTrue(queue.getEntries().contains(new ReleaseRequestQueue.Entry(mockAddress(10), Coin.valueOf(10)))); }
### Question: ReleaseRequestQueue { public void process(int maxIterations, Processor processor) { ListIterator<Entry> iterator = entries.listIterator(); List<Entry> toRetry = new ArrayList<>(); int i = 0; while (iterator.hasNext() && i < maxIterations) { Entry entry = iterator.next(); iterator.remove(); ++i; if (!processor.process(entry)) { toRetry.add(entry); } } entries.addAll(toRetry); } ReleaseRequestQueue(List<Entry> entries); List<Entry> getEntriesWithoutHash(); List<Entry> getEntriesWithHash(); List<Entry> getEntries(); void add(Address destination, Coin amount, Keccak256 rskTxHash); void add(Address destination, Coin amount); void process(int maxIterations, Processor processor); }### Answer: @Test public void process() { class Indexer { public int index = 0; } Indexer idx = new Indexer(); queue.process(30, entry -> { assertEquals(entry, queueEntries.get(idx.index)); return idx.index++ % 2 == 0; }); assertEquals(5, idx.index); assertEquals(Arrays.asList( new ReleaseRequestQueue.Entry(mockAddress(5), Coin.COIN), new ReleaseRequestQueue.Entry(mockAddress(3), Coin.MILLICOIN) ), queue.getEntries()); }
### Question: RepositoryBtcBlockStoreWithCache implements BtcBlockStoreWithCache { @Override public synchronized StoredBlock getChainHead() { byte[] ba = repository.getStorageBytes(contractAddress, DataWord.fromString(BLOCK_STORE_CHAIN_HEAD_KEY)); if (ba == null) { return null; } return byteArrayToStoredBlock(ba); } RepositoryBtcBlockStoreWithCache(NetworkParameters btcNetworkParams, Repository repository, Map<Sha256Hash, StoredBlock> cacheBlocks, RskAddress contractAddress); @Override synchronized void put(StoredBlock storedBlock); @Override synchronized StoredBlock get(Sha256Hash hash); @Override synchronized StoredBlock getChainHead(); @Override synchronized void setChainHead(StoredBlock newChainHead); @Override void close(); @Override NetworkParameters getParams(); @Override StoredBlock getFromCache(Sha256Hash branchBlockHash); @Override StoredBlock getStoredBlockAtMainChainHeight(int height); @Override StoredBlock getStoredBlockAtMainChainDepth(int depth); static final String BLOCK_STORE_CHAIN_HEAD_KEY; static final int MAX_DEPTH_STORED_BLOCKS; static final int MAX_SIZE_MAP_STORED_BLOCKS; }### Answer: @Test public void getChainHead_Test() throws BlockStoreException { BtcBlockStoreWithCache btcBlockStore = createBlockStore(); assertEquals(networkParameters.getGenesisBlock(), btcBlockStore.getChainHead().getHeader()); }
### Question: RepositoryBtcBlockStoreWithCache implements BtcBlockStoreWithCache { @Override public NetworkParameters getParams() { return btcNetworkParams; } RepositoryBtcBlockStoreWithCache(NetworkParameters btcNetworkParams, Repository repository, Map<Sha256Hash, StoredBlock> cacheBlocks, RskAddress contractAddress); @Override synchronized void put(StoredBlock storedBlock); @Override synchronized StoredBlock get(Sha256Hash hash); @Override synchronized StoredBlock getChainHead(); @Override synchronized void setChainHead(StoredBlock newChainHead); @Override void close(); @Override NetworkParameters getParams(); @Override StoredBlock getFromCache(Sha256Hash branchBlockHash); @Override StoredBlock getStoredBlockAtMainChainHeight(int height); @Override StoredBlock getStoredBlockAtMainChainDepth(int depth); static final String BLOCK_STORE_CHAIN_HEAD_KEY; static final int MAX_DEPTH_STORED_BLOCKS; static final int MAX_SIZE_MAP_STORED_BLOCKS; }### Answer: @Test public void getParams_Test() { BtcBlockStoreWithCache btcBlockStore = createBlockStore(); assertEquals(networkParameters, btcBlockStore.getParams()); }
### Question: RemascStorageProvider { public Coin getRewardBalance() { if (rewardBalance != null) { return rewardBalance; } DataWord address = DataWord.fromString(REWARD_BALANCE_KEY); DataWord value = this.repository.getStorageValue(this.contractAddress, address); if (value == null) { return Coin.ZERO; } return new Coin(value.getData()); } RemascStorageProvider(Repository repository, RskAddress contractAddress); Coin getFederationBalance(); Coin getRewardBalance(); void setFederationBalance(Coin federationBalance); void setRewardBalance(Coin rewardBalance); Coin getBurnedBalance(); void setBurnedBalance(Coin burnedBalance); void addToBurnBalance(Coin amountToBurn); Boolean getBrokenSelectionRule(); void setBrokenSelectionRule(Boolean brokenSelectionRule); void save(); }### Answer: @Test public void getDefautRewardBalance() { RskAddress accountAddress = randomAddress(); Repository repository = createRepository(); RemascStorageProvider provider = new RemascStorageProvider(repository, accountAddress); Assert.assertEquals(Coin.ZERO, provider.getRewardBalance()); }
### Question: RemascStorageProvider { public Coin getBurnedBalance() { if (burnedBalance != null) { return burnedBalance; } DataWord address = DataWord.fromString(BURNED_BALANCE_KEY); DataWord value = this.repository.getStorageValue(this.contractAddress, address); if (value == null) { return Coin.ZERO; } return new Coin(value.getData()); } RemascStorageProvider(Repository repository, RskAddress contractAddress); Coin getFederationBalance(); Coin getRewardBalance(); void setFederationBalance(Coin federationBalance); void setRewardBalance(Coin rewardBalance); Coin getBurnedBalance(); void setBurnedBalance(Coin burnedBalance); void addToBurnBalance(Coin amountToBurn); Boolean getBrokenSelectionRule(); void setBrokenSelectionRule(Boolean brokenSelectionRule); void save(); }### Answer: @Test public void getDefautBurnedBalance() { RskAddress accountAddress = randomAddress(); Repository repository = createRepository(); RemascStorageProvider provider = new RemascStorageProvider(repository, accountAddress); Assert.assertEquals(Coin.ZERO, provider.getBurnedBalance()); }
### Question: RemascStorageProvider { public Boolean getBrokenSelectionRule() { if (brokenSelectionRule!= null) { return brokenSelectionRule; } DataWord address = DataWord.fromString(BROKEN_SELECTION_RULE_KEY); byte[] bytes = this.repository.getStorageBytes(this.contractAddress, address); if (bytes == null || bytes.length == 0) { return Boolean.FALSE; } if (bytes[0] == 0) { return Boolean.FALSE; } else { return Boolean.TRUE; } } RemascStorageProvider(Repository repository, RskAddress contractAddress); Coin getFederationBalance(); Coin getRewardBalance(); void setFederationBalance(Coin federationBalance); void setRewardBalance(Coin rewardBalance); Coin getBurnedBalance(); void setBurnedBalance(Coin burnedBalance); void addToBurnBalance(Coin amountToBurn); Boolean getBrokenSelectionRule(); void setBrokenSelectionRule(Boolean brokenSelectionRule); void save(); }### Answer: @Test public void getDefaultBrokenSelectionRule() { RskAddress accountAddress = randomAddress(); Repository repository = createRepository(); RemascStorageProvider provider = new RemascStorageProvider(repository, accountAddress); Assert.assertEquals(Boolean.FALSE, provider.getBrokenSelectionRule()); }
### Question: RemascFederationProvider { public int getFederationSize() { return this.federationSupport.getFederationSize(); } RemascFederationProvider( ActivationConfig activationConfig, BridgeConstants bridgeConstants, Repository repository, Block processingBlock); int getFederationSize(); RskAddress getFederatorAddress(int n); }### Answer: @Test public void getDefaultFederationSize() { RemascFederationProvider provider = getRemascFederationProvider(); Assert.assertEquals(3, provider.getFederationSize()); }
### Question: RemascFederationProvider { public RskAddress getFederatorAddress(int n) { byte[] publicKey = this.federationSupport.getFederatorBtcPublicKey(n); return new RskAddress(ECKey.fromPublicOnly(publicKey).getAddress()); } RemascFederationProvider( ActivationConfig activationConfig, BridgeConstants bridgeConstants, Repository repository, Block processingBlock); int getFederationSize(); RskAddress getFederatorAddress(int n); }### Answer: @Test public void getFederatorAddress() { RemascFederationProvider provider = getRemascFederationProvider(); byte[] address = provider.getFederatorAddress(0).getBytes(); Assert.assertNotNull(address); Assert.assertEquals(20, address.length); }
### Question: BlockDifficulty implements Comparable<BlockDifficulty>, Serializable { public BlockDifficulty add(BlockDifficulty other) { return new BlockDifficulty(value.add(other.value)); } BlockDifficulty(BigInteger value); byte[] getBytes(); BigInteger asBigInteger(); @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); BlockDifficulty add(BlockDifficulty other); BlockDifficulty subtract(BlockDifficulty other); @Override int compareTo(@Nonnull BlockDifficulty other); static final BlockDifficulty ZERO; static final BlockDifficulty ONE; }### Answer: @Test public void addOneToZero() { BlockDifficulty d1 = new BlockDifficulty(BigInteger.ZERO); BlockDifficulty d2 = new BlockDifficulty(BigInteger.ONE); assertThat(d1.add(d2), is(d2)); } @Test public void addOneToOne() { BlockDifficulty d1 = new BlockDifficulty(BigInteger.ONE); BlockDifficulty d2 = new BlockDifficulty(BigInteger.ONE); assertThat(d1.add(d2), is(new BlockDifficulty(BigInteger.valueOf(2)))); } @Test public void addLargeValues() { BlockDifficulty d1 = new BlockDifficulty(BigInteger.valueOf(Long.MAX_VALUE)); BlockDifficulty d2 = new BlockDifficulty(BigInteger.valueOf(Integer.MAX_VALUE)); assertThat(d1.add(d2), is(new BlockDifficulty(new BigInteger("9223372039002259454")))); }
### Question: BlockDifficulty implements Comparable<BlockDifficulty>, Serializable { @Override public int compareTo(@Nonnull BlockDifficulty other) { return value.compareTo(other.value); } BlockDifficulty(BigInteger value); byte[] getBytes(); BigInteger asBigInteger(); @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); BlockDifficulty add(BlockDifficulty other); BlockDifficulty subtract(BlockDifficulty other); @Override int compareTo(@Nonnull BlockDifficulty other); static final BlockDifficulty ZERO; static final BlockDifficulty ONE; }### Answer: @Test public void testComparable() { BlockDifficulty zero = BlockDifficulty.ZERO; BlockDifficulty d1 = new BlockDifficulty(BigInteger.valueOf(Long.MAX_VALUE)); BlockDifficulty d2 = new BlockDifficulty(BigInteger.valueOf(Integer.MAX_VALUE)); assertThat(zero.compareTo(zero), is(0)); assertThat(d1.compareTo(d1), is(0)); assertThat(d2.compareTo(d2), is(0)); assertThat(zero.compareTo(d1), is(-1)); assertThat(zero.compareTo(d2), is(-1)); assertThat(d1.compareTo(zero), is(1)); assertThat(d2.compareTo(zero), is(1)); assertThat(d1.compareTo(d2), is(1)); assertThat(d2.compareTo(d1), is(-1)); }
### Question: Wallet { public List<byte[]> getAccountAddresses() { List<byte[]> addresses = new ArrayList<>(); Set<RskAddress> keys = new HashSet<>(); synchronized(accessLock) { for (RskAddress addr: this.initialAccounts) { addresses.add(addr.getBytes()); } for (byte[] address: keyDS.keys()) { keys.add(new RskAddress(address)); } keys.addAll(accounts.keySet()); keys.removeAll(this.initialAccounts); for (RskAddress addr: keys) { addresses.add(addr.getBytes()); } } return addresses; } Wallet(KeyValueDataSource keyDS); List<byte[]> getAccountAddresses(); String[] getAccountAddressesAsHex(); RskAddress addAccount(); RskAddress addAccount(String passphrase); RskAddress addAccount(Account account); Account getAccount(RskAddress addr); Account getAccount(RskAddress addr, String passphrase); boolean unlockAccount(RskAddress addr, String passphrase, long duration); boolean unlockAccount(RskAddress addr, String passphrase); boolean lockAccount(RskAddress addr); byte[] addAccountWithSeed(String seed); byte[] addAccountWithPrivateKey(byte[] privateKeyBytes); RskAddress addAccountWithPrivateKey(byte[] privateKeyBytes, String passphrase); }### Answer: @Test public void getEmptyAccountList() { Wallet wallet = WalletFactory.createWallet(); List<byte[]> addresses = wallet.getAccountAddresses(); Assert.assertNotNull(addresses); Assert.assertTrue(addresses.isEmpty()); }
### Question: Wallet { public byte[] addAccountWithSeed(String seed) { return addAccountWithPrivateKey(Keccak256Helper.keccak256(seed.getBytes(StandardCharsets.UTF_8))); } Wallet(KeyValueDataSource keyDS); List<byte[]> getAccountAddresses(); String[] getAccountAddressesAsHex(); RskAddress addAccount(); RskAddress addAccount(String passphrase); RskAddress addAccount(Account account); Account getAccount(RskAddress addr); Account getAccount(RskAddress addr, String passphrase); boolean unlockAccount(RskAddress addr, String passphrase, long duration); boolean unlockAccount(RskAddress addr, String passphrase); boolean lockAccount(RskAddress addr); byte[] addAccountWithSeed(String seed); byte[] addAccountWithPrivateKey(byte[] privateKeyBytes); RskAddress addAccountWithPrivateKey(byte[] privateKeyBytes, String passphrase); }### Answer: @Test public void addAccountWithSeed() { Wallet wallet = WalletFactory.createWallet(); byte[] address = wallet.addAccountWithSeed("seed"); Assert.assertNotNull(address); byte[] calculatedAddress = ECKey.fromPrivate(Keccak256Helper.keccak256("seed".getBytes())).getAddress(); Assert.assertArrayEquals(calculatedAddress, address); List<byte[]> addresses = wallet.getAccountAddresses(); Assert.assertNotNull(addresses); Assert.assertFalse(addresses.isEmpty()); Assert.assertEquals(1, addresses.size()); byte[] addr = addresses.get(0); Assert.assertNotNull(addr); Assert.assertArrayEquals(address, addr); }
### Question: Wallet { public boolean unlockAccount(RskAddress addr, String passphrase, long duration) { long ending = System.currentTimeMillis() + duration; boolean unlocked = unlockAccount(addr, passphrase); if (unlocked) { synchronized (accessLock) { unlocksTimeouts.put(addr, ending); } } return unlocked; } Wallet(KeyValueDataSource keyDS); List<byte[]> getAccountAddresses(); String[] getAccountAddressesAsHex(); RskAddress addAccount(); RskAddress addAccount(String passphrase); RskAddress addAccount(Account account); Account getAccount(RskAddress addr); Account getAccount(RskAddress addr, String passphrase); boolean unlockAccount(RskAddress addr, String passphrase, long duration); boolean unlockAccount(RskAddress addr, String passphrase); boolean lockAccount(RskAddress addr); byte[] addAccountWithSeed(String seed); byte[] addAccountWithPrivateKey(byte[] privateKeyBytes); RskAddress addAccountWithPrivateKey(byte[] privateKeyBytes, String passphrase); }### Answer: @Test public void unlockNonexistentAccount() { Wallet wallet = WalletFactory.createWallet(); RskAddress addr = new RskAddress("0x0000000000000000000000000000000000000023"); Assert.assertFalse(wallet.unlockAccount(addr, "passphrase")); }
### Question: Wallet { public boolean lockAccount(RskAddress addr) { synchronized (accessLock) { if (!accounts.containsKey(addr)) { return false; } accounts.remove(addr); return true; } } Wallet(KeyValueDataSource keyDS); List<byte[]> getAccountAddresses(); String[] getAccountAddressesAsHex(); RskAddress addAccount(); RskAddress addAccount(String passphrase); RskAddress addAccount(Account account); Account getAccount(RskAddress addr); Account getAccount(RskAddress addr, String passphrase); boolean unlockAccount(RskAddress addr, String passphrase, long duration); boolean unlockAccount(RskAddress addr, String passphrase); boolean lockAccount(RskAddress addr); byte[] addAccountWithSeed(String seed); byte[] addAccountWithPrivateKey(byte[] privateKeyBytes); RskAddress addAccountWithPrivateKey(byte[] privateKeyBytes, String passphrase); }### Answer: @Test public void lockAccount() { Wallet wallet = WalletFactory.createWallet(); byte[] address = wallet.addAccount("passphrase").getBytes(); Assert.assertNotNull(address); Assert.assertTrue(wallet.unlockAccount(new RskAddress(address), "passphrase")); Account account = wallet.getAccount(new RskAddress(address)); Assert.assertNotNull(account); Assert.assertArrayEquals(address, account.getAddress().getBytes()); Assert.assertTrue(wallet.lockAccount(new RskAddress(address))); Account account2 = wallet.getAccount(new RskAddress(address)); Assert.assertNull(account2); } @Test public void lockNonexistentAccount() { Wallet wallet = WalletFactory.createWallet(); RskAddress addr = new RskAddress("0x0000000000000000000000000000000000000023"); Assert.assertFalse(wallet.lockAccount(addr)); }
### Question: Wallet { public Account getAccount(RskAddress addr) { synchronized (accessLock) { if (!accounts.containsKey(addr)) { return null; } if (unlocksTimeouts.containsKey(addr)) { long ending = unlocksTimeouts.get(addr); long time = System.currentTimeMillis(); if (ending < time) { unlocksTimeouts.remove(addr); accounts.remove(addr); return null; } } return new Account(ECKey.fromPrivate(accounts.get(addr))); } } Wallet(KeyValueDataSource keyDS); List<byte[]> getAccountAddresses(); String[] getAccountAddressesAsHex(); RskAddress addAccount(); RskAddress addAccount(String passphrase); RskAddress addAccount(Account account); Account getAccount(RskAddress addr); Account getAccount(RskAddress addr, String passphrase); boolean unlockAccount(RskAddress addr, String passphrase, long duration); boolean unlockAccount(RskAddress addr, String passphrase); boolean lockAccount(RskAddress addr); byte[] addAccountWithSeed(String seed); byte[] addAccountWithPrivateKey(byte[] privateKeyBytes); RskAddress addAccountWithPrivateKey(byte[] privateKeyBytes, String passphrase); }### Answer: @Test public void getUnknownAccount() { Wallet wallet = WalletFactory.createWallet(); RskAddress addr = new RskAddress("0x0000000000000000000000000000000000000023"); Account account = wallet.getAccount(addr); Assert.assertNull(account); }
### Question: Wallet { public byte[] addAccountWithPrivateKey(byte[] privateKeyBytes) { Account account = new Account(ECKey.fromPrivate(privateKeyBytes)); synchronized (accessLock) { RskAddress addr = addAccount(account); if (!this.initialAccounts.contains(addr)) { this.initialAccounts.add(addr); } return addr.getBytes(); } } Wallet(KeyValueDataSource keyDS); List<byte[]> getAccountAddresses(); String[] getAccountAddressesAsHex(); RskAddress addAccount(); RskAddress addAccount(String passphrase); RskAddress addAccount(Account account); Account getAccount(RskAddress addr); Account getAccount(RskAddress addr, String passphrase); boolean unlockAccount(RskAddress addr, String passphrase, long duration); boolean unlockAccount(RskAddress addr, String passphrase); boolean lockAccount(RskAddress addr); byte[] addAccountWithSeed(String seed); byte[] addAccountWithPrivateKey(byte[] privateKeyBytes); RskAddress addAccountWithPrivateKey(byte[] privateKeyBytes, String passphrase); }### Answer: @Test public void addAccountWithPrivateKey() { Wallet wallet = WalletFactory.createWallet(); byte[] privateKeyBytes = Keccak256Helper.keccak256("seed".getBytes()); byte[] address = wallet.addAccountWithPrivateKey(privateKeyBytes); Assert.assertNotNull(address); byte[] calculatedAddress = ECKey.fromPrivate(Keccak256Helper.keccak256("seed".getBytes())).getAddress(); Assert.assertArrayEquals(calculatedAddress, address); List<byte[]> addresses = wallet.getAccountAddresses(); Assert.assertNotNull(addresses); Assert.assertFalse(addresses.isEmpty()); Assert.assertEquals(1, addresses.size()); byte[] addr = addresses.get(0); Assert.assertNotNull(addr); Assert.assertArrayEquals(address, addr); }
### Question: SnapshotManager { @VisibleForTesting public List<Long> getSnapshots() { return this.snapshots; } SnapshotManager( Blockchain blockchain, BlockStore blockStore, TransactionPool transactionPool, MinerServer minerServer); int takeSnapshot(); boolean resetSnapshots(); boolean revertToSnapshot(int snapshotId); @VisibleForTesting List<Long> getSnapshots(); }### Answer: @Test public void createWithNoSnapshot() { Assert.assertNotNull(manager.getSnapshots()); Assert.assertTrue(manager.getSnapshots().isEmpty()); }
### Question: GarbageCollector implements InternalService { private void collect(long untilBlock) { BlockHeader untilHeader = blockStore.getChainBlockByNumber(untilBlock).getHeader(); multiTrieStore.collect(repositoryLocator.snapshotAt(untilHeader).getRoot()); } GarbageCollector(CompositeEthereumListener emitter, int blocksPerEpoch, int numberOfEpochs, MultiTrieStore multiTrieStore, BlockStore blockStore, RepositoryLocator repositoryLocator); @Override void start(); @Override void stop(); }### Answer: @Test public void collectsOnBlocksPerEpochModulo() { for (int i = 100; i < 105; i++) { Block block = block(i); listener.onBestBlock(block, null); } verify(multiTrieStore, never()).collect(any()); byte[] stateRoot = new byte[] {0x42, 0x43, 0x02}; withSnapshotStateRootAtBlockNumber(85, stateRoot); Block block = block(105); listener.onBestBlock(block, null); verify(multiTrieStore).collect(stateRoot); } @Test public void collectsOnBlocksPerEpochModuloAndMinimumOfStatesToKeep() { for (int i = 0; i < 21; i++) { Block block = block(i); listener.onBestBlock(block, null); } verify(multiTrieStore, never()).collect(any()); byte[] stateRoot = new byte[] {0x42, 0x43, 0x02}; withSnapshotStateRootAtBlockNumber(1, stateRoot); Block block = block(21); listener.onBestBlock(block, null); verify(multiTrieStore).collect(stateRoot); }
### Question: BlockChainImpl implements Blockchain { @Override public Block getBlockByHash(byte[] hash) { return blockStore.getBlockByHash(hash); } BlockChainImpl(BlockStore blockStore, ReceiptStore receiptStore, TransactionPool transactionPool, EthereumListener listener, BlockValidator blockValidator, BlockExecutor blockExecutor, StateRootHandler stateRootHandler); @VisibleForTesting void setBlockValidator(BlockValidator validator); @Override long getSize(); @Override ImportResult tryToConnect(Block block); @Override BlockChainStatus getStatus(); @Override void setStatus(Block block, BlockDifficulty totalDifficulty); @Override Block getBlockByHash(byte[] hash); @Override List<Block> getBlocksByNumber(long number); @Override List<BlockInformation> getBlocksInformationByNumber(long number); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override void removeBlocksByNumber(long number); @Override Block getBlockByNumber(long number); @Override Block getBestBlock(); void setNoValidation(boolean noValidation); @Override TransactionInfo getTransactionInfo(byte[] hash); @Override BlockDifficulty getTotalDifficulty(); @Override @VisibleForTesting byte[] getBestBlockHash(); }### Answer: @Test public void getUnknownBlockByHash() { Assert.assertNull(blockChain.getBlockByHash(new BlockGenerator().getBlock(1).getHash().getBytes())); }
### Question: BlockChainImpl implements Blockchain { @Override public TransactionInfo getTransactionInfo(byte[] hash) { TransactionInfo txInfo = receiptStore.get(hash); if (txInfo == null) { return null; } Transaction tx = this.getBlockByHash(txInfo.getBlockHash()).getTransactionsList().get(txInfo.getIndex()); txInfo.setTransaction(tx); return txInfo; } BlockChainImpl(BlockStore blockStore, ReceiptStore receiptStore, TransactionPool transactionPool, EthereumListener listener, BlockValidator blockValidator, BlockExecutor blockExecutor, StateRootHandler stateRootHandler); @VisibleForTesting void setBlockValidator(BlockValidator validator); @Override long getSize(); @Override ImportResult tryToConnect(Block block); @Override BlockChainStatus getStatus(); @Override void setStatus(Block block, BlockDifficulty totalDifficulty); @Override Block getBlockByHash(byte[] hash); @Override List<Block> getBlocksByNumber(long number); @Override List<BlockInformation> getBlocksInformationByNumber(long number); @Override boolean hasBlockInSomeBlockchain(@Nonnull final byte[] hash); @Override void removeBlocksByNumber(long number); @Override Block getBlockByNumber(long number); @Override Block getBestBlock(); void setNoValidation(boolean noValidation); @Override TransactionInfo getTransactionInfo(byte[] hash); @Override BlockDifficulty getTotalDifficulty(); @Override @VisibleForTesting byte[] getBestBlockHash(); }### Answer: @Test public void getUnknownTransactionInfoAsNull() { Assert.assertNull(blockChain.getTransactionInfo(new byte[] { 0x01 })); } @Test public void getTransactionInfo() { Block block = getBlockWithOneTransaction(); Assert.assertEquals(ImportResult.IMPORTED_BEST, blockChain.tryToConnect(block)); Transaction tx = block.getTransactionsList().get(0); Assert.assertNotNull(blockChain.getTransactionInfo(tx.getHash().getBytes())); }
### Question: BlockUtils { public static boolean tooMuchProcessTime(long nanoseconds) { return nanoseconds > MAX_BLOCK_PROCESS_TIME_NANOSECONDS; } private BlockUtils(); static boolean tooMuchProcessTime(long nanoseconds); static boolean blockInSomeBlockChain(Block block, Blockchain blockChain); static Set<Keccak256> unknownDirectAncestorsHashes(Block block, Blockchain blockChain, NetBlockStore store); static Set<Keccak256> unknownAncestorsHashes(Keccak256 blockHash, Blockchain blockChain, NetBlockStore store); static Set<Keccak256> unknownAncestorsHashes(Set<Keccak256> hashesToProcess, Blockchain blockChain, NetBlockStore store, boolean withUncles); static void addBlockToList(List<Block> blocks, Block block); static List<Block> sortBlocksByNumber(List<Block> blocks); }### Answer: @Test public void tooMuchProcessTime() { Assert.assertFalse(BlockUtils.tooMuchProcessTime(0)); Assert.assertFalse(BlockUtils.tooMuchProcessTime(1000)); Assert.assertFalse(BlockUtils.tooMuchProcessTime(1_000_000L)); Assert.assertFalse(BlockUtils.tooMuchProcessTime(1_000_000_000L)); Assert.assertFalse(BlockUtils.tooMuchProcessTime(60_000_000_000L)); Assert.assertTrue(BlockUtils.tooMuchProcessTime(60_000_000_001L)); Assert.assertTrue(BlockUtils.tooMuchProcessTime(1_000_000_000_000L)); }
### Question: TransactionPoolImpl implements TransactionPool { @Override public PendingState getPendingState() { return getPendingState(getCurrentRepository()); } TransactionPoolImpl( RskSystemProperties config, RepositoryLocator repositoryLocator, BlockStore blockStore, BlockFactory blockFactory, EthereumListener listener, TransactionExecutorFactory transactionExecutorFactory, SignatureCache signatureCache, int outdatedThreshold, int outdatedTimeout); @Override void start(); @Override void stop(); boolean hasCleanerFuture(); void cleanUp(); int getOutdatedThreshold(); int getOutdatedTimeout(); Block getBestBlock(); @Override PendingState getPendingState(); @Override synchronized List<Transaction> addTransactions(final List<Transaction> txs); @Override synchronized TransactionPoolAddResult addTransaction(final Transaction tx); @Override synchronized void processBest(Block newBlock); @VisibleForTesting void acceptBlock(Block block); @VisibleForTesting void retractBlock(Block block); @VisibleForTesting void removeObsoleteTransactions(long currentBlock, int depth, int timeout); @VisibleForTesting synchronized void removeObsoleteTransactions(long timeSeconds); @Override synchronized void removeTransactions(List<Transaction> txs); @Override synchronized List<Transaction> getPendingTransactions(); @Override synchronized List<Transaction> getQueuedTransactions(); }### Answer: @Test public void usingAccountsWithInitialBalance() { createTestAccounts(2, Coin.valueOf(10L)); PendingState pendingState = transactionPool.getPendingState(); Assert.assertNotNull(pendingState); Account account1 = createAccount(1); Account account2 = createAccount(2); Assert.assertEquals(BigInteger.TEN, pendingState.getBalance(account1.getAddress()).asBigInteger()); Assert.assertEquals(BigInteger.TEN, pendingState.getBalance(account2.getAddress()).asBigInteger()); }
### Question: TransactionPoolImpl implements TransactionPool { @Override public synchronized List<Transaction> getPendingTransactions() { removeObsoleteTransactions(this.outdatedThreshold, this.outdatedTimeout); return Collections.unmodifiableList(pendingTransactions.getTransactions()); } TransactionPoolImpl( RskSystemProperties config, RepositoryLocator repositoryLocator, BlockStore blockStore, BlockFactory blockFactory, EthereumListener listener, TransactionExecutorFactory transactionExecutorFactory, SignatureCache signatureCache, int outdatedThreshold, int outdatedTimeout); @Override void start(); @Override void stop(); boolean hasCleanerFuture(); void cleanUp(); int getOutdatedThreshold(); int getOutdatedTimeout(); Block getBestBlock(); @Override PendingState getPendingState(); @Override synchronized List<Transaction> addTransactions(final List<Transaction> txs); @Override synchronized TransactionPoolAddResult addTransaction(final Transaction tx); @Override synchronized void processBest(Block newBlock); @VisibleForTesting void acceptBlock(Block block); @VisibleForTesting void retractBlock(Block block); @VisibleForTesting void removeObsoleteTransactions(long currentBlock, int depth, int timeout); @VisibleForTesting synchronized void removeObsoleteTransactions(long timeSeconds); @Override synchronized void removeTransactions(List<Transaction> txs); @Override synchronized List<Transaction> getPendingTransactions(); @Override synchronized List<Transaction> getQueuedTransactions(); }### Answer: @Test public void getEmptyPendingTransactionList() { List<Transaction> transactions = transactionPool.getPendingTransactions(); Assert.assertNotNull(transactions); Assert.assertTrue(transactions.isEmpty()); } @Test public void getEmptyTransactionList() { List<Transaction> transactions = transactionPool.getPendingTransactions(); Assert.assertNotNull(transactions); Assert.assertTrue(transactions.isEmpty()); }
### Question: SelectionRule { public static boolean isThisBlockHashSmaller(byte[] thisBlockHash, byte[] compareBlockHash) { return FastByteComparisons.compareTo( thisBlockHash, BYTE_ARRAY_OFFSET, BYTE_ARRAY_LENGTH, compareBlockHash, BYTE_ARRAY_OFFSET, BYTE_ARRAY_LENGTH) < 0; } static boolean shouldWeAddThisBlock( BlockDifficulty blockDifficulty, BlockDifficulty currentDifficulty, Block block, Block currentBlock); static boolean isBrokenSelectionRule( BlockHeader processingBlockHeader, List<Sibling> siblings); static boolean isThisBlockHashSmaller(byte[] thisBlockHash, byte[] compareBlockHash); }### Answer: @Test public void smallerBlockHashTest() { byte[] lowerHash = new byte[]{0}; byte[] biggerHash = new byte[]{1}; assertTrue(SelectionRule.isThisBlockHashSmaller(lowerHash, biggerHash)); assertFalse(SelectionRule.isThisBlockHashSmaller(biggerHash, lowerHash)); }
### Question: BlockChainFlusher implements InternalService { private void flush() { if (nFlush == 0) { flushAll(); } nFlush++; nFlush = nFlush % flushNumberOfBlocks; } BlockChainFlusher( int flushNumberOfBlocks, CompositeEthereumListener emitter, TrieStore trieStore, BlockStore blockStore, ReceiptStore receiptStore); @Override void start(); @Override void stop(); }### Answer: @Test public void flushesAfterNInvocations() { for (int i = 0; i < 6; i++) { listener.onBestBlock(null, null); } verify(trieStore, never()).flush(); verify(blockStore, never()).flush(); verify(receiptStore, never()).flush(); listener.onBestBlock(null, null); verify(trieStore).flush(); verify(blockStore).flush(); verify(receiptStore).flush(); }
### Question: Uint24 implements Comparable<Uint24> { public int intValue() { return intValue; } Uint24(int intValue); byte[] encode(); int intValue(); @Override boolean equals(Object o); @Override int hashCode(); @Override int compareTo(Uint24 o); @Override String toString(); static Uint24 decode(byte[] bytes, int offset); static final int SIZE; static final int BYTES; static final Uint24 ZERO; static final Uint24 MAX_VALUE; }### Answer: @Test(expected = IllegalArgumentException.class) public void instantiateMaxPlusOne() { new Uint24(Uint24.MAX_VALUE.intValue() + 1); }
### Question: Uint24 implements Comparable<Uint24> { public static Uint24 decode(byte[] bytes, int offset) { int intValue = (bytes[offset + 2] & 0xFF) + ((bytes[offset + 1] & 0xFF) << 8) + ((bytes[offset ] & 0xFF) << 16); return new Uint24(intValue); } Uint24(int intValue); byte[] encode(); int intValue(); @Override boolean equals(Object o); @Override int hashCode(); @Override int compareTo(Uint24 o); @Override String toString(); static Uint24 decode(byte[] bytes, int offset); static final int SIZE; static final int BYTES; static final Uint24 ZERO; static final Uint24 MAX_VALUE; }### Answer: @Test public void decodeOffsettedValue() { byte[] bytes = new byte[] {0x21, 0x53, (byte) 0xf2, (byte) 0xf4, 0x04, 0x55}; Uint24 decoded = Uint24.decode(bytes, 2); assertThat(decoded, is(new Uint24(15922180))); } @Test(expected = ArrayIndexOutOfBoundsException.class) public void decodeSmallArray() { byte[] bytes = new byte[] {0x21, 0x53, (byte) 0xf2}; Uint24.decode(bytes, 2); }