method2testcases stringlengths 118 3.08k |
|---|
### Question:
TimecodeUtils { public static float convertTimecodeToSeconds(String timecode) { String[] timeParts = timecode.split(":"); int hours = Integer.parseInt(timeParts[0]); int minutes = Integer.parseInt(timeParts[1]); float seconds = Float.parseFloat(timeParts[2]) + (60 * minutes) + (60 * 60 * hours); return seconds; } static String convertSecondsToTimecode(float totalSeconds); static String convertSecondsToTimecode(float totalSeconds, int decimalScale); static float convertTimecodeToSeconds(String timecode); }### Answer:
@Test public void testTimecodeToSeconds() { String timecode = "00:00:50.000"; assertEquals(50f, TimecodeUtils.convertTimecodeToSeconds(timecode)); timecode = "00:01:10.000"; assertEquals(70f, TimecodeUtils.convertTimecodeToSeconds(timecode)); timecode = "00:00:05.000"; assertEquals(5f, TimecodeUtils.convertTimecodeToSeconds(timecode)); timecode = "00:00:05.011"; assertEquals(5.011f, TimecodeUtils.convertTimecodeToSeconds(timecode)); timecode = "00:00:11.07"; assertEquals(11.07f, TimecodeUtils.convertTimecodeToSeconds(timecode)); timecode = "02:11:22.123"; assertEquals((60*60*2) + (60*11) + 22.123f, TimecodeUtils.convertTimecodeToSeconds(timecode)); } |
### Question:
Server implements Instance, Communicatable { @Override public void stop() { if (getChannel() != null) getChannel().close(); unregister(); } Server(String name, String id, Base base, String map, ServerGroup group); boolean isStatic(); @Override void start(); @Override void stop(); @Override void onConnect(Channel channel); @Override void onDisconnect(); @Override void register(); @Override void unregister(); void onPlayerConnect(PlayerObject playerObject); void onPlayerDisconnect(PlayerObject playerObject); @Override void onMessage(Message message); @Override void sendMessage(Message message); @Override void onHandshakeSuccess(); @Override String getName(); @Override String getId(); boolean isRegistered(); @Override ServerGroup getGroup(); @Override Channel getChannel(); Base getBase(); InetSocketAddress getAddress(); void setAddress(InetSocketAddress address); void setChannel(Channel channel); String getState(); void setState(String state); String getExtra(); void setExtra(String extra); String getMotd(); void setMotd(String motd); Set<PlayerObject> getOnlinePlayers(); int getPort(); void setPort(Integer port); int getOnlinePlayerCount(); void setOnlinePlayerCount(int onlinePlayerCount); int getMaxPlayers(); void setMaxPlayers(int maxPlayers); String getMap(); void setMap(String map); boolean hasMap(); boolean isStarting(); DoAfterAmount getTemplateUpdate(); void setTemplateUpdate(DoAfterAmount templateUpdate); void executeCommand(String command); ServerObject toServerObject(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void stop() { } |
### Question:
Server implements Instance, Communicatable { @Override public void register() { if (isRegistered()) return; getGroup().onServerConnect(this); setState("ONLINE"); for (ProxyGroup proxyGroup : TimoCloudCore.getInstance().getInstanceManager().getProxyGroups()) { if (!proxyGroup.getServerGroups().contains(getGroup())) continue; proxyGroup.registerServer(this); } this.starting = false; this.registered = true; TimoCloudCore.getInstance().info("Server " + getName() + " registered."); TimoCloudCore.getInstance().getEventManager().fireEvent(new ServerRegisterEvent(toServerObject())); } Server(String name, String id, Base base, String map, ServerGroup group); boolean isStatic(); @Override void start(); @Override void stop(); @Override void onConnect(Channel channel); @Override void onDisconnect(); @Override void register(); @Override void unregister(); void onPlayerConnect(PlayerObject playerObject); void onPlayerDisconnect(PlayerObject playerObject); @Override void onMessage(Message message); @Override void sendMessage(Message message); @Override void onHandshakeSuccess(); @Override String getName(); @Override String getId(); boolean isRegistered(); @Override ServerGroup getGroup(); @Override Channel getChannel(); Base getBase(); InetSocketAddress getAddress(); void setAddress(InetSocketAddress address); void setChannel(Channel channel); String getState(); void setState(String state); String getExtra(); void setExtra(String extra); String getMotd(); void setMotd(String motd); Set<PlayerObject> getOnlinePlayers(); int getPort(); void setPort(Integer port); int getOnlinePlayerCount(); void setOnlinePlayerCount(int onlinePlayerCount); int getMaxPlayers(); void setMaxPlayers(int maxPlayers); String getMap(); void setMap(String map); boolean hasMap(); boolean isStarting(); DoAfterAmount getTemplateUpdate(); void setTemplateUpdate(DoAfterAmount templateUpdate); void executeCommand(String command); ServerObject toServerObject(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void register() { } |
### Question:
Server implements Instance, Communicatable { public void onPlayerConnect(PlayerObject playerObject) { if (!getOnlinePlayers().contains(playerObject)) getOnlinePlayers().add(playerObject); } Server(String name, String id, Base base, String map, ServerGroup group); boolean isStatic(); @Override void start(); @Override void stop(); @Override void onConnect(Channel channel); @Override void onDisconnect(); @Override void register(); @Override void unregister(); void onPlayerConnect(PlayerObject playerObject); void onPlayerDisconnect(PlayerObject playerObject); @Override void onMessage(Message message); @Override void sendMessage(Message message); @Override void onHandshakeSuccess(); @Override String getName(); @Override String getId(); boolean isRegistered(); @Override ServerGroup getGroup(); @Override Channel getChannel(); Base getBase(); InetSocketAddress getAddress(); void setAddress(InetSocketAddress address); void setChannel(Channel channel); String getState(); void setState(String state); String getExtra(); void setExtra(String extra); String getMotd(); void setMotd(String motd); Set<PlayerObject> getOnlinePlayers(); int getPort(); void setPort(Integer port); int getOnlinePlayerCount(); void setOnlinePlayerCount(int onlinePlayerCount); int getMaxPlayers(); void setMaxPlayers(int maxPlayers); String getMap(); void setMap(String map); boolean hasMap(); boolean isStarting(); DoAfterAmount getTemplateUpdate(); void setTemplateUpdate(DoAfterAmount templateUpdate); void executeCommand(String command); ServerObject toServerObject(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void onPlayerConnect() { } |
### Question:
Server implements Instance, Communicatable { public void onPlayerDisconnect(PlayerObject playerObject) { if (getOnlinePlayers().contains(playerObject)) getOnlinePlayers().remove(playerObject); } Server(String name, String id, Base base, String map, ServerGroup group); boolean isStatic(); @Override void start(); @Override void stop(); @Override void onConnect(Channel channel); @Override void onDisconnect(); @Override void register(); @Override void unregister(); void onPlayerConnect(PlayerObject playerObject); void onPlayerDisconnect(PlayerObject playerObject); @Override void onMessage(Message message); @Override void sendMessage(Message message); @Override void onHandshakeSuccess(); @Override String getName(); @Override String getId(); boolean isRegistered(); @Override ServerGroup getGroup(); @Override Channel getChannel(); Base getBase(); InetSocketAddress getAddress(); void setAddress(InetSocketAddress address); void setChannel(Channel channel); String getState(); void setState(String state); String getExtra(); void setExtra(String extra); String getMotd(); void setMotd(String motd); Set<PlayerObject> getOnlinePlayers(); int getPort(); void setPort(Integer port); int getOnlinePlayerCount(); void setOnlinePlayerCount(int onlinePlayerCount); int getMaxPlayers(); void setMaxPlayers(int maxPlayers); String getMap(); void setMap(String map); boolean hasMap(); boolean isStarting(); DoAfterAmount getTemplateUpdate(); void setTemplateUpdate(DoAfterAmount templateUpdate); void executeCommand(String command); ServerObject toServerObject(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void onPlayerDisconnect() { } |
### Question:
Server implements Instance, Communicatable { @Override public String getName() { return name; } Server(String name, String id, Base base, String map, ServerGroup group); boolean isStatic(); @Override void start(); @Override void stop(); @Override void onConnect(Channel channel); @Override void onDisconnect(); @Override void register(); @Override void unregister(); void onPlayerConnect(PlayerObject playerObject); void onPlayerDisconnect(PlayerObject playerObject); @Override void onMessage(Message message); @Override void sendMessage(Message message); @Override void onHandshakeSuccess(); @Override String getName(); @Override String getId(); boolean isRegistered(); @Override ServerGroup getGroup(); @Override Channel getChannel(); Base getBase(); InetSocketAddress getAddress(); void setAddress(InetSocketAddress address); void setChannel(Channel channel); String getState(); void setState(String state); String getExtra(); void setExtra(String extra); String getMotd(); void setMotd(String motd); Set<PlayerObject> getOnlinePlayers(); int getPort(); void setPort(Integer port); int getOnlinePlayerCount(); void setOnlinePlayerCount(int onlinePlayerCount); int getMaxPlayers(); void setMaxPlayers(int maxPlayers); String getMap(); void setMap(String map); boolean hasMap(); boolean isStarting(); DoAfterAmount getTemplateUpdate(); void setTemplateUpdate(DoAfterAmount templateUpdate); void executeCommand(String command); ServerObject toServerObject(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void getName() { } |
### Question:
Server implements Instance, Communicatable { @Override public String getId() { return id; } Server(String name, String id, Base base, String map, ServerGroup group); boolean isStatic(); @Override void start(); @Override void stop(); @Override void onConnect(Channel channel); @Override void onDisconnect(); @Override void register(); @Override void unregister(); void onPlayerConnect(PlayerObject playerObject); void onPlayerDisconnect(PlayerObject playerObject); @Override void onMessage(Message message); @Override void sendMessage(Message message); @Override void onHandshakeSuccess(); @Override String getName(); @Override String getId(); boolean isRegistered(); @Override ServerGroup getGroup(); @Override Channel getChannel(); Base getBase(); InetSocketAddress getAddress(); void setAddress(InetSocketAddress address); void setChannel(Channel channel); String getState(); void setState(String state); String getExtra(); void setExtra(String extra); String getMotd(); void setMotd(String motd); Set<PlayerObject> getOnlinePlayers(); int getPort(); void setPort(Integer port); int getOnlinePlayerCount(); void setOnlinePlayerCount(int onlinePlayerCount); int getMaxPlayers(); void setMaxPlayers(int maxPlayers); String getMap(); void setMap(String map); boolean hasMap(); boolean isStarting(); DoAfterAmount getTemplateUpdate(); void setTemplateUpdate(DoAfterAmount templateUpdate); void executeCommand(String command); ServerObject toServerObject(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void getId() { } |
### Question:
Server implements Instance, Communicatable { @Override public ServerGroup getGroup() { return group; } Server(String name, String id, Base base, String map, ServerGroup group); boolean isStatic(); @Override void start(); @Override void stop(); @Override void onConnect(Channel channel); @Override void onDisconnect(); @Override void register(); @Override void unregister(); void onPlayerConnect(PlayerObject playerObject); void onPlayerDisconnect(PlayerObject playerObject); @Override void onMessage(Message message); @Override void sendMessage(Message message); @Override void onHandshakeSuccess(); @Override String getName(); @Override String getId(); boolean isRegistered(); @Override ServerGroup getGroup(); @Override Channel getChannel(); Base getBase(); InetSocketAddress getAddress(); void setAddress(InetSocketAddress address); void setChannel(Channel channel); String getState(); void setState(String state); String getExtra(); void setExtra(String extra); String getMotd(); void setMotd(String motd); Set<PlayerObject> getOnlinePlayers(); int getPort(); void setPort(Integer port); int getOnlinePlayerCount(); void setOnlinePlayerCount(int onlinePlayerCount); int getMaxPlayers(); void setMaxPlayers(int maxPlayers); String getMap(); void setMap(String map); boolean hasMap(); boolean isStarting(); DoAfterAmount getTemplateUpdate(); void setTemplateUpdate(DoAfterAmount templateUpdate); void executeCommand(String command); ServerObject toServerObject(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void getGroup() { } |
### Question:
Server implements Instance, Communicatable { @Override public Channel getChannel() { return channel; } Server(String name, String id, Base base, String map, ServerGroup group); boolean isStatic(); @Override void start(); @Override void stop(); @Override void onConnect(Channel channel); @Override void onDisconnect(); @Override void register(); @Override void unregister(); void onPlayerConnect(PlayerObject playerObject); void onPlayerDisconnect(PlayerObject playerObject); @Override void onMessage(Message message); @Override void sendMessage(Message message); @Override void onHandshakeSuccess(); @Override String getName(); @Override String getId(); boolean isRegistered(); @Override ServerGroup getGroup(); @Override Channel getChannel(); Base getBase(); InetSocketAddress getAddress(); void setAddress(InetSocketAddress address); void setChannel(Channel channel); String getState(); void setState(String state); String getExtra(); void setExtra(String extra); String getMotd(); void setMotd(String motd); Set<PlayerObject> getOnlinePlayers(); int getPort(); void setPort(Integer port); int getOnlinePlayerCount(); void setOnlinePlayerCount(int onlinePlayerCount); int getMaxPlayers(); void setMaxPlayers(int maxPlayers); String getMap(); void setMap(String map); boolean hasMap(); boolean isStarting(); DoAfterAmount getTemplateUpdate(); void setTemplateUpdate(DoAfterAmount templateUpdate); void executeCommand(String command); ServerObject toServerObject(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void getChannel() { } |
### Question:
FloatParser implements ConfigurationParser { @Override public Float parseValue(String value, Class targetType) { if(value == null) throw new ConfigurationParserException("Could not parse 'null' to float"); return Float.parseFloat(value); } @Override Set<Class> getResponsibleClasses(); @Override Float parseValue(String value, Class targetType); }### Answer:
@Test(expected = NumberFormatException.class) public void parseInvalidDouble2() { parser.parseValue("5,555.5", Float.class); fail(); }
@Test public void parseValue() { assertEquals(1.0f, parser.parseValue("1", Float.class)); assertEquals(-5.564f, parser.parseValue("-5.564", Float.class)); assertEquals(35005f, parser.parseValue("35005", Float.class)); assertEquals(-8f, parser.parseValue("-8", Float.class)); assertEquals(0f, parser.parseValue("0", Float.class)); }
@Test(expected = ConfigurationParserException.class) public void parseNull() { parser.parseValue(null, Float.class); fail(); }
@Test(expected = NumberFormatException.class) public void parseInvalidDouble1() { parser.parseValue("asdf", Float.class); fail(); } |
### Question:
ShortParser implements ConfigurationParser { @Override public Set<Class> getResponsibleClasses() { Set<Class> responsibleClasses = new HashSet<>(); responsibleClasses.add(Short.class); responsibleClasses.add(short.class); return responsibleClasses; } @Override Set<Class> getResponsibleClasses(); @Override Short parseValue(String value, Class targetType); }### Answer:
@Test public void getResponsibleClasses() { Set<Class> responsibleClasses = parser.getResponsibleClasses(); assertTrue(responsibleClasses.contains(Short.class)); assertTrue(responsibleClasses.contains(short.class)); } |
### Question:
ShortParser implements ConfigurationParser { @Override public Short parseValue(String value, Class targetType) { if(value == null) throw new ConfigurationParserException("Could not parse 'null' to short"); return Short.parseShort(value); } @Override Set<Class> getResponsibleClasses(); @Override Short parseValue(String value, Class targetType); }### Answer:
@Test public void parseValue() { assertEquals((short)1, parser.parseValue("1", Short.class)); assertEquals((short)-5564, parser.parseValue("-5564", Short.class)); assertEquals((short)3505, parser.parseValue("3505", Short.class)); assertEquals((short)-8, parser.parseValue("-8", Short.class)); assertEquals((short)0, parser.parseValue("0", Short.class)); }
@Test(expected = ConfigurationParserException.class) public void parseNull() { parser.parseValue(null, Short.class); fail(); }
@Test(expected = NumberFormatException.class) public void parseInvalidDouble1() { parser.parseValue("asdf", Short.class); fail(); }
@Test(expected = NumberFormatException.class) public void parseInvalidDouble2() { parser.parseValue("5.5", Short.class); fail(); } |
### Question:
ByteParser implements ConfigurationParser { @Override public Set<Class> getResponsibleClasses() { Set<Class> responsibleClasses = new HashSet<>(); responsibleClasses.add(Byte.class); responsibleClasses.add(byte.class); return responsibleClasses; } @Override Set<Class> getResponsibleClasses(); @Override Byte parseValue(String value, Class targetType); }### Answer:
@Test public void getResponsibleClasses() { Set<Class> responsibleClasses = parser.getResponsibleClasses(); assertTrue(responsibleClasses.contains(Byte.class)); assertTrue(responsibleClasses.contains(byte.class)); } |
### Question:
ByteParser implements ConfigurationParser { @Override public Byte parseValue(String value, Class targetType) { if(value == null) throw new ConfigurationParserException("Could not parse 'null' to byte"); return Byte.parseByte(value); } @Override Set<Class> getResponsibleClasses(); @Override Byte parseValue(String value, Class targetType); }### Answer:
@Test public void parseValue() { assertEquals((byte)1, parser.parseValue("1", Byte.class)); assertEquals((byte)53, parser.parseValue("53", Byte.class)); assertEquals((byte)-69, parser.parseValue("-69", Byte.class)); }
@Test(expected = ConfigurationParserException.class) public void parseNull() { parser.parseValue(null, Byte.class); fail(); }
@Test(expected = NumberFormatException.class) public void parseInvalidNum() { parser.parseValue("-454282", Byte.class); fail(); }
@Test(expected = NumberFormatException.class) public void parseInvalidString() { parser.parseValue("s", Byte.class); fail(); } |
### Question:
BooleanParser implements ConfigurationParser { @Override public Set<Class> getResponsibleClasses() { Set<Class> responsibleClasses = new HashSet<>(); responsibleClasses.add(Boolean.class); responsibleClasses.add(boolean.class); return responsibleClasses; } @Override Set<Class> getResponsibleClasses(); @Override Boolean parseValue(String value, Class targetType); }### Answer:
@Test public void getResponsibleClasses() { Set<Class> responsibleClasses = parser.getResponsibleClasses(); assertTrue(responsibleClasses.contains(Boolean.class)); assertTrue(responsibleClasses.contains(boolean.class)); } |
### Question:
BooleanParser implements ConfigurationParser { @Override public Boolean parseValue(String value, Class targetType) { if(value == null) throw new ConfigurationParserException("Could not parse 'null' to boolean"); Set<String> trueSet = new HashSet<>(Arrays.asList("1", "true", "yes")); value = value.toLowerCase(); return trueSet.contains(value); } @Override Set<Class> getResponsibleClasses(); @Override Boolean parseValue(String value, Class targetType); }### Answer:
@Test public void parseValue() { assertEquals(Boolean.TRUE, parser.parseValue("1", Boolean.class)); assertEquals(Boolean.TRUE, parser.parseValue("yes", Boolean.class)); assertEquals(Boolean.TRUE, parser.parseValue("true", Boolean.class)); assertEquals(Boolean.FALSE, parser.parseValue("asfdsdgf", Boolean.class)); assertEquals(Boolean.FALSE, parser.parseValue("", Boolean.class)); }
@Test(expected = ConfigurationParserException.class) public void parseNull() { parser.parseValue(null, Boolean.class); fail(); } |
### Question:
DoubleParser implements ConfigurationParser { @Override public Set<Class> getResponsibleClasses() { Set<Class> responsibleClasses = new HashSet<>(); responsibleClasses.add(Double.class); responsibleClasses.add(double.class); return responsibleClasses; } @Override Set<Class> getResponsibleClasses(); @Override Double parseValue(String value, Class targetType); }### Answer:
@Test public void getResponsibleClasses() { Set<Class> responsibleClasses = parser.getResponsibleClasses(); assertTrue(responsibleClasses.contains(Double.class)); assertTrue(responsibleClasses.contains(double.class)); } |
### Question:
DoubleParser implements ConfigurationParser { @Override public Double parseValue(String value, Class targetType) { if(value == null) throw new ConfigurationParserException("Could not parse 'null' to double"); return Double.parseDouble(value); } @Override Set<Class> getResponsibleClasses(); @Override Double parseValue(String value, Class targetType); }### Answer:
@Test public void parseValue() { assertEquals(1.0d, parser.parseValue("1", Double.class)); assertEquals(-5.564d, parser.parseValue("-5.564", Double.class)); assertEquals(3500.5d, parser.parseValue("3500.5", Double.class)); assertEquals(-8d, parser.parseValue("-8", Double.class)); assertEquals(0d, parser.parseValue("0", Double.class)); }
@Test(expected = ConfigurationParserException.class) public void parseNull() { parser.parseValue(null, Double.class); fail(); }
@Test(expected = NumberFormatException.class) public void parseInvalidDouble1() { parser.parseValue("asdf", Double.class); fail(); }
@Test(expected = NumberFormatException.class) public void parseInvalidDouble2() { parser.parseValue("5,555.5", Double.class); fail(); } |
### Question:
CharArrayParser implements ConfigurationParser { @Override public Set<Class> getResponsibleClasses() { Set<Class> responsibleClasses = new HashSet<>(); responsibleClasses.add(Character[].class); responsibleClasses.add(char[].class); return responsibleClasses; } @Override Set<Class> getResponsibleClasses(); @Override char[] parseValue(String value, Class targetType); }### Answer:
@Test public void getResponsibleClasses() { Set<Class> responsibleClasses = parser.getResponsibleClasses(); assertTrue(responsibleClasses.contains(Character[].class)); assertTrue(responsibleClasses.contains(char[].class)); } |
### Question:
CharArrayParser implements ConfigurationParser { @Override public char[] parseValue(String value, Class targetType) { if(value == null) throw new ConfigurationParserException("Could not parse 'null' to char[]"); return value.toCharArray(); } @Override Set<Class> getResponsibleClasses(); @Override char[] parseValue(String value, Class targetType); }### Answer:
@Test public void parseValue() { assertTrue(Arrays.equals("sss1".toCharArray(), (char[])parser.parseValue("sss1", Character[].class))); assertTrue(Arrays.equals("äd aqsd".toCharArray(), (char[])parser.parseValue("äd aqsd", Character[].class))); assertTrue(Arrays.equals("-9".toCharArray(), (char[])parser.parseValue("-9", Character[].class))); }
@Test(expected = ConfigurationParserException.class) public void parseNull() { parser.parseValue(null, Character[].class); fail(); } |
### Question:
IntParser implements ConfigurationParser { @Override public Set<Class> getResponsibleClasses() { Set<Class> responsibleClasses = new HashSet<>(); responsibleClasses.add(Integer.class); responsibleClasses.add(int.class); return responsibleClasses; } @Override Set<Class> getResponsibleClasses(); @Override Integer parseValue(String value, Class targetType); }### Answer:
@Test public void getResponsibleClasses() { Set<Class> responsibleClasses = parser.getResponsibleClasses(); assertTrue(responsibleClasses.contains(Integer.class)); assertTrue(responsibleClasses.contains(int.class)); } |
### Question:
IntParser implements ConfigurationParser { @Override public Integer parseValue(String value, Class targetType) { if(value == null) throw new ConfigurationParserException("Could not parse 'null' to int"); return Integer.parseInt(value); } @Override Set<Class> getResponsibleClasses(); @Override Integer parseValue(String value, Class targetType); }### Answer:
@Test public void parseValue() { assertEquals(1, parser.parseValue("1", Integer.class)); assertEquals(-5564, parser.parseValue("-5564", Integer.class)); assertEquals(35005, parser.parseValue("35005", Integer.class)); assertEquals(-8, parser.parseValue("-8", Integer.class)); assertEquals(0, parser.parseValue("0", Integer.class)); }
@Test(expected = ConfigurationParserException.class) public void parseNull() { parser.parseValue(null, Integer.class); fail(); }
@Test(expected = NumberFormatException.class) public void parseInvalidDouble1() { parser.parseValue("asdf", Integer.class); fail(); }
@Test(expected = NumberFormatException.class) public void parseInvalidDouble2() { parser.parseValue("5555.5", Integer.class); fail(); } |
### Question:
Parsers { public static List<ConfigurationParser> getDefaultParsers() { List<ConfigurationParser> defaultParser = new ArrayList<>(); defaultParser.add(new BooleanParser()); defaultParser.add(new ByteParser()); defaultParser.add(new CharArrayParser()); defaultParser.add(new CharParser()); defaultParser.add(new DoubleParser()); defaultParser.add(new FloatParser()); defaultParser.add(new IntParser()); defaultParser.add(new LongParser()); defaultParser.add(new ShortParser()); defaultParser.add(new StringParser()); return defaultParser; } private Parsers(); static List<ConfigurationParser> getDefaultParsers(); }### Answer:
@Test public void getDefaultParsers() { List<ConfigurationParser> configurationParsers = Parsers.getDefaultParsers(); assertTrue(containsClassOfType(configurationParsers, BooleanParser.class)); assertTrue(containsClassOfType(configurationParsers, ByteParser.class)); assertTrue(containsClassOfType(configurationParsers, CharArrayParser.class)); assertTrue(containsClassOfType(configurationParsers, CharParser.class)); assertTrue(containsClassOfType(configurationParsers, DoubleParser.class)); assertTrue(containsClassOfType(configurationParsers, FloatParser.class)); assertTrue(containsClassOfType(configurationParsers, IntParser.class)); assertTrue(containsClassOfType(configurationParsers, LongParser.class)); assertTrue(containsClassOfType(configurationParsers, ShortParser.class)); assertTrue(containsClassOfType(configurationParsers, StringParser.class)); } |
### Question:
CharParser implements ConfigurationParser { @Override public Set<Class> getResponsibleClasses() { Set<Class> responsibleClasses = new HashSet<>(); responsibleClasses.add(Character.class); responsibleClasses.add(char.class); return responsibleClasses; } @Override Set<Class> getResponsibleClasses(); @Override Character parseValue(String value, Class targetType); }### Answer:
@Test public void getResponsibleClasses() { Set<Class> responsibleClasses = parser.getResponsibleClasses(); assertTrue(responsibleClasses.contains(Character.class)); assertTrue(responsibleClasses.contains(char.class)); } |
### Question:
CharParser implements ConfigurationParser { @Override public Character parseValue(String value, Class targetType) { if(value == null) throw new ConfigurationParserException("Could not parse 'null' to char"); if(value.length() != 1) throw new ConfigurationParserException("value must contain only one character"); return value.charAt(0); } @Override Set<Class> getResponsibleClasses(); @Override Character parseValue(String value, Class targetType); }### Answer:
@Test public void parseValue() { assertEquals('2', parser.parseValue("2", Character.class)); assertEquals('ä', parser.parseValue("ä", Character.class)); assertEquals('l', parser.parseValue("l", Character.class)); }
@Test(expected = ConfigurationParserException.class) public void parseNull() { parser.parseValue(null, Character.class); fail(); }
@Test(expected = ConfigurationParserException.class) public void parseToLongString() { parser.parseValue("tooManyChars", Character.class); fail(); } |
### Question:
StringParser implements ConfigurationParser { @Override public Set<Class> getResponsibleClasses() { return Collections.singleton(String.class); } @Override Set<Class> getResponsibleClasses(); @Override String parseValue(String value, Class targetType); }### Answer:
@Test public void getResponsibleClasses() { Set<Class> responsibleClasses = parser.getResponsibleClasses(); assertTrue(responsibleClasses.contains(String.class)); } |
### Question:
StringParser implements ConfigurationParser { @Override public String parseValue(String value, Class targetType) { if(value == null) throw new ConfigurationParserException("Could not parse 'null' to string"); return value; } @Override Set<Class> getResponsibleClasses(); @Override String parseValue(String value, Class targetType); }### Answer:
@Test public void parseValue() { assertEquals("asdfadga11d54sfg#drfg$%&/(", parser.parseValue("asdfadga11d54sfg#drfg$%&/(", String.class)); }
@Test(expected = ConfigurationParserException.class) public void parseNull() { parser.parseValue(null, String.class); fail(); } |
### Question:
LongParser implements ConfigurationParser { @Override public Set<Class> getResponsibleClasses() { Set<Class> responsibleClasses = new HashSet<>(); responsibleClasses.add(Long.class); responsibleClasses.add(long.class); return responsibleClasses; } @Override Set<Class> getResponsibleClasses(); @Override Long parseValue(String value, Class targetType); }### Answer:
@Test public void getResponsibleClasses() { Set<Class> responsibleClasses = parser.getResponsibleClasses(); assertTrue(responsibleClasses.contains(Long.class)); assertTrue(responsibleClasses.contains(long.class)); } |
### Question:
LongParser implements ConfigurationParser { @Override public Long parseValue(String value, Class targetType) { if(value == null) throw new ConfigurationParserException("Could not parse 'null' to long"); return Long.parseLong(value); } @Override Set<Class> getResponsibleClasses(); @Override Long parseValue(String value, Class targetType); }### Answer:
@Test public void parseValue() { assertEquals(1L, parser.parseValue("1", Long.class)); assertEquals(-5564L, parser.parseValue("-5564", Long.class)); assertEquals(35005L, parser.parseValue("35005", Long.class)); assertEquals(-8L, parser.parseValue("-8", Long.class)); assertEquals(0L, parser.parseValue("0", Long.class)); }
@Test(expected = ConfigurationParserException.class) public void parseNull() { parser.parseValue(null, Long.class); fail(); }
@Test(expected = NumberFormatException.class) public void parseInvalidDouble1() { parser.parseValue("asdf", Long.class); fail(); }
@Test(expected = NumberFormatException.class) public void parseInvalidDouble2() { parser.parseValue("5,555.5", Long.class); fail(); } |
### Question:
EnvironmentVariableLoader implements ConfigurationLoader { @Override public Properties loadConfigurations() { Properties properties = new Properties(); Map<String, String> envVars = System.getenv(); envVars.forEach(properties::put); return properties; } @Override Properties loadConfigurations(); }### Answer:
@Test public void loadConfigurations() { EnvironmentVariableLoader loader = new EnvironmentVariableLoader(); Properties properties = loader.loadConfigurations(); Set<Map.Entry<String, String>> systemEnvEntrySet = System.getenv().entrySet(); for (Map.Entry<String, String> systemEnvEntry : systemEnvEntrySet) { String key = systemEnvEntry.getKey(); String value = systemEnvEntry.getValue(); assertNotNull(properties.getProperty(key)); assertEquals(value, properties.getProperty(key)); } } |
### Question:
ConfigurationProcessorBuilder { public ConfigurationProcessorBuilder addConfigurationParser(ConfigurationParser configurationParser) { if (configurationParser == null) { throw new NullPointerException("configurationParser must not be null"); } this.configurationParsers.add(configurationParser); return this; } ConfigurationProcessorBuilder(); ConfigurationProcessorBuilder addConfigurationParser(ConfigurationParser configurationParser); ConfigurationProcessorBuilder addConfigurationParsers(List<ConfigurationParser> configurationParsers); ConfigurationProcessorBuilder setConfigurationLoader(ConfigurationLoader configurationLoader); ConfigurationProcessor build(); }### Answer:
@Test public void addConfigurationParser() { new ConfigurationProcessorBuilder().addConfigurationParser(new ConfigurationParser() { @Override public Set<Class> getResponsibleClasses() { return null; } @Override public Object parseValue(String value, Class targetClass) { return null; } }); }
@Test(expected = NullPointerException.class) public void addConfigurationParserNull() { new ConfigurationProcessorBuilder().addConfigurationParser(null); fail(); } |
### Question:
ConfigurationProcessorBuilder { public ConfigurationProcessorBuilder setConfigurationLoader(ConfigurationLoader configurationLoader) { if (configurationLoader == null) { throw new NullPointerException("configurationLoader must not be null"); } this.configurationLoader = configurationLoader; return this; } ConfigurationProcessorBuilder(); ConfigurationProcessorBuilder addConfigurationParser(ConfigurationParser configurationParser); ConfigurationProcessorBuilder addConfigurationParsers(List<ConfigurationParser> configurationParsers); ConfigurationProcessorBuilder setConfigurationLoader(ConfigurationLoader configurationLoader); ConfigurationProcessor build(); }### Answer:
@Test public void setConfigurationLoader() { new ConfigurationProcessorBuilder().setConfigurationLoader(() -> null); }
@Test(expected = NullPointerException.class) public void setConfigurationLoaderNull() { new ConfigurationProcessorBuilder().setConfigurationLoader(null); fail(); } |
### Question:
ConfigurationProcessorBuilder { public ConfigurationProcessor build() { Properties configurations = configurationLoader.loadConfigurations(); Map<Class, ConfigurationParser> mappedConfigurationParsers = new HashMap<>(); for (ConfigurationParser configurationParser : configurationParsers) { Set<Class> responsibleClasses = configurationParser.getResponsibleClasses(); for (Class clazz : responsibleClasses) { mappedConfigurationParsers.put(clazz, configurationParser); LOGGER.fine(MessageFormat.format("''{0}'' mapped on ''{1}''", clazz.getTypeName(), configurationParser.getClass().getTypeName())); } } LOGGER.finest(MessageFormat.format("Available configurations: {0}", configurations.toString())); return new ConfigurationProcessor(configurations, mappedConfigurationParsers); } ConfigurationProcessorBuilder(); ConfigurationProcessorBuilder addConfigurationParser(ConfigurationParser configurationParser); ConfigurationProcessorBuilder addConfigurationParsers(List<ConfigurationParser> configurationParsers); ConfigurationProcessorBuilder setConfigurationLoader(ConfigurationLoader configurationLoader); ConfigurationProcessor build(); }### Answer:
@Test public void build() throws NoSuchFieldException, IllegalAccessException { ConfigurationLoader configurationLoader = new ConfigurationLoaderDummyImpl("test.test", "Value"); ConfigurationParser configurationParser1 = new ConfigurationParserDummyImpl(String.class); ConfigurationParser configurationParser2 = new ConfigurationParserDummy2Impl(Long.class); ConfigurationProcessor configurationProcessor = new ConfigurationProcessorBuilder() .setConfigurationLoader(configurationLoader) .addConfigurationParser(configurationParser1) .addConfigurationParser(configurationParser2) .build(); Properties properties = (Properties)RefelctionTestUtils.getFieldValue(configurationProcessor, "configurations"); Map<String, ConfigurationParser> configurationParsers = (Map<String, ConfigurationParser>)RefelctionTestUtils.getFieldValue(configurationProcessor, "configurationParsers"); assertNotNull(properties); assertEquals(properties.get("test.test"), "Value"); assertNotNull(configurationParsers); assertEquals(configurationParsers.size(), 2); assertEquals(configurationParsers.get(String.class).getClass().getTypeName(), ConfigurationParserDummyImpl.class.getTypeName()); assertEquals(configurationParsers.get(Long.class).getClass().getTypeName(), ConfigurationParserDummy2Impl.class.getTypeName()); } |
### Question:
HierarchicalLoader implements ConfigurationLoader { @Override public Properties loadConfigurations() { return properties; } private HierarchicalLoader(Properties properties); @Override Properties loadConfigurations(); }### Answer:
@Test public void builder() { String keyDuplicate = "test.test"; String keyA = "testA"; String keyB = "testB"; Map<String, String> propertiesA = new HashMap<>(); Map<String, String> propertiesB = new HashMap<>(); propertiesA.put(keyDuplicate, "value.value"); propertiesA.put(keyA, "valueA.value"); propertiesB.put(keyDuplicate, "valueB.value"); propertiesB.put(keyB, "valueB.value"); DummyLoader dummyLoaderA = new DummyLoader(propertiesA); DummyLoader dummyLoaderB = new DummyLoader(propertiesB); ConfigurationLoader configurationLoader = new HierarchicalLoader.Builder() .addLoader(dummyLoaderA) .addLoader(dummyLoaderB).build(); Properties properties = configurationLoader.loadConfigurations(); assertNotNull(properties); assertEquals("valueB.value", properties.getProperty(keyDuplicate)); assertEquals("valueA.value", properties.getProperty(keyA)); assertEquals("valueB.value", properties.getProperty(keyB)); assertNull(properties.getProperty("not found")); } |
### Question:
FloatParser implements ConfigurationParser { @Override public Set<Class> getResponsibleClasses() { Set<Class> responsibleClasses = new HashSet<>(); responsibleClasses.add(Float.class); responsibleClasses.add(float.class); return responsibleClasses; } @Override Set<Class> getResponsibleClasses(); @Override Float parseValue(String value, Class targetType); }### Answer:
@Test public void getResponsibleClasses() { Set<Class> responsibleClasses = parser.getResponsibleClasses(); assertTrue(responsibleClasses.contains(Float.class)); assertTrue(responsibleClasses.contains(float.class)); } |
### Question:
GuiceVerticleFactory implements VerticleFactory { @Override public String prefix() { return PREFIX; } Injector getInjector(); GuiceVerticleFactory setInjector(Injector injector); @Override String prefix(); @Override Verticle createVerticle(String verticleName, ClassLoader classLoader); static final String PREFIX; }### Answer:
@Test public void testPrefix() { assertEquals("java-guice", factory.prefix()); } |
### Question:
GuiceVerticleFactory implements VerticleFactory { @Override public Verticle createVerticle(String verticleName, ClassLoader classLoader) throws Exception { verticleName = VerticleFactory.removePrefix(verticleName); @SuppressWarnings("unchecked") Class<Verticle> loader = (Class<Verticle>) classLoader.loadClass(GuiceVerticleLoader.class.getName()); Constructor<Verticle> ctor = loader.getConstructor(String.class, ClassLoader.class, Injector.class); if (ctor == null) { throw new IllegalStateException("Could not find GuiceVerticleLoader constructor"); } return ctor.newInstance(verticleName, classLoader, getInjector()); } Injector getInjector(); GuiceVerticleFactory setInjector(Injector injector); @Override String prefix(); @Override Verticle createVerticle(String verticleName, ClassLoader classLoader); static final String PREFIX; }### Answer:
@Test public void testCreateVerticle() throws Exception { String identifier = GuiceVerticleFactory.PREFIX + ":" + TestGuiceVerticle.class.getName(); Verticle verticle = factory.createVerticle(identifier, this.getClass().getClassLoader()); assertThat(verticle, instanceOf(GuiceVerticleLoader.class)); GuiceVerticleLoader loader = (GuiceVerticleLoader) verticle; assertEquals(TestGuiceVerticle.class.getName(), loader.getVerticleName()); } |
### Question:
GuiceVerticleFactory implements VerticleFactory { public GuiceVerticleFactory setInjector(Injector injector) { this.injector = injector; return this; } Injector getInjector(); GuiceVerticleFactory setInjector(Injector injector); @Override String prefix(); @Override Verticle createVerticle(String verticleName, ClassLoader classLoader); static final String PREFIX; }### Answer:
@Test public void testSetInjector() throws Exception { assertNull(factory.getInjector()); Injector injector = mock(Injector.class); factory.setInjector(injector); assertEquals(injector, factory.getInjector()); } |
### Question:
ReflectUtils { public static Class<?> forName(String name) { try { return name2class(name); } catch (ClassNotFoundException e) { throw new IllegalStateException("Not found class " + name + ", cause: " + e.getMessage(), e); } } static String getName(Class<?> c); static String getDesc(Class<?> c); static String desc2name(String desc); static Class<?> forName(String name); static Class<?> name2class(String name); static boolean isPrimitives(Class<?> cls); static boolean isPrimitive(Class<?> cls); static final char JVM_VOID; static final char JVM_BOOLEAN; static final char JVM_BYTE; static final char JVM_CHAR; static final char JVM_DOUBLE; static final char JVM_FLOAT; static final char JVM_INT; static final char JVM_LONG; static final char JVM_SHORT; }### Answer:
@Test public void testForName() throws ClassNotFoundException { int i = 12; System.out.println(ReflectUtils.getDesc(int.class)); System.out.println(ReflectUtils.getDesc(A.class)); String str = ReflectUtils.getDesc(int.class); System.out.println(ReflectUtils.name2class(ReflectUtils.desc2name(str))); } |
### Question:
ZkClient { public void watch(LinkedBlockingQueue<PathStatus> queue, final String p) throws Exception { if (this.stop.get() == true) { return; } logger.info("---------->watch path:{}", p); PathChildrenCache cache = new PathChildrenCache(this.client, p, true); list.add(cache); cache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT); cache.getListenable().addListener((cf, event) -> { switch (event.getType()) { case CHILD_ADDED: String path = event.getData().getPath(); String param = new String(event.getData().getData()); String addr = path.split("@")[1]; logger.info("------->CHILD_ADDED :{}:{}", path, addr); queue.offer(new PathStatus("CHILD_ADDED", Pair.of(addr, param), p)); break; case CHILD_UPDATED: String updatePath = event.getData().getPath(); logger.info("------>CHILD_UPDATED :" + event.getData().getPath()); String updateParam = new String(event.getData().getData()); String updateAddr = updatePath.split("@")[1]; queue.offer(new PathStatus("CHILD_UPDATED", Pair.of(updateAddr, updateParam), p)); break; case CHILD_REMOVED: String path2 = event.getData().getPath(); String addr2 = path2.split("@")[1]; logger.info("------>CHILD_REMOVED :{}:{}" + path2, addr2); queue.offer(new PathStatus("CHILD_REMOVED", Pair.of(addr2, ""), p)); break; default: break; } }); } private ZkClient(); static ZkClient ins(); Set<Pair<String, String>> get(String basePath, String serviceName); void create(String basePath, Set<String> serviceNames, String addr); void watch(LinkedBlockingQueue<PathStatus> queue, final String p); void close(); }### Answer:
@Test public void testWatch() throws Exception { } |
### Question:
ZkClient { public void create(String basePath, Set<String> serviceNames, String addr) { serviceNames.forEach(u -> { URL url = URL.valueOf(u); String path = basePath + url.getPath() + "/tcp@" + addr; try { if (client.checkExists().forPath(path) == null) { client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path, url.toParameterString().getBytes()); } } catch (Exception e) { e.printStackTrace(); } }); } private ZkClient(); static ZkClient ins(); Set<Pair<String, String>> get(String basePath, String serviceName); void create(String basePath, Set<String> serviceNames, String addr); void watch(LinkedBlockingQueue<PathStatus> queue, final String p); void close(); }### Answer:
@Test public void testCreate() throws Exception { ZkClient.ins().create("",new HashSet<>(),""); TimeUnit.HOURS.sleep(1); } |
### Question:
NettyServer extends NettyRemotingAbstract { public NettyServer() { nettyServerConfig = new NettyServerConfig(); this.serverBootstrap = new ServerBootstrap(); if (useEpoll()) { logger.info("----->use epollEventLoopGroup"); this.eventLoopGroupBoss = new EpollEventLoopGroup(1, new NamedThreadFactory("EpollNettyServerBoss_", false)); this.eventLoopGroupWorker = new EpollEventLoopGroup(nettyServerConfig.getServerWorkerThreads(), new NamedThreadFactory("NettyEpollServerWorker_", false)); } else { this.eventLoopGroupBoss = new NioEventLoopGroup(1, new NamedThreadFactory("NettyServerBoss_", false)); this.eventLoopGroupWorker = new NioEventLoopGroup(nettyServerConfig.getServerWorkerThreads(), new NamedThreadFactory("NettyServerWorker_", false)); } } NettyServer(); void start(); void await(); void setGetBeanFunc(Function<Class, Object> getBeanFunc); Function<Class, Object> getGetBeanFunc(); String getAddr(); int getPort(); }### Answer:
@Test public void testNettyServer() throws InterruptedException { NettyServer server = new NettyServer(); server.start(); ZkServiceRegister reg = new ZkServiceRegister("/youpin/services/", server.getAddr() + ":" + server.getPort(), "", null); reg.register(); reg.start(); TimeUnit.HOURS.sleep(1); } |
### Question:
InterProcessReadWriteLock { public InterProcessMutex writeLock() { return writeMutex; } InterProcessReadWriteLock(CuratorFramework client, String basePath); InterProcessReadWriteLock(CuratorFramework client, String basePath, byte[] lockData); InterProcessMutex readLock(); InterProcessMutex writeLock(); }### Answer:
@Test public void testSetNodeData() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); final byte[] nodeData = new byte[] { 1, 2, 3, 4 }; InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/lock", nodeData); nodeData[0] = 5; lock.writeLock().acquire(); List<String> children = client.getChildren().forPath("/lock"); Assert.assertEquals(1, children.size()); byte dataInZk[] = client.getData().forPath("/lock/" + children.get(0)); Assert.assertNotNull(dataInZk); Assert.assertEquals(new byte[] { 1, 2, 3, 4 }, dataInZk); lock.writeLock().release(); } finally { CloseableUtils.closeQuietly(client); } } |
### Question:
SimpleDistributedQueue { public byte[] poll(long timeout, TimeUnit unit) throws Exception { return internalPoll(timeout, unit); } SimpleDistributedQueue(CuratorFramework client, String path); byte[] element(); byte[] remove(); byte[] take(); boolean offer(byte[] data); byte[] peek(); byte[] poll(long timeout, TimeUnit unit); byte[] poll(); }### Answer:
@Test public void testPollWithTimeout() throws Exception { CuratorFramework clients[] = null; try { String dir = "/testOffer1"; final int num_clients = 1; clients = new CuratorFramework[num_clients]; SimpleDistributedQueue queueHandles[] = new SimpleDistributedQueue[num_clients]; for ( int i = 0; i < clients.length; i++ ) { clients[i] = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); clients[i].start(); queueHandles[i] = new SimpleDistributedQueue(clients[i], dir); } Assert.assertNull(queueHandles[0].poll(3, TimeUnit.SECONDS)); } finally { closeAll(clients); } } |
### Question:
SimpleDistributedQueue { public byte[] remove() throws Exception { byte[] bytes = internalElement(true, null); if ( bytes == null ) { throw new NoSuchElementException(); } return bytes; } SimpleDistributedQueue(CuratorFramework client, String path); byte[] element(); byte[] remove(); byte[] take(); boolean offer(byte[] data); byte[] peek(); byte[] poll(long timeout, TimeUnit unit); byte[] poll(); }### Answer:
@Test public void testRemova1() throws Exception { CuratorFramework clients[] = null; try { String dir = "/testRemove1"; final int num_clients = 1; clients = new CuratorFramework[num_clients]; SimpleDistributedQueue queueHandles[] = new SimpleDistributedQueue[num_clients]; for ( int i = 0; i < clients.length; i++ ) { clients[i] = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); clients[i].start(); queueHandles[i] = new SimpleDistributedQueue(clients[i], dir); } try { queueHandles[0].remove(); } catch ( NoSuchElementException e ) { return; } assertTrue(false); } finally { closeAll(clients); } } |
### Question:
DistributedBarrier { public synchronized void waitOnBarrier() throws Exception { waitOnBarrier(-1, null); } DistributedBarrier(CuratorFramework client, String barrierPath); synchronized void setBarrier(); synchronized void removeBarrier(); synchronized void waitOnBarrier(); synchronized boolean waitOnBarrier(long maxWait, TimeUnit unit); }### Answer:
@Test public void testNoBarrier() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); final DistributedBarrier barrier = new DistributedBarrier(client, "/barrier"); Assert.assertTrue(barrier.waitOnBarrier(10, TimeUnit.SECONDS)); ExecutorService service = Executors.newSingleThreadExecutor(); Future<Object> future = service.submit ( new Callable<Object>() { @Override public Object call() throws Exception { barrier.waitOnBarrier(); return ""; } } ); Assert.assertTrue(future.get(10, TimeUnit.SECONDS) != null); } finally { client.close(); } } |
### Question:
PathChildrenCache implements Closeable { protected void ensurePath() throws Exception { ensureContainers.ensure(); } @Deprecated @SuppressWarnings("deprecation") PathChildrenCache(CuratorFramework client, String path, PathChildrenCacheMode mode); @Deprecated @SuppressWarnings("deprecation") PathChildrenCache(CuratorFramework client, String path, PathChildrenCacheMode mode, ThreadFactory threadFactory); PathChildrenCache(CuratorFramework client, String path, boolean cacheData); PathChildrenCache(CuratorFramework client, String path, boolean cacheData, ThreadFactory threadFactory); PathChildrenCache(CuratorFramework client, String path, boolean cacheData, boolean dataIsCompressed, ThreadFactory threadFactory); PathChildrenCache(CuratorFramework client, String path, boolean cacheData, boolean dataIsCompressed, final ExecutorService executorService); PathChildrenCache(CuratorFramework client, String path, boolean cacheData, boolean dataIsCompressed, final CloseableExecutorService executorService); void start(); @Deprecated void start(boolean buildInitial); void start(StartMode mode); void rebuild(); void rebuildNode(String fullPath); @Override void close(); ListenerContainer<PathChildrenCacheListener> getListenable(); List<ChildData> getCurrentData(); ChildData getCurrentData(String fullPath); void clearDataBytes(String fullPath); boolean clearDataBytes(String fullPath, int ifVersion); void clearAndRefresh(); void clear(); }### Answer:
@Test public void testEnsurePath() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { PathChildrenCache cache = new PathChildrenCache(client, "/one/two/three", false); cache.start(); timing.sleepABit(); try { client.create().forPath("/one/two/three/four"); } catch ( KeeperException.NoNodeException e ) { Assert.fail("Path should exist", e); } } finally { CloseableUtils.closeQuietly(client); } } |
### Question:
DistributedAtomicLong implements DistributedAtomicNumber<Long> { @Override public AtomicValue<Long> get() throws Exception { return new AtomicLong(value.get()); } DistributedAtomicLong(CuratorFramework client, String counterPath, RetryPolicy retryPolicy); DistributedAtomicLong(CuratorFramework client, String counterPath, RetryPolicy retryPolicy, PromotedToLock promotedToLock); @Override AtomicValue<Long> get(); @Override void forceSet(Long newValue); @Override AtomicValue<Long> compareAndSet(Long expectedValue, Long newValue); @Override AtomicValue<Long> trySet(Long newValue); @Override boolean initialize(Long initialize); @Override AtomicValue<Long> increment(); @Override AtomicValue<Long> decrement(); @Override AtomicValue<Long> add(Long delta); @Override AtomicValue<Long> subtract(Long delta); }### Answer:
@Test public void testCorruptedValue() throws Exception { final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { client.create().forPath("/counter", "foo".getBytes()); DistributedAtomicLong dal = new DistributedAtomicLong(client, "/counter", new RetryOneTime(1)); try { dal.get().postValue(); } catch ( BufferUnderflowException e ) { Assert.fail("", e); } catch ( BufferOverflowException e ) { Assert.fail("", e); } catch ( RuntimeException e ) { } } finally { client.close(); } } |
### Question:
DistributedAtomicLong implements DistributedAtomicNumber<Long> { @Override public AtomicValue<Long> compareAndSet(Long expectedValue, Long newValue) throws Exception { return new AtomicLong(value.compareAndSet(valueToBytes(expectedValue), valueToBytes(newValue))); } DistributedAtomicLong(CuratorFramework client, String counterPath, RetryPolicy retryPolicy); DistributedAtomicLong(CuratorFramework client, String counterPath, RetryPolicy retryPolicy, PromotedToLock promotedToLock); @Override AtomicValue<Long> get(); @Override void forceSet(Long newValue); @Override AtomicValue<Long> compareAndSet(Long expectedValue, Long newValue); @Override AtomicValue<Long> trySet(Long newValue); @Override boolean initialize(Long initialize); @Override AtomicValue<Long> increment(); @Override AtomicValue<Long> decrement(); @Override AtomicValue<Long> add(Long delta); @Override AtomicValue<Long> subtract(Long delta); }### Answer:
@Test public void testCompareAndSet() throws Exception { final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { final AtomicBoolean doIncrement = new AtomicBoolean(false); DistributedAtomicLong dal = new DistributedAtomicLong(client, "/counter", new RetryOneTime(1)) { @Override public byte[] valueToBytes(Long newValue) { if ( doIncrement.get() ) { DistributedAtomicLong inc = new DistributedAtomicLong(client, "/counter", new RetryOneTime(1)); try { inc.increment(); } catch ( Exception e ) { throw new Error(e); } } return super.valueToBytes(newValue); } }; dal.forceSet(1L); Assert.assertTrue(dal.compareAndSet(1L, 5L).succeeded()); Assert.assertFalse(dal.compareAndSet(1L, 5L).succeeded()); doIncrement.set(true); Assert.assertFalse(dal.compareAndSet(5L, 10L).succeeded()); } finally { client.close(); } } |
### Question:
DistributedAtomicLong implements DistributedAtomicNumber<Long> { @Override public void forceSet(Long newValue) throws Exception { value.forceSet(valueToBytes(newValue)); } DistributedAtomicLong(CuratorFramework client, String counterPath, RetryPolicy retryPolicy); DistributedAtomicLong(CuratorFramework client, String counterPath, RetryPolicy retryPolicy, PromotedToLock promotedToLock); @Override AtomicValue<Long> get(); @Override void forceSet(Long newValue); @Override AtomicValue<Long> compareAndSet(Long expectedValue, Long newValue); @Override AtomicValue<Long> trySet(Long newValue); @Override boolean initialize(Long initialize); @Override AtomicValue<Long> increment(); @Override AtomicValue<Long> decrement(); @Override AtomicValue<Long> add(Long delta); @Override AtomicValue<Long> subtract(Long delta); }### Answer:
@Test public void testForceSet() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { final DistributedAtomicLong dal = new DistributedAtomicLong(client, "/counter", new RetryOneTime(1)); ExecutorService executorService = Executors.newFixedThreadPool(2); executorService.submit ( new Callable<Object>() { @Override public Object call() throws Exception { for ( int i = 0; i < 1000; ++i ) { dal.increment(); Thread.sleep(10); } return null; } } ); executorService.submit ( new Callable<Object>() { @Override public Object call() throws Exception { for ( int i = 0; i < 1000; ++i ) { dal.forceSet(0L); Thread.sleep(10); } return null; } } ); Assert.assertTrue(dal.get().preValue() < 10); } finally { client.close(); } } |
### Question:
LeaderSelector implements Closeable { public synchronized void interruptLeadership() { Future<?> task = ourTask.get(); if ( task != null ) { task.cancel(true); } } LeaderSelector(CuratorFramework client, String leaderPath, LeaderSelectorListener listener); @SuppressWarnings("UnusedParameters") @Deprecated LeaderSelector(CuratorFramework client, String leaderPath, ThreadFactory threadFactory, Executor executor, LeaderSelectorListener listener); LeaderSelector(CuratorFramework client, String leaderPath, ExecutorService executorService, LeaderSelectorListener listener); LeaderSelector(CuratorFramework client, String leaderPath, CloseableExecutorService executorService, LeaderSelectorListener listener); void autoRequeue(); void setId(String id); String getId(); void start(); boolean requeue(); synchronized void close(); Collection<Participant> getParticipants(); Participant getLeader(); boolean hasLeadership(); synchronized void interruptLeadership(); }### Answer:
@Test public void testInterruptLeadership() throws Exception { LeaderSelector selector = null; Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); final CountDownLatch isLeaderLatch = new CountDownLatch(1); final CountDownLatch losingLeaderLatch = new CountDownLatch(1); LeaderSelectorListener listener = new LeaderSelectorListener() { @Override public void takeLeadership(CuratorFramework client) throws Exception { isLeaderLatch.countDown(); try { Thread.currentThread().join(); } finally { losingLeaderLatch.countDown(); } } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; selector = new LeaderSelector(client, "/leader", listener); selector.start(); Assert.assertTrue(timing.awaitLatch(isLeaderLatch)); selector.interruptLeadership(); Assert.assertTrue(timing.awaitLatch(losingLeaderLatch)); } finally { CloseableUtils.closeQuietly(selector); CloseableUtils.closeQuietly(client); } } |
### Question:
LeaderSelector implements Closeable { public void autoRequeue() { autoRequeue.set(true); } LeaderSelector(CuratorFramework client, String leaderPath, LeaderSelectorListener listener); @SuppressWarnings("UnusedParameters") @Deprecated LeaderSelector(CuratorFramework client, String leaderPath, ThreadFactory threadFactory, Executor executor, LeaderSelectorListener listener); LeaderSelector(CuratorFramework client, String leaderPath, ExecutorService executorService, LeaderSelectorListener listener); LeaderSelector(CuratorFramework client, String leaderPath, CloseableExecutorService executorService, LeaderSelectorListener listener); void autoRequeue(); void setId(String id); String getId(); void start(); boolean requeue(); synchronized void close(); Collection<Participant> getParticipants(); Participant getLeader(); boolean hasLeadership(); synchronized void interruptLeadership(); }### Answer:
@Test public void testAutoRequeue() throws Exception { Timing timing = new Timing(); LeaderSelector selector = null; CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).sessionTimeoutMs(timing.session()).build(); try { client.start(); final Semaphore semaphore = new Semaphore(0); LeaderSelectorListener listener = new LeaderSelectorListener() { @Override public void takeLeadership(CuratorFramework client) throws Exception { Thread.sleep(10); semaphore.release(); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; selector = new LeaderSelector(client, "/leader", listener); selector.autoRequeue(); selector.start(); Assert.assertTrue(timing.acquireSemaphore(semaphore, 2)); } finally { CloseableUtils.closeQuietly(selector); CloseableUtils.closeQuietly(client); } } |
### Question:
RetryLoop { RetryLoop(RetryPolicy retryPolicy, AtomicReference<TracerDriver> tracer) { this.retryPolicy = retryPolicy; this.tracer = tracer; } RetryLoop(RetryPolicy retryPolicy, AtomicReference<TracerDriver> tracer); static RetrySleeper getDefaultRetrySleeper(); static T callWithRetry(CuratorZookeeperClient client, Callable<T> proc); boolean shouldContinue(); void markComplete(); static boolean shouldRetry(int rc); static boolean isRetryException(Throwable exception); void takeException(Exception exception); }### Answer:
@Test public void testRetryLoop() throws Exception { CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(), 10000, 10000, null, new RetryOneTime(1)); client.start(); try { int loopCount = 0; RetryLoop retryLoop = client.newRetryLoop(); while ( retryLoop.shouldContinue() ) { if ( ++loopCount > 2 ) { Assert.fail(); break; } try { client.getZooKeeper().create("/test", new byte[]{1,2,3}, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); retryLoop.markComplete(); } catch ( Exception e ) { retryLoop.takeException(e); } } Assert.assertTrue(loopCount > 0); } finally { client.close(); } } |
### Question:
CloseableExecutorService implements Closeable { @Override public void close() { isOpen.set(false); Iterator<Future<?>> iterator = futures.iterator(); while ( iterator.hasNext() ) { Future<?> future = iterator.next(); iterator.remove(); if ( !future.isDone() && !future.isCancelled() && !future.cancel(true) ) { log.warn("Could not cancel " + future); } } if (shutdownOnClose) { executorService.shutdownNow(); } } CloseableExecutorService(ExecutorService executorService); CloseableExecutorService(ExecutorService executorService, boolean shutdownOnClose); boolean isShutdown(); @Override void close(); Future<V> submit(Callable<V> task); Future<?> submit(Runnable task); }### Answer:
@Test public void testBasicRunnable() throws InterruptedException { try { CloseableExecutorService service = new CloseableExecutorService(executorService); CountDownLatch startLatch = new CountDownLatch(QTY); CountDownLatch latch = new CountDownLatch(QTY); for ( int i = 0; i < QTY; ++i ) { submitRunnable(service, startLatch, latch); } Assert.assertTrue(startLatch.await(3, TimeUnit.SECONDS)); service.close(); Assert.assertTrue(latch.await(3, TimeUnit.SECONDS)); } catch ( AssertionError e ) { throw e; } catch ( Throwable e ) { e.printStackTrace(); } } |
### Question:
ZKPaths { public static List<String> split(String path) { PathUtils.validatePath(path); return PATH_SPLITTER.splitToList(path); } private ZKPaths(); static CreateMode getContainerCreateMode(); static boolean hasContainerSupport(); static String fixForNamespace(String namespace, String path); static String fixForNamespace(String namespace, String path, boolean isSequential); static String getNodeFromPath(String path); static PathAndNode getPathAndNode(String path); static List<String> split(String path); static void mkdirs(ZooKeeper zookeeper, String path); static void mkdirs(ZooKeeper zookeeper, String path, boolean makeLastNode); static void mkdirs(ZooKeeper zookeeper, String path, boolean makeLastNode, InternalACLProvider aclProvider); static void mkdirs(ZooKeeper zookeeper, String path, boolean makeLastNode, InternalACLProvider aclProvider, boolean asContainers); static void deleteChildren(ZooKeeper zookeeper, String path, boolean deleteSelf); static List<String> getSortedChildren(ZooKeeper zookeeper, String path); static String makePath(String parent, String child); static String makePath(String parent, String firstChild, String... restChildren); static final String PATH_SEPARATOR; }### Answer:
@Test public void testSplit() { Assert.assertEquals(ZKPaths.split("/"), Collections.emptyList()); Assert.assertEquals(ZKPaths.split("/test"), Collections.singletonList("test")); Assert.assertEquals(ZKPaths.split("/test/one"), Arrays.asList("test", "one")); Assert.assertEquals(ZKPaths.split("/test/one/two"), Arrays.asList("test", "one", "two")); } |
### Question:
NamespaceFacade extends CuratorFrameworkImpl { @Override public String getNamespace() { return namespace.getNamespace(); } NamespaceFacade(CuratorFrameworkImpl client, String namespace); @Override CuratorFramework nonNamespaceView(); @Override CuratorFramework usingNamespace(String newNamespace); @Override String getNamespace(); @Override void start(); @Override void close(); @Override Listenable<ConnectionStateListener> getConnectionStateListenable(); @Override Listenable<CuratorListener> getCuratorListenable(); @Override Listenable<UnhandledErrorListener> getUnhandledErrorListenable(); @Override void sync(String path, Object context); @Override CuratorZookeeperClient getZookeeperClient(); @Override EnsurePath newNamespaceAwareEnsurePath(String path); }### Answer:
@Test public void testGetNamespace() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); CuratorFramework client2 = CuratorFrameworkFactory.builder().namespace("snafu").retryPolicy(new RetryOneTime(1)).connectString("").build(); try { client.start(); CuratorFramework fooClient = client.usingNamespace("foo"); CuratorFramework barClient = client.usingNamespace("bar"); Assert.assertEquals(client.getNamespace(), ""); Assert.assertEquals(client2.getNamespace(), "snafu"); Assert.assertEquals(fooClient.getNamespace(), "foo"); Assert.assertEquals(barClient.getNamespace(), "bar"); } finally { CloseableUtils.closeQuietly(client2); CloseableUtils.closeQuietly(client); } } |
### Question:
NamespaceFacade extends CuratorFrameworkImpl { @Override String unfixForNamespace(String path) { return namespace.unfixForNamespace(path); } NamespaceFacade(CuratorFrameworkImpl client, String namespace); @Override CuratorFramework nonNamespaceView(); @Override CuratorFramework usingNamespace(String newNamespace); @Override String getNamespace(); @Override void start(); @Override void close(); @Override Listenable<ConnectionStateListener> getConnectionStateListenable(); @Override Listenable<CuratorListener> getCuratorListenable(); @Override Listenable<UnhandledErrorListener> getUnhandledErrorListenable(); @Override void sync(String path, Object context); @Override CuratorZookeeperClient getZookeeperClient(); @Override EnsurePath newNamespaceAwareEnsurePath(String path); }### Answer:
@Test public void testUnfixForEmptyNamespace() { CuratorFramework client = CuratorFrameworkFactory.builder().namespace("").retryPolicy(new RetryOneTime(1)).connectString("").build(); CuratorFrameworkImpl clientImpl = (CuratorFrameworkImpl) client; Assert.assertEquals(clientImpl.unfixForNamespace("/foo/bar"), "/foo/bar"); CloseableUtils.closeQuietly(client); } |
### Question:
UriSpec implements Iterable<UriSpec.Part> { public String build() { return build(null, Maps.<String, Object>newHashMap()); } UriSpec(); UriSpec(String rawSpec); String build(); String build(ServiceInstance<?> serviceInstance); String build(Map<String, Object> variables); String build(ServiceInstance<?> serviceInstance, Map<String, Object> variables); @Override Iterator<Part> iterator(); List<Part> getParts(); void add(Part part); void remove(Part part); @SuppressWarnings("RedundantIfStatement") @Override boolean equals(Object o); @Override int hashCode(); static final String FIELD_SCHEME; static final String FIELD_NAME; static final String FIELD_ID; static final String FIELD_ADDRESS; static final String FIELD_PORT; static final String FIELD_SSL_PORT; static final String FIELD_REGISTRATION_TIME_UTC; static final String FIELD_SERVICE_TYPE; static final String FIELD_OPEN_BRACE; static final String FIELD_CLOSE_BRACE; }### Answer:
@Test public void testScheme() { UriSpec spec = new UriSpec("{scheme}: ServiceInstanceBuilder<Void> builder = new ServiceInstanceBuilder<Void>(); builder.id("x"); builder.name("foo"); builder.port(5); ServiceInstance<Void> instance = builder.build(); Assert.assertEquals(spec.build(instance), "http: builder.sslPort(5); instance = builder.build(); Assert.assertEquals(spec.build(instance), "https: }
@Test public void testFromInstance() { ServiceInstanceBuilder<Void> builder = new ServiceInstanceBuilder<Void>(); builder.address("1.2.3.4"); builder.name("foo"); builder.id("bar"); builder.port(5); builder.sslPort(6); builder.registrationTimeUTC(789); builder.serviceType(ServiceType.PERMANENT); ServiceInstance<Void> instance = builder.build(); UriSpec spec = new UriSpec("{scheme}: Map<String, Object> m = Maps.newHashMap(); m.put("scheme", "test"); Assert.assertEquals(spec.build(instance, m), "test: } |
### Question:
UriSpec implements Iterable<UriSpec.Part> { @Override public Iterator<Part> iterator() { return Iterators.unmodifiableIterator(parts.iterator()); } UriSpec(); UriSpec(String rawSpec); String build(); String build(ServiceInstance<?> serviceInstance); String build(Map<String, Object> variables); String build(ServiceInstance<?> serviceInstance, Map<String, Object> variables); @Override Iterator<Part> iterator(); List<Part> getParts(); void add(Part part); void remove(Part part); @SuppressWarnings("RedundantIfStatement") @Override boolean equals(Object o); @Override int hashCode(); static final String FIELD_SCHEME; static final String FIELD_NAME; static final String FIELD_ID; static final String FIELD_ADDRESS; static final String FIELD_PORT; static final String FIELD_SSL_PORT; static final String FIELD_REGISTRATION_TIME_UTC; static final String FIELD_SERVICE_TYPE; static final String FIELD_OPEN_BRACE; static final String FIELD_CLOSE_BRACE; }### Answer:
@Test public void testBasic() { UriSpec spec = new UriSpec("{one}{two}three-four-five{six}seven{eight}"); Iterator<UriSpec.Part> iterator = spec.iterator(); checkPart(iterator.next(), "one", true); checkPart(iterator.next(), "two", true); checkPart(iterator.next(), "three-four-five", false); checkPart(iterator.next(), "six", true); checkPart(iterator.next(), "seven", false); checkPart(iterator.next(), "eight", true); } |
### Question:
ChirpTimelineEntity extends PersistentEntity<ChirpTimelineCommand, ChirpTimelineEvent, NotUsed> { private Persist addChirp(AddChirp cmd, CommandContext<Done> ctx) { return ctx.thenPersist(new ChirpAdded(cmd.chirp), evt -> { ctx.reply(Done.getInstance()); topic.publish(cmd.chirp); }); } @Inject ChirpTimelineEntity(ChirpTopic topic); @Override Behavior initialBehavior(Optional<NotUsed> snapshotState); }### Answer:
@Test public void testAddChirp() { ChirpTopicStub topic = new ChirpTopicStub(); PersistentEntityTestDriver<ChirpTimelineCommand, ChirpTimelineEvent, NotUsed> driver = new PersistentEntityTestDriver<>(system, new ChirpTimelineEntity(topic), "user-1"); Chirp chirp = new Chirp("user-1", "Hello, world"); PersistentEntityTestDriver.Outcome<ChirpTimelineEvent, NotUsed> outcome = driver.run(new AddChirp(chirp)); assertEquals(Done.getInstance(), outcome.getReplies().get(0)); assertEquals(chirp, ((ChirpTimelineEvent.ChirpAdded) outcome.events().get(0)).chirp); assertEquals(chirp, topic.chirps.get(0)); assertEquals(Collections.emptyList(), driver.getAllIssues()); } |
### Question:
PlanIdentifier { public static boolean isPlan(URI planIdentifier) { return planIdentifier.getSchemeSpecificPart().endsWith(PLAN_FILE_SUFFIX); } private PlanIdentifier(); static URI parse(String planIdentifier); static URI parse(URI planIdentifier); static boolean isPlan(URI planIdentifier); static boolean isPlan(Path path); }### Answer:
@Test public void testIsPlanURI() { assertEquals(true,PlanIdentifier.isPlan(URI.create("file: assertEquals(false,PlanIdentifier.isPlan(URI.create("file: }
@Test public void testIsPlanPath() { assertEquals(true,PlanIdentifier.isPlan(Paths.get(URI.create("file: assertEquals(false,PlanIdentifier.isPlan(Paths.get(URI.create("file: } |
### Question:
PerfPlan implements Serializable { public PerfPlan(SaladDocument saladDocument, URI uri, String saladSource) { this.saladDocument = saladDocument; this.uri = uri; this.saladSource = saladSource; } PerfPlan(SaladDocument saladDocument, URI uri, String saladSource); SaladDocument getSaladPlan(); String getSource(); URI getUri(); void sendTestSourceRead(EventBus bus); static final Pattern RERUN_PATH_SPECIFICATION; }### Answer:
@Test public void testPerfPlan() { List<Tag> t = new ArrayList<Tag>(); List<SimulationDefinition> s = new ArrayList<SimulationDefinition>(); PerfPlan pp = new PerfPlan(new SaladDocument(new Plan(t, null, null, null, "test", null, s), new ArrayList<Comment>()), URI.create("test"),"test"); assertEquals("test",pp.getUri().toString()); } |
### Question:
PerfPlan implements Serializable { public SaladDocument getSaladPlan() { return saladDocument; } PerfPlan(SaladDocument saladDocument, URI uri, String saladSource); SaladDocument getSaladPlan(); String getSource(); URI getUri(); void sendTestSourceRead(EventBus bus); static final Pattern RERUN_PATH_SPECIFICATION; }### Answer:
@Test public void testGetSaladPlan() { List<Tag> t = new ArrayList<Tag>(); List<SimulationDefinition> s = new ArrayList<SimulationDefinition>(); PerfPlan pp = new PerfPlan(new SaladDocument(new Plan(t, null, null, null, "test", null,s), new ArrayList<Comment>()), URI.create("test"),"test"); assertEquals("test",pp.getSaladPlan().getPlan().getName()); } |
### Question:
PerfPlan implements Serializable { public URI getUri() { return uri; } PerfPlan(SaladDocument saladDocument, URI uri, String saladSource); SaladDocument getSaladPlan(); String getSource(); URI getUri(); void sendTestSourceRead(EventBus bus); static final Pattern RERUN_PATH_SPECIFICATION; }### Answer:
@Test public void testGetUri() { List<Tag> t = new ArrayList<Tag>(); List<SimulationDefinition> s = new ArrayList<SimulationDefinition>(); PerfPlan pp = new PerfPlan(new SaladDocument(new Plan(t, null, null, null, "test", null, s), new ArrayList<Comment>()), URI.create("test"),"test"); assertEquals("test",pp.getUri().toString()); } |
### Question:
PathPlanSupplier implements PlanSupplier { @Override public List<PerfPlan> get() { List<PerfPlan> planPaths = loadPlans(paths); if (planPaths.isEmpty()) { if (paths.isEmpty()) { log.warn(() -> "Got no path to plans directory or plans file"); } else { log.warn(() -> "No planss found at " + paths.stream().map(URI::toString).collect(joining(", "))); } } return planPaths; } PathPlanSupplier(Supplier<ClassLoader> classLoader, List<String> planPaths, PlanParser parser); @Override List<PerfPlan> get(); }### Answer:
@Test public void testGet() { Supplier<ClassLoader> classLoader = FeatureBuilder.class::getClassLoader; PlanParser parser = new PlanParser(UUID::randomUUID); List<String> list = new ArrayList<String>(); list.add("./src/test/java/resources"); List<PerfPlan> plans = new PathPlanSupplier(classLoader,list , parser).get(); assertTrue(plans.get(0).getUri().toString().contains("test/java/resources/test.plan")); } |
### Question:
PerfPlanParser implements cucumber.perf.salad.PlanParser { @Override public PerfPlan parse(URI path, String source, Supplier<UUID> idGenerator) { return parseSalad(path, source); } @Override PerfPlan parse(URI path, String source, Supplier<UUID> idGenerator); @Override String version(); }### Answer:
@Test public void testParse() { URI uri = URI.create("src/test/java/resources/test.plan"); Resource r = new UriResource(Paths.get(uri.getPath())); String source = null; try { source = Encoding.readFile(r); } catch (RuntimeException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } PerfPlan p = new PerfPlanParser().parse(URI.create("src/test/java/resources/test.plan"), source, UUID::randomUUID); assertEquals("simulation 1", p.getSaladPlan().getPlan().getChildren().get(0).getName()); } |
### Question:
FeatureBuilder { public static List<Feature> FindFeatures(String prefix, List<Feature> features) { List<Feature> result = new ArrayList<Feature>(); for (Feature f : features) { if (f.getName().toLowerCase().startsWith(prefix)) { result.add(f); } } return result; } static RuntimeOptions createRuntimeOptions(Class<?> clazz); static RuntimeOptions createRuntimeOptions(List<String> args); static List<Feature> getFeatures(RuntimeOptions runtimeOptions); static List<Feature> FindFeatures(String prefix, List<Feature> features); static List<ScenarioDefinition> FindScenarios(String prefix, String feature,
List<Feature> features); static List<List<ScenarioDefinition>> GetScenarios(List<Feature> features); }### Answer:
@Test public void testFindFeatures() { List<Feature> features = FeatureBuilder.getFeatures(FeatureBuilder.createRuntimeOptions(options1.class)); List<Feature> f= FeatureBuilder.FindFeatures("t",features); assertEquals(1,f.size()); } |
### Question:
FeatureBuilder { public static List<ScenarioDefinition> FindScenarios(String prefix, String feature, List<Feature> features) { List<ScenarioDefinition> result = new ArrayList<ScenarioDefinition>(); for (Feature f : features) { if (f.getName().equalsIgnoreCase(feature)) { for (Iterator<Node> iterator = f.children().iterator(); iterator.hasNext();) { Node n = iterator.next(); if (n instanceof ScenarioDefinition) { if (((ScenarioDefinition)n).getName().startsWith(prefix)) { result.add(((ScenarioDefinition)n)); } } } } } return result; } static RuntimeOptions createRuntimeOptions(Class<?> clazz); static RuntimeOptions createRuntimeOptions(List<String> args); static List<Feature> getFeatures(RuntimeOptions runtimeOptions); static List<Feature> FindFeatures(String prefix, List<Feature> features); static List<ScenarioDefinition> FindScenarios(String prefix, String feature,
List<Feature> features); static List<List<ScenarioDefinition>> GetScenarios(List<Feature> features); }### Answer:
@Test public void testFindScenarios() { List<Feature> features = FeatureBuilder.getFeatures(FeatureBuilder.createRuntimeOptions(options1.class)); List<ScenarioDefinition> f= FeatureBuilder.FindScenarios("scenario 1", "test", features); assertEquals(1,f.size()); } |
### Question:
FeatureBuilder { public static List<List<ScenarioDefinition>> GetScenarios(List<Feature> features) { List<List<ScenarioDefinition>> result = new ArrayList<List<ScenarioDefinition>>(); for (Feature f : features) { List<ScenarioDefinition> sc = new ArrayList<ScenarioDefinition>(); for (Iterator<Node> iterator = f.children().iterator(); iterator.hasNext();) { Node n = iterator.next(); if (n instanceof ScenarioDefinition) { sc.add(((ScenarioDefinition)n)); } } result.add(sc); } return result; } static RuntimeOptions createRuntimeOptions(Class<?> clazz); static RuntimeOptions createRuntimeOptions(List<String> args); static List<Feature> getFeatures(RuntimeOptions runtimeOptions); static List<Feature> FindFeatures(String prefix, List<Feature> features); static List<ScenarioDefinition> FindScenarios(String prefix, String feature,
List<Feature> features); static List<List<ScenarioDefinition>> GetScenarios(List<Feature> features); }### Answer:
@Test public void testGetScenarios() { List<Feature> features = FeatureBuilder.getFeatures(FeatureBuilder.createRuntimeOptions(options1.class)); List<List<ScenarioDefinition>> s = FeatureBuilder.GetScenarios(features); assertEquals(3,s.size()); } |
### Question:
PerfGroup { public int getCount() { return count; } PerfGroup(String keyword, String text,int threads, int count,DataTable slices); PerfGroup(Group group); int getMaxThreads(); void setThreads(int threads); int getRunning(); String getKeyword(); String getText(); void incrementRunning(); void decrementRunning(); int getRan(); void incrementRan(); int getThreads(); int getCount(); DataTable getSlices(); Slice getSlice(); List<Feature> getFeatures(); void setFeatures(List<Feature> features); }### Answer:
@Test public void testPerfGroupStringStringIntIntDataTable() { List<TableCell> tcl = Arrays.asList(new TableCell[] {new TableCell(null, "value out")}); List<TableCell> tcl2 = Arrays.asList(new TableCell[] {new TableCell(null, "test")}); DataTable d = new DataTable(Arrays.asList(new TableRow[] {new TableRow(null, tcl),new TableRow(null, tcl2)})); PerfGroup pg = new PerfGroup("When","Test",1, 3, d); assertEquals(3,pg.getCount()); }
@Test public void testPerfGroupGroup() { List<Node> args = new ArrayList<Node>(); args.add(new Count(null,"Count","3")); args.add(new Runners(null,"Runners","1")); PerfGroup pg = new PerfGroup(new Group(null, "Group", "test.feature", args)); assertEquals(3,pg.getCount()); } |
### Question:
PerfGroup { public int getMaxThreads() { return maxThreads; } PerfGroup(String keyword, String text,int threads, int count,DataTable slices); PerfGroup(Group group); int getMaxThreads(); void setThreads(int threads); int getRunning(); String getKeyword(); String getText(); void incrementRunning(); void decrementRunning(); int getRan(); void incrementRan(); int getThreads(); int getCount(); DataTable getSlices(); Slice getSlice(); List<Feature> getFeatures(); void setFeatures(List<Feature> features); }### Answer:
@Test public void testGetMaxThreads() { PerfRuntimeOptionsFactory optf = new PerfRuntimeOptionsFactory(options1.class); PerfRuntimeOptions opt = optf.create(); PlanParser parser = new PlanParser(UUID::randomUUID); Supplier<ClassLoader> classLoader = this.getClass()::getClassLoader; List<PerfPlan> res = new PathPlanSupplier(classLoader, opt.getPlanPaths(), parser).get(); List <PerfGroup> pg = buildGroups(res.get(0).getSaladPlan().getPlan().getChildren().get(0)); assertEquals(2,pg.get(0).getMaxThreads()); } |
### Question:
PerfGroup { public void setThreads(int threads) { this.threads = threads; } PerfGroup(String keyword, String text,int threads, int count,DataTable slices); PerfGroup(Group group); int getMaxThreads(); void setThreads(int threads); int getRunning(); String getKeyword(); String getText(); void incrementRunning(); void decrementRunning(); int getRan(); void incrementRan(); int getThreads(); int getCount(); DataTable getSlices(); Slice getSlice(); List<Feature> getFeatures(); void setFeatures(List<Feature> features); }### Answer:
@Test public void testSetThreads() { List<Node> args = new ArrayList<Node>(); args.add(new Count(null,"Count","3")); args.add(new Runners(null,"Runners","1")); PerfGroup pg = new PerfGroup(new Group(null, "Group", "test.feature", args)); pg.setThreads(11); assertEquals(11,pg.getThreads()); } |
### Question:
PerfGroup { public int getRunning() { return running; } PerfGroup(String keyword, String text,int threads, int count,DataTable slices); PerfGroup(Group group); int getMaxThreads(); void setThreads(int threads); int getRunning(); String getKeyword(); String getText(); void incrementRunning(); void decrementRunning(); int getRan(); void incrementRan(); int getThreads(); int getCount(); DataTable getSlices(); Slice getSlice(); List<Feature> getFeatures(); void setFeatures(List<Feature> features); }### Answer:
@Test public void testGetRunning() { List<Node> args = new ArrayList<Node>(); args.add(new Count(null,"Count","3")); args.add(new Runners(null,"Runners","1")); PerfGroup pg = new PerfGroup(new Group(null, "Group", "test.feature",args)); assertEquals(0,pg.getRunning()); } |
### Question:
PerfGroup { public String getKeyword() { return keyword; } PerfGroup(String keyword, String text,int threads, int count,DataTable slices); PerfGroup(Group group); int getMaxThreads(); void setThreads(int threads); int getRunning(); String getKeyword(); String getText(); void incrementRunning(); void decrementRunning(); int getRan(); void incrementRan(); int getThreads(); int getCount(); DataTable getSlices(); Slice getSlice(); List<Feature> getFeatures(); void setFeatures(List<Feature> features); }### Answer:
@Test public void testGetKeyword() { List<Node> args = new ArrayList<Node>(); args.add(new Count(null,"Count","3")); args.add(new Runners(null,"Runners","1")); PerfGroup pg = new PerfGroup(new Group(null, "Group", "test.feature", args)); assertEquals("Group",pg.getKeyword()); } |
### Question:
PerfGroup { public String getText() { return text; } PerfGroup(String keyword, String text,int threads, int count,DataTable slices); PerfGroup(Group group); int getMaxThreads(); void setThreads(int threads); int getRunning(); String getKeyword(); String getText(); void incrementRunning(); void decrementRunning(); int getRan(); void incrementRan(); int getThreads(); int getCount(); DataTable getSlices(); Slice getSlice(); List<Feature> getFeatures(); void setFeatures(List<Feature> features); }### Answer:
@Test public void testGetText() { List<Node> args = new ArrayList<Node>(); args.add(new Count(null,"Count","3")); args.add(new Runners(null,"Runners","1")); PerfGroup pg = new PerfGroup(new Group(null, "Group", "test.feature", args)); assertEquals("test.feature",pg.getText()); } |
### Question:
PerfGroup { public void incrementRunning() { this.running++; } PerfGroup(String keyword, String text,int threads, int count,DataTable slices); PerfGroup(Group group); int getMaxThreads(); void setThreads(int threads); int getRunning(); String getKeyword(); String getText(); void incrementRunning(); void decrementRunning(); int getRan(); void incrementRan(); int getThreads(); int getCount(); DataTable getSlices(); Slice getSlice(); List<Feature> getFeatures(); void setFeatures(List<Feature> features); }### Answer:
@Test public void testIncrementRunning() { List<Node> args = new ArrayList<Node>(); args.add(new Count(null,"Count","3")); args.add(new Runners(null,"Runners","1")); PerfGroup pg = new PerfGroup(new Group(null, "Group", "test.feature",args)); pg.incrementRunning(); assertEquals(1,pg.getRunning()); } |
### Question:
PerfGroup { public void decrementRunning() { this.running--; } PerfGroup(String keyword, String text,int threads, int count,DataTable slices); PerfGroup(Group group); int getMaxThreads(); void setThreads(int threads); int getRunning(); String getKeyword(); String getText(); void incrementRunning(); void decrementRunning(); int getRan(); void incrementRan(); int getThreads(); int getCount(); DataTable getSlices(); Slice getSlice(); List<Feature> getFeatures(); void setFeatures(List<Feature> features); }### Answer:
@Test public void testDecrementRunning() { List<Node> args = new ArrayList<Node>(); args.add(new Count(null,"Count","3")); args.add(new Runners(null,"Runners","1")); PerfGroup pg = new PerfGroup(new Group(null, "Group", "test.feature", args)); pg.decrementRunning(); assertEquals(-1,pg.getRunning()); } |
### Question:
PerfGroup { public int getRan() { return ran; } PerfGroup(String keyword, String text,int threads, int count,DataTable slices); PerfGroup(Group group); int getMaxThreads(); void setThreads(int threads); int getRunning(); String getKeyword(); String getText(); void incrementRunning(); void decrementRunning(); int getRan(); void incrementRan(); int getThreads(); int getCount(); DataTable getSlices(); Slice getSlice(); List<Feature> getFeatures(); void setFeatures(List<Feature> features); }### Answer:
@Test public void testGetRan() { List<Node> args = new ArrayList<Node>(); args.add(new Count(null,"Count","3")); args.add(new Runners(null,"Runners","1")); PerfGroup pg = new PerfGroup(new Group(null, "Group", "test.feature", args)); pg.incrementRan(); pg.incrementRan(); assertEquals(2,pg.getRan()); } |
### Question:
PercentileCreator implements StatisticCreator { public PercentileCreator( String[] options){ for (String opt : options) { try { postfix = opt; try { Integer.parseInt(opt); opt = opt+".0d"; } catch( Exception e) {} percentile = Double.parseDouble(opt); } catch( Exception e) { percentile = 90.0d; postfix= "90"; } } } PercentileCreator( String[] options); @SuppressWarnings("unchecked") @Override Object run(Object obj); @Override Stats run(HashMap<String, List<Long>> sortedResults); }### Answer:
@Test public void testPercentileCreator() { try { PercentileCreator stddev = new PercentileCreator(new String[] {"50"}); HashMap<String, List<Long>> results = new HashMap<String, List<Long>>(); List<Long> sorted = new ArrayList<Long>(); sorted.add((long) 1300); sorted.add((long) 2000); sorted.add((long) 2400); sorted.add((long) 2300); sorted.add((long) 3000); results.put("test",sorted); Stats s = stddev.run(results); assertEquals("Failed to get proper Prctl", 2400.0d, s.getStatistic("prctl_50", "test"), 0.001); } catch (CucumberException e) { fail("CucumberException"); } } |
### Question:
LoggerFormatter implements EventListener, EventWriter { public LoggerFormatter(AppendableBuilder builder) { this.builder = builder; } LoggerFormatter(AppendableBuilder builder); LoggerFormatter(AppendableBuilder builder, String[] options); @Override void setEventPublisher(EventPublisher publisher); @Override void setEventBus(EventBus eventBus); SimulationResult createSimulationResult(List<Map<String, Object>> mapList); List<GroupResult> createGroupResultList(List<Map<String, Object>> mapList); }### Answer:
@Test public void testLoggerFormatter() { try { new LoggerFormatter(new AppendableBuilder("file: assertFalse(deleteFile("C:/test/log.json")); } catch (CucumberException e) { fail("Issue"); } } |
### Question:
JUnitFormatter implements EventListener { public JUnitFormatter(AppendableBuilder builder) { this.builder = builder; } JUnitFormatter(AppendableBuilder builder); @Override void setEventPublisher(EventPublisher publisher); void process(Statistics stats); }### Answer:
@Test public void testJUnitFormatter() { new JUnitFormatter(new AppendableBuilder("C:/test/junit.xml")); assertTrue(true); } |
### Question:
JUnitFormatter implements EventListener { private void finishReport() { try { this.out = this.builder.build(); rootElement.setAttribute("name", JUnitFormatter.class.getName()); rootElement.setAttribute("failures", String.valueOf(rootElement.getElementsByTagName("failure").getLength())); rootElement.setAttribute("skipped", String.valueOf(rootElement.getElementsByTagName("skipped").getLength())); rootElement.setAttribute("time", sumTimes(rootElement.getElementsByTagName("testcase"))); if (rootElement.getElementsByTagName("testcase").getLength() == 0) { addDummyTestCase(); } TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.INDENT, "yes"); StreamResult result = new StreamResult(out); DOMSource source = new DOMSource(doc); trans.transform(source, result); closeQuietly(out); } catch (TransformerException e) { throw new CucumberException("Error while transforming.", e); } } JUnitFormatter(AppendableBuilder builder); @Override void setEventPublisher(EventPublisher publisher); void process(Statistics stats); }### Answer:
@Test public void testFinishReport() { JUnitFormatter junit = new JUnitFormatter(new AppendableBuilder("C:/test/junittest.xml")); PluginFactory pf = new PluginFactory(); PerfRuntimeOptions options = new PerfRuntimeOptions(); Plugins plugins = new Plugins(this.getClass().getClassLoader(), pf, options); plugins.addPlugin(junit); plugins.setEventBusOnPlugins(eventBus); eventBus.send(new StatisticsFinished(eventBus.getTime(),eventBus.getTimeMillis(),new Statistics())); assertTrue(deleteFile("C:/test/junittest.xml")); } |
### Question:
SummaryTextFormatter implements EventListener { public SummaryTextFormatter(AppendableBuilder builder){ this.builder= builder; } SummaryTextFormatter(AppendableBuilder builder); @Override void setEventPublisher(EventPublisher publisher); }### Answer:
@Test public void testSummaryTextFormatter() { try { new SummaryTextFormatter(new AppendableBuilder("file: } catch (CucumberException e) { fail("CucumberException"); } assertTrue(true); } |
### Question:
SummaryTextFormatter implements EventListener { private void process(Statistics stats) { reset(); createLines(stats); this.finishReport(); } SummaryTextFormatter(AppendableBuilder builder); @Override void setEventPublisher(EventPublisher publisher); }### Answer:
@Test public void testProcess() { SummaryTextFormatter stf = new SummaryTextFormatter(new AppendableBuilder("file: PluginFactory pf = new PluginFactory(); PerfRuntimeOptions options = new PerfRuntimeOptions(); Plugins plugins = new Plugins(this.getClass().getClassLoader(), pf, options); plugins.addPlugin(stf); plugins.setEventBusOnPlugins(eventBus); eventBus.send(new StatisticsFinished(eventBus.getTime(),eventBus.getTimeMillis(),new Statistics())); assertTrue(deleteFile("C:/test/summarytext.txt")); } |
### Question:
TaurusFormatter implements EventListener, EventWriter { public TaurusFormatter(AppendableBuilder builder) { this.builder = builder; } TaurusFormatter(AppendableBuilder builder); @Override void setEventPublisher(EventPublisher publisher); @Override void setEventBus(EventBus eventBus); }### Answer:
@Test public void testTaurusFormatter() { try { new TaurusFormatter(new AppendableBuilder("file: } catch (CucumberException e) { fail("CucumberException"); } assertTrue(true); } |
### Question:
TaurusFormatter implements EventListener, EventWriter { private void process(Statistics result) { reset(); addLines(result); this.finishReport(); } TaurusFormatter(AppendableBuilder builder); @Override void setEventPublisher(EventPublisher publisher); @Override void setEventBus(EventBus eventBus); }### Answer:
@Test public void testProcess() { TaurusFormatter stf = new TaurusFormatter(new AppendableBuilder("file: PluginFactory pf = new PluginFactory(); PerfRuntimeOptions options = new PerfRuntimeOptions(); Plugins plugins = new Plugins(this.getClass().getClassLoader(), pf, options); plugins.addPlugin(stf); plugins.setEventBusOnPlugins(eventBus); eventBus.send(new StatisticsFinished(eventBus.getTime(),eventBus.getTimeMillis(),new Statistics())); assertTrue(deleteFile("C:/test/taurusout.csv")); } |
### Question:
ChartPointsFormatter implements EventListener, EventWriter,StrictAware,PluginSpawner { public ChartPointsFormatter(AppendableBuilder builder, String[] options) { this.builder = builder; boolean foundCP = false; for (String opt : options) { if (!opt.isEmpty()&&!foundCP) { try { this.chartPoints = Integer.parseInt(opt); foundCP = true; } catch( Exception e) { pluginMinionTypes.add(opt); } } else pluginMinionTypes.add(opt); } } ChartPointsFormatter(AppendableBuilder builder, String[] options); ChartPointsFormatter(AppendableBuilder builder); @Override void setEventPublisher(EventPublisher publisher); @Override void setStrict(boolean strict); @Override void setEventBus(EventBus eventBus); }### Answer:
@Test public void testChartPointsFormatter() { try { new ChartPointsFormatter(new AppendableBuilder("file: } catch (CucumberException e) { fail("CucumberException"); } assertTrue(true); } |
### Question:
ChartPointsFormatter implements EventListener, EventWriter,StrictAware,PluginSpawner { private void process(SimulationResult result) { if (result != null) { eventBus.send(new ChartStarted(eventBus.getTime(),eventBus.getTimeMillis())); createMinions(); Chart chart = null; HashMap<String,List<GroupResult>> results = new HashMap<String,List<GroupResult>>(); if (result.getChildResults() != null && !result.getChildResults().isEmpty()) { for (GroupResult o : result.getChildResults()) { if (results.containsKey(o.getName())) { results.get(o.getName()).add(o); } else { results.put(o.getName(), new ArrayList<GroupResult>(Arrays.asList(o))); } } chart = createChart(new BaseResult(result.getName(),result.getResult(),result.getStart(),result.getStop()), result.getStart(),result.getStop(),results); } reset(); addLines(chart); this.finishReport(); eventBus.send(new ChartFinished(eventBus.getTime(),eventBus.getTimeMillis(),chart)); } } ChartPointsFormatter(AppendableBuilder builder, String[] options); ChartPointsFormatter(AppendableBuilder builder); @Override void setEventPublisher(EventPublisher publisher); @Override void setStrict(boolean strict); @Override void setEventBus(EventBus eventBus); }### Answer:
@Test public void testProcess() { try { ChartPointsFormatter cpf = new ChartPointsFormatter(new AppendableBuilder("file: PluginFactory pf = new PluginFactory(); PerfRuntimeOptions options = new PerfRuntimeOptions(); Plugins plugins = new Plugins(this.getClass().getClassLoader(), pf, options); plugins.addPlugin(cpf); plugins.setEventBusOnPlugins(eventBus); eventBus.send(new StatisticsFinished(eventBus.getTime(),eventBus.getTimeMillis(),new Statistics())); } catch (CucumberException e) { fail("CucumberException"); } assertFalse(deleteFile("C:/test/chartpoints.csv")); } |
### Question:
StdDeviationCreator implements StatisticCreator { public StdDeviationCreator(){ } StdDeviationCreator(); @SuppressWarnings("unchecked") @Override Object run(Object obj); @Override Stats run(HashMap<String, List<Long>> sortedResults); }### Answer:
@Test public void testStdDeviationCreator() { try { StdDeviationCreator stddev = new StdDeviationCreator(); HashMap<String, List<Long>> results = new HashMap<String, List<Long>>(); List<Long> sorted = new ArrayList<Long>(); sorted.add((long) 1300); sorted.add((long) 2000); sorted.add((long) 2400); sorted.add((long) 2300); sorted.add((long) 3000); results.put("test",sorted); Stats s = stddev.run(results); assertEquals("Failed to get proper Stddev", 554.977, s.getStatistic("stdev", "test"), 0.001); } catch (CucumberException e) { fail("CucumberException"); } } |
### Question:
CucumberPerf { public Duration convertRuntime(String time) { Duration d = Duration.between(LocalTime.MIN, LocalTime.parse(time)); return d; } CucumberPerf(Class<?> clazz); CucumberPerf(Class<?> clazz, PerfRuntimeOptions options); CucumberPerf(PerfRuntimeOptions options); CucumberPerf(String[] args); void runThreads(); void printResult(); Duration convertRuntime(String time); LocalDateTime getEnd(LocalDateTime start, String time); long getMaxRan(); long getTotalRanCount(); LocalDateTime getStart(); LocalDateTime getEnd(); String getRunTime(); int getMaxThreads(); Plugins getPlugins(); }### Answer:
@Test public void testConvertRuntime() { CucumberPerf cp = new CucumberPerf(options1.class); Duration rt = cp.convertRuntime("00:00:30"); assertEquals(rt.toString(),"PT30S"); } |
### Question:
CucumberPerf { public long getMaxRan() { return maxRan; } CucumberPerf(Class<?> clazz); CucumberPerf(Class<?> clazz, PerfRuntimeOptions options); CucumberPerf(PerfRuntimeOptions options); CucumberPerf(String[] args); void runThreads(); void printResult(); Duration convertRuntime(String time); LocalDateTime getEnd(LocalDateTime start, String time); long getMaxRan(); long getTotalRanCount(); LocalDateTime getStart(); LocalDateTime getEnd(); String getRunTime(); int getMaxThreads(); Plugins getPlugins(); }### Answer:
@Test public void testGetMaxRan() { CucumberPerf cp = new CucumberPerf(options1.class); try { cp.runThreads(); } catch (Throwable e) { fail("Error:"+e.getMessage()); } assertEquals(cp.getMaxRan(),6); } |
### Question:
CucumberPerf { public long getTotalRanCount() { return totalRanCount; } CucumberPerf(Class<?> clazz); CucumberPerf(Class<?> clazz, PerfRuntimeOptions options); CucumberPerf(PerfRuntimeOptions options); CucumberPerf(String[] args); void runThreads(); void printResult(); Duration convertRuntime(String time); LocalDateTime getEnd(LocalDateTime start, String time); long getMaxRan(); long getTotalRanCount(); LocalDateTime getStart(); LocalDateTime getEnd(); String getRunTime(); int getMaxThreads(); Plugins getPlugins(); }### Answer:
@Test public void testGetTotalRanCount() { CucumberPerf cp = new CucumberPerf(options0.class); try { cp.runThreads(); } catch (Throwable e) { fail("Error:"+e.getMessage()); } assertEquals(cp.getTotalRanCount(),6); } |
### Question:
CucumberPerf { public LocalDateTime getStart() { return start; } CucumberPerf(Class<?> clazz); CucumberPerf(Class<?> clazz, PerfRuntimeOptions options); CucumberPerf(PerfRuntimeOptions options); CucumberPerf(String[] args); void runThreads(); void printResult(); Duration convertRuntime(String time); LocalDateTime getEnd(LocalDateTime start, String time); long getMaxRan(); long getTotalRanCount(); LocalDateTime getStart(); LocalDateTime getEnd(); String getRunTime(); int getMaxThreads(); Plugins getPlugins(); }### Answer:
@Test public void testGetStart() { } |
### Question:
CucumberPerf { public LocalDateTime getEnd(LocalDateTime start, String time) { LocalDateTime endt = LocalDateTime.from(start).plus(convertRuntime(time)); return endt; } CucumberPerf(Class<?> clazz); CucumberPerf(Class<?> clazz, PerfRuntimeOptions options); CucumberPerf(PerfRuntimeOptions options); CucumberPerf(String[] args); void runThreads(); void printResult(); Duration convertRuntime(String time); LocalDateTime getEnd(LocalDateTime start, String time); long getMaxRan(); long getTotalRanCount(); LocalDateTime getStart(); LocalDateTime getEnd(); String getRunTime(); int getMaxThreads(); Plugins getPlugins(); }### Answer:
@Test public void testGetEnd() { } |
### Question:
CucumberPerf { public String getRunTime() { Duration d = Duration.between(start, end); return d.toString(); } CucumberPerf(Class<?> clazz); CucumberPerf(Class<?> clazz, PerfRuntimeOptions options); CucumberPerf(PerfRuntimeOptions options); CucumberPerf(String[] args); void runThreads(); void printResult(); Duration convertRuntime(String time); LocalDateTime getEnd(LocalDateTime start, String time); long getMaxRan(); long getTotalRanCount(); LocalDateTime getStart(); LocalDateTime getEnd(); String getRunTime(); int getMaxThreads(); Plugins getPlugins(); }### Answer:
@Test public void testGetRunTime() { } |
### Question:
CucumberPerf { public int getMaxThreads() { return maxThreads; } CucumberPerf(Class<?> clazz); CucumberPerf(Class<?> clazz, PerfRuntimeOptions options); CucumberPerf(PerfRuntimeOptions options); CucumberPerf(String[] args); void runThreads(); void printResult(); Duration convertRuntime(String time); LocalDateTime getEnd(LocalDateTime start, String time); long getMaxRan(); long getTotalRanCount(); LocalDateTime getStart(); LocalDateTime getEnd(); String getRunTime(); int getMaxThreads(); Plugins getPlugins(); }### Answer:
@Test public void testGetMaxThreads() { CucumberPerf cp = new CucumberPerf(options1.class); try { cp.runThreads(); } catch (Throwable e) { fail("Error:"+e.getMessage()); } assertEquals(cp.getMaxThreads(),3); } |
### Question:
NamePredicate implements Predicate { @Override public boolean apply(Node n) { String name = ""; if (n instanceof Simulation) { name = ((Simulation) n).getName(); } else if (n instanceof SimulationPeriod) { name = ((SimulationPeriod) n).getName(); } else if (n instanceof Plan) { name = ((Plan) n).getName(); } for (Pattern pattern : patterns) { if (pattern.matcher(name).find()) { return true; } } return false; } NamePredicate(List<Pattern> patterns); @Override boolean apply(Node n); }### Answer:
@Test public void anchored_name_pattern_matches_exact_name() { Simulation n = mock(Simulation.class); NamePredicate predicate = new NamePredicate(asList(Pattern.compile("^a name$"))); when(n.getName()).thenReturn("a name"); assertTrue(predicate.apply(n)); }
@Test public void anchored_name_pattern_does_not_match_part_of_name() { Simulation n = mock(Simulation.class); NamePredicate predicate = new NamePredicate(asList(Pattern.compile("^a name$"))); when(n.getName()).thenReturn("a name with suffix"); assertFalse(predicate.apply(n)); }
@Test public void non_anchored_name_pattern_matches_part_of_name() { Simulation n = mock(Simulation.class); NamePredicate predicate = new NamePredicate(asList(Pattern.compile("a name"))); when(n.getName()).thenReturn("a name with suffix"); assertTrue(predicate.apply(n)); }
@Test public void wildcard_name_pattern_matches_part_of_name() { Simulation n = mock(Simulation.class); NamePredicate predicate = new NamePredicate(asList(Pattern.compile("a .* name"))); when(n.getName()).thenReturn("a pickleEvent name"); assertTrue(predicate.apply(n)); } |
### Question:
FeatureFilter { public static boolean isMatch(Feature feature, String text) { if (text.startsWith("@")) { List<String> tags = getGroupTags(text); TagPredicate tp = new TagPredicate(tags); for (Pickle pe : feature.getPickles()) { if (tp.test(pe)) { return true; } } } else { if (feature.getName().equalsIgnoreCase(text) || feature.getUri().toString() .substring(feature.getUri().toString().lastIndexOf("/") + 1).equalsIgnoreCase(text)) return true; } return false; } FeatureFilter(List<Feature> features); List<Feature> filter(String text); static boolean isMatch(Feature feature, String text); static List<String> getGroupTags(String text); static Pattern TAG_PATTERN; }### Answer:
@Test public void isMatchTrueTest() { PerfRuntimeOptions options = new PerfRuntimeOptions(Arrays.asList(new String[] {"-g steps","src/test/java/resources"})); List<Feature> features = FeatureBuilder.getFeatures(FeatureBuilder.createRuntimeOptions(options.getCucumberOptions())); assertTrue(FeatureFilter.isMatch(features.get(1), "@onlyfilter")); }
@Test public void isMatchFalseTest() { PerfRuntimeOptions options = new PerfRuntimeOptions(Arrays.asList(new String[] {"-g steps","src/test/java/resources"})); List<Feature> features = FeatureBuilder.getFeatures(FeatureBuilder.createRuntimeOptions(options.getCucumberOptions())); assertFalse(FeatureFilter.isMatch(features.get(0), "@notefilter")); } |
### Question:
FeatureFilter { public static List<String> getGroupTags(String text) { List<String> tags = new ArrayList<String>(); if (text.startsWith("@")) { Matcher m = TAG_PATTERN.matcher(text); while (m.find()) { tags.add(m.group()); } } return tags; } FeatureFilter(List<Feature> features); List<Feature> filter(String text); static boolean isMatch(Feature feature, String text); static List<String> getGroupTags(String text); static Pattern TAG_PATTERN; }### Answer:
@Test public void getGroupTagsTest() { assertTrue(FeatureFilter.getGroupTags("@onlyfilter,@only").size()==2); } |
### Question:
PerfRuntimeOptions { public List<String> getPlanPaths() { return planPaths; } PerfRuntimeOptions(); PerfRuntimeOptions(List<String> argv); List<String> getPluginsNames(); boolean isDryRun(); boolean isMonochrome(); boolean isStrict(); boolean isFailFast(); List<String> getPlanPaths(); List<Pattern> getNameFilters(); List<String> getTagFilters(); List<String> getCucumberOptions(); PerfRuntimeOptions addPlanPaths(List<String> planPaths); PerfRuntimeOptions addNameFilters(List<String> nameFilters); PerfRuntimeOptions addTagFilters(List<String> tagFilters); PerfRuntimeOptions addPlugins(List<String> plugins); void disableDisplay(); PerfRuntimeOptions addCucumberOptions(List<String> args); void setDryRun(boolean dryRun); void setStrict(boolean strict); void setMonochrome(boolean monochrome); void setFailFast(boolean failFast); static final String VERSION; static final String USAGE_RESOURCE; }### Answer:
@Test public void testPerfRuntimeOptionsListOfString() { PerfRuntimeOptions pro = new PerfRuntimeOptions(Arrays.asList(new String[] {"plans=src/test/java/resources","-p pretty","-g steps","src/test/java/resources"})); assertEquals("src/test/java/resources",pro.getPlanPaths().get(0)); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.