You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@plc4x.apache.org by sr...@apache.org on 2021/04/24 21:30:50 UTC
[plc4x] 07/08: plc4j: refactored test-utils
This is an automated email from the ASF dual-hosted git repository.
sruehl pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/plc4x.git
commit 9225b17cd8dd58dd3dfdd942e9b09a9dcba0dc17
Author: Sebastian Rühl <sr...@apache.org>
AuthorDate: Sat Apr 24 22:47:57 2021 +0200
plc4j: refactored test-utils
+ ParserSerializerTestsuiteRunner and DriverTestsuiteRunner have now the ability to convert from the old jackson based xml serialization to the new mpsec serializer based approach
+ split up DriverTestsuiteRunner into multiple classes
+ fixed parser testsuites using the old reduced format
---
.../protocols/ads/ParserSerializerTestsuite.xml | 24 +-
.../knxnetip/ParserSerializerTestsuite.xml | 90 ++--
.../protocol/abeth/AbEthParserSerializerTest.java | 2 +-
.../ads/AdsDiscoverySerializerParserTest.java | 2 +-
.../protocol/ads/AdsSerializerParserTest.java | 2 +-
.../plc4x/java/canopen/CANOpenPayloadTest.java | 2 +-
.../plc4x/java/canopen/CANOpenWiresharkTest.java | 2 +-
.../readwrite/EIPParserSerializerTestsuite.java | 2 +-
.../readwrite/FirmataParserSerializerTest.java | 2 +-
.../knxnetip/KnxNetIpParserSerializerTest.java | 2 +-
.../java/modbus/ModbusParserSerializerTest.java | 2 +-
.../java/s7/readwrite/S7ParserSerializerTest.java | 2 +-
...estsuiteRunner.java => XmlTestsuiteLoader.java} | 4 +-
.../plc4x/test/driver/DriverTestsuiteRunner.java | 508 +--------------------
.../java/org/apache/plc4x/test/driver/Lalala.java | 44 --
.../exceptions/DriverTestsuiteException.java | 6 +-
.../test/driver/internal/ConnectionManager.java | 68 +++
.../test/driver/internal/DriverTestsuite.java | 236 ++++++++++
.../DriverTestsuiteConfiguration.java} | 59 +--
.../test/driver/{model => internal}/StepType.java | 23 +-
.../plc4x/test/driver/internal/TestStep.java | 138 ++++++
.../plc4x/test/driver/internal/Testcase.java | 110 +++++
.../driver/{model => internal}/api/TestField.java | 2 +-
.../{model => internal}/api/TestFieldRequest.java | 2 +-
.../{model => internal}/api/TestReadRequest.java | 2 +-
.../{model => internal}/api/TestRequest.java | 2 +-
.../{model => internal}/api/TestValueField.java | 2 +-
.../{model => internal}/api/TestWriteRequest.java | 2 +-
.../internal/handlers/ApiRequestHandler.java | 93 ++++
.../internal/handlers/ApiResponseHandler.java | 93 ++++
.../handlers/IncomingPlcBytesHandler.java} | 12 +-
.../handlers/IncomingPlcMessageHandler.java | 76 +++
.../internal/handlers/OutgoingPlcBytesHandler.java | 48 ++
.../handlers/OutgoingPlcMessageHandler.java | 52 +++
.../test/driver/internal/utils/ChannelUtil.java | 45 ++
.../TestField.java => internal/utils/Delay.java} | 28 +-
.../utils/Synchronizer.java} | 12 +-
.../driver/internal/validator/ApiValidator.java | 44 ++
.../apache/plc4x/test/driver/model/TestStep.java | 68 ---
.../apache/plc4x/test/driver/model/Testcase.java | 61 ---
.../plc4x/test/mapper/TestSuiteMappingModule.java | 2 +
.../plc4x/test/migration/MessageResolver.java | 202 ++++++++
.../migration/MessageValidatorAndMigrator.java | 297 ++++++++++++
.../plc4x/test/migration/MigrationException.java | 32 ++
.../plc4x/test/migration/TestCasePatcher.java | 61 +++
.../ParserSerializerTestsuiteRunner.java | 299 +-----------
.../protocols/ads/ParserSerializerTestsuite.xml | 24 +-
.../knxnetip/ParserSerializerTestsuite.xml | 36 +-
.../protocol/df1/Df1ParserSerializerTest.java | 2 +-
49 files changed, 1824 insertions(+), 1105 deletions(-)
diff --git a/plc4go/assets/testing/protocols/ads/ParserSerializerTestsuite.xml b/plc4go/assets/testing/protocols/ads/ParserSerializerTestsuite.xml
index 6113134..6fcac92 100644
--- a/plc4go/assets/testing/protocols/ads/ParserSerializerTestsuite.xml
+++ b/plc4go/assets/testing/protocols/ads/ParserSerializerTestsuite.xml
@@ -58,7 +58,7 @@
</sourceAmsNetId>
<sourceAmsPort dataType="uint" bitLength="16">851</sourceAmsPort>
<commandId>
- <commandId dataType="uint" bitLength="16">2</commandId>
+ <CommandId dataType="uint" bitLength="16" stringRepresentation="ADS_READ">2</CommandId>
</commandId>
<state>
<State>
@@ -125,7 +125,7 @@
</sourceAmsNetId>
<sourceAmsPort dataType="uint" bitLength="16">851</sourceAmsPort>
<commandId>
- <commandId dataType="uint" bitLength="16">2</commandId>
+ <CommandId dataType="uint" bitLength="16" stringRepresentation="ADS_READ">2</CommandId>
</commandId>
<state>
<State>
@@ -148,7 +148,7 @@
<AdsData>
<AdsReadResponse>
<result>
- <result dataType="uint" bitLength="32">0</result>
+ <ReturnCode dataType="uint" bitLength="32" stringRepresentation="OK">0</ReturnCode>
</result>
<length dataType="uint" bitLength="32">1</length>
<data isList="true">
@@ -196,7 +196,7 @@
</sourceAmsNetId>
<sourceAmsPort dataType="uint" bitLength="16">65534</sourceAmsPort>
<commandId>
- <commandId dataType="uint" bitLength="16">9</commandId>
+ <CommandId dataType="uint" bitLength="16" stringRepresentation="ADS_READ_WRITE">9</CommandId>
</commandId>
<state>
<State>
@@ -294,7 +294,7 @@
</sourceAmsNetId>
<sourceAmsPort dataType="uint" bitLength="16">851</sourceAmsPort>
<commandId>
- <commandId dataType="uint" bitLength="16">9</commandId>
+ <CommandId dataType="uint" bitLength="16" stringRepresentation="ADS_READ_WRITE">9</CommandId>
</commandId>
<state>
<State>
@@ -317,7 +317,7 @@
<AdsData>
<AdsReadWriteResponse>
<result>
- <result dataType="uint" bitLength="32">0</result>
+ <ReturnCode dataType="uint" bitLength="32" stringRepresentation="OK">0</ReturnCode>
</result>
<length dataType="uint" bitLength="32">4</length>
<data isList="true">
@@ -368,7 +368,7 @@
</sourceAmsNetId>
<sourceAmsPort dataType="uint" bitLength="16">65534</sourceAmsPort>
<commandId>
- <commandId dataType="uint" bitLength="16">2</commandId>
+ <CommandId dataType="uint" bitLength="16" stringRepresentation="ADS_READ">2</CommandId>
</commandId>
<state>
<State>
@@ -435,7 +435,7 @@
</sourceAmsNetId>
<sourceAmsPort dataType="uint" bitLength="16">851</sourceAmsPort>
<commandId>
- <commandId dataType="uint" bitLength="16">2</commandId>
+ <CommandId dataType="uint" bitLength="16" stringRepresentation="ADS_READ">2</CommandId>
</commandId>
<state>
<State>
@@ -458,7 +458,7 @@
<AdsData>
<AdsReadResponse>
<result>
- <result dataType="uint" bitLength="32">0</result>
+ <ReturnCode dataType="uint" bitLength="32" stringRepresentation="OK">0</ReturnCode>
</result>
<length dataType="uint" bitLength="32">1</length>
<data isList="true">
@@ -506,7 +506,7 @@
</sourceAmsNetId>
<sourceAmsPort dataType="uint" bitLength="16">65534</sourceAmsPort>
<commandId>
- <commandId dataType="uint" bitLength="16">3</commandId>
+ <CommandId dataType="uint" bitLength="16" stringRepresentation="ADS_WRITE">3</CommandId>
</commandId>
<state>
<State>
@@ -579,7 +579,7 @@
</sourceAmsNetId>
<sourceAmsPort dataType="uint" bitLength="16">851</sourceAmsPort>
<commandId>
- <commandId dataType="uint" bitLength="16">3</commandId>
+ <CommandId dataType="uint" bitLength="16" stringRepresentation="ADS_WRITE">3</CommandId>
</commandId>
<state>
<State>
@@ -602,7 +602,7 @@
<AdsData>
<AdsWriteResponse>
<result>
- <result dataType="uint" bitLength="32">0</result>
+ <ReturnCode dataType="uint" bitLength="32" stringRepresentation="OK">0</ReturnCode>
</result>
</AdsWriteResponse>
</AdsData>
diff --git a/plc4go/assets/testing/protocols/knxnetip/ParserSerializerTestsuite.xml b/plc4go/assets/testing/protocols/knxnetip/ParserSerializerTestsuite.xml
index da66223..bc38437 100644
--- a/plc4go/assets/testing/protocols/knxnetip/ParserSerializerTestsuite.xml
+++ b/plc4go/assets/testing/protocols/knxnetip/ParserSerializerTestsuite.xml
@@ -52,7 +52,7 @@
</tunnelingRequestDataBlock>
<cemi className="org.apache.plc4x.java.knxnetip.readwrite.CEMIBusmonInd">
<additionalInformationLength>7</additionalInformationLength>
- <additionalInformation>
+ <additionalInformation isList="true">
<additionalInformation className="org.apache.plc4x.java.knxnetip.readwrite.CEMIAdditionalInformationBusmonitorInfo">
<frameErrorFlag>false</frameErrorFlag>
<bitErrorFlag>false</bitErrorFlag>
@@ -92,7 +92,7 @@
</tunnelingRequestDataBlock>
<cemi className="org.apache.plc4x.java.knxnetip.readwrite.CEMIBusmonInd">
<additionalInformationLength>7</additionalInformationLength>
- <additionalInformation>
+ <additionalInformation isList="true">
<additionalInformation className="org.apache.plc4x.java.knxnetip.readwrite.CEMIAdditionalInformationBusmonitorInfo">
<frameErrorFlag>false</frameErrorFlag>
<bitErrorFlag>false</bitErrorFlag>
@@ -132,11 +132,11 @@
<HPAIDiscoveryEndpoint>
<structureLength dataType="uint" bitLength="8">8</structureLength>
<hostProtocolCode>
- <hostProtocolCode dataType="uint" bitLength="8">1</hostProtocolCode>
+ <HostProtocolCode dataType="uint" bitLength="8" stringRepresentation="IPV4_UDP">1</HostProtocolCode>
</hostProtocolCode>
<ipAddress>
<IPAddress>
- <addr>
+ <addr isList="true">
<value dataType="int" bitLength="8">-64</value>
<value dataType="int" bitLength="8">-88</value>
<value dataType="int" bitLength="8">42</value>
@@ -169,11 +169,11 @@
<HPAIControlEndpoint>
<structureLength dataType="uint" bitLength="8">8</structureLength>
<hostProtocolCode>
- <hostProtocolCode dataType="uint" bitLength="8">1</hostProtocolCode>
+ <HostProtocolCode dataType="uint" bitLength="8" stringRepresentation="IPV4_UDP">1</HostProtocolCode>
</hostProtocolCode>
<ipAddress>
<IPAddress>
- <addr>
+ <addr isList="true">
<value dataType="int" bitLength="8">-64</value>
<value dataType="int" bitLength="8">-88</value>
<value dataType="int" bitLength="8">42</value>
@@ -189,7 +189,7 @@
<structureLength dataType="uint" bitLength="8">54</structureLength>
<descriptionType dataType="uint" bitLength="8">1</descriptionType>
<knxMedium>
- <knxMedium dataType="uint" bitLength="8">2</knxMedium>
+ <KnxMedium dataType="uint" bitLength="8" stringRepresentation="MEDIUM_TP1">2</KnxMedium>
</knxMedium>
<deviceStatus>
<DeviceStatus>
@@ -210,7 +210,7 @@
<installationNumber dataType="uint" bitLength="8">0</installationNumber>
</ProjectInstallationIdentifier>
</projectInstallationIdentifier>
- <knxNetIpDeviceSerialNumber>
+ <knxNetIpDeviceSerialNumber isList="true">
<value dataType="int" bitLength="8">0</value>
<value dataType="int" bitLength="8">8</value>
<value dataType="int" bitLength="8">45</value>
@@ -220,7 +220,7 @@
</knxNetIpDeviceSerialNumber>
<knxNetIpDeviceMulticastAddress>
<IPAddress>
- <addr>
+ <addr isList="true">
<value dataType="int" bitLength="8">-32</value>
<value dataType="int" bitLength="8">0</value>
<value dataType="int" bitLength="8">23</value>
@@ -230,7 +230,7 @@
</knxNetIpDeviceMulticastAddress>
<knxNetIpDeviceMacAddress>
<MACAddress>
- <addr>
+ <addr isList="true">
<value dataType="int" bitLength="8">0</value>
<value dataType="int" bitLength="8">10</value>
<value dataType="int" bitLength="8">-77</value>
@@ -240,7 +240,7 @@
</addr>
</MACAddress>
</knxNetIpDeviceMacAddress>
- <deviceFriendlyName>
+ <deviceFriendlyName isList="true">
<value dataType="int" bitLength="8">71</value>
<value dataType="int" bitLength="8">105</value>
<value dataType="int" bitLength="8">114</value>
@@ -278,7 +278,7 @@
<DIBSuppSvcFamilies>
<structureLength dataType="uint" bitLength="8">8</structureLength>
<descriptionType dataType="uint" bitLength="8">2</descriptionType>
- <serviceIds>
+ <serviceIds isList="true">
<ServiceId>
<serviceType dataType="uint" bitLength="8">2</serviceType>
<KnxNetIpCore>
@@ -320,11 +320,11 @@
<HPAIControlEndpoint>
<structureLength dataType="uint" bitLength="8">8</structureLength>
<hostProtocolCode>
- <hostProtocolCode dataType="uint" bitLength="8">1</hostProtocolCode>
+ <HostProtocolCode dataType="uint" bitLength="8" stringRepresentation="IPV4_UDP">1</HostProtocolCode>
</hostProtocolCode>
<ipAddress>
<IPAddress>
- <addr>
+ <addr isList="true">
<value dataType="int" bitLength="8">0</value>
<value dataType="int" bitLength="8">0</value>
<value dataType="int" bitLength="8">0</value>
@@ -358,7 +358,7 @@
<structureLength dataType="uint" bitLength="8">54</structureLength>
<descriptionType dataType="uint" bitLength="8">1</descriptionType>
<knxMedium>
- <knxMedium dataType="uint" bitLength="8">2</knxMedium>
+ <KnxMedium dataType="uint" bitLength="8" stringRepresentation="MEDIUM_TP1">2</KnxMedium>
</knxMedium>
<deviceStatus>
<DeviceStatus>
@@ -379,7 +379,7 @@
<installationNumber dataType="uint" bitLength="8">0</installationNumber>
</ProjectInstallationIdentifier>
</projectInstallationIdentifier>
- <knxNetIpDeviceSerialNumber>
+ <knxNetIpDeviceSerialNumber isList="true">
<value dataType="int" bitLength="8">0</value>
<value dataType="int" bitLength="8">8</value>
<value dataType="int" bitLength="8">45</value>
@@ -389,7 +389,7 @@
</knxNetIpDeviceSerialNumber>
<knxNetIpDeviceMulticastAddress>
<IPAddress>
- <addr>
+ <addr isList="true">
<value dataType="int" bitLength="8">-32</value>
<value dataType="int" bitLength="8">0</value>
<value dataType="int" bitLength="8">23</value>
@@ -399,7 +399,7 @@
</knxNetIpDeviceMulticastAddress>
<knxNetIpDeviceMacAddress>
<MACAddress>
- <addr>
+ <addr isList="true">
<value dataType="int" bitLength="8">0</value>
<value dataType="int" bitLength="8">10</value>
<value dataType="int" bitLength="8">-77</value>
@@ -409,7 +409,7 @@
</addr>
</MACAddress>
</knxNetIpDeviceMacAddress>
- <deviceFriendlyName>
+ <deviceFriendlyName isList="true">
<value dataType="int" bitLength="8">71</value>
<value dataType="int" bitLength="8">105</value>
<value dataType="int" bitLength="8">114</value>
@@ -447,7 +447,7 @@
<DIBSuppSvcFamilies>
<structureLength dataType="uint" bitLength="8">8</structureLength>
<descriptionType dataType="uint" bitLength="8">2</descriptionType>
- <serviceIds>
+ <serviceIds isList="true">
<ServiceId>
<serviceType dataType="uint" bitLength="8">2</serviceType>
<KnxNetIpCore>
@@ -490,11 +490,11 @@
<HPAIDiscoveryEndpoint>
<structureLength dataType="uint" bitLength="8">8</structureLength>
<hostProtocolCode>
- <hostProtocolCode dataType="uint" bitLength="8">1</hostProtocolCode>
+ <HostProtocolCode dataType="uint" bitLength="8" stringRepresentation="IPV4_UDP">1</HostProtocolCode>
</hostProtocolCode>
<ipAddress>
<IPAddress>
- <addr>
+ <addr isList="true">
<value dataType="int" bitLength="8">-64</value>
<value dataType="int" bitLength="8">-88</value>
<value dataType="int" bitLength="8">42</value>
@@ -509,11 +509,11 @@
<HPAIDataEndpoint>
<structureLength dataType="uint" bitLength="8">8</structureLength>
<hostProtocolCode>
- <hostProtocolCode dataType="uint" bitLength="8">1</hostProtocolCode>
+ <HostProtocolCode dataType="uint" bitLength="8" stringRepresentation="IPV4_UDP">1</HostProtocolCode>
</hostProtocolCode>
<ipAddress>
<IPAddress>
- <addr>
+ <addr isList="true">
<value dataType="int" bitLength="8">-64</value>
<value dataType="int" bitLength="8">-88</value>
<value dataType="int" bitLength="8">42</value>
@@ -530,7 +530,7 @@
<connectionType dataType="uint" bitLength="8">4</connectionType>
<ConnectionRequestInformationTunnelConnection>
<knxLayer>
- <knxLayer dataType="uint" bitLength="8">2</knxLayer>
+ <KnxLayer dataType="uint" bitLength="8" stringRepresentation="TUNNEL_LINK_LAYER">2</KnxLayer>
</knxLayer>
<reserved dataType="uint" bitLength="8">0</reserved>
</ConnectionRequestInformationTunnelConnection>
@@ -554,16 +554,16 @@
<ConnectionResponse>
<communicationChannelId dataType="uint" bitLength="8">2</communicationChannelId>
<status>
- <status dataType="uint" bitLength="8">0</status>
+ <Status dataType="uint" bitLength="8" stringRepresentation="NO_ERROR">0</Status>
</status>
<HPAIDataEndpoint>
<structureLength dataType="uint" bitLength="8">8</structureLength>
<hostProtocolCode>
- <hostProtocolCode dataType="uint" bitLength="8">1</hostProtocolCode>
+ <HostProtocolCode dataType="uint" bitLength="8" stringRepresentation="IPV4_UDP">1</HostProtocolCode>
</hostProtocolCode>
<ipAddress>
<IPAddress>
- <addr>
+ <addr isList="true">
<value dataType="int" bitLength="8">-64</value>
<value dataType="int" bitLength="8">-88</value>
<value dataType="int" bitLength="8">42</value>
@@ -608,11 +608,11 @@
<HPAIControlEndpoint>
<structureLength dataType="uint" bitLength="8">8</structureLength>
<hostProtocolCode>
- <hostProtocolCode dataType="uint" bitLength="8">1</hostProtocolCode>
+ <HostProtocolCode dataType="uint" bitLength="8" stringRepresentation="IPV4_UDP">1</HostProtocolCode>
</hostProtocolCode>
<ipAddress>
<IPAddress>
- <addr>
+ <addr isList="true">
<value dataType="int" bitLength="8">-64</value>
<value dataType="int" bitLength="8">-88</value>
<value dataType="int" bitLength="8">42</value>
@@ -641,7 +641,7 @@
<ConnectionStateResponse>
<communicationChannelId dataType="uint" bitLength="8">2</communicationChannelId>
<status>
- <status dataType="uint" bitLength="8">0</status>
+ <Status dataType="uint" bitLength="8" stringRepresentation="NO_ERROR">0</Status>
</status>
</ConnectionStateResponse>
</KnxNetIpMessage>
@@ -701,7 +701,7 @@
<communicationChannelId dataType="uint" bitLength="8">103</communicationChannelId>
<sequenceCounter dataType="uint" bitLength="8">0</sequenceCounter>
<status>
- <status dataType="uint" bitLength="8">0</status>
+ <Status dataType="uint" bitLength="8" stringRepresentation="NO_ERROR">0</Status>
</status>
</DeviceConfigurationAckDataBlock>
</deviceConfigurationAckDataBlock>
@@ -727,11 +727,11 @@
<HPAIControlEndpoint>
<structureLength dataType="uint" bitLength="8">8</structureLength>
<hostProtocolCode>
- <hostProtocolCode dataType="uint" bitLength="8">1</hostProtocolCode>
+ <HostProtocolCode dataType="uint" bitLength="8" stringRepresentation="IPV4_UDP">1</HostProtocolCode>
</hostProtocolCode>
<ipAddress>
<IPAddress>
- <addr>
+ <addr isList="true">
<value dataType="int" bitLength="8">-64</value>
<value dataType="int" bitLength="8">-88</value>
<value dataType="int" bitLength="8">42</value>
@@ -760,7 +760,7 @@
<DisconnectResponse>
<communicationChannelId dataType="uint" bitLength="8">102</communicationChannelId>
<status>
- <status dataType="uint" bitLength="8">0</status>
+ <Status dataType="uint" bitLength="8" stringRepresentation="NO_ERROR">0</Status>
</status>
</DisconnectResponse>
</KnxNetIpMessage>
@@ -791,7 +791,7 @@
<messageCode dataType="uint" bitLength="8">41</messageCode>
<LDataInd>
<additionalInformationLength dataType="uint" bitLength="8">0</additionalInformationLength>
- <additionalInformation>
+ <additionalInformation isList="true">
</additionalInformation>
<dataFrame>
<LDataFrame>
@@ -815,7 +815,7 @@
<subGroup dataType="uint" bitLength="8">10</subGroup>
</KnxAddress>
</sourceAddress>
- <destinationAddress>
+ <destinationAddress isList="true">
<value dataType="int" bitLength="8">18</value>
<value dataType="int" bitLength="8">12</value>
</destinationAddress>
@@ -831,7 +831,7 @@
<apciType dataType="uint" bitLength="4">2</apciType>
<ApduDataGroupValueWrite>
<dataFirstByte dataType="int" bitLength="6">1</dataFirstByte>
- <data>
+ <data isList="true">
</data>
</ApduDataGroupValueWrite>
</ApduData>
@@ -878,7 +878,7 @@
<messageCode dataType="uint" bitLength="8">43</messageCode>
<LBusmonInd>
<additionalInformationLength dataType="uint" bitLength="8">7</additionalInformationLength>
- <additionalInformation>
+ <additionalInformation isList="true">
<CEMIAdditionalInformation>
<additionalInformationType dataType="uint" bitLength="8">3</additionalInformationType>
<CEMIAdditionalInformationBusmonitorInfo>
@@ -925,7 +925,7 @@
<subGroup dataType="uint" bitLength="8">30</subGroup>
</KnxAddress>
</sourceAddress>
- <destinationAddress>
+ <destinationAddress isList="true">
<value dataType="int" bitLength="8">12</value>
<value dataType="int" bitLength="8">-31</value>
</destinationAddress>
@@ -975,7 +975,7 @@
<communicationChannelId dataType="uint" bitLength="8">107</communicationChannelId>
<sequenceCounter dataType="uint" bitLength="8">0</sequenceCounter>
<status>
- <status dataType="uint" bitLength="8">0</status>
+ <Status dataType="uint" bitLength="8" stringRepresentation="NO_ERROR">0</Status>
</status>
</TunnelingResponseDataBlock>
</tunnelingResponseDataBlock>
@@ -999,11 +999,11 @@
<HPAIDiscoveryEndpoint>
<structureLength dataType="uint" bitLength="8">8</structureLength>
<hostProtocolCode>
- <hostProtocolCode dataType="uint" bitLength="8">1</hostProtocolCode>
+ <HostProtocolCode dataType="uint" bitLength="8" stringRepresentation="IPV4_UDP">1</HostProtocolCode>
</hostProtocolCode>
<ipAddress>
<IPAddress>
- <addr>
+ <addr isList="true">
<value dataType="int" bitLength="8">-64</value>
<value dataType="int" bitLength="8">-88</value>
<value dataType="int" bitLength="8">42</value>
@@ -1018,11 +1018,11 @@
<HPAIDataEndpoint>
<structureLength dataType="uint" bitLength="8">8</structureLength>
<hostProtocolCode>
- <hostProtocolCode dataType="uint" bitLength="8">1</hostProtocolCode>
+ <HostProtocolCode dataType="uint" bitLength="8" stringRepresentation="IPV4_UDP">1</HostProtocolCode>
</hostProtocolCode>
<ipAddress>
<IPAddress>
- <addr>
+ <addr isList="true">
<value dataType="int" bitLength="8">-64</value>
<value dataType="int" bitLength="8">-88</value>
<value dataType="int" bitLength="8">42</value>
diff --git a/plc4j/drivers/ab-eth/src/test/java/org/apache/plc4x/protocol/abeth/AbEthParserSerializerTest.java b/plc4j/drivers/ab-eth/src/test/java/org/apache/plc4x/protocol/abeth/AbEthParserSerializerTest.java
index bcc278d..bfb0109 100644
--- a/plc4j/drivers/ab-eth/src/test/java/org/apache/plc4x/protocol/abeth/AbEthParserSerializerTest.java
+++ b/plc4j/drivers/ab-eth/src/test/java/org/apache/plc4x/protocol/abeth/AbEthParserSerializerTest.java
@@ -24,7 +24,7 @@ import org.apache.plc4x.test.parserserializer.ParserSerializerTestsuiteRunner;
public class AbEthParserSerializerTest extends ParserSerializerTestsuiteRunner {
public AbEthParserSerializerTest() {
- super("/protocols/abeth/ParserSerializerTestsuite.xml", true, true);
+ super("/protocols/abeth/ParserSerializerTestsuite.xml", true);
}
}
diff --git a/plc4j/drivers/ads/src/test/java/org/apache/plc4x/protocol/ads/AdsDiscoverySerializerParserTest.java b/plc4j/drivers/ads/src/test/java/org/apache/plc4x/protocol/ads/AdsDiscoverySerializerParserTest.java
index bf82ca8..29b4670 100644
--- a/plc4j/drivers/ads/src/test/java/org/apache/plc4x/protocol/ads/AdsDiscoverySerializerParserTest.java
+++ b/plc4j/drivers/ads/src/test/java/org/apache/plc4x/protocol/ads/AdsDiscoverySerializerParserTest.java
@@ -24,7 +24,7 @@ import org.apache.plc4x.test.parserserializer.ParserSerializerTestsuiteRunner;
public class AdsDiscoverySerializerParserTest extends ParserSerializerTestsuiteRunner {
public AdsDiscoverySerializerParserTest() {
- super("/protocols/ads/AdsDiscoverySerializerTest.xml", true, true);
+ super("/protocols/ads/AdsDiscoverySerializerTest.xml", true);
}
}
diff --git a/plc4j/drivers/ads/src/test/java/org/apache/plc4x/protocol/ads/AdsSerializerParserTest.java b/plc4j/drivers/ads/src/test/java/org/apache/plc4x/protocol/ads/AdsSerializerParserTest.java
index f4a2c72..6885234 100644
--- a/plc4j/drivers/ads/src/test/java/org/apache/plc4x/protocol/ads/AdsSerializerParserTest.java
+++ b/plc4j/drivers/ads/src/test/java/org/apache/plc4x/protocol/ads/AdsSerializerParserTest.java
@@ -24,7 +24,7 @@ import org.apache.plc4x.test.parserserializer.ParserSerializerTestsuiteRunner;
public class AdsSerializerParserTest extends ParserSerializerTestsuiteRunner {
public AdsSerializerParserTest() {
- super("/protocols/ads/ParserSerializerTestsuite.xml", true, true);
+ super("/protocols/ads/ParserSerializerTestsuite.xml", true);
}
}
diff --git a/plc4j/drivers/canopen/src/test/java/org/apache/plc4x/java/canopen/CANOpenPayloadTest.java b/plc4j/drivers/canopen/src/test/java/org/apache/plc4x/java/canopen/CANOpenPayloadTest.java
index 2e3fb21..700a6d6 100644
--- a/plc4j/drivers/canopen/src/test/java/org/apache/plc4x/java/canopen/CANOpenPayloadTest.java
+++ b/plc4j/drivers/canopen/src/test/java/org/apache/plc4x/java/canopen/CANOpenPayloadTest.java
@@ -23,7 +23,7 @@ import org.apache.plc4x.test.parserserializer.ParserSerializerTestsuiteRunner;
public class CANOpenPayloadTest extends ParserSerializerTestsuiteRunner {
public CANOpenPayloadTest() {
- super("/protocols/canopen/CANOpenPayloadTestSuite.xml", true, true);
+ super("/protocols/canopen/CANOpenPayloadTestSuite.xml", true);
}
}
diff --git a/plc4j/drivers/canopen/src/test/java/org/apache/plc4x/java/canopen/CANOpenWiresharkTest.java b/plc4j/drivers/canopen/src/test/java/org/apache/plc4x/java/canopen/CANOpenWiresharkTest.java
index 69fe9a8..6eb9589 100644
--- a/plc4j/drivers/canopen/src/test/java/org/apache/plc4x/java/canopen/CANOpenWiresharkTest.java
+++ b/plc4j/drivers/canopen/src/test/java/org/apache/plc4x/java/canopen/CANOpenWiresharkTest.java
@@ -23,7 +23,7 @@ import org.apache.plc4x.test.parserserializer.ParserSerializerTestsuiteRunner;
public class CANOpenWiresharkTest extends ParserSerializerTestsuiteRunner {
public CANOpenWiresharkTest() {
- super("/protocols/canopen/CANOpenWiresharkTestSuite.xml", true, true);
+ super("/protocols/canopen/CANOpenWiresharkTestSuite.xml", true);
}
}
diff --git a/plc4j/drivers/eip/src/test/java/org/apache/plc4x/java/eip/readwrite/EIPParserSerializerTestsuite.java b/plc4j/drivers/eip/src/test/java/org/apache/plc4x/java/eip/readwrite/EIPParserSerializerTestsuite.java
index 15546ae..1b7607d 100644
--- a/plc4j/drivers/eip/src/test/java/org/apache/plc4x/java/eip/readwrite/EIPParserSerializerTestsuite.java
+++ b/plc4j/drivers/eip/src/test/java/org/apache/plc4x/java/eip/readwrite/EIPParserSerializerTestsuite.java
@@ -23,7 +23,7 @@ import org.apache.plc4x.test.parserserializer.ParserSerializerTestsuiteRunner;
public class EIPParserSerializerTestsuite extends ParserSerializerTestsuiteRunner {
public EIPParserSerializerTestsuite() {
- super("/protocols/eip/ParserSerializerTestsuite.xml", true, true);
+ super("/protocols/eip/ParserSerializerTestsuite.xml", true);
}
}
diff --git a/plc4j/drivers/firmata/src/test/java/org/apache/plc4x/java/firmata/readwrite/FirmataParserSerializerTest.java b/plc4j/drivers/firmata/src/test/java/org/apache/plc4x/java/firmata/readwrite/FirmataParserSerializerTest.java
index 5e9cca6..b22475c 100644
--- a/plc4j/drivers/firmata/src/test/java/org/apache/plc4x/java/firmata/readwrite/FirmataParserSerializerTest.java
+++ b/plc4j/drivers/firmata/src/test/java/org/apache/plc4x/java/firmata/readwrite/FirmataParserSerializerTest.java
@@ -23,7 +23,7 @@ import org.apache.plc4x.test.parserserializer.ParserSerializerTestsuiteRunner;
public class FirmataParserSerializerTest extends ParserSerializerTestsuiteRunner {
public FirmataParserSerializerTest() {
- super("/protocols/firmata/ParserSerializerTestsuite.xml", true, true);
+ super("/protocols/firmata/ParserSerializerTestsuite.xml", true);
}
}
diff --git a/plc4j/drivers/knxnetip/src/test/java/org/apache/plc4x/java/knxnetip/KnxNetIpParserSerializerTest.java b/plc4j/drivers/knxnetip/src/test/java/org/apache/plc4x/java/knxnetip/KnxNetIpParserSerializerTest.java
index b4649fc..32915bb 100644
--- a/plc4j/drivers/knxnetip/src/test/java/org/apache/plc4x/java/knxnetip/KnxNetIpParserSerializerTest.java
+++ b/plc4j/drivers/knxnetip/src/test/java/org/apache/plc4x/java/knxnetip/KnxNetIpParserSerializerTest.java
@@ -24,7 +24,7 @@ import org.apache.plc4x.test.parserserializer.ParserSerializerTestsuiteRunner;
public class KnxNetIpParserSerializerTest extends ParserSerializerTestsuiteRunner {
public KnxNetIpParserSerializerTest() {
- super("/protocols/knxnetip/ParserSerializerTestsuite.xml", true, true);
+ super("/protocols/knxnetip/ParserSerializerTestsuite.xml", true);
}
}
diff --git a/plc4j/drivers/modbus/src/test/java/org/apache/plc4x/java/modbus/ModbusParserSerializerTest.java b/plc4j/drivers/modbus/src/test/java/org/apache/plc4x/java/modbus/ModbusParserSerializerTest.java
index 3111969..673bb2d 100644
--- a/plc4j/drivers/modbus/src/test/java/org/apache/plc4x/java/modbus/ModbusParserSerializerTest.java
+++ b/plc4j/drivers/modbus/src/test/java/org/apache/plc4x/java/modbus/ModbusParserSerializerTest.java
@@ -23,7 +23,7 @@ import org.apache.plc4x.test.parserserializer.ParserSerializerTestsuiteRunner;
public class ModbusParserSerializerTest extends ParserSerializerTestsuiteRunner {
public ModbusParserSerializerTest() {
- super("/protocols/modbus/ParserSerializerTestsuite.xml", true,true);
+ super("/protocols/modbus/ParserSerializerTestsuite.xml", true);
}
}
diff --git a/plc4j/drivers/s7/src/test/java/org/apache/plc4x/java/s7/readwrite/S7ParserSerializerTest.java b/plc4j/drivers/s7/src/test/java/org/apache/plc4x/java/s7/readwrite/S7ParserSerializerTest.java
index 1408b1f..a7331b7 100644
--- a/plc4j/drivers/s7/src/test/java/org/apache/plc4x/java/s7/readwrite/S7ParserSerializerTest.java
+++ b/plc4j/drivers/s7/src/test/java/org/apache/plc4x/java/s7/readwrite/S7ParserSerializerTest.java
@@ -23,7 +23,7 @@ import org.apache.plc4x.test.parserserializer.ParserSerializerTestsuiteRunner;
public class S7ParserSerializerTest extends ParserSerializerTestsuiteRunner {
public S7ParserSerializerTest() {
- super("/protocols/s7/ParserSerializerTestsuite.xml", true, true);
+ super("/protocols/s7/ParserSerializerTestsuite.xml", true);
}
}
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/XmlTestsuiteRunner.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/XmlTestsuiteLoader.java
similarity index 96%
rename from plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/XmlTestsuiteRunner.java
rename to plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/XmlTestsuiteLoader.java
index 1553f1d..7e03499 100644
--- a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/XmlTestsuiteRunner.java
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/XmlTestsuiteLoader.java
@@ -31,13 +31,13 @@ import java.net.URL;
*
* It adds handling of resource loading and helps in navigating test framework to suite source files.
*/
-public abstract class XmlTestsuiteRunner {
+public abstract class XmlTestsuiteLoader {
protected final String testsuiteDocument;
protected final InputStream testsuiteDocumentXml;
protected final URI suiteUri;
- protected XmlTestsuiteRunner(String testsuiteDocument) {
+ protected XmlTestsuiteLoader(String testsuiteDocument) {
this.testsuiteDocument = testsuiteDocument;
this.testsuiteDocumentXml = getClass().getResourceAsStream(testsuiteDocument);
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/DriverTestsuiteRunner.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/DriverTestsuiteRunner.java
index 95122b4..fd02779 100644
--- a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/DriverTestsuiteRunner.java
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/DriverTestsuiteRunner.java
@@ -18,509 +18,43 @@ under the License.
*/
package org.apache.plc4x.test.driver;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.dataformat.xml.XmlMapper;
-import io.netty.buffer.ByteBuf;
-import io.netty.buffer.Unpooled;
-import io.netty.channel.Channel;
-import io.netty.channel.embedded.Plc4xEmbeddedChannel;
-import org.apache.commons.lang3.NotImplementedException;
-import org.apache.plc4x.java.PlcDriverManager;
-import org.apache.plc4x.java.api.PlcConnection;
-import org.apache.plc4x.java.api.exceptions.PlcConnectionException;
-import org.apache.plc4x.java.api.exceptions.PlcRuntimeException;
-import org.apache.plc4x.java.api.messages.PlcReadRequest;
-import org.apache.plc4x.java.api.messages.PlcResponse;
-import org.apache.plc4x.java.api.messages.PlcWriteRequest;
-import org.apache.plc4x.java.spi.connection.ChannelExposingConnection;
-import org.apache.plc4x.java.spi.connection.GeneratedDriverBase;
-import org.apache.plc4x.java.spi.generation.*;
-import org.apache.plc4x.java.spi.utils.XmlSerializable;
-import org.apache.plc4x.test.XmlTestsuiteRunner;
-import org.apache.plc4x.test.dom4j.LocationAwareDocumentFactory;
-import org.apache.plc4x.test.dom4j.LocationAwareElement;
-import org.apache.plc4x.test.dom4j.LocationAwareSAXReader;
+import org.apache.plc4x.test.XmlTestsuiteLoader;
import org.apache.plc4x.test.driver.exceptions.DriverTestsuiteException;
-import org.apache.plc4x.test.driver.model.DriverTestsuite;
-import org.apache.plc4x.test.driver.model.StepType;
-import org.apache.plc4x.test.driver.model.TestStep;
-import org.apache.plc4x.test.driver.model.Testcase;
-import org.apache.plc4x.test.mapper.TestSuiteMappingModule;
-import org.dom4j.Document;
-import org.dom4j.DocumentException;
-import org.dom4j.Element;
-import org.dom4j.QName;
-import org.dom4j.io.SAXReader;
+import org.apache.plc4x.test.driver.internal.DriverTestsuite;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.xmlunit.builder.DiffBuilder;
-import org.xmlunit.diff.Diff;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.transform.*;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamResult;
-import java.io.StringWriter;
-import java.util.*;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.TimeUnit;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
-public class DriverTestsuiteRunner extends XmlTestsuiteRunner {
+public class DriverTestsuiteRunner extends XmlTestsuiteLoader {
- private static final Logger LOGGER = LoggerFactory.getLogger(DriverTestsuiteRunner.class);
+ private final Set<String> ignoredTestCases = new HashSet<>();
- private CompletableFuture<? extends PlcResponse> responseFuture;
-
- private final Set<String>ignoredTestCases = new HashSet<>();
+ private final boolean autoMigrate;
public DriverTestsuiteRunner(String testsuiteDocument, String... ignoredTestCases) {
+ this(testsuiteDocument, false, ignoredTestCases);
+ }
+
+ public DriverTestsuiteRunner(String testsuiteDocument, boolean autoMigrate, String... ignoredTestCases) {
super(testsuiteDocument);
+ this.autoMigrate = autoMigrate;
Collections.addAll(this.ignoredTestCases, ignoredTestCases);
}
@TestFactory
- public Iterable<DynamicTest> getTestsuiteTests() throws DriverTestsuiteException {
- DriverTestsuite testSuite = parseTestsuite();
- List<DynamicTest> dynamicTests = new LinkedList<>();
- for (Testcase testcase : testSuite.getTestcases()) {
- String testcaseName = testcase.getName();
-
- String testcaseLabel = testSuite.getName() + ": " + testcaseName;
- DynamicTest test = DynamicTest.dynamicTest(testcaseLabel, getSourceUri(testcase), () -> {
- Assumptions.assumeFalse(() -> ignoredTestCases.contains(testcaseName),"Testcase "+ testcaseName+ " ignored");
- run(testSuite, testcase);
- }
- );
- dynamicTests.add(test);
- }
- return dynamicTests;
- }
-
- private DriverTestsuite parseTestsuite() throws DriverTestsuiteException {
- try {
- SAXReader reader = new LocationAwareSAXReader();
- reader.setDocumentFactory(new LocationAwareDocumentFactory());
- Document document = reader.read(testsuiteDocumentXml);
- Element testsuiteXml = document.getRootElement();
- boolean bigEndian = !"false".equals(testsuiteXml.attributeValue("bigEndian"));
- String testsuiteName = testsuiteXml.element(new QName("name")).getTextTrim();
- String driverName = testsuiteXml.element(new QName("driver-name")).getTextTrim();
- Element driverParametersElement = testsuiteXml.element(new QName("driver-parameters"));
- Map<String, String> driverParameters = null;
- if (driverParametersElement != null) {
- driverParameters = new HashMap<>();
- for (Element parameter : driverParametersElement.elements(new QName("parameter"))) {
- String parameterName = parameter.element(new QName("name")).getTextTrim();
- String parameterValue = parameter.element(new QName("value")).getTextTrim();
- driverParameters.put(parameterName, parameterValue);
- }
- }
-
- List<TestStep> setupSteps = new LinkedList<>();
- if(testsuiteXml.element(new QName("setup")) != null) {
- Element setupElement = testsuiteXml.element(new QName("setup"));
- for (Element element : setupElement.elements()) {
- setupSteps.add(parseTestStep(element));
- }
- }
-
- List<TestStep> teardownSteps = new LinkedList<>();
- if(testsuiteXml.element(new QName("teardown")) != null) {
- Element teardownElement = testsuiteXml.element(new QName("teardown"));
- for (Element element : teardownElement.elements()) {
- setupSteps.add(parseTestStep(element));
- }
- }
-
- List<Element> testcasesXml = testsuiteXml.elements(new QName("testcase"));
- List<Testcase> testcases = new ArrayList<>(testcasesXml.size());
- for(Element testcaseXml : testcasesXml) {
- Element nameElement = testcaseXml.element(new QName("name"));
- Element descriptionElement = testcaseXml.element(new QName("description"));
- Element stepsElement = testcaseXml.element(new QName("steps"));
-
- String name = nameElement.getTextTrim();
- String description = (descriptionElement != null) ? descriptionElement.getTextTrim() : null;
-
- List<TestStep> steps = new LinkedList<>();
- for (Element element : stepsElement.elements()) {
- steps.add(parseTestStep(element));
- }
- Testcase testcase = new Testcase(name, description, steps);
- if (testcaseXml instanceof LocationAwareElement) {
- testcase.setLocation(((LocationAwareElement) testcaseXml).getLocation());
- }
- testcases.add(testcase);
- }
- LOGGER.info(String.format("Found %d testcases.", testcases.size()));
-
- // Force the driver to not wait for the connection before returning the connection.
- System.setProperty(GeneratedDriverBase.PROPERTY_PLC4X_FORCE_AWAIT_SETUP_COMPLETE, "false");
-
- // Force the driver to not wait for the disconnection before returning closing the channel.
- System.setProperty(GeneratedDriverBase.PROPERTY_PLC4X_FORCE_AWAIT_DISCONNECT_COMPLETE, "false");
-
- TimeUnit.MILLISECONDS.sleep(200);
-
- return new DriverTestsuite(testsuiteName, driverName, driverParameters, setupSteps, teardownSteps, testcases, bigEndian);
- } catch (DocumentException e) {
- throw new DriverTestsuiteException("Error parsing testsuite xml", e);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- throw new DriverTestsuiteException("Interruption setting up testsuite xml", e);
- }
- }
-
- private PlcConnection getConnection(String driverName, Map<String, String> driverParameters)
- throws DriverTestsuiteException {
- try {
- StringBuilder sb = new StringBuilder();
- if(driverParameters != null) {
- for (Map.Entry<String, String> parameter : driverParameters.entrySet()) {
- sb.append("&").append(parameter.getKey()).append("=").append(parameter.getValue());
- }
- }
- if(sb.length() > 0) {
- sb.replace(0, 1, "?");
- }
- return new PlcDriverManager().getConnection(driverName + ":test://hurz" + sb.toString());
- } catch (PlcConnectionException e) {
- throw new DriverTestsuiteException("Error loading driver", e);
- }
- }
-
- private void run(DriverTestsuite testsuite, Testcase testcase) throws DriverTestsuiteException {
- LOGGER.info(String.format("Starting testcase: %s", testcase.getName()));
- final PlcConnection plcConnection = getConnection(testsuite.getDriverName(), testsuite.getDriverParameters());
- final Plc4xEmbeddedChannel embeddedChannel = getEmbeddedChannel(plcConnection);
- final boolean bigEndian = testsuite.isBigEndian();
- // Be sure this is reset, just in case a previous testcase failed.
- responseFuture = null;
- if (!testsuite.getSetupSteps().isEmpty()) {
- LOGGER.info("Running setup steps");
- for (TestStep setupStep : testsuite.getSetupSteps()) {
- executeStep(setupStep, plcConnection, embeddedChannel, bigEndian);
- }
- LOGGER.info("Finished setup steps");
- }
- LOGGER.info("Running test steps");
- for (TestStep step : testcase.getSteps()) {
- executeStep(step, plcConnection, embeddedChannel, bigEndian);
- }
- LOGGER.info("Finished test steps");
- if(!testsuite.getTeardownSteps().isEmpty()) {
- LOGGER.info("Running teardown steps");
- for (TestStep teardownStep : testsuite.getTeardownSteps()) {
- executeStep(teardownStep, plcConnection, embeddedChannel, bigEndian);
- }
- LOGGER.info("Finished teardown steps");
- }
- LOGGER.info(String.format("Finished testcase: %s", testcase.getName()));
- }
-
- private void executeStep(TestStep testStep, PlcConnection plcConnection, Plc4xEmbeddedChannel embeddedChannel, boolean bigEndian) throws DriverTestsuiteException {
- LOGGER.info(String.format(" - Running step: '%s' - %s", testStep.getName(), testStep.getType()));
- final Element payload = testStep.getPayload();
- try {
- switch (testStep.getType()) {
- case OUTGOING_PLC_BYTES: {
- // As we're in the asynchronous world, give the driver some time to respond.
- shortDelay();
- // Prepare a ByteBuf that contains the data which would have been sent to the PLC.
- final byte[] data = getOutboundBytes(embeddedChannel);
- // Validate the data actually matches the expected message.
- validateBytes(payload, data, bigEndian);
- break;
- }
- case OUTGOING_PLC_MESSAGE: {
- // As we're in the asynchronous world, give the driver some time to respond.
- shortDelay();
- // Prepare a ByteBuf that contains the data which would have been sent to the PLC.
- final byte[] data = getOutboundBytes(embeddedChannel);
- // Validate the data actually matches the expected message.
- validateMessage(payload, testStep.getParserArguments(), data, bigEndian);
- break;
- }
- case INCOMING_PLC_BYTES: {
- // TODO: Implement
- throw new NotImplementedException("incoming-plc-bytes not implemented yet");
- }
- case INCOMING_PLC_MESSAGE: {
- // Get a byte representation of the incoming message.
- final byte[] data = getBytesFromXml(payload, bigEndian);
- // Send the bytes to the channel.
- embeddedChannel.writeInbound(Unpooled.wrappedBuffer(data));
- break;
- }
- case API_REQUEST: {
- switch(payload.attributeValue("className")) {
- case "org.apache.plc4x.test.driver.model.api.TestReadRequest": {
- final PlcReadRequest.Builder builder = plcConnection.readRequestBuilder();
- if(payload.element("fields") != null) {
- for (Element fieldElement : payload.element("fields").elements("field")) {
- builder.addItem(fieldElement.elementText("name"), fieldElement.elementText("address"));
- }
- }
- final PlcReadRequest plc4xRequest = builder.build();
- // Currently we can only process one response at at time, throw an error if more
- // are submitted.
- if (responseFuture != null) {
- throw new DriverTestsuiteException("Previous response not handled.");
- }
- // Save the response for being used later on.
- responseFuture = plc4xRequest.execute();
- break;
- }
- case "org.apache.plc4x.test.driver.model.api.TestWriteRequest": {
- final PlcWriteRequest.Builder builder = plcConnection.writeRequestBuilder();
- if(payload.element("fields") != null) {
- for (Element fieldElement : payload.element("fields").elements("field")) {
- List<Element> valueElements = fieldElement.elements("value");
- List<String> valueStrings = new ArrayList<>(valueElements.size());
- for (Element valueElement : valueElements) {
- valueStrings.add(valueElement.getTextTrim());
- }
- builder.addItem(fieldElement.elementText("name"),
- fieldElement.elementText("address"), valueStrings.toArray(new Object[0]));
- }
- }
- final PlcWriteRequest plc4xRequest = builder.build();
- // Currently we can only process one response at at time, throw an error if more
- // are submitted.
- if (responseFuture != null) {
- throw new DriverTestsuiteException("Previous response not handled.");
- }
- // Save the response for being used later on.
- responseFuture = plc4xRequest.execute();
- break;
- }
- }
-
- break;
- }
- case API_RESPONSE: {
- if(responseFuture == null) {
- throw new DriverTestsuiteException("No response expected.");
- }
- PlcResponse plcResponse;
- try {
- plcResponse = responseFuture.get(5000, TimeUnit.MILLISECONDS);
- } catch(Exception e) {
- throw new DriverTestsuiteException("Got no response within 5000ms.");
- }
-
- // Reset the future.
- responseFuture = null;
- final String serializedResponse = serializeToXmlString((XmlSerializable) plcResponse);
- validateApiMessage(payload, serializedResponse);
-
- break;
+ public Iterable<DynamicTest> createTestSuite() throws DriverTestsuiteException {
+ return DriverTestsuite.parseTestsuite(suiteUri, testsuiteDocumentXml, autoMigrate).getTestcases().stream()
+ .map(testcase -> DynamicTest.dynamicTest(testcase.getTestCaseLabel(), getSourceUri(testcase), () -> {
+ Assumptions.assumeFalse(() -> ignoredTestCases.contains(testcase.getName()), "Testcase " + testcase.getName() + " ignored");
+ testcase.run();
}
- case DELAY: {
- delay(1000);
- break;
- }
- case TERMINATE: {
- embeddedChannel.close();
- }
- }
- } catch (Exception e) {
- LOGGER.error(" Failed: Error running step: " + testStep.getName() + ": " + e.getMessage());
- throw new DriverTestsuiteException("Error running the step " + testStep.getName(), e);
- }
- LOGGER.info(" Done");
- }
-
- private TestStep parseTestStep(Element curElement) throws DriverTestsuiteException {
- final String elementName = curElement.getName();
- final StepType stepType = StepType.valueOf(elementName.toUpperCase().replace("-", "_"));
- final String stepName = curElement.attributeValue(new QName("name"));
- Element parserArgumentsNode = null;
- Element definitionNode = null;
- for (Element element : curElement.elements()) {
- if(element.getName().equals("parser-arguments")) {
- parserArgumentsNode = element;
- } else if (definitionNode == null) {
- definitionNode = element;
- } else {
- throw new DriverTestsuiteException("Error processing the xml. Only one content node allowed.");
- }
- }
- final List<String> parserArguments = new ArrayList<>();
- if(parserArgumentsNode != null) {
- for (Element parserArgumentNode : parserArgumentsNode.elements()) {
- parserArguments.add(parserArgumentNode.getTextTrim());
- }
- }
- TestStep testStep = new TestStep(stepType, stepName, parserArguments, definitionNode);
- if (curElement instanceof LocationAwareElement) {
- testStep.setLocation(((LocationAwareElement) curElement).getLocation());
- }
- return testStep;
- }
-
- private Plc4xEmbeddedChannel getEmbeddedChannel(PlcConnection plcConnection) {
- if(plcConnection instanceof ChannelExposingConnection) {
- ChannelExposingConnection connection = (ChannelExposingConnection) plcConnection;
- Channel channel = connection.getChannel();
- if(channel instanceof Plc4xEmbeddedChannel) {
- return (Plc4xEmbeddedChannel) channel;
- }
- throw new PlcRuntimeException("Expecting EmbeddedChannel");
- }
- throw new PlcRuntimeException("Expecting ChannelExposingConnection");
- }
-
- @SuppressWarnings("unchecked")
- private Class<? extends Message> getMessageType(String messageClassName) throws DriverTestsuiteException {
- try {
- final Class<?> messageClass = Class.forName(messageClassName);
- if(Message.class.isAssignableFrom(messageClass)) {
- return (Class<? extends Message>) messageClass;
- }
- throw new DriverTestsuiteException("IO class must implement Message interface");
- } catch (ClassNotFoundException e) {
- throw new DriverTestsuiteException("Error loading message class", e);
- }
- }
-
- @SuppressWarnings("unchecked")
- private Class<? extends MessageIO<?,?>> getMessageIOType(String messageClassName) throws DriverTestsuiteException {
- String ioClassName = messageClassName.substring(0, messageClassName.lastIndexOf('.')) + ".io." +
- messageClassName.substring(messageClassName.lastIndexOf('.') + 1) + "IO";
- try {
- final Class<?> ioClass = Class.forName(ioClassName);
- if(MessageIO.class.isAssignableFrom(ioClass)) {
- return (Class<? extends MessageIO<?,?>>) ioClass;
- }
- throw new DriverTestsuiteException("IO class muss implement MessageIO interface");
- } catch (ClassNotFoundException e) {
- throw new DriverTestsuiteException("Error loading io class", e);
- }
- }
-
- private byte[] getOutboundBytes(Plc4xEmbeddedChannel embeddedChannel) throws DriverTestsuiteException {
- ByteBuf byteBuf = null;
- for(int i = 0; i < 500; i++) {
- byteBuf = embeddedChannel.readOutbound();
- if(byteBuf != null) {
- break;
- }
- delay(10);
- }
- if(byteBuf == null) {
- throw new DriverTestsuiteException("No outbound message available within 5000ms");
- }
- final byte[] data = new byte[byteBuf.readableBytes()];
- byteBuf.readBytes(data);
- return data;
+ ))
+ .collect(Collectors.toList());
}
- private byte[] getBytesFromXml(Element referenceXml, boolean bigEndian) throws DriverTestsuiteException {
- final String className = referenceXml.attributeValue(new QName("className"));
- final WriteBufferByteBased writeBuffer = new WriteBufferByteBased(1024, !bigEndian);
- try {
- final MessageIO messageIO = getMessageIOType(className).newInstance();
- final String referenceXmlString = referenceXml.asXML();
- final ObjectMapper mapper = new XmlMapper().enableDefaultTyping().registerModule(new TestSuiteMappingModule());
- final Message message = mapper.readValue(referenceXmlString, getMessageType(className));
- try {
- messageIO.serialize(writeBuffer, message);
- final byte[] data = new byte[message.getLengthInBytes()];
- System.arraycopy(writeBuffer.getData(), 0, data, 0, writeBuffer.getPos());
- return data;
- } catch (ParseException e) {
- throw new DriverTestsuiteException("Error serializing message", e);
- }
- } catch (IllegalAccessException | JsonProcessingException | InstantiationException e) {
- throw new DriverTestsuiteException("Error parsing message", e);
- }
- }
-
- private void validateBytes(Element referenceXml, byte[] data, boolean bigEndian) throws DriverTestsuiteException {
- // TODO: Implement this ...
- }
-
- private void validateMessage(Element referenceXml, List<String> parserArguments, byte[] data, boolean bigEndian) throws DriverTestsuiteException {
- final ObjectMapper mapper = new XmlMapper().enableDefaultTyping().registerModule(new TestSuiteMappingModule());
- final ReadBufferByteBased readBuffer = new ReadBufferByteBased(data, !bigEndian);
- try {
- final String className = referenceXml.attributeValue(new QName("className"));
- final MessageIO<?,?> messageIO = getMessageIOType(className).newInstance();
- final Object parsedOutput = messageIO.parse(readBuffer, parserArguments.toArray(new String[0]));
- final String xmlString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(parsedOutput);
- final String referenceXmlString = referenceXml.asXML();
- final Diff diff = DiffBuilder.compare(referenceXmlString)
- .withTest(xmlString).checkForSimilar().ignoreComments().ignoreWhitespace()
- .build();
- if (diff.hasDifferences()) {
- LOGGER.warn(xmlString);
- LOGGER.warn(diff.toString());
- throw new DriverTestsuiteException("Differences were found after parsing.\n" + diff.toString());
- }
- } catch (ParseException | IllegalAccessException | JsonProcessingException | InstantiationException e) {
- throw new DriverTestsuiteException("Error parsing message", e);
- }
- }
-
- private void validateApiMessage(Element referenceXml, String apiMessage) throws DriverTestsuiteException {
- final String referenceXmlString = referenceXml.asXML();
- final Diff diff = DiffBuilder.compare(referenceXmlString)
- .withTest(apiMessage).checkForSimilar().ignoreComments().ignoreWhitespace()
- .build();
- if (diff.hasDifferences()) {
- LOGGER.warn(apiMessage);
- LOGGER.warn(diff.toString());
- throw new DriverTestsuiteException("Differences were found after parsing.\n" + diff.toString());
- }
- }
-
- private void shortDelay() throws DriverTestsuiteException {
- delay(23);
- }
-
- private void delay(int milliseconds) throws DriverTestsuiteException {
- try {
- TimeUnit.MILLISECONDS.sleep(milliseconds);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- throw new DriverTestsuiteException("Interrupted during delay.");
- }
- }
-
- private String serializeToXmlString(XmlSerializable value) {
- try {
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- DocumentBuilder builder = dbf.newDocumentBuilder();
- org.w3c.dom.Document doc = builder.newDocument();
- org.w3c.dom.Element root = doc.createElement("root");
- doc.appendChild(root);
- value.xmlSerialize(root);
- DOMSource domSource = new DOMSource(doc.getDocumentElement().getFirstChild());
- StringWriter writer = new StringWriter();
- StreamResult result = new StreamResult(writer);
- TransformerFactory tf = TransformerFactory.newInstance();
- Transformer transformer = tf.newTransformer();
- transformer.setOutputProperty(OutputKeys.INDENT, "yes");
- transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
- transformer.setOutputProperty("omit-xml-declaration", "yes");
- transformer.transform(domSource, result);
- return writer.toString();
- } catch (ParserConfigurationException e) {
- throw new RuntimeException(e);
- } catch (TransformerConfigurationException e) {
- throw new RuntimeException(e);
- } catch (TransformerException e) {
- throw new RuntimeException(e);
- }
- }
-
-
-
}
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/Lalala.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/Lalala.java
deleted file mode 100644
index d79a1d3..0000000
--- a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/Lalala.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one
-or more contributor license agreements. See the NOTICE file
-distributed with this work for additional information
-regarding copyright ownership. The ASF licenses this file
-to you under the Apache License, Version 2.0 (the
-"License"); you may not use this file except in compliance
-with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing,
-software distributed under the License is distributed on an
-"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-KIND, either express or implied. See the License for the
-specific language governing permissions and limitations
-under the License.
-*/
-package org.apache.plc4x.test.driver;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.dataformat.xml.XmlMapper;
-import org.apache.plc4x.test.driver.model.api.TestField;
-import org.apache.plc4x.test.driver.model.api.TestReadRequest;
-import org.apache.plc4x.test.driver.model.api.TestRequest;
-
-public class Lalala {
- public static void main(String[] args) throws Exception {
- ObjectMapper mapper = new XmlMapper().enableDefaultTyping();
-
- TestField[] testFields = new TestField[1];
- testFields[0] = new TestField("hurz", "%Q0.0:BOOL");
- TestRequest request = new TestReadRequest(testFields);
-
- String xmlString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(request);
-
- System.out.println(xmlString);
-
- TestRequest newRequest = mapper.readValue(xmlString, TestRequest.class);
-
- System.out.println(newRequest);
- }
-
-}
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/exceptions/DriverTestsuiteException.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/exceptions/DriverTestsuiteException.java
index 9a71161..5eb3683 100644
--- a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/exceptions/DriverTestsuiteException.java
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/exceptions/DriverTestsuiteException.java
@@ -19,7 +19,11 @@
package org.apache.plc4x.test.driver.exceptions;
-public class DriverTestsuiteException extends Exception {
+public class DriverTestsuiteException extends RuntimeException {
+
+ public DriverTestsuiteException(Throwable cause) {
+ super(cause);
+ }
public DriverTestsuiteException(String message) {
super(message);
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/ConnectionManager.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/ConnectionManager.java
new file mode 100644
index 0000000..7e4d7d8
--- /dev/null
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/ConnectionManager.java
@@ -0,0 +1,68 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+package org.apache.plc4x.test.driver.internal;
+
+import io.netty.channel.Channel;
+import io.netty.channel.embedded.Plc4xEmbeddedChannel;
+import org.apache.plc4x.java.PlcDriverManager;
+import org.apache.plc4x.java.api.PlcConnection;
+import org.apache.plc4x.java.api.exceptions.PlcConnectionException;
+import org.apache.plc4x.java.api.exceptions.PlcRuntimeException;
+import org.apache.plc4x.java.spi.connection.ChannelExposingConnection;
+import org.apache.plc4x.test.driver.exceptions.DriverTestsuiteException;
+
+import java.util.Map;
+
+public class ConnectionManager {
+
+ PlcDriverManager plcDriverManager;
+
+ public ConnectionManager() {
+ this.plcDriverManager = new PlcDriverManager();
+ }
+
+ public PlcConnection getConnection(String driverName, Map<String, String> driverParameters) throws DriverTestsuiteException {
+ try {
+ StringBuilder sb = new StringBuilder();
+ if (driverParameters != null) {
+ for (Map.Entry<String, String> parameter : driverParameters.entrySet()) {
+ sb.append("&").append(parameter.getKey()).append("=").append(parameter.getValue());
+ }
+ }
+ if (sb.length() > 0) {
+ sb.replace(0, 1, "?");
+ }
+ return plcDriverManager.getConnection(driverName + ":test://hurz" + sb);
+ } catch (PlcConnectionException e) {
+ throw new DriverTestsuiteException("Error loading driver", e);
+ }
+ }
+
+ public Plc4xEmbeddedChannel getEmbeddedChannel(PlcConnection plcConnection) {
+ if (!(plcConnection instanceof ChannelExposingConnection)) {
+ throw new PlcRuntimeException("Expecting ChannelExposingConnection");
+ }
+ ChannelExposingConnection connection = (ChannelExposingConnection) plcConnection;
+ Channel channel = connection.getChannel();
+ if (!(channel instanceof Plc4xEmbeddedChannel)) {
+ throw new PlcRuntimeException("Expecting EmbeddedChannel");
+ }
+ return (Plc4xEmbeddedChannel) channel;
+ }
+}
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/DriverTestsuite.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/DriverTestsuite.java
new file mode 100644
index 0000000..bb290e2
--- /dev/null
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/DriverTestsuite.java
@@ -0,0 +1,236 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+package org.apache.plc4x.test.driver.internal;
+
+import org.apache.plc4x.java.spi.connection.GeneratedDriverBase;
+import org.apache.plc4x.test.dom4j.LocationAwareDocumentFactory;
+import org.apache.plc4x.test.dom4j.LocationAwareElement;
+import org.apache.plc4x.test.dom4j.LocationAwareSAXReader;
+import org.apache.plc4x.test.driver.exceptions.DriverTestsuiteException;
+import org.apache.plc4x.test.driver.internal.utils.Delay;
+import org.apache.plc4x.test.driver.internal.utils.Synchronizer;
+import org.dom4j.Document;
+import org.dom4j.DocumentException;
+import org.dom4j.Element;
+import org.dom4j.QName;
+import org.dom4j.io.SAXReader;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.InputStream;
+import java.net.URI;
+import java.util.*;
+import java.util.stream.Collectors;
+
+public class DriverTestsuite {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(DriverTestsuite.class);
+
+ private final DriverTestsuiteConfiguration driverTestsuiteConfiguration;
+
+ private List<TestStep> setupSteps;
+ private List<TestStep> teardownSteps;
+ private List<Testcase> testcases;
+
+ private DriverTestsuite(DriverTestsuiteConfiguration driverTestsuiteConfiguration) {
+ this.driverTestsuiteConfiguration = driverTestsuiteConfiguration;
+ }
+
+ private void setSetupSteps(List<TestStep> setupSteps) {
+ this.setupSteps = setupSteps;
+ }
+
+ private void setTeardownSteps(List<TestStep> teardownSteps) {
+ this.teardownSteps = teardownSteps;
+ }
+
+ private void setTestcases(List<Testcase> testcases) {
+ this.testcases = testcases;
+ }
+
+ public static DriverTestsuite parseTestsuite(URI suiteUri, InputStream testsuiteDocumentXml, boolean autoMigrate ) throws DriverTestsuiteException {
+ try {
+ SAXReader reader = new LocationAwareSAXReader();
+ reader.setDocumentFactory(new LocationAwareDocumentFactory());
+ Document document = reader.read(testsuiteDocumentXml);
+ Element testsuiteXml = document.getRootElement();
+
+ // Force the driver to not wait for the connection before returning the connection.
+ System.setProperty(GeneratedDriverBase.PROPERTY_PLC4X_FORCE_AWAIT_SETUP_COMPLETE, "false");
+
+ // Force the driver to not wait for the disconnection before returning closing the channel.
+ System.setProperty(GeneratedDriverBase.PROPERTY_PLC4X_FORCE_AWAIT_DISCONNECT_COMPLETE, "false");
+
+ // TODO: replace with signal
+ Delay.delay(200);
+
+ // Shared instance for synchronizing
+ Synchronizer synchronizer = new Synchronizer();
+ DriverTestsuiteBuilder driverTestsuiteBuilder = new DriverTestsuiteBuilder(suiteUri, testsuiteXml, synchronizer, autoMigrate);
+ return driverTestsuiteBuilder.build();
+ } catch (DocumentException e) {
+ throw new DriverTestsuiteException("Error parsing testsuite xml", e);
+ }
+ }
+
+ public DriverTestsuiteConfiguration getDriverTestsuiteConfiguration() {
+ return driverTestsuiteConfiguration;
+ }
+
+ public List<Testcase> getTestcases() {
+ return testcases;
+ }
+
+ public String getName() {
+ return driverTestsuiteConfiguration.getTestSuiteName();
+ }
+
+ public List<TestStep> getSetupSteps() {
+ return setupSteps;
+ }
+
+ public List<TestStep> getTeardownSteps() {
+ return teardownSteps;
+ }
+
+
+ private static class DriverTestsuiteBuilder {
+
+ private final URI suiteUri;
+
+ private final Synchronizer synchronizer;
+
+ private final Element testsuiteXml;
+
+ private final String testsuiteName;
+
+ private final String protocolName;
+
+ private final String outputFlavor;
+
+ private final String driverName;
+
+ private final Element driverParametersElement;
+
+ private final boolean bigEndian;
+
+ private final boolean autoMigrate;
+
+ public DriverTestsuiteBuilder(URI suiteUri, Element testsuiteXml, Synchronizer synchronizer, boolean autoMigrate) {
+ this.suiteUri = suiteUri;
+ this.synchronizer = synchronizer;
+ this.testsuiteXml = testsuiteXml;
+ this.testsuiteName = extractText(testsuiteXml, "name");
+ this.protocolName = extractText(testsuiteXml, "protocolName");
+ this.outputFlavor = extractText(testsuiteXml, "outputFlavor");
+ this.driverName = extractText(testsuiteXml, "driver-name");
+ this.driverParametersElement = testsuiteXml.element(new QName("driver-parameters"));
+ this.bigEndian = !"false".equals(testsuiteXml.attributeValue("bigEndian"));
+ this.autoMigrate = autoMigrate;
+ }
+
+ private DriverTestsuite build() {
+ DriverTestsuiteConfiguration driverTestsuiteConfiguration = new DriverTestsuiteConfiguration(
+ suiteUri,
+ testsuiteName,
+ protocolName,
+ outputFlavor,
+ driverName,
+ parseDriverParameters(driverParametersElement),
+ autoMigrate,
+ bigEndian
+ );
+ DriverTestsuite driverTestsuite = new DriverTestsuite(driverTestsuiteConfiguration);
+ driverTestsuite.setTestcases(parseTestCases(driverTestsuite));
+ driverTestsuite.setSetupSteps(parseSetupSteps(driverTestsuiteConfiguration));
+ driverTestsuite.setTeardownSteps(parseTearDownSteps(driverTestsuiteConfiguration));
+ return driverTestsuite;
+ }
+
+ private String extractText(Element testsuiteXml, String name) {
+ Element element = testsuiteXml.element(new QName(name));
+ if (element == null) {
+ throw new RuntimeException("Required element " + name + " not present");
+ }
+ return element.getTextTrim();
+ }
+
+ private List<Testcase> parseTestCases(DriverTestsuite driverTestsuite) {
+ List<Testcase> testcases = testsuiteXml.elements(new QName("testcase")).stream()
+ .map(testcaseXml -> {
+ Testcase testcase = new Testcase(
+ driverTestsuite, extractText(testcaseXml, "name"),
+ parseDescription(testcaseXml),
+ parseSteps(testcaseXml, driverTestsuite.driverTestsuiteConfiguration),
+ synchronizer
+ );
+ if (testcaseXml instanceof LocationAwareElement) {
+ testcase.setLocation(((LocationAwareElement) testcaseXml).getLocation());
+ }
+ return testcase;
+ })
+ .collect(Collectors.toList());
+ LOGGER.info("Found {} testcases.", testcases.size());
+ return testcases;
+ }
+
+ private List<TestStep> parseSteps(Element testcaseXml, DriverTestsuiteConfiguration driverTestsuiteConfiguration) {
+ return testcaseXml.element(new QName("steps")).elements().stream()
+ .map(subElement -> TestStep.parseTestStep(subElement, synchronizer, driverTestsuiteConfiguration))
+ .collect(Collectors.toList());
+ }
+
+ private String parseDescription(Element testcaseXml) {
+ Element descriptionElement = testcaseXml.element(new QName("description"));
+ return (descriptionElement != null) ? descriptionElement.getTextTrim() : null;
+ }
+
+ private List<TestStep> parseTearDownSteps(DriverTestsuiteConfiguration driverTestsuiteConfiguration) throws DriverTestsuiteException {
+ return parseSteps("teardown", driverTestsuiteConfiguration);
+ }
+
+ private List<TestStep> parseSetupSteps(DriverTestsuiteConfiguration driverTestsuiteConfiguration) throws DriverTestsuiteException {
+ return parseSteps("setup", driverTestsuiteConfiguration);
+ }
+
+ private List<TestStep> parseSteps(String type, DriverTestsuiteConfiguration driverTestsuiteConfiguration) throws DriverTestsuiteException {
+ Element element = testsuiteXml.element(new QName(type));
+ if (element == null) {
+ return Collections.emptyList();
+ }
+ return element.elements().stream()
+ .map(subElement -> TestStep.parseTestStep(subElement, synchronizer, driverTestsuiteConfiguration))
+ .collect(Collectors.toCollection(LinkedList::new));
+ }
+
+ private Map<String, String> parseDriverParameters(Element driverParametersElement) {
+ if (driverParametersElement == null) {
+ return Collections.emptyMap();
+ }
+ Map<String, String> driverParameters = new HashMap<>();
+ for (Element parameter : driverParametersElement.elements(new QName("parameter"))) {
+ String parameterName = extractText(parameter, "name");
+ String parameterValue = extractText(parameter, "value");
+ driverParameters.put(parameterName, parameterValue);
+ }
+ return driverParameters;
+ }
+ }
+
+}
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/DriverTestsuite.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/DriverTestsuiteConfiguration.java
similarity index 52%
rename from plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/DriverTestsuite.java
rename to plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/DriverTestsuiteConfiguration.java
index 1a83bf1..591cc05 100644
--- a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/DriverTestsuite.java
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/DriverTestsuiteConfiguration.java
@@ -16,59 +16,62 @@ KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
-package org.apache.plc4x.test.driver.model;
+package org.apache.plc4x.test.driver.internal;
-import java.util.List;
+import java.net.URI;
import java.util.Map;
-public class DriverTestsuite {
-
- private final String name;
+public class DriverTestsuiteConfiguration {
+ private final URI suiteUri;
+ private final String testSuiteName;
+ private final String protocolName;
+ private final String outputFlavor;
private final String driverName;
private final Map<String, String> driverParameters;
- private final List<TestStep> setupSteps;
- private final List<TestStep> teardownSteps;
- private final List<Testcase> testcases;
+ private final boolean autoMigrate;
private final boolean bigEndian;
- public DriverTestsuite(String name, String driverName, Map<String, String> driverParameters,
- List<TestStep> setupSteps, List<TestStep> teardownSteps,
- List<Testcase> testcases, boolean bigEndian) {
- this.name = name;
+ public DriverTestsuiteConfiguration(URI suiteUri, String testSuiteName, String protocolName, String outputFlavor, String driverName, Map<String, String> driverParameters, boolean autoMigrate, boolean bigEndian) {
+ this.suiteUri = suiteUri;
+ this.testSuiteName = testSuiteName;
+ this.protocolName = protocolName;
+ this.outputFlavor = outputFlavor;
this.driverName = driverName;
+ // TODO: convert to immutable map
this.driverParameters = driverParameters;
- this.setupSteps = setupSteps;
- this.teardownSteps = teardownSteps;
- this.testcases = testcases;
+ this.autoMigrate = autoMigrate;
this.bigEndian = bigEndian;
}
- public String getName() {
- return name;
+ public URI getSuiteUri() {
+ return suiteUri;
}
- public String getDriverName() {
- return driverName;
+ public String getTestSuiteName() {
+ return testSuiteName;
}
- public Map<String, String> getDriverParameters() {
- return driverParameters;
+ public String getProtocolName() {
+ return protocolName;
+ }
+
+ public String getOutputFlavor() {
+ return outputFlavor;
}
- public List<TestStep> getSetupSteps() {
- return setupSteps;
+ public String getDriverName() {
+ return driverName;
}
- public List<TestStep> getTeardownSteps() {
- return teardownSteps;
+ public Map<String, String> getDriverParameters() {
+ return driverParameters;
}
- public List<Testcase> getTestcases() {
- return testcases;
+ public boolean isAutoMigrate() {
+ return autoMigrate;
}
public boolean isBigEndian() {
return bigEndian;
}
-
}
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/StepType.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/StepType.java
similarity index 64%
rename from plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/StepType.java
rename to plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/StepType.java
index 374a2f8..fac2c23 100644
--- a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/StepType.java
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/StepType.java
@@ -16,20 +16,18 @@ KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
-package org.apache.plc4x.test.driver.model;
+package org.apache.plc4x.test.driver.internal;
+/**
+ * ________________________PLC ---------- PLC4X --------- Application
+ * SEND_PLC_MESSAGE: | <-------- | |
+ * SEND_PLC_BYTES: | <-------- | |
+ * RECEIVE_PLC_MESSAGE: | --------> | |
+ * RECEIVE_PLC_BYTES: | --------> | |
+ * API_REQUEST: | | <-------- |
+ * API_RESPONSE: | | --------> |
+ */
public enum StepType {
-
- /*
- PLC --------- PLC4X --------- Application
- SEND_PLC_MESSAGE: <--------
- SEND_PLC_BYTES: <--------
- RECEIVE_PLC_MESSAGE: -------->
- RECEIVE_PLC_BYTES: -------->
- API_REQUEST: <--------
- API_RESPONSE: -------->
- */
-
OUTGOING_PLC_MESSAGE,
OUTGOING_PLC_BYTES,
INCOMING_PLC_MESSAGE,
@@ -38,5 +36,4 @@ public enum StepType {
API_RESPONSE,
DELAY,
TERMINATE
-
}
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/TestStep.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/TestStep.java
new file mode 100644
index 0000000..4f19eaa
--- /dev/null
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/TestStep.java
@@ -0,0 +1,138 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+package org.apache.plc4x.test.driver.internal;
+
+import io.netty.channel.embedded.Plc4xEmbeddedChannel;
+import org.apache.plc4x.java.api.PlcConnection;
+import org.apache.plc4x.test.dom4j.LocationAwareElement;
+import org.apache.plc4x.test.driver.exceptions.DriverTestsuiteException;
+import org.apache.plc4x.test.driver.internal.handlers.*;
+import org.apache.plc4x.test.driver.internal.utils.Delay;
+import org.apache.plc4x.test.driver.internal.utils.Synchronizer;
+import org.apache.plc4x.test.model.Location;
+import org.apache.plc4x.test.model.LocationAware;
+import org.dom4j.Element;
+import org.dom4j.QName;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+
+public class TestStep implements LocationAware {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(TestStep.class);
+
+ private final StepType type;
+ private final String name;
+ private final Location location;
+
+ private final ApiRequestHandler apiRequestHandler;
+ private final ApiResponseHandler apiResponseHandler;
+ private final IncomingPlcBytesHandler incomingPlcBytesHandler;
+ private final IncomingPlcMessageHandler incomingPlcMessageHandler;
+ private final OutgoingPlcBytesHandler outgoingPlcBytesHandler;
+ private final OutgoingPlcMessageHandler outgoingPlcMessageHandler;
+
+ private TestStep(StepType type, String name, Location location, List<String> parserArguments, Element payload, Synchronizer synchronizer, DriverTestsuiteConfiguration driverTestsuiteConfiguration) {
+ this.type = type;
+ this.name = name;
+ this.location = location;
+ apiRequestHandler = new ApiRequestHandler(payload, synchronizer);
+ apiResponseHandler = new ApiResponseHandler(payload, synchronizer);
+ incomingPlcBytesHandler = new IncomingPlcBytesHandler();
+ incomingPlcMessageHandler = new IncomingPlcMessageHandler(driverTestsuiteConfiguration, payload, parserArguments);
+ outgoingPlcBytesHandler = new OutgoingPlcBytesHandler(payload);
+ outgoingPlcMessageHandler = new OutgoingPlcMessageHandler(driverTestsuiteConfiguration, payload, parserArguments);
+ }
+
+ public static TestStep parseTestStep(Element curElement, Synchronizer synchronizer, DriverTestsuiteConfiguration driverTestsuiteConfiguration) throws DriverTestsuiteException {
+ final String elementName = curElement.getName();
+ final StepType stepType = StepType.valueOf(elementName.toUpperCase().replace("-", "_"));
+ final String stepName = curElement.attributeValue(new QName("name"));
+ Element parserArgumentsNode = null;
+ Element definitionNode = null;
+ for (Element element : curElement.elements()) {
+ if (element.getName().equals("parser-arguments")) {
+ parserArgumentsNode = element;
+ } else if (definitionNode == null) {
+ definitionNode = element;
+ } else {
+ throw new DriverTestsuiteException("Error processing the xml. Only one content node allowed.");
+ }
+ }
+ final List<String> parserArguments = new ArrayList<>();
+ if (parserArgumentsNode != null) {
+ for (Element parserArgumentNode : parserArgumentsNode.elements()) {
+ parserArguments.add(parserArgumentNode.getTextTrim());
+ }
+ }
+ Location location = null;
+ if (curElement instanceof LocationAwareElement) {
+ location = ((LocationAwareElement) curElement).getLocation();
+ }
+ return new TestStep(stepType, stepName, location, parserArguments, definitionNode, synchronizer, driverTestsuiteConfiguration);
+ }
+
+ @Override
+ public Optional<Location> getLocation() {
+ return Optional.ofNullable(location);
+ }
+
+ public void execute(PlcConnection plcConnection, Plc4xEmbeddedChannel embeddedChannel, boolean bigEndian) throws DriverTestsuiteException {
+ assert type != null;
+ LOGGER.info(String.format(" - Running step: '%s' - %s", name, type));
+ try {
+ switch (type) {
+ case OUTGOING_PLC_BYTES:
+ outgoingPlcBytesHandler.executeOutgoingPlcBytes(embeddedChannel, bigEndian);
+ break;
+ case OUTGOING_PLC_MESSAGE:
+ outgoingPlcMessageHandler.executeOutgoingPlcMessage(embeddedChannel, bigEndian);
+ break;
+ case INCOMING_PLC_BYTES:
+ incomingPlcBytesHandler.executeIncomingPlcBytes();
+ break;
+ case INCOMING_PLC_MESSAGE:
+ incomingPlcMessageHandler.executeIncomingPlcMessage(embeddedChannel, bigEndian);
+ break;
+ case API_REQUEST:
+ apiRequestHandler.executeApiRequest(plcConnection);
+ break;
+ case API_RESPONSE:
+ apiResponseHandler.executeApiResponse();
+ break;
+ case DELAY:
+ Delay.delay(1000);
+ break;
+ case TERMINATE:
+ embeddedChannel.close();
+ break;
+ default:
+ throw new DriverTestsuiteException("Unknown step type" + type);
+ }
+ } catch (Exception e) {
+ LOGGER.error(" Failed: Error running step: {}: {}", name, e.getMessage());
+ throw new DriverTestsuiteException("Error running the step " + name, e);
+ }
+ LOGGER.info(" Done");
+ }
+
+}
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/Testcase.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/Testcase.java
new file mode 100644
index 0000000..243c730
--- /dev/null
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/Testcase.java
@@ -0,0 +1,110 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+package org.apache.plc4x.test.driver.internal;
+
+import io.netty.channel.embedded.Plc4xEmbeddedChannel;
+import org.apache.plc4x.java.api.PlcConnection;
+import org.apache.plc4x.test.driver.DriverTestsuiteRunner;
+import org.apache.plc4x.test.driver.exceptions.DriverTestsuiteException;
+import org.apache.plc4x.test.driver.internal.utils.Synchronizer;
+import org.apache.plc4x.test.model.Location;
+import org.apache.plc4x.test.model.LocationAware;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.List;
+import java.util.Optional;
+
+public class Testcase implements LocationAware {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(DriverTestsuiteRunner.class);
+
+ private final DriverTestsuite driverTestsuite;
+ private final ConnectionManager connectionManager;
+ private final String name;
+ private final String description;
+ private final List<TestStep> steps;
+ private final Synchronizer synchronizer;
+ private Location location;
+
+
+ public Testcase(DriverTestsuite driverTestsuite, String name, String description, List<TestStep> steps, Synchronizer synchronizer) {
+ this.driverTestsuite = driverTestsuite;
+ this.connectionManager = new ConnectionManager();
+ this.name = name;
+ this.description = description;
+ this.steps = steps;
+ this.synchronizer = synchronizer;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public List<TestStep> getSteps() {
+ return steps;
+ }
+
+ public void setLocation(Location location) {
+ this.location = location;
+ }
+
+ public String getTestCaseLabel() {
+ return driverTestsuite.getName() + ": " + name;
+ }
+
+ @Override
+ public Optional<Location> getLocation() {
+ return Optional.ofNullable(location);
+ }
+
+ public void run() throws DriverTestsuiteException {
+ assert driverTestsuite != null;
+ LOGGER.info("Starting testcase: {}", name);
+ final PlcConnection plcConnection = connectionManager.getConnection(driverTestsuite.getDriverTestsuiteConfiguration().getDriverName(), driverTestsuite.getDriverTestsuiteConfiguration().getDriverParameters());
+ final Plc4xEmbeddedChannel embeddedChannel = connectionManager.getEmbeddedChannel(plcConnection);
+ final boolean bigEndian = driverTestsuite.getDriverTestsuiteConfiguration().isBigEndian();
+ // Be sure this is reset, just in case a previous testcase failed.
+ synchronizer.responseFuture = null;
+ if (!driverTestsuite.getSetupSteps().isEmpty()) {
+ LOGGER.info("Running setup steps");
+ for (TestStep setupStep : driverTestsuite.getSetupSteps()) {
+ setupStep.execute(plcConnection, embeddedChannel, bigEndian);
+ }
+ LOGGER.info("Finished setup steps");
+ }
+ LOGGER.info("Running test steps");
+ for (TestStep step : steps) {
+ step.execute(plcConnection, embeddedChannel, bigEndian);
+ }
+ LOGGER.info("Finished test steps");
+ if (!driverTestsuite.getTeardownSteps().isEmpty()) {
+ LOGGER.info("Running teardown steps");
+ for (TestStep teardownStep : driverTestsuite.getTeardownSteps()) {
+ teardownStep.execute(plcConnection, embeddedChannel, bigEndian);
+ }
+ LOGGER.info("Finished teardown steps");
+ }
+ LOGGER.info(String.format("Finished testcase: %s", driverTestsuite.getName()));
+ }
+}
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/api/TestField.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/api/TestField.java
similarity index 95%
copy from plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/api/TestField.java
copy to plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/api/TestField.java
index 3dd0cfb..6464330 100644
--- a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/api/TestField.java
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/api/TestField.java
@@ -16,7 +16,7 @@ KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
-package org.apache.plc4x.test.driver.model.api;
+package org.apache.plc4x.test.driver.internal.api;
public class TestField {
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/api/TestFieldRequest.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/api/TestFieldRequest.java
similarity index 95%
rename from plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/api/TestFieldRequest.java
rename to plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/api/TestFieldRequest.java
index cf3dbf8..656903a 100644
--- a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/api/TestFieldRequest.java
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/api/TestFieldRequest.java
@@ -16,7 +16,7 @@ KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
-package org.apache.plc4x.test.driver.model.api;
+package org.apache.plc4x.test.driver.internal.api;
import com.fasterxml.jackson.annotation.JsonProperty;
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/api/TestReadRequest.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/api/TestReadRequest.java
similarity index 95%
rename from plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/api/TestReadRequest.java
rename to plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/api/TestReadRequest.java
index 4a08b29..c215dc5 100644
--- a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/api/TestReadRequest.java
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/api/TestReadRequest.java
@@ -16,7 +16,7 @@ KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
-package org.apache.plc4x.test.driver.model.api;
+package org.apache.plc4x.test.driver.internal.api;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/api/TestRequest.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/api/TestRequest.java
similarity index 94%
copy from plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/api/TestRequest.java
copy to plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/api/TestRequest.java
index 273f36f..d01d852 100644
--- a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/api/TestRequest.java
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/api/TestRequest.java
@@ -16,7 +16,7 @@ KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
-package org.apache.plc4x.test.driver.model.api;
+package org.apache.plc4x.test.driver.internal.api;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/api/TestValueField.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/api/TestValueField.java
similarity index 95%
rename from plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/api/TestValueField.java
rename to plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/api/TestValueField.java
index 6ca866d..8c25acc 100644
--- a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/api/TestValueField.java
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/api/TestValueField.java
@@ -16,7 +16,7 @@ KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
-package org.apache.plc4x.test.driver.model.api;
+package org.apache.plc4x.test.driver.internal.api;
public class TestValueField extends TestField {
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/api/TestWriteRequest.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/api/TestWriteRequest.java
similarity index 95%
rename from plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/api/TestWriteRequest.java
rename to plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/api/TestWriteRequest.java
index e9d3ef2..f9216b4 100644
--- a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/api/TestWriteRequest.java
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/api/TestWriteRequest.java
@@ -16,7 +16,7 @@ KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
-package org.apache.plc4x.test.driver.model.api;
+package org.apache.plc4x.test.driver.internal.api;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/handlers/ApiRequestHandler.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/handlers/ApiRequestHandler.java
new file mode 100644
index 0000000..72be54a
--- /dev/null
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/handlers/ApiRequestHandler.java
@@ -0,0 +1,93 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+package org.apache.plc4x.test.driver.internal.handlers;
+
+import org.apache.plc4x.java.api.PlcConnection;
+import org.apache.plc4x.java.api.exceptions.PlcRuntimeException;
+import org.apache.plc4x.java.api.messages.PlcReadRequest;
+import org.apache.plc4x.java.api.messages.PlcWriteRequest;
+import org.apache.plc4x.test.driver.exceptions.DriverTestsuiteException;
+import org.apache.plc4x.test.driver.internal.utils.Synchronizer;
+import org.dom4j.Element;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class ApiRequestHandler {
+
+ private final Element payload;
+
+ private final Synchronizer synchronizer;
+
+ public ApiRequestHandler(Element payload, Synchronizer synchronizer) {
+ this.payload = payload;
+ this.synchronizer = synchronizer;
+ }
+
+ public void executeApiRequest(PlcConnection plcConnection) {
+ assert synchronizer != null;
+ // TODO: replace with language agnostic lookup
+ String className = payload.attributeValue("className");
+ switch (className) {
+ case "org.apache.plc4x.test.driver.internal.api.TestReadRequest": {
+ final PlcReadRequest.Builder builder = plcConnection.readRequestBuilder();
+ if (payload.element("fields") != null) {
+ for (Element fieldElement : payload.element("fields").elements("field")) {
+ builder.addItem(fieldElement.elementText("name"), fieldElement.elementText("address"));
+ }
+ }
+ final PlcReadRequest plc4xRequest = builder.build();
+ // Currently we can only process one response at at time, throw an error if more
+ // are submitted.
+ if (synchronizer.responseFuture != null) {
+ throw new DriverTestsuiteException("Previous response not handled.");
+ }
+ // Save the response for being used later on.
+ synchronizer.responseFuture = plc4xRequest.execute();
+ break;
+ }
+ case "org.apache.plc4x.test.driver.internal.api.TestWriteRequest": {
+ final PlcWriteRequest.Builder builder = plcConnection.writeRequestBuilder();
+ if (payload.element("fields") != null) {
+ for (Element fieldElement : payload.element("fields").elements("field")) {
+ List<Element> valueElements = fieldElement.elements("value");
+ List<String> valueStrings = new ArrayList<>(valueElements.size());
+ for (Element valueElement : valueElements) {
+ valueStrings.add(valueElement.getTextTrim());
+ }
+ builder.addItem(fieldElement.elementText("name"),
+ fieldElement.elementText("address"), valueStrings.toArray(new Object[0]));
+ }
+ }
+ final PlcWriteRequest plc4xRequest = builder.build();
+ // Currently we can only process one response at at time, throw an error if more
+ // are submitted.
+ if (synchronizer.responseFuture != null) {
+ throw new DriverTestsuiteException("Previous response not handled.");
+ }
+ // Save the response for being used later on.
+ synchronizer.responseFuture = plc4xRequest.execute();
+ break;
+ }
+ default:
+ throw new PlcRuntimeException("Unknown class name" + className);
+ }
+ }
+
+}
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/handlers/ApiResponseHandler.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/handlers/ApiResponseHandler.java
new file mode 100644
index 0000000..1631e50
--- /dev/null
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/handlers/ApiResponseHandler.java
@@ -0,0 +1,93 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+package org.apache.plc4x.test.driver.internal.handlers;
+
+import org.apache.plc4x.java.api.messages.PlcResponse;
+import org.apache.plc4x.java.spi.utils.XmlSerializable;
+import org.apache.plc4x.test.driver.exceptions.DriverTestsuiteException;
+import org.apache.plc4x.test.driver.internal.utils.Synchronizer;
+import org.apache.plc4x.test.driver.internal.validator.ApiValidator;
+import org.dom4j.Element;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import java.io.StringWriter;
+import java.util.concurrent.TimeUnit;
+
+public class ApiResponseHandler {
+
+ private final Element payload;
+
+ private final Synchronizer synchronizer;
+
+ public ApiResponseHandler(Element payload, Synchronizer synchronizer) {
+ this.payload = payload;
+ this.synchronizer = synchronizer;
+ }
+
+ public void executeApiResponse() {
+ assert synchronizer != null;
+ if (synchronizer.responseFuture == null) {
+ throw new DriverTestsuiteException("No response expected.");
+ }
+ PlcResponse plcResponse;
+ try {
+ plcResponse = synchronizer.responseFuture.get(5000, TimeUnit.MILLISECONDS);
+ } catch (Exception e) {
+ throw new DriverTestsuiteException("Got no response within 5000ms.");
+ }
+
+ // Reset the future.
+ synchronizer.responseFuture = null;
+ final String serializedResponse = serializeToXmlString((XmlSerializable) plcResponse);
+ ApiValidator.validateApiMessage(payload, serializedResponse);
+ }
+
+ private String serializeToXmlString(XmlSerializable value) {
+ try {
+ // TODO: replace with language agnostic lookup
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ DocumentBuilder builder = dbf.newDocumentBuilder();
+ org.w3c.dom.Document doc = builder.newDocument();
+ org.w3c.dom.Element root = doc.createElement("root");
+ doc.appendChild(root);
+ value.xmlSerialize(root);
+ DOMSource domSource = new DOMSource(doc.getDocumentElement().getFirstChild());
+ StringWriter writer = new StringWriter();
+ StreamResult result = new StreamResult(writer);
+ TransformerFactory tf = TransformerFactory.newInstance();
+ Transformer transformer = tf.newTransformer();
+ transformer.setOutputProperty(OutputKeys.INDENT, "yes");
+ transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
+ transformer.setOutputProperty("omit-xml-declaration", "yes");
+ transformer.transform(domSource, result);
+ return writer.toString();
+ } catch (ParserConfigurationException | TransformerException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+}
diff --git a/plc4j/drivers/s7/src/test/java/org/apache/plc4x/java/s7/readwrite/S7ParserSerializerTest.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/handlers/IncomingPlcBytesHandler.java
similarity index 71%
copy from plc4j/drivers/s7/src/test/java/org/apache/plc4x/java/s7/readwrite/S7ParserSerializerTest.java
copy to plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/handlers/IncomingPlcBytesHandler.java
index 1408b1f..d64486f 100644
--- a/plc4j/drivers/s7/src/test/java/org/apache/plc4x/java/s7/readwrite/S7ParserSerializerTest.java
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/handlers/IncomingPlcBytesHandler.java
@@ -16,14 +16,14 @@ KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
-package org.apache.plc4x.java.s7.readwrite;
+package org.apache.plc4x.test.driver.internal.handlers;
-import org.apache.plc4x.test.parserserializer.ParserSerializerTestsuiteRunner;
+import org.apache.commons.lang3.NotImplementedException;
-public class S7ParserSerializerTest extends ParserSerializerTestsuiteRunner {
+public class IncomingPlcBytesHandler {
- public S7ParserSerializerTest() {
- super("/protocols/s7/ParserSerializerTestsuite.xml", true, true);
+ public void executeIncomingPlcBytes() {
+ // TODO: Implement
+ throw new NotImplementedException("incoming-plc-bytes not implemented yet");
}
-
}
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/handlers/IncomingPlcMessageHandler.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/handlers/IncomingPlcMessageHandler.java
new file mode 100644
index 0000000..bbd37c7
--- /dev/null
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/handlers/IncomingPlcMessageHandler.java
@@ -0,0 +1,76 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+package org.apache.plc4x.test.driver.internal.handlers;
+
+import io.netty.buffer.Unpooled;
+import io.netty.channel.embedded.Plc4xEmbeddedChannel;
+import org.apache.plc4x.java.spi.generation.Message;
+import org.apache.plc4x.java.spi.generation.MessageIO;
+import org.apache.plc4x.java.spi.generation.ParseException;
+import org.apache.plc4x.java.spi.generation.WriteBufferByteBased;
+import org.apache.plc4x.test.driver.exceptions.DriverTestsuiteException;
+import org.apache.plc4x.test.driver.internal.DriverTestsuiteConfiguration;
+import org.apache.plc4x.test.migration.MessageResolver;
+import org.apache.plc4x.test.migration.MessageValidatorAndMigrator;
+import org.dom4j.Element;
+import org.dom4j.QName;
+
+import java.util.List;
+
+public class IncomingPlcMessageHandler {
+
+ private final DriverTestsuiteConfiguration driverTestsuiteConfiguration;
+
+ private final Element payload;
+
+ private final List<String> parserArguments;
+
+ public IncomingPlcMessageHandler(DriverTestsuiteConfiguration driverTestsuiteConfiguration, Element payload, List<String> parserArguments) {
+ this.driverTestsuiteConfiguration = driverTestsuiteConfiguration;
+ this.payload = payload;
+ this.parserArguments = parserArguments;
+ }
+
+ public void executeIncomingPlcMessage(Plc4xEmbeddedChannel embeddedChannel, boolean bigEndian) {
+ // Get a byte representation of the incoming message.
+ final byte[] data = getBytesFromXml(payload, bigEndian);
+ // Send the bytes to the channel.
+ embeddedChannel.writeInbound(Unpooled.wrappedBuffer(data));
+ }
+
+ @SuppressWarnings({"rawtypes", "unchecked"})
+ public byte[] getBytesFromXml(Element referenceXml, boolean bigEndian) throws DriverTestsuiteException {
+ final WriteBufferByteBased writeBuffer = new WriteBufferByteBased(1024, !bigEndian);
+ final String className = referenceXml.attributeValue(new QName("className"));
+ MessageIO messageIO = MessageResolver.getMessageIO(driverTestsuiteConfiguration.getProtocolName(), driverTestsuiteConfiguration.getOutputFlavor(), referenceXml.getName(), className);
+ // Get Message and Validate
+ Message message = MessageValidatorAndMigrator.validateInboundMessageMigrateAndGet(messageIO, referenceXml, className, parserArguments, driverTestsuiteConfiguration.isAutoMigrate(), driverTestsuiteConfiguration.getSuiteUri());
+
+ // Get Bytes
+ try {
+ messageIO.serialize(writeBuffer, message);
+ final byte[] data = new byte[message.getLengthInBytes()];
+ System.arraycopy(writeBuffer.getData(), 0, data, 0, writeBuffer.getPos());
+ return data;
+ } catch (ParseException e) {
+ throw new DriverTestsuiteException("Error serializing message", e);
+ }
+ }
+
+}
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/handlers/OutgoingPlcBytesHandler.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/handlers/OutgoingPlcBytesHandler.java
new file mode 100644
index 0000000..d90062a
--- /dev/null
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/handlers/OutgoingPlcBytesHandler.java
@@ -0,0 +1,48 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+package org.apache.plc4x.test.driver.internal.handlers;
+
+import io.netty.channel.embedded.Plc4xEmbeddedChannel;
+import org.apache.plc4x.test.driver.exceptions.DriverTestsuiteException;
+import org.apache.plc4x.test.driver.internal.utils.ChannelUtil;
+import org.apache.plc4x.test.driver.internal.utils.Delay;
+import org.dom4j.Element;
+
+public class OutgoingPlcBytesHandler {
+
+ private final Element payload;
+
+ public OutgoingPlcBytesHandler(Element payload) {
+ this.payload = payload;
+ }
+
+ public void executeOutgoingPlcBytes(Plc4xEmbeddedChannel embeddedChannel, boolean bigEndian) {
+ // As we're in the asynchronous world, give the driver some time to respond.
+ Delay.shortDelay();
+ // Prepare a ByteBuf that contains the data which would have been sent to the PLC.
+ final byte[] data = ChannelUtil.getOutboundBytes(embeddedChannel);
+ // Validate the data actually matches the expected message.
+ validateBytes(payload, data, bigEndian);
+ }
+
+
+ private void validateBytes(Element referenceXml, byte[] data, boolean bigEndian) throws DriverTestsuiteException {
+ // TODO: Implement this ...
+ }
+}
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/handlers/OutgoingPlcMessageHandler.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/handlers/OutgoingPlcMessageHandler.java
new file mode 100644
index 0000000..e01fbd5
--- /dev/null
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/handlers/OutgoingPlcMessageHandler.java
@@ -0,0 +1,52 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+package org.apache.plc4x.test.driver.internal.handlers;
+
+import io.netty.channel.embedded.Plc4xEmbeddedChannel;
+import org.apache.plc4x.test.driver.internal.DriverTestsuiteConfiguration;
+import org.apache.plc4x.test.driver.internal.utils.ChannelUtil;
+import org.apache.plc4x.test.driver.internal.utils.Delay;
+import org.apache.plc4x.test.migration.MessageValidatorAndMigrator;
+import org.dom4j.Element;
+
+import java.util.List;
+
+public class OutgoingPlcMessageHandler {
+
+ private final DriverTestsuiteConfiguration driverTestsuiteConfiguration;
+
+ private final Element payload;
+
+ private final List<String> parserArguments;
+
+ public OutgoingPlcMessageHandler(DriverTestsuiteConfiguration driverTestsuiteConfiguration, Element payload, List<String> parserArguments) {
+ this.driverTestsuiteConfiguration = driverTestsuiteConfiguration;
+ this.payload = payload;
+ this.parserArguments = parserArguments;
+ }
+
+ public void executeOutgoingPlcMessage(Plc4xEmbeddedChannel embeddedChannel, boolean bigEndian) {
+ // As we're in the asynchronous world, give the driver some time to respond.
+ Delay.shortDelay();
+ // Prepare a ByteBuf that contains the data which would have been sent to the PLC.
+ final byte[] data = ChannelUtil.getOutboundBytes(embeddedChannel);
+ // Validate the data actually matches the expected message.
+ MessageValidatorAndMigrator.validateOutboundMessageAndMigrate("TODO: insert testcase name here",driverTestsuiteConfiguration.getProtocolName(), driverTestsuiteConfiguration.getOutputFlavor(), payload, parserArguments, data, bigEndian, driverTestsuiteConfiguration.isAutoMigrate(), driverTestsuiteConfiguration.getSuiteUri());
+ }
+}
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/utils/ChannelUtil.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/utils/ChannelUtil.java
new file mode 100644
index 0000000..cddb849
--- /dev/null
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/utils/ChannelUtil.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.plc4x.test.driver.internal.utils;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.embedded.Plc4xEmbeddedChannel;
+import org.apache.plc4x.test.driver.exceptions.DriverTestsuiteException;
+
+public class ChannelUtil {
+
+ public static final int MAX_TRIES = 500;
+
+ public static byte[] getOutboundBytes(Plc4xEmbeddedChannel embeddedChannel) throws DriverTestsuiteException {
+ ByteBuf byteBuf = null;
+ for (int i = 0; i < MAX_TRIES; i++) {
+ byteBuf = embeddedChannel.readOutbound();
+ if (byteBuf != null) {
+ break;
+ }
+ Delay.delay(10);
+ }
+ if (byteBuf == null) {
+ throw new DriverTestsuiteException(String.format("No outbound message available within %dms", 10 * MAX_TRIES));
+ }
+ final byte[] data = new byte[byteBuf.readableBytes()];
+ byteBuf.readBytes(data);
+ return data;
+ }
+}
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/api/TestField.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/utils/Delay.java
similarity index 53%
rename from plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/api/TestField.java
rename to plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/utils/Delay.java
index 3dd0cfb..b2e375d 100644
--- a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/api/TestField.java
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/utils/Delay.java
@@ -16,24 +16,26 @@ KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
-package org.apache.plc4x.test.driver.model.api;
+package org.apache.plc4x.test.driver.internal.utils;
-public class TestField {
+import org.apache.plc4x.test.driver.exceptions.DriverTestsuiteException;
- private final String name;
- private final String address;
+import java.util.concurrent.TimeUnit;
- public TestField(String name, String address) {
- this.name = name;
- this.address = address;
- }
+public class Delay {
- public String getName() {
- return name;
+ // TODO: replace with signals
+ public static void shortDelay() throws DriverTestsuiteException {
+ delay(23);
}
- public String getAddress() {
- return address;
+ // TODO: replace with signals
+ public static void delay(int milliseconds) throws DriverTestsuiteException {
+ try {
+ TimeUnit.MILLISECONDS.sleep(milliseconds);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new DriverTestsuiteException("Interrupted during delay.");
+ }
}
-
}
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/api/TestRequest.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/utils/Synchronizer.java
similarity index 72%
rename from plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/api/TestRequest.java
rename to plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/utils/Synchronizer.java
index 273f36f..148ba68 100644
--- a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/api/TestRequest.java
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/utils/Synchronizer.java
@@ -16,10 +16,14 @@ KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
-package org.apache.plc4x.test.driver.model.api;
+package org.apache.plc4x.test.driver.internal.utils;
-import com.fasterxml.jackson.annotation.JsonTypeInfo;
+import org.apache.plc4x.java.api.messages.PlcResponse;
-@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "className")
-public interface TestRequest {
+import java.util.concurrent.CompletableFuture;
+
+public class Synchronizer {
+
+ // TODO: replace with signal
+ public CompletableFuture<? extends PlcResponse> responseFuture;
}
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/validator/ApiValidator.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/validator/ApiValidator.java
new file mode 100644
index 0000000..fba60d9
--- /dev/null
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/validator/ApiValidator.java
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.plc4x.test.driver.internal.validator;
+
+import org.apache.plc4x.test.driver.exceptions.DriverTestsuiteException;
+import org.apache.plc4x.test.driver.internal.handlers.ApiResponseHandler;
+import org.dom4j.Element;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.xmlunit.builder.DiffBuilder;
+import org.xmlunit.diff.Diff;
+
+public class ApiValidator {
+ private static final Logger LOGGER = LoggerFactory.getLogger(ApiValidator.class);
+
+ public static void validateApiMessage(Element referenceXml, String apiMessage) throws DriverTestsuiteException {
+ final String referenceXmlString = referenceXml.asXML();
+ final Diff diff = DiffBuilder.compare(referenceXmlString)
+ .withTest(apiMessage).checkForSimilar().ignoreComments().ignoreWhitespace()
+ .build();
+ if (diff.hasDifferences()) {
+ LOGGER.warn(apiMessage);
+ LOGGER.warn(diff.toString());
+ throw new DriverTestsuiteException("Differences were found after parsing.\n" + diff.toString());
+ }
+ }
+}
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/TestStep.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/TestStep.java
deleted file mode 100644
index 31f9ba0..0000000
--- a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/TestStep.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one
-or more contributor license agreements. See the NOTICE file
-distributed with this work for additional information
-regarding copyright ownership. The ASF licenses this file
-to you under the Apache License, Version 2.0 (the
-"License"); you may not use this file except in compliance
-with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing,
-software distributed under the License is distributed on an
-"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-KIND, either express or implied. See the License for the
-specific language governing permissions and limitations
-under the License.
-*/
-package org.apache.plc4x.test.driver.model;
-
-import org.apache.plc4x.test.model.Location;
-import org.apache.plc4x.test.model.LocationAware;
-import org.dom4j.Element;
-
-import java.util.List;
-import java.util.Optional;
-
-public class TestStep implements LocationAware {
-
- private final StepType type;
- private final String name;
- private final List<String> parserArguments;
- private final Element payload;
- private Location location;
-
- public TestStep(StepType type, String name, List<String> parserArguments, Element payload) {
- this.type = type;
- this.name = name;
- this.parserArguments = parserArguments;
- this.payload = payload;
- }
-
- public StepType getType() {
- return type;
- }
-
- public String getName() {
- return name;
- }
-
- public List<String> getParserArguments() {
- return parserArguments;
- }
-
- public Element getPayload() {
- return payload;
- }
-
- public void setLocation(Location location) {
- this.location = location;
- }
-
- @Override
- public Optional<Location> getLocation() {
- return Optional.ofNullable(location);
- }
-
-}
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/Testcase.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/Testcase.java
deleted file mode 100644
index 5333eb9..0000000
--- a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/model/Testcase.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one
-or more contributor license agreements. See the NOTICE file
-distributed with this work for additional information
-regarding copyright ownership. The ASF licenses this file
-to you under the Apache License, Version 2.0 (the
-"License"); you may not use this file except in compliance
-with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing,
-software distributed under the License is distributed on an
-"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-KIND, either express or implied. See the License for the
-specific language governing permissions and limitations
-under the License.
-*/
-package org.apache.plc4x.test.driver.model;
-
-import org.apache.plc4x.test.model.Location;
-import org.apache.plc4x.test.model.LocationAware;
-
-import java.util.List;
-import java.util.Optional;
-
-public class Testcase implements LocationAware {
-
- private final String name;
- private final String description;
- private final List<TestStep> steps;
- private Location location;
-
- public Testcase(String name, String description, List<TestStep> steps) {
- this.name = name;
- this.description = description;
- this.steps = steps;
- }
-
- public String getName() {
- return name;
- }
-
- public String getDescription() {
- return description;
- }
-
- public List<TestStep> getSteps() {
- return steps;
- }
-
- public void setLocation(Location location) {
- this.location = location;
- }
-
- @Override
- public Optional<Location> getLocation() {
- return Optional.ofNullable(location);
- }
-
-}
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/mapper/TestSuiteMappingModule.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/mapper/TestSuiteMappingModule.java
index 79f277f..a0d94f4 100644
--- a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/mapper/TestSuiteMappingModule.java
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/mapper/TestSuiteMappingModule.java
@@ -33,7 +33,9 @@ import java.io.IOException;
/**
* Custom module for Jackson to handle types in the way we wish - turning byte and byte[] into hex strings.
+ * @deprecated replaced by custom serializer
*/
+@Deprecated
public class TestSuiteMappingModule extends SimpleModule {
public TestSuiteMappingModule() {
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/migration/MessageResolver.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/migration/MessageResolver.java
new file mode 100644
index 0000000..665acc8
--- /dev/null
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/migration/MessageResolver.java
@@ -0,0 +1,202 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.plc4x.test.migration;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.plc4x.java.spi.generation.MessageIO;
+import org.apache.plc4x.java.spi.generation.ParseException;
+import org.apache.plc4x.java.spi.generation.ReadBuffer;
+import org.apache.plc4x.java.spi.generation.WriteBuffer;
+import org.apache.plc4x.test.driver.exceptions.DriverTestsuiteException;
+import org.apache.plc4x.test.parserserializer.exceptions.ParserSerializerTestsuiteException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.LinkedList;
+import java.util.List;
+
+public class MessageResolver {
+
+ private final static Logger LOGGER = LoggerFactory.getLogger(MessageResolver.class);
+
+ /**
+ * Returns the messageIO class based on a convention out of {@code protocolName} {@code outputFlavor} and {@code name}.
+ * If this fails its tries a fallback using the deprecated attribute {@code className}
+ *
+ * @param protocolName name of the protocol
+ * @param outputFlavor flavor of the output (e.g read-write)
+ * @param name name of the message
+ * @param className deprecated fallback classname attribute
+ * @return the found MessageIO
+ * @throws DriverTestsuiteException if a MessageIO couldn't be found.
+ */
+ @SuppressWarnings("rawtypes")
+ public static MessageIO getMessageIO(String protocolName, String outputFlavor, String name, @Deprecated String className) throws DriverTestsuiteException {
+ try {
+ return MessageResolver.getMessageIOType(protocolName, outputFlavor, name).newInstance();
+ } catch (InstantiationException | IllegalAccessException ignore) {
+ LOGGER.warn("\n!!!Un-migrated test!!!\n");
+ try {
+ return MessageResolver.getMessageIOTypeFallback(className).newInstance();
+ } catch (InstantiationException | IllegalAccessException e) {
+ throw new DriverTestsuiteException(e);
+ }
+ }
+ }
+
+ public static MessageIO getMessageIOStaticLinked(String protocolName, String outputFlavor, String typeName, @Deprecated String classNameAttributeValue) throws ParserSerializerTestsuiteException {
+ String ioClassName, ioRootClassName;
+ try {
+ String classPackage = String.format("org.apache.plc4x.java.%s.%s", protocolName, StringUtils.replace(outputFlavor, "-", ""));
+ try {
+ Package.getPackage(classPackage);
+ } catch (RuntimeException e) {
+ throw new RuntimeException("fallback to old", e);
+ }
+ ioRootClassName = classPackage + "." + typeName;
+ ioClassName = classPackage + ".io." + typeName + "IO";
+ try {
+ Class.forName(ioRootClassName);
+ Class.forName(ioClassName);
+ } catch (ClassNotFoundException e) {
+ throw new RuntimeException("fallback to old", e);
+ }
+ } catch (RuntimeException e) {
+ LOGGER.error("Error in serializer", e);
+ ioRootClassName = classNameAttributeValue.substring(0, classNameAttributeValue.lastIndexOf('.') + 1) + typeName;
+ ioClassName = classNameAttributeValue.substring(0, classNameAttributeValue.lastIndexOf('.') + 1) + "io." + typeName + "IO";
+ }
+ try {
+ Class<?> ioRootClass = Class.forName(ioRootClassName);
+ Class<?> ioClass = Class.forName(ioClassName);
+ Method staticParseMethod = null;
+ Method staticSerializeMethod = null;
+ final List<Class<?>> parameterTypes = new LinkedList<>();
+ for (Method method : ioClass.getMethods()) {
+ if (method.getName().equals("staticParse") && Modifier.isStatic(method.getModifiers()) &&
+ (method.getReturnType() == ioRootClass)) {
+ staticParseMethod = method;
+
+ // Get a list of additional parameter types for the parser.
+ for (int i = 1; i < method.getParameterCount(); i++) {
+ Class<?> parameterType = staticParseMethod.getParameterTypes()[i];
+ parameterTypes.add(parameterType);
+ }
+ }
+ if (method.getName().equals("staticSerialize") && Modifier.isStatic(method.getModifiers()) &&
+ (method.getParameterTypes()[1] == ioRootClass)) {
+ staticSerializeMethod = method;
+ }
+ }
+ if ((staticParseMethod == null) || (staticSerializeMethod == null)) {
+ throw new ParserSerializerTestsuiteException(
+ "Unable to instantiate IO component. Missing static parse or serialize methods.");
+ }
+ final Method parseMethod = staticParseMethod;
+ final Method serializeMethod = staticSerializeMethod;
+ return new MessageIO() {
+ @Override
+ public Object parse(ReadBuffer io, Object... args) throws ParseException {
+ try {
+ Object[] argValues = new Object[args.length + 1];
+ argValues[0] = io;
+ for (int i = 1; i <= args.length; i++) {
+ String parameterValue = (String) args[i - 1];
+ Class<?> parameterType = parameterTypes.get(i - 1);
+ if (parameterType == Boolean.class) {
+ argValues[i] = Boolean.parseBoolean(parameterValue);
+ } else if (parameterType == Byte.class) {
+ argValues[i] = Byte.parseByte(parameterValue);
+ } else if (parameterType == Short.class) {
+ argValues[i] = Short.parseShort(parameterValue);
+ } else if (parameterType == Integer.class) {
+ argValues[i] = Integer.parseInt(parameterValue);
+ } else if (parameterType == Long.class) {
+ argValues[i] = Long.parseLong(parameterValue);
+ } else if (parameterType == Float.class) {
+ argValues[i] = Float.parseFloat(parameterValue);
+ } else if (parameterType == Double.class) {
+ argValues[i] = Double.parseDouble(parameterValue);
+ } else if (parameterType == String.class) {
+ argValues[i] = parameterValue;
+ } else if (Enum.class.isAssignableFrom(parameterType)) {
+ argValues[i] = Enum.valueOf((Class<? extends Enum>) parameterType, parameterValue);
+ } else {
+ throw new ParseException("Currently unsupported parameter type");
+ }
+ }
+
+ return parseMethod.invoke(null, argValues);
+ } catch (IllegalAccessException | InvocationTargetException e) {
+ throw new ParseException("error parsing", e);
+ }
+ }
+
+ @Override
+ public void serialize(WriteBuffer io, Object value, Object... args) throws ParseException {
+ try {
+ serializeMethod.invoke(null, io, value);
+ } catch (IllegalAccessException | InvocationTargetException e) {
+ throw new ParseException("error serializing", e);
+ }
+ }
+ };
+ } catch (ClassNotFoundException e) {
+ throw new ParserSerializerTestsuiteException("Unable to instantiate IO component", e);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private static Class<? extends MessageIO<?, ?>> getMessageIOType(String protocolName, String outputFlavor, String typeName) throws DriverTestsuiteException {
+ String classPackage = String.format("org.apache.plc4x.java.%s.%s", protocolName, StringUtils.replace(outputFlavor, "-", ""));
+ try {
+ Package.getPackage(classPackage);
+ } catch (RuntimeException e) {
+ throw new RuntimeException("fallback to old", e);
+ }
+ String ioRootClassName = classPackage + "." + typeName;
+ String ioClassName = classPackage + ".io." + typeName + "IO";
+ try {
+ Class.forName(ioRootClassName);
+ return (Class<? extends MessageIO<?, ?>>) Class.forName(ioClassName);
+ } catch (ClassNotFoundException e) {
+ throw new RuntimeException("fallback to old", e);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private static Class<? extends MessageIO<?, ?>> getMessageIOTypeFallback(String messageClassName) throws DriverTestsuiteException {
+ String ioClassName = messageClassName.substring(0, messageClassName.lastIndexOf('.')) + ".io." +
+ messageClassName.substring(messageClassName.lastIndexOf('.') + 1) + "IO";
+ try {
+ final Class<?> ioClass = Class.forName(ioClassName);
+ if (MessageIO.class.isAssignableFrom(ioClass)) {
+ return (Class<? extends MessageIO<?, ?>>) ioClass;
+ }
+ throw new DriverTestsuiteException("IO class muss implement MessageIO interface");
+ } catch (ClassNotFoundException e) {
+ throw new DriverTestsuiteException("Error loading io class", e);
+ }
+ }
+
+}
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/migration/MessageValidatorAndMigrator.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/migration/MessageValidatorAndMigrator.java
new file mode 100644
index 0000000..b51d4b4
--- /dev/null
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/migration/MessageValidatorAndMigrator.java
@@ -0,0 +1,297 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.plc4x.test.migration;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.dataformat.xml.XmlMapper;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.plc4x.java.spi.generation.*;
+import org.apache.plc4x.test.driver.exceptions.DriverTestsuiteException;
+import org.apache.plc4x.test.mapper.TestSuiteMappingModule;
+import org.dom4j.Element;
+import org.dom4j.QName;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.xmlunit.builder.DiffBuilder;
+import org.xmlunit.diff.Diff;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.net.URI;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.List;
+
+// TODO: once migrated from old to new reuse as auto-updater for out-of date testsuites (actual will be used as new expected).
+public class MessageValidatorAndMigrator {
+
+ private final static Logger LOGGER = LoggerFactory.getLogger(MessageValidatorAndMigrator.class);
+
+ /**
+ * Validates a outbound message and migrates it to the expectation if the parameter {@code autoMigrate} is set to true
+ *
+ * @param testCaseName name of the testcase
+ * @param protocolName name of the protocol
+ * @param outputFlavor flavor of the output (e.g read-write)
+ * @param referenceXml the xml we expect the outbound message to be
+ * @param parserArguments the parser arguments to create an instance of the message
+ * @param data the bytes of the message
+ * @param bigEndian if BOM is big endian
+ * @param autoMigrate indicates if we want to migrate to a new version
+ * @param siteURI the file which we want to auto migrate
+ * @throws DriverTestsuiteException if something goes wrong
+ */
+ @SuppressWarnings({"rawtypes", "unchecked"})
+ public static void validateOutboundMessageAndMigrate(String testCaseName, String protocolName, String outputFlavor, Element referenceXml, List<String> parserArguments, byte[] data, boolean bigEndian, boolean autoMigrate, URI siteURI) throws DriverTestsuiteException {
+ @Deprecated final String className = referenceXml.attributeValue(new QName("className"));
+ MessageIO messageIO = MessageResolver.getMessageIO(protocolName, outputFlavor, referenceXml.getName(), className);
+ validateOutboundMessageAndMigrate(testCaseName, messageIO, referenceXml, parserArguments, data, bigEndian, autoMigrate, siteURI);
+ }
+
+ /**
+ * Validates a outbound message and migrates it to the expectation if the parameter {@code autoMigrate} is set to true
+ *
+ * @param testCaseName name of the testcase
+ * @param messageIO the pre-constructed MessageIO
+ * @param referenceXml the xml we expect the outbound message to be
+ * @param parserArguments the parser arguments to create an instance of the message
+ * @param data the bytes of the message
+ * @param bigEndian if BOM is big endian
+ * @param autoMigrate indicates if we want to migrate to a new version
+ * @param siteURI the file which we want to auto migrate
+ * @throws DriverTestsuiteException if something goes wrong
+ */
+ @SuppressWarnings({"rawtypes", "unchecked"})
+ public static void validateOutboundMessageAndMigrate(String testCaseName, MessageIO messageIO, Element referenceXml, List<String> parserArguments, byte[] data, boolean bigEndian, boolean autoMigrate, URI siteURI) throws DriverTestsuiteException {
+ final ReadBufferByteBased readBuffer = new ReadBufferByteBased(data, !bigEndian);
+
+ try {
+ final Object parsedOutput = messageIO.parse(readBuffer, parserArguments.toArray());
+ final String referenceXmlString = referenceXml.asXML();
+ try {
+ // First try to use the native xml writer
+ WriteBufferXmlBased writeBufferXmlBased = new WriteBufferXmlBased();
+ messageIO.serialize(writeBufferXmlBased, parsedOutput);
+ String xmlString = writeBufferXmlBased.getXmlString();
+ final Diff diff = DiffBuilder.compare(referenceXmlString)
+ .withTest(xmlString).checkForSimilar().ignoreComments().ignoreWhitespace()
+ .build();
+ if (diff.hasDifferences()) {
+ String border = StringUtils.repeat("=", 100);
+ String centeredDiffDetectedMessage = StringUtils.center(" Diff detected ", 100, "=");
+ String centeredTestCaseName = StringUtils.center(testCaseName, 100, "=");
+ LOGGER.warn(String.format(
+ "\n" +
+ // Border
+ "%1$s\n" +
+ // Testcase name
+ "%5$s\n" +
+ // diff detected message
+ "%2$s\n" +
+ // Border
+ "%1$s\n" +
+ // xml
+ "%3$s\n" +
+ // Border
+ "%1$s\n%1$s\n" +
+ // Text
+ "Differences were found after parsing (Use the above xml in the testsuite to disable this warning).\n" +
+ // Diff
+ "%4$s\n" +
+ // Double Border
+ "%1$s\n%1$s\n" +
+ // Text
+ "Falling back to old jackson based xml mapper\n",
+ border,
+ centeredDiffDetectedMessage,
+ xmlString,
+ diff,
+ centeredTestCaseName));
+ throw new MigrationException(xmlString);
+ }
+ } catch (RuntimeException | ParseException e) {
+ if (!(e instanceof MigrationException)) {
+ LOGGER.error("Error in serializer", e);
+ }
+ LOGGER.warn("Un-migrated test", e);
+ final ObjectMapper mapper = new XmlMapper().enableDefaultTyping().registerModule(new TestSuiteMappingModule());
+ String xmlStringFallback = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(parsedOutput);
+ final Diff diff2 = DiffBuilder.compare(referenceXmlString)
+ .withTest(xmlStringFallback).checkForSimilar().ignoreComments().ignoreWhitespace()
+ .build();
+ if (diff2.hasDifferences()) {
+ String border = StringUtils.repeat("=", 100);
+ String centeredDiffDetectedMessage = StringUtils.center(" Diff detected ", 100, "=");
+ // TODO: insert testcase name
+ String centeredTestCaseName = StringUtils.center("TODO: insert testcase name here", 100, "=");
+ LOGGER.warn(String.format(
+ "\n" +
+ // Border
+ "%1$s\n" +
+ // Testcase name
+ "%5$s\n" +
+ // diff detected message
+ "%2$s\n" +
+ // Border
+ "%1$s\n" +
+ // xml
+ "%3$s\n" +
+ // Border
+ "%1$s\n%1$s\n" +
+ // Text
+ "Differences were found after parsing (Use the above xml in the testsuite to disable this warning).\n" +
+ // Diff
+ "%4$s\n" +
+ // Double Border
+ "%1$s\n%1$s\n" +
+ // Text
+ "Falling back to old jackson based xml mapper\n",
+ border,
+ centeredDiffDetectedMessage,
+ referenceXmlString,
+ diff2,
+ centeredTestCaseName));
+ throw new DriverTestsuiteException("Differences were found after parsing.\n" + diff2);
+ } else {
+ LOGGER.info("No diff detected with old");
+ }
+ if (autoMigrate && e instanceof MigrationException) {
+ Path path = Paths.get(siteURI);
+ LOGGER.info("Migrating {} now", path);
+ Charset charset = StandardCharsets.UTF_8;
+
+ String content;
+ try {
+ content = new String(Files.readAllBytes(path), charset);
+ } catch (IOException ioException) {
+ throw new RuntimeException(ioException);
+ }
+ String indent = TestCasePatcher.determineIndent(content, xmlStringFallback);
+ String searchString = TestCasePatcher.indent(xmlStringFallback, indent);
+ String newXml = ((MigrationException) e).newXml;
+ newXml = TestCasePatcher.indent(newXml, indent);
+ content = StringUtils.replaceOnce(content, searchString, newXml);
+ try {
+ Files.write(path, content.getBytes(charset));
+ } catch (IOException ioException) {
+ throw new RuntimeException(ioException);
+ }
+ LOGGER.info("Done migrating {}", path);
+ }
+ }
+ } catch (ParseException | JsonProcessingException e) {
+ throw new DriverTestsuiteException("Error parsing message", e);
+ }
+ }
+
+ /**
+ * Validates a inbound message and migrates it to the expectation if the parameter {@code autoMigrate} is set to true
+ *
+ * @param protocolName name of the protocol
+ * @param outputFlavor flavor of the output (e.g read-write)
+ * @param referenceXml the xml we expect the outbound messag
+ * @param className @param className deprecated fallback classname attribute
+ * @param parserArguments the parser arguments to create an instance of the message
+ * @param autoMigrate indicates if we want to migrate to a new version
+ * @param siteURI the file which we want to auto migrate
+ * @return the message if all went well
+ */
+ @SuppressWarnings("rawtypes")
+ public static Message validateInboundMessageMigrateAndGet(String protocolName, String outputFlavor, Element referenceXml, @Deprecated String className, List<String> parserArguments, boolean autoMigrate, URI siteURI) {
+ MessageIO messageIO = MessageResolver.getMessageIO(protocolName, outputFlavor, referenceXml.getName(), className);
+ return validateInboundMessageMigrateAndGet(messageIO, referenceXml, className, parserArguments, autoMigrate, siteURI);
+ }
+
+ /**
+ * Validates a inbound message and migrates it to the expectation if the parameter {@code autoMigrate} is set to true
+ *
+ * @param messageIO the pre-constructed MessageIO
+ * @param referenceXml the xml we expect the outbound messag
+ * @param className @param className deprecated fallback classname attribute
+ * @param parserArguments the parser arguments to create an instance of the message
+ * @param autoMigrate indicates if we want to migrate to a new version
+ * @param siteURI the file which we want to auto migrate
+ * @return the message if all went well
+ */
+ @SuppressWarnings({"rawtypes", "unchecked"})
+ public static Message validateInboundMessageMigrateAndGet(MessageIO messageIO, Element referenceXml, @Deprecated String className, List<String> parserArguments, boolean autoMigrate, URI siteURI) {
+
+ final String referenceXmlString = referenceXml.asXML();
+ try {
+ return (Message) messageIO.parse(new ReadBufferXmlBased(new ByteArrayInputStream(referenceXmlString.getBytes(StandardCharsets.UTF_8))), parserArguments.toArray(new String[0]));
+ } catch (RuntimeException | ParseException e) {
+ LOGGER.warn("Unmigrated test", e);
+ final ObjectMapper mapper = new XmlMapper().enableDefaultTyping().registerModule(new TestSuiteMappingModule());
+ Message message;
+ try {
+ message = mapper.readValue(referenceXmlString, getMessageType(className));
+ } catch (JsonProcessingException innerE) {
+ throw new DriverTestsuiteException("Error parsing message", innerE);
+ }
+ try {
+ WriteBufferXmlBased writeBufferXmlBased = new WriteBufferXmlBased();
+ messageIO.serialize(writeBufferXmlBased, message);
+ if (autoMigrate) {
+ Path path = Paths.get(siteURI);
+ LOGGER.info("Migrating {} now", path);
+ Charset charset = StandardCharsets.UTF_8;
+
+ String content;
+ try {
+ content = new String(Files.readAllBytes(path), charset);
+ } catch (IOException ioException) {
+ throw new RuntimeException(ioException);
+ }
+ String indent = TestCasePatcher.determineIndent(content, referenceXmlString);
+ String searchString = indent + referenceXmlString;
+ String newXml = writeBufferXmlBased.getXmlString();
+ newXml = TestCasePatcher.indent(newXml, indent);
+ content = StringUtils.replaceOnce(content, searchString, newXml);
+ try {
+ Files.write(path, content.getBytes(charset));
+ } catch (IOException ioException) {
+ throw new RuntimeException(ioException);
+ }
+ LOGGER.info("Done migrating {}", path);
+ }
+ } catch (ParseException parseException) {
+ LOGGER.warn("could not migrate", e);
+ }
+ return message;
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private static Class<? extends Message> getMessageType(String messageClassName) throws DriverTestsuiteException {
+ try {
+ final Class<?> messageClass = Class.forName(messageClassName);
+ if (Message.class.isAssignableFrom(messageClass)) {
+ return (Class<? extends Message>) messageClass;
+ }
+ throw new DriverTestsuiteException("IO class must implement Message interface");
+ } catch (ClassNotFoundException e) {
+ throw new DriverTestsuiteException("Error loading message class", e);
+ }
+ }
+}
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/migration/MigrationException.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/migration/MigrationException.java
new file mode 100644
index 0000000..19e638e
--- /dev/null
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/migration/MigrationException.java
@@ -0,0 +1,32 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.plc4x.test.migration;
+
+/**
+ * Indicates an exception where a migration could happen.
+ * The field {@code newXml} can be used as new value.
+ */
+public class MigrationException extends RuntimeException {
+ public final String newXml;
+
+ public MigrationException(String newXml) {
+ this.newXml = newXml;
+ }
+}
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/migration/TestCasePatcher.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/migration/TestCasePatcher.java
new file mode 100644
index 0000000..157beb2
--- /dev/null
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/migration/TestCasePatcher.java
@@ -0,0 +1,61 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+package org.apache.plc4x.test.migration;
+
+import org.apache.commons.lang3.StringUtils;
+
+import java.util.Arrays;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+
+public class TestCasePatcher {
+
+ public static String indent(String xmlDocument, String indent) {
+ return Arrays.stream(xmlDocument.split("\n")).map(s -> indent + s + "\n").collect(Collectors.joining());
+ }
+
+ public static String determineIndent(String xmlDocument, String xmlFragment) {
+ assert xmlDocument != null;
+ assert xmlFragment != null;
+
+ Pattern pattern = getPatternForFragment(xmlFragment);
+ Matcher matcher = pattern.matcher(xmlDocument);
+ if (!matcher.find()) {
+ throw new RuntimeException("Could not match");
+ }
+ return matcher.group(1);
+ }
+
+ private static Pattern getPatternForFragment(String xmlFragment) {
+ StringBuilder patternString = new StringBuilder();
+ String[] lines = xmlFragment.split("\n");
+ for (int i = 0; i < lines.length; i++) {
+ String line = lines[i];
+ line = StringUtils.replace(line, "\"", "\\\"");
+ line = StringUtils.replace(line, ".", "\\.");
+ if (i == 0) {
+ patternString.append("([ ]*)").append(line).append("\\n");
+ continue;
+ }
+ patternString.append("[ ]*").append(line).append("\\n");
+ }
+ return Pattern.compile(patternString.toString());
+ }
+}
diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/parserserializer/ParserSerializerTestsuiteRunner.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/parserserializer/ParserSerializerTestsuiteRunner.java
index fb0a4d0..2292f61 100644
--- a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/parserserializer/ParserSerializerTestsuiteRunner.java
+++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/parserserializer/ParserSerializerTestsuiteRunner.java
@@ -19,18 +19,15 @@
package org.apache.plc4x.test.parserserializer;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
-import org.apache.commons.lang3.StringUtils;
import org.apache.plc4x.java.spi.generation.*;
-import org.apache.plc4x.test.XmlTestsuiteRunner;
+import org.apache.plc4x.test.XmlTestsuiteLoader;
import org.apache.plc4x.test.dom4j.LocationAwareDocumentFactory;
import org.apache.plc4x.test.dom4j.LocationAwareElement;
import org.apache.plc4x.test.dom4j.LocationAwareSAXReader;
-import org.apache.plc4x.test.mapper.TestSuiteMappingModule;
+import org.apache.plc4x.test.migration.MessageResolver;
+import org.apache.plc4x.test.migration.MessageValidatorAndMigrator;
import org.apache.plc4x.test.parserserializer.exceptions.ParserSerializerTestsuiteException;
import org.apache.plc4x.test.parserserializer.model.ParserSerializerTestsuite;
import org.apache.plc4x.test.parserserializer.model.Testcase;
@@ -44,32 +41,16 @@ import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.xmlunit.builder.DiffBuilder;
-import org.xmlunit.diff.Diff;
-import java.io.IOException;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
import java.net.URISyntaxException;
-import java.nio.charset.Charset;
-import java.nio.charset.StandardCharsets;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
import java.util.*;
@SuppressWarnings({"unchecked", "rawtypes"})
-public class ParserSerializerTestsuiteRunner extends XmlTestsuiteRunner {
+public class ParserSerializerTestsuiteRunner extends XmlTestsuiteLoader {
private static final Logger LOGGER = LoggerFactory.getLogger(ParserSerializerTestsuiteRunner.class);
/**
- * set to true during testcase migration
- */
- private final boolean failOnUnMigrated;
-
- /**
* if set to true if will automigrate and on the next run test should be green
*/
private final boolean autoMigrate;
@@ -80,13 +61,8 @@ public class ParserSerializerTestsuiteRunner extends XmlTestsuiteRunner {
this(testsuiteDocument, false, ignoredTestCases);
}
- public ParserSerializerTestsuiteRunner(String testsuiteDocument, boolean failOnUnMigrated, String... ignoredTestCases) {
- this(testsuiteDocument, false, false, ignoredTestCases);
- }
-
- public ParserSerializerTestsuiteRunner(String testsuiteDocument, boolean failOnUnMigrated, boolean autoMigrate, String... ignoredTestCases) {
+ public ParserSerializerTestsuiteRunner(String testsuiteDocument, boolean autoMigrate, String... ignoredTestCases) {
super(testsuiteDocument);
- this.failOnUnMigrated = failOnUnMigrated;
this.autoMigrate = autoMigrate;
Collections.addAll(this.ignoredTestCases, ignoredTestCases);
}
@@ -158,107 +134,34 @@ public class ParserSerializerTestsuiteRunner extends XmlTestsuiteRunner {
private void run(ParserSerializerTestsuite testSuite, Testcase testcase) throws ParserSerializerTestsuiteException {
ReadBufferByteBased readBuffer = new ReadBufferByteBased(testcase.getRaw(), testSuite.isLittleEndian());
- String referenceXml = testcase.getXml().elements().get(0).asXML();
- MessageIO messageIO = getMessageIOForTestcase(testcase);
try {
- Object msg = messageIO.parse(readBuffer, testcase.getParserArguments().toArray());
- {
- try {
- // First try to use the native xml writer
- WriteBufferXmlBased writerBufferXmlBased = new WriteBufferXmlBased();
- messageIO.serialize(writerBufferXmlBased, msg);
- String xmlString = writerBufferXmlBased.getXmlString();
- Diff diff = DiffBuilder.compare(referenceXml).withTest(xmlString).ignoreComments().ignoreWhitespace().build();
- if (diff.hasDifferences()) {
- String border = StringUtils.repeat("=", 100);
- String centeredDiffDetectedMessage = StringUtils.center(" Diff detected ", 100, "=");
- String centeredTestCaseName = StringUtils.center(testcase.getName(), 100, "=");
- System.err.printf(
- "\n" +
- // Border
- "%1$s\n" +
- // Testcase name
- "%5$s\n" +
- // diff detected message
- "%2$s\n" +
- // Border
- "%1$s\n" +
- // xml
- "%3$s\n" +
- // Border
- "%1$s\n%1$s\n" +
- // Text
- "Differences were found after parsing (Use the above xml in the testsuite to disable this warning).\n" +
- // Diff
- "%4$s\n" +
- // Double Border
- "%1$s\n%1$s\n" +
- // Text
- "Falling back to old jackson based xml mapper\n",
- border,
- centeredDiffDetectedMessage,
- xmlString,
- diff,
- centeredTestCaseName);
-
- throw new MigrationException(xmlString);
- }
- } catch (RuntimeException e) {
- if (!(e instanceof MigrationException)) {
- System.err.println("Error in serializer");
- System.err.println(e.getMessage());
- e.printStackTrace();
- }
- ObjectMapper mapper = new XmlMapper().enableDefaultTyping().registerModule(new TestSuiteMappingModule());
- String xmlStringFallback = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(msg);
- Diff diff2 = DiffBuilder.compare(referenceXml).withTest(xmlStringFallback).ignoreComments().ignoreWhitespace().build();
- if (diff2.hasDifferences()) {
- System.out.println(xmlStringFallback);
- throw new ParserSerializerTestsuiteException("Differences were found after parsing.\n" + diff2);
- } else {
- System.out.println("No diff detected with old");
- }
- if (autoMigrate && e instanceof MigrationException) {
- Path path = Paths.get(suiteUri);
- System.out.printf("Migrating %s now", path);
- Charset charset = StandardCharsets.UTF_8;
-
- String content;
- try {
- content = new String(Files.readAllBytes(path), charset);
- } catch (IOException ioException) {
- throw new RuntimeException(ioException);
- }
- // We need to indent the search string properly
- String indent = StringUtils.repeat(' ', 6);
- String searchString = StringUtils.replace(xmlStringFallback, "\n", "\n" + indent);
- searchString = StringUtils.trim(searchString);
- String newXml = ((MigrationException) e).newXml;
- newXml = StringUtils.replace(newXml, "\n", "\n" + indent);
- // Remove last wrong indent
- newXml = newXml.substring(0, newXml.length() - 7);
- content = StringUtils.replaceOnce(content, searchString, newXml);
- try {
- Files.write(path, content.getBytes(charset));
- } catch (IOException ioException) {
- throw new RuntimeException(ioException);
- }
- System.out.printf("Done migrating %s", path);
- }
- if (failOnUnMigrated) {
- throw new RuntimeException("fail on un-migrated set to true. Please migrate testcase", e);
- }
- }
- }
+ MessageIO messageIO = MessageResolver.getMessageIOStaticLinked(
+ testcase.getProtocolName(),
+ testcase.getOutputFlavor(),
+ testcase.getXml().elements().get(0).getName(),
+ testcase.getXml().elements().get(0).attributeValue(new QName("className"))
+ );
+ Object parsedOutput = messageIO.parse(readBuffer, testcase.getParserArguments().toArray());
+ MessageValidatorAndMigrator.validateOutboundMessageAndMigrate(
+ testcase.getName(),
+ messageIO,
+ testcase.getXml().elements().get(0),
+ testcase.getParserArguments(),
+ testcase.getRaw(),
+ !testSuite.isLittleEndian(),
+ autoMigrate,
+ suiteUri
+ );
- WriteBufferByteBased writeBuffer = new WriteBufferByteBased(((Message) msg).getLengthInBytes(), testSuite.isLittleEndian());
- messageIO.serialize(writeBuffer, msg);
+ WriteBufferByteBased writeBuffer = new WriteBufferByteBased(((Message) parsedOutput).getLengthInBytes(), testSuite.isLittleEndian());
+ messageIO.serialize(writeBuffer, parsedOutput);
byte[] data = writeBuffer.getData();
if (testcase.getRaw().length != data.length) {
LOGGER.info("Expected a byte array with a length of " + testcase.getRaw().length +
" but got one with " + data.length);
}
+ // TODO: improve output
if (!Arrays.equals(testcase.getRaw(), data)) {
int i;
for (i = 0; i < data.length; i++) {
@@ -272,158 +175,6 @@ public class ParserSerializerTestsuiteRunner extends XmlTestsuiteRunner {
}
} catch (ParseException e) {
throw new ParserSerializerTestsuiteException("Unable to parse message", e);
- } catch (JsonProcessingException e) {
- throw new ParserSerializerTestsuiteException("Unable to serialize parsed message as XML string", e);
- }
- }
-
- private MessageIO getMessageIOForTestcase(Testcase testcase) throws ParserSerializerTestsuiteException {
- String ioClassName, ioRootClassName;
- try {
- String classPackage = String.format("org.apache.plc4x.java.%s.%s", testcase.getProtocolName(), StringUtils.replace(testcase.getOutputFlavor(), "-", ""));
- try {
- Package.getPackage(classPackage);
- } catch (RuntimeException e) {
- System.err.println("Error resolving package for " + classPackage);
- switch (testcase.getTestSuiteName()) {
- case "Firmata":
- classPackage = "org.apache.plc4x.java.firmata.readwrite";
- break;
- case "Allen-Bradley ETH":
- classPackage = "org.apache.plc4x.java.abeth.readwrite";
- break;
- case "Beckhoff ADS/AMS Discovery":
- classPackage = "org.apache.plc4x.java.ads.discovery.readwrite";
- break;
- case "Beckhoff ADS/AMS":
- classPackage = "org.apache.plc4x.java.ads.readwrite";
- break;
- case "Tests of CANopen frames payload":
- classPackage = "org.apache.plc4x.java.canopen.readwrite";
- break;
- case "Tests of CANopen frames from Wireshark sample PCAP files":
- classPackage = "org.apache.plc4x.java.canopen.readwrite";
- break;
- case "EIP":
- classPackage = "org.apache.plc4x.java.eip.readwrite";
- break;
- case "Modbus":
- classPackage = "org.apache.plc4x.java.modbus.readwrite";
- break;
- case "S7":
- classPackage = "org.apache.plc4x.java.s7.readwrite";
- break;
- case "KNXNet/IP":
- classPackage = "org.apache.plc4x.java.knxnetip.readwrite";
- break;
- default:
- throw new RuntimeException(String.format("fallback to old. No packageName for '%s' configured.\nAdd the required package to the switch clause above", testcase.getTestSuiteName()));
- }
- }
- String fullQualifiedClassName = classPackage + "." + testcase.getXml().elements().get(0).getName();
- ioRootClassName = fullQualifiedClassName.substring(0, fullQualifiedClassName.lastIndexOf('.') + 1) + testcase.getRootType();
- ioClassName = fullQualifiedClassName.substring(0, fullQualifiedClassName.lastIndexOf('.') + 1) + "io." +
- testcase.getRootType() + "IO";
- try {
- Class.forName(ioRootClassName);
- Class.forName(ioClassName);
- } catch (ClassNotFoundException e) {
- throw new RuntimeException("fallback to old", e);
- }
- } catch (RuntimeException e) {
- System.err.println("Error in serializer");
- System.err.println(e.getMessage());
- e.printStackTrace();
- String fullQualifiedClassName = testcase.getXml().elements().get(0).attributeValue(new QName("className"));
- ioRootClassName = fullQualifiedClassName.substring(0, fullQualifiedClassName.lastIndexOf('.') + 1) + testcase.getRootType();
- ioClassName = fullQualifiedClassName.substring(0, fullQualifiedClassName.lastIndexOf('.') + 1) + "io." +
- testcase.getRootType() + "IO";
- }
- try {
- Class<?> ioRootClass = Class.forName(ioRootClassName);
- Class<?> ioClass = Class.forName(ioClassName);
- Method parseMethodTmp = null;
- Method serializeMethodTmp = null;
- final List<Class<?>> parameterTypes = new LinkedList<>();
- for (Method method : ioClass.getMethods()) {
- if (method.getName().equals("staticParse") && Modifier.isStatic(method.getModifiers()) &&
- (method.getReturnType() == ioRootClass)) {
- parseMethodTmp = method;
-
- // Get a list of additional parameter types for the parser.
- for (int i = 1; i < method.getParameterCount(); i++) {
- Class<?> parameterType = parseMethodTmp.getParameterTypes()[i];
- parameterTypes.add(parameterType);
- }
- }
- if (method.getName().equals("staticSerialize") && Modifier.isStatic(method.getModifiers()) &&
- (method.getParameterTypes()[1] == ioRootClass)) {
- serializeMethodTmp = method;
- }
- }
- if ((parseMethodTmp == null) || (serializeMethodTmp == null)) {
- throw new ParserSerializerTestsuiteException(
- "Unable to instantiate IO component. Missing static parse or serialize methods.");
- }
- final Method parseMethod = parseMethodTmp;
- final Method serializeMethod = serializeMethodTmp;
- return new MessageIO() {
- @Override
- public Object parse(ReadBuffer io, Object... args) throws ParseException {
- try {
- Object[] argValues = new Object[args.length + 1];
- argValues[0] = io;
- for (int i = 1; i <= args.length; i++) {
- String parameterValue = (String) args[i - 1];
- Class<?> parameterType = parameterTypes.get(i - 1);
- if (parameterType == Boolean.class) {
- argValues[i] = Boolean.parseBoolean(parameterValue);
- } else if (parameterType == Byte.class) {
- argValues[i] = Byte.parseByte(parameterValue);
- } else if (parameterType == Short.class) {
- argValues[i] = Short.parseShort(parameterValue);
- } else if (parameterType == Integer.class) {
- argValues[i] = Integer.parseInt(parameterValue);
- } else if (parameterType == Long.class) {
- argValues[i] = Long.parseLong(parameterValue);
- } else if (parameterType == Float.class) {
- argValues[i] = Float.parseFloat(parameterValue);
- } else if (parameterType == Double.class) {
- argValues[i] = Double.parseDouble(parameterValue);
- } else if (parameterType == String.class) {
- argValues[i] = parameterValue;
- } else if (Enum.class.isAssignableFrom(parameterType)) {
- argValues[i] = Enum.valueOf((Class<? extends Enum>) parameterType, parameterValue);
- } else {
- throw new ParseException("Currently unsupported parameter type");
- }
- }
-
- return parseMethod.invoke(null, argValues);
- } catch (IllegalAccessException | InvocationTargetException e) {
- throw new ParseException("error parsing", e);
- }
- }
-
- @Override
- public void serialize(WriteBuffer io, Object value, Object... args) throws ParseException {
- try {
- serializeMethod.invoke(null, io, value);
- } catch (IllegalAccessException | InvocationTargetException e) {
- throw new ParseException("error serializing", e);
- }
- }
- };
- } catch (ClassNotFoundException e) {
- throw new ParserSerializerTestsuiteException("Unable to instantiate IO component", e);
- }
- }
-
- private static class MigrationException extends RuntimeException {
- final String newXml;
-
- public MigrationException(String newXml) {
- this.newXml = newXml;
}
}
diff --git a/protocols/ads/src/test/resources/protocols/ads/ParserSerializerTestsuite.xml b/protocols/ads/src/test/resources/protocols/ads/ParserSerializerTestsuite.xml
index 6113134..6fcac92 100644
--- a/protocols/ads/src/test/resources/protocols/ads/ParserSerializerTestsuite.xml
+++ b/protocols/ads/src/test/resources/protocols/ads/ParserSerializerTestsuite.xml
@@ -58,7 +58,7 @@
</sourceAmsNetId>
<sourceAmsPort dataType="uint" bitLength="16">851</sourceAmsPort>
<commandId>
- <commandId dataType="uint" bitLength="16">2</commandId>
+ <CommandId dataType="uint" bitLength="16" stringRepresentation="ADS_READ">2</CommandId>
</commandId>
<state>
<State>
@@ -125,7 +125,7 @@
</sourceAmsNetId>
<sourceAmsPort dataType="uint" bitLength="16">851</sourceAmsPort>
<commandId>
- <commandId dataType="uint" bitLength="16">2</commandId>
+ <CommandId dataType="uint" bitLength="16" stringRepresentation="ADS_READ">2</CommandId>
</commandId>
<state>
<State>
@@ -148,7 +148,7 @@
<AdsData>
<AdsReadResponse>
<result>
- <result dataType="uint" bitLength="32">0</result>
+ <ReturnCode dataType="uint" bitLength="32" stringRepresentation="OK">0</ReturnCode>
</result>
<length dataType="uint" bitLength="32">1</length>
<data isList="true">
@@ -196,7 +196,7 @@
</sourceAmsNetId>
<sourceAmsPort dataType="uint" bitLength="16">65534</sourceAmsPort>
<commandId>
- <commandId dataType="uint" bitLength="16">9</commandId>
+ <CommandId dataType="uint" bitLength="16" stringRepresentation="ADS_READ_WRITE">9</CommandId>
</commandId>
<state>
<State>
@@ -294,7 +294,7 @@
</sourceAmsNetId>
<sourceAmsPort dataType="uint" bitLength="16">851</sourceAmsPort>
<commandId>
- <commandId dataType="uint" bitLength="16">9</commandId>
+ <CommandId dataType="uint" bitLength="16" stringRepresentation="ADS_READ_WRITE">9</CommandId>
</commandId>
<state>
<State>
@@ -317,7 +317,7 @@
<AdsData>
<AdsReadWriteResponse>
<result>
- <result dataType="uint" bitLength="32">0</result>
+ <ReturnCode dataType="uint" bitLength="32" stringRepresentation="OK">0</ReturnCode>
</result>
<length dataType="uint" bitLength="32">4</length>
<data isList="true">
@@ -368,7 +368,7 @@
</sourceAmsNetId>
<sourceAmsPort dataType="uint" bitLength="16">65534</sourceAmsPort>
<commandId>
- <commandId dataType="uint" bitLength="16">2</commandId>
+ <CommandId dataType="uint" bitLength="16" stringRepresentation="ADS_READ">2</CommandId>
</commandId>
<state>
<State>
@@ -435,7 +435,7 @@
</sourceAmsNetId>
<sourceAmsPort dataType="uint" bitLength="16">851</sourceAmsPort>
<commandId>
- <commandId dataType="uint" bitLength="16">2</commandId>
+ <CommandId dataType="uint" bitLength="16" stringRepresentation="ADS_READ">2</CommandId>
</commandId>
<state>
<State>
@@ -458,7 +458,7 @@
<AdsData>
<AdsReadResponse>
<result>
- <result dataType="uint" bitLength="32">0</result>
+ <ReturnCode dataType="uint" bitLength="32" stringRepresentation="OK">0</ReturnCode>
</result>
<length dataType="uint" bitLength="32">1</length>
<data isList="true">
@@ -506,7 +506,7 @@
</sourceAmsNetId>
<sourceAmsPort dataType="uint" bitLength="16">65534</sourceAmsPort>
<commandId>
- <commandId dataType="uint" bitLength="16">3</commandId>
+ <CommandId dataType="uint" bitLength="16" stringRepresentation="ADS_WRITE">3</CommandId>
</commandId>
<state>
<State>
@@ -579,7 +579,7 @@
</sourceAmsNetId>
<sourceAmsPort dataType="uint" bitLength="16">851</sourceAmsPort>
<commandId>
- <commandId dataType="uint" bitLength="16">3</commandId>
+ <CommandId dataType="uint" bitLength="16" stringRepresentation="ADS_WRITE">3</CommandId>
</commandId>
<state>
<State>
@@ -602,7 +602,7 @@
<AdsData>
<AdsWriteResponse>
<result>
- <result dataType="uint" bitLength="32">0</result>
+ <ReturnCode dataType="uint" bitLength="32" stringRepresentation="OK">0</ReturnCode>
</result>
</AdsWriteResponse>
</AdsData>
diff --git a/protocols/knxnetip/src/test/resources/protocols/knxnetip/ParserSerializerTestsuite.xml b/protocols/knxnetip/src/test/resources/protocols/knxnetip/ParserSerializerTestsuite.xml
index 311dbb1..bc38437 100644
--- a/protocols/knxnetip/src/test/resources/protocols/knxnetip/ParserSerializerTestsuite.xml
+++ b/protocols/knxnetip/src/test/resources/protocols/knxnetip/ParserSerializerTestsuite.xml
@@ -132,7 +132,7 @@
<HPAIDiscoveryEndpoint>
<structureLength dataType="uint" bitLength="8">8</structureLength>
<hostProtocolCode>
- <hostProtocolCode dataType="uint" bitLength="8">1</hostProtocolCode>
+ <HostProtocolCode dataType="uint" bitLength="8" stringRepresentation="IPV4_UDP">1</HostProtocolCode>
</hostProtocolCode>
<ipAddress>
<IPAddress>
@@ -169,7 +169,7 @@
<HPAIControlEndpoint>
<structureLength dataType="uint" bitLength="8">8</structureLength>
<hostProtocolCode>
- <hostProtocolCode dataType="uint" bitLength="8">1</hostProtocolCode>
+ <HostProtocolCode dataType="uint" bitLength="8" stringRepresentation="IPV4_UDP">1</HostProtocolCode>
</hostProtocolCode>
<ipAddress>
<IPAddress>
@@ -189,7 +189,7 @@
<structureLength dataType="uint" bitLength="8">54</structureLength>
<descriptionType dataType="uint" bitLength="8">1</descriptionType>
<knxMedium>
- <knxMedium dataType="uint" bitLength="8">2</knxMedium>
+ <KnxMedium dataType="uint" bitLength="8" stringRepresentation="MEDIUM_TP1">2</KnxMedium>
</knxMedium>
<deviceStatus>
<DeviceStatus>
@@ -320,7 +320,7 @@
<HPAIControlEndpoint>
<structureLength dataType="uint" bitLength="8">8</structureLength>
<hostProtocolCode>
- <hostProtocolCode dataType="uint" bitLength="8">1</hostProtocolCode>
+ <HostProtocolCode dataType="uint" bitLength="8" stringRepresentation="IPV4_UDP">1</HostProtocolCode>
</hostProtocolCode>
<ipAddress>
<IPAddress>
@@ -358,7 +358,7 @@
<structureLength dataType="uint" bitLength="8">54</structureLength>
<descriptionType dataType="uint" bitLength="8">1</descriptionType>
<knxMedium>
- <knxMedium dataType="uint" bitLength="8">2</knxMedium>
+ <KnxMedium dataType="uint" bitLength="8" stringRepresentation="MEDIUM_TP1">2</KnxMedium>
</knxMedium>
<deviceStatus>
<DeviceStatus>
@@ -490,7 +490,7 @@
<HPAIDiscoveryEndpoint>
<structureLength dataType="uint" bitLength="8">8</structureLength>
<hostProtocolCode>
- <hostProtocolCode dataType="uint" bitLength="8">1</hostProtocolCode>
+ <HostProtocolCode dataType="uint" bitLength="8" stringRepresentation="IPV4_UDP">1</HostProtocolCode>
</hostProtocolCode>
<ipAddress>
<IPAddress>
@@ -509,7 +509,7 @@
<HPAIDataEndpoint>
<structureLength dataType="uint" bitLength="8">8</structureLength>
<hostProtocolCode>
- <hostProtocolCode dataType="uint" bitLength="8">1</hostProtocolCode>
+ <HostProtocolCode dataType="uint" bitLength="8" stringRepresentation="IPV4_UDP">1</HostProtocolCode>
</hostProtocolCode>
<ipAddress>
<IPAddress>
@@ -530,7 +530,7 @@
<connectionType dataType="uint" bitLength="8">4</connectionType>
<ConnectionRequestInformationTunnelConnection>
<knxLayer>
- <knxLayer dataType="uint" bitLength="8">2</knxLayer>
+ <KnxLayer dataType="uint" bitLength="8" stringRepresentation="TUNNEL_LINK_LAYER">2</KnxLayer>
</knxLayer>
<reserved dataType="uint" bitLength="8">0</reserved>
</ConnectionRequestInformationTunnelConnection>
@@ -554,12 +554,12 @@
<ConnectionResponse>
<communicationChannelId dataType="uint" bitLength="8">2</communicationChannelId>
<status>
- <status dataType="uint" bitLength="8">0</status>
+ <Status dataType="uint" bitLength="8" stringRepresentation="NO_ERROR">0</Status>
</status>
<HPAIDataEndpoint>
<structureLength dataType="uint" bitLength="8">8</structureLength>
<hostProtocolCode>
- <hostProtocolCode dataType="uint" bitLength="8">1</hostProtocolCode>
+ <HostProtocolCode dataType="uint" bitLength="8" stringRepresentation="IPV4_UDP">1</HostProtocolCode>
</hostProtocolCode>
<ipAddress>
<IPAddress>
@@ -608,7 +608,7 @@
<HPAIControlEndpoint>
<structureLength dataType="uint" bitLength="8">8</structureLength>
<hostProtocolCode>
- <hostProtocolCode dataType="uint" bitLength="8">1</hostProtocolCode>
+ <HostProtocolCode dataType="uint" bitLength="8" stringRepresentation="IPV4_UDP">1</HostProtocolCode>
</hostProtocolCode>
<ipAddress>
<IPAddress>
@@ -641,7 +641,7 @@
<ConnectionStateResponse>
<communicationChannelId dataType="uint" bitLength="8">2</communicationChannelId>
<status>
- <status dataType="uint" bitLength="8">0</status>
+ <Status dataType="uint" bitLength="8" stringRepresentation="NO_ERROR">0</Status>
</status>
</ConnectionStateResponse>
</KnxNetIpMessage>
@@ -701,7 +701,7 @@
<communicationChannelId dataType="uint" bitLength="8">103</communicationChannelId>
<sequenceCounter dataType="uint" bitLength="8">0</sequenceCounter>
<status>
- <status dataType="uint" bitLength="8">0</status>
+ <Status dataType="uint" bitLength="8" stringRepresentation="NO_ERROR">0</Status>
</status>
</DeviceConfigurationAckDataBlock>
</deviceConfigurationAckDataBlock>
@@ -727,7 +727,7 @@
<HPAIControlEndpoint>
<structureLength dataType="uint" bitLength="8">8</structureLength>
<hostProtocolCode>
- <hostProtocolCode dataType="uint" bitLength="8">1</hostProtocolCode>
+ <HostProtocolCode dataType="uint" bitLength="8" stringRepresentation="IPV4_UDP">1</HostProtocolCode>
</hostProtocolCode>
<ipAddress>
<IPAddress>
@@ -760,7 +760,7 @@
<DisconnectResponse>
<communicationChannelId dataType="uint" bitLength="8">102</communicationChannelId>
<status>
- <status dataType="uint" bitLength="8">0</status>
+ <Status dataType="uint" bitLength="8" stringRepresentation="NO_ERROR">0</Status>
</status>
</DisconnectResponse>
</KnxNetIpMessage>
@@ -975,7 +975,7 @@
<communicationChannelId dataType="uint" bitLength="8">107</communicationChannelId>
<sequenceCounter dataType="uint" bitLength="8">0</sequenceCounter>
<status>
- <status dataType="uint" bitLength="8">0</status>
+ <Status dataType="uint" bitLength="8" stringRepresentation="NO_ERROR">0</Status>
</status>
</TunnelingResponseDataBlock>
</tunnelingResponseDataBlock>
@@ -999,7 +999,7 @@
<HPAIDiscoveryEndpoint>
<structureLength dataType="uint" bitLength="8">8</structureLength>
<hostProtocolCode>
- <hostProtocolCode dataType="uint" bitLength="8">1</hostProtocolCode>
+ <HostProtocolCode dataType="uint" bitLength="8" stringRepresentation="IPV4_UDP">1</HostProtocolCode>
</hostProtocolCode>
<ipAddress>
<IPAddress>
@@ -1018,7 +1018,7 @@
<HPAIDataEndpoint>
<structureLength dataType="uint" bitLength="8">8</structureLength>
<hostProtocolCode>
- <hostProtocolCode dataType="uint" bitLength="8">1</hostProtocolCode>
+ <HostProtocolCode dataType="uint" bitLength="8" stringRepresentation="IPV4_UDP">1</HostProtocolCode>
</hostProtocolCode>
<ipAddress>
<IPAddress>
diff --git a/sandbox/test-java-df1-driver/src/test/java/org/apache/plc4x/protocol/df1/Df1ParserSerializerTest.java b/sandbox/test-java-df1-driver/src/test/java/org/apache/plc4x/protocol/df1/Df1ParserSerializerTest.java
index b9b76d8..84fd5c4 100644
--- a/sandbox/test-java-df1-driver/src/test/java/org/apache/plc4x/protocol/df1/Df1ParserSerializerTest.java
+++ b/sandbox/test-java-df1-driver/src/test/java/org/apache/plc4x/protocol/df1/Df1ParserSerializerTest.java
@@ -24,7 +24,7 @@ import org.apache.plc4x.test.parserserializer.ParserSerializerTestsuiteRunner;
public class Df1ParserSerializerTest extends ParserSerializerTestsuiteRunner {
public Df1ParserSerializerTest() {
- super("/protocols/df1/ParserSerializerTestsuite.xml", true, true);
+ super("/protocols/df1/ParserSerializerTestsuite.xml", true);
}
}