method2testcases
stringlengths
118
3.08k
### Question: RedisList extends Commands { public long insertBefore(String key, String pivot, String value) { return getJedis().linsert(key, BinaryClient.LIST_POSITION.BEFORE, pivot, value); } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer: @Test public void testInsertBefore() throws Exception { deleteKeyForTest(); redisList.lPush(testKey,"12"); long result = redisList.insertBefore(testKey, "12", "value"); Assert.assertEquals(2L, result); deleteKeyForTest(); }
### Question: RedisList extends Commands { public List<String> range(String key, long start, long end) { logger.debug("Get range: [" + key + "] form " + start + " to " + end); return getJedis().lrange(key, start, end); } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer: @Test public void testRange() throws Exception { deleteKeyForTest(); redisList.rPush(testKey,"23","12"); List<String> result = redisList.range(testKey, 0L, -1L); Assert.assertEquals(Arrays.<String>asList("23","12"), result); deleteKeyForTest(); }
### Question: RedisList extends Commands { public long remove(String key, long count, String value) { return getJedis().lrem(key, count, value); } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer: @Test public void testRemove() throws Exception { deleteKeyForTest(); redisList.lPush(testKey,"23","123","23"); redisList.remove(testKey, 1L, "23"); Assert.assertEquals(Arrays.<String>asList("123","23"), redisList.allElements(testKey)); redisList.lPush(testKey,"23"); redisList.remove(testKey, -1L, "23"); Assert.assertEquals(Arrays.<String>asList("23","123"), redisList.allElements(testKey)); deleteKeyForTest(); }
### Question: RedisList extends Commands { public String trim(String key, long start, long end) { return getJedis().ltrim(key, start, end); } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer: @Test public void testTrim() throws Exception { deleteKeyForTest(); redisList.rPush(testKey,"1","2","3","4"); String result = redisList.trim(testKey, 0L, 1L); Assert.assertEquals(Arrays.<String>asList("1","2"), redisList.allElements(testKey)); Assert.assertEquals("OK",result); }
### Question: RedisList extends Commands { public String index(String key, long index) { return getJedis().lindex(key, index); } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer: @Test public void testIndex() throws Exception { deleteKeyForTest(); redisList.rPush(testKey,"tests"); String result = redisList.index(testKey, 0L); Assert.assertEquals("tests", result); deleteKeyForTest(); }
### Question: RedisSet extends Commands { public Long save(String key, String... member) { return getJedis().sadd(key, member); } private RedisSet(); synchronized static RedisSet getInstance(); Long save(String key, String... member); Long remove(String key, String... members); Set<String> getMembersSet(String key); String pop(String key); Set<String> pop(String key, long count); Long size(String key); boolean contain(String key, String member); String randomMember(String key); List<String> randomMember(String key, int count); Set<String> inter(String... keys); Long interStore(String key, String... keys); Set<String> union(String... keys); Long unionStore(String key, String... keys); Set<String> diff(String... keys); Long diffStore(String key, String... keys); Long moveMember(String fromKey, String toKey, String member); }### Answer: @Test public void testAdd() throws Exception { deleteKey(); Long result = redisSet.save(key, "member","12","12"); Assert.assertEquals((Long)2L, result); showKey(); deleteKey(); }
### Question: RedisSet extends Commands { public Long remove(String key, String... members) { return getJedis().srem(key, members); } private RedisSet(); synchronized static RedisSet getInstance(); Long save(String key, String... member); Long remove(String key, String... members); Set<String> getMembersSet(String key); String pop(String key); Set<String> pop(String key, long count); Long size(String key); boolean contain(String key, String member); String randomMember(String key); List<String> randomMember(String key, int count); Set<String> inter(String... keys); Long interStore(String key, String... keys); Set<String> union(String... keys); Long unionStore(String key, String... keys); Set<String> diff(String... keys); Long diffStore(String key, String... keys); Long moveMember(String fromKey, String toKey, String member); }### Answer: @Test public void testRemove() throws Exception { redisSet.save(key,"2","23","3434","343223"); Long result = redisSet.remove(key, "2","23"); Assert.assertEquals((Long)2L, result); deleteKey(); }
### Question: RedisSet extends Commands { public Set<String> getMembersSet(String key) { return getJedis().smembers(key); } private RedisSet(); synchronized static RedisSet getInstance(); Long save(String key, String... member); Long remove(String key, String... members); Set<String> getMembersSet(String key); String pop(String key); Set<String> pop(String key, long count); Long size(String key); boolean contain(String key, String member); String randomMember(String key); List<String> randomMember(String key, int count); Set<String> inter(String... keys); Long interStore(String key, String... keys); Set<String> union(String... keys); Long unionStore(String key, String... keys); Set<String> diff(String... keys); Long diffStore(String key, String... keys); Long moveMember(String fromKey, String toKey, String member); }### Answer: @Test public void testGetMembersSet() throws Exception { redisSet.save(key,"2","23"); Set<String> result = redisSet.getMembersSet(key); Assert.assertEquals(new HashSet<String>(Arrays.asList("2","23")), result); deleteKey(); }
### Question: PropertyFile { public static String update(String key,String value) throws ReadConfigException { String result; try { props = getProperties(Configs.PROPERTY_FILE); OutputStream fos = new FileOutputStream(Configs.PROPERTY_FILE); result = (String)props.replace(key,value); props.store(fos, "Update '" + key + "' value"); }catch (Exception e){ e.printStackTrace(); throw new ReadConfigException(ExceptionInfo.UPDATE_CONFIG_KEY_FAILED,e,PropertyFile.class); } return result; } static MythProperties getProperties(String propertyFile); static String save(String key, String value); static String delete(String key); static String update(String key,String value); static int getMaxId(); static Map<String,RedisPoolProperty> getAllPoolConfig(); }### Answer: @Test public void testUpdate() throws Exception { PropertyFile.save(testKey,"origin"); String result = PropertyFile.update(testKey, "value"); PropertyFile.delete(testKey); Assert.assertEquals("origin", result); }
### Question: RedisSet extends Commands { public String pop(String key) { return getJedis().spop(key); } private RedisSet(); synchronized static RedisSet getInstance(); Long save(String key, String... member); Long remove(String key, String... members); Set<String> getMembersSet(String key); String pop(String key); Set<String> pop(String key, long count); Long size(String key); boolean contain(String key, String member); String randomMember(String key); List<String> randomMember(String key, int count); Set<String> inter(String... keys); Long interStore(String key, String... keys); Set<String> union(String... keys); Long unionStore(String key, String... keys); Set<String> diff(String... keys); Long diffStore(String key, String... keys); Long moveMember(String fromKey, String toKey, String member); }### Answer: @Test public void testPop() throws Exception { redisSet.save(key,"1","2","3"); String result = redisSet.pop(key); System.out.println("随机删除:"+result); Long results = redisSet.size(key); Assert.assertEquals((Long)2L,results); deleteKey(); }
### Question: RedisSet extends Commands { public boolean contain(String key, String member) { return getJedis().sismember(key, member); } private RedisSet(); synchronized static RedisSet getInstance(); Long save(String key, String... member); Long remove(String key, String... members); Set<String> getMembersSet(String key); String pop(String key); Set<String> pop(String key, long count); Long size(String key); boolean contain(String key, String member); String randomMember(String key); List<String> randomMember(String key, int count); Set<String> inter(String... keys); Long interStore(String key, String... keys); Set<String> union(String... keys); Long unionStore(String key, String... keys); Set<String> diff(String... keys); Long diffStore(String key, String... keys); Long moveMember(String fromKey, String toKey, String member); }### Answer: @Test public void testContain() throws Exception { redisSet.save(key,"member"); boolean result = redisSet.contain(key, "member"); Assert.assertEquals(true, result); deleteKey(); }
### Question: RedisSet extends Commands { public String randomMember(String key) { return getJedis().srandmember(key); } private RedisSet(); synchronized static RedisSet getInstance(); Long save(String key, String... member); Long remove(String key, String... members); Set<String> getMembersSet(String key); String pop(String key); Set<String> pop(String key, long count); Long size(String key); boolean contain(String key, String member); String randomMember(String key); List<String> randomMember(String key, int count); Set<String> inter(String... keys); Long interStore(String key, String... keys); Set<String> union(String... keys); Long unionStore(String key, String... keys); Set<String> diff(String... keys); Long diffStore(String key, String... keys); Long moveMember(String fromKey, String toKey, String member); }### Answer: @Test public void testRandomMember() throws Exception { redisSet.save(key,"sa"); String result = redisSet.randomMember(key); assert result!=null; deleteKey(); }
### Question: RedisSet extends Commands { public Set<String> inter(String... keys) { return getJedis().sinter(keys); } private RedisSet(); synchronized static RedisSet getInstance(); Long save(String key, String... member); Long remove(String key, String... members); Set<String> getMembersSet(String key); String pop(String key); Set<String> pop(String key, long count); Long size(String key); boolean contain(String key, String member); String randomMember(String key); List<String> randomMember(String key, int count); Set<String> inter(String... keys); Long interStore(String key, String... keys); Set<String> union(String... keys); Long unionStore(String key, String... keys); Set<String> diff(String... keys); Long diffStore(String key, String... keys); Long moveMember(String fromKey, String toKey, String member); }### Answer: @Test public void testInter() throws Exception { redisSet.save(key,"1","2","3"); redisSet.save("1","2","4"); Set<String> result = redisSet.inter(key,"1"); Assert.assertEquals(new HashSet<String>(Arrays.asList("2")), result); redisSet.deleteKey(key,"1"); }
### Question: RedisSet extends Commands { public Long interStore(String key, String... keys) { return getJedis().sinterstore(key, keys); } private RedisSet(); synchronized static RedisSet getInstance(); Long save(String key, String... member); Long remove(String key, String... members); Set<String> getMembersSet(String key); String pop(String key); Set<String> pop(String key, long count); Long size(String key); boolean contain(String key, String member); String randomMember(String key); List<String> randomMember(String key, int count); Set<String> inter(String... keys); Long interStore(String key, String... keys); Set<String> union(String... keys); Long unionStore(String key, String... keys); Set<String> diff(String... keys); Long diffStore(String key, String... keys); Long moveMember(String fromKey, String toKey, String member); }### Answer: @Test public void testInterStore() throws Exception { redisSet.save("store","1","23","45"); System.out.println(redisSet.getMembersSet("store")); redisSet.save(key,"1","2","3"); redisSet.save("1","2","4"); Long f = redisSet.interStore("store",key,"1"); System.out.println(f+" : "+redisSet.getMembersSet("store").toString()); Set<String> result = redisSet.getMembersSet("store"); Assert.assertEquals(new HashSet<String>(Arrays.asList("2")),result); redisSet.deleteKey(key,"1","store"); }
### Question: RedisSet extends Commands { public Set<String> union(String... keys) { return getJedis().sunion(keys); } private RedisSet(); synchronized static RedisSet getInstance(); Long save(String key, String... member); Long remove(String key, String... members); Set<String> getMembersSet(String key); String pop(String key); Set<String> pop(String key, long count); Long size(String key); boolean contain(String key, String member); String randomMember(String key); List<String> randomMember(String key, int count); Set<String> inter(String... keys); Long interStore(String key, String... keys); Set<String> union(String... keys); Long unionStore(String key, String... keys); Set<String> diff(String... keys); Long diffStore(String key, String... keys); Long moveMember(String fromKey, String toKey, String member); }### Answer: @Test public void testUnion() throws Exception { redisSet.save("1","1","2","3"); redisSet.save("2","2","3","4"); Set<String> result = redisSet.union("1","2"); Assert.assertEquals(new HashSet<String>(Arrays.asList("1","2","3","4")), result); redisSet.deleteKey("1","2"); }
### Question: RedisSet extends Commands { public Long unionStore(String key, String... keys) { return getJedis().sunionstore(key, keys); } private RedisSet(); synchronized static RedisSet getInstance(); Long save(String key, String... member); Long remove(String key, String... members); Set<String> getMembersSet(String key); String pop(String key); Set<String> pop(String key, long count); Long size(String key); boolean contain(String key, String member); String randomMember(String key); List<String> randomMember(String key, int count); Set<String> inter(String... keys); Long interStore(String key, String... keys); Set<String> union(String... keys); Long unionStore(String key, String... keys); Set<String> diff(String... keys); Long diffStore(String key, String... keys); Long moveMember(String fromKey, String toKey, String member); }### Answer: @Test public void testUnionStore() throws Exception { redisSet.save("1","1","2","3"); redisSet.save("2","2","3","4"); Long num = redisSet.unionStore("store","1","2"); System.out.println(num); Set<String> result = redisSet.getMembersSet("store"); Assert.assertEquals(new HashSet<String>(Arrays.asList("1","2","3","4")), result); redisSet.deleteKey("1","2","store"); }
### Question: RedisSet extends Commands { public Set<String> diff(String... keys) { return getJedis().sdiff(keys); } private RedisSet(); synchronized static RedisSet getInstance(); Long save(String key, String... member); Long remove(String key, String... members); Set<String> getMembersSet(String key); String pop(String key); Set<String> pop(String key, long count); Long size(String key); boolean contain(String key, String member); String randomMember(String key); List<String> randomMember(String key, int count); Set<String> inter(String... keys); Long interStore(String key, String... keys); Set<String> union(String... keys); Long unionStore(String key, String... keys); Set<String> diff(String... keys); Long diffStore(String key, String... keys); Long moveMember(String fromKey, String toKey, String member); }### Answer: @Test public void testDiff() throws Exception { redisSet.save("1","1","2","3","5"); redisSet.save("2","2","3","4","6"); redisSet.save("3","1","4"); Set<String> result = redisSet.diff("1","2","3"); Assert.assertEquals(new HashSet<String>(Arrays.asList("5")), result); redisSet.deleteKey("1","2"); }
### Question: RedisSet extends Commands { public Long diffStore(String key, String... keys) { return getJedis().sdiffstore(key, keys); } private RedisSet(); synchronized static RedisSet getInstance(); Long save(String key, String... member); Long remove(String key, String... members); Set<String> getMembersSet(String key); String pop(String key); Set<String> pop(String key, long count); Long size(String key); boolean contain(String key, String member); String randomMember(String key); List<String> randomMember(String key, int count); Set<String> inter(String... keys); Long interStore(String key, String... keys); Set<String> union(String... keys); Long unionStore(String key, String... keys); Set<String> diff(String... keys); Long diffStore(String key, String... keys); Long moveMember(String fromKey, String toKey, String member); }### Answer: @Test public void testDiffStore() throws Exception { redisSet.save("1","1","2","3","5"); redisSet.save("2","2","3","4","6"); redisSet.save("3","1","4"); Long num = redisSet.diffStore("store","1","2","3"); System.out.println(num); Set<String> result = redisSet.getMembersSet("store"); Assert.assertEquals(new HashSet<String>(Arrays.asList("5")), result); redisSet.deleteKey("store","1","2","3"); }
### Question: RedisSet extends Commands { public Long moveMember(String fromKey, String toKey, String member) { return getJedis().smove(fromKey, toKey, member); } private RedisSet(); synchronized static RedisSet getInstance(); Long save(String key, String... member); Long remove(String key, String... members); Set<String> getMembersSet(String key); String pop(String key); Set<String> pop(String key, long count); Long size(String key); boolean contain(String key, String member); String randomMember(String key); List<String> randomMember(String key, int count); Set<String> inter(String... keys); Long interStore(String key, String... keys); Set<String> union(String... keys); Long unionStore(String key, String... keys); Set<String> diff(String... keys); Long diffStore(String key, String... keys); Long moveMember(String fromKey, String toKey, String member); }### Answer: @Test public void testMoveMember() throws Exception { redisSet.save("1","2","3"); redisSet.save("2","2"); Long re = redisSet.moveMember("1", "2", "3"); System.out.println(re); Set<String> results = redisSet.getMembersSet("2"); Assert.assertEquals(new HashSet<String>(Arrays.asList("2","3")),results); redisSet.deleteKey("1","2"); }
### Question: PropertyFile { public static int getMaxId() throws ReadConfigException { String maxId; try { props = getProperties(Configs.PROPERTY_FILE); maxId = props.getString(Configs.MAX_POOL_ID); if (maxId == null) { save(Configs.MAX_POOL_ID, Configs.START_ID + ""); props = getProperties(Configs.PROPERTY_FILE); maxId = props.getString(Configs.MAX_POOL_ID); } }catch (Exception e){ e.printStackTrace(); throw new ReadConfigException(ExceptionInfo.OPEN_CONFIG_FAILED+"-获取maxId",e,PropertyFile.class); } return Integer.parseInt(maxId); } static MythProperties getProperties(String propertyFile); static String save(String key, String value); static String delete(String key); static String update(String key,String value); static int getMaxId(); static Map<String,RedisPoolProperty> getAllPoolConfig(); }### Answer: @Test public void testMaxId() throws ReadConfigException { int maxId = PropertyFile.getMaxId(); System.out.println(maxId); assert(maxId>=1000); }
### Question: RedisSortSet extends Commands { public Long save(String key, Double score, String member) { return getJedis().zadd(key, score, member); } private RedisSortSet(); synchronized static RedisSortSet getInstance(); Long save(String key, Double score, String member); Long index(String key, String member); Double score(String key, String member); Long rank(String key, String member); Set<String> range(String key, long start, long end); Set<Tuple> rangeWithScores(String key, long start, long end); Set<String> rangeByIndex(String key, long start, long end); Set<String> rangeByScore(String key, Double min, Double max); Set<String> rangeByLex(String key, String max, String min); Long removeByLex(String key, String min, String max); Long countByLex(String key, String min, String max); Set<String> getMemberSet(String key); Set<String> getMemberSetDesc(String key); Set<Tuple> getMemberSetWithScore(String key); Long interStore(String desKey, String... fromKey); Double increase(String key, Double score, String member); Long remove(String key, String... value); Long removeByRank(String key, long start, long end); Long removeByScore(String key, Double min, Double max); Long size(String key); Long count(String key, double min, double max); }### Answer: @Test public void testAdd() throws Exception { redisSortSet.save(key,3.3,"one"); redisSortSet.save(key,5.3,"two"); Long result = redisSortSet.save(key, 2.12, "member"); show(); Assert.assertEquals((Long)1L, result); }
### Question: RedisSortSet extends Commands { public Long index(String key, String member) { return getJedis().zrank(key, member); } private RedisSortSet(); synchronized static RedisSortSet getInstance(); Long save(String key, Double score, String member); Long index(String key, String member); Double score(String key, String member); Long rank(String key, String member); Set<String> range(String key, long start, long end); Set<Tuple> rangeWithScores(String key, long start, long end); Set<String> rangeByIndex(String key, long start, long end); Set<String> rangeByScore(String key, Double min, Double max); Set<String> rangeByLex(String key, String max, String min); Long removeByLex(String key, String min, String max); Long countByLex(String key, String min, String max); Set<String> getMemberSet(String key); Set<String> getMemberSetDesc(String key); Set<Tuple> getMemberSetWithScore(String key); Long interStore(String desKey, String... fromKey); Double increase(String key, Double score, String member); Long remove(String key, String... value); Long removeByRank(String key, long start, long end); Long removeByScore(String key, Double min, Double max); Long size(String key); Long count(String key, double min, double max); }### Answer: @Test public void testIndex() throws Exception { redisSortSet.save(key, 2.12, "members"); redisSortSet.save(key, 2.52, "member"); redisSortSet.save(key, 2.02, "member"); Long result = redisSortSet.index(key, "member"); show(); Assert.assertEquals((Long)0L, result); }
### Question: RedisSortSet extends Commands { public Double score(String key, String member) { return getJedis().zscore(key, member); } private RedisSortSet(); synchronized static RedisSortSet getInstance(); Long save(String key, Double score, String member); Long index(String key, String member); Double score(String key, String member); Long rank(String key, String member); Set<String> range(String key, long start, long end); Set<Tuple> rangeWithScores(String key, long start, long end); Set<String> rangeByIndex(String key, long start, long end); Set<String> rangeByScore(String key, Double min, Double max); Set<String> rangeByLex(String key, String max, String min); Long removeByLex(String key, String min, String max); Long countByLex(String key, String min, String max); Set<String> getMemberSet(String key); Set<String> getMemberSetDesc(String key); Set<Tuple> getMemberSetWithScore(String key); Long interStore(String desKey, String... fromKey); Double increase(String key, Double score, String member); Long remove(String key, String... value); Long removeByRank(String key, long start, long end); Long removeByScore(String key, Double min, Double max); Long size(String key); Long count(String key, double min, double max); }### Answer: @Test public void testScore() throws Exception { redisSortSet.save(key, 2.52, "member"); Double result = redisSortSet.score(key, "member"); show(); Assert.assertEquals((Double)2.52, result); }
### Question: RedisSortSet extends Commands { public Long rank(String key, String member) { return getJedis().zrevrank(key, member); } private RedisSortSet(); synchronized static RedisSortSet getInstance(); Long save(String key, Double score, String member); Long index(String key, String member); Double score(String key, String member); Long rank(String key, String member); Set<String> range(String key, long start, long end); Set<Tuple> rangeWithScores(String key, long start, long end); Set<String> rangeByIndex(String key, long start, long end); Set<String> rangeByScore(String key, Double min, Double max); Set<String> rangeByLex(String key, String max, String min); Long removeByLex(String key, String min, String max); Long countByLex(String key, String min, String max); Set<String> getMemberSet(String key); Set<String> getMemberSetDesc(String key); Set<Tuple> getMemberSetWithScore(String key); Long interStore(String desKey, String... fromKey); Double increase(String key, Double score, String member); Long remove(String key, String... value); Long removeByRank(String key, long start, long end); Long removeByScore(String key, Double min, Double max); Long size(String key); Long count(String key, double min, double max); }### Answer: @Test public void testRank() throws Exception { redisSortSet.save(key, 2.52, "member"); redisSortSet.save(key, 2.52, "members"); Long result = redisSortSet.rank(key, "member"); Assert.assertEquals((Long)1L, result); }
### Question: RedisSortSet extends Commands { public Set<String> rangeByIndex(String key, long start, long end) { return getJedis().zrevrange(key, start, end); } private RedisSortSet(); synchronized static RedisSortSet getInstance(); Long save(String key, Double score, String member); Long index(String key, String member); Double score(String key, String member); Long rank(String key, String member); Set<String> range(String key, long start, long end); Set<Tuple> rangeWithScores(String key, long start, long end); Set<String> rangeByIndex(String key, long start, long end); Set<String> rangeByScore(String key, Double min, Double max); Set<String> rangeByLex(String key, String max, String min); Long removeByLex(String key, String min, String max); Long countByLex(String key, String min, String max); Set<String> getMemberSet(String key); Set<String> getMemberSetDesc(String key); Set<Tuple> getMemberSetWithScore(String key); Long interStore(String desKey, String... fromKey); Double increase(String key, Double score, String member); Long remove(String key, String... value); Long removeByRank(String key, long start, long end); Long removeByScore(String key, Double min, Double max); Long size(String key); Long count(String key, double min, double max); }### Answer: @Test public void testRangeByIndex() throws Exception { redisSortSet.save(key,2.3,"a"); redisSortSet.save(key,2.3,"b"); redisSortSet.save(key,2.1,"c"); Set<String> result = redisSortSet.rangeByIndex(key, 0L, 1L); for(String s:result){ System.out.println(s); } show(); Assert.assertEquals(new HashSet<String>(Arrays.asList("b","a")), result); }
### Question: RedisSortSet extends Commands { public Set<String> rangeByScore(String key, Double min, Double max) { return getJedis().zrevrangeByScore(key, max, min); } private RedisSortSet(); synchronized static RedisSortSet getInstance(); Long save(String key, Double score, String member); Long index(String key, String member); Double score(String key, String member); Long rank(String key, String member); Set<String> range(String key, long start, long end); Set<Tuple> rangeWithScores(String key, long start, long end); Set<String> rangeByIndex(String key, long start, long end); Set<String> rangeByScore(String key, Double min, Double max); Set<String> rangeByLex(String key, String max, String min); Long removeByLex(String key, String min, String max); Long countByLex(String key, String min, String max); Set<String> getMemberSet(String key); Set<String> getMemberSetDesc(String key); Set<Tuple> getMemberSetWithScore(String key); Long interStore(String desKey, String... fromKey); Double increase(String key, Double score, String member); Long remove(String key, String... value); Long removeByRank(String key, long start, long end); Long removeByScore(String key, Double min, Double max); Long size(String key); Long count(String key, double min, double max); }### Answer: @Test public void testRangeByScore() throws Exception { redisSortSet.save(key,2.3,"a"); redisSortSet.save(key,2.3,"b"); redisSortSet.save(key,2.1,"c"); Set<String> result = redisSortSet.rangeByScore(key, 0d, 2.2d); for(String s:result){ System.out.println(s); } show(); Assert.assertEquals(new HashSet<String>(Arrays.asList("b","a","c")), result); }
### Question: RedisSortSet extends Commands { public Long interStore(String desKey, String... fromKey) { return getJedis().zinterstore(desKey, fromKey); } private RedisSortSet(); synchronized static RedisSortSet getInstance(); Long save(String key, Double score, String member); Long index(String key, String member); Double score(String key, String member); Long rank(String key, String member); Set<String> range(String key, long start, long end); Set<Tuple> rangeWithScores(String key, long start, long end); Set<String> rangeByIndex(String key, long start, long end); Set<String> rangeByScore(String key, Double min, Double max); Set<String> rangeByLex(String key, String max, String min); Long removeByLex(String key, String min, String max); Long countByLex(String key, String min, String max); Set<String> getMemberSet(String key); Set<String> getMemberSetDesc(String key); Set<Tuple> getMemberSetWithScore(String key); Long interStore(String desKey, String... fromKey); Double increase(String key, Double score, String member); Long remove(String key, String... value); Long removeByRank(String key, long start, long end); Long removeByScore(String key, Double min, Double max); Long size(String key); Long count(String key, double min, double max); }### Answer: @Test public void testInterStore() throws Exception { redisSortSet.save(key,1.1,"a"); redisSortSet.save(key,1.1,"b"); redisSortSet.save("key1",1.1,"b"); redisSortSet.save("key1",1.1,"a"); redisSortSet.save("key2",1.1,"a"); redisSortSet.save(key,1.1,"t"); Long result = redisSortSet.interStore("desKey", key,"key1"); show(key,"key1","desKey","key2"); Assert.assertEquals((Long)2L, result); }
### Question: RedisSortSet extends Commands { public Double increase(String key, Double score, String member) { return getJedis().zincrby(key, score, member); } private RedisSortSet(); synchronized static RedisSortSet getInstance(); Long save(String key, Double score, String member); Long index(String key, String member); Double score(String key, String member); Long rank(String key, String member); Set<String> range(String key, long start, long end); Set<Tuple> rangeWithScores(String key, long start, long end); Set<String> rangeByIndex(String key, long start, long end); Set<String> rangeByScore(String key, Double min, Double max); Set<String> rangeByLex(String key, String max, String min); Long removeByLex(String key, String min, String max); Long countByLex(String key, String min, String max); Set<String> getMemberSet(String key); Set<String> getMemberSetDesc(String key); Set<Tuple> getMemberSetWithScore(String key); Long interStore(String desKey, String... fromKey); Double increase(String key, Double score, String member); Long remove(String key, String... value); Long removeByRank(String key, long start, long end); Long removeByScore(String key, Double min, Double max); Long size(String key); Long count(String key, double min, double max); }### Answer: @Test public void testIncrease() throws Exception { redisSortSet.save(key,1.1,"member"); Double result = redisSortSet.increase(key, 1.1, "member"); show(); Assert.assertEquals((Double)2.2d, result); }
### Question: RedisSortSet extends Commands { public Long remove(String key, String... value) { return getJedis().zrem(key, value); } private RedisSortSet(); synchronized static RedisSortSet getInstance(); Long save(String key, Double score, String member); Long index(String key, String member); Double score(String key, String member); Long rank(String key, String member); Set<String> range(String key, long start, long end); Set<Tuple> rangeWithScores(String key, long start, long end); Set<String> rangeByIndex(String key, long start, long end); Set<String> rangeByScore(String key, Double min, Double max); Set<String> rangeByLex(String key, String max, String min); Long removeByLex(String key, String min, String max); Long countByLex(String key, String min, String max); Set<String> getMemberSet(String key); Set<String> getMemberSetDesc(String key); Set<Tuple> getMemberSetWithScore(String key); Long interStore(String desKey, String... fromKey); Double increase(String key, Double score, String member); Long remove(String key, String... value); Long removeByRank(String key, long start, long end); Long removeByScore(String key, Double min, Double max); Long size(String key); Long count(String key, double min, double max); }### Answer: @Test public void testRemove() throws Exception { redisSortSet.save(key,1.1,"value"); Long result = redisSortSet.remove(key, "value"); show(); Assert.assertEquals((Long)1L, result); }
### Question: RedisSortSet extends Commands { public Long removeByRank(String key, long start, long end) { return getJedis().zremrangeByRank(key, start, end); } private RedisSortSet(); synchronized static RedisSortSet getInstance(); Long save(String key, Double score, String member); Long index(String key, String member); Double score(String key, String member); Long rank(String key, String member); Set<String> range(String key, long start, long end); Set<Tuple> rangeWithScores(String key, long start, long end); Set<String> rangeByIndex(String key, long start, long end); Set<String> rangeByScore(String key, Double min, Double max); Set<String> rangeByLex(String key, String max, String min); Long removeByLex(String key, String min, String max); Long countByLex(String key, String min, String max); Set<String> getMemberSet(String key); Set<String> getMemberSetDesc(String key); Set<Tuple> getMemberSetWithScore(String key); Long interStore(String desKey, String... fromKey); Double increase(String key, Double score, String member); Long remove(String key, String... value); Long removeByRank(String key, long start, long end); Long removeByScore(String key, Double min, Double max); Long size(String key); Long count(String key, double min, double max); }### Answer: @Test public void testRemoveByRank() throws Exception { redisSortSet.save(key,2.3,"a"); redisSortSet.save(key,2.3,"b"); redisSortSet.save(key,2.1,"c"); redisSortSet.save(key,2.3,"d"); redisSortSet.save(key,2.3,"r"); redisSortSet.save(key,2.1,"u"); Long result = redisSortSet.removeByRank(key, 0L, 1L); show(); Assert.assertEquals((Long)2L, result); }
### Question: PropertyFile { public static Map<String,RedisPoolProperty> getAllPoolConfig() throws ReadConfigException { Map<String,RedisPoolProperty> map = new HashMap<>(); int maxId; try { maxId = getMaxId(); props = getProperties(Configs.PROPERTY_FILE); } catch (IOException e) { e.printStackTrace(); logger.error(ExceptionInfo.OPEN_CONFIG_FAILED,e); return map; } for(int i=Configs.START_ID;i<=maxId;i++){ String poolId = props.getString(i+Configs.SEPARATE+Configs.POOL_ID); if(poolId==null) continue; RedisPoolProperty property = RedisPoolProperty.initByIdFromConfig(poolId); map.put(poolId,property); } return map; } static MythProperties getProperties(String propertyFile); static String save(String key, String value); static String delete(String key); static String update(String key,String value); static int getMaxId(); static Map<String,RedisPoolProperty> getAllPoolConfig(); }### Answer: @Test public void testList() throws Exception { Map<String,RedisPoolProperty> map = PropertyFile.getAllPoolConfig(); for(String key:map.keySet()){ System.out.println(">> "+key+" <<"); RedisPoolProperty property = map.get(key); Map lists= MythReflect.getFieldsValue(property); for(Object keys:lists.keySet()){ System.out.println(keys.toString()+":"+lists.get(keys)); } System.out.println("----------------------------------------------------"); } }
### Question: RedisSortSet extends Commands { public Long removeByScore(String key, Double min, Double max) { return getJedis().zremrangeByScore(key, min, max); } private RedisSortSet(); synchronized static RedisSortSet getInstance(); Long save(String key, Double score, String member); Long index(String key, String member); Double score(String key, String member); Long rank(String key, String member); Set<String> range(String key, long start, long end); Set<Tuple> rangeWithScores(String key, long start, long end); Set<String> rangeByIndex(String key, long start, long end); Set<String> rangeByScore(String key, Double min, Double max); Set<String> rangeByLex(String key, String max, String min); Long removeByLex(String key, String min, String max); Long countByLex(String key, String min, String max); Set<String> getMemberSet(String key); Set<String> getMemberSetDesc(String key); Set<Tuple> getMemberSetWithScore(String key); Long interStore(String desKey, String... fromKey); Double increase(String key, Double score, String member); Long remove(String key, String... value); Long removeByRank(String key, long start, long end); Long removeByScore(String key, Double min, Double max); Long size(String key); Long count(String key, double min, double max); }### Answer: @Test public void testRemoveByScore() throws Exception { redisSortSet.save(key,2.3,"a"); redisSortSet.save(key,2.3,"b"); redisSortSet.save(key,2.1,"c"); redisSortSet.save(key,1.9,"d"); redisSortSet.save(key,2.0,"r"); redisSortSet.save(key,2.1,"u"); Long result = redisSortSet.removeByScore(key, 1.9d, 2.1d); Assert.assertEquals((Long)4L, result); }
### Question: RedisSortSet extends Commands { public Long size(String key) { return getJedis().zcard(key); } private RedisSortSet(); synchronized static RedisSortSet getInstance(); Long save(String key, Double score, String member); Long index(String key, String member); Double score(String key, String member); Long rank(String key, String member); Set<String> range(String key, long start, long end); Set<Tuple> rangeWithScores(String key, long start, long end); Set<String> rangeByIndex(String key, long start, long end); Set<String> rangeByScore(String key, Double min, Double max); Set<String> rangeByLex(String key, String max, String min); Long removeByLex(String key, String min, String max); Long countByLex(String key, String min, String max); Set<String> getMemberSet(String key); Set<String> getMemberSetDesc(String key); Set<Tuple> getMemberSetWithScore(String key); Long interStore(String desKey, String... fromKey); Double increase(String key, Double score, String member); Long remove(String key, String... value); Long removeByRank(String key, long start, long end); Long removeByScore(String key, Double min, Double max); Long size(String key); Long count(String key, double min, double max); }### Answer: @Test public void testSize() throws Exception { redisSortSet.save(key,2.3,"a"); redisSortSet.save(key,2.3,"b"); redisSortSet.save(key,2.1,"c"); Long result = redisSortSet.size(key); show(); Assert.assertEquals((Long)3L, result); }
### Question: RedisSortSet extends Commands { public Long count(String key, double min, double max) { return getJedis().zcount(key, min, max); } private RedisSortSet(); synchronized static RedisSortSet getInstance(); Long save(String key, Double score, String member); Long index(String key, String member); Double score(String key, String member); Long rank(String key, String member); Set<String> range(String key, long start, long end); Set<Tuple> rangeWithScores(String key, long start, long end); Set<String> rangeByIndex(String key, long start, long end); Set<String> rangeByScore(String key, Double min, Double max); Set<String> rangeByLex(String key, String max, String min); Long removeByLex(String key, String min, String max); Long countByLex(String key, String min, String max); Set<String> getMemberSet(String key); Set<String> getMemberSetDesc(String key); Set<Tuple> getMemberSetWithScore(String key); Long interStore(String desKey, String... fromKey); Double increase(String key, Double score, String member); Long remove(String key, String... value); Long removeByRank(String key, long start, long end); Long removeByScore(String key, Double min, Double max); Long size(String key); Long count(String key, double min, double max); }### Answer: @Test public void testCount() throws Exception { redisSortSet.save(key,2.3,"a"); redisSortSet.save(key,2.3,"b"); redisSortSet.save(key,2.1,"c"); Long result = redisSortSet.count(key, 2.1,2.2); show(); Assert.assertEquals((Long)1L, result); }
### Question: RedisKey extends Commands { public String set(String key, String value) { return getJedis().set(key, value); } private RedisKey(); synchronized static RedisKey getInstance(); String get(String key); String set(String key, String value); byte[] dump(String key); Long setExpire(String key, int second, String value); String setExpireMs(String key, long second, String value); long increaseKey(String key); long decreaseKey(String key); long append(String key, String value); List<String> getMultiKeys(String... keys); String setMultiKey(String... keys); String getEncoding(String key); Set<String> listAllKeys(int db); }### Answer: @Test public void createData1(){ for(int i=0;i<5000;i++){ redisKey.set("aaa"+i,"dfdfdfdf"); } } @Test public void createData2(){ for(int i=0;i<5000;i++){ redisKey.set("qq"+i,"dfdfdfdf"); } } @Test public void createData3(){ for(int i=0;i<5000;i++){ redisKey.set("pp"+i,"dfdfdfdf"); } } @Test public void testType() throws Exception { redisKey.set(key,"12"); String result = redisKey.type(key); Assert.assertEquals("string", result); }
### Question: RedisKey extends Commands { public String get(String key) { Jedis jedis = getJedis(); if ("string".equals(jedis.type(key))) { return jedis.get(key); } else { logger.error(ExceptionInfo.KEY_TYPE_NOT_STRING + " and type is " + jedis.type(key)); return null; } } private RedisKey(); synchronized static RedisKey getInstance(); String get(String key); String set(String key, String value); byte[] dump(String key); Long setExpire(String key, int second, String value); String setExpireMs(String key, long second, String value); long increaseKey(String key); long decreaseKey(String key); long append(String key, String value); List<String> getMultiKeys(String... keys); String setMultiKey(String... keys); String getEncoding(String key); Set<String> listAllKeys(int db); }### Answer: @Test public void testStatus(){ Map<String,String> map = redisKey.getStatus(); System.out.println(map.get("db0")); }
### Question: RedisKey extends Commands { public byte[] dump(String key) { return getJedis().dump(key); } private RedisKey(); synchronized static RedisKey getInstance(); String get(String key); String set(String key, String value); byte[] dump(String key); Long setExpire(String key, int second, String value); String setExpireMs(String key, long second, String value); long increaseKey(String key); long decreaseKey(String key); long append(String key, String value); List<String> getMultiKeys(String... keys); String setMultiKey(String... keys); String getEncoding(String key); Set<String> listAllKeys(int db); }### Answer: @Test public void testDump() throws Exception { byte[] result = redisKey.dump(key); Assert.assertArrayEquals(null, result); }
### Question: RedisKey extends Commands { public Long setExpire(String key, int second, String value) { Jedis jedis = getJedis(); jedis.set(key, value); return expire(key, second); } private RedisKey(); synchronized static RedisKey getInstance(); String get(String key); String set(String key, String value); byte[] dump(String key); Long setExpire(String key, int second, String value); String setExpireMs(String key, long second, String value); long increaseKey(String key); long decreaseKey(String key); long append(String key, String value); List<String> getMultiKeys(String... keys); String setMultiKey(String... keys); String getEncoding(String key); Set<String> listAllKeys(int db); }### Answer: @Test public void testSetExpire() throws Exception { Long result = redisKey.setExpire(key, 0, "value"); assert(1L == result); }
### Question: RedisKey extends Commands { public String setExpireMs(String key, long second, String value) { return getJedis().psetex(key, second, value); } private RedisKey(); synchronized static RedisKey getInstance(); String get(String key); String set(String key, String value); byte[] dump(String key); Long setExpire(String key, int second, String value); String setExpireMs(String key, long second, String value); long increaseKey(String key); long decreaseKey(String key); long append(String key, String value); List<String> getMultiKeys(String... keys); String setMultiKey(String... keys); String getEncoding(String key); Set<String> listAllKeys(int db); }### Answer: @Test public void testSetExpireMs() throws Exception { String result = redisKey.setExpireMs(key, 12L, "value"); Assert.assertEquals("OK", result); }
### Question: PoolManagement { public String createRedisPool(RedisPoolProperty property) throws Exception { int maxId = PropertyFile.getMaxId(); maxId++; property.setPoolId(maxId + ""); Map<String, ?> map = MythReflect.getFieldsValue(property); for (String key : map.keySet()) { PropertyFile.save(maxId + Configs.SEPARATE + key, map.get(key) + ""); } PropertyFile.delete(Configs.MAX_POOL_ID); PropertyFile.save(Configs.MAX_POOL_ID, maxId + ""); logger.info(NoticeInfo.CRETE_POOL + maxId); return maxId + ""; } private PoolManagement(); synchronized static PoolManagement getInstance(); RedisPools getRedisPool(); RedisPools getRedisPool(String poolId); RedisPools createRedisPoolAndConnection(RedisPoolProperty property); String createRedisPool(RedisPoolProperty property); boolean checkConnection(RedisPoolProperty property); boolean switchPool(String PoolId); String deleteRedisPool(String poolId); boolean clearAllPools(); boolean destroyRedisPool(String poolId); boolean destroyRedisPool(RedisPools redisPools); ConcurrentMap<String, RedisPools> getPoolMap(); }### Answer: @Test public void testCreateRedisPool() throws Exception { String result = poolManagement.createRedisPool(property); RedisPoolProperty getObject = RedisPoolProperty.initByIdFromConfig(result); Assert.assertEquals(getObject.toString(), property.toString()); }
### Question: RedisKey extends Commands { public long increaseKey(String key) throws TypeErrorException { checkIntValue(key); return getJedis().incr(key); } private RedisKey(); synchronized static RedisKey getInstance(); String get(String key); String set(String key, String value); byte[] dump(String key); Long setExpire(String key, int second, String value); String setExpireMs(String key, long second, String value); long increaseKey(String key); long decreaseKey(String key); long append(String key, String value); List<String> getMultiKeys(String... keys); String setMultiKey(String... keys); String getEncoding(String key); Set<String> listAllKeys(int db); }### Answer: @Test public void testIncreaseKey() throws Exception { redisKey.set(key,"1"); long result = redisKey.increaseKey(key); Assert.assertEquals(2L, result); testDeleteKey(); }
### Question: RedisKey extends Commands { public long decreaseKey(String key) throws TypeErrorException { checkIntValue(key); return getJedis().decr(key); } private RedisKey(); synchronized static RedisKey getInstance(); String get(String key); String set(String key, String value); byte[] dump(String key); Long setExpire(String key, int second, String value); String setExpireMs(String key, long second, String value); long increaseKey(String key); long decreaseKey(String key); long append(String key, String value); List<String> getMultiKeys(String... keys); String setMultiKey(String... keys); String getEncoding(String key); Set<String> listAllKeys(int db); }### Answer: @Test public void testDecreaseKey() throws Exception { redisKey.set(key,"1"); long result = redisKey.decreaseKey(key); Assert.assertEquals(0L, result); testDeleteKey(); }
### Question: RedisKey extends Commands { public long append(String key, String value) { return getJedis().append(key, value); } private RedisKey(); synchronized static RedisKey getInstance(); String get(String key); String set(String key, String value); byte[] dump(String key); Long setExpire(String key, int second, String value); String setExpireMs(String key, long second, String value); long increaseKey(String key); long decreaseKey(String key); long append(String key, String value); List<String> getMultiKeys(String... keys); String setMultiKey(String... keys); String getEncoding(String key); Set<String> listAllKeys(int db); }### Answer: @Test public void testAppend() throws Exception { redisKey.set(key,"1"); long result = redisKey.append(key, "value"); Assert.assertEquals(6L, result); }
### Question: RedisKey extends Commands { public List<String> getMultiKeys(String... keys) { return getJedis().mget(keys); } private RedisKey(); synchronized static RedisKey getInstance(); String get(String key); String set(String key, String value); byte[] dump(String key); Long setExpire(String key, int second, String value); String setExpireMs(String key, long second, String value); long increaseKey(String key); long decreaseKey(String key); long append(String key, String value); List<String> getMultiKeys(String... keys); String setMultiKey(String... keys); String getEncoding(String key); Set<String> listAllKeys(int db); }### Answer: @Test public void testGetMultiKeys() throws Exception { redisKey.set(key,"1"); redisKey.set("1","2"); List<String> result = redisKey.getMultiKeys(key,"1"); Assert.assertEquals(Arrays.<String>asList("1","2"), result); testDeleteKey(); redisKey.deleteKey("1"); }
### Question: RedisKey extends Commands { public String setMultiKey(String... keys) { return getJedis().mset(keys); } private RedisKey(); synchronized static RedisKey getInstance(); String get(String key); String set(String key, String value); byte[] dump(String key); Long setExpire(String key, int second, String value); String setExpireMs(String key, long second, String value); long increaseKey(String key); long decreaseKey(String key); long append(String key, String value); List<String> getMultiKeys(String... keys); String setMultiKey(String... keys); String getEncoding(String key); Set<String> listAllKeys(int db); }### Answer: @Test public void testSetMultiKey() throws Exception { String result = redisKey.setMultiKey("keys","a",key,"b"); Assert.assertEquals("OK", result); List<String> results = redisKey.getMultiKeys(key,"keys"); Assert.assertEquals(Arrays.<String>asList("b","a"), results); testDeleteKey(); redisKey.deleteKey("keys"); }
### Question: RedisKey extends Commands { public String getEncoding(String key) { return getJedis().objectEncoding(key); } private RedisKey(); synchronized static RedisKey getInstance(); String get(String key); String set(String key, String value); byte[] dump(String key); Long setExpire(String key, int second, String value); String setExpireMs(String key, long second, String value); long increaseKey(String key); long decreaseKey(String key); long append(String key, String value); List<String> getMultiKeys(String... keys); String setMultiKey(String... keys); String getEncoding(String key); Set<String> listAllKeys(int db); }### Answer: @Test public void testGetEncoding() throws Exception { redisKey.set(key,"78.89"); String result = redisKey.getEncoding(key); Assert.assertEquals("embstr", result); testDeleteKey(); }
### Question: RedisKey extends Commands { public Set<String> listAllKeys(int db) { logger.debug("RedisKey Management:" + this.getPools()); setDb(db); return getJedis().keys("*"); } private RedisKey(); synchronized static RedisKey getInstance(); String get(String key); String set(String key, String value); byte[] dump(String key); Long setExpire(String key, int second, String value); String setExpireMs(String key, long second, String value); long increaseKey(String key); long decreaseKey(String key); long append(String key, String value); List<String> getMultiKeys(String... keys); String setMultiKey(String... keys); String getEncoding(String key); Set<String> listAllKeys(int db); }### Answer: @Test public void testListKey(){ Set<String> sets = redisKey.listAllKeys(redisKey.getDb()); for(String d:sets){ System.out.println(d); } System.out.println(sets.size()); }
### Question: RedisHash extends Commands { public Long save(String key, String member, String value) { return getJedis().hset(key, member, value); } private RedisHash(); synchronized static RedisHash getInstance(); Long save(String key, String member, String value); String save(String key, Map<String, String> map); Long saveWhenNotExist(String key, String member, String value); String get(String key, String member); List<String> get(String key, String... member); Set<String> getMembers(String key); List<String> getValues(String key); Map<String, String> getAllMap(String key); Long increase(String key, String member, long value); Double increaseByFloat(String key, String member, double value); Long length(String key); Long remove(String key, String... members); }### Answer: @Test public void testSave() throws Exception { redisHash.save(key,"member","value"); Long result = redisHash.save(key, "member", "value2"); show(); Assert.assertEquals((Long)0L, result); } @Test public void testSave2() throws Exception { redisHash.save(key,"String","value"); String result = redisHash.save(key, new HashMap<String, String>() {{ put("String", "String"); put("String1","12"); }}); show(); Assert.assertEquals("OK", result); }
### Question: PoolManagement { public RedisPools createRedisPoolAndConnection(RedisPoolProperty property) throws Exception { return getRedisPool(createRedisPool(property)); } private PoolManagement(); synchronized static PoolManagement getInstance(); RedisPools getRedisPool(); RedisPools getRedisPool(String poolId); RedisPools createRedisPoolAndConnection(RedisPoolProperty property); String createRedisPool(RedisPoolProperty property); boolean checkConnection(RedisPoolProperty property); boolean switchPool(String PoolId); String deleteRedisPool(String poolId); boolean clearAllPools(); boolean destroyRedisPool(String poolId); boolean destroyRedisPool(RedisPools redisPools); ConcurrentMap<String, RedisPools> getPoolMap(); }### Answer: @Test public void testCreateRedisPoolAndConnection() throws Exception { RedisPools result = poolManagement.createRedisPoolAndConnection(property); Jedis jedis = result.getJedis(); jedis.set("names","testCreateRedisPoolAndConnection"); Assert.assertEquals("testCreateRedisPoolAndConnection",jedis.get("names")); jedis.del("names"); }
### Question: RedisHash extends Commands { public Long saveWhenNotExist(String key, String member, String value) { return getJedis().hsetnx(key, member, value); } private RedisHash(); synchronized static RedisHash getInstance(); Long save(String key, String member, String value); String save(String key, Map<String, String> map); Long saveWhenNotExist(String key, String member, String value); String get(String key, String member); List<String> get(String key, String... member); Set<String> getMembers(String key); List<String> getValues(String key); Map<String, String> getAllMap(String key); Long increase(String key, String member, long value); Double increaseByFloat(String key, String member, double value); Long length(String key); Long remove(String key, String... members); }### Answer: @Test public void testSaveWhenNotExist() throws Exception { redisHash.save(key,"member","value"); Long result = redisHash.saveWhenNotExist(key, "member", "value2"); show(); Assert.assertEquals((Long)0L, result); }
### Question: RedisHash extends Commands { public String get(String key, String member) { return getJedis().hget(key, member); } private RedisHash(); synchronized static RedisHash getInstance(); Long save(String key, String member, String value); String save(String key, Map<String, String> map); Long saveWhenNotExist(String key, String member, String value); String get(String key, String member); List<String> get(String key, String... member); Set<String> getMembers(String key); List<String> getValues(String key); Map<String, String> getAllMap(String key); Long increase(String key, String member, long value); Double increaseByFloat(String key, String member, double value); Long length(String key); Long remove(String key, String... members); }### Answer: @Test public void testGet() throws Exception { redisHash.save(key,"member","value"); String result = redisHash.get(key, "member"); show(); Assert.assertEquals("value", result); }
### Question: RedisHash extends Commands { public Set<String> getMembers(String key) { return getJedis().hkeys(key); } private RedisHash(); synchronized static RedisHash getInstance(); Long save(String key, String member, String value); String save(String key, Map<String, String> map); Long saveWhenNotExist(String key, String member, String value); String get(String key, String member); List<String> get(String key, String... member); Set<String> getMembers(String key); List<String> getValues(String key); Map<String, String> getAllMap(String key); Long increase(String key, String member, long value); Double increaseByFloat(String key, String member, double value); Long length(String key); Long remove(String key, String... members); }### Answer: @Test public void testGetMembers() throws Exception { redisHash.save(key,"member","value"); redisHash.save(key,"member2","value"); Set<String> result = redisHash.getMembers(key); show(); Assert.assertEquals(new HashSet(Arrays.asList("member","member2")), result); }
### Question: RedisHash extends Commands { public List<String> getValues(String key) { return getJedis().hvals(key); } private RedisHash(); synchronized static RedisHash getInstance(); Long save(String key, String member, String value); String save(String key, Map<String, String> map); Long saveWhenNotExist(String key, String member, String value); String get(String key, String member); List<String> get(String key, String... member); Set<String> getMembers(String key); List<String> getValues(String key); Map<String, String> getAllMap(String key); Long increase(String key, String member, long value); Double increaseByFloat(String key, String member, double value); Long length(String key); Long remove(String key, String... members); }### Answer: @Test public void testGetValues() throws Exception { redisHash.save(key,"member","value"); redisHash.save(key,"member2","value"); List<String> result = redisHash.getValues(key); show(); Assert.assertEquals(Arrays.asList("value","value"), result); }
### Question: RedisHash extends Commands { public Long increase(String key, String member, long value) throws TypeErrorException { Long result; try { result = getJedis().hincrBy(key, member, value); } catch (Exception e) { throw new TypeErrorException(ExceptionInfo.TYPE_ERROR, e, RedisHash.class); } return result; } private RedisHash(); synchronized static RedisHash getInstance(); Long save(String key, String member, String value); String save(String key, Map<String, String> map); Long saveWhenNotExist(String key, String member, String value); String get(String key, String member); List<String> get(String key, String... member); Set<String> getMembers(String key); List<String> getValues(String key); Map<String, String> getAllMap(String key); Long increase(String key, String member, long value); Double increaseByFloat(String key, String member, double value); Long length(String key); Long remove(String key, String... members); }### Answer: @Test public void testIncrease() throws Exception { redisHash.save(key,"member","34"); Long result = redisHash.increase(key, "member", 56L); show(); Assert.assertEquals((Long)90L, result); }
### Question: RedisHash extends Commands { public Double increaseByFloat(String key, String member, double value) throws TypeErrorException { Double result; try { result = getJedis().hincrByFloat(key, member, value); } catch (Exception e) { throw new TypeErrorException(ExceptionInfo.TYPE_ERROR, e, RedisHash.class); } return result; } private RedisHash(); synchronized static RedisHash getInstance(); Long save(String key, String member, String value); String save(String key, Map<String, String> map); Long saveWhenNotExist(String key, String member, String value); String get(String key, String member); List<String> get(String key, String... member); Set<String> getMembers(String key); List<String> getValues(String key); Map<String, String> getAllMap(String key); Long increase(String key, String member, long value); Double increaseByFloat(String key, String member, double value); Long length(String key); Long remove(String key, String... members); }### Answer: @Test public void testIncreaseByFloat() throws Exception { redisHash.save(key,"member","1"); Double result = redisHash.increaseByFloat(key, "member", 22d); Assert.assertEquals((Double) 23.0, result); }
### Question: RedisHash extends Commands { public Long length(String key) { return getJedis().hlen(key); } private RedisHash(); synchronized static RedisHash getInstance(); Long save(String key, String member, String value); String save(String key, Map<String, String> map); Long saveWhenNotExist(String key, String member, String value); String get(String key, String member); List<String> get(String key, String... member); Set<String> getMembers(String key); List<String> getValues(String key); Map<String, String> getAllMap(String key); Long increase(String key, String member, long value); Double increaseByFloat(String key, String member, double value); Long length(String key); Long remove(String key, String... members); }### Answer: @Test public void testLength() throws Exception { redisHash.save(key,"member","23.2"); redisHash.save(key,"member1","23.2"); redisHash.save(key,"member2","23.2"); Long result = redisHash.length(key); show(); Assert.assertEquals((Long)3L, result); }
### Question: RedisHash extends Commands { public Long remove(String key, String... members) { return getJedis().hdel(key, members); } private RedisHash(); synchronized static RedisHash getInstance(); Long save(String key, String member, String value); String save(String key, Map<String, String> map); Long saveWhenNotExist(String key, String member, String value); String get(String key, String member); List<String> get(String key, String... member); Set<String> getMembers(String key); List<String> getValues(String key); Map<String, String> getAllMap(String key); Long increase(String key, String member, long value); Double increaseByFloat(String key, String member, double value); Long length(String key); Long remove(String key, String... members); }### Answer: @Test public void testRemove() throws Exception { redisHash.save(key,"member","23.2"); Long result = redisHash.remove(key, "member"); show(); Assert.assertEquals((Long)1L, result); }
### Question: PoolManagement { public RedisPools getRedisPool() { if (currentPoolId == null) { logger.error(ExceptionInfo.NOT_EXIST_CURRENT_POOL); return null; } try { return getRedisPool(currentPoolId); } catch (Exception e) { logger.error(e.getMessage()); logger.debug(NoticeInfo.ERROR_INFO, e); return null; } } private PoolManagement(); synchronized static PoolManagement getInstance(); RedisPools getRedisPool(); RedisPools getRedisPool(String poolId); RedisPools createRedisPoolAndConnection(RedisPoolProperty property); String createRedisPool(RedisPoolProperty property); boolean checkConnection(RedisPoolProperty property); boolean switchPool(String PoolId); String deleteRedisPool(String poolId); boolean clearAllPools(); boolean destroyRedisPool(String poolId); boolean destroyRedisPool(RedisPools redisPools); ConcurrentMap<String, RedisPools> getPoolMap(); }### Answer: @Test public void testGetRedisPool() throws Exception { RedisPools result = poolManagement.getRedisPool(); System.out.println(result.getDatabaseNum()); Jedis jedis = result.getJedis(); jedis.keys(""); jedis.set("names","testGetRedisPool"); Assert.assertEquals("testGetRedisPool",jedis.get("names")); }
### Question: PoolManagement { public boolean checkConnection(RedisPoolProperty property) { if (!validate(property)) { return false; } RedisPools pools = new RedisPools(); pools.setProperty(property); boolean flag = pools.available(); pools.destroyPool(); return flag; } private PoolManagement(); synchronized static PoolManagement getInstance(); RedisPools getRedisPool(); RedisPools getRedisPool(String poolId); RedisPools createRedisPoolAndConnection(RedisPoolProperty property); String createRedisPool(RedisPoolProperty property); boolean checkConnection(RedisPoolProperty property); boolean switchPool(String PoolId); String deleteRedisPool(String poolId); boolean clearAllPools(); boolean destroyRedisPool(String poolId); boolean destroyRedisPool(RedisPools redisPools); ConcurrentMap<String, RedisPools> getPoolMap(); }### Answer: @Test public void testCheckConnection(){ property = new RedisPoolProperty(); property.setHost("120.25.203.47"); property.setMaxActive(400); property.setMaxIdle(100); property.setMaxWaitMills(10000); property.setTestOnBorrow(false); property.setName("myth"); property.setPort(6381); property.setPassword("myth"); property.setTimeout(600); boolean result = poolManagement.checkConnection(property); System.out.println(result); Assert.assertEquals(true, result); }
### Question: Metadata { public List<String> getDisplayOrder() { return mDisplayOrder; } Metadata(List<String> displayOrder, Map<String, JsonObject> groups, Map<String, GroupDef> groupDefinitions, List<Field> fields); List<String> getDisplayOrder(); Map<String, JsonObject> getGroups(); Map<String, GroupDef> getGroupDefinitions(); List<Field> getFields(); }### Answer: @Test public void hasCorrectDisplayOrder() { assertEquals(7, subject.getDisplayOrder().size()); assertEquals("group.date", subject.getDisplayOrder().get(1)); }
### Question: Metadata { public List<Field> getFields() { return mFields; } Metadata(List<String> displayOrder, Map<String, JsonObject> groups, Map<String, GroupDef> groupDefinitions, List<Field> fields); List<String> getDisplayOrder(); Map<String, JsonObject> getGroups(); Map<String, GroupDef> getGroupDefinitions(); List<Field> getFields(); }### Answer: @Test public void hasCorrectStringField() { Field field = subject.getFields().get(0); assertEquals("Text title", field.getTitle()); assertEquals("string", field.getValue()); } @Test public void hasCorrectNumberField() { Field field = subject.getFields().get(4); assertEquals("GPA", field.getTitle()); assertEquals("3.7", field.getValue()); } @Test public void hasCorrectBooleanField() { Field field = subject.getFields().get(6); assertEquals("is this a boolean?", field.getTitle()); assertEquals("True", field.getValue()); }
### Question: BitcoinUtils { public static List<String> generateMnemonic(byte[] seedData) { if (MnemonicCode.INSTANCE == null) { return null; } try { return MnemonicCode.INSTANCE.toMnemonic(seedData); } catch (MnemonicException.MnemonicLengthException e) { Timber.e(e, "Unable to create mnemonic from word list"); } return null; } static void init(Context context); static List<String> generateMnemonic(byte[] seedData); static Wallet createWallet(NetworkParameters params, String seedPhrase); @NonNull static Wallet createWallet(NetworkParameters params, byte[] entropy); static Wallet loadWallet(InputStream walletStream, NetworkParameters networkParameters); static boolean updateRequired(Wallet wallet); static Wallet updateWallet(Wallet wallet); static boolean isValidPassphrase(String passphrase); }### Answer: @Test public void testGenerateMnemonic() throws Exception { byte[] seedData = new byte[32]; String expectedMnemonic = ABANDON_ABANDON_ART; List<String> seedPhrase = BitcoinUtils.generateMnemonic(seedData); assertFalse(ListUtils.isEmpty(seedPhrase)); String mnemonic = StringUtils.join(" ", seedPhrase); assertFalse("Mnemonic phrase should not be empty", mnemonic.isEmpty()); assertEquals("0-seed should generate simple mnemonic phrase", expectedMnemonic, mnemonic); }
### Question: BitcoinUtils { public static boolean isValidPassphrase(String passphrase) { try { byte[] entropy = MnemonicCode.INSTANCE.toEntropy(Arrays.asList(passphrase.split(" "))); return entropy.length > 0; } catch (MnemonicException e) { Timber.e(e, "Invalid passphrase"); return false; } } static void init(Context context); static List<String> generateMnemonic(byte[] seedData); static Wallet createWallet(NetworkParameters params, String seedPhrase); @NonNull static Wallet createWallet(NetworkParameters params, byte[] entropy); static Wallet loadWallet(InputStream walletStream, NetworkParameters networkParameters); static boolean updateRequired(Wallet wallet); static Wallet updateWallet(Wallet wallet); static boolean isValidPassphrase(String passphrase); }### Answer: @Test public void detectsValidPassphrases() { String seedPhrase = ABANDON_ABANDON_ART; assertTrue("This should be a valid phrase", BitcoinUtils.isValidPassphrase(seedPhrase)); } @Test public void detectsInvalidPassphrases() { String seedPhrase = "This phrase is too short and not random enough"; assertFalse("This should be an invalid phrase", BitcoinUtils.isValidPassphrase(seedPhrase)); }
### Question: Cloud { public void createPacketsFile() { File packetsFile = new File(this.sharedDir, "Packets.txt"); if (packetsFile.exists()) { try { packetsFile.createNewFile(); } catch (IOException e) { log.error("Cannot create", e); } } try (PrintWriter writer = new PrintWriter(new FileOutputStream(packetsFile))) { for (Class<? extends Packet> packet : PacketManager.getInstance().getPackets()) writer.println(packet.getSimpleName()); } catch (FileNotFoundException e) { log.error("file not found", e); } } Cloud(); void stop(); void createPacketsFile(); static Logger getLogger(); static void main(String... args); }### Answer: @Test public void testPacketsCreationFile() { Cloud cloud = new Cloud(); cloud.createPacketsFile(); File file = new File(cloud.getSharedDir(), "Packets.txt"); try (BufferedReader inputStream = new BufferedReader(new FileReader(file))) { List<String> lines = inputStream.lines().collect(Collectors.toList()); for (int i = 0; i < lines.size(); i++) { assertEquals(PacketManager.getInstance().getPackets().get(i).getSimpleName(), lines.get(i)); } } catch (IOException e) { e.printStackTrace(); } }
### Question: QuestionRepository implements QuestionDataSource { @Override public Flowable<List<Question>> loadQuestions(boolean forceRemote) { if (forceRemote) { return refreshData(); } else { if (caches.size() > 0) { return Flowable.just(caches); } else { return localDataSource.loadQuestions(false) .take(1) .flatMap(Flowable::fromIterable) .doOnNext(question -> caches.add(question)) .toList() .toFlowable() .filter(list -> !list.isEmpty()) .switchIfEmpty( refreshData()); } } } @Inject QuestionRepository(@Local QuestionDataSource localDataSource, @Remote QuestionDataSource remoteDataSource); @Override Flowable<List<Question>> loadQuestions(boolean forceRemote); Flowable<Question> getQuestion(long questionId); @Override void addQuestion(Question question); @Override void clearData(); }### Answer: @Test public void loadQuestions_ShouldReturnCache_IfItIsAvailable() { repository.caches.addAll(questions); repository.loadQuestions(false).subscribe(questionsTestSubscriber); verifyZeroInteractions(localDataSource); verifyZeroInteractions(remoteDataSource); questionsTestSubscriber.assertValue(questions); } @Test public void loadQuestions_ShouldReturnFromLocal_IfCacheIsNotAvailable() { doReturn(Flowable.just(questions)).when(localDataSource).loadQuestions(false); doReturn(Flowable.just(questions)).when(remoteDataSource).loadQuestions(true); repository.loadQuestions(false).subscribe(questionsTestSubscriber); verify(localDataSource).loadQuestions(false); verify(remoteDataSource).loadQuestions(true); questionsTestSubscriber.assertValue(questions); }
### Question: QuestionRemoteDataSource implements QuestionDataSource { @Override public void clearData() { throw new UnsupportedOperationException("Unsupported operation"); } @Inject QuestionRemoteDataSource(QuestionService questionService); @Override Flowable<List<Question>> loadQuestions(boolean forceRemote); @Override void addQuestion(Question question); @Override void clearData(); }### Answer: @Test(expected = UnsupportedOperationException.class) public void clearData_NoThingToDoWithRemoteService() { remoteDataSource.clearData(); then(questionService).shouldHaveZeroInteractions(); }
### Question: QuestionRepository implements QuestionDataSource { public Flowable<Question> getQuestion(long questionId) { return Flowable.fromIterable(caches).filter(question -> question.getId() == questionId); } @Inject QuestionRepository(@Local QuestionDataSource localDataSource, @Remote QuestionDataSource remoteDataSource); @Override Flowable<List<Question>> loadQuestions(boolean forceRemote); Flowable<Question> getQuestion(long questionId); @Override void addQuestion(Question question); @Override void clearData(); }### Answer: @Test public void getQuestion_ShouldReturnFromCache() { question1.setId(1); question2.setId(2); question3.setId(3); repository.caches.addAll(questions); TestSubscriber<Question> subscriber = new TestSubscriber<>(); repository.getQuestion(1).subscribe(subscriber); then(localDataSource).shouldHaveZeroInteractions(); then(remoteDataSource).shouldHaveZeroInteractions(); subscriber.assertValue(question1); }
### Question: QuestionRepository implements QuestionDataSource { @Override public void clearData() { caches.clear(); localDataSource.clearData(); } @Inject QuestionRepository(@Local QuestionDataSource localDataSource, @Remote QuestionDataSource remoteDataSource); @Override Flowable<List<Question>> loadQuestions(boolean forceRemote); Flowable<Question> getQuestion(long questionId); @Override void addQuestion(Question question); @Override void clearData(); }### Answer: @Test public void clearData_ShouldClearCachesAndLocalData() { repository.caches.addAll(questions); repository.clearData(); assertThat(repository.caches, empty()); then(localDataSource).should().clearData(); }
### Question: QuestionRepository implements QuestionDataSource { @Override public void addQuestion(Question question) { throw new UnsupportedOperationException("Unsupported operation"); } @Inject QuestionRepository(@Local QuestionDataSource localDataSource, @Remote QuestionDataSource remoteDataSource); @Override Flowable<List<Question>> loadQuestions(boolean forceRemote); Flowable<Question> getQuestion(long questionId); @Override void addQuestion(Question question); @Override void clearData(); }### Answer: @Test(expected = UnsupportedOperationException.class) public void addQuestion_ShouldThrowException() { repository.addQuestion(question1); }
### Question: QuestionLocalDataSource implements QuestionDataSource { @Override public Flowable<List<Question>> loadQuestions(boolean forceRemote) { return questionDao.getAllQuestions(); } @Inject QuestionLocalDataSource(QuestionDao questionDao); @Override Flowable<List<Question>> loadQuestions(boolean forceRemote); @Override void addQuestion(Question question); @Override void clearData(); }### Answer: @Test public void loadQuestions_ShouldReturnFromDatabase() { List<Question> questions = Arrays.asList(new Question(), new Question()); TestSubscriber<List<Question>> subscriber = new TestSubscriber<>(); given(questionDao.getAllQuestions()).willReturn(Flowable.just(questions)); localDataSource.loadQuestions(false).subscribe(subscriber); then(questionDao).should().getAllQuestions(); }
### Question: QuestionLocalDataSource implements QuestionDataSource { @Override public void addQuestion(Question question) { questionDao.insert(question); } @Inject QuestionLocalDataSource(QuestionDao questionDao); @Override Flowable<List<Question>> loadQuestions(boolean forceRemote); @Override void addQuestion(Question question); @Override void clearData(); }### Answer: @Test public void addQuestion_ShouldInsertToDatabase() { Question question = new Question(); localDataSource.addQuestion(question); then(questionDao).should().insert(question); }
### Question: QuestionLocalDataSource implements QuestionDataSource { @Override public void clearData() { questionDao.deleteAll(); } @Inject QuestionLocalDataSource(QuestionDao questionDao); @Override Flowable<List<Question>> loadQuestions(boolean forceRemote); @Override void addQuestion(Question question); @Override void clearData(); }### Answer: @Test public void clearData_ShouldDeleteAllDataInDatabase() { localDataSource.clearData(); then(questionDao).should().deleteAll(); }
### Question: QuestionRemoteDataSource implements QuestionDataSource { @Override public Flowable<List<Question>> loadQuestions(boolean forceRemote) { return questionService.loadQuestionsByTag(Config.ANDROID_QUESTION_TAG).map(QuestionResponse::getQuestions); } @Inject QuestionRemoteDataSource(QuestionService questionService); @Override Flowable<List<Question>> loadQuestions(boolean forceRemote); @Override void addQuestion(Question question); @Override void clearData(); }### Answer: @Test public void loadQuestions_ShouldReturnFromRemoteService() { QuestionResponse questionResponse = new QuestionResponse(); TestSubscriber<List<Question>> subscriber = new TestSubscriber<>(); given(questionService.loadQuestionsByTag(Config.ANDROID_QUESTION_TAG)).willReturn(Flowable.just(questionResponse)); remoteDataSource.loadQuestions(anyBoolean()).subscribe(subscriber); then(questionService).should().loadQuestionsByTag(Config.ANDROID_QUESTION_TAG); }
### Question: QuestionRemoteDataSource implements QuestionDataSource { @Override public void addQuestion(Question question) { throw new UnsupportedOperationException("Unsupported operation"); } @Inject QuestionRemoteDataSource(QuestionService questionService); @Override Flowable<List<Question>> loadQuestions(boolean forceRemote); @Override void addQuestion(Question question); @Override void clearData(); }### Answer: @Test(expected = UnsupportedOperationException.class) public void addQuestion_NoThingToDoWithRemoteService() { Question question = mock(Question.class); remoteDataSource.addQuestion(question); then(questionService).shouldHaveZeroInteractions(); }
### Question: ToStringUserInterface extends AbstractUserInterface implements Appendable { @Override public String toString() { return b.toString(); } @Override int hashCode(); @Override String toString(); @Override boolean equals(Object obj); @Override Appendable append(CharSequence csq); @Override Appendable append(CharSequence csq, int start, int end); @Override Appendable append(char c); }### Answer: @Test public void testUserToStringNamed() { ToStringUserInterface ui = X_AutoUi.makeUi(MODEL, UserViewNamed.class, ToStringUserInterface.class); Assert.assertEquals("email: email,\nname: name,\nid: id", ui.toString()); } @Test public void testUserToStringWrapped() { UserInterface<User> ui = X_AutoUi.makeUi(MODEL, UserViewWrapped.class, ToStringUserInterface.class); Assert.assertEquals("email: email,\nname: name,\nid: id,\n", ui.toString()); }
### Question: LogInjector { public Log defaultLogger() { return (level, debug) -> (level == LogLevel.ERROR ? SYS_ERR : SYS_OUT) .print(level, debug); } Log defaultLogger(); }### Answer: @Test public void testDefaultLogging() throws Throwable { final String msg = "Success! " + hashCode(); borrowSout( ()-> LogInjector.DEFAULT.log(LogLevel.INFO, msg) , lines-> Assert.assertEquals("[INFO] " + msg, lines.first()) ); assertTrue("Failed", !failed); Log.defaultLogger().log(LogInjectorTest.class, "Default Logging Works!"); }
### Question: SlideRenderer { public void renderSlide(DomBuffer into, UiContainerExpr slide) { final DomBuffer out; if ("xapi-slide".equals(into.getTagName())) { out = into; } else { out = into.makeTag("xapi-slide"); } slide.getAttribute("id") .mapNullSafe(UiAttrExpr::getExpression) .mapNullSafe(ASTHelper::extractStringValue) .readIfPresent(out::setId); final ComposableXapiVisitor<DomBuffer> visitor = new ComposableXapiVisitor<>(); visitor .withUiContainerExpr((tag, buffer)->{ renderSlideChild(out, tag, visitor, slide); return false; }) .visit(slide.getBody(), out); } void renderSlide(DomBuffer into, UiContainerExpr slide); }### Answer: @Test public void testAllSlidesCanRender() throws IOException, ParseException { items.forAll(item->{ SlideRenderer renderer = new SlideRenderer(); final DomBuffer into = new DomBuffer() .setNewLine(true) .setTrimWhitespace(false); renderer.renderSlide(into, item.out2()); X_Log.info(X_Source.pathToLogLink(item.out1().getResourceName()), "\n", item.out2(), "\nRenders:", into, "\n\n" ); }); }
### Question: SPUtils { public String getString(@NonNull String key) { return getString(key, ""); } private SPUtils(String spName); static SPUtils getInstance(); static SPUtils getInstance(String spName); void put(@NonNull String key, @NonNull String value); String getString(@NonNull String key); String getString(@NonNull String key, @NonNull String defaultValue); void put(@NonNull String key, int value); int getInt(@NonNull String key); int getInt(@NonNull String key, int defaultValue); void put(@NonNull String key, long value); long getLong(@NonNull String key); long getLong(@NonNull String key, long defaultValue); void put(@NonNull String key, float value); float getFloat(@NonNull String key); float getFloat(@NonNull String key, float defaultValue); void put(@NonNull String key, boolean value); boolean getBoolean(@NonNull String key); boolean getBoolean(@NonNull String key, boolean defaultValue); void put(@NonNull String key, @NonNull Set<String> values); Set<String> getStringSet(@NonNull String key); Set<String> getStringSet(@NonNull String key, @NonNull Set<String> defaultValue); Map<String, ?> getAll(); boolean contains(@NonNull String key); void remove(@NonNull String key); void clear(); }### Answer: @Test public void getString() throws Exception { Assert.assertEquals("stringVal1", spUtils1.getString("stringKey1")); Assert.assertEquals("stringVal", spUtils1.getString("stringKey", "stringVal")); Assert.assertEquals("", spUtils1.getString("stringKey")); Assert.assertEquals("stringVal2", spUtils2.getString("stringKey2")); Assert.assertEquals("stringVal", spUtils2.getString("stringKey", "stringVal")); Assert.assertEquals("", spUtils2.getString("stringKey")); }
### Question: SPUtils { public int getInt(@NonNull String key) { return getInt(key, -1); } private SPUtils(String spName); static SPUtils getInstance(); static SPUtils getInstance(String spName); void put(@NonNull String key, @NonNull String value); String getString(@NonNull String key); String getString(@NonNull String key, @NonNull String defaultValue); void put(@NonNull String key, int value); int getInt(@NonNull String key); int getInt(@NonNull String key, int defaultValue); void put(@NonNull String key, long value); long getLong(@NonNull String key); long getLong(@NonNull String key, long defaultValue); void put(@NonNull String key, float value); float getFloat(@NonNull String key); float getFloat(@NonNull String key, float defaultValue); void put(@NonNull String key, boolean value); boolean getBoolean(@NonNull String key); boolean getBoolean(@NonNull String key, boolean defaultValue); void put(@NonNull String key, @NonNull Set<String> values); Set<String> getStringSet(@NonNull String key); Set<String> getStringSet(@NonNull String key, @NonNull Set<String> defaultValue); Map<String, ?> getAll(); boolean contains(@NonNull String key); void remove(@NonNull String key); void clear(); }### Answer: @Test public void getInt() throws Exception { Assert.assertEquals(1, spUtils1.getInt("intKey1")); Assert.assertEquals(2048, spUtils1.getInt("intKey", 2048)); Assert.assertEquals(-1, spUtils1.getInt("intKey")); Assert.assertEquals(2, spUtils2.getInt("intKey2")); Assert.assertEquals(2048, spUtils2.getInt("intKey", 2048)); Assert.assertEquals(-1, spUtils2.getInt("intKey")); }
### Question: SPUtils { public long getLong(@NonNull String key) { return getLong(key, -1L); } private SPUtils(String spName); static SPUtils getInstance(); static SPUtils getInstance(String spName); void put(@NonNull String key, @NonNull String value); String getString(@NonNull String key); String getString(@NonNull String key, @NonNull String defaultValue); void put(@NonNull String key, int value); int getInt(@NonNull String key); int getInt(@NonNull String key, int defaultValue); void put(@NonNull String key, long value); long getLong(@NonNull String key); long getLong(@NonNull String key, long defaultValue); void put(@NonNull String key, float value); float getFloat(@NonNull String key); float getFloat(@NonNull String key, float defaultValue); void put(@NonNull String key, boolean value); boolean getBoolean(@NonNull String key); boolean getBoolean(@NonNull String key, boolean defaultValue); void put(@NonNull String key, @NonNull Set<String> values); Set<String> getStringSet(@NonNull String key); Set<String> getStringSet(@NonNull String key, @NonNull Set<String> defaultValue); Map<String, ?> getAll(); boolean contains(@NonNull String key); void remove(@NonNull String key); void clear(); }### Answer: @Test public void getLong() throws Exception { Assert.assertEquals(1L, spUtils1.getLong("longKey1")); Assert.assertEquals(2048L, spUtils1.getLong("longKey", 2048)); Assert.assertEquals(-1L, spUtils1.getLong("longKey")); Assert.assertEquals(2L, spUtils2.getLong("longKey2")); Assert.assertEquals(2048L, spUtils2.getLong("longKey", 2048)); Assert.assertEquals(-1L, spUtils2.getLong("longKey")); }
### Question: SPUtils { public float getFloat(@NonNull String key) { return getFloat(key, -1f); } private SPUtils(String spName); static SPUtils getInstance(); static SPUtils getInstance(String spName); void put(@NonNull String key, @NonNull String value); String getString(@NonNull String key); String getString(@NonNull String key, @NonNull String defaultValue); void put(@NonNull String key, int value); int getInt(@NonNull String key); int getInt(@NonNull String key, int defaultValue); void put(@NonNull String key, long value); long getLong(@NonNull String key); long getLong(@NonNull String key, long defaultValue); void put(@NonNull String key, float value); float getFloat(@NonNull String key); float getFloat(@NonNull String key, float defaultValue); void put(@NonNull String key, boolean value); boolean getBoolean(@NonNull String key); boolean getBoolean(@NonNull String key, boolean defaultValue); void put(@NonNull String key, @NonNull Set<String> values); Set<String> getStringSet(@NonNull String key); Set<String> getStringSet(@NonNull String key, @NonNull Set<String> defaultValue); Map<String, ?> getAll(); boolean contains(@NonNull String key); void remove(@NonNull String key); void clear(); }### Answer: @Test public void getFloat() throws Exception { Assert.assertEquals(1f, spUtils1.getFloat("floatKey1"), 0f); Assert.assertEquals(2048f, spUtils1.getFloat("floatKey", 2048f), 0f); Assert.assertEquals(-1f, spUtils1.getFloat("floatKey"), 0f); Assert.assertEquals(2f, spUtils2.getFloat("floatKey2"), 0f); Assert.assertEquals(2048f, spUtils2.getFloat("floatKey", 2048f), 0f); Assert.assertEquals(-1f, spUtils2.getFloat("floatKey"), 0f); }
### Question: SPUtils { public boolean getBoolean(@NonNull String key) { return getBoolean(key, false); } private SPUtils(String spName); static SPUtils getInstance(); static SPUtils getInstance(String spName); void put(@NonNull String key, @NonNull String value); String getString(@NonNull String key); String getString(@NonNull String key, @NonNull String defaultValue); void put(@NonNull String key, int value); int getInt(@NonNull String key); int getInt(@NonNull String key, int defaultValue); void put(@NonNull String key, long value); long getLong(@NonNull String key); long getLong(@NonNull String key, long defaultValue); void put(@NonNull String key, float value); float getFloat(@NonNull String key); float getFloat(@NonNull String key, float defaultValue); void put(@NonNull String key, boolean value); boolean getBoolean(@NonNull String key); boolean getBoolean(@NonNull String key, boolean defaultValue); void put(@NonNull String key, @NonNull Set<String> values); Set<String> getStringSet(@NonNull String key); Set<String> getStringSet(@NonNull String key, @NonNull Set<String> defaultValue); Map<String, ?> getAll(); boolean contains(@NonNull String key); void remove(@NonNull String key); void clear(); }### Answer: @Test public void getBoolean() throws Exception { Assert.assertTrue(spUtils1.getBoolean("booleanKey1")); Assert.assertTrue(spUtils1.getBoolean("booleanKey", true)); Assert.assertFalse(spUtils1.getBoolean("booleanKey")); Assert.assertTrue(spUtils2.getBoolean("booleanKey2")); Assert.assertTrue(spUtils2.getBoolean("booleanKey", true)); Assert.assertFalse(spUtils2.getBoolean("booleanKey")); }
### Question: SPUtils { public Map<String, ?> getAll() { return sp.getAll(); } private SPUtils(String spName); static SPUtils getInstance(); static SPUtils getInstance(String spName); void put(@NonNull String key, @NonNull String value); String getString(@NonNull String key); String getString(@NonNull String key, @NonNull String defaultValue); void put(@NonNull String key, int value); int getInt(@NonNull String key); int getInt(@NonNull String key, int defaultValue); void put(@NonNull String key, long value); long getLong(@NonNull String key); long getLong(@NonNull String key, long defaultValue); void put(@NonNull String key, float value); float getFloat(@NonNull String key); float getFloat(@NonNull String key, float defaultValue); void put(@NonNull String key, boolean value); boolean getBoolean(@NonNull String key); boolean getBoolean(@NonNull String key, boolean defaultValue); void put(@NonNull String key, @NonNull Set<String> values); Set<String> getStringSet(@NonNull String key); Set<String> getStringSet(@NonNull String key, @NonNull Set<String> defaultValue); Map<String, ?> getAll(); boolean contains(@NonNull String key); void remove(@NonNull String key); void clear(); }### Answer: @Test public void getAll() throws Exception { Map<String, ?> map; System.out.println("sp1 {"); map = spUtils1.getAll(); for (Map.Entry<String, ?> entry : map.entrySet()) { System.out.println(" " + entry.getKey() + ": " + entry.getValue()); } System.out.println("}"); System.out.println("sp2 {"); map = spUtils2.getAll(); for (Map.Entry<String, ?> entry : map.entrySet()) { System.out.println(" " + entry.getKey() + ": " + entry.getValue()); } System.out.println("}"); }
### Question: SPUtils { public void remove(@NonNull String key) { sp.edit().remove(key).apply(); } private SPUtils(String spName); static SPUtils getInstance(); static SPUtils getInstance(String spName); void put(@NonNull String key, @NonNull String value); String getString(@NonNull String key); String getString(@NonNull String key, @NonNull String defaultValue); void put(@NonNull String key, int value); int getInt(@NonNull String key); int getInt(@NonNull String key, int defaultValue); void put(@NonNull String key, long value); long getLong(@NonNull String key); long getLong(@NonNull String key, long defaultValue); void put(@NonNull String key, float value); float getFloat(@NonNull String key); float getFloat(@NonNull String key, float defaultValue); void put(@NonNull String key, boolean value); boolean getBoolean(@NonNull String key); boolean getBoolean(@NonNull String key, boolean defaultValue); void put(@NonNull String key, @NonNull Set<String> values); Set<String> getStringSet(@NonNull String key); Set<String> getStringSet(@NonNull String key, @NonNull Set<String> defaultValue); Map<String, ?> getAll(); boolean contains(@NonNull String key); void remove(@NonNull String key); void clear(); }### Answer: @Test public void testRemove() throws Exception { Assert.assertEquals("stringVal1", spUtils1.getString("stringKey1")); spUtils1.remove("stringKey1"); Assert.assertEquals("", spUtils1.getString("stringKey1")); Assert.assertEquals("stringVal2", spUtils2.getString("stringKey2")); spUtils2.remove("stringKey2"); Assert.assertEquals("", spUtils2.getString("stringKey2")); }
### Question: SPUtils { public boolean contains(@NonNull String key) { return sp.contains(key); } private SPUtils(String spName); static SPUtils getInstance(); static SPUtils getInstance(String spName); void put(@NonNull String key, @NonNull String value); String getString(@NonNull String key); String getString(@NonNull String key, @NonNull String defaultValue); void put(@NonNull String key, int value); int getInt(@NonNull String key); int getInt(@NonNull String key, int defaultValue); void put(@NonNull String key, long value); long getLong(@NonNull String key); long getLong(@NonNull String key, long defaultValue); void put(@NonNull String key, float value); float getFloat(@NonNull String key); float getFloat(@NonNull String key, float defaultValue); void put(@NonNull String key, boolean value); boolean getBoolean(@NonNull String key); boolean getBoolean(@NonNull String key, boolean defaultValue); void put(@NonNull String key, @NonNull Set<String> values); Set<String> getStringSet(@NonNull String key); Set<String> getStringSet(@NonNull String key, @NonNull Set<String> defaultValue); Map<String, ?> getAll(); boolean contains(@NonNull String key); void remove(@NonNull String key); void clear(); }### Answer: @Test public void testContains() throws Exception { Assert.assertTrue(spUtils1.contains("stringKey1")); Assert.assertFalse(spUtils1.contains("stringKey")); Assert.assertTrue(spUtils2.contains("stringKey2")); Assert.assertFalse(spUtils2.contains("stringKey")); }
### Question: SPUtils { public void clear() { sp.edit().clear().apply(); } private SPUtils(String spName); static SPUtils getInstance(); static SPUtils getInstance(String spName); void put(@NonNull String key, @NonNull String value); String getString(@NonNull String key); String getString(@NonNull String key, @NonNull String defaultValue); void put(@NonNull String key, int value); int getInt(@NonNull String key); int getInt(@NonNull String key, int defaultValue); void put(@NonNull String key, long value); long getLong(@NonNull String key); long getLong(@NonNull String key, long defaultValue); void put(@NonNull String key, float value); float getFloat(@NonNull String key); float getFloat(@NonNull String key, float defaultValue); void put(@NonNull String key, boolean value); boolean getBoolean(@NonNull String key); boolean getBoolean(@NonNull String key, boolean defaultValue); void put(@NonNull String key, @NonNull Set<String> values); Set<String> getStringSet(@NonNull String key); Set<String> getStringSet(@NonNull String key, @NonNull Set<String> defaultValue); Map<String, ?> getAll(); boolean contains(@NonNull String key); void remove(@NonNull String key); void clear(); }### Answer: @Test public void clear() throws Exception { spUtils1.clear(); Assert.assertEquals("", spUtils1.getString("stringKey1")); Assert.assertEquals(-1, spUtils1.getInt("intKey1")); Assert.assertEquals(-1L, spUtils1.getLong("longKey1")); Assert.assertEquals(-1f, spUtils1.getFloat("floatKey1"), 0f); Assert.assertFalse(spUtils1.getBoolean("booleanKey1")); spUtils2.clear(); Assert.assertEquals("", spUtils2.getString("stringKey2")); Assert.assertEquals(-1, spUtils2.getInt("intKey2")); Assert.assertEquals(-1L, spUtils2.getLong("longKey1")); Assert.assertEquals(-1f, spUtils2.getFloat("floatKey1"), 0f); Assert.assertFalse(spUtils2.getBoolean("booleanKey1")); }
### Question: ProxyConfig { public String getProxyHost() { return proxyHost; } ProxyConfig(PropertyLoader propertyLoader); boolean isProxyRequired(); String getProxyType(); String getProxyHost(); int getProxyPort(); String getProxyAddress(); String getProxyUsername(); String getProxyPassword(); String getNonProxyHosts(); }### Answer: @Test public void proxySettingsObtainedInOrder() { Properties properties = givenDefaultProperties(); environmentVariables.set("HTTP_PROXY", "http: ProxyConfig proxyConfig = new ProxyConfig(new DefaultPropertyLoader(properties)); assertThat(proxyConfig.getProxyHost(), is("proxyhost3")); System.setProperty("http.proxyHost", "proxyhost2"); proxyConfig = new ProxyConfig(new DefaultPropertyLoader(properties)); assertThat(proxyConfig.getProxyHost(), is("proxyhost2")); given(properties.getProperty("proxy.host")).willReturn("proxyhost1"); proxyConfig = new ProxyConfig(new DefaultPropertyLoader(properties)); assertThat(proxyConfig.getProxyHost(), is("proxyhost1")); }
### Question: CaselessProperties extends Properties { @Override public synchronized Object put(Object key, Object value) { lookup.put(((String) key), (String) key); return super.put(key, value); } @Override synchronized Object put(Object key, Object value); @Override String getProperty(String key); @Override String getProperty(String key, String defaultValue); }### Answer: @Test public void propertyKeyOriginalCaseIsAvailalbe() { Properties properties = new CaselessProperties(); properties.put("a.SETTING", "value"); @SuppressWarnings("unchecked") Enumeration<String> en = (Enumeration<String>) properties.propertyNames(); String propName = en.nextElement(); assertThat(propName, is("a.SETTING")); }
### Question: DefaultPropertyLoader implements PropertyLoader { @Override public String getProperty(String key) { String value = retrieveProperty(key); if (value.isEmpty()) { throw new IllegalArgumentException(String.format("Unable to find property %s", key)); } return value; } DefaultPropertyLoader(Properties properties); String getEnvironment(); @Override String getProperty(String key); @Override String getProperty(String key, String defaultValue); @Override boolean getPropertyAsBoolean(String key, String defaultValue); @Override int getPropertyAsInteger(String key, String defaultValue); @Override Map<String, String> getPropertiesStartingWith(String keyPrefix); @Override Map<String, String> getPropertiesStartingWith(String keyPrefix, boolean trimPrefix); }### Answer: @Test public void environmentPropertiesOverrideDefaultProperties() { Properties properties = givenDefaultProperties(); given(properties.getProperty("a.setting")).willReturn("false"); given(properties.getProperty("SIT.a.setting")).willReturn("true"); DefaultPropertyLoader loader = new DefaultPropertyLoader(properties); assertThat(loader.getProperty("a.setting"), is("false")); given(properties.getProperty(eq("environment"), any())).willReturn("SIT"); loader = new DefaultPropertyLoader(properties); assertThat(loader.getProperty("a.setting"), is("true")); }
### Question: DefaultPropertyLoader implements PropertyLoader { public String getEnvironment() { return environment; } DefaultPropertyLoader(Properties properties); String getEnvironment(); @Override String getProperty(String key); @Override String getProperty(String key, String defaultValue); @Override boolean getPropertyAsBoolean(String key, String defaultValue); @Override int getPropertyAsInteger(String key, String defaultValue); @Override Map<String, String> getPropertiesStartingWith(String keyPrefix); @Override Map<String, String> getPropertiesStartingWith(String keyPrefix, boolean trimPrefix); }### Answer: @Test public void systemPropertyWillOverrideEnvironment() throws Exception { Properties properties = givenDefaultProperties(); System.setProperty("environment", "SIT"); DefaultPropertyLoader loader = new DefaultPropertyLoader(properties); assertThat(loader.getEnvironment(), is("SIT")); }
### Question: DefaultPropertyLoader implements PropertyLoader { @Override public Map<String, String> getPropertiesStartingWith(String keyPrefix) { return getPropertiesStartingWith(keyPrefix, false); } DefaultPropertyLoader(Properties properties); String getEnvironment(); @Override String getProperty(String key); @Override String getProperty(String key, String defaultValue); @Override boolean getPropertyAsBoolean(String key, String defaultValue); @Override int getPropertyAsInteger(String key, String defaultValue); @Override Map<String, String> getPropertiesStartingWith(String keyPrefix); @Override Map<String, String> getPropertiesStartingWith(String keyPrefix, boolean trimPrefix); }### Answer: @Test public void canSearchForPopertiesWithPrefixMatchingCase() throws IOException { Properties properties = givenDefaultSearchProperties(); DefaultPropertyLoader loader = new DefaultPropertyLoader(properties); Map<String, String> found = loader.getPropertiesStartingWith("a.setting."); assertThat(found.values().size(), is(1)); assertThat(found.keySet().iterator().next(), is("a.setting.2")); } @Test public void canSearchForPopertiesAngGetOriginalPropertyCase() throws IOException { Properties properties = givenDefaultSearchProperties(); DefaultPropertyLoader loader = new DefaultPropertyLoader(properties); Map<String, String> found = loader.getPropertiesStartingWith("a."); assertThat(found.values().size(), is(2)); assertThat(found.keySet().iterator().next(), is("a.SETTING.1")); } @Test public void canSearchForPopertiesAngGetKeysWithoutPrefix() throws IOException { Properties properties = givenDefaultSearchProperties(); DefaultPropertyLoader loader = new DefaultPropertyLoader(properties); Map<String, String> found = loader.getPropertiesStartingWith("a.setting.", true); assertThat(found.values().size(), is(1)); assertThat(found.keySet().iterator().next(), is("2")); }
### Question: DefaultPropertiesLoader implements PropertiesLoader { @Override public Properties getProperties() { return properties; } protected DefaultPropertiesLoader(String properties, String userProperties); private DefaultPropertiesLoader(); static DefaultPropertiesLoader getInstance(); @Override Properties getProperties(); }### Answer: @Test public void userPropertiesOverrideConfigProperties() { String defaultProperties = "a.setting=false"; String userProperties = "a.setting=true"; Properties properties = new DefaultPropertiesLoader(defaultProperties, "").getProperties(); assertThat(properties.getProperty("a.setting"), is("false")); properties = new DefaultPropertiesLoader(defaultProperties, userProperties).getProperties(); assertThat(properties.getProperty("a.setting"), is("true")); }
### Question: ConcordionBase implements ResourceRegistry { @Override public boolean isRegistered(Closeable resource, ResourceScope scope) { return getResourcePairFromScope(resource, scope).isPresent(); } @Override void registerCloseableResource(Closeable resource, ResourceScope scope); @Override void registerCloseableResource(Closeable resource, ResourceScope scope, CloseListener listener); @Override boolean isRegistered(Closeable resource, ResourceScope scope); @Override void closeResource(Closeable resource); }### Answer: @Test public void isRegisteredReturnsFalseIfNotRegistered() { assertFalse(test1.isRegistered(resource0, ResourceScope.SPECIFICATION)); }
### Question: PrometheusMetricsReporter extends AbstractMetricsReporter implements MetricsReporter { @Override public void reportSpan(SpanData spanData) { String[] labelValues = getLabelValues(spanData); if (labelValues != null) { this.histogram.labels(labelValues).observe(spanData.getDuration() / (double)1000000); } } private PrometheusMetricsReporter(String name, CollectorRegistry registry, List<MetricLabel> labels); @Override void reportSpan(SpanData spanData); static Builder newMetricsReporter(); }### Answer: @Test public void testReportSpan() { PrometheusMetricsReporter reporter = PrometheusMetricsReporter.newMetricsReporter() .withCollectorRegistry(collectorRegistry) .withConstLabel("span.kind", Tags.SPAN_KIND_CLIENT) .build(); Map<String,Object> spanTags = new HashMap<String,Object>(); spanTags.put(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT); SpanData spanData = mock(SpanData.class); when(spanData.getOperationName()).thenReturn("testop"); when(spanData.getTags()).thenReturn(spanTags); when(spanData.getDuration()).thenReturn(100000L); reporter.reportSpan(spanData); List<MetricFamilySamples> samples = reporter.getHistogram().collect(); assertEquals(1, samples.size()); assertEquals(17, samples.get(0).samples.size()); for (int i=0; i < samples.get(0).samples.size(); i++) { Sample sample = samples.get(0).samples.get(i); assertEquals("testop", sample.labelValues.get(0)); List<String> labelNames = new ArrayList<String>(sample.labelNames); if (labelNames.get(labelNames.size()-1).equals("le")) { labelNames.remove(labelNames.size()-1); if (sample.labelValues.get(sample.labelNames.size()-1).equals("+Inf")) { assertEquals(1, (int)sample.value); } } assertEquals(Arrays.asList(reporter.getLabelNames()), labelNames); } }
### Question: PrometheusMetricsReporter extends AbstractMetricsReporter implements MetricsReporter { protected static String convertLabel(String label) { StringBuilder builder = new StringBuilder(label); for (int i=0; i < builder.length(); i++) { char ch = builder.charAt(i); if (!(ch == '_' || ch == ':' || Character.isLetter(ch) || (i > 0 && Character.isDigit(ch)))) { builder.setCharAt(i, '_'); } } return builder.toString(); } private PrometheusMetricsReporter(String name, CollectorRegistry registry, List<MetricLabel> labels); @Override void reportSpan(SpanData spanData); static Builder newMetricsReporter(); }### Answer: @Test public void testConvertLabel() { assertEquals("Hello9", PrometheusMetricsReporter.convertLabel("Hello9")); assertEquals("Hello_there", PrometheusMetricsReporter.convertLabel("Hello there")); assertEquals("_tag1", PrometheusMetricsReporter.convertLabel("1tag1")); assertEquals("tag_:_", PrometheusMetricsReporter.convertLabel("tag£:%")); }
### Question: TagMetricLabel implements MetricLabel { @Override public Object value(SpanData spanData) { Object ret = spanData.getTags().get(name()); return ret == null ? defaultValue : ret; } TagMetricLabel(String name, Object defaultValue); @Override String name(); @Override Object defaultValue(); @Override Object value(SpanData spanData); }### Answer: @Test public void testLabelFromTagWithValue() { MetricLabel label = new TagMetricLabel(TEST_LABEL, TEST_LABEL_DEFAULT); Map<String,Object> tags = new HashMap<String,Object>(); tags.put(TEST_LABEL, "TagValue"); SpanData spanData = mock(SpanData.class); when(spanData.getTags()).thenReturn(tags); assertEquals("TagValue", label.value(spanData)); } @Test public void testLabelFromTagWithNull() { MetricLabel label = new TagMetricLabel(TEST_LABEL, TEST_LABEL_DEFAULT); Map<String,Object> tags = new HashMap<String,Object>(); tags.put(TEST_LABEL, null); SpanData spanData = mock(SpanData.class); when(spanData.getTags()).thenReturn(tags); assertEquals(TEST_LABEL_DEFAULT, label.value(spanData)); }
### Question: BaggageMetricLabel implements MetricLabel { @Override public Object value(SpanData spanData) { Object ret = spanData.getBaggageItem(name()); return ret == null ? defaultValue : ret; } BaggageMetricLabel(String name, Object defaultValue); @Override String name(); @Override Object defaultValue(); @Override Object value(SpanData spanData); }### Answer: @Test public void testLabelFromBaggage() { MetricLabel label = new BaggageMetricLabel(TEST_LABEL, TEST_LABEL_DEFAULT); SpanData spanData = mock(SpanData.class); when(spanData.getBaggageItem(anyString())).thenReturn("BaggageValue"); assertEquals("BaggageValue", label.value(spanData)); verify(spanData, times(1)).getBaggageItem(TEST_LABEL); }
### Question: InsertOrReplaceProxy implements MethodInterceptor { @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { if (method.getName().equals("toString") && args.length == 0) { String sql = toString((String) proxy.invoke(realInsert, args)); return sql; } return proxy.invoke(realInsert, args); } Insert getInstance(Class<Insert> clazz, Insert realInsert); @Override Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy); String toString(String sql); }### Answer: @Test public void intercept() throws Exception { String sql = "INSERT INTO person (id, name) VALUES (1, 'KK')"; CCJSqlParserManager pm = new CCJSqlParserManager(); Insert insert = (Insert) pm.parse(new StringReader(sql)); Insert insertProxy = new InsertOrReplaceProxy().getInstance(Insert.class, insert); Table table = insertProxy.getTable(); Assert.assertEquals("person", table.getName()); String string = insertProxy.toString(); Assert.assertEquals("INSERT OR REPLACE INTO person (id, name) VALUES (1, 'KK')", string); }
### Question: ShadowResources { public String getString(@StringRes int id) throws NotFoundException { return getText(id).toString(); } ShadowResources(); String getString(@StringRes int id); @NonNull String[] getStringArray(@ArrayRes int id); @NonNull int[] getIntArray(@ArrayRes int id); String getPackageName(); }### Answer: @Test public void getString() throws Exception { Assert.assertEquals("KBUnitTest", resources.getString(R.string.test_string)); }
### Question: ShadowResources { @NonNull public String[] getStringArray(@ArrayRes int id) throws NotFoundException { Map<Integer, String> idNameMap = getArrayIdTable(); Map<String, List<String>> stringArrayMap = getResourceStringArrayMap(); if (idNameMap.containsKey(id)) { String name = idNameMap.get(id); if (stringArrayMap.containsKey(name)) { List<String> stringList = stringArrayMap.get(name); return stringList.toArray(new String[0]); } } throw new Resources.NotFoundException("String array resource ID #0x" + Integer.toHexString(id)); } ShadowResources(); String getString(@StringRes int id); @NonNull String[] getStringArray(@ArrayRes int id); @NonNull int[] getIntArray(@ArrayRes int id); String getPackageName(); }### Answer: @Test public void getStringArray() throws Exception { String[] array = resources.getStringArray(R.array.arrayName); Assert.assertEquals("item0", array[0]); Assert.assertEquals("item1", array[1]); }