method2testcases
stringlengths 118
6.63k
|
---|
### Question:
JsonUtil { public static String toJson(long[] ids) { StringBuilder sb = new StringBuilder(); sb.append("["); if (ids != null) { for (int i = 0; i < ids.length; i++) { if (i > 0) { sb.append(", "); } sb.append(ids[i]); } } sb.append("]"); return sb.toString(); } static String toJsonStr(String value); static boolean isValidJsonObject(String json); static boolean isValidJsonObject(String json, boolean allowBlank); static boolean isValidJsonArray(String json); static boolean isValidJsonArray(String json, boolean allowBlank); static String toJson(long[] ids); static String toJson(Jsonable[] values); }### Answer:
@Test public void testToJson() { Assert.assertEquals("[1, 2, 3]", JsonUtil.toJson(new long[]{1, 2, 3})); } |
### Question:
MemCacheTemplate implements CacheAble<T> { @Override public boolean set(String key, T value) { return set(key, value, expireTime); } @Override T get(String key); @Override Map<String, T> getMulti(String[] keys); @Override boolean set(String key, T value); @Override boolean set(String key, T value, Date expdate); @SuppressWarnings("unchecked") @Override CasValue<T> getCas(String key); @Override boolean cas(String key, CasValue<T> casValue); @Override boolean cas(String key, CasValue<T> casValue, Date expdate); @Override boolean delete(String key); void setExpire(long expire); void setExpireL1(long expireL1); Date getExpireTime(); Date getExpireTimeL1(); MemcacheClient getMaster(); List<MemcacheClient> getMasterL1List(); MemcacheClient getSlave(); List<MemcacheClient> getSlaveL1List(); boolean isSetbackMaster(); void setMaster(MemcacheClient master); void setMasterL1List(List<MemcacheClient> masterL1List); void setSlave(MemcacheClient slave); void setSlaveL1List(List<MemcacheClient> slaveL1List); void setSetbackMaster(boolean setbackMaster); boolean isMasterAsOneL1(); void setMasterAsOneL1(boolean masterAsOneL1); String getWirtePolicy(); void setWirtePolicy(String wirtePolicy); }### Answer:
@Test public void testSet() { String key = MemCacheUtil.toKey("123", "module.c"); MemCacheTemplate<String> memCacheTemplate = getMemCacheTemplate(); if (memCacheTemplate.set(key, "dsadsadsadsadas")) { String value = memCacheTemplate.get(key); Assert.assertEquals("dsadsadsadsadas", value); memCacheTemplate.delete(key); value = memCacheTemplate.get(key); Assert.assertEquals(null, value); } } |
### Question:
MD5Util { public static String md5(String src) { return md5(src.getBytes()); } static String md5(String src); static String md5(byte[] bytes); static String encodeHex(byte[] bytes); static String md5(long[] array); static byte[] long2Byte(long[] longArray); static void main(String[] args); }### Answer:
@Test public void testMd5() { String strMd5 = MD5Util.md5("123456"); ApiLogger.debug("MD5UtilTest testMd5 strMd5:" + strMd5); Assert.assertEquals("e10adc3949ba59abbe56e057f20f883e", strMd5); } |
### Question:
Crc32Util { public static long getCrc32(byte[] b) { CRC32 crc = crc32Provider.get(); crc.reset(); crc.update(b); return crc.getValue(); } static long getCrc32(byte[] b); static long getCrc32(String str); static void main(String[] args); }### Answer:
@Test public void testCrc32() { long h = Crc32Util.getCrc32(String.valueOf("256")); ApiLogger.debug("Crc32UtilTest testCrc32 h:" + h); } |
### Question:
ArrayUtil { public static int[] toRawIntArr(String strArr[]) { int[] intArr = new int[strArr.length]; for (int i = 0; i < strArr.length; i++) { intArr[i] = Integer.parseInt(strArr[i]); } return intArr; } private ArrayUtil(); static Long[] toLongArr(String[] strArr); static Long[] toLongArr(long[] longArr); static long[] toRawLongArr(String[] strArr); static int[] toRawIntArr(String strArr[]); static long[] toLongArr(Collection<Long> ids); static int[] toIntArr(Collection<Integer> ids); static String[] splitSimpleString(String str); static String toSimpleString(long a[]); static void reverse(long[] b); static void reverse(long[][] b); static long[] reverseCopy(long[] original, int newLength); static long[] reverseCopyRange(long[] original, int from, int to); static long[] removeAll(long[] sourceArray, long[] removeArray); static long[] removeAll(long[] sourceArray, Set<Long> removeSet); static long[] sort(long left[], long right[]); static void sortDesc(long[] a); static long[] intersectionOrder(long[] arr1, long[] arr2); static long[] addTo(long[] left, long[] right); static long[] addTo(long[] arr, long id); static long[] addTo(long[] arr, long id, int limit); static long[] getLimited(long[] arr, int limit); }### Answer:
@Test public void testToRawIntArr(){ String[] inputArray1 = { "2", "2", "4", "6", "8", "15" }; int[] result = ArrayUtil.toRawIntArr(inputArray1); Assert.assertArrayEquals(new int[] { 2, 2, 4, 6, 8, 15 }, result); } |
### Question:
ArrayUtil { public static long[] reverseCopy(long[] original, int newLength) { long[] result = new long[newLength]; int originalLimit = original.length - newLength; for (int i = original.length - 1, resultIdx = 0; i >= originalLimit; i--) { result[resultIdx++] = original[i]; } return result; } private ArrayUtil(); static Long[] toLongArr(String[] strArr); static Long[] toLongArr(long[] longArr); static long[] toRawLongArr(String[] strArr); static int[] toRawIntArr(String strArr[]); static long[] toLongArr(Collection<Long> ids); static int[] toIntArr(Collection<Integer> ids); static String[] splitSimpleString(String str); static String toSimpleString(long a[]); static void reverse(long[] b); static void reverse(long[][] b); static long[] reverseCopy(long[] original, int newLength); static long[] reverseCopyRange(long[] original, int from, int to); static long[] removeAll(long[] sourceArray, long[] removeArray); static long[] removeAll(long[] sourceArray, Set<Long> removeSet); static long[] sort(long left[], long right[]); static void sortDesc(long[] a); static long[] intersectionOrder(long[] arr1, long[] arr2); static long[] addTo(long[] left, long[] right); static long[] addTo(long[] arr, long id); static long[] addTo(long[] arr, long id, int limit); static long[] getLimited(long[] arr, int limit); }### Answer:
@Test public void testReverseCopy(){ long[] inputArray1 = { 2, 2, 4, 6, 8, 15 }; long[] result = ArrayUtil.reverseCopy(inputArray1, inputArray1.length); Assert.assertArrayEquals(new long[] { 15, 8, 6, 4, 2, 2 }, result); } |
### Question:
ArrayUtil { public static long[] sort(long left[], long right[]) { long[] result = addTo(left, right); Arrays.sort(result); return result; } private ArrayUtil(); static Long[] toLongArr(String[] strArr); static Long[] toLongArr(long[] longArr); static long[] toRawLongArr(String[] strArr); static int[] toRawIntArr(String strArr[]); static long[] toLongArr(Collection<Long> ids); static int[] toIntArr(Collection<Integer> ids); static String[] splitSimpleString(String str); static String toSimpleString(long a[]); static void reverse(long[] b); static void reverse(long[][] b); static long[] reverseCopy(long[] original, int newLength); static long[] reverseCopyRange(long[] original, int from, int to); static long[] removeAll(long[] sourceArray, long[] removeArray); static long[] removeAll(long[] sourceArray, Set<Long> removeSet); static long[] sort(long left[], long right[]); static void sortDesc(long[] a); static long[] intersectionOrder(long[] arr1, long[] arr2); static long[] addTo(long[] left, long[] right); static long[] addTo(long[] arr, long id); static long[] addTo(long[] arr, long id, int limit); static long[] getLimited(long[] arr, int limit); }### Answer:
@Test public void testSort() { long[] inputArray1 = { 2, 2, 4, 6, 8, 15 }; long[] inputArray2 = { 0, 0, 1, 3, 7, 9, 10, 11 }; long[] result = ArrayUtil.sort(inputArray1, inputArray2); Assert.assertArrayEquals(new long[] {0, 0, 1, 2, 2, 3, 4, 6, 7, 8, 9, 10, 11, 15}, result); result = ArrayUtil.sort(inputArray1, new long[]{}); Assert.assertArrayEquals(inputArray1, result); result = ArrayUtil.sort(new long[]{}, inputArray2); Assert.assertArrayEquals(inputArray2, result); } |
### Question:
ArrayUtil { public static void sortDesc(long[] a) { Arrays.sort(a); reverse(a); } private ArrayUtil(); static Long[] toLongArr(String[] strArr); static Long[] toLongArr(long[] longArr); static long[] toRawLongArr(String[] strArr); static int[] toRawIntArr(String strArr[]); static long[] toLongArr(Collection<Long> ids); static int[] toIntArr(Collection<Integer> ids); static String[] splitSimpleString(String str); static String toSimpleString(long a[]); static void reverse(long[] b); static void reverse(long[][] b); static long[] reverseCopy(long[] original, int newLength); static long[] reverseCopyRange(long[] original, int from, int to); static long[] removeAll(long[] sourceArray, long[] removeArray); static long[] removeAll(long[] sourceArray, Set<Long> removeSet); static long[] sort(long left[], long right[]); static void sortDesc(long[] a); static long[] intersectionOrder(long[] arr1, long[] arr2); static long[] addTo(long[] left, long[] right); static long[] addTo(long[] arr, long id); static long[] addTo(long[] arr, long id, int limit); static long[] getLimited(long[] arr, int limit); }### Answer:
@Test public void testSortDesc() { long[] inputArray1 = { 2, 2, 4, 6, 8, 15 }; ArrayUtil.sortDesc(inputArray1); System.out.println(Arrays.toString(inputArray1)); Assert.assertArrayEquals(new long[] { 15, 8, 6, 4, 2, 2 }, inputArray1); } |
### Question:
ArrayUtil { public static long[] addTo(long[] left, long[] right){ if (left == null) { return ArrayUtils.clone(right); } else if (right == null) { return ArrayUtils.clone(left); } long[] result = new long[left.length + right.length]; int pos = 0; System.arraycopy(left, 0, result, pos, left.length); pos += left.length; System.arraycopy(right, 0, result, pos, right.length); return result; } private ArrayUtil(); static Long[] toLongArr(String[] strArr); static Long[] toLongArr(long[] longArr); static long[] toRawLongArr(String[] strArr); static int[] toRawIntArr(String strArr[]); static long[] toLongArr(Collection<Long> ids); static int[] toIntArr(Collection<Integer> ids); static String[] splitSimpleString(String str); static String toSimpleString(long a[]); static void reverse(long[] b); static void reverse(long[][] b); static long[] reverseCopy(long[] original, int newLength); static long[] reverseCopyRange(long[] original, int from, int to); static long[] removeAll(long[] sourceArray, long[] removeArray); static long[] removeAll(long[] sourceArray, Set<Long> removeSet); static long[] sort(long left[], long right[]); static void sortDesc(long[] a); static long[] intersectionOrder(long[] arr1, long[] arr2); static long[] addTo(long[] left, long[] right); static long[] addTo(long[] arr, long id); static long[] addTo(long[] arr, long id, int limit); static long[] getLimited(long[] arr, int limit); }### Answer:
@Test public void testAddToArrays(){ long[] array1 = { 2, 2, 4, 6, 8, 15 }; long id = 345; long[] result = ArrayUtil.addTo(array1, id); Assert.assertArrayEquals(new long[] { 2, 2, 4, 6, 8, 15, 345 }, result); }
@Test public void testAddToLimit() { long[] array1 = { 2, 2, 4, 6, 8, 15, 17 }; long id = 345; int limit = 10; long[] result = ArrayUtil.addTo(array1, id, limit); Assert.assertArrayEquals(new long[] { 2, 2, 4, 6, 8, 15, 17, 345 }, result); result = ArrayUtil.addTo(result, 4, limit); Assert.assertArrayEquals(new long[] { 2, 2, 4, 6, 8, 15, 17, 345}, result); result = ArrayUtil.addTo(result, 124, limit); result = ArrayUtil.addTo(result, 125, limit); Assert.assertArrayEquals(new long[] { 2, 2, 4, 6, 8, 15, 17, 345, 124, 125}, result); result = ArrayUtil.addTo(result, 126, limit); Assert.assertArrayEquals(new long[] { 2, 4, 6, 8, 15, 17, 345, 124, 125, 126}, result); result = ArrayUtil.addTo(result, 127, limit); Assert.assertArrayEquals(new long[] { 4, 6, 8, 15, 17, 345, 124, 125, 126, 127}, result); } |
### Question:
ArrayUtil { public static long[] getLimited(long[] arr, int limit) { if (arr == null) { return arr; } if (arr.length > limit) { long[] result = new long[limit]; System.arraycopy(arr, arr.length - limit, result, 0, limit); return result; } else { return arr; } } private ArrayUtil(); static Long[] toLongArr(String[] strArr); static Long[] toLongArr(long[] longArr); static long[] toRawLongArr(String[] strArr); static int[] toRawIntArr(String strArr[]); static long[] toLongArr(Collection<Long> ids); static int[] toIntArr(Collection<Integer> ids); static String[] splitSimpleString(String str); static String toSimpleString(long a[]); static void reverse(long[] b); static void reverse(long[][] b); static long[] reverseCopy(long[] original, int newLength); static long[] reverseCopyRange(long[] original, int from, int to); static long[] removeAll(long[] sourceArray, long[] removeArray); static long[] removeAll(long[] sourceArray, Set<Long> removeSet); static long[] sort(long left[], long right[]); static void sortDesc(long[] a); static long[] intersectionOrder(long[] arr1, long[] arr2); static long[] addTo(long[] left, long[] right); static long[] addTo(long[] arr, long id); static long[] addTo(long[] arr, long id, int limit); static long[] getLimited(long[] arr, int limit); }### Answer:
@Test public void testGetLimited(){ long[] array1 = { 1, 2, 4, 6, 8, 15, 17 }; long[] array2 = { 1, 2, 4, 6, 8, 15, 17, 18, 19, 20, 21}; long[] array3 = null; long[] array4 = {}; int limit = 10; long[] result = ArrayUtil.getLimited(array1, limit); Assert.assertArrayEquals(new long[] { 1, 2, 4, 6, 8, 15, 17}, result); result = ArrayUtil.getLimited(array2, limit); Assert.assertArrayEquals(new long[] { 2, 4, 6, 8, 15, 17, 18, 19, 20, 21}, result); result = ArrayUtil.getLimited(array3, limit); Assert.assertArrayEquals(null, result); result = ArrayUtil.getLimited(array4, limit); Assert.assertArrayEquals(new long[]{}, result); } |
### Question:
MemCacheTemplate implements CacheAble<T> { @Override public boolean delete(String key) { boolean rs = delete(key, master); if (rs == false) { return rs; } if(slave != null){ delete(key, slave); } delete(key, masterL1List); delete(key, slaveL1List); return rs; } @Override T get(String key); @Override Map<String, T> getMulti(String[] keys); @Override boolean set(String key, T value); @Override boolean set(String key, T value, Date expdate); @SuppressWarnings("unchecked") @Override CasValue<T> getCas(String key); @Override boolean cas(String key, CasValue<T> casValue); @Override boolean cas(String key, CasValue<T> casValue, Date expdate); @Override boolean delete(String key); void setExpire(long expire); void setExpireL1(long expireL1); Date getExpireTime(); Date getExpireTimeL1(); MemcacheClient getMaster(); List<MemcacheClient> getMasterL1List(); MemcacheClient getSlave(); List<MemcacheClient> getSlaveL1List(); boolean isSetbackMaster(); void setMaster(MemcacheClient master); void setMasterL1List(List<MemcacheClient> masterL1List); void setSlave(MemcacheClient slave); void setSlaveL1List(List<MemcacheClient> slaveL1List); void setSetbackMaster(boolean setbackMaster); boolean isMasterAsOneL1(); void setMasterAsOneL1(boolean masterAsOneL1); String getWirtePolicy(); void setWirtePolicy(String wirtePolicy); }### Answer:
@Test public void testDelete() { String key = MemCacheUtil.toKey("123", "module.c"); MemCacheTemplate<String> memCacheTemplate = getMemCacheTemplate(); if (memCacheTemplate.set(key, "dsadsadsadsadas")) { String value = memCacheTemplate.get(key); Assert.assertEquals("dsadsadsadsadas", value); memCacheTemplate.delete(key); value = memCacheTemplate.get(key); Assert.assertEquals(null, value); } } |
### Question:
Util { public static int convertInt(Object obj) { return convertInt(obj, 0); } static String toStr(byte[] data); static byte[] toBytes(String str); static double convertDouble(String src); static double convertDouble(String src, double defaultValue); static int convertInt(Object obj); static int convertInt(Object obj, int defaultValue); static long convertLong(String src); static long convertLong(String src, long defaultValue); static void trim(StringBuffer sb,char c); static String urlDecoder(String s, String charcoding); static String urlEncoder(String s, String charcoding); static String toEscChar(String s); static String htmlEscapeOnce(String s); static String htmlUnEscapeOnce(String s); static String getPicIdFromUrl(String url); static String getProfileImgUrl(long uid, int size, long iconver, byte gender); static long getVersionFromImgUrl(String imageUrl); static String toEscapeJson(String s); }### Answer:
@Test public void testConvertInt() { assertEquals(0, Util.convertInt("")); assertEquals(0, Util.convertInt("-")); assertEquals(12443, Util.convertInt("12443")); assertEquals(-12443, Util.convertInt("-12443")); assertEquals(Integer.MAX_VALUE, Util.convertInt(String.valueOf(Integer.MAX_VALUE))); assertEquals(Integer.MIN_VALUE, Util.convertInt(String.valueOf(Integer.MIN_VALUE))); } |
### Question:
Util { public static long convertLong(String src) { return convertLong(src, 0); } static String toStr(byte[] data); static byte[] toBytes(String str); static double convertDouble(String src); static double convertDouble(String src, double defaultValue); static int convertInt(Object obj); static int convertInt(Object obj, int defaultValue); static long convertLong(String src); static long convertLong(String src, long defaultValue); static void trim(StringBuffer sb,char c); static String urlDecoder(String s, String charcoding); static String urlEncoder(String s, String charcoding); static String toEscChar(String s); static String htmlEscapeOnce(String s); static String htmlUnEscapeOnce(String s); static String getPicIdFromUrl(String url); static String getProfileImgUrl(long uid, int size, long iconver, byte gender); static long getVersionFromImgUrl(String imageUrl); static String toEscapeJson(String s); }### Answer:
@Test public void testConvertLong() { assertEquals(0L, Util.convertLong("")); assertEquals(0L, Util.convertLong("-")); assertEquals(12443, Util.convertLong("12443")); assertEquals(-12443, Util.convertLong("-12443")); assertEquals(Long.MAX_VALUE, Util.convertLong(String.valueOf(Long.MAX_VALUE))); assertEquals(Long.MIN_VALUE, Util.convertLong(String.valueOf(Long.MIN_VALUE))); }
@Test public void testParseLong() { assertEquals(12443l,Util.convertLong("12443")); } |
### Question:
Util { public static String urlEncoder(String s, String charcoding) { if (s == null) return null; try { return URLEncoder.encode(s, charcoding); } catch (Exception e) { } return null; } static String toStr(byte[] data); static byte[] toBytes(String str); static double convertDouble(String src); static double convertDouble(String src, double defaultValue); static int convertInt(Object obj); static int convertInt(Object obj, int defaultValue); static long convertLong(String src); static long convertLong(String src, long defaultValue); static void trim(StringBuffer sb,char c); static String urlDecoder(String s, String charcoding); static String urlEncoder(String s, String charcoding); static String toEscChar(String s); static String htmlEscapeOnce(String s); static String htmlUnEscapeOnce(String s); static String getPicIdFromUrl(String url); static String getProfileImgUrl(long uid, int size, long iconver, byte gender); static long getVersionFromImgUrl(String imageUrl); static String toEscapeJson(String s); }### Answer:
@Test public void testUrlEncoder() { assertEquals("%2C",Util.urlEncoder(",", "UTF-8")); } |
### Question:
Util { public static String urlDecoder(String s, String charcoding) { if (s == null) return null; try { return URLDecoder.decode(s, charcoding); } catch (Exception e) { } return null; } static String toStr(byte[] data); static byte[] toBytes(String str); static double convertDouble(String src); static double convertDouble(String src, double defaultValue); static int convertInt(Object obj); static int convertInt(Object obj, int defaultValue); static long convertLong(String src); static long convertLong(String src, long defaultValue); static void trim(StringBuffer sb,char c); static String urlDecoder(String s, String charcoding); static String urlEncoder(String s, String charcoding); static String toEscChar(String s); static String htmlEscapeOnce(String s); static String htmlUnEscapeOnce(String s); static String getPicIdFromUrl(String url); static String getProfileImgUrl(long uid, int size, long iconver, byte gender); static long getVersionFromImgUrl(String imageUrl); static String toEscapeJson(String s); }### Answer:
@Test public void testUrlDecoder() { assertEquals(",",Util.urlDecoder("%2C", "UTF-8")); } |
### Question:
Util { public static String htmlEscapeOnce(String s) { if (StringUtils.isBlank(s)){ return s; } s = s.replaceAll("&", "&"); s = s.replaceAll("<", "<"); s = s.replaceAll(">", ">"); s = s.replaceAll("\"", """); return s; } static String toStr(byte[] data); static byte[] toBytes(String str); static double convertDouble(String src); static double convertDouble(String src, double defaultValue); static int convertInt(Object obj); static int convertInt(Object obj, int defaultValue); static long convertLong(String src); static long convertLong(String src, long defaultValue); static void trim(StringBuffer sb,char c); static String urlDecoder(String s, String charcoding); static String urlEncoder(String s, String charcoding); static String toEscChar(String s); static String htmlEscapeOnce(String s); static String htmlUnEscapeOnce(String s); static String getPicIdFromUrl(String url); static String getProfileImgUrl(long uid, int size, long iconver, byte gender); static long getVersionFromImgUrl(String imageUrl); static String toEscapeJson(String s); }### Answer:
@Test public void testHtmlEscapeOnce() { String src = "&<span class=\"java\"/>"; String target = Util.htmlEscapeOnce(src); assertEquals("&amp;<span class="java"/>", target); } |
### Question:
Util { public static String htmlUnEscapeOnce(String s) { if (StringUtils.isBlank(s)){ return s; } s = s.replaceAll("&", "&"); s = s.replaceAll("<", "<"); s = s.replaceAll(">", ">"); s = s.replaceAll(""", "\""); return s; } static String toStr(byte[] data); static byte[] toBytes(String str); static double convertDouble(String src); static double convertDouble(String src, double defaultValue); static int convertInt(Object obj); static int convertInt(Object obj, int defaultValue); static long convertLong(String src); static long convertLong(String src, long defaultValue); static void trim(StringBuffer sb,char c); static String urlDecoder(String s, String charcoding); static String urlEncoder(String s, String charcoding); static String toEscChar(String s); static String htmlEscapeOnce(String s); static String htmlUnEscapeOnce(String s); static String getPicIdFromUrl(String url); static String getProfileImgUrl(long uid, int size, long iconver, byte gender); static long getVersionFromImgUrl(String imageUrl); static String toEscapeJson(String s); }### Answer:
@Test public void testHtmlUnEscapeOnce() { String src = "&amp;<span class="java"/>"; String target = Util.htmlUnEscapeOnce(src); assertEquals("&<span class=\"java\"/>", target); } |
### Question:
MemCacheTemplate implements CacheAble<T> { @Override public boolean cas(String key, CasValue<T> casValue) { boolean result = cas(key, casValue, expireTime); if (result == false) { ApiLogger.warn("MemCacheTemplate cas key:" + key + ", result:" + result); } return result; } @Override T get(String key); @Override Map<String, T> getMulti(String[] keys); @Override boolean set(String key, T value); @Override boolean set(String key, T value, Date expdate); @SuppressWarnings("unchecked") @Override CasValue<T> getCas(String key); @Override boolean cas(String key, CasValue<T> casValue); @Override boolean cas(String key, CasValue<T> casValue, Date expdate); @Override boolean delete(String key); void setExpire(long expire); void setExpireL1(long expireL1); Date getExpireTime(); Date getExpireTimeL1(); MemcacheClient getMaster(); List<MemcacheClient> getMasterL1List(); MemcacheClient getSlave(); List<MemcacheClient> getSlaveL1List(); boolean isSetbackMaster(); void setMaster(MemcacheClient master); void setMasterL1List(List<MemcacheClient> masterL1List); void setSlave(MemcacheClient slave); void setSlaveL1List(List<MemcacheClient> slaveL1List); void setSetbackMaster(boolean setbackMaster); boolean isMasterAsOneL1(); void setMasterAsOneL1(boolean masterAsOneL1); String getWirtePolicy(); void setWirtePolicy(String wirtePolicy); }### Answer:
@Test public void testCas() { String key = MemCacheUtil.toKey("123", "module.c"); MemCacheTemplate<String> memCacheTemplate = getMemCacheTemplate(); if (memCacheTemplate.set(key, "dsadsadsadsadas")) { CasValue<String> valueCas = memCacheTemplate.getCas(key); String value = (String) valueCas.getValue() + 0; valueCas.setValue(value); memCacheTemplate.cas(key, valueCas); value = memCacheTemplate.get(key); Assert.assertEquals(value, valueCas.getValue()); memCacheTemplate.delete(key); value = memCacheTemplate.get(key); Assert.assertEquals(null, value); } } |
### Question:
IpUtil { public static boolean isIp(String in){ if(in==null){ return false; } return ipPattern.matcher(in).matches(); } static String intToIp(int i); static int ipToInt(final String addr); static long ipToLong(final String addr); static String longToIp(long i); static boolean isIp(String in); static Map<String,String> getLocalIps(); static String getLocalIp(); static String getSingleLocalIp(); static int ramdomAvailablePort(); static boolean availablePort(int port); static void main(String[] args); }### Answer:
@Test public void testIsIp(){ org.junit.Assert.assertTrue(IpUtil.isIp("127.0.0.1")); org.junit.Assert.assertTrue(IpUtil.isIp("10.75.0.60")); org.junit.Assert.assertTrue(IpUtil.isIp("192.168.1.1")); org.junit.Assert.assertTrue(IpUtil.isIp("175.41.9.194")); }
@Test public void testIsIpFalse(){ org.junit.Assert.assertFalse(IpUtil.isIp("aaa")); org.junit.Assert.assertFalse(IpUtil.isIp("1000.75.0.60")); org.junit.Assert.assertFalse(IpUtil.isIp("192.168.1")); org.junit.Assert.assertFalse(IpUtil.isIp("175.41.9.a")); } |
### Question:
IpUtil { public static int ipToInt(final String addr) { final String[] addressBytes = addr.split("\\."); int ip = 0; for (int i = 0; i < 4; i++) { ip <<= 8; ip |= Integer.parseInt(addressBytes[i]); } return ip; } static String intToIp(int i); static int ipToInt(final String addr); static long ipToLong(final String addr); static String longToIp(long i); static boolean isIp(String in); static Map<String,String> getLocalIps(); static String getLocalIp(); static String getSingleLocalIp(); static int ramdomAvailablePort(); static boolean availablePort(int port); static void main(String[] args); }### Answer:
@Test public void testIPToInt(){ org.junit.Assert.assertEquals(2130706433,IpUtil.ipToInt("127.0.0.1")); org.junit.Assert.assertEquals(172687420,IpUtil.ipToInt("10.75.0.60")); org.junit.Assert.assertEquals(-1062731519,IpUtil.ipToInt("192.168.1.1")); org.junit.Assert.assertEquals(-1356265022,IpUtil.ipToInt("175.41.9.194")); } |
### Question:
IpUtil { public static String getLocalIp() { Map<String,String> ips = getLocalIps(); List<String> faceNames = new ArrayList<String>(ips.keySet()); Collections.sort(faceNames); for(String name:faceNames){ if("lo".equals(name)){ continue; } String ip = ips.get(name); if(!StringUtils.isBlank(ip)){ return ip; } } return "127.0.0.1"; } static String intToIp(int i); static int ipToInt(final String addr); static long ipToLong(final String addr); static String longToIp(long i); static boolean isIp(String in); static Map<String,String> getLocalIps(); static String getLocalIp(); static String getSingleLocalIp(); static int ramdomAvailablePort(); static boolean availablePort(int port); static void main(String[] args); }### Answer:
@Test public void testGetLocalIp(){ String localIp = IpUtil.getLocalIp(); System.out.println(localIp); org.junit.Assert.assertNotNull(localIp); } |
### Question:
IpUtil { public static int ramdomAvailablePort(){ int port = 0; do{ port = (int) ((MAX_USER_PORT_NUMBER-MIN_USER_PORT_NUMBER) * Math.random())+MIN_USER_PORT_NUMBER; }while(!availablePort(port)); return port; } static String intToIp(int i); static int ipToInt(final String addr); static long ipToLong(final String addr); static String longToIp(long i); static boolean isIp(String in); static Map<String,String> getLocalIps(); static String getLocalIp(); static String getSingleLocalIp(); static int ramdomAvailablePort(); static boolean availablePort(int port); static void main(String[] args); }### Answer:
@Test public void testGetRandomPort(){ int port = IpUtil.ramdomAvailablePort(); System.out.println(port); org.junit.Assert.assertTrue(port > 0 && port <65535); } |
### Question:
HashUtil { public static int getHash(long id, int splitCount, String hashAlg) { return getHash(id, splitCount, hashAlg, NoneHash.NEW); } static int getHash(long id, int splitCount, String hashAlg); static int getHash(long id, int splitCount, String hashAlg, String noneHash); }### Answer:
@Test public void testGetHashCrc32() { int hash = HashUtil.getHash(1821155363, 32, HashAlg.CRC32); Assert.assertEquals(12, hash); hash = HashUtil.getHash(1821155363, 128, HashAlg.CRC32); Assert.assertEquals(51, hash); }
@Test public void testGetHashNone() { int hash = HashUtil.getHash(1821155363, 32, HashAlg.NONE); Assert.assertEquals(1, hash); hash = HashUtil.getHash(1821155363, 128, HashAlg.NONE); Assert.assertEquals(64, hash); } |
### Question:
DateUtil { public static String formateDateTime(Date date){ return dateTimeSdf.get().format(date); } static String getYearMonth(Date date); static String formateYearMonthDay(Date date); static Date parseYearMonthDay(String timeStr, Date defaultValue); static String formateDateTime(Date date); static Date parseDateTime(String timeStr, Date defaultValue); static final int getCurrentHour(); static final int getLastHour(); static final int getNextHour(); static Date getFirstDayOfCurMonth(); static Date getFirstDayInMonth(Date date); static Date getFirstDayInMonth(int month); static boolean isCurrentMonth(Date date); }### Answer:
@Test public void testFormateDateTime() { assertEquals("2011-11-25 13:12:01", DateUtil.formateDateTime(new Date(1322197921282L))); Date currentTime = DateUtil.parseDateTime("2009-01-01 00:00:00", null); System.out.println(currentTime + ", " + (currentTime.getTime() / 1000)); currentTime = DateUtil.parseDateTime("2009-06-01 00:00:00", null); System.out.println(currentTime + ", " + (currentTime.getTime() / 1000)); currentTime = DateUtil.parseDateTime("2010-01-01 00:00:00", null); System.out.println(currentTime + ", " + (currentTime.getTime() / 1000)); currentTime = DateUtil.parseDateTime("2011-01-01 00:00:00", null); System.out.println(currentTime + ", " + (currentTime.getTime() / 1000)); currentTime = DateUtil.parseDateTime("2011-06-01 00:00:00", null); System.out.println(currentTime + ", " + (currentTime.getTime() / 1000)); currentTime = DateUtil.parseDateTime("2013-01-01 00:00:00", null); System.out.println(currentTime + ", " + (currentTime.getTime() / 1000)); currentTime = DateUtil.parseDateTime("2015-01-01 00:00:00", null); System.out.println(currentTime + ", " + (currentTime.getTime() / 1000)); } |
### Question:
DateUtil { public static Date parseDateTime(String timeStr, Date defaultValue){ if(timeStr == null){ return defaultValue; } try { return dateTimeSdf.get().parse(timeStr); } catch (ParseException e) { return defaultValue; } } static String getYearMonth(Date date); static String formateYearMonthDay(Date date); static Date parseYearMonthDay(String timeStr, Date defaultValue); static String formateDateTime(Date date); static Date parseDateTime(String timeStr, Date defaultValue); static final int getCurrentHour(); static final int getLastHour(); static final int getNextHour(); static Date getFirstDayOfCurMonth(); static Date getFirstDayInMonth(Date date); static Date getFirstDayInMonth(int month); static boolean isCurrentMonth(Date date); }### Answer:
@Test public void testParseDateTime() { System.out.println(new Date(515483463000L)); System.out.println(new Date(1356969600000L)); assertEquals(new Date(1325390268000L), DateUtil.parseDateTime("2012-01-01 11:57:48", null)); } |
### Question:
DateUtil { public static String getYearMonth(Date date){ return yearMonthSdf.get().format(date); } static String getYearMonth(Date date); static String formateYearMonthDay(Date date); static Date parseYearMonthDay(String timeStr, Date defaultValue); static String formateDateTime(Date date); static Date parseDateTime(String timeStr, Date defaultValue); static final int getCurrentHour(); static final int getLastHour(); static final int getNextHour(); static Date getFirstDayOfCurMonth(); static Date getFirstDayInMonth(Date date); static Date getFirstDayInMonth(int month); static boolean isCurrentMonth(Date date); }### Answer:
@Test public void testGetYearMonth() { Date date = DateUtil.parseDateTime("2012-01-01 11:57:48", null); assertEquals("12_01", DateUtil.getYearMonth(date)); date = DateUtil.parseDateTime("2012-12-01 00:00:00", null); ApiLogger.debug(date + ", " + date.getTime()); }
@Test public void testGetYearMonthDay() { assertEquals("11_11", DateUtil.getYearMonth(new Date(1322197921282L))); } |
### Question:
ApacheHttpClient implements ApiHttpClient { @Deprecated public String requestURL(String url, Map<String, ?> nameValues) { if(HttpManager.isBlockResource(url)){ debug("requestURL blockResource url="+url); return null; } ByteArrayOutputStream out = new ByteArrayOutputStream(); String result = null; try { long t = System.currentTimeMillis(); requestURL(url, nameValues, out); result = new String(out.toByteArray(), "utf-8"); if (isDebugEnabled()) { if (result.length() > 500) { debug("getURL:" + url + ", time:" + (System.currentTimeMillis() - t) + ", result:" + result.substring(0, 500)); } else { debug("getURL:" + url + ", time:" + (System.currentTimeMillis() - t) + ", result:" + result); } } } catch (Exception e) { warn("requestURL error, URL:" + url, e); } return result; } ApacheHttpClient(); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize,int minThread,int maxThread); @Deprecated String getURL(String url); @Deprecated void getURL(String url, ByteBuffer bb); @Deprecated int getURL(String url, OutputStream out); @Deprecated String requestURL(String url, Map<String, ?> nameValues); @Deprecated int requestURL(String url, Map<String, ?> nameValues, OutputStream out); @Deprecated String multURL_UTF8(String url, Map<String, Object> nameValues); void setProxyHostPort(String proxyHostPort); String getProxyHostPort(); HttpClient getClient(); @Deprecated String requestURL(String url, Map<String, String> nameValues, Map<String,String> headers); @Deprecated int requestURL(String url, Map<String, ?> nameValues, Map<String,?> headers, OutputStream out); void setAccessLog(AccessLog accessLog); @Override String get(String url); String get(String url,Map<String,String> headers); @Override String get(String url, String charset); String get(String url,Map<String,String> headers, String charset); String getAsync(final String url); String getAsync(final String url, final long timeout); Future<String> getAsyncFuture(final String url); String postAsync(final String url,final Map<String, ?> nameValues); Future<String> postAsyncFuture(final String url,final Map<String, ?> nameValues); byte[] getByte(String url); @Override String post(String url, Map<String, ?> nameValues); @Override String post(String url, Map<String, ?> nameValues, String charset); String post(String url, Map<String, ?> nameValues,Map<String,String> headers, String charset); String postMulti(String url, Map<String, Object> nameValues); String postMulti(String url, Map<String, Object> nameValues,String charset); String postMulti(String url, InputStream in); String postMulti(String url, byte[] buf); T get(String url, ResultConvert<T> c); T get(String url,String charset,ResultConvert<T> c); T post(String url,Map<String, ?> nameValues, ResultConvert<T> c); T post(String url, Map<String, ?> nameValues,String charset, ResultConvert<T> c); T postMulti(String url, Map<String, Object> nameValues,String charset, ResultConvert<T> c); RequestBuilder buildGet(String url); RequestBuilder buildPost(String url); }### Answer:
@Test public void testRequestUrl(){ ApiHttpClient client = new ApacheHttpClient(100, 1000, 1000, 1024*100); String result = client.get("http: ApiLogger.debug(result); Assert.assertTrue(!StringUtils.isBlank(result)); } |
### Question:
DateUtil { public static String formateYearMonthDay(Date date){ return yearMonthDaySdf.get().format(date); } static String getYearMonth(Date date); static String formateYearMonthDay(Date date); static Date parseYearMonthDay(String timeStr, Date defaultValue); static String formateDateTime(Date date); static Date parseDateTime(String timeStr, Date defaultValue); static final int getCurrentHour(); static final int getLastHour(); static final int getNextHour(); static Date getFirstDayOfCurMonth(); static Date getFirstDayInMonth(Date date); static Date getFirstDayInMonth(int month); static boolean isCurrentMonth(Date date); }### Answer:
@Test public void testFormateYearMonthDay() { assertEquals("2011-11-25", DateUtil.formateYearMonthDay(new Date(1322197921282L))); } |
### Question:
DateUtil { public static Date parseYearMonthDay(String timeStr, Date defaultValue){ if(timeStr == null){ return defaultValue; } try { return yearMonthDaySdf.get().parse(timeStr); } catch (ParseException e) { return defaultValue; } } static String getYearMonth(Date date); static String formateYearMonthDay(Date date); static Date parseYearMonthDay(String timeStr, Date defaultValue); static String formateDateTime(Date date); static Date parseDateTime(String timeStr, Date defaultValue); static final int getCurrentHour(); static final int getLastHour(); static final int getNextHour(); static Date getFirstDayOfCurMonth(); static Date getFirstDayInMonth(Date date); static Date getFirstDayInMonth(int month); static boolean isCurrentMonth(Date date); }### Answer:
@Test public void testParseYearMonthDay() { assertEquals(new Date(1325347200000L), DateUtil.parseYearMonthDay("2012-01-01", null)); Date date = DateUtil.parseYearMonthDay("2012-12-01", null); ApiLogger.debug(date + ", " + date.getTime()); ApiLogger.debug(new Date(1000000000000L) + ", " + new Date(1000000000000L).getTime()); ApiLogger.debug(new Date(1000L * 60 * 43200) + ", " + new Date(1000L * 60 * 43200).getTime() + ", " + (1000L * 60 * 43200)); } |
### Question:
DateUtil { public static Date getFirstDayInMonth(Date date){ Calendar calendar = Calendar.getInstance(); if(date != null){ calendar.setTime(date); } calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); return calendar.getTime(); } static String getYearMonth(Date date); static String formateYearMonthDay(Date date); static Date parseYearMonthDay(String timeStr, Date defaultValue); static String formateDateTime(Date date); static Date parseDateTime(String timeStr, Date defaultValue); static final int getCurrentHour(); static final int getLastHour(); static final int getNextHour(); static Date getFirstDayOfCurMonth(); static Date getFirstDayInMonth(Date date); static Date getFirstDayInMonth(int month); static boolean isCurrentMonth(Date date); }### Answer:
@Test public void testGetFirstDayInMonth() { assertEquals(new Date(1320076800282L), DateUtil.getFirstDayInMonth(new Date(1322197921282L))); } |
### Question:
DateUtil { public static boolean isCurrentMonth(Date date){ if(date != null){ Calendar dest = Calendar.getInstance(); dest.setTime(date); Calendar now = Calendar.getInstance(); return now.get(Calendar.YEAR) == dest.get(Calendar.YEAR) && now.get(Calendar.MONTH) == dest.get(Calendar.MONTH); } return false; } static String getYearMonth(Date date); static String formateYearMonthDay(Date date); static Date parseYearMonthDay(String timeStr, Date defaultValue); static String formateDateTime(Date date); static Date parseDateTime(String timeStr, Date defaultValue); static final int getCurrentHour(); static final int getLastHour(); static final int getNextHour(); static Date getFirstDayOfCurMonth(); static Date getFirstDayInMonth(Date date); static Date getFirstDayInMonth(int month); static boolean isCurrentMonth(Date date); }### Answer:
@Test public void testGsCurrentMonth(){ assertEquals(true, DateUtil.isCurrentMonth(new Date())); assertEquals(false, DateUtil.isCurrentMonth(new Date(1322197921282L))); } |
### Question:
StandardThreadExecutor extends java.util.concurrent.AbstractExecutorService { public StandardThreadExecutor(){ this(DEFAULT_MIN_SPARE_THREADS,DEFAULT_MAX_THREADS); } StandardThreadExecutor(); StandardThreadExecutor(int minSpareThreads,int maxThreads); StandardThreadExecutor(int minSpareThreads,int maxThreads,int taskQueueCapacity); void execute(Runnable command); int getThreadPriority(); boolean isDaemon(); String getNamePrefix(); int getMaxIdleTime(); int getMaxThreads(); int getMinSpareThreads(); String getName(); void setThreadPriority(int threadPriority); void setDaemon(boolean daemon); void setNamePrefix(String namePrefix); void setMaxIdleTime(int maxIdleTime); void setMaxThreads(int maxThreads); void setMinSpareThreads(int minSpareThreads); void setName(String name); int getActiveCount(); int getSubmittedTasksCount(); long getCompletedTaskCount(); int getCorePoolSize(); int getLargestPoolSize(); int getPoolSize(); int getQueueSize(); int getQueueCapacity(); @Override void shutdown(); @Override List<Runnable> shutdownNow(); @Override boolean isShutdown(); @Override boolean isTerminated(); @Override boolean awaitTermination(long timeout, TimeUnit unit); static final int DEFAULT_MIN_SPARE_THREADS; static final int DEFAULT_MAX_THREADS; }### Answer:
@Test public void testStandardThreadExecutor(){ int minThread = 2; int maxThead = 10; StandardThreadExecutor executor = new StandardThreadExecutor(minThread,maxThead); for(int i=0;i<minThread;i++){ executor.submit(new SleepTask(10000)); } Assert.assertEquals(minThread,executor.getPoolSize()); for(int i=minThread;i<maxThead;i++){ executor.submit(new SleepTask(10000)); } Assert.assertEquals(maxThead,executor.getPoolSize()); for(int i=0;i<maxThead;i++){ executor.submit(new SleepTask(10000)); } Assert.assertEquals(maxThead,executor.getQueueSize()); try{ executor.submit(new SleepTask(10000)); Assert.fail(); }catch(RejectedExecutionException e){ Assert.assertTrue(true); } } |
### Question:
StandardThreadExecutor extends java.util.concurrent.AbstractExecutorService { public int getPoolSize() { return executor.getPoolSize(); } StandardThreadExecutor(); StandardThreadExecutor(int minSpareThreads,int maxThreads); StandardThreadExecutor(int minSpareThreads,int maxThreads,int taskQueueCapacity); void execute(Runnable command); int getThreadPriority(); boolean isDaemon(); String getNamePrefix(); int getMaxIdleTime(); int getMaxThreads(); int getMinSpareThreads(); String getName(); void setThreadPriority(int threadPriority); void setDaemon(boolean daemon); void setNamePrefix(String namePrefix); void setMaxIdleTime(int maxIdleTime); void setMaxThreads(int maxThreads); void setMinSpareThreads(int minSpareThreads); void setName(String name); int getActiveCount(); int getSubmittedTasksCount(); long getCompletedTaskCount(); int getCorePoolSize(); int getLargestPoolSize(); int getPoolSize(); int getQueueSize(); int getQueueCapacity(); @Override void shutdown(); @Override List<Runnable> shutdownNow(); @Override boolean isShutdown(); @Override boolean isTerminated(); @Override boolean awaitTermination(long timeout, TimeUnit unit); static final int DEFAULT_MIN_SPARE_THREADS; static final int DEFAULT_MAX_THREADS; }### Answer:
@Test public void testJdkThreadExecutor(){ int minThread = 2; int maxThead = 10; ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(maxThead); ThreadPoolExecutor executor = new ThreadPoolExecutor(minThread,maxThead, 60, TimeUnit.SECONDS,queue,Executors.defaultThreadFactory()); for(int i=0;i<minThread;i++){ executor.submit(new SleepTask(10000)); } Assert.assertEquals(minThread,executor.getPoolSize()); for(int i=minThread;i<maxThead;i++){ executor.submit(new SleepTask(10000)); } Assert.assertEquals(2,executor.getPoolSize()); Assert.assertEquals(8,queue.size()); for(int i=0;i<maxThead;i++){ executor.submit(new SleepTask(10000)); } Assert.assertEquals(maxThead,executor.getPoolSize()); try{ executor.submit(new SleepTask(10000)); Assert.fail(); }catch(RejectedExecutionException e){ Assert.assertTrue(true); } } |
### Question:
ApacheHttpClient implements ApiHttpClient { @Override public String get(String url) { return get(url,DEFAULT_CHARSET); } ApacheHttpClient(); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize,int minThread,int maxThread); @Deprecated String getURL(String url); @Deprecated void getURL(String url, ByteBuffer bb); @Deprecated int getURL(String url, OutputStream out); @Deprecated String requestURL(String url, Map<String, ?> nameValues); @Deprecated int requestURL(String url, Map<String, ?> nameValues, OutputStream out); @Deprecated String multURL_UTF8(String url, Map<String, Object> nameValues); void setProxyHostPort(String proxyHostPort); String getProxyHostPort(); HttpClient getClient(); @Deprecated String requestURL(String url, Map<String, String> nameValues, Map<String,String> headers); @Deprecated int requestURL(String url, Map<String, ?> nameValues, Map<String,?> headers, OutputStream out); void setAccessLog(AccessLog accessLog); @Override String get(String url); String get(String url,Map<String,String> headers); @Override String get(String url, String charset); String get(String url,Map<String,String> headers, String charset); String getAsync(final String url); String getAsync(final String url, final long timeout); Future<String> getAsyncFuture(final String url); String postAsync(final String url,final Map<String, ?> nameValues); Future<String> postAsyncFuture(final String url,final Map<String, ?> nameValues); byte[] getByte(String url); @Override String post(String url, Map<String, ?> nameValues); @Override String post(String url, Map<String, ?> nameValues, String charset); String post(String url, Map<String, ?> nameValues,Map<String,String> headers, String charset); String postMulti(String url, Map<String, Object> nameValues); String postMulti(String url, Map<String, Object> nameValues,String charset); String postMulti(String url, InputStream in); String postMulti(String url, byte[] buf); T get(String url, ResultConvert<T> c); T get(String url,String charset,ResultConvert<T> c); T post(String url,Map<String, ?> nameValues, ResultConvert<T> c); T post(String url, Map<String, ?> nameValues,String charset, ResultConvert<T> c); T postMulti(String url, Map<String, Object> nameValues,String charset, ResultConvert<T> c); RequestBuilder buildGet(String url); RequestBuilder buildPost(String url); }### Answer:
@Test public void testGet(){ ApiHttpClient client = new ApacheHttpClient(100, 1000, 1000, 1024*100); String result = client.get("http: ApiLogger.debug(result); Assert.assertTrue(!StringUtils.isBlank(result)); }
@Test public void testGetSlow(){ ApiHttpClient client = new ApacheHttpClient(100, 1000, 1000, 1024*100); String result = client.get("http: ApiLogger.debug(result); Assert.assertTrue(StringUtils.isBlank(result)); } |
### Question:
ApacheHttpClient implements ApiHttpClient { @Override public String post(String url, Map<String, ?> nameValues) { return post(url,nameValues,DEFAULT_CHARSET); } ApacheHttpClient(); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize,int minThread,int maxThread); @Deprecated String getURL(String url); @Deprecated void getURL(String url, ByteBuffer bb); @Deprecated int getURL(String url, OutputStream out); @Deprecated String requestURL(String url, Map<String, ?> nameValues); @Deprecated int requestURL(String url, Map<String, ?> nameValues, OutputStream out); @Deprecated String multURL_UTF8(String url, Map<String, Object> nameValues); void setProxyHostPort(String proxyHostPort); String getProxyHostPort(); HttpClient getClient(); @Deprecated String requestURL(String url, Map<String, String> nameValues, Map<String,String> headers); @Deprecated int requestURL(String url, Map<String, ?> nameValues, Map<String,?> headers, OutputStream out); void setAccessLog(AccessLog accessLog); @Override String get(String url); String get(String url,Map<String,String> headers); @Override String get(String url, String charset); String get(String url,Map<String,String> headers, String charset); String getAsync(final String url); String getAsync(final String url, final long timeout); Future<String> getAsyncFuture(final String url); String postAsync(final String url,final Map<String, ?> nameValues); Future<String> postAsyncFuture(final String url,final Map<String, ?> nameValues); byte[] getByte(String url); @Override String post(String url, Map<String, ?> nameValues); @Override String post(String url, Map<String, ?> nameValues, String charset); String post(String url, Map<String, ?> nameValues,Map<String,String> headers, String charset); String postMulti(String url, Map<String, Object> nameValues); String postMulti(String url, Map<String, Object> nameValues,String charset); String postMulti(String url, InputStream in); String postMulti(String url, byte[] buf); T get(String url, ResultConvert<T> c); T get(String url,String charset,ResultConvert<T> c); T post(String url,Map<String, ?> nameValues, ResultConvert<T> c); T post(String url, Map<String, ?> nameValues,String charset, ResultConvert<T> c); T postMulti(String url, Map<String, Object> nameValues,String charset, ResultConvert<T> c); RequestBuilder buildGet(String url); RequestBuilder buildPost(String url); }### Answer:
@Test public void testPost(){ ApiHttpClient client = new ApacheHttpClient(100, 1000, 1000, 1024*100); String result = client.post("http: ApiLogger.debug(result); Assert.assertTrue(!StringUtils.isBlank(result)); }
@Test public void testPostSlow(){ ApiHttpClient client = new ApacheHttpClient(100, 1000, 1000, 1024*100); String result = client.post("http: ApiLogger.debug(result); Assert.assertTrue(StringUtils.isBlank(result)); } |
### Question:
LoginViewModel extends BaseViewModel { public void login() { if (InputHelper.isEmpty(userName) || InputHelper.isEmpty(password)) { AlertUtils.showToastShortMessage(App.getInstance(), "Please input username and password!"); return; } String auth = StringUtils.getBasicAuth(userName, password); execute(true, RestHelper.createRemoteSourceMapper(githubService.login(auth), null), user -> { userManager.startUserSession(user, auth); navigatorHelper.navigateMainActivity(true); }); } @Inject LoginViewModel(GithubService githubService, UserManager userManager); void login(); public String userName; public String password; }### Answer:
@Test public void loginSuccess() throws Exception { String pass = "abc"; User user = sampleUser(1L); String token = StringUtils.getBasicAuth(user.getLogin(), pass); when(githubService.login(any())).thenReturn(successResponse(user)); when(userManager.startUserSession(any(), any())).thenReturn(null); viewModel.setUserName(user.login); viewModel.setPassword(pass); viewModel.login(); verify(stateLiveData, times(1)).setValue(State.loading(null)); verify(stateLiveData, times(1)).setValue(State.success(null)); verify(userManager).startUserSession(user, token); verify(mNavigatorHelper).navigateMainActivity(true); }
@Test public void loginError() throws Exception { when(githubService.login(any())).thenReturn(errorResponse(401, "blah blah")); viewModel.login(); verify(stateLiveData, times(1)).setValue(State.loading(null)); verify(stateLiveData, times(1)).setValue(State.error("blah blah")); verifyZeroInteractions(userManager); } |
### Question:
GirlService { public Girl findOne(Integer id) { return girlRepository.findOne(id); } @Transactional void insertTwo(); void getAge(Integer id); Girl findOne(Integer id); }### Answer:
@Test public void findOne() throws Exception { Girl girl = girlService.findOne(19); Assert.assertEquals(new Integer(14), girl.getAge()); }
@Test public void findOne() throws Exception { } |
### Question:
GirlController { @GetMapping(value = "/girls") public List<Girl> girlList() { logger.info("girlList"); return girlRepository.findAll(); } @GetMapping(value = "/girls") List<Girl> girlList(); @PostMapping(value = "/girls") Object girlAdd(@Valid Girl girl, BindingResult bindingResult); @GetMapping(value = "/girl/{id}") Girl girlFindOne(@PathVariable("id") Integer id); @PutMapping(value = "/girls/{id}") Girl girlUpdate(@PathVariable("id") Integer id,
@RequestParam("name") String name,
@RequestParam("age") Integer age); @DeleteMapping(value = "/girls/{id}") void girlDelete(@PathVariable("id") Integer id); @GetMapping(value = "/girls/age/{age}") List<Girl> girlListByAge(@PathVariable("age") Integer age); @PostMapping(value = "/girls/two") void girlTwo(); @GetMapping(value = "/girls/getAge/{id}") void getAge(@PathVariable("id") Integer id); }### Answer:
@Test public void girlList() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/girls")) .andExpect(MockMvcResultMatchers.status().isOk()); } |
### Question:
RedisLockUtil { public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime) { String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME_UNIT, expireTime); return LOCK_SUCCESS.equals(result); } static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime); static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId); }### Answer:
@Test public void tryGetDistributedLockTest() throws Exception { String key = "testDistributedLockKey"; String requestId = UUID.randomUUID().toString(); boolean getDistributedLockResult = RedisLockUtil.tryGetDistributedLock(JEDIS, key, requestId, 60 * 1000 * 60); System.out.println("getDistributedLockResult=" + getDistributedLockResult); Assert.assertTrue(getDistributedLockResult); } |
### Question:
RedisLockUtil { public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId) { String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId)); return RELEASE_SUCCESS.equals(result); } static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime); static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId); }### Answer:
@Test public void releaseDistributedLockTest() throws Exception { String key = "testDistributedLockKey"; String requestId = UUID.randomUUID().toString(); boolean releaseDistributedLockResult = RedisLockUtil.releaseDistributedLock(JEDIS, key, requestId); System.out.println("releaseDistributedLockResult=" + releaseDistributedLockResult); Assert.assertTrue(releaseDistributedLockResult); } |
### Question:
HttpUtil { public static String get(String requestUrl) { HttpGet get = new HttpGet(requestUrl); return executeRequest(get, Charset.forName(DEFAULT_ENCODING)); } static String get(String requestUrl); static String post(String requestUrl, Object data, ContentType contentType); static String uploadFile(String requestUrl, Object data); }### Answer:
@Test public void get() throws UnsupportedEncodingException { GetUserRequest request = new GetUserRequest("/user/getUserList"); request.setUserId(1L); request.setUsername("李白"); String result = HttpUtil.get(request.composeUrl(baseUrl, request.getQueryParameters())); AbstractResponse response = JacksonUtil.readValue(result, request.getResponseClass()); log.info(response.toString()); } |
### Question:
HttpUtil { public static String post(String requestUrl, Object data, ContentType contentType) { if (StringUtils.isBlank(requestUrl)) { throw new RuntimeException("requestUrl cann't be null"); } if (contentType == null) { throw new RuntimeException("contentType cann't be null"); } HttpPost post = new HttpPost(requestUrl); if (data != null) { StringEntity entity = new StringEntity(data.toString(), contentType); post.setEntity(entity); } logger.info("HttpClient request uri -> " + requestUrl); logger.info("HttpClient request body -> " + data); return executeRequest(post, contentType.getCharset()); } static String get(String requestUrl); static String post(String requestUrl, Object data, ContentType contentType); static String uploadFile(String requestUrl, Object data); }### Answer:
@Test public void postFormData() throws UnsupportedEncodingException { UpdateUserRequest request = new UpdateUserRequest("/user/updateUser"); request.setMethod(MethodTypeEnum.POST); request.setHttpContentType(ContentType.APPLICATION_FORM_URLENCODED); request.setUserId(1L); request.setUsername("李太白"); String result = HttpUtil.post(request.composeUrl(baseUrl, request.getQueryParameters()), null, request.getHttpContentType()); AbstractResponse response = JacksonUtil.readValue(result, request.getResponseClass()); log.info(response.toString()); }
@Test public void postJsonObject() throws UnsupportedEncodingException { CreateUserRequest request = new CreateUserRequest("/user/createUser"); request.setMethod(MethodTypeEnum.POST); request.setHttpContentType(ContentType.APPLICATION_JSON); CreateUserRequest.CreateUserBody body = new CreateUserRequest.CreateUserBody(); body.setUsername("白居易"); request.setBody(body); String result = HttpUtil.post(request.composeUrl(baseUrl, request.getQueryParameters()), JacksonUtil.toJson(request.getBody()), request.getHttpContentType()); AbstractResponse response = JacksonUtil.readValue(result, request.getResponseClass()); log.info(response.toString()); } |
### Question:
HttpUtil { public static String uploadFile(String requestUrl, Object data) { if (StringUtils.isBlank(requestUrl)) { throw new RuntimeException("requestUrl cann't be null"); } MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setCharset(Charset.forName(DEFAULT_ENCODING)); ContentType contentType = ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), DEFAULT_ENCODING); HttpPost post = new HttpPost(requestUrl); if (data != null) { if (data instanceof File) { FileBody fileBody = new FileBody((File) data); multipartEntityBuilder.addPart("file", fileBody); } else { Field[] fields = data.getClass().getDeclaredFields(); try { for (Field field : fields) { field.setAccessible(true); Object fieldValue = field.get(data); if (fieldValue != null) { if (File.class.equals(field.getType())) { FileBody fileBody = new FileBody((File) field.get(data)); multipartEntityBuilder.addPart(field.getName(), fileBody); } else { StringBody stringBody = new StringBody(field.get(data).toString(), contentType); multipartEntityBuilder.addPart(field.getName(), stringBody); } } } } catch (IllegalAccessException e) { logger.error("Upload file IllegalAccessException -> " + e); throw new RuntimeException("Upload file IllegalAccessException"); } } HttpEntity reqEntity = multipartEntityBuilder.build(); post.setEntity(reqEntity); } logger.info("HttpClient request uri -> " + requestUrl); logger.info("HttpClient request body -> " + data); return executeRequest(post, Charset.forName(DEFAULT_ENCODING)); } static String get(String requestUrl); static String post(String requestUrl, Object data, ContentType contentType); static String uploadFile(String requestUrl, Object data); }### Answer:
@Test public void uploadFile() throws UnsupportedEncodingException { UploadFileRequest request = new UploadFileRequest("/user/uploadFile"); request.setMethod(MethodTypeEnum.POST); request.setHttpContentType(ContentType.MULTIPART_FORM_DATA); UploadFileRequest.UploadFileBody body = new UploadFileRequest.UploadFileBody(); body.setFile(new File("D:\\workspace\\idea\\individual\\springboot-learn\\springboot-http-client\\src\\main\\resources\\static\\images.jpg")); request.setBody(body); String result = HttpUtil.uploadFile(request.composeUrl(baseUrl, request.getQueryParameters()), request.getBody()); AbstractResponse response = JacksonUtil.readValue(result, request.getResponseClass()); log.info(response.toString()); } |
### Question:
ImageUtil { public static List<String> generateThumbnail2Directory(String path, String... files) throws IOException { return generateThumbnail2Directory(DEFAULT_SCALE, path, files); } static List<String> generateThumbnail2Directory(String path, String... files); static List<String> generateThumbnail2Directory(double scale, String pathname, String... files); static void generateDirectoryThumbnail(String pathname); static void generateDirectoryThumbnail(String pathname, double scale); static String appendSuffix(String fileName, String suffix); static boolean isImage(String extension); static String getFileExtention(String fileName); }### Answer:
@Test public void testGenerateThumbnail2Directory() throws IOException { String path = "D:\\workspace\\idea\\individual\\springboot-learn\\springboot-thumbnail\\image"; String[] files = new String[]{ "image/1.jpg", "image/2.jpg" }; List<String> list = ImageUtil.generateThumbnail2Directory(path, files); System.out.println(list); } |
### Question:
ImageUtil { public static void generateDirectoryThumbnail(String pathname) throws IOException { generateDirectoryThumbnail(pathname, DEFAULT_SCALE); } static List<String> generateThumbnail2Directory(String path, String... files); static List<String> generateThumbnail2Directory(double scale, String pathname, String... files); static void generateDirectoryThumbnail(String pathname); static void generateDirectoryThumbnail(String pathname, double scale); static String appendSuffix(String fileName, String suffix); static boolean isImage(String extension); static String getFileExtention(String fileName); }### Answer:
@Test public void testGenerateDirectoryThumbnail() throws IOException { String path = "D:\\workspace\\idea\\individual\\springboot-learn\\springboot-thumbnail\\image"; ImageUtil.generateDirectoryThumbnail(path); } |
### Question:
ReflectionUtil { public static @NotNull List<String> getArgsForMethod(@NotNull List<String> args, @NotNull Method method) { if (args.size() == 0 && method.getParameterCount() == 0) { return Collections.emptyList(); } List<String> argsOut = new ArrayList<>(); if (args.size() < method.getParameterCount()) { argsOut.addAll(args); } else { for (int i = 0; i < method.getParameterCount(); i++) { argsOut.add(args.get(i)); } } return argsOut; } static @NotNull List<String> getArgsForMethod(@NotNull List<String> args, @NotNull Method method); static @NotNull String getFormattedMethodSignature(Method method); static @NotNull String getMethodId(Method method); static @NotNull String getArgMismatchString(Method method); }### Answer:
@Test public void ensureArgsForMethodAccurate() throws NoSuchMethodException { List<String> inputStr = Arrays.asList("1", "nextMethod", "param", "param2"); Method testClass1234 = ReflTestClass.ReflSubClass.class.getMethod("get1234", int.class); List<String> out = ReflectionUtil.getArgsForMethod(inputStr, testClass1234); assertEquals(1, out.size()); assertEquals("1", out.get(0)); inputStr = Arrays.asList("1", "2", "3"); Method lotsOfParams = ReflTestClass.class.getMethod("methodWithLotsOfParams", int.class, int.class, int.class, int.class, int.class, int.class, int.class); out = ReflectionUtil.getArgsForMethod(inputStr, lotsOfParams); assertEquals(inputStr.size(), out.size()); for (int i = 0; i < inputStr.size(); i++) { assertEquals(inputStr.get(i), out.get(i)); } inputStr = new ArrayList<>(); Method noParams = ReflTestClass.class.getMethod("getSomeNumbers"); out = ReflectionUtil.getArgsForMethod(inputStr, noParams); assertEquals(0, out.size()); } |
### Question:
TypeHandler { public @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String> input) throws InputException { return instantiateTypes(classes, input, null); } TypeHandler(Logger logger); @Nullable String getOutputFor(@Nullable Object object); @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String> input); @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String> input, @Nullable PlatformSender<?> sender); boolean registerHandler(Handler handler); @Nullable IHandler getIHandlerForClass(Class<?> clazz); @NotNull Collection<IHandler> getAllInputHandlers(); @NotNull Collection<OHandler> getAllOutputHandlers(); }### Answer:
@Test public void ensurePolymorphicInput() throws InputException { Class[] requestedTypes = {AnEnum.class, AnEnum.class}; String[] inputArgs = {"VAL_1", "VAL_5"}; Object[] output = typeHandler.instantiateTypes(requestedTypes, Arrays.asList(inputArgs)); assertTrue(output[0] instanceof AnEnum); assertTrue(output[1] instanceof AnEnum); Assertions.assertEquals(AnEnum.VAL_1, output[0]); Assertions.assertEquals(AnEnum.VAL_5, output[1]); }
@Test public void ensureThrowsOnNoSuchIHandler() { Assertions.assertThrows(InputException.class, () -> { Class[] requestedType = {CASE_NEVER_WILL_BE_REGISTERED}; typeHandler.instantiateTypes(requestedType, Collections.singletonList("blah")); }); }
@Test public void ensureNullAlwaysAvailable() throws InputException { Object[] array = typeHandler.instantiateTypes(new Class[]{Object.class}, Collections.singletonList(TypeHandler.NULL_INSTANCE_KEYWORD)); Object instance = array[0]; assertNull(instance); } |
### Question:
TypeHandler { public @Nullable String getOutputFor(@Nullable Object object) { if (object == null) { return null; } OHandler handler = getOHandlerForClass(object.getClass()); if (handler != null) { return handler.getFormattedOutput(object); } else { return String.valueOf(object); } } TypeHandler(Logger logger); @Nullable String getOutputFor(@Nullable Object object); @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String> input); @NotNull Object[] instantiateTypes(Class<?>[] classes, List<String> input, @Nullable PlatformSender<?> sender); boolean registerHandler(Handler handler); @Nullable IHandler getIHandlerForClass(Class<?> clazz); @NotNull Collection<IHandler> getAllInputHandlers(); @NotNull Collection<OHandler> getAllOutputHandlers(); }### Answer:
@Test public void ensureNullInputGivesNullOutput() { String output = typeHandler.getOutputFor(null); assertNull(output); } |
### Question:
ReflectionUtil { public static @NotNull String getMethodId(Method method) { return getFormattedMethodSignature(method).replaceAll(" ", ""); } static @NotNull List<String> getArgsForMethod(@NotNull List<String> args, @NotNull Method method); static @NotNull String getFormattedMethodSignature(Method method); static @NotNull String getMethodId(Method method); static @NotNull String getArgMismatchString(Method method); }### Answer:
@Test public void ensureNoWhitespaceInMethodIds() throws NoSuchMethodException { Method method = ReflTestClass.class.getMethod("getSomeNumbers"); String id = ReflectionUtil.getMethodId(method); long whitespaceCount = id.chars() .filter(Character::isWhitespace) .count(); if (whitespaceCount != 0) { System.out.println("Illegal whitespace chars found in id: " + id); } assertEquals(0, whitespaceCount); } |
### Question:
ReflectionUtil { public static @NotNull String getArgMismatchString(Method method) { final String methodName = method.getName(); final Class<?> returnType = method.getReturnType(); final String returnTypeName = returnType.getSimpleName(); String returnInfo; if (returnType.equals(Void.TYPE)) { returnInfo = "returns void."; } else if (startsWithVowel.test(returnTypeName)) { returnInfo = "returns an " + returnTypeName; } else { returnInfo = "returns a " + returnTypeName; } return "Method " + methodName + " requires " + method.getParameterCount() + " args and " + returnInfo + "\n" + ReflectionUtil.getFormattedMethodSignature(method); } static @NotNull List<String> getArgsForMethod(@NotNull List<String> args, @NotNull Method method); static @NotNull String getFormattedMethodSignature(Method method); static @NotNull String getMethodId(Method method); static @NotNull String getArgMismatchString(Method method); }### Answer:
@Test public void validateArgsMismatchContent() throws NoSuchMethodException { BiConsumer<Method, String> validateBasics = (method, s) -> { s = s.toLowerCase(); assertTrue(s.contains(method.getName().toLowerCase())); assertTrue(s.contains(method.getReturnType().getSimpleName().toLowerCase())); assertTrue(s.contains(String.valueOf(method.getParameterCount()))); }; Method voidReturn = ReflTestClass.class.getMethod("methodWithLotsOfParams", int.class, int.class, int.class, int.class, int.class, int.class, int.class); String voidReturnDescriptor = ReflectionUtil.getArgMismatchString(voidReturn); validateBasics.accept(voidReturn, voidReturnDescriptor); assertTrue(voidReturnDescriptor.toLowerCase().contains("void")); Method getSubClass = ReflTestClass.class.getMethod("getSubClass"); String getterDescriptor = ReflectionUtil.getArgMismatchString(getSubClass); validateBasics.accept(getSubClass, getterDescriptor); assertTrue(getterDescriptor.toLowerCase().contains(" a ")); Method getSomeNumbers = ReflTestClass.class.getMethod("getSomeNumbers"); String someNumbersDescriptor = ReflectionUtil.getArgMismatchString(getSomeNumbers); validateBasics.accept(getSomeNumbers, someNumbersDescriptor); assertTrue(someNumbersDescriptor.toLowerCase().contains(" an ")); } |
### Question:
MethodMap { public @NotNull Set<Method> getAllMethods() { return new HashSet<>(backingMap.values()); } private MethodMap(); MethodMap(@NotNull Class<?> clazz); @Nullable Method getById(String identifier); boolean containsId(String identifier); @NotNull Set<Method> getAllMethods(); @NotNull Set<String> getAllIds(); @NotNull Class<?> getMappedClass(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static final MethodMap EMPTY; }### Answer:
@Test public void testContainsMethods() { MethodMap methodmap = new MethodMap(TESTER); Set<Method> mappedMethods = methodmap.getAllMethods(); long missing = Arrays.stream(TESTER.getMethods()) .filter(m -> Modifier.isPublic(m.getModifiers())) .filter(m -> !mappedMethods.contains(m)) .peek(m -> System.out.println(m.getName() + " MISSING!")) .count(); assertEquals(0, missing); } |
### Question:
MethodMap { public @NotNull Set<String> getAllIds() { return new HashSet<>(backingMap.keySet()); } private MethodMap(); MethodMap(@NotNull Class<?> clazz); @Nullable Method getById(String identifier); boolean containsId(String identifier); @NotNull Set<Method> getAllMethods(); @NotNull Set<String> getAllIds(); @NotNull Class<?> getMappedClass(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static final MethodMap EMPTY; }### Answer:
@Test public void testContainsIds() { MethodMap methodMap = new MethodMap(TESTER); Set<String> identifiers = methodMap.getAllIds(); long missing = Arrays.stream(TESTER.getMethods()) .filter(m -> Modifier.isPublic(m.getModifiers())) .map(ReflectionUtil::getMethodId) .filter(s -> !identifiers.contains(s)) .peek(s -> System.out.println("Method map does not contain expected: " + s)) .count(); assertEquals(0, missing); } |
### Question:
MethodMap { @Override public int hashCode() { return 67 * backingMap.hashCode(); } private MethodMap(); MethodMap(@NotNull Class<?> clazz); @Nullable Method getById(String identifier); boolean containsId(String identifier); @NotNull Set<Method> getAllMethods(); @NotNull Set<String> getAllIds(); @NotNull Class<?> getMappedClass(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static final MethodMap EMPTY; }### Answer:
@Test public void ensureHashcodes() { MethodMap map1 = new MethodMap(TESTER); MethodMap map2 = new MethodMap(TESTER); assertEquals(map1.hashCode(), map2.hashCode()); } |
### Question:
FileDownloader { public static void setup(Context context) { FileDownloadHelper.holdContext(context.getApplicationContext()); } static void setup(Context context); static DownloadMgrInitialParams.InitCustomMaker setupOnApplicationOnCreate(Application application); static void init(final Context context); static void init(final Context context,
final DownloadMgrInitialParams.InitCustomMaker maker); static FileDownloader getImpl(); static void setGlobalPost2UIInterval(final int intervalMillisecond); static void setGlobalHandleSubPackageSize(final int packageSize); static void enableAvoidDropFrame(); static void disableAvoidDropFrame(); static boolean isEnabledAvoidDropFrame(); BaseDownloadTask create(final String url); boolean start(final FileDownloadListener listener, final boolean isSerial); void pause(final FileDownloadListener listener); void pauseAll(); int pause(final int id); boolean clear(final int id, final String targetFilePath); void clearAllTaskData(); long getSoFar(final int downloadId); long getTotal(final int id); byte getStatusIgnoreCompleted(final int id); byte getStatus(final String url, final String path); byte getStatus(final int id, final String path); int replaceListener(String url, FileDownloadListener listener); int replaceListener(String url, String path, FileDownloadListener listener); int replaceListener(int id, FileDownloadListener listener); void bindService(); void bindService(final Runnable runnable); void unBindService(); boolean unBindServiceIfIdle(); boolean isServiceConnected(); void addServiceConnectListener(final FileDownloadConnectListener listener); void removeServiceConnectListener(final FileDownloadConnectListener listener); void startForeground(int id, Notification notification); void stopForeground(boolean removeNotification); @SuppressWarnings("UnusedParameters") boolean setTaskCompleted(String url, String path, long totalBytes); @SuppressWarnings("UnusedParameters") boolean setTaskCompleted(@SuppressWarnings("deprecation") List<FileDownloadTaskAtom> taskAtomList); boolean setMaxNetworkThreadCount(final int count); FileDownloadLine insureServiceBind(); FileDownloadLineAsync insureServiceBindAsync(); }### Answer:
@Test public void setup_withContext_hold() { FileDownloader.setup(application); Assert.assertEquals(application.getApplicationContext(), FileDownloadHelper.getAppContext()); } |
### Question:
FileDownloader { public static DownloadMgrInitialParams.InitCustomMaker setupOnApplicationOnCreate(Application application) { final Context context = application.getApplicationContext(); FileDownloadHelper.holdContext(context); DownloadMgrInitialParams.InitCustomMaker customMaker = new DownloadMgrInitialParams.InitCustomMaker(); CustomComponentHolder.getImpl().setInitCustomMaker(customMaker); return customMaker; } static void setup(Context context); static DownloadMgrInitialParams.InitCustomMaker setupOnApplicationOnCreate(Application application); static void init(final Context context); static void init(final Context context,
final DownloadMgrInitialParams.InitCustomMaker maker); static FileDownloader getImpl(); static void setGlobalPost2UIInterval(final int intervalMillisecond); static void setGlobalHandleSubPackageSize(final int packageSize); static void enableAvoidDropFrame(); static void disableAvoidDropFrame(); static boolean isEnabledAvoidDropFrame(); BaseDownloadTask create(final String url); boolean start(final FileDownloadListener listener, final boolean isSerial); void pause(final FileDownloadListener listener); void pauseAll(); int pause(final int id); boolean clear(final int id, final String targetFilePath); void clearAllTaskData(); long getSoFar(final int downloadId); long getTotal(final int id); byte getStatusIgnoreCompleted(final int id); byte getStatus(final String url, final String path); byte getStatus(final int id, final String path); int replaceListener(String url, FileDownloadListener listener); int replaceListener(String url, String path, FileDownloadListener listener); int replaceListener(int id, FileDownloadListener listener); void bindService(); void bindService(final Runnable runnable); void unBindService(); boolean unBindServiceIfIdle(); boolean isServiceConnected(); void addServiceConnectListener(final FileDownloadConnectListener listener); void removeServiceConnectListener(final FileDownloadConnectListener listener); void startForeground(int id, Notification notification); void stopForeground(boolean removeNotification); @SuppressWarnings("UnusedParameters") boolean setTaskCompleted(String url, String path, long totalBytes); @SuppressWarnings("UnusedParameters") boolean setTaskCompleted(@SuppressWarnings("deprecation") List<FileDownloadTaskAtom> taskAtomList); boolean setMaxNetworkThreadCount(final int count); FileDownloadLine insureServiceBind(); FileDownloadLineAsync insureServiceBindAsync(); }### Answer:
@Test public void setupOnApplicationOnCreate_withContext_hold() { FileDownloader.setupOnApplicationOnCreate(application); Assert.assertEquals(application.getApplicationContext(), FileDownloadHelper.getAppContext()); } |
### Question:
DownloadRunnable implements Runnable { @Override public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); FileDownloadConnection connection = null; final long beginOffset = connectTask.getProfile().currentOffset; boolean isConnected = false; do { try { if (paused) { return; } isConnected = false; connection = connectTask.connect(); final int code = connection.getResponseCode(); if (FileDownloadLog.NEED_LOG) { FileDownloadLog.d(this, "the connection[%d] for %d, is connected %s with code[%d]", connectionIndex, downloadId, connectTask.getProfile(), code); } if (code != HttpURLConnection.HTTP_PARTIAL && code != HttpURLConnection.HTTP_OK) { throw new SocketException(FileDownloadUtils. formatString("Connection failed with request[%s] response[%s] http-state[%d] on task[%d-%d], " + "which is changed after verify connection, so please try again.", connectTask.getRequestHeader(), connection.getResponseHeaderFields(), code, downloadId, connectionIndex)); } isConnected = true; final FetchDataTask.Builder builder = new FetchDataTask.Builder(); if (paused) return; fetchDataTask = builder .setDownloadId(downloadId) .setConnectionIndex(connectionIndex) .setCallback(callback) .setHost(this) .setWifiRequired(isWifiRequired) .setConnection(connection) .setConnectionProfile(this.connectTask.getProfile()) .setPath(path) .build(); fetchDataTask.run(); if (paused){ fetchDataTask.pause(); } break; } catch (IllegalAccessException | IOException | FileDownloadGiveUpRetryException | IllegalArgumentException e) { if (callback.isRetry(e)) { if (!isConnected) { callback.onRetry(e, 0); } else if (fetchDataTask != null) { final long invalidIncreaseBytes = fetchDataTask.currentOffset - beginOffset; callback.onRetry(e, invalidIncreaseBytes); } else { FileDownloadLog.w(this, "it is valid to retry and connection is valid but" + " create fetch-data-task failed, so give up directly with %s", e); callback.onError(e); break; } } else { callback.onError(e); break; } } finally { if (connection != null) connection.ending(); } } while (true); } private DownloadRunnable(int id, int connectionIndex, ConnectTask connectTask,
ProcessCallback callback, boolean isWifiRequired, String path); void pause(); void discard(); @Override void run(); }### Answer:
@Test public void run_withConnectFailed_retry() throws IOException, IllegalAccessException { when(mockConnectTask.connect()).thenThrow(mockIOException); downloadRunnable.run(); verify(mockCallback).onRetry(mockIOException, 0); }
@Test public void run_responseCodeNotMet_error() throws IOException, IllegalAccessException { final FileDownloadConnection connection = mock(FileDownloadConnection.class); when(connection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_PRECON_FAILED); when(mockConnectTask.connect()).thenReturn(connection); downloadRunnable.run(); verify(mockCallback).onRetry(any(Exception.class), anyLong()); verify(mockCallback).onError(any(Exception.class)); } |
### Question:
ErrorParser { @NonNull static StripeError parseError(String rawError) { StripeError stripeError = new StripeError(); try { JSONObject jsonError = new JSONObject(rawError); JSONObject errorObject = jsonError.getJSONObject(FIELD_ERROR); stripeError.charge = errorObject.optString(FIELD_CHARGE); stripeError.code = errorObject.optString(FIELD_CODE); stripeError.decline_code = errorObject.optString(FIELD_DECLINE_CODE); stripeError.message = errorObject.optString(FIELD_MESSAGE); stripeError.param = errorObject.optString(FIELD_PARAM); stripeError.type = errorObject.optString(FIELD_TYPE); } catch (JSONException jsonException) { stripeError.message = MALFORMED_RESPONSE_MESSAGE; } return stripeError; } }### Answer:
@Test public void parseError_withInvalidRequestError_createsCorrectObject() { ErrorParser.StripeError parsedStripeError = ErrorParser.parseError(RAW_INVALID_REQUEST_ERROR); String errorMessage = "The Stripe API is only accessible over HTTPS. " + "Please see <https: assertEquals(errorMessage, parsedStripeError.message); assertEquals("invalid_request_error", parsedStripeError.type); assertEquals("", parsedStripeError.param); }
@Test public void parseError_withNoErrorMessage_addsInvalidResponseMessage() { ErrorParser.StripeError badStripeError = ErrorParser.parseError(RAW_INCORRECT_FORMAT_ERROR); assertEquals(ErrorParser.MALFORMED_RESPONSE_MESSAGE, badStripeError.message); assertNull(badStripeError.type); } |
### Question:
ModelUtils { static boolean isWholePositiveNumber(@Nullable String value) { return value != null && TextUtils.isDigitsOnly(value); } }### Answer:
@Test public void wholePositiveNumberShouldPassWithLeadingZero() { assertTrue(ModelUtils.isWholePositiveNumber("000")); }
@Test public void wholePositiveNumberShouldFailIfNegative() { assertFalse(ModelUtils.isWholePositiveNumber("-1")); }
@Test public void wholePositiveNumberShouldFailIfLetters() { assertFalse(ModelUtils.isWholePositiveNumber("1a")); }
@Test public void wholePositiveNumberShouldFailNull() { assertFalse(ModelUtils.isWholePositiveNumber(null)); }
@Test public void wholePositiveNumberShouldPassIfEmpty() { assertTrue(ModelUtils.isWholePositiveNumber("")); }
@Test public void wholePositiveNumberShouldPass() { assertTrue(ModelUtils.isWholePositiveNumber("123")); } |
### Question:
ModelUtils { static int normalizeYear(int year, Calendar now) { if (year < 100 && year >= 0) { String currentYear = String.valueOf(now.get(Calendar.YEAR)); String prefix = currentYear.substring(0, currentYear.length() - 2); year = Integer.parseInt(String.format(Locale.US, "%s%02d", prefix, year)); } return year; } }### Answer:
@Test public void normalizeSameCenturyShouldPass() { Calendar now = Calendar.getInstance(); int year = 1997; now.set(Calendar.YEAR, year); assertEquals(ModelUtils.normalizeYear(97, now), year); }
@Test public void normalizeDifferentCenturyShouldFail() { Calendar now = Calendar.getInstance(); int year = 1997; now.set(Calendar.YEAR, year); assertNotEquals(ModelUtils.normalizeYear(97, now), 2097); } |
### Question:
SourceCodeVerification extends StripeJsonModel { @NonNull @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); try{ jsonObject.put(FIELD_ATTEMPTS_REMAINING, mAttemptsRemaining); StripeJsonUtils.putStringIfNotNull(jsonObject, FIELD_STATUS, mStatus); } catch (JSONException ignored) { } return jsonObject; } SourceCodeVerification(int attemptsRemaining, @Status String status); int getAttemptsRemaining(); @Status String getStatus(); @NonNull @Override Map<String, Object> toMap(); @NonNull @Override JSONObject toJson(); @Nullable static SourceCodeVerification fromString(@Nullable String jsonString); @Nullable static SourceCodeVerification fromJson(@Nullable JSONObject jsonObject); }### Answer:
@Test public void fromJsonString_backToJson_createsIdenticalElement() { try { JSONObject rawConversion = new JSONObject(EXAMPLE_JSON_CODE_VERIFICATION); assertJsonEquals(rawConversion, mCodeVerification.toJson()); } catch (JSONException jsonException) { fail("Test Data failure: " + jsonException.getLocalizedMessage()); } } |
### Question:
SourceCodeVerification extends StripeJsonModel { @NonNull @Override public Map<String, Object> toMap() { Map<String, Object> hashMap = new HashMap<>(); hashMap.put(FIELD_ATTEMPTS_REMAINING, mAttemptsRemaining); if (mStatus != null) { hashMap.put(FIELD_STATUS, mStatus); } return hashMap; } SourceCodeVerification(int attemptsRemaining, @Status String status); int getAttemptsRemaining(); @Status String getStatus(); @NonNull @Override Map<String, Object> toMap(); @NonNull @Override JSONObject toJson(); @Nullable static SourceCodeVerification fromString(@Nullable String jsonString); @Nullable static SourceCodeVerification fromJson(@Nullable JSONObject jsonObject); }### Answer:
@Test public void fromJsonString_toMap_createsExpectedMap() { assertMapEquals(EXAMPLE_MAP_CODE_VERIFICATION, mCodeVerification.toMap()); } |
### Question:
SourceReceiver extends StripeJsonModel { @NonNull @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); StripeJsonUtils.putStringIfNotNull(jsonObject, FIELD_ADDRESS, mAddress); try { jsonObject.put(FIELD_AMOUNT_CHARGED, mAmountCharged); jsonObject.put(FIELD_AMOUNT_RECEIVED, mAmountReceived); jsonObject.put(FIELD_AMOUNT_RETURNED, mAmountReturned); } catch (JSONException jsonException) { return jsonObject; } return jsonObject; } SourceReceiver(String address,
long amountCharged,
long amountReceived,
long amountReturned); String getAddress(); void setAddress(String address); long getAmountCharged(); void setAmountCharged(long amountCharged); long getAmountReceived(); void setAmountReceived(long amountReceived); long getAmountReturned(); void setAmountReturned(long amountReturned); @NonNull @Override Map<String, Object> toMap(); @NonNull @Override JSONObject toJson(); @Nullable static SourceReceiver fromString(@Nullable String jsonString); @Nullable static SourceReceiver fromJson(@Nullable JSONObject jsonObject); }### Answer:
@Test public void fromJsonString_backToJson_createsIdenticalElement() { try { JSONObject rawConversion = new JSONObject(EXAMPLE_JSON_RECEIVER); assertJsonEquals(rawConversion, mSourceReceiver.toJson()); } catch (JSONException jsonException) { fail("Test Data failure: " + jsonException.getLocalizedMessage()); } } |
### Question:
SourceReceiver extends StripeJsonModel { @NonNull @Override public Map<String, Object> toMap() { Map<String, Object> hashMap = new HashMap<>(); if (!StripeTextUtils.isBlank(mAddress)) { hashMap.put(FIELD_ADDRESS, mAddress); } hashMap.put(FIELD_ADDRESS, mAddress); hashMap.put(FIELD_AMOUNT_CHARGED, mAmountCharged); hashMap.put(FIELD_AMOUNT_RECEIVED, mAmountReceived); hashMap.put(FIELD_AMOUNT_RETURNED, mAmountReturned); return hashMap; } SourceReceiver(String address,
long amountCharged,
long amountReceived,
long amountReturned); String getAddress(); void setAddress(String address); long getAmountCharged(); void setAmountCharged(long amountCharged); long getAmountReceived(); void setAmountReceived(long amountReceived); long getAmountReturned(); void setAmountReturned(long amountReturned); @NonNull @Override Map<String, Object> toMap(); @NonNull @Override JSONObject toJson(); @Nullable static SourceReceiver fromString(@Nullable String jsonString); @Nullable static SourceReceiver fromJson(@Nullable JSONObject jsonObject); }### Answer:
@Test public void fromJsonString_toMap_createsExpectedMap() { assertMapEquals(EXAMPLE_MAP_RECEIVER, mSourceReceiver.toMap()); } |
### Question:
StripeSourceTypeModel extends StripeJsonModel { @Nullable static Map<String, Object> jsonObjectToMapWithoutKeys( @Nullable JSONObject jsonObject, @Nullable Set<String> omitKeys) { if (jsonObject == null) { return null; } Set<String> keysToOmit = omitKeys == null ? new HashSet<String>() : omitKeys; Map<String, Object> map = new HashMap<>(); Iterator<String> keyIterator = jsonObject.keys(); while (keyIterator.hasNext()) { String key = keyIterator.next(); Object value = jsonObject.opt(key); if (NULL.equals(value) || value == null || keysToOmit.contains(key)) { continue; } map.put(key, value); } if (map.isEmpty()) { return null; } else { return map; } } StripeSourceTypeModel(); @NonNull Map<String, Object> getAdditionalFields(); }### Answer:
@Test public void jsonObjectToMapWithoutKeys_whenHasKeyInput_returnsMapOmittingKeys() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("a_key", "a_value"); jsonObject.put("b_key", "b_value"); jsonObject.put("c_key", "c_value"); jsonObject.put("d_key", "d_value"); } catch (JSONException unexpected) { fail("Unexpected error: " + unexpected.getLocalizedMessage()); } Set<String> omitKeys = new HashSet<String>() {{ add("a_key"); add("d_key"); }}; Map<String, Object> resultMap = jsonObjectToMapWithoutKeys(jsonObject, omitKeys); assertNotNull(resultMap); assertEquals(2, resultMap.size()); assertEquals("b_value", resultMap.get("b_key")); assertEquals("c_value", resultMap.get("c_key")); assertFalse(resultMap.containsKey("a_key")); assertFalse(resultMap.containsKey("d_key")); }
@Test public void jsonObjectToMapWithoutKeys_whenAllKeysGiven_returnsNull() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("a_key", "a_value"); jsonObject.put("b_key", "b_value"); } catch (JSONException unexpected) { fail("Unexpected error: " + unexpected.getLocalizedMessage()); } Set<String> omitKeys = new HashSet<String>() {{ add("a_key"); add("b_key"); }}; Map<String, Object> resultMap = jsonObjectToMapWithoutKeys(jsonObject, omitKeys); assertNull(resultMap); }
@Test public void jsonObjectToMapWithoutKeys_whenOtherKeysGiven_returnsFullMap() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("a_key", "a_value"); jsonObject.put("b_key", "b_value"); } catch (JSONException unexpected) { fail("Unexpected error: " + unexpected.getLocalizedMessage()); } Set<String> omitKeys = new HashSet<String>() {{ add("c_key"); add("d_key"); }}; Map<String, Object> resultMap = jsonObjectToMapWithoutKeys(jsonObject, omitKeys); assertNotNull(resultMap); assertEquals("a_value", resultMap.get("a_key")); assertEquals("b_value", resultMap.get("b_key")); } |
### Question:
StripeJsonUtils { @Nullable static String getString( @NonNull JSONObject jsonObject, @NonNull @Size(min = 1) String fieldName) throws JSONException { return nullIfNullOrEmpty(jsonObject.getString(fieldName)); } }### Answer:
@Test public void getString_whenFieldContainsRawNull_returnsNull() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("key", "null"); assertNull(StripeJsonUtils.getString(jsonObject, "key")); } catch (JSONException jex) { fail("No exception expected"); } }
@Test(expected = JSONException.class) public void getString_whenFieldNotPresent_throwsJsonException() throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put("key", "value"); StripeJsonUtils.getString(jsonObject, "differentKey"); fail("Expected an exception."); }
@Test public void getString_whenFieldPresent_findsAndReturnsField() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("key", "value"); assertEquals("value", StripeJsonUtils.getString(jsonObject, "key")); } catch (JSONException jex) { fail("No exception expected"); } } |
### Question:
StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoJsonObject( @Nullable JSONObject jsonObject, @Nullable Map<String, Object> additionalFields) { if (jsonObject == null || additionalFields == null || additionalFields.isEmpty()) { return; } for (String key : additionalFields.keySet()) { try { if (additionalFields.get(key) != null) { jsonObject.put(key, additionalFields.get(key)); } } catch (JSONException ignored) { } } } StripeSourceTypeModel(); @NonNull Map<String, Object> getAdditionalFields(); }### Answer:
@Test public void putAdditionalFieldsIntoJsonObject_whenHasFields_putsThemIntoObject() { JSONObject jsonObject = new JSONObject(); Map<String, Object> additionalFields = new HashMap<>(); additionalFields.put("a_key", "a_value"); additionalFields.put("b_key", "b_value"); putAdditionalFieldsIntoJsonObject(jsonObject, additionalFields); assertEquals(2, jsonObject.length()); assertEquals("a_value", jsonObject.optString("a_key")); assertEquals("b_value", jsonObject.optString("b_key")); }
@Test public void putAdditionalFieldsIntoJsonObject_whenHasDuplicateFields_putsThemIntoObject() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("a_key", "original"); } catch (JSONException unexpected) { fail("Unexpected exception: " + unexpected); } Map<String, Object> additionalFields = new HashMap<>(); additionalFields.put("a_key", "a_value"); additionalFields.put("b_key", "b_value"); putAdditionalFieldsIntoJsonObject(jsonObject, additionalFields); assertEquals(2, jsonObject.length()); assertEquals("a_value", jsonObject.optString("a_key")); assertEquals("b_value", jsonObject.optString("b_key")); }
@Test public void putAdditionalFieldsIntoJsonObject_whenNoFieldsArePassed_doesNothing() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("a", "a_value"); } catch (JSONException unexpected) { fail("Unexpected error: " + unexpected.getLocalizedMessage()); } Map<String, Object> emptyMap = new HashMap<>(); putAdditionalFieldsIntoJsonObject(jsonObject, emptyMap); assertEquals(1, jsonObject.length()); }
@Test public void putAdditionalFieldsIntoJsonObject_whenNullPassedInEitherArgument_doesNothing() { Map<String, Object> littleMap = new HashMap<String, Object>() {{ put("a", "a_value"); }}; JSONObject jsonObject = new JSONObject(); putAdditionalFieldsIntoJsonObject(null, littleMap); putAdditionalFieldsIntoJsonObject(jsonObject, null); assertEquals(0, jsonObject.length()); } |
### Question:
StripeSourceTypeModel extends StripeJsonModel { static void putAdditionalFieldsIntoMap( @Nullable Map<String, Object> map, @Nullable Map<String, Object> additionalFields) { if (map == null || additionalFields == null || additionalFields.isEmpty()) { return; } for(String key : additionalFields.keySet()) { map.put(key, additionalFields.get(key)); } } StripeSourceTypeModel(); @NonNull Map<String, Object> getAdditionalFields(); }### Answer:
@Test public void putAdditionalFieldsIntoMap_whenGivenFields_putsThemIntoTheMap() { Map<String, Object> originalMap = new HashMap<String, Object>() {{ put("a", "a_val"); put("b", "b_val"); }}; Map<String, Object> extraMap = new HashMap<String, Object>() {{ put("c", 100); put("d", false); }}; putAdditionalFieldsIntoMap(originalMap, extraMap); assertEquals(4, originalMap.size()); assertEquals("a_val", originalMap.get("a")); assertEquals("b_val", originalMap.get("b")); assertEquals(100, originalMap.get("c")); assertEquals(false, originalMap.get("d")); }
@Test public void putAdditionalFieldsIntoMap_whenGivenDuplicateFields_putsThemIntoTheMap() { Map<String, Object> originalMap = new HashMap<String, Object>() {{ put("a", "a_val"); put("b", "b_val"); }}; Map<String, Object> extraMap = new HashMap<String, Object>() {{ put("a", 100); put("d", false); }}; putAdditionalFieldsIntoMap(originalMap, extraMap); assertEquals(3, originalMap.size()); assertEquals(100, originalMap.get("a")); assertEquals("b_val", originalMap.get("b")); assertEquals(false, originalMap.get("d")); }
@Test public void putAdditionalFieldsIntoMap_whenGivenEmptyMap_doesNothing() { Map<String, Object> originalMap = new HashMap<String, Object>() {{ put("a", "a_val"); put("b", "b_val"); }}; Map<String, Object> emptyMap = new HashMap<>(); putAdditionalFieldsIntoMap(originalMap, emptyMap); assertEquals(2, originalMap.size()); assertEquals("a_val", originalMap.get("a")); assertEquals("b_val", originalMap.get("b")); }
@Test public void putAdditionalFieldsIntoMap_whenGivenNullForEitherInput_doesNothing() { Map<String, Object> littleMap = new HashMap<String, Object>() {{ put("a", "b"); }}; putAdditionalFieldsIntoMap(null, littleMap); putAdditionalFieldsIntoMap(littleMap, null); assertEquals(1, littleMap.size()); assertEquals("b", littleMap.get("a")); } |
### Question:
LoggingUtils { static void addNameAndVersion( @NonNull Map<String, Object> paramsObject, @NonNull Context context) { Context applicationContext = context.getApplicationContext(); if (applicationContext != null && applicationContext.getPackageManager() != null) { try { PackageInfo info = applicationContext.getPackageManager().getPackageInfo( applicationContext.getPackageName(), 0); String nameString = null; if (info.applicationInfo != null) { CharSequence name = info.applicationInfo.loadLabel(applicationContext.getPackageManager()); if (name != null) { nameString = name.toString(); } paramsObject.put(FIELD_APP_NAME, nameString); } if (StripeTextUtils.isBlank(nameString)) { paramsObject.put(FIELD_APP_NAME, info.packageName); } paramsObject.put(FIELD_APP_VERSION, info.versionCode); } catch (PackageManager.NameNotFoundException nameNotFound) { paramsObject.put(FIELD_APP_NAME, UNKNOWN); paramsObject.put(FIELD_APP_VERSION, UNKNOWN); } } else { paramsObject.put(FIELD_APP_NAME, NO_CONTEXT); paramsObject.put(FIELD_APP_VERSION, NO_CONTEXT); } } }### Answer:
@Test public void addNameAndVersion_whenApplicationContextIsNull_addsNoContextValues() { Context context = mock(Context.class); when(context.getApplicationContext()).thenReturn(null); Map<String, Object> paramsMap = new HashMap<>(); LoggingUtils.addNameAndVersion(paramsMap, context); assertEquals(LoggingUtils.NO_CONTEXT, paramsMap.get(LoggingUtils.FIELD_APP_NAME)); assertEquals(LoggingUtils.NO_CONTEXT, paramsMap.get(LoggingUtils.FIELD_APP_VERSION)); }
@Test public void addNameAndVersion_whenPackageInfoNotFound_addsUnknownValues() { Context context = mock(Context.class); when(context.getApplicationContext()).thenReturn(context); final String dummyName = "dummy_name"; PackageManager manager = mock(PackageManager.class); when(context.getPackageManager()).thenReturn(manager); when(context.getPackageName()).thenReturn(dummyName); try { when(manager.getPackageInfo(dummyName, 0)) .thenThrow(new PackageManager.NameNotFoundException()); } catch (PackageManager.NameNotFoundException namex) { fail("Unexpected exception thrown."); } Map<String, Object> paramsMap = new HashMap<>(); LoggingUtils.addNameAndVersion(paramsMap, context); assertEquals(LoggingUtils.UNKNOWN, paramsMap.get(LoggingUtils.FIELD_APP_NAME)); assertEquals(LoggingUtils.UNKNOWN, paramsMap.get(LoggingUtils.FIELD_APP_VERSION)); } |
### Question:
LoggingUtils { @NonNull static String getEventParamName(@NonNull @LoggingEventName String eventName) { return ANALYTICS_NAME + '.' + eventName; } }### Answer:
@Test public void getEventParamName_withTokenCreation_createsExpectedParameter() { final String expectedEventParam = "stripe_android.token_creation"; assertEquals(expectedEventParam, LoggingUtils.getEventParamName(LoggingUtils.EVENT_TOKEN_CREATION)); } |
### Question:
LoggingUtils { @NonNull static String getAnalyticsUa() { return ANALYTICS_PREFIX + "." + ANALYTICS_NAME + "-" + ANALYTICS_VERSION; } }### Answer:
@Test public void getAnalyticsUa_returnsExpectedValue() { final String androidAnalyticsUserAgent = "analytics.stripe_android-1.0"; assertEquals(androidAnalyticsUserAgent, LoggingUtils.getAnalyticsUa()); } |
### Question:
CardUtils { @NonNull @Card.CardBrand public static String getPossibleCardType(@Nullable String cardNumber) { return getPossibleCardType(cardNumber, true); } @NonNull @Card.CardBrand static String getPossibleCardType(@Nullable String cardNumber); static boolean isValidCardNumber(@Nullable String cardNumber); }### Answer:
@Test public void getPossibleCardType_withEmptyCard_returnsUnknown() { assertEquals(Card.UNKNOWN, CardUtils.getPossibleCardType(" ")); }
@Test public void getPossibleCardType_withNullCardNumber_returnsUnknown() { assertEquals(Card.UNKNOWN, CardUtils.getPossibleCardType(null)); }
@Test public void getPossibleCardType_withVisaPrefix_returnsVisa() { assertEquals(Card.VISA, CardUtils.getPossibleCardType("4899 99")); assertEquals(Card.VISA, CardUtils.getPossibleCardType("4")); }
@Test public void getPossibleCardType_withAmexPrefix_returnsAmex() { assertEquals(Card.AMERICAN_EXPRESS, CardUtils.getPossibleCardType("345")); assertEquals(Card.AMERICAN_EXPRESS, CardUtils.getPossibleCardType("37999999999")); }
@Test public void getPossibleCardType_withJCBPrefix_returnsJCB() { assertEquals(Card.JCB, CardUtils.getPossibleCardType("3535 3535")); }
@Test public void getPossibleCardType_withMasterCardPrefix_returnsMasterCard() { assertEquals(Card.MASTERCARD, CardUtils.getPossibleCardType("2222 452")); assertEquals(Card.MASTERCARD, CardUtils.getPossibleCardType("5050")); }
@Test public void getPossibleCardType_withDinersClubPrefix_returnsDinersClub() { assertEquals(Card.DINERS_CLUB, CardUtils.getPossibleCardType("303922 2234")); assertEquals(Card.DINERS_CLUB, CardUtils.getPossibleCardType("36778 9098")); }
@Test public void getPossibleCardType_withDiscoverPrefix_returnsDiscover() { assertEquals(Card.DISCOVER, CardUtils.getPossibleCardType("60355")); assertEquals(Card.DISCOVER, CardUtils.getPossibleCardType("62")); assertEquals(Card.DISCOVER, CardUtils.getPossibleCardType("6433 8 90923")); assertEquals(Card.DISCOVER, CardUtils.getPossibleCardType("6523452309209340293423")); }
@Test public void getPossibleCardType_withNonsenseNumber_returnsUnknown() { assertEquals(Card.UNKNOWN, CardUtils.getPossibleCardType("1234567890123456")); assertEquals(Card.UNKNOWN, CardUtils.getPossibleCardType("9999 9999 9999 9999")); assertEquals(Card.UNKNOWN, CardUtils.getPossibleCardType("3")); } |
### Question:
StripeJsonUtils { @Nullable static String optString( @NonNull JSONObject jsonObject, @NonNull @Size(min = 1) String fieldName) { return nullIfNullOrEmpty(jsonObject.optString(fieldName)); } }### Answer:
@Test public void optString_whenFieldPresent_findsAndReturnsField() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("key", "value"); assertEquals("value", StripeJsonUtils.optString(jsonObject, "key")); } catch (JSONException jex) { fail("No exception expected"); } }
@Test public void optString_whenFieldContainsRawNull_returnsNull() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("key", "null"); assertNull(StripeJsonUtils.optString(jsonObject, "key")); } catch (JSONException jex) { fail("No exception expected"); } }
@Test public void optString_whenFieldNotPresent_returnsNull() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("key", "value"); Object ob = StripeJsonUtils.optString(jsonObject, "nokeyshere"); assertNull(ob); } catch (JSONException jex) { fail("No exception expected"); } } |
### Question:
CardUtils { static boolean isValidCardLength(@Nullable String cardNumber) { return cardNumber != null && isValidCardLength(cardNumber, getPossibleCardType(cardNumber, false)); } @NonNull @Card.CardBrand static String getPossibleCardType(@Nullable String cardNumber); static boolean isValidCardNumber(@Nullable String cardNumber); }### Answer:
@Test public void isValidCardLength_whenValidVisaNumber_returnsTrue() { assertTrue(CardUtils.isValidCardLength("4242424242424242")); }
@Test public void isValidCardLength_whenValidJCBNumber_returnsTrue() { assertTrue(CardUtils.isValidCardLength("3530111333300000")); }
@Test public void isValidCardLength_whenValidDiscover_returnsTrue() { assertTrue(CardUtils.isValidCardLength("6011000990139424")); }
@Test public void isValidCardLength_whenValidDinersClub_returnsTrue() { assertTrue(CardUtils.isValidCardLength("30569309025904")); }
@Test public void isValidCardLength_whenValidMasterCard_returnsTrue() { assertTrue(CardUtils.isValidCardLength("5555555555554444")); }
@Test public void isValidCardLength_whenValidAmEx_returnsTrue() { assertTrue(CardUtils.isValidCardLength("378282246310005")); }
@Test public void isValidCardLength_whenNull_returnsFalse() { assertFalse(CardUtils.isValidCardLength(null)); }
@Test public void isValidCardLength_whenVisaStyleNumberButDinersClubLength_returnsFalse() { assertFalse(CardUtils.isValidCardLength("42424242424242")); }
@Test public void isValidCardLength_whenVisaStyleNumberButAmExLength_returnsFalse() { assertFalse(CardUtils.isValidCardLength("424242424242424")); }
@Test public void isValidCardLength_whenAmExStyleNumberButVisaLength_returnsFalse() { assertFalse(CardUtils.isValidCardLength("3782822463100050")); }
@Test public void isValidCardLength_whenAmExStyleNumberButDinersClubLength_returnsFalse() { assertFalse(CardUtils.isValidCardLength("37828224631000")); }
@Test public void isValidCardLength_whenDinersClubStyleNumberButVisaLength_returnsFalse() { assertFalse(CardUtils.isValidCardLength("3056930902590400")); }
@Test public void isValidCardLength_whenDinersClubStyleNumberStyleNumberButAmexLength_returnsFalse() { assertFalse(CardUtils.isValidCardLength("305693090259040")); }
@Test public void isValidCardLengthWithBrand_whenBrandUnknown_alwaysReturnsFalse() { String validVisa = "4242424242424242"; assertTrue(CardUtils.isValidCardLength(validVisa)); assertFalse(CardUtils.isValidCardLength(validVisa, Card.UNKNOWN)); } |
### Question:
CardUtils { static boolean isValidLuhnNumber(@Nullable String cardNumber) { if (cardNumber == null) { return false; } boolean isOdd = true; int sum = 0; for (int index = cardNumber.length() - 1; index >= 0; index--) { char c = cardNumber.charAt(index); if (!Character.isDigit(c)) { return false; } int digitInteger = Character.getNumericValue(c); isOdd = !isOdd; if (isOdd) { digitInteger *= 2; } if (digitInteger > 9) { digitInteger -= 9; } sum += digitInteger; } return sum % 10 == 0; } @NonNull @Card.CardBrand static String getPossibleCardType(@Nullable String cardNumber); static boolean isValidCardNumber(@Nullable String cardNumber); }### Answer:
@Test public void isValidLuhnNumber_whenValidVisaNumber_returnsTrue() { assertTrue(CardUtils.isValidLuhnNumber("4242424242424242")); }
@Test public void isValidLuhnNumber_whenValidJCBNumber_returnsTrue() { assertTrue(CardUtils.isValidLuhnNumber("3530111333300000")); }
@Test public void isValidLuhnNumber_whenValidDiscover_returnsTrue() { assertTrue(CardUtils.isValidLuhnNumber("6011000990139424")); }
@Test public void isValidLuhnNumber_whenValidDinersClub_returnsTrue() { assertTrue(CardUtils.isValidLuhnNumber("30569309025904")); }
@Test public void isValidLuhnNumber_whenValidMasterCard_returnsTrue() { assertTrue(CardUtils.isValidLuhnNumber("5555555555554444")); }
@Test public void isValidLuhnNumber_whenValidAmEx_returnsTrue() { assertTrue(CardUtils.isValidLuhnNumber("378282246310005")); }
@Test public void isValidLunhNumber_whenNumberIsInvalid_returnsFalse() { assertFalse(CardUtils.isValidLuhnNumber("4242424242424243")); }
@Test public void isValidLuhnNumber_whenInputIsNull_returnsFalse() { assertFalse(CardUtils.isValidLuhnNumber(null)); }
@Test public void isValidLuhnNumber_whenInputIsNotNumeric_returnsFalse() { assertFalse(CardUtils.isValidLuhnNumber("abcdefg")); assertFalse(CardUtils.isValidLuhnNumber("4242 4242 4242 4242")); assertFalse(CardUtils.isValidLuhnNumber("4242-4242-4242-4242")); } |
### Question:
StripeJsonUtils { @Nullable static Map<String, Object> jsonObjectToMap(@Nullable JSONObject jsonObject) { if (jsonObject == null) { return null; } Map<String, Object> map = new HashMap<>(); Iterator<String> keyIterator = jsonObject.keys(); while(keyIterator.hasNext()) { String key = keyIterator.next(); Object value = jsonObject.opt(key); if (NULL.equals(value) || value == null) { continue; } if (value instanceof JSONObject) { map.put(key, jsonObjectToMap((JSONObject) value)); } else if (value instanceof JSONArray) { map.put(key, jsonArrayToList((JSONArray) value)); } else { map.put(key, value); } } return map; } }### Answer:
@Test public void jsonObjectToMap_forNull_returnsNull() { assertNull(StripeJsonUtils.jsonObjectToMap(null)); }
@Test public void jsonObjectToMap_forSimpleObjects_returnsExpectedMap() { Map<String, Object> expectedMap = new HashMap<>(); expectedMap.put("akey", "avalue"); expectedMap.put("bkey", "bvalue"); expectedMap.put("boolkey", true); expectedMap.put("numkey", 123); try { JSONObject testJsonObject = new JSONObject(SIMPLE_JSON_TEST_OBJECT); Map<String, Object> mappedObject = StripeJsonUtils.jsonObjectToMap(testJsonObject); JsonTestUtils.assertMapEquals(expectedMap, mappedObject); } catch (JSONException jsonException) { fail("Test data failure " + jsonException.getLocalizedMessage()); } }
@Test public void jsonObjectToMap_forNestedObjects_returnsExpectedMap() { Map<String, Object> expectedMap = new HashMap<>(); expectedMap.put("top_key", new HashMap<String, Object>() {{ put("first_inner_key", new HashMap<String, Object>() {{ put("innermost_key", 1000); put("second_innermost_key", "second_inner_value"); }}); put("second_inner_key", "just a value"); }}); expectedMap.put("second_outer_key", new HashMap<String, Object>() {{ put("another_inner_key", false); }}); try { JSONObject testJsonObject = new JSONObject(NESTED_JSON_TEST_OBJECT); Map<String, Object> mappedObject = StripeJsonUtils.jsonObjectToMap(testJsonObject); JsonTestUtils.assertMapEquals(expectedMap, mappedObject); } catch (JSONException jsonException) { fail("Test data failure " + jsonException.getLocalizedMessage()); } }
@Test public void jsonObjectToMap_withNestedObjectAndArrays_returnsExpectedMap() { Map<String, Object> expectedMap = new HashMap<>(); expectedMap.put("other_outer_key", false); final List<Object> itemsList = new ArrayList<>(); itemsList.add(new HashMap<String, Object>() {{ put("id", 123); }}); itemsList.add(new HashMap<String, Object>() {{ put("id", "this time with letters"); }}); itemsList.add("a string item"); itemsList.add(256); itemsList.add(Arrays.asList(1, 2, "C", 4)); itemsList.add(Arrays.asList(new HashMap<String, Object>() {{ put("deep", "deepValue"); }})); expectedMap.put("outer_key", new HashMap<String, Object>() {{ put("items", itemsList); put("another_key", "a simple value this time"); }}); try { JSONObject testJsonObject = new JSONObject(NESTED_MIXED_ARRAY_OBJECT); Map<String, Object> convertedMap = StripeJsonUtils.jsonObjectToMap(testJsonObject); JsonTestUtils.assertMapEquals(expectedMap, convertedMap); } catch (JSONException jsonException) { fail("Test data failure " + jsonException.getLocalizedMessage()); } } |
### Question:
MaskedCardView extends LinearLayout { @VisibleForTesting int[] getTextColorValues() { int[] colorValues = new int[4]; colorValues[0] = mSelectedColorInt; colorValues[1] = mSelectedAlphaColorInt; colorValues[2] = mUnselectedTextColorInt; colorValues[3] = mUnselectedTextAlphaColorInt; return colorValues; } MaskedCardView(Context context); MaskedCardView(Context context, AttributeSet attrs); MaskedCardView(Context context, AttributeSet attrs, int defStyle); @Override boolean isSelected(); @Override void setSelected(boolean selected); }### Answer:
@Test public void init_setsColorValuesWithAlpha() { final int alpha = 204; int[] colorValues = mMaskedCardView.getTextColorValues(); assertEquals(4, colorValues.length); assertEquals(colorValues[1], ColorUtils.setAlphaComponent(colorValues[0], alpha)); assertEquals(colorValues[3], ColorUtils.setAlphaComponent(colorValues[2], alpha)); } |
### Question:
SelectShippingMethodWidget extends FrameLayout { public ShippingMethod getSelectedShippingMethod() { return mShippingMethodAdapter.getSelectedShippingMethod(); } SelectShippingMethodWidget(Context context); SelectShippingMethodWidget(Context context, AttributeSet attrs); SelectShippingMethodWidget(Context context, AttributeSet attrs, int defStyleAttr); ShippingMethod getSelectedShippingMethod(); void setShippingMethods(List<ShippingMethod> shippingMethods, ShippingMethod defaultShippingMethod); }### Answer:
@Test public void selectShippingMethodWidget_whenSelected_selectionChanges() { assertEquals(mShippingMethodAdapter.getSelectedShippingMethod(), mShippingMethods.get(0)); mShippingMethodAdapter.setSelectedIndex(1); assertEquals(mShippingMethodAdapter.getSelectedShippingMethod(), mShippingMethods.get(1)); } |
### Question:
ExpiryDateEditText extends StripeEditText { public boolean isDateValid() { return mIsDateValid; } ExpiryDateEditText(Context context); ExpiryDateEditText(Context context, AttributeSet attrs); ExpiryDateEditText(Context context, AttributeSet attrs, int defStyleAttr); boolean isDateValid(); @Nullable @Size(2) int[] getValidDateFields(); void setExpiryDateEditListener(ExpiryDateEditListener expiryDateEditListener); }### Answer:
@Test public void afterAddingFinalDigit_whenGoingFromInvalidToValid_callsListener() { if (Calendar.getInstance().get(Calendar.YEAR) > 2059) { fail("Update the code with a date that is still valid. Also, hello from the past."); } mExpiryDateEditText.append("1"); mExpiryDateEditText.append("2"); mExpiryDateEditText.append("5"); verifyZeroInteractions(mExpiryDateEditListener); mExpiryDateEditText.append("9"); assertTrue(mExpiryDateEditText.isDateValid()); verify(mExpiryDateEditListener, times(1)).onExpiryDateComplete(); }
@Test public void afterAddingFinalDigit_whenDeletingItem_revertsToInvalidState() { if (Calendar.getInstance().get(Calendar.YEAR) > 2059) { fail("Update the code with a date that is still valid. Also, hello from the past."); } mExpiryDateEditText.append("12"); mExpiryDateEditText.append("59"); assertTrue(mExpiryDateEditText.isDateValid()); ViewTestUtils.sendDeleteKeyEvent(mExpiryDateEditText); verify(mExpiryDateEditListener, times(1)).onExpiryDateComplete(); assertFalse(mExpiryDateEditText.isDateValid()); } |
### Question:
ExpiryDateEditText extends StripeEditText { @VisibleForTesting int updateSelectionIndex( int newLength, int editActionStart, int editActionAddition) { int newPosition, gapsJumped = 0; boolean skipBack = false; if (editActionStart <= 2 && editActionStart + editActionAddition >= 2) { gapsJumped = 1; } if (editActionAddition == 0 && editActionStart == 3) { skipBack = true; } newPosition = editActionStart + editActionAddition + gapsJumped; if (skipBack && newPosition > 0) { newPosition--; } return newPosition <= newLength ? newPosition : newLength; } ExpiryDateEditText(Context context); ExpiryDateEditText(Context context, AttributeSet attrs); ExpiryDateEditText(Context context, AttributeSet attrs, int defStyleAttr); boolean isDateValid(); @Nullable @Size(2) int[] getValidDateFields(); void setExpiryDateEditListener(ExpiryDateEditListener expiryDateEditListener); }### Answer:
@Test public void updateSelectionIndex_whenMovingAcrossTheGap_movesToEnd() { assertEquals(3, mExpiryDateEditText.updateSelectionIndex(3, 1, 1)); }
@Test public void updateSelectionIndex_atStart_onlyMovesForwardByOne() { assertEquals(1, mExpiryDateEditText.updateSelectionIndex(1, 0, 1)); }
@Test public void updateSelectionIndex_whenDeletingAcrossTheGap_staysAtEnd() { assertEquals(2, mExpiryDateEditText.updateSelectionIndex(2, 4, 0)); } |
### Question:
ExpiryDateEditText extends StripeEditText { @Nullable @Size(2) public int[] getValidDateFields() { if (!mIsDateValid) { return null; } int [] monthYearPair = new int[2]; String rawNumericInput = getText().toString().replaceAll("/", ""); String[] dateFields = DateUtils.separateDateStringParts(rawNumericInput); try { monthYearPair[0] = Integer.parseInt(dateFields[0]); monthYearPair[1] = DateUtils.convertTwoDigitYearToFour(Integer.parseInt(dateFields[1])); } catch (NumberFormatException numEx) { return null; } return monthYearPair; } ExpiryDateEditText(Context context); ExpiryDateEditText(Context context, AttributeSet attrs); ExpiryDateEditText(Context context, AttributeSet attrs, int defStyleAttr); boolean isDateValid(); @Nullable @Size(2) int[] getValidDateFields(); void setExpiryDateEditListener(ExpiryDateEditListener expiryDateEditListener); }### Answer:
@Test public void getValidDateFields_whenDataIsValid_returnsExpectedValues() { assertTrue(Calendar.getInstance().get(Calendar.YEAR) < 2050); mExpiryDateEditText.append("12"); mExpiryDateEditText.append("50"); int [] retrievedDate = mExpiryDateEditText.getValidDateFields(); assertNotNull(retrievedDate); assertEquals(12, retrievedDate[0]); assertEquals(2050, retrievedDate[1]); }
@Test public void getValidDateFields_whenDateIsValidFormatButExpired_returnsNull() { assertTrue(Calendar.getInstance().get(Calendar.YEAR) < 2080); mExpiryDateEditText.append("12"); mExpiryDateEditText.append("12"); assertNull(mExpiryDateEditText.getValidDateFields()); }
@Test public void getValidDateFields_whenDateIsIncomplete_returnsNull() { mExpiryDateEditText.append("4"); assertNull(mExpiryDateEditText.getValidDateFields()); }
@Test public void getValidDateFields_whenDateIsValidAndThenChangedToInvalid_returnsNull() { assertTrue(Calendar.getInstance().get(Calendar.YEAR) < 2050); mExpiryDateEditText.append("12"); mExpiryDateEditText.append("50"); ViewTestUtils.sendDeleteKeyEvent(mExpiryDateEditText); assertNull(mExpiryDateEditText.getValidDateFields()); } |
### Question:
StripeJsonUtils { @Nullable @SuppressWarnings("unchecked") static JSONObject mapToJsonObject(@Nullable Map<String, ? extends Object> mapObject) { if (mapObject == null) { return null; } JSONObject jsonObject = new JSONObject(); for (String key : mapObject.keySet()) { Object value = mapObject.get(key); if (value == null) { continue; } try { if (value instanceof Map<?, ?>) { try { Map<String, Object> mapValue = (Map<String, Object>) value; jsonObject.put(key, mapToJsonObject(mapValue)); } catch (ClassCastException classCastException) { } } else if (value instanceof List<?>) { jsonObject.put(key, listToJsonArray((List<Object>) value)); } else if (value instanceof Number || value instanceof Boolean) { jsonObject.put(key, value); } else { jsonObject.put(key, value.toString()); } } catch (JSONException jsonException) { } } return jsonObject; } }### Answer:
@Test public void mapToJsonObject_forNull_returnsNull() { assertNull(StripeJsonUtils.mapToJsonObject(null)); }
@Test public void mapToJsonObject_forSimpleObjects_returnsExpectedObject() { Map<String, Object> testMap = new HashMap<>(); testMap.put("akey", "avalue"); testMap.put("bkey", "bvalue"); testMap.put("boolkey", true); testMap.put("numkey", 123); try { JSONObject expectedJsonObject = new JSONObject(SIMPLE_JSON_TEST_OBJECT); JSONObject testObject = StripeJsonUtils.mapToJsonObject(testMap); JsonTestUtils.assertJsonEquals(expectedJsonObject, testObject); } catch (JSONException jsonException) { fail("Test data failure " + jsonException.getLocalizedMessage()); } }
@Test public void mapToJsonObject_forNestedMaps_returnsExpectedObject() { Map<String, Object> testMap = new HashMap<>(); testMap.put("top_key", new HashMap<String, Object>() {{ put("first_inner_key", new HashMap<String, Object>() {{ put("innermost_key", 1000); put("second_innermost_key", "second_inner_value"); }}); put("second_inner_key", "just a value"); }}); testMap.put("second_outer_key", new HashMap<String, Object>() {{ put("another_inner_key", false); }}); try { JSONObject expectedJsonObject = new JSONObject(NESTED_JSON_TEST_OBJECT); JSONObject testJsonObject = StripeJsonUtils.mapToJsonObject(testMap); JsonTestUtils.assertJsonEquals(expectedJsonObject, testJsonObject); } catch (JSONException jsonException) { fail("Test data failure " + jsonException.getLocalizedMessage()); } }
@Test public void mapToJsonObject_withNestedMapAndLists_returnsExpectedObject() { Map<String, Object> testMap = new HashMap<>(); testMap.put("other_outer_key", false); final List<Object> itemsList = new ArrayList<>(); itemsList.add(new HashMap<String, Object>() {{ put("id", 123); }}); itemsList.add(new HashMap<String, Object>() {{ put("id", "this time with letters"); }}); itemsList.add("a string item"); itemsList.add(256); itemsList.add(Arrays.asList(1, 2, "C", 4)); itemsList.add(Arrays.asList(new HashMap<String, Object>() {{ put("deep", "deepValue"); }})); testMap.put("outer_key", new HashMap<String, Object>() {{ put("items", itemsList); put("another_key", "a simple value this time"); }}); try { JSONObject expectedJsonObject = new JSONObject(NESTED_MIXED_ARRAY_OBJECT); JSONObject testJsonObject = StripeJsonUtils.mapToJsonObject(testMap); JsonTestUtils.assertJsonEquals(expectedJsonObject, testJsonObject); } catch (JSONException jsonException) { fail("Test data failure " + jsonException.getLocalizedMessage()); } } |
### Question:
StripeJsonUtils { @Nullable @SuppressWarnings("unchecked") static JSONArray listToJsonArray(@Nullable List values) { if (values == null) { return null; } JSONArray jsonArray = new JSONArray(); for (Object object : values) { if (object instanceof Map<?, ?>) { try { Map<String, Object> mapObject = (Map<String, Object>) object; jsonArray.put(mapToJsonObject(mapObject)); } catch (ClassCastException classCastException) { } } else if (object instanceof List<?>) { jsonArray.put(listToJsonArray((List) object)); } else if (object instanceof Number || object instanceof Boolean) { jsonArray.put(object); } else { jsonArray.put(object.toString()); } } return jsonArray; } }### Answer:
@Test public void listToJsonArray_forNull_returnsNull() { assertNull(StripeJsonUtils.listToJsonArray(null)); }
@Test public void listToJsonArray_forSimpleList_returnsExpectedArray() { List<Object> testList = new ArrayList<>(); testList.add(1); testList.add(2); testList.add(3); testList.add("a"); testList.add(true); testList.add("cde"); try { JSONArray expectedJsonArray = new JSONArray(SIMPLE_JSON_TEST_ARRAY); JSONArray testJsonArray = StripeJsonUtils.listToJsonArray(testList); JsonTestUtils.assertJsonArrayEquals(expectedJsonArray, testJsonArray); } catch (JSONException jsonException) { fail("Test data failure " + jsonException.getLocalizedMessage()); } } |
### Question:
CardNumberEditText extends StripeEditText { public boolean isCardNumberValid() { return mIsCardNumberValid; } CardNumberEditText(Context context); CardNumberEditText(Context context, AttributeSet attrs); CardNumberEditText(Context context, AttributeSet attrs, int defStyleAttr); @NonNull @Card.CardBrand String getCardBrand(); @Nullable String getCardNumber(); int getLengthMax(); boolean isCardNumberValid(); }### Answer:
@Test public void setText_whenTextIsValidCommonLengthNumber_changesCardValidState() { mCardNumberEditText.setText(VALID_VISA_WITH_SPACES); assertTrue(mCardNumberEditText.isCardNumberValid()); verify(mCardNumberCompleteListener, times(1)).onCardNumberComplete(); }
@Test public void setText_whenTextIsSpacelessValidNumber_changesToSpaceNumberAndValidates() { mCardNumberEditText.setText(VALID_VISA_NO_SPACES); assertTrue(mCardNumberEditText.isCardNumberValid()); verify(mCardNumberCompleteListener, times(1)).onCardNumberComplete(); }
@Test public void setText_whenTextIsValidAmExDinersClubLengthNumber_changesCardValidState() { mCardNumberEditText.setText(VALID_AMEX_WITH_SPACES); assertTrue(mCardNumberEditText.isCardNumberValid()); verify(mCardNumberCompleteListener, times(1)).onCardNumberComplete(); }
@Test public void setText_whenTextChangesFromValidToInvalid_changesCardValidState() { mCardNumberEditText.setText(VALID_VISA_WITH_SPACES); reset(mCardNumberCompleteListener); String mutable = mCardNumberEditText.getText().toString(); mutable = mutable.substring(0, 18); mCardNumberEditText.setText(mutable); assertFalse(mCardNumberEditText.isCardNumberValid()); verifyZeroInteractions(mCardNumberCompleteListener); }
@Test public void setText_whenTextIsInvalidCommonLengthNumber_doesNotNotifyListener() { String almostValid = VALID_VISA_WITH_SPACES.substring(0, 18) + "3"; mCardNumberEditText.setText(almostValid); assertFalse(mCardNumberEditText.isCardNumberValid()); verifyZeroInteractions(mCardNumberCompleteListener); } |
### Question:
CardNumberEditText extends StripeEditText { @Nullable public String getCardNumber() { return mIsCardNumberValid ? StripeTextUtils.removeSpacesAndHyphens(getText().toString()) : null; } CardNumberEditText(Context context); CardNumberEditText(Context context, AttributeSet attrs); CardNumberEditText(Context context, AttributeSet attrs, int defStyleAttr); @NonNull @Card.CardBrand String getCardBrand(); @Nullable String getCardNumber(); int getLengthMax(); boolean isCardNumberValid(); }### Answer:
@Test public void getCardNumber_whenValidCard_returnsCardNumberWithoutSpaces() { mCardNumberEditText.setText(VALID_VISA_WITH_SPACES); assertEquals(VALID_VISA_NO_SPACES, mCardNumberEditText.getCardNumber()); mCardNumberEditText.setText(VALID_AMEX_WITH_SPACES); assertEquals(VALID_AMEX_NO_SPACES, mCardNumberEditText.getCardNumber()); mCardNumberEditText.setText(VALID_DINERS_CLUB_WITH_SPACES); assertEquals(VALID_DINERS_CLUB_NO_SPACES, mCardNumberEditText.getCardNumber()); }
@Test public void getCardNumber_whenIncompleteCard_returnsNull() { mCardNumberEditText.setText( VALID_DINERS_CLUB_WITH_SPACES .substring(0, VALID_DINERS_CLUB_WITH_SPACES.length() - 2)); assertNull(mCardNumberEditText.getCardNumber()); }
@Test public void getCardNumber_whenInvalidCardNumber_returnsNull() { String almostVisa = VALID_VISA_WITH_SPACES.substring(0, VALID_VISA_WITH_SPACES.length() - 1); almostVisa += "3"; mCardNumberEditText.setText(almostVisa); assertNull(mCardNumberEditText.getCardNumber()); }
@Test public void getCardNumber_whenValidNumberIsChangedToInvalid_returnsNull() { mCardNumberEditText.setText(VALID_AMEX_WITH_SPACES); ViewTestUtils.sendDeleteKeyEvent(mCardNumberEditText); assertNull(mCardNumberEditText.getCardNumber()); } |
### Question:
StripeJsonUtils { @Nullable static List<Object> jsonArrayToList(@Nullable JSONArray jsonArray) { if (jsonArray == null) { return null; } List<Object> objectList = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { try { Object ob = jsonArray.get(i); if (ob instanceof JSONArray) { objectList.add(jsonArrayToList((JSONArray) ob)); } else if (ob instanceof JSONObject) { Map<String, Object> objectMap = jsonObjectToMap((JSONObject) ob); if (objectMap != null) { objectList.add(objectMap); } } else { if (NULL.equals(ob)) { continue; } objectList.add(ob); } } catch (JSONException ignored) { } } return objectList; } }### Answer:
@Test public void jsonArrayToList_forNull_returnsNull() { assertNull(StripeJsonUtils.jsonArrayToList(null)); }
@Test public void jsonArrayToList_forSimpleList_returnsExpectedList() { List<Object> expectedList = new ArrayList<>(); expectedList.add(1); expectedList.add(2); expectedList.add(3); expectedList.add("a"); expectedList.add(true); expectedList.add("cde"); try { JSONArray testJsonArray = new JSONArray(SIMPLE_JSON_TEST_ARRAY); List<Object> convertedJsonArray = StripeJsonUtils.jsonArrayToList(testJsonArray); JsonTestUtils.assertListEquals(expectedList, convertedJsonArray); } catch (JSONException jsonException) { fail("Test data failure " + jsonException.getLocalizedMessage()); } } |
### Question:
StripeEditText extends TextInputEditText { @ColorInt @SuppressWarnings("deprecation") public int getDefaultErrorColorInt() { @ColorInt int errorColor; determineDefaultErrorColor(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { errorColor = getResources().getColor(mDefaultErrorColorResId, null); } else { errorColor = getResources().getColor(mDefaultErrorColorResId); } return errorColor; } StripeEditText(Context context); StripeEditText(Context context, AttributeSet attrs); StripeEditText(Context context, AttributeSet attrs, int defStyleAttr); @Nullable ColorStateList getCachedColorStateList(); boolean getShouldShowError(); @ColorInt @SuppressWarnings("deprecation") int getDefaultErrorColorInt(); @Override InputConnection onCreateInputConnection(EditorInfo outAttrs); void setErrorColor(@ColorInt int errorColor); void setHintDelayed(@StringRes final int hintResource, long delayMilliseconds); @SuppressWarnings("deprecation") void setShouldShowError(boolean shouldShowError); }### Answer:
@Test @SuppressWarnings("deprecation") public void getDefaultErrorColorInt_onDarkTheme_returnsDarkError() { mEditText.setTextColor( mActivityController.get().getResources() .getColor(android.R.color.primary_text_dark)); @ColorInt int colorInt = mEditText.getDefaultErrorColorInt(); @ColorInt int expectedErrorInt = mActivityController.get().getResources().getColor(R.color.error_text_dark_theme); assertEquals(expectedErrorInt, colorInt); }
@Test @SuppressWarnings("deprecation") public void getDefaultErrorColorInt_onLightTheme_returnsLightError() { mEditText.setTextColor( mActivityController.get().getResources() .getColor(android.R.color.primary_text_light)); @ColorInt int colorInt = mEditText.getDefaultErrorColorInt(); @ColorInt int expectedErrorInt = mActivityController.get().getResources().getColor(R.color.error_text_light_theme); assertEquals(expectedErrorInt, colorInt); } |
### Question:
PaymentMethodsActivity extends AppCompatActivity { @VisibleForTesting void initializeCustomerSourceData() { Customer cachedCustomer = mCustomerSessionProxy == null ? CustomerSession.getInstance().getCachedCustomer() : mCustomerSessionProxy.getCachedCustomer(); if (cachedCustomer != null) { mCustomer = cachedCustomer; createListFromCustomerSources(); } else { getCustomerFromSession(); } } static Intent newIntent(Context context); @Override boolean onPrepareOptionsMenu(Menu menu); @Override boolean onCreateOptionsMenu(Menu menu); @Override boolean onOptionsItemSelected(MenuItem item); static final String EXTRA_SELECTED_PAYMENT; }### Answer:
@Test public void onCreate_withCachedCustomer_showsUi() { Customer customer = Customer.fromString(CustomerSessionTest.FIRST_TEST_CUSTOMER_OBJECT); when(mCustomerSessionProxy.getCachedCustomer()).thenReturn(customer); mActivityController.get().initializeCustomerSourceData(); assertNotNull(mProgressBar); assertNotNull(mRecyclerView); assertNotNull(mAddCardView); assertEquals(View.VISIBLE, mAddCardView.getVisibility()); assertEquals(View.VISIBLE, mRecyclerView.getVisibility()); assertEquals(View.GONE, mProgressBar.getVisibility()); }
@Test public void onCreate_withoutCacheCustomer_callsApiAndDisplaysProgressBarWhileWaiting() { Customer customer = Customer.fromString(CustomerSessionTest.FIRST_TEST_CUSTOMER_OBJECT); assertNotNull(customer); when(mCustomerSessionProxy.getCachedCustomer()).thenReturn(null); ArgumentCaptor<CustomerSession.CustomerRetrievalListener> listenerArgumentCaptor = ArgumentCaptor.forClass(CustomerSession.CustomerRetrievalListener.class); assertNotNull(mProgressBar); assertNotNull(mRecyclerView); assertNotNull(mAddCardView); mActivityController.get().initializeCustomerSourceData(); verify(mCustomerSessionProxy).retrieveCurrentCustomer(listenerArgumentCaptor.capture()); assertEquals(View.VISIBLE, mProgressBar.getVisibility()); assertEquals(View.VISIBLE, mAddCardView.getVisibility()); assertEquals(View.VISIBLE, mRecyclerView.getVisibility()); CustomerSession.CustomerRetrievalListener listener = listenerArgumentCaptor.getValue(); assertNotNull(listener); listener.onCustomerRetrieved(customer); assertEquals(View.GONE, mProgressBar.getVisibility()); }
@Test public void onClickAddSourceView_withoutPaymentSessoin_launchesAddSourceActivityWithoutLog() { Customer customer = Customer.fromString(CustomerSessionTest.FIRST_TEST_CUSTOMER_OBJECT); when(mCustomerSessionProxy.getCachedCustomer()).thenReturn(customer); mActivityController.get().initializeCustomerSourceData(); mAddCardView.performClick(); ShadowActivity.IntentForResult intentForResult = mShadowActivity.getNextStartedActivityForResult(); assertNotNull(intentForResult); assertEquals(AddSourceActivity.class.getName(), intentForResult.intent.getComponent().getClassName()); assertFalse(intentForResult.intent.hasExtra(EXTRA_PAYMENT_SESSION_ACTIVE)); } |
### Question:
CardMultilineWidget extends LinearLayout { @Nullable public Card getCard() { if (validateAllFields()) { String cardNumber = mCardNumberEditText.getCardNumber(); int[] cardDate = mExpiryDateEditText.getValidDateFields(); String cvcValue = mCvcEditText.getText().toString(); Card card = new Card(cardNumber, cardDate[0], cardDate[1], cvcValue); if (mShouldShowPostalCode) { card.setAddressZip(mPostalCodeEditText.getText().toString()); } return card.addLoggingToken(CARD_MULTILINE_TOKEN); } return null; } CardMultilineWidget(Context context); CardMultilineWidget(Context context, AttributeSet attrs); CardMultilineWidget(Context context, AttributeSet attrs, int defStyleAttr); @VisibleForTesting CardMultilineWidget(Context context, boolean shouldShowPostalCode); void clear(); void setCardInputListener(@Nullable CardInputListener cardInputListener); @Nullable Card getCard(); boolean validateAllFields(); @Override void onWindowFocusChanged(boolean hasWindowFocus); void setShouldShowPostalCode(boolean shouldShowPostalCode); @Override boolean isEnabled(); @Override void setEnabled(boolean enabled); }### Answer:
@Test public void getCard_whenInputIsValidVisaWithZip_returnsCardObjectWithLoggingToken() { assertTrue(Calendar.getInstance().get(Calendar.YEAR) < 2050); mFullGroup.cardNumberEditText.setText(VALID_VISA_WITH_SPACES); mFullGroup.expiryDateEditText.append("12"); mFullGroup.expiryDateEditText.append("50"); mFullGroup.cvcEditText.append("123"); mFullGroup.postalCodeEditText.append("12345"); Card card = mCardMultilineWidget.getCard(); assertNotNull(card); assertEquals(VALID_VISA_NO_SPACES, card.getNumber()); assertNotNull(card.getExpMonth()); assertNotNull(card.getExpYear()); assertEquals(12, card.getExpMonth().intValue()); assertEquals(2050, card.getExpYear().intValue()); assertEquals("123", card.getCVC()); assertEquals("12345", card.getAddressZip()); assertTrue(card.validateCard()); assertArrayEquals(EXPECTED_LOGGING_ARRAY, card.getLoggingTokens().toArray()); }
@Test public void getCard_whenInputIsValidVisaButInputHasNoZip_returnsNull() { assertTrue(Calendar.getInstance().get(Calendar.YEAR) < 2050); mFullGroup.cardNumberEditText.setText(VALID_VISA_WITH_SPACES); mFullGroup.expiryDateEditText.append("12"); mFullGroup.expiryDateEditText.append("50"); mFullGroup.cvcEditText.append("123"); Card card = mCardMultilineWidget.getCard(); assertNull(card); }
@Test public void getCard_whenInputIsValidVisaAndNoZipRequired_returnsFullCardAndExpectedLogging() { assertTrue(Calendar.getInstance().get(Calendar.YEAR) < 2050); mNoZipGroup.cardNumberEditText.setText(VALID_VISA_WITH_SPACES); mNoZipGroup.expiryDateEditText.append("12"); mNoZipGroup.expiryDateEditText.append("50"); mNoZipGroup.cvcEditText.append("123"); Card card = mNoZipCardMultilineWidget.getCard(); assertNotNull(card); assertEquals(VALID_VISA_NO_SPACES, card.getNumber()); assertNotNull(card.getExpMonth()); assertNotNull(card.getExpYear()); assertEquals(12, card.getExpMonth().intValue()); assertEquals(2050, card.getExpYear().intValue()); assertEquals("123", card.getCVC()); assertNull(card.getAddressZip()); assertTrue(card.validateCard()); assertArrayEquals(EXPECTED_LOGGING_ARRAY, card.getLoggingTokens().toArray()); } |
### Question:
CardMultilineWidget extends LinearLayout { static boolean isPostalCodeMaximalLength(boolean isZip, @Nullable String text) { return isZip && text != null && text.length() == 5; } CardMultilineWidget(Context context); CardMultilineWidget(Context context, AttributeSet attrs); CardMultilineWidget(Context context, AttributeSet attrs, int defStyleAttr); @VisibleForTesting CardMultilineWidget(Context context, boolean shouldShowPostalCode); void clear(); void setCardInputListener(@Nullable CardInputListener cardInputListener); @Nullable Card getCard(); boolean validateAllFields(); @Override void onWindowFocusChanged(boolean hasWindowFocus); void setShouldShowPostalCode(boolean shouldShowPostalCode); @Override boolean isEnabled(); @Override void setEnabled(boolean enabled); }### Answer:
@Test public void isPostalCodeMaximalLength_whenZipEnteredAndIsMaximalLength_returnsTrue() { assertTrue(CardMultilineWidget.isPostalCodeMaximalLength(true, "12345")); }
@Test public void isPostalCodeMaximalLength_whenZipEnteredAndIsNotMaximalLength_returnsFalse() { assertFalse(CardMultilineWidget.isPostalCodeMaximalLength(true, "123")); }
@Test public void isPostalCodeMaximalLength_whenZipEnteredAndIsEmpty_returnsFalse() { assertFalse(CardMultilineWidget.isPostalCodeMaximalLength(true, "")); }
@Test public void isPostalCodeMaximalLength_whenZipEnteredAndIsNull_returnsFalse() { assertFalse(CardMultilineWidget.isPostalCodeMaximalLength(true, null)); }
@Test public void isPostalCodeMaximalLength_whenNotZip_returnsFalse() { assertFalse(CardMultilineWidget.isPostalCodeMaximalLength(false, "12345")); } |
### Question:
CardMultilineWidget extends LinearLayout { public void clear() { mCardNumberEditText.setText(""); mExpiryDateEditText.setText(""); mCvcEditText.setText(""); mPostalCodeEditText.setText(""); mCardNumberEditText.setShouldShowError(false); mExpiryDateEditText.setShouldShowError(false); mCvcEditText.setShouldShowError(false); mPostalCodeEditText.setShouldShowError(false); updateBrand(Card.UNKNOWN); } CardMultilineWidget(Context context); CardMultilineWidget(Context context, AttributeSet attrs); CardMultilineWidget(Context context, AttributeSet attrs, int defStyleAttr); @VisibleForTesting CardMultilineWidget(Context context, boolean shouldShowPostalCode); void clear(); void setCardInputListener(@Nullable CardInputListener cardInputListener); @Nullable Card getCard(); boolean validateAllFields(); @Override void onWindowFocusChanged(boolean hasWindowFocus); void setShouldShowPostalCode(boolean shouldShowPostalCode); @Override boolean isEnabled(); @Override void setEnabled(boolean enabled); }### Answer:
@Test public void clear_whenZipRequiredAndAllFieldsEntered_clearsAllfields() { assertTrue(Calendar.getInstance().get(Calendar.YEAR) < 2050); mFullGroup.cardNumberEditText.setText(VALID_VISA_WITH_SPACES); mFullGroup.expiryDateEditText.append("12"); mFullGroup.expiryDateEditText.append("50"); mFullGroup.cvcEditText.append("123"); mFullGroup.postalCodeEditText.append("12345"); mCardMultilineWidget.clear(); assertEquals("", mFullGroup.cardNumberEditText.getText().toString()); assertEquals("", mFullGroup.expiryDateEditText.getText().toString()); assertEquals("", mFullGroup.cvcEditText.getText().toString()); assertEquals("", mFullGroup.postalCodeEditText.getText().toString()); } |
### Question:
CardMultilineWidget extends LinearLayout { public void setShouldShowPostalCode(boolean shouldShowPostalCode) { mShouldShowPostalCode = shouldShowPostalCode; adjustViewForPostalCodeAttribute(); } CardMultilineWidget(Context context); CardMultilineWidget(Context context, AttributeSet attrs); CardMultilineWidget(Context context, AttributeSet attrs, int defStyleAttr); @VisibleForTesting CardMultilineWidget(Context context, boolean shouldShowPostalCode); void clear(); void setCardInputListener(@Nullable CardInputListener cardInputListener); @Nullable Card getCard(); boolean validateAllFields(); @Override void onWindowFocusChanged(boolean hasWindowFocus); void setShouldShowPostalCode(boolean shouldShowPostalCode); @Override boolean isEnabled(); @Override void setEnabled(boolean enabled); }### Answer:
@Test public void initView_whenZipRequiredThenSetToHidden_secondRowLosesPostalCodeAndAdjustsMargin() { assertEquals(View.VISIBLE, mFullGroup.postalCodeInputLayout.getVisibility()); mCardMultilineWidget.setShouldShowPostalCode(false); assertEquals(View.GONE, mFullGroup.postalCodeInputLayout.getVisibility()); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mFullGroup.cvcInputLayout.getLayoutParams(); assertEquals(0, params.rightMargin); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { assertEquals(0, params.getMarginEnd()); } }
@Test public void initView_whenZipHiddenThenSetToRequired_secondRowAddsPostalCodeAndAdjustsMargin() { assertEquals(View.GONE, mNoZipGroup.postalCodeInputLayout.getVisibility()); mNoZipCardMultilineWidget.setShouldShowPostalCode(true); assertEquals(View.VISIBLE, mNoZipGroup.postalCodeInputLayout.getVisibility()); int expectedMargin = mNoZipCardMultilineWidget.getResources() .getDimensionPixelSize(R.dimen.add_card_expiry_middle_margin); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mNoZipGroup.cvcInputLayout.getLayoutParams(); assertEquals(expectedMargin, params.rightMargin); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { assertEquals(expectedMargin, params.getMarginEnd()); } } |
### Question:
DateUtils { @IntRange(from = 1000, to = 9999) static int convertTwoDigitYearToFour(@IntRange(from = 0, to = 99) int inputYear) { return convertTwoDigitYearToFour(inputYear, Calendar.getInstance()); } }### Answer:
@Test public void convertTwoDigitYearToFour_whenCurrentYearIsLessThanEighty_addsNormalBase() { Calendar earlyCenturyCalendar = Calendar.getInstance(); earlyCenturyCalendar.set(Calendar.YEAR, 2017); assertEquals(DateUtils.convertTwoDigitYearToFour(19, earlyCenturyCalendar), 2019); }
@Test public void convertTwoDigitYearToFour_whenDateIsNearCenturyButYearIsSmall_addsIncreasedBase() { Calendar lateCenturyCalendar = Calendar.getInstance(); lateCenturyCalendar.set(Calendar.YEAR, 2081); assertEquals(DateUtils.convertTwoDigitYearToFour(8, lateCenturyCalendar), 2108); }
@Test public void convertTwoDigitYearToFour_whenDateIsNearCenturyAndYearIsLarge_addsNormalBase() { Calendar lateCenturyCalendar = Calendar.getInstance(); lateCenturyCalendar.set(Calendar.YEAR, 2088); assertEquals(DateUtils.convertTwoDigitYearToFour(95, lateCenturyCalendar), 2095); }
@Test public void convertTwoDigitYearToFour_whenDateIsEarlyCenturyAndYearIsLarge_addsLowerBase() { Calendar earlyCenturyCalendar = Calendar.getInstance(); earlyCenturyCalendar.set(Calendar.YEAR, 2502); assertEquals(DateUtils.convertTwoDigitYearToFour(95, earlyCenturyCalendar), 2495); earlyCenturyCalendar.set(Calendar.YEAR, 2017); assertEquals(DateUtils.convertTwoDigitYearToFour(99, earlyCenturyCalendar), 1999); }
@Test public void convertTwoDigitYearToFour_whenDateIsMidCenturyAndYearIsLarge_addsNormalBase() { Calendar midCenturyCalendar = Calendar.getInstance(); midCenturyCalendar.set(Calendar.YEAR, 3535); assertEquals(DateUtils.convertTwoDigitYearToFour(99, midCenturyCalendar), 3599); } |
### Question:
DateUtils { static String createDateStringFromIntegerInput( @IntRange(from = 1, to = 12) int month, @IntRange(from = 0, to = 9999) int year) { String monthString = String.valueOf(month); if (monthString.length() == 1) { monthString = "0" + monthString; } String yearString = String.valueOf(year); if (yearString.length() == 3) { return ""; } if (yearString.length() > 2) { yearString = yearString.substring(yearString.length() - 2); } else if (yearString.length() == 1) { yearString = "0" + yearString; } return monthString + yearString; } }### Answer:
@Test public void createDateStringFromIntegerInput_whenDateHasOneDigitMonthAndYear_addsZero() { assertEquals("0102", DateUtils.createDateStringFromIntegerInput(1, 2)); }
@Test public void createDateStringFromIntegerInput_whenDateHasTwoDigitValues_returnsExpectedValue() { assertEquals("1132", DateUtils.createDateStringFromIntegerInput(11, 32)); }
@Test public void createDateStringFromIntegerInput_whenDateHasFullYear_truncatesYear() { assertEquals("0132", DateUtils.createDateStringFromIntegerInput(1, 2032)); }
@Test public void createDateStringFromIntegerInput_whenDateHasThreeDigitYear_returnsEmpty() { assertEquals("", DateUtils.createDateStringFromIntegerInput(12, 101)); } |
### Question:
DateUtils { static boolean isExpiryDataValid(int expiryMonth, int expiryYear) { return isExpiryDataValid(expiryMonth, expiryYear, Calendar.getInstance()); } }### Answer:
@Test public void isExpiryDataValid_whenDateIsAfterCalendarYear_returnsTrue() { Calendar testCalendar = Calendar.getInstance(); testCalendar.set(Calendar.YEAR, 2018); testCalendar.set(Calendar.MONTH, Calendar.JANUARY); assertTrue(DateUtils.isExpiryDataValid(1, 2019, testCalendar)); }
@Test public void isExpiryDataValid_whenDateIsSameCalendarYearButLaterMonth_returnsTrue() { Calendar testCalendar = Calendar.getInstance(); testCalendar.set(Calendar.YEAR, 2018); testCalendar.set(Calendar.MONTH, Calendar.JANUARY); assertTrue(DateUtils.isExpiryDataValid(2, 2018, testCalendar)); }
@Test public void isExpiryDataValid_whenDateIsSameCalendarYearAndMonth_returnsTrue() { Calendar testCalendar = Calendar.getInstance(); testCalendar.set(Calendar.YEAR, 2018); testCalendar.set(Calendar.MONTH, Calendar.JANUARY); assertTrue(DateUtils.isExpiryDataValid(1, 2018, testCalendar)); }
@Test public void isExpiryDataValid_whenDateIsSameCalendarYearButEarlierMonth_returnsFalse() { Calendar testCalendar = Calendar.getInstance(); testCalendar.set(Calendar.YEAR, 2018); testCalendar.set(Calendar.MONTH, Calendar.MARCH); assertFalse(DateUtils.isExpiryDataValid(1, 2018, testCalendar)); }
@Test public void isExpiryDataValid_whenMonthIsInvalid_returnsFalse() { assertFalse(DateUtils.isExpiryDataValid(15, 2019)); assertFalse(DateUtils.isExpiryDataValid(-1, 2019)); }
@Test public void isExpiryDataValid_whenYearIsInvalid_returnsFalse() { assertFalse(DateUtils.isExpiryDataValid(5, -1)); assertFalse("Should not validate years beyond 9980", DateUtils.isExpiryDataValid(5, 9985)); } |
### Question:
DateUtils { @Size(2) @NonNull static String[] separateDateStringParts(@NonNull @Size(max = 4) String expiryInput) { String[] parts = new String[2]; if (expiryInput.length() >= 2) { parts[0] = expiryInput.substring(0, 2); parts[1] = expiryInput.substring(2); } else { parts[0] = expiryInput; parts[1] = ""; } return parts; } }### Answer:
@Test public void separateDateStringParts_withValidDate_properlySeparatesString() { String[] parts = DateUtils.separateDateStringParts("1234"); String[] expected = {"12", "34"}; assertArrayEquals(expected, parts); }
@Test public void separateDateStringParts_withPartialDate_properlySeparatesString() { String[] parts = DateUtils.separateDateStringParts("123"); String[] expected = {"12", "3"}; assertArrayEquals(expected, parts); }
@Test public void separateDateStringParts_withLessThanHalfOfDate_properlySeparatesString() { String[] parts = DateUtils.separateDateStringParts("1"); String[] expected = {"1", ""}; assertArrayEquals(expected, parts); }
@Test public void separateDateStringParts_withEmptyInput_returnsNonNullEmptyOutput() { String[] parts = DateUtils.separateDateStringParts(""); String[] expected = {"", ""}; assertArrayEquals(expected, parts); } |
### Question:
DateUtils { static boolean isValidMonth(@Nullable String monthString) { if (monthString == null) { return false; } try { int monthInt = Integer.parseInt(monthString); return monthInt > 0 && monthInt <= 12; } catch (NumberFormatException numEx) { return false; } } }### Answer:
@Test public void isValidMonth_forProperMonths_returnsTrue() { String[] validMonths = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"}; for (int i = 0; i < validMonths.length; i++) { assertTrue(DateUtils.isValidMonth(validMonths[i])); } }
@Test public void isValidMonth_forInvalidNumericInput_returnsFalse() { assertFalse(DateUtils.isValidMonth("15")); assertFalse(DateUtils.isValidMonth("0")); assertFalse(DateUtils.isValidMonth("-08")); }
@Test public void isValidMonth_forNullInput_returnsFalse() { assertFalse(DateUtils.isValidMonth(null)); }
@Test public void isValidMonth_forNonNumericInput_returnsFalse() { assertFalse(DateUtils.isValidMonth(" ")); assertFalse(DateUtils.isValidMonth("abc")); assertFalse(DateUtils.isValidMonth("January")); assertFalse(DateUtils.isValidMonth("\n")); } |
### Question:
CountryAdapter extends ArrayAdapter { @NonNull @Override public Filter getFilter() { return mFilter; } CountryAdapter(Context context, List<String> countries); @Override int getCount(); @Override String getItem(int i); @Override long getItemId(int i); @Override View getView(int i, View view, ViewGroup viewGroup); @NonNull @Override Filter getFilter(); }### Answer:
@Test public void filter_whenCountryInputNoMatch_showsAllResults() { Filter filter = mCountryAdapter.getFilter(); filter.filter("NONEXISTANT COUNTRY"); int countryLength = mCountryAdapter.mCountries.size(); assertEquals(mCountryAdapter.mSuggestions.size(), countryLength); }
@Test public void filter_whenCountryInputMatches_filters() { Filter filter = mCountryAdapter.getFilter(); int countryLength = mCountryAdapter.mCountries.size(); filter.filter("a"); assertTrue(mCountryAdapter.mSuggestions.size() < countryLength); for (String suggestedCountry: mCountryAdapter.mSuggestions) { assertTrue(suggestedCountry.toLowerCase().startsWith("a")); } }
@Test public void filter_whenCountryInputMatchesExactly_showsAllResults() { Filter filter = mCountryAdapter.getFilter(); int countryLength = mCountryAdapter.mCountries.size(); filter.filter("Uganda"); assertEquals(mCountryAdapter.mSuggestions.size(), countryLength); } |
### Question:
ViewUtils { static TypedValue getThemeAccentColor(Context context) { int colorAttr; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { colorAttr = android.R.attr.colorAccent; } else { colorAttr = context .getResources() .getIdentifier("colorAccent", "attr", context.getPackageName()); } TypedValue outValue = new TypedValue(); context.getTheme().resolveAttribute(colorAttr, outValue, true); return outValue; } }### Answer:
@Test public void getThemeAccentColor_whenOnPostLollipopConfig_getsNonzeroColor() { @ColorInt int color = ViewUtils.getThemeAccentColor(mActivityController.get()).data; assertTrue(Color.alpha(color) > 0); }
@Test @Config(sdk = 16) public void getThemeAccentColor_whenOnPreKitKatConfig_getsNonzeroColor() { @ColorInt int color = ViewUtils.getThemeAccentColor(mActivityController.get()).data; assertTrue(Color.alpha(color) > 0); } |
### Question:
ViewUtils { static TypedValue getThemeColorControlNormal(Context context) { int colorAttr; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { colorAttr = android.R.attr.colorControlNormal; } else { colorAttr = context .getResources() .getIdentifier("colorControlNormal", "attr", context.getPackageName()); } TypedValue outValue = new TypedValue(); context.getTheme().resolveAttribute(colorAttr, outValue, true); return outValue; } }### Answer:
@Test public void getThemeColorControlNormal_whenOnPostLollipopConfig_getsNonzeroColor() { @ColorInt int color = ViewUtils.getThemeColorControlNormal(mActivityController.get()).data; assertTrue(Color.alpha(color) > 0); }
@Test @Config(sdk = 16) public void getThemeColorControlNormal_whenOnPreKitKatConfig_getsNonzeroColor() { @ColorInt int color = ViewUtils.getThemeColorControlNormal(mActivityController.get()).data; assertTrue(Color.alpha(color) > 0); } |
### Question:
ViewUtils { static boolean isColorTransparent(@ColorInt int color) { return Color.alpha(color) < 0x10; } }### Answer:
@Test public void isColorTransparent_whenColorIsZero_returnsTrue() { assertTrue(ViewUtils.isColorTransparent(0)); }
@Test public void isColorTransparent_whenColorIsNonzeroButHasLowAlpha_returnsTrue() { @ColorInt int invisibleBlue = 0x050000ff; @ColorInt int invisibleRed = 0x0bff0000; assertTrue(ViewUtils.isColorTransparent(invisibleBlue)); assertTrue(ViewUtils.isColorTransparent(invisibleRed)); }
@Test public void isColorTransparent_whenColorIsNotCloseToTransparent_returnsFalse() { @ColorInt int brightWhite = 0xffffffff; @ColorInt int completelyBlack = 0xff000000; assertFalse(ViewUtils.isColorTransparent(brightWhite)); assertFalse(ViewUtils.isColorTransparent(completelyBlack)); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.