src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
ElementAtNumberFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { boolean isStringArray = args[0] instanceof VStringArray; if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray numberArray = (VNumberArray)args[0]; int index = ((VNumber)arg...
@Test public void computeString() throws Exception{ ElementAtNumberFunction elementAtNumberFunction = new ElementAtNumberFunction(); VType index = VDouble.of(2.0, Alarm.none(), Time.now(), Display.none()); VType array = VStringArray.of(List.of("a", "b", "c")); VString vString = (VString) elementAtNumberFunction.compute...
ArrayOfFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(args[0] instanceof VString){ List<String> data = new ArrayList<>(); for (Object arg : args) { if(arg == null){ data.add(null); } else { data.add(((VString)arg).getValue()); } } return VStringArray.of(data, Alarm.none(), Time....
@Test public void compute() { ArrayOfFunction arrayOfFunction = new ArrayOfFunction(); assertEquals("arrayOf", arrayOfFunction.getName()); assertEquals("array", arrayOfFunction.getCategory()); VString a = VString.of("a", Alarm.none(), Time.now()); VString b = VString.of("b", Alarm.none(), Time.now()); VString c = VStri...
ArrayDivisionFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { if(VTypeHelper.isNumericArray(args[0]) && VTypeHelper.isNumericArray(args[1])){ VNumberArray array1 = (VNumberArray)args[0]; VNumberArray array2 = (VNumberArray)args[1]; if(array1.getData().size() != array...
@Test public void compute() throws Exception{ ArrayDivisionFunction arrayDivisionFunction = new ArrayDivisionFunction(); assertEquals("arrayDiv", arrayDivisionFunction.getName()); assertEquals("array", arrayDivisionFunction.getCategory()); VType array1 = VNumberArray.of(ArrayDouble.of(2.0, 10.0, 30.0), Alarm.none(), Ti...
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 createNo...
@Test public void testGetFullPath(){ when(nodeDAO.getFullPath("nodeId")).thenReturn("/a/b/c"); assertEquals("/a/b/c", nodeDAO.getFullPath("nodeId")); }
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; } } ...
@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(...
ArrayMultiplicationFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { if(args[0] instanceof VNumberArray && args[1] instanceof VNumberArray){ VNumberArray array1 = (VNumberArray)args[0]; VNumberArray array2 = (VNumberArray)args[1]; if(array1.getData().size() != array2....
@Test public void compute() throws Exception{ ArrayMultiplicationFunction arrayMultiplicationFunction = new ArrayMultiplicationFunction(); assertEquals("arrayMult", arrayMultiplicationFunction.getName()); assertEquals("array", arrayMultiplicationFunction.getCategory()); VType array1 = VNumberArray.of(ArrayDouble.of(1.0...
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( ...
@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(...
ScaleArrayFormulaFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception{ if(args.length != 2 && args.length != 3){ throw new Exception(String.format("Function %s takes 2 or 3 aruments, got %d", getName(), args.length)); } if(VTypeHelper.isNumericArray(args[0])){ VNumberArray...
@Test public void compute() throws Exception{ ScaleArrayFormulaFunction scaleArray = new ScaleArrayFormulaFunction(); assertEquals("scale", scaleArray.getName()); assertEquals("array", scaleArray.getCategory()); VType factor = VDouble.of(2.0, Alarm.none(), Time.now(), Display.none()); VType array = VNumberArray.of(Arra...
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(...
@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());...
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(...
@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...
SnapshotDataConverter { protected static SnapshotPvDataType getDataType(VType vType) { if(vType instanceof VNumber) { VNumber vNumber = (VNumber)vType; Class<?> clazz = vNumber.getValue().getClass(); if(clazz.equals(Byte.class)) { return SnapshotPvDataType.BYTE; } else if(clazz.equals(UByte.class)) { return SnapshotPvD...
@Test public void testGetDataType() { VByte vByte = VByte.of(new Byte((byte) 1), alarm, time, display); assertEquals(SnapshotPvDataType.BYTE, SnapshotDataConverter.getDataType(vByte)); VUByte vUByte = VUByte.of(new UByte((byte) 1), alarm, time, display); assertEquals(SnapshotPvDataType.UBYTE, SnapshotDataConverter.getD...
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.getD...
@Test public void compute() { ArrayInverseScalarDivisionFunction arrayScalarDivisionFunction = new ArrayInverseScalarDivisionFunction(); assertEquals("arrayDivScalarInv", arrayScalarDivisionFunction.getName()); assertEquals("array", arrayScalarDivisionFunction.getCategory()); VType array = VNumberArray.of(ArrayDouble.o...
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().d...
@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(...
HistogramOfFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if (VTypeHelper.isNumericArray(args[0])) { VNumberArray numberArray = (VNumberArray) args[0]; if (numberArray == null) { return null; } VNumberArray previousValue = null; VNumberArray previousResult = null; Range previousXRa...
@Test public void compute() { HistogramOfFunction function = new HistogramOfFunction(); assertEquals("histogramOf", function.getName()); assertEquals("array", function.getCategory()); double[] data = new double[1000]; for(int i = 0; i < 1000; i++){ data[i] = 1.0 * i; } VDoubleArray vDoubleArray = VDoubleArray.of(ArrayD...
SubArrayFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { VNumber fromIndex = (VNumber) args[1]; VNumber toIndex = (VNumber) args[2]; if(VTypeHelper.isNumericArray(args[0])){ VNumberArray array = (VNumberArray)args[0]; if(fromIndex.getValue().intValue() < 0 || (fromIn...
@Test public void compute() throws Exception{ SubArrayFunction subArrayFunction = new SubArrayFunction(); assertEquals("subArray", subArrayFunction.getName()); assertEquals("array", subArrayFunction.getCategory()); VType array = VNumberArray.of(ArrayDouble.of(1.0, 2.0, 3.0, 4.0, 5.0), Alarm.none(), Time.now(), Display....
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(); }
@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_ch...
VTypeHelper { final public static double toDouble(final VType value) { return toDouble(value, 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 isNume...
@Test public void testToDouble(){ VDouble doubleValue = VDouble.of(7.7, Alarm.none(), Time.now(), Display.none()); double result = VTypeHelper.toDouble(doubleValue); assertEquals(7.7, result, 0); VString stringValue = VString.of("7.7", Alarm.none(), Time.now()); result = VTypeHelper.toDouble(doubleValue); assertEquals(...
SnapshotDataConverter { public static SnapshotPv fromVType(VType vType) { SnapshotPvDataType dataType = getDataType(vType); if(vType instanceof VNumber) { VNumber vNumber = (VNumber)vType; Alarm alarm = vNumber.getAlarm(); Instant instant = vNumber.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(al...
@Test(expected = RuntimeException.class) public void testUnsupportedType() { VEnumArray vEnumArray = VEnumArray.of(ArrayInteger.of(1, 2, 3), EnumDisplay.of("a", "b", "c"), Alarm.none(), Time.now()); SnapshotDataConverter.fromVType(vEnumArray); }
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];...
@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 =...
VTypeHelper { public static String toString(final VType value) { if (value == null) { return "null"; } if (isDisconnected(value)) { return null; } if (value instanceof VNumber) { return ((VNumber) value).getValue().toString(); } if (value instanceof VEnum) { return ((VEnum) value).getValue(); } if (value instanceof VSt...
@Test public void testGetString(){ assertEquals("null", VTypeHelper.toString(null)); VTable table = VTable.of(Arrays.asList(VDouble.class), Arrays.asList("name"), Arrays.asList(ArrayDouble.of(7.7))); assertNotNull(VTypeHelper.toString(table)); VDouble vDouble = VDouble.of(7.7, Alarm.disconnected(), Time.now(), Display....
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 val...
@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(dou...
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...
@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()); a...
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); sta...
@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, VTypeHelpe...
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 toSt...
@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(); T...
VTypeHelper { public static VType transformTimestamp(final VType value, final Instant time) { if (value instanceof VDouble) { final VDouble number = (VDouble) value; return VDouble.of(number.getValue().doubleValue(), number.getAlarm(), Time.of(time), number.getDisplay()); } if (value instanceof VNumber) { final VNumber...
@Test public void testTransformTimestamp(){ Instant instant = Instant.now(); VInt intValue = VInt.of(7, Alarm.none(), Time.of(Instant.EPOCH), Display.none()); intValue = (VInt)VTypeHelper.transformTimestamp(intValue, instant); assertEquals(instant, intValue.getTime().getTimestamp()); VDouble doubleValue = VDouble.of(7....
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 wri...
@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\"]", s...
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, f...
@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.l...
VTypeHelper { public static String formatArray(Array array, int maxElements) { StringBuilder builder = new StringBuilder(); builder.append(VType.typeOf(array).getSimpleName()); if (maxElements < 0) { builder.append(array.getData().toString()); return builder.toString(); } else if (maxElements == 0) { return builder.toS...
@Test public void testFormatArrayNumbersArrayZeroLength(){ ListInteger listInteger = ArrayInteger.of(); Array array = VNumberArray.of(listInteger, Alarm.none(), Time.now(), Display.none()); String string = VTypeHelper.formatArray(array, 3); assertEquals("VIntArray", string); } @Test public void testFormatArrayZeroMax()...
SnapshotDataConverter { protected static String getNumberArrayValueString(VNumberArray vNumberArray) { List<Object> valueList = new ArrayList<>(); if(vNumberArray instanceof VByteArray || vNumberArray instanceof VUByteArray || vNumberArray instanceof VShortArray || vNumberArray instanceof VUShortArray || vNumberArray i...
@Test public void testGetArrayValueString() { VNumberArray vNumberArray = VByteArray.of(CollectionNumbers.toListByte((byte) 1, (byte) 2), alarm, time, display); assertEquals("[1,2]", SnapshotDataConverter.getNumberArrayValueString(vNumberArray)); vNumberArray = VUByteArray.of(CollectionNumbers.toListUByte((byte) 1, (by...
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(); tr...
@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 = VIntA...
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....
@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...
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...
@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.cre...
SnapshotDataConverter { public static VType toVType(SnapshotPv snapshotPv) { if(snapshotPv.getValue() == null) { return null; } ObjectMapper objectMapper = new ObjectMapper(); boolean isScalar = SCALAR_AS_JSON.equals(snapshotPv.getSizes()); ListInteger sizes = toSizes(snapshotPv); Alarm alarm = toAlarm(snapshotPv); Tim...
@Test public void testToVType() { SnapshotPv snapshotPv = SnapshotPv.builder().alarmName("name").alarmStatus(AlarmStatus.NONE) .alarmSeverity(AlarmSeverity.NONE).dataType(SnapshotPvDataType.BYTE) .sizes(SnapshotDataConverter.SCALAR_AS_JSON).time(1000L).timens(7000).value("[1]").build(); VByte vByte = (VByte) SnapshotDa...
SnapshotDataConverter { public static SnapshotItem fromSnapshotPv(SnapshotPv snapshotPv, SnapshotPv readback) { if(snapshotPv == null) { return null; } SnapshotItem snapshotItem = SnapshotItem.builder() .configPv(snapshotPv.getConfigPv()) .snapshotId(snapshotPv.getSnapshotId()) .build(); if(snapshotPv.getValue() != nul...
@Test public void testFromSnapshotPv() { SnapshotPv snapshotPv = SnapshotPv.builder().alarmName("name").alarmSeverity(AlarmSeverity.NONE).alarmStatus(AlarmStatus.NONE) .snapshotId(2).dataType(SnapshotPvDataType.LONG).time(1000L).timens(7000).value("[1]").sizes("[1]").configPv(ConfigPv.builder().id(1).build()).build(); ...
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("la...
@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.getTim...
SnapshotPvRowMapper implements RowMapper<SnapshotPv> { @Override public SnapshotPv mapRow(ResultSet resultSet, int rowIndex) throws SQLException { ConfigPv configPv = new ConfigPvRowMapper().mapRow(resultSet, rowIndex); return SnapshotPv.builder() .configPv(configPv) .snapshotId(resultSet.getInt("snapshot_node_id")) .a...
@Test public void testSnapshotPvRowMapperNullReadback() throws Exception{ ResultSet resultSet = Mockito.mock(ResultSet.class); when(resultSet.getInt("snapshot_node_id")).thenReturn(1); when(resultSet.getBoolean("fetch_status")).thenReturn(true); when(resultSet.getString("severity")).thenReturn("NONE"); when(resultSet.g...
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...
@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(); obj...
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); @GetMa...
@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")...
SnapshotController extends BaseController { @PutMapping("/snapshot/{configUniqueId}") public Node saveSnapshot(@PathVariable String configUniqueId, @RequestParam(required = true) String snapshotName, @RequestParam(required = true) String userName, @RequestParam(required = true) String comment, @RequestBody(required = t...
@Test public void testSaveSnapshot() throws Exception{ Mockito.reset(services); List<SnapshotItem> snapshotItems = Arrays.asList(SnapshotItem.builder().build()); when(services.saveSnapshot(Mockito.anyString(), Mockito.argThat(new ArgumentMatcher<List<SnapshotItem>>() { @Override public boolean matches(List<SnapshotItem...
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); @Ove...
@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.getNo...
ConfigurationController extends BaseController { @GetMapping("/root") public Node getRootNode() { return services.getRootNode(); } @PutMapping("/node/{parentsUniqueId}") Node createNode(@PathVariable String parentsUniqueId, @RequestBody final Node node); @GetMapping("/node/{uniqueNodeId}") Node getNode(@PathVariable f...
@Test public void testGetRootNode() throws Exception { when(services.getRootNode()).thenReturn(rootNode); MockHttpServletRequestBuilder request = get("/root").contentType(JSON); MvcResult result = mockMvc.perform(request).andExpect(status().isOk()).andExpect(content().contentType(JSON)) .andReturn(); String s = result....
ConfigurationController extends BaseController { @PutMapping("/node/{parentsUniqueId}") public Node createNode(@PathVariable String parentsUniqueId, @RequestBody final Node node) { if(node.getUserName() == null || node.getUserName().isEmpty()) { throw new IllegalArgumentException("User name must be non-null and of non-...
@Test public void testCreateFolder() throws Exception { when(services.createNode("p", folderFromClient)).thenReturn(folderFromClient); MockHttpServletRequestBuilder request = put("/node/p").contentType(JSON) .content(objectMapper.writeValueAsString(folderFromClient)); MvcResult result = mockMvc.perform(request).andExpe...
ConfigurationController extends BaseController { @GetMapping("/node/{uniqueNodeId}/children") public List<Node> getChildNodes(@PathVariable final String uniqueNodeId) { return services.getChildNodes(uniqueNodeId); } @PutMapping("/node/{parentsUniqueId}") Node createNode(@PathVariable String parentsUniqueId, @RequestBo...
@Test public void testGetChildNodes() throws Exception{ reset(services); when(services.getChildNodes("p")).thenAnswer(new Answer<List<Node>>() { public List<Node> answer(InvocationOnMock invocation) throws Throwable { return Arrays.asList(config1); } }); MockHttpServletRequestBuilder request = get("/node/p/children").c...
ConfigurationController extends BaseController { @GetMapping("/node/{uniqueNodeId}") public Node getNode(@PathVariable final String uniqueNodeId) { return services.getNode(uniqueNodeId); } @PutMapping("/node/{parentsUniqueId}") Node createNode(@PathVariable String parentsUniqueId, @RequestBody final Node node); @GetMa...
@Test public void testGetNonExistingConfig() throws Exception { when(services.getNode("x")).thenThrow(new NodeNotFoundException("lasdfk")); MockHttpServletRequestBuilder request = get("/node/x").contentType(JSON); mockMvc.perform(request).andExpect(status().isNotFound()); } @Test public void testGetFolder() throws Exce...
ConfigurationController extends BaseController { @GetMapping("/config/{uniqueNodeId}/snapshots") public List<Node> getSnapshots(@PathVariable String uniqueNodeId) { return services.getSnapshots(uniqueNodeId); } @PutMapping("/node/{parentsUniqueId}") Node createNode(@PathVariable String parentsUniqueId, @RequestBody fi...
@Test public void testGetSnapshots() throws Exception { when(services.getSnapshots("s")).thenReturn(Arrays.asList(snapshot)); MockHttpServletRequestBuilder request = get("/config/s/snapshots").contentType(JSON); MvcResult result = mockMvc.perform(request).andExpect(status().isOk()).andExpect(content().contentType(JSON)...
ConfigurationController extends BaseController { @DeleteMapping("/node/{uniqueNodeId}") public void deleteNode(@PathVariable final String uniqueNodeId) { services.deleteNode(uniqueNodeId); } @PutMapping("/node/{parentsUniqueId}") Node createNode(@PathVariable String parentsUniqueId, @RequestBody final Node node); @Get...
@Test public void testDeleteFolder() throws Exception { MockHttpServletRequestBuilder request = delete("/node/a"); mockMvc.perform(request).andExpect(status().isOk()); doThrow(new IllegalArgumentException()).when(services).deleteNode("a"); request = delete("/node/a"); mockMvc.perform(request).andExpect(status().isBadRe...
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...
@Test public void testGetSnapshots() { services.getSnapshots(anyString()); verify(nodeDAO, times(1)).getSnapshots(anyString()); reset(nodeDAO); }
ConfigurationController extends BaseController { @PostMapping("/node/{uniqueNodeId}") public Node moveNode(@PathVariable String uniqueNodeId, @RequestParam(value = "to", required = true) String to, @RequestParam(value = "username", required = true) String userName) { return services.moveNode(uniqueNodeId, to, userName)...
@Test public void testMoveNode() throws Exception { when(services.moveNode("a", "b", "username")).thenReturn(Node.builder().id(2).uniqueId("a").build()); MockHttpServletRequestBuilder request = post("/node/a").param("to", "b").param("username", "username"); MvcResult result = mockMvc.perform(request).andExpect(status()...
ConfigurationController extends BaseController { @PostMapping("/config/{uniqueNodeId}/update") public ResponseEntity<Node> updateConfiguration(@PathVariable String uniqueNodeId, @RequestBody UpdateConfigHolder updateConfigHolder) { if(updateConfigHolder.getConfig() == null) { throw new IllegalArgumentException("Cannot ...
@Test public void testUpdateConfig() throws Exception { Node config = Node.builder().nodeType(NodeType.CONFIGURATION).userName("myusername").id(0).build(); List<ConfigPv> configPvList = Arrays.asList(ConfigPv.builder().id(1).pvName("name").build()); UpdateConfigHolder holder = UpdateConfigHolder.builder().config(config...
ConfigurationController extends BaseController { @PostMapping("/node/{uniqueNodeId}/update") public Node updateNode(@PathVariable String uniqueNodeId, @RequestParam(value = "customTimeForMigration", required = true) String customTimeForMigration, @RequestBody Node nodeToUpdate) { return services.updateNode(nodeToUpdate...
@Test public void testUpdateNode() throws Exception { Node node = Node.builder().name("foo").uniqueId("a").build(); when(services.updateNode(node, false)).thenReturn(node); MockHttpServletRequestBuilder request = post("/node/a/update") .param("customTimeForMigration", "false") .contentType(JSON) .content(objectMapper.w...
ConfigurationController extends BaseController { @GetMapping("/config/{uniqueNodeId}/items") public List<ConfigPv> getConfigPvs(@PathVariable String uniqueNodeId) { return services.getConfigPvs(uniqueNodeId); } @PutMapping("/node/{parentsUniqueId}") Node createNode(@PathVariable String parentsUniqueId, @RequestBody fi...
@Test public void testGetConfigPvs() throws Exception{ ConfigPv configPv = ConfigPv.builder() .id(1) .pvName("pvname") .build(); when(services.getConfigPvs("cpv")).thenReturn(Arrays.asList(configPv)); MockHttpServletRequestBuilder request = get("/config/cpv/items"); MvcResult result = mockMvc.perform(request).andExpect...
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(messag...
@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 = ...
ConfigurationController extends BaseController { @GetMapping("/path") public List<Node> getFromPath(@RequestParam(value = "path") String path){ List<Node> nodes = services.getFromPath(path); if(nodes == null){ throw new ResponseStatusException(HttpStatus.NOT_FOUND); } return nodes; } @PutMapping("/node/{parentsUniqueI...
@Test public void testGetFromPath() throws Exception{ when(services.getFromPath("/a/b/c")).thenReturn(null); MockHttpServletRequestBuilder request = get("/path?path=/a/b/c"); mockMvc.perform(request).andExpect(status().isNotFound()); request = get("/path"); mockMvc.perform(request).andExpect(status().isBadRequest()); N...
ConfigurationController extends BaseController { @GetMapping("/path/{uniqueNodeId}") public String getFullPath(@PathVariable String uniqueNodeId){ String fullPath = services.getFullPath(uniqueNodeId); if(fullPath == null){ throw new ResponseStatusException(HttpStatus.NOT_FOUND); } return fullPath; } @PutMapping("/node...
@Test public void testGetFullPath() throws Exception{ when(services.getFullPath("nonexisting")).thenReturn(null); MockHttpServletRequestBuilder request = get("/path/nonexsiting"); mockMvc.perform(request).andExpect(status().isNotFound()); when(services.getFullPath("existing")).thenReturn("/a/b/c"); request = get("/path...
SeverityLevelHelper { final public static SeverityLevel decodeSeverity(final VType value) { final Alarm alarm = Alarm.alarmOf(value); if (alarm == null) return SeverityLevel.OK; switch (alarm.getSeverity()) { case NONE: return SeverityLevel.OK; case MINOR: return SeverityLevel.MINOR; case MAJOR: return SeverityLevel.MA...
@Test public void decodeSeverity() { assertEquals(SeverityLevel.INVALID, SeverityLevelHelper.decodeSeverity(null)); VInt intValue = VInt.of(7, Alarm.disconnected(), Time.now(), Display.none()); SeverityLevel severityLevel = SeverityLevelHelper.decodeSeverity(intValue); assertEquals(SeverityLevel.INVALID, severityLevel)...
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 VTyp...
@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 = Severi...
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_ind...
@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(ArrayDoubl...
DroppedPVNameParser { public static List<String> parseDroppedPVs(String text) throws Exception { text = text.trim(); if (text.startsWith("[") && text.endsWith("]")) text = text.substring(1, text.length()-2); final List<String> names = new ArrayList<>(); final int len = text.length(); int start = 0, pos = 0; while (pos ...
@Test public void testSingle() throws Exception { List<String> names = DroppedPVNameParser.parseDroppedPVs("SomePVName"); assertThat(names, equalTo(List.of("SomePVName"))); names = DroppedPVNameParser.parseDroppedPVs("loc: assertThat(names, equalTo(List.of("loc: names = DroppedPVNameParser.parseDroppedPVs("loc: assertT...
TimestampHelper { public static Instant roundUp(final Instant time, final Duration duration) { return roundUp(time, duration.getSeconds()); } static Instant roundUp(final Instant time, final Duration duration); static Instant roundUp(final Instant time, final long seconds); static Timestamp toSQLTimestamp(Instant star...
@Test public void testRoundUp() throws Exception { final Instant orig = Instant.from(TimestampFormats.SECONDS_FORMAT.parse("2012-01-19 12:23:14")); String text = TimestampFormats.SECONDS_FORMAT.format(orig); System.out.println(text); assertThat(text, equalTo("2012-01-19 12:23:14")); Instant time; time = TimestampHelper...
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> ge...
@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 b...
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(); }
@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 k...
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_...
@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 (Ill...
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)); initializeDisplayMod...
@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(fil...
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((Loc...
@Test public void testRGB() { assertThat(JFXUtil.webRGB(new WidgetColor(15, 255, 0)), equalTo("#0FFF00")); assertThat(JFXUtil.webRGB(new WidgetColor(0, 16, 255)), equalTo("#0010FF")); }
SVGHelper { public static Image loadSVG(String imageFileName, double width, double height){ String cachedSVGFileName = imageFileName + "_" + width + "_" + height; return ImageCache.cache(cachedSVGFileName, () -> { try(InputStream inputStream = ModelResourceUtil.openResourceStream(imageFileName)){ return loadSVG(inputSt...
@Test public void testSVGHelper(){ try { Image image = SVGHelper.loadSVG(getPath("interlock.svg"), 400d, 400d); assertTrue(image.getHeight() > 0); assertTrue(image.getWidth() > 0); } catch (Exception e) { fail(e.getMessage()); } } @Test public void testSVGHelperPngFile(){ String path = null; try { path = getPath("inter...
ProcessOPI { public Set<File> process() { getExtensionByStringHandling(this.rootFile.getName()).ifPresentOrElse(ext -> { if (!ext.equalsIgnoreCase("bob") && !ext.equalsIgnoreCase("opi")) { throw new UnsupportedOperationException("File extension " + ext + " is not supported. The supported extensions are .bob and .opi.")...
@Test(expected = UnsupportedOperationException.class) public void testRandomFile() { File file = new File(getClass().getClassLoader().getResource("random.txt").getFile()); ProcessOPI processOPI = new ProcessOPI(file); Set<File> result = processOPI.process(); } @Test public void testEmptyBOBList() { File file = new File...
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); vo...
@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(); ...
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 ...
@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 encodedPathWithDe...
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...
@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 encodedPathWithDe...
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 alarmP...
@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 encodedPathWithDe...
FormulaTreeRootNode extends TreeItem<FormulaTreeByCategoryNode> { public void addChild(FormulaFunction child) { for (FormulaTreeCategoryNode category : categories) { if (category.getValue().getSignature().equals(child.getCategory())) { category.addChild(child); return; } } FormulaTreeCategoryNode newCategory = new Form...
@Test public void testGivenNoExistingCategoryAddingChildFormulaToRootNodeCreatesCategory() { String categoryName = "CATEGORY"; String formula1Name = "TEST_NAME"; FormulaFunction func = createFormula(formula1Name, "TEST_DESC", categoryName); FormulaTreeRootNode rootNode = new FormulaTreeRootNode(); rootNode.addChild(fun...
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(...
@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.CONFIGU...
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 i...
@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()); }
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, St...
@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)); a...
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, o...
@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 conf...
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); }
@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().pvNa...
RunnerFileContentRenderer { public String getRenderedRunnerFileContent(FeatureRunner featureRunner) throws CucablePluginException { final String runnerTemplatePath = featureRunner.getRunnerTemplatePath(); final String runnerClassName = featureRunner.getRunnerClassName(); String fileString = fileIO.readContentFromFile(r...
@Test public void getRenderedFeatureFileContentFromTextFileTest() throws Exception { String template = "package parallel;\n" + "\n" + "import cucumber.api.CucumberOptions;\n" + "\n" + "@CucumberOptions(\n" + " monochrome = false,\n" + " features = {\"classpath:parallel/features/[CUCABLE:FEATURE].feature\"},\n" + " plug...
PropertyManager { public void setDesiredNumberOfFeaturesPerRunner(int desiredNumberOfFeaturesPerRunner) { this.desiredNumberOfFeaturesPerRunner = desiredNumberOfFeaturesPerRunner; } @Inject PropertyManager(final CucableLogger logger, final FileIO fileIO); String getSourceRunnerTemplateFile(); void setSourceRunnerTempl...
@Test public void setDesiredNumberOfFeaturesPerRunnerTest() { propertyManager.setDesiredNumberOfFeaturesPerRunner(5); assertThat(propertyManager.getDesiredNumberOfFeaturesPerRunner(), is(5)); }
PropertyManager { public void setParallelizationMode(final String parallelizationMode) throws CucablePluginException { try { this.parallelizationMode = ParallelizationMode.valueOf(parallelizationMode.toUpperCase()); } catch (IllegalArgumentException e) { throw new CucablePluginException( "Unknown <parallelizationMode> ...
@Test public void wrongParallelizationModeTest() throws CucablePluginException { expectedException.expect(CucablePluginException.class); expectedException.expectMessage("Unknown <parallelizationMode> 'unknown'. Please use 'scenarios' or 'features'."); propertyManager.setParallelizationMode("unknown"); }
PropertyManager { public void checkForMissingMandatoryProperties() throws CucablePluginException { List<String> missingProperties = new ArrayList<>(); if (sourceFeatures == null || sourceFeatures.isEmpty()) { saveMissingProperty("", "<sourceFeatures>", missingProperties); } saveMissingProperty(sourceRunnerTemplateFile,...
@Test public void logMissingPropertiesTest() throws CucablePluginException { expectedException.expect(WrongOrMissingPropertiesException.class); expectedException.expectMessage("Properties not specified correctly in the configuration section of your pom file: [<sourceFeatures>, <sourceRunnerTemplateFile>, <generatedRunn...
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 lo...
@Test public void infoTest() { logger.initialize(mockedLogger, "default"); logger.info("Test"); verify(mockedLogger, times(1)) .info("Test"); }
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 CharSequenc...
@Test public void logInfoSeparatorTest() { logger.initialize(mockedLogger, "default"); logger.logInfoSeparator(CucableLogger.CucableLogLevel.DEFAULT); verify(mockedLogger, times(1)) .info("-------------------------------------"); }
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(); }
@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("r...
GherkinDocumentParser { public List<SingleScenario> getSingleScenariosFromFeature( final String featureContent, final String featureFilePath, final List<Integer> scenarioLineNumbers) throws CucablePluginException { String escapedFeatureContent = featureContent.replace("\\n", "\\\\n"); GherkinDocument gherkinDocument = ...
@Test public void invalidFeatureTest() throws Exception { gherkinDocumentParser.getSingleScenariosFromFeature("", "", null); verify(mockedLogger, times(1)).warn("No parsable gherkin."); } @Test public void validFeatureTest() throws Exception { String featureContent = "@featureTag\n" + "Feature: test feature\n" + "\n" +...
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);...
@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> singleS...
GherkinDocumentParser { private DataTable replaceDataTableExamplePlaceholder( final DataTable dataTable, final Map<String, List<String>> exampleMap, final int rowIndex ) { if (dataTable == null) { return null; } List<List<String>> dataTableRows = dataTable.getRows(); DataTable replacedDataTable = new DataTable(); for (...
@Test public void replaceDataTableExamplePlaceholderTest() throws Exception { String featureContent = "Feature: test feature 3\n" + "\n" + " Scenario Outline: This is a scenario outline\n" + " When I search for key <key>\n" + " | test | <key> | <value> |" + "\n" + " Examples:\n" + " | key | value |\n" + " | 1 | one |\n...
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 argumen...
@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.convertGherkinStepsT...
GherkinToCucableConverter { Map<String, List<String>> convertGherkinExampleTableToCucableExampleMap( final Examples exampleTable ) { Map<String, List<String>> exampleMap; List<TableCell> headerCells = exampleTable.getTableHeader().getCells(); exampleMap = headerCells.stream().collect( Collectors.toMap(headerCell -> "<"...
@Test public void convertGherkinExampleTableToCucableExampleMapTest() { Location location = new Location(1, 2); List<Tag> tags = new ArrayList<>(); Tag tag = new Tag(location, "@tag"); tags.add(tag); String keyword = "keyword"; String name = "name"; String description = "description"; List<TableCell> headerCells = new ...
FeatureFileContentRenderer { private String getRenderedFeatureFileContent(List<SingleScenario> singleScenarios) { StringBuilder renderedContent = new StringBuilder(); SingleScenario firstScenario = singleScenarios.get(0); addLanguage(renderedContent, firstScenario.getFeatureLanguage()); addTags(renderedContent, firstSc...
@Test public void getRenderedFeatureFileContentTest() { String expectedOutput = "@featureTag1\n" + "@featureTag2\n" + "Feature: featureName\n" + "featureDescription\n" + "\n" + "@scenarioTag1\n" + "@scenarioTag2\n" + "Scenario: scenarioName\n" + "scenarioDescription\n" + "Step 1\n" + "Step 2\n" + "\n# Source feature: T...
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(dataTableSepa...
@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"; ...
FeatureFileContentRenderer { private String formatDocString(final String docString) { if (docString == null || docString.isEmpty()) { return ""; } return "\"\"\"" + LINE_SEPARATOR + docString + LINE_SEPARATOR + "\"\"\"" + LINE_SEPARATOR; } }
@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"...
FeatureFileConverter { public void generateParallelizableFeatures( final List<CucableFeature> cucableFeatures) throws CucablePluginException { int featureFileCounter = 0; List<String> allGeneratedFeaturePaths = new ArrayList<>(); for (CucableFeature cucableFeature : cucableFeatures) { List<Path> paths = fileSystemManag...
@Test public void generateParallelizableFeaturesEmptyFeaturesTest() throws CucablePluginException { List<CucableFeature> cucableFeatures = new ArrayList<>(); featureFileConverter.generateParallelizableFeatures(cucableFeatures); } @Test public void convertEmptyPathListToSingleScenariosAndRunnersTest() throws Exception {...
CucablePlugin extends AbstractMojo { public void execute() throws CucablePluginException { logger.initialize(getLog(), logLevel); propertyManager.setSourceRunnerTemplateFile(sourceRunnerTemplateFile); propertyManager.setGeneratedRunnerDirectory(generatedRunnerDirectory); propertyManager.setSourceFeatures(sourceFeatures...
@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)); }
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(St...
@Test(expected = FileCreationException.class) public void writeToInvalidFileTest() throws Exception { fileIO.writeContentToFile(null, ""); }
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); }
@Test(expected = MissingFileException.class) public void readFromMissingFileTest() throws Exception { String wrongPath = testFolder.getRoot().getPath().concat("/missing.tmp"); fileIO.readContentFromFile(wrongPath); }
FileSystemManager { public void prepareGeneratedFeatureAndRunnerDirectories() throws CucablePluginException { createDirIfNotExists(propertyManager.getGeneratedFeatureDirectory()); removeFilesFromPath(propertyManager.getGeneratedFeatureDirectory(), "feature"); createDirIfNotExists(propertyManager.getGeneratedRunnerDirec...
@Test(expected = PathCreationException.class) public void prepareGeneratedFeatureAndRunnerDirsMissingFeatureDirTest() throws Exception { when(propertyManager.getGeneratedFeatureDirectory()).thenReturn(""); fileSystemManager.prepareGeneratedFeatureAndRunnerDirectories(); } @Test(expected = PathCreationException.class) p...
FileSystemManager { public List<Path> getPathsFromCucableFeature(final CucableFeature cucableFeature) throws CucablePluginException { if (cucableFeature == null) { return Collections.emptyList(); } String sourceFeatures = cucableFeature.getName(). replace("file: File sourceFeaturesFile = new File(sourceFeatures); if (s...
@Test public void getPathsFromCucableFeatureNullTest() throws CucablePluginException { List<Path> pathsFromCucableFeature = fileSystemManager.getPathsFromCucableFeature(null); assertThat(pathsFromCucableFeature, is(notNullValue())); assertThat(pathsFromCucableFeature.size(), is(0)); } @Test(expected = CucablePluginExce...
PropertyManager { public void setGeneratedRunnerDirectory(final String generatedRunnerDirectory) { this.generatedRunnerDirectory = generatedRunnerDirectory; } @Inject PropertyManager(final CucableLogger logger, final FileIO fileIO); String getSourceRunnerTemplateFile(); void setSourceRunnerTemplateFile(final String so...
@Test public void setGeneratedRunnerDirectoryTest() { propertyManager.setGeneratedRunnerDirectory("test"); assertThat(propertyManager.getGeneratedRunnerDirectory(), is("test")); }
PropertyManager { public void setGeneratedFeatureDirectory(final String generatedFeatureDirectory) { this.generatedFeatureDirectory = generatedFeatureDirectory; } @Inject PropertyManager(final CucableLogger logger, final FileIO fileIO); String getSourceRunnerTemplateFile(); void setSourceRunnerTemplateFile(final Strin...
@Test public void setGeneratedFeatureDirectoryTest() { propertyManager.setGeneratedFeatureDirectory("test"); assertThat(propertyManager.getGeneratedFeatureDirectory(), is("test")); }
PropertyManager { public void setDesiredNumberOfRunners(final int desiredNumberOfRunners) { this.desiredNumberOfRunners = desiredNumberOfRunners; } @Inject PropertyManager(final CucableLogger logger, final FileIO fileIO); String getSourceRunnerTemplateFile(); void setSourceRunnerTemplateFile(final String sourceRunnerT...
@Test public void setDesiredNumberOfRunnersTest() { propertyManager.setDesiredNumberOfRunners(12); assertThat(propertyManager.getDesiredNumberOfRunners(), is(12)); }