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)args[1]).getValue().intValue(); if(index < 0 || index > numberArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VDouble.of(numberArray.getData().getDouble(index), Alarm.none(), Time.now(), Display.none()); } else if(isStringArray && args[1] instanceof VNumber){ VStringArray stringArray = (VStringArray)args[0]; int index = ((VDouble)args[1]).getValue().intValue(); if(index < 0 || index > stringArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VString.of(stringArray.getData().get(index), stringArray.getAlarm(), stringArray.getTime()); } else{ return isStringArray ? DEFAULT_EMPTY_STRING : DEFAULT_NAN_DOUBLE; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
@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(array, index); assertEquals("c", vString.getValue()); vString = (VString)elementAtNumberFunction.compute(array, array); assertEquals("", vString.getValue()); } @Test(expected = Exception.class) public void invalidArguments1() throws Exception{ ElementAtNumberFunction elementAtNumberFunction = new ElementAtNumberFunction(); VType index = VDouble.of(8.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()); elementAtNumberFunction.compute(array, index); } @Test(expected = Exception.class) public void invalidArguments2() throws Exception{ ElementAtNumberFunction elementAtNumberFunction = new ElementAtNumberFunction(); VType index = VDouble.of(-1.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()); elementAtNumberFunction.compute(array, index); }
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.now()); } else if(args[0] instanceof VNumber){ List<VNumber> elements = Arrays.asList(args).stream().map(arg -> (VNumber)arg).collect(Collectors.toList()); ListDouble data = new ListDouble() { @Override public double getDouble(int index) { VNumber number = elements.get(index); if (number == null || number.getValue() == null) return Double.NaN; else return number.getValue().doubleValue(); } @Override public int size() { return elements.size(); } }; return VNumberArray.of(data, Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override boolean isVarArgs(); @Override VType compute(VType... args); }
@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 = VString.of("c", Alarm.none(), Time.now()); VStringArray vStringArray = (VStringArray)arrayOfFunction.compute(a, b, c); assertEquals(3, vStringArray.getData().size()); assertEquals("a", vStringArray.getData().get(0)); assertEquals("b", vStringArray.getData().get(1)); assertEquals("c", vStringArray.getData().get(2)); VInt d0 = VInt.of(1, Alarm.none(), Time.now(), Display.none()); VInt d1 = VInt.of(2, Alarm.none(), Time.now(), Display.none()); VInt d2 = VInt.of(3, Alarm.none(), Time.now(), Display.none()); VNumberArray vNumberArray = (VNumberArray)arrayOfFunction.compute(d0, d1, d2); assertEquals(3, vNumberArray.getData().size()); assertEquals(1, vNumberArray.getData().getInt(0)); assertEquals(2, vNumberArray.getData().getInt(1)); assertEquals(3, vNumberArray.getData().getInt(2)); VEnum vEnum = VEnum.of(0, EnumDisplay.of(), Alarm.none(), Time.now()); vNumberArray = (VNumberArray)arrayOfFunction.compute(vEnum); assertTrue(Double.valueOf(vNumberArray.getData().getDouble(0)).equals(Double.NaN)); }
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() != array2.getData().size()){ throw new Exception(String.format("Function %s cannot compute as specified arrays are of different length", getName())); } return VNumberArray.of( ListMath.divide(array1.getData(), array2.getData()), 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); }
@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(), Time.now(), Display.none()); VType array2 = VNumberArray.of(ArrayDouble.of(1.0, 2.0, 5.0), Alarm.none(), Time.now(), Display.none()); VNumberArray result = (VNumberArray)arrayDivisionFunction.compute(array1, array2); assertEquals(3, result.getData().size()); assertEquals(2, result.getData().getInt(0)); assertEquals(5, result.getData().getInt(1)); assertEquals(6, result.getData().getInt(2)); VType exponent = VDouble.of(2.0, Alarm.none(), Time.now(), Display.none()); result = (VNumberArray)arrayDivisionFunction.compute(array1, exponent); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); } @Test(expected = Exception.class) public void testWrongArguments() throws Exception{ ArrayDivisionFunction arrayDivisionFunction = new ArrayDivisionFunction(); VType array1 = VNumberArray.of(ArrayDouble.of(1.0, 2.0), Alarm.none(), Time.now(), Display.none()); VType array2 = VNumberArray.of(ArrayDouble.of(2.0, 5.0, 7.0), Alarm.none(), Time.now(), Display.none()); arrayDivisionFunction.compute(array1, array2); }
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); }
@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; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
@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()); }
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.getData().size()){ throw new Exception(String.format("Function %s cannot compute as specified arrays are of different length", getName())); } return VNumberArray.of( ListMath.multiply(array1.getData(), array2.getData()), 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); }
@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, 2.0, 3.0), Alarm.of(AlarmSeverity.MAJOR, AlarmStatus.NONE, ""), Time.now(), Display.none()); VType array2 = VNumberArray.of(ArrayDouble.of(2.0, 5.0, 7.0), Alarm.of(AlarmSeverity.MINOR, AlarmStatus.NONE, ""), Time.now(), Display.none()); VNumberArray result = (VNumberArray)arrayMultiplicationFunction.compute(array1, array2); assertEquals(3, result.getData().size()); assertEquals(2, result.getData().getInt(0)); assertEquals(10, result.getData().getInt(1)); assertEquals(21, result.getData().getInt(2)); VType exponent = VDouble.of(2.0, Alarm.none(), Time.now(), Display.none()); result = (VNumberArray)arrayMultiplicationFunction.compute(array1, exponent); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); } @Test(expected = Exception.class) public void testWrongArguments() throws Exception{ ArrayMultiplicationFunction arrayMultiplicationFunction = new ArrayMultiplicationFunction(); VType array1 = VNumberArray.of(ArrayDouble.of(1.0, 2.0), Alarm.of(AlarmSeverity.MAJOR, AlarmStatus.NONE, ""), Time.now(), Display.none()); VType array2 = VNumberArray.of(ArrayDouble.of(2.0, 5.0, 7.0), Alarm.of(AlarmSeverity.MINOR, AlarmStatus.NONE, ""), Time.now(), Display.none()); arrayMultiplicationFunction.compute(array1, array2); }
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); }
@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)); }
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 array = (VNumberArray)args[0]; VNumber factor = (VNumber) args[1]; double offset = args.length == 3 ? ((VNumber)args[2]).getValue().doubleValue() : 0.0; return VNumberArray.of( ListMath.rescale(array.getData(), factor.getValue().doubleValue(), offset), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override boolean isVarArgs(); @Override VType compute(VType... args); }
@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(ArrayDouble.of(1.0, 2.0, 3.0), Alarm.none(), Time.now(), Display.none()); VType offset = VDouble.of(1.0, Alarm.none(), Time.now(), Display.none()); VNumberArray result = (VNumberArray)scaleArray.compute(array, factor, offset); assertEquals(3, result.getData().size()); assertTrue(result.getData().getDouble(0) == 3); assertTrue(result.getData().getDouble(1) == 5); assertTrue(result.getData().getDouble(2) == 7); result = (VNumberArray)scaleArray.compute(array, factor); assertEquals(3, result.getData().size()); assertTrue(result.getData().getDouble(0) == 2); assertTrue(result.getData().getDouble(1) == 4); assertTrue(result.getData().getDouble(2) == 6); assertEquals(3, result.getData().size()); assertTrue(result.getData().getDouble(0) == 2); assertTrue(result.getData().getDouble(1) == 4); assertTrue(result.getData().getDouble(2) == 6); result = (VNumberArray)scaleArray.compute(factor, factor, offset); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); } @Test(expected = Exception.class) public void testWrongNnumberOfArgumenst1() throws Exception{ ScaleArrayFormulaFunction scaleArray = new ScaleArrayFormulaFunction(); VType factor = 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()); VType offset = VDouble.of(1.0, Alarm.none(), Time.now(), Display.none()); scaleArray.compute(array, factor, offset, offset); } @Test(expected = Exception.class) public void testWrongNnumberOfArgumenst2() throws Exception{ ScaleArrayFormulaFunction scaleArray = new ScaleArrayFormulaFunction(); VType array = VNumberArray.of(ArrayDouble.of(1.0, 2.0, 3.0), Alarm.none(), Time.now(), Display.none()); scaleArray.compute(array); }
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); }
@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()); }
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); }
@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)); }
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 SnapshotPvDataType.UBYTE; } else if(clazz.equals(Short.class)) { return SnapshotPvDataType.SHORT; } else if(clazz.equals(UShort.class)) { return SnapshotPvDataType.USHORT; } else if(clazz.equals(Integer.class)) { return SnapshotPvDataType.INTEGER; } else if(clazz.equals(UInteger.class)) { return SnapshotPvDataType.UINTEGER; } else if(clazz.equals(Long.class)) { return SnapshotPvDataType.LONG; } else if(clazz.equals(ULong.class)) { return SnapshotPvDataType.ULONG; } else if(clazz.equals(Float.class)) { return SnapshotPvDataType.FLOAT; } else if(clazz.equals(Double.class)){ return SnapshotPvDataType.DOUBLE; } throw new PVConversionException("Data class " + vNumber.getValue().getClass().getCanonicalName() + " not supported"); } else if(vType instanceof VNumberArray) { VNumberArray vNumberArray = (VNumberArray)vType; Class<?> clazz = vNumberArray.getData().getClass(); if(clazz.equals(ArrayByte.class) || clazz.getSuperclass().equals(ListByte.class)) { return SnapshotPvDataType.BYTE; } else if(clazz.equals(ArrayUByte.class) || clazz.getSuperclass().equals(ListUByte.class)) { return SnapshotPvDataType.UBYTE; } else if(clazz.equals(ArrayShort.class) || clazz.getSuperclass().equals(ListShort.class)) { return SnapshotPvDataType.SHORT; } else if(clazz.equals(ArrayUShort.class) || clazz.getSuperclass().equals(ListUShort.class)) { return SnapshotPvDataType.USHORT; } else if(clazz.equals(ArrayInteger.class) || clazz.getSuperclass().equals(ListInteger.class)) { return SnapshotPvDataType.INTEGER; } else if(clazz.equals(ArrayUInteger.class) || clazz.getSuperclass().equals(ListUInteger.class)) { return SnapshotPvDataType.UINTEGER; } else if(clazz.equals(ArrayLong.class) || clazz.getSuperclass().equals(ListLong.class)) { return SnapshotPvDataType.LONG; } else if(clazz.equals(ArrayULong.class) || clazz.getSuperclass().equals(ListULong.class)) { return SnapshotPvDataType.ULONG; } else if(clazz.equals(ArrayFloat.class) || clazz.getSuperclass().equals(ListFloat.class)) { return SnapshotPvDataType.FLOAT; } else if(clazz.equals(ArrayDouble.class) || clazz.getSuperclass().equals(ListDouble.class)) { return SnapshotPvDataType.DOUBLE; } throw new PVConversionException("Data class " + vNumberArray.getData().getClass().getCanonicalName() + " not supported"); } else if(vType instanceof VString) { return SnapshotPvDataType.STRING; } else if(vType instanceof VEnum){ return SnapshotPvDataType.ENUM; } else if(vType instanceof VStringArray){ return SnapshotPvDataType.STRING; } throw new PVConversionException(String.format("Unable to perform data conversion on type %s", vType.getClass().getCanonicalName())); } private SnapshotDataConverter(); static SnapshotItem fromSnapshotPv(SnapshotPv snapshotPv, SnapshotPv readback); static SnapshotPv fromVType(VType vType); static VType toVType(SnapshotPv snapshotPv); }
@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.getDataType(vUByte)); VShort vShort = VShort.of(new Short((short) 1), alarm, time, display); assertEquals(SnapshotPvDataType.SHORT, SnapshotDataConverter.getDataType(vShort)); VUShort vUShort = VUShort.of(new UShort((short) 1), alarm, time, display); assertEquals(SnapshotPvDataType.USHORT, SnapshotDataConverter.getDataType(vUShort)); VInt vInt = VInt.of(new Integer(1), alarm, time, display); assertEquals(SnapshotPvDataType.INTEGER, SnapshotDataConverter.getDataType(vInt)); VUInt vUInt = VUInt.of(new UInteger(1), alarm, time, display); assertEquals(SnapshotPvDataType.UINTEGER, SnapshotDataConverter.getDataType(vUInt)); VLong vLong = VLong.of(new Long(1), alarm, time, display); assertEquals(SnapshotPvDataType.LONG, SnapshotDataConverter.getDataType(vLong)); VULong vULong = VULong.of(new ULong(1), alarm, time, display); assertEquals(SnapshotPvDataType.ULONG, SnapshotDataConverter.getDataType(vULong)); VFloat vFloat = VFloat.of(new Float(1.1), alarm, time, display); assertEquals(SnapshotPvDataType.FLOAT, SnapshotDataConverter.getDataType(vFloat)); VDouble vDouble = VDouble.of(new Double(1), alarm, time, display); assertEquals(SnapshotPvDataType.DOUBLE, SnapshotDataConverter.getDataType(vDouble)); VString vString = VString.of("string", alarm, time); assertEquals(SnapshotPvDataType.STRING, SnapshotDataConverter.getDataType(vString)); VEnum vEnum = VEnum.of(0, EnumDisplay.of("choice1"), alarm, time); assertEquals(SnapshotPvDataType.ENUM, SnapshotDataConverter.getDataType(vEnum)); VByteArray vByteArray = VByteArray.of(new ArrayByte(CollectionNumbers.toListByte((byte) 1)), alarm, time, display); assertEquals(SnapshotPvDataType.BYTE, SnapshotDataConverter.getDataType(vByteArray)); VNumberArray vNumberArray = VNumberArray.of(CollectionNumbers.toList(new byte[] { (byte) 1 }), alarm, time, display); assertEquals(SnapshotPvDataType.BYTE, SnapshotDataConverter.getDataType(vNumberArray)); ListByte listByte = new ListByte() { @Override public int size() { return 1; } @Override public byte getByte(int index) { return (byte) 1; } }; vByteArray = VByteArray.of(listByte, alarm, time, Display.none()); assertEquals(SnapshotPvDataType.BYTE, SnapshotDataConverter.getDataType(vByteArray)); VUByteArray vUByteArray = VUByteArray.of(new ArrayUByte(CollectionNumbers.toListUByte((byte) 1)), alarm, time, display); assertEquals(SnapshotPvDataType.UBYTE, SnapshotDataConverter.getDataType(vUByteArray)); ListUByte listUByte = new ListUByte() { @Override public int size() { return 1; } @Override public byte getByte(int index) { return (byte) 1; } }; vUByteArray = VUByteArray.of(listUByte, alarm, time, Display.none()); assertEquals(SnapshotPvDataType.UBYTE, SnapshotDataConverter.getDataType(vUByteArray)); VShortArray vShortArray = VShortArray.of(new ArrayShort(CollectionNumbers.toListShort((short) 1)), alarm, time, display); assertEquals(SnapshotPvDataType.SHORT, SnapshotDataConverter.getDataType(vShortArray)); vNumberArray = VNumberArray.of(CollectionNumbers.toList(new short[] { (short) 1 }), alarm, time, display); assertEquals(SnapshotPvDataType.SHORT, SnapshotDataConverter.getDataType(vNumberArray)); ListShort listShort = new ListShort() { @Override public int size() { return 1; } @Override public short getShort(int index) { return (short) 1; } }; vShortArray = VShortArray.of(listShort, alarm, time, Display.none()); assertEquals(SnapshotPvDataType.SHORT, SnapshotDataConverter.getDataType(vShortArray)); VUShortArray vUShortArray = VUShortArray.of(new ArrayUShort(CollectionNumbers.toListUShort((short) 1)), alarm, time, display); assertEquals(SnapshotPvDataType.USHORT, SnapshotDataConverter.getDataType(vUShortArray)); ListUShort listUShort = new ListUShort() { @Override public int size() { return 1; } @Override public short getShort(int index) { return (short) 1; } }; vUShortArray = VUShortArray.of(listUShort, alarm, time, Display.none()); assertEquals(SnapshotPvDataType.USHORT, SnapshotDataConverter.getDataType(vUShortArray)); VIntArray vIntArray = VIntArray.of(new ArrayInteger(CollectionNumbers.toListInt(1)), alarm, time, display); assertEquals(SnapshotPvDataType.INTEGER, SnapshotDataConverter.getDataType(vIntArray)); vNumberArray = VNumberArray.of(CollectionNumbers.toList(new int[] { 1 }), alarm, time, display); assertEquals(SnapshotPvDataType.INTEGER, SnapshotDataConverter.getDataType(vNumberArray)); ListInteger listInteger = new ListInteger() { @Override public int size() { return 1; } @Override public int getInt(int index) { return 1; } }; vIntArray = VIntArray.of(listInteger, alarm, time, Display.none()); assertEquals(SnapshotPvDataType.INTEGER, SnapshotDataConverter.getDataType(vIntArray)); VUIntArray vUIntArray = VUIntArray.of(new ArrayUInteger(CollectionNumbers.toListUInt(1)), alarm, time, display); assertEquals(SnapshotPvDataType.UINTEGER, SnapshotDataConverter.getDataType(vUIntArray)); ListUInteger listUInteger = new ListUInteger() { @Override public int size() { return 1; } @Override public int getInt(int index) { return 1; } }; vUIntArray = VUIntArray.of(listUInteger, alarm, time, Display.none()); assertEquals(SnapshotPvDataType.UINTEGER, SnapshotDataConverter.getDataType(vUIntArray)); VLongArray vLongArray = VLongArray.of(new ArrayLong(CollectionNumbers.toListLong(1L)), alarm, time, display); assertEquals(SnapshotPvDataType.LONG, SnapshotDataConverter.getDataType(vLongArray)); vNumberArray = VNumberArray.of(CollectionNumbers.toList(new long[] { 1 }), alarm, time, display); assertEquals(SnapshotPvDataType.LONG, SnapshotDataConverter.getDataType(vNumberArray)); ListLong listLong = new ListLong() { @Override public int size() { return 1; } @Override public long getLong(int index) { return 1L; } }; vLongArray = VLongArray.of(listLong, alarm, time, Display.none()); assertEquals(SnapshotPvDataType.LONG, SnapshotDataConverter.getDataType(vLongArray)); VULongArray vULongArray = VULongArray.of(new ArrayULong(CollectionNumbers.toListULong(1L)), alarm, time, display); assertEquals(SnapshotPvDataType.ULONG, SnapshotDataConverter.getDataType(vULongArray)); ListULong listULong = new ListULong() { @Override public int size() { return 1; } @Override public long getLong(int index) { return 1L; } }; vULongArray = VULongArray.of(listULong, alarm, time, Display.none()); assertEquals(SnapshotPvDataType.ULONG, SnapshotDataConverter.getDataType(vULongArray)); VFloatArray vFloatArray = VFloatArray.of(new ArrayFloat(CollectionNumbers.toListFloat(1.1f)), alarm, time, display); assertEquals(SnapshotPvDataType.FLOAT, SnapshotDataConverter.getDataType(vFloatArray)); vNumberArray = VNumberArray.of(CollectionNumbers.toList(new float[] { 1.1f }), alarm, time, display); assertEquals(SnapshotPvDataType.FLOAT, SnapshotDataConverter.getDataType(vNumberArray)); ListFloat listFloat = new ListFloat() { @Override public int size() { return 1; } @Override public float getFloat(int index) { return 1.1f; } }; vFloatArray = VFloatArray.of(listFloat, alarm, time, Display.none()); assertEquals(SnapshotPvDataType.FLOAT, SnapshotDataConverter.getDataType(vFloatArray)); VDoubleArray vDoubleArray = VDoubleArray.of(new ArrayDouble(CollectionNumbers.toListDouble(1.1)), alarm, time, display); assertEquals(SnapshotPvDataType.DOUBLE, SnapshotDataConverter.getDataType(vDoubleArray)); vNumberArray = VNumberArray.of(CollectionNumbers.toList(new double[] { 1.1 }), alarm, time, display); assertEquals(SnapshotPvDataType.DOUBLE, SnapshotDataConverter.getDataType(vNumberArray)); ListDouble listDouble = new ListDouble() { @Override public int size() { return 1; } @Override public double getDouble(int index) { return 1.1; } }; vDoubleArray = VDoubleArray.of(listDouble, alarm, time, Display.none()); assertEquals(SnapshotPvDataType.DOUBLE, SnapshotDataConverter.getDataType(vDoubleArray)); }
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); }
@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)); }
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); }
@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)); }
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 previousXRange = null; if (previousValue == numberArray) { return previousResult; } Statistics stats = StatisticsUtil.statisticsOf(numberArray.getData()); int nBins = args.length == 1 ? 100 : ((VNumber) args[1]).getValue().intValue(); Range aggregatedRange = aggregateRange(stats.getRange(), previousXRange); Range xRange; if (Ranges.overlap(aggregatedRange, stats.getRange()) >= 0.75) { xRange = aggregatedRange; } else { xRange = stats.getRange(); } IteratorNumber newValues = numberArray.getData().iterator(); double previousMaxCount = Double.MIN_VALUE; int[] binData = new int[nBins]; double maxCount = 0; while (newValues.hasNext()) { double value = newValues.nextDouble(); if (xRange.contains(value)) { int bin = (int) Math.floor(xRange.normalize(value) * nBins); if (bin == nBins) { bin--; } binData[bin]++; if (binData[bin] > maxCount) { maxCount = binData[bin]; } } } if (previousMaxCount > maxCount && previousMaxCount < maxCount * 2.0) { maxCount = previousMaxCount; } Display display = Display.of(Range.of(0.0, maxCount), Range.of(0.0, maxCount), Range.of(0.0, maxCount), Range.of(0.0, maxCount), "count", NumberFormats.precisionFormat(0)); return VNumberArray.of(ArrayInteger.of(binData), Alarm.none(), Time.now(), display); } else { return BaseArrayFunction.DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override boolean isVarArgs(); @Override VType compute(VType... args); }
@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(ArrayDouble.of(data), Alarm.none(), Time.now(), Display.none()); VNumberArray vNumberArray = (VNumberArray)function.compute(vDoubleArray); assertEquals(100, vNumberArray.getData().size()); assertEquals(10, vNumberArray.getData().getInt(0)); assertEquals(10, (int)vNumberArray.getDisplay().getDisplayRange().getMaximum()); VNumber vNumber = VInt.of(200, Alarm.none(), Time.now(), Display.none()); vNumberArray = (VNumberArray)function.compute(vDoubleArray, vNumber); assertEquals(200, vNumberArray.getData().size()); assertEquals(5, vNumberArray.getData().getInt(0)); assertEquals(5, (int)vNumberArray.getDisplay().getDisplayRange().getMaximum()); vNumberArray = (VNumberArray)function.compute(vNumber); assertTrue(Double.valueOf(vNumberArray.getData().getDouble(0)).equals(Double.NaN)); }
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 || (fromIndex.getValue().intValue() > toIndex.getValue().intValue()) || (toIndex.getValue().intValue() - fromIndex.getValue().intValue() > array.getData().size())){ throw new Exception("Limits for sub array invalid"); } return VNumberArray.of( array.getData().subList(fromIndex.getValue().intValue(), toIndex.getValue().intValue()), Alarm.none(), Time.now(), Display.none()); } else if(args[0] instanceof VStringArray){ VStringArray array = (VStringArray)args[0]; if(fromIndex.getValue().intValue() < 0 || (fromIndex.getValue().intValue() > toIndex.getValue().intValue()) || (toIndex.getValue().intValue() - fromIndex.getValue().intValue() > array.getData().size())){ throw new Exception("Limits for sub array invalid"); } return VStringArray.of( array.getData().subList(fromIndex.getValue().intValue(), toIndex.getValue().intValue()), Alarm.none(), Time.now()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
@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.none()); VType from = VDouble.of(1.0, Alarm.none(), Time.now(), Display.none()); VType to = VDouble.of(3.0, Alarm.none(), Time.now(), Display.none()); VNumberArray result = (VNumberArray)subArrayFunction.compute(array, from, to); assertEquals(2, result.getData().size()); assertEquals(2, result.getData().getInt(0)); assertEquals(3, result.getData().getInt(1)); result = (VNumberArray)subArrayFunction.compute(from, from, to); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); VStringArray stringArray = VStringArray.of(List.of("a", "b", "c", "d", "e")); VStringArray stringResult = (VStringArray) subArrayFunction.compute(stringArray, from, to); assertEquals(2, stringResult.getData().size()); assertEquals("b", stringResult.getData().get(0)); assertEquals("c", stringResult.getData().get(1)); }
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_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)); }
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 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); }
@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(7.7, result, 0); stringValue = VString.of("NotANumber", Alarm.none(), Time.now()); result = VTypeHelper.toDouble(stringValue); assertEquals(Double.NaN, result, 0); VEnum enumValue = VEnum.of(7, EnumDisplay.of("a", "b"), Alarm.none(), Time.now()); result = VTypeHelper.toDouble(enumValue); assertEquals(7.0, result, 0); VStatistics statisticsValue = VStatistics.of(7.7, 0.1, 0.0, 10.0, 5, Alarm.none(), Time.now(), Display.none()); result = VTypeHelper.toDouble(statisticsValue); assertEquals(7.7, result, 0); VDoubleArray doubleArray = VDoubleArray.of(ArrayDouble.of(7.7, 8.8), Alarm.none(), Time.now(), Display.none()); result = VTypeHelper.toDouble(doubleArray); assertEquals(7.7, result, 0); VEnumArray enumArray = VEnumArray.of(ArrayInteger.of(0, 1), EnumDisplay.of("a", "b"), Alarm.none(), Time.now()); result = VTypeHelper.toDouble(enumArray); assertEquals(0.0, result, 0); VBoolean booleanValue = VBoolean.of(true, Alarm.none(), Time.now()); assertEquals(1.0, VTypeHelper.toDouble(booleanValue), 0); booleanValue = VBoolean.of(false, Alarm.none(), Time.now()); assertEquals(0.0, VTypeHelper.toDouble(booleanValue), 0); } @Test public void testArrayToDoubleWithValidIndex(){ VDoubleArray doubleArray = VDoubleArray.of(ArrayDouble.of(7.7, 8.8), Alarm.none(), Time.now(), Display.none()); double result = VTypeHelper.toDouble(doubleArray, 0); assertEquals(7.7, result, 0); result = VTypeHelper.toDouble(doubleArray, 1); assertEquals(8.8, result, 0); VEnumArray enumArray = VEnumArray.of(ArrayInteger.of(0, 1), EnumDisplay.of("a", "b"), Alarm.none(), Time.now()); result = VTypeHelper.toDouble(enumArray); assertEquals(0.0, result, 0); assertEquals(1.0, result, 1); VDouble doubleValue = VDouble.of(7.7, Alarm.none(), Time.now(), Display.none()); result = VTypeHelper.toDouble(doubleValue, 0); assertEquals(7.7, result, 0); } @Test public void testArrayToDoubleWithInvalidIndex1(){ VDoubleArray doubleArray = VDoubleArray.of(ArrayDouble.of(7.7, 8.8), Alarm.none(), Time.now(), Display.none()); double result = VTypeHelper.toDouble(doubleArray, 7); assertEquals(result, Double.NaN, 0); } @Test public void testArrayToDoubleWithInvalidIndex2(){ VEnumArray enumArray = VEnumArray.of(ArrayInteger.of(0, 1), EnumDisplay.of("a", "b"), Alarm.none(), Time.now()); double result = VTypeHelper.toDouble(enumArray, 7); assertEquals(result, Double.NaN, 0); } @Test public void testArrayToDoubleWithInvalidIndex3(){ VDoubleArray doubleArray = VDoubleArray.of(ArrayDouble.of(7.7, 8.8), Alarm.none(), Time.now(), Display.none()); double result = VTypeHelper.toDouble(doubleArray, -1); assertEquals(result, Double.NaN, 0); }
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(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getScalarValueString(vNumber.getValue())) .dataType(dataType) .sizes(SCALAR_AS_JSON) .build(); } else if(vType instanceof VNumberArray) { VNumberArray vNumberArray = (VNumberArray)vType; Alarm alarm = vNumberArray.getAlarm(); Instant instant = vNumberArray.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getNumberArrayValueString(vNumberArray)) .dataType(dataType) .sizes(getDimensionString(vNumberArray)) .build(); } else if(vType instanceof VString){ VString vString = (VString)vType; Alarm alarm = vString.getAlarm(); Instant instant = vString.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getScalarValueString(vString.getValue())) .dataType(dataType) .sizes(SCALAR_AS_JSON) .build(); } else if(vType instanceof VStringArray){ VStringArray vStringArray = (VStringArray) vType; Alarm alarm = vStringArray.getAlarm(); Instant instant = vStringArray.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getStringArrayValueString(vStringArray)) .dataType(dataType) .sizes(getDimensionString(vStringArray)) .build(); } else if(vType instanceof VEnum){ VEnum vEnum = (VEnum)vType; Alarm alarm = vEnum.getAlarm(); Instant instant = vEnum.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getEnumValueString(vEnum)) .dataType(dataType) .sizes(SCALAR_AS_JSON) .build(); } throw new PVConversionException(String.format("VType \"%s\" not supported", vType.getClass().getCanonicalName())); } private SnapshotDataConverter(); static SnapshotItem fromSnapshotPv(SnapshotPv snapshotPv, SnapshotPv readback); static SnapshotPv fromVType(VType vType); static VType toVType(SnapshotPv snapshotPv); }
@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]; 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); }
@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); }
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 VString) { return ((VString) value).getValue(); } return value.toString(); } 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); }
@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.none()); assertNull(VTypeHelper.toString(vDouble)); vDouble = VDouble.of(7.7, Alarm.none(), Time.now(), Display.none()); assertEquals("7.7", VTypeHelper.toString(vDouble)); VEnum enumValue = VEnum.of(0, EnumDisplay.of("a", "b"), Alarm.none(), Time.now()); assertEquals("a", VTypeHelper.toString(enumValue)); assertEquals("b", VTypeHelper.toString(VString.of("b", Alarm.none(), Time.now()))); }
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); }
@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)); }
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); }
@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)); }
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); }
@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)); }
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); }
@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)); }
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 number = (VNumber) value; return VInt.of(number.getValue().intValue(), number.getAlarm(), Time.of(time), number.getDisplay()); } if (value instanceof VString) { final VString string = (VString) value; return VString.of(string.getValue(), string.getAlarm(), Time.of(time)); } if (value instanceof VDoubleArray) { final VDoubleArray number = (VDoubleArray) value; return VDoubleArray.of(number.getData(), number.getAlarm(), Time.of(time), number.getDisplay()); } if (value instanceof VEnum) { final VEnum labelled = (VEnum) value; return VEnum.of(labelled.getIndex(), labelled.getDisplay(), labelled.getAlarm(), Time.of(time)); } return null; } 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); }
@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.7, Alarm.none(), Time.of(Instant.EPOCH), Display.none()); doubleValue = (VDouble)VTypeHelper.transformTimestamp(doubleValue, instant); assertEquals(instant, doubleValue.getTime().getTimestamp()); VString stringValue = VString.of("test", Alarm.none(), Time.of(Instant.EPOCH)); stringValue = (VString)VTypeHelper.transformTimestamp(stringValue, instant); assertEquals(instant, stringValue.getTime().getTimestamp()); VEnum enumValue = VEnum.of(7, EnumDisplay.of("a", "b"), Alarm.none(), Time.now()); enumValue = (VEnum)VTypeHelper.transformTimestamp(enumValue, instant); assertEquals(instant, enumValue.getTime().getTimestamp()); VDoubleArray doubleArray = VDoubleArray.of(ArrayDouble.of(7.7, 8.8), Alarm.none(), Time.now(), Display.none()); doubleArray = (VDoubleArray)VTypeHelper.transformTimestamp(doubleArray, instant); assertEquals(instant, doubleArray.getTime().getTimestamp()); VEnumArray enumArray = VEnumArray.of(ArrayInteger.of(0, 1), EnumDisplay.of("a", "b"), Alarm.none(), Time.now()); assertNull(VTypeHelper.transformTimestamp(enumArray, instant)); }
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); }
@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); }
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); }
@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)); }
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.toString(); } ListInteger sizes = array.getSizes(); int sizesSize = sizes.size(); int totalElements = 1; for (int i = 0; i < sizesSize; i++) { totalElements *= sizes.getInt(i); } if (totalElements == 0) { return builder.toString(); } int numberOfElementsToFormat = Math.min(totalElements, maxElements); builder.append("["); if ((array instanceof VIntArray) || (array instanceof VUIntArray)) { VNumberArray numberArray = (VNumberArray) array; ListNumber listNumber = numberArray.getData(); for (int i = 0; i < numberOfElementsToFormat - 1; i++) { builder.append(listNumber.getInt(i)).append(", "); } builder.append(listNumber.getInt(numberOfElementsToFormat - 1)); } else if ((array instanceof VLongArray) || (array instanceof VULongArray)) { VNumberArray numberArray = (VNumberArray) array; ListNumber listNumber = numberArray.getData(); for (int i = 0; i < numberOfElementsToFormat - 1; i++) { builder.append(listNumber.getLong(i)).append(", "); } builder.append(listNumber.getLong(numberOfElementsToFormat - 1)); } else if ((array instanceof VShortArray) || (array instanceof VUShortArray)) { VNumberArray numberArray = (VNumberArray) array; ListNumber listNumber = numberArray.getData(); for (int i = 0; i < numberOfElementsToFormat - 1; i++) { builder.append(listNumber.getShort(i)).append(", "); } builder.append(listNumber.getShort(numberOfElementsToFormat - 1)); } else if ((array instanceof VByteArray) || (array instanceof VUByteArray)) { VNumberArray numberArray = (VNumberArray) array; ListNumber listNumber = numberArray.getData(); for (int i = 0; i < numberOfElementsToFormat - 1; i++) { builder.append(listNumber.getByte(i)).append(", "); } builder.append(listNumber.getByte(numberOfElementsToFormat - 1)); } else if ((array instanceof VDoubleArray)) { VNumberArray numberArray = (VNumberArray) array; ListNumber listNumber = numberArray.getData(); for (int i = 0; i < numberOfElementsToFormat - 1; i++) { builder.append(listNumber.getDouble(i)).append(", "); } builder.append(listNumber.getDouble(numberOfElementsToFormat - 1)); } else if ((array instanceof VFloatArray)) { VNumberArray numberArray = (VNumberArray) array; ListNumber listNumber = numberArray.getData(); for (int i = 0; i < numberOfElementsToFormat - 1; i++) { builder.append(listNumber.getFloat(i)).append(", "); } builder.append(listNumber.getFloat(numberOfElementsToFormat - 1)); } else if ((array instanceof VBooleanArray)) { VBooleanArray booleanArray = (VBooleanArray) array; ListBoolean listBoolean = booleanArray.getData(); for (int i = 0; i < numberOfElementsToFormat - 1; i++) { builder.append(listBoolean.getBoolean(i)).append(", "); } builder.append(listBoolean.getBoolean(numberOfElementsToFormat - 1)); } else if (array instanceof VStringArray) { VStringArray stringArray = (VStringArray) array; List<String> listString = stringArray.getData(); for (int i = 0; i < numberOfElementsToFormat - 1; i++) { builder.append(listString.get(i)).append(", "); } builder.append(listString.get(numberOfElementsToFormat - 1)); } else if (array instanceof VEnumArray) { VEnumArray enumArray = (VEnumArray) array; List<String> listString = enumArray.getData(); for (int i = 0; i < numberOfElementsToFormat - 1; i++) { builder.append(listString.get(i)).append(", "); } builder.append(listString.get(numberOfElementsToFormat - 1)); } if (numberOfElementsToFormat < totalElements) { builder.append(",..."); } else { builder.append("]"); } return builder.toString(); } 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); }
@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(){ ListInteger listInteger = ArrayInteger.of(1, 2, 3, 4, 5); Array array = VNumberArray.of(listInteger, Alarm.none(), Time.now(), Display.none()); String string = VTypeHelper.formatArray(array, 0); assertEquals("VIntArray", string); } @Test public void testFormatArrayNegativeMax(){ ListInteger listInteger = ArrayInteger.of(1, 2, 3, 4, 5); Array array = VNumberArray.of(listInteger, Alarm.none(), Time.now(), Display.none()); String string = VTypeHelper.formatArray(array, -1); assertEquals("VIntArray[1, 2, 3, 4, 5]", string); } @Test public void testFormatArrayWithSizes(){ ListInteger sizes = ArrayInteger.of(2, 3); ListInteger listInteger = ArrayInteger.of(11, 12, 21, 22, 31, 32); Array array = VNumberArray.of(listInteger, sizes, Alarm.none(), Time.now(), Display.none()); String string = VTypeHelper.formatArray(array, 3); assertEquals("VIntArray[11, 12, 21,...", string); string = VTypeHelper.formatArray(array, 10); assertEquals("VIntArray[11, 12, 21, 22, 31, 32]", string); } @Test public void testFormatIntArray(){ ListInteger listInteger = ArrayInteger.of(-1, 2, 3, 4, 5); Array array = VIntArray.of(listInteger, Alarm.none(), Time.now(), Display.none()); String string = VTypeHelper.formatArray(array, 3); assertEquals("VIntArray[-1, 2, 3,...", string); string = VTypeHelper.formatArray(array, 10); assertEquals("VIntArray[-1, 2, 3, 4, 5]", string); ListUInteger listUInteger = ArrayUInteger.of(1, 2, 3, 4, 5); array = VUIntArray.of(listUInteger, Alarm.none(), Time.now(), Display.none()); string = VTypeHelper.formatArray(array, 3); assertEquals("VUIntArray[1, 2, 3,...", string); string = VTypeHelper.formatArray(array, 10); assertEquals("VUIntArray[1, 2, 3, 4, 5]", string); } @Test public void testFormatLongArray(){ ListLong list = ArrayLong.of(-1L, 2L, 3L, 4L, 5L); Array array = VLongArray.of(list, Alarm.none(), Time.now(), Display.none()); String string = VTypeHelper.formatArray(array, 3); assertEquals("VLongArray[-1, 2, 3,...", string); string = VTypeHelper.formatArray(array, 10); assertEquals("VLongArray[-1, 2, 3, 4, 5]", string); ListULong listU = ArrayULong.of(1L, 2L, 3L, 4L, 5L); array = VUIntArray.of(listU, Alarm.none(), Time.now(), Display.none()); string = VTypeHelper.formatArray(array, 3); assertEquals("VULongArray[1, 2, 3,...", string); string = VTypeHelper.formatArray(array, 10); assertEquals("VULongArray[1, 2, 3, 4, 5]", string); } @Test public void testFormatShortArray(){ ListShort list = ArrayShort.of((short)-1, (short)2, (short)3, (short)4, (short)5); Array array = VShortArray.of(list, Alarm.none(), Time.now(), Display.none()); String string = VTypeHelper.formatArray(array, 3); assertEquals("VShortArray[-1, 2, 3,...", string); string = VTypeHelper.formatArray(array, 10); assertEquals("VShortArray[-1, 2, 3, 4, 5]", string); ListUShort listU = ArrayUShort.of((short)1, (short)2, (short)3, (short)4, (short)5); array = VUShortArray.of(listU, Alarm.none(), Time.now(), Display.none()); string = VTypeHelper.formatArray(array, 3); assertEquals("VUShortArray[1, 2, 3,...", string); string = VTypeHelper.formatArray(array, 10); assertEquals("VUShortArray[1, 2, 3, 4, 5]", string); } @Test public void testFormatByteArray(){ ListByte list = ArrayByte.of((byte)-1, (byte)2, (byte)3, (byte)4, (byte)5); Array array = VByteArray.of(list, Alarm.none(), Time.now(), Display.none()); String string = VTypeHelper.formatArray(array, 3); assertEquals("VByteArray[-1, 2, 3,...", string); string = VTypeHelper.formatArray(array, 10); assertEquals("VByteArray[-1, 2, 3, 4, 5]", string); ListUByte listU = ArrayUByte.of((byte)1, (byte)2, (byte)3, (byte)4, (byte)5); array = VUShortArray.of(listU, Alarm.none(), Time.now(), Display.none()); string = VTypeHelper.formatArray(array, 3); assertEquals("VUByteArray[1, 2, 3,...", string); string = VTypeHelper.formatArray(array, 10); assertEquals("VUByteArray[1, 2, 3, 4, 5]", string); } @Test public void testFormatBooleanArray(){ ListBoolean list = ArrayBoolean.of(true, true, false, false ,false); Array array = VBooleanArray.of(list, Alarm.none(), Time.now()); String string = VTypeHelper.formatArray(array, 3); assertEquals("VBooleanArray[true, true, false,...", string); string = VTypeHelper.formatArray(array, 10); assertEquals("VBooleanArray[true, true, false, false, false]", string); } @Test public void testFormatDoubleArray(){ ListDouble list = ArrayDouble.of(-1d, 0.27, 3.0f, 4.0f, 5.0f); Array array = VDoubleArray.of(list, Alarm.none(), Time.now(), Display.none()); String string = VTypeHelper.formatArray(array, 3); assertEquals("VDoubleArray[-1.0, 0.27, 3.0,...", string); string = VTypeHelper.formatArray(array, 10); assertEquals("VDoubleArray[-1.0, 0.27, 3.0, 4.0, 5.0]", string); } @Test public void testFormatFloatArray(){ ListFloat list = ArrayFloat.of(-1f, 0.27f, 3.0f, 4.0f, 5.0f); Array array = VDoubleArray.of(list, Alarm.none(), Time.now(), Display.none()); String string = VTypeHelper.formatArray(array, 3); assertEquals("VFloatArray[-1.0, 0.27, 3.0,...", string); string = VTypeHelper.formatArray(array, 10); assertEquals("VFloatArray[-1.0, 0.27, 3.0, 4.0, 5.0]", string); } @Test public void testFormatStringArray(){ Array array = VStringArray.of(Arrays.asList("a", "b", "c", "d", "e"), Alarm.none(), Time.now()); String string = VTypeHelper.formatArray(array, 3); assertEquals("VStringArray[a, b, c,...", string); string = VTypeHelper.formatArray(array, 10); assertEquals("VStringArray[a, b, c, d, e]", string); } @Test public void testFormatEnumArray(){ ListInteger listInteger = ArrayInteger.of(0, 1, 2, 3, 4); Array array = VEnumArray.of(listInteger, EnumDisplay.of("a", "b", "c", "d", "e"), Alarm.none(), Time.now()); String string = VTypeHelper.formatArray(array, 3); assertEquals("VEnumArray[a, b, c,...", string); string = VTypeHelper.formatArray(array, 10); assertEquals("VEnumArray[a, b, c, d, e]", string); }
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 instanceof VIntArray || vNumberArray instanceof VUIntArray || vNumberArray instanceof VLongArray || vNumberArray instanceof VULongArray) { IteratorNumber iterator = vNumberArray.getData().iterator(); while(iterator.hasNext()) { valueList.add(iterator.nextLong()); } } else if(vNumberArray instanceof VFloatArray) { IteratorFloat iterator = ((VFloatArray)vNumberArray).getData().iterator(); while(iterator.hasNext()) { valueList.add(iterator.nextFloat()); } } else if(vNumberArray instanceof VDoubleArray) { IteratorDouble iterator = ((VDoubleArray)vNumberArray).getData().iterator(); while(iterator.hasNext()) { valueList.add(iterator.nextDouble()); } } else { throw new PVConversionException(String.format("Unable to create JSON string for array type %s", vNumberArray.getClass().getCanonicalName())); } ObjectMapper objectMapper = new ObjectMapper(); try { return objectMapper.writeValueAsString(valueList); } catch (JsonProcessingException e) { throw new PVConversionException("Unable to write array values as JSON string"); } } private SnapshotDataConverter(); static SnapshotItem fromSnapshotPv(SnapshotPv snapshotPv, SnapshotPv readback); static SnapshotPv fromVType(VType vType); static VType toVType(SnapshotPv snapshotPv); }
@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, (byte) 2), alarm, time, display); assertEquals("[1,2]", SnapshotDataConverter.getNumberArrayValueString(vNumberArray)); vNumberArray = VShortArray.of(CollectionNumbers.toListShort((short) -1, (short) 2), alarm, time, display); assertEquals("[-1,2]", SnapshotDataConverter.getNumberArrayValueString(vNumberArray)); vNumberArray = VUShortArray.of(CollectionNumbers.toListUShort((short) 1, (short) 2), alarm, time, display); assertEquals("[1,2]", SnapshotDataConverter.getNumberArrayValueString(vNumberArray)); vNumberArray = VIntArray.of(CollectionNumbers.toListInt(-1, 2), alarm, time, display); assertEquals("[-1,2]", SnapshotDataConverter.getNumberArrayValueString(vNumberArray)); vNumberArray = VUIntArray.of(CollectionNumbers.toListUInt(1, 2), alarm, time, display); assertEquals("[1,2]", SnapshotDataConverter.getNumberArrayValueString(vNumberArray)); vNumberArray = VLongArray.of(CollectionNumbers.toListLong(-1L, 2L), alarm, time, display); assertEquals("[-1,2]", SnapshotDataConverter.getNumberArrayValueString(vNumberArray)); vNumberArray = VULongArray.of(CollectionNumbers.toListULong(1L, 2L), alarm, time, display); assertEquals("[1,2]", SnapshotDataConverter.getNumberArrayValueString(vNumberArray)); vNumberArray = VFloatArray.of(CollectionNumbers.toListFloat(1.2f, 2.1f), alarm, time, display); assertEquals("[1.2,2.1]", SnapshotDataConverter.getNumberArrayValueString(vNumberArray)); vNumberArray = VDoubleArray.of(CollectionNumbers.toListDouble(1.2, 2.1), alarm, time, display); assertEquals("[1.2,2.1]", SnapshotDataConverter.getNumberArrayValueString(vNumberArray)); }
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); }
@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)); }
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); }
@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()); }
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); }
@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); }
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); Time time = toTime(snapshotPv); Display display = Display.none(); try { switch(snapshotPv.getDataType()) { case BYTE:{ byte[] values = objectMapper.readValue(snapshotPv.getValue(), byte[].class); if(isScalar) { return VByte.of(values[0], alarm, time, display); } else { return VByteArray.of(CollectionNumbers.toListByte(values), sizes, alarm, time, display); } } case UBYTE:{ byte[] values = objectMapper.readValue(snapshotPv.getValue(), byte[].class); if(isScalar) { return VUByte.of(values[0], alarm, time, display); } else { return VByteArray.of(CollectionNumbers.toListUByte(values), sizes, alarm, time, display); } } case SHORT:{ short[] values = objectMapper.readValue(snapshotPv.getValue(), short[].class); if(isScalar) { return VShort.of(values[0], alarm, time, display); } else { return VShortArray.of(CollectionNumbers.toListShort(values), sizes, alarm, time, display); } } case USHORT:{ short[] values = objectMapper.readValue(snapshotPv.getValue(), short[].class); if(isScalar) { return VUShort.of(values[0], alarm, time, display); } else { return VUShortArray.of(CollectionNumbers.toListUShort(values), sizes, alarm, time, display); } } case INTEGER:{ int[] values = objectMapper.readValue(snapshotPv.getValue(), int[].class); if(isScalar) { return VInt.of(values[0], alarm, time, display); } else { return VIntArray.of(CollectionNumbers.toListInt(values), sizes, alarm, time, display); } } case UINTEGER:{ int[] values = objectMapper.readValue(snapshotPv.getValue(), int[].class); if(isScalar) { return VUInt.of(values[0], alarm, time, display); } else { return VUIntArray.of(CollectionNumbers.toListUInt(values), sizes, alarm, time, display); } } case LONG:{ long[] values = objectMapper.readValue(snapshotPv.getValue(), long[].class); if(isScalar) { return VLong.of(values[0], alarm, time, display); } else { return VLongArray.of(CollectionNumbers.toListLong(values), sizes, alarm, time, display); } } case ULONG:{ long[] values = objectMapper.readValue(snapshotPv.getValue(), long[].class); if(isScalar) { return VULong.of(values[0], alarm, time, display); } else { return VULongArray.of(CollectionNumbers.toListULong(values), sizes, alarm, time, display); } } case FLOAT:{ float[] values = objectMapper.readValue(snapshotPv.getValue(), float[].class); if(isScalar) { return VFloat.of(values[0], alarm, time, display); } else { return VFloatArray.of(CollectionNumbers.toListFloat(values), sizes, alarm, time, display); } } case DOUBLE:{ double[] values = objectMapper.readValue(snapshotPv.getValue(), double[].class); if(isScalar) { return VDouble.of(values[0], alarm, time, display); } else { return VDoubleArray.of(CollectionNumbers.toListDouble(values), sizes, alarm, time, display); } } case STRING:{ String[] values = objectMapper.readValue(snapshotPv.getValue(), String[].class); if(isScalar) { return VString.of(values[0], alarm, time); } else { return VStringArray.of(Arrays.asList(values), sizes, alarm, time); } } case ENUM:{ Object[] values = objectMapper.readValue(snapshotPv.getValue(), Object[].class); if (values.length == 2) { int index = (int) values[0]; List<String> choices = (List<String>) values[1]; EnumDisplay enumDisplay = EnumDisplay.of(choices); if (isScalar) { return VEnum.of(index, enumDisplay, alarm, time); } else { throw new PVConversionException("VEnumArray not supported"); } } else if (values.length == 1) { if (isScalar) { return VEnum.of(0, EnumDisplay.of((String) values[0]), alarm, time); } else { throw new PVConversionException("VEnumArray not supported"); } } else { throw new PVConversionException("Wrong data size! VEnum DB data has been corrupted!"); } } } } catch (Exception e) { throw new PVConversionException(String.format("Unable to convert to VType, cause: %s", e.getMessage())); } throw new PVConversionException(String.format("Cannot convert to PVType from internal type %s", snapshotPv.getDataType())); } private SnapshotDataConverter(); static SnapshotItem fromSnapshotPv(SnapshotPv snapshotPv, SnapshotPv readback); static SnapshotPv fromVType(VType vType); static VType toVType(SnapshotPv snapshotPv); }
@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) SnapshotDataConverter.toVType(snapshotPv); assertEquals(1, vByte.getValue().byteValue()); assertEquals(1000L, vByte.getTime().getTimestamp().getEpochSecond()); assertEquals(7000, vByte.getTime().getTimestamp().getNano()); assertEquals(AlarmSeverity.NONE, vByte.getAlarm().getSeverity()); assertEquals(AlarmStatus.NONE, vByte.getAlarm().getStatus()); assertEquals("name", vByte.getAlarm().getName()); snapshotPv = SnapshotPv.builder().alarmName("name").alarmStatus(AlarmStatus.NONE) .alarmSeverity(AlarmSeverity.NONE).dataType(SnapshotPvDataType.UBYTE) .sizes(SnapshotDataConverter.SCALAR_AS_JSON).time(1000L).timens(7000).value("[1]").build(); VUByte vUByte = (VUByte) SnapshotDataConverter.toVType(snapshotPv); assertEquals(1, vUByte.getValue().byteValue()); assertEquals(1000L, vUByte.getTime().getTimestamp().getEpochSecond()); assertEquals(7000, vUByte.getTime().getTimestamp().getNano()); assertEquals(AlarmSeverity.NONE, vUByte.getAlarm().getSeverity()); assertEquals(AlarmStatus.NONE, vUByte.getAlarm().getStatus()); assertEquals("name", vUByte.getAlarm().getName()); snapshotPv = SnapshotPv.builder().alarmName("name").alarmStatus(AlarmStatus.NONE) .alarmSeverity(AlarmSeverity.NONE).dataType(SnapshotPvDataType.BYTE).sizes("[1,2,3]").time(1000L) .timens(7000).value("[1,2,3,4,5,6]").build(); VByteArray vByteArray = (VByteArray) SnapshotDataConverter.toVType(snapshotPv); assertEquals(6, vByteArray.getData().size()); snapshotPv = SnapshotPv.builder().alarmName("name").alarmStatus(AlarmStatus.NONE) .alarmSeverity(AlarmSeverity.NONE).dataType(SnapshotPvDataType.UBYTE).sizes("[1,2,3]").time(1000L) .timens(7000).value("[1,2,3,4,5,6]").build(); assertTrue(SnapshotDataConverter.toVType(snapshotPv) instanceof VUByteArray); snapshotPv = SnapshotPv.builder().alarmName("name").alarmStatus(AlarmStatus.NONE) .alarmSeverity(AlarmSeverity.NONE).dataType(SnapshotPvDataType.INTEGER) .sizes(SnapshotDataConverter.SCALAR_AS_JSON).time(1000L).timens(7000).value("[1]").build(); assertTrue(SnapshotDataConverter.toVType(snapshotPv) instanceof VInt); snapshotPv.setDataType(SnapshotPvDataType.UINTEGER); assertTrue(SnapshotDataConverter.toVType(snapshotPv) instanceof VUInt); snapshotPv.setDataType(SnapshotPvDataType.SHORT); assertTrue(SnapshotDataConverter.toVType(snapshotPv) instanceof VShort); snapshotPv.setDataType(SnapshotPvDataType.USHORT); assertTrue(SnapshotDataConverter.toVType(snapshotPv) instanceof VUShort); snapshotPv.setDataType(SnapshotPvDataType.LONG); assertTrue(SnapshotDataConverter.toVType(snapshotPv) instanceof VLong); snapshotPv.setDataType(SnapshotPvDataType.ULONG); assertTrue(SnapshotDataConverter.toVType(snapshotPv) instanceof VULong); snapshotPv.setDataType(SnapshotPvDataType.FLOAT); snapshotPv.setValue("[1.1]"); assertTrue(SnapshotDataConverter.toVType(snapshotPv) instanceof VFloat); snapshotPv.setDataType(SnapshotPvDataType.DOUBLE); snapshotPv.setValue("[1.1]"); assertTrue(SnapshotDataConverter.toVType(snapshotPv) instanceof VDouble); snapshotPv = SnapshotPv.builder().alarmName("name").alarmStatus(AlarmStatus.NONE) .alarmSeverity(AlarmSeverity.NONE).dataType(SnapshotPvDataType.SHORT).sizes("[1,2,3]").time(1000L) .timens(7000).value("[1,2,3,4,5,6]").build(); assertTrue(SnapshotDataConverter.toVType(snapshotPv) instanceof VShortArray); snapshotPv.setDataType(SnapshotPvDataType.USHORT); assertTrue(SnapshotDataConverter.toVType(snapshotPv) instanceof VUShortArray); snapshotPv.setDataType(SnapshotPvDataType.INTEGER); assertTrue(SnapshotDataConverter.toVType(snapshotPv) instanceof VIntArray); snapshotPv.setDataType(SnapshotPvDataType.UINTEGER); assertTrue(SnapshotDataConverter.toVType(snapshotPv) instanceof VUIntArray); snapshotPv.setDataType(SnapshotPvDataType.LONG); assertTrue(SnapshotDataConverter.toVType(snapshotPv) instanceof VLongArray); snapshotPv.setDataType(SnapshotPvDataType.ULONG); assertTrue(SnapshotDataConverter.toVType(snapshotPv) instanceof VULongArray); snapshotPv.setDataType(SnapshotPvDataType.FLOAT); snapshotPv.setValue("[1.1, 2.2]"); assertTrue(SnapshotDataConverter.toVType(snapshotPv) instanceof VFloatArray); snapshotPv.setDataType(SnapshotPvDataType.DOUBLE); assertTrue(SnapshotDataConverter.toVType(snapshotPv) instanceof VDoubleArray); snapshotPv.setDataType(SnapshotPvDataType.STRING); snapshotPv.setSizes(SnapshotDataConverter.SCALAR_AS_JSON); snapshotPv.setValue("[\"string\"]"); assertTrue(SnapshotDataConverter.toVType(snapshotPv) instanceof VString); snapshotPv = SnapshotPv.builder().alarmName("name").alarmStatus(AlarmStatus.NONE) .alarmSeverity(AlarmSeverity.NONE).dataType(SnapshotPvDataType.STRING).sizes("[1,2,3]").time(1000L) .timens(7000).value("[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\"]").build(); assertTrue(SnapshotDataConverter.toVType(snapshotPv) instanceof VStringArray); snapshotPv = SnapshotPv.builder().alarmName("name").alarmStatus(AlarmStatus.NONE) .alarmSeverity(AlarmSeverity.NONE).dataType(SnapshotPvDataType.ENUM).sizes("[1]").time(1000L) .timens(7000).value("[1,[\"a\",\"b\",\"c\"]]").build(); assertTrue(SnapshotDataConverter.toVType(snapshotPv) instanceof VEnum); } @Test public void jsonTest() throws Exception { VLongArray vIntArray = VLongArray.of(new ArrayLong(CollectionNumbers.toListLong(-1, 2, 3)), alarm, time, display); String json1 = org.epics.vtype.json.VTypeToJson.toJson(vIntArray).toString(); VULongArray vULongArray = VULongArray.of(new ArrayULong(CollectionNumbers.toListULong(1, 2, 3)), alarm, time, display); VTypeToJson.toJson(vULongArray).toString(); VLongArray deserialized1 = (VLongArray) VTypeToJson .toVType(Json.createReader(new ByteArrayInputStream(json1.getBytes())).readObject()); assertEquals(-1, deserialized1.getData().getLong(0)); }
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() != null) { snapshotItem.setValue(toVType(snapshotPv)); } if(readback != null) { snapshotItem.setReadbackValue(toVType(readback)); } return snapshotItem; } private SnapshotDataConverter(); static SnapshotItem fromSnapshotPv(SnapshotPv snapshotPv, SnapshotPv readback); static SnapshotPv fromVType(VType vType); static VType toVType(SnapshotPv snapshotPv); }
@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(); SnapshotPv readback = 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(); SnapshotItem snapshotItem = SnapshotDataConverter.fromSnapshotPv(snapshotPv, readback); assertEquals(2, snapshotItem.getSnapshotId()); assertEquals(1, snapshotItem.getConfigPv().getId()); assertNotNull(snapshotItem.getReadbackValue()); snapshotPv = SnapshotPv.builder().snapshotId(1).configPv(ConfigPv.builder().id(1).build()).build(); snapshotItem = SnapshotDataConverter.fromSnapshotPv(snapshotPv, readback); assertNull(snapshotItem.getValue()); snapshotItem = SnapshotDataConverter.fromSnapshotPv(snapshotPv, null); assertNull(snapshotItem.getReadbackValue()); }
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); }
@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); }
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")) .alarmSeverity(resultSet.getString("severity") == null ? null : AlarmSeverity.valueOf(resultSet.getString("severity"))) .alarmStatus(resultSet.getString("status") == null ? null : AlarmStatus.valueOf(resultSet.getString("status"))) .time(resultSet.getLong("time")) .timens(resultSet.getInt("timens")) .value(resultSet.getString("value")) .sizes(resultSet.getString("sizes")) .dataType(resultSet.getString("data_type") == null ? null : SnapshotPvDataType.valueOf(resultSet.getString("data_type"))) .build(); } @Override SnapshotPv mapRow(ResultSet resultSet, int rowIndex); }
@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.getString("status")).thenReturn("NONE"); when(resultSet.getLong("time")).thenReturn(777L); when(resultSet.getInt("timens")).thenReturn(1); when(resultSet.getString("value")).thenReturn("[7]"); when(resultSet.getString("sizes")).thenReturn("[1]"); when(resultSet.getString("data_type")).thenReturn("INTEGER"); when(resultSet.getString("name")).thenReturn("pvname"); when(resultSet.getString("readback_name")).thenReturn("pvname"); when(resultSet.getString("provider")).thenReturn("ca"); assertTrue(new SnapshotPvRowMapper().mapRow(resultSet, 0) instanceof SnapshotPv); }
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); }
@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()); }
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); }
@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>>() { }); }
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 = true) List<SnapshotItem> snapshotItems) { if(snapshotName.length() == 0 || userName.length() == 0 || comment.length() == 0) { throw new IllegalArgumentException("Snapshot name, user name and comment must be of non-zero length"); } return services.saveSnapshot(configUniqueId, snapshotItems, snapshotName, userName, comment); } @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); }
@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> o) { return true; } }), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(Node.builder().build()); MockHttpServletRequestBuilder request = put("/snapshot/configid").param("snapshotName", "a").param("comment", "c").param("userName", "u"); mockMvc.perform(request).andExpect(status().isBadRequest()); request = put("/snapshot/configid") .contentType(JSON) .content(objectMapper.writeValueAsString(snapshotItems)) .param("snapshotName", "a").param("comment", "c").param("userName", "u"); MvcResult result = mockMvc.perform(request).andExpect(status().isOk()).andExpect(content().contentType(JSON)) .andReturn(); objectMapper.readValue(result.getResponse().getContentAsString(), Node.class); }
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); }
@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); }
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 final String uniqueNodeId); @GetMapping("/root") Node getRootNode(); @GetMapping("/node/{uniqueNodeId}/parent") Node getParentNode(@PathVariable String uniqueNodeId); @GetMapping("/node/{uniqueNodeId}/children") List<Node> getChildNodes(@PathVariable final String uniqueNodeId); @PostMapping("/config/{uniqueNodeId}/update") ResponseEntity<Node> updateConfiguration(@PathVariable String uniqueNodeId, @RequestBody UpdateConfigHolder updateConfigHolder); @DeleteMapping("/node/{uniqueNodeId}") void deleteNode(@PathVariable final String uniqueNodeId); @GetMapping("/config/{uniqueNodeId}/snapshots") List<Node> getSnapshots(@PathVariable String uniqueNodeId); @PostMapping("/node/{uniqueNodeId}") Node moveNode(@PathVariable String uniqueNodeId, @RequestParam(value = "to", required = true) String to, @RequestParam(value = "username", required = true) String userName); @PostMapping("/node/{uniqueNodeId}/update") Node updateNode(@PathVariable String uniqueNodeId, @RequestParam(value = "customTimeForMigration", required = true) String customTimeForMigration, @RequestBody Node nodeToUpdate); @GetMapping("/config/{uniqueNodeId}/items") List<ConfigPv> getConfigPvs(@PathVariable String uniqueNodeId); @GetMapping("/path/{uniqueNodeId}") String getFullPath(@PathVariable String uniqueNodeId); @GetMapping("/path") List<Node> getFromPath(@RequestParam(value = "path") String path); }
@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.getResponse().getContentAsString(); objectMapper.readValue(s, Node.class); }
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-zero length"); } if(node.getName() == null || node.getName().isEmpty()) { throw new IllegalArgumentException("Node name must be non-null and of non-zero length"); } return services.createNode(parentsUniqueId, node); } @PutMapping("/node/{parentsUniqueId}") Node createNode(@PathVariable String parentsUniqueId, @RequestBody final Node node); @GetMapping("/node/{uniqueNodeId}") Node getNode(@PathVariable final String uniqueNodeId); @GetMapping("/root") Node getRootNode(); @GetMapping("/node/{uniqueNodeId}/parent") Node getParentNode(@PathVariable String uniqueNodeId); @GetMapping("/node/{uniqueNodeId}/children") List<Node> getChildNodes(@PathVariable final String uniqueNodeId); @PostMapping("/config/{uniqueNodeId}/update") ResponseEntity<Node> updateConfiguration(@PathVariable String uniqueNodeId, @RequestBody UpdateConfigHolder updateConfigHolder); @DeleteMapping("/node/{uniqueNodeId}") void deleteNode(@PathVariable final String uniqueNodeId); @GetMapping("/config/{uniqueNodeId}/snapshots") List<Node> getSnapshots(@PathVariable String uniqueNodeId); @PostMapping("/node/{uniqueNodeId}") Node moveNode(@PathVariable String uniqueNodeId, @RequestParam(value = "to", required = true) String to, @RequestParam(value = "username", required = true) String userName); @PostMapping("/node/{uniqueNodeId}/update") Node updateNode(@PathVariable String uniqueNodeId, @RequestParam(value = "customTimeForMigration", required = true) String customTimeForMigration, @RequestBody Node nodeToUpdate); @GetMapping("/config/{uniqueNodeId}/items") List<ConfigPv> getConfigPvs(@PathVariable String uniqueNodeId); @GetMapping("/path/{uniqueNodeId}") String getFullPath(@PathVariable String uniqueNodeId); @GetMapping("/path") List<Node> getFromPath(@RequestParam(value = "path") String path); }
@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).andExpect(status().isOk()).andExpect(content().contentType(JSON)) .andReturn(); String s = result.getResponse().getContentAsString(); objectMapper.readValue(s, Node.class); } @Test public void testCreateFolderParentIdDoesNotExist() throws Exception { when(services.createNode("p", folderFromClient)) .thenThrow(new IllegalArgumentException("Parent folder does not exist")); MockHttpServletRequestBuilder request = put("/node/p").contentType(JSON) .content(objectMapper.writeValueAsString(folderFromClient)); mockMvc.perform(request).andExpect(status().isBadRequest()); } @Test public void testCreateConfig() throws Exception { reset(services); Node config = Node.builder().nodeType(NodeType.CONFIGURATION).name("config").uniqueId("hhh") .userName("user").build(); when(services.createNode("p", config)).thenAnswer(new Answer<Node>() { public Node answer(InvocationOnMock invocation) throws Throwable { return config1; } }); MockHttpServletRequestBuilder request = put("/node/p").contentType(JSON).content(objectMapper.writeValueAsString(config)); MvcResult result = mockMvc.perform(request).andExpect(status().isOk()).andExpect(content().contentType(JSON)) .andReturn(); objectMapper.readValue(result.getResponse().getContentAsString(), Node.class); }
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, @RequestBody final Node node); @GetMapping("/node/{uniqueNodeId}") Node getNode(@PathVariable final String uniqueNodeId); @GetMapping("/root") Node getRootNode(); @GetMapping("/node/{uniqueNodeId}/parent") Node getParentNode(@PathVariable String uniqueNodeId); @GetMapping("/node/{uniqueNodeId}/children") List<Node> getChildNodes(@PathVariable final String uniqueNodeId); @PostMapping("/config/{uniqueNodeId}/update") ResponseEntity<Node> updateConfiguration(@PathVariable String uniqueNodeId, @RequestBody UpdateConfigHolder updateConfigHolder); @DeleteMapping("/node/{uniqueNodeId}") void deleteNode(@PathVariable final String uniqueNodeId); @GetMapping("/config/{uniqueNodeId}/snapshots") List<Node> getSnapshots(@PathVariable String uniqueNodeId); @PostMapping("/node/{uniqueNodeId}") Node moveNode(@PathVariable String uniqueNodeId, @RequestParam(value = "to", required = true) String to, @RequestParam(value = "username", required = true) String userName); @PostMapping("/node/{uniqueNodeId}/update") Node updateNode(@PathVariable String uniqueNodeId, @RequestParam(value = "customTimeForMigration", required = true) String customTimeForMigration, @RequestBody Node nodeToUpdate); @GetMapping("/config/{uniqueNodeId}/items") List<ConfigPv> getConfigPvs(@PathVariable String uniqueNodeId); @GetMapping("/path/{uniqueNodeId}") String getFullPath(@PathVariable String uniqueNodeId); @GetMapping("/path") List<Node> getFromPath(@RequestParam(value = "path") String path); }
@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").contentType(JSON); MvcResult result = mockMvc.perform(request).andExpect(status().isOk()).andExpect(content().contentType(JSON)) .andReturn(); List<Node> childNodes = objectMapper.readValue(result.getResponse().getContentAsString(), new TypeReference<List<Node>>() { }); assertEquals(1, childNodes.size()); } @Test public void testGetChildNodesNonExistingNode() throws Exception{ reset(services); when(services.getChildNodes("non-existing")).thenThrow(NodeNotFoundException.class); MockHttpServletRequestBuilder request = get("/node/non-existing/children").contentType(JSON); mockMvc.perform(request).andExpect(status().isNotFound()); }
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); @GetMapping("/node/{uniqueNodeId}") Node getNode(@PathVariable final String uniqueNodeId); @GetMapping("/root") Node getRootNode(); @GetMapping("/node/{uniqueNodeId}/parent") Node getParentNode(@PathVariable String uniqueNodeId); @GetMapping("/node/{uniqueNodeId}/children") List<Node> getChildNodes(@PathVariable final String uniqueNodeId); @PostMapping("/config/{uniqueNodeId}/update") ResponseEntity<Node> updateConfiguration(@PathVariable String uniqueNodeId, @RequestBody UpdateConfigHolder updateConfigHolder); @DeleteMapping("/node/{uniqueNodeId}") void deleteNode(@PathVariable final String uniqueNodeId); @GetMapping("/config/{uniqueNodeId}/snapshots") List<Node> getSnapshots(@PathVariable String uniqueNodeId); @PostMapping("/node/{uniqueNodeId}") Node moveNode(@PathVariable String uniqueNodeId, @RequestParam(value = "to", required = true) String to, @RequestParam(value = "username", required = true) String userName); @PostMapping("/node/{uniqueNodeId}/update") Node updateNode(@PathVariable String uniqueNodeId, @RequestParam(value = "customTimeForMigration", required = true) String customTimeForMigration, @RequestBody Node nodeToUpdate); @GetMapping("/config/{uniqueNodeId}/items") List<ConfigPv> getConfigPvs(@PathVariable String uniqueNodeId); @GetMapping("/path/{uniqueNodeId}") String getFullPath(@PathVariable String uniqueNodeId); @GetMapping("/path") List<Node> getFromPath(@RequestParam(value = "path") String path); }
@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 Exception { when(services.getNode("q")).thenReturn(Node.builder().id(1).uniqueId("q").build()); MockHttpServletRequestBuilder request = get("/node/q"); MvcResult result = mockMvc.perform(request).andExpect(status().isOk()).andExpect(content().contentType(JSON)) .andReturn(); objectMapper.readValue(result.getResponse().getContentAsString(), Node.class); } @Test public void testGetConfiguration() throws Exception { Mockito.reset(services); when(services.getNode("a")).thenReturn(Node.builder().build()); MockHttpServletRequestBuilder request = get("/node/a"); MvcResult result = mockMvc.perform(request).andExpect(status().isOk()).andExpect(content().contentType(JSON)) .andReturn(); objectMapper.readValue(result.getResponse().getContentAsString(), Node.class); } @Test public void testGetNonExistingConfiguration() throws Exception { Mockito.reset(services); when(services.getNode("a")).thenThrow(NodeNotFoundException.class); MockHttpServletRequestBuilder request = get("/node/a"); mockMvc.perform(request).andExpect(status().isNotFound()); } @Test public void testGetNonExistingFolder() throws Exception { Mockito.reset(services); when(services.getNode("a")).thenThrow(NodeNotFoundException.class); MockHttpServletRequestBuilder request = get("/node/a"); mockMvc.perform(request).andExpect(status().isNotFound()); when(services.getNode("b")).thenThrow(IllegalArgumentException.class); request = get("/node/b"); mockMvc.perform(request).andExpect(status().isBadRequest()); } @Test public void testGetFolderIllegalArgument() throws Exception { when(services.getNode("a")).thenThrow(IllegalArgumentException.class); MockHttpServletRequestBuilder request = get("/node/a"); mockMvc.perform(request).andExpect(status().isBadRequest()); }
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 final Node node); @GetMapping("/node/{uniqueNodeId}") Node getNode(@PathVariable final String uniqueNodeId); @GetMapping("/root") Node getRootNode(); @GetMapping("/node/{uniqueNodeId}/parent") Node getParentNode(@PathVariable String uniqueNodeId); @GetMapping("/node/{uniqueNodeId}/children") List<Node> getChildNodes(@PathVariable final String uniqueNodeId); @PostMapping("/config/{uniqueNodeId}/update") ResponseEntity<Node> updateConfiguration(@PathVariable String uniqueNodeId, @RequestBody UpdateConfigHolder updateConfigHolder); @DeleteMapping("/node/{uniqueNodeId}") void deleteNode(@PathVariable final String uniqueNodeId); @GetMapping("/config/{uniqueNodeId}/snapshots") List<Node> getSnapshots(@PathVariable String uniqueNodeId); @PostMapping("/node/{uniqueNodeId}") Node moveNode(@PathVariable String uniqueNodeId, @RequestParam(value = "to", required = true) String to, @RequestParam(value = "username", required = true) String userName); @PostMapping("/node/{uniqueNodeId}/update") Node updateNode(@PathVariable String uniqueNodeId, @RequestParam(value = "customTimeForMigration", required = true) String customTimeForMigration, @RequestBody Node nodeToUpdate); @GetMapping("/config/{uniqueNodeId}/items") List<ConfigPv> getConfigPvs(@PathVariable String uniqueNodeId); @GetMapping("/path/{uniqueNodeId}") String getFullPath(@PathVariable String uniqueNodeId); @GetMapping("/path") List<Node> getFromPath(@RequestParam(value = "path") String path); }
@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)) .andReturn(); objectMapper.readValue(result.getResponse().getContentAsString(), new TypeReference<List<Node>>() { }); reset(services); } @Test public void testGetSnapshotsForNonExistingConfig() throws Exception { when(services.getSnapshots("x")).thenThrow(new NodeNotFoundException("lasdfk")); MockHttpServletRequestBuilder request = get("/config/x/snapshots").contentType(JSON); mockMvc.perform(request).andExpect(status().isNotFound()); }
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); @GetMapping("/node/{uniqueNodeId}") Node getNode(@PathVariable final String uniqueNodeId); @GetMapping("/root") Node getRootNode(); @GetMapping("/node/{uniqueNodeId}/parent") Node getParentNode(@PathVariable String uniqueNodeId); @GetMapping("/node/{uniqueNodeId}/children") List<Node> getChildNodes(@PathVariable final String uniqueNodeId); @PostMapping("/config/{uniqueNodeId}/update") ResponseEntity<Node> updateConfiguration(@PathVariable String uniqueNodeId, @RequestBody UpdateConfigHolder updateConfigHolder); @DeleteMapping("/node/{uniqueNodeId}") void deleteNode(@PathVariable final String uniqueNodeId); @GetMapping("/config/{uniqueNodeId}/snapshots") List<Node> getSnapshots(@PathVariable String uniqueNodeId); @PostMapping("/node/{uniqueNodeId}") Node moveNode(@PathVariable String uniqueNodeId, @RequestParam(value = "to", required = true) String to, @RequestParam(value = "username", required = true) String userName); @PostMapping("/node/{uniqueNodeId}/update") Node updateNode(@PathVariable String uniqueNodeId, @RequestParam(value = "customTimeForMigration", required = true) String customTimeForMigration, @RequestBody Node nodeToUpdate); @GetMapping("/config/{uniqueNodeId}/items") List<ConfigPv> getConfigPvs(@PathVariable String uniqueNodeId); @GetMapping("/path/{uniqueNodeId}") String getFullPath(@PathVariable String uniqueNodeId); @GetMapping("/path") List<Node> getFromPath(@RequestParam(value = "path") String path); }
@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().isBadRequest()); }
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); }
@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); } @PutMapping("/node/{parentsUniqueId}") Node createNode(@PathVariable String parentsUniqueId, @RequestBody final Node node); @GetMapping("/node/{uniqueNodeId}") Node getNode(@PathVariable final String uniqueNodeId); @GetMapping("/root") Node getRootNode(); @GetMapping("/node/{uniqueNodeId}/parent") Node getParentNode(@PathVariable String uniqueNodeId); @GetMapping("/node/{uniqueNodeId}/children") List<Node> getChildNodes(@PathVariable final String uniqueNodeId); @PostMapping("/config/{uniqueNodeId}/update") ResponseEntity<Node> updateConfiguration(@PathVariable String uniqueNodeId, @RequestBody UpdateConfigHolder updateConfigHolder); @DeleteMapping("/node/{uniqueNodeId}") void deleteNode(@PathVariable final String uniqueNodeId); @GetMapping("/config/{uniqueNodeId}/snapshots") List<Node> getSnapshots(@PathVariable String uniqueNodeId); @PostMapping("/node/{uniqueNodeId}") Node moveNode(@PathVariable String uniqueNodeId, @RequestParam(value = "to", required = true) String to, @RequestParam(value = "username", required = true) String userName); @PostMapping("/node/{uniqueNodeId}/update") Node updateNode(@PathVariable String uniqueNodeId, @RequestParam(value = "customTimeForMigration", required = true) String customTimeForMigration, @RequestBody Node nodeToUpdate); @GetMapping("/config/{uniqueNodeId}/items") List<ConfigPv> getConfigPvs(@PathVariable String uniqueNodeId); @GetMapping("/path/{uniqueNodeId}") String getFullPath(@PathVariable String uniqueNodeId); @GetMapping("/path") List<Node> getFromPath(@RequestParam(value = "path") String path); }
@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().isOk()).andExpect(content().contentType(JSON)) .andReturn(); objectMapper.readValue(result.getResponse().getContentAsString(), Node.class); }
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 update a null configuration"); } else if(updateConfigHolder.getConfigPvList() == null) { throw new IllegalArgumentException("Cannot update a configration with a null config PV list"); } else if(updateConfigHolder.getConfig().getUserName() == null || updateConfigHolder.getConfig().getUserName().isEmpty()) { throw new IllegalArgumentException("Will not update a configuration where user name is null or empty"); } for(ConfigPv configPv : updateConfigHolder.getConfigPvList()) { if(configPv.getPvName() == null || configPv.getPvName().isEmpty()) { throw new IllegalArgumentException("Cannot update configuration, encountered a null or empty PV name"); } } return new ResponseEntity<>(services.updateConfiguration(updateConfigHolder.getConfig(), updateConfigHolder.getConfigPvList()), HttpStatus.OK); } @PutMapping("/node/{parentsUniqueId}") Node createNode(@PathVariable String parentsUniqueId, @RequestBody final Node node); @GetMapping("/node/{uniqueNodeId}") Node getNode(@PathVariable final String uniqueNodeId); @GetMapping("/root") Node getRootNode(); @GetMapping("/node/{uniqueNodeId}/parent") Node getParentNode(@PathVariable String uniqueNodeId); @GetMapping("/node/{uniqueNodeId}/children") List<Node> getChildNodes(@PathVariable final String uniqueNodeId); @PostMapping("/config/{uniqueNodeId}/update") ResponseEntity<Node> updateConfiguration(@PathVariable String uniqueNodeId, @RequestBody UpdateConfigHolder updateConfigHolder); @DeleteMapping("/node/{uniqueNodeId}") void deleteNode(@PathVariable final String uniqueNodeId); @GetMapping("/config/{uniqueNodeId}/snapshots") List<Node> getSnapshots(@PathVariable String uniqueNodeId); @PostMapping("/node/{uniqueNodeId}") Node moveNode(@PathVariable String uniqueNodeId, @RequestParam(value = "to", required = true) String to, @RequestParam(value = "username", required = true) String userName); @PostMapping("/node/{uniqueNodeId}/update") Node updateNode(@PathVariable String uniqueNodeId, @RequestParam(value = "customTimeForMigration", required = true) String customTimeForMigration, @RequestBody Node nodeToUpdate); @GetMapping("/config/{uniqueNodeId}/items") List<ConfigPv> getConfigPvs(@PathVariable String uniqueNodeId); @GetMapping("/path/{uniqueNodeId}") String getFullPath(@PathVariable String uniqueNodeId); @GetMapping("/path") List<Node> getFromPath(@RequestParam(value = "path") String path); }
@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).configPvList(configPvList).build(); when(services.updateConfiguration(holder.getConfig(), holder.getConfigPvList())).thenReturn(config); MockHttpServletRequestBuilder request = post("/config/a/update").contentType(JSON) .content(objectMapper.writeValueAsString(holder)); MvcResult result = mockMvc.perform(request).andExpect(status().isOk()).andExpect(content().contentType(JSON)) .andReturn(); objectMapper.readValue(result.getResponse().getContentAsString(), Node.class); } @Test public void testUpdateConfigBadConfigPv() throws Exception { Node config = Node.builder().nodeType(NodeType.CONFIGURATION).id(0).build(); UpdateConfigHolder holder = UpdateConfigHolder.builder().build(); MockHttpServletRequestBuilder request = post("/config/a/update").contentType(JSON) .content(objectMapper.writeValueAsString(holder)); mockMvc.perform(request).andExpect(status().isBadRequest()); holder.setConfig(config); request = post("/config/a/update").contentType(JSON) .content(objectMapper.writeValueAsString(holder)); mockMvc.perform(request).andExpect(status().isBadRequest()); List<ConfigPv> configPvList = Arrays.asList(ConfigPv.builder().build()); holder.setConfigPvList(configPvList); when(services.updateConfiguration(holder.getConfig(), holder.getConfigPvList())).thenReturn(config); request = post("/config/a/update").contentType(JSON) .content(objectMapper.writeValueAsString(holder)); mockMvc.perform(request).andExpect(status().isBadRequest()); request = post("/config/a/update").contentType(JSON) .content(objectMapper.writeValueAsString(holder)); mockMvc.perform(request).andExpect(status().isBadRequest()); config.setUserName(""); request = post("/config/a/update").contentType(JSON) .content(objectMapper.writeValueAsString(holder)); mockMvc.perform(request).andExpect(status().isBadRequest()); configPvList = Arrays.asList(ConfigPv.builder().pvName("").build()); holder.setConfigPvList(configPvList); request = post("/config/a/update").contentType(JSON) .content(objectMapper.writeValueAsString(holder)); mockMvc.perform(request).andExpect(status().isBadRequest()); }
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, Boolean.valueOf(customTimeForMigration)); } @PutMapping("/node/{parentsUniqueId}") Node createNode(@PathVariable String parentsUniqueId, @RequestBody final Node node); @GetMapping("/node/{uniqueNodeId}") Node getNode(@PathVariable final String uniqueNodeId); @GetMapping("/root") Node getRootNode(); @GetMapping("/node/{uniqueNodeId}/parent") Node getParentNode(@PathVariable String uniqueNodeId); @GetMapping("/node/{uniqueNodeId}/children") List<Node> getChildNodes(@PathVariable final String uniqueNodeId); @PostMapping("/config/{uniqueNodeId}/update") ResponseEntity<Node> updateConfiguration(@PathVariable String uniqueNodeId, @RequestBody UpdateConfigHolder updateConfigHolder); @DeleteMapping("/node/{uniqueNodeId}") void deleteNode(@PathVariable final String uniqueNodeId); @GetMapping("/config/{uniqueNodeId}/snapshots") List<Node> getSnapshots(@PathVariable String uniqueNodeId); @PostMapping("/node/{uniqueNodeId}") Node moveNode(@PathVariable String uniqueNodeId, @RequestParam(value = "to", required = true) String to, @RequestParam(value = "username", required = true) String userName); @PostMapping("/node/{uniqueNodeId}/update") Node updateNode(@PathVariable String uniqueNodeId, @RequestParam(value = "customTimeForMigration", required = true) String customTimeForMigration, @RequestBody Node nodeToUpdate); @GetMapping("/config/{uniqueNodeId}/items") List<ConfigPv> getConfigPvs(@PathVariable String uniqueNodeId); @GetMapping("/path/{uniqueNodeId}") String getFullPath(@PathVariable String uniqueNodeId); @GetMapping("/path") List<Node> getFromPath(@RequestParam(value = "path") String path); }
@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.writeValueAsString(node)); MvcResult result = mockMvc.perform(request).andExpect(status().isOk()).andExpect(content().contentType(JSON)) .andReturn(); objectMapper.readValue(result.getResponse().getContentAsString(), Node.class); }
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 final Node node); @GetMapping("/node/{uniqueNodeId}") Node getNode(@PathVariable final String uniqueNodeId); @GetMapping("/root") Node getRootNode(); @GetMapping("/node/{uniqueNodeId}/parent") Node getParentNode(@PathVariable String uniqueNodeId); @GetMapping("/node/{uniqueNodeId}/children") List<Node> getChildNodes(@PathVariable final String uniqueNodeId); @PostMapping("/config/{uniqueNodeId}/update") ResponseEntity<Node> updateConfiguration(@PathVariable String uniqueNodeId, @RequestBody UpdateConfigHolder updateConfigHolder); @DeleteMapping("/node/{uniqueNodeId}") void deleteNode(@PathVariable final String uniqueNodeId); @GetMapping("/config/{uniqueNodeId}/snapshots") List<Node> getSnapshots(@PathVariable String uniqueNodeId); @PostMapping("/node/{uniqueNodeId}") Node moveNode(@PathVariable String uniqueNodeId, @RequestParam(value = "to", required = true) String to, @RequestParam(value = "username", required = true) String userName); @PostMapping("/node/{uniqueNodeId}/update") Node updateNode(@PathVariable String uniqueNodeId, @RequestParam(value = "customTimeForMigration", required = true) String customTimeForMigration, @RequestBody Node nodeToUpdate); @GetMapping("/config/{uniqueNodeId}/items") List<ConfigPv> getConfigPvs(@PathVariable String uniqueNodeId); @GetMapping("/path/{uniqueNodeId}") String getFullPath(@PathVariable String uniqueNodeId); @GetMapping("/path") List<Node> getFromPath(@RequestParam(value = "path") String path); }
@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(status().isOk()).andExpect(content().contentType(JSON)) .andReturn(); objectMapper.readValue(result.getResponse().getContentAsString(), new TypeReference<List<ConfigPv>>() { }); }
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); }
@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); }
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/{parentsUniqueId}") Node createNode(@PathVariable String parentsUniqueId, @RequestBody final Node node); @GetMapping("/node/{uniqueNodeId}") Node getNode(@PathVariable final String uniqueNodeId); @GetMapping("/root") Node getRootNode(); @GetMapping("/node/{uniqueNodeId}/parent") Node getParentNode(@PathVariable String uniqueNodeId); @GetMapping("/node/{uniqueNodeId}/children") List<Node> getChildNodes(@PathVariable final String uniqueNodeId); @PostMapping("/config/{uniqueNodeId}/update") ResponseEntity<Node> updateConfiguration(@PathVariable String uniqueNodeId, @RequestBody UpdateConfigHolder updateConfigHolder); @DeleteMapping("/node/{uniqueNodeId}") void deleteNode(@PathVariable final String uniqueNodeId); @GetMapping("/config/{uniqueNodeId}/snapshots") List<Node> getSnapshots(@PathVariable String uniqueNodeId); @PostMapping("/node/{uniqueNodeId}") Node moveNode(@PathVariable String uniqueNodeId, @RequestParam(value = "to", required = true) String to, @RequestParam(value = "username", required = true) String userName); @PostMapping("/node/{uniqueNodeId}/update") Node updateNode(@PathVariable String uniqueNodeId, @RequestParam(value = "customTimeForMigration", required = true) String customTimeForMigration, @RequestBody Node nodeToUpdate); @GetMapping("/config/{uniqueNodeId}/items") List<ConfigPv> getConfigPvs(@PathVariable String uniqueNodeId); @GetMapping("/path/{uniqueNodeId}") String getFullPath(@PathVariable String uniqueNodeId); @GetMapping("/path") List<Node> getFromPath(@RequestParam(value = "path") String path); }
@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()); Node node = Node.builder().name("name").uniqueId("uniqueId").build(); when(services.getFromPath("/a/b/c")).thenReturn(Arrays.asList(node)); request = get("/path?path=/a/b/c"); MvcResult result = mockMvc.perform(request).andExpect(status().isOk()).andReturn(); List<Node> nodes = objectMapper.readValue(result.getResponse().getContentAsString(), new TypeReference<List<Node>>() { }); assertEquals(1, nodes.size()); }
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/{parentsUniqueId}") Node createNode(@PathVariable String parentsUniqueId, @RequestBody final Node node); @GetMapping("/node/{uniqueNodeId}") Node getNode(@PathVariable final String uniqueNodeId); @GetMapping("/root") Node getRootNode(); @GetMapping("/node/{uniqueNodeId}/parent") Node getParentNode(@PathVariable String uniqueNodeId); @GetMapping("/node/{uniqueNodeId}/children") List<Node> getChildNodes(@PathVariable final String uniqueNodeId); @PostMapping("/config/{uniqueNodeId}/update") ResponseEntity<Node> updateConfiguration(@PathVariable String uniqueNodeId, @RequestBody UpdateConfigHolder updateConfigHolder); @DeleteMapping("/node/{uniqueNodeId}") void deleteNode(@PathVariable final String uniqueNodeId); @GetMapping("/config/{uniqueNodeId}/snapshots") List<Node> getSnapshots(@PathVariable String uniqueNodeId); @PostMapping("/node/{uniqueNodeId}") Node moveNode(@PathVariable String uniqueNodeId, @RequestParam(value = "to", required = true) String to, @RequestParam(value = "username", required = true) String userName); @PostMapping("/node/{uniqueNodeId}/update") Node updateNode(@PathVariable String uniqueNodeId, @RequestParam(value = "customTimeForMigration", required = true) String customTimeForMigration, @RequestBody Node nodeToUpdate); @GetMapping("/config/{uniqueNodeId}/items") List<ConfigPv> getConfigPvs(@PathVariable String uniqueNodeId); @GetMapping("/path/{uniqueNodeId}") String getFullPath(@PathVariable String uniqueNodeId); @GetMapping("/path") List<Node> getFromPath(@RequestParam(value = "path") String path); }
@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/existing"); MvcResult result = mockMvc.perform(request).andExpect(status().isOk()).andReturn(); assertEquals("/a/b/c", result.getResponse().getContentAsString()); }
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.MAJOR; case INVALID: return SeverityLevel.INVALID; default: return SeverityLevel.UNDEFINED; } } final static SeverityLevel decodeSeverity(final VType value); final static String getStatusMessage(final VType value); }
@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); intValue = VInt.of(7, Alarm.none(), Time.now(), Display.none()); severityLevel = SeverityLevelHelper.decodeSeverity(intValue); assertEquals(SeverityLevel.OK, severityLevel); intValue = VInt.of(7, Alarm.lolo(), Time.now(), Display.none()); severityLevel = SeverityLevelHelper.decodeSeverity(intValue); assertEquals(SeverityLevel.MAJOR, severityLevel); intValue = VInt.of(7, Alarm.hihi(), Time.now(), Display.none()); severityLevel = SeverityLevelHelper.decodeSeverity(intValue); assertEquals(SeverityLevel.MAJOR, severityLevel); intValue = VInt.of(7, Alarm.low(), Time.now(), Display.none()); severityLevel = SeverityLevelHelper.decodeSeverity(intValue); assertEquals(SeverityLevel.MINOR, severityLevel); intValue = VInt.of(7, Alarm.high(), Time.now(), Display.none()); severityLevel = SeverityLevelHelper.decodeSeverity(intValue); assertEquals(SeverityLevel.MINOR, 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 VType value); }
@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); }
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(); }
@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); }
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 < len) { final char c = text.charAt(pos); if (c == '"') pos = locateClosingQuote(text, pos+1); else if (c == '(') pos = locateClosingBrace(text, pos+1); else if ("\r\n\t,; ".indexOf(c) >= 0) { final String name = text.substring(start, pos).trim(); if (! name.isEmpty()) names.add(name); start = ++pos; } else ++pos; } if (pos > start) { final String name = text.substring(start, pos).trim(); if (! name.isEmpty()) names.add(name); } return names; } static List<String> parseDroppedPVs(String text); }
@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: assertThat(names, equalTo(List.of("loc: names = DroppedPVNameParser.parseDroppedPVs("loc: assertThat(names, equalTo(List.of("loc: } @Test public void testNewline() throws Exception { List<String> names = DroppedPVNameParser.parseDroppedPVs("pv1\npv2"); assertThat(names, equalTo(List.of("pv1", "pv2"))); names = DroppedPVNameParser.parseDroppedPVs("pv1\r\npv2"); assertThat(names, equalTo(List.of("pv1", "pv2"))); names = DroppedPVNameParser.parseDroppedPVs("pv1\rpv2"); assertThat(names, equalTo(List.of("pv1", "pv2"))); names = DroppedPVNameParser.parseDroppedPVs("[ pv1\npv2 ] "); assertThat(names, equalTo(List.of("pv1", "pv2"))); } @Test public void testTab() throws Exception { List<String> names = DroppedPVNameParser.parseDroppedPVs("pv1\tpv2"); assertThat(names, equalTo(List.of("pv1", "pv2"))); names = DroppedPVNameParser.parseDroppedPVs(" pv1 \t pv2 \t pv3"); assertThat(names, equalTo(List.of("pv1", "pv2", "pv3"))); } @Test public void testComma() throws Exception { List<String> names = DroppedPVNameParser.parseDroppedPVs("pv1,pv2"); assertThat(names, equalTo(List.of("pv1", "pv2"))); names = DroppedPVNameParser.parseDroppedPVs(" pv1, pv2 , pv3"); assertThat(names, equalTo(List.of("pv1", "pv2", "pv3"))); names = DroppedPVNameParser.parseDroppedPVs(" pv1, loc: assertThat(names, equalTo(List.of("pv1", "loc: names = DroppedPVNameParser.parseDroppedPVs(" pv1, sim: assertThat(names, equalTo(List.of("pv1", "sim: names = DroppedPVNameParser.parseDroppedPVs(" pv1, loc: assertThat(names, equalTo(List.of("pv1", "loc: names = DroppedPVNameParser.parseDroppedPVs(" pv1; pv2 ; pv3"); assertThat(names, equalTo(List.of("pv1", "pv2", "pv3"))); } @Test public void testSpace() throws Exception { List<String> names = DroppedPVNameParser.parseDroppedPVs("pv1 pv2"); assertThat(names, equalTo(List.of("pv1", "pv2"))); names = DroppedPVNameParser.parseDroppedPVs("pv1 sim: assertThat(names, equalTo(List.of("pv1", "sim: names = DroppedPVNameParser.parseDroppedPVs(" pv1 loc: assertThat(names, equalTo(List.of("pv1", "loc: }
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 start); static Instant fromSQLTimestamp(Timestamp timestamp); final static long SECS_PER_HOUR; final static long SECS_PER_MINUTE; final static long SECS_PER_DAY; }
@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.roundUp(orig, 10); text = TimestampFormats.SECONDS_FORMAT.format(time); System.out.println(text); assertThat(text, equalTo("2012-01-19 12:23:20")); time = TimestampHelper.roundUp(orig, TimeDuration.ofSeconds(30)); text = TimestampFormats.SECONDS_FORMAT.format(time); System.out.println(text); assertThat(text, equalTo("2012-01-19 12:23:30")); time = TimestampHelper.roundUp(orig, 60); text = TimestampFormats.SECONDS_FORMAT.format(time); System.out.println(text); assertThat(text, equalTo("2012-01-19 12:24:00")); time = TimestampHelper.roundUp(orig, TimeDuration.ofHours(1.0)); text = TimestampFormats.SECONDS_FORMAT.format(time); System.out.println(text); assertThat(text, equalTo("2012-01-19 13:00:00")); time = TimestampHelper.roundUp(orig, 2L*60*60); text = TimestampFormats.SECONDS_FORMAT.format(time); System.out.println(text); assertThat(text, equalTo("2012-01-19 14:00:00")); assertThat(24L*60*60, equalTo(TimestampHelper.SECS_PER_DAY)); time = TimestampHelper.roundUp(orig, TimestampHelper.SECS_PER_DAY); text = TimestampFormats.SECONDS_FORMAT.format(time); System.out.println(text); assertThat(text, equalTo("2012-01-20 00:00:00")); time = TimestampHelper.roundUp(orig, 3*TimestampHelper.SECS_PER_DAY); text = TimestampFormats.SECONDS_FORMAT.format(time); System.out.println(text); assertThat(text, equalTo("2012-01-22 00:00:00")); time = TimestampHelper.roundUp(orig, 13*TimestampHelper.SECS_PER_DAY); text = TimestampFormats.SECONDS_FORMAT.format(time); System.out.println(text); assertThat(text, equalTo("2012-02-01 00:00:00")); assertThat(24L*60*60, equalTo(TimestampHelper.SECS_PER_DAY)); time = TimestampHelper.roundUp(orig, (3*TimestampHelper.SECS_PER_DAY)/2); text = TimestampFormats.SECONDS_FORMAT.format(time); System.out.println(text); assertThat(text, equalTo("2012-01-20 12:00:00")); }
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); }
@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()); }
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 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)); }
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(); }
@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")); } }
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; }
@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); }
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); }
@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(inputStream, width, height); } catch ( Exception ex ) { logger.log(Level.WARNING, String.format("Failure loading image: %s", imageFileName), ex); } return null; }); } static Image loadSVG(String imageFileName, double width, double height); static Image loadSVG(InputStream fileStream, double width, double height); }
@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("interlock.png"); } catch (Exception e) { fail(e.getMessage()); return; } assertNull(SVGHelper.loadSVG(path, 400d, 400d)); } @Test public void testSVGHelperJpgFile(){ String path = null; try { path = getPath("interlock.jpg"); } catch (Exception e) { fail(e.getMessage()); return; } assertNull(SVGHelper.loadSVG(path, 400d, 400d)); } @Test public void testSVGHelperGifFile() throws Exception{ String path = null; try { path = getPath("interlock.gif"); } catch (Exception e) { fail(e.getMessage()); return; } assertNull(SVGHelper.loadSVG(path, 400d, 400d)); } @Test public void testSVGHelperTiffFile() throws Exception{ String path = null; try { path = getPath("interlock.tiff"); } catch (Exception e) { fail(e.getMessage()); return; } assertNull(SVGHelper.loadSVG(path, 400d, 400d)); }
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."); } }, () -> { throw new UnsupportedOperationException("File extension unknown"); }); System.out.println("Processing file : " + this.rootFile); getAllLinkedFiles(this.rootFile); return this.allLinkedFiles; } ProcessOPI(File rootFile); Set<File> process(); static synchronized Set<File> getLinkedFiles(File file); }
@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(getClass().getClassLoader().getResource("bob/root_with_no_children.bob").getFile()); ProcessOPI processOPI = new ProcessOPI(file); Set<File> result = processOPI.process(); assertTrue("Failed to parse a bob screen with no children, expected empty list but found list " + result , result.isEmpty()); } @Test public void testEmptyOPIList() { File file = new File(getClass().getClassLoader().getResource("opi/root_with_no_children.opi").getFile()); ProcessOPI processOPI = new ProcessOPI(file); Set<File> result = processOPI.process(); assertTrue("Failed to parse a bob screen with no children, expected empty list but found list " + result , result.isEmpty()); } @Test public void testBOBList() { File file = new File(getClass().getClassLoader().getResource("bob/root.bob").getFile()); ProcessOPI processOPI = new ProcessOPI(file); Set<File> result = processOPI.process(); Set<File> expectedFiles = new HashSet<>(); expectedFiles.add(new File(getClass().getClassLoader().getResource("bob/child_1/child_1.bob").getFile())); expectedFiles.add(new File(getClass().getClassLoader().getResource("bob/child_1/grand_child_1_1/grand_child_1_1.bob").getFile())); expectedFiles.add(new File(getClass().getClassLoader().getResource("bob/child_2/child_2.bob").getFile())); expectedFiles.add(new File(getClass().getClassLoader().getResource("bob/child_3/child_3.bob").getFile())); assertThat(result, is(expectedFiles)); } @Test public void testOPIList() { File file = new File(getClass().getClassLoader().getResource("opi/root.opi").getFile()); ProcessOPI processOPI = new ProcessOPI(file); Set<File> result = processOPI.process(); Set<File> expectedFiles = new HashSet<>(); expectedFiles.add(new File(getClass().getClassLoader().getResource("opi/child_1/child_1.opi").getFile())); expectedFiles.add(new File(getClass().getClassLoader().getResource("opi/child_1/grand_child_1_1/grand_child_1_1.opi").getFile())); expectedFiles.add(new File(getClass().getClassLoader().getResource("opi/child_2/child_2.opi").getFile())); expectedFiles.add(new File(getClass().getClassLoader().getResource("opi/child_3/child_3.opi").getFile())); assertThat(result, is(expectedFiles)); } @Test public void testBOBCyclicLinksList() { File file = new File(getClass().getClassLoader().getResource("bob/cyclic/cyclic_1.bob").getFile()); ProcessOPI processOPI = new ProcessOPI(file); Set<File> result = processOPI.process(); Set<File> expectedFiles = new HashSet<>(); expectedFiles.add(new File(getClass().getClassLoader().getResource("bob/cyclic/cyclic_2.bob").getFile())); assertThat(result, is(expectedFiles)); } @Test public void testOPICyclicLinksList() { File file = new File(getClass().getClassLoader().getResource("opi/cyclic/cyclic_1.opi").getFile()); ProcessOPI processOPI = new ProcessOPI(file); Set<File> result = processOPI.process(); Set<File> expectedFiles = new HashSet<>(); expectedFiles.add(new File(getClass().getClassLoader().getResource("opi/cyclic/cyclic_2.opi").getFile())); assertThat(result, is(expectedFiles)); }
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(); }
@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(); }
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); }
@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)); }
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); }
@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)); }
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); }
@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)); }
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 FormulaTreeCategoryNode(child); categories.add(newCategory); this.getChildren().add(newCategory); } FormulaTreeRootNode(); void addChild(FormulaFunction child); }
@Test public void testGivenNoExistingCategoryAddingChildFormulaToRootNodeCreatesCategory() { String categoryName = "CATEGORY"; String formula1Name = "TEST_NAME"; FormulaFunction func = createFormula(formula1Name, "TEST_DESC", categoryName); FormulaTreeRootNode rootNode = new FormulaTreeRootNode(); rootNode.addChild(func); assertThat(rootNode.getChildren().size(), equalTo(1)); TreeItem<FormulaTreeByCategoryNode> category = rootNode.getChildren().get(0); assertThat(category.getValue().getSignature(), equalTo(categoryName)); assertThat(category.getValue().getDescription(), equalTo("")); assertThat(category.getChildren().size(), equalTo(1)); List<String> formulaSignatures = getFormulaSignaturesFromCategory(category); assertTrue(formulaSignatures.contains(formula1Name + "()")); } @Test public void testGivenExistingCategoryAddingChildFormulaToRootNodeDoesNotCreateCategory() { String categoryName = "CATEGORY"; String formula1Name = "TEST_NAME"; String formula2Name = "TEST_NAME2"; FormulaFunction firstFunc = createFormula(formula1Name, "TEST_DESC", categoryName); FormulaFunction secondFunc = createFormula(formula2Name, "TEST_DESC2", categoryName); FormulaTreeRootNode rootNode = new FormulaTreeRootNode(); rootNode.addChild(firstFunc); assertThat(rootNode.getChildren().size(), equalTo(1)); rootNode.addChild(secondFunc); assertThat(rootNode.getChildren().size(), equalTo(1)); TreeItem<FormulaTreeByCategoryNode> category = rootNode.getChildren().get(0); assertThat(category.getChildren().size(), equalTo(2)); List<String> formulaSignatures = getFormulaSignaturesFromCategory(category); assertTrue(formulaSignatures.contains(formula1Name + "()")); assertTrue(formulaSignatures.contains(formula2Name + "()")); }
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; }
@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); }
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; }
@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, 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; }
@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())); }
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); }
@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); }
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().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()); }
RunnerFileContentRenderer { public String getRenderedRunnerFileContent(FeatureRunner featureRunner) throws CucablePluginException { final String runnerTemplatePath = featureRunner.getRunnerTemplatePath(); final String runnerClassName = featureRunner.getRunnerClassName(); String fileString = fileIO.readContentFromFile(runnerTemplatePath); checkForPlaceholderErrors(fileString); if (runnerTemplatePath.trim().toLowerCase().endsWith(".java")) { fileString = replaceJavaTemplatePlaceholders(runnerTemplatePath, runnerClassName, fileString); } fileString = replaceFeatureFilePlaceholder(fileString, featureRunner.getFeatureFileNames()); fileString = fileString.replace(CUCABLE_RUNNER_PLACEHOLDER, runnerClassName); fileString = replaceCustomParameters(fileString); fileString = addCucableInfo(fileString, runnerTemplatePath); return fileString; } @Inject RunnerFileContentRenderer( final FileIO fileIO, final PropertyManager propertyManager, final CucableLogger logger ); String getRenderedRunnerFileContent(FeatureRunner featureRunner); }
@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" + " plugin = {\"json:target/cucumber-report/[CUCABLE:RUNNER].json\"}\n" + ")\n" + "public class [CUCABLE:RUNNER] {\n" + "}\n"; when(fileIO.readContentFromFile(anyString())).thenReturn(template); String expectedOutput = "package parallel;\n" + "\n" + "import cucumber.api.CucumberOptions;\n" + "\n" + "@CucumberOptions(\n" + " monochrome = false,\n" + " features = {\"classpath:parallel/features/featureFileName.feature\"},\n" + " plugin = {\"json:target/cucumber-report/RunnerClass.json\"}\n" + ")\n" + "public class RunnerClass {\n" + "}\n" + "\n" + "\n" + " ArrayList<String> featureFileNames = new ArrayList<>(); featureFileNames.add("featureFileName"); FeatureRunner featureRunner = new FeatureRunner( "pathToTemplate", "RunnerClass", featureFileNames ); String renderedRunnerFileContent = runnerFileContentRenderer.getRenderedRunnerFileContent(featureRunner); renderedRunnerFileContent = renderedRunnerFileContent.replaceAll("\\r\\n", "\n"); assertThat(renderedRunnerFileContent, is(expectedOutput)); } @Test public void getRenderedFeatureFileContentReplaceBackslashInCommentTest() 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" + " plugin = {\"json:target/cucumber-report/[CUCABLE:RUNNER].json\"}\n" + ")\n" + "public class [CUCABLE:RUNNER] {\n" + "}\n"; when(fileIO.readContentFromFile(anyString())).thenReturn(template); String expectedOutput = "package parallel;\n" + "\n" + "import cucumber.api.CucumberOptions;\n" + "\n" + "@CucumberOptions(\n" + " monochrome = false,\n" + " features = {\"classpath:parallel/features/featureFileName.feature\"},\n" + " plugin = {\"json:target/cucumber-report/RunnerClass.json\"}\n" + ")\n" + "public class RunnerClass {\n" + "}\n" + "\n" + "\n" + " ArrayList<String> featureFileNames = new ArrayList<>(); featureFileNames.add("featureFileName"); FeatureRunner featureRunner = new FeatureRunner( "c:\\unknown\\path", "RunnerClass", featureFileNames ); String renderedRunnerFileContent = runnerFileContentRenderer.getRenderedRunnerFileContent(featureRunner); renderedRunnerFileContent = renderedRunnerFileContent.replaceAll("\\r\\n", "\n"); assertThat(renderedRunnerFileContent, is(expectedOutput)); } @Test public void getRenderedFeatureFileContentFromJavaFileTest() throws Exception { String template = "package parallel;\n" + "\n" + "package some.package;\n" + "import cucumber.api.CucumberOptions;\n" + "\n" + "@CucumberOptions(\n" + " monochrome = false,\n" + " features = {\"classpath:parallel/features/[CUCABLE:FEATURE].feature\"},\n" + " plugin = {\"json:target/cucumber-report/[CUCABLE:RUNNER].json\"}\n" + ")\n" + "public class MyClass {\n" + "}\n"; when(fileIO.readContentFromFile(anyString())).thenReturn(template); String expectedOutput = "\n" + "\n" + "\n" + "import cucumber.api.CucumberOptions;\n" + "\n" + "@CucumberOptions(\n" + " monochrome = false,\n" + " features = {\"classpath:parallel/features/featureFileName.feature\"},\n" + " plugin = {\"json:target/cucumber-report/RunnerClass.json\"}\n" + ")\n" + "public class RunnerClass {\n" + "}\n" + "\n" + "\n" + " ArrayList<String> featureFileNames = new ArrayList<>(); featureFileNames.add("featureFileName"); FeatureRunner featureRunner = new FeatureRunner( "MyClass.java", "RunnerClass", featureFileNames ); String renderedRunnerFileContent = runnerFileContentRenderer.getRenderedRunnerFileContent(featureRunner); renderedRunnerFileContent = renderedRunnerFileContent.replaceAll("\\r\\n", "\n"); assertThat(renderedRunnerFileContent, is(expectedOutput)); } @Test public void multipleFeatureRunnerTest() throws Exception { String template = "package parallel;\n" + "\n" + "package some.package;\n" + "import cucumber.api.CucumberOptions;\n" + "\n" + "@CucumberOptions(\n" + " monochrome = false,\n" + " features = {\"classpath:parallel/features/[CUCABLE:FEATURE].feature\"},\n" + " plugin = {\"json:target/cucumber-report/[CUCABLE:RUNNER].json\"}\n" + ")\n" + "public class MyClass {\n" + "}\n"; when(fileIO.readContentFromFile(anyString())).thenReturn(template); String expectedOutput = "\n" + "\n" + "\n" + "import cucumber.api.CucumberOptions;\n" + "\n" + "@CucumberOptions(\n" + " monochrome = false,\n" + " features = {\"classpath:parallel/features/featureFileName.feature\",\n" + "\"classpath:parallel/features/featureFileName2.feature\"},\n" + " plugin = {\"json:target/cucumber-report/RunnerClass.json\"}\n" + ")\n" + "public class RunnerClass {\n" + "}\n" + "\n" + "\n" + " ArrayList<String> featureFileNames = new ArrayList<>(); featureFileNames.add("featureFileName"); featureFileNames.add("featureFileName2"); FeatureRunner featureRunner = new FeatureRunner( "MyClass.java", "RunnerClass", featureFileNames ); String renderedRunnerFileContent = runnerFileContentRenderer.getRenderedRunnerFileContent(featureRunner); renderedRunnerFileContent = renderedRunnerFileContent.replaceAll("\\r\\n", "\n"); assertThat(renderedRunnerFileContent, is(expectedOutput)); } @Test(expected = CucablePluginException.class) public void deprecatedPlaceholderTest() 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" + " plugin = {\"json:target/cucumber-report/[CUCABLE:RUNNER].json\"}\n" + ")\n" + "public class [FEATURE_FILE_NAME] {\n" + "}\n"; when(fileIO.readContentFromFile(anyString())).thenReturn(template); ArrayList<String> featureFileNames = new ArrayList<>(); featureFileNames.add("featureFileName"); FeatureRunner featureRunner = new FeatureRunner( "MyClass.java", "RunnerClass", featureFileNames ); runnerFileContentRenderer.getRenderedRunnerFileContent(featureRunner); } @Test public void customParametersTest() throws CucablePluginException { String template = "Template [CUCABLE:FEATURE] [CUCABLE:CUSTOM:test1]!\n[CUCABLE:CUSTOM:test2], [CUCABLE:CUSTOM:test1]..."; when(fileIO.readContentFromFile(anyString())).thenReturn(template); Map<String, String> customParameters = new HashMap<>(); customParameters.put("test1", "testvalue1"); customParameters.put("test2", "another value"); ArrayList<String> featureFileNames = new ArrayList<>(); featureFileNames.add("featureFileName"); FeatureRunner featureRunner = new FeatureRunner( "pathToTemplate", "RunnerClass", featureFileNames ); when(propertyManager.getCustomPlaceholders()).thenReturn(customParameters); String renderedRunnerFileContent = runnerFileContentRenderer.getRenderedRunnerFileContent(featureRunner); renderedRunnerFileContent = renderedRunnerFileContent.replaceAll("\\r\\n", "\n"); assertThat(renderedRunnerFileContent, is( "Template [CUCABLE:FEATURE] testvalue1!\n" + "another value, testvalue1...\n" + "\n" + " } @Test(expected = CucablePluginException.class) public void missingRequiredPlaceholderTest() throws Exception { String template = "No Placeholder included"; when(fileIO.readContentFromFile(anyString())).thenReturn(template); ArrayList<String> featureFileNames = new ArrayList<>(); featureFileNames.add("featureFileName"); FeatureRunner featureRunner = new FeatureRunner( "MyClass.java", "RunnerClass", featureFileNames ); runnerFileContentRenderer.getRenderedRunnerFileContent(featureRunner); }
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(); }
@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> '" + 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(); }
@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, "<sourceRunnerTemplateFile>", missingProperties); saveMissingProperty(generatedRunnerDirectory, "<generatedRunnerDirectory>", missingProperties); saveMissingProperty(generatedFeatureDirectory, "<generatedFeatureDirectory>", missingProperties); if (!missingProperties.isEmpty()) { throw new WrongOrMissingPropertiesException(missingProperties); } } @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(); }
@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>, <generatedRunnerDirectory>, <generatedFeatureDirectory>]"); propertyManager.checkForMissingMandatoryProperties(); }
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); }
@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 CharSequence logString, CucableLogLevel... cucableLogLevels); void warn(final CharSequence logString); }
@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("ro"), is("Scenariu")); assertThat(gherkinTranslations.getScenarioKeyword("ru"), is("Сценарий")); assertThat(gherkinTranslations.getScenarioKeyword("fr"), is("Scénario")); assertThat(gherkinTranslations.getScenarioKeyword("gibberish"), is("Scenario")); }
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 = getGherkinDocumentFromFeatureFileContent(escapedFeatureContent); Feature feature = gherkinDocument.getFeature(); if (feature == null) { return Collections.emptyList(); } String featureName = feature.getKeyword() + ": " + feature.getName(); String featureLanguage = feature.getLanguage(); String featureDescription = feature.getDescription(); List<String> featureTags = gherkinToCucableConverter.convertGherkinTagsToCucableTags(feature.getTags()); ArrayList<SingleScenario> singleScenarioFeatures = new ArrayList<>(); List<Step> backgroundSteps = new ArrayList<>(); List<ScenarioDefinition> scenarioDefinitions = feature.getChildren(); for (ScenarioDefinition scenarioDefinition : scenarioDefinitions) { String scenarioName = scenarioDefinition.getKeyword() + ": " + scenarioDefinition.getName(); String scenarioDescription = scenarioDefinition.getDescription(); if (scenarioDefinition instanceof Background) { Background background = (Background) scenarioDefinition; backgroundSteps = gherkinToCucableConverter.convertGherkinStepsToCucableSteps(background.getSteps()); continue; } if (scenarioDefinition instanceof Scenario) { Scenario scenario = (Scenario) scenarioDefinition; if (scenarioLineNumbers == null || scenarioLineNumbers.isEmpty() || scenarioLineNumbers.contains(scenario.getLocation().getLine())) { SingleScenario singleScenario = new SingleScenario( featureName, featureFilePath, featureLanguage, featureDescription, scenarioName, scenarioDescription, featureTags, backgroundSteps ); addGherkinScenarioInformationToSingleScenario(scenario, singleScenario); if (scenarioShouldBeIncluded(singleScenario)) { singleScenarioFeatures.add(singleScenario); } } continue; } if (scenarioDefinition instanceof ScenarioOutline) { ScenarioOutline scenarioOutline = (ScenarioOutline) scenarioDefinition; if (scenarioLineNumbers == null || scenarioLineNumbers.isEmpty() || scenarioLineNumbers.contains(scenarioOutline.getLocation().getLine())) { List<SingleScenario> outlineScenarios = getSingleScenariosFromOutline( scenarioOutline, featureName, featureFilePath, featureLanguage, featureDescription, featureTags, backgroundSteps ); for (SingleScenario singleScenario : outlineScenarios) { if (scenarioShouldBeIncluded(singleScenario)) { singleScenarioFeatures.add(singleScenario); } } } } } return singleScenarioFeatures; } @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); }
@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" + "@scenario1Tag1\n" + "@scenario1Tag2\n" + "Scenario: This is a scenario with two steps\n" + "Given this is step 1\n" + "Then this is step 2\n"; List<SingleScenario> singleScenariosFromFeature = gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); assertThat(singleScenariosFromFeature.size(), is(1)); SingleScenario scenario = singleScenariosFromFeature.get(0); assertThat(scenario.getScenarioName(), is("Scenario: This is a scenario with two steps")); assertThat(scenario.getSteps().size(), is(2)); assertThat(scenario.getBackgroundSteps().size(), is(0)); } @Test public void validFeatureOneIncludeTagTest() throws Exception { String featureContent = getTwoScenariosWithTags(); when(propertyManager.getIncludeScenarioTags()).thenReturn("@tag1"); List<SingleScenario> singleScenariosFromFeature = gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); assertThat(singleScenariosFromFeature.size(), is(1)); } @Test public void validFeatureOneScenarioNameTest() throws Exception { String featureContent = getTwoScenariosWithTags(); when(propertyManager.getScenarioNames()).thenReturn(Collections.singletonList("scenario 1")); List<SingleScenario> singleScenariosFromFeature = gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); assertThat(singleScenariosFromFeature.size(), is(1)); } @Test public void validFeatureOneScenarioNameNonEnglishTest() throws Exception { String featureContent = getTwoScenariosNonEnglish(); when(propertyManager.getScenarioNames()).thenReturn(Collections.singletonList("Mulțumesc")); List<SingleScenario> singleScenariosFromFeature = gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); assertThat(singleScenariosFromFeature.size(), is(2)); } @Test(expected = CucablePluginException.class) public void invalidFeatureOneIncludeTagTest() throws Exception { String featureContent = getTwoScenariosWithTags(); when(propertyManager.getIncludeScenarioTags()).thenReturn("@tag1 wrongOperator @tag2"); gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); } @Test public void validFeatureTwoIncludeTagsTest() throws Exception { String featureContent = getTwoScenariosWithTags(); when(propertyManager.getIncludeScenarioTags()).thenReturn("@tag1 or @tag3"); List<SingleScenario> singleScenariosFromFeature = gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); assertThat(singleScenariosFromFeature.size(), is(2)); } @Test public void validFeatureTwoScenarioNamesTest() throws Exception { String featureContent = getTwoScenariosWithTags(); when(propertyManager.getScenarioNames()).thenReturn(Arrays.asList("scenario 1", "scenario 2")); List<SingleScenario> singleScenariosFromFeature = gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); assertThat(singleScenariosFromFeature.size(), is(2)); } @Test public void validFeatureTwoIncludeTagsOneScenarioNameTest() throws Exception { String featureContent = getTwoScenariosWithTags(); when(propertyManager.getIncludeScenarioTags()).thenReturn("@tag1 or @tag3"); when(propertyManager.getScenarioNames()).thenReturn(Collections.singletonList("scenario 1")); List<SingleScenario> singleScenariosFromFeature = gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); assertThat(singleScenariosFromFeature.size(), is(1)); } @Test public void validFeatureMatchingIncludeTagsNoMatchingScenarioNameTest() throws Exception { String featureContent = getTwoScenariosWithTags(); when(propertyManager.getIncludeScenarioTags()).thenReturn("@tag1 or @tag3"); when(propertyManager.getScenarioNames()).thenReturn(Collections.singletonList("scenario 3")); List<SingleScenario> singleScenariosFromFeature = gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); assertThat(singleScenariosFromFeature.size(), is(0)); } @Test public void validFeatureNoMatchingIncludeTagsMatchingScenarioNameTest() throws Exception { String featureContent = getTwoScenariosWithTags(); when(propertyManager.getIncludeScenarioTags()).thenReturn("@tag4"); when(propertyManager.getScenarioNames()).thenReturn(Collections.singletonList("scenario 1")); List<SingleScenario> singleScenariosFromFeature = gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); assertThat(singleScenariosFromFeature.size(), is(0)); } @Test public void validFeatureEmptyScenarioNameListTest() throws Exception { String featureContent = getTwoScenariosWithTags(); when(propertyManager.getScenarioNames()).thenReturn(Collections.singletonList("")); List<SingleScenario> singleScenariosFromFeature = gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); assertThat(singleScenariosFromFeature.size(), is(2)); } @Test public void validFeatureTwoIncludeTagsWithAndConnectorTest() throws Exception { String featureContent = getTwoScenariosWithTags(); when(propertyManager.getIncludeScenarioTags()).thenReturn("@tag1 and @tag2"); List<SingleScenario> singleScenariosFromFeature = gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); assertThat(singleScenariosFromFeature.size(), is(1)); } @Test public void validFeatureOneIncludeTagNoScenarioTagsTest() throws Exception { String featureContent = "@featureTag\n" + "Feature: test feature\n" + "\n" + "Scenario: scenario 1"; when(propertyManager.getIncludeScenarioTags()).thenReturn("@tag1"); List<SingleScenario> singleScenariosFromFeature = gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); assertThat(singleScenariosFromFeature.size(), is(0)); } @Test public void validFeatureTagIsConsideredInIncludeTags() throws Exception { String featureContent = getTwoScenariosWithTags(); when(propertyManager.getIncludeScenarioTags()).thenReturn("@featureTag"); List<SingleScenario> singleScenariosFromFeature = gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); assertThat(singleScenariosFromFeature.size(), is(2)); } @Test(expected = CucablePluginException.class) public void parseErrorTest() throws Exception { String featureContent = "&/ASD"; gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); } @Test public void validFeatureWithDataTableTest() throws Exception { String featureContent = "@featureTag\n" + "Feature: test feature\n" + "\n" + "@scenario1Tag1\n" + "@scenario1Tag2\n" + "Scenario: This is a scenario with two steps\n" + "Given this is step 1\n" + "|value1|value2|\n" + "Then this is step 2\n"; List<SingleScenario> singleScenariosFromFeature = gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); assertThat(singleScenariosFromFeature.size(), is(1)); SingleScenario scenario = singleScenariosFromFeature.get(0); assertThat(scenario.getScenarioName(), is("Scenario: This is a scenario with two steps")); assertThat(scenario.getSteps().size(), is(2)); assertThat(scenario.getBackgroundSteps().size(), is(0)); assertThat(scenario.getSteps().get(0).getDataTable(), is(notNullValue())); assertThat(scenario.getSteps().get(0).getDataTable().getRows().size(), is(1)); assertThat(scenario.getSteps().get(0).getDataTable().getRows().get(0).size(), is(2)); } @Test public void validFeatureWithBackgroundScenarioTest() throws Exception { String featureContent = "Feature: FeatureName\n" + "\n" + " Background:\n" + " Given BackgroundGivenStep\n" + " And BackgroundGivenStep2\n" + "\n" + " @tag1\n" + " @tag2\n" + " Scenario: This is a scenario with background\n" + " Then ThenStep"; List<SingleScenario> singleScenariosFromFeature = gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); assertThat(singleScenariosFromFeature.size(), is(1)); SingleScenario scenario = singleScenariosFromFeature.get(0); assertThat(scenario.getScenarioName(), is("Scenario: This is a scenario with background")); assertThat(scenario.getSteps().size(), is(1)); assertThat(scenario.getBackgroundSteps().size(), is(2)); assertThat(scenario.getSteps().get(0).getDataTable(), is(nullValue())); } @Test public void validFeatureWithScenarioOutlineTest() 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" + " Then I see the value '<value>'\n" + "\n" + " Examples:\n" + " | key | value |\n" + " | 1 | one |\n" + " | 2 | two |"; List<SingleScenario> singleScenariosFromFeature = gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); assertThat(singleScenariosFromFeature.size(), is(2)); SingleScenario scenario = singleScenariosFromFeature.get(0); assertThat(scenario.getScenarioName(), is("Scenario: This is a scenario outline")); assertThat(scenario.getSteps().size(), is(2)); assertThat(scenario.getBackgroundSteps().size(), is(0)); assertThat(scenario.getSteps().get(0).getDataTable(), is(nullValue())); assertThat(scenario.getSteps().get(0).getName(), is("When I search for key 1")); assertThat(scenario.getSteps().get(1).getName(), is("Then I see the value 'one'")); scenario = singleScenariosFromFeature.get(1); assertThat(scenario.getScenarioName(), is("Scenario: This is a scenario outline")); assertThat(scenario.getSteps().size(), is(2)); assertThat(scenario.getBackgroundSteps().size(), is(0)); assertThat(scenario.getSteps().get(0).getDataTable(), is(nullValue())); assertThat(scenario.getSteps().get(0).getName(), is("When I search for key 2")); assertThat(scenario.getSteps().get(1).getName(), is("Then I see the value 'two'")); } @Test public void validFeatureWithScenarioOutlineAndTwoExampleTablesTest() 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" + " Then I see the value '<value>'\n" + "\n" + " Examples:\n" + " | key | value |\n" + " | 1 | one |\n" + " | 2 | two |\n" + "\n" + " Examples:\n" + " | key | value |\n" + " | 1 | uno |\n" + " | 2 | dos |"; List<SingleScenario> singleScenariosFromFeature = gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); assertThat(singleScenariosFromFeature.size(), is(4)); SingleScenario scenario = singleScenariosFromFeature.get(0); assertThat(scenario.getScenarioName(), is("Scenario: This is a scenario outline")); assertThat(scenario.getSteps().size(), is(2)); assertThat(scenario.getBackgroundSteps().size(), is(0)); assertThat(scenario.getSteps().get(0).getDataTable(), is(nullValue())); assertThat(scenario.getSteps().get(0).getName(), is("When I search for key 1")); assertThat(scenario.getSteps().get(1).getName(), is("Then I see the value 'one'")); scenario = singleScenariosFromFeature.get(1); assertThat(scenario.getScenarioName(), is("Scenario: This is a scenario outline")); assertThat(scenario.getSteps().size(), is(2)); assertThat(scenario.getBackgroundSteps().size(), is(0)); assertThat(scenario.getSteps().get(0).getDataTable(), is(nullValue())); assertThat(scenario.getSteps().get(0).getName(), is("When I search for key 2")); assertThat(scenario.getSteps().get(1).getName(), is("Then I see the value 'two'")); scenario = singleScenariosFromFeature.get(2); assertThat(scenario.getScenarioName(), is("Scenario: This is a scenario outline")); assertThat(scenario.getSteps().size(), is(2)); assertThat(scenario.getBackgroundSteps().size(), is(0)); assertThat(scenario.getSteps().get(0).getDataTable(), is(nullValue())); assertThat(scenario.getSteps().get(0).getName(), is("When I search for key 1")); assertThat(scenario.getSteps().get(1).getName(), is("Then I see the value 'uno'")); scenario = singleScenariosFromFeature.get(3); assertThat(scenario.getScenarioName(), is("Scenario: This is a scenario outline")); assertThat(scenario.getSteps().size(), is(2)); assertThat(scenario.getBackgroundSteps().size(), is(0)); assertThat(scenario.getSteps().get(0).getDataTable(), is(nullValue())); assertThat(scenario.getSteps().get(0).getName(), is("When I search for key 2")); assertThat(scenario.getSteps().get(1).getName(), is("Then I see the value 'dos'")); } @Test public void validScenarioNamesWithScenarioOutlineTest() throws Exception { String featureContent = "Feature: test feature 3\n" + "\n" + " Scenario Outline: This is a scenario outline, key = <key>, value = <value>\n" + " This is a step\n" + " How about another step\n" + "\n" + " Examples:\n" + " | key | value |\n" + " | 1 | one |\n" + " | 2 | two |"; List<SingleScenario> singleScenariosFromFeature = gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); assertThat(singleScenariosFromFeature.size(), is(2)); SingleScenario scenario = singleScenariosFromFeature.get(0); assertThat(scenario.getScenarioName(), is("Scenario: This is a scenario outline, key = 1, value = one")); scenario = singleScenariosFromFeature.get(1); assertThat(scenario.getScenarioName(), is("Scenario: This is a scenario outline, key = 2, value = two")); } @Test public void validScenarioWithLineBreakInExampleTableTest() throws Exception { String featureContent = "Feature: test feature 3\n" + "\n" + " Scenario Outline: This is a scenario outline\n" + " Given this is a step with <key> and <value>\n" + "\n" + " Examples:\n" + " | key | value |\n" + " | 1 | one |\n" + " | 23 | two\\nthree |"; List<SingleScenario> singleScenariosFromFeature = gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); String stepName = singleScenariosFromFeature.get(1).getSteps().get(0).getName(); assertThat(stepName, is("Given this is a step with 23 and two\\nthree")); } @Test public void replacePlaceholderInStringWithMissingPlaceholdersTest() 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" + " | someKey | someValue |\n" + " | 1 | one |\n"; List<SingleScenario> singleScenariosFromFeature = gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); assertThat(singleScenariosFromFeature.get(0).getScenarioName(), is("Scenario: This is a scenario with <key> and <value>!")); } @Test public void taggedFeatureAndExamplesTest() throws Exception { String featureContent = getScenarioWithFeatureAndExampleTags(); List<SingleScenario> singleScenariosFromFeature = gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); assertThat(singleScenariosFromFeature.size(), is(3)); assertThat(singleScenariosFromFeature.get(0).getSteps().size(), is(2)); assertThat(singleScenariosFromFeature.get(1).getSteps().size(), is(2)); assertThat(singleScenariosFromFeature.get(2).getSteps().size(), is(2)); } @Test public void taggedFeatureAndExamplesRequestedExampleTagTest() throws Exception { String featureContent = getScenarioWithFeatureAndExampleTags(); when(propertyManager.getIncludeScenarioTags()).thenReturn("@exampleTag1"); List<SingleScenario> singleScenariosFromFeature = gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); assertThat(singleScenariosFromFeature.size(), is(1)); assertThat(singleScenariosFromFeature.get(0).getSteps().size(), is(2)); } @Test public void taggedFeatureAndExamplesRequestedFeatureAndExampleTagTest() throws Exception { String featureContent = getScenarioWithFeatureAndExampleTags(); when(propertyManager.getIncludeScenarioTags()).thenReturn("@featureTag and @exampleTag1"); List<SingleScenario> singleScenariosFromFeature = gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); assertThat(singleScenariosFromFeature.size(), is(1)); assertThat(singleScenariosFromFeature.get(0).getSteps().size(), is(2)); } @Test public void taggedFeatureAndExamplesRequestedInvalidExampleTagTest() throws Exception { String featureContent = getScenarioWithFeatureAndExampleTags(); when(propertyManager.getIncludeScenarioTags()).thenReturn("@exampleTag1 and @exampleTag2"); List<SingleScenario> singleScenariosFromFeature = gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); assertThat(singleScenariosFromFeature.size(), is(0)); }
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); }
@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!")); }
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 (List<String> dataTableRow : dataTableRows) { List<String> replacedDataTableRow = new ArrayList<>(); for (String dataTableCell : dataTableRow) { replacedDataTableRow.add(replacePlaceholderInString(dataTableCell, exampleMap, rowIndex)); } replacedDataTable.addRow(replacedDataTableRow); } return replacedDataTable; } @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); }
@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"; List<SingleScenario> singleScenariosFromFeature = gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); assertThat(singleScenariosFromFeature.size(), is(1)); assertThat(singleScenariosFromFeature.get(0).getSteps().size(), is(1)); DataTable dataTable = singleScenariosFromFeature.get(0).getSteps().get(0).getDataTable(); assertThat(dataTable.getRows().size(), is(1)); List<String> firstRow = dataTable.getRows().get(0); assertThat(firstRow.get(0), is("test")); assertThat(firstRow.get(1), is("1")); assertThat(firstRow.get(2), is("one")); }
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; } }
@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")); }
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 -> "<" + headerCell.getValue() + ">", headerCell -> new ArrayList<>(), (a, b) -> b, LinkedHashMap::new)); Object[] columnKeys = exampleMap.keySet().toArray(); List<TableRow> tableBody = exampleTable.getTableBody(); tableBody.stream().map(TableRow::getCells).forEachOrdered( cells -> IntStream.range(0, cells.size()).forEachOrdered(i -> { String columnKey = (String) columnKeys[i]; List<String> values = exampleMap.get(columnKey); values.add(cells.get(i).getValue()); })); return exampleMap; } }
@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 ArrayList<>(); headerCells.add(new TableCell(location, "headerCell1")); headerCells.add(new TableCell(location, "headerCell2")); headerCells.add(new TableCell(location, "headerCell3")); TableRow tableHeader = new TableRow(location, headerCells); List<TableRow> tableBody = new ArrayList<>(); List<TableCell> bodyCells = new ArrayList<>(); bodyCells.add(new TableCell(location, "bodyCell1")); bodyCells.add(new TableCell(location, "bodyCell2")); bodyCells.add(new TableCell(location, "bodyCell3")); tableBody.add(new TableRow(location, bodyCells)); bodyCells = new ArrayList<>(); bodyCells.add(new TableCell(location, "bodyCell4")); bodyCells.add(new TableCell(location, "bodyCell5")); bodyCells.add(new TableCell(location, "bodyCell6")); tableBody.add(new TableRow(location, bodyCells)); Examples examples = new Examples(location, tags, keyword, name, description, tableHeader, tableBody); List<String> includeTags = new ArrayList<>(); List<String> excludeTags = new ArrayList<>(); Map<String, List<String>> table = gherkinToCucableConverter.convertGherkinExampleTableToCucableExampleMap(examples); assertThat(table.size(), is(3)); }
FeatureFileContentRenderer { private String getRenderedFeatureFileContent(List<SingleScenario> singleScenarios) { StringBuilder renderedContent = new StringBuilder(); SingleScenario firstScenario = singleScenarios.get(0); addLanguage(renderedContent, firstScenario.getFeatureLanguage()); addTags(renderedContent, firstScenario.getFeatureTags()); addNameAndDescription( renderedContent, firstScenario.getFeatureName(), firstScenario.getFeatureDescription() ); for (SingleScenario singleScenario : singleScenarios) { renderedContent.append(LINE_SEPARATOR); List<String> scenarioTags = singleScenario.getScenarioTags(); if (scenarioTags != null && firstScenario.getFeatureTags() != null) { scenarioTags.removeAll(firstScenario.getFeatureTags()); } addTags(renderedContent, scenarioTags); addTags(renderedContent, singleScenario.getExampleTags()); addNameAndDescription( renderedContent, singleScenario.getScenarioName(), singleScenario.getScenarioDescription() ); addSteps(renderedContent, singleScenario.getBackgroundSteps()); addSteps(renderedContent, singleScenario.getSteps()); } addComments(renderedContent, firstScenario.getFeatureFilePath()); return renderedContent.toString(); } }
@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: TESTPATH\n" + "# Generated by Cucable\n"; String featureName = "Feature: featureName"; String featureDescription = "featureDescription"; String featureLanguage = ""; List<String> featureTags = Arrays.asList("@featureTag1", "@featureTag2"); String scenarioName = "Scenario: scenarioName"; String scenarioDescription = "scenarioDescription"; List<Step> backgroundSteps = Arrays.asList( new Step("Step 1", null, null), new Step("Step 2", null, null) ); List<String> scenarioTags = Arrays.asList("@scenarioTag1", "@scenarioTag2"); String featureFilePath = "TESTPATH"; SingleScenario singleScenario = new SingleScenario(featureName, featureFilePath, featureLanguage, featureDescription, scenarioName, scenarioDescription, featureTags, backgroundSteps); singleScenario.setScenarioTags(scenarioTags); String renderedFeatureFileContent = featureFileContentRenderer.getRenderedFeatureFileContent(singleScenario); renderedFeatureFileContent = renderedFeatureFileContent.replaceAll("\\r\\n", "\n"); assertThat(renderedFeatureFileContent, is(expectedOutput)); } @Test public void getRenderedFeatureFileContentNonEnglishTest() { String expectedOutput = "# language: de\n\n" + "@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: TESTPATH\n" + "# Generated by Cucable\n"; String featureName = "Feature: featureName"; String featureDescription = "featureDescription"; String featureLanguage = "de"; List<String> featureTags = Arrays.asList("@featureTag1", "@featureTag2"); String scenarioName = "Scenario: scenarioName"; String scenarioDescription = "scenarioDescription"; List<Step> backgroundSteps = Arrays.asList( new Step("Step 1", null, null), new Step("Step 2", null, null) ); List<String> scenarioTags = Arrays.asList("@scenarioTag1", "@scenarioTag2"); String featureFilePath = "TESTPATH"; SingleScenario singleScenario = new SingleScenario(featureName, featureFilePath, featureLanguage, featureDescription, scenarioName, scenarioDescription, featureTags, backgroundSteps); singleScenario.setScenarioTags(scenarioTags); String renderedFeatureFileContent = featureFileContentRenderer.getRenderedFeatureFileContent(singleScenario); renderedFeatureFileContent = renderedFeatureFileContent.replaceAll("\\r\\n", "\n"); assertThat(renderedFeatureFileContent, is(expectedOutput)); } @Test public void getRenderedFeatureFileContentReplaceBackslashesInCommentsTest() { String expectedOutput = "# language: de\n\n" + "@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: c:/unknown/path\n" + "# Generated by Cucable\n"; String featureName = "Feature: featureName"; String featureDescription = "featureDescription"; String featureLanguage = "de"; List<String> featureTags = Arrays.asList("@featureTag1", "@featureTag2"); String scenarioName = "Scenario: scenarioName"; String scenarioDescription = "scenarioDescription"; List<Step> backgroundSteps = Arrays.asList( new Step("Step 1", null, null), new Step("Step 2", null, null) ); List<String> scenarioTags = Arrays.asList("@scenarioTag1", "@scenarioTag2"); String featureFilePath = "c:\\unknown\\path"; SingleScenario singleScenario = new SingleScenario(featureName, featureFilePath, featureLanguage, featureDescription, scenarioName, scenarioDescription, featureTags, backgroundSteps); singleScenario.setScenarioTags(scenarioTags); String renderedFeatureFileContent = featureFileContentRenderer.getRenderedFeatureFileContent(singleScenario); renderedFeatureFileContent = renderedFeatureFileContent.replaceAll("\\r\\n", "\n"); assertThat(renderedFeatureFileContent, is(expectedOutput)); }
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(); } }
@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)); }
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"; 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)); }
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 = fileSystemManager.getPathsFromCucableFeature(cucableFeature); if (paths.size() == 0) { logger.warn("No features and runners could be created. Please check your properties!"); } for (Path path : paths) { List<String> generatedFeatureFilePaths = generateParallelizableFeatures(path, cucableFeature.getLineNumbers()); allGeneratedFeaturePaths.addAll(generatedFeatureFilePaths); featureFileCounter += generatedFeatureFilePaths.size(); } } int runnerFileCounter; if (propertyManager.getDesiredNumberOfFeaturesPerRunner() > 0) { runnerFileCounter = generateRunnerClassesWithDesiredNumberOfFeatures( allGeneratedFeaturePaths, propertyManager.getDesiredNumberOfFeaturesPerRunner() ); } else { runnerFileCounter = generateRunnerClassesWithDesiredNumberOfRunners( allGeneratedFeaturePaths, propertyManager.getDesiredNumberOfRunners() ); } logger.logInfoSeparator(DEFAULT); logger.info( String.format("Cucable created %d separate %s and %d %s.", featureFileCounter, Language.singularPlural(featureFileCounter, "feature file", "feature files"), runnerFileCounter, Language.singularPlural(runnerFileCounter, "runner", "runners") ), DEFAULT, COMPACT, MINIMAL ); } @Inject FeatureFileConverter( PropertyManager propertyManager, GherkinDocumentParser gherkinDocumentParser, FeatureFileContentRenderer featureFileContentRenderer, RunnerFileContentRenderer runnerFileContentRenderer, FileIO fileIO, FileSystemManager fileSystemManager, CucableLogger logger ); void generateParallelizableFeatures( final List<CucableFeature> cucableFeatures); }
@Test public void generateParallelizableFeaturesEmptyFeaturesTest() throws CucablePluginException { List<CucableFeature> cucableFeatures = new ArrayList<>(); featureFileConverter.generateParallelizableFeatures(cucableFeatures); } @Test public void convertEmptyPathListToSingleScenariosAndRunnersTest() throws Exception { propertyManager.setParallelizationMode(PropertyManager.ParallelizationMode.SCENARIOS.toString()); List<CucableFeature> cucableFeatures = new ArrayList<>(); cucableFeatures.add(new CucableFeature("", null)); featureFileConverter.generateParallelizableFeatures(cucableFeatures); } @Test public void invalidLineNumberTest() throws Exception { List<CucableFeature> cucableFeatures = new ArrayList<>(); cucableFeatures.add(new CucableFeature("FEATURE_FILE.feature", Collections.singletonList(2))); featureFileConverter.generateParallelizableFeatures(cucableFeatures); } @Test public void convertToSingleScenariosAndRunnersTest() throws Exception { String generatedFeatureDir = testFolder.getRoot().getPath().concat("/features/"); String generatedRunnerDir = testFolder.getRoot().getPath().concat("/runners/"); final String FEATURE_FILE_NAME = "FEATURE_FILE.feature"; propertyManager.setNumberOfTestRuns(1); propertyManager.setGeneratedFeatureDirectory(generatedFeatureDir); propertyManager.setGeneratedRunnerDirectory(generatedRunnerDir); when(fileIO.readContentFromFile(FEATURE_FILE_NAME)).thenReturn("TEST_CONTENT"); List<CucableFeature> cucableFeatures = new ArrayList<>(); CucableFeature cucableFeature = new CucableFeature(FEATURE_FILE_NAME, null); cucableFeatures.add(cucableFeature); when(fileSystemManager.getPathsFromCucableFeature(cucableFeature)).thenReturn(Collections.singletonList(Paths.get(cucableFeature.getName()))); List<SingleScenario> scenarioList = new ArrayList<>(); SingleScenario singleScenario = getSingleScenario(); scenarioList.add(singleScenario); when(gherkinDocumentParser.getSingleScenariosFromFeature("TEST_CONTENT", FEATURE_FILE_NAME, null)).thenReturn(scenarioList); String featureFileContent = "test"; when(featureFileContentRenderer.getRenderedFeatureFileContent(singleScenario)).thenReturn(featureFileContent); when(runnerFileContentRenderer.getRenderedRunnerFileContent(any(FeatureRunner.class))).thenReturn("RUNNER_CONTENT"); featureFileConverter.generateParallelizableFeatures(cucableFeatures); ArgumentCaptor<String> logCaptor = ArgumentCaptor.forClass(String.class); verify(logger, times(1)).info(logCaptor.capture(), any(CucableLogger.CucableLogLevel.class), any(CucableLogger.CucableLogLevel.class), any(CucableLogger.CucableLogLevel.class)); assertThat(logCaptor.getAllValues().get(0), is("Cucable created 1 separate feature file and 1 runner.")); verify(fileIO, times(2)).writeContentToFile(anyString(), anyString()); } @Test public void convertToSingleScenariosAndRunnersWithScenarioNameTest() throws Exception { String generatedFeatureDir = testFolder.getRoot().getPath().concat("/features/"); String generatedRunnerDir = testFolder.getRoot().getPath().concat("/runners/"); String scenarioMatchText = "Feature: feature1\n Scenario: scenarioName1"; final String FEATURE_FILE_NAME = "FEATURE_FILE.feature"; final String GENERATED_FEATURE_FILE_NAME = "FEATURE_FILE_scenario001_run001_IT.feature"; propertyManager.setNumberOfTestRuns(1); propertyManager.setGeneratedFeatureDirectory(generatedFeatureDir); propertyManager.setGeneratedRunnerDirectory(generatedRunnerDir); propertyManager.setScenarioNames("scenarioName1"); when(fileIO.readContentFromFile(FEATURE_FILE_NAME)).thenReturn("TEST_CONTENT"); when(fileIO.readContentFromFile(generatedFeatureDir + "/" + GENERATED_FEATURE_FILE_NAME)).thenReturn(scenarioMatchText); List<CucableFeature> cucableFeatures = new ArrayList<>(); CucableFeature cucableFeature = new CucableFeature(FEATURE_FILE_NAME, null); cucableFeatures.add(cucableFeature); when(fileSystemManager.getPathsFromCucableFeature(cucableFeature)).thenReturn(Collections.singletonList(Paths.get(cucableFeature.getName()))); List<SingleScenario> scenarioList = new ArrayList<>(); SingleScenario singleScenario = getSingleScenario(); scenarioList.add(singleScenario); when(gherkinDocumentParser.getSingleScenariosFromFeature("TEST_CONTENT", FEATURE_FILE_NAME, null)).thenReturn(scenarioList); when(gherkinDocumentParser.matchScenarioWithScenarioNames("en", scenarioMatchText)).thenReturn(0); String featureFileContent = "test"; when(featureFileContentRenderer.getRenderedFeatureFileContent(singleScenario)).thenReturn(featureFileContent); when(runnerFileContentRenderer.getRenderedRunnerFileContent(any(FeatureRunner.class))).thenReturn("RUNNER_CONTENT"); featureFileConverter.generateParallelizableFeatures(cucableFeatures); ArgumentCaptor<String> logCaptor = ArgumentCaptor.forClass(String.class); verify(logger, times(1)).info(logCaptor.capture(), any(CucableLogger.CucableLogLevel.class), any(CucableLogger.CucableLogLevel.class), any(CucableLogger.CucableLogLevel.class)); assertThat(logCaptor.getAllValues().get(0), is("Cucable created 1 separate feature file and 1 runner.")); verify(fileIO, times(2)).writeContentToFile(anyString(), anyString()); } @Test public void convertToSingleScenariosAndRunnersWithFeaturesModeTest() throws Exception { String generatedFeatureDir = testFolder.getRoot().getPath().concat("/features/"); String generatedRunnerDir = testFolder.getRoot().getPath().concat("/runners/"); final String FEATURE_FILE_NAME = "FEATURE_FILE.feature"; propertyManager.setNumberOfTestRuns(1); propertyManager.setGeneratedFeatureDirectory(generatedFeatureDir); propertyManager.setGeneratedRunnerDirectory(generatedRunnerDir); propertyManager.setParallelizationMode("features"); when(fileIO.readContentFromFile(FEATURE_FILE_NAME)).thenReturn("TEST_CONTENT"); List<CucableFeature> cucableFeatures = new ArrayList<>(); CucableFeature cucableFeature = new CucableFeature(FEATURE_FILE_NAME, null); cucableFeatures.add(cucableFeature); when(fileSystemManager.getPathsFromCucableFeature(cucableFeature)).thenReturn(Collections.singletonList(Paths.get(cucableFeature.getName()))); List<SingleScenario> scenarioList = new ArrayList<>(); SingleScenario singleScenario = getSingleScenario(); scenarioList.add(singleScenario); when(gherkinDocumentParser.getSingleScenariosFromFeature("TEST_CONTENT", FEATURE_FILE_NAME, null)).thenReturn(scenarioList); String featureFileContent = "test"; when(featureFileContentRenderer.getRenderedFeatureFileContent(singleScenario)).thenReturn(featureFileContent); when(runnerFileContentRenderer.getRenderedRunnerFileContent(any(FeatureRunner.class))).thenReturn("RUNNER_CONTENT"); featureFileConverter.generateParallelizableFeatures(cucableFeatures); verify(fileIO, times(2)).writeContentToFile(anyString(), anyString()); } @Test public void convertToSingleScenariosAndMultiRunnersTest() throws Exception { String generatedFeatureDir = testFolder.getRoot().getPath().concat("/features/"); String generatedRunnerDir = testFolder.getRoot().getPath().concat("/runners/"); final String FEATURE_FILE_NAME = "FEATURE_FILE.feature"; propertyManager.setNumberOfTestRuns(1); propertyManager.setDesiredNumberOfRunners(1); propertyManager.setGeneratedFeatureDirectory(generatedFeatureDir); propertyManager.setGeneratedRunnerDirectory(generatedRunnerDir); propertyManager.setParallelizationMode("scenarios"); when(fileIO.readContentFromFile(FEATURE_FILE_NAME)).thenReturn("TEST_CONTENT"); List<CucableFeature> cucableFeatures = new ArrayList<>(); CucableFeature cucableFeature = new CucableFeature(FEATURE_FILE_NAME, null); cucableFeatures.add(cucableFeature); when(fileSystemManager.getPathsFromCucableFeature(cucableFeature)).thenReturn(Collections.singletonList(Paths.get(cucableFeature.getName()))); List<SingleScenario> scenarioList = new ArrayList<>(); SingleScenario singleScenario = getSingleScenario(); scenarioList.add(singleScenario); scenarioList.add(singleScenario); when(gherkinDocumentParser.getSingleScenariosFromFeature("TEST_CONTENT", FEATURE_FILE_NAME, null)).thenReturn(scenarioList); String featureFileContent = "test"; when(featureFileContentRenderer.getRenderedFeatureFileContent(singleScenario)).thenReturn(featureFileContent); when(runnerFileContentRenderer.getRenderedRunnerFileContent(any(FeatureRunner.class))).thenReturn("RUNNER_CONTENT"); featureFileConverter.generateParallelizableFeatures(cucableFeatures); verify(fileIO, times(3)).writeContentToFile(anyString(), anyString()); } @Test public void convertToSingleScenariosAndMultiRunnersWithScenarioNamesTest() throws Exception { String generatedFeatureDir = testFolder.getRoot().getPath().concat("/features/"); String generatedRunnerDir = testFolder.getRoot().getPath().concat("/runners/"); final String scenarioMatch1Text = "Feature: feature1\n Scenario: scenarioName1"; final String scenarioMatch2Text = "Feature: feature2\n Scenario: scenarioName2"; final String FEATURE_FILE_NAME = "FEATURE_FILE.feature"; final String GENERATED_FEATURE_FILE_NAME1 = "FEATURE_FILE_scenario001_run001_IT.feature"; final String GENERATED_FEATURE_FILE_NAME2 = "FEATURE_FILE_scenario002_run001_IT.feature"; propertyManager.setNumberOfTestRuns(1); propertyManager.setGeneratedFeatureDirectory(generatedFeatureDir); propertyManager.setGeneratedRunnerDirectory(generatedRunnerDir); propertyManager.setParallelizationMode("scenarios"); propertyManager.setScenarioNames("scenarioName1, scenarioName2"); when(fileIO.readContentFromFile(FEATURE_FILE_NAME)).thenReturn("TEST_CONTENT"); when(fileIO.readContentFromFile(generatedFeatureDir + "/" + GENERATED_FEATURE_FILE_NAME1)).thenReturn(scenarioMatch1Text); when(fileIO.readContentFromFile(generatedFeatureDir + "/" + GENERATED_FEATURE_FILE_NAME2)).thenReturn(scenarioMatch2Text); when(fileIO.readContentFromFile(generatedFeatureDir + "/" + FEATURE_FILE_NAME)).thenReturn("TEST_CONTENT"); List<CucableFeature> cucableFeatures = new ArrayList<>(); CucableFeature cucableFeature = new CucableFeature(FEATURE_FILE_NAME, null); cucableFeatures.add(cucableFeature); when(fileSystemManager.getPathsFromCucableFeature(cucableFeature)).thenReturn(Collections.singletonList(Paths.get(cucableFeature.getName()))); List<SingleScenario> scenarioList = new ArrayList<>(); SingleScenario singleScenario = getSingleScenario(); scenarioList.add(singleScenario); scenarioList.add(singleScenario); when(gherkinDocumentParser.getSingleScenariosFromFeature("TEST_CONTENT", FEATURE_FILE_NAME, null)).thenReturn(scenarioList); when(gherkinDocumentParser.matchScenarioWithScenarioNames("en", scenarioMatch1Text)).thenReturn(0); when(gherkinDocumentParser.matchScenarioWithScenarioNames("en", scenarioMatch2Text)).thenReturn(1); String featureFileContent = "test"; when(featureFileContentRenderer.getRenderedFeatureFileContent(singleScenario)).thenReturn(featureFileContent); when(runnerFileContentRenderer.getRenderedRunnerFileContent(any(FeatureRunner.class))).thenReturn("RUNNER_CONTENT"); featureFileConverter.generateParallelizableFeatures(cucableFeatures); ArgumentCaptor<String> logCaptor = ArgumentCaptor.forClass(String.class); verify(logger, times(1)).info(logCaptor.capture(), any(CucableLogger.CucableLogLevel.class), any(CucableLogger.CucableLogLevel.class), any(CucableLogger.CucableLogLevel.class)); assertThat(logCaptor.getAllValues().get(0), is("Cucable created 2 separate feature files and 2 runners.")); verify(fileIO, times(4)).writeContentToFile(anyString(), anyString()); } @Test public void convertToSingleScenariosAndMultiRunnersWithScenarioNamesAndExampleKeywordTest() throws Exception { String generatedFeatureDir = testFolder.getRoot().getPath().concat("/features/"); String generatedRunnerDir = testFolder.getRoot().getPath().concat("/runners/"); final String scenarioMatch1Text = "Feature: feature1\n Scenario: scenarioName1"; final String scenarioMatch2Text = "Feature: feature2\n Example: scenarioName2"; final String FEATURE_FILE_NAME = "FEATURE_FILE.feature"; final String GENERATED_FEATURE_FILE_NAME1 = "FEATURE_FILE_scenario001_run001_IT.feature"; final String GENERATED_FEATURE_FILE_NAME2 = "FEATURE_FILE_scenario002_run001_IT.feature"; propertyManager.setNumberOfTestRuns(1); propertyManager.setGeneratedFeatureDirectory(generatedFeatureDir); propertyManager.setGeneratedRunnerDirectory(generatedRunnerDir); propertyManager.setParallelizationMode("scenarios"); propertyManager.setScenarioNames("scenarioName1, scenarioName2"); when(fileIO.readContentFromFile(FEATURE_FILE_NAME)).thenReturn("TEST_CONTENT"); when(fileIO.readContentFromFile(generatedFeatureDir + "/" + GENERATED_FEATURE_FILE_NAME1)).thenReturn(scenarioMatch1Text); when(fileIO.readContentFromFile(generatedFeatureDir + "/" + GENERATED_FEATURE_FILE_NAME2)).thenReturn(scenarioMatch2Text); when(fileIO.readContentFromFile(generatedFeatureDir + "/" + FEATURE_FILE_NAME)).thenReturn("TEST_CONTENT"); List<CucableFeature> cucableFeatures = new ArrayList<>(); CucableFeature cucableFeature = new CucableFeature(FEATURE_FILE_NAME, null); cucableFeatures.add(cucableFeature); when(fileSystemManager.getPathsFromCucableFeature(cucableFeature)).thenReturn(Collections.singletonList(Paths.get(cucableFeature.getName()))); List<SingleScenario> scenarioList = new ArrayList<>(); SingleScenario singleScenario = getSingleScenario(); scenarioList.add(singleScenario); scenarioList.add(singleScenario); when(gherkinDocumentParser.getSingleScenariosFromFeature("TEST_CONTENT", FEATURE_FILE_NAME, null)).thenReturn(scenarioList); when(gherkinDocumentParser.matchScenarioWithScenarioNames("en", scenarioMatch1Text)).thenReturn(0); when(gherkinDocumentParser.matchScenarioWithScenarioNames("en", scenarioMatch2Text)).thenReturn(1); String featureFileContent = "test"; when(featureFileContentRenderer.getRenderedFeatureFileContent(singleScenario)).thenReturn(featureFileContent); when(runnerFileContentRenderer.getRenderedRunnerFileContent(any(FeatureRunner.class))).thenReturn("RUNNER_CONTENT"); featureFileConverter.generateParallelizableFeatures(cucableFeatures); ArgumentCaptor<String> logCaptor = ArgumentCaptor.forClass(String.class); verify(logger, times(1)).info(logCaptor.capture(), any(CucableLogger.CucableLogLevel.class), any(CucableLogger.CucableLogLevel.class), any(CucableLogger.CucableLogLevel.class)); assertThat(logCaptor.getAllValues().get(0), is("Cucable created 2 separate feature files and 2 runners.")); verify(fileIO, times(4)).writeContentToFile(anyString(), anyString()); } @Test public void convertToSingleScenariosAndMultiRunnersFeaturesModeTest() throws Exception { String generatedFeatureDir = testFolder.getRoot().getPath().concat("/features/"); String generatedRunnerDir = testFolder.getRoot().getPath().concat("/runners/"); final String FEATURE_FILE_NAME = "FEATURE_FILE.feature"; propertyManager.setNumberOfTestRuns(1); propertyManager.setDesiredNumberOfRunners(1); propertyManager.setGeneratedFeatureDirectory(generatedFeatureDir); propertyManager.setGeneratedRunnerDirectory(generatedRunnerDir); propertyManager.setParallelizationMode(PropertyManager.ParallelizationMode.FEATURES.toString()); when(fileIO.readContentFromFile(FEATURE_FILE_NAME)).thenReturn("TEST_CONTENT"); List<CucableFeature> cucableFeatures = new ArrayList<>(); CucableFeature cucableFeature = new CucableFeature(FEATURE_FILE_NAME, null); cucableFeatures.add(cucableFeature); when(fileSystemManager.getPathsFromCucableFeature(cucableFeature)).thenReturn(Collections.singletonList(Paths.get(cucableFeature.getName()))); when(runnerFileContentRenderer.getRenderedRunnerFileContent(any(FeatureRunner.class))).thenReturn("RUNNER_CONTENT"); featureFileConverter.generateParallelizableFeatures(cucableFeatures); verify(fileIO, times(2)).writeContentToFile(anyString(), anyString()); } @Test(expected = CucablePluginException.class) public void noScenariosMatchingScenarioNamesTest() throws Exception { String generatedFeatureDir = testFolder.getRoot().getPath().concat("/features/"); String generatedRunnerDir = testFolder.getRoot().getPath().concat("/runners/"); final String FEATURE_FILE_NAME = "FEATURE_FILE.feature"; final String GENERATED_FEATURE_FILE_NAME = "FEATURE_FILE_scenario001_run001_IT.feature"; final String scenarioNoMatchText = "Feature: feature1\n Scenario: noMatch"; propertyManager.setNumberOfTestRuns(1); propertyManager.setGeneratedFeatureDirectory(generatedFeatureDir); propertyManager.setGeneratedRunnerDirectory(generatedRunnerDir); propertyManager.setScenarioNames("scenarioName1"); when(fileIO.readContentFromFile(FEATURE_FILE_NAME)).thenReturn("TEST_CONTENT"); when(fileIO.readContentFromFile(generatedFeatureDir + "/" + GENERATED_FEATURE_FILE_NAME)).thenReturn(scenarioNoMatchText); List<CucableFeature> cucableFeatures = new ArrayList<>(); CucableFeature cucableFeature = new CucableFeature(FEATURE_FILE_NAME, null); cucableFeatures.add(cucableFeature); when(fileSystemManager.getPathsFromCucableFeature(cucableFeature)).thenReturn(Collections.singletonList(Paths.get(cucableFeature.getName()))); List<SingleScenario> scenarioList = new ArrayList<>(); SingleScenario singleScenario = getSingleScenario(); scenarioList.add(singleScenario); when(gherkinDocumentParser.getSingleScenariosFromFeature("TEST_CONTENT", FEATURE_FILE_NAME, null)).thenReturn(scenarioList); when(gherkinDocumentParser.matchScenarioWithScenarioNames("en", scenarioNoMatchText)).thenReturn(-1); String featureFileContent = "test"; when(featureFileContentRenderer.getRenderedFeatureFileContent(singleScenario)).thenReturn(featureFileContent); when(runnerFileContentRenderer.getRenderedRunnerFileContent(any(FeatureRunner.class))).thenReturn("RUNNER_CONTENT"); featureFileConverter.generateParallelizableFeatures(cucableFeatures); }
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(); }
@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(String filePath); }
@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.getGeneratedRunnerDirectory()); removeFilesFromPath(propertyManager.getGeneratedRunnerDirectory(), "java"); } @Inject FileSystemManager(PropertyManager propertyManager); List<Path> getPathsFromCucableFeature(final CucableFeature cucableFeature); void prepareGeneratedFeatureAndRunnerDirectories(); }
@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(); }
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 (sourceFeatures.trim().isEmpty()) { return Collections.emptyList(); } if (sourceFeaturesFile.isFile() && sourceFeatures.endsWith(FEATURE_FILE_EXTENSION)) { return Collections.singletonList(Paths.get(sourceFeatures)); } if (sourceFeaturesFile.isDirectory()) { return getFilesWithFeatureExtension(sourceFeatures); } throw new CucablePluginException( sourceFeatures + " is not a feature file or a directory." ); } @Inject FileSystemManager(PropertyManager propertyManager); List<Path> getPathsFromCucableFeature(final CucableFeature cucableFeature); void prepareGeneratedFeatureAndRunnerDirectories(); }
@Test public void getPathsFromCucableFeatureNullTest() throws CucablePluginException { List<Path> pathsFromCucableFeature = fileSystemManager.getPathsFromCucableFeature(null); assertThat(pathsFromCucableFeature, is(notNullValue())); assertThat(pathsFromCucableFeature.size(), is(0)); } @Test(expected = CucablePluginException.class) public void getPathsFromCucableFeatureInvalidFeatureTest() throws CucablePluginException { CucableFeature cucableFeatures = new CucableFeature("name.feature", null); fileSystemManager.getPathsFromCucableFeature(cucableFeatures); } @Test public void getPathsFromCucableFeatureValidEmptyPathTest() throws CucablePluginException { CucableFeature cucableFeatures = new CucableFeature(testFolder.getRoot().getPath(), null); List<Path> pathsFromCucableFeature = fileSystemManager.getPathsFromCucableFeature(cucableFeatures); assertThat(pathsFromCucableFeature, is(notNullValue())); assertThat(pathsFromCucableFeature.size(), is(0)); } @Test public void getPathsFromCucableFeatureFullPathTest() throws CucablePluginException { CucableFeature cucableFeatures = new CucableFeature("src/test/resources", null); List<Path> pathsFromCucableFeature = fileSystemManager.getPathsFromCucableFeature(cucableFeatures); assertThat(pathsFromCucableFeature, is(notNullValue())); assertThat(pathsFromCucableFeature.size(), is(2)); } @Test public void getPathsFromCucableFeatureValidFeatureTest() throws CucablePluginException { CucableFeature cucableFeatures = new CucableFeature("src/test/resources/feature1.feature", null); List<Path> pathsFromCucableFeature = fileSystemManager.getPathsFromCucableFeature(cucableFeatures); assertThat(pathsFromCucableFeature, is(notNullValue())); assertThat(pathsFromCucableFeature.size(), is(1)); }
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(); }
@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 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(); }
@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 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(); }
@Test public void setDesiredNumberOfRunnersTest() { propertyManager.setDesiredNumberOfRunners(12); assertThat(propertyManager.getDesiredNumberOfRunners(), is(12)); }