method2testcases
stringlengths 118
3.08k
|
---|
### Question:
UpDevice { public static UpDevice fromJSON(JSONObject json) throws JSONException { UpDevice device = new UpDevice(); device.name = json.optString("name", null); device.networks = fromNetworks(json, "networks"); device.meta = fromMeta(json); return device; } UpDevice(); UpDevice(String name); UpDevice addNetworkInterface(String networkAdress, String networkType); String getName(); void setName(String name); List<UpNetworkInterface> getNetworks(); void setNetworks(List<UpNetworkInterface> networks); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Object getProperty(String key); void addProperty(String key, String value); Map<String, String> getMeta(); void setMeta(Map<String, String> meta); JSONObject toJSON(); static UpDevice fromJSON(JSONObject json); }### Answer:
@Test public void fromJSON() throws JSONException{ assertThat(UpDevice.fromJSON(dummyJSONDevice())) .isEqualTo(dummyDevice()); }
@Test public void fromJSONString() throws JSONException{ JSONObject dummyJSONDevice = dummyJSONDevice(); JSONObject temp = new JSONObject(dummyJSONDevice.toMap()); assertThat(UpDevice.fromJSON(temp)) .isEqualTo(dummyDevice()); }
@Test public void fromJSONForEmpty() throws JSONException{ assertThat(UpDevice.fromJSON(new JSONObject())) .isEqualTo(new UpDevice()); } |
### Question:
DeviceDao { public void save(UpDevice device) { if (device.getNetworks() != null){ for (UpNetworkInterface ni : device.getNetworks()){ interfaceMap.put(createInterfaceKey(ni), device); if(!networkTypeMap.containsKey(ni.getNetType())){ networkTypeMap.put(ni.getNetType(), new ArrayList<UpDevice>()); } networkTypeMap.get(ni.getNetType()).add(device); if(!addressMap.containsKey(ni.getNetworkAddress())){ addressMap.put(ni.getNetworkAddress(), new ArrayList<UpDevice>()); } addressMap.get(ni.getNetworkAddress()).add(device); } } deviceMap.put(device.getName().toLowerCase(),device); } DeviceDao(InitialProperties bundle); void save(UpDevice device); void update(String oldname, UpDevice device); void delete(String name); List<UpDevice> list(); List<UpDevice> list(String address, String networktype); UpDevice find(String name); void clear(); }### Answer:
@Ignore @Test(expected=Exception.class) public void should_not_save_a_device_with_the_same_name(){ dao.save(new UpDevice("my.device")); dao.save(new UpDevice("my.device")); } |
### Question:
Notify extends Message { @Override public int hashCode() { int hash = 0; if (this.eventKey != null){ hash += this.eventKey.hashCode(); } if (this.driver != null){ hash += this.driver.hashCode(); } if (this.instanceId != null){ hash += this.instanceId.hashCode(); } return hash; } Notify(); Notify(String eventKey); Notify(String eventKey, String driver); Notify(String eventKey, String driver, String instanceId); String getEventKey(); void setEventKey(String eventKey); Map<String, Object> getParameters(); void setParameters(Map<String, Object> parameters); Notify addParameter(String key, String value); Notify addParameter(String key, Number value); Object getParameter(String key); @Override boolean equals(Object obj); @Override int hashCode(); String getDriver(); void setDriver(String driver); String getInstanceId(); void setInstanceId(String instanceId); JSONObject toJSON(); static Notify fromJSON(JSONObject json); @Override String toString(); }### Answer:
@Test public void hash(){ Notify e1 = new Notify("e"); Notify e2 = new Notify("e"); Notify ed1 = new Notify("e","d"); Notify ed2 = new Notify("e","d"); Notify edid1 = new Notify("e","d","id"); Notify edid2 = new Notify("e","d","id"); Notify edid3 = new Notify("e","d","idx"); Notify edid4 = new Notify("e","dx","id"); Notify edid5 = new Notify("ex","d","id"); assertThat(e2.hashCode()).isEqualTo(e1.hashCode()); assertThat(ed1.hashCode()).isEqualTo(ed2.hashCode()); assertThat(edid1.hashCode()).isEqualTo(edid2.hashCode()); assertThat(edid1.hashCode()).isNotEqualTo(edid3.hashCode()); assertThat(edid1.hashCode()).isNotEqualTo(edid4.hashCode()); assertThat(edid1.hashCode()).isNotEqualTo(edid5.hashCode()); } |
### Question:
Notify extends Message { public JSONObject toJSON() throws JSONException { JSONObject json = super.toJSON(); json.put("eventKey",this.eventKey); json.put("driver",this.driver); json.put("instanceId",this.instanceId); if (this.parameters != null) json.put("parameters",this.parameters); return json; } Notify(); Notify(String eventKey); Notify(String eventKey, String driver); Notify(String eventKey, String driver, String instanceId); String getEventKey(); void setEventKey(String eventKey); Map<String, Object> getParameters(); void setParameters(Map<String, Object> parameters); Notify addParameter(String key, String value); Notify addParameter(String key, Number value); Object getParameter(String key); @Override boolean equals(Object obj); @Override int hashCode(); String getDriver(); void setDriver(String driver); String getInstanceId(); void setInstanceId(String instanceId); JSONObject toJSON(); static Notify fromJSON(JSONObject json); @Override String toString(); }### Answer:
@Test public void toJSON() throws JSONException{ assertThat(dummyJSON()).isEqualTo(dummyNotify().toJSON()); }
@Test public void toJSONWithEmpty() throws JSONException{ JSONObject json = new JSONObject(){{ put("type", Message.Type.NOTIFY.name()); }}; assertThat(json).isEqualTo(new Notify().toJSON()); } |
### Question:
StringUtils { static boolean contains(char c, String what) { return what.indexOf(c) >= 0; } static int skip_spaces_reverse(StringBuilder s, int pos); static int skip_spaces(StringBuilder s, int pos); static boolean is_space(char c); static List<String> split_str(StringBuilder s, String c); static String strip(StringBuilder s, String what); static String strip_post(StringBuilder s, String what); static String strip_post(String str, String what); static String strip(String s, String what); static void set_defaultAutoLineLenght(int length); static int get_defaultAutoLineLenght(); static String autoLineBreak(String what); static String autoLineBreak(StringBuilder what, int length); static String autoLineBreak(StringBuilder what); static String autoLineBreak(String what, int length); static String formatDouble(double d, int rounding); static String formatDouble(double d); static boolean isYes(String maybe_a_yes_value); @Deprecated static String exceptionToString(Exception ex); static String skipLeadingLines(String sourceString, int lines); static String byteArrayToString(byte[] data); static String addLineNumbers(String text); }### Answer:
@Test public void testContains() { System.out.println("contains"); assertFalse(StringUtils.contains(' ', "")); assertTrue(StringUtils.contains('x', "xxxx")); assertTrue(StringUtils.contains('x', "xyz")); assertFalse(StringUtils.contains('x', "yyyyyyyyyyyy")); try { StringUtils.contains('x', null); fail( "nullpointer throws no exception"); } catch( NullPointerException ex ) { } } |
### Question:
StringUtils { public static void set_defaultAutoLineLenght(int length) { defaultAutoLineLength = length; } static int skip_spaces_reverse(StringBuilder s, int pos); static int skip_spaces(StringBuilder s, int pos); static boolean is_space(char c); static List<String> split_str(StringBuilder s, String c); static String strip(StringBuilder s, String what); static String strip_post(StringBuilder s, String what); static String strip_post(String str, String what); static String strip(String s, String what); static void set_defaultAutoLineLenght(int length); static int get_defaultAutoLineLenght(); static String autoLineBreak(String what); static String autoLineBreak(StringBuilder what, int length); static String autoLineBreak(StringBuilder what); static String autoLineBreak(String what, int length); static String formatDouble(double d, int rounding); static String formatDouble(double d); static boolean isYes(String maybe_a_yes_value); @Deprecated static String exceptionToString(Exception ex); static String skipLeadingLines(String sourceString, int lines); static String byteArrayToString(byte[] data); static String addLineNumbers(String text); }### Answer:
@Test public void testSet_defaultAutoLineLenght() { System.out.println("set_defaultAutoLineLenght"); StringUtils.set_defaultAutoLineLenght(10); assertEquals(10, StringUtils.get_defaultAutoLineLenght()); } |
### Question:
StringUtils { public static int get_defaultAutoLineLenght() { return defaultAutoLineLength; } static int skip_spaces_reverse(StringBuilder s, int pos); static int skip_spaces(StringBuilder s, int pos); static boolean is_space(char c); static List<String> split_str(StringBuilder s, String c); static String strip(StringBuilder s, String what); static String strip_post(StringBuilder s, String what); static String strip_post(String str, String what); static String strip(String s, String what); static void set_defaultAutoLineLenght(int length); static int get_defaultAutoLineLenght(); static String autoLineBreak(String what); static String autoLineBreak(StringBuilder what, int length); static String autoLineBreak(StringBuilder what); static String autoLineBreak(String what, int length); static String formatDouble(double d, int rounding); static String formatDouble(double d); static boolean isYes(String maybe_a_yes_value); @Deprecated static String exceptionToString(Exception ex); static String skipLeadingLines(String sourceString, int lines); static String byteArrayToString(byte[] data); static String addLineNumbers(String text); }### Answer:
@Test public void testGet_defaultAutoLineLenght() { System.out.println("get_defaultAutoLineLenght"); StringUtils.set_defaultAutoLineLenght(10); assertEquals(10, StringUtils.get_defaultAutoLineLenght()); } |
### Question:
StringUtils { @Deprecated public static String exceptionToString(Exception ex) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); PrintStream s = new PrintStream(bos); ex.printStackTrace(s); s.flush(); return bos.toString(); } static int skip_spaces_reverse(StringBuilder s, int pos); static int skip_spaces(StringBuilder s, int pos); static boolean is_space(char c); static List<String> split_str(StringBuilder s, String c); static String strip(StringBuilder s, String what); static String strip_post(StringBuilder s, String what); static String strip_post(String str, String what); static String strip(String s, String what); static void set_defaultAutoLineLenght(int length); static int get_defaultAutoLineLenght(); static String autoLineBreak(String what); static String autoLineBreak(StringBuilder what, int length); static String autoLineBreak(StringBuilder what); static String autoLineBreak(String what, int length); static String formatDouble(double d, int rounding); static String formatDouble(double d); static boolean isYes(String maybe_a_yes_value); @Deprecated static String exceptionToString(Exception ex); static String skipLeadingLines(String sourceString, int lines); static String byteArrayToString(byte[] data); static String addLineNumbers(String text); }### Answer:
@Test public void testExceptionToString() { System.out.println("exceptionToString"); try { int i = Integer.parseInt("asdfasdf"); } catch( NumberFormatException ex ) { String res = StringUtils.exceptionToString(ex); if( res.length() < 100 ) { System.out.println(res); fail( "something wrong with that exception to String function"); } } } |
### Question:
StringUtils { public static String byteArrayToString(byte[] data) { if (data == null) { return ""; } StringBuilder str = new StringBuilder(); for (int index = 0; index < data.length; index++) { str.append((char) (data[index])); } return str.toString(); } static int skip_spaces_reverse(StringBuilder s, int pos); static int skip_spaces(StringBuilder s, int pos); static boolean is_space(char c); static List<String> split_str(StringBuilder s, String c); static String strip(StringBuilder s, String what); static String strip_post(StringBuilder s, String what); static String strip_post(String str, String what); static String strip(String s, String what); static void set_defaultAutoLineLenght(int length); static int get_defaultAutoLineLenght(); static String autoLineBreak(String what); static String autoLineBreak(StringBuilder what, int length); static String autoLineBreak(StringBuilder what); static String autoLineBreak(String what, int length); static String formatDouble(double d, int rounding); static String formatDouble(double d); static boolean isYes(String maybe_a_yes_value); @Deprecated static String exceptionToString(Exception ex); static String skipLeadingLines(String sourceString, int lines); static String byteArrayToString(byte[] data); static String addLineNumbers(String text); }### Answer:
@Test public void testByteArrayToString() { System.out.println("byteArrayToString"); byte[] bytes = {72,97,108,108,111}; assertEquals("Hallo",StringUtils.byteArrayToString(bytes)); } |
### Question:
ParseJNLP { public Properties getProperties() { return properties; } ParseJNLP( File file ); Properties getProperties(); String getMainJar(); List<String> getJars(); String getCodeBase(); String print(); void print( StringBuilder stream, Node node, int depth ); static void main( final String[] argv); }### Answer:
@Test public void testGetProperties() throws ParserConfigurationException, IOException, SAXException { for( TestFile test : test_cases ) { System.out.println("getProperties for " + test.resource); ParseJNLP instance = new ParseJNLP(test.getFile()); Properties expResult = test.getProperties(); Properties result = instance.getProperties(); assertEquals(expResult, result); } } |
### Question:
ParseJNLP { public String getMainJar() { return mainJar; } ParseJNLP( File file ); Properties getProperties(); String getMainJar(); List<String> getJars(); String getCodeBase(); String print(); void print( StringBuilder stream, Node node, int depth ); static void main( final String[] argv); }### Answer:
@Test public void testGetMainJar() throws ParserConfigurationException, IOException, SAXException { for( TestFile test : test_cases ) { System.out.println("getMainJar for " + test.resource ); ParseJNLP instance = new ParseJNLP(test.getFile()); String expResult = test.getMainJar(); String result = instance.getMainJar(); assertEquals(expResult, result); } } |
### Question:
ParseJNLP { public List<String> getJars() { return jars; } ParseJNLP( File file ); Properties getProperties(); String getMainJar(); List<String> getJars(); String getCodeBase(); String print(); void print( StringBuilder stream, Node node, int depth ); static void main( final String[] argv); }### Answer:
@Test public void testGetJars() throws ParserConfigurationException, IOException, SAXException { for( TestFile test : test_cases ) { System.out.println("getJars for " + test.resource); ParseJNLP instance = new ParseJNLP(test.getFile()); List<String> expResult = test.getJars(); List<String> result = instance.getJars(); assertEquals(expResult, result); } } |
### Question:
ParseJNLP { public String getCodeBase() { return codeBase; } ParseJNLP( File file ); Properties getProperties(); String getMainJar(); List<String> getJars(); String getCodeBase(); String print(); void print( StringBuilder stream, Node node, int depth ); static void main( final String[] argv); }### Answer:
@Test public void testGetCodeBase() throws ParserConfigurationException, IOException, SAXException { for (TestFile test : test_cases) { System.out.println("getCodeBase for " + test.resource); ParseJNLP instance = new ParseJNLP(test.getFile()); String expResult = test.getCodeBase(); String result = instance.getCodeBase(); assertEquals(expResult, result); } } |
### Question:
BaseHolidays { public static LocalDate getEaster( int year ) { Easterformular easter_formular = new Easterformular(year); int day = easter_formular.easterday(); if( day <= 31 ) { return new LocalDate( year, 3, day ); } else { return new LocalDate( year, 4, day - 31 ); } } BaseHolidays( String CountryCode ); HolidayInfo create( DateMidnight date, boolean floating, boolean official, String name ); HolidayInfo create( LocalDate date, boolean floating, boolean official, String name ); HolidayInfo create( int year, int month, int day, boolean floating, boolean official, String name ); static LocalDate getEaster( int year ); int getNumberOfCountryCodes(); LocalDate getEuropeanSummerTimeBegin( int year ); LocalDate getEuropeanSummerTimeEnd( int year ); LocalDate getLastSundayOf( int year, int month ); abstract Collection<HolidayInfo> getHolidays(int year); HolidayInfo getHolidayForDay( Calendar date ); HolidayInfo getHolidayForDay( DateMidnight date ); HolidayInfo getHolidayForDay( LocalDate date ); public String CountryCode; }### Answer:
@Test public void testGetEaster() { System.out.println("getEaster"); LocalDate[] dates = { new LocalDate(2008,3,23), new LocalDate(2009,4,12), new LocalDate(2010,4,4), new LocalDate(2011,4,24) }; for( LocalDate dm : dates ) { System.out.println("getEaster " + dm.getYear()); int year = dm.getYear(); LocalDate result = BaseHolidays.getEaster(year); assertEquals(dm, result); } for( int year = 1970; year < 2030; year++ ) { System.out.print("getEaster " + year + ": "); LocalDate result = BaseHolidays.getEaster(year); System.out.println(result); } } |
### Question:
BaseHolidays { public LocalDate getEuropeanSummerTimeBegin( int year ) { return getLastSundayOf( year, 3 ); } BaseHolidays( String CountryCode ); HolidayInfo create( DateMidnight date, boolean floating, boolean official, String name ); HolidayInfo create( LocalDate date, boolean floating, boolean official, String name ); HolidayInfo create( int year, int month, int day, boolean floating, boolean official, String name ); static LocalDate getEaster( int year ); int getNumberOfCountryCodes(); LocalDate getEuropeanSummerTimeBegin( int year ); LocalDate getEuropeanSummerTimeEnd( int year ); LocalDate getLastSundayOf( int year, int month ); abstract Collection<HolidayInfo> getHolidays(int year); HolidayInfo getHolidayForDay( Calendar date ); HolidayInfo getHolidayForDay( DateMidnight date ); HolidayInfo getHolidayForDay( LocalDate date ); public String CountryCode; }### Answer:
@Test @Ignore("Not implemented") public void testGetEuropeanSummerTimeBegin() { System.out.println("getEuropeanSummerTimeBegin"); int year = 0; BaseHolidays instance = null; LocalDate expResult = null; LocalDate result = instance.getEuropeanSummerTimeBegin(year); assertEquals(expResult, result); fail("The test case is a prototype."); } |
### Question:
BaseHolidays { public LocalDate getEuropeanSummerTimeEnd( int year ) { return getLastSundayOf( year, 10 ); } BaseHolidays( String CountryCode ); HolidayInfo create( DateMidnight date, boolean floating, boolean official, String name ); HolidayInfo create( LocalDate date, boolean floating, boolean official, String name ); HolidayInfo create( int year, int month, int day, boolean floating, boolean official, String name ); static LocalDate getEaster( int year ); int getNumberOfCountryCodes(); LocalDate getEuropeanSummerTimeBegin( int year ); LocalDate getEuropeanSummerTimeEnd( int year ); LocalDate getLastSundayOf( int year, int month ); abstract Collection<HolidayInfo> getHolidays(int year); HolidayInfo getHolidayForDay( Calendar date ); HolidayInfo getHolidayForDay( DateMidnight date ); HolidayInfo getHolidayForDay( LocalDate date ); public String CountryCode; }### Answer:
@Test @Ignore("Not implemented") public void testGetEuropeanSummerTimeEnd() { System.out.println("getEuropeanSummerTimeEnd"); int year = 0; BaseHolidays instance = null; LocalDate expResult = null; LocalDate result = instance.getEuropeanSummerTimeEnd(year); assertEquals(expResult, result); fail("The test case is a prototype."); } |
### Question:
BaseHolidays { public LocalDate getLastSundayOf( int year, int month ) { LocalDate dm = new LocalDate( year, month, 31 ); while( true ) { if( dm.getDayOfWeek() == DateTimeConstants.SUNDAY ) return dm; dm = dm.minusDays(1); } } BaseHolidays( String CountryCode ); HolidayInfo create( DateMidnight date, boolean floating, boolean official, String name ); HolidayInfo create( LocalDate date, boolean floating, boolean official, String name ); HolidayInfo create( int year, int month, int day, boolean floating, boolean official, String name ); static LocalDate getEaster( int year ); int getNumberOfCountryCodes(); LocalDate getEuropeanSummerTimeBegin( int year ); LocalDate getEuropeanSummerTimeEnd( int year ); LocalDate getLastSundayOf( int year, int month ); abstract Collection<HolidayInfo> getHolidays(int year); HolidayInfo getHolidayForDay( Calendar date ); HolidayInfo getHolidayForDay( DateMidnight date ); HolidayInfo getHolidayForDay( LocalDate date ); public String CountryCode; }### Answer:
@Test @Ignore("Not implemented") public void testGetLastSundayOf() { System.out.println("getLastSundayOf"); int year = 0; int month = 0; BaseHolidays instance = null; LocalDate expResult = null; LocalDate result = instance.getLastSundayOf(year, month); assertEquals(expResult, result); fail("The test case is a prototype."); } |
### Question:
DBString extends DBValue { @Override public DBDataType getDBType() { return DBDataType.DB_TYPE_STRING; } DBString( String name, int max_len ); DBString( String name, String title, int max_len ); DBString( String name, String title, int max_len, boolean is_already_lowercase ); @Override DBDataType getDBType(); @Override void loadFromDB(Object obj); @Override String getValue(); @Override String toString(); @Override void loadFromString(String s); @Override boolean acceptString(String s); @Override DBString getCopy(); @Override void loadFromCopy(Object obj); int getMaxLen(); boolean isEmpty(); boolean isEmptyTrimmed(); }### Answer:
@Test public void testGetDBType() { System.out.println("getDBType"); for (TestCases test : test_cases) { DBString instance = test.instance; DBDataType expResult = DBDataType.DB_TYPE_STRING; DBDataType result = instance.getDBType(); assertEquals(expResult, result); } } |
### Question:
DBString extends DBValue { @Override public void loadFromDB(Object obj) { value = (String)obj; } DBString( String name, int max_len ); DBString( String name, String title, int max_len ); DBString( String name, String title, int max_len, boolean is_already_lowercase ); @Override DBDataType getDBType(); @Override void loadFromDB(Object obj); @Override String getValue(); @Override String toString(); @Override void loadFromString(String s); @Override boolean acceptString(String s); @Override DBString getCopy(); @Override void loadFromCopy(Object obj); int getMaxLen(); boolean isEmpty(); boolean isEmptyTrimmed(); }### Answer:
@Test public void testLoadFromDB() { System.out.println("loadFromDB"); for (TestCases test : test_cases) { Object obj = test.db_value; DBString instance = test.instance; instance.loadFromDB(obj); assertEquals(test.exp_value, instance.getValue()); } } |
### Question:
DBString extends DBValue { @Override public String getValue() { return value; } DBString( String name, int max_len ); DBString( String name, String title, int max_len ); DBString( String name, String title, int max_len, boolean is_already_lowercase ); @Override DBDataType getDBType(); @Override void loadFromDB(Object obj); @Override String getValue(); @Override String toString(); @Override void loadFromString(String s); @Override boolean acceptString(String s); @Override DBString getCopy(); @Override void loadFromCopy(Object obj); int getMaxLen(); boolean isEmpty(); boolean isEmptyTrimmed(); }### Answer:
@Test public void testGetValue() { System.out.println("getValue"); for (TestCases test : test_cases) { Object obj = test.db_value; DBString instance = test.instance; instance.loadFromDB(obj); assertEquals(test.exp_value, instance.getValue()); } } |
### Question:
DBString extends DBValue { @Override public String toString() { return value; } DBString( String name, int max_len ); DBString( String name, String title, int max_len ); DBString( String name, String title, int max_len, boolean is_already_lowercase ); @Override DBDataType getDBType(); @Override void loadFromDB(Object obj); @Override String getValue(); @Override String toString(); @Override void loadFromString(String s); @Override boolean acceptString(String s); @Override DBString getCopy(); @Override void loadFromCopy(Object obj); int getMaxLen(); boolean isEmpty(); boolean isEmptyTrimmed(); }### Answer:
@Test public void testToString() { System.out.println("toString"); for (TestCases test : test_cases) { DBString instance = test.instance; String expResult = test.exp_value; String result = instance.toString(); assertEquals(expResult, result); } } |
### Question:
DBString extends DBValue { @Override public void loadFromString(String s) { value = s; } DBString( String name, int max_len ); DBString( String name, String title, int max_len ); DBString( String name, String title, int max_len, boolean is_already_lowercase ); @Override DBDataType getDBType(); @Override void loadFromDB(Object obj); @Override String getValue(); @Override String toString(); @Override void loadFromString(String s); @Override boolean acceptString(String s); @Override DBString getCopy(); @Override void loadFromCopy(Object obj); int getMaxLen(); boolean isEmpty(); boolean isEmptyTrimmed(); }### Answer:
@Test public void testLoadFromString() { System.out.println("loadFromString"); for (TestCases test : test_cases) { String obj = test.db_value; DBString instance = test.instance; instance.loadFromString(obj); assertEquals(test.exp_value, instance.getValue()); } } |
### Question:
DBString extends DBValue { @Override public boolean acceptString(String s) { if( s.length() > max_len ) return false; return true; } DBString( String name, int max_len ); DBString( String name, String title, int max_len ); DBString( String name, String title, int max_len, boolean is_already_lowercase ); @Override DBDataType getDBType(); @Override void loadFromDB(Object obj); @Override String getValue(); @Override String toString(); @Override void loadFromString(String s); @Override boolean acceptString(String s); @Override DBString getCopy(); @Override void loadFromCopy(Object obj); int getMaxLen(); boolean isEmpty(); boolean isEmptyTrimmed(); }### Answer:
@Test public void testAcceptString() { System.out.println("acceptString"); ArrayList<SimpleEntry<String,Boolean>> test_strings = new ArrayList(); test_strings.add(new SimpleEntry<>(NORMAL_STRING, true)); test_strings.add(new SimpleEntry<>(LONG_STRING, false)); for (TestCases test : test_cases) { for( SimpleEntry<String,Boolean> e : test_strings ) { String s = e.getKey(); DBString instance = test.instance; boolean expResult = e.getValue(); boolean result = instance.acceptString(s); assertEquals(expResult, result); } } } |
### Question:
DBString extends DBValue { @Override public DBString getCopy() { DBString s = new DBString( name, title, max_len ); s.value = value; return s; } DBString( String name, int max_len ); DBString( String name, String title, int max_len ); DBString( String name, String title, int max_len, boolean is_already_lowercase ); @Override DBDataType getDBType(); @Override void loadFromDB(Object obj); @Override String getValue(); @Override String toString(); @Override void loadFromString(String s); @Override boolean acceptString(String s); @Override DBString getCopy(); @Override void loadFromCopy(Object obj); int getMaxLen(); boolean isEmpty(); boolean isEmptyTrimmed(); }### Answer:
@Test public void testGetCopy() { System.out.println("getCopy"); for (TestCases test : test_cases) { DBString instance = test.instance; DBString result = instance.getCopy(); assertNotSame(result, instance); } } |
### Question:
DBString extends DBValue { @Override public void loadFromCopy(Object obj) { value = (String)obj; } DBString( String name, int max_len ); DBString( String name, String title, int max_len ); DBString( String name, String title, int max_len, boolean is_already_lowercase ); @Override DBDataType getDBType(); @Override void loadFromDB(Object obj); @Override String getValue(); @Override String toString(); @Override void loadFromString(String s); @Override boolean acceptString(String s); @Override DBString getCopy(); @Override void loadFromCopy(Object obj); int getMaxLen(); boolean isEmpty(); boolean isEmptyTrimmed(); }### Answer:
@Test public void testLoadFromCopy() { System.out.println("loadFromCopy"); for (TestCases test : test_cases) { Object obj = NORMAL_STRING; DBString instance = test.instance; instance.loadFromCopy(obj); assertEquals(obj, instance.value); } } |
### Question:
DBString extends DBValue { public int getMaxLen() { return max_len; } DBString( String name, int max_len ); DBString( String name, String title, int max_len ); DBString( String name, String title, int max_len, boolean is_already_lowercase ); @Override DBDataType getDBType(); @Override void loadFromDB(Object obj); @Override String getValue(); @Override String toString(); @Override void loadFromString(String s); @Override boolean acceptString(String s); @Override DBString getCopy(); @Override void loadFromCopy(Object obj); int getMaxLen(); boolean isEmpty(); boolean isEmptyTrimmed(); }### Answer:
@Test public void testGetMaxLen() { System.out.println("getMaxLen"); for (TestCases test : test_cases) { DBString instance = test.instance; int result = instance.getMaxLen(); assertEquals(MAX_LEN, result); } } |
### Question:
DBString extends DBValue { public boolean isEmpty() { return value.isEmpty(); } DBString( String name, int max_len ); DBString( String name, String title, int max_len ); DBString( String name, String title, int max_len, boolean is_already_lowercase ); @Override DBDataType getDBType(); @Override void loadFromDB(Object obj); @Override String getValue(); @Override String toString(); @Override void loadFromString(String s); @Override boolean acceptString(String s); @Override DBString getCopy(); @Override void loadFromCopy(Object obj); int getMaxLen(); boolean isEmpty(); boolean isEmptyTrimmed(); }### Answer:
@Test public void testIsEmpty() { System.out.println("isEmpty"); for (TestCases test : test_cases) { DBString instance = test.instance; boolean expResult = false; boolean result = instance.isEmpty(); assertEquals(expResult, result); } } |
### Question:
DBString extends DBValue { public boolean isEmptyTrimmed() { return value.trim().isEmpty(); } DBString( String name, int max_len ); DBString( String name, String title, int max_len ); DBString( String name, String title, int max_len, boolean is_already_lowercase ); @Override DBDataType getDBType(); @Override void loadFromDB(Object obj); @Override String getValue(); @Override String toString(); @Override void loadFromString(String s); @Override boolean acceptString(String s); @Override DBString getCopy(); @Override void loadFromCopy(Object obj); int getMaxLen(); boolean isEmpty(); boolean isEmptyTrimmed(); }### Answer:
@Test @Ignore("Not implemented") public void testIsEmptyTrimmed() { System.out.println("isEmptyTrimmed"); DBString instance = null; boolean expResult = false; boolean result = instance.isEmptyTrimmed(); assertEquals(expResult, result); fail("The test case is a prototype."); } |
### Question:
StringUtils { public static int skip_spaces_reverse(StringBuilder s, int pos) { return skip_char_reverse(s, " \t\n\r", pos); } static int skip_spaces_reverse(StringBuilder s, int pos); static int skip_spaces(StringBuilder s, int pos); static boolean is_space(char c); static List<String> split_str(StringBuilder s, String c); static String strip(StringBuilder s, String what); static String strip_post(StringBuilder s, String what); static String strip_post(String str, String what); static String strip(String s, String what); static void set_defaultAutoLineLenght(int length); static int get_defaultAutoLineLenght(); static String autoLineBreak(String what); static String autoLineBreak(StringBuilder what, int length); static String autoLineBreak(StringBuilder what); static String autoLineBreak(String what, int length); static String formatDouble(double d, int rounding); static String formatDouble(double d); static boolean isYes(String maybe_a_yes_value); @Deprecated static String exceptionToString(Exception ex); static String skipLeadingLines(String sourceString, int lines); static String byteArrayToString(byte[] data); static String addLineNumbers(String text); }### Answer:
@Test public void testSkip_spaces_reverse() { System.out.println("skip_spaces_reverse"); assertEquals(15, StringUtils.skip_spaces_reverse(new StringBuilder("das ist ein Test"), 15)); assertEquals(10, StringUtils.skip_spaces_reverse(new StringBuilder("das ist ein \t Test"), 14)); assertEquals(10, StringUtils.skip_spaces_reverse(new StringBuilder("das ist ein Test"), 10)); try { StringUtils.skip_spaces_reverse(null, 1 ); fail( "nullpointer throws no exception"); } catch( NullPointerException ex ) { } } |
### Question:
StringUtils { public static int skip_spaces(StringBuilder s, int pos) { return skip_char(s, " \t\n\r", pos); } static int skip_spaces_reverse(StringBuilder s, int pos); static int skip_spaces(StringBuilder s, int pos); static boolean is_space(char c); static List<String> split_str(StringBuilder s, String c); static String strip(StringBuilder s, String what); static String strip_post(StringBuilder s, String what); static String strip_post(String str, String what); static String strip(String s, String what); static void set_defaultAutoLineLenght(int length); static int get_defaultAutoLineLenght(); static String autoLineBreak(String what); static String autoLineBreak(StringBuilder what, int length); static String autoLineBreak(StringBuilder what); static String autoLineBreak(String what, int length); static String formatDouble(double d, int rounding); static String formatDouble(double d); static boolean isYes(String maybe_a_yes_value); @Deprecated static String exceptionToString(Exception ex); static String skipLeadingLines(String sourceString, int lines); static String byteArrayToString(byte[] data); static String addLineNumbers(String text); }### Answer:
@Test public void testSkip_spaces() { System.out.println("skip_spaces"); assertEquals(12, StringUtils.skip_spaces(new StringBuilder( "das ist ein Text"), 7)); assertEquals(2, StringUtils.skip_spaces(new StringBuilder( "das ist ein Text"), 2)); assertEquals(4, StringUtils.skip_spaces(new StringBuilder( "das ist ein Text"), 4)); assertEquals(4, StringUtils.skip_spaces(new StringBuilder( "das ist ein Text"), 3)); try { StringUtils.skip_spaces(null, 1 ); fail( "nullpointer throws no exception"); } catch( NullPointerException ex ) { } } |
### Question:
StringUtils { public static boolean is_space(char c) { if (c == ' ' || c == '\t' || c == '\n' || c == '\r') { return true; } return false; } static int skip_spaces_reverse(StringBuilder s, int pos); static int skip_spaces(StringBuilder s, int pos); static boolean is_space(char c); static List<String> split_str(StringBuilder s, String c); static String strip(StringBuilder s, String what); static String strip_post(StringBuilder s, String what); static String strip_post(String str, String what); static String strip(String s, String what); static void set_defaultAutoLineLenght(int length); static int get_defaultAutoLineLenght(); static String autoLineBreak(String what); static String autoLineBreak(StringBuilder what, int length); static String autoLineBreak(StringBuilder what); static String autoLineBreak(String what, int length); static String formatDouble(double d, int rounding); static String formatDouble(double d); static boolean isYes(String maybe_a_yes_value); @Deprecated static String exceptionToString(Exception ex); static String skipLeadingLines(String sourceString, int lines); static String byteArrayToString(byte[] data); static String addLineNumbers(String text); }### Answer:
@Test public void testIs_space() { System.out.println("is_space"); assertTrue(StringUtils.is_space(' ')); assertTrue(StringUtils.is_space('\t')); assertTrue(StringUtils.is_space('\r')); assertTrue(StringUtils.is_space('\n')); assertFalse(StringUtils.is_space('\0')); assertFalse(StringUtils.is_space('x')); } |
### Question:
NetworkStatusPresenter implements NetworkStatusContract.Presenter { @Override public void getNodes() { stopNodeRefresh(); startNodeRefresh(); } NetworkStatusPresenter(NetworkStatusContract.View view, Feature6LoWPANProtocol centralNode); @Override void startNodeRefresh(); @Override void stopNodeRefresh(); @Override void getNodes(); @Override void onNodeSelected(SensorNode node); }### Answer:
@Test public void toGetTheNodeListTheFeatureIsCalled(){ mPresenter.getNodes(); verify(mFeature).getNetworkNodeList(any(Feature6LoWPANProtocol.NetworkNodeListCallback.class)); }
@Test public void whenTheNodeListCallbackIsCalledTheViewIsUpdated(){ mPresenter.getNodes(); ArgumentCaptor<Feature6LoWPANProtocol.NetworkNodeListCallback> callback = ArgumentCaptor.forClass(Feature6LoWPANProtocol.NetworkNodeListCallback.class); verify(mFeature).getNetworkNodeList(callback.capture()); callback.getValue().onComplete(SENSOR_NODES); verify(mView).showNodes(SENSOR_NODES); } |
### Question:
NetworkResponse { public void append(@NonNull byte[] bytes) { for(byte b : bytes){ mData.add(b); } } void append(@NonNull byte[] bytes); short getTimestamp(); short getCommandId(); short getLength(); boolean isCompleted(); byte[] getPayload(); }### Answer:
@Test public void theByteAreAppendedToTheResponse(){ mResp.append(new byte[]{1,2,3}); } |
### Question:
OrderableCsvFile implements Comparable<OrderableCsvFile> { public File getFile() { return file; } OrderableCsvFile(File file, String checksum); Integer getOrder(); String getChecksum(); File getFile(); @Override int compareTo(OrderableCsvFile that); }### Answer:
@Test public void shouldSortAccordingToCsvOrder() throws IOException { URL url = getClass().getClassLoader().getResource("org/openmrs/module/initializer/include/csv/orders"); File[] files = new File(url.getPath()).listFiles(); List<OrderableCsvFile> orderableFiles = new ArrayList<OrderableCsvFile>(); for (File f : files) { orderableFiles.add(new OrderableCsvFile(f, "")); } Collections.sort(orderableFiles); Assert.assertEquals("5_order_500.csv", orderableFiles.get(0).getFile().getName()); Assert.assertEquals("4_order_1000.csv", orderableFiles.get(1).getFile().getName()); Assert.assertEquals("1_order_1500.csv", orderableFiles.get(2).getFile().getName()); } |
### Question:
MappingsConceptLineProcessor extends ConceptLineProcessor { public Concept fill(Concept concept, CsvLine line) throws IllegalArgumentException { if (!CollectionUtils.isEmpty(concept.getConceptMappings())) { concept.getConceptMappings().clear(); } String mappingsStr = line.get(HEADER_MAPPINGS_SAMEAS); if (!StringUtils.isEmpty(mappingsStr)) { for (ConceptMap mapping : listParser.parseList(mappingsStr)) { concept.addConceptMapping(mapping); } } return concept; } @Autowired MappingsConceptLineProcessor(@Qualifier("conceptService") ConceptService conceptService,
ConceptMapListParser listParser); Concept fill(Concept concept, CsvLine line); }### Answer:
@Test public void fill_shouldParseSameAsMappings() { String[] headerLine = { "Same as mappings" }; String[] line = { "cambodia:123; foo:456" }; MappingsConceptLineProcessor p = new MappingsConceptLineProcessor(cs, new ConceptMapListParser(cs)); Concept c = p.fill(new Concept(), new CsvLine(headerLine, line)); Collection<ConceptMap> mappings = c.getConceptMappings(); Assert.assertEquals(2, mappings.size()); Set<String> names = new HashSet<String>(); for (ConceptMap m : mappings) { String source = m.getConceptReferenceTerm().getConceptSource().getName(); String code = m.getConceptReferenceTerm().getCode(); names.add(source + ":" + code); } Assert.assertTrue(names.contains("cambodia:123")); Assert.assertTrue(names.contains("foo:456")); }
@Test public void fill_shouldHandleNoSameAsMappings() { String[] headerLine = { "Same as mappings" }; String[] line = { null }; MappingsConceptLineProcessor p = new MappingsConceptLineProcessor(cs, new ConceptMapListParser(cs)); Concept c = p.fill(new Concept(), new CsvLine(headerLine, line)); Assert.assertTrue(CollectionUtils.isEmpty(c.getConceptMappings())); } |
### Question:
IntRange extends AbstractList<Integer> implements ArrayWritable<Integer>, RandomAccess, Serializable { @Override public int size() { return size; } IntRange(int start, int end); IntRange(int start, int end, int step); @Override Integer get(int index); int intGet(int index); int intValue(int i); @Override boolean contains(@Nullable Object o); @Override int indexOf(@Nullable Object o); int indexOf(int i); @Override int lastIndexOf(@Nullable Object o); @Override IntRangeIterator iterator(); @Override IntRangeIterator listIterator(); @Override IntRangeIterator listIterator(int index); @Override int size(); @Override void writeToArray(int offset, @Nullable Object[] array, int tgtOfs, int num); }### Answer:
@Test public void testSize() { Assert.assertEquals(ir0.size(), 10); Assert.assertEquals(ir1.size(), 4); } |
### Question:
IntRange extends AbstractList<Integer> implements ArrayWritable<Integer>, RandomAccess, Serializable { @Override public Integer get(int index) { return Integer.valueOf(intGet(index)); } IntRange(int start, int end); IntRange(int start, int end, int step); @Override Integer get(int index); int intGet(int index); int intValue(int i); @Override boolean contains(@Nullable Object o); @Override int indexOf(@Nullable Object o); int indexOf(int i); @Override int lastIndexOf(@Nullable Object o); @Override IntRangeIterator iterator(); @Override IntRangeIterator listIterator(); @Override IntRangeIterator listIterator(int index); @Override int size(); @Override void writeToArray(int offset, @Nullable Object[] array, int tgtOfs, int num); }### Answer:
@Test public void testGet() { Assert.assertEquals(ir0.get(0).intValue(), 10); Assert.assertEquals(ir0.get(4).intValue(), 14); Assert.assertEquals(ir1.get(2).intValue(), 26); Assert.assertEquals(ir1.get(3).intValue(), 29); } |
### Question:
IntRange extends AbstractList<Integer> implements ArrayWritable<Integer>, RandomAccess, Serializable { @Override public IntRangeIterator iterator() { return new IntRangeIterator(start, step, size); } IntRange(int start, int end); IntRange(int start, int end, int step); @Override Integer get(int index); int intGet(int index); int intValue(int i); @Override boolean contains(@Nullable Object o); @Override int indexOf(@Nullable Object o); int indexOf(int i); @Override int lastIndexOf(@Nullable Object o); @Override IntRangeIterator iterator(); @Override IntRangeIterator listIterator(); @Override IntRangeIterator listIterator(int index); @Override int size(); @Override void writeToArray(int offset, @Nullable Object[] array, int tgtOfs, int num); }### Answer:
@Test public void testIterator() { testIterator(ir0); testIterator(ir1); } |
### Question:
ReusableIterator implements Iterable<T> { @Override public Iterator<T> iterator() { return new CopyOnReadIterator(this.iterator); } ReusableIterator(Iterator<T> iterator); ReusableIterator(Iterator<T> iterator, List<T> cache); @Override Iterator<T> iterator(); }### Answer:
@Test public void testIterator() { final int size = 10; final Iterator<Integer> iterator = IntStream.range(0, size).iterator(); final Iterable<Integer> iterable = new ReusableIterator<>(iterator); final Iterator<Integer> iter1 = iterable.iterator(); final int firstLimit = 3; for (int i = 0; i < firstLimit; i++) { Assert.assertEquals(iter1.next(), Integer.valueOf(i)); } final Iterator<Integer> iter2 = iterable.iterator(); final int secondLimit = 8; for (int i = 0; i < secondLimit; i++) { Assert.assertEquals(iter2.next(), Integer.valueOf(i)); } final Iterator<Integer> iter3 = iterable.iterator(); final int thirdLimit = 5; for (int i = 0; i < thirdLimit; i++) { Assert.assertEquals(iter3.next(), Integer.valueOf(i)); } for (int i = firstLimit; i < size; i++) { Assert.assertEquals(iter1.next(), Integer.valueOf(i)); } Assert.assertFalse(iter1.hasNext()); for (int i = secondLimit; i < size; i++) { Assert.assertEquals(iter2.next(), Integer.valueOf(i)); } Assert.assertFalse(iter2.hasNext()); for (int i = thirdLimit; i < size; i++) { Assert.assertEquals(iter3.next(), Integer.valueOf(i)); } Assert.assertFalse(iter3.hasNext()); } |
### Question:
CharRange extends AbstractList<Character> implements ArrayWritable<Character>, RandomAccess, Serializable { @Override public CharRangeIterator listIterator() { return new CharRangeIterator(delegate.listIterator()); } CharRange(char low, char high); CharRange(char low, char high, int step); CharRange(IntRange delegate); @Override Character get(int index); char charGet(int index); @Override boolean contains(@Nullable Object o); @Override int indexOf(@Nullable Object o); int indexOf(char c); @Override int lastIndexOf(@Nullable Object o); @Override CharRangeIterator iterator(); @Override CharRangeIterator listIterator(); @Override CharRangeIterator listIterator(int index); @Override int size(); @Override void writeToArray(int offset, @Nullable Object[] array, int tgtOfs, int num); char charValue(int i); }### Answer:
@Test public void testListIterator() { ListIterator<Character> iterator = range.listIterator(range.size() + 1); Assert.assertEquals(iterator.nextIndex(), range.size()); Assert.assertThrows(NoSuchElementException.class, iterator::next); for (char i = end; i >= start; i--) { Assert.assertTrue(iterator.hasPrevious()); Assert.assertEquals(iterator.previous(), Character.valueOf(i)); } Assert.assertFalse(iterator.hasPrevious()); Assert.assertTrue(iterator.hasNext()); Assert.assertEquals(iterator.nextIndex(), 0); Assert.assertEquals(iterator.previousIndex(), -1); Assert.assertThrows(NoSuchElementException.class, iterator::previous); } |
### Question:
StringUtil { public static String enquote(String s) { StringBuilder sb = new StringBuilder(s.length() + 2); try { enquote(s, sb); } catch (IOException e) { LOGGER.error("Could not enquote String", e); } return sb.toString(); } private StringUtil(); static String enquote(String s); static void enquote(String s, Appendable a); static Pattern getIdentifierPattern(); static String enquoteIfNecessary(String s); static void enquoteIfNecessary(String s, Appendable a); static String enquoteIfNecessary(String s, Pattern p); static void enquoteIfNecessary(String s, Appendable a, Pattern valid); static void enquoteIfNecessary(String s, Appendable a, Pattern valid, Pattern exception); static String unquote(String s); static void unquote(String s, Appendable a); static String unescapeQuotes(String s); static void unescapeQuotes(String s, Appendable a); static String escapeQuotes(String s); static void escapeQuotes(String s, Appendable a); static void appendArray(Appendable a, Object[] array, String sepString); static void appendArrayEnquoted(Appendable a, Object[] array, String sepString); static void appendIterable(Appendable a, Iterable<?> it, String sepString); static void appendIterableEnquoted(Appendable a, Iterable<?> it, String sepString); static void appendObject(Appendable a, @Nullable Object obj); }### Answer:
@Test public void testEnquote() { Assert.assertEquals(StringUtil.enquote(""), "\"\""); Assert.assertEquals(StringUtil.enquote("abc"), "\"abc\""); Assert.assertEquals(StringUtil.enquote("\"abc\""), "\"\\\"abc\\\"\""); Assert.assertEquals(StringUtil.enquote("ab\"c"), "\"ab\\\"c\""); Assert.assertEquals(StringUtil.enquote("ab\\\"c"), "\"ab\\\\\\\"c\""); } |
### Question:
StringUtil { public static String enquoteIfNecessary(String s) { StringBuilder sb = new StringBuilder(); try { enquoteIfNecessary(s, sb); return sb.toString(); } catch (IOException ex) { throw new AssertionError("StringBuilder should not throw", ex); } } private StringUtil(); static String enquote(String s); static void enquote(String s, Appendable a); static Pattern getIdentifierPattern(); static String enquoteIfNecessary(String s); static void enquoteIfNecessary(String s, Appendable a); static String enquoteIfNecessary(String s, Pattern p); static void enquoteIfNecessary(String s, Appendable a, Pattern valid); static void enquoteIfNecessary(String s, Appendable a, Pattern valid, Pattern exception); static String unquote(String s); static void unquote(String s, Appendable a); static String unescapeQuotes(String s); static void unescapeQuotes(String s, Appendable a); static String escapeQuotes(String s); static void escapeQuotes(String s, Appendable a); static void appendArray(Appendable a, Object[] array, String sepString); static void appendArrayEnquoted(Appendable a, Object[] array, String sepString); static void appendIterable(Appendable a, Iterable<?> it, String sepString); static void appendIterableEnquoted(Appendable a, Iterable<?> it, String sepString); static void appendObject(Appendable a, @Nullable Object obj); }### Answer:
@Test public void testEnquoteIfNecessary() { Assert.assertEquals(StringUtil.enquoteIfNecessary(""), ""); Assert.assertEquals(StringUtil.enquoteIfNecessary("abc"), "abc"); Assert.assertEquals(StringUtil.enquoteIfNecessary("\"abc\""), "\"\\\"abc\\\"\""); Assert.assertEquals(StringUtil.enquoteIfNecessary("ab\"c"), "\"ab\\\"c\""); Assert.assertEquals(StringUtil.enquoteIfNecessary("ab\\\"c"), "\"ab\\\\\\\"c\""); } |
### Question:
StringUtil { public static String escapeQuotes(String s) { StringBuilder sb = new StringBuilder(s.length()); try { escapeQuotes(s, sb); } catch (IOException e) { LOGGER.error("Could not escape quotes", e); } return sb.toString(); } private StringUtil(); static String enquote(String s); static void enquote(String s, Appendable a); static Pattern getIdentifierPattern(); static String enquoteIfNecessary(String s); static void enquoteIfNecessary(String s, Appendable a); static String enquoteIfNecessary(String s, Pattern p); static void enquoteIfNecessary(String s, Appendable a, Pattern valid); static void enquoteIfNecessary(String s, Appendable a, Pattern valid, Pattern exception); static String unquote(String s); static void unquote(String s, Appendable a); static String unescapeQuotes(String s); static void unescapeQuotes(String s, Appendable a); static String escapeQuotes(String s); static void escapeQuotes(String s, Appendable a); static void appendArray(Appendable a, Object[] array, String sepString); static void appendArrayEnquoted(Appendable a, Object[] array, String sepString); static void appendIterable(Appendable a, Iterable<?> it, String sepString); static void appendIterableEnquoted(Appendable a, Iterable<?> it, String sepString); static void appendObject(Appendable a, @Nullable Object obj); }### Answer:
@Test public void testEscapeQuotes() { Assert.assertEquals(StringUtil.escapeQuotes(""), ""); Assert.assertEquals(StringUtil.escapeQuotes("abc"), "abc"); Assert.assertEquals(StringUtil.escapeQuotes("\"abc\""), "\\\"abc\\\""); Assert.assertEquals(StringUtil.escapeQuotes("ab\"c"), "ab\\\"c"); Assert.assertEquals(StringUtil.escapeQuotes("ab\\\"c"), "ab\\\\\\\"c"); Assert.assertEquals(StringUtil.escapeQuotes("ab\\\\\"c"), "ab\\\\\\\\\\\"c"); } |
### Question:
IOUtil { public static Writer asBufferedUTF8Writer(final File file) throws IOException { return Files.newBufferedWriter(file.toPath(), StandardCharsets.UTF_8); } private IOUtil(); static InputStream asUncompressedInputStream(InputStream is); static InputStream asBufferedInputStream(InputStream is); static InputStream asBufferedInputStream(File file); static OutputStream asBufferedOutputStream(OutputStream os); static OutputStream asBufferedOutputStream(File file); static Reader asBufferedUTF8Reader(final File file); static Reader asBufferedUTF8Reader(final InputStream is); static Reader asUTF8Reader(final InputStream is); static Writer asBufferedUTF8Writer(final File file); static Writer asBufferedUTF8Writer(final OutputStream os); static Writer asUTF8Writer(final OutputStream os); static InputStream asUncompressedBufferedNonClosingInputStream(InputStream is); static Reader asUncompressedBufferedNonClosingUTF8Reader(final InputStream is); static OutputStream asBufferedNonClosingOutputStream(OutputStream os); static Writer asBufferedNonClosingUTF8Writer(final OutputStream os); }### Answer:
@Test public void uncompressedInputStreamTest() throws IOException { final String msg = "Hello World"; try (ByteArrayOutputStream plain = new ByteArrayOutputStream(); ByteArrayOutputStream compressed = new ByteArrayOutputStream()) { try (Writer plainWriter = IOUtil.asBufferedUTF8Writer(plain); Writer compressedWriter = IOUtil.asBufferedUTF8Writer(new GZIPOutputStream(compressed))) { plainWriter.append(msg); compressedWriter.append(msg); } try (BufferedReader plainReader = buildReader(plain.toByteArray()); BufferedReader compressedReader = buildReader(compressed.toByteArray())) { Assert.assertEquals(plainReader.readLine(), msg); Assert.assertEquals(compressedReader.readLine(), msg); } } } |
### Question:
RandomUtil { public <T> @Nullable T choose(T[] array) { return choose(array, random); } RandomUtil(); RandomUtil(Random random); T choose(T[] array); static T choose(T[] array, Random rand); T choose(List<? extends T> list); static T choose(List<? extends T> list, Random rand); Random getRandom(); int[] distinctIntegers(int num, int min, int max); static int[] distinctIntegers(int num, int min, int max, Random rand); int[] distinctIntegers(int num, int max); static int[] distinctIntegers(int num, int max, Random rand); List<T> sample(List<? extends T> list, int num); static List<T> sample(List<? extends T> list, int num, Random rand); List<T> sampleUnique(List<? extends T> list, int num); static List<T> sampleUnique(List<? extends T> list, int num, Random rand); }### Answer:
@Test public void testChooseArray() { Assert.assertNull(util.choose(new Object[0])); Assert.assertEquals(util.choose(new Object[] {1}), 1); final Integer chosenElement = util.choose(array); Assert.assertNotNull(chosenElement); Assert.assertTrue(0 <= chosenElement && chosenElement < HIGH); }
@Test public void testChooseList() { Assert.assertNull(util.choose(Collections.emptyList())); Assert.assertEquals(util.choose(Collections.singletonList(1)), (Integer) 1); final Integer chosenElement = util.choose(list); Assert.assertNotNull(chosenElement); Assert.assertTrue(0 <= chosenElement && chosenElement < HIGH); } |
### Question:
RandomUtil { public <T> List<T> sampleUnique(List<? extends T> list, int num) { return sampleUnique(list, num, random); } RandomUtil(); RandomUtil(Random random); T choose(T[] array); static T choose(T[] array, Random rand); T choose(List<? extends T> list); static T choose(List<? extends T> list, Random rand); Random getRandom(); int[] distinctIntegers(int num, int min, int max); static int[] distinctIntegers(int num, int min, int max, Random rand); int[] distinctIntegers(int num, int max); static int[] distinctIntegers(int num, int max, Random rand); List<T> sample(List<? extends T> list, int num); static List<T> sample(List<? extends T> list, int num, Random rand); List<T> sampleUnique(List<? extends T> list, int num); static List<T> sampleUnique(List<? extends T> list, int num, Random rand); }### Answer:
@Test public void testSampleUnique() { Assert.assertEquals(util.sampleUnique(Collections.emptyList(), HIGH), Collections.emptyList()); List<Integer> result = util.sampleUnique(list, HIGH); Assert.assertEquals(result.size(), HIGH); result.sort(Integer::compareTo); Assert.assertEquals(result, list); result = util.sampleUnique(list, HIGH - 1); Assert.assertEquals(result.size(), HIGH - 1); Assert.assertEquals(new HashSet<>(result).size(), HIGH - 1); Assert.assertTrue(list.containsAll(result)); } |
### Question:
RandomUtil { public <T> List<T> sample(List<? extends T> list, int num) { return sample(list, num, random); } RandomUtil(); RandomUtil(Random random); T choose(T[] array); static T choose(T[] array, Random rand); T choose(List<? extends T> list); static T choose(List<? extends T> list, Random rand); Random getRandom(); int[] distinctIntegers(int num, int min, int max); static int[] distinctIntegers(int num, int min, int max, Random rand); int[] distinctIntegers(int num, int max); static int[] distinctIntegers(int num, int max, Random rand); List<T> sample(List<? extends T> list, int num); static List<T> sample(List<? extends T> list, int num, Random rand); List<T> sampleUnique(List<? extends T> list, int num); static List<T> sampleUnique(List<? extends T> list, int num, Random rand); }### Answer:
@Test public void testSampleList() { Assert.assertEquals(util.sample(Collections.emptyList(), HIGH), Collections.emptyList()); List<Integer> result = util.sample(list, HIGH); Assert.assertEquals(result.size(), HIGH); Assert.assertTrue(list.containsAll(result)); result = util.sample(list, HIGH * 2); Assert.assertEquals(result.size(), HIGH * 2); Assert.assertTrue(list.containsAll(result)); } |
### Question:
ReflectUtil { public static <T> @Nullable Constructor<T> findConstructor(Class<T> clazz, Class<?>... params) { try { return clazz.getConstructor(params); } catch (NoSuchMethodException e) { @SuppressWarnings("unchecked") Constructor<T>[] ctors = (Constructor<T>[]) clazz.getConstructors(); for (Constructor<T> candidate : ctors) { if (w2pEquals(candidate.getParameterTypes(), params)) { return candidate; } } return null; } } private ReflectUtil(); static Constructor<T> findConstructor(Class<T> clazz, Class<?>... params); static @Nullable Method findMethod(Class<?> clazz, String name, Class<?>... params); static @Nullable Method findMatchingMethod(Class<?> clazz, String name, @Nullable Object... args); static @Nullable Method findMethodRT(Class<?> clazz,
String name,
@Nullable Class<?> returnType,
Class<?>... params); }### Answer:
@Test public void testConstructors() { @SuppressWarnings("unchecked") final Constructor<TestClass> actualConstructor = (Constructor<TestClass>) TestClass.class.getConstructors()[0]; final Constructor<TestClass> constructor1 = ReflectUtil.findConstructor(TestClass.class, SIGNATURE_1); final Constructor<TestClass> constructor2 = ReflectUtil.findConstructor(TestClass.class, SIGNATURE_2); final Constructor<TestClass> constructor3 = ReflectUtil.findConstructor(TestClass.class, SIGNATURE_3); final Constructor<TestClass> constructor4 = ReflectUtil.findConstructor(TestClass.class, SIGNATURE_4); Assert.assertEquals(constructor1, actualConstructor); Assert.assertEquals(constructor2, actualConstructor); Assert.assertEquals(constructor3, actualConstructor); Assert.assertNull(constructor4); } |
### Question:
ReflectUtil { public static @Nullable Method findMethod(Class<?> clazz, String name, Class<?>... params) { try { return clazz.getMethod(name, params); } catch (NoSuchMethodException e) { Method[] methods = clazz.getMethods(); for (Method candidate : methods) { if (candidate.getName().equals(name) && w2pEquals(candidate.getParameterTypes(), params)) { return candidate; } } return null; } } private ReflectUtil(); static Constructor<T> findConstructor(Class<T> clazz, Class<?>... params); static @Nullable Method findMethod(Class<?> clazz, String name, Class<?>... params); static @Nullable Method findMatchingMethod(Class<?> clazz, String name, @Nullable Object... args); static @Nullable Method findMethodRT(Class<?> clazz,
String name,
@Nullable Class<?> returnType,
Class<?>... params); }### Answer:
@Test public void testMethod() { final Method method1 = ReflectUtil.findMethod(TestClass.class, methodName, SIGNATURE_1); final Method method2 = ReflectUtil.findMethod(TestClass.class, methodName, SIGNATURE_2); final Method method3 = ReflectUtil.findMethod(TestClass.class, methodName, SIGNATURE_3); final Method method4 = ReflectUtil.findMethod(TestClass.class, methodName, SIGNATURE_4); final Method method5 = ReflectUtil.findMethod(TestClass.class, "randomName", SIGNATURE_1); Assert.assertEquals(method1, methodToFind); Assert.assertEquals(method2, methodToFind); Assert.assertEquals(method3, methodToFind); Assert.assertNull(method4); Assert.assertNull(method5); } |
### Question:
ReflectUtil { public static @Nullable Method findMatchingMethod(Class<?> clazz, String name, @Nullable Object... args) { for (Method m : clazz.getMethods()) { if (!m.getName().equals(name)) { continue; } if (isMatch(m.getParameterTypes(), args)) { return m; } } return null; } private ReflectUtil(); static Constructor<T> findConstructor(Class<T> clazz, Class<?>... params); static @Nullable Method findMethod(Class<?> clazz, String name, Class<?>... params); static @Nullable Method findMatchingMethod(Class<?> clazz, String name, @Nullable Object... args); static @Nullable Method findMethodRT(Class<?> clazz,
String name,
@Nullable Class<?> returnType,
Class<?>... params); }### Answer:
@Test public void testMethodByArgs() { final Method method1 = ReflectUtil.findMatchingMethod(TestClass.class, methodName, 1, Boolean.TRUE, 'c', (byte) 3); final Method method2 = ReflectUtil.findMatchingMethod(TestClass.class, methodName, 1, null, 'c', (byte) 3); final Method method3 = ReflectUtil.findMatchingMethod(TestClass.class, methodName, 1, true, null, null); final Method method4 = ReflectUtil.findMatchingMethod(TestClass.class, methodName, 4L, false); final Method method5 = ReflectUtil.findMatchingMethod(TestClass.class, "randomName", 1, true, 'c', (byte) 3); Assert.assertEquals(method1, methodToFind); Assert.assertEquals(method2, methodToFind); Assert.assertNull(method3); Assert.assertNull(method4); Assert.assertNull(method5); } |
### Question:
BackedGeneralPriorityQueue extends AbstractSmartCollection<E> implements SmartGeneralPriorityQueue<E, K> { @Override public E extractMin() { Entry<E, K> min = backingQueue.extractMin(); return min.element; } BackedGeneralPriorityQueue(); BackedGeneralPriorityQueue(int initialCapacity); BackedGeneralPriorityQueue(List<? extends E> init, List<K> keys); BackedGeneralPriorityQueue(Supplier<? extends SmartDynamicPriorityQueue<Entry<E, K>>> supplier); BackedGeneralPriorityQueue(SmartDynamicPriorityQueue<Entry<E, K>> backingQueue); @Override E choose(); @Override ElementReference chooseRef(); @Override @Nullable ElementReference find(@Nullable Object element); @Override void quickClear(); @Override void deepClear(); @SuppressWarnings("nullness") // function is only called on elements of the iterator for which we know non-nullness @Override Iterator<E> iterator(); @Override E get(ElementReference ref); @Override ElementReference referencedAdd(E elem); @Override ElementReference add(E elem, @Nullable K key); @Override void setDefaultKey(K defaultKey); @Override void changeKey(ElementReference ref, K newKey); @Override void remove(ElementReference ref); @Override Iterator<ElementReference> referenceIterator(); @Override void replace(ElementReference ref, E newElement); @Override int size(); @Override boolean isEmpty(); @Override void clear(); @Override E peekMin(); @Override E extractMin(); }### Answer:
@Test public void testExtractMin() { for (int i = 0; i < 5; i++) { Assert.assertEquals(this.queue.extractMin(), Character.valueOf((char) ('j' - i))); } } |
### Question:
UnorderedCollection extends AbstractSmartCollection<E> implements CapacityManagement { @Override public <T extends E> void addAll(T[] array) { ensureCapacity(size + array.length); for (T t : array) { storage.array[size] = new Reference<>(t, size); size++; } } UnorderedCollection(); UnorderedCollection(int initialCapacity); @SuppressWarnings("initialization") // addAll only access initialized data structures UnorderedCollection(Collection<? extends E> coll); @Override boolean ensureCapacity(int minCapacity); @Override boolean ensureAdditionalCapacity(int additionalSpace); @Override void hintNextCapacity(int nextCapacityHint); @Override E get(ElementReference ref); @Override ElementReference referencedAdd(E elem); @Override void remove(ElementReference ref); @Override Iterator<ElementReference> referenceIterator(); @Override void replace(ElementReference ref, E newElement); @Override E choose(); @Override ElementReference chooseRef(); @Override Iterable<ElementReference> references(); @Override void addAll(T[] array); @Override boolean addAll(Collection<? extends E> coll); @Override void quickClear(); @SuppressWarnings("nullness") // setting 'null' is fine, when (according to JavaDoc) calling quickClear() first @Override void deepClear(); @Override Iterator<E> iterator(); @Override int size(); @Override boolean isEmpty(); @SuppressWarnings("nullness") // setting 'null' is fine, because we also decrease the size @Override void clear(); void swap(UnorderedCollection<E> other); }### Answer:
@Test public void testAddArray() { this.collection.addAll(new Integer[] {1, 1, 1}); }
@Test public void testAddCollection() { this.collection.addAll(Arrays.asList(2, 2, 2)); }
@Test public void testAddIterable() { this.collection.addAll((Iterable<Integer>) Arrays.asList(3, 3, 3)); } |
### Question:
UnorderedCollection extends AbstractSmartCollection<E> implements CapacityManagement { @Override public void remove(ElementReference ref) { remove(extractValidIndex(ref)); } UnorderedCollection(); UnorderedCollection(int initialCapacity); @SuppressWarnings("initialization") // addAll only access initialized data structures UnorderedCollection(Collection<? extends E> coll); @Override boolean ensureCapacity(int minCapacity); @Override boolean ensureAdditionalCapacity(int additionalSpace); @Override void hintNextCapacity(int nextCapacityHint); @Override E get(ElementReference ref); @Override ElementReference referencedAdd(E elem); @Override void remove(ElementReference ref); @Override Iterator<ElementReference> referenceIterator(); @Override void replace(ElementReference ref, E newElement); @Override E choose(); @Override ElementReference chooseRef(); @Override Iterable<ElementReference> references(); @Override void addAll(T[] array); @Override boolean addAll(Collection<? extends E> coll); @Override void quickClear(); @SuppressWarnings("nullness") // setting 'null' is fine, when (according to JavaDoc) calling quickClear() first @Override void deepClear(); @Override Iterator<E> iterator(); @Override int size(); @Override boolean isEmpty(); @SuppressWarnings("nullness") // setting 'null' is fine, because we also decrease the size @Override void clear(); void swap(UnorderedCollection<E> other); }### Answer:
@Test(dependsOnMethods = {"testAddArray", "testAddCollection", "testAddIterable"}) public void testRemove() { Assert.assertTrue(this.collection.remove(0)); Assert.assertTrue(this.collection.remove(1)); Assert.assertTrue(this.collection.remove(2)); Assert.assertTrue(this.collection.remove(3)); } |
### Question:
DOTFrame extends JFrame { public void addGraph(String name, Reader dotText) throws IOException { dotPanel.addGraph(name, dotText); } DOTFrame(); DOTFrame(String title); void addGraph(String name, Reader dotText); void addGraph(String name, String dotText); }### Answer:
@Test(timeOut = 30000) public void testFrame() throws InvocationTargetException, InterruptedException { if (JVMUtil.getCanonicalSpecVersion() > 8) { throw new SkipException("The headless AWT environment currently only works with Java 8 and below"); } final Random random = new Random(42); SwingUtilities.invokeAndWait(() -> { final DOTFrame frame = new DOTFrame(); frame.addGraph("1", TestUtil.generateRandomAutomatonDot(random)); frame.addGraph("2", TestUtil.generateRandomAutomatonDot(random)); try { frame.addGraph("3", new StringReader(TestUtil.generateRandomAutomatonDot(random))); } catch (IOException e) { throw new RuntimeException(e); } frame.setVisible(true); }); } |
### Question:
BricsDFA extends AbstractBricsAutomaton implements DFA<State, Character> { @Override public State getInitialState() { return automaton.getInitialState(); } BricsDFA(Automaton automaton); BricsDFA(Automaton automaton, boolean totalize); @Override State getInitialState(); @Override State getSuccessor(State state, Character input); @Override State getTransition(State state, Character input); }### Answer:
@Test public void testStructuralEquality() { AbstractBricsAutomaton.GraphView graphView = dfa.graphView(); Assert.assertEquals(dfa.getInitialState(), bricsAutomaton.getInitialState()); Set<State> states1 = new HashSet<>(bricsAutomaton.getStates()); Set<State> states2 = new HashSet<>(dfa.getStates()); Assert.assertEquals(states1, states2); for (State s : dfa) { Assert.assertEquals(dfa.isAccepting(s), s.isAccept()); Set<Transition> trans1 = new HashSet<>(graphView.getOutgoingEdges(s)); Set<Transition> trans2 = new HashSet<>(s.getTransitions()); Assert.assertEquals(trans1, trans2); } } |
### Question:
AbstractLTSminLTL extends AbstractLTSmin<I, A, L> implements ModelCheckerLasso<I, A, String, L> { @Override public void setMultiplier(double multiplier) { unfolder.setMultiplier(multiplier); } protected AbstractLTSminLTL(boolean keepFiles, Function<String, I> string2Input,
int minimumUnfolds, double multiplier); @Override double getMultiplier(); @Override void setMultiplier(double multiplier); @Override int getMinimumUnfolds(); @Override void setMinimumUnfolds(int minimumUnfolds); static final LTSminVersion REQUIRED_VERSION; }### Answer:
@Test public void testComputeUnfolds() { Assert.assertEquals(getModelChecker().computeUnfolds(1), 3); getModelChecker().setMultiplier(2.0); Assert.assertEquals(getModelChecker().computeUnfolds(2), 4); }
@Test public void testSetMultiplier() { getModelChecker().setMultiplier(1337.0); Assert.assertEquals(getModelChecker().getMultiplier(), 1337.0, 0.0); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testSetMultiplierExcept() { getModelChecker().setMultiplier(-1.0); } |
### Question:
AbstractLTSminLTL extends AbstractLTSmin<I, A, L> implements ModelCheckerLasso<I, A, String, L> { @Override public void setMinimumUnfolds(int minimumUnfolds) { unfolder.setMinimumUnfolds(minimumUnfolds); } protected AbstractLTSminLTL(boolean keepFiles, Function<String, I> string2Input,
int minimumUnfolds, double multiplier); @Override double getMultiplier(); @Override void setMultiplier(double multiplier); @Override int getMinimumUnfolds(); @Override void setMinimumUnfolds(int minimumUnfolds); static final LTSminVersion REQUIRED_VERSION; }### Answer:
@Test public void testSetMinimumUnfolds() { getModelChecker().setMinimumUnfolds(1337); Assert.assertEquals(getModelChecker().getMinimumUnfolds(), 1337); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testSetMinimumUnfoldsExcept() { getModelChecker().setMinimumUnfolds(0); } |
### Question:
LTSminLTLParser { public static boolean isValidLetterFormula(String formula) { try { requireValidLetterFormula(formula); } catch (IllegalArgumentException iae) { LOGGER.debug("Couldn't parse formula", iae); return false; } return true; } private LTSminLTLParser(); static String requireValidLetterFormula(String formula); static boolean isValidLetterFormula(String formula); static String requireValidIOFormula(String formula); static boolean isValidIOFormula(String formula); }### Answer:
@Test(dataProvider = "letter") public void testLetterFormulae(final String formula, boolean expectedValidity) { Assert.assertEquals(LTSminLTLParser.isValidLetterFormula(formula), expectedValidity); } |
### Question:
LTSminLTLParser { public static boolean isValidIOFormula(String formula) { try { requireValidIOFormula(formula); } catch (IllegalArgumentException iae) { LOGGER.debug("Couldn't parse formula", iae); return false; } return true; } private LTSminLTLParser(); static String requireValidLetterFormula(String formula); static boolean isValidLetterFormula(String formula); static String requireValidIOFormula(String formula); static boolean isValidIOFormula(String formula); }### Answer:
@Test(dataProvider = "io") public void testIOFormulae(final String formula, boolean expectedValidity) { Assert.assertEquals(LTSminLTLParser.isValidIOFormula(formula), expectedValidity); } |
### Question:
LTSminVersion { public static LTSminVersion parse(String version) { final Matcher matcher = VERSION_PATTERN.matcher(version); if (matcher.find()) { final String major = matcher.group(1); final String minor = matcher.group(2); final String patch = matcher.group(3); if (major == null || minor == null || patch == null) { return fallback(version); } final LTSminVersion result = of(Integer.parseInt(major), Integer.parseInt(minor), Integer.parseInt(patch)); LOGGER.debug("Found version '{}'", version); LOGGER.debug("Parsed as '{}'", result); return result; } else { return fallback(version); } } private LTSminVersion(int major, int minor, int patch); static LTSminVersion of(int major, int minor, int patch); static LTSminVersion parse(String version); boolean supports(LTSminVersion required); @Override String toString(); @Override boolean equals(@Nullable Object o); @Override int hashCode(); }### Answer:
@Test public void testParse() { final String v300 = "v3.0.0"; final String v300beta = "v3.0.0-beta1"; final String v300broken = "v3.0broken.0"; final String noV = "3.0.0"; final String prefixV = "prefixv3.0.0"; Assert.assertEquals(LTSminVersion.parse(v300), LTSminVersion.of(3, 0, 0)); Assert.assertEquals(LTSminVersion.parse(v300beta), LTSminVersion.of(3, 0, 0)); Assert.assertEquals(LTSminVersion.parse(v300broken), LTSminVersion.of(0, 0, 0)); Assert.assertEquals(LTSminVersion.parse(noV), LTSminVersion.of(0, 0, 0)); Assert.assertEquals(LTSminVersion.parse(prefixV), LTSminVersion.of(0, 0, 0)); } |
### Question:
LTSminVersion { public boolean supports(LTSminVersion required) { if (major > required.major) { return true; } else if (major == required.major) { if (minor > required.minor) { return true; } else if (minor == required.minor) { return patch >= required.patch; } } return false; } private LTSminVersion(int major, int minor, int patch); static LTSminVersion of(int major, int minor, int patch); static LTSminVersion parse(String version); boolean supports(LTSminVersion required); @Override String toString(); @Override boolean equals(@Nullable Object o); @Override int hashCode(); }### Answer:
@Test public void testSupports() { Assert.assertTrue(LTSminVersion.of(3, 0, 0).supports(LTSminVersion.of(3, 0, 0))); Assert.assertTrue(LTSminVersion.of(4, 0, 0).supports(LTSminVersion.of(3, 0, 0))); Assert.assertFalse(LTSminVersion.of(2, 0, 0).supports(LTSminVersion.of(3, 0, 0))); Assert.assertTrue(LTSminVersion.of(3, 1, 0).supports(LTSminVersion.of(3, 1, 0))); Assert.assertTrue(LTSminVersion.of(3, 2, 0).supports(LTSminVersion.of(3, 1, 0))); Assert.assertFalse(LTSminVersion.of(3, 1, 0).supports(LTSminVersion.of(3, 2, 0))); Assert.assertTrue(LTSminVersion.of(3, 1, 0).supports(LTSminVersion.of(3, 1, 0))); Assert.assertTrue(LTSminVersion.of(3, 1, 1).supports(LTSminVersion.of(3, 1, 0))); Assert.assertFalse(LTSminVersion.of(3, 1, 0).supports(LTSminVersion.of(3, 1, 1))); } |
### Question:
SharedWord extends Word<I> { @Override public int length() { return this.length; } SharedWord(@Nullable Object[] storage); @SuppressWarnings("unchecked") SharedWord(@Nullable Object[] storage, int offset, int length); @SuppressWarnings({"unchecked", "nullness"}) SharedWord(List<? extends I> other); @Override int length(); @Override Iterator<I> iterator(); @Override Spliterator<I> spliterator(); @Override Word<I> subWordInternal(int fromIndex, int toIndex); @Override void writeToArray(int offset, @Nullable Object[] array, int tgtOfs, int num); @Override I getSymbol(int index); @Override I lastSymbol(); @Override I firstSymbol(); @Override Word<I> flatten(); @Override Word<I> trimmed(); }### Answer:
@Test public void testLength() { Assert.assertEquals(LENGTH, testWord.length()); } |
### Question:
EmptyWord extends Word<Object> { @Override public int length() { return 0; } @Override int length(); @Override Spliterator<Object> spliterator(); @Override Word<Object> subWordInternal(int fromIndex, int toIndex); @Override void writeToArray(int offset, @Nullable Object[] array, int tgtOffset, int length); @Override Object getSymbol(int index); @Override List<Object> asList(); @Override Word<Object> canonicalNext(Alphabet<Object> sigma); @Override Object lastSymbol(); @Override Word<Object> append(Object symbol); @Override Word<Object> prepend(Object symbol); @Override boolean isPrefixOf(Word<?> other); @Override Word<Object> longestCommonPrefix(Word<?> other); @Override boolean isSuffixOf(Word<?> other); @Override Word<Object> longestCommonSuffix(Word<?> other); @Override Word<Object> flatten(); @Override Word<Object> trimmed(); @Override @SuppressWarnings("unchecked") Word<T> transform(Function<? super Object, ? extends T> transformer); static final EmptyWord INSTANCE; }### Answer:
@Test public void testLength() { Assert.assertEquals(0, testWord.length()); } |
### Question:
WordBuilder extends AbstractList<I> { public WordBuilder<I> reverse() { ensureUnlocked(); int lowIdx = 0, highIdx = length - 1; while (lowIdx < highIdx) { Object tmp = array[lowIdx]; array[lowIdx++] = array[highIdx]; array[highIdx--] = tmp; } return this; } WordBuilder(); WordBuilder(int initialCapacity); WordBuilder(I initSym, int count); WordBuilder(int capacity, I initSym, int count); WordBuilder(Word<I> init); WordBuilder(int capacity, Word<I> init); WordBuilder<I> append(I symbol); WordBuilder<I> append(List<? extends I> symList); WordBuilder<I> append(Word<? extends I> word); @SafeVarargs final WordBuilder<I> append(Word<? extends I>... words); @SafeVarargs final WordBuilder<I> append(I... symbols); void ensureAdditionalCapacity(int add); void ensureCapacity(int cap); WordBuilder<I> repeatAppend(int num, Word<I> word); WordBuilder<I> repeatAppend(int num, I symbol); WordBuilder<I> truncate(int truncLen); Word<I> toWord(int fromIndex, int toIndex); Word<I> toWord(); @Override boolean add(I e); @Override I get(int index); @SuppressWarnings("unchecked") I getSymbol(int index); @Override I set(int index, I element); WordBuilder<I> setSymbol(int index, I symbol); @Override void clear(); @Override int size(); WordBuilder<I> reverse(); }### Answer:
@Test public void reverseTest() { WordBuilder<Character> wb = new WordBuilder<>(); final Word<Character> abc = Word.fromCharSequence("abc"); final Word<Character> cba = Word.fromCharSequence("cba"); wb.append(abc); wb = wb.reverse(); Assert.assertEquals(cba, wb.toWord()); } |
### Question:
WordBuilder extends AbstractList<I> { public Word<I> toWord(int fromIndex, int toIndex) { if (fromIndex < 0 || toIndex > length) { throw new IndexOutOfBoundsException(); } int len = toIndex - fromIndex; lock = true; return new SharedWord<>(array, fromIndex, len); } WordBuilder(); WordBuilder(int initialCapacity); WordBuilder(I initSym, int count); WordBuilder(int capacity, I initSym, int count); WordBuilder(Word<I> init); WordBuilder(int capacity, Word<I> init); WordBuilder<I> append(I symbol); WordBuilder<I> append(List<? extends I> symList); WordBuilder<I> append(Word<? extends I> word); @SafeVarargs final WordBuilder<I> append(Word<? extends I>... words); @SafeVarargs final WordBuilder<I> append(I... symbols); void ensureAdditionalCapacity(int add); void ensureCapacity(int cap); WordBuilder<I> repeatAppend(int num, Word<I> word); WordBuilder<I> repeatAppend(int num, I symbol); WordBuilder<I> truncate(int truncLen); Word<I> toWord(int fromIndex, int toIndex); Word<I> toWord(); @Override boolean add(I e); @Override I get(int index); @SuppressWarnings("unchecked") I getSymbol(int index); @Override I set(int index, I element); WordBuilder<I> setSymbol(int index, I symbol); @Override void clear(); @Override int size(); WordBuilder<I> reverse(); }### Answer:
@Test public void toWordTest() { WordBuilder<Character> wb = new WordBuilder<>(); final Word<Character> abc = Word.fromCharSequence("abc"); wb.clear(); wb.repeatAppend(3, abc); Assert.assertEquals(abc, wb.toWord(3, 6)); Assert.assertThrows(IndexOutOfBoundsException.class, () -> wb.toWord(-1, wb.size())); Assert.assertThrows(IndexOutOfBoundsException.class, () -> wb.toWord(0, wb.size() + 1)); } |
### Question:
AbstractLasso implements Lasso<I, D> { @Override public Word<I> getWord() { return word; } <S> AbstractLasso(DetOutputAutomaton<S, I, ?, D> automaton, Collection<? extends I> inputs, int unfoldTimes); @Override DetOutputAutomaton<?, I, ?, D> getAutomaton(); @Override int getUnfolds(); @Override Word<I> getWord(); @Override Word<I> getLoop(); @Override Word<I> getPrefix(); @Override D getOutput(); @Override SortedSet<Integer> getLoopBeginIndices(); @Override Integer getInitialState(); @Override @Nullable Integer getSuccessor(Integer state, I input); @Override Collection<Integer> getStates(); @Override Alphabet<I> getInputAlphabet(); @Override @Nullable Integer getTransition(Integer state, I input); static final String NO_LASSO; }### Answer:
@Test public void testGetWord() { Assert.assertEquals(lasso1.getWord(), Word.fromSymbols("a")); Assert.assertEquals(lasso2.getWord(), Word.fromSymbols("a", "a")); Assert.assertEquals(lasso3.getWord(), Word.fromSymbols("a", "a", "a")); } |
### Question:
AbstractLasso implements Lasso<I, D> { @Override public Word<I> getLoop() { return loop; } <S> AbstractLasso(DetOutputAutomaton<S, I, ?, D> automaton, Collection<? extends I> inputs, int unfoldTimes); @Override DetOutputAutomaton<?, I, ?, D> getAutomaton(); @Override int getUnfolds(); @Override Word<I> getWord(); @Override Word<I> getLoop(); @Override Word<I> getPrefix(); @Override D getOutput(); @Override SortedSet<Integer> getLoopBeginIndices(); @Override Integer getInitialState(); @Override @Nullable Integer getSuccessor(Integer state, I input); @Override Collection<Integer> getStates(); @Override Alphabet<I> getInputAlphabet(); @Override @Nullable Integer getTransition(Integer state, I input); static final String NO_LASSO; }### Answer:
@Test public void testGetLoop() { Assert.assertEquals(lasso1.getLoop(), Word.fromSymbols("a")); Assert.assertEquals(lasso2.getLoop(), Word.fromSymbols("a")); Assert.assertEquals(lasso3.getLoop(), Word.fromSymbols("a", "a")); } |
### Question:
AbstractLasso implements Lasso<I, D> { @Override public Word<I> getPrefix() { return prefix; } <S> AbstractLasso(DetOutputAutomaton<S, I, ?, D> automaton, Collection<? extends I> inputs, int unfoldTimes); @Override DetOutputAutomaton<?, I, ?, D> getAutomaton(); @Override int getUnfolds(); @Override Word<I> getWord(); @Override Word<I> getLoop(); @Override Word<I> getPrefix(); @Override D getOutput(); @Override SortedSet<Integer> getLoopBeginIndices(); @Override Integer getInitialState(); @Override @Nullable Integer getSuccessor(Integer state, I input); @Override Collection<Integer> getStates(); @Override Alphabet<I> getInputAlphabet(); @Override @Nullable Integer getTransition(Integer state, I input); static final String NO_LASSO; }### Answer:
@Test public void testGetPrefix() { Assert.assertEquals(lasso1.getPrefix(), Word.epsilon()); Assert.assertEquals(lasso2.getPrefix(), Word.fromSymbols("a")); Assert.assertEquals(lasso3.getPrefix(), Word.fromSymbols("a")); } |
### Question:
AbstractLasso implements Lasso<I, D> { @Override public SortedSet<Integer> getLoopBeginIndices() { return loopBeginIndices; } <S> AbstractLasso(DetOutputAutomaton<S, I, ?, D> automaton, Collection<? extends I> inputs, int unfoldTimes); @Override DetOutputAutomaton<?, I, ?, D> getAutomaton(); @Override int getUnfolds(); @Override Word<I> getWord(); @Override Word<I> getLoop(); @Override Word<I> getPrefix(); @Override D getOutput(); @Override SortedSet<Integer> getLoopBeginIndices(); @Override Integer getInitialState(); @Override @Nullable Integer getSuccessor(Integer state, I input); @Override Collection<Integer> getStates(); @Override Alphabet<I> getInputAlphabet(); @Override @Nullable Integer getTransition(Integer state, I input); static final String NO_LASSO; }### Answer:
@Test public void testGetLoopBeginIndices() { final SortedSet<Integer> indices = new TreeSet<>(); indices.add(0); indices.add(1); Assert.assertEquals(lasso1.getLoopBeginIndices(), indices); indices.clear(); indices.add(1); indices.add(2); Assert.assertEquals(lasso2.getLoopBeginIndices(), indices); indices.clear(); indices.add(1); indices.add(3); Assert.assertEquals(lasso3.getLoopBeginIndices(), indices); } |
### Question:
GsonTypeChecker extends TypeChecker { @Override public boolean isValidType(Class<?> clazz, boolean throwException) { return isValidType(clazz, throwException, null); } @Override boolean isValidType(Class<?> clazz, boolean throwException); @Override String getTypeName(Class<?> clazz); }### Answer:
@Test(dataProvider = "validTypes") public void testValidType(Class<?> clazz) { assertTrue(typeChecker.isValidType(clazz)); }
@Test(dataProvider = "validTypes") public void testValidTypeWithException(Class<?> clazz) { assertTrue(typeChecker.isValidType(clazz, true)); }
@Test(dataProvider = "invalidTypes") public void testInvalidType(Class<?> clazz) { assertFalse(typeChecker.isValidType(clazz)); }
@Test(dataProvider = "invalidTypes", expectedExceptions = {IllegalArgumentException.class}) public void testInvalidTypeWithException(Class<?> clazz) { assertFalse(typeChecker.isValidType(clazz, true)); } |
### Question:
GsonTypeChecker extends TypeChecker { @Override public String getTypeName(Class<?> clazz) { if (clazz == void.class || clazz == Void.class) { return void.class.getName(); } if (clazz == boolean.class || Boolean.class == clazz) { return boolean.class.getName(); } if (clazz == double.class || clazz == float.class || Double.class == clazz || Float.class == clazz) { return double.class.getName(); } if (clazz == byte.class || clazz == char.class || clazz == int.class || clazz == short.class || clazz == long.class || clazz == Character.class || Number.class.isAssignableFrom(clazz)) { return int.class.getName(); } if (clazz == String.class) { return "string"; } if (clazz.isArray()) { return "array"; } return "struct"; } @Override boolean isValidType(Class<?> clazz, boolean throwException); @Override String getTypeName(Class<?> clazz); }### Answer:
@Test(dataProvider = "typeNames") public void testGetTypeName(Class<?> clazz, String name) { assertEquals(typeChecker.getTypeName(clazz), name); } |
### Question:
CrashesViewModel { public ViewState getCrashNotFoundViewState() { return new ViewState.Builder().withVisible(crashViewModels.isEmpty()).build(); } CrashesViewModel(List<CrashViewModel> crashViewModels); List<CrashViewModel> getCrashViewModels(); ViewState getCrashNotFoundViewState(); }### Answer:
@Test public void shouldReturnCrashNotFoundVisibilityAsVISBILEWhenThereAreNoCrashes() throws Exception { CrashesViewModel viewModel = new CrashesViewModel(new ArrayList<CrashViewModel>()); assertThat(viewModel.getCrashNotFoundViewState().getVisibility(), is(View.VISIBLE)); }
@Test public void shouldReturnCrashNotFoundVisibilityAsGONEWhenThereAreCrashes() throws Exception { CrashesViewModel viewModel = new CrashesViewModel(asList(mock(CrashViewModel.class))); assertThat(viewModel.getCrashNotFoundViewState().getVisibility(), is(View.GONE)); } |
### Question:
ViewState { public int getVisibility() { return visibility; } private ViewState(int visibility); int getVisibility(); }### Answer:
@Test public void shouldReturnViewStateBasedOnVisibilityCriteria() throws Exception { assertThat(new ViewState.Builder().withVisible(true).build().getVisibility(), is(View.VISIBLE)); assertThat(new ViewState.Builder().withVisible(false).build().getVisibility(), is(View.GONE)); } |
### Question:
CrashViewModel { public String getPlace() { String[] placeTrail = crash.getPlace().split("\\."); return placeTrail[placeTrail.length - 1]; } CrashViewModel(); CrashViewModel(Crash crash); String getPlace(); String getExactLocationOfCrash(); String getReasonOfCrash(); String getStackTrace(); String getCrashInfo(); String getDeviceManufacturer(); String getDeviceName(); String getDeviceAndroidApiVersion(); String getDeviceBrand(); AppInfoViewModel getAppInfoViewModel(); int getIdentifier(); String getDate(); void populate(Crash crash); }### Answer:
@Test public void shouldReturnPlaceOfCrash() throws Exception { Crash crash = mock(Crash.class); when(crash.getPlace()).thenReturn("com.singhajit.sherlock.core.Crash:20"); when(crash.getAppInfo()).thenReturn(mock(AppInfo.class)); CrashViewModel viewModel = new CrashViewModel(crash); assertThat(viewModel.getPlace(), is("Crash:20")); } |
### Question:
CrashViewModel { public String getDate() { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("h:mm a EEE, MMM d, yyyy"); return simpleDateFormat.format(crash.getDate()); } CrashViewModel(); CrashViewModel(Crash crash); String getPlace(); String getExactLocationOfCrash(); String getReasonOfCrash(); String getStackTrace(); String getCrashInfo(); String getDeviceManufacturer(); String getDeviceName(); String getDeviceAndroidApiVersion(); String getDeviceBrand(); AppInfoViewModel getAppInfoViewModel(); int getIdentifier(); String getDate(); void populate(Crash crash); }### Answer:
@Test public void shouldReturnDateOfCrash() throws Exception { Crash crash = mock(Crash.class); Calendar calendar = Calendar.getInstance(); calendar.set(2017, 4, 15, 10, 50, 55); when(crash.getDate()).thenReturn(calendar.getTime()); when(crash.getAppInfo()).thenReturn(mock(AppInfo.class)); CrashViewModel viewModel = new CrashViewModel(crash); assertThat(viewModel.getDate(), is("10:50 AM Mon, May 15, 2017")); } |
### Question:
CrashViewModel { public int getIdentifier() { return crash.getId(); } CrashViewModel(); CrashViewModel(Crash crash); String getPlace(); String getExactLocationOfCrash(); String getReasonOfCrash(); String getStackTrace(); String getCrashInfo(); String getDeviceManufacturer(); String getDeviceName(); String getDeviceAndroidApiVersion(); String getDeviceBrand(); AppInfoViewModel getAppInfoViewModel(); int getIdentifier(); String getDate(); void populate(Crash crash); }### Answer:
@Test public void shouldReturnIdentifier() throws Exception { Crash crash = mock(Crash.class); when(crash.getId()).thenReturn(1); when(crash.getAppInfo()).thenReturn(mock(AppInfo.class)); CrashViewModel viewModel = new CrashViewModel(crash); assertThat(viewModel.getIdentifier(), is(1)); } |
### Question:
MavenCodeLocationPackager { String trimLogLevel(final String line) { final String editableLine = line; final int index = indexOfEndOfSegments(line, "[", "INFO", "]"); String trimmedLine = editableLine.substring(index); if (trimmedLine.startsWith(" ")) { trimmedLine = trimmedLine.substring(1); } return trimmedLine; } MavenCodeLocationPackager(final ExternalIdFactory externalIdFactory); List<MavenParseResult> extractCodeLocations(final String sourcePath, final String mavenOutputText, final String targetScope, final String excludedModules, final String includedModules); static final List<String> indentationStrings; static final List<String> KNOWN_SCOPES; static final String ORPHAN_LIST_PARENT_NODE_NAME; static final String ORPHAN_LIST_PARENT_NODE_GROUP; static final String ORPHAN_LIST_PARENT_NODE_VERSION; }### Answer:
@Test public void testTrimLogLevel() { final MavenCodeLocationPackager mavenCodeLocationPackager = new MavenCodeLocationPackager(null); String actualLine = ""; final String expectedValue = "thing"; actualLine = mavenCodeLocationPackager.trimLogLevel("weird garbage 3525356 [thingsINFO 346534623465]" + expectedValue); assertEquals(expectedValue, actualLine); actualLine = mavenCodeLocationPackager.trimLogLevel("[thingsINFO 346534623465]" + expectedValue); assertEquals(expectedValue, actualLine); actualLine = mavenCodeLocationPackager.trimLogLevel("[thingsINFO]" + expectedValue); assertEquals(expectedValue, actualLine); actualLine = mavenCodeLocationPackager.trimLogLevel(" [INFO] " + expectedValue); assertEquals(expectedValue, actualLine); } |
### Question:
MavenCodeLocationPackager { boolean isProjectSection(final String line) { return doesLineContainSegmentsInOrder(line, "---", "dependency", ":", "tree"); } MavenCodeLocationPackager(final ExternalIdFactory externalIdFactory); List<MavenParseResult> extractCodeLocations(final String sourcePath, final String mavenOutputText, final String targetScope, final String excludedModules, final String includedModules); static final List<String> indentationStrings; static final List<String> KNOWN_SCOPES; static final String ORPHAN_LIST_PARENT_NODE_NAME; static final String ORPHAN_LIST_PARENT_NODE_GROUP; static final String ORPHAN_LIST_PARENT_NODE_VERSION; }### Answer:
@Test public void testIsProjectSection() { final MavenCodeLocationPackager mavenCodeLocationPackager = new MavenCodeLocationPackager(null); assertFalse(mavenCodeLocationPackager.isProjectSection(" ")); assertFalse(mavenCodeLocationPackager.isProjectSection(" ")); assertFalse(mavenCodeLocationPackager.isProjectSection("---maven-dependency-plugin:")); assertFalse(mavenCodeLocationPackager.isProjectSection("---maven-dependency-plugin:other stuff")); assertFalse(mavenCodeLocationPackager.isProjectSection("maven-dependency-plugin:tree stuff")); assertTrue(mavenCodeLocationPackager.isProjectSection("---maven-dependency-plugin:tree stuff")); assertTrue(mavenCodeLocationPackager.isProjectSection("things --- stuff maven-dependency-plugin garbage:tree stuff")); assertTrue(mavenCodeLocationPackager.isProjectSection("things --- stuff maven-dependency-plugin:tree stuff")); assertTrue(mavenCodeLocationPackager.isProjectSection("---maven-dependency-plugin:tree")); assertTrue(mavenCodeLocationPackager.isProjectSection(" --- maven-dependency-plugin : tree")); } |
### Question:
MavenCodeLocationPackager { boolean isDependencyTreeUpdates(final String line) { if (line.contains("checking for updates")) { return true; } else { return false; } } MavenCodeLocationPackager(final ExternalIdFactory externalIdFactory); List<MavenParseResult> extractCodeLocations(final String sourcePath, final String mavenOutputText, final String targetScope, final String excludedModules, final String includedModules); static final List<String> indentationStrings; static final List<String> KNOWN_SCOPES; static final String ORPHAN_LIST_PARENT_NODE_NAME; static final String ORPHAN_LIST_PARENT_NODE_GROUP; static final String ORPHAN_LIST_PARENT_NODE_VERSION; }### Answer:
@Test public void testIsDependencyTreeUpdates() { final MavenCodeLocationPackager mavenCodeLocationPackager = new MavenCodeLocationPackager(null); assertTrue(mavenCodeLocationPackager.isDependencyTreeUpdates("artifact com.google.guava:guava:jar:15.0:compile checking for updates from")); assertTrue(mavenCodeLocationPackager.isDependencyTreeUpdates(" artifact com.google.guava:guava: checking for updates")); assertTrue(mavenCodeLocationPackager.isDependencyTreeUpdates(" checking for updates artifact com.google.guava:guava: ")); assertTrue(mavenCodeLocationPackager.isDependencyTreeUpdates("checking for updates")); assertFalse(mavenCodeLocationPackager.isDependencyTreeUpdates("com.google.guava:guava:jar:15.0:compile")); assertFalse(mavenCodeLocationPackager.isDependencyTreeUpdates("+- com.google.guava:guava:jar:15.0:compile")); assertFalse(mavenCodeLocationPackager.isDependencyTreeUpdates("| \\- com.google.guava:guava:jar:15.0:compile")); } |
### Question:
MavenCodeLocationPackager { boolean doesLineContainSegmentsInOrder(final String line, final String... segments) { Boolean lineContainsSegments = true; final int index = indexOfEndOfSegments(line, segments); if (index == -1) { lineContainsSegments = false; } return lineContainsSegments; } MavenCodeLocationPackager(final ExternalIdFactory externalIdFactory); List<MavenParseResult> extractCodeLocations(final String sourcePath, final String mavenOutputText, final String targetScope, final String excludedModules, final String includedModules); static final List<String> indentationStrings; static final List<String> KNOWN_SCOPES; static final String ORPHAN_LIST_PARENT_NODE_NAME; static final String ORPHAN_LIST_PARENT_NODE_GROUP; static final String ORPHAN_LIST_PARENT_NODE_VERSION; }### Answer:
@Test public void testDoesLineContainSegmentsInOrder() { final MavenCodeLocationPackager mavenCodeLocationPackager = new MavenCodeLocationPackager(null); assertFalse(mavenCodeLocationPackager.doesLineContainSegmentsInOrder("")); assertFalse(mavenCodeLocationPackager.doesLineContainSegmentsInOrder("stuff and things")); assertFalse(mavenCodeLocationPackager.doesLineContainSegmentsInOrder("stuff and things", "things", "and")); assertFalse(mavenCodeLocationPackager.doesLineContainSegmentsInOrder("stuff and things", "things", "and", "stuff")); assertTrue(mavenCodeLocationPackager.doesLineContainSegmentsInOrder("stuff and things", "stuff")); assertTrue(mavenCodeLocationPackager.doesLineContainSegmentsInOrder("stuff and things", "stuff", "and")); assertTrue(mavenCodeLocationPackager.doesLineContainSegmentsInOrder("stuff and things", "stuff", "and", "things")); assertTrue(mavenCodeLocationPackager.doesLineContainSegmentsInOrder("stuff and things", "and")); assertTrue(mavenCodeLocationPackager.doesLineContainSegmentsInOrder("stuff and things", "things")); } |
### Question:
GopkgLockParser { public DependencyGraph parseDepLock(final String depLockContents) { final MutableDependencyGraph graph = new MutableMapDependencyGraph(); final GopkgLock gopkgLock = new Toml().read(depLockContents).to(GopkgLock.class); for (final Project project : gopkgLock.getProjects()) { if (project != null) { final NameVersion projectNameVersion = createProjectNameVersion(project); project.getPackages().stream() .map(packageName -> createDependencyName(projectNameVersion.getName(), packageName)) .map(dependencyName -> createGoDependency(dependencyName, projectNameVersion.getVersion())) .forEach(graph::addChildToRoot); } } return graph; } GopkgLockParser(final ExternalIdFactory externalIdFactory); DependencyGraph parseDepLock(final String depLockContents); }### Answer:
@Test public void gopkgParserTest() throws IOException { final GopkgLockParser gopkgLockParser = new GopkgLockParser(new ExternalIdFactory()); final String gopkgLockContents = IOUtils.toString(getClass().getResourceAsStream("/go/Gopkg.lock"), StandardCharsets.UTF_8); final DependencyGraph dependencyGraph = gopkgLockParser.parseDepLock(gopkgLockContents); Assert.assertNotNull(dependencyGraph); DependencyGraphResourceTestUtil.assertGraph("/go/Go_GopkgExpected_graph.json", dependencyGraph); } |
### Question:
BazelVariableSubstitutor { public List<String> substitute(final List<String> origStrings) { final List<String> modifiedStrings = new ArrayList<>(origStrings.size()); for (String origString : origStrings) { modifiedStrings.add(substitute(origString)); } return modifiedStrings; } BazelVariableSubstitutor(final String bazelTarget); BazelVariableSubstitutor(final String bazelTarget, final String bazelTargetDependencyId); List<String> substitute(final List<String> origStrings); }### Answer:
@Test public void testTargetOnly() { BazelVariableSubstitutor substitutor = new BazelVariableSubstitutor(" final List<String> origArgs = new ArrayList<>(); origArgs.add("query"); origArgs.add("filter(\"@.*:jar\", deps(${detect.bazel.target}))"); final List<String> adjustedArgs = substitutor.substitute(origArgs); assertEquals(2, adjustedArgs.size()); assertEquals("query", adjustedArgs.get(0)); assertEquals("filter(\"@.*:jar\", deps( }
@Test public void testBoth() { BazelVariableSubstitutor substitutor = new BazelVariableSubstitutor(" final List<String> origArgs = new ArrayList<>(); origArgs.add("query"); origArgs.add("filter(\"@.*:jar\", deps(${detect.bazel.target}))"); origArgs.add("kind(maven_jar, ${detect.bazel.target.dependency})"); final List<String> adjustedArgs = substitutor.substitute(origArgs); assertEquals(3, adjustedArgs.size()); assertEquals("query", adjustedArgs.get(0)); assertEquals("filter(\"@.*:jar\", deps( assertEquals("kind(maven_jar, } |
### Question:
VndrParser { public VndrParser(final ExternalIdFactory externalIdFactory) { this.externalIdFactory = externalIdFactory; } VndrParser(final ExternalIdFactory externalIdFactory); DependencyGraph parseVendorConf(final List<String> vendorConfContents); public ExternalIdFactory externalIdFactory; }### Answer:
@Test public void vndrParserTest() throws IOException { final TestUtil testUtil = new TestUtil(); final VndrParser vndrParser = new VndrParser(new ExternalIdFactory()); final String text = testUtil.getResourceAsUTF8String("/go/vendor.conf"); final List<String> vendorConfContents = Arrays.asList(text.split("\r?\n")); final DependencyGraph dependencyGraph = vndrParser.parseVendorConf(vendorConfContents); Assert.assertNotNull(dependencyGraph); DependencyGraphResourceTestUtil.assertGraph("/go/Go_VndrExpected_graph.json", dependencyGraph); } |
### Question:
BitbakeListTasksParser { public Optional<String> parseTargetArchitecture(final String standardOutput) { return Arrays.stream(standardOutput.split(System.lineSeparator())) .filter(this::lineContainsArchitecture) .map(this::getArchitectureFromLine) .findFirst(); } Optional<String> parseTargetArchitecture(final String standardOutput); }### Answer:
@Test public void parseTargetArchitectureTest() { final TestUtil testUtil = new TestUtil(); final String listtaskOutput = testUtil.getResourceAsUTF8String("/bitbake/listtasks_output.txt"); final BitbakeListTasksParser bitbakeListTasksParser = new BitbakeListTasksParser(); final Optional<String> architecture = bitbakeListTasksParser.parseTargetArchitecture(listtaskOutput); assert architecture.isPresent(); System.out.println(architecture.get()); assert architecture.get().equals("i586-poky-linux"); } |
### Question:
GraphParserTransformer { public DependencyGraph transform(final GraphParser graphParser, final String targetArchitecture) { final Map<String, GraphNode> nodes = graphParser.getNodes(); final Map<String, GraphEdge> edges = graphParser.getEdges(); final LazyExternalIdDependencyGraphBuilder graphBuilder = new LazyExternalIdDependencyGraphBuilder(); for (final GraphNode graphNode : nodes.values()) { final String name = getNameFromNode(graphNode); final DependencyId dependencyId = new NameDependencyId(name); final Optional<String> version = getVersionFromNode(graphNode); if (version.isPresent()) { final ExternalId externalId = new ExternalId(Forge.YOCTO); externalId.name = name; externalId.version = version.get(); externalId.architecture = targetArchitecture; graphBuilder.setDependencyInfo(dependencyId, name, version.get(), externalId); } graphBuilder.addChildToRoot(dependencyId); } for (final GraphEdge graphEdge : edges.values()) { final DependencyId node1 = new NameDependencyId(getNameFromNode(graphEdge.getNode1())); final DependencyId node2 = new NameDependencyId(getNameFromNode(graphEdge.getNode2())); graphBuilder.addParentWithChild(node1, node2); } return graphBuilder.build(); } DependencyGraph transform(final GraphParser graphParser, final String targetArchitecture); }### Answer:
@Test public void transform() throws IOException { final GraphParserTransformer graphParserTransformer = new GraphParserTransformer(); final InputStream inputStream = new ClassPathResource("/bitbake/recipe-depends.dot").getInputStream(); final GraphParser graphParser = new GraphParser(inputStream); final DependencyGraph dependencyGraph = graphParserTransformer.transform(graphParser, "i586-poky-linux"); assert dependencyGraph.getRootDependencies().size() == 480; } |
### Question:
ClangCompileCommandParser { public String getCompilerCommand(final String origCompileCommand) { final String[] parts = origCompileCommand.trim().split("\\s+"); return parts[0]; } String getCompilerCommand(final String origCompileCommand); List<String> getCompilerArgsForGeneratingDepsMkFile(final String origCompileCommand, final String depsMkFilePath, final Map<String, String> optionOverrides); }### Answer:
@Test public void testGetCompilerCmd() { ClangCompileCommandParser compileCommandParser = new ClangCompileCommandParser(); Map<String, String> optionOverrides = new HashMap<>(1); optionOverrides.put("-o", "/dev/null"); String compilerCommand = compileCommandParser.getCompilerCommand( "g++ -DDOUBLEQUOTED=\"A value for the compiler\" -DSINGLEQUOTED='Another value for the compiler' file.c -o file.o"); assertEquals("g++", compilerCommand); } |
### Question:
CpanListParser { List<String> getDirectModuleNames(final List<String> directDependenciesText) { final List<String> modules = new ArrayList<>(); for (final String line : directDependenciesText) { if (StringUtils.isBlank(line)) { continue; } if (line.contains("-->") || ((line.contains(" ... ") && line.contains("Configuring")))) { continue; } modules.add(line.split("~")[0].trim()); } return modules; } CpanListParser(final ExternalIdFactory externalIdFactory); DependencyGraph parse(final List<String> cpanListText, final List<String> directDependenciesText); }### Answer:
@Test public void getDirectModuleNamesTest() { final List<String> names = cpanListParser.getDirectModuleNames(showDepsText); assertEquals(4, names.size()); assertTrue(names.contains("ExtUtils::MakeMaker")); assertTrue(names.contains("Test::More")); assertTrue(names.contains("perl")); assertTrue(names.contains("ExtUtils::MakeMaker")); } |
### Question:
CondaListParser { public Dependency condaListElementToDependency(final String platform, final CondaListElement element) { final String name = element.name; final String version = String.format("%s-%s-%s", element.version, element.buildString, platform); final ExternalId externalId = externalIdFactory.createNameVersionExternalId(Forge.ANACONDA, name, version); return new Dependency(name, version, externalId); } CondaListParser(final Gson gson, final ExternalIdFactory externalIdFactory); DependencyGraph parse(final String listJsonText, final String infoJsonText); Dependency condaListElementToDependency(final String platform, final CondaListElement element); }### Answer:
@Test public void condaListElementToDependencyNodeTransformerTest() { final String platform = "linux"; final CondaListElement element = new CondaListElement(); element.name = "sampleName"; element.version = "sampleVersion"; element.buildString = "py36_0"; final Dependency dependency = condaListParser.condaListElementToDependency(platform, element); assertEquals("sampleName", dependency.name); assertEquals("sampleVersion-py36_0-linux", dependency.version); assertEquals("sampleName=sampleVersion-py36_0-linux", dependency.externalId.createExternalId()); } |
### Question:
CondaListParser { public DependencyGraph parse(final String listJsonText, final String infoJsonText) { final Type listType = new TypeToken<ArrayList<CondaListElement>>() { }.getType(); final List<CondaListElement> condaList = gson.fromJson(listJsonText, listType); final CondaInfo condaInfo = gson.fromJson(infoJsonText, CondaInfo.class); final String platform = condaInfo.platform; final MutableDependencyGraph graph = new MutableMapDependencyGraph(); for (final CondaListElement condaListElement : condaList) { graph.addChildToRoot(condaListElementToDependency(platform, condaListElement)); } return graph; } CondaListParser(final Gson gson, final ExternalIdFactory externalIdFactory); DependencyGraph parse(final String listJsonText, final String infoJsonText); Dependency condaListElementToDependency(final String platform, final CondaListElement element); }### Answer:
@Test public void smallParseTest() { final String condaInfoJson = testUtil.getResourceAsUTF8String("/conda/condaInfo.json"); final String condaListJson = testUtil.getResourceAsUTF8String("/conda/condaListSmall.json"); final DependencyGraph dependencyGraph = condaListParser.parse(condaListJson, condaInfoJson); DependencyGraphResourceTestUtil.assertGraph("/conda/condaListSmallExpected_graph.json", dependencyGraph); }
@Test public void largeParseTest() { final String condaInfoJson = testUtil.getResourceAsUTF8String("/conda/condaInfo.json"); final String condaListJson = testUtil.getResourceAsUTF8String("/conda/condaListLarge.json"); final DependencyGraph dependencyGraph = condaListParser.parse(condaListJson, condaInfoJson); DependencyGraphResourceTestUtil.assertGraph("/conda/condaListLargeExpected_graph.json", dependencyGraph); } |
### Question:
MavenCodeLocationPackager { Dependency textToProject(final String componentText) { if (!isGav(componentText)) { return null; } final String[] gavParts = componentText.split(":"); final String group = gavParts[0]; final String artifact = gavParts[1]; String version; if (gavParts.length == 4) { version = gavParts[gavParts.length - 1]; } else if (gavParts.length == 5) { version = gavParts[gavParts.length - 1]; } else { logger.debug(String.format("%s does not look like a dependency we can parse", componentText)); return null; } final ExternalId externalId = externalIdFactory.createMavenExternalId(group, artifact, version); return new Dependency(artifact, version, externalId); } MavenCodeLocationPackager(final ExternalIdFactory externalIdFactory); List<MavenParseResult> extractCodeLocations(final String sourcePath, final String mavenOutputText, final String targetScope, final String excludedModules, final String includedModules); static final List<String> indentationStrings; static final List<String> KNOWN_SCOPES; static final String ORPHAN_LIST_PARENT_NODE_NAME; static final String ORPHAN_LIST_PARENT_NODE_GROUP; static final String ORPHAN_LIST_PARENT_NODE_VERSION; }### Answer:
@Test public void testParseProject() { final MavenCodeLocationPackager mavenCodeLocationPackager = new MavenCodeLocationPackager(new ExternalIdFactory()); Dependency dependency = mavenCodeLocationPackager.textToProject("stuff:things:jar:0.0.1"); assertNotNull(dependency); dependency = mavenCodeLocationPackager.textToProject("stuff:things:jar:classifier:0.0.1"); assertNotNull(dependency); dependency = mavenCodeLocationPackager.textToProject("stuff:things:jar"); assertNull(dependency); dependency = mavenCodeLocationPackager.textToProject("stuff:things:jar:classifier:0.0.1:monkey"); assertNull(dependency); } |
### Question:
ProductMapper { public Product toProduct(ProductDto product) { return this.mapper.map(product, Product.class); } ProductMapper(); ProductDto toProductDto(Product product); List<ProductDto> toProductDtoList(List<Product> products); Product toProduct(ProductDto product); }### Answer:
@Test public void testProductDto2JpaMapping() { ProductDto productDto = ProductDto.builder() .id("product-1") .name("product-1") .brand("brand-1") .description("description-1") .category(ImmutableList.of("one", "two")) .price(BigDecimal.TEN) .build(); Product productJpa = mapper.toProduct(productDto); softly.then(productJpa.getId()).isEqualTo(productDto.getId()); softly.then(productJpa.getName()).isEqualTo(productDto.getName()); softly.then(productJpa.getBrand()).isEqualTo(productDto.getBrand()); softly.then(productJpa.getDescription()).isEqualTo(productDto.getDescription()); softly.then(productJpa.getPrice()).isEqualTo(productDto.getPrice()); assertThat(productJpa.getCategories()).isNotNull(); softly.then(productJpa.getCategories()).usingElementComparatorOnFields("category"); } |
### Question:
ProductMapper { public ProductDto toProductDto(Product product) { return this.mapper.map(product, ProductDto.class); } ProductMapper(); ProductDto toProductDto(Product product); List<ProductDto> toProductDtoList(List<Product> products); Product toProduct(ProductDto product); }### Answer:
@Test public void testProductJpa2DtoMapping() { Product productJpa = Product.builder() .id("product-1") .name("product-1") .brand("brand-1") .description("description-1") .categories(ImmutableList.of( Category.builder().name("one").build(), Category.builder().name("two").build())) .price(BigDecimal.TEN) .build(); ProductDto productDto = mapper.toProductDto(productJpa); softly.then(productDto.getId()).isEqualTo(productJpa.getId()); softly.then(productDto.getName()).isEqualTo(productJpa.getName()); softly.then(productDto.getBrand()).isEqualTo(productJpa.getBrand()); softly.then(productDto.getDescription()).isEqualTo(productJpa.getDescription()); softly.then(productDto.getPrice()).isEqualTo(productJpa.getPrice()); softly.then(productDto.getCategory()).isEqualTo(ImmutableList.of("one","two")); } |
### Question:
OrderMapper { public OrderForm toOrderForm(OrderDto order) { return this.mapper.map(order, OrderForm.class); } OrderMapper(); OrderDto toOrderDto(OrderForm order); OrderForm toOrderForm(OrderDto order); List<OrderDto> toOrderDtoList(List<OrderForm> orders); }### Answer:
@Test public void testEmptyOrderDto() { OrderDto orderDto = OrderDto.builder() .id("order-1") .userId("user-1") .status(OrderDto.Status.SUBMITTED) .build(); OrderForm orderJpa = mapper.toOrderForm(orderDto); softly.then(orderJpa.getId()).isEqualTo(orderDto.getId()); softly.then(orderJpa.getUserId()).isEqualTo(orderDto.getUserId()); softly.then(orderJpa.getStatus()).isEqualTo(orderDto.getStatus()); }
@Test public void testOrderDtoWithOrderItemDto() { OrderDto orderDto = OrderDto.builder() .id("order-1") .userId("user-1") .status(OrderDto.Status.SUBMITTED) .items(ImmutableList.of( OrderItemDto.builder() .productId("product-1") .quantity(10) .build() )) .build(); OrderForm orderJpa = mapper.toOrderForm(orderDto); softly.then(orderJpa.getId()).isEqualTo(orderDto.getId()); softly.then(orderJpa.getUserId()).isEqualTo(orderDto.getUserId()); softly.then(orderJpa.getStatus()).isEqualTo(orderDto.getStatus()); softly.then(orderJpa.getItems()) .isNotNull() .hasSize(1); softly.then(orderJpa.getItems().get(0).getId()).isNull(); softly.then(orderJpa.getItems().get(0).getOrder()) .isNotNull() .hasFieldOrPropertyWithValue("id", "order-1"); softly.then(orderJpa.getItems().get(0).getProductId()).isEqualTo("product-1"); softly.then(orderJpa.getItems().get(0).getQuantity()).isEqualTo(10); } |
### Question:
OrderMapper { public OrderDto toOrderDto(OrderForm order) { return this.mapper.map(order, OrderDto.class); } OrderMapper(); OrderDto toOrderDto(OrderForm order); OrderForm toOrderForm(OrderDto order); List<OrderDto> toOrderDtoList(List<OrderForm> orders); }### Answer:
@Test public void testOrderJpaToOrderDto() throws IOException { OrderForm orderJpa = OrderForm.builder() .id("orderJpa-1") .userId("user-1") .status(OrderDto.Status.SUBMITTED) .items(ImmutableList.of( OrderItem.builder() .productId("product-1") .quantity(10) .build() )) .build(); OrderDto orderDto = mapper.toOrderDto(orderJpa); softly.then(orderDto.getId()).isEqualTo(orderJpa.getId()); softly.then(orderDto.getUserId()).isEqualTo(orderJpa.getUserId()); softly.then(orderDto.getStatus()).isEqualTo(orderJpa.getStatus()); softly.then(orderDto.getItems()) .isNotNull() .hasSize(1); softly.then(orderDto.getItems().get(0).getProductId()).isEqualTo("product-1"); softly.then(orderDto.getItems().get(0).getQuantity()).isEqualTo(10); ObjectMapper jsonMapper = new ObjectMapper(); String jsonOrderDto = jsonMapper.writeValueAsString(orderDto); OrderDto pojoOrderDto = jsonMapper.readValue(jsonOrderDto, OrderDto.class); softly.then(pojoOrderDto.getId()).isEqualTo(orderJpa.getId()); softly.then(pojoOrderDto.getUserId()).isEqualTo(orderJpa.getUserId()); softly.then(pojoOrderDto.getStatus()).isEqualTo(orderJpa.getStatus()); softly.then(pojoOrderDto.getItems()) .isNotNull() .hasSize(1); softly.then(pojoOrderDto.getItems().get(0).getProductId()).isEqualTo("product-1"); softly.then(pojoOrderDto.getItems().get(0).getQuantity()).isEqualTo(10); } |
### Question:
UserMapper { public User toUser(UserDto user) { return this.mapper.map(user, User.class); } UserMapper(); UserDto toUserDto(User user); List<UserDto> toUserDtoList(List<User> users); User toUser(UserDto user); }### Answer:
@Test public void testUserDtoMapping() { UserDto userDto = UserDto.builder() .id("user-1") .title("Mr") .givenName("Mickey") .familyName("Mouse") .email("[email protected]") .bday(LocalDate.of(1928,1,1).atStartOfDay()) .build(); User userJpa = mapper.toUser(userDto); softly.then(userJpa.getId()).isEqualTo(userDto.getId()); softly.then(userJpa.getTitle()).isEqualTo(userDto.getTitle()); softly.then(userJpa.getFirstname()).isEqualTo(userDto.getGivenName()); softly.then(userJpa.getLastname()).isEqualTo(userDto.getFamilyName()); softly.then(userJpa.getEmail()).isEqualTo(userDto.getEmail()); softly.then(userJpa.getDob()).isEqualTo(userDto.getBday().toLocalDate()); } |
### Question:
UserMapper { public UserDto toUserDto(User user) { return this.mapper.map(user, UserDto.class); } UserMapper(); UserDto toUserDto(User user); List<UserDto> toUserDtoList(List<User> users); User toUser(UserDto user); }### Answer:
@Test public void testUserJpaMapping() { User userJpa = User.builder() .id("user-1") .title("Mr") .firstname("Mickey") .lastname("Mouse") .email("[email protected]") .dob(LocalDate.of(1928,1,1)) .build(); UserDto userDto = mapper.toUserDto(userJpa); softly.then(userDto.getId()).isEqualTo(userJpa.getId()); softly.then(userDto.getTitle()).isEqualTo(userJpa.getTitle()); softly.then(userDto.getGivenName()).isEqualTo(userJpa.getFirstname()); softly.then(userDto.getFamilyName()).isEqualTo(userJpa.getLastname()); softly.then(userDto.getEmail()).isEqualTo(userJpa.getEmail()); softly.then(userDto.getBday()).isEqualTo(userJpa.getDob().atStartOfDay()); } |
### Question:
UserRepository { public List<User> findAll() { return Collections.unmodifiableList(new ArrayList<>(mapUsers.values())); } UserRepository(); List<User> findAll(); Optional<User> findOne(String id); User save(User newUser); Optional<User> remove(String id); }### Answer:
@Test public void testLoadedProducts(){ List<User> allUsers = userRepository.findAll(); log.info(name+" loaded User data = " + allUsers); assertThat(allUsers).isNotNull().hasSize(3); } |
### Question:
SudokuArguments { @Param(value = 1, mappedBy = Mapper.class) abstract List<List<List<List<List<List<List<Set<Set<Set<Set<Set<Set<Collection<Integer>>>>>>>>>>>>>> number(); }### Answer:
@Test void testSudoku() { SudokuArguments_Parser.ParseResult parsed = new SudokuArguments_Parser().parse(new String[]{""}); assertTrue(parsed instanceof SudokuArguments_Parser.ParsingSuccess); SudokuArguments args = ((SudokuArguments_Parser.ParsingSuccess) parsed).getResult(); assertTrue(args.number().isEmpty()); } |
### Question:
OptionalIntegerArguments { @Option(value = "a", mnemonic = 'a', mappedBy = Mapper.class) abstract Optional<Integer> a(); }### Answer:
@Test void testPresent() { OptionalIntegerArguments args = new OptionalIntegerArguments_Parser().parseOrExit(new String[]{"-a", "1"}); assertEquals(Optional.of(1), args.a()); } |
### Question:
AllDoublesArguments { @Param(1) abstract List<Double> positional(); }### Answer:
@Test void positional() { f.assertThat("--obj=1.5", "--prim=1.5", "5.5", "3.5").succeeds( "positional", asList(5.5d, 3.5d), "listOfDoubles", emptyList(), "optionalDouble", Optional.empty(), "doubleObject", 1.5d, "primitiveDouble", 1.5d); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.