method2testcases
stringlengths 118
3.08k
|
---|
### Question:
CommandExecutor implements Callable<Integer> { @Override public Integer call() throws Exception { String cmd = process_builder.command().get(0); final int sep = cmd.lastIndexOf('/'); if (sep >= 0) cmd = cmd.substring(sep+1); process = process_builder.start(); final Thread stdout = new LogWriter(process.getInputStream(), cmd, Level.INFO); final Thread stderr = new LogWriter(process.getErrorStream(), cmd, Level.WARNING); stdout.start(); stderr.start(); if (process.waitFor(WAIT_SECONDS, TimeUnit.SECONDS)) { stderr.join(); stdout.join(); final int status = process.exitValue(); if (status != 0) logger.log(Level.WARNING, "Command {0} exited with status {1}", new Object[] { process_builder.command(), status }); return status; } return null; } CommandExecutor(final String cmd, final File directory); static List<String> splitCmd(final String cmd); @Override Integer call(); boolean isActive(); @Override String toString(); }### Answer:
@Test public void testShortCommand() throws Exception { if (is_windows) return; final String cmd = "./cmd_short.sh \"With one arg\" another_arg"; final Integer status = new CommandExecutor(cmd, examples_dir).call(); final String log = getLoggedMessages(); assertThat(log, containsString("Example warning")); assertThat(log, containsString("2 arguments")); assertThat(log, containsString("Finished OK")); assertThat(status, equalTo(0)); }
@Test public void testErrorCommand() throws Exception { if (is_windows) return; final Integer status = new CommandExecutor("cmds/cmd_short.sh", examples_dir.getParentFile()).call(); final String log = getLoggedMessages(); assertThat(log, containsString("Wrong directory")); assertThat(log, containsString("exited with status 2")); assertThat(status, equalTo(2)); } |
### Question:
ResourceParser { public static URI createResourceURI(final String resource) throws Exception { try { final URI uri = URI.create(resource); if (uri.getScheme() != null) return uri; else { final Path fileResource = Paths.get(resource); return fileResource.toUri(); } } catch (Throwable ex) { try { return new File(resource).toURI(); } catch (Exception file_ex) { throw new Exception("Cannot create URI for '" + resource + "'", ex); } } } static URI createResourceURI(final String resource); static File getFile(final URI resource); static URI getURI(final File file); static InputStream getContent(final URI resource); static List<String> parsePVs(final URI resource); static String getAppName(final URI resource); static String getTargetName(final URI resource); static Stream<Map.Entry<String, String>> getQueryItemStream(final URI resource); static Map<String, List<String>> parseQueryArgs(final URI resource); static String encode(final String text); static final String PV_SCHEMA; }### Answer:
@Test public void checkWebToURI() throws Exception { URI uri = createResourceURI("http: System.out.println(uri); assertThat(uri.getScheme(), equalTo("http")); assertThat(uri.getHost(), equalTo("some.site")); assertThat(uri.getPath(), equalTo("/file/path")); } |
### Question:
SimProposal extends Proposal { public SimProposal(final String name, final String... arguments) { super(name); this.arguments = arguments; } SimProposal(final String name, final String... arguments); @Override String getDescription(); @Override List<MatchSegment> getMatch(final String text); }### Answer:
@Test public void testSimProposal() { Proposal proposal = new SimProposal("sim: assertThat(proposal.getDescription(), equalTo("sim: assertThat(proposal.apply("sine"), equalTo("sim: assertThat(proposal.apply("sim: equalTo("sim: assertThat(proposal.apply("sin(-10, 10, 2)"), equalTo("sim: assertThat(proposal.apply("sin(-10, 10, 2"), equalTo("sim: proposal = new SimProposal("sim: assertThat(proposal.getDescription(), equalTo("sim: assertThat(proposal.apply("sin(-10,10, 0.1, 2 )"), equalTo("sim: } |
### Question:
History implements ProposalProvider { public History() { this(10); } History(); History(final int max_size); @Override String getName(); synchronized void add(final Proposal proposal); @Override synchronized List<Proposal> lookup(String text); }### Answer:
@Test public void testHistory() { final History history = new History(); List<Proposal> proposals = history.lookup("test"); assertThat(proposals.size(), equalTo(0)); history.add(new Proposal("Test1")); history.add(new Proposal("Other")); history.add(new Proposal("Test2")); proposals = history.lookup("test"); assertThat(getValues(proposals), hasItems("Test1", "Test2")); assertThat(getValues(proposals), equalTo(List.of("Test2", "Test1"))); proposals = history.lookup("ther"); assertThat(getValues(proposals), equalTo(List.of("Other"))); assertThat(proposals.get(0).apply("ther"), equalTo("Other")); } |
### Question:
Services implements IServices { @Override public List<ConfigPv> getConfigPvs(String configUniqueId) { logger.info("Getting config pvs config id id {}", configUniqueId); return nodeDAO.getConfigPvs(configUniqueId); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName,
String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }### Answer:
@Test public void testGetConfigPvs() { when(nodeDAO.getConfigPvs("a")).thenReturn(Arrays.asList(ConfigPv.builder().build())); assertNotNull(services.getConfigPvs("a")); } |
### Question:
ScanCommandImplTool { @SuppressWarnings("unchecked") public static <C extends ScanCommand> ScanCommandImpl<C> implement(final C command, final JythonSupport jython) throws Exception { for (ScanCommandImplFactory factory : factories) { ScanCommandImpl<?> impl = factory.createImplementation(command, jython); if (impl != null) return (ScanCommandImpl<C>)impl; } throw new Exception("Unknown command " + command.getClass().getName()); } @SuppressWarnings("unchecked") static ScanCommandImpl<C> implement(final C command, final JythonSupport jython); static List<ScanCommandImpl<?>> implement(final List<ScanCommand> commands, final JythonSupport jython); }### Answer:
@Test public void testImplementation() throws Exception { final ScanCommand cmd = new CommentCommand("Test"); final ScanCommandImpl<ScanCommand> impl = ScanCommandImplTool.implement(cmd, null); System.out.println(impl); assertThat(impl, instanceOf(CommentCommandImpl.class)); } |
### Question:
Proposal { public String apply(final String text) { final StringBuilder result = new StringBuilder(); final List<MatchSegment> match = getMatch(text); for (MatchSegment seg : match) if (seg.getType() != MatchSegment.Type.COMMENT) result.append(seg.getText()); return result.toString(); } Proposal(final String value); String getValue(); String getDescription(); List<MatchSegment> getMatch(final String text); String apply(final String text); @Override String toString(); }### Answer:
@Test public void testPlainProposal() { Proposal proposal = new Proposal("Test1"); assertThat(proposal.apply("est"), equalTo("Test1")); assertThat(proposal.apply("anything"), equalTo("Test1")); } |
### Question:
Proposal { public List<MatchSegment> getMatch(final String text) { final int match = value.indexOf(text); if (match < 0) return List.of(MatchSegment.normal(value)); else { final List<MatchSegment> segs = new ArrayList<>(); if (match > 0) segs.add(MatchSegment.normal(value.substring(0, match))); if (! text.isEmpty()) segs.add(MatchSegment.match(text)); final int rest = match + text.length(); if (value.length() > rest) segs.add(MatchSegment.normal(value.substring(rest))); return segs; } } Proposal(final String value); String getValue(); String getDescription(); List<MatchSegment> getMatch(final String text); String apply(final String text); @Override String toString(); }### Answer:
@Test public void testMatch() { Proposal proposal = new Proposal("Test1"); List<MatchSegment> match = proposal.getMatch("es"); assertThat(match, equalTo(List.of(MatchSegment.normal("T"), MatchSegment.match("es"), MatchSegment.normal("t1")))); match = proposal.getMatch("Tes"); assertThat(match, equalTo(List.of(MatchSegment.match("Tes"), MatchSegment.normal("t1")))); } |
### Question:
LocProposal extends Proposal { static List<String> splitNameTypeAndInitialValues(final String text) { final List<String> result = new ArrayList<>(); int sep = text.indexOf('<'); if (sep >= 0) { result.add(text.substring(0, sep).trim()); int pos = text.indexOf('>', sep+1); if (pos < 0) result.add(text.substring(sep+1).trim()); else { result.add(text.substring(sep+1, pos).trim()); sep = text.indexOf('(', pos); if (sep >= 0) addInitialValues(result, text.substring(sep+1)); } } else { sep = text.indexOf('('); if (sep >= 0) { result.add(text.substring(0, sep).trim()); result.add(null); addInitialValues(result, text.substring(sep+1)); } else { result.add(text.trim()); result.add(null); } } return result; } LocProposal(final String name, final String type, final String... initial_values); @Override String getDescription(); @Override List<MatchSegment> getMatch(final String text); }### Answer:
@Test public void testArguments() { List<String> split = LocProposal.splitNameTypeAndInitialValues("loc: assertThat(split, equalTo(Arrays.asList("loc: split = LocProposal.splitNameTypeAndInitialValues("loc: assertThat(split, equalTo(Arrays.asList("loc: split = LocProposal.splitNameTypeAndInitialValues("loc: assertThat(split, equalTo(Arrays.asList("loc: split = LocProposal.splitNameTypeAndInitialValues("loc: assertThat(split, equalTo(Arrays.asList("loc: split = LocProposal.splitNameTypeAndInitialValues("loc: assertThat(split, equalTo(Arrays.asList("loc: } |
### Question:
LocProposal extends Proposal { public LocProposal(final String name, final String type, final String... initial_values) { super(name); this.type = type; this.initial_values = initial_values; } LocProposal(final String name, final String type, final String... initial_values); @Override String getDescription(); @Override List<MatchSegment> getMatch(final String text); }### Answer:
@Test public void testLocProposal() { Proposal proposal = new LocProposal("loc: assertThat(proposal.getDescription(), equalTo("loc: proposal = new LocProposal("loc: assertThat(proposal.getDescription(), equalTo("loc: proposal = new LocProposal("loc: assertThat(proposal.getDescription(), equalTo("loc: proposal = new LocProposal("loc: assertThat(proposal.getDescription(), equalTo("loc: } |
### Question:
PreferencesReader { static String replaceProperties(final String value) { if (value == null) return value; String result = value; Matcher matcher = PROP_PATTERN.matcher(value); while (matcher.find()) { final String prop_spec = matcher.group(); final String prop_name = prop_spec.substring(2, prop_spec.length()-1); final int start = matcher.start(); final int end = matcher.end(); String prop = System.getProperty(prop_name); if (prop == null) prop = System.getenv(prop_name); if (prop == null) { Logger.getLogger(PreferencesReader.class.getPackageName()) .log(Level.SEVERE, "Reading Preferences: Java system property or Environment variable'" + prop_spec + "' is not defined"); break; } else result = result.substring(0, start) + prop + result.substring(end); matcher = PROP_PATTERN.matcher(result); } return result; } PreferencesReader(final Class<?> package_class, final String preferences_properties_filename); Set<String> getKeys(final String regex); String get(final String key); boolean getBoolean(final String key); int getInt(final String key); double getDouble(final String key); }### Answer:
@Test public void testProperties() { System.out.println(PreferencesReader.replaceProperties("Running on Java $(java.version) in $(java.home)")); System.out.println("Expect warning about undefined property"); assertThat(PreferencesReader.replaceProperties("$(VeryUnlikelyToExist)"), equalTo("$(VeryUnlikelyToExist)")); System.setProperty("test", "OK"); assertThat(PreferencesReader.replaceProperties("$(test)"), equalTo("OK")); assertThat(PreferencesReader.replaceProperties("This is $(test)"), equalTo("This is OK")); } |
### Question:
UpdateThrottle { public UpdateThrottle(final long dormant_time, final TimeUnit unit, final Runnable update) { this(dormant_time, unit, update, TIMER); } UpdateThrottle(final long dormant_time, final TimeUnit unit, final Runnable update); UpdateThrottle(final long dormant_time, final TimeUnit unit, final Runnable update, final ScheduledExecutorService timer); void setDormantTime(final long dormant_time, final TimeUnit unit); void trigger(); void dispose(); static final ScheduledExecutorService TIMER; }### Answer:
@Test(timeout=5000) public void testUpdateThrottle() throws Exception { final Runnable update = new Runnable() { @Override public void run() { System.out.println("<- Update!"); updates.incrementAndGet(); synchronized (this) { notifyAll(); } } }; final UpdateThrottle throttle = new UpdateThrottle(1L, TimeUnit.SECONDS, update); assertThat(updates.get(), equalTo(0)); System.out.println("-> Trigger.."); throttle.trigger(); Thread.sleep(100); assertThat(updates.get(), equalTo(1)); System.out.println("-> Trigger.."); throttle.trigger(); System.out.println("-> Trigger.."); throttle.trigger(); System.out.println("-> Trigger.."); throttle.trigger(); assertThat(updates.get(), equalTo(1)); TimeUnit.SECONDS.sleep(2); assertThat(updates.get(), equalTo(2)); throttle.setDormantTime(500, TimeUnit.MILLISECONDS); throttle.trigger(); TimeUnit.MILLISECONDS.sleep(100); assertThat(updates.get(), equalTo(3)); throttle.trigger(); TimeUnit.MILLISECONDS.sleep(100); assertThat(updates.get(), equalTo(3)); TimeUnit.MILLISECONDS.sleep(500); assertThat(updates.get(), equalTo(4)); } |
### Question:
Services implements IServices { @Override public Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment) { logger.info("Saving snapshot for config id {}", configUniqueId); logger.info("Snapshot name: {}, values:", snapshotName); for (SnapshotItem snapshotItem : snapshotItems) { logger.info(snapshotItem.toString()); } return nodeDAO.saveSnapshot(configUniqueId, snapshotItems, snapshotName, comment, userName); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName,
String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }### Answer:
@Test public void testSaveSnapshot() { when(nodeDAO.saveSnapshot("a", Collections.emptyList(), "b", "c", "d")).thenReturn(Node.builder().nodeType(NodeType.SNAPSHOT).build()); assertNotNull(services.saveSnapshot("a", Collections.emptyList(), "b", "d", "c")); } |
### Question:
Services implements IServices { @Override public List<Node> getFromPath(String path){ return nodeDAO.getFromPath(path); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName,
String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }### Answer:
@Test public void testGetFromPath(){ Node node = Node.builder().name("SomeFolder").build(); when(nodeDAO.getFromPath("path")).thenReturn(Arrays.asList(node)); assertEquals("SomeFolder", services.getFromPath("path").get(0).getName()); } |
### Question:
ArrayScalarDivisionFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray array1 = (VNumberArray)args[0]; VNumber factor = (VNumber) args[1]; return VNumberArray.of( ListMath.rescale(array1.getData(), 1d / factor.getValue().doubleValue(), 0), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }### Answer:
@Test public void compute(){ ArrayScalarDivisionFunction arrayScalarDivisionFunction = new ArrayScalarDivisionFunction(); assertEquals("arrayDivScalar", arrayScalarDivisionFunction.getName()); assertEquals("array", arrayScalarDivisionFunction.getCategory()); VType array = VNumberArray.of(ArrayDouble.of(2.0, 10.0, 30.0), Alarm.of(AlarmSeverity.MAJOR, AlarmStatus.NONE, ""), Time.now(), Display.none()); VType factor = VDouble.of(2.0, Alarm.none(), Time.now(), Display.none()); VNumberArray result = (VNumberArray)arrayScalarDivisionFunction.compute(array, factor); assertEquals(3, result.getData().size()); assertEquals(1, result.getData().getInt(0)); assertEquals(5, result.getData().getInt(1)); assertEquals(15, result.getData().getInt(2)); result = (VNumberArray)arrayScalarDivisionFunction.compute(array, array); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); } |
### Question:
ArrayMinFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if (VTypeHelper.isNumericArray(args[0])) { return VDouble.of(Arrays.stream(VTypeHelper.toDoubles(args[0])).summaryStatistics().getMin(), Alarm.none(), Time.now(), Display.none()); } else { return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }### Answer:
@Test public void compute() { ArrayMinFunction arrayMinFunction = new ArrayMinFunction(); assertEquals("arrayMin", arrayMinFunction.getName()); assertEquals("array", arrayMinFunction.getCategory()); VNumberArray doubleArray = VNumberArray.of(ArrayDouble.of(-1.0, 0, 1.0, 2.0, 3.0, 4.0, 5), Alarm.none(), Time.now(), Display.none()); VDouble min = (VDouble) arrayMinFunction.compute(doubleArray); assertEquals("arrayMin Failed to calculate min for double array", Double.valueOf(-1.0), min.getValue()); VNumberArray intArray = VNumberArray.of(ArrayInteger.of(-1, 0, 1, 2, 3, 4, 5), Alarm.none(), Time.now(), Display.none()); min = (VDouble) arrayMinFunction.compute(intArray); assertEquals("arrayMin Failed to calculate min for int array", Double.valueOf(-1), min.getValue()); } |
### Question:
Services implements IServices { @Override public String getFullPath(String uniqueNodeId){ return nodeDAO.getFullPath(uniqueNodeId); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName,
String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }### Answer:
@Test public void testGetFullPath(){ when(nodeDAO.getFullPath("nodeId")).thenReturn("/a/b/c"); assertEquals("/a/b/c", nodeDAO.getFullPath("nodeId")); } |
### Question:
ArrayMaxFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if (VTypeHelper.isNumericArray(args[0])) { return VDouble.of(Arrays.stream(VTypeHelper.toDoubles(args[0])).summaryStatistics().getMax(), Alarm.none(), Time.now(), Display.none()); } else { return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }### Answer:
@Test public void compute() { ArrayMaxFunction arrayMaxFunction = new ArrayMaxFunction(); assertEquals("arrayMax", arrayMaxFunction.getName()); assertEquals("array", arrayMaxFunction.getCategory()); VNumberArray doubleArray = VNumberArray.of(ArrayDouble.of(1.0, 2.0, 3.0, 4.0, 5), Alarm.none(), Time.now(), Display.none()); VDouble max = (VDouble) arrayMaxFunction.compute(doubleArray); assertEquals("arrayMax Failed to calculate max for double array", Double.valueOf(5), max.getValue()); VNumberArray intArray = VNumberArray.of(ArrayInteger.of(1, 2, 3, 4, 5), Alarm.none(), Time.now(), Display.none()); max = (VDouble) arrayMaxFunction.compute(intArray); assertEquals("arrayMax Failed to calculate max for int array", Double.valueOf(5), max.getValue()); } |
### Question:
ArrayRangeOfFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(args[0] instanceof VNumberArray){ VNumberArray array = (VNumberArray)args[0]; Range range = array.getDisplay().getDisplayRange(); double min = range.getMinimum(); double max = range.getMaximum(); return VNumberArray.of( ArrayDouble.of(min, max), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }### Answer:
@Test public void compute() { ArrayRangeOfFunction arrayRangeOfFunction = new ArrayRangeOfFunction(); assertEquals("arrayRangeOf", arrayRangeOfFunction.getName()); assertEquals("array", arrayRangeOfFunction.getCategory()); Display display = Display.of(Range.of(1d, 10d), Range.of(10d, 20d), Range.of(20d, 30d), Range.of(30d, 40d), "N", new DecimalFormat("")); VNumberArray numberArray = VNumberArray.of(ArrayDouble.of(1d, 2d), Alarm.none(), Time.now(), display); VNumberArray range = (VNumberArray)arrayRangeOfFunction.compute(numberArray); assertEquals(1, range.getData().getInt(0)); assertEquals(10, range.getData().getInt(1)); } |
### Question:
ArrayStatsFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if (VTypeHelper.isNumericArray(args[0])) { DoubleSummaryStatistics stats = Arrays.stream(VTypeHelper.toDoubles(args[0])).summaryStatistics(); return VStatistics.of(stats.getAverage(), Double.NaN, stats.getMin(), stats.getMax(), (int) stats.getCount(), Alarm.none(), Time.now(), Display.none()); } else { return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }### Answer:
@Test public void compute() { ArrayStatsFunction arrayStatsFunction = new ArrayStatsFunction(); assertEquals("arrayStats", arrayStatsFunction.getName()); assertEquals("array", arrayStatsFunction.getCategory()); VNumberArray numberArray = VNumberArray.of(ArrayDouble.of(1d, 2d), Alarm.none(), Time.now(), Display.none()); VStatistics stats = (VStatistics) arrayStatsFunction.compute(numberArray); assertEquals("arrayStats Failed to calculate min", Double.valueOf(1), stats.getMin()); assertEquals("arrayStats Failed to calculate max", Double.valueOf(2), stats.getMax()); } |
### Question:
ArraySumFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray array = (VNumberArray)args[0]; VNumber offset = (VNumber)args[1]; return VNumberArray.of( ListMath.rescale(array.getData(), 1, offset.getValue().doubleValue()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }### Answer:
@Test public void compute() { ArraySumFunction scaleArrayFunction = new ArraySumFunction(); assertEquals("arraySum", scaleArrayFunction.getName()); assertEquals("array", scaleArrayFunction.getCategory()); VType offset = VDouble.of(2.0, Alarm.none(), Time.now(), Display.none()); VType array = VNumberArray.of(ArrayDouble.of(1.0, 2.0, 3.0), Alarm.none(), Time.now(), Display.none()); VNumberArray result = (VNumberArray)scaleArrayFunction.compute(array, offset); assertEquals(3, result.getData().size()); assertTrue(result.getData().getDouble(0) == 3); assertTrue(result.getData().getDouble(1) == 4); assertTrue(result.getData().getDouble(2) == 5); result = (VNumberArray)scaleArrayFunction.compute(offset, offset); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); result = (VNumberArray)scaleArrayFunction.compute(offset, array); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); } |
### Question:
ArrayInverseScalarDivisionFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(args[0] instanceof VNumber && VTypeHelper.isNumericArray(args[1])){ VNumberArray array = (VNumberArray)args[1]; VNumber factor = (VNumber) args[0]; return VNumberArray.of( ListMath.inverseRescale(array.getData(), factor.getValue().doubleValue(), 0), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }### Answer:
@Test public void compute() { ArrayInverseScalarDivisionFunction arrayScalarDivisionFunction = new ArrayInverseScalarDivisionFunction(); assertEquals("arrayDivScalarInv", arrayScalarDivisionFunction.getName()); assertEquals("array", arrayScalarDivisionFunction.getCategory()); VType array = VNumberArray.of(ArrayDouble.of(2.0, 10.0, 20.0), Alarm.of(AlarmSeverity.MAJOR, AlarmStatus.NONE, ""), Time.now(), Display.none()); VType factor = VDouble.of(100.0, Alarm.none(), Time.now(), Display.none()); VNumberArray result = (VNumberArray)arrayScalarDivisionFunction.compute(factor, array); assertEquals(3, result.getData().size()); assertEquals(50, result.getData().getInt(0)); assertEquals(10, result.getData().getInt(1)); assertEquals(5, result.getData().getInt(2)); result = (VNumberArray)arrayScalarDivisionFunction.compute(array, array); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); } |
### Question:
ArrayPowFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray array = (VNumberArray)args[0]; VNumber exponent = (VNumber)args[1]; return VNumberArray.of( ListMath.pow(array.getData(), exponent.getValue().doubleValue()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }### Answer:
@Test public void compute() { ArrayPowFunction arrayPowFunction = new ArrayPowFunction(); assertEquals("arrayPow", arrayPowFunction.getName()); assertEquals("array", arrayPowFunction.getCategory()); VType exponent = VDouble.of(2.0, Alarm.none(), Time.now(), Display.none()); VType array = VNumberArray.of(ArrayDouble.of(1.0, 2.0, 3.0), Alarm.none(), Time.now(), Display.none()); VNumberArray result = (VNumberArray)arrayPowFunction.compute(array, exponent); assertEquals(3, result.getData().size()); assertTrue(result.getData().getDouble(0) == 1); assertTrue(result.getData().getDouble(1) == 4); assertTrue(result.getData().getDouble(2) == 9); result = (VNumberArray)arrayPowFunction.compute(exponent, exponent); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); result = (VNumberArray)arrayPowFunction.compute(exponent, array); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); } |
### Question:
FieldRequest { public void encode(final ByteBuffer buffer) throws Exception { desc.encode(buffer); } FieldRequest(final String request); FieldRequest(final int pipeline, final String request); void encodeType(final ByteBuffer buffer); void encode(final ByteBuffer buffer); @Override String toString(); }### Answer:
@Test public void testEmpty() throws Exception { FieldRequest request = new FieldRequest(""); System.out.println(request); ByteBuffer buffer = encode(request); System.out.println(Hexdump.toHexdump(buffer)); }
@Test public void testPlainFields() throws Exception { FieldRequest request = new FieldRequest("field(proton_charge,pixel)"); System.out.println(request); ByteBuffer buffer = encode(request); System.out.println(Hexdump.toHexdump(buffer)); }
@Test public void testSubFields() throws Exception { FieldRequest request = new FieldRequest("field(value, timeStamp.userTag)"); System.out.println(request); ByteBuffer buffer = encode(request); System.out.println(Hexdump.toHexdump(buffer)); request = new FieldRequest("field(proton_charge,pixel,timeStamp.userTag)"); System.out.println(request); buffer = encode(request); System.out.println(Hexdump.toHexdump(buffer)); PVATypeRegistry registry = new PVATypeRegistry(); final PVAData decoded = registry.decodeType("", buffer); System.out.println(decoded.formatType()); }
@Test public void testPipeline() throws Exception { FieldRequest request = new FieldRequest(10, "field(value)"); System.out.println(request); ByteBuffer buffer = encode(request); System.out.println(Hexdump.toHexdump(buffer)); } |
### Question:
VTypeHelper { public static double[] toDoubles(final VType value) { final double[] array; if (value instanceof VNumberArray) { final ListNumber list = ((VNumberArray) value).getData(); array = new double[list.size()]; for (int i = 0; i < array.length; ++i) { array[i] = list.getDouble(i); } } else array = new double[0]; return array; } final static double toDouble(final VType value); static double[] toDoubles(final VType value); static String toString(final VType value); static double toDouble(final VType value, final int index); static boolean isNumericArray(final VType value); static int getArraySize(final VType value); static Alarm highestAlarmOf(final VType a, VType b); static Time lastestTimeOf(final VType a, final VType b); final static Instant getTimestamp(final VType value); static VType transformTimestamp(final VType value,
final Instant time); static VType transformTimestampToNow(final VType value); static boolean isDisconnected(final VType value); static AlarmSeverity getSeverity(final VType value); static String formatArray(Array array, int maxElements); }### Answer:
@Test public void testToDoubles(){ VDoubleArray doubleArray = VDoubleArray.of(ArrayDouble.of(7.7, 8.8), Alarm.none(), Time.now(), Display.none()); double[] result = VTypeHelper.toDoubles(doubleArray); assertEquals(2, result.length); assertEquals(7.7, result[0], 0); assertEquals(8.8, result[1], 0); VDouble doubleValue = VDouble.of(7.7, Alarm.none(), Time.now(), Display.none()); result = VTypeHelper.toDoubles(doubleValue); assertEquals(0, result.length); } |
### Question:
VTypeHelper { public static boolean isNumericArray(final VType value) { return value instanceof VNumberArray || value instanceof VEnumArray; } final static double toDouble(final VType value); static double[] toDoubles(final VType value); static String toString(final VType value); static double toDouble(final VType value, final int index); static boolean isNumericArray(final VType value); static int getArraySize(final VType value); static Alarm highestAlarmOf(final VType a, VType b); static Time lastestTimeOf(final VType a, final VType b); final static Instant getTimestamp(final VType value); static VType transformTimestamp(final VType value,
final Instant time); static VType transformTimestampToNow(final VType value); static boolean isDisconnected(final VType value); static AlarmSeverity getSeverity(final VType value); static String formatArray(Array array, int maxElements); }### Answer:
@Test public void testIsNumericArray(){ VDouble vDouble = VDouble.of(7.7, Alarm.none(), Time.now(), Display.none()); assertFalse(VTypeHelper.isNumericArray(vDouble)); VDoubleArray doubleArray = VDoubleArray.of(ArrayDouble.of(7.7, 8.8), Alarm.none(), Time.now(), Display.none()); assertTrue(VTypeHelper.isNumericArray(doubleArray)); VEnumArray enumArray = VEnumArray.of(ArrayInteger.of(0, 1), EnumDisplay.of("a", "b"), Alarm.none(), Time.now()); assertTrue(VTypeHelper.isNumericArray(enumArray)); } |
### Question:
VTypeHelper { public static int getArraySize(final VType value) { final ListInteger sizes; if (value instanceof VNumberArray) { sizes = ((VNumberArray) value).getSizes(); } else if (value instanceof VEnumArray) { sizes = ((VEnumArray) value).getSizes(); } else if (value instanceof VStringArray) { sizes = ((VStringArray) value).getSizes(); } else { return 0; } return sizes.size() > 0 ? sizes.getInt(0) : 0; } final static double toDouble(final VType value); static double[] toDoubles(final VType value); static String toString(final VType value); static double toDouble(final VType value, final int index); static boolean isNumericArray(final VType value); static int getArraySize(final VType value); static Alarm highestAlarmOf(final VType a, VType b); static Time lastestTimeOf(final VType a, final VType b); final static Instant getTimestamp(final VType value); static VType transformTimestamp(final VType value,
final Instant time); static VType transformTimestampToNow(final VType value); static boolean isDisconnected(final VType value); static AlarmSeverity getSeverity(final VType value); static String formatArray(Array array, int maxElements); }### Answer:
@Test public void testGetArraySize(){ VDoubleArray doubleArray = VDoubleArray.of(ArrayDouble.of(7.7, 8.8), Alarm.none(), Time.now(), Display.none()); assertEquals(2, VTypeHelper.getArraySize(doubleArray)); VEnumArray enumArray = VEnumArray.of(ArrayInteger.of(0, 1), EnumDisplay.of("a", "b"), Alarm.none(), Time.now()); assertEquals(2, VTypeHelper.getArraySize(enumArray)); VStringArray stringArray = VStringArray.of(Arrays.asList("a","b"), Alarm.none(), Time.now()); assertEquals(2, VTypeHelper.getArraySize(stringArray)); } |
### Question:
VTypeHelper { public static Time lastestTimeOf(final VType a, final VType b) { final Time ta = Time.timeOf(a); final Time tb = Time.timeOf(b); if (ta.getTimestamp().isAfter(tb.getTimestamp())) { return ta; } return tb; } final static double toDouble(final VType value); static double[] toDoubles(final VType value); static String toString(final VType value); static double toDouble(final VType value, final int index); static boolean isNumericArray(final VType value); static int getArraySize(final VType value); static Alarm highestAlarmOf(final VType a, VType b); static Time lastestTimeOf(final VType a, final VType b); final static Instant getTimestamp(final VType value); static VType transformTimestamp(final VType value,
final Instant time); static VType transformTimestampToNow(final VType value); static boolean isDisconnected(final VType value); static AlarmSeverity getSeverity(final VType value); static String formatArray(Array array, int maxElements); }### Answer:
@Test public void testGetLatestTimeOf(){ Instant now = Instant.now(); Time t1 = Time.of(Instant.EPOCH); Time t2 = Time.of(now); VInt i1 = VInt.of(1, Alarm.none(), t1, Display.none()); VInt i2 = VInt.of(2, Alarm.none(), t2, Display.none()); assertEquals(t2, VTypeHelper.lastestTimeOf(i1, i2)); assertEquals(t2, VTypeHelper.lastestTimeOf(i2, i1)); } |
### Question:
VTypeHelper { final public static Instant getTimestamp(final VType value) { final Time time = Time.timeOf(value); if (time != null && time.isValid()) { return time.getTimestamp(); } return Instant.now(); } final static double toDouble(final VType value); static double[] toDoubles(final VType value); static String toString(final VType value); static double toDouble(final VType value, final int index); static boolean isNumericArray(final VType value); static int getArraySize(final VType value); static Alarm highestAlarmOf(final VType a, VType b); static Time lastestTimeOf(final VType a, final VType b); final static Instant getTimestamp(final VType value); static VType transformTimestamp(final VType value,
final Instant time); static VType transformTimestampToNow(final VType value); static boolean isDisconnected(final VType value); static AlarmSeverity getSeverity(final VType value); static String formatArray(Array array, int maxElements); }### Answer:
@Test public void testGetTimestamp() throws Exception{ Instant epoch = Instant.EPOCH; Time t = Time.of(epoch); VInt i1 = VInt.of(1, Alarm.none(), t, Display.none()); assertEquals(epoch, VTypeHelper.getTimestamp(i1)); t = Time.nowInvalid(); i1 = VInt.of(1, Alarm.none(), t, Display.none()); Instant now = Instant.now(); Thread.sleep(2); assertTrue(VTypeHelper.getTimestamp(i1).isAfter(now)); } |
### Question:
SnapshotDataConverter { protected static String getScalarValueString(Object value) { ObjectMapper objectMapper = new ObjectMapper(); Object[] valueArray = {value}; try { return objectMapper.writeValueAsString(valueArray); } catch (JsonProcessingException e) { throw new PVConversionException(String.format("Unable to write scalar value \"%s\" as JSON string", value.toString())); } } private SnapshotDataConverter(); static SnapshotItem fromSnapshotPv(SnapshotPv snapshotPv, SnapshotPv readback); static SnapshotPv fromVType(VType vType); static VType toVType(SnapshotPv snapshotPv); }### Answer:
@Test public void testGetScalarValueString() { assertEquals("[1]", SnapshotDataConverter.getScalarValueString(Integer.valueOf(1))); assertEquals("[1.1]", SnapshotDataConverter.getScalarValueString(Double.valueOf(1.1))); String string = SnapshotDataConverter.getScalarValueString("string"); assertEquals("[\"string\"]", string); } |
### Question:
VTypeHelper { public static Alarm highestAlarmOf(final VType a, VType b) { return Alarm.highestAlarmOf(java.util.List.of(a, b), false); } final static double toDouble(final VType value); static double[] toDoubles(final VType value); static String toString(final VType value); static double toDouble(final VType value, final int index); static boolean isNumericArray(final VType value); static int getArraySize(final VType value); static Alarm highestAlarmOf(final VType a, VType b); static Time lastestTimeOf(final VType a, final VType b); final static Instant getTimestamp(final VType value); static VType transformTimestamp(final VType value,
final Instant time); static VType transformTimestampToNow(final VType value); static boolean isDisconnected(final VType value); static AlarmSeverity getSeverity(final VType value); static String formatArray(Array array, int maxElements); }### Answer:
@Test public void highestAlarmOf() { VType arg1 = VInt.of(0, Alarm.none(), Time.now(), Display.none()); VType arg2 = VInt.of(0, Alarm.lolo(), Time.now(), Display.none()); Alarm alarm = VTypeHelper.highestAlarmOf(arg1, arg2); assertTrue("Failed to correctly calculate highest alarm expected LOLO, got : " + alarm, Alarm.lolo().equals(alarm)); } |
### Question:
SnapshotDataConverter { protected static String getDimensionString(VNumberArray vNumberArray) { ListInteger sizes = vNumberArray.getSizes(); List<Integer> sizesAsIntList = new ArrayList<>(); for(int i = 0; i < sizes.size(); i++) { sizesAsIntList.add(sizes.getInt(i)); } ObjectMapper objectMapper = new ObjectMapper(); try { return objectMapper.writeValueAsString(sizesAsIntList); } catch (JsonProcessingException e) { throw new PVConversionException("Unable to write sizes of number array as JSON string"); } } private SnapshotDataConverter(); static SnapshotItem fromSnapshotPv(SnapshotPv snapshotPv, SnapshotPv readback); static SnapshotPv fromVType(VType vType); static VType toVType(SnapshotPv snapshotPv); }### Answer:
@Test public void testGetDimensionString() { VNumberArray vNumberArray = VIntArray.of(CollectionNumbers.toListInt(1, 2, 3, 4, 5, 6), CollectionNumbers.toListInt(1, 2, 3), alarm, time, display); vNumberArray.getSizes(); assertEquals("[1,2,3]", SnapshotDataConverter.getDimensionString(vNumberArray)); vNumberArray = VIntArray.of(CollectionNumbers.toListInt(1, 2, 3), CollectionNumbers.toListInt(1, 2), alarm, time, display); vNumberArray.getSizes(); assertEquals("[1,2]", SnapshotDataConverter.getDimensionString(vNumberArray)); vNumberArray = VIntArray.of(CollectionNumbers.toListInt(1), CollectionNumbers.toListInt(1), alarm, time, display); vNumberArray.getSizes(); assertEquals("[1]", SnapshotDataConverter.getDimensionString(vNumberArray)); } |
### Question:
SnapshotDataConverter { protected static ListInteger toSizes(SnapshotPv snapshotPv) { ObjectMapper objectMapper = new ObjectMapper(); try { int[] sizes = objectMapper.readValue(snapshotPv.getSizes(), int[].class); return CollectionNumbers.toListInt(sizes); } catch (Exception e) { throw new PVConversionException(String.format("Unable to convert string %s to int array", snapshotPv.getSizes())); } } private SnapshotDataConverter(); static SnapshotItem fromSnapshotPv(SnapshotPv snapshotPv, SnapshotPv readback); static SnapshotPv fromVType(VType vType); static VType toVType(SnapshotPv snapshotPv); }### Answer:
@Test public void testDesrializeSizes() { ListInteger sizes = SnapshotDataConverter.toSizes(SnapshotPv.builder().sizes("[1,2]").build()); assertEquals(2, sizes.size()); assertEquals(1, sizes.getInt(0)); }
@Test(expected = PVConversionException.class) public void testDeserializeBadSizes() { SnapshotDataConverter.toSizes(SnapshotPv.builder().sizes("[1,2").build()); } |
### Question:
Services implements IServices { @Override public Node createNode(String parentsUniqueId, Node node) { Node parentFolder = nodeDAO.getNode(parentsUniqueId); if (parentFolder == null || !parentFolder.getNodeType().equals(NodeType.FOLDER)) { String message = String.format("Cannot create new folder as parent folder with id=%s does not exist.", parentsUniqueId); logger.error(message); throw new IllegalArgumentException(message); } node = nodeDAO.createNode(parentsUniqueId, node); logger.info("Created new node: {}", node); return node; } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName,
String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testCreateConfigurationNoParent() { services.createNode("x", configFromClient); }
@Test(expected = IllegalArgumentException.class) public void createNewFolderNoParentSpecified() { Node folderFromClient = Node.builder().name("SomeFolder").build(); services.createNode(null, folderFromClient); } |
### Question:
NodeRowMapper implements RowMapper<Node> { @Override public Node mapRow(ResultSet resultSet, int rowIndex) throws SQLException { return Node.builder() .id(resultSet.getInt("id")) .nodeType(NodeType.valueOf(resultSet.getString("type"))) .created(resultSet.getTimestamp("created")) .lastModified(resultSet.getTimestamp("last_modified")) .name(resultSet.getString("name")) .userName(resultSet.getString("username")) .uniqueId(resultSet.getString("unique_id")) .build(); } @Override Node mapRow(ResultSet resultSet, int rowIndex); }### Answer:
@Test public void testRowMapper() throws Exception { ResultSet resultSet = Mockito.mock(ResultSet.class); when(resultSet.getInt("id")).thenReturn(1); when(resultSet.getString("name")).thenReturn("name"); when(resultSet.getTimestamp("created")).thenReturn(new Timestamp(System.currentTimeMillis())); when(resultSet.getTimestamp("last_modified")).thenReturn(new Timestamp(System.currentTimeMillis())); when(resultSet.getString("username")).thenReturn("username"); when(resultSet.getString("type")).thenReturn(NodeType.FOLDER.toString()); assertTrue(new NodeRowMapper().mapRow(resultSet, 0) instanceof Node); } |
### Question:
SnapshotController extends BaseController { @GetMapping("/snapshot/{uniqueNodeId}") public Node getSnapshot(@PathVariable String uniqueNodeId) { return services.getSnapshot(uniqueNodeId); } @GetMapping("/snapshot/{uniqueNodeId}") Node getSnapshot(@PathVariable String uniqueNodeId); @GetMapping("/snapshot/{uniqueNodeId}/items") List<SnapshotItem> getSnapshotItems(@PathVariable String uniqueNodeId); @PutMapping("/snapshot/{configUniqueId}") Node saveSnapshot(@PathVariable String configUniqueId,
@RequestParam(required = true) String snapshotName,
@RequestParam(required = true) String userName,
@RequestParam(required = true) String comment,
@RequestBody(required = true) List<SnapshotItem> snapshotItems); }### Answer:
@Test public void testGetSnapshot() throws Exception{ Mockito.reset(services); when(services.getSnapshot("b")).thenReturn(snapshot); MockHttpServletRequestBuilder request = get("/snapshot/b"); MvcResult result = mockMvc.perform(request).andExpect(status().isOk()).andExpect(content().contentType(JSON)) .andReturn(); objectMapper.readValue(result.getResponse().getContentAsString(), Node.class); }
@Test public void testGetNonExistingSnapshot() throws Exception{ when(services.getSnapshot("c")).thenThrow(new SnapshotNotFoundException("askdmdsf")); MockHttpServletRequestBuilder request = get("/snapshot/c"); mockMvc.perform(request).andExpect(status().isNotFound()); }
@Test public void testNonExistingSnapshot() throws Exception{ when(services.getSnapshot("x")).thenThrow(new SnapshotNotFoundException("lasdfk")); MockHttpServletRequestBuilder request = get("/snapshot/x").contentType(JSON); mockMvc.perform(request).andExpect(status().isNotFound()); } |
### Question:
SnapshotController extends BaseController { @GetMapping("/snapshot/{uniqueNodeId}/items") public List<SnapshotItem> getSnapshotItems(@PathVariable String uniqueNodeId) { return services.getSnapshotItems(uniqueNodeId); } @GetMapping("/snapshot/{uniqueNodeId}") Node getSnapshot(@PathVariable String uniqueNodeId); @GetMapping("/snapshot/{uniqueNodeId}/items") List<SnapshotItem> getSnapshotItems(@PathVariable String uniqueNodeId); @PutMapping("/snapshot/{configUniqueId}") Node saveSnapshot(@PathVariable String configUniqueId,
@RequestParam(required = true) String snapshotName,
@RequestParam(required = true) String userName,
@RequestParam(required = true) String comment,
@RequestBody(required = true) List<SnapshotItem> snapshotItems); }### Answer:
@Test public void testGetSnapshotItems() throws Exception{ SnapshotItem si = SnapshotItem.builder() .configPv(ConfigPv.builder().id(1).pvName("pvName").build()) .snapshotId(2) .build(); when(services.getSnapshotItems("si")).thenReturn(Arrays.asList(si)); MockHttpServletRequestBuilder request = get("/snapshot/si/items"); MvcResult result = mockMvc.perform(request).andExpect(status().isOk()).andExpect(content().contentType(JSON)) .andReturn(); objectMapper.readValue(result.getResponse().getContentAsString(), new TypeReference<List<SnapshotItem>>() { }); } |
### Question:
Services implements IServices { @Override public Node getNode(String nodeId) { logger.info("Getting node {}", nodeId); return nodeDAO.getNode(nodeId); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName,
String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }### Answer:
@Test public void testGetConfigNotNull() { when(nodeDAO.getNode("a")).thenReturn(configFromClient); Node config = services.getNode("a"); assertEquals(1, config.getId()); }
@Test public void testGetFolder() { when(nodeDAO.getNode("a")).thenReturn(Node.builder().id(77).uniqueId("a").build()); assertNotNull(services.getNode("a")); }
@Test public void testGetNonExsitingFolder() { when(nodeDAO.getNode("a")).thenReturn(null); assertNull(services.getNode("a")); reset(nodeDAO); } |
### Question:
Services implements IServices { @Override public List<Node> getSnapshots(String configUniqueId) { logger.info("Obtaining snapshot for config id={}", configUniqueId); return nodeDAO.getSnapshots(configUniqueId); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName,
String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }### Answer:
@Test public void testGetSnapshots() { services.getSnapshots(anyString()); verify(nodeDAO, times(1)).getSnapshots(anyString()); reset(nodeDAO); } |
### Question:
Services implements IServices { @Override public Node getSnapshot(String snapshotUniqueId) { Node snapshot = nodeDAO.getSnapshot(snapshotUniqueId); if (snapshot == null) { String message = String.format("Snapshot with id=%s not found", snapshotUniqueId); logger.error(message); throw new SnapshotNotFoundException(message); } logger.info("Retrieved snapshot id={}", snapshotUniqueId); return snapshot; } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName,
String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }### Answer:
@Test public void testGetSnapshotNotFound() { when(nodeDAO.getSnapshot("s")).thenReturn(null); try { services.getSnapshot("s"); fail("Exception expected here"); } catch (Exception e) { } reset(nodeDAO); }
@Test public void testGetSnapshot() { when(nodeDAO.getSnapshot("s")).thenReturn(mock(Node.class)); Node snapshot = services.getSnapshot("s"); assertNotNull(snapshot); reset(nodeDAO); } |
### Question:
SeverityLevelHelper { final public static String getStatusMessage(final VType value) { final Alarm alarm = Alarm.alarmOf(value); if (alarm != null) return alarm.getName(); return SeverityLevel.OK.toString(); } final static SeverityLevel decodeSeverity(final VType value); final static String getStatusMessage(final VType value); }### Answer:
@Test public void getStatusMessage() { VInt intValue = VInt.of(7, Alarm.disconnected(), Time.now(), Display.none()); String statusMessage = SeverityLevelHelper.getStatusMessage(intValue); assertEquals("Disconnected", statusMessage); intValue = VInt.of(7, Alarm.none(), Time.now(), Display.none()); statusMessage = SeverityLevelHelper.getStatusMessage(intValue); assertEquals("None", statusMessage); intValue = VInt.of(7, Alarm.lolo(), Time.now(), Display.none()); statusMessage = SeverityLevelHelper.getStatusMessage(intValue); assertEquals("LOLO", statusMessage); intValue = VInt.of(7, Alarm.hihi(), Time.now(), Display.none()); statusMessage = SeverityLevelHelper.getStatusMessage(intValue); assertEquals("HIHI", statusMessage); intValue = VInt.of(7, Alarm.low(), Time.now(), Display.none()); statusMessage = SeverityLevelHelper.getStatusMessage(intValue); assertEquals("LOW", statusMessage); intValue = VInt.of(7, Alarm.high(), Time.now(), Display.none()); statusMessage = SeverityLevelHelper.getStatusMessage(intValue); assertEquals("HIGH", statusMessage); } |
### Question:
PlotSample implements PlotDataItem<Instant> { @Override public double getValue() { return org.phoebus.core.vtypes.VTypeHelper.toDouble(value, waveform_index.get()); } PlotSample(final AtomicInteger waveform_index, final String source, final VType value, final String info); PlotSample(final AtomicInteger waveform_index, final String source, final VType value); PlotSample(final String source, final VType value); PlotSample(final String source, final String info); PlotSample(final double x, final double y); String getSource(); VType getVType(); @Override Instant getPosition(); @Override double getValue(); @Override double getStdDev(); @Override double getMin(); @Override double getMax(); @Override String getInfo(); @Override String toString(); }### Answer:
@Test public void getValue() { VDouble vDouble = VDouble.of(7.7, Alarm.none(), Time.now(), Display.none()); PlotSample plotSample = new PlotSample(new AtomicInteger(0), "source", vDouble, "info"); double result = plotSample.getValue(); assertEquals(7.7, result, 0); VDoubleArray vDoubleArray = VDoubleArray.of(ArrayDouble.of(7.7, 8.8, 9.9), Alarm.none(), Time.now(), Display.none()); plotSample = new PlotSample(new AtomicInteger(1), "source", vDoubleArray, "info"); result = plotSample.getValue(); assertEquals(8.8, result, 0); } |
### Question:
EdmConverter { public DisplayModel getDisplayModel() { return model; } EdmConverter(final File input, final AssetLocator asset_locator); DisplayModel getDisplayModel(); void write(final File output); int nextGroup(); void downloadAsset(final String asset); Collection<String> getIncludedDisplays(); Collection<String> getLinkedDisplays(); void addPositionOffset(final int x, final int y); int getOffsetX(); int getOffsetY(); void convertWidget(final Widget parent, final EdmEntity edm); void correctChildWidgets(final Widget parent); void addIncludedDisplay(final String included_display); void addLinkedDisplay(final String linked_display); }### Answer:
@Test public void testConverter() throws Exception { EdmModel.reloadEdmColorFile("colors.list", getClass().getResourceAsStream("/colors.list")); final File edl = new File(getClass().getResource("/Maintenance_12hr.edl").getFile()); final EdmConverter converter = new EdmConverter(edl, null); final ByteArrayOutputStream buf = new ByteArrayOutputStream(); final ModelWriter writer = new ModelWriter(buf); writer.writeModel(converter.getDisplayModel()); writer.close(); System.out.println(buf.toString()); } |
### Question:
Cache { public Cache(final Duration timeout) { this.timeout = timeout; } Cache(final Duration timeout); T getCachedOrNew(final String key, final CreateEntry<String, T> creator); Collection<String> getKeys(); void clear(); }### Answer:
@Test public void testCache() throws Exception { final Cache<String> cache = new Cache<>(Duration.ofSeconds(2)); final CountDownLatch set_A = new CountDownLatch(1); final AtomicReference<String> A = new AtomicReference<>(); final ExecutorService pool = Executors.newCachedThreadPool(); pool.submit(() -> { final String key = "A"; logger.fine("> Requesting " + key + " for 1st time ..."); A.set(cache.getCachedOrNew(key, this::createEntry)); set_A.countDown(); logger.fine("< Got initial" + key); return null; }); pool.submit(() -> { final String key = "B"; logger.fine("> Requesting " + key + "..."); cache.getCachedOrNew(key, this::createEntry); logger.fine("< Got " + key); return null; }); pool.submit(() -> { final String key = "A"; logger.fine("> Requesting " + key + " again (cached)..."); cache.getCachedOrNew(key, this::createEntry); logger.fine("< Got cached " + key); return null; }); String A2 = cache.getCachedOrNew("A", this::createEntry); assertThat(A2, equalTo("Entry for A")); set_A.await(); assertThat(A2, sameInstance(A.get())); logger.fine("Allowing to expire"); TimeUnit.SECONDS.sleep(3); A2 = cache.getCachedOrNew("A", this::createEntry); assertThat(A2, not(sameInstance(A.get()))); logger.fine("Waiting for cache cleanup"); TimeUnit.SECONDS.sleep(6); final Collection<String> keys = cache.getKeys(); logger.fine("Remaining entries: " + keys); assertThat(keys.size(), equalTo(0)); } |
### Question:
Version implements Comparable<Version> { public static Version parse(final String version) { Matcher matcher = VERSION_PATTERN.matcher(version); if (matcher.matches()) return new Version(Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2)), Integer.parseInt(matcher.group(3))); matcher = SHORT_VERSION_PATTERN.matcher(version); if (matcher.matches()) return new Version(Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2)), 0); throw new IllegalArgumentException("Invalid version string '" + version + "'"); } Version(final int major, final int minor, final int patch); static Version parse(final String version); int getMajor(); int getMinor(); int getPatch(); @Override int hashCode(); @Override boolean equals(final Object obj); @Override int compareTo(final Version other); @Override String toString(); }### Answer:
@Test public void testParse() { assertThat(Version.parse("2.0.1").getMajor(), equalTo(2)); assertThat(Version.parse("2.0.1").getMinor(), equalTo(0)); assertThat(Version.parse("2.0.1").getPatch(), equalTo(1)); }
@Test public void testError() { try { Version.parse("2"); fail("Didn't detect invalid version"); } catch (IllegalArgumentException ex) { assertThat(ex.getMessage(), containsString("Invalid version string")); } try { Version.parse("2.1.2.3"); fail("Didn't detect invalid version"); } catch (IllegalArgumentException ex) { assertThat(ex.getMessage(), containsString("Invalid version string")); } } |
### Question:
Converter { public Converter(final File input, final File output) throws Exception { logger.log(Level.INFO, "Convert " + input + " -> " + output); final ADLWidget root = ParserADL.getNextElement(input); colorMap = getColorMap(root); logger.log(Level.FINE, "Color map: " + Arrays.toString(colorMap)); initializeDisplayModel(input.getName(), root); logger.log(Level.FINE, "Display '" + display.getName() + "' size " + display.propWidth().getValue() + " x " + display.propHeight().getValue()); convertChildren(root.getObjects(), display, colorMap); logger.log(Level.FINE, "Writing " + output); final ModelWriter writer = new ModelWriter(new FileOutputStream(output)); writer.writeModel(display); writer.close(); } Converter(final File input, final File output); static void convertChildren(final List<ADLWidget> childWidgets, final Widget parentModel, final WidgetColor[] colorMap); static void main(final String[] original_args); static final Logger logger; }### Answer:
@Test public void testConverter() throws Exception { final String filename = ConverterTest.class.getResource("/Main_XXXX.adl").getFile(); if (filename.isEmpty()) throw new Exception("Cannot obtain test file"); final File output = File.createTempFile("Main_XXX", ".bob"); output.deleteOnExit(); new Converter(new File(filename), output); final BufferedReader dump = new BufferedReader(new FileReader(output)); dump.lines().forEach(System.out::println); dump.close(); final ModelReader reader = new ModelReader(new FileInputStream(output)); final DisplayModel model = reader.readModel(); testCalcRule(model); } |
### Question:
JFXUtil extends org.phoebus.ui.javafx.JFXUtil { public static String webRGB(final WidgetColor color) { return webRGBCache.computeIfAbsent(color, col -> { if (col.getAlpha() < 255) return "rgba(" + col.getRed() + ',' + col.getGreen() + ',' + col.getBlue() + ',' + col.getAlpha()/255f + ')'; else return String.format((Locale) null, "#%02X%02X%02X", col.getRed(), col.getGreen(), col.getBlue()); }); } static Color convert(final WidgetColor color); static String webRGB(final WidgetColor color); static StringBuilder appendWebRGB(final StringBuilder buf, final WidgetColor color); static String shadedStyle(final WidgetColor color); static WidgetColor convert(final Color color); static Font convert(final WidgetFont font); static String cssFont(final String prefix, final Font font); static ImageView getIcon(final String name); static Pos computePos(final HorizontalAlignment horiz, final VerticalAlignment vert); }### Answer:
@Test public void testRGB() { assertThat(JFXUtil.webRGB(new WidgetColor(15, 255, 0)), equalTo("#0FFF00")); assertThat(JFXUtil.webRGB(new WidgetColor(0, 16, 255)), equalTo("#0010FF")); } |
### Question:
ResettableTimeout { public void reset() { final ScheduledFuture<?> previous = timeout.getAndSet(timer.schedule(signal_no_more_messages, timeout_secs, TimeUnit.SECONDS)); if (previous != null) previous.cancel(false); } ResettableTimeout(final long timeout_secs); void reset(); boolean awaitTimeout(final long seconds); void shutdown(); }### Answer:
@Test public void testReset() throws Exception { System.out.println("Timeout in 4 secs?"); final ResettableTimeout timer = new ResettableTimeout(4); final ScheduledExecutorService resetter = Executors.newSingleThreadScheduledExecutor(); resetter.scheduleAtFixedRate(() -> { System.out.println("Reset.."); timer.reset(); }, 1, 1, TimeUnit.SECONDS); assertThat(timer.awaitTimeout(8), equalTo(false)); resetter.shutdown(); System.out.println("Stopped the resets. Should now time out in 4 secs"); assertThat(timer.awaitTimeout(6), equalTo(true)); timer.shutdown(); } |
### Question:
AlarmContext { static String encodedURLPath(String path) { return String.valueOf(path).replace(": } static synchronized void registerPV(AlarmPV alarmPV); static synchronized void releasePV(AlarmPV alarmPV); static synchronized void acknowledgePV(AlarmPV alarmPV, boolean ack); static synchronized void enablePV(AlarmPV alarmPV, boolean enable); }### Answer:
@Test public void testURLEncoding() { String pathWithDelimiter = "OPR/TEST/sim: String pathWithColon = "OPR/TEST/SR:test:pv"; String pathWithDelimiterAndColon = "OPR/TEST/sim: String encodedPathWithDelimiter = "OPR/TEST/sim%3A%2F%2Ftest"; String encodedPathWithColon = "OPR/TEST/SR%3Atest%3Apv"; String encodedPathWithDelimiterAndColon = "OPR/TEST/sim%3A%2F%2FSR%3Atest%3Apv"; assertEquals("Failed to encode pv name the delimiter", encodedPathWithDelimiter, AlarmContext.encodedURLPath(pathWithDelimiter)); assertEquals("Failed to encode pv name with colon", encodedPathWithColon, AlarmContext.encodedURLPath(pathWithColon)); assertEquals("Failed to encode pv name with delimiter and colon", encodedPathWithDelimiterAndColon, AlarmContext.encodedURLPath(pathWithDelimiterAndColon)); } |
### Question:
AlarmContext { static String decodedURLPath(String path) { return String.valueOf(path).replace(encodecDelimiter, ": } static synchronized void registerPV(AlarmPV alarmPV); static synchronized void releasePV(AlarmPV alarmPV); static synchronized void acknowledgePV(AlarmPV alarmPV, boolean ack); static synchronized void enablePV(AlarmPV alarmPV, boolean enable); }### Answer:
@Test public void testURLDecoding() { String pathWithDelimiter = "OPR/TEST/sim: String pathWithColon = "OPR/TEST/SR:test:pv"; String pathWithDelimiterAndColon = "OPR/TEST/sim: String encodedPathWithDelimiter = "OPR/TEST/sim%3A%2F%2Ftest"; String encodedPathWithColon = "OPR/TEST/SR%3Atest%3Apv"; String encodedPathWithDelimiterAndColon = "OPR/TEST/sim%3A%2F%2FSR%3Atest%3Apv"; assertEquals("Failed to decode pv name the delimiter", pathWithDelimiter, AlarmContext.decodedURLPath(encodedPathWithDelimiter)); assertEquals("Failed to decode pv name with colon", pathWithColon, AlarmContext.decodedURLPath(encodedPathWithColon)); assertEquals("Failed to decode pv name with delimiter and colon", pathWithDelimiterAndColon, AlarmContext.decodedURLPath(encodedPathWithDelimiterAndColon)); } |
### Question:
AlarmContext { static String decodedKafaPath(String path) { return path.replace("\\/","/"); } static synchronized void registerPV(AlarmPV alarmPV); static synchronized void releasePV(AlarmPV alarmPV); static synchronized void acknowledgePV(AlarmPV alarmPV, boolean ack); static synchronized void enablePV(AlarmPV alarmPV, boolean enable); }### Answer:
@Test public void testKafkaPathDecoding() { String pathWithDelimiter = "OPR/TEST/sim: String pathWithColon = "OPR/TEST/SR:test:pv"; String pathWithDelimiterAndColon = "OPR/TEST/sim: String encodedPathWithDelimiter = "OPR/TEST/sim:\\/\\/test"; String encodedPathWithColon = "OPR/TEST/SR:test:pv"; String encodedPathWithDelimiterAndColon = "OPR/TEST/sim:\\/\\/SR:test:pv"; assertEquals("Failed to decode pv kafka path the delimiter", pathWithDelimiter, AlarmContext.decodedKafaPath(encodedPathWithDelimiter)); assertEquals("Failed to decode pv kafka path with colon", pathWithColon, AlarmContext.decodedKafaPath(encodedPathWithColon)); assertEquals("Failed to decode pv kafka path with delimiter and colon", pathWithDelimiterAndColon, AlarmContext.decodedKafaPath(encodedPathWithDelimiterAndColon)); } |
### Question:
Node implements Comparable<Node> { @Override public int compareTo(Node other) { if(nodeType.equals(NodeType.FOLDER) && other.getNodeType().equals(NodeType.CONFIGURATION)){ return -1; } else if(getNodeType().equals(NodeType.CONFIGURATION) && other.getNodeType().equals(NodeType.FOLDER)){ return 1; } else{ return getName().compareTo(other.getName()); } } void putProperty(String key, String value); void removeProperty(String key); String getProperty(String key); void addTag(Tag tag); void removeTag(Tag tag); @Override boolean equals(Object other); @Override int hashCode(); @Override int compareTo(Node other); static final int ROOT_NODE_ID; }### Answer:
@Test public void testCompareTo() { Node folder1 = Node.builder().name("a").build(); Node folder2 = Node.builder().name("b").build(); Node folder3 = Node.builder().name("a").build(); Node config = Node.builder().nodeType(NodeType.CONFIGURATION).name("c1").build(); Node config2 = Node.builder().nodeType(NodeType.CONFIGURATION).name("c2").build(); assertTrue(folder3.compareTo(folder1) == 0); assertTrue(folder2.compareTo(folder1) > 0); assertTrue(folder1.compareTo(folder2) < 0); assertTrue(folder1.compareTo(config) < 0); assertTrue(config.compareTo(folder1) > 0); assertTrue(config.compareTo(config2) < 0); } |
### Question:
Node implements Comparable<Node> { @Override public int hashCode() { return Objects.hash(nodeType, uniqueId); } void putProperty(String key, String value); void removeProperty(String key); String getProperty(String key); void addTag(Tag tag); void removeTag(Tag tag); @Override boolean equals(Object other); @Override int hashCode(); @Override int compareTo(Node other); static final int ROOT_NODE_ID; }### Answer:
@Test public void testHashCode() { Node node1 = Node.builder().uniqueId("unique").nodeType(NodeType.FOLDER).build(); Node node2 = Node.builder().uniqueId("unique").nodeType(NodeType.CONFIGURATION).build(); assertNotEquals(node1.hashCode(), node2.hashCode()); } |
### Question:
Node implements Comparable<Node> { @Override public boolean equals(Object other) { if(other == null) { return false; } if(other instanceof Node) { Node otherNode = (Node)other; return nodeType.equals(otherNode.getNodeType()) && uniqueId.equals(otherNode.getUniqueId()); } return false; } void putProperty(String key, String value); void removeProperty(String key); String getProperty(String key); void addTag(Tag tag); void removeTag(Tag tag); @Override boolean equals(Object other); @Override int hashCode(); @Override int compareTo(Node other); static final int ROOT_NODE_ID; }### Answer:
@Test public void testEquals() { Node node1 = Node.builder().uniqueId("unique").nodeType(NodeType.FOLDER).build(); Node node2 = Node.builder().uniqueId("unique").nodeType(NodeType.CONFIGURATION).build(); Node node3 = Node.builder().uniqueId("unique").nodeType(NodeType.FOLDER).build(); assertFalse(node1.equals(null)); assertFalse(node1.equals(node2)); assertTrue(node1.equals(node3)); assertFalse(node1.equals(new Object())); } |
### Question:
ConfigPv implements Comparable<ConfigPv> { @Override public boolean equals(Object other) { if(other instanceof ConfigPv) { ConfigPv otherConfigPv = (ConfigPv)other; return Objects.equals(pvName, otherConfigPv.getPvName()) && Objects.equals(readbackPvName, otherConfigPv.getReadbackPvName()) && Objects.equals(readOnly, otherConfigPv.isReadOnly()); } return false; } @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); @Override int compareTo(ConfigPv other); }### Answer:
@Test public void testEquals() { ConfigPv configPV1 = ConfigPv.builder().pvName("a").readbackPvName("b").readOnly(true).build(); assertFalse(configPV1.equals(new Object())); assertFalse(configPV1.equals(null)); ConfigPv configPV2 = ConfigPv.builder().pvName("a").readbackPvName("b").readOnly(true).build(); ConfigPv configPV3 = ConfigPv.builder().pvName("a").readbackPvName("c").readOnly(true).build(); assertEquals(configPV1, configPV2); assertNotEquals(configPV1, configPV3); configPV1 = ConfigPv.builder().pvName("a").readbackPvName("b").readOnly(true).build(); configPV2 = ConfigPv.builder().pvName("b").readbackPvName("b").readOnly(true).build(); assertNotEquals(configPV1, configPV2); configPV1 = ConfigPv.builder().pvName("a").readOnly(true).build(); configPV2 = ConfigPv.builder().pvName("b").readOnly(true).build(); assertNotEquals(configPV1, configPV2); configPV1 = ConfigPv.builder().pvName("a").readOnly(true).build(); configPV2 = ConfigPv.builder().pvName("a").readOnly(true).build(); assertEquals(configPV1, configPV2); } |
### Question:
ConfigPv implements Comparable<ConfigPv> { @Override public int hashCode() { return Objects.hash(pvName, readbackPvName, readOnly); } @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); @Override int compareTo(ConfigPv other); }### Answer:
@Test public void testHashCode() { ConfigPv configPV1 = ConfigPv.builder().pvName("a").readbackPvName("b").readOnly(true).build(); ConfigPv configPV2 = ConfigPv.builder().pvName("a").readbackPvName("b").readOnly(true).build(); assertEquals(configPV1.hashCode(), configPV2.hashCode()); configPV1 = ConfigPv.builder().pvName("a").readbackPvName("b").readOnly(true).build(); configPV2 = ConfigPv.builder().pvName("b").readbackPvName("b").readOnly(true).build(); assertNotEquals(configPV1.hashCode(), configPV2.hashCode()); configPV1 = ConfigPv.builder().pvName("a").readOnly(true).build(); configPV2 = ConfigPv.builder().pvName("b").readOnly(true).build(); assertNotEquals(configPV1.hashCode(), configPV2.hashCode()); configPV1 = ConfigPv.builder().pvName("a").readOnly(true).build(); configPV2 = ConfigPv.builder().pvName("a").readOnly(true).build(); assertEquals(configPV1.hashCode(), configPV2.hashCode()); } |
### Question:
PropertyManager { public void setDesiredNumberOfFeaturesPerRunner(int desiredNumberOfFeaturesPerRunner) { this.desiredNumberOfFeaturesPerRunner = desiredNumberOfFeaturesPerRunner; } @Inject PropertyManager(final CucableLogger logger, final FileIO fileIO); String getSourceRunnerTemplateFile(); void setSourceRunnerTemplateFile(final String sourceRunnerTemplateFile); String getGeneratedRunnerDirectory(); void setGeneratedRunnerDirectory(final String generatedRunnerDirectory); List<CucableFeature> getSourceFeatures(); void setSourceFeatures(final String sourceFeatures); String getGeneratedFeatureDirectory(); void setGeneratedFeatureDirectory(final String generatedFeatureDirectory); int getNumberOfTestRuns(); void setNumberOfTestRuns(final int numberOfTestRuns); String getIncludeScenarioTags(); void setIncludeScenarioTags(final String includeScenarioTags); ParallelizationMode getParallelizationMode(); void setParallelizationMode(final String parallelizationMode); Map<String, String> getCustomPlaceholders(); void setCustomPlaceholders(final Map<String, String> customPlaceholders); int getDesiredNumberOfRunners(); void setDesiredNumberOfRunners(final int desiredNumberOfRunners); int getDesiredNumberOfFeaturesPerRunner(); void setDesiredNumberOfFeaturesPerRunner(int desiredNumberOfFeaturesPerRunner); List<String> getScenarioNames(); void setScenarioNames(final String scenarioNames); void checkForMissingMandatoryProperties(); void checkForDisallowedPropertyCombinations(); void logProperties(); boolean isCucumberFeatureListFileSource(); }### Answer:
@Test public void setDesiredNumberOfFeaturesPerRunnerTest() { propertyManager.setDesiredNumberOfFeaturesPerRunner(5); assertThat(propertyManager.getDesiredNumberOfFeaturesPerRunner(), is(5)); } |
### Question:
PropertyManager { public void setParallelizationMode(final String parallelizationMode) throws CucablePluginException { try { this.parallelizationMode = ParallelizationMode.valueOf(parallelizationMode.toUpperCase()); } catch (IllegalArgumentException e) { throw new CucablePluginException( "Unknown <parallelizationMode> '" + parallelizationMode + "'. Please use 'scenarios' or 'features'." ); } } @Inject PropertyManager(final CucableLogger logger, final FileIO fileIO); String getSourceRunnerTemplateFile(); void setSourceRunnerTemplateFile(final String sourceRunnerTemplateFile); String getGeneratedRunnerDirectory(); void setGeneratedRunnerDirectory(final String generatedRunnerDirectory); List<CucableFeature> getSourceFeatures(); void setSourceFeatures(final String sourceFeatures); String getGeneratedFeatureDirectory(); void setGeneratedFeatureDirectory(final String generatedFeatureDirectory); int getNumberOfTestRuns(); void setNumberOfTestRuns(final int numberOfTestRuns); String getIncludeScenarioTags(); void setIncludeScenarioTags(final String includeScenarioTags); ParallelizationMode getParallelizationMode(); void setParallelizationMode(final String parallelizationMode); Map<String, String> getCustomPlaceholders(); void setCustomPlaceholders(final Map<String, String> customPlaceholders); int getDesiredNumberOfRunners(); void setDesiredNumberOfRunners(final int desiredNumberOfRunners); int getDesiredNumberOfFeaturesPerRunner(); void setDesiredNumberOfFeaturesPerRunner(int desiredNumberOfFeaturesPerRunner); List<String> getScenarioNames(); void setScenarioNames(final String scenarioNames); void checkForMissingMandatoryProperties(); void checkForDisallowedPropertyCombinations(); void logProperties(); boolean isCucumberFeatureListFileSource(); }### Answer:
@Test public void wrongParallelizationModeTest() throws CucablePluginException { expectedException.expect(CucablePluginException.class); expectedException.expectMessage("Unknown <parallelizationMode> 'unknown'. Please use 'scenarios' or 'features'."); propertyManager.setParallelizationMode("unknown"); } |
### Question:
CucableLogger { public void info(final CharSequence logString, CucableLogLevel... cucableLogLevels) { log(LogLevel.INFO, logString, cucableLogLevels); } void initialize(final Log mojoLogger, final String currentLogLevel); void logInfoSeparator(final CucableLogLevel... cucableLogLevels); void info(final CharSequence logString, CucableLogLevel... cucableLogLevels); void warn(final CharSequence logString); }### Answer:
@Test public void infoTest() { logger.initialize(mockedLogger, "default"); logger.info("Test"); verify(mockedLogger, times(1)) .info("Test"); } |
### Question:
CucableLogger { public void logInfoSeparator(final CucableLogLevel... cucableLogLevels) { info("-------------------------------------", cucableLogLevels); } void initialize(final Log mojoLogger, final String currentLogLevel); void logInfoSeparator(final CucableLogLevel... cucableLogLevels); void info(final CharSequence logString, CucableLogLevel... cucableLogLevels); void warn(final CharSequence logString); }### Answer:
@Test public void logInfoSeparatorTest() { logger.initialize(mockedLogger, "default"); logger.logInfoSeparator(CucableLogger.CucableLogLevel.DEFAULT); verify(mockedLogger, times(1)) .info("-------------------------------------"); } |
### Question:
GherkinTranslations { String getScenarioKeyword(final String language) { GherkinDialect dialect; try { dialect = gherkinDialectProvider.getDialect(language, null); } catch (Exception e) { return SCENARIO; } return dialect.getScenarioKeywords().get(0); } @Inject GherkinTranslations(); }### Answer:
@Test public void getScenarioKeywordTesnt() { assertThat(gherkinTranslations.getScenarioKeyword("en"), is("Scenario")); assertThat(gherkinTranslations.getScenarioKeyword("de"), is("Szenario")); assertThat(gherkinTranslations.getScenarioKeyword("no"), is("Scenario")); assertThat(gherkinTranslations.getScenarioKeyword("ro"), is("Scenariu")); assertThat(gherkinTranslations.getScenarioKeyword("ru"), is("Сценарий")); assertThat(gherkinTranslations.getScenarioKeyword("fr"), is("Scénario")); assertThat(gherkinTranslations.getScenarioKeyword("gibberish"), is("Scenario")); } |
### Question:
GherkinDocumentParser { private String replacePlaceholderInString( final String sourceString, final Map<String, List<String>> exampleMap, final int rowIndex) { String result = sourceString; Matcher m = SCENARIO_OUTLINE_PLACEHOLDER_PATTERN.matcher(sourceString); while (m.find()) { String currentPlaceholder = m.group(0); List<String> placeholderColumn = exampleMap.get(currentPlaceholder); if (placeholderColumn != null) { result = result.replace(currentPlaceholder, placeholderColumn.get(rowIndex)); } } return result; } @Inject GherkinDocumentParser(
final GherkinToCucableConverter gherkinToCucableConverter,
final GherkinTranslations gherkinTranslations,
final PropertyManager propertyManager,
final CucableLogger logger); List<SingleScenario> getSingleScenariosFromFeature(
final String featureContent,
final String featureFilePath,
final List<Integer> scenarioLineNumbers); int matchScenarioWithScenarioNames(String language, String stringToMatch); }### Answer:
@Test public void replacePlaceholderInStringTest() throws Exception { String featureContent = "Feature: test feature 3\n" + "\n" + " Scenario Outline: This is a scenario with <key> and <value>!\n" + " Given this is a step\n" + "\n" + " Examples:\n" + " | key | value |\n" + " | 1 | one |\n"; List<SingleScenario> singleScenariosFromFeature = gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); assertThat(singleScenariosFromFeature.get(0).getScenarioName(), is("Scenario: This is a scenario with 1 and one!")); } |
### Question:
GherkinToCucableConverter { List<com.trivago.vo.Step> convertGherkinStepsToCucableSteps(final List<Step> gherkinSteps) { List<com.trivago.vo.Step> steps = new ArrayList<>(); for (Step gherkinStep : gherkinSteps) { com.trivago.vo.Step step; com.trivago.vo.DataTable dataTable = null; String docString = null; Node argument = gherkinStep.getArgument(); if (argument instanceof DataTable) { dataTable = convertGherkinDataTableToCucableDataTable((DataTable) argument); } else if (argument instanceof DocString) { docString = ((DocString) argument).getContent(); } String keywordAndName = gherkinStep.getKeyword().concat(gherkinStep.getText()); step = new com.trivago.vo.Step(keywordAndName, dataTable, docString); steps.add(step); } return steps; } }### Answer:
@Test public void convertGherkinStepsToCucableStepsTest() { List<Step> gherkinSteps = Arrays.asList( new Step(new Location(1, 1), "Given ", "this is a test step", null), new Step(new Location(2, 1), "Then ", "I get a test result", null) ); List<com.trivago.vo.Step> steps = gherkinToCucableConverter.convertGherkinStepsToCucableSteps(gherkinSteps); assertThat(steps.size(), is(gherkinSteps.size())); com.trivago.vo.Step firstStep = steps.get(0); assertThat(firstStep.getName(), is("Given this is a test step")); com.trivago.vo.Step secondStep = steps.get(1); assertThat(secondStep.getName(), is("Then I get a test result")); } |
### Question:
FeatureFileContentRenderer { private String formatDataTableString(final DataTable dataTable) { if (dataTable == null) { return ""; } char dataTableSeparator = '|'; StringBuilder dataTableStringBuilder = new StringBuilder(); for (List<String> rowValues : dataTable.getRows()) { dataTableStringBuilder.append(dataTableSeparator); for (String rowValue : rowValues) { dataTableStringBuilder.append(rowValue).append(dataTableSeparator); } dataTableStringBuilder.append(LINE_SEPARATOR); } return dataTableStringBuilder.toString(); } }### Answer:
@Test public void formatDataTableStringTest() { String expectedOutput = "Feature: featureName\n" + "featureDescription\n" + "\n" + "Scenario: scenarioName\n" + "scenarioDescription\n" + "Step 1\n" + "|cell11|cell12|cell13|\n" + "|cell21|cell22|cell23|\n" + "\n# Source feature: TESTPATH\n" + "# Generated by Cucable\n"; String featureName = "Feature: featureName"; String featureLanguage = ""; String featureDescription = "featureDescription"; String scenarioName = "Scenario: scenarioName"; String scenarioDescription = "scenarioDescription"; DataTable dataTable = new DataTable(); dataTable.addRow(Arrays.asList("cell11", "cell12", "cell13")); dataTable.addRow(Arrays.asList("cell21", "cell22", "cell23")); List<Step> steps = Collections.singletonList(new Step("Step 1", dataTable, null)); String featureFilePath = "TESTPATH"; SingleScenario singleScenario = new SingleScenario(featureName, featureFilePath, featureLanguage, featureDescription, scenarioName, scenarioDescription, new ArrayList<>(), new ArrayList<>()); singleScenario.setSteps(steps); String renderedFeatureFileContent = featureFileContentRenderer.getRenderedFeatureFileContent(singleScenario); renderedFeatureFileContent = renderedFeatureFileContent.replaceAll("\\r\\n", "\n"); assertThat(renderedFeatureFileContent, is(expectedOutput)); } |
### Question:
FeatureFileContentRenderer { private String formatDocString(final String docString) { if (docString == null || docString.isEmpty()) { return ""; } return "\"\"\"" + LINE_SEPARATOR + docString + LINE_SEPARATOR + "\"\"\"" + LINE_SEPARATOR; } }### Answer:
@Test public void formatDocStringTest() { String expectedOutput = "Feature: featureName\n" + "\n" + "Scenario: scenarioName\n" + "Step 1\n" + "\"\"\"\n" + "DOCSTRING LINE 1\n" + "DOCSTRING LINE 2\n" + "\"\"\"\n" + "\n# Source feature: TESTPATH\n" + "# Generated by Cucable\n"; String featureName = "Feature: featureName"; String scenarioName = "Scenario: scenarioName"; List<Step> steps = Collections.singletonList(new Step("Step 1", null, "DOCSTRING LINE 1\nDOCSTRING LINE 2")); String featureFilePath = "TESTPATH"; SingleScenario singleScenario = new SingleScenario(featureName, featureFilePath, null, null, scenarioName, null, new ArrayList<>(), new ArrayList<>()); singleScenario.setSteps(steps); String renderedFeatureFileContent = featureFileContentRenderer.getRenderedFeatureFileContent(singleScenario); renderedFeatureFileContent = renderedFeatureFileContent.replaceAll("\\r\\n", "\n"); assertThat(renderedFeatureFileContent, is(expectedOutput)); } |
### Question:
CucablePlugin extends AbstractMojo { public void execute() throws CucablePluginException { logger.initialize(getLog(), logLevel); propertyManager.setSourceRunnerTemplateFile(sourceRunnerTemplateFile); propertyManager.setGeneratedRunnerDirectory(generatedRunnerDirectory); propertyManager.setSourceFeatures(sourceFeatures); propertyManager.setGeneratedFeatureDirectory(generatedFeatureDirectory); propertyManager.setNumberOfTestRuns(numberOfTestRuns); propertyManager.setIncludeScenarioTags(includeScenarioTags); propertyManager.setParallelizationMode(parallelizationMode); propertyManager.setCustomPlaceholders(customPlaceholders); propertyManager.setDesiredNumberOfRunners(desiredNumberOfRunners); propertyManager.setDesiredNumberOfFeaturesPerRunner(desiredNumberOfFeaturesPerRunner); propertyManager.setScenarioNames(scenarioNames); propertyManager.checkForMissingMandatoryProperties(); propertyManager.checkForDisallowedPropertyCombinations(); logPluginInformationHeader(); propertyManager.logProperties(); fileManager.prepareGeneratedFeatureAndRunnerDirectories(); featureFileConverter.generateParallelizableFeatures(propertyManager.getSourceFeatures()); } @Inject CucablePlugin(
PropertyManager propertyManager,
FileSystemManager fileManager,
FeatureFileConverter featureFileConverter,
CucableLogger logger
); void execute(); }### Answer:
@Test public void logInvocationTest() throws Exception { cucablePlugin.execute(); verify(logger, times(1)).initialize(mojoLogger, "default"); verify(logger, times(1)).info(anyString(), any(CucableLogger.CucableLogLevel.class)); verify(logger, times(2)).logInfoSeparator(any(CucableLogger.CucableLogLevel.class)); } |
### Question:
FileIO { public void writeContentToFile(String content, String filePath) throws FileCreationException { try { FileUtils.fileWrite(filePath, "UTF-8", content); } catch (IOException e) { throw new FileCreationException(filePath); } } void writeContentToFile(String content, String filePath); String readContentFromFile(String filePath); }### Answer:
@Test(expected = FileCreationException.class) public void writeToInvalidFileTest() throws Exception { fileIO.writeContentToFile(null, ""); } |
### Question:
FileIO { public String readContentFromFile(String filePath) throws MissingFileException { try { return FileUtils.fileRead(filePath, "UTF-8"); } catch (IOException e) { throw new MissingFileException(filePath); } } void writeContentToFile(String content, String filePath); String readContentFromFile(String filePath); }### Answer:
@Test(expected = MissingFileException.class) public void readFromMissingFileTest() throws Exception { String wrongPath = testFolder.getRoot().getPath().concat("/missing.tmp"); fileIO.readContentFromFile(wrongPath); } |
### Question:
FileSystemManager { public void prepareGeneratedFeatureAndRunnerDirectories() throws CucablePluginException { createDirIfNotExists(propertyManager.getGeneratedFeatureDirectory()); removeFilesFromPath(propertyManager.getGeneratedFeatureDirectory(), "feature"); createDirIfNotExists(propertyManager.getGeneratedRunnerDirectory()); removeFilesFromPath(propertyManager.getGeneratedRunnerDirectory(), "java"); } @Inject FileSystemManager(PropertyManager propertyManager); List<Path> getPathsFromCucableFeature(final CucableFeature cucableFeature); void prepareGeneratedFeatureAndRunnerDirectories(); }### Answer:
@Test(expected = PathCreationException.class) public void prepareGeneratedFeatureAndRunnerDirsMissingFeatureDirTest() throws Exception { when(propertyManager.getGeneratedFeatureDirectory()).thenReturn(""); fileSystemManager.prepareGeneratedFeatureAndRunnerDirectories(); }
@Test(expected = PathCreationException.class) public void prepareGeneratedFeatureAndRunnerDirsMissingRunnerDirTest() throws Exception { String featurePath = testFolder.getRoot().getPath().concat("/featureDir"); when(propertyManager.getGeneratedFeatureDirectory()).thenReturn(featurePath); when(propertyManager.getGeneratedRunnerDirectory()).thenReturn(""); fileSystemManager.prepareGeneratedFeatureAndRunnerDirectories(); }
@Test public void prepareGeneratedFeatureAndRunnerDirsTest() throws Exception { String featurePath = testFolder.getRoot().getPath().concat("/featureDir"); String runnerPath = testFolder.getRoot().getPath().concat("/runnerDir"); when(propertyManager.getGeneratedFeatureDirectory()).thenReturn(featurePath); when(propertyManager.getGeneratedRunnerDirectory()).thenReturn(runnerPath); fileSystemManager.prepareGeneratedFeatureAndRunnerDirectories(); } |
### Question:
PropertyManager { public void setGeneratedRunnerDirectory(final String generatedRunnerDirectory) { this.generatedRunnerDirectory = generatedRunnerDirectory; } @Inject PropertyManager(final CucableLogger logger, final FileIO fileIO); String getSourceRunnerTemplateFile(); void setSourceRunnerTemplateFile(final String sourceRunnerTemplateFile); String getGeneratedRunnerDirectory(); void setGeneratedRunnerDirectory(final String generatedRunnerDirectory); List<CucableFeature> getSourceFeatures(); void setSourceFeatures(final String sourceFeatures); String getGeneratedFeatureDirectory(); void setGeneratedFeatureDirectory(final String generatedFeatureDirectory); int getNumberOfTestRuns(); void setNumberOfTestRuns(final int numberOfTestRuns); String getIncludeScenarioTags(); void setIncludeScenarioTags(final String includeScenarioTags); ParallelizationMode getParallelizationMode(); void setParallelizationMode(final String parallelizationMode); Map<String, String> getCustomPlaceholders(); void setCustomPlaceholders(final Map<String, String> customPlaceholders); int getDesiredNumberOfRunners(); void setDesiredNumberOfRunners(final int desiredNumberOfRunners); int getDesiredNumberOfFeaturesPerRunner(); void setDesiredNumberOfFeaturesPerRunner(int desiredNumberOfFeaturesPerRunner); List<String> getScenarioNames(); void setScenarioNames(final String scenarioNames); void checkForMissingMandatoryProperties(); void checkForDisallowedPropertyCombinations(); void logProperties(); boolean isCucumberFeatureListFileSource(); }### Answer:
@Test public void setGeneratedRunnerDirectoryTest() { propertyManager.setGeneratedRunnerDirectory("test"); assertThat(propertyManager.getGeneratedRunnerDirectory(), is("test")); } |
### Question:
PropertyManager { public void setGeneratedFeatureDirectory(final String generatedFeatureDirectory) { this.generatedFeatureDirectory = generatedFeatureDirectory; } @Inject PropertyManager(final CucableLogger logger, final FileIO fileIO); String getSourceRunnerTemplateFile(); void setSourceRunnerTemplateFile(final String sourceRunnerTemplateFile); String getGeneratedRunnerDirectory(); void setGeneratedRunnerDirectory(final String generatedRunnerDirectory); List<CucableFeature> getSourceFeatures(); void setSourceFeatures(final String sourceFeatures); String getGeneratedFeatureDirectory(); void setGeneratedFeatureDirectory(final String generatedFeatureDirectory); int getNumberOfTestRuns(); void setNumberOfTestRuns(final int numberOfTestRuns); String getIncludeScenarioTags(); void setIncludeScenarioTags(final String includeScenarioTags); ParallelizationMode getParallelizationMode(); void setParallelizationMode(final String parallelizationMode); Map<String, String> getCustomPlaceholders(); void setCustomPlaceholders(final Map<String, String> customPlaceholders); int getDesiredNumberOfRunners(); void setDesiredNumberOfRunners(final int desiredNumberOfRunners); int getDesiredNumberOfFeaturesPerRunner(); void setDesiredNumberOfFeaturesPerRunner(int desiredNumberOfFeaturesPerRunner); List<String> getScenarioNames(); void setScenarioNames(final String scenarioNames); void checkForMissingMandatoryProperties(); void checkForDisallowedPropertyCombinations(); void logProperties(); boolean isCucumberFeatureListFileSource(); }### Answer:
@Test public void setGeneratedFeatureDirectoryTest() { propertyManager.setGeneratedFeatureDirectory("test"); assertThat(propertyManager.getGeneratedFeatureDirectory(), is("test")); } |
### Question:
PropertyManager { public void setDesiredNumberOfRunners(final int desiredNumberOfRunners) { this.desiredNumberOfRunners = desiredNumberOfRunners; } @Inject PropertyManager(final CucableLogger logger, final FileIO fileIO); String getSourceRunnerTemplateFile(); void setSourceRunnerTemplateFile(final String sourceRunnerTemplateFile); String getGeneratedRunnerDirectory(); void setGeneratedRunnerDirectory(final String generatedRunnerDirectory); List<CucableFeature> getSourceFeatures(); void setSourceFeatures(final String sourceFeatures); String getGeneratedFeatureDirectory(); void setGeneratedFeatureDirectory(final String generatedFeatureDirectory); int getNumberOfTestRuns(); void setNumberOfTestRuns(final int numberOfTestRuns); String getIncludeScenarioTags(); void setIncludeScenarioTags(final String includeScenarioTags); ParallelizationMode getParallelizationMode(); void setParallelizationMode(final String parallelizationMode); Map<String, String> getCustomPlaceholders(); void setCustomPlaceholders(final Map<String, String> customPlaceholders); int getDesiredNumberOfRunners(); void setDesiredNumberOfRunners(final int desiredNumberOfRunners); int getDesiredNumberOfFeaturesPerRunner(); void setDesiredNumberOfFeaturesPerRunner(int desiredNumberOfFeaturesPerRunner); List<String> getScenarioNames(); void setScenarioNames(final String scenarioNames); void checkForMissingMandatoryProperties(); void checkForDisallowedPropertyCombinations(); void logProperties(); boolean isCucumberFeatureListFileSource(); }### Answer:
@Test public void setDesiredNumberOfRunnersTest() { propertyManager.setDesiredNumberOfRunners(12); assertThat(propertyManager.getDesiredNumberOfRunners(), is(12)); } |
### Question:
LineServerManager { public static void manage(String line, final LineListener lineListener) { if (isNotRunningAlready() && isSurefirePluginStarting(line)) { server = new LineServer(PORT); server.addListener(lineListener); server.start(); running.set(true); } else if (isRunning() && isBuildFinished(line)) { server.stop(); running.set(false); server = null; } } static void manage(String line, final LineListener lineListener); static boolean enabled; }### Answer:
@Test public void shouldNotTryAndProcessingAnyThingIfTheBuildFailsBeforeSurefireEvenBegins() { manage(buildFailure(), lineProcessor); assertTrue(canNotConnectToServer()); }
@Test public void shouldShutdownTheServerWhenTheBuildFails() { manage(surefire(), lineProcessor); manage(buildFailure(), lineProcessor); assertTrue(canNotConnectToServer()); }
@Test public void shouldShutdownTheServerWhenTheBuildIsASuccess() { manage(surefire(), lineProcessor); manage(buildSuccess(), lineProcessor); assertTrue(canNotConnectToServer()); }
@Test public void shouldNotBlowUpTryingToStartTheServerAgainIfTheSurefireIsRanAgain() { manage(surefire(), lineProcessor); manage(surefire(), lineProcessor); }
@Test public void shouldNotKillTheServerIfTheSurefireIsRanAgain() { manage(surefire(), lineProcessor); manage(surefire(), lineProcessor); assertTrue(canConnectToServer()); }
@Test public void shouldStartTheServerWhenTheSurefirePluginIsAboutToStart() { manage(surefire(), lineProcessor); assertTrue(canConnectToServer()); }
@Test public void shouldNotStartForJustAnyPluginStarting() { manage(plugin("some-other-plugin"), lineProcessor); assertTrue(canNotConnectToServer()); } |
### Question:
RemoveLogLevelFilter implements LogEntryFilter { @Override public String filter(Context context) { if (context.config.isRemoveLogLevel()) { String text = context.entryText; text = text.replace("[" + context.logLevel + "] ", ""); text = text.replace("[" + context.logLevel.toLowerCase() + "] ", ""); return text; } return context.entryText; } @Override String filter(Context context); }### Answer:
@Test public void shouldNotCareAboutCase() { assertEquals("", filter.filter(context("info", true, MockLogLevel.INFO.name()))); }
@Test public void removeLeadingScopeText() { for (MockLogLevel level : MockLogLevel.values()) { assertEquals("", filter.filter(context(true, level.name()))); } }
@Test public void doNotThingWithTheFlagIsFalse() { for (MockLogLevel level : MockLogLevel.values()) { assertEquals("[" + level.name() + "] ", filter.filter(context(false, level.name()))); } } |
### Question:
AddTimestampFilter implements LogEntryFilter { @Override public String filter(Context context) { StringBuilder builder = new StringBuilder(); if (isPatternProvided(context)) { builder.append(formatter(context).format(new Date())); builder.append(" "); } builder.append(context.entryText); return builder.toString(); } @Override String filter(Context context); }### Answer:
@Test public void patternProvided() { SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy"); assertEquals(format.format(new Date()) + " entry", filter.filter(context("entry", "MM/dd/yyyy"))); }
@Test public void noDatePatternProvided() { assertEquals("entry", filter.filter(context("entry", " "))); } |
### Question:
Slf4jLogLevel { public static String toString(int level) { String text = ""; switch (level) { case LocationAwareLogger.TRACE_INT: text = "TRACE"; break; case LocationAwareLogger.DEBUG_INT: text = "DEBUG"; break; case LocationAwareLogger.WARN_INT: text = "WARN"; break; case LocationAwareLogger.ERROR_INT: text = "ERROR"; break; case LocationAwareLogger.INFO_INT: text = "INFO"; break; default: throw new IllegalArgumentException("Not sure what log level this is (level=" + level + ")"); } return text; } static String toString(int level); }### Answer:
@Test(expected = IllegalArgumentException.class) public void unsupportedLevel() { Slf4jLogLevel.toString(Integer.MAX_VALUE); }
@Test public void levels() { assertEquals("TRACE", Slf4jLogLevel.toString(LocationAwareLogger.TRACE_INT)); assertEquals("DEBUG", Slf4jLogLevel.toString(LocationAwareLogger.DEBUG_INT)); assertEquals("INFO", Slf4jLogLevel.toString(LocationAwareLogger.INFO_INT)); assertEquals("WARN", Slf4jLogLevel.toString(LocationAwareLogger.WARN_INT)); assertEquals("ERROR", Slf4jLogLevel.toString(LocationAwareLogger.ERROR_INT)); } |
### Question:
RedisPoolProperty { public static RedisPoolProperty initByIdFromConfig(String id){ RedisPoolProperty property = new RedisPoolProperty(); String pre = id+Configs.SEPARATE; List<String> lists = MythReflect.getFieldByClass(RedisPoolProperty.class); Map<String ,Object> map = new HashMap<>(); MythProperties config; try { config = PropertyFile.getProperties(Configs.PROPERTY_FILE); for (String field:lists){ map.put(field,config.getString(pre+field)); } property = (RedisPoolProperty) MythReflect.setFieldsValue(property,map); } catch (Exception e) { e.printStackTrace(); } return property; } static RedisPoolProperty initByIdFromConfig(String id); static void updateConfigFile(RedisPoolProperty property); @Override String toString(); }### Answer:
@Test public void testInitByIdFromConfig() throws Exception { } |
### Question:
PoolManagement { public boolean switchPool(String PoolId) { try { if (PropertyFile.getAllPoolConfig().containsKey(PoolId)) { currentPoolId = PoolId; return true; } else { return false; } } catch (ReadConfigException e) { e.printStackTrace(); return false; } } private PoolManagement(); synchronized static PoolManagement getInstance(); RedisPools getRedisPool(); RedisPools getRedisPool(String poolId); RedisPools createRedisPoolAndConnection(RedisPoolProperty property); String createRedisPool(RedisPoolProperty property); boolean checkConnection(RedisPoolProperty property); boolean switchPool(String PoolId); String deleteRedisPool(String poolId); boolean clearAllPools(); boolean destroyRedisPool(String poolId); boolean destroyRedisPool(RedisPools redisPools); ConcurrentMap<String, RedisPools> getPoolMap(); }### Answer:
@Test public void testSwitchPool() throws Exception { } |
### Question:
PoolManagement { public String deleteRedisPool(String poolId) throws IOException { try { configFile = PropertyFile.getProperties(propertyFile); String exist = configFile.getString(poolId + Configs.SEPARATE + Configs.POOL_ID); if (exist == null) { logger.error(ExceptionInfo.DELETE_POOL_NOT_EXIST + poolId); return null; } for (String key : MythReflect.getFieldByClass(RedisPoolProperty.class)) { PropertyFile.delete(poolId + Configs.SEPARATE + key); } } catch (Exception e) { logger.error(ExceptionInfo.OPEN_CONFIG_FAILED, e); return null; } logger.info(NoticeInfo.DELETE_POOL_SUCCESS + poolId, PoolManagement.class); return poolId; } private PoolManagement(); synchronized static PoolManagement getInstance(); RedisPools getRedisPool(); RedisPools getRedisPool(String poolId); RedisPools createRedisPoolAndConnection(RedisPoolProperty property); String createRedisPool(RedisPoolProperty property); boolean checkConnection(RedisPoolProperty property); boolean switchPool(String PoolId); String deleteRedisPool(String poolId); boolean clearAllPools(); boolean destroyRedisPool(String poolId); boolean destroyRedisPool(RedisPools redisPools); ConcurrentMap<String, RedisPools> getPoolMap(); }### Answer:
@Test public void testDeleteRedisPool() throws Exception { String id = null; String result = poolManagement.deleteRedisPool(id); Assert.assertEquals(id, result); } |
### Question:
PoolManagement { public boolean clearAllPools() throws Exception { int maxId = PropertyFile.getMaxId(); for (int i = Configs.START_ID; i <= maxId; i++) { String result = deleteRedisPool(i + ""); if (result != null) { logger.info(NoticeInfo.DELETE_POOL_SUCCESS + i); } else { logger.info(NoticeInfo.DELETE_POOL_FAILED + i); } } return true; } private PoolManagement(); synchronized static PoolManagement getInstance(); RedisPools getRedisPool(); RedisPools getRedisPool(String poolId); RedisPools createRedisPoolAndConnection(RedisPoolProperty property); String createRedisPool(RedisPoolProperty property); boolean checkConnection(RedisPoolProperty property); boolean switchPool(String PoolId); String deleteRedisPool(String poolId); boolean clearAllPools(); boolean destroyRedisPool(String poolId); boolean destroyRedisPool(RedisPools redisPools); ConcurrentMap<String, RedisPools> getPoolMap(); }### Answer:
@Test public void testClearAllPools() throws Exception { } |
### Question:
PoolManagement { public boolean destroyRedisPool(String poolId) { if (poolMap.containsKey(poolId)) { boolean flag = poolMap.get(poolId).destroyPool(); poolMap.remove(poolId); return flag; } else { return false; } } private PoolManagement(); synchronized static PoolManagement getInstance(); RedisPools getRedisPool(); RedisPools getRedisPool(String poolId); RedisPools createRedisPoolAndConnection(RedisPoolProperty property); String createRedisPool(RedisPoolProperty property); boolean checkConnection(RedisPoolProperty property); boolean switchPool(String PoolId); String deleteRedisPool(String poolId); boolean clearAllPools(); boolean destroyRedisPool(String poolId); boolean destroyRedisPool(RedisPools redisPools); ConcurrentMap<String, RedisPools> getPoolMap(); }### Answer:
@Test public void testDestroyRedisPool() throws Exception { boolean result = poolManagement.destroyRedisPool("1292"); Assert.assertEquals(false, result); } |
### Question:
MythReflect { public static List<String> getFieldsByInstance(Object object) throws IllegalAccessException { target = object.getClass(); return getFieldByClass(target); } static List<String> getFieldsByInstance(Object object); static List<String> getFieldByClass(Class targets); static Map<String, Object> getFieldsValue(Object object); static Object setFieldsValue(Object object, Map<String, Object> maps); }### Answer:
@Test public void testGetFieldsByInstance() throws Exception { Target target = new Target(); List<String> result = MythReflect.getFieldsByInstance(target); Assert.assertEquals(Collections.<String>singletonList("name"), result); } |
### Question:
MythReflect { public static List<String> getFieldByClass(Class targets) { target = targets; List<String> list = new ArrayList<>(); Field[] fields = target.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); String name = field.getName(); list.add(name); } return list; } static List<String> getFieldsByInstance(Object object); static List<String> getFieldByClass(Class targets); static Map<String, Object> getFieldsValue(Object object); static Object setFieldsValue(Object object, Map<String, Object> maps); }### Answer:
@Test public void testGetFieldByClass() throws Exception { List<String> result = MythReflect.getFieldByClass(Target.class); Assert.assertEquals(Collections.<String>singletonList("name"), result); } |
### Question:
MythReflect { public static Map<String, Object> getFieldsValue(Object object) throws IllegalAccessException { Map<String, Object> map = new HashMap<>(); target = object.getClass(); for (Field field : target.getDeclaredFields()) { field.setAccessible(true); Object value = field.get(object); String name = field.getName(); map.put(name, value); } return map; } static List<String> getFieldsByInstance(Object object); static List<String> getFieldByClass(Class targets); static Map<String, Object> getFieldsValue(Object object); static Object setFieldsValue(Object object, Map<String, Object> maps); }### Answer:
@Test public void testGetFieldsValue() throws Exception { Target target = new Target(); target.setName("myth"); Map<String, Object> result = MythReflect.getFieldsValue(target); Assert.assertEquals(new HashMap<String, Object>() {{ put("name", "myth"); }}, result); } |
### Question:
MythReflect { public static Object setFieldsValue(Object object, Map<String, Object> maps) throws Exception { target = object.getClass(); try { for (Field field : target.getDeclaredFields()) { field.setAccessible(true); String type = field.getType().getName(); switch (type) { case "java.lang.Integer": field.set(object, Integer.parseInt(maps.get(field.getName()).toString())); break; case "java.lang.String": field.set(object, maps.get(field.getName())); break; case "boolean": field.set(object, "true".equals(maps.get(field.getName()).toString())); break; } } } catch (Exception e) { throw new TypeErrorException(ExceptionInfo.TYPE_ERROR, e, MythReflect.class); } return object; } static List<String> getFieldsByInstance(Object object); static List<String> getFieldByClass(Class targets); static Map<String, Object> getFieldsValue(Object object); static Object setFieldsValue(Object object, Map<String, Object> maps); }### Answer:
@Test public void testSetFieldsValue() throws Exception { Target target = new Target(); Target result = (Target) MythReflect.setFieldsValue(target, new HashMap<String, Object>() {{ put("name", "myth"); }}); Assert.assertEquals("myth", result.getName()); } |
### Question:
MythTime { public static String getTime() { Date date = new Date(); simpleDateFormat = new SimpleDateFormat("HH:mm:ss:MM"); return simpleDateFormat.format(date); } static String getTime(); static String getDateTime(); static String getDate(); }### Answer:
@Test public void getTime() throws Exception { System.out.println(MythTime.getTime()); } |
### Question:
MythTime { public static String getDateTime() { Date date = new Date(); simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:MM"); return simpleDateFormat.format(date); } static String getTime(); static String getDateTime(); static String getDate(); }### Answer:
@Test public void getDateTime() throws Exception { System.out.println(MythTime.getDateTime()); } |
### Question:
PropertyFile { public static String save(String key, String value) throws ReadConfigException { String result; try { getFromFile(); result = (String)props.setProperty(key, value); props.store(fos, "Update '" + key + "' value"); } catch (IOException e) { e.printStackTrace(); throw new ReadConfigException(ExceptionInfo.SAVE_CONFIG__KEY_FAILED,e,PropertyFile.class); } return result; } static MythProperties getProperties(String propertyFile); static String save(String key, String value); static String delete(String key); static String update(String key,String value); static int getMaxId(); static Map<String,RedisPoolProperty> getAllPoolConfig(); }### Answer:
@Test public void testSave() throws Exception { PropertyFile.delete(testKey); String result = PropertyFile.save(testKey, "value"); PropertyFile.delete(testKey); Assert.assertEquals(null, result); } |
### Question:
MythTime { public static String getDate() { Date date = new Date(); simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); return simpleDateFormat.format(date); } static String getTime(); static String getDateTime(); static String getDate(); }### Answer:
@Test public void testDate(){ System.out.println(MythTime.getDate()); } |
### Question:
RedisList extends Commands { public long rPush(String key, String... values) { return getJedis().rpush(key, values); } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer:
@Test public void testRPush() throws Exception { redisList.deleteKey(testKey); redisList.rPush(testKey, "values"); redisList.rPush(testKey, "values"); redisList.rPush(testKey, "values"); redisList.rPush(testKey, "values"); redisList.rPush(testKey, "values"); long result = redisList.rPush(testKey, "values"); Assert.assertEquals(6L, result); }
@Test public void testType() throws Exception { deleteKeyForTest(); redisList.rPush(testKey,"er"); String result = redisList.type(testKey); Assert.assertEquals("list", result); deleteKeyForTest(); } |
### Question:
RedisList extends Commands { public long lPush(String key, String... values) { return getJedis().lpush(key, values); } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer:
@Test public void testLPush() throws Exception { redisList.deleteKey(testKey); long result = redisList.lPush(testKey, "values"); Assert.assertEquals(1L, result); } |
### Question:
RedisList extends Commands { public long lPushX(String key, String... value) { return getJedis().lpushx(key, value); } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer:
@Test public void testLPushX() throws Exception { redisList.deleteKey(testKey); long result = redisList.lPushX(testKey, "value"); Assert.assertEquals(0L, result); } |
### Question:
RedisList extends Commands { public long rPushX(String key, String... value) { return getJedis().rpushx(key, value); } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer:
@Test public void testRPushX() throws Exception { deleteKeyForTest(); long result = redisList.rPushX(testKey, "value"); Assert.assertEquals(0L, result); } |
### Question:
RedisList extends Commands { public String rPop(String key) { return getJedis().rpop(key); } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer:
@Test public void testRPop() throws Exception { deleteKeyForTest(); redisList.rPush(testKey,"1","2"); String result = redisList.rPop(testKey); Assert.assertEquals("2", result); deleteKeyForTest(); } |
### Question:
RedisList extends Commands { public String lPop(String key) { return getJedis().lpop(key); } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer:
@Test public void testLPop() throws Exception { redisList.deleteKey(testKey); String result = redisList.lPop(testKey); Assert.assertEquals(null, result); } |
### Question:
RedisList extends Commands { public String rPopLPush(String one, String other) { return getJedis().rpoplpush(one, other); } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer:
@Test public void testRPopLPush() throws Exception { redisList.deleteKey("one"); redisList.deleteKey("other"); redisList.rPush("one","1"); redisList.rPush("other","2"); Assert.assertEquals("1",redisList.rPopLPush("one", "other")); Assert.assertEquals(null,redisList.rPopLPush("one", "other")); redisList.deleteKey("one"); redisList.deleteKey("other"); } |
### Question:
RedisList extends Commands { public long length(String key) { return getJedis().llen(key); } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer:
@Test public void testLength() throws Exception { deleteKeyForTest(); redisList.rPush(testKey,"1"); redisList.lPush(testKey,"2"); long result = redisList.length(testKey); Assert.assertEquals(2L, result); deleteKeyForTest(); } |
### Question:
RedisList extends Commands { public String setByIndex(String key, long index, String value) throws ActionErrorException { String result; try { result = getJedis().lset(key, index, value); return result; } catch (Exception e) { throw new ActionErrorException(ExceptionInfo.KEY_NOT_EXIST, e, RedisList.class); } } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer:
@Test public void testSetByIndex() throws Exception { redisList.lPush(testKey,"12"); String result = redisList.setByIndex(testKey, 0L, "value"); Assert.assertEquals("OK", result); deleteKeyForTest(); } |
### Question:
PropertyFile { public static String delete(String key) throws ReadConfigException { String result; try { getFromFile(); result = (String) props.remove(key); props.store(fos, "Delete '" + key + "' value"); }catch (Exception e){ e.printStackTrace(); throw new ReadConfigException(ExceptionInfo.DELETE_CONFIG_KEY_FAILED,e,PropertyFile.class); } return result; } static MythProperties getProperties(String propertyFile); static String save(String key, String value); static String delete(String key); static String update(String key,String value); static int getMaxId(); static Map<String,RedisPoolProperty> getAllPoolConfig(); }### Answer:
@Test public void testDelete() throws Exception { String result = PropertyFile.delete(testKey); Assert.assertEquals(null, result); } |
### Question:
RedisList extends Commands { public long insertAfter(String key, String pivot, String value) { return getJedis().linsert(key, BinaryClient.LIST_POSITION.AFTER, pivot, value); } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer:
@Test public void testInsertAfter() throws Exception { deleteKeyForTest(); redisList.lPush(testKey,"12"); long result = redisList.insertAfter(testKey, "12", "value"); Assert.assertEquals(2L, result); deleteKeyForTest(); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.