From 75ae4f93dc8e1366635592d910ca72ebc3c1b90c Mon Sep 17 00:00:00 2001 From: Parracho Date: Tue, 24 Oct 2023 09:33:31 +0100 Subject: [PATCH 1/6] feat: created branch and new test classes --- .../managers/DtrSearchManagerTest.java | 44 +++++++++++++ .../managers/ProcessDataModelTest.java | 36 +++++++++++ .../productpass/services/AasServiceTest.java | 4 ++ .../services/CatenaXServiceTest.java | 60 +++++++++++++++++ .../services/DataPlaneServiceTest.java | 16 +++++ .../services/DataTransferServiceTest.java | 64 +++++++++++++++++++ 6 files changed, 224 insertions(+) create mode 100644 consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/DtrSearchManagerTest.java create mode 100644 consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/ProcessDataModelTest.java create mode 100644 consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/AasServiceTest.java create mode 100644 consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/CatenaXServiceTest.java create mode 100644 consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/DataPlaneServiceTest.java create mode 100644 consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/DataTransferServiceTest.java diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/DtrSearchManagerTest.java b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/DtrSearchManagerTest.java new file mode 100644 index 000000000..0aa628594 --- /dev/null +++ b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/DtrSearchManagerTest.java @@ -0,0 +1,44 @@ +package org.eclipse.tractusx.productpass.managers; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class DtrSearchManagerTest { + + @Test + void getState() { + } + + @Test + void setState() { + } + + @Test + void createDataModelFile() { + } + + @Test + void getDataModelPath() { + } + + @Test + void getDataModelDir() { + } + + @Test + void addConnectionToBpnEntry() { + } + + @Test + void loadDataModel() { + } + + @Test + void getDtrDataModel() { + } + + @Test + void saveDtrDataModel() { + } +} diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/ProcessDataModelTest.java b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/ProcessDataModelTest.java new file mode 100644 index 000000000..d3b9574da --- /dev/null +++ b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/ProcessDataModelTest.java @@ -0,0 +1,36 @@ +package org.eclipse.tractusx.productpass.managers; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class ProcessDataModelTest { + + @Test + void getDataModel() { + } + + @Test + void setDataModel() { + } + + @Test + void addProcess() { + } + + @Test + void setState() { + } + + @Test + void getState() { + } + + @Test + void getProcess() { + } + + @Test + void processExists() { + } +} diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/AasServiceTest.java b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/AasServiceTest.java new file mode 100644 index 000000000..a5ce3f81c --- /dev/null +++ b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/AasServiceTest.java @@ -0,0 +1,4 @@ +import static org.junit.jupiter.api.Assertions.*; +class AasServiceTest { + +} diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/CatenaXServiceTest.java b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/CatenaXServiceTest.java new file mode 100644 index 000000000..84f16c9ae --- /dev/null +++ b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/CatenaXServiceTest.java @@ -0,0 +1,60 @@ +package org.eclipse.tractusx.productpass.services; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class CatenaXServiceTest { + + @Test + void addEndpoint() { + } + + @Test + void getDiscoveryEndpoints() { + } + + @Test + void getDiscoveryEndpoint() { + } + + @Test + void updateDiscovery() { + } + + @Test + void updateDefaultDiscovery() { + } + + @Test + void updateEndpointFile() { + } + + @Test + void testUpdateEndpointFile() { + } + + @Test + void updateDefaultDiscoveryFile() { + } + + @Test + void testUpdateDefaultDiscoveryFile() { + } + + @Test + void testGetDiscoveryEndpoint() { + } + + @Test + void testGetDiscoveryEndpoints() { + } + + @Test + void getEdcDiscovery() { + } + + @Test + void getBpnDiscovery() { + } +} diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/DataPlaneServiceTest.java b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/DataPlaneServiceTest.java new file mode 100644 index 000000000..f3567519e --- /dev/null +++ b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/DataPlaneServiceTest.java @@ -0,0 +1,16 @@ +package org.eclipse.tractusx.productpass.services; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class DataPlaneServiceTest { + + @Test + void getTransferData() { + } + + @Test + void getPassport() { + } +} diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/DataTransferServiceTest.java b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/DataTransferServiceTest.java new file mode 100644 index 000000000..c368c7ac1 --- /dev/null +++ b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/DataTransferServiceTest.java @@ -0,0 +1,64 @@ +package org.eclipse.tractusx.productpass.services; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class DataTransferServiceTest { + + @Test + void getContractOfferByAssetId() { + } + + @Test + void buildRequest() { + } + + @Test + void buildOffer() { + } + + @Test + void getContractOfferCatalog() { + } + + @Test + void searchDigitalTwinCatalog() { + } + + @Test + void doContractNegotiation() { + } + + @Test + void testDoContractNegotiation() { + } + + @Test + void seeNegotiation() { + } + + @Test + void testSeeNegotiation() { + } + + @Test + void initiateTransfer() { + } + + @Test + void seeTransfer() { + } + + @Test + void testSeeTransfer() { + } + + @Test + void getPassport() { + } + + @Test + void generateTransferId() { + } +} From 413b5fbc3c5abf2eca2c3ddad63d17238e90a9b4 Mon Sep 17 00:00:00 2001 From: Parracho Date: Wed, 25 Oct 2023 09:32:40 +0100 Subject: [PATCH 2/6] feat: merged develop last updates --- .../managers/ProcessManagerTest.java | 64 +++++++++++++++++++ .../productpass/services/AasServiceTest.java | 50 ++++++++++++++- 2 files changed, 113 insertions(+), 1 deletion(-) create mode 100644 consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/ProcessManagerTest.java diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/ProcessManagerTest.java b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/ProcessManagerTest.java new file mode 100644 index 000000000..af7560333 --- /dev/null +++ b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/ProcessManagerTest.java @@ -0,0 +1,64 @@ +package org.eclipse.tractusx.productpass.managers; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class ProcessManagerTest { + + @Test + void loadDataModel() { + } + + @Test + void saveDataModel() { + } + + @Test + void getProcess() { + } + + @Test + void generateStatusToken() { + } + + @Test + void generateToken() { + } + + @Test + void checkProcess() { + } + + @Test + void testCheckProcess() { + } + + @Test + void startNegotiation() { + } + + @Test + void setProcess() { + } + + @Test + void setProcessState() { + } + + @Test + void getProcessState() { + } + + @Test + void createProcess() { + } + + @Test + void testCreateProcess() { + } + + @Test + void deleteSearchDir() { + } +} diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/AasServiceTest.java b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/AasServiceTest.java index a5ce3f81c..f8c191f40 100644 --- a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/AasServiceTest.java +++ b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/AasServiceTest.java @@ -1,4 +1,52 @@ +package org.eclipse.tractusx.productpass.services; + +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.*; + class AasServiceTest { - + + @Test + void searchDigitalTwin() { + } + + @Test + void getPathEndpoint() { + } + + @Test + void searchSubModelBySemanticId() { + } + + @Test + void testSearchSubModelBySemanticId() { + } + + @Test + void getDigitalTwin() { + } + + @Test + void getSubModelBySemanticId() { + } + + @Test + void testGetSubModelBySemanticId() { + } + + @Test + void getTokenHeader() { + } + + @Test + void getRegistryUrl() { + } + + @Test + void decentralDtrSearch() { + } + + @Test + void queryDigitalTwin() { + } } From 2ba44dcb6cbf96a95cf87e70fce9c808c170b86b Mon Sep 17 00:00:00 2001 From: Parracho Date: Mon, 18 Dec 2023 09:19:13 +0000 Subject: [PATCH 3/6] feat: created unit tests for managers, services and controller --- .../managers/DtrSearchManager.java | 10 +- .../productpass/managers/ProcessManager.java | 3 +- .../productpass/models/auth/UserInfo.java | 4 + .../models/catenax/BpnDiscovery.java | 7 + .../models/manager/SearchStatus.java | 1 + .../productpass/services/AasService.java | 1 - .../services/AuthenticationService.java | 1 + .../services/DataTransferService.java | 1 + .../productpass/services/IrsService.java | 2 - .../src/main/java/utils/HttpUtil.java | 2 +- .../src/main/java/utils/JsonUtil.java | 1 + .../test/java/mocks/MockedHttpSession.java | 80 +++ .../api/ContractControllerTest.java | 481 +++++++++++++ .../managers/DtrSearchManagerTest.java | 207 +++++- .../managers/ProcessDataModelTest.java | 90 ++- .../managers/ProcessManagerTest.java | 630 +++++++++++++++++- .../productpass/managers/TreeManagerTest.java | 211 ++++++ .../productpass/services/AasServiceTest.java | 237 ++++++- .../services/AuthenticationServiceTest.java | 102 +++ .../services/CatenaXServiceTest.java | 246 ++++++- .../services/DataPlaneServiceTest.java | 69 +- .../services/DataTransferServiceTest.java | 301 ++++++++- .../productpass/services/IrsServiceTest.java | 165 +++++ .../test/resources/dpp/assets/TestAsset.json | 21 + .../catalogs/TestContractOfferCatalog.json | 63 ++ .../dpp/catalogs/TestDigitalTwinCatalog.json | 51 ++ .../dpp/contractpolicies/TestPolicy.json | 8 + .../dpp/digitaltwins/TestDigitalTwin.json | 68 ++ .../discovery/MockedDiscoveryEndpoints.json | 15 + .../resources/dpp/irs/TestJobHistory.json | 9 + .../resources/dpp/irs/TestJobResponse.json | 292 ++++++++ .../dpp/irs/TestStartJobResponse.json | 3 + .../resources/dpp/irs/TestTreeDataModel.json | 214 ++++++ .../TestResponseInitNegotiation.json | 13 + .../negotiation/TestResponseNegotiation.json | 18 + .../resources/dpp/payloads/TestPassport.json | 248 +++++++ .../test/resources/dpp/token/MockedToken.json | 9 + .../resources/dpp/token/MockedUserInfo.json | 5 + .../transfer/TestResponseInitTransfer.json | 13 + .../dpp/transfer/TestResponseTransfer.json | 27 + 40 files changed, 3817 insertions(+), 112 deletions(-) create mode 100644 consumer-backend/productpass/src/test/java/mocks/MockedHttpSession.java create mode 100644 consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/http/controllers/api/ContractControllerTest.java create mode 100644 consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/TreeManagerTest.java create mode 100644 consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/AuthenticationServiceTest.java create mode 100644 consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/IrsServiceTest.java create mode 100644 consumer-backend/productpass/src/test/resources/dpp/assets/TestAsset.json create mode 100644 consumer-backend/productpass/src/test/resources/dpp/catalogs/TestContractOfferCatalog.json create mode 100644 consumer-backend/productpass/src/test/resources/dpp/catalogs/TestDigitalTwinCatalog.json create mode 100644 consumer-backend/productpass/src/test/resources/dpp/contractpolicies/TestPolicy.json create mode 100644 consumer-backend/productpass/src/test/resources/dpp/digitaltwins/TestDigitalTwin.json create mode 100644 consumer-backend/productpass/src/test/resources/dpp/discovery/MockedDiscoveryEndpoints.json create mode 100644 consumer-backend/productpass/src/test/resources/dpp/irs/TestJobHistory.json create mode 100644 consumer-backend/productpass/src/test/resources/dpp/irs/TestJobResponse.json create mode 100644 consumer-backend/productpass/src/test/resources/dpp/irs/TestStartJobResponse.json create mode 100644 consumer-backend/productpass/src/test/resources/dpp/irs/TestTreeDataModel.json create mode 100644 consumer-backend/productpass/src/test/resources/dpp/negotiation/TestResponseInitNegotiation.json create mode 100644 consumer-backend/productpass/src/test/resources/dpp/negotiation/TestResponseNegotiation.json create mode 100644 consumer-backend/productpass/src/test/resources/dpp/payloads/TestPassport.json create mode 100644 consumer-backend/productpass/src/test/resources/dpp/token/MockedToken.json create mode 100644 consumer-backend/productpass/src/test/resources/dpp/token/MockedUserInfo.json create mode 100644 consumer-backend/productpass/src/test/resources/dpp/transfer/TestResponseInitTransfer.json create mode 100644 consumer-backend/productpass/src/test/resources/dpp/transfer/TestResponseTransfer.json diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/managers/DtrSearchManager.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/managers/DtrSearchManager.java index d53ec8f58..ef2afe42f 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/managers/DtrSearchManager.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/managers/DtrSearchManager.java @@ -43,6 +43,7 @@ import java.nio.file.Path; import java.time.Duration; +import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -340,11 +341,11 @@ public void run() { */ public DtrSearchManager addConnectionToBpnEntry(String bpn, Dtr dtr) { if (!(bpn.isEmpty() || bpn.isBlank() || dtr.getEndpoint().isEmpty() || dtr.getEndpoint().isBlank())) { - if (this.dtrDataModel.contains(bpn)) { + if (this.dtrDataModel.containsKey(bpn)) { if (!this.dtrDataModel.get(bpn).contains(dtr)) this.dtrDataModel.get(bpn).add(dtr); } else { - this.dtrDataModel.put(bpn, List.of(dtr)); + this.dtrDataModel.put(bpn, new ArrayList<>(){{add(dtr);}}); } } return this; @@ -512,9 +513,10 @@ private ConcurrentHashMap> loadDtrDataModel() { return result; } catch (Exception e) { LogUtil.printException(e, "Was not possible to load Dtr Data Model!"); - return new ConcurrentHashMap>(); + ConcurrentHashMap> newDtrDataModel = new ConcurrentHashMap>(); + saveDtrDataModel(newDtrDataModel); + return newDtrDataModel; } - } } diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/managers/ProcessManager.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/managers/ProcessManager.java index 30fca2d79..b987d9108 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/managers/ProcessManager.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/managers/ProcessManager.java @@ -579,7 +579,6 @@ public Process createProcess(HttpServletRequest httpRequest, String processId, S * @throws ManagerException * if unable to create the status file. */ - public String newStatusFile(String processId, String connectorAddress, Long created, Boolean childrenCondition){ try { String path = this.getProcessFilePath(processId, this.metaFileName); @@ -685,6 +684,7 @@ public String setBpn(String processId, String bpn) { throw new ManagerException(this.getClass().getName(), e, "It was not possible to create/update the status file"); } } + /** * Set the children condition in the status file *

@@ -698,6 +698,7 @@ public String setBpn(String processId, String bpn) { * @throws ManagerException * if unable to update the status file. */ + @SuppressWarnings("Unused") public String setChildrenCondition(String processId, Boolean childrenCondition) { try { String path = this.getProcessFilePath(processId, this.metaFileName); diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/auth/UserInfo.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/auth/UserInfo.java index 7879c6d8a..2f80a522d 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/auth/UserInfo.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/auth/UserInfo.java @@ -23,6 +23,7 @@ package org.eclipse.tractusx.productpass.models.auth; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; @@ -35,6 +36,9 @@ public class UserInfo { /** ATTRIBUTES **/ @JsonProperty("sub") String sub; + @JsonProperty("bpn") + @JsonIgnore + String bpn; @JsonProperty("email_verified") String email_verified; @JsonProperty("name") diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/catenax/BpnDiscovery.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/catenax/BpnDiscovery.java index 5fdd59213..afa9cf275 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/catenax/BpnDiscovery.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/catenax/BpnDiscovery.java @@ -25,8 +25,12 @@ package org.eclipse.tractusx.productpass.models.catenax; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; import java.util.List; import java.util.stream.Collectors; @@ -41,6 +45,9 @@ public class BpnDiscovery { @JsonProperty("bpns") List bpns; + @JsonProperty("bpnNumbers") + List bpnNumbers; + /** CONSTRUCTOR(S) **/ @SuppressWarnings("Unused") public BpnDiscovery(List bpns) { diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/manager/SearchStatus.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/manager/SearchStatus.java index 4fb4bb09e..8ee33d623 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/manager/SearchStatus.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/models/manager/SearchStatus.java @@ -108,6 +108,7 @@ public void setUpdated(Long updated) { public Dtr getDtr(String id) { return this.dtrs.get(id); } + /** * Gets a new DTR into the DTR map object. *

diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/AasService.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/AasService.java index 1a1c5cbfb..a6424643c 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/AasService.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/AasService.java @@ -73,7 +73,6 @@ public class AasService extends BaseService { private DtrSearchManager dtrSearchManager; private final ProcessManager processManager; private DataTransferService dataService; - private PassportConfig passportConfig; diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/AuthenticationService.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/AuthenticationService.java index a603cc08f..0fe35dc34 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/AuthenticationService.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/AuthenticationService.java @@ -37,6 +37,7 @@ import org.springframework.stereotype.Service; import utils.HttpUtil; import utils.JsonUtil; +import utils.LogUtil; import java.util.ArrayList; import java.util.List; diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/DataTransferService.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/DataTransferService.java index b0c7c70b5..ee5b7440d 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/DataTransferService.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/DataTransferService.java @@ -794,6 +794,7 @@ public class NegotiateContract implements Runnable { private String processId; /** CONSTRUCTOR(S) **/ + public NegotiateContract() {}; public NegotiateContract(ProcessDataModel dataModel, String processId, String bpn, Dataset dataset, Status status) { this.dataModel = dataModel; this.processId = processId; diff --git a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/IrsService.java b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/IrsService.java index b8d06e710..c46d7b9c9 100644 --- a/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/IrsService.java +++ b/consumer-backend/productpass/src/main/java/org/eclipse/tractusx/productpass/services/IrsService.java @@ -58,9 +58,7 @@ public class IrsService extends BaseService { /** ATTRIBUTES **/ HttpUtil httpUtil; - JsonUtil jsonUtil; - String irsEndpoint; String irsJobPath; String callbackUrl; diff --git a/consumer-backend/productpass/src/main/java/utils/HttpUtil.java b/consumer-backend/productpass/src/main/java/utils/HttpUtil.java index 6fefdf544..ac5c48329 100644 --- a/consumer-backend/productpass/src/main/java/utils/HttpUtil.java +++ b/consumer-backend/productpass/src/main/java/utils/HttpUtil.java @@ -608,7 +608,7 @@ public URI buildUri(String url, Map params, Boolean encoded){ * the base URL. * @param params * the Map with key/value pair from each parameter. - * @param encode + * @param encoded * if true will encode the value of each parameter. * * @return a {@code String} with the build URL. diff --git a/consumer-backend/productpass/src/main/java/utils/JsonUtil.java b/consumer-backend/productpass/src/main/java/utils/JsonUtil.java index cfbc17419..9b4186fb0 100644 --- a/consumer-backend/productpass/src/main/java/utils/JsonUtil.java +++ b/consumer-backend/productpass/src/main/java/utils/JsonUtil.java @@ -23,6 +23,7 @@ package utils; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JacksonException; import com.fasterxml.jackson.core.json.JsonWriteFeature; import com.fasterxml.jackson.core.type.TypeReference; diff --git a/consumer-backend/productpass/src/test/java/mocks/MockedHttpSession.java b/consumer-backend/productpass/src/test/java/mocks/MockedHttpSession.java new file mode 100644 index 000000000..9f79688c1 --- /dev/null +++ b/consumer-backend/productpass/src/test/java/mocks/MockedHttpSession.java @@ -0,0 +1,80 @@ +package mocks; + +import jakarta.servlet.ServletContext; +import jakarta.servlet.http.HttpSession; +import utils.DateTimeUtil; + +import java.util.*; +import java.util.stream.Collectors; + +public class MockedHttpSession implements HttpSession { + + private Map attributes; + private String id; + private long creationTime; + + public MockedHttpSession() { + attributes = new HashMap(); + id = UUID.randomUUID().toString(); + creationTime = DateTimeUtil.getTimestamp(); + } + @Override + public long getCreationTime() { + return creationTime; + } + + @Override + public String getId() { + return id; + } + + @Override + public long getLastAccessedTime() { + return 0; + } + + @Override + public ServletContext getServletContext() { + return null; + } + + @Override + public void setMaxInactiveInterval(int i) { + + } + + @Override + public int getMaxInactiveInterval() { + return 0; + } + + @Override + public Object getAttribute(String s) { + return attributes.get(s); + } + + @Override + public Enumeration getAttributeNames() { + return (Enumeration) attributes.keySet().stream().collect(Collectors.toList()); + } + + @Override + public void setAttribute(String s, Object o) { + attributes.put(s, o); + } + + @Override + public void removeAttribute(String s) { + attributes.remove(s); + } + + @Override + public void invalidate() { + + } + + @Override + public boolean isNew() { + return false; + } +} diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/http/controllers/api/ContractControllerTest.java b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/http/controllers/api/ContractControllerTest.java new file mode 100644 index 000000000..8ca4b344b --- /dev/null +++ b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/http/controllers/api/ContractControllerTest.java @@ -0,0 +1,481 @@ +package org.eclipse.tractusx.productpass.http.controllers.api; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.eclipse.tractusx.productpass.config.DiscoveryConfig; +import org.eclipse.tractusx.productpass.config.DtrConfig; +import org.eclipse.tractusx.productpass.config.PassportConfig; +import org.eclipse.tractusx.productpass.config.ProcessConfig; +import org.eclipse.tractusx.productpass.exceptions.ServiceInitializationException; +import org.eclipse.tractusx.productpass.managers.DtrSearchManager; +import org.eclipse.tractusx.productpass.managers.ProcessDataModel; +import org.eclipse.tractusx.productpass.managers.ProcessManager; +import org.eclipse.tractusx.productpass.models.catenax.BpnDiscovery; +import org.eclipse.tractusx.productpass.models.http.Response; +import org.eclipse.tractusx.productpass.models.http.requests.DiscoverySearch; +import org.eclipse.tractusx.productpass.models.http.requests.Search; +import org.eclipse.tractusx.productpass.models.http.requests.TokenRequest; +import org.eclipse.tractusx.productpass.models.manager.History; +import org.eclipse.tractusx.productpass.models.manager.Process; +import org.eclipse.tractusx.productpass.models.manager.Status; +import org.eclipse.tractusx.productpass.services.*; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.core.env.Environment; +import org.springframework.mock.env.MockEnvironment; +import org.springframework.test.util.ReflectionTestUtils; +import utils.*; + +import java.util.*; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.when; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class ContractControllerTest { + @Mock + private HttpServletRequest httpRequest; + @Mock + private HttpServletResponse httpResponse; + private DataTransferService dataService; + @Mock + private VaultService vaultService; + private AasService aasService; + private AuthenticationService authService; + private PassportConfig passportConfig; + private DiscoveryConfig discoveryConfig; + private DtrConfig dtrConfig; + @Mock + private Environment env; + ProcessManager processManager; + DtrSearchManager dtrSearchManager; + private ProcessConfig processConfig; + CatenaXService catenaXService; + HttpUtil httpUtil; + private JsonUtil jsonUtil; + private FileUtil fileUtil; + private YamlUtil yamlUtil; + private ContractController contractController; + private Map configuration; + + @BeforeAll + void setUpAll() throws ServiceInitializationException { + MockitoAnnotations.openMocks(this); + + fileUtil = new FileUtil(); + yamlUtil = new YamlUtil(fileUtil); + jsonUtil = new JsonUtil(fileUtil); + + Map application = yamlUtil.readFile(FileUtil.getWorkdirPath() + "/src/main/resources/application.yml"); + configuration = (Map) jsonUtil.toMap(application.get("configuration")); + + env = initEnv(); + httpUtil = Mockito.spy(new HttpUtil(env)); + + Map vaultConfig = yamlUtil.readFile(fileUtil.getDataDir() + "/VaultConfig/vault.token.yml"); + Map client = (Map) jsonUtil.toMap(vaultConfig.get("client")); + when(vaultService.getLocalSecret("client.id")).thenReturn(client.get("id").toString()); + when(vaultService.getLocalSecret("client.secret")).thenReturn(client.get("secret").toString()); + Map edc = (Map) jsonUtil.toMap(vaultConfig.get("edc")); + when(vaultService.getLocalSecret("edc.apiKey")).thenReturn(edc.get("apiKey").toString()); + when(vaultService.getLocalSecret("edc.participantId")).thenReturn(edc.get("participantId").toString()); + + Map passport = (Map) jsonUtil.toMap(configuration.get("passport")); + passportConfig = new PassportConfig(); + passportConfig.setSearchIdSchema(passport.get("searchIdSchema").toString()); + dtrConfig = initDtrConfig(); + discoveryConfig = initDiscoveryConfig(); + processConfig = new ProcessConfig(); + processConfig.setDir("process"); + + + dataService = new DataTransferService(env, httpUtil, jsonUtil,vaultService, processManager, dtrConfig); + authService = new AuthenticationService(vaultService, env, httpUtil, jsonUtil); + catenaXService = Mockito.spy(new CatenaXService(env, fileUtil, httpUtil, jsonUtil, vaultService, dtrSearchManager, authService, discoveryConfig, dataService, dtrConfig)); + processManager = Mockito.spy(new ProcessManager(httpUtil,jsonUtil, fileUtil, processConfig)); + dtrSearchManager = new DtrSearchManager(fileUtil,jsonUtil, dataService, dtrConfig, processManager); + aasService = new AasService(env, httpUtil, jsonUtil, authService, dtrConfig, dtrSearchManager, processManager, dataService, passportConfig); + + contractController = initController(); + + } + + private ContractController initController() { + ContractController controller = new ContractController(); + ReflectionTestUtils.setField(controller, "httpRequest", httpRequest); + ReflectionTestUtils.setField(controller, "httpResponse", httpResponse); + ReflectionTestUtils.setField(controller, "dataService", dataService); + ReflectionTestUtils.setField(controller, "vaultService", vaultService); + ReflectionTestUtils.setField(controller, "aasService", aasService); + ReflectionTestUtils.setField(controller, "authService", authService); + ReflectionTestUtils.setField(controller, "passportConfig", passportConfig); + ReflectionTestUtils.setField(controller, "discoveryConfig", discoveryConfig); + ReflectionTestUtils.setField(controller, "dtrConfig", dtrConfig); + ReflectionTestUtils.setField(controller, "env", env); + ReflectionTestUtils.setField(controller, "processManager", processManager); + ReflectionTestUtils.setField(controller, "dtrSearchManager", dtrSearchManager); + ReflectionTestUtils.setField(controller, "processConfig", processConfig); + ReflectionTestUtils.setField(controller, "catenaXService", catenaXService); + ReflectionTestUtils.setField(controller, "httpUtil", httpUtil); + ReflectionTestUtils.setField(controller, "jsonUtil", jsonUtil); + + + return controller; + } + + private DtrConfig initDtrConfig() { + DtrConfig dtrConfig = new DtrConfig(); + DtrConfig.Timeouts timeouts = new DtrConfig.Timeouts(); + timeouts.setSearch(10); + timeouts.setNegotiation(40); + timeouts.setTransfer(10); + timeouts.setDigitalTwin(20); + dtrConfig.setTimeouts(timeouts); + dtrConfig.setTemporaryStorage(new DtrConfig.TemporaryStorage(true, 12)); + + Map dtr = (Map) jsonUtil.toMap(configuration.get("dtr")); + Map decentralApis = (Map) jsonUtil.toMap(dtr.get("decentralApis")); + DtrConfig.DecentralApis decentralApisObj = new DtrConfig.DecentralApis(); + decentralApisObj.setSearch(decentralApis.get("search").toString()); + decentralApisObj.setDigitalTwin(decentralApis.get("digitalTwin").toString()); + decentralApisObj.setSubModel(decentralApis.get("subModel").toString()); + dtrConfig.setDecentralApis(decentralApisObj); + + dtrConfig.setSemanticIdTypeKey(dtr.get("semanticIdTypeKey").toString()); + + return dtrConfig; + } + + private DiscoveryConfig initDiscoveryConfig() { + DiscoveryConfig discoveryConfig = new DiscoveryConfig(); + Map discovery = (Map) jsonUtil.toMap(configuration.get("discovery")); + discoveryConfig.setEndpoint(discovery.get("endpoint").toString()); + discoveryConfig.setEdc((DiscoveryConfig.EDCConfig) jsonUtil.bindObject(discovery.get("edc"), DiscoveryConfig.EDCConfig.class)); + discoveryConfig.setBpn((DiscoveryConfig.BPNConfig) jsonUtil.bindObject(discovery.get("bpn"), DiscoveryConfig.BPNConfig.class)); + return discoveryConfig; + } + + private MockEnvironment initEnv() { + MockEnvironment env = new MockEnvironment(); + Map edc = (Map) jsonUtil.toMap(configuration.get("edc")); + env.setProperty("configuration.edc.endpoint", edc.get("endpoint").toString()); + env.setProperty("configuration.edc.catalog", edc.get("catalog").toString()); + env.setProperty("configuration.edc.management", edc.get("management").toString()); + env.setProperty("configuration.edc.negotiation", edc.get("negotiation").toString()); + env.setProperty("configuration.edc.transfer", edc.get("transfer").toString()); + + Map keycloak = (Map) jsonUtil.toMap(configuration.get("keycloak")); + env.setProperty("configuration.keycloak.tokenUri", keycloak.get("tokenUri").toString()); + env.setProperty("configuration.keycloak.userInfoUri", keycloak.get("userInfoUri").toString()); + + return env; + } + + @Test + @Order(1) + void createNotAuthorizedResponse() { + Response response = contractController.create(null); + + assertEquals(401, response.getStatus()); + assertEquals("Not Authorized", response.getStatusText()); + } + @Test + void createBadRequestMissingMandatoryParametersResponse() { + String token = authService.getToken().getAccessToken(); + when(httpRequest.getHeader("Authorization")).thenReturn("Bearer " + token); + + Response response = contractController.create(new DiscoverySearch()); + + assertEquals(400, response.getStatus()); + assertEquals("Bad Request", response.getStatusText()); + assertEquals("One or all the mandatory parameters [id] are missing", response.getMessage()); + } + + @Test + void createNotFoundBpnNumberResponse() { + + String token = authService.getToken().getAccessToken(); + when(httpRequest.getHeader("Authorization")).thenReturn("Bearer " + token); + + DiscoverySearch discoverySearch = new DiscoverySearch(); + discoverySearch.setId("XYZ78901"); + Response response = contractController.create(discoverySearch); + + assertEquals(404, response.getStatus()); + assertEquals("Not Found", response.getStatusText()); + assertEquals("Failed to get the bpn number from the discovery service", response.getMessage()); + + } + + @Test + void createInternalServerErrorCantStartProcess() { + + String token = authService.getToken().getAccessToken(); + when(httpRequest.getHeader("Authorization")).thenReturn("Bearer " + token); + BpnDiscovery.BpnEndpoint bpnDiscoveryEndpoint = new BpnDiscovery.BpnEndpoint(); + bpnDiscoveryEndpoint.setKey("bpn"); + bpnDiscoveryEndpoint.setResourceId(UUID.randomUUID().toString()); + bpnDiscoveryEndpoint.setType("TEST"); + bpnDiscoveryEndpoint.setValue("BPN00000"); + BpnDiscovery bpnDiscovery = new BpnDiscovery(new ArrayList<>(){{add(bpnDiscoveryEndpoint);}}); + + doReturn(List.of(bpnDiscovery)).when(catenaXService).getBpnDiscovery(anyString(), anyString()); + + + DiscoverySearch discoverySearch = new DiscoverySearch(); + discoverySearch.setId("XYZ78901"); + Response response = contractController.create(discoverySearch); + + LogUtil.printMessage(jsonUtil.toJson(response, true)); + + assertEquals(500, response.getStatus()); + assertEquals("Internal Server Error", response.getStatusText()); + assertEquals("It was not possible to create the process and search for the decentral digital twin registries", response.getMessage()); + + } + + @Test + @Order(2) + void searchNotAuthorizeResponse() { + Response response = contractController.search(null); + + assertEquals(401, response.getStatus()); + assertEquals("Not Authorized", response.getStatusText()); + } + + @Test + void searchBadRequestMissingMandatoryParametersResponse() { + String token = authService.getToken().getAccessToken(); + when(httpRequest.getHeader("Authorization")).thenReturn("Bearer " + token); + + Response response = contractController.search(new Search()); + + assertEquals(400, response.getStatus()); + assertEquals("Bad Request", response.getStatusText()); + assertEquals("One or all the mandatory parameters [id] are missing", response.getMessage()); + } + + @Test + void searchBadRequestProcessIdNullResponse() { + + String token = authService.getToken().getAccessToken(); + when(httpRequest.getHeader("Authorization")).thenReturn("Bearer " + token); + + Search search = new Search(); + search.setId("XYZ78901"); + Response response = contractController.search(search); + + assertEquals(400, response.getStatus()); + assertEquals("Bad Request", response.getStatusText()); + assertEquals("No processId was found on the request body!", response.getMessage()); + + } + + @Test + void searchBadRequestProcessIdEmptyResponse() { + + String token = authService.getToken().getAccessToken(); + when(httpRequest.getHeader("Authorization")).thenReturn("Bearer " + token); + + Search search = new Search(); + search.setId("XYZ78901"); + search.setProcessId(""); + Response response = contractController.search(search); + + assertEquals(400, response.getStatus()); + assertEquals("Bad Request", response.getStatusText()); + assertEquals("Process id is required for decentral digital twin registry searches!", response.getMessage()); + + } + + @Test + void searchBadRequestSearchStatusDoesNotExistResponse() { + + String token = authService.getToken().getAccessToken(); + when(httpRequest.getHeader("Authorization")).thenReturn("Bearer " + token); + + Search search = new Search(); + search.setId("XYZ78901"); + search.setProcessId(UUID.randomUUID().toString()); + Response response = contractController.search(search); + + LogUtil.printMessage(jsonUtil.toJson(response, true)); + + assertEquals(400, response.getStatus()); + assertEquals("Bad Request", response.getStatusText()); + assertEquals("The searchStatus id does not exists!", response.getMessage()); + + } + + @Test + @Order(3) + void statusNotAuthorizeResponse() { + Response response = contractController.status(null); + + assertEquals(401, response.getStatus()); + assertEquals("Not Authorized", response.getStatusText()); + } + + @Test + void statusBadRequestProcessIdDoesNotExistResponse() { + + String token = authService.getToken().getAccessToken(); + when(httpRequest.getHeader("Authorization")).thenReturn("Bearer " + token); + doReturn(new ProcessDataModel()).when(processManager).loadDataModel(httpRequest); + + Response response = contractController.status(UUID.randomUUID().toString()); + + assertEquals(400, response.getStatus()); + assertEquals("Bad Request", response.getStatusText()); + assertEquals("The process id does not exists!", response.getMessage()); + } + + @Test + @Order(4) + void cancelNotAuthorizeResponse() { + Response response = contractController.cancel(null); + + assertEquals(401, response.getStatus()); + assertEquals("Not Authorized", response.getStatusText()); + } + + @Test + void cancelBadRequestMissingMandatoryParametersResponse() { + String token = authService.getToken().getAccessToken(); + when(httpRequest.getHeader("Authorization")).thenReturn("Bearer " + token); + + Response response = contractController.cancel(new TokenRequest()); + + assertEquals(400, response.getStatus()); + assertEquals("Bad Request", response.getStatusText()); + assertEquals("One or all the mandatory parameters [processId, contractId, token] are missing", response.getMessage()); + } + + @Test + void cancelForbiddenContractDeclineResponse() { + String statusStr = "contract-decline"; + String token = authService.getToken().getAccessToken(); + when(httpRequest.getHeader("Authorization")).thenReturn("Bearer " + token); + + Status status = new Status(); + status.setHistory(new HashMap<>()); + status.setHistory(statusStr, new History("id", statusStr, DateTimeUtil.getTimestamp())); + doReturn(true).when(processManager).checkProcess(eq(httpRequest), anyString()); + doReturn(new Process()).when(processManager).getProcess(eq(httpRequest), anyString()); + doReturn(status).when(processManager).getStatus(anyString()); + + TokenRequest requestToken = new TokenRequest(); + requestToken.setContractId(UUID.randomUUID().toString()); + requestToken.setProcessId(UUID.randomUUID().toString()); + requestToken.setToken(UUID.randomUUID().toString()); + + Response response = contractController.cancel(requestToken); + + assertEquals(403, response.getStatus()); + assertEquals("Forbidden", response.getStatusText()); + assertEquals("This contract was declined! Please request a new one", response.getMessage()); + } + + @Test + void cancelForbiddenNegotiationCanceledResponse() { + String statusStr = "negotiation-canceled"; + String token = authService.getToken().getAccessToken(); + when(httpRequest.getHeader("Authorization")).thenReturn("Bearer " + token); + + Status status = new Status(); + status.setHistory(new HashMap<>()); + status.setHistory(statusStr, new History("id", statusStr, DateTimeUtil.getTimestamp())); + doReturn(true).when(processManager).checkProcess(eq(httpRequest), anyString()); + doReturn(new Process()).when(processManager).getProcess(eq(httpRequest), anyString()); + doReturn(status).when(processManager).getStatus(anyString()); + + TokenRequest requestToken = new TokenRequest(); + requestToken.setContractId(UUID.randomUUID().toString()); + requestToken.setProcessId(UUID.randomUUID().toString()); + requestToken.setToken(UUID.randomUUID().toString()); + + Response response = contractController.cancel(requestToken); + + assertEquals(403, response.getStatus()); + assertEquals("Forbidden", response.getStatusText()); + assertEquals("This negotiation has already been canceled! Please request a new one", response.getMessage()); + } + + @Test + void cancelBadRequestNoContractResponse() { + String token = authService.getToken().getAccessToken(); + when(httpRequest.getHeader("Authorization")).thenReturn("Bearer " + token); + + Status status = new Status(); + status.setHistory(new HashMap<>()); + doReturn(true).when(processManager).checkProcess(eq(httpRequest), anyString()); + doReturn(new Process()).when(processManager).getProcess(eq(httpRequest), anyString()); + doReturn(status).when(processManager).getStatus(anyString()); + + TokenRequest requestToken = new TokenRequest(); + requestToken.setContractId(UUID.randomUUID().toString()); + requestToken.setProcessId(UUID.randomUUID().toString()); + requestToken.setToken(UUID.randomUUID().toString()); + + Response response = contractController.cancel(requestToken); + + LogUtil.printMessage(jsonUtil.toJson(response, true)); + + assertEquals(400, response.getStatus()); + assertEquals("Bad Request", response.getStatusText()); + assertEquals("No contract is available!", response.getMessage()); + } + + + @Test + @Order(5) + void signNotAuthorizeResponse() { + Response response = contractController.sign(null); + + assertEquals(401, response.getStatus()); + assertEquals("Not Authorized", response.getStatusText()); + } + + @Test + void signBadRequestMissingMandatoryParametersResponse() { + String token = authService.getToken().getAccessToken(); + when(httpRequest.getHeader("Authorization")).thenReturn("Bearer " + token); + + Response response = contractController.sign(new TokenRequest()); + + assertEquals(400, response.getStatus()); + assertEquals("Bad Request", response.getStatusText()); + assertEquals("One or all the mandatory parameters [processId, contractId, token] are missing", response.getMessage()); + } + + @Test + void cancelForbiddenContractSignedResponse() { + String statusStr = "contract-signed"; + String token = authService.getToken().getAccessToken(); + when(httpRequest.getHeader("Authorization")).thenReturn("Bearer " + token); + + Status status = new Status(); + status.setHistory(new HashMap<>()); + status.setHistory(statusStr, new History("id", statusStr, DateTimeUtil.getTimestamp())); + doReturn(true).when(processManager).checkProcess(eq(httpRequest), anyString()); + doReturn(new Process()).when(processManager).getProcess(eq(httpRequest), anyString()); + doReturn(status).when(processManager).getStatus(anyString()); + + TokenRequest requestToken = new TokenRequest(); + requestToken.setContractId(UUID.randomUUID().toString()); + requestToken.setProcessId(UUID.randomUUID().toString()); + requestToken.setToken(UUID.randomUUID().toString()); + + Response response = contractController.sign(requestToken); + + assertEquals(403, response.getStatus()); + assertEquals("Forbidden", response.getStatusText()); + assertEquals("This contract is already signed!", response.getMessage()); + } +} diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/DtrSearchManagerTest.java b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/DtrSearchManagerTest.java index 0aa628594..9f9250b17 100644 --- a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/DtrSearchManagerTest.java +++ b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/DtrSearchManagerTest.java @@ -1,44 +1,227 @@ package org.eclipse.tractusx.productpass.managers; +import org.eclipse.tractusx.productpass.config.DtrConfig; +import org.eclipse.tractusx.productpass.config.ProcessConfig; +import org.eclipse.tractusx.productpass.config.VaultConfig; +import org.eclipse.tractusx.productpass.exceptions.ServiceInitializationException; +import org.eclipse.tractusx.productpass.models.catenax.Dtr; +import org.eclipse.tractusx.productpass.models.manager.SearchStatus; +import org.eclipse.tractusx.productpass.models.negotiation.Catalog; +import org.eclipse.tractusx.productpass.services.DataTransferService; +import org.eclipse.tractusx.productpass.services.VaultService; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.core.env.Environment; +import org.springframework.mock.env.MockEnvironment; +import org.springframework.test.util.ReflectionTestUtils; +import utils.*; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.when; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) class DtrSearchManagerTest { - @Test - void getState() { + private DtrSearchManager dtrSearchManager; + private final String testAssetPath = "/src/test/resources/dpp/assets/TestAsset.json"; + @Mock + private ProcessManager processManager; + @Mock + private DataTransferService dataTransferService; + @Mock + private DtrConfig dtrConfig; + @Mock + Environment env; + @Mock + private FileUtil fileUtil; + @Mock + private JsonUtil jsonUtil; + + @BeforeAll + void setUpAll() { + fileUtil = new FileUtil(); + jsonUtil = new JsonUtil(fileUtil); + dtrConfig = initDtrConfig(); + env = Mockito.mock(Environment.class); + HttpUtil httpUtil = new HttpUtil(env); + dataTransferService = Mockito.mock(DataTransferService.class); + ProcessConfig processConfig = new ProcessConfig(); + processConfig.setDir("process"); + processManager = new ProcessManager(httpUtil, jsonUtil, fileUtil, processConfig); + dtrSearchManager = new DtrSearchManager(fileUtil, jsonUtil, dataTransferService, dtrConfig, processManager); + + fileUtil.deleteFile(dtrSearchManager.getDataModelPath()); + dtrSearchManager.loadDataModel(); + + when(dtrConfig.getTemporaryStorage().getEnabled()).thenReturn(true); } - @Test - void setState() { + private DtrConfig initDtrConfig() { + DtrConfig dtrConfig = new DtrConfig(); + /*dtrConfig.setAssetType("data.core.digitalTwinRegistry"); + dtrConfig.setEndpointInterface("SUBMODEL-3.0"); + dtrConfig.setDspEndpointKey("dspEndpoint"); + dtrConfig.setInternalDtr("https://materialpass.int.demo.catena-x.net/BPNL000000000000"); + dtrConfig.setSemanticIdTypeKey("Submodel"); + DtrConfig.DecentralApis decentralApis = new DtrConfig.DecentralApis(); + decentralApis.setSearch("/lookup/shells"); + decentralApis.setDigitalTwin("/shell-descriptors"); + decentralApis.setSubModel("/submodel-descriptors"); + dtrConfig.setDecentralApis(decentralApis);*/ + DtrConfig.Timeouts timeouts = new DtrConfig.Timeouts(); + timeouts.setSearch(10); + timeouts.setNegotiation(40); + timeouts.setTransfer(10); + timeouts.setDigitalTwin(20); + dtrConfig.setTimeouts(timeouts); + dtrConfig.setTemporaryStorage(new DtrConfig.TemporaryStorage(true, 12)); + + return dtrConfig; } @Test void createDataModelFile() { - } + Map> initialDtrDataModel = dtrSearchManager.getDtrDataModel(); - @Test - void getDataModelPath() { + assertTrue(initialDtrDataModel.isEmpty()); + + String dtrDataModelPath = dtrSearchManager.createDataModelFile(); + Map> newDtrDataModel = dtrSearchManager.getDtrDataModel(); + + assertNotNull(dtrDataModelPath); + assertNotNull(newDtrDataModel); + assertTrue(newDtrDataModel.isEmpty()); } @Test - void getDataModelDir() { + void addConnectionToBpnEntry() { + Map> initialDtrDataModel = dtrSearchManager.getDtrDataModel(); + + assertTrue(initialDtrDataModel.isEmpty()); + + String bpn = "BPN001"; + String contractId = UUID.randomUUID().toString(); + String assetId = UUID.randomUUID().toString(); + String endpoint = "dtr.endpoint"; + Long validUntil = DateTimeUtil.getTimestamp(); + Dtr newDtr = new Dtr(contractId, endpoint, assetId, bpn, validUntil); + + dtrSearchManager.addConnectionToBpnEntry(bpn, newDtr); + + ConcurrentHashMap> updatedDtrDataModel = dtrSearchManager.getDtrDataModel(); + Dtr updatedDtr = updatedDtrDataModel.get(bpn).get(0); + + assertEquals(1, updatedDtrDataModel.get(bpn).size()); + assertEquals(newDtr, updatedDtr); + assertEquals(bpn, updatedDtr.getBpn()); + assertEquals(contractId, updatedDtr.getContractId()); + assertEquals(assetId, updatedDtr.getAssetId()); + + dtrSearchManager.deleteBpns(dtrSearchManager.getDtrDataModel(), List.of(bpn)); + dtrSearchManager.saveDtrDataModel(); } @Test - void addConnectionToBpnEntry() { + void deleteBpns() { + int maxDtrs = 4; + int count = 0; + List bpnsList = new ArrayList<>(); + while (count < maxDtrs) { + String bpn = UUID.randomUUID().toString(); + String endpoint = UUID.randomUUID().toString(); + Dtr dtr = new Dtr(); + dtr.setBpn(bpn); + dtr.setEndpoint(endpoint); + bpnsList.add(bpn); + dtrSearchManager.addConnectionToBpnEntry(bpn, dtr); + ++count; + } + + ConcurrentHashMap> dtrDataModel = dtrSearchManager.getDtrDataModel(); + + assertEquals(4, dtrDataModel.size()); + + dtrSearchManager.deleteBpns(dtrDataModel, bpnsList); + + assertEquals(0 , dtrDataModel.size()); } @Test - void loadDataModel() { + void saveAndLoadDataModel() { + ConcurrentHashMap> dtrDataModel = dtrSearchManager.getDtrDataModel(); + + assertTrue(dtrDataModel.isEmpty()); + + String bpn1 = "BPN001"; + String contractId1 = UUID.randomUUID().toString(); + String assetId1 = UUID.randomUUID().toString(); + String endpoint1 = "dtr.endpoint1"; + Long validUntil1 = DateTimeUtil.getTimestamp(); + Dtr dtr1 = new Dtr(contractId1, endpoint1, assetId1, bpn1, validUntil1); + String bpn2 = "BPN002"; + String contractId2 = UUID.randomUUID().toString(); + String assetId2 = UUID.randomUUID().toString(); + String endpoint2 = "dtr.endpoint2"; + Long validUntil2 = DateTimeUtil.getTimestamp(); + Dtr dtr2 = new Dtr(contractId2, endpoint2, assetId2, bpn2, validUntil2); + String contractId3 = UUID.randomUUID().toString(); + String assetId3 = UUID.randomUUID().toString(); + String endpoint3 = "dtr.endpoint3"; + Long validUntil3 = DateTimeUtil.getTimestamp(); + Dtr dtr3 = new Dtr(contractId3, endpoint3, assetId3, bpn2, validUntil3); + + dtrSearchManager.addConnectionToBpnEntry(bpn1, dtr1); + dtrSearchManager.addConnectionToBpnEntry(bpn2, dtr2); + dtrSearchManager.addConnectionToBpnEntry(bpn2, dtr3); + dtrSearchManager.saveDtrDataModel(dtrDataModel); + dtrDataModel = dtrSearchManager.loadDataModel(); + + assertFalse(dtrDataModel.isEmpty()); + assertEquals(2, dtrDataModel.size()); + assertEquals(1, dtrDataModel.get(bpn1).size()); + assertEquals(2, dtrDataModel.get(bpn2).size()); + + dtrSearchManager.deleteBpns(dtrSearchManager.getDtrDataModel(), List.of(bpn1, bpn2)); + dtrSearchManager.saveDtrDataModel(); } @Test - void getDtrDataModel() { + void updateProcess() { //TODO + String bpn1 = "BPN001"; + String contractId1 = UUID.randomUUID().toString(); + String assetId1 = UUID.randomUUID().toString(); + String endpoint1 = "dtr.endpoint1"; + Long validUntil1 = DateTimeUtil.getTimestamp(); + Dtr dtr1 = new Dtr(contractId1, endpoint1, assetId1, bpn1, validUntil1); + } @Test - void saveDtrDataModel() { + void searchEndpoint() { //TODO + Object contractOffer = jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testAssetPath, Object.class); + Catalog catalog = new Catalog(); + catalog.setContractOffer(contractOffer); + String connectionUrl = "test.connection.url"; + when(dataTransferService.searchDigitalTwinCatalog(connectionUrl)).thenReturn(catalog); + String bpn = "BPN000001"; + String testProcessId = processManager.initProcess(); + + dtrSearchManager.searchEndpoint(testProcessId, bpn, connectionUrl); + + SearchStatus searchStatus = processManager.getSearchStatus(testProcessId); + + // assertEquals(bpn, searchStatus.getDtrs().get(0).getBpn()); + // assertEquals(connectionUrl, searchStatus.getDtrs().get(0).getEndpoint()); } } diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/ProcessDataModelTest.java b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/ProcessDataModelTest.java index d3b9574da..1f4a3647b 100644 --- a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/ProcessDataModelTest.java +++ b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/ProcessDataModelTest.java @@ -1,36 +1,110 @@ package org.eclipse.tractusx.productpass.managers; +import org.eclipse.tractusx.productpass.exceptions.DataModelException; +import org.eclipse.tractusx.productpass.models.manager.Process; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.Mock; + +import java.lang.reflect.UndeclaredThrowableException; +import java.util.HashMap; +import java.util.Map; import static org.junit.jupiter.api.Assertions.*; class ProcessDataModelTest { - @Test - void getDataModel() { + @Mock + private ProcessDataModel processDataModel; + @Mock + private Process testProcess; + + private final String processId = "1"; + private final String initProcessState = "INITIATED"; + + + @BeforeEach + void setUp() { + processDataModel = new ProcessDataModel(); + testProcess = new Process(processId, initProcessState); + processDataModel.setDataModel(new HashMap() {{ + put(processId, testProcess); + }}); } @Test - void setDataModel() { + void setAndGetDataModel() { + String newProcessId = "2"; + String newProcessState = "TEST"; + Process newProcess = new Process(newProcessId, newProcessState); + + Map initialMap = processDataModel.getDataModel(); + processDataModel.setDataModel(Map.of(processId, testProcess, newProcessId, newProcess)); + Map updatedMap = processDataModel.getDataModel(); + + //Initial Map tests + assertNotNull(initialMap); + assertTrue(initialMap.containsKey("1")); + assertEquals("1", initialMap.get(processId).getId()); + assertTrue(initialMap.size() == 1); + //Updated Map tests + assertNotNull(updatedMap); + assertTrue(updatedMap.containsKey("2")); + assertEquals("2", updatedMap.get(newProcessId).getId()); + assertTrue(updatedMap.size() == 2); } @Test - void addProcess() { + void addAndGetProcess() { + processDataModel.addProcess(testProcess); + + Process process = processDataModel.getProcess(processId); + assertNotNull(process); + assertEquals("1", process.getId()); + assertEquals("INITIATED", process.getState()); } @Test - void setState() { + void setAndGetState() { + String initialState = processDataModel.getState(processId); + processDataModel.setState(processId, "UPDATED"); + + String updatedState = processDataModel.getState(processId); + + assertEquals("INITIATED", initialState); + assertEquals("UPDATED", updatedState); + } + + @Test() + void setStateThrowsDataModelExceptionByNonexistentProcessId() { + Throwable exception = assertThrows(DataModelException.class, () -> processDataModel.setState("100", "TEST")); + assertEquals("[org.eclipse.tractusx.productpass.managers.ProcessDataModel] The process does not exists!", exception.getMessage()); } @Test - void getState() { + void processExists() { + assertTrue(processDataModel.processExists(processId)); + assertFalse(processDataModel.processExists("100")); } @Test - void getProcess() { + void startProcessSuccessfully() { + processDataModel.startProcess(processId, new Runnable() { + @Override + public void run() {} + }); + Process process = processDataModel.getProcess(processId); + assertNotNull(process); + assertEquals("RUNNING", process.getState()); } @Test - void processExists() { + void startProcessThrowsDataModelExceptionByNonexistentProcessId() { + Throwable exception = assertThrows(DataModelException.class, () -> processDataModel.startProcess("100", new Runnable() { + @Override + public void run() {} + })); + assertEquals("[org.eclipse.tractusx.productpass.managers.ProcessDataModel] It was not possible to start the process, " + + "[org.eclipse.tractusx.productpass.managers.ProcessDataModel] The process does not exists!", exception.getMessage()); } } diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/ProcessManagerTest.java b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/ProcessManagerTest.java index af7560333..c7335a105 100644 --- a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/ProcessManagerTest.java +++ b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/ProcessManagerTest.java @@ -1,64 +1,670 @@ package org.eclipse.tractusx.productpass.managers; -import org.junit.jupiter.api.Test; +import com.fasterxml.jackson.databind.JsonNode; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpSession; +import mocks.MockedHttpSession; +import org.eclipse.tractusx.productpass.config.ProcessConfig; +import org.eclipse.tractusx.productpass.exceptions.ManagerException; +import org.eclipse.tractusx.productpass.models.catenax.Dtr; +import org.eclipse.tractusx.productpass.models.dtregistry.DigitalTwin; +import org.eclipse.tractusx.productpass.models.edc.DataPlaneEndpoint; +import org.eclipse.tractusx.productpass.models.http.requests.Search; +import org.eclipse.tractusx.productpass.models.http.responses.IdResponse; +import org.eclipse.tractusx.productpass.models.irs.JobHistory; +import org.eclipse.tractusx.productpass.models.manager.History; +import org.eclipse.tractusx.productpass.models.manager.Process; +import org.eclipse.tractusx.productpass.models.manager.Status; +import org.eclipse.tractusx.productpass.models.negotiation.*; +import org.junit.jupiter.api.*; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.core.env.Environment; +import org.springframework.test.util.ReflectionTestUtils; +import utils.*; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static java.lang.Thread.sleep; import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.when; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@RunWith(MockitoJUnitRunner.class) class ProcessManagerTest { - @Test - void loadDataModel() { + private ProcessManager processManager; + private final String processDataModelName = "processDataModel"; + private String baseDataDirPath; + private Process testProcess; + private String testProcessId; + private List processIdDirToDelete; + private final String testPassportPath = "/src/test/resources/dpp/payloads/TestPassport.json"; + private final String testDigitalTwinPath = "/src/test/resources/dpp/digitaltwins/TestDigitalTwin.json"; + @Mock + Environment env; + @Mock + private HttpSession mockedHttpSession; + @Mock + private HttpUtil httpUtil; + private JsonUtil jsonUtil; + private FileUtil fileUtil; + @Mock + private ProcessConfig processConfig; + @Mock + private HttpServletRequest mockedHttpServletRequest; + + @BeforeAll + void setUpAll() { + env = Mockito.mock(Environment.class); + httpUtil = new HttpUtil(env); + fileUtil = new FileUtil(); + jsonUtil = new JsonUtil(fileUtil); + processConfig = new ProcessConfig(); + processConfig.setDir("process"); + processManager = new ProcessManager(httpUtil, jsonUtil, fileUtil, processConfig); + ReflectionTestUtils.setField(processManager, "env", env); + mockedHttpServletRequest = Mockito.mock(HttpServletRequest.class); + mockedHttpSession = new MockedHttpSession(); + baseDataDirPath = Path.of(fileUtil.getDataDir(), processConfig.getDir()).toString(); + } + + @BeforeEach + void setUp() { + when(mockedHttpServletRequest.getSession()).thenReturn(mockedHttpSession); + when(env.getProperty("passport.dataTransfer.encrypt", Boolean.class, true)).thenReturn(true); + when(env.getProperty("passport.dataTransfer.indent", Boolean.class, true)).thenReturn(true); + + processIdDirToDelete = new ArrayList<>(); + testProcessId = processManager.initProcess(); + processIdDirToDelete.add(testProcessId); + testProcess = processManager.createProcess(testProcessId, mockedHttpServletRequest); + } + + @AfterAll + void tearDownAll() { + for (String processIdToDelete : processIdDirToDelete) { + String dataDirPath = Path.of(baseDataDirPath, processIdToDelete).toString(); + try { + //Delete testProcessId dir from tmp directory + processManager.deleteSearchDir(processIdToDelete); + } catch (Exception e) { + //Delete testProcessId dir from data directory + if (fileUtil.pathExists(dataDirPath)) + fileUtil.deleteDir(dataDirPath); + continue; + } + //Delete testProcessId dir from data directory + fileUtil.deleteDir(dataDirPath); + } } @Test - void saveDataModel() { + void loadDataModel() { + ProcessDataModel processDataModel = processManager.loadDataModel(mockedHttpServletRequest); + assertNotNull(processDataModel); + + ProcessDataModel sessionProcessDataModel = (ProcessDataModel) mockedHttpSession.getAttribute(processDataModelName); + assertNotNull(sessionProcessDataModel); + + assertEquals(processDataModel, sessionProcessDataModel); } @Test - void getProcess() { + void saveDataModelAndGetProcess() { + ProcessDataModel initiatedProcessDataModel = processManager.loadDataModel(mockedHttpServletRequest); + + ProcessDataModel newProcessDataModel = new ProcessDataModel(); + newProcessDataModel.addProcess(testProcess); + processManager.saveDataModel(mockedHttpServletRequest, newProcessDataModel); + + assertNotEquals(initiatedProcessDataModel, newProcessDataModel); + assertEquals(testProcessId, processManager.getProcess(mockedHttpServletRequest, testProcessId).getId()); + assertEquals("CREATED", processManager.getProcess(mockedHttpServletRequest, testProcessId).getState()); + } @Test void generateStatusToken() { + String contractId = UUID.randomUUID().toString(); + String newContractId = UUID.randomUUID().toString(); + Status status = processManager.getStatus(testProcessId); + String testToken = processManager.generateStatusToken(status, contractId); + String equalTestToken = processManager.generateStatusToken(status, contractId); + String diffTestToken = processManager.generateStatusToken(status, newContractId); + + assertNotNull(testToken); + assertEquals(equalTestToken, testToken); + assertNotEquals(diffTestToken, testToken); } @Test void generateToken() { + String contractId = UUID.randomUUID().toString(); + String newContractId = UUID.randomUUID().toString(); + String testToken = processManager.generateToken(testProcess, contractId); + String equalTestToken = processManager.generateToken(testProcess, contractId); + String diffTestToken = processManager.generateToken(testProcess, newContractId); + + assertNotNull(testToken); + assertEquals(equalTestToken, testToken); + assertNotEquals(diffTestToken, testToken); } @Test - void checkProcess() { + void createProcess() { + String newProcessId = UUID.randomUUID().toString(); + processIdDirToDelete.add(newProcessId); + Process nullConnectorAddressProcess = processManager.createProcess(mockedHttpServletRequest); + processIdDirToDelete.add(nullConnectorAddressProcess.getId()); + Process connectorAddressProcess = processManager.createProcess(mockedHttpServletRequest, "testAddress"); + processIdDirToDelete.add(connectorAddressProcess.getId()); + Process processWithChildren = processManager.createProcess(newProcessId, true, mockedHttpServletRequest); + Process processWithBpn = processManager.createProcess(mockedHttpServletRequest, "100", "BPN00000"); + processIdDirToDelete.add("100"); + + assertNotNull(nullConnectorAddressProcess); + assertNotNull(connectorAddressProcess); + assertNotNull(processWithChildren); + + assertEquals("", processManager.getStatus(nullConnectorAddressProcess.getId()).getEndpoint()); + assertEquals("testAddress", processManager.getStatus(connectorAddressProcess.getId()).getEndpoint()); + assertEquals(true, processManager.getStatus(processWithChildren.getId()).getChildren()); + assertEquals("BPN00000", processManager.getStatus(processWithBpn.getId()).getBpn()); + } + + @Test + void getNullProcess() { + assertNull(processManager.getProcess(mockedHttpServletRequest, "1")); + } + + @Test + void getProcessThrowsManagerException() { + Throwable exception = assertThrows(ManagerException.class, () -> processManager.getProcess(null, null)); + assertEquals("[org.eclipse.tractusx.productpass.managers.ProcessManager] It was not possible to get process [null], " + + "[org.eclipse.tractusx.productpass.managers.ProcessManager] Failed to load Process DataModel!, " + + "Cannot invoke \"jakarta.servlet.http.HttpServletRequest.getSession()\" because \"httpRequest\" is null" + , exception.getMessage()); } @Test - void testCheckProcess() { + void checkProcess() { + String newProcessId = UUID.randomUUID().toString(); + processIdDirToDelete.add(newProcessId); + + //Check Process from HTTP request + assertTrue(processManager.checkProcess(mockedHttpServletRequest, testProcessId)); + assertFalse(processManager.checkProcess(mockedHttpServletRequest, newProcessId)); + + //Check Process from storage File + assertTrue(processManager.checkProcess(testProcessId)); + assertFalse(processManager.checkProcess(newProcessId)); } @Test - void startNegotiation() { + void checkProcessThrowsManagerException() { + Throwable exception = assertThrows(ManagerException.class, () -> processManager.checkProcess( null)); + assertEquals("[org.eclipse.tractusx.productpass.managers.ProcessManager] It was not possible to check if process exists [null], " + + "Cannot invoke \"String.isEmpty()\" because \"segment\" is null", exception.getMessage()); + + exception = assertThrows(ManagerException.class, () -> processManager.checkProcess( null,testProcessId)); + assertEquals("[org.eclipse.tractusx.productpass.managers.ProcessManager] It was not possible to check if process exists ["+ testProcessId +"], " + + "[org.eclipse.tractusx.productpass.managers.ProcessManager] Failed to load Process DataModel!, " + + "Cannot invoke \"jakarta.servlet.http.HttpServletRequest.getSession()\" because \"httpRequest\" is null", + exception.getMessage()); } @Test void setProcess() { + String newProcessId = UUID.randomUUID().toString(); + processIdDirToDelete.add(newProcessId); + Process newProcess = new Process(newProcessId, "NEW"); + Process nullProcess = processManager.getProcess(mockedHttpServletRequest, newProcessId); + processManager.setProcess(mockedHttpServletRequest, newProcess); + + Process process = processManager.getProcess(mockedHttpServletRequest, newProcessId); + + assertNull(nullProcess); + assertNotNull(process); + assertEquals(newProcessId, process.getId()); + assertEquals("NEW", process.getState()); + + } + @Test + void setProcessThrowsManagerException() { + Throwable exception = assertThrows(ManagerException.class, () -> processManager.setProcess(null, testProcess)); + assertEquals("[org.eclipse.tractusx.productpass.managers.ProcessManager] It was not possible to set process ["+testProcessId+"], " + + "[org.eclipse.tractusx.productpass.managers.ProcessManager] Failed to load Process DataModel!, " + + "Cannot invoke \"jakarta.servlet.http.HttpServletRequest.getSession()\" because \"httpRequest\" is null", + exception.getMessage()); } @Test - void setProcessState() { + void setAndGetProcessState() { + String newProcessState = "UPDATED"; + String initialStateProcess = processManager.getProcessState(mockedHttpServletRequest, testProcessId); + processManager.setProcessState(mockedHttpServletRequest, testProcessId, newProcessState); + String updatedProcess = processManager.getProcessState(mockedHttpServletRequest, testProcessId); + + assertNotEquals(initialStateProcess, updatedProcess); + assertEquals("CREATED", initialStateProcess); + assertEquals("UPDATED", updatedProcess); } @Test - void getProcessState() { + void setAndGetStatus() { + String historyId = "test-status"; + String status = "TEST"; + processManager.setStatus(testProcessId, historyId, new History(testProcessId, status)); + + Status updatedStatus = processManager.getStatus(testProcessId); + + assertEquals(status, updatedStatus.getHistory(historyId).getStatus()); + assertEquals(testProcessId, updatedStatus.getHistory(historyId).getId()); } @Test - void createProcess() { + void setStatusThrowsManagerException() { + Throwable exception = assertThrows(ManagerException.class, () -> processManager.setStatus(null, null, null)); + assertEquals("[org.eclipse.tractusx.productpass.managers.ProcessManager] It was not possible to create/update the status file, " + + "Cannot invoke \"String.isEmpty()\" because \"segment\" is null", exception.getMessage()); } @Test - void testCreateProcess() { + void setBpn() { + String inititalBpn = processManager.getStatus(testProcessId).getBpn(); + String updatedBpn = "BPN000000000"; + processManager.setBpn(testProcessId, updatedBpn); + + Status updatedStatus = processManager.getStatus(testProcessId); + + assertEquals("", inititalBpn); + assertEquals(updatedBpn, updatedStatus.getBpn()); + } + + @Test + void setTreeState() { + String inititalTreeState = processManager.getStatus(testProcessId).getBpn(); + String updatedTreeState = "father/children1"; + processManager.setTreeState(testProcessId, updatedTreeState); + + Status updatedStatus = processManager.getStatus(testProcessId); + + assertEquals("", inititalTreeState); + assertEquals(updatedTreeState, updatedStatus.getTreeState()); + } + + @Test + void setJobHistory() { + String inititalJobHistoryId = processManager.getStatus(testProcessId).getJob().getJobId(); + + String jobHistoryId = UUID.randomUUID().toString(); + String searchId = UUID.randomUUID().toString(); + String globalAssetId = UUID.randomUUID().toString(); + JobHistory updateJobHistory = new JobHistory(); + updateJobHistory.setJobId(jobHistoryId); + updateJobHistory.setSearchId(searchId); + updateJobHistory.setGlobalAssetId(globalAssetId); + updateJobHistory.setChildren(2); + + processManager.setJobHistory(testProcessId, updateJobHistory); + + Status updatedJobHistory = processManager.getStatus(testProcessId); + + assertNull(inititalJobHistoryId); + assertEquals(jobHistoryId, updatedJobHistory.getJob().getJobId()); + assertEquals(searchId, updatedJobHistory.getJob().getSearchId()); + assertEquals(globalAssetId, updatedJobHistory.getJob().getGlobalAssetId()); + assertEquals(2, updatedJobHistory.getJob().getChildren()); + + //Test Job Children Found method + processManager.setJobChildrenFound(testProcessId, 4); + updatedJobHistory = processManager.getStatus(testProcessId); + assertEquals(4, updatedJobHistory.getJob().getChildren()); + } + + @Test + void setSemanticIdAndEndpoint() { + String inititalSemanticId = processManager.getStatus(testProcessId).getSemanticId(); + String initialEndpoint = processManager.getStatus(testProcessId).getEndpoint(); + String updatedSemanticId = "test:1.0.0$SemanticIdTest"; + String updatedEndpoint = "test.com"; + processManager.setSemanticId(testProcessId, updatedSemanticId); + processManager.setEndpoint(testProcessId, updatedEndpoint); + + Status updatedStatus = processManager.getStatus(testProcessId); + + //SemanticId Tests + assertEquals("", inititalSemanticId); + assertEquals(updatedSemanticId, updatedStatus.getSemanticId()); + //Endpoint Tests + assertEquals("", initialEndpoint); + assertEquals(updatedEndpoint, updatedStatus.getEndpoint()); + } + + @Test + void setSearchAndGetSearchStatus() { + Search initialSearch = processManager.getSearchStatus(testProcessId).getSearch(); + String searchId = UUID.randomUUID().toString(); + Search updateSearch = new Search(); + updateSearch.setProcessId(testProcessId); + updateSearch.setId(searchId); + updateSearch.setIdType("testType"); + + processManager.setSearch(testProcessId, updateSearch); + Search getUpdatedSearch = processManager.getSearchStatus(testProcessId).getSearch(); + + assertNull(initialSearch); + assertEquals(searchId, getUpdatedSearch.getId()); + assertEquals(testProcessId, getUpdatedSearch.getProcessId()); + assertEquals("testType", getUpdatedSearch.getIdType()); } @Test void deleteSearchDir() { + String processId = processManager.initProcess(); + processIdDirToDelete.add(processId); + + assertTrue(processManager.deleteSearchDir(processId)); + } + + @Test + void deleteSearchDirThrowsManagerException() { + Throwable exception = assertThrows(ManagerException.class, () -> processManager.deleteSearchDir("1000")); + assertEquals("[org.eclipse.tractusx.productpass.managers.ProcessManager] It was not possible to create/update the search in search status file, " + + "[org.eclipse.tractusx.productpass.managers.ProcessManager] Temporary process file does not exists for id [1000]!" + , exception.getMessage()); + } + + @Test + void addSearchStatusDtr() { + int initialDtrCount = processManager.getSearchStatus(testProcessId).getDtrs().size(); + String contractId = UUID.randomUUID().toString(); + String assetId = UUID.randomUUID().toString(); + String endpoint = "dtr.endpoint"; + String bpn = "BPN01"; + Long validUntil = DateTimeUtil.getTimestamp(); + Dtr newDtr = new Dtr(contractId, endpoint, assetId, bpn, validUntil); + + processManager.addSearchStatusDtr(testProcessId, newDtr); + + Dtr updatedDtr = processManager.getSearchStatus(testProcessId).getDtr(CrypUtil.md5(endpoint)); + + assertEquals(0, initialDtrCount); + + assertEquals(1, processManager.getSearchStatus(testProcessId).getDtrs().size()); + assertNotNull(updatedDtr); + assertEquals(contractId, updatedDtr.getContractId()); + assertEquals(assetId, updatedDtr.getAssetId()); + assertEquals(endpoint, updatedDtr.getEndpoint()); + assertEquals(bpn, updatedDtr.getBpn()); + assertEquals(validUntil, updatedDtr.getValidUntil()); + } + + @Test + void newStatusFile() { + Status initialStatus = processManager.getStatus(testProcessId); + String initialConnectorAddress = initialStatus.getEndpoint(); + boolean initialChildren = initialStatus.getChildren(); + long initialCreateTime = initialStatus.getCreated(); + + String newConnectorAddress = "test.connector.address"; + boolean newChildren = false; + long newCreateTime = DateTimeUtil.getTimestamp(); + processManager.newStatusFile(testProcessId, newConnectorAddress, newCreateTime, newChildren); + + Status updatedStatus = processManager.getStatus(testProcessId); + + assertNotEquals(initialConnectorAddress, updatedStatus.getEndpoint()); + assertNotEquals(initialChildren, updatedStatus.getChildren()); + assertNotEquals(initialCreateTime, updatedStatus.getCreated()); + + assertEquals(newConnectorAddress, updatedStatus.getEndpoint()); + assertEquals(newChildren, updatedStatus.getChildren()); + assertEquals(newCreateTime, updatedStatus.getCreated()); + } + + @Test + void saveTransferInfo() { + String connectorAddress = UUID.randomUUID().toString(); + String semanticId = UUID.randomUUID().toString(); + String dataPlaneUrl = "dataplane.url.endpoint"; + String bpn = "BPN01"; + boolean children = false; + + processManager.saveTransferInfo(testProcessId, connectorAddress, semanticId, dataPlaneUrl, bpn, children); + + Status updatedStatus = processManager.getStatus(testProcessId); + + assertEquals(connectorAddress, updatedStatus.getEndpoint()); + assertEquals(semanticId, updatedStatus.getSemanticId()); + assertEquals(dataPlaneUrl, updatedStatus.getDataPlaneUrl()); + assertEquals(bpn, updatedStatus.getBpn()); + assertEquals(children, updatedStatus.getChildren()); + } + + @Test + void saveNegotiationRequestAndNegotiation() { + NegotiationRequest negotiationRequest = new NegotiationRequest(); + String providerId = UUID.randomUUID().toString(); + String connectorId = UUID.randomUUID().toString(); + negotiationRequest.setProtocol("HTTP"); + negotiationRequest.setProviderId(providerId); + negotiationRequest.setConnectorAddress("connectorAddress"); + negotiationRequest.setConnectorId(connectorId); + + String negotiationId = UUID.randomUUID().toString(); + String contractAgreement = UUID.randomUUID().toString(); + Negotiation negotiation = new Negotiation(); + negotiation.setProtocol("HTTP"); + negotiation.setEdcType("edcType1"); + negotiation.setId(negotiationId); + negotiation.setState("NEGOTIATED"); + negotiation.setContractAgreementId(contractAgreement); + + Map initialNegotiation = processManager.loadNegotiation(testProcessId); + + assertNull(initialNegotiation); + + processManager.saveNegotiationRequest(testProcessId, negotiationRequest, new IdResponse(testProcessId, null), false); + + processManager.saveNegotiation(testProcessId, negotiation, false); + Map updatedNegotiation = processManager.loadNegotiation(testProcessId); + + assertFalse(updatedNegotiation.isEmpty()); + assertEquals(2, updatedNegotiation.size()); + + LogUtil.printTest("NEGOTIATION: " + jsonUtil.toJson(updatedNegotiation, true)); + + Map init = (Map) updatedNegotiation.get("init"); + NegotiationRequest updatedNegotiationRequest = (NegotiationRequest) jsonUtil.bindObject(init.get("request"), NegotiationRequest.class); + + assertEquals(providerId, updatedNegotiationRequest.getProviderId()); + assertEquals(connectorId, updatedNegotiationRequest.getConnectorId()); + assertEquals("HTTP", updatedNegotiationRequest.getProtocol()); + + Map get = (Map) updatedNegotiation.get("get"); + Negotiation updatedNegotiationObj = (Negotiation) jsonUtil.bindObject(get.get("response"), Negotiation.class); + + assertEquals(negotiationId, updatedNegotiationObj.getId()); + assertEquals("NEGOTIATED", updatedNegotiationObj.getState()); + assertEquals("HTTP", updatedNegotiationObj.getProtocol()); + assertEquals("edcType1", updatedNegotiationObj.getEdcType()); + } + + @Test + void cancelProcessAndSetDecline() { + processManager.startNegotiation(mockedHttpServletRequest, testProcessId, new Runnable() { + @Override + public void run() { + try { + while(true) { + LogUtil.printMessage("NEGOTIATING....!"); + sleep(1); + } + } catch (InterruptedException e) { + LogUtil.printMessage("PROCESS STOPED!"); + } + } + }); + Process process = processManager.getProcess(mockedHttpServletRequest, testProcessId); + + assertEquals("RUNNING", process.getState()); + + processManager.cancelProcess(mockedHttpServletRequest, testProcessId); + Status status = processManager.getStatus(testProcessId); + + assertEquals("CANCELLED", status.getStatus()); + + processManager.setDecline(mockedHttpServletRequest, testProcessId); + process = processManager.getProcess(mockedHttpServletRequest, testProcessId); + status = processManager.getStatus(testProcessId); + + assertEquals("ABORTED", process.getState()); + assertEquals("DECLINED", status.getStatus()); + } + + @Test + void setSigned() { + String contractId = UUID.randomUUID().toString(); + Long signedAt = DateTimeUtil.getTimestamp(); + processManager.setSigned(mockedHttpServletRequest, testProcessId, contractId, signedAt); + + Process process = processManager.getProcess(mockedHttpServletRequest, testProcessId); + History history = processManager.getStatus(testProcessId).getHistory("contract-signed"); + + assertEquals("STARTING", process.getState()); + assertEquals("SIGNED", history.getStatus()); + assertEquals(contractId, history.getId()); + assertEquals(signedAt, history.getStarted()); + } + + @Test + void saveAndLoadDataset() { + String assetId = UUID.randomUUID().toString(); + String datasetId = UUID.randomUUID().toString(); + Long started = DateTimeUtil.getTimestamp(); + Dataset dataset = new Dataset(); + dataset.setId(datasetId); + dataset.setAssetId(assetId); + dataset.setAssetName("TEST"); + + Dataset initialDataset = processManager.loadDataset(testProcessId); + + assertNull(initialDataset); + + processManager.saveDataset(testProcessId, dataset, started, false); + Dataset updatedDataset = processManager.loadDataset(testProcessId); + + assertNotNull(updatedDataset); + assertEquals(datasetId, updatedDataset.getId()); + assertEquals(assetId, updatedDataset.getAssetId()); + assertEquals("TEST", updatedDataset.getAssetName()); + } + + @Test + void saveTransferRequestAndTransfer() { + TransferRequest transferRequest = new TransferRequest(); + String contractId = UUID.randomUUID().toString(); + String assetId = UUID.randomUUID().toString(); + String connectorId = UUID.randomUUID().toString(); + transferRequest.setProtocol("HTTP"); + transferRequest.setContractId(contractId); + transferRequest.setAssetId(assetId); + transferRequest.setConnectorAddress("connectorAddress"); + transferRequest.setConnectorId(connectorId); + + String transferId = UUID.randomUUID().toString(); + Transfer transfer = new Transfer(); + transfer.setState("COMPLETED"); + transfer.setEdcType("edcType1"); + transfer.setId(transferId); + + Map initialTransfer = processManager.loadTransfer(testProcessId); + + assertNull(initialTransfer); + + processManager.saveTransferRequest(testProcessId, transferRequest, new IdResponse(testProcessId, null), false); + + processManager.saveTransfer(testProcessId, transfer, false); + Map updatedTransfer = processManager.loadTransfer(testProcessId); + + assertFalse(updatedTransfer.isEmpty()); + assertEquals(2, updatedTransfer.size()); + + LogUtil.printTest("TRANSFER: " + jsonUtil.toJson(updatedTransfer, true)); + + Map init = (Map) updatedTransfer.get("init"); + TransferRequest updatedTransferRequest = (TransferRequest) jsonUtil.bindObject(init.get("request"), TransferRequest.class); + + assertEquals(contractId, updatedTransferRequest.getContractId()); + assertEquals(connectorId, updatedTransferRequest.getConnectorId()); + assertEquals("HTTP", updatedTransferRequest.getProtocol()); + + Map get = (Map) updatedTransfer.get("get"); + Transfer updatedTransferObj = (Transfer) jsonUtil.bindObject(get.get("response"), Transfer.class); + + assertEquals(transferId, updatedTransferObj.getId()); + assertEquals("COMPLETED", updatedTransferObj.getState()); + assertEquals("edcType1", updatedTransferObj.getEdcType()); + } + + @Test + void getContractId() { + } + + + @Test + void loadPassportReturnsManagerException() { + Throwable exception = assertThrows(ManagerException.class, () -> processManager.loadPassport(testProcessId)); + assertEquals("[org.eclipse.tractusx.productpass.managers.ProcessManager] It was not possible to load the passport!, " + + "[org.eclipse.tractusx.productpass.managers.ProcessManager] Passport file " + + "[C:\\Environment\\gitRepository\\tx-digital-product-pass\\consumer-backend\\productpass\\data\\process\\" + testProcessId + "\\passport.json] not found!" + , exception.getMessage()); + + } + @Test + void saveAndLoadPassport() { + when(env.getProperty("passport.dataTransfer.encrypt", Boolean.class, true)).thenReturn(false); + + DataPlaneEndpoint dataPlaneEndpoint = new DataPlaneEndpoint(); + String id = UUID.randomUUID().toString(); + String authKey = UUID.randomUUID().toString(); + String contractId = UUID.randomUUID().toString(); + String authCode = processManager.generateToken(processManager.getProcess(mockedHttpServletRequest, testProcessId), contractId); + dataPlaneEndpoint.setId(id); + dataPlaneEndpoint.setEndpoint("passportEndpoint"); + dataPlaneEndpoint.setAuthCode(authCode); + dataPlaneEndpoint.setAuthKey(authKey); + + + JsonNode passport = (JsonNode) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testPassportPath, JsonNode.class); + + processManager.savePassport(testProcessId, dataPlaneEndpoint, passport); + + JsonNode loadedPassport = processManager.loadPassport(testProcessId); + Status status = processManager.getStatus(testProcessId); + + assertEquals(passport, loadedPassport); + assertEquals("RETRIEVED", status.getHistory("data-retrieved").getStatus()); + } + + @Test + void saveDigitalTwin() { + DigitalTwin digitalTwin = (DigitalTwin) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testDigitalTwinPath, DigitalTwin.class); + Long createdAt = DateTimeUtil.getTimestamp(); + + processManager.saveDigitalTwin(testProcessId, digitalTwin, createdAt); + + Status status = processManager.getStatus(testProcessId); + + assertEquals("READY", status.getHistory("digital-twin-request").getStatus()); + assertEquals(createdAt, status.getHistory("digital-twin-request").getStarted()); } } diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/TreeManagerTest.java b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/TreeManagerTest.java new file mode 100644 index 000000000..1c5cd77f2 --- /dev/null +++ b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/TreeManagerTest.java @@ -0,0 +1,211 @@ +package org.eclipse.tractusx.productpass.managers; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpSession; +import mocks.MockedHttpSession; +import org.eclipse.tractusx.productpass.config.IrsConfig; +import org.eclipse.tractusx.productpass.config.PassportConfig; +import org.eclipse.tractusx.productpass.config.ProcessConfig; +import org.eclipse.tractusx.productpass.models.irs.JobHistory; +import org.eclipse.tractusx.productpass.models.irs.JobResponse; +import org.eclipse.tractusx.productpass.models.manager.Node; +import org.eclipse.tractusx.productpass.models.manager.NodeComponent; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.core.env.Environment; +import utils.FileUtil; +import utils.HttpUtil; +import utils.JsonUtil; +import utils.YamlUtil; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.when; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class TreeManagerTest { + + private TreeManager treeManager; + private JobResponse testJobResponse; + private JobHistory testJobHistory; + private Map treeDataModel; + private final String testJobResposnsePath = "/src/test/resources/dpp/irs/TestJobResponse.json"; + private final String testJobHistoryPath = "/src/test/resources/dpp/irs/TestJobHistory.json"; + private final String testTreeDataModelPath = "/src/test/resources/dpp/irs/TestTreeDataModel.json"; + private String baseDataDirPath; + private String testProcessId; + private Map configuration; + @Mock + private HttpServletRequest request; + private HttpSession httpSession; + private IrsConfig irsConfig; + private PassportConfig passportConfig; + private ProcessConfig processConfig; + private ProcessManager processManager; + private FileUtil fileUtil; + private JsonUtil jsonUtil; + private HttpUtil httpUtil; + private YamlUtil yamlUtil; + @Mock + private Environment env; + + @BeforeAll + void setUpAll() { + MockitoAnnotations.openMocks(this); + + fileUtil = new FileUtil(); + yamlUtil = new YamlUtil(fileUtil); + jsonUtil = new JsonUtil(fileUtil); + + Map application = yamlUtil.readFile(FileUtil.getWorkdirPath() + "/src/main/resources/application.yml"); + configuration = (Map) jsonUtil.toMap(application.get("configuration")); + + httpUtil = Mockito.spy(new HttpUtil(env)); + httpSession = new MockedHttpSession(); + + when(request.getSession()).thenReturn(httpSession); + + irsConfig = initIrsConfig(); + Map passport = (Map) jsonUtil.toMap(configuration.get("passport")); + passportConfig = new PassportConfig(); + passportConfig.setSearchIdSchema(passport.get("searchIdSchema").toString()); + processConfig = new ProcessConfig(); + processConfig.setDir("process"); + baseDataDirPath = Path.of(fileUtil.getDataDir(), processConfig.getDir()).toString(); + + processManager = new ProcessManager(httpUtil,jsonUtil, fileUtil, processConfig); + + treeManager = new TreeManager(fileUtil, jsonUtil, processManager, irsConfig, passportConfig); + + testProcessId = processManager.initProcess(); + processManager.createProcess(testProcessId, request); + + testJobResponse = (JobResponse) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testJobResposnsePath, JobResponse.class); + testJobHistory = (JobHistory) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testJobHistoryPath, JobHistory.class); + treeDataModel = (Map) jsonUtil.toMap(jsonUtil.fromJsonFile(FileUtil.getWorkdirPath() + testTreeDataModelPath)); + } + + @AfterAll + void tearDownAll() { + String dataDirPath = Path.of(baseDataDirPath, testProcessId).toString(); + try { + //Delete testProcessId dir from tmp directory + processManager.deleteSearchDir(testProcessId); + } catch (Exception e) { + //Delete testProcessId dir from data directory + if (fileUtil.pathExists(dataDirPath)) + fileUtil.deleteDir(dataDirPath); + } + //Delete testProcessId dir from data directory + fileUtil.deleteDir(dataDirPath); + + } + + private IrsConfig initIrsConfig() { + Map irs = (Map) jsonUtil.toMap(configuration.get("irs")); + + IrsConfig irsConfig = new IrsConfig(); + irsConfig.setEnabled((Boolean) irs.get("enabled")); + irsConfig.setEndpoint(irs.get("endpoint").toString()); + irsConfig.setPaths((IrsConfig.Paths) jsonUtil.bindObject(irs.get("paths"), IrsConfig.Paths.class)); + irsConfig.setTree((IrsConfig.TreeConfig) jsonUtil.bindObject(irs.get("tree"), IrsConfig.TreeConfig.class)); + irsConfig.setCallbackUrl(irs.get("callbackUrl").toString()); + + return irsConfig; + } + + @Test + void getTreeFilePath() { + String treePath = treeManager.getTreeFilePath(testProcessId); + + assertNotNull(treePath); + assertTrue(treePath.contains(testProcessId)); + assertTrue(treePath.contains(irsConfig.getTree().getFileName())); + } + + @Test + void createTreeFile() { + String path = treeManager.createTreeFile(testProcessId); + + assertNotNull(path); + assertTrue(treeManager.treeExists(testProcessId)); + } + + @Test + void generateSearchId() { + String globalAssetId = UUID.randomUUID().toString(); + + String searchId = TreeManager.generateSearchId(testProcessId, globalAssetId); + + assertNotNull(searchId); + assertEquals(32, searchId.getBytes(StandardCharsets.UTF_8).length); + } + + @Test + void populateAndGetTree() { + + treeManager.createTreeFile(testProcessId); + processManager.setJobHistory(testProcessId, testJobHistory); + + String path = treeManager.populateTree(treeDataModel,testProcessId, testJobHistory, testJobResponse); + assertNotNull(path); + + Map treeMap = treeManager.getTree(testProcessId); + assertNotNull(treeMap); + + Node parent = (Node) jsonUtil.bindObject(treeMap.get("urn:uuid:efcb5f8d-f31c-4b1f-b090-9c878054554d"), Node.class); + assertNotNull(parent); + assertEquals("urn:uuid:82e78a83-3ddd-64c1-455d-8f7629833f17", parent.getId()); + assertEquals("Battery_BAT-XYZ789", parent.getIdShort()); + assertEquals("CX:XYZ78901:BAT-XYZ789", parent.getSearchId()); + + Node child = parent.getChild("urn:uuid:d8ec6acc-1ad7-47b4-bc7e-612122d9d552"); + assertNotNull(child); + assertEquals("urn:uuid:ace301f6-92c5-4623-a022-c2a30dfee0e2", child.getId()); + assertEquals("BatteryModule_EVMODULE-TRJ712", child.getIdShort()); + assertEquals("CX:XYZ78901:EVMODULE-TRJ712", child.getSearchId()); + } + + @Test + void getTreeComponents() { + treeManager.createTreeFile(testProcessId); + processManager.setJobHistory(testProcessId, testJobHistory); + + treeManager.populateTree(treeDataModel,testProcessId, testJobHistory, testJobResponse); + + List treeComponents = treeManager.getTreeComponents(testProcessId); + + assertNotNull(treeComponents); + assertEquals(1, treeComponents.size()); + + NodeComponent parent = treeComponents.get(0); + + assertNotNull(parent); + assertEquals("urn:uuid:efcb5f8d-f31c-4b1f-b090-9c878054554d", parent.getId()); + assertEquals("Battery_BAT-XYZ789", parent.getName()); + assertEquals("CX:XYZ78901:BAT-XYZ789", parent.getSearchId()); + + List children = parent.getChildren(); + + assertNotNull(children); + assertEquals(1, children.size()); + NodeComponent child = children.get(0); + + assertNotNull(child); + assertEquals("urn:uuid:d8ec6acc-1ad7-47b4-bc7e-612122d9d552", child.getId()); + assertEquals("BatteryModule_EVMODULE-TRJ712", child.getName()); + assertEquals("CX:XYZ78901:EVMODULE-TRJ712", child.getSearchId()); + + } + +} diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/AasServiceTest.java b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/AasServiceTest.java index f8c191f40..6de9bf74e 100644 --- a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/AasServiceTest.java +++ b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/AasServiceTest.java @@ -1,52 +1,255 @@ package org.eclipse.tractusx.productpass.services; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpSession; +import mocks.MockedHttpSession; +import org.bouncycastle.asn1.x509.GeneralName; +import org.eclipse.tractusx.productpass.config.DtrConfig; +import org.eclipse.tractusx.productpass.config.PassportConfig; +import org.eclipse.tractusx.productpass.config.ProcessConfig; +import org.eclipse.tractusx.productpass.exceptions.ServiceInitializationException; +import org.eclipse.tractusx.productpass.managers.DtrSearchManager; +import org.eclipse.tractusx.productpass.managers.ProcessManager; +import org.eclipse.tractusx.productpass.models.auth.JwtToken; +import org.eclipse.tractusx.productpass.models.catenax.Discovery; +import org.eclipse.tractusx.productpass.models.dtregistry.DigitalTwin; +import org.eclipse.tractusx.productpass.models.dtregistry.SubModel; +import org.eclipse.tractusx.productpass.models.edc.AssetSearch; +import org.eclipse.tractusx.productpass.models.edc.DataPlaneEndpoint; +import org.eclipse.tractusx.productpass.models.http.requests.Search; +import org.eclipse.tractusx.productpass.models.manager.History; +import org.eclipse.tractusx.productpass.models.manager.Status; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.mock.env.MockEnvironment; +import utils.*; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Map; +import java.util.UUID; import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.when; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) class AasServiceTest { - @Test - void searchDigitalTwin() { + private AasService aasService; + private Map configuration; + String mockedDigitalTwin; + private final String digitalTwinId = "365e6fbe-bb34-11ec-8422-0242ac120002"; + private final String semanticId = "urn:bamm:io.catenax.battery.battery_pass:3.0.1#BatteryPass"; + private final String testDigitalTwinPath = "/src/test/resources/dpp/digitaltwins/TestDigitalTwin.json"; + private String baseDataDirPath; + private String testProcessId; + @Mock + private Environment env; + private HttpUtil httpUtil; + private JsonUtil jsonUtil; + private FileUtil fileUtil; + private YamlUtil yamlUtil; + @Mock + private HttpServletRequest request; + @Mock + private HttpSession mockedHttpSession; + private AuthenticationService authenticationService; + private final String mockedTokenPath = "/src/test/resources/dpp/token/MockedToken.json"; + private JwtToken mockedToken; + @Mock + private VaultService vaultService; + private DtrConfig dtrConfig; + private ProcessConfig processConfig; + private PassportConfig passportConfig; + private DtrSearchManager dtrSearchManager; + private ProcessManager processManager; + private DataTransferService dataTransferService; + @BeforeAll + void setUpAll() throws ServiceInitializationException { + MockitoAnnotations.openMocks(this); + fileUtil = new FileUtil(); + jsonUtil = new JsonUtil(fileUtil); + yamlUtil = new YamlUtil(fileUtil); + + Map application = yamlUtil.readFile(FileUtil.getWorkdirPath() + "/src/main/resources/application.yml"); + configuration = (Map) jsonUtil.toMap(application.get("configuration")); + + env = initEnv(); + httpUtil = Mockito.spy(new HttpUtil(env)); + + + Map vaultConfig = yamlUtil.readFile(fileUtil.getDataDir() + "/VaultConfig/vault.token.yml"); + Map client = (Map) jsonUtil.toMap(vaultConfig.get("client")); + when(vaultService.getLocalSecret("client.id")).thenReturn(client.get("id").toString()); + when(vaultService.getLocalSecret("client.secret")).thenReturn(client.get("secret").toString()); + Map edc = (Map) jsonUtil.toMap(vaultConfig.get("edc")); + when(vaultService.getLocalSecret("edc.apiKey")).thenReturn(edc.get("apiKey").toString()); + when(vaultService.getLocalSecret("edc.participantId")).thenReturn(edc.get("participantId").toString()); + + dtrConfig = initDtrConfig(); + processConfig = new ProcessConfig(); + processConfig.setDir("process"); + baseDataDirPath = Path.of(fileUtil.getDataDir(), processConfig.getDir()).toString(); + processManager = new ProcessManager(httpUtil, jsonUtil, fileUtil, processConfig); + dtrSearchManager = new DtrSearchManager(fileUtil,jsonUtil, dataTransferService, dtrConfig, processManager); + dataTransferService = new DataTransferService(env, httpUtil, jsonUtil,vaultService, processManager, dtrConfig); + authenticationService = Mockito.spy(new AuthenticationService(vaultService, env, httpUtil, jsonUtil)); + mockedToken = (JwtToken) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + mockedTokenPath, JwtToken.class); + doReturn(mockedToken).when(authenticationService).getToken(); + + passportConfig = new PassportConfig(); + + aasService = new AasService(env, httpUtil, jsonUtil, authenticationService, dtrConfig, dtrSearchManager, processManager, dataTransferService, passportConfig); + + mockedDigitalTwin = jsonUtil.toJson(jsonUtil.fromJsonFile(FileUtil.getWorkdirPath() + testDigitalTwinPath), true); + testProcessId = processManager.initProcess(); + + mockedHttpSession = new MockedHttpSession(); + + doReturn(new ResponseEntity<>(new ArrayList(){{add(digitalTwinId);}}, HttpStatus.OK)) + .when(httpUtil).doGet(anyString(), eq(ArrayList.class), any(HttpHeaders.class), any(Map.class), eq(true), eq(false)); + + doReturn(new ResponseEntity<>(mockedDigitalTwin, HttpStatus.OK)) + .when(httpUtil).doGet(anyString(), eq(String.class), any(HttpHeaders.class), any(Map.class), eq(true), eq(false)); } - @Test - void getPathEndpoint() { + @AfterAll + void tearDownAll() { + String dataDirPath = Path.of(baseDataDirPath, testProcessId).toString(); + try { + //Delete testProcessId dir from tmp directory + processManager.deleteSearchDir(testProcessId); + } catch (Exception e) { + //Delete testProcessId dir from data directory + if (fileUtil.pathExists(dataDirPath)) + fileUtil.deleteDir(dataDirPath); + } + //Delete testProcessId dir from data directory + fileUtil.deleteDir(dataDirPath); } - @Test - void searchSubModelBySemanticId() { + private DtrConfig initDtrConfig() { + DtrConfig dtrConfig = new DtrConfig(); + DtrConfig.Timeouts timeouts = new DtrConfig.Timeouts(); + timeouts.setSearch(10); + timeouts.setNegotiation(40); + timeouts.setTransfer(10); + timeouts.setDigitalTwin(20); + dtrConfig.setTimeouts(timeouts); + dtrConfig.setTemporaryStorage(new DtrConfig.TemporaryStorage(true, 12)); + + Map dtr = (Map) jsonUtil.toMap(configuration.get("dtr")); + Map decentralApis = (Map) jsonUtil.toMap(dtr.get("decentralApis")); + DtrConfig.DecentralApis decentralApisObj = new DtrConfig.DecentralApis(); + decentralApisObj.setSearch(decentralApis.get("search").toString()); + decentralApisObj.setDigitalTwin(decentralApis.get("digitalTwin").toString()); + decentralApisObj.setSubModel(decentralApis.get("subModel").toString()); + dtrConfig.setDecentralApis(decentralApisObj); + + dtrConfig.setSemanticIdTypeKey(dtr.get("semanticIdTypeKey").toString()); + + return dtrConfig; } - @Test - void testSearchSubModelBySemanticId() { + private MockEnvironment initEnv() { + MockEnvironment env = new MockEnvironment(); + Map edc = (Map) jsonUtil.toMap(configuration.get("edc")); + env.setProperty("configuration.edc.endpoint", edc.get("endpoint").toString()); + env.setProperty("configuration.edc.catalog", edc.get("catalog").toString()); + env.setProperty("configuration.edc.management", edc.get("management").toString()); + env.setProperty("configuration.edc.negotiation", edc.get("negotiation").toString()); + env.setProperty("configuration.edc.transfer", edc.get("transfer").toString()); + + Map keycloak = (Map) jsonUtil.toMap(configuration.get("keycloak")); + env.setProperty("configuration.keycloak.tokenUri", keycloak.get("tokenUri").toString()); + env.setProperty("configuration.keycloak.userInfoUri", keycloak.get("userInfoUri").toString()); + + return env; } @Test - void getDigitalTwin() { + void searchAndGetDigitalTwin() { + DigitalTwin mockedDigitalTwinObj = (DigitalTwin) jsonUtil.bindObject(jsonUtil.toJsonNode(mockedDigitalTwin), DigitalTwin.class); + String assetType = "DigitalTwin"; + String assetId = digitalTwinId; + int position = 0; + + DigitalTwin digitalTwin = aasService.searchDigitalTwin(assetType, assetId, position, null, null); + + assertNotNull(digitalTwin); + assertEquals(digitalTwinId, digitalTwin.getIdentification()); + assertEquals(mockedDigitalTwinObj.getIdShort(), digitalTwin.getIdShort()); + assertEquals(mockedDigitalTwinObj.getGlobalAssetId(), digitalTwin.getGlobalAssetId()); } @Test - void getSubModelBySemanticId() { + void getPathEndpoint() { + String pathSearch = aasService.getPathEndpoint("search"); + assertEquals(dtrConfig.getDecentralApis().getSearch(), pathSearch); + + String pathDigitalTwin = aasService.getPathEndpoint("digitalTwin"); + assertEquals(dtrConfig.getDecentralApis().getDigitalTwin(), pathDigitalTwin); + + String pathSubmodel = aasService.getPathEndpoint("subModel"); + assertEquals(dtrConfig.getDecentralApis().getSubModel(), pathSubmodel); } @Test - void testGetSubModelBySemanticId() { + void searchAndGetSubModelBySemanticId() { + DigitalTwin mockedDigitalTwinObj = (DigitalTwin) jsonUtil.bindObject(jsonUtil.toJsonNode(mockedDigitalTwin), DigitalTwin.class); + + SubModel submodel = aasService.searchSubModelBySemanticId(mockedDigitalTwinObj, semanticId); + + assertNotNull(submodel); + assertEquals(semanticId, submodel.getSemanticId().getKeys().get(0).getValue()); + assertEquals(dtrConfig.getSemanticIdTypeKey(), submodel.getSemanticId().getKeys().get(0).getType()); + assertEquals(mockedDigitalTwinObj.getSubmodelDescriptors().get(0).getIdentification(), submodel.getIdentification()); } + @Test void getTokenHeader() { - } + HttpHeaders headers = aasService.getTokenHeader(null); - @Test - void getRegistryUrl() { + assertNotNull(headers); + assertEquals(1, headers.get("Authorization").size()); + assertTrue(headers.get("Authorization").get(0).contains("Bearer")); } + @Test void decentralDtrSearch() { - } + Search searchBody = new Search(); + searchBody.setProcessId(testProcessId); + searchBody.setId("IMR18650V1"); - @Test - void queryDigitalTwin() { + String historyId = "digital-twin-found"; + String historyStatus = "TEST"; + String endpoint = "test.endpoint"; + + + when(request.getSession()).thenReturn(mockedHttpSession); + + processManager.createProcess(testProcessId, request); + processManager.setEndpoint(testProcessId, endpoint); + processManager.setStatus(testProcessId, historyId, new History(testProcessId, historyStatus)); + AssetSearch result = aasService.decentralDtrSearch(testProcessId, searchBody); + + assertNotNull(result); + assertEquals(testProcessId, result.getAssetId()); + assertEquals(endpoint, result.getConnectorAddress()); } + } diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/AuthenticationServiceTest.java b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/AuthenticationServiceTest.java new file mode 100644 index 000000000..b10bf7e86 --- /dev/null +++ b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/AuthenticationServiceTest.java @@ -0,0 +1,102 @@ +package org.eclipse.tractusx.productpass.services; + +import com.fasterxml.jackson.databind.JsonNode; +import jakarta.servlet.http.HttpServletRequest; +import org.eclipse.tractusx.productpass.exceptions.ServiceInitializationException; +import org.eclipse.tractusx.productpass.models.auth.JwtToken; +import org.eclipse.tractusx.productpass.models.auth.UserInfo; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.core.env.Environment; +import utils.*; + +import java.util.Map; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.when; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class AuthenticationServiceTest { + + private AuthenticationService authenticationService; + private final String mockedTokenPath = "/src/test/resources/dpp/token/MockedToken.json"; + private final String mockedUserInfoPath = "/src/test/resources/dpp/token/MockedUserInfo.json"; + private JwtToken mockedToken; + private UserInfo mockedUserInfo; + @Mock + private VaultService vaultService; + @Mock + private Environment env; + private HttpUtil httpUtil; + private JsonUtil jsonUtil; + private YamlUtil yamlUtil; + private FileUtil fileUtil; + @Mock + private HttpServletRequest httpRequest; + + @BeforeAll + void setUpAll() throws ServiceInitializationException { + MockitoAnnotations.openMocks(this); + httpUtil = new HttpUtil(env); + fileUtil = new FileUtil(); + jsonUtil = new JsonUtil(fileUtil); + yamlUtil = new YamlUtil(fileUtil); + + Map application = yamlUtil.readFile(FileUtil.getWorkdirPath() + "/src/main/resources/application.yml"); + Map configuration = (Map) jsonUtil.toMap(application.get("configuration")); + Map keycloak = (Map) jsonUtil.toMap(configuration.get("keycloak")); + when(env.getProperty("configuration.keycloak.tokenUri", String.class, "")).thenReturn(keycloak.get("tokenUri").toString()); + when(env.getProperty("configuration.keycloak.userInfoUri", String.class, "")).thenReturn(keycloak.get("userInfoUri").toString()); + authenticationService = Mockito.spy(new AuthenticationService(vaultService, env, httpUtil, jsonUtil)); + + mockedToken = (JwtToken) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + mockedTokenPath, JwtToken.class); + mockedUserInfo = (UserInfo) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + mockedUserInfoPath, UserInfo.class); + doReturn(mockedToken).when(authenticationService).getToken(); + doReturn(mockedUserInfo).when(authenticationService).getUserInfo(mockedToken.getAccessToken()); + } + + @BeforeEach + void setUp() { + Map vaultConfig = yamlUtil.readFile(fileUtil.getDataDir() + "/VaultConfig/vault.token.yml"); + Map client = (Map) jsonUtil.toMap(vaultConfig.get("client")); + + when(vaultService.getLocalSecret("client.id")).thenReturn(client.get("id").toString()); + when(vaultService.getLocalSecret("client.secret")).thenReturn(client.get("secret").toString()); + } + + + @Test + void getToken() { + + JwtToken jwtToken = authenticationService.getToken(); + + assertNotNull(jwtToken); + assertNotNull(jwtToken.getAccessToken()); + assertFalse(jwtToken.getAccessToken().isEmpty()); + } + + @Test + void isAuthenticated() { + JwtToken jwtToken = authenticationService.getToken(); + + when(httpRequest.getHeader("Authorization")).thenReturn("Bearer " + jwtToken.getAccessToken()); + + assertTrue(authenticationService.isAuthenticated(httpRequest)); + } + + @Test + void getUserInfo() { + JwtToken jwtToken = authenticationService.getToken(); + + UserInfo userInfo = authenticationService.getUserInfo(jwtToken.getAccessToken()); + + assertNotNull(userInfo); + } +} diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/CatenaXServiceTest.java b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/CatenaXServiceTest.java index 84f16c9ae..0294251f1 100644 --- a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/CatenaXServiceTest.java +++ b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/CatenaXServiceTest.java @@ -1,60 +1,252 @@ package org.eclipse.tractusx.productpass.services; +import com.fasterxml.jackson.databind.JsonNode; +import org.eclipse.tractusx.productpass.config.DiscoveryConfig; +import org.eclipse.tractusx.productpass.config.DtrConfig; +import org.eclipse.tractusx.productpass.config.ProcessConfig; +import org.eclipse.tractusx.productpass.exceptions.ServiceInitializationException; +import org.eclipse.tractusx.productpass.managers.DtrSearchManager; +import org.eclipse.tractusx.productpass.managers.ProcessManager; +import org.eclipse.tractusx.productpass.models.auth.JwtToken; +import org.eclipse.tractusx.productpass.models.catenax.BpnDiscovery; +import org.eclipse.tractusx.productpass.models.catenax.Discovery; +import org.eclipse.tractusx.productpass.models.catenax.EdcDiscoveryEndpoint; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.mock.env.MockEnvironment; +import utils.*; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.when; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) class CatenaXServiceTest { - @Test - void addEndpoint() { + private CatenaXService catenaXService; + private Map configuration; + private DataTransferService dataTransferService; + private DtrSearchManager dtrSearchManager; + private AuthenticationService authenticationService; + private final String mockedTokenPath = "/src/test/resources/dpp/token/MockedToken.json"; + private JwtToken mockedToken; + private final String mockedDiscoveryEndpointsPath = "/src/test/resources/dpp/discovery/MockedDiscoveryEndpoints.json"; + @Mock + private VaultService vaultService; + private DtrConfig dtrConfig; + private DiscoveryConfig discoveryConfig; + private YamlUtil yamlUtil; + private JsonUtil jsonUtil; + + private HttpUtil httpUtil; + private FileUtil fileUtil; + @Mock + private Environment env; + private Discovery discovery; + + @BeforeAll + void setUpAll() throws ServiceInitializationException { + MockitoAnnotations.openMocks(this); + fileUtil = new FileUtil(); + yamlUtil = new YamlUtil(fileUtil); + jsonUtil = new JsonUtil(fileUtil); + + Map application = yamlUtil.readFile(FileUtil.getWorkdirPath() + "/src/main/resources/application.yml"); + configuration = (Map) jsonUtil.toMap(application.get("configuration")); + + env = initEnv(); + httpUtil = Mockito.spy(new HttpUtil(env)); + + Map vaultConfig = yamlUtil.readFile(fileUtil.getDataDir() + "/VaultConfig/vault.token.yml"); + Map client = (Map) jsonUtil.toMap(vaultConfig.get("client")); + when(vaultService.getLocalSecret("client.id")).thenReturn(client.get("id").toString()); + when(vaultService.getLocalSecret("client.secret")).thenReturn(client.get("secret").toString()); + Map edc = (Map) jsonUtil.toMap(vaultConfig.get("edc")); + when(vaultService.getLocalSecret("edc.apiKey")).thenReturn(edc.get("apiKey").toString()); + when(vaultService.getLocalSecret("edc.participantId")).thenReturn(edc.get("participantId").toString()); + + authenticationService = Mockito.spy(new AuthenticationService(vaultService, env, httpUtil, jsonUtil)); + + mockedToken = (JwtToken) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + mockedTokenPath, JwtToken.class); + doReturn(mockedToken).when(authenticationService).getToken(); + + ProcessConfig processConfig = new ProcessConfig(); + processConfig.setDir("process"); + ProcessManager processManager = new ProcessManager(httpUtil, jsonUtil, fileUtil, processConfig); + dataTransferService = new DataTransferService(env, httpUtil,jsonUtil, vaultService, processManager, dtrConfig); + + discoveryConfig = initDiscoveryConfig(); + dtrConfig = initDtrConfig(); + + dtrSearchManager = new DtrSearchManager(fileUtil, jsonUtil, dataTransferService, dtrConfig, processManager); + catenaXService = new CatenaXService(env, fileUtil, httpUtil, jsonUtil, vaultService, dtrSearchManager, authenticationService, discoveryConfig, dataTransferService, dtrConfig); + + discovery = new Discovery(new ArrayList<>()); + + when(vaultService.setLocalSecret(anyString(), any(List.class))).thenReturn(true); } - @Test - void getDiscoveryEndpoints() { - } + private MockEnvironment initEnv() { + MockEnvironment env = new MockEnvironment(); + Map edc = (Map) jsonUtil.toMap(configuration.get("edc")); + env.setProperty("configuration.edc.endpoint", edc.get("endpoint").toString()); + env.setProperty("configuration.edc.catalog", edc.get("catalog").toString()); + env.setProperty("configuration.edc.management", edc.get("management").toString()); + env.setProperty("configuration.edc.negotiation", edc.get("negotiation").toString()); + env.setProperty("configuration.edc.transfer", edc.get("transfer").toString()); - @Test - void getDiscoveryEndpoint() { - } + Map keycloak = (Map) jsonUtil.toMap(configuration.get("keycloak")); + env.setProperty("configuration.keycloak.tokenUri", keycloak.get("tokenUri").toString()); + env.setProperty("configuration.keycloak.userInfoUri", keycloak.get("userInfoUri").toString()); - @Test - void updateDiscovery() { + return env; } - - @Test - void updateDefaultDiscovery() { + private DiscoveryConfig initDiscoveryConfig() { + DiscoveryConfig discoveryConfig = new DiscoveryConfig(); + Map discovery = (Map) jsonUtil.toMap(configuration.get("discovery")); + discoveryConfig.setEndpoint(discovery.get("endpoint").toString()); + discoveryConfig.setEdc((DiscoveryConfig.EDCConfig) jsonUtil.bindObject(discovery.get("edc"), DiscoveryConfig.EDCConfig.class)); + discoveryConfig.setBpn((DiscoveryConfig.BPNConfig) jsonUtil.bindObject(discovery.get("bpn"), DiscoveryConfig.BPNConfig.class)); + return discoveryConfig; } - @Test - void updateEndpointFile() { + private DtrConfig initDtrConfig() { + DtrConfig dtrConfig = new DtrConfig(); + DtrConfig.Timeouts timeouts = new DtrConfig.Timeouts(); + timeouts.setSearch(10); + timeouts.setNegotiation(40); + timeouts.setTransfer(10); + timeouts.setDigitalTwin(20); + dtrConfig.setTimeouts(timeouts); + dtrConfig.setTemporaryStorage(new DtrConfig.TemporaryStorage(true, 12)); + + return dtrConfig; } @Test - void testUpdateEndpointFile() { - } + void getDiscoveryEndpoints() { + Discovery mockedDefaultDiscovery = (Discovery) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + mockedDiscoveryEndpointsPath, Discovery.class); - @Test - void updateDefaultDiscoveryFile() { - } + doReturn(new ResponseEntity<>(jsonUtil.toJsonNode(jsonUtil.toJson(mockedDefaultDiscovery, true)), HttpStatus.OK)) + .when(httpUtil).doPost(anyString(), eq(JsonNode.class), any(HttpHeaders.class), any(Map.class), any(Object.class), eq(false), eq(false)); - @Test - void testUpdateDefaultDiscoveryFile() { - } + Discovery defaultDiscovery = catenaXService.start(); - @Test - void testGetDiscoveryEndpoint() { + assertNotNull(defaultDiscovery); + assertEquals(2, defaultDiscovery.getEndpoints().size()); } - @Test - void testGetDiscoveryEndpoints() { + void addEndpoint() { + String edcKey = "manufacturerPartId"; + String edcResourceId = UUID.randomUUID().toString(); + Discovery.Endpoint edcEndpoint = new Discovery.Endpoint(); + edcEndpoint.setType(edcKey); + edcEndpoint.setEndpointAddress("test.edc.address"); + edcEndpoint.setResourceId(edcResourceId); + String bpnKey = "bpn"; + String bpnResourceId = UUID.randomUUID().toString(); + Discovery.Endpoint bpnEndpoint = new Discovery.Endpoint(); + bpnEndpoint.setType(bpnKey); + bpnEndpoint.setEndpointAddress("test..bpn.address"); + bpnEndpoint.setResourceId(bpnResourceId); + discovery.getEndpoints().add(edcEndpoint); + + doReturn(new ResponseEntity<>(jsonUtil.toJsonNode(jsonUtil.toJson(discovery, true)), HttpStatus.OK)) + .when(httpUtil).doPost(anyString(), eq(JsonNode.class), any(HttpHeaders.class), any(Map.class), any(Object.class), eq(false), eq(false)); + + Discovery discoveryUpdated = catenaXService.addEndpoint(edcKey); + + assertNotNull(discoveryUpdated); + assertEquals(3, discoveryUpdated.getEndpoints().size()); + + discovery.getEndpoints().add(bpnEndpoint); + discoveryUpdated = catenaXService.addEndpoint(bpnKey); + + assertNotNull(discoveryUpdated); + assertEquals(3, discoveryUpdated.getEndpoints().size()); } @Test void getEdcDiscovery() { + String bpn = UUID.randomUUID().toString(); + EdcDiscoveryEndpoint mockedEdcDiscoveryEndpoint = new EdcDiscoveryEndpoint(); + mockedEdcDiscoveryEndpoint.setBpn(bpn); + mockedEdcDiscoveryEndpoint.setConnectorEndpoint(List.of("test.endpoint")); + + when(vaultService.getLocalSecret(eq("discovery.edc"))).thenReturn(new ArrayList<>(){{add("test.endpoint");}}); + doReturn(new ResponseEntity<>(jsonUtil.toJsonNode(new ArrayList<>(){{add(mockedEdcDiscoveryEndpoint);}}), HttpStatus.OK)) + .when(httpUtil).doPost(anyString(), eq(JsonNode.class), any(HttpHeaders.class), any(Map.class), any(Object.class), eq(false), eq(false)); + + List edcDiscoveryEndpoints = catenaXService.getEdcDiscovery(List.of(bpn)); + + assertNotNull(edcDiscoveryEndpoints); + + EdcDiscoveryEndpoint edcDiscoveryEndpoint = (EdcDiscoveryEndpoint) jsonUtil.bindObject(edcDiscoveryEndpoints.get(0), EdcDiscoveryEndpoint.class); + + assertEquals(1, edcDiscoveryEndpoints.size()); + assertEquals(bpn, edcDiscoveryEndpoint.getBpn()); + assertEquals("test.endpoint", edcDiscoveryEndpoint.getConnectorEndpoint().get(0)); } @Test + @Order(4) void getBpnDiscovery() { + String edcKey = "manufacturerPartId"; + String edcResourceId = UUID.randomUUID().toString(); + Discovery.Endpoint edcEndpoint = new Discovery.Endpoint(); + edcEndpoint.setType(edcKey); + edcEndpoint.setEndpointAddress("test.edc.address"); + edcEndpoint.setResourceId(edcResourceId); + String bpnKey = "bpn"; + String bpnResourceId = UUID.randomUUID().toString(); + String bpn = "BPN00001"; + Discovery.Endpoint bpnEndpoint = new Discovery.Endpoint(); + bpnEndpoint.setType(bpnKey); + bpnEndpoint.setEndpointAddress("test.bpn.address"); + bpnEndpoint.setResourceId(bpnResourceId); + discovery.getEndpoints().add(edcEndpoint); + discovery.getEndpoints().add(bpnEndpoint); + + when(vaultService.getLocalSecret("discovery.bpn")).thenReturn(new ArrayList<>(){{add("test.endpoint");}}); + + Mockito.doAnswer(invocation -> { + Map> body = invocation.getArgument(4); + if (body.containsKey("types")) { + return new ResponseEntity<>(jsonUtil.toJsonNode(jsonUtil.toJson(discovery, true)), HttpStatus.OK); + } + BpnDiscovery.BpnEndpoint bpnDiscoveryEndpoint = new BpnDiscovery.BpnEndpoint(); + bpnDiscoveryEndpoint.setKey(bpnKey); + bpnDiscoveryEndpoint.setResourceId(bpnResourceId); + bpnDiscoveryEndpoint.setType("TEST"); + bpnDiscoveryEndpoint.setValue(bpn); + BpnDiscovery bpnDiscovery = new BpnDiscovery(new ArrayList<>(){{add(bpnDiscoveryEndpoint);}}); + return new ResponseEntity<>(jsonUtil.toJsonNode(jsonUtil.toJson(bpnDiscovery, true)), HttpStatus.OK); + }).when(httpUtil).doPost(anyString(), eq(JsonNode.class), any(HttpHeaders.class), any(Map.class), any(Object.class), eq(false), eq(false)); + + List bpnDiscoveryList = catenaXService.getBpnDiscovery(bpnResourceId, bpnKey); + + assertNotNull(bpnDiscoveryList); + + BpnDiscovery bpnDiscoveryEndpoint = (BpnDiscovery) jsonUtil.bindObject(bpnDiscoveryList.get(0), BpnDiscovery.class); + + assertEquals(1, bpnDiscoveryList.size()); + assertTrue(bpnDiscoveryEndpoint.getBpnNumbers().contains(bpn)); + assertEquals(bpnResourceId, bpnDiscoveryEndpoint.getBpns().get(0).getResourceId()); + } } diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/DataPlaneServiceTest.java b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/DataPlaneServiceTest.java index f3567519e..cc71f1575 100644 --- a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/DataPlaneServiceTest.java +++ b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/DataPlaneServiceTest.java @@ -1,16 +1,79 @@ package org.eclipse.tractusx.productpass.services; +import com.fasterxml.jackson.databind.JsonNode; +import org.eclipse.tractusx.productpass.exceptions.ServiceInitializationException; +import org.eclipse.tractusx.productpass.models.edc.DataPlaneEndpoint; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.util.ReflectionTestUtils; +import utils.FileUtil; +import utils.HttpUtil; +import utils.JsonUtil; + +import java.util.HashMap; +import java.util.UUID; import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.when; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) class DataPlaneServiceTest { - @Test - void getTransferData() { + private DataPlaneService dataPlaneService; + private final String testPassportPath = "/src/test/resources/dpp/payloads/TestPassport.json"; + @Mock + private HttpUtil httpUtil; + private JsonUtil jsonUtil; + + @BeforeAll + void setUpAll() throws ServiceInitializationException { + MockitoAnnotations.openMocks(this); + FileUtil fileUtil = new FileUtil(); + jsonUtil = new JsonUtil(fileUtil); + + dataPlaneService = new DataPlaneService(); + ReflectionTestUtils.setField(dataPlaneService, "httpUtil", httpUtil); + ReflectionTestUtils.setField(dataPlaneService, "jsonUtil", jsonUtil); + + when(httpUtil.getHeaders()).thenReturn(new HttpHeaders()); + when(httpUtil.getParams()).thenReturn(new HashMap<>()); + + when(httpUtil.doGet(anyString(), any(Class.class), any(HttpHeaders.class), any(), eq(true), eq(true))) + .then(invocation -> { + JsonNode passport = (JsonNode) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testPassportPath, JsonNode.class); + return new ResponseEntity<>(passport, HttpStatus.OK); + }); + } @Test - void getPassport() { + void getPassportFromEndpoint() { + String id = UUID.randomUUID().toString(); + String endpoint = UUID.randomUUID().toString(); + String authKey = UUID.randomUUID().toString(); + String authCode = UUID.randomUUID().toString(); + DataPlaneEndpoint dataPlaneEndpoint = new DataPlaneEndpoint(); + dataPlaneEndpoint.setId(id); + dataPlaneEndpoint.setEndpoint(endpoint); + dataPlaneEndpoint.setAuthKey(authKey); + dataPlaneEndpoint.setAuthCode(authCode); + String dataPLaneEndpointStr = "test.endpoint"; + + JsonNode passport = dataPlaneService.getPassportFromEndpoint(dataPlaneEndpoint, dataPLaneEndpointStr); + + assertNotNull(passport); + assertEquals("\"27.04.2022\"", passport.get("datePlacedOnMarket").toString()); + assertEquals("\"96\"", passport.get("warrantyPeriod").toString()); + assertEquals("210", passport.get("cO2FootprintTotal").toString()); } + } diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/DataTransferServiceTest.java b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/DataTransferServiceTest.java index c368c7ac1..ef1ddc6ad 100644 --- a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/DataTransferServiceTest.java +++ b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/DataTransferServiceTest.java @@ -1,64 +1,317 @@ package org.eclipse.tractusx.productpass.services; +import com.fasterxml.jackson.databind.JsonNode; +import org.eclipse.tractusx.productpass.config.DtrConfig; +import org.eclipse.tractusx.productpass.config.ProcessConfig; +import org.eclipse.tractusx.productpass.config.VaultConfig; +import org.eclipse.tractusx.productpass.exceptions.ServiceInitializationException; +import org.eclipse.tractusx.productpass.managers.ProcessManager; +import org.eclipse.tractusx.productpass.models.http.responses.IdResponse; +import org.eclipse.tractusx.productpass.models.manager.Status; +import org.eclipse.tractusx.productpass.models.negotiation.*; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.mock.env.MockEnvironment; +import utils.*; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.when; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) class DataTransferServiceTest { - @Test - void getContractOfferByAssetId() { - } + private DataTransferService dataTransferService; + private Dataset dataSet; + private Set policy; + private String bpn; + private final String testPolicyPath = "/src/test/resources/dpp/contractpolicies/TestPolicy.json"; + private final String testDTCatalogPath = "/src/test/resources/dpp/catalogs/TestDigitalTwinCatalog.json"; + private final String testCOCatalogPath = "/src/test/resources/dpp/catalogs/TestContractOfferCatalog.json"; + private final String testResponseInitNegotiationPath = "/src/test/resources/dpp/negotiation/TestResponseInitNegotiation.json"; + private final String testResponseNegotiationPath = "/src/test/resources/dpp/negotiation/TestResponseNegotiation.json"; + private final String testResponseInitTransferPath = "/src/test/resources/dpp/transfer/TestResponseInitTransfer.json"; + private final String testResponseTransferPath = "/src/test/resources/dpp/transfer/TestResponseTransfer.json"; + @Mock + private VaultService vaultService; + @Mock + private ProcessManager processManager; + @Mock + private DtrConfig dtrConfig; + @Mock + private Environment env; + @Mock + private HttpUtil httpUtil; + private JsonUtil jsonUtil; + private YamlUtil yamlUtil; + private FileUtil fileUtil; - @Test - void buildRequest() { - } + @BeforeAll + void setUpAll() throws ServiceInitializationException { + MockitoAnnotations.openMocks(this); + dtrConfig = initDtrConfig(); + fileUtil = new FileUtil(); + jsonUtil = new JsonUtil(fileUtil); + yamlUtil = new YamlUtil(fileUtil); + env = initEnv(); + Map vaultConfig = yamlUtil.readFile(fileUtil.getDataDir() + "/VaultConfig/vault.token.yml"); + Map edc = (Map) jsonUtil.toMap(vaultConfig.get("edc")); + when(vaultService.getLocalSecret("edc.apiKey")).thenReturn(edc.get("apiKey").toString()); + when(vaultService.getLocalSecret("edc.participantId")).thenReturn(edc.get("participantId").toString()); - @Test - void buildOffer() { + bpn = edc.get("participantId").toString(); + + ProcessConfig processConfig = new ProcessConfig(); + processConfig.setDir("process"); + processManager = new ProcessManager(httpUtil, jsonUtil, fileUtil, processConfig); + + dataTransferService = new DataTransferService(env, httpUtil,jsonUtil, vaultService, processManager, dtrConfig); + + when(httpUtil.getHeaders()).thenReturn(new HttpHeaders()); + when(httpUtil.getParams()).thenReturn(new HashMap<>()); } - @Test - void getContractOfferCatalog() { + @BeforeEach + void setUp() { + Set policy = (Set) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testPolicyPath, Set.class); + + Dataset dataSet = new Dataset(); + String dataSetId = UUID.randomUUID().toString(); + String assetId = UUID.randomUUID().toString(); + dataSet.setAssetName("TEST"); + dataSet.setId(dataSetId); + dataSet.setType("test-type"); + dataSet.setAssetId(assetId); + dataSet.setPolicy(List.of(policy)); + + this.dataSet = dataSet; + this.policy = policy; } - @Test - void searchDigitalTwinCatalog() { + private MockEnvironment initEnv() { + MockEnvironment env = new MockEnvironment(); + Map application = yamlUtil.readFile(FileUtil.getWorkdirPath() + "/src/main/resources/application.yml"); + Map configuration = (Map) jsonUtil.toMap(application.get("configuration")); + Map edc = (Map) jsonUtil.toMap(configuration.get("edc")); + env.setProperty("configuration.edc.endpoint", edc.get("endpoint").toString()); + env.setProperty("configuration.edc.catalog", edc.get("catalog").toString()); + env.setProperty("configuration.edc.management", edc.get("management").toString()); + env.setProperty("configuration.edc.negotiation", edc.get("negotiation").toString()); + env.setProperty("configuration.edc.transfer", edc.get("transfer").toString()); + + return env; } - @Test - void doContractNegotiation() { + private DtrConfig initDtrConfig() { + DtrConfig dtrConfig = new DtrConfig(); + DtrConfig.Timeouts timeouts = new DtrConfig.Timeouts(); + timeouts.setSearch(10); + timeouts.setNegotiation(40); + timeouts.setTransfer(10); + timeouts.setDigitalTwin(20); + dtrConfig.setTimeouts(timeouts); + dtrConfig.setTemporaryStorage(new DtrConfig.TemporaryStorage(true, 12)); + + return dtrConfig; } - @Test - void testDoContractNegotiation() { + private VaultConfig initVaultConfig() { + Map application = yamlUtil.readFile(FileUtil.getWorkdirPath() + "/src/main/resources/application.yml"); + Map configuration = (Map) jsonUtil.toMap(application.get("configuration")); + Map vault = (Map) jsonUtil.toMap(configuration.get("vault")); + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setFile(vault.get("file").toString()); + + return vaultConfig; } @Test - void seeNegotiation() { + void checkEdcConsumerConnection() { + when(httpUtil.doPost(anyString(), any(Class.class), any(HttpHeaders.class), any(Map.class), any(Object.class), eq(false), eq(false))) + .thenReturn(new ResponseEntity<>(jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testCOCatalogPath, JsonNode.class), HttpStatus.OK)); + + String participantId = dataTransferService.checkEdcConsumerConnection(); + + assertNotNull(participantId); + assertEquals(vaultService.getLocalSecret("edc.participantId"), participantId); } @Test - void testSeeNegotiation() { + void buildRequestAndOffer() { + Status status = new Status(); + status.setEndpoint("test.endpoint"); + + NegotiationRequest negotiationRequest = dataTransferService.buildRequest(dataSet, status, bpn); + + assertNotNull(negotiationRequest); + assertEquals(status.getEndpoint(), negotiationRequest.getConnectorAddress()); + assertEquals(bpn, negotiationRequest.getConnectorId()); + + Offer offer = negotiationRequest.getOffer(); + + assertNotNull(offer); + assertEquals(dataSet.getAssetId(), offer.getAssetId()); + assertEquals(policy.getId(), offer.getOfferId()); + assertNotNull(offer.getPolicy()); } @Test - void initiateTransfer() { + void getContractOfferCatalog() { + String providerUrl = UUID.randomUUID().toString(); + Catalog catalog = (Catalog) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testCOCatalogPath, Catalog.class); + String assetId = catalog.getParticipantId(); + + when(httpUtil.doPost(anyString(), any(Class.class), any(HttpHeaders.class), any(Map.class), any(Object.class), eq(false), eq(false))) + .then(invocation -> { + CatalogRequest body = invocation.getArgument(4); + if (body.getProviderUrl().equals(providerUrl)) { + return new ResponseEntity<>(jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testCOCatalogPath, JsonNode.class), HttpStatus.OK); + } + return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); + }); + + Catalog offerCatalog = dataTransferService.getContractOfferCatalog(providerUrl, assetId); + + assertNotNull(offerCatalog); + assertNotEquals(catalog, offerCatalog); + assertEquals(catalog.getId(), offerCatalog.getId()); + assertEquals(catalog.getType(), offerCatalog.getType()); + assertEquals(catalog.getParticipantId(), offerCatalog.getParticipantId()); + assertEquals(catalog.getContext(), offerCatalog.getContext()); + + Map contractOffer = (Map) jsonUtil.toMap(offerCatalog.getContractOffers()); + assertEquals("batterypass test data", contractOffer.get("edc:description")); + } @Test - void seeTransfer() { + void searchDigitalTwinCatalog() { + String providerUrl = UUID.randomUUID().toString(); + Catalog catalog = (Catalog) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testDTCatalogPath, Catalog.class); + + when(httpUtil.doPost(anyString(), any(Class.class), any(HttpHeaders.class), any(Map.class), any(Object.class), eq(false), eq(false))) + .then(invocation -> { + CatalogRequest body = invocation.getArgument(4); + if (body.getProviderUrl().equals(CatenaXUtil.buildDataEndpoint(providerUrl))) { + return new ResponseEntity<>(jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testDTCatalogPath, JsonNode.class), HttpStatus.OK); + } + return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); + }); + + Catalog digitalTwinCatalog = dataTransferService.searchDigitalTwinCatalog(providerUrl); + + assertNotNull(digitalTwinCatalog); + assertNotEquals(catalog, digitalTwinCatalog); + assertEquals(catalog.getId(), digitalTwinCatalog.getId()); + assertEquals(catalog.getType(), digitalTwinCatalog.getType()); + assertEquals(catalog.getParticipantId(), digitalTwinCatalog.getParticipantId()); + assertEquals(catalog.getContext(), digitalTwinCatalog.getContext()); + + Map contractOffer = (Map) jsonUtil.toMap(digitalTwinCatalog.getContractOffers()); + assertEquals("data.core.digitalTwinRegistry", contractOffer.get("edc:type")); } @Test - void testSeeTransfer() { + void doContractNegotiationAndSeeNegotiation() { + String providerUrl = UUID.randomUUID().toString(); + + Offer offer = dataTransferService.buildOffer(dataSet, 0); + + when(httpUtil.doPost(anyString(), any(Class.class), any(HttpHeaders.class), any(Map.class), any(NegotiationRequest.class), eq(false), eq(false))) + .then(invocation -> { + NegotiationRequest body = invocation.getArgument(4); + if (body instanceof NegotiationRequest) { + return new ResponseEntity<>(jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testResponseInitNegotiationPath, JsonNode.class), HttpStatus.OK); + } + return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); + }); + + IdResponse response = dataTransferService.doContractNegotiation(offer, bpn, providerUrl); + + assertNotNull(response); + assertEquals("189f4957-0fbe-4d73-b215-977e3303a45e", response.getId()); + assertEquals("edc:IdResponseDto", response.getType()); + + when(httpUtil.doGet(anyString(), any(Class.class), any(HttpHeaders.class), any(Map.class), eq(false), eq(false))) + .thenReturn(new ResponseEntity<>(jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testResponseNegotiationPath, JsonNode.class), HttpStatus.OK)); + + Negotiation negotiation = dataTransferService.seeNegotiation(response.getId()); + + assertEquals(response.getId(), negotiation.getId()); + assertEquals("edc:ContractNegotiationDto", negotiation.getType()); + assertEquals("FINALIZED", negotiation.getState()); } - @Test - void getPassport() { + private Negotiation getNegotiation() { + String providerUrl = UUID.randomUUID().toString(); + Offer offer = dataTransferService.buildOffer(dataSet, 0); + + when(httpUtil.doPost(anyString(), any(Class.class), any(HttpHeaders.class), any(Map.class), any(NegotiationRequest.class), eq(false), eq(false))) + .then(invocation -> { + NegotiationRequest body = invocation.getArgument(4); + if (body instanceof NegotiationRequest) { + return new ResponseEntity<>(jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testResponseInitNegotiationPath, JsonNode.class), HttpStatus.OK); + } + return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); + }); + + IdResponse negotiationResponse = dataTransferService.doContractNegotiation(offer, bpn, providerUrl); + + when(httpUtil.doGet(anyString(), any(Class.class), any(HttpHeaders.class), any(Map.class), eq(false), eq(false))) + .thenReturn(new ResponseEntity<>(jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testResponseNegotiationPath, JsonNode.class), HttpStatus.OK)); + + return dataTransferService.seeNegotiation(negotiationResponse.getId()); } @Test - void generateTransferId() { + void initiateTransferAndSeeTransfer() { + + Negotiation negotiation = getNegotiation(); + Status status = new Status(); + status.setEndpoint("test.endpoint"); + + TransferRequest transferRequest = new TransferRequest( + jsonUtil.toJsonNode(Map.of("odrl", "http://www.w3.org/ns/odrl/2/")), + dataSet.getAssetId(), + status.getEndpoint(), + bpn, + negotiation.getContractAgreementId(), + null, + false, + null, + "dataspace-protocol-http", + null + ); + + when(httpUtil.doPost(anyString(), any(Class.class), any(HttpHeaders.class), any(Map.class), any(Object.class), eq(false), eq(false))) + .thenReturn(new ResponseEntity<>(jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testResponseInitTransferPath, JsonNode.class).toString(), HttpStatus.OK)); + + IdResponse response = dataTransferService.initiateTransfer(transferRequest); + + assertNotNull(response); + assertEquals("9ab72e5b-f2d4-4f60-85e6-0985f9b6b579", response.getId()); + assertEquals("edc:IdResponseDto", response.getType()); + + when(httpUtil.doGet(anyString(), any(Class.class), any(HttpHeaders.class), any(Map.class), eq(false), eq(false))) + .thenReturn(new ResponseEntity<>(jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testResponseTransferPath, JsonNode.class), HttpStatus.OK)); + + Transfer transfer = dataTransferService.seeTransfer(response.getId()); + + assertEquals(response.getId(), transfer.getId()); + assertEquals("edc:TransferProcessDto", transfer.getType()); + assertEquals("COMPLETED", transfer.getState()); } } diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/IrsServiceTest.java b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/IrsServiceTest.java new file mode 100644 index 000000000..ee6681670 --- /dev/null +++ b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/IrsServiceTest.java @@ -0,0 +1,165 @@ +package org.eclipse.tractusx.productpass.services; + +import com.fasterxml.jackson.databind.JsonNode; +import org.eclipse.tractusx.productpass.config.IrsConfig; +import org.eclipse.tractusx.productpass.config.PassportConfig; +import org.eclipse.tractusx.productpass.config.ProcessConfig; +import org.eclipse.tractusx.productpass.exceptions.ServiceInitializationException; +import org.eclipse.tractusx.productpass.managers.ProcessManager; +import org.eclipse.tractusx.productpass.managers.TreeManager; +import org.eclipse.tractusx.productpass.models.auth.JwtToken; +import org.eclipse.tractusx.productpass.models.irs.JobHistory; +import org.eclipse.tractusx.productpass.models.irs.JobRequest; +import org.eclipse.tractusx.productpass.models.irs.JobResponse; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.mock.env.MockEnvironment; +import utils.FileUtil; +import utils.HttpUtil; +import utils.JsonUtil; +import utils.YamlUtil; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.when; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class IrsServiceTest { + + private IrsService irsService; + private IrsConfig irsConfig; + private final String testJobResposnsePath = "/src/test/resources/dpp/irs/TestJobResponse.json"; + private final String testStartJobResposnsePath = "/src/test/resources/dpp/irs/TestStartJobResponse.json"; + private Map configuration; + private final String mockedTokenPath = "/src/test/resources/dpp/token/MockedToken.json"; + private JwtToken mockedToken; + @Mock + private Environment env; + private HttpUtil httpUtil; + private JsonUtil jsonUtil; + private YamlUtil yamlUtil; + private FileUtil fileUtil; + private ProcessManager processManager; + private TreeManager treeManager; + private AuthenticationService authenticationService; + @Mock + private VaultService vaultService; + @BeforeAll + void setUpAll() throws ServiceInitializationException { + MockitoAnnotations.openMocks(this); + fileUtil = new FileUtil(); + jsonUtil = new JsonUtil(fileUtil); + yamlUtil = new YamlUtil(fileUtil); + httpUtil = Mockito.spy(new HttpUtil(env)); + + Map application = yamlUtil.readFile(FileUtil.getWorkdirPath() + "/src/main/resources/application.yml"); + configuration = (Map) jsonUtil.toMap(application.get("configuration")); + Map vaultConfig = yamlUtil.readFile(fileUtil.getDataDir() + "/VaultConfig/vault.token.yml"); + Map client = (Map) jsonUtil.toMap(vaultConfig.get("client")); + when(vaultService.getLocalSecret("client.id")).thenReturn(client.get("id").toString()); + when(vaultService.getLocalSecret("client.secret")).thenReturn(client.get("secret").toString()); + + + env = initEnv(); + irsConfig = initIrsConfig(); + ProcessConfig processConfig = new ProcessConfig(); + PassportConfig passportConfig = new PassportConfig(); + authenticationService = Mockito.spy(new AuthenticationService(vaultService, env, httpUtil, jsonUtil)); + processManager = Mockito.spy(new ProcessManager(httpUtil, jsonUtil, fileUtil, processConfig)); + treeManager = new TreeManager(fileUtil, jsonUtil, processManager, irsConfig, passportConfig); + + irsService = new IrsService(env, processManager, irsConfig, treeManager, httpUtil, vaultService, jsonUtil, authenticationService); + + mockedToken = (JwtToken) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + mockedTokenPath, JwtToken.class); + doReturn(mockedToken).when(authenticationService).getToken(); + } + + private IrsConfig initIrsConfig() { + Map irs = (Map) jsonUtil.toMap(configuration.get("irs")); + + IrsConfig irsConfig = new IrsConfig(); + irsConfig.setEnabled((Boolean) irs.get("enabled")); + irsConfig.setEndpoint(irs.get("endpoint").toString()); + irsConfig.setPaths((IrsConfig.Paths) jsonUtil.bindObject(irs.get("paths"), IrsConfig.Paths.class)); + irsConfig.setTree((IrsConfig.TreeConfig) jsonUtil.bindObject(irs.get("tree"), IrsConfig.TreeConfig.class)); + irsConfig.setCallbackUrl(irs.get("callbackUrl").toString()); + + return irsConfig; + } + + private MockEnvironment initEnv() { + MockEnvironment env = new MockEnvironment(); + + Map keycloak = (Map) jsonUtil.toMap(configuration.get("keycloak")); + env.setProperty("configuration.keycloak.tokenUri", keycloak.get("tokenUri").toString()); + env.setProperty("configuration.keycloak.userInfoUri", keycloak.get("userInfoUri").toString()); + + return env; + } + + @BeforeEach + void setUp() { + doReturn(new ResponseEntity<>(jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testStartJobResposnsePath, JsonNode.class), HttpStatus.OK)) + .when(httpUtil).doPost(anyString(), any(Class.class), any(HttpHeaders.class), any(Map.class), any(JobRequest.class), eq(false), eq(false)); + + doReturn(new ResponseEntity<>(jsonUtil.toJson(jsonUtil.fromJsonFile(FileUtil.getWorkdirPath() + testJobResposnsePath), true), HttpStatus.OK)) + .when(httpUtil).doGet(anyString(), any(Class.class), any(HttpHeaders.class), any(Map.class), eq(true), eq(false)); + + doReturn("TEST_PATH").when(processManager).setJobHistory(anyString(), any(JobHistory.class)); + } + + @Test + void startJob() { + String processId = UUID.randomUUID().toString(); + String globalAssetId = UUID.randomUUID().toString(); + String searchId = UUID.randomUUID().toString(); + String bpn = UUID.randomUUID().toString(); + + Map result = irsService.startJob(processId, globalAssetId, searchId, bpn); + + assertNotNull(result); + assertEquals("0bbc712b-17a1-4c9d-9c9c-a7fae8082841", result.get("id")); + } + + @Test + void getChildren() { + String expectedJobId = "0bbc712b-17a1-4c9d-9c9c-a7fae8082841"; + String processId = UUID.randomUUID().toString(); + String path = "test.path"; + String globalAssetId = UUID.randomUUID().toString(); + String bpn = UUID.randomUUID().toString(); + + String jobId = irsService.getChildren(processId, path, globalAssetId, bpn); + + assertEquals(expectedJobId, jobId); + } + + @Test + void getJob() { + JobResponse test = (JobResponse) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testJobResposnsePath, JobResponse.class); + String jobId = "0bbc712b-17a1-4c9d-9c9c-a7fae8082841"; + JobResponse jobResponse = irsService.getJob(jobId); + + assertNotNull(jobResponse); + assertEquals(test.getJob().getId(), jobResponse.getJob().getId()); + assertEquals(test.getJob().getGlobalAssetId(), jobResponse.getJob().getGlobalAssetId()); + assertEquals(test.getJob().getState(), jobResponse.getJob().getState()); + assertEquals(jobId, jobResponse.getJob().getId()); + } + + +} diff --git a/consumer-backend/productpass/src/test/resources/dpp/assets/TestAsset.json b/consumer-backend/productpass/src/test/resources/dpp/assets/TestAsset.json new file mode 100644 index 000000000..5b9db9c51 --- /dev/null +++ b/consumer-backend/productpass/src/test/resources/dpp/assets/TestAsset.json @@ -0,0 +1,21 @@ +{ + "@context": {}, + "asset": { + "@type": "data.core.digitalTwinRegistry", + "@id": "digital-twin-registry", + "properties": { + "type": "data.core.digitalTwinRegistry", + "description": "Digital Twin Registry for DPP", + "contenttype": "application/json" + } + }, + "dataAddress": { + "@type": "DataAddress", + "type": "HttpData", + "proxyPath": "true", + "proxyBody": "true", + "proxyMethod": "true", + "proxyQueryParams": "true", + "baseUrl": "https://materialpass.int.demo.catena-x.net/semantics/registry/api/v3.0" + } +} diff --git a/consumer-backend/productpass/src/test/resources/dpp/catalogs/TestContractOfferCatalog.json b/consumer-backend/productpass/src/test/resources/dpp/catalogs/TestContractOfferCatalog.json new file mode 100644 index 000000000..f617eb955 --- /dev/null +++ b/consumer-backend/productpass/src/test/resources/dpp/catalogs/TestContractOfferCatalog.json @@ -0,0 +1,63 @@ +{ + "@id": "c86305ef-e8ee-4163-913c-ce074dfa274f", + "@type": "dcat:Catalog", + "dcat:dataset": { + "@id": "urn:uuid:9992f962-6f69-875d-0ea4-fb4db3bb3b23", + "@type": "dcat:Dataset", + "odrl:hasPolicy": { + "@id": "ZDkxMzRjNmQtNWUzNy03ZDc5LTRkOTEtZmM5MGIzZWVkMzMw:dXJuOnV1aWQ6OTk5MmY5NjItNmY2OS04NzVkLTBlYTQtZmI0ZGIzYmIzYjIz:YjZkMzFkNGYtNGYyNS00MWI1LWFkMzctNjJjY2U4NGI3NjA0", + "@type": "odrl:Set", + "odrl:permission": { + "odrl:target": "urn:uuid:9992f962-6f69-875d-0ea4-fb4db3bb3b23", + "odrl:action": { + "odrl:type": "USE" + }, + "odrl:constraint": { + "odrl:or": { + "odrl:leftOperand": "PURPOSE", + "odrl:operator": { + "@id": "odrl:eq" + }, + "odrl:rightOperand": "ID 3.0 Trace" + } + } + }, + "odrl:prohibition": [], + "odrl:obligation": [], + "odrl:target": "urn:uuid:9992f962-6f69-875d-0ea4-fb4db3bb3b23" + }, + "dcat:distribution": [ + { + "@type": "dcat:Distribution", + "dct:format": { + "@id": "HttpProxy" + }, + "dcat:accessService": "e2a066b3-5a16-45dc-8552-8d96ac787e02" + }, + { + "@type": "dcat:Distribution", + "dct:format": { + "@id": "AmazonS3" + }, + "dcat:accessService": "e2a066b3-5a16-45dc-8552-8d96ac787e02" + } + ], + "edc:description": "batterypass test data", + "edc:id": "urn:uuid:9992f962-6f69-875d-0ea4-fb4db3bb3b23" + }, + "dcat:service": { + "@id": "e2a066b3-5a16-45dc-8552-8d96ac787e02", + "@type": "dcat:DataService", + "dct:terms": "connector", + "dct:endpointUrl": "https://materialpass.int.demo.catena-x.net/BPNL000000000000/api/v1/dsp" + }, + "edc:participantId": "BPNL00000000CBA5", + "@context": { + "dct": "https://purl.org/dc/terms/", + "tx": "https://w3id.org/tractusx/v0.0.1/ns/", + "edc": "https://w3id.org/edc/v0.0.1/ns/", + "dcat": "https://www.w3.org/ns/dcat/", + "odrl": "http://www.w3.org/ns/odrl/2/", + "dspace": "https://w3id.org/dspace/v0.8/" + } +} diff --git a/consumer-backend/productpass/src/test/resources/dpp/catalogs/TestDigitalTwinCatalog.json b/consumer-backend/productpass/src/test/resources/dpp/catalogs/TestDigitalTwinCatalog.json new file mode 100644 index 000000000..d54febe7f --- /dev/null +++ b/consumer-backend/productpass/src/test/resources/dpp/catalogs/TestDigitalTwinCatalog.json @@ -0,0 +1,51 @@ +{ + "@id": "bb824702-08dc-4315-9ff1-6373330a0cd9", + "@type": "dcat:Catalog", + "dcat:dataset": { + "@id": "registry-asset", + "@type": "dcat:Dataset", + "odrl:hasPolicy": { + "@id": "ZGVmYXVsdC1jb250cmFjdC1kZWZpbml0aW9u:cmVnaXN0cnktYXNzZXQ=:MTIxMjYzMzgtYzhkMC00MGQ4LTkxYWMtZmY2ZTY0ZTQ5ZmM0", + "@type": "odrl:Set", + "odrl:permission": [], + "odrl:prohibition": [], + "odrl:obligation": [], + "odrl:target": "registry-asset" + }, + "dcat:distribution": [ + { + "@type": "dcat:Distribution", + "dct:format": { + "@id": "HttpProxy" + }, + "dcat:accessService": "bc491229-1b41-49a9-9101-a430a4907e6e" + }, + { + "@type": "dcat:Distribution", + "dct:format": { + "@id": "AmazonS3" + }, + "dcat:accessService": "bc491229-1b41-49a9-9101-a430a4907e6e" + } + ], + "edc:type": "data.core.digitalTwinRegistry", + "edc:description": "Digital Twin Registry for DPP", + "edc:id": "registry-asset", + "edc:contenttype": "application/json" + }, + "dcat:service": { + "@id": "bc491229-1b41-49a9-9101-a430a4907e6e", + "@type": "dcat:DataService", + "dct:terms": "connector", + "dct:endpointUrl": "https://materialpass.int.demo.catena-x.net/BPNL000000000000/api/v1/dsp" + }, + "edc:participantId": "BPNL00000000CBA5", + "@context": { + "dct": "https://purl.org/dc/terms/", + "tx": "https://w3id.org/tractusx/v0.0.1/ns/", + "edc": "https://w3id.org/edc/v0.0.1/ns/", + "dcat": "https://www.w3.org/ns/dcat/", + "odrl": "http://www.w3.org/ns/odrl/2/", + "dspace": "https://w3id.org/dspace/v0.8/" + } +} diff --git a/consumer-backend/productpass/src/test/resources/dpp/contractpolicies/TestPolicy.json b/consumer-backend/productpass/src/test/resources/dpp/contractpolicies/TestPolicy.json new file mode 100644 index 000000000..460c4f79a --- /dev/null +++ b/consumer-backend/productpass/src/test/resources/dpp/contractpolicies/TestPolicy.json @@ -0,0 +1,8 @@ +{ + "@id": "ZGVmYXVsdC1jb250cmFjdC1kZWZpbml0aW9u:cmVnaXN0cnktYXNzZXQ=:MTIxMjYzMzgtYzhkMC00MGQ4LTkxYWMtZmY2ZTY0ZTQ5ZmM0", + "@type": "odrl:Set", + "odrl:permission" : [], + "odrl:prohibition": [], + "odrl:obligation": [], + "odrl:target": "registry-asset" +} diff --git a/consumer-backend/productpass/src/test/resources/dpp/digitaltwins/TestDigitalTwin.json b/consumer-backend/productpass/src/test/resources/dpp/digitaltwins/TestDigitalTwin.json new file mode 100644 index 000000000..249c717b7 --- /dev/null +++ b/consumer-backend/productpass/src/test/resources/dpp/digitaltwins/TestDigitalTwin.json @@ -0,0 +1,68 @@ +{ + "description": [ + { + "language": "en", + "text": "Battery Passport shell descriptor" + } + ], + "idShort": "Battery_IMR18650V1", + "id": "365e6fbe-bb34-11ec-8422-0242ac120002", + "specificAssetIds": [ + { + "name": "partInstanceId", + "value": "IMR18650V1", + "externalSubjectId": { + "type": "ExternalReference", + "keys": [ + { + "type": "Submodel", + "value": "" + } + ] + } + } + ], + "submodelDescriptors": [ + { + "endpoints": [ + { + "interface": "SUBMODEL-3.0", + "protocolInformation": { + "href": "https://materialpass.int.demo.catena-x.net/BPNL000000000000/365e6fbe-bb34-11ec-8422-0242ac120002-61125dc3-5e6f-4f4b-838d-447432b97918/submodel", + "endpointProtocol": "HTTP", + "endpointProtocolVersion": [ + "1.1" + ], + "subprotocol": "DSP", + "subprotocolBody": "id=365e6fbe-bb34-11ec-8422-0242ac120002-61125dc3-5e6f-4f4b-838d-447432b97918;dspEndpoint=https://materialpass.int.demo.catena-x.net/BPNL000000000000/", + "subprotocolBodyEncoding": "plain", + "securityAttributes": [ + { + "type": "NONE", + "key": "NONE", + "value": "NONE" + } + ] + } + } + ], + "idShort": "batteryPass", + "id": "61125dc3-5e6f-4f4b-838d-447432b97918", + "semanticId": { + "type": "ExternalReference", + "keys": [ + { + "type": "Submodel", + "value": "urn:bamm:io.catenax.battery.battery_pass:3.0.1#BatteryPass" + } + ] + }, + "description": [ + { + "language": "en", + "text": "Battery Passport Submodel" + } + ] + } + ] +} diff --git a/consumer-backend/productpass/src/test/resources/dpp/discovery/MockedDiscoveryEndpoints.json b/consumer-backend/productpass/src/test/resources/dpp/discovery/MockedDiscoveryEndpoints.json new file mode 100644 index 000000000..35c86d01c --- /dev/null +++ b/consumer-backend/productpass/src/test/resources/dpp/discovery/MockedDiscoveryEndpoints.json @@ -0,0 +1,15 @@ +{ + "endpoints" : [ { + "type" : "manufacturerPartId", + "description" : "Service to discover BPN for different kind of type numbers", + "endpointAddress" : "https://semantics.int.demo.catena-x.net/bpndiscovery", + "documentation" : "https://semantics.int.demo.catena-x.net/bpndiscovery/swagger-ui/index.html", + "resourceId" : "278a9cd3-2201-47d1-8474-a0beb6b6f21b" + }, { + "type" : "bpn", + "description" : "Service to discover connector endpoints based on bpns", + "endpointAddress" : "https://portal-backend.int.demo.catena-x.net/api/administration/Connectors/discovery", + "documentation" : "https://portal-backend.int.demo.catena-x.net/api/administration/swagger/index.html", + "resourceId" : "63739df2-84ce-4309-8d71-5a0f29e789e1" + } ] +} diff --git a/consumer-backend/productpass/src/test/resources/dpp/irs/TestJobHistory.json b/consumer-backend/productpass/src/test/resources/dpp/irs/TestJobHistory.json new file mode 100644 index 000000000..48603dd49 --- /dev/null +++ b/consumer-backend/productpass/src/test/resources/dpp/irs/TestJobHistory.json @@ -0,0 +1,9 @@ +{ + "jobId": "0bbc712b-17a1-4c9d-9c9c-a7fae8082841", + "searchId": "d32b9af47f41dd87d3e3ca77532341ad", + "globalAssetId": "urn:uuid:efcb5f8d-f31c-4b1f-b090-9c878054554d", + "path": "/urn:uuid:efcb5f8d-f31c-4b1f-b090-9c878054554d", + "created": 1699027271226, + "updated": 1699027655138, + "children": 1 +} diff --git a/consumer-backend/productpass/src/test/resources/dpp/irs/TestJobResponse.json b/consumer-backend/productpass/src/test/resources/dpp/irs/TestJobResponse.json new file mode 100644 index 000000000..2acb2d76c --- /dev/null +++ b/consumer-backend/productpass/src/test/resources/dpp/irs/TestJobResponse.json @@ -0,0 +1,292 @@ +{ + "job": { + "id": "0bbc712b-17a1-4c9d-9c9c-a7fae8082841", + "globalAssetId": "urn:uuid:efcb5f8d-f31c-4b1f-b090-9c878054554d", + "state": "COMPLETED", + "exception": null, + "createdOn": "2023-10-23T16:39:11.152183246Z", + "startedOn": "2023-10-23T16:39:11.152314446Z", + "lastModifiedOn": "2023-10-23T16:56:36.951457812Z", + "completedOn": "2023-10-23T16:56:36.951460713Z", + "owner": "sa241", + "summary": { + "asyncFetchedItems": { + "running": 0, + "completed": 2, + "failed": 0 + }, + "bpnLookups": { + "completed": 0, + "failed": 0 + } + }, + "parameter": { + "bomLifecycle": "asBuilt", + "aspects": [ + "SerialPart" + ], + "depth": 1, + "bpn": "BPNL00000000CBA5", + "direction": "downward", + "collectAspects": false, + "lookupBPNs": false, + "callbackUrl": "https://materialpass.int.demo.catena-x.net/api/irs/1eff01dd-80cf-47e9-b2b7-c0b953009da9/dabfe4a4e08a6ce8e4c3b026b1ade235?id=urn:uuid:efcb5f8d-f31c-4b1f-b090-9c878054554d&state=COMPLETED" + } + }, + "relationships": [ + { + "catenaXId": "urn:uuid:efcb5f8d-f31c-4b1f-b090-9c878054554d", + "linkedItem": { + "quantity": { + "quantityNumber": 5.0, + "measurementUnit": { + "datatypeURI": null, + "lexicalValue": "piece" + } + }, + "lifecycleContext": "asBuilt", + "assembledOn": "2023-01-09T17:26:54.709Z", + "lastModifiedOn": "2023-01-09T17:26:54.709Z", + "childCatenaXId": "urn:uuid:d8ec6acc-1ad7-47b4-bc7e-612122d9d552" + }, + "aspectType": "SingleLevelBomAsBuilt", + "bpn": "BPNL00000000CBA5" + } + ], + "shells": [ + { + "administration": null, + "description": [ + { + "language": "en", + "text": "Battery Digital Twin" + } + ], + "globalAssetId": "urn:uuid:efcb5f8d-f31c-4b1f-b090-9c878054554d", + "idShort": "Battery_BAT-XYZ789", + "id": "urn:uuid:3d050cd8-cdc7-4d65-9f37-70a65d5f53f5", + "specificAssetIds": [ + { + "name": "partInstanceId", + "subjectId": null, + "value": "BAT-XYZ789", + "semanticId": null + }, + { + "name": "manufacturerPartId", + "subjectId": null, + "value": "XYZ78901", + "semanticId": null + } + ], + "submodelDescriptors": [ + { + "administration": null, + "description": [], + "idShort": "SerialPart", + "id": "urn:uuid:1ea64f49-8b2b-4cd2-818e-cf9d452c6fea", + "semanticId": { + "keys": [ + { + "value": "urn:bamm:io.catenax.serial_part:1.0.1#SerialPart", + "type": "Submodel" + } + ], + "type": "ExternalReference" + }, + "endpoints": [ + { + "protocolInformation": { + "href": "https://materialpass.int.demo.catena-x.net/BPNL000000000000/api/public/data/urn:uuid:1ea64f49-8b2b-4cd2-818e-cf9d452c6fea" + , + "endpointProtocol": "HTTP", + "endpointProtocolVersion": [ + "1.1" + ], + "subprotocol": "DSP", + "subprotocolBody": "id=urn:uuid:3e4a5957-f226-478a-ab18-79ced49d6195;dspEndpoint=https://materialpass.int.demo.catena-x.net/BPNL000000000000" + , + "subprotocolBodyEncoding": "plain" + }, + "interface": "SUBMODEL-3.0" + } + ] + } + ] + }, + { + "administration": null, + "description": [ + { + "language": "en", + "text": "Battery Module Digital Twin" + } + ], + "globalAssetId": "urn:uuid:d8ec6acc-1ad7-47b4-bc7e-612122d9d552", + "idShort": "BatteryModule_EVMODULE-TRJ712", + "id": "urn:uuid:ace301f6-92c5-4623-a022-c2a30dfee0e2", + "specificAssetIds": [ + { + "name": "partInstanceId", + "subjectId": null, + "value": "EVMODULE-TRJ712", + "semanticId": null + }, + { + "name": "manufacturerPartId", + "subjectId": null, + "value": "XYZ78901", + "semanticId": null + } + ], + "submodelDescriptors": [ + { + "administration": null, + "description": [ + { + "language": "en", + "text": "Digital Product Passport Submodel" + } + ], + "idShort": "singleLevelBomAsBuilt", + "id": "urn:uuid:c216bece-b17f-4679-8b62-ec25810ca1c4", + "semanticId": { + "keys": [ + { + "value": "urn:bamm:io.catenax.single_level_bom_as_built:1.0.0#SingleLevelBomAsBuilt", + "type": "Submodel" + } + ], + "type": "ExternalReference" + }, + "endpoints": [ + { + "protocolInformation": { + "href": "https://materialpass.int.demo.catena-x.net/BPNL000000000000/api/public/data/urn:uuid:c216bece-b17f-4679-8b62-ec25810ca1c4" + , + "endpointProtocol": "HTTP", + "endpointProtocolVersion": [ + "1.1" + ], + "subprotocol": "DSP", + "subprotocolBody": "id=urn:uuid:3e4a5957-f226-478a-ab18-79ced49d6195;dspEndpoint=https://materialpass.int.demo.catena-x.net/BPNL000000000000/" + , + "subprotocolBodyEncoding": "plain" + }, + "interface": "SUBMODEL-3.0" + } + ] + }, + { + "administration": null, + "description": [], + "idShort": "SerialPart", + "id": "urn:uuid:906e5e5e-f9c1-427c-b923-e5f863bc40df", + "semanticId": { + "keys": [ + { + "value": "urn:bamm:io.catenax.serial_part:1.0.1#SerialPart", + "type": "Submodel" + } + ], + "type": "ExternalReference" + }, + "endpoints": [ + { + "protocolInformation": { + "href": "https://materialpass.int.demo.catena-x.net/BPNL000000000000/api/public/data/urn:uuid:906e5e5e-f9c1-427c-b923-e5f863bc40df" + , + "endpointProtocol": "HTTP", + "endpointProtocolVersion": [ + "1.1" + ], + "subprotocol": "DSP", + "subprotocolBody": "id=urn:uuid:3e4a5957-f226-478a-ab18-79ced49d6195;dspEndpoint=https://materialpass.int.demo.catena-x.net/BPNL000000000000" + , + "subprotocolBodyEncoding": "plain" + }, + "interface": "SUBMODEL-3.0" + } + ] + }, + { + "administration": null, + "description": [ + { + "language": "en", + "text": "Digital Product Passport Submodel" + } + ], + "idShort": "digitalProductPass", + "id": "urn:uuid:754b6c6c-d74a-4dd0-a62c-f07959f15332", + "semanticId": { + "keys": [ + { + "value": "urn:bamm:io.catenax.generic.digital_product_passport:1.0.0#DigitalProductPassport", + "type": "Submodel" + } + ], + "type": "ExternalReference" + }, + "endpoints": [ + { + "protocolInformation": { + "href": "https://materialpass.int.demo.catena-x.net/BPNL000000000000/api/public/data/urn:uuid:754b6c6c-d74a-4dd0-a62c-f07959f15332" + , + "endpointProtocol": "HTTP", + "endpointProtocolVersion": [ + "1.1" + ], + "subprotocol": "DSP", + "subprotocolBody": "id=urn:uuid:3e4a5957-f226-478a-ab18-79ced49d6195;dspEndpoint=https://materialpass.int.demo.catena-x.net/BPNL000000000000/" + , + "subprotocolBodyEncoding": "plain" + }, + "interface": "SUBMODEL-3.0" + } + ] + }, + { + "administration": null, + "description": [ + { + "language": "en", + "text": "Digital Product Passport Submodel" + } + ], + "idShort": "SingleLevelUsageAsBuilt", + "id": "urn:uuid:25ea2646-d57f-4b31-97a0-d0d7b3b35d37", + "semanticId": { + "keys": [ + { + "value": "urn:bamm:io.catenax.single_level_usage_as_built:1.0.1#SingleLevelUsageAsBuilt", + "type": "Submodel" + } + ], + "type": "ExternalReference" + }, + "endpoints": [ + { + "protocolInformation": { + "href": "https://materialpass.int.demo.catena-x.net/BPNL000000000000/api/public/data/urn:uuid:25ea2646-d57f-4b31-97a0-d0d7b3b35d37" + , + "endpointProtocol": "HTTP", + "endpointProtocolVersion": [ + "1.1" + ], + "subprotocol": "DSP", + "subprotocolBody": "id=urn:uuid:3e4a5957-f226-478a-ab18-79ced49d6195;dspEndpoint=https://materialpass.int.demo.catena-x.net/BPNL000000000000/" + , + "subprotocolBodyEncoding": "plain" + }, + "interface": "SUBMODEL-3.0" + } + ] + } + ] + } + ], + "tombstones": [], + "submodels": [], + "bpns": [] +} diff --git a/consumer-backend/productpass/src/test/resources/dpp/irs/TestStartJobResponse.json b/consumer-backend/productpass/src/test/resources/dpp/irs/TestStartJobResponse.json new file mode 100644 index 000000000..765d9888a --- /dev/null +++ b/consumer-backend/productpass/src/test/resources/dpp/irs/TestStartJobResponse.json @@ -0,0 +1,3 @@ +{ + "id": "0bbc712b-17a1-4c9d-9c9c-a7fae8082841" +} diff --git a/consumer-backend/productpass/src/test/resources/dpp/irs/TestTreeDataModel.json b/consumer-backend/productpass/src/test/resources/dpp/irs/TestTreeDataModel.json new file mode 100644 index 000000000..9cae60431 --- /dev/null +++ b/consumer-backend/productpass/src/test/resources/dpp/irs/TestTreeDataModel.json @@ -0,0 +1,214 @@ +{ + "urn:uuid:efcb5f8d-f31c-4b1f-b090-9c878054554d" : { + "id" : "urn:uuid:82e78a83-3ddd-64c1-455d-8f7629833f17", + "globalAssetId" : "urn:uuid:efcb5f8d-f31c-4b1f-b090-9c878054554d", + "idShort" : "Battery_BAT-XYZ789", + "searchId" : "CX:XYZ78901:BAT-XYZ789", + "path" : "/urn:uuid:efcb5f8d-f31c-4b1f-b090-9c878054554d", + "digitalTwin" : { + "description" : [ { + "language" : "en", + "text" : "Battery Digital Twin" + } ], + "idShort" : "Battery_BAT-XYZ789", + "globalAssetId" : "urn:uuid:efcb5f8d-f31c-4b1f-b090-9c878054554d", + "displayName" : [ ], + "id" : "urn:uuid:82e78a83-3ddd-64c1-455d-8f7629833f17", + "specificAssetIds" : [ { + "supplementalSemanticIds" : [ ], + "name" : "partInstanceId", + "value" : "BAT-XYZ789", + "externalSubjectId" : { + "type" : "ExternalReference", + "keys" : [ { + "type" : "GlobalReference", + "value" : "BPNL00000000CBA5" + } ] + } + }, { + "supplementalSemanticIds" : [ ], + "name" : "manufacturerPartId", + "value" : "XYZ78901", + "externalSubjectId" : { + "type" : "ExternalReference", + "keys" : [ { + "type" : "GlobalReference", + "value" : "BPNL00000000CBA5" + }, { + "type" : "GlobalReference", + "value" : "PUBLIC_READABLE" + } ] + } + } ], + "submodelDescriptors" : [ { + "description" : [ ], + "idShort" : "singleLevelBomAsBuilt", + "supplementalSemanticId" : [ ], + "id" : "urn:uuid:d02f5568-0ff7-b0d3-1adb-b246b81333bc", + "semanticId" : { + "type" : "ExternalReference", + "keys" : [ { + "type" : "Submodel", + "value" : "urn:bamm:io.catenax.single_level_bom_as_built:1.0.0#SingleLevelBomAsBuilt" + } ] + }, + "endpoints" : [ { + "interface" : "SUBMODEL-3.0", + "protocolInformation" : { + "href" : "https://materialpass.int.demo.catena-x.net/BPNL000000000000/api/public/data/urn:uuid:d02f5568-0ff7-b0d3-1adb-b246b81333bc" + , + "endpointProtocol" : "HTTP", + "subprotocol" : "DSP", + "subprotocolBody" : "id=urn:uuid:1f0aa91b-7978-d8fe-a0c9-20c31928dc68;dspEndpoint=https://materialpass.int.demo.catena-x.net/BPNL000000000000" + , + "subprotocolBodyEncoding" : "plain", + "securityAttributes" : [ { + "type" : "NONE", + "key" : "NONE", + "value" : "NONE" + } ], + "endpointProtocolVersion" : [ "1.1" ] + } + } ] + }, { + "description" : [ { + "language" : "en", + "text" : "Digital Product Passport Submodel" + } ], + "idShort" : "digitalProductPass", + "supplementalSemanticId" : [ ], + "id" : "urn:uuid:f82e3855-3338-33fc-5130-95fec40b805b", + "semanticId" : { + "type" : "ExternalReference", + "keys" : [ { + "type" : "Submodel", + "value" : "urn:bamm:io.catenax.generic.digital_product_passport:1.0.0#DigitalProductPassport" + } ] + }, + "endpoints" : [ { + "interface" : "SUBMODEL-3.0", + "protocolInformation" : { + "href" : "https://materialpass.int.demo.catena-x.net/BPNL000000000000/api/public/data/urn:uuid:f82e3855-3338-33fc-5130-95fec40b805b" + , + "endpointProtocol" : "HTTP", + "subprotocol" : "DSP", + "subprotocolBody" : "id=urn:uuid:1f0aa91b-7978-d8fe-a0c9-20c31928dc68;dspEndpoint=https://materialpass.int.demo.catena-x.net/BPNL000000000000" + , + "subprotocolBodyEncoding" : "plain", + "securityAttributes" : [ { + "type" : "NONE", + "key" : "NONE", + "value" : "NONE" + } ], + "endpointProtocolVersion" : [ "1.1" ] + } + } ] + } ] + }, + "children" : { + "urn:uuid:d8ec6acc-1ad7-47b4-bc7e-612122d9d552" : { + "id" : "urn:uuid:577bb93c-6e6e-a07a-c429-d72b4bc2021d", + "globalAssetId" : "urn:uuid:d8ec6acc-1ad7-47b4-bc7e-612122d9d552", + "idShort" : "Battery_EVMODULE-TRJ712", + "searchId" : "CX:XYZ78901:EVMODULE-TRJ712", + "path" : "/urn:uuid:efcb5f8d-f31c-4b1f-b090-9c878054554d/urn:uuid:d8ec6acc-1ad7-47b4-bc7e-612122d9d552", + "digitalTwin" : { + "description" : [ { + "language" : "en", + "text" : "Battery Module Digital Twin" + } ], + "idShort" : "Battery_EVMODULE-TRJ712", + "globalAssetId" : "urn:uuid:d8ec6acc-1ad7-47b4-bc7e-612122d9d552", + "id" : "urn:uuid:577bb93c-6e6e-a07a-c429-d72b4bc2021d", + "specificAssetIds" : [ { + "name" : "manufacturerPartId", + "value" : "XYZ78901" + }, { + "name" : "partInstanceId", + "value" : "EVMODULE-TRJ712" + } ], + "submodelDescriptors" : [ { + "description" : [ { + "language" : "en", + "text" : "Digital Product Passport Submodel" + } ], + "idShort" : "digitalProductPass", + "id" : "urn:uuid:13a47464-2826-a597-c3ad-6471ac8fb372", + "semanticId" : { + "type" : "ExternalReference", + "keys" : [ { + "type" : "Submodel", + "value" : "urn:bamm:io.catenax.generic.digital_product_passport:1.0.0#DigitalProductPassport" + } ] + }, + "endpoints" : [ { + "interface" : "SUBMODEL-3.0", + "protocolInformation" : { + "href" : "https://materialpass.int.demo.catena-x.net/BPNL000000000000/api/public/data/urn:uuid:13a47464-2826-a597-c3ad-6471ac8fb372" + , + "endpointProtocol" : "HTTP", + "subprotocol" : "DSP", + "subprotocolBody" : "id=urn:uuid:1f0aa91b-7978-d8fe-a0c9-20c31928dc68;dspEndpoint=https://materialpass.int.demo.catena-x.net/BPNL000000000000" + , + "subprotocolBodyEncoding" : "plain", + "endpointProtocolVersion" : [ "1.1" ] + } + } ] + }, { + "description" : [ { + "language" : "en", + "text" : "Digital Product Passport Submodel" + } ], + "idShort" : "SingleLevelUsageAsBuilt", + "id" : "urn:uuid:90a95f5f-c46e-b086-6675-810b2849bc4a", + "semanticId" : { + "type" : "ExternalReference", + "keys" : [ { + "type" : "Submodel", + "value" : "urn:bamm:io.catenax.single_level_usage_as_built:1.0.1#SingleLevelUsageAsBuilt" + } ] + }, + "endpoints" : [ { + "interface" : "SUBMODEL-3.0", + "protocolInformation" : { + "href" : "https://materialpass.int.demo.catena-x.net/BPNL000000000000/api/public/data/urn:uuid:90a95f5f-c46e-b086-6675-810b2849bc4a" + , + "endpointProtocol" : "HTTP", + "subprotocol" : "DSP", + "subprotocolBody" : "id=urn:uuid:1f0aa91b-7978-d8fe-a0c9-20c31928dc68;dspEndpoint=https://materialpass.int.demo.catena-x.net/BPNL000000000000" + , + "subprotocolBodyEncoding" : "plain", + "endpointProtocolVersion" : [ "1.1" ] + } + } ] + }, { + "description" : [ ], + "idShort" : "singleLevelBomAsBuilt", + "id" : "urn:uuid:94184a05-00fc-9db8-24cb-d5c217660a82", + "semanticId" : { + "type" : "ExternalReference", + "keys" : [ { + "type" : "Submodel", + "value" : "urn:bamm:io.catenax.single_level_bom_as_built:1.0.0#SingleLevelBomAsBuilt" + } ] + }, + "endpoints" : [ { + "interface" : "SUBMODEL-3.0", + "protocolInformation" : { + "href" : "https://materialpass.int.demo.catena-x.net/BPNL000000000000/api/public/data/urn:uuid:94184a05-00fc-9db8-24cb-d5c217660a82" + , + "endpointProtocol" : "HTTP", + "subprotocol" : "DSP", + "subprotocolBody" : "id=urn:uuid:1f0aa91b-7978-d8fe-a0c9-20c31928dc68;dspEndpoint=https://materialpass.int.demo.catena-x.net/BPNL000000000000" + , + "subprotocolBodyEncoding" : "plain", + "endpointProtocolVersion" : [ "1.1" ] + } + } ] + } ] + }, + "children" : { } + } + } + } +} diff --git a/consumer-backend/productpass/src/test/resources/dpp/negotiation/TestResponseInitNegotiation.json b/consumer-backend/productpass/src/test/resources/dpp/negotiation/TestResponseInitNegotiation.json new file mode 100644 index 000000000..b88c88c0b --- /dev/null +++ b/consumer-backend/productpass/src/test/resources/dpp/negotiation/TestResponseInitNegotiation.json @@ -0,0 +1,13 @@ +{ + "@type" : "edc:IdResponseDto", + "@id" : "189f4957-0fbe-4d73-b215-977e3303a45e", + "edc:createdAt" : 1699439557127, + "@context" : { + "dct" : "https://purl.org/dc/terms/", + "tx" : "https://w3id.org/tractusx/v0.0.1/ns/", + "edc" : "https://w3id.org/edc/v0.0.1/ns/", + "dcat" : "https://www.w3.org/ns/dcat/", + "odrl" : "http://www.w3.org/ns/odrl/2/", + "dspace" : "https://w3id.org/dspace/v0.8/" + } +} diff --git a/consumer-backend/productpass/src/test/resources/dpp/negotiation/TestResponseNegotiation.json b/consumer-backend/productpass/src/test/resources/dpp/negotiation/TestResponseNegotiation.json new file mode 100644 index 000000000..42efa386c --- /dev/null +++ b/consumer-backend/productpass/src/test/resources/dpp/negotiation/TestResponseNegotiation.json @@ -0,0 +1,18 @@ +{ + "@type": "edc:ContractNegotiationDto", + "@id": "189f4957-0fbe-4d73-b215-977e3303a45e", + "edc:type": "CONSUMER", + "edc:protocol": "dataspace-protocol-http", + "edc:state": "FINALIZED", + "edc:counterPartyAddress": "https://materialpass.int.demo.catena-x.net/BPNL000000000000/api/v1/dsp", + "edc:callbackAddresses": [], + "edc:contractAgreementId": "ZGVmYXVsdC1jb250cmFjdC1kZWZpbml0aW9u:cmVnaXN0cnktYXNzZXQ=:NmRjMDFlOTQtMGE0MC00MTQzLThhOTYtY2IyMmYxN2JjZGJj", + "@context": { + "dct": "https://purl.org/dc/terms/", + "tx": "https://w3id.org/tractusx/v0.0.1/ns/", + "edc": "https://w3id.org/edc/v0.0.1/ns/", + "dcat": "https://www.w3.org/ns/dcat/", + "odrl": "http://www.w3.org/ns/odrl/2/", + "dspace": "https://w3id.org/dspace/v0.8/" + } +} diff --git a/consumer-backend/productpass/src/test/resources/dpp/payloads/TestPassport.json b/consumer-backend/productpass/src/test/resources/dpp/payloads/TestPassport.json new file mode 100644 index 000000000..3310386e8 --- /dev/null +++ b/consumer-backend/productpass/src/test/resources/dpp/payloads/TestPassport.json @@ -0,0 +1,248 @@ +{ + "electrochemicalProperties" : { + "ratedCapacity" : 94, + "batteryEnergy" : { + "energyRoundtripEfficiencyChange" : 48.2, + "maximumAllowedBatteryEnergy" : 85000, + "energyRoundtripEfficiency" : 25 + }, + "ratioMaximumAllowedBatteryPowerAndMaximumAllowedBatteryEnergy" : 0.588, + "batteryVoltage" : { + "nominalVoltage" : 3.7, + "maxVoltage" : 4.2, + "minVoltage" : 2.5 + }, + "internalResistance" : { + "cellinternalResistance" : 0.36, + "packinternalResistanceIncrease" : 1, + "packinternalResistance" : 100 + }, + "capacityThresholdExhaustion" : 23, + "batteryPower" : { + "powerFade" : 23, + "originalPowerCapability" : -1.7976931348623157E308, + "originalPowerCapabilityLimits" : -1.7976931348623157E308, + "maximumAllowedBatteryPower" : -1.7976931348623157E308, + "powerCapabilityAt20Charge" : -1.7976931348623157E308, + "powerCapabilityAt80Charge" : -1.7976931348623157E308 + }, + "capacityFade" : 1.55 + }, + "document" : { + "responsibleSourcing" : [ { + "title" : "2021 Responsible Sourcing document", + "fileLocation" : null + } ], + "packagingInstructions" : [ { + "title" : "Packing Instruction v.2.0", + "fileLocation" : null + } ], + "transportationInstructions" : [ { + "title" : "Transport manual", + "fileLocation" : null + } ], + "vehicleDismantlingProcedure" : [ { + "title" : "Car dismantling manual", + "fileLocation" : "http://www.ietf.org/rfc/rfc2396.txt" + } ], + "testReportsResults" : [ { + "title" : "Battery Test Reports", + "fileLocation" : "http://www.Batterytestreports.de" + } ], + "batteryDismantlingProcedure" : [ { + "title" : "Dismantling Manual", + "fileLocation" : "http://www.dissmantlingmanual.org" + } ], + "safetyMeasures" : [ { + "title" : "Safety Instruction", + "fileLocation" : "http://www.safetyinstructions.txt" + } ], + "declarationOfConformity" : [ { + "title" : "Declaration of Conformity No. 3", + "fileLocation" : null + } ] + }, + "datePlacedOnMarket" : "27.04.2022", + "cellChemistry" : { + "electrolyteComposition" : [ { + "materialPercentageMassFraction" : null, + "materialWeight" : null, + "materialName" : "dimethyl carbonate (DCM)" + } ], + "anodeCompositionOther" : [ { + "materialPercentageMassFraction" : null, + "materialWeight" : null, + "materialName" : "Carboxymethyl cellulose" + } ], + "recyclateContentActiveMaterials" : [ { + "materialPercentageMassFraction" : 6, + "materialWeight" : null, + "materialName" : "Ni/2021/PlantE" + }, { + "materialPercentageMassFraction" : 4, + "materialWeight" : null, + "materialName" : "Li/2021/PlantE" + }, { + "materialPercentageMassFraction" : 0, + "materialWeight" : null, + "materialName" : "Pb(battery model does not contain Pb)" + }, { + "materialPercentageMassFraction" : 0, + "materialWeight" : null, + "materialName" : "Co(battery model does not contain Pb)" + } ], + "anodeActiveMaterials" : [ { + "materialPercentageMassFraction" : null, + "materialWeight" : null, + "materialName" : "Graphite" + } ], + "cathodeActiveMaterials" : [ { + "materialPercentageMassFraction" : null, + "materialWeight" : null, + "materialName" : "LiMn2O4 Lithium Manganese Oxide" + } ], + "cathodeCompositionOther" : [ { + "materialPercentageMassFraction" : null, + "materialWeight" : null, + "materialName" : "binder:PVDF" + } ] + }, + "physicalDimensions" : { + "length" : 2000, + "width" : 1000, + "weight" : 3500, + "diameter" : null, + "height" : 200 + }, + "temperatureRangeIdleState" : { + "temperatureRangeIdleStateUpperLimit" : 50, + "temperatureRangeIdleStateLowerLimit" : -20 + }, + "batteryCycleLife" : { + "cycleLifeTestCRate" : 2, + "cycleLifeTestDepthOfDischarge" : 1.8, + "expectedLifetime" : 2500 + }, + "manufacturer" : { + "name" : "CompanyE", + "contact" : { + "faxNumber" : "+49 89 0987654324", + "website" : "https://www.CompanyE.com", + "phoneNumber" : "+49 89 1234567893", + "email" : "companyE@company.com" + }, + "address" : { + "locality" : { + "value" : "CityE", + "technicalKey" : "BLOCK" + }, + "country" : { + "shortName" : "Germany" + }, + "postCode" : { + "value" : "65-250E", + "technicalKey" : "CEDEX" + }, + "thoroughfare" : { + "value" : "StreetE", + "number" : "1", + "technicalKey" : "STREET" + }, + "premise" : { + "value" : null, + "technicalKey" : "BUILDING" + }, + "postalDeliveryPoint" : { + "value" : null, + "technicalKey" : "intERURBAN_DELIVERY_POint" + } + } + }, + "warrantyPeriod" : "96", + "composition" : { + "compositionOfBattery" : [ { + "materialPercentageMassFraction" : null, + "materialWeight" : null, + "materialName" : "Separator: PE" + } ], + "criticalRawMaterials" : "Lithium, Natural graphite", + "components" : { + "componentsPartNumber" : "Voltage cables", + "componentsSupplier" : [ { + "componentsSupplierName" : "AB Corporation", + "address" : { + "locality" : { + "value" : "CityF", + "technicalKey" : "BLOCK" + }, + "country" : { + "shortName" : "Germany" + }, + "postCode" : { + "value" : "65-250F", + "technicalKey" : "CEDEX" + }, + "thoroughfare" : { + "value" : "StreetF", + "number" : "1", + "technicalKey" : "STREET" + }, + "premise" : { + "value" : "PlantF", + "technicalKey" : "BUILDING" + }, + "postalDeliveryPoint" : { + "value" : null, + "technicalKey" : "INTERURBAN_DELIVERY_POINT" + } + }, + "contact" : { + "faxNumber" : "+49 89 0987654324", + "website" : "https://www.companyF.com", + "phoneNumber" : "+49 89 1234567893", + "email" : "companyF@companyF.com" + } + } ] + } + }, + "manufacturing" : { + "dateOfManufacturing" : "2022-01-24", + "address" : { + "locality" : { + "value" : "CityE", + "technicalKey" : "BLOCK" + }, + "country" : { + "shortName" : "Germany" + }, + "postCode" : { + "value" : "65-250E", + "technicalKey" : "CEDEX" + }, + "thoroughfare" : { + "value" : "StreetE", + "number" : "1", + "technicalKey" : "STREET" + }, + "premise" : { + "value" : "PlantE", + "technicalKey" : "BUILDING" + }, + "postalDeliveryPoint" : { + "value" : "GateE", + "technicalKey" : "INTERURBAN_DELIVERY_POINT" + } + } + }, + "batteryIdentification" : { + "batteryType" : "Lithium-Manganese-Oxide (LMO)", + "batteryIDDMCCode" : "IMR18650V1", + "batteryModel" : "Pi4 Orionis" + }, + "stateOfBattery" : { + "stateOfHealth" : 20, + "statusBattery" : "first life", + "stateOfCharge" : 50 + }, + "cO2FootprintTotal" : 210 + } diff --git a/consumer-backend/productpass/src/test/resources/dpp/token/MockedToken.json b/consumer-backend/productpass/src/test/resources/dpp/token/MockedToken.json new file mode 100644 index 000000000..5ce80313f --- /dev/null +++ b/consumer-backend/productpass/src/test/resources/dpp/token/MockedToken.json @@ -0,0 +1,9 @@ +{ + "access_token" : "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJIVUgzYjZrMzZvbFNQVTRDRTRaMVUxUjhVeHg4eFQwS3p4QXdLb3NkVk1VIn0.eyJleHAiOjE3MDEyNDYxNjMsImlhdCI6MTcwMTI0NTg2MywianRpIjoiNTEyNDNmOTAtNzk5MC00YTNkLWFkYjAtNDVhOWVkZmJhMGIzIiwiaXNzIjoiaHR0cHM6Ly9jZW50cmFsaWRwLmludC5kZW1vLmNhdGVuYS14Lm5ldC9hdXRoL3JlYWxtcy9DWC1DZW50cmFsIiwiYXVkIjpbIkNsMjItQ1gtQlBORCIsIkNsMjEtQ1gtREYiLCJ0ZWNobmljYWxfcm9sZXNfbWFuYWdlbWVudCIsIkNsNS1DWC1DdXN0b2RpYW4iLCJDbDItQ1gtUG9ydGFsIiwiYWNjb3VudCIsIkNsMy1DWC1TZW1hbnRpYyJdLCJzdWIiOiJlMzk2MmFiMi00MWQ2LTQ3NmUtODMwZS1jYzhkMjZjM2VjMzkiLCJ0eXAiOiJCZWFyZXIiLCJhenAiOiJzYTI0MSIsImFsbG93ZWQtb3JpZ2lucyI6WyJodHRwczovL251bGwiXSwicmVhbG1fYWNjZXNzIjp7InJvbGVzIjpbIm9mZmxpbmVfYWNjZXNzIiwiZGVmYXVsdC1yb2xlcy1jYXRlbmEteCByZWFsbSIsInVtYV9hdXRob3JpemF0aW9uIl19LCJyZXNvdXJjZV9hY2Nlc3MiOnsiQ2wyMi1DWC1CUE5EIjp7InJvbGVzIjpbInZpZXdfYnBuX2Rpc2NvdmVyeSIsImRlbGV0ZV9icG5fZGlzY292ZXJ5IiwiYWRkX2Jwbl9kaXNjb3ZlcnkiXX0sIkNsMjEtQ1gtREYiOnsicm9sZXMiOlsidmlld19kaXNjb3ZlcnlfZW5kcG9pbnQiXX0sInRlY2huaWNhbF9yb2xlc19tYW5hZ2VtZW50Ijp7InJvbGVzIjpbIkRhdGFzcGFjZSBEaXNjb3ZlcnkiLCJTZW1hbnRpYyBNb2RlbCBNYW5hZ2VtZW50IiwiQ1ggTWVtYmVyc2hpcCBJbmZvIl19LCJDbDUtQ1gtQ3VzdG9kaWFuIjp7InJvbGVzIjpbInZpZXdfd2FsbGV0Il19LCJDbDItQ1gtUG9ydGFsIjp7InJvbGVzIjpbInZpZXdfY29ubmVjdG9ycyIsInZpZXdfbWVtYmVyc2hpcCJdfSwiYWNjb3VudCI6eyJyb2xlcyI6WyJtYW5hZ2UtYWNjb3VudCIsIm1hbmFnZS1hY2NvdW50LWxpbmtzIiwidmlldy1wcm9maWxlIl19LCJDbDMtQ1gtU2VtYW50aWMiOnsicm9sZXMiOlsidmlld19zZW1hbnRpY19tb2RlbCJdfX0sInNjb3BlIjoib3BlbmlkIHByb2ZpbGUgZW1haWwiLCJicG4iOiJCUE5MMDAwMDAwMDBDQkE1IiwiY2xpZW50SG9zdCI6IjEwLjI0MC4wLjQiLCJjbGllbnRJZCI6InNhMjQxIiwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJzZXJ2aWNlLWFjY291bnQtc2EyNDEiLCJjbGllbnRBZGRyZXNzIjoiMTAuMjQwLjAuNCJ9.VKHzxWS8myBybtwNNcsZ2dnn5D899a4y9zi2uuHPyuC4FOC0vpUXH620qOak84oy1tlSu8hg9m5qLmrPg1D3_YJHPEi7Q1eGOaCWN9R6JQ4PQQbCgsi3q2GLWm5eRtLR-4CE3MCrNp_8-tqz9oiTARO5r4LY6YcLkIydtOwncTm3hzGUqwl6VlCb3birih2xyvyANqptr52-odBjxvqaTwSTqBBH_FEJQvxrFt8gl3rkgf4tBYbltCbDsvWZt3qkAK_RhRsO6AJOPL8vIU1_tsHGwaULIAzkWH_zYgo_rgyrjTrUIE8PXLJPpJ1bk6zwKtfmFYqGTxGsMEaBC1QfgQ", + "expires_in" : 300, + "refresh_expires_in" : 0, + "token_type" : "Bearer", + "id_token" : "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJIVUgzYjZrMzZvbFNQVTRDRTRaMVUxUjhVeHg4eFQwS3p4QXdLb3NkVk1VIn0.eyJleHAiOjE3MDEyNDYxNjMsImlhdCI6MTcwMTI0NTg2MywiYXV0aF90aW1lIjowLCJqdGkiOiI2MGEyMWExMS0yZTM5LTQ1NWQtYmE5Yy02NjMxOGI5MTNlNTQiLCJpc3MiOiJodHRwczovL2NlbnRyYWxpZHAuaW50LmRlbW8uY2F0ZW5hLXgubmV0L2F1dGgvcmVhbG1zL0NYLUNlbnRyYWwiLCJhdWQiOiJzYTI0MSIsInN1YiI6ImUzOTYyYWIyLTQxZDYtNDc2ZS04MzBlLWNjOGQyNmMzZWMzOSIsInR5cCI6IklEIiwiYXpwIjoic2EyNDEiLCJhdF9oYXNoIjoiTmpESGRUUHpJbzZ4ZnlxYV9oQ1UwUSIsImJwbiI6IkJQTkwwMDAwMDAwMENCQTUiLCJjbGllbnRIb3N0IjoiMTAuMjQwLjAuNCIsImNsaWVudElkIjoic2EyNDEiLCJlbWFpbF92ZXJpZmllZCI6ZmFsc2UsInByZWZlcnJlZF91c2VybmFtZSI6InNlcnZpY2UtYWNjb3VudC1zYTI0MSIsImNsaWVudEFkZHJlc3MiOiIxMC4yNDAuMC40In0.cv3LbOCHCzUhGh7GBr7nP2oBpYqUWCjBoAtgOLVjPdOJMFUIUggDXoRQMOGJCi9iyOqkrrkMcIXkMxxq8UI3FqmKzwAvGE3XOPniOvgA9JlHthQyX6QY4Sdifw1u9tVxHr-s_sHMss2iNYmxICRQLj08vfzbw41x0YG07hRIE6V7QwVCTxgXehbyJaKuPTiRk6T6npERHFUxKQZF3W_2wObvYqYzhlfOvWK04pZs1jQHyEQ_6QqtIsFc-fg7TBwgBvm2K40zr_-AmxG-Q6S9upckedj8GFCevUWs-k9BnaXhYV0zoIMPw7V-FD3XzmvP9wsGVhkBDYUwC_g0-o55ow", + "not-before-policy" : "1660280763", + "scope" : "openid profile email" +} diff --git a/consumer-backend/productpass/src/test/resources/dpp/token/MockedUserInfo.json b/consumer-backend/productpass/src/test/resources/dpp/token/MockedUserInfo.json new file mode 100644 index 000000000..90ed0fdec --- /dev/null +++ b/consumer-backend/productpass/src/test/resources/dpp/token/MockedUserInfo.json @@ -0,0 +1,5 @@ +{ + "sub" : "e3962ab2-41d6-476e-830e-cc8d26c3ec39", + "email_verified" : "false", + "preferred_username" : "service-account-sa241" +} diff --git a/consumer-backend/productpass/src/test/resources/dpp/transfer/TestResponseInitTransfer.json b/consumer-backend/productpass/src/test/resources/dpp/transfer/TestResponseInitTransfer.json new file mode 100644 index 000000000..c820dd975 --- /dev/null +++ b/consumer-backend/productpass/src/test/resources/dpp/transfer/TestResponseInitTransfer.json @@ -0,0 +1,13 @@ +{ + "@type": "edc:IdResponseDto", + "@id": "9ab72e5b-f2d4-4f60-85e6-0985f9b6b579", + "edc:createdAt": 1699439575484, + "@context": { + "dct": "https://purl.org/dc/terms/", + "tx": "https://w3id.org/tractusx/v0.0.1/ns/", + "edc": "https://w3id.org/edc/v0.0.1/ns/", + "dcat": "https://www.w3.org/ns/dcat/", + "odrl": "http://www.w3.org/ns/odrl/2/", + "dspace": "https://w3id.org/dspace/v0.8/" + } +} diff --git a/consumer-backend/productpass/src/test/resources/dpp/transfer/TestResponseTransfer.json b/consumer-backend/productpass/src/test/resources/dpp/transfer/TestResponseTransfer.json new file mode 100644 index 000000000..a244baa7e --- /dev/null +++ b/consumer-backend/productpass/src/test/resources/dpp/transfer/TestResponseTransfer.json @@ -0,0 +1,27 @@ +{ + "@id": "9ab72e5b-f2d4-4f60-85e6-0985f9b6b579", + "@type": "edc:TransferProcessDto", + "edc:state": "COMPLETED", + "edc:stateTimestamp": 1699439577253, + "edc:type": "CONSUMER", + "edc:callbackAddresses": [], + "edc:dataDestination": { + "edc:type": "HttpProxy" + }, + "edc:dataRequest": { + "@type": "edc:DataRequestDto", + "@id": "9ab72e5b-f2d4-4f60-85e6-0985f9b6b579", + "edc:assetId": "365e6fbe-bb34-11ec-8422-0242ac120002-61125dc3-5e6f-4f4b-838d-447432b97918", + "edc:contractId": "ZGVmYXVsdC1jb250cmFjdC1kZWZpbml0aW9u:cmVnaXN0cnktYXNzZXQ=:NmRjMDFlOTQtMGE0MC00MTQzLThhOTYtY2IyMmYxN2JjZGJj", + "edc:connectorId": "BPNL00000000CBA5" + }, + "edc:receiverHttpEndpoint": "https://materialpass.int.demo.catena-x.net/BPNL000000000000/endpoint/ebc08cdc-fc22-41e8-9394-81142de0b35a/365e6fbe-bb34-11ec-8422-0242ac120002-61125dc3-5e6f-4f4b-838d-447432b97918", + "@context": { + "dct": "https://purl.org/dc/terms/", + "tx": "https://w3id.org/tractusx/v0.0.1/ns/", + "edc": "https://w3id.org/edc/v0.0.1/ns/", + "dcat": "https://www.w3.org/ns/dcat/", + "odrl": "http://www.w3.org/ns/odrl/2/", + "dspace": "https://w3id.org/dspace/v0.8/" + } +} From 8ebb4e7349749cceb84d4aa36c064d07e53a1b9b Mon Sep 17 00:00:00 2001 From: Mathias Brunkow Moser Date: Mon, 8 Jan 2024 17:53:27 +0100 Subject: [PATCH 4/6] fix: fixed all the unit tests to the new v2.0.1 version Co-authored-by: Mathias Brunkow Moser Co-authored-by: Mathias Moser <71728767+matbmoser@users.noreply.github.com> Co-authored-by: Parracho Co-authored-by: Diogo Parracho <136568749+dsrparracho@users.noreply.github.com> --- .../api/ContractControllerTest.java | 481 ------------------ .../java}/managers/DtrSearchManagerTest.java | 55 +- .../java}/managers/ProcessDataModelTest.java | 13 +- .../java}/managers/ProcessManagerTest.java | 79 +-- .../test/java}/managers/TreeManagerTest.java | 34 +- .../test/java/mocks/MockedHttpSession.java | 0 .../test/java}/services/AasServiceTest.java | 82 +-- .../services/AuthenticationServiceTest.java | 40 +- .../java}/services/CatenaXServiceTest.java | 71 +-- .../java}/services/DataPlaneServiceTest.java | 12 +- .../services/DataTransferServiceTest.java | 79 +-- .../test/java}/services/IrsServiceTest.java | 64 ++- .../src/test/resources/application-test.yml | 144 ++++++ .../test/resources/dpp/assets/TestAsset.json | 0 .../catalogs/TestContractOfferCatalog.json | 2 +- .../dpp/catalogs/TestDigitalTwinCatalog.json | 2 +- .../dpp/contractpolicies/TestPolicy.json | 0 .../dpp/digitaltwins/TestDigitalTwin.json | 0 .../discovery/MockedDiscoveryEndpoints.json | 0 .../resources/dpp/irs/TestJobHistory.json | 0 .../resources/dpp/irs/TestJobResponse.json | 0 .../dpp/irs/TestStartJobResponse.json | 0 .../resources/dpp/irs/TestTreeDataModel.json | 0 .../TestResponseInitNegotiation.json | 0 .../negotiation/TestResponseNegotiation.json | 0 .../resources/dpp/payloads/TestPassport.json | 0 .../test/resources/dpp/token/MockedToken.json | 0 .../resources/dpp/token/MockedUserInfo.json | 0 .../transfer/TestResponseInitTransfer.json | 0 .../dpp/transfer/TestResponseTransfer.json | 0 30 files changed, 441 insertions(+), 717 deletions(-) delete mode 100644 consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/http/controllers/api/ContractControllerTest.java rename {consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass => dpp-backend/digitalproductpass/src/test/java}/managers/DtrSearchManagerTest.java (81%) rename {consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass => dpp-backend/digitalproductpass/src/test/java}/managers/ProcessDataModelTest.java (83%) rename {consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass => dpp-backend/digitalproductpass/src/test/java}/managers/ProcessManagerTest.java (88%) rename {consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass => dpp-backend/digitalproductpass/src/test/java}/managers/TreeManagerTest.java (83%) rename {consumer-backend/productpass => dpp-backend/digitalproductpass}/src/test/java/mocks/MockedHttpSession.java (100%) rename {consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass => dpp-backend/digitalproductpass/src/test/java}/services/AasServiceTest.java (76%) rename {consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass => dpp-backend/digitalproductpass/src/test/java}/services/AuthenticationServiceTest.java (66%) rename {consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass => dpp-backend/digitalproductpass/src/test/java}/services/CatenaXServiceTest.java (80%) rename {consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass => dpp-backend/digitalproductpass/src/test/java}/services/DataPlaneServiceTest.java (85%) rename {consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass => dpp-backend/digitalproductpass/src/test/java}/services/DataTransferServiceTest.java (76%) rename {consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass => dpp-backend/digitalproductpass/src/test/java}/services/IrsServiceTest.java (67%) create mode 100644 dpp-backend/digitalproductpass/src/test/resources/application-test.yml rename {consumer-backend/productpass => dpp-backend/digitalproductpass}/src/test/resources/dpp/assets/TestAsset.json (100%) rename {consumer-backend/productpass => dpp-backend/digitalproductpass}/src/test/resources/dpp/catalogs/TestContractOfferCatalog.json (97%) rename {consumer-backend/productpass => dpp-backend/digitalproductpass}/src/test/resources/dpp/catalogs/TestDigitalTwinCatalog.json (97%) rename {consumer-backend/productpass => dpp-backend/digitalproductpass}/src/test/resources/dpp/contractpolicies/TestPolicy.json (100%) rename {consumer-backend/productpass => dpp-backend/digitalproductpass}/src/test/resources/dpp/digitaltwins/TestDigitalTwin.json (100%) rename {consumer-backend/productpass => dpp-backend/digitalproductpass}/src/test/resources/dpp/discovery/MockedDiscoveryEndpoints.json (100%) rename {consumer-backend/productpass => dpp-backend/digitalproductpass}/src/test/resources/dpp/irs/TestJobHistory.json (100%) rename {consumer-backend/productpass => dpp-backend/digitalproductpass}/src/test/resources/dpp/irs/TestJobResponse.json (100%) rename {consumer-backend/productpass => dpp-backend/digitalproductpass}/src/test/resources/dpp/irs/TestStartJobResponse.json (100%) rename {consumer-backend/productpass => dpp-backend/digitalproductpass}/src/test/resources/dpp/irs/TestTreeDataModel.json (100%) rename {consumer-backend/productpass => dpp-backend/digitalproductpass}/src/test/resources/dpp/negotiation/TestResponseInitNegotiation.json (100%) rename {consumer-backend/productpass => dpp-backend/digitalproductpass}/src/test/resources/dpp/negotiation/TestResponseNegotiation.json (100%) rename {consumer-backend/productpass => dpp-backend/digitalproductpass}/src/test/resources/dpp/payloads/TestPassport.json (100%) rename {consumer-backend/productpass => dpp-backend/digitalproductpass}/src/test/resources/dpp/token/MockedToken.json (100%) rename {consumer-backend/productpass => dpp-backend/digitalproductpass}/src/test/resources/dpp/token/MockedUserInfo.json (100%) rename {consumer-backend/productpass => dpp-backend/digitalproductpass}/src/test/resources/dpp/transfer/TestResponseInitTransfer.json (100%) rename {consumer-backend/productpass => dpp-backend/digitalproductpass}/src/test/resources/dpp/transfer/TestResponseTransfer.json (100%) diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/http/controllers/api/ContractControllerTest.java b/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/http/controllers/api/ContractControllerTest.java deleted file mode 100644 index 8ca4b344b..000000000 --- a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/http/controllers/api/ContractControllerTest.java +++ /dev/null @@ -1,481 +0,0 @@ -package org.eclipse.tractusx.productpass.http.controllers.api; - -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import org.eclipse.tractusx.productpass.config.DiscoveryConfig; -import org.eclipse.tractusx.productpass.config.DtrConfig; -import org.eclipse.tractusx.productpass.config.PassportConfig; -import org.eclipse.tractusx.productpass.config.ProcessConfig; -import org.eclipse.tractusx.productpass.exceptions.ServiceInitializationException; -import org.eclipse.tractusx.productpass.managers.DtrSearchManager; -import org.eclipse.tractusx.productpass.managers.ProcessDataModel; -import org.eclipse.tractusx.productpass.managers.ProcessManager; -import org.eclipse.tractusx.productpass.models.catenax.BpnDiscovery; -import org.eclipse.tractusx.productpass.models.http.Response; -import org.eclipse.tractusx.productpass.models.http.requests.DiscoverySearch; -import org.eclipse.tractusx.productpass.models.http.requests.Search; -import org.eclipse.tractusx.productpass.models.http.requests.TokenRequest; -import org.eclipse.tractusx.productpass.models.manager.History; -import org.eclipse.tractusx.productpass.models.manager.Process; -import org.eclipse.tractusx.productpass.models.manager.Status; -import org.eclipse.tractusx.productpass.services.*; -import org.junit.jupiter.api.*; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.springframework.core.env.Environment; -import org.springframework.mock.env.MockEnvironment; -import org.springframework.test.util.ReflectionTestUtils; -import utils.*; - -import java.util.*; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.when; - -@TestInstance(TestInstance.Lifecycle.PER_CLASS) -@TestMethodOrder(MethodOrderer.OrderAnnotation.class) -class ContractControllerTest { - @Mock - private HttpServletRequest httpRequest; - @Mock - private HttpServletResponse httpResponse; - private DataTransferService dataService; - @Mock - private VaultService vaultService; - private AasService aasService; - private AuthenticationService authService; - private PassportConfig passportConfig; - private DiscoveryConfig discoveryConfig; - private DtrConfig dtrConfig; - @Mock - private Environment env; - ProcessManager processManager; - DtrSearchManager dtrSearchManager; - private ProcessConfig processConfig; - CatenaXService catenaXService; - HttpUtil httpUtil; - private JsonUtil jsonUtil; - private FileUtil fileUtil; - private YamlUtil yamlUtil; - private ContractController contractController; - private Map configuration; - - @BeforeAll - void setUpAll() throws ServiceInitializationException { - MockitoAnnotations.openMocks(this); - - fileUtil = new FileUtil(); - yamlUtil = new YamlUtil(fileUtil); - jsonUtil = new JsonUtil(fileUtil); - - Map application = yamlUtil.readFile(FileUtil.getWorkdirPath() + "/src/main/resources/application.yml"); - configuration = (Map) jsonUtil.toMap(application.get("configuration")); - - env = initEnv(); - httpUtil = Mockito.spy(new HttpUtil(env)); - - Map vaultConfig = yamlUtil.readFile(fileUtil.getDataDir() + "/VaultConfig/vault.token.yml"); - Map client = (Map) jsonUtil.toMap(vaultConfig.get("client")); - when(vaultService.getLocalSecret("client.id")).thenReturn(client.get("id").toString()); - when(vaultService.getLocalSecret("client.secret")).thenReturn(client.get("secret").toString()); - Map edc = (Map) jsonUtil.toMap(vaultConfig.get("edc")); - when(vaultService.getLocalSecret("edc.apiKey")).thenReturn(edc.get("apiKey").toString()); - when(vaultService.getLocalSecret("edc.participantId")).thenReturn(edc.get("participantId").toString()); - - Map passport = (Map) jsonUtil.toMap(configuration.get("passport")); - passportConfig = new PassportConfig(); - passportConfig.setSearchIdSchema(passport.get("searchIdSchema").toString()); - dtrConfig = initDtrConfig(); - discoveryConfig = initDiscoveryConfig(); - processConfig = new ProcessConfig(); - processConfig.setDir("process"); - - - dataService = new DataTransferService(env, httpUtil, jsonUtil,vaultService, processManager, dtrConfig); - authService = new AuthenticationService(vaultService, env, httpUtil, jsonUtil); - catenaXService = Mockito.spy(new CatenaXService(env, fileUtil, httpUtil, jsonUtil, vaultService, dtrSearchManager, authService, discoveryConfig, dataService, dtrConfig)); - processManager = Mockito.spy(new ProcessManager(httpUtil,jsonUtil, fileUtil, processConfig)); - dtrSearchManager = new DtrSearchManager(fileUtil,jsonUtil, dataService, dtrConfig, processManager); - aasService = new AasService(env, httpUtil, jsonUtil, authService, dtrConfig, dtrSearchManager, processManager, dataService, passportConfig); - - contractController = initController(); - - } - - private ContractController initController() { - ContractController controller = new ContractController(); - ReflectionTestUtils.setField(controller, "httpRequest", httpRequest); - ReflectionTestUtils.setField(controller, "httpResponse", httpResponse); - ReflectionTestUtils.setField(controller, "dataService", dataService); - ReflectionTestUtils.setField(controller, "vaultService", vaultService); - ReflectionTestUtils.setField(controller, "aasService", aasService); - ReflectionTestUtils.setField(controller, "authService", authService); - ReflectionTestUtils.setField(controller, "passportConfig", passportConfig); - ReflectionTestUtils.setField(controller, "discoveryConfig", discoveryConfig); - ReflectionTestUtils.setField(controller, "dtrConfig", dtrConfig); - ReflectionTestUtils.setField(controller, "env", env); - ReflectionTestUtils.setField(controller, "processManager", processManager); - ReflectionTestUtils.setField(controller, "dtrSearchManager", dtrSearchManager); - ReflectionTestUtils.setField(controller, "processConfig", processConfig); - ReflectionTestUtils.setField(controller, "catenaXService", catenaXService); - ReflectionTestUtils.setField(controller, "httpUtil", httpUtil); - ReflectionTestUtils.setField(controller, "jsonUtil", jsonUtil); - - - return controller; - } - - private DtrConfig initDtrConfig() { - DtrConfig dtrConfig = new DtrConfig(); - DtrConfig.Timeouts timeouts = new DtrConfig.Timeouts(); - timeouts.setSearch(10); - timeouts.setNegotiation(40); - timeouts.setTransfer(10); - timeouts.setDigitalTwin(20); - dtrConfig.setTimeouts(timeouts); - dtrConfig.setTemporaryStorage(new DtrConfig.TemporaryStorage(true, 12)); - - Map dtr = (Map) jsonUtil.toMap(configuration.get("dtr")); - Map decentralApis = (Map) jsonUtil.toMap(dtr.get("decentralApis")); - DtrConfig.DecentralApis decentralApisObj = new DtrConfig.DecentralApis(); - decentralApisObj.setSearch(decentralApis.get("search").toString()); - decentralApisObj.setDigitalTwin(decentralApis.get("digitalTwin").toString()); - decentralApisObj.setSubModel(decentralApis.get("subModel").toString()); - dtrConfig.setDecentralApis(decentralApisObj); - - dtrConfig.setSemanticIdTypeKey(dtr.get("semanticIdTypeKey").toString()); - - return dtrConfig; - } - - private DiscoveryConfig initDiscoveryConfig() { - DiscoveryConfig discoveryConfig = new DiscoveryConfig(); - Map discovery = (Map) jsonUtil.toMap(configuration.get("discovery")); - discoveryConfig.setEndpoint(discovery.get("endpoint").toString()); - discoveryConfig.setEdc((DiscoveryConfig.EDCConfig) jsonUtil.bindObject(discovery.get("edc"), DiscoveryConfig.EDCConfig.class)); - discoveryConfig.setBpn((DiscoveryConfig.BPNConfig) jsonUtil.bindObject(discovery.get("bpn"), DiscoveryConfig.BPNConfig.class)); - return discoveryConfig; - } - - private MockEnvironment initEnv() { - MockEnvironment env = new MockEnvironment(); - Map edc = (Map) jsonUtil.toMap(configuration.get("edc")); - env.setProperty("configuration.edc.endpoint", edc.get("endpoint").toString()); - env.setProperty("configuration.edc.catalog", edc.get("catalog").toString()); - env.setProperty("configuration.edc.management", edc.get("management").toString()); - env.setProperty("configuration.edc.negotiation", edc.get("negotiation").toString()); - env.setProperty("configuration.edc.transfer", edc.get("transfer").toString()); - - Map keycloak = (Map) jsonUtil.toMap(configuration.get("keycloak")); - env.setProperty("configuration.keycloak.tokenUri", keycloak.get("tokenUri").toString()); - env.setProperty("configuration.keycloak.userInfoUri", keycloak.get("userInfoUri").toString()); - - return env; - } - - @Test - @Order(1) - void createNotAuthorizedResponse() { - Response response = contractController.create(null); - - assertEquals(401, response.getStatus()); - assertEquals("Not Authorized", response.getStatusText()); - } - @Test - void createBadRequestMissingMandatoryParametersResponse() { - String token = authService.getToken().getAccessToken(); - when(httpRequest.getHeader("Authorization")).thenReturn("Bearer " + token); - - Response response = contractController.create(new DiscoverySearch()); - - assertEquals(400, response.getStatus()); - assertEquals("Bad Request", response.getStatusText()); - assertEquals("One or all the mandatory parameters [id] are missing", response.getMessage()); - } - - @Test - void createNotFoundBpnNumberResponse() { - - String token = authService.getToken().getAccessToken(); - when(httpRequest.getHeader("Authorization")).thenReturn("Bearer " + token); - - DiscoverySearch discoverySearch = new DiscoverySearch(); - discoverySearch.setId("XYZ78901"); - Response response = contractController.create(discoverySearch); - - assertEquals(404, response.getStatus()); - assertEquals("Not Found", response.getStatusText()); - assertEquals("Failed to get the bpn number from the discovery service", response.getMessage()); - - } - - @Test - void createInternalServerErrorCantStartProcess() { - - String token = authService.getToken().getAccessToken(); - when(httpRequest.getHeader("Authorization")).thenReturn("Bearer " + token); - BpnDiscovery.BpnEndpoint bpnDiscoveryEndpoint = new BpnDiscovery.BpnEndpoint(); - bpnDiscoveryEndpoint.setKey("bpn"); - bpnDiscoveryEndpoint.setResourceId(UUID.randomUUID().toString()); - bpnDiscoveryEndpoint.setType("TEST"); - bpnDiscoveryEndpoint.setValue("BPN00000"); - BpnDiscovery bpnDiscovery = new BpnDiscovery(new ArrayList<>(){{add(bpnDiscoveryEndpoint);}}); - - doReturn(List.of(bpnDiscovery)).when(catenaXService).getBpnDiscovery(anyString(), anyString()); - - - DiscoverySearch discoverySearch = new DiscoverySearch(); - discoverySearch.setId("XYZ78901"); - Response response = contractController.create(discoverySearch); - - LogUtil.printMessage(jsonUtil.toJson(response, true)); - - assertEquals(500, response.getStatus()); - assertEquals("Internal Server Error", response.getStatusText()); - assertEquals("It was not possible to create the process and search for the decentral digital twin registries", response.getMessage()); - - } - - @Test - @Order(2) - void searchNotAuthorizeResponse() { - Response response = contractController.search(null); - - assertEquals(401, response.getStatus()); - assertEquals("Not Authorized", response.getStatusText()); - } - - @Test - void searchBadRequestMissingMandatoryParametersResponse() { - String token = authService.getToken().getAccessToken(); - when(httpRequest.getHeader("Authorization")).thenReturn("Bearer " + token); - - Response response = contractController.search(new Search()); - - assertEquals(400, response.getStatus()); - assertEquals("Bad Request", response.getStatusText()); - assertEquals("One or all the mandatory parameters [id] are missing", response.getMessage()); - } - - @Test - void searchBadRequestProcessIdNullResponse() { - - String token = authService.getToken().getAccessToken(); - when(httpRequest.getHeader("Authorization")).thenReturn("Bearer " + token); - - Search search = new Search(); - search.setId("XYZ78901"); - Response response = contractController.search(search); - - assertEquals(400, response.getStatus()); - assertEquals("Bad Request", response.getStatusText()); - assertEquals("No processId was found on the request body!", response.getMessage()); - - } - - @Test - void searchBadRequestProcessIdEmptyResponse() { - - String token = authService.getToken().getAccessToken(); - when(httpRequest.getHeader("Authorization")).thenReturn("Bearer " + token); - - Search search = new Search(); - search.setId("XYZ78901"); - search.setProcessId(""); - Response response = contractController.search(search); - - assertEquals(400, response.getStatus()); - assertEquals("Bad Request", response.getStatusText()); - assertEquals("Process id is required for decentral digital twin registry searches!", response.getMessage()); - - } - - @Test - void searchBadRequestSearchStatusDoesNotExistResponse() { - - String token = authService.getToken().getAccessToken(); - when(httpRequest.getHeader("Authorization")).thenReturn("Bearer " + token); - - Search search = new Search(); - search.setId("XYZ78901"); - search.setProcessId(UUID.randomUUID().toString()); - Response response = contractController.search(search); - - LogUtil.printMessage(jsonUtil.toJson(response, true)); - - assertEquals(400, response.getStatus()); - assertEquals("Bad Request", response.getStatusText()); - assertEquals("The searchStatus id does not exists!", response.getMessage()); - - } - - @Test - @Order(3) - void statusNotAuthorizeResponse() { - Response response = contractController.status(null); - - assertEquals(401, response.getStatus()); - assertEquals("Not Authorized", response.getStatusText()); - } - - @Test - void statusBadRequestProcessIdDoesNotExistResponse() { - - String token = authService.getToken().getAccessToken(); - when(httpRequest.getHeader("Authorization")).thenReturn("Bearer " + token); - doReturn(new ProcessDataModel()).when(processManager).loadDataModel(httpRequest); - - Response response = contractController.status(UUID.randomUUID().toString()); - - assertEquals(400, response.getStatus()); - assertEquals("Bad Request", response.getStatusText()); - assertEquals("The process id does not exists!", response.getMessage()); - } - - @Test - @Order(4) - void cancelNotAuthorizeResponse() { - Response response = contractController.cancel(null); - - assertEquals(401, response.getStatus()); - assertEquals("Not Authorized", response.getStatusText()); - } - - @Test - void cancelBadRequestMissingMandatoryParametersResponse() { - String token = authService.getToken().getAccessToken(); - when(httpRequest.getHeader("Authorization")).thenReturn("Bearer " + token); - - Response response = contractController.cancel(new TokenRequest()); - - assertEquals(400, response.getStatus()); - assertEquals("Bad Request", response.getStatusText()); - assertEquals("One or all the mandatory parameters [processId, contractId, token] are missing", response.getMessage()); - } - - @Test - void cancelForbiddenContractDeclineResponse() { - String statusStr = "contract-decline"; - String token = authService.getToken().getAccessToken(); - when(httpRequest.getHeader("Authorization")).thenReturn("Bearer " + token); - - Status status = new Status(); - status.setHistory(new HashMap<>()); - status.setHistory(statusStr, new History("id", statusStr, DateTimeUtil.getTimestamp())); - doReturn(true).when(processManager).checkProcess(eq(httpRequest), anyString()); - doReturn(new Process()).when(processManager).getProcess(eq(httpRequest), anyString()); - doReturn(status).when(processManager).getStatus(anyString()); - - TokenRequest requestToken = new TokenRequest(); - requestToken.setContractId(UUID.randomUUID().toString()); - requestToken.setProcessId(UUID.randomUUID().toString()); - requestToken.setToken(UUID.randomUUID().toString()); - - Response response = contractController.cancel(requestToken); - - assertEquals(403, response.getStatus()); - assertEquals("Forbidden", response.getStatusText()); - assertEquals("This contract was declined! Please request a new one", response.getMessage()); - } - - @Test - void cancelForbiddenNegotiationCanceledResponse() { - String statusStr = "negotiation-canceled"; - String token = authService.getToken().getAccessToken(); - when(httpRequest.getHeader("Authorization")).thenReturn("Bearer " + token); - - Status status = new Status(); - status.setHistory(new HashMap<>()); - status.setHistory(statusStr, new History("id", statusStr, DateTimeUtil.getTimestamp())); - doReturn(true).when(processManager).checkProcess(eq(httpRequest), anyString()); - doReturn(new Process()).when(processManager).getProcess(eq(httpRequest), anyString()); - doReturn(status).when(processManager).getStatus(anyString()); - - TokenRequest requestToken = new TokenRequest(); - requestToken.setContractId(UUID.randomUUID().toString()); - requestToken.setProcessId(UUID.randomUUID().toString()); - requestToken.setToken(UUID.randomUUID().toString()); - - Response response = contractController.cancel(requestToken); - - assertEquals(403, response.getStatus()); - assertEquals("Forbidden", response.getStatusText()); - assertEquals("This negotiation has already been canceled! Please request a new one", response.getMessage()); - } - - @Test - void cancelBadRequestNoContractResponse() { - String token = authService.getToken().getAccessToken(); - when(httpRequest.getHeader("Authorization")).thenReturn("Bearer " + token); - - Status status = new Status(); - status.setHistory(new HashMap<>()); - doReturn(true).when(processManager).checkProcess(eq(httpRequest), anyString()); - doReturn(new Process()).when(processManager).getProcess(eq(httpRequest), anyString()); - doReturn(status).when(processManager).getStatus(anyString()); - - TokenRequest requestToken = new TokenRequest(); - requestToken.setContractId(UUID.randomUUID().toString()); - requestToken.setProcessId(UUID.randomUUID().toString()); - requestToken.setToken(UUID.randomUUID().toString()); - - Response response = contractController.cancel(requestToken); - - LogUtil.printMessage(jsonUtil.toJson(response, true)); - - assertEquals(400, response.getStatus()); - assertEquals("Bad Request", response.getStatusText()); - assertEquals("No contract is available!", response.getMessage()); - } - - - @Test - @Order(5) - void signNotAuthorizeResponse() { - Response response = contractController.sign(null); - - assertEquals(401, response.getStatus()); - assertEquals("Not Authorized", response.getStatusText()); - } - - @Test - void signBadRequestMissingMandatoryParametersResponse() { - String token = authService.getToken().getAccessToken(); - when(httpRequest.getHeader("Authorization")).thenReturn("Bearer " + token); - - Response response = contractController.sign(new TokenRequest()); - - assertEquals(400, response.getStatus()); - assertEquals("Bad Request", response.getStatusText()); - assertEquals("One or all the mandatory parameters [processId, contractId, token] are missing", response.getMessage()); - } - - @Test - void cancelForbiddenContractSignedResponse() { - String statusStr = "contract-signed"; - String token = authService.getToken().getAccessToken(); - when(httpRequest.getHeader("Authorization")).thenReturn("Bearer " + token); - - Status status = new Status(); - status.setHistory(new HashMap<>()); - status.setHistory(statusStr, new History("id", statusStr, DateTimeUtil.getTimestamp())); - doReturn(true).when(processManager).checkProcess(eq(httpRequest), anyString()); - doReturn(new Process()).when(processManager).getProcess(eq(httpRequest), anyString()); - doReturn(status).when(processManager).getStatus(anyString()); - - TokenRequest requestToken = new TokenRequest(); - requestToken.setContractId(UUID.randomUUID().toString()); - requestToken.setProcessId(UUID.randomUUID().toString()); - requestToken.setToken(UUID.randomUUID().toString()); - - Response response = contractController.sign(requestToken); - - assertEquals(403, response.getStatus()); - assertEquals("Forbidden", response.getStatusText()); - assertEquals("This contract is already signed!", response.getMessage()); - } -} diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/DtrSearchManagerTest.java b/dpp-backend/digitalproductpass/src/test/java/managers/DtrSearchManagerTest.java similarity index 81% rename from consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/DtrSearchManagerTest.java rename to dpp-backend/digitalproductpass/src/test/java/managers/DtrSearchManagerTest.java index 9f9250b17..827453f64 100644 --- a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/DtrSearchManagerTest.java +++ b/dpp-backend/digitalproductpass/src/test/java/managers/DtrSearchManagerTest.java @@ -1,14 +1,17 @@ -package org.eclipse.tractusx.productpass.managers; - -import org.eclipse.tractusx.productpass.config.DtrConfig; -import org.eclipse.tractusx.productpass.config.ProcessConfig; -import org.eclipse.tractusx.productpass.config.VaultConfig; -import org.eclipse.tractusx.productpass.exceptions.ServiceInitializationException; -import org.eclipse.tractusx.productpass.models.catenax.Dtr; -import org.eclipse.tractusx.productpass.models.manager.SearchStatus; -import org.eclipse.tractusx.productpass.models.negotiation.Catalog; -import org.eclipse.tractusx.productpass.services.DataTransferService; -import org.eclipse.tractusx.productpass.services.VaultService; +package managers; + +import org.eclipse.tractusx.digitalproductpass.Application; +import org.eclipse.tractusx.digitalproductpass.config.DtrConfig; +import org.eclipse.tractusx.digitalproductpass.config.ProcessConfig; +import org.eclipse.tractusx.digitalproductpass.config.VaultConfig; +import org.eclipse.tractusx.digitalproductpass.exceptions.ServiceInitializationException; +import org.eclipse.tractusx.digitalproductpass.managers.DtrSearchManager; +import org.eclipse.tractusx.digitalproductpass.managers.ProcessManager; +import org.eclipse.tractusx.digitalproductpass.models.catenax.Dtr; +import org.eclipse.tractusx.digitalproductpass.models.manager.SearchStatus; +import org.eclipse.tractusx.digitalproductpass.models.negotiation.Catalog; +import org.eclipse.tractusx.digitalproductpass.services.DataTransferService; +import org.eclipse.tractusx.digitalproductpass.services.VaultService; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; @@ -16,11 +19,20 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.env.Environment; import org.springframework.mock.env.MockEnvironment; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.util.ReflectionTestUtils; import utils.*; +import java.io.InputStream; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -34,7 +46,7 @@ class DtrSearchManagerTest { private DtrSearchManager dtrSearchManager; - private final String testAssetPath = "/src/test/resources/dpp/assets/TestAsset.json"; + private final String testAssetPath = "/dpp/assets/TestAsset.json"; @Mock private ProcessManager processManager; @Mock @@ -53,6 +65,7 @@ void setUpAll() { fileUtil = new FileUtil(); jsonUtil = new JsonUtil(fileUtil); dtrConfig = initDtrConfig(); + env = Mockito.mock(Environment.class); HttpUtil httpUtil = new HttpUtil(env); dataTransferService = Mockito.mock(DataTransferService.class); @@ -69,24 +82,14 @@ void setUpAll() { private DtrConfig initDtrConfig() { DtrConfig dtrConfig = new DtrConfig(); - /*dtrConfig.setAssetType("data.core.digitalTwinRegistry"); - dtrConfig.setEndpointInterface("SUBMODEL-3.0"); - dtrConfig.setDspEndpointKey("dspEndpoint"); - dtrConfig.setInternalDtr("https://materialpass.int.demo.catena-x.net/BPNL000000000000"); - dtrConfig.setSemanticIdTypeKey("Submodel"); - DtrConfig.DecentralApis decentralApis = new DtrConfig.DecentralApis(); - decentralApis.setSearch("/lookup/shells"); - decentralApis.setDigitalTwin("/shell-descriptors"); - decentralApis.setSubModel("/submodel-descriptors"); - dtrConfig.setDecentralApis(decentralApis);*/ DtrConfig.Timeouts timeouts = new DtrConfig.Timeouts(); timeouts.setSearch(10); - timeouts.setNegotiation(40); + timeouts.setDtrRequestProcess(40); + timeouts.setNegotiation(10); timeouts.setTransfer(10); timeouts.setDigitalTwin(20); dtrConfig.setTimeouts(timeouts); dtrConfig.setTemporaryStorage(new DtrConfig.TemporaryStorage(true, 12)); - return dtrConfig; } @@ -209,7 +212,9 @@ void updateProcess() { //TODO @Test void searchEndpoint() { //TODO - Object contractOffer = jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testAssetPath, Object.class); + String file = Paths.get(fileUtil.getBaseClassDir(this.getClass()), testAssetPath).toString(); + Object contractOffer = jsonUtil.fromJsonFileToObject(file, Object.class); + assertNotNull(contractOffer); Catalog catalog = new Catalog(); catalog.setContractOffer(contractOffer); String connectionUrl = "test.connection.url"; diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/ProcessDataModelTest.java b/dpp-backend/digitalproductpass/src/test/java/managers/ProcessDataModelTest.java similarity index 83% rename from consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/ProcessDataModelTest.java rename to dpp-backend/digitalproductpass/src/test/java/managers/ProcessDataModelTest.java index 1f4a3647b..2a678792e 100644 --- a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/ProcessDataModelTest.java +++ b/dpp-backend/digitalproductpass/src/test/java/managers/ProcessDataModelTest.java @@ -1,7 +1,8 @@ -package org.eclipse.tractusx.productpass.managers; +package managers; -import org.eclipse.tractusx.productpass.exceptions.DataModelException; -import org.eclipse.tractusx.productpass.models.manager.Process; +import org.eclipse.tractusx.digitalproductpass.exceptions.DataModelException; +import org.eclipse.tractusx.digitalproductpass.managers.ProcessDataModel; +import org.eclipse.tractusx.digitalproductpass.models.manager.Process; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; @@ -78,7 +79,7 @@ void setAndGetState() { @Test() void setStateThrowsDataModelExceptionByNonexistentProcessId() { Throwable exception = assertThrows(DataModelException.class, () -> processDataModel.setState("100", "TEST")); - assertEquals("[org.eclipse.tractusx.productpass.managers.ProcessDataModel] The process does not exists!", exception.getMessage()); + assertEquals("[org.eclipse.tractusx.digitalproductpass.managers.ProcessDataModel] The process does not exists!", exception.getMessage()); } @Test @@ -104,7 +105,7 @@ void startProcessThrowsDataModelExceptionByNonexistentProcessId() { @Override public void run() {} })); - assertEquals("[org.eclipse.tractusx.productpass.managers.ProcessDataModel] It was not possible to start the process, " + - "[org.eclipse.tractusx.productpass.managers.ProcessDataModel] The process does not exists!", exception.getMessage()); + assertEquals("[org.eclipse.tractusx.digitalproductpass.managers.ProcessDataModel] It was not possible to start the process, " + + "[org.eclipse.tractusx.digitalproductpass.managers.ProcessDataModel] The process does not exists!", exception.getMessage()); } } diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/ProcessManagerTest.java b/dpp-backend/digitalproductpass/src/test/java/managers/ProcessManagerTest.java similarity index 88% rename from consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/ProcessManagerTest.java rename to dpp-backend/digitalproductpass/src/test/java/managers/ProcessManagerTest.java index c7335a105..4638c967a 100644 --- a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/ProcessManagerTest.java +++ b/dpp-backend/digitalproductpass/src/test/java/managers/ProcessManagerTest.java @@ -1,21 +1,23 @@ -package org.eclipse.tractusx.productpass.managers; +package managers; import com.fasterxml.jackson.databind.JsonNode; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import mocks.MockedHttpSession; -import org.eclipse.tractusx.productpass.config.ProcessConfig; -import org.eclipse.tractusx.productpass.exceptions.ManagerException; -import org.eclipse.tractusx.productpass.models.catenax.Dtr; -import org.eclipse.tractusx.productpass.models.dtregistry.DigitalTwin; -import org.eclipse.tractusx.productpass.models.edc.DataPlaneEndpoint; -import org.eclipse.tractusx.productpass.models.http.requests.Search; -import org.eclipse.tractusx.productpass.models.http.responses.IdResponse; -import org.eclipse.tractusx.productpass.models.irs.JobHistory; -import org.eclipse.tractusx.productpass.models.manager.History; -import org.eclipse.tractusx.productpass.models.manager.Process; -import org.eclipse.tractusx.productpass.models.manager.Status; -import org.eclipse.tractusx.productpass.models.negotiation.*; +import org.eclipse.tractusx.digitalproductpass.config.ProcessConfig; +import org.eclipse.tractusx.digitalproductpass.exceptions.ManagerException; +import org.eclipse.tractusx.digitalproductpass.managers.ProcessDataModel; +import org.eclipse.tractusx.digitalproductpass.managers.ProcessManager; +import org.eclipse.tractusx.digitalproductpass.models.catenax.Dtr; +import org.eclipse.tractusx.digitalproductpass.models.dtregistry.DigitalTwin; +import org.eclipse.tractusx.digitalproductpass.models.edc.DataPlaneEndpoint; +import org.eclipse.tractusx.digitalproductpass.models.http.requests.Search; +import org.eclipse.tractusx.digitalproductpass.models.http.responses.IdResponse; +import org.eclipse.tractusx.digitalproductpass.models.irs.JobHistory; +import org.eclipse.tractusx.digitalproductpass.models.manager.History; +import org.eclipse.tractusx.digitalproductpass.models.manager.Process; +import org.eclipse.tractusx.digitalproductpass.models.manager.Status; +import org.eclipse.tractusx.digitalproductpass.models.negotiation.*; import org.junit.jupiter.api.*; import org.junit.runner.RunWith; import org.mockito.Mock; @@ -26,6 +28,7 @@ import utils.*; import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -45,8 +48,8 @@ class ProcessManagerTest { private Process testProcess; private String testProcessId; private List processIdDirToDelete; - private final String testPassportPath = "/src/test/resources/dpp/payloads/TestPassport.json"; - private final String testDigitalTwinPath = "/src/test/resources/dpp/digitaltwins/TestDigitalTwin.json"; + private final String testPassportPath = "/dpp/payloads/TestPassport.json"; + private final String testDigitalTwinPath = "/dpp/digitaltwins/TestDigitalTwin.json"; @Mock Environment env; @Mock @@ -161,12 +164,11 @@ void generateToken() { void createProcess() { String newProcessId = UUID.randomUUID().toString(); processIdDirToDelete.add(newProcessId); - Process nullConnectorAddressProcess = processManager.createProcess(mockedHttpServletRequest); + Process nullConnectorAddressProcess = processManager.createProcess(mockedHttpServletRequest, ""); processIdDirToDelete.add(nullConnectorAddressProcess.getId()); Process connectorAddressProcess = processManager.createProcess(mockedHttpServletRequest, "testAddress"); processIdDirToDelete.add(connectorAddressProcess.getId()); Process processWithChildren = processManager.createProcess(newProcessId, true, mockedHttpServletRequest); - Process processWithBpn = processManager.createProcess(mockedHttpServletRequest, "100", "BPN00000"); processIdDirToDelete.add("100"); assertNotNull(nullConnectorAddressProcess); @@ -176,7 +178,6 @@ void createProcess() { assertEquals("", processManager.getStatus(nullConnectorAddressProcess.getId()).getEndpoint()); assertEquals("testAddress", processManager.getStatus(connectorAddressProcess.getId()).getEndpoint()); assertEquals(true, processManager.getStatus(processWithChildren.getId()).getChildren()); - assertEquals("BPN00000", processManager.getStatus(processWithBpn.getId()).getBpn()); } @Test @@ -187,8 +188,8 @@ void getNullProcess() { @Test void getProcessThrowsManagerException() { Throwable exception = assertThrows(ManagerException.class, () -> processManager.getProcess(null, null)); - assertEquals("[org.eclipse.tractusx.productpass.managers.ProcessManager] It was not possible to get process [null], " + - "[org.eclipse.tractusx.productpass.managers.ProcessManager] Failed to load Process DataModel!, " + + assertEquals("[org.eclipse.tractusx.digitalproductpass.managers.ProcessManager] It was not possible to get process [null], " + + "[org.eclipse.tractusx.digitalproductpass.managers.ProcessManager] Failed to load Process DataModel!, " + "Cannot invoke \"jakarta.servlet.http.HttpServletRequest.getSession()\" because \"httpRequest\" is null" , exception.getMessage()); } @@ -210,12 +211,12 @@ void checkProcess() { @Test void checkProcessThrowsManagerException() { Throwable exception = assertThrows(ManagerException.class, () -> processManager.checkProcess( null)); - assertEquals("[org.eclipse.tractusx.productpass.managers.ProcessManager] It was not possible to check if process exists [null], " + + assertEquals("[org.eclipse.tractusx.digitalproductpass.managers.ProcessManager] It was not possible to check if process exists [null], " + "Cannot invoke \"String.isEmpty()\" because \"segment\" is null", exception.getMessage()); exception = assertThrows(ManagerException.class, () -> processManager.checkProcess( null,testProcessId)); - assertEquals("[org.eclipse.tractusx.productpass.managers.ProcessManager] It was not possible to check if process exists ["+ testProcessId +"], " + - "[org.eclipse.tractusx.productpass.managers.ProcessManager] Failed to load Process DataModel!, " + + assertEquals("[org.eclipse.tractusx.digitalproductpass.managers.ProcessManager] It was not possible to check if process exists ["+ testProcessId +"], " + + "[org.eclipse.tractusx.digitalproductpass.managers.ProcessManager] Failed to load Process DataModel!, " + "Cannot invoke \"jakarta.servlet.http.HttpServletRequest.getSession()\" because \"httpRequest\" is null", exception.getMessage()); } @@ -239,8 +240,8 @@ void setProcess() { @Test void setProcessThrowsManagerException() { Throwable exception = assertThrows(ManagerException.class, () -> processManager.setProcess(null, testProcess)); - assertEquals("[org.eclipse.tractusx.productpass.managers.ProcessManager] It was not possible to set process ["+testProcessId+"], " + - "[org.eclipse.tractusx.productpass.managers.ProcessManager] Failed to load Process DataModel!, " + + assertEquals("[org.eclipse.tractusx.digitalproductpass.managers.ProcessManager] It was not possible to set process ["+testProcessId+"], " + + "[org.eclipse.tractusx.digitalproductpass.managers.ProcessManager] Failed to load Process DataModel!, " + "Cannot invoke \"jakarta.servlet.http.HttpServletRequest.getSession()\" because \"httpRequest\" is null", exception.getMessage()); } @@ -272,7 +273,7 @@ void setAndGetStatus() { @Test void setStatusThrowsManagerException() { Throwable exception = assertThrows(ManagerException.class, () -> processManager.setStatus(null, null, null)); - assertEquals("[org.eclipse.tractusx.productpass.managers.ProcessManager] It was not possible to create/update the status file, " + + assertEquals("[org.eclipse.tractusx.digitalproductpass.managers.ProcessManager] It was not possible to create/update the status file, " + "Cannot invoke \"String.isEmpty()\" because \"segment\" is null", exception.getMessage()); } @@ -333,10 +334,12 @@ void setJobHistory() { void setSemanticIdAndEndpoint() { String inititalSemanticId = processManager.getStatus(testProcessId).getSemanticId(); String initialEndpoint = processManager.getStatus(testProcessId).getEndpoint(); + String initialDataPlaneUrl = processManager.getStatus(testProcessId).getDataPlaneUrl(); String updatedSemanticId = "test:1.0.0$SemanticIdTest"; String updatedEndpoint = "test.com"; + String updatedDataPlaneUrl = "test-dataplane.com"; processManager.setSemanticId(testProcessId, updatedSemanticId); - processManager.setEndpoint(testProcessId, updatedEndpoint); + processManager.setEndpoint(testProcessId, updatedEndpoint, updatedDataPlaneUrl); Status updatedStatus = processManager.getStatus(testProcessId); @@ -346,6 +349,9 @@ void setSemanticIdAndEndpoint() { //Endpoint Tests assertEquals("", initialEndpoint); assertEquals(updatedEndpoint, updatedStatus.getEndpoint()); + //Data Plane Tests + assertEquals("", initialDataPlaneUrl); + assertEquals(updatedDataPlaneUrl, updatedStatus.getDataPlaneUrl()); } @Test @@ -377,8 +383,8 @@ void deleteSearchDir() { @Test void deleteSearchDirThrowsManagerException() { Throwable exception = assertThrows(ManagerException.class, () -> processManager.deleteSearchDir("1000")); - assertEquals("[org.eclipse.tractusx.productpass.managers.ProcessManager] It was not possible to create/update the search in search status file, " + - "[org.eclipse.tractusx.productpass.managers.ProcessManager] Temporary process file does not exists for id [1000]!" + assertEquals("[org.eclipse.tractusx.digitalproductpass.managers.ProcessManager] It was not possible to create/update the search in search status file, " + + "[org.eclipse.tractusx.digitalproductpass.managers.ProcessManager] Temporary process file does not exists for id [1000]!" , exception.getMessage()); } @@ -622,12 +628,7 @@ void getContractId() { @Test void loadPassportReturnsManagerException() { - Throwable exception = assertThrows(ManagerException.class, () -> processManager.loadPassport(testProcessId)); - assertEquals("[org.eclipse.tractusx.productpass.managers.ProcessManager] It was not possible to load the passport!, " + - "[org.eclipse.tractusx.productpass.managers.ProcessManager] Passport file " + - "[C:\\Environment\\gitRepository\\tx-digital-product-pass\\consumer-backend\\productpass\\data\\process\\" + testProcessId + "\\passport.json] not found!" - , exception.getMessage()); - + assertThrows(ManagerException.class, () -> processManager.loadPassport(testProcessId)); } @Test void saveAndLoadPassport() { @@ -644,7 +645,8 @@ void saveAndLoadPassport() { dataPlaneEndpoint.setAuthKey(authKey); - JsonNode passport = (JsonNode) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testPassportPath, JsonNode.class); + String file = Paths.get(fileUtil.getBaseClassDir(this.getClass()), testPassportPath).toString(); + JsonNode passport = (JsonNode) jsonUtil.fromJsonFileToObject(file, JsonNode.class); processManager.savePassport(testProcessId, dataPlaneEndpoint, passport); @@ -657,9 +659,10 @@ void saveAndLoadPassport() { @Test void saveDigitalTwin() { - DigitalTwin digitalTwin = (DigitalTwin) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testDigitalTwinPath, DigitalTwin.class); + String file = Paths.get(fileUtil.getBaseClassDir(this.getClass()), testDigitalTwinPath).toString(); + DigitalTwin digitalTwin = (DigitalTwin) jsonUtil.fromJsonFileToObject(file, DigitalTwin.class); Long createdAt = DateTimeUtil.getTimestamp(); - + assertNotNull(digitalTwin); processManager.saveDigitalTwin(testProcessId, digitalTwin, createdAt); Status status = processManager.getStatus(testProcessId); diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/TreeManagerTest.java b/dpp-backend/digitalproductpass/src/test/java/managers/TreeManagerTest.java similarity index 83% rename from consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/TreeManagerTest.java rename to dpp-backend/digitalproductpass/src/test/java/managers/TreeManagerTest.java index 1c5cd77f2..8fb49391c 100644 --- a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/managers/TreeManagerTest.java +++ b/dpp-backend/digitalproductpass/src/test/java/managers/TreeManagerTest.java @@ -1,15 +1,17 @@ -package org.eclipse.tractusx.productpass.managers; +package managers; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import mocks.MockedHttpSession; -import org.eclipse.tractusx.productpass.config.IrsConfig; -import org.eclipse.tractusx.productpass.config.PassportConfig; -import org.eclipse.tractusx.productpass.config.ProcessConfig; -import org.eclipse.tractusx.productpass.models.irs.JobHistory; -import org.eclipse.tractusx.productpass.models.irs.JobResponse; -import org.eclipse.tractusx.productpass.models.manager.Node; -import org.eclipse.tractusx.productpass.models.manager.NodeComponent; +import org.eclipse.tractusx.digitalproductpass.config.IrsConfig; +import org.eclipse.tractusx.digitalproductpass.config.PassportConfig; +import org.eclipse.tractusx.digitalproductpass.config.ProcessConfig; +import org.eclipse.tractusx.digitalproductpass.managers.ProcessManager; +import org.eclipse.tractusx.digitalproductpass.managers.TreeManager; +import org.eclipse.tractusx.digitalproductpass.models.irs.JobHistory; +import org.eclipse.tractusx.digitalproductpass.models.irs.JobResponse; +import org.eclipse.tractusx.digitalproductpass.models.manager.Node; +import org.eclipse.tractusx.digitalproductpass.models.manager.NodeComponent; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -25,6 +27,7 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Path; +import java.nio.file.Paths; import java.util.List; import java.util.Map; import java.util.UUID; @@ -39,9 +42,9 @@ class TreeManagerTest { private JobResponse testJobResponse; private JobHistory testJobHistory; private Map treeDataModel; - private final String testJobResposnsePath = "/src/test/resources/dpp/irs/TestJobResponse.json"; - private final String testJobHistoryPath = "/src/test/resources/dpp/irs/TestJobHistory.json"; - private final String testTreeDataModelPath = "/src/test/resources/dpp/irs/TestTreeDataModel.json"; + private final String testJobResposnsePath = "/dpp/irs/TestJobResponse.json"; + private final String testJobHistoryPath = "/dpp/irs/TestJobHistory.json"; + private final String testTreeDataModelPath = "/dpp/irs/TestTreeDataModel.json"; private String baseDataDirPath; private String testProcessId; private Map configuration; @@ -66,8 +69,9 @@ void setUpAll() { fileUtil = new FileUtil(); yamlUtil = new YamlUtil(fileUtil); jsonUtil = new JsonUtil(fileUtil); + String configurationFilePath = Paths.get(fileUtil.getBaseClassDir(this.getClass()), "application-test.yml").toString(); + Map application = yamlUtil.readFile(configurationFilePath); - Map application = yamlUtil.readFile(FileUtil.getWorkdirPath() + "/src/main/resources/application.yml"); configuration = (Map) jsonUtil.toMap(application.get("configuration")); httpUtil = Mockito.spy(new HttpUtil(env)); @@ -90,9 +94,9 @@ void setUpAll() { testProcessId = processManager.initProcess(); processManager.createProcess(testProcessId, request); - testJobResponse = (JobResponse) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testJobResposnsePath, JobResponse.class); - testJobHistory = (JobHistory) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testJobHistoryPath, JobHistory.class); - treeDataModel = (Map) jsonUtil.toMap(jsonUtil.fromJsonFile(FileUtil.getWorkdirPath() + testTreeDataModelPath)); + testJobResponse = (JobResponse) jsonUtil.fromJsonFileToObject(Paths.get(fileUtil.getBaseClassDir(this.getClass()), testJobResposnsePath).toString(), JobResponse.class); + testJobHistory = (JobHistory) jsonUtil.fromJsonFileToObject(Paths.get(fileUtil.getBaseClassDir(this.getClass()), testJobHistoryPath).toString(), JobHistory.class); + treeDataModel = (Map) jsonUtil.toMap(jsonUtil.fromJsonFile(Paths.get(fileUtil.getBaseClassDir(this.getClass()), testTreeDataModelPath).toString())); } @AfterAll diff --git a/consumer-backend/productpass/src/test/java/mocks/MockedHttpSession.java b/dpp-backend/digitalproductpass/src/test/java/mocks/MockedHttpSession.java similarity index 100% rename from consumer-backend/productpass/src/test/java/mocks/MockedHttpSession.java rename to dpp-backend/digitalproductpass/src/test/java/mocks/MockedHttpSession.java diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/AasServiceTest.java b/dpp-backend/digitalproductpass/src/test/java/services/AasServiceTest.java similarity index 76% rename from consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/AasServiceTest.java rename to dpp-backend/digitalproductpass/src/test/java/services/AasServiceTest.java index 6de9bf74e..11a6b8350 100644 --- a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/AasServiceTest.java +++ b/dpp-backend/digitalproductpass/src/test/java/services/AasServiceTest.java @@ -1,24 +1,29 @@ -package org.eclipse.tractusx.productpass.services; +package services; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import mocks.MockedHttpSession; import org.bouncycastle.asn1.x509.GeneralName; -import org.eclipse.tractusx.productpass.config.DtrConfig; -import org.eclipse.tractusx.productpass.config.PassportConfig; -import org.eclipse.tractusx.productpass.config.ProcessConfig; -import org.eclipse.tractusx.productpass.exceptions.ServiceInitializationException; -import org.eclipse.tractusx.productpass.managers.DtrSearchManager; -import org.eclipse.tractusx.productpass.managers.ProcessManager; -import org.eclipse.tractusx.productpass.models.auth.JwtToken; -import org.eclipse.tractusx.productpass.models.catenax.Discovery; -import org.eclipse.tractusx.productpass.models.dtregistry.DigitalTwin; -import org.eclipse.tractusx.productpass.models.dtregistry.SubModel; -import org.eclipse.tractusx.productpass.models.edc.AssetSearch; -import org.eclipse.tractusx.productpass.models.edc.DataPlaneEndpoint; -import org.eclipse.tractusx.productpass.models.http.requests.Search; -import org.eclipse.tractusx.productpass.models.manager.History; -import org.eclipse.tractusx.productpass.models.manager.Status; +import org.eclipse.tractusx.digitalproductpass.config.DtrConfig; +import org.eclipse.tractusx.digitalproductpass.config.PassportConfig; +import org.eclipse.tractusx.digitalproductpass.config.ProcessConfig; +import org.eclipse.tractusx.digitalproductpass.config.SecurityConfig; +import org.eclipse.tractusx.digitalproductpass.exceptions.ServiceInitializationException; +import org.eclipse.tractusx.digitalproductpass.managers.DtrSearchManager; +import org.eclipse.tractusx.digitalproductpass.managers.ProcessManager; +import org.eclipse.tractusx.digitalproductpass.models.auth.JwtToken; +import org.eclipse.tractusx.digitalproductpass.models.catenax.Discovery; +import org.eclipse.tractusx.digitalproductpass.models.dtregistry.DigitalTwin; +import org.eclipse.tractusx.digitalproductpass.models.dtregistry.SubModel; +import org.eclipse.tractusx.digitalproductpass.models.edc.AssetSearch; +import org.eclipse.tractusx.digitalproductpass.models.edc.DataPlaneEndpoint; +import org.eclipse.tractusx.digitalproductpass.models.http.requests.Search; +import org.eclipse.tractusx.digitalproductpass.models.manager.History; +import org.eclipse.tractusx.digitalproductpass.models.manager.Status; +import org.eclipse.tractusx.digitalproductpass.services.AasService; +import org.eclipse.tractusx.digitalproductpass.services.AuthenticationService; +import org.eclipse.tractusx.digitalproductpass.services.DataTransferService; +import org.eclipse.tractusx.digitalproductpass.services.VaultService; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -35,6 +40,7 @@ import utils.*; import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.Map; import java.util.UUID; @@ -52,7 +58,7 @@ class AasServiceTest { String mockedDigitalTwin; private final String digitalTwinId = "365e6fbe-bb34-11ec-8422-0242ac120002"; private final String semanticId = "urn:bamm:io.catenax.battery.battery_pass:3.0.1#BatteryPass"; - private final String testDigitalTwinPath = "/src/test/resources/dpp/digitaltwins/TestDigitalTwin.json"; + private final String testDigitalTwinPath = "/dpp/digitaltwins/TestDigitalTwin.json"; private String baseDataDirPath; private String testProcessId; @Mock @@ -66,7 +72,7 @@ class AasServiceTest { @Mock private HttpSession mockedHttpSession; private AuthenticationService authenticationService; - private final String mockedTokenPath = "/src/test/resources/dpp/token/MockedToken.json"; + private final String mockedTokenPath = "/dpp/token/MockedToken.json"; private JwtToken mockedToken; @Mock private VaultService vaultService; @@ -76,27 +82,34 @@ class AasServiceTest { private DtrSearchManager dtrSearchManager; private ProcessManager processManager; private DataTransferService dataTransferService; + + private SecurityConfig securityConfig; @BeforeAll void setUpAll() throws ServiceInitializationException { MockitoAnnotations.openMocks(this); fileUtil = new FileUtil(); jsonUtil = new JsonUtil(fileUtil); yamlUtil = new YamlUtil(fileUtil); - - Map application = yamlUtil.readFile(FileUtil.getWorkdirPath() + "/src/main/resources/application.yml"); + securityConfig = new SecurityConfig(); + securityConfig.setAuthorization(new SecurityConfig.AuthorizationConfig(false, false)); + securityConfig.setStartUpChecks(new SecurityConfig.StartUpCheckConfig(false, false)); + String configurationFilePath = Paths.get(fileUtil.getBaseClassDir(this.getClass()), "application-test.yml").toString(); + Map application = yamlUtil.readFile(configurationFilePath); configuration = (Map) jsonUtil.toMap(application.get("configuration")); env = initEnv(); httpUtil = Mockito.spy(new HttpUtil(env)); + String mockClientId="xynasdnsda12312"; + String mockClientTestReturn="212123asddsad54546"; + String mockApiKey="aqweas1230sad"; + String mockBpn="BPNL00000000000"; - Map vaultConfig = yamlUtil.readFile(fileUtil.getDataDir() + "/VaultConfig/vault.token.yml"); - Map client = (Map) jsonUtil.toMap(vaultConfig.get("client")); - when(vaultService.getLocalSecret("client.id")).thenReturn(client.get("id").toString()); - when(vaultService.getLocalSecret("client.secret")).thenReturn(client.get("secret").toString()); - Map edc = (Map) jsonUtil.toMap(vaultConfig.get("edc")); - when(vaultService.getLocalSecret("edc.apiKey")).thenReturn(edc.get("apiKey").toString()); - when(vaultService.getLocalSecret("edc.participantId")).thenReturn(edc.get("participantId").toString()); + when(vaultService.getLocalSecret("client.id")).thenReturn(mockClientId); + when(vaultService.getLocalSecret("client.secret")).thenReturn(mockClientTestReturn); + + when(vaultService.getLocalSecret("edc.apiKey")).thenReturn(mockApiKey); + when(vaultService.getLocalSecret("edc.participantId")).thenReturn(mockBpn); dtrConfig = initDtrConfig(); processConfig = new ProcessConfig(); @@ -105,15 +118,15 @@ void setUpAll() throws ServiceInitializationException { processManager = new ProcessManager(httpUtil, jsonUtil, fileUtil, processConfig); dtrSearchManager = new DtrSearchManager(fileUtil,jsonUtil, dataTransferService, dtrConfig, processManager); dataTransferService = new DataTransferService(env, httpUtil, jsonUtil,vaultService, processManager, dtrConfig); - authenticationService = Mockito.spy(new AuthenticationService(vaultService, env, httpUtil, jsonUtil)); - mockedToken = (JwtToken) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + mockedTokenPath, JwtToken.class); + authenticationService = Mockito.spy(new AuthenticationService(vaultService, env, httpUtil, jsonUtil, securityConfig)); + mockedToken = (JwtToken) jsonUtil.fromJsonFileToObject(Paths.get(fileUtil.getBaseClassDir(this.getClass()), mockedTokenPath).toString(), JwtToken.class); doReturn(mockedToken).when(authenticationService).getToken(); passportConfig = new PassportConfig(); aasService = new AasService(env, httpUtil, jsonUtil, authenticationService, dtrConfig, dtrSearchManager, processManager, dataTransferService, passportConfig); - mockedDigitalTwin = jsonUtil.toJson(jsonUtil.fromJsonFile(FileUtil.getWorkdirPath() + testDigitalTwinPath), true); + mockedDigitalTwin = jsonUtil.toJson(jsonUtil.fromJsonFile(Paths.get(fileUtil.getBaseClassDir(this.getClass()), testDigitalTwinPath).toString()), true); testProcessId = processManager.initProcess(); mockedHttpSession = new MockedHttpSession(); @@ -144,7 +157,8 @@ private DtrConfig initDtrConfig() { DtrConfig dtrConfig = new DtrConfig(); DtrConfig.Timeouts timeouts = new DtrConfig.Timeouts(); timeouts.setSearch(10); - timeouts.setNegotiation(40); + timeouts.setDtrRequestProcess(40); + timeouts.setNegotiation(10); timeouts.setTransfer(10); timeouts.setDigitalTwin(20); dtrConfig.setTimeouts(timeouts); @@ -237,13 +251,13 @@ void decentralDtrSearch() { String historyId = "digital-twin-found"; String historyStatus = "TEST"; - String endpoint = "test.endpoint"; - + String endpoint = "test.endpoint.com"; + String dataplane = "test.dataplane.com"; when(request.getSession()).thenReturn(mockedHttpSession); processManager.createProcess(testProcessId, request); - processManager.setEndpoint(testProcessId, endpoint); + processManager.setEndpoint(testProcessId, endpoint, dataplane); processManager.setStatus(testProcessId, historyId, new History(testProcessId, historyStatus)); AssetSearch result = aasService.decentralDtrSearch(testProcessId, searchBody); diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/AuthenticationServiceTest.java b/dpp-backend/digitalproductpass/src/test/java/services/AuthenticationServiceTest.java similarity index 66% rename from consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/AuthenticationServiceTest.java rename to dpp-backend/digitalproductpass/src/test/java/services/AuthenticationServiceTest.java index b10bf7e86..dcfcc0107 100644 --- a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/AuthenticationServiceTest.java +++ b/dpp-backend/digitalproductpass/src/test/java/services/AuthenticationServiceTest.java @@ -1,10 +1,13 @@ -package org.eclipse.tractusx.productpass.services; +package services; import com.fasterxml.jackson.databind.JsonNode; import jakarta.servlet.http.HttpServletRequest; -import org.eclipse.tractusx.productpass.exceptions.ServiceInitializationException; -import org.eclipse.tractusx.productpass.models.auth.JwtToken; -import org.eclipse.tractusx.productpass.models.auth.UserInfo; +import org.eclipse.tractusx.digitalproductpass.config.SecurityConfig; +import org.eclipse.tractusx.digitalproductpass.exceptions.ServiceInitializationException; +import org.eclipse.tractusx.digitalproductpass.models.auth.JwtToken; +import org.eclipse.tractusx.digitalproductpass.models.auth.UserInfo; +import org.eclipse.tractusx.digitalproductpass.services.AuthenticationService; +import org.eclipse.tractusx.digitalproductpass.services.VaultService; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -15,6 +18,7 @@ import org.springframework.core.env.Environment; import utils.*; +import java.nio.file.Paths; import java.util.Map; import java.util.UUID; @@ -26,8 +30,8 @@ class AuthenticationServiceTest { private AuthenticationService authenticationService; - private final String mockedTokenPath = "/src/test/resources/dpp/token/MockedToken.json"; - private final String mockedUserInfoPath = "/src/test/resources/dpp/token/MockedUserInfo.json"; + private final String mockedTokenPath = "/dpp/token/MockedToken.json"; + private final String mockedUserInfoPath = "/dpp/token/MockedUserInfo.json"; private JwtToken mockedToken; private UserInfo mockedUserInfo; @Mock @@ -38,6 +42,7 @@ class AuthenticationServiceTest { private JsonUtil jsonUtil; private YamlUtil yamlUtil; private FileUtil fileUtil; + private SecurityConfig securityConfig; @Mock private HttpServletRequest httpRequest; @@ -48,30 +53,23 @@ void setUpAll() throws ServiceInitializationException { fileUtil = new FileUtil(); jsonUtil = new JsonUtil(fileUtil); yamlUtil = new YamlUtil(fileUtil); - - Map application = yamlUtil.readFile(FileUtil.getWorkdirPath() + "/src/main/resources/application.yml"); + securityConfig = new SecurityConfig(); + securityConfig.setAuthorization(new SecurityConfig.AuthorizationConfig(false, false)); + securityConfig.setStartUpChecks(new SecurityConfig.StartUpCheckConfig(false, false)); + String configurationFilePath = Paths.get(fileUtil.getBaseClassDir(this.getClass()), "application-test.yml").toString(); + Map application = yamlUtil.readFile(configurationFilePath); Map configuration = (Map) jsonUtil.toMap(application.get("configuration")); Map keycloak = (Map) jsonUtil.toMap(configuration.get("keycloak")); when(env.getProperty("configuration.keycloak.tokenUri", String.class, "")).thenReturn(keycloak.get("tokenUri").toString()); when(env.getProperty("configuration.keycloak.userInfoUri", String.class, "")).thenReturn(keycloak.get("userInfoUri").toString()); - authenticationService = Mockito.spy(new AuthenticationService(vaultService, env, httpUtil, jsonUtil)); + authenticationService = Mockito.spy(new AuthenticationService(vaultService, env, httpUtil, jsonUtil, securityConfig)); - mockedToken = (JwtToken) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + mockedTokenPath, JwtToken.class); - mockedUserInfo = (UserInfo) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + mockedUserInfoPath, UserInfo.class); + mockedToken = (JwtToken) jsonUtil.fromJsonFileToObject(Paths.get(fileUtil.getBaseClassDir(this.getClass()), mockedTokenPath).toString(), JwtToken.class); + mockedUserInfo = (UserInfo) jsonUtil.fromJsonFileToObject(Paths.get(fileUtil.getBaseClassDir(this.getClass()), mockedUserInfoPath).toString(), UserInfo.class); doReturn(mockedToken).when(authenticationService).getToken(); doReturn(mockedUserInfo).when(authenticationService).getUserInfo(mockedToken.getAccessToken()); } - @BeforeEach - void setUp() { - Map vaultConfig = yamlUtil.readFile(fileUtil.getDataDir() + "/VaultConfig/vault.token.yml"); - Map client = (Map) jsonUtil.toMap(vaultConfig.get("client")); - - when(vaultService.getLocalSecret("client.id")).thenReturn(client.get("id").toString()); - when(vaultService.getLocalSecret("client.secret")).thenReturn(client.get("secret").toString()); - } - - @Test void getToken() { diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/CatenaXServiceTest.java b/dpp-backend/digitalproductpass/src/test/java/services/CatenaXServiceTest.java similarity index 80% rename from consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/CatenaXServiceTest.java rename to dpp-backend/digitalproductpass/src/test/java/services/CatenaXServiceTest.java index 0294251f1..e4b13b352 100644 --- a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/CatenaXServiceTest.java +++ b/dpp-backend/digitalproductpass/src/test/java/services/CatenaXServiceTest.java @@ -1,16 +1,21 @@ -package org.eclipse.tractusx.productpass.services; +package services; import com.fasterxml.jackson.databind.JsonNode; -import org.eclipse.tractusx.productpass.config.DiscoveryConfig; -import org.eclipse.tractusx.productpass.config.DtrConfig; -import org.eclipse.tractusx.productpass.config.ProcessConfig; -import org.eclipse.tractusx.productpass.exceptions.ServiceInitializationException; -import org.eclipse.tractusx.productpass.managers.DtrSearchManager; -import org.eclipse.tractusx.productpass.managers.ProcessManager; -import org.eclipse.tractusx.productpass.models.auth.JwtToken; -import org.eclipse.tractusx.productpass.models.catenax.BpnDiscovery; -import org.eclipse.tractusx.productpass.models.catenax.Discovery; -import org.eclipse.tractusx.productpass.models.catenax.EdcDiscoveryEndpoint; +import org.eclipse.tractusx.digitalproductpass.config.DiscoveryConfig; +import org.eclipse.tractusx.digitalproductpass.config.DtrConfig; +import org.eclipse.tractusx.digitalproductpass.config.ProcessConfig; +import org.eclipse.tractusx.digitalproductpass.config.SecurityConfig; +import org.eclipse.tractusx.digitalproductpass.exceptions.ServiceInitializationException; +import org.eclipse.tractusx.digitalproductpass.managers.DtrSearchManager; +import org.eclipse.tractusx.digitalproductpass.managers.ProcessManager; +import org.eclipse.tractusx.digitalproductpass.models.auth.JwtToken; +import org.eclipse.tractusx.digitalproductpass.models.catenax.BpnDiscovery; +import org.eclipse.tractusx.digitalproductpass.models.catenax.Discovery; +import org.eclipse.tractusx.digitalproductpass.models.catenax.EdcDiscoveryEndpoint; +import org.eclipse.tractusx.digitalproductpass.services.AuthenticationService; +import org.eclipse.tractusx.digitalproductpass.services.CatenaXService; +import org.eclipse.tractusx.digitalproductpass.services.DataTransferService; +import org.eclipse.tractusx.digitalproductpass.services.VaultService; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; @@ -25,6 +30,7 @@ import org.springframework.mock.env.MockEnvironment; import utils.*; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -43,9 +49,9 @@ class CatenaXServiceTest { private DataTransferService dataTransferService; private DtrSearchManager dtrSearchManager; private AuthenticationService authenticationService; - private final String mockedTokenPath = "/src/test/resources/dpp/token/MockedToken.json"; + private final String mockedTokenPath = "/dpp/token/MockedToken.json"; private JwtToken mockedToken; - private final String mockedDiscoveryEndpointsPath = "/src/test/resources/dpp/discovery/MockedDiscoveryEndpoints.json"; + private final String mockedDiscoveryEndpointsPath = "/dpp/discovery/MockedDiscoveryEndpoints.json"; @Mock private VaultService vaultService; private DtrConfig dtrConfig; @@ -59,30 +65,37 @@ class CatenaXServiceTest { private Environment env; private Discovery discovery; + private SecurityConfig securityConfig; @BeforeAll void setUpAll() throws ServiceInitializationException { MockitoAnnotations.openMocks(this); fileUtil = new FileUtil(); yamlUtil = new YamlUtil(fileUtil); jsonUtil = new JsonUtil(fileUtil); - - Map application = yamlUtil.readFile(FileUtil.getWorkdirPath() + "/src/main/resources/application.yml"); + securityConfig = new SecurityConfig(); + securityConfig.setAuthorization(new SecurityConfig.AuthorizationConfig(false, false)); + securityConfig.setStartUpChecks(new SecurityConfig.StartUpCheckConfig(false, false)); + String configurationFilePath = Paths.get(fileUtil.getBaseClassDir(this.getClass()), "application-test.yml").toString(); + Map application = yamlUtil.readFile(configurationFilePath); configuration = (Map) jsonUtil.toMap(application.get("configuration")); env = initEnv(); httpUtil = Mockito.spy(new HttpUtil(env)); - Map vaultConfig = yamlUtil.readFile(fileUtil.getDataDir() + "/VaultConfig/vault.token.yml"); - Map client = (Map) jsonUtil.toMap(vaultConfig.get("client")); - when(vaultService.getLocalSecret("client.id")).thenReturn(client.get("id").toString()); - when(vaultService.getLocalSecret("client.secret")).thenReturn(client.get("secret").toString()); - Map edc = (Map) jsonUtil.toMap(vaultConfig.get("edc")); - when(vaultService.getLocalSecret("edc.apiKey")).thenReturn(edc.get("apiKey").toString()); - when(vaultService.getLocalSecret("edc.participantId")).thenReturn(edc.get("participantId").toString()); + String mockClientId="xynasdnsda12312"; + String mockClientTestReturn="212123asddsad54546"; + String mockApiKey="aqweas1230sad"; + String mockBpn="BPNL00000000000"; + + when(vaultService.getLocalSecret("client.id")).thenReturn(mockClientId); + when(vaultService.getLocalSecret("client.secret")).thenReturn(mockClientTestReturn); + + when(vaultService.getLocalSecret("edc.apiKey")).thenReturn(mockApiKey); + when(vaultService.getLocalSecret("edc.participantId")).thenReturn(mockBpn); - authenticationService = Mockito.spy(new AuthenticationService(vaultService, env, httpUtil, jsonUtil)); + authenticationService = Mockito.spy(new AuthenticationService(vaultService, env, httpUtil, jsonUtil, securityConfig)); - mockedToken = (JwtToken) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + mockedTokenPath, JwtToken.class); + mockedToken = (JwtToken) jsonUtil.fromJsonFileToObject(Paths.get(fileUtil.getBaseClassDir(this.getClass()), mockedTokenPath).toString(), JwtToken.class); doReturn(mockedToken).when(authenticationService).getToken(); ProcessConfig processConfig = new ProcessConfig(); @@ -129,18 +142,18 @@ private DtrConfig initDtrConfig() { DtrConfig dtrConfig = new DtrConfig(); DtrConfig.Timeouts timeouts = new DtrConfig.Timeouts(); timeouts.setSearch(10); - timeouts.setNegotiation(40); + timeouts.setDtrRequestProcess(40); + timeouts.setNegotiation(10); timeouts.setTransfer(10); timeouts.setDigitalTwin(20); dtrConfig.setTimeouts(timeouts); dtrConfig.setTemporaryStorage(new DtrConfig.TemporaryStorage(true, 12)); - return dtrConfig; } @Test void getDiscoveryEndpoints() { - Discovery mockedDefaultDiscovery = (Discovery) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + mockedDiscoveryEndpointsPath, Discovery.class); + Discovery mockedDefaultDiscovery = (Discovery) jsonUtil.fromJsonFileToObject(Paths.get(fileUtil.getBaseClassDir(this.getClass()), mockedDiscoveryEndpointsPath).toString(), Discovery.class); doReturn(new ResponseEntity<>(jsonUtil.toJsonNode(jsonUtil.toJson(mockedDefaultDiscovery, true)), HttpStatus.OK)) .when(httpUtil).doPost(anyString(), eq(JsonNode.class), any(HttpHeaders.class), any(Map.class), any(Object.class), eq(false), eq(false)); @@ -190,7 +203,7 @@ void getEdcDiscovery() { when(vaultService.getLocalSecret(eq("discovery.edc"))).thenReturn(new ArrayList<>(){{add("test.endpoint");}}); doReturn(new ResponseEntity<>(jsonUtil.toJsonNode(new ArrayList<>(){{add(mockedEdcDiscoveryEndpoint);}}), HttpStatus.OK)) - .when(httpUtil).doPost(anyString(), eq(JsonNode.class), any(HttpHeaders.class), any(Map.class), any(Object.class), eq(false), eq(false)); + .when(httpUtil).doPost(anyString(), eq(JsonNode.class), any(HttpHeaders.class), any(Map.class), any(Object.class), eq(false), eq(false), anyInt()); List edcDiscoveryEndpoints = catenaXService.getEdcDiscovery(List.of(bpn)); @@ -236,7 +249,7 @@ void getBpnDiscovery() { bpnDiscoveryEndpoint.setValue(bpn); BpnDiscovery bpnDiscovery = new BpnDiscovery(new ArrayList<>(){{add(bpnDiscoveryEndpoint);}}); return new ResponseEntity<>(jsonUtil.toJsonNode(jsonUtil.toJson(bpnDiscovery, true)), HttpStatus.OK); - }).when(httpUtil).doPost(anyString(), eq(JsonNode.class), any(HttpHeaders.class), any(Map.class), any(Object.class), eq(false), eq(false)); + }).when(httpUtil).doPost(anyString(), eq(JsonNode.class), any(HttpHeaders.class), any(Map.class), any(Object.class), eq(false), eq(false), anyInt()); List bpnDiscoveryList = catenaXService.getBpnDiscovery(bpnResourceId, bpnKey); diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/DataPlaneServiceTest.java b/dpp-backend/digitalproductpass/src/test/java/services/DataPlaneServiceTest.java similarity index 85% rename from consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/DataPlaneServiceTest.java rename to dpp-backend/digitalproductpass/src/test/java/services/DataPlaneServiceTest.java index cc71f1575..9ad8fa995 100644 --- a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/DataPlaneServiceTest.java +++ b/dpp-backend/digitalproductpass/src/test/java/services/DataPlaneServiceTest.java @@ -1,8 +1,9 @@ -package org.eclipse.tractusx.productpass.services; +package services; import com.fasterxml.jackson.databind.JsonNode; -import org.eclipse.tractusx.productpass.exceptions.ServiceInitializationException; -import org.eclipse.tractusx.productpass.models.edc.DataPlaneEndpoint; +import org.eclipse.tractusx.digitalproductpass.exceptions.ServiceInitializationException; +import org.eclipse.tractusx.digitalproductpass.models.edc.DataPlaneEndpoint; +import org.eclipse.tractusx.digitalproductpass.services.DataPlaneService; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; @@ -18,6 +19,7 @@ import utils.HttpUtil; import utils.JsonUtil; +import java.nio.file.Paths; import java.util.HashMap; import java.util.UUID; @@ -29,7 +31,7 @@ class DataPlaneServiceTest { private DataPlaneService dataPlaneService; - private final String testPassportPath = "/src/test/resources/dpp/payloads/TestPassport.json"; + private final String testPassportPath = "/dpp/payloads/TestPassport.json"; @Mock private HttpUtil httpUtil; private JsonUtil jsonUtil; @@ -49,7 +51,7 @@ void setUpAll() throws ServiceInitializationException { when(httpUtil.doGet(anyString(), any(Class.class), any(HttpHeaders.class), any(), eq(true), eq(true))) .then(invocation -> { - JsonNode passport = (JsonNode) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testPassportPath, JsonNode.class); + JsonNode passport = (JsonNode) jsonUtil.fromJsonFileToObject(Paths.get(fileUtil.getBaseClassDir(this.getClass()), testPassportPath).toString(), JsonNode.class); return new ResponseEntity<>(passport, HttpStatus.OK); }); diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/DataTransferServiceTest.java b/dpp-backend/digitalproductpass/src/test/java/services/DataTransferServiceTest.java similarity index 76% rename from consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/DataTransferServiceTest.java rename to dpp-backend/digitalproductpass/src/test/java/services/DataTransferServiceTest.java index ef1ddc6ad..bf81157fc 100644 --- a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/DataTransferServiceTest.java +++ b/dpp-backend/digitalproductpass/src/test/java/services/DataTransferServiceTest.java @@ -1,14 +1,16 @@ -package org.eclipse.tractusx.productpass.services; +package services; import com.fasterxml.jackson.databind.JsonNode; -import org.eclipse.tractusx.productpass.config.DtrConfig; -import org.eclipse.tractusx.productpass.config.ProcessConfig; -import org.eclipse.tractusx.productpass.config.VaultConfig; -import org.eclipse.tractusx.productpass.exceptions.ServiceInitializationException; -import org.eclipse.tractusx.productpass.managers.ProcessManager; -import org.eclipse.tractusx.productpass.models.http.responses.IdResponse; -import org.eclipse.tractusx.productpass.models.manager.Status; -import org.eclipse.tractusx.productpass.models.negotiation.*; +import org.eclipse.tractusx.digitalproductpass.config.DtrConfig; +import org.eclipse.tractusx.digitalproductpass.config.ProcessConfig; +import org.eclipse.tractusx.digitalproductpass.config.VaultConfig; +import org.eclipse.tractusx.digitalproductpass.exceptions.ServiceInitializationException; +import org.eclipse.tractusx.digitalproductpass.managers.ProcessManager; +import org.eclipse.tractusx.digitalproductpass.models.http.responses.IdResponse; +import org.eclipse.tractusx.digitalproductpass.models.manager.Status; +import org.eclipse.tractusx.digitalproductpass.models.negotiation.*; +import org.eclipse.tractusx.digitalproductpass.services.DataTransferService; +import org.eclipse.tractusx.digitalproductpass.services.VaultService; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -22,6 +24,7 @@ import org.springframework.mock.env.MockEnvironment; import utils.*; +import java.nio.file.Paths; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -38,13 +41,13 @@ class DataTransferServiceTest { private Dataset dataSet; private Set policy; private String bpn; - private final String testPolicyPath = "/src/test/resources/dpp/contractpolicies/TestPolicy.json"; - private final String testDTCatalogPath = "/src/test/resources/dpp/catalogs/TestDigitalTwinCatalog.json"; - private final String testCOCatalogPath = "/src/test/resources/dpp/catalogs/TestContractOfferCatalog.json"; - private final String testResponseInitNegotiationPath = "/src/test/resources/dpp/negotiation/TestResponseInitNegotiation.json"; - private final String testResponseNegotiationPath = "/src/test/resources/dpp/negotiation/TestResponseNegotiation.json"; - private final String testResponseInitTransferPath = "/src/test/resources/dpp/transfer/TestResponseInitTransfer.json"; - private final String testResponseTransferPath = "/src/test/resources/dpp/transfer/TestResponseTransfer.json"; + private final String testPolicyPath = "/dpp/contractpolicies/TestPolicy.json"; + private final String testDTCatalogPath = "/dpp/catalogs/TestDigitalTwinCatalog.json"; + private final String testCOCatalogPath = "/dpp/catalogs/TestContractOfferCatalog.json"; + private final String testResponseInitNegotiationPath = "/dpp/negotiation/TestResponseInitNegotiation.json"; + private final String testResponseNegotiationPath = "/dpp/negotiation/TestResponseNegotiation.json"; + private final String testResponseInitTransferPath = "/dpp/transfer/TestResponseInitTransfer.json"; + private final String testResponseTransferPath = "/dpp/transfer/TestResponseTransfer.json"; @Mock private VaultService vaultService; @Mock @@ -67,12 +70,11 @@ void setUpAll() throws ServiceInitializationException { jsonUtil = new JsonUtil(fileUtil); yamlUtil = new YamlUtil(fileUtil); env = initEnv(); - Map vaultConfig = yamlUtil.readFile(fileUtil.getDataDir() + "/VaultConfig/vault.token.yml"); - Map edc = (Map) jsonUtil.toMap(vaultConfig.get("edc")); - when(vaultService.getLocalSecret("edc.apiKey")).thenReturn(edc.get("apiKey").toString()); - when(vaultService.getLocalSecret("edc.participantId")).thenReturn(edc.get("participantId").toString()); + bpn = "BPNL00000000000"; + String mockApiKey = "12345678979ayasdmasdjncjxnzc"; + when(vaultService.getLocalSecret("edc.apiKey")).thenReturn(mockApiKey); + when(vaultService.getLocalSecret("edc.participantId")).thenReturn(bpn); - bpn = edc.get("participantId").toString(); ProcessConfig processConfig = new ProcessConfig(); processConfig.setDir("process"); @@ -86,7 +88,8 @@ void setUpAll() throws ServiceInitializationException { @BeforeEach void setUp() { - Set policy = (Set) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testPolicyPath, Set.class); + String filePath = Paths.get(fileUtil.getBaseClassDir(this.getClass()), testPolicyPath).toString(); + Set policy = (Set) jsonUtil.fromJsonFileToObject(filePath, Set.class); Dataset dataSet = new Dataset(); String dataSetId = UUID.randomUUID().toString(); @@ -103,7 +106,8 @@ void setUp() { private MockEnvironment initEnv() { MockEnvironment env = new MockEnvironment(); - Map application = yamlUtil.readFile(FileUtil.getWorkdirPath() + "/src/main/resources/application.yml"); + String configurationFilePath = Paths.get(fileUtil.getBaseClassDir(this.getClass()), "application-test.yml").toString(); + Map application = yamlUtil.readFile(configurationFilePath); Map configuration = (Map) jsonUtil.toMap(application.get("configuration")); Map edc = (Map) jsonUtil.toMap(configuration.get("edc")); env.setProperty("configuration.edc.endpoint", edc.get("endpoint").toString()); @@ -119,17 +123,18 @@ private DtrConfig initDtrConfig() { DtrConfig dtrConfig = new DtrConfig(); DtrConfig.Timeouts timeouts = new DtrConfig.Timeouts(); timeouts.setSearch(10); - timeouts.setNegotiation(40); + timeouts.setDtrRequestProcess(40); + timeouts.setNegotiation(10); timeouts.setTransfer(10); timeouts.setDigitalTwin(20); dtrConfig.setTimeouts(timeouts); dtrConfig.setTemporaryStorage(new DtrConfig.TemporaryStorage(true, 12)); - return dtrConfig; } private VaultConfig initVaultConfig() { - Map application = yamlUtil.readFile(FileUtil.getWorkdirPath() + "/src/main/resources/application.yml"); + String configurationFilePath = Paths.get(fileUtil.getBaseClassDir(this.getClass()), "application-test.yml").toString(); + Map application = yamlUtil.readFile(configurationFilePath); Map configuration = (Map) jsonUtil.toMap(application.get("configuration")); Map vault = (Map) jsonUtil.toMap(configuration.get("vault")); VaultConfig vaultConfig = new VaultConfig(); @@ -141,7 +146,7 @@ private VaultConfig initVaultConfig() { @Test void checkEdcConsumerConnection() { when(httpUtil.doPost(anyString(), any(Class.class), any(HttpHeaders.class), any(Map.class), any(Object.class), eq(false), eq(false))) - .thenReturn(new ResponseEntity<>(jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testCOCatalogPath, JsonNode.class), HttpStatus.OK)); + .thenReturn(new ResponseEntity<>(jsonUtil.fromJsonFileToObject(Paths.get(fileUtil.getBaseClassDir(this.getClass()), testCOCatalogPath).toString(), JsonNode.class), HttpStatus.OK)); String participantId = dataTransferService.checkEdcConsumerConnection(); @@ -171,14 +176,14 @@ void buildRequestAndOffer() { @Test void getContractOfferCatalog() { String providerUrl = UUID.randomUUID().toString(); - Catalog catalog = (Catalog) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testCOCatalogPath, Catalog.class); + Catalog catalog = (Catalog) jsonUtil.fromJsonFileToObject(Paths.get(fileUtil.getBaseClassDir(this.getClass()), testCOCatalogPath).toString(), Catalog.class); String assetId = catalog.getParticipantId(); when(httpUtil.doPost(anyString(), any(Class.class), any(HttpHeaders.class), any(Map.class), any(Object.class), eq(false), eq(false))) .then(invocation -> { CatalogRequest body = invocation.getArgument(4); if (body.getProviderUrl().equals(providerUrl)) { - return new ResponseEntity<>(jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testCOCatalogPath, JsonNode.class), HttpStatus.OK); + return new ResponseEntity<>(jsonUtil.fromJsonFileToObject(Paths.get(fileUtil.getBaseClassDir(this.getClass()), testCOCatalogPath).toString(), JsonNode.class), HttpStatus.OK); } return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); }); @@ -200,13 +205,13 @@ void getContractOfferCatalog() { @Test void searchDigitalTwinCatalog() { String providerUrl = UUID.randomUUID().toString(); - Catalog catalog = (Catalog) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testDTCatalogPath, Catalog.class); + Catalog catalog = (Catalog) jsonUtil.fromJsonFileToObject(Paths.get(fileUtil.getBaseClassDir(this.getClass()), testDTCatalogPath).toString(), Catalog.class); when(httpUtil.doPost(anyString(), any(Class.class), any(HttpHeaders.class), any(Map.class), any(Object.class), eq(false), eq(false))) .then(invocation -> { CatalogRequest body = invocation.getArgument(4); if (body.getProviderUrl().equals(CatenaXUtil.buildDataEndpoint(providerUrl))) { - return new ResponseEntity<>(jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testDTCatalogPath, JsonNode.class), HttpStatus.OK); + return new ResponseEntity<>(jsonUtil.fromJsonFileToObject(Paths.get(fileUtil.getBaseClassDir(this.getClass()), testDTCatalogPath).toString(), JsonNode.class), HttpStatus.OK); } return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); }); @@ -234,7 +239,7 @@ void doContractNegotiationAndSeeNegotiation() { .then(invocation -> { NegotiationRequest body = invocation.getArgument(4); if (body instanceof NegotiationRequest) { - return new ResponseEntity<>(jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testResponseInitNegotiationPath, JsonNode.class), HttpStatus.OK); + return new ResponseEntity<>(jsonUtil.fromJsonFileToObject(Paths.get(fileUtil.getBaseClassDir(this.getClass()), testResponseInitNegotiationPath).toString(), JsonNode.class), HttpStatus.OK); } return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); }); @@ -246,7 +251,7 @@ void doContractNegotiationAndSeeNegotiation() { assertEquals("edc:IdResponseDto", response.getType()); when(httpUtil.doGet(anyString(), any(Class.class), any(HttpHeaders.class), any(Map.class), eq(false), eq(false))) - .thenReturn(new ResponseEntity<>(jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testResponseNegotiationPath, JsonNode.class), HttpStatus.OK)); + .thenReturn(new ResponseEntity<>(jsonUtil.fromJsonFileToObject(Paths.get(fileUtil.getBaseClassDir(this.getClass()), testResponseNegotiationPath).toString(), JsonNode.class), HttpStatus.OK)); Negotiation negotiation = dataTransferService.seeNegotiation(response.getId()); @@ -263,7 +268,7 @@ private Negotiation getNegotiation() { .then(invocation -> { NegotiationRequest body = invocation.getArgument(4); if (body instanceof NegotiationRequest) { - return new ResponseEntity<>(jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testResponseInitNegotiationPath, JsonNode.class), HttpStatus.OK); + return new ResponseEntity<>(jsonUtil.fromJsonFileToObject(Paths.get(fileUtil.getBaseClassDir(this.getClass()), testResponseInitNegotiationPath).toString(), JsonNode.class), HttpStatus.OK); } return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); }); @@ -271,7 +276,7 @@ private Negotiation getNegotiation() { IdResponse negotiationResponse = dataTransferService.doContractNegotiation(offer, bpn, providerUrl); when(httpUtil.doGet(anyString(), any(Class.class), any(HttpHeaders.class), any(Map.class), eq(false), eq(false))) - .thenReturn(new ResponseEntity<>(jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testResponseNegotiationPath, JsonNode.class), HttpStatus.OK)); + .thenReturn(new ResponseEntity<>(jsonUtil.fromJsonFileToObject(Paths.get(fileUtil.getBaseClassDir(this.getClass()), testResponseNegotiationPath).toString(), JsonNode.class), HttpStatus.OK)); return dataTransferService.seeNegotiation(negotiationResponse.getId()); } @@ -297,7 +302,7 @@ void initiateTransferAndSeeTransfer() { ); when(httpUtil.doPost(anyString(), any(Class.class), any(HttpHeaders.class), any(Map.class), any(Object.class), eq(false), eq(false))) - .thenReturn(new ResponseEntity<>(jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testResponseInitTransferPath, JsonNode.class).toString(), HttpStatus.OK)); + .thenReturn(new ResponseEntity<>(jsonUtil.fromJsonFileToObject(Paths.get(fileUtil.getBaseClassDir(this.getClass()), testResponseInitTransferPath).toString(), JsonNode.class).toString(), HttpStatus.OK)); IdResponse response = dataTransferService.initiateTransfer(transferRequest); @@ -306,7 +311,7 @@ void initiateTransferAndSeeTransfer() { assertEquals("edc:IdResponseDto", response.getType()); when(httpUtil.doGet(anyString(), any(Class.class), any(HttpHeaders.class), any(Map.class), eq(false), eq(false))) - .thenReturn(new ResponseEntity<>(jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testResponseTransferPath, JsonNode.class), HttpStatus.OK)); + .thenReturn(new ResponseEntity<>(jsonUtil.fromJsonFileToObject(Paths.get(fileUtil.getBaseClassDir(this.getClass()), testResponseTransferPath).toString(), JsonNode.class), HttpStatus.OK)); Transfer transfer = dataTransferService.seeTransfer(response.getId()); diff --git a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/IrsServiceTest.java b/dpp-backend/digitalproductpass/src/test/java/services/IrsServiceTest.java similarity index 67% rename from consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/IrsServiceTest.java rename to dpp-backend/digitalproductpass/src/test/java/services/IrsServiceTest.java index ee6681670..6d5521243 100644 --- a/consumer-backend/productpass/src/test/java/org/eclipse/tractusx/productpass/services/IrsServiceTest.java +++ b/dpp-backend/digitalproductpass/src/test/java/services/IrsServiceTest.java @@ -1,16 +1,20 @@ -package org.eclipse.tractusx.productpass.services; +package services; import com.fasterxml.jackson.databind.JsonNode; -import org.eclipse.tractusx.productpass.config.IrsConfig; -import org.eclipse.tractusx.productpass.config.PassportConfig; -import org.eclipse.tractusx.productpass.config.ProcessConfig; -import org.eclipse.tractusx.productpass.exceptions.ServiceInitializationException; -import org.eclipse.tractusx.productpass.managers.ProcessManager; -import org.eclipse.tractusx.productpass.managers.TreeManager; -import org.eclipse.tractusx.productpass.models.auth.JwtToken; -import org.eclipse.tractusx.productpass.models.irs.JobHistory; -import org.eclipse.tractusx.productpass.models.irs.JobRequest; -import org.eclipse.tractusx.productpass.models.irs.JobResponse; +import org.eclipse.tractusx.digitalproductpass.config.IrsConfig; +import org.eclipse.tractusx.digitalproductpass.config.PassportConfig; +import org.eclipse.tractusx.digitalproductpass.config.ProcessConfig; +import org.eclipse.tractusx.digitalproductpass.config.SecurityConfig; +import org.eclipse.tractusx.digitalproductpass.exceptions.ServiceInitializationException; +import org.eclipse.tractusx.digitalproductpass.managers.ProcessManager; +import org.eclipse.tractusx.digitalproductpass.managers.TreeManager; +import org.eclipse.tractusx.digitalproductpass.models.auth.JwtToken; +import org.eclipse.tractusx.digitalproductpass.models.irs.JobHistory; +import org.eclipse.tractusx.digitalproductpass.models.irs.JobRequest; +import org.eclipse.tractusx.digitalproductpass.models.irs.JobResponse; +import org.eclipse.tractusx.digitalproductpass.services.AuthenticationService; +import org.eclipse.tractusx.digitalproductpass.services.IrsService; +import org.eclipse.tractusx.digitalproductpass.services.VaultService; import org.junit.jupiter.api.*; import org.mockito.Mock; import org.mockito.Mockito; @@ -26,6 +30,7 @@ import utils.YamlUtil; import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -42,16 +47,17 @@ class IrsServiceTest { private IrsService irsService; private IrsConfig irsConfig; - private final String testJobResposnsePath = "/src/test/resources/dpp/irs/TestJobResponse.json"; - private final String testStartJobResposnsePath = "/src/test/resources/dpp/irs/TestStartJobResponse.json"; + private final String testJobResposnsePath = "/dpp/irs/TestJobResponse.json"; + private final String testStartJobResposnsePath = "/dpp/irs/TestStartJobResponse.json"; private Map configuration; - private final String mockedTokenPath = "/src/test/resources/dpp/token/MockedToken.json"; + private final String mockedTokenPath = "/dpp/token/MockedToken.json"; private JwtToken mockedToken; @Mock private Environment env; private HttpUtil httpUtil; private JsonUtil jsonUtil; private YamlUtil yamlUtil; + private SecurityConfig securityConfig; private FileUtil fileUtil; private ProcessManager processManager; private TreeManager treeManager; @@ -64,27 +70,37 @@ void setUpAll() throws ServiceInitializationException { fileUtil = new FileUtil(); jsonUtil = new JsonUtil(fileUtil); yamlUtil = new YamlUtil(fileUtil); + securityConfig = new SecurityConfig(); + securityConfig.setAuthorization(new SecurityConfig.AuthorizationConfig(false, false)); + securityConfig.setStartUpChecks(new SecurityConfig.StartUpCheckConfig(false, false)); httpUtil = Mockito.spy(new HttpUtil(env)); - Map application = yamlUtil.readFile(FileUtil.getWorkdirPath() + "/src/main/resources/application.yml"); + String configurationFilePath = Paths.get(fileUtil.getBaseClassDir(this.getClass()), "application-test.yml").toString(); + Map application = yamlUtil.readFile(configurationFilePath); configuration = (Map) jsonUtil.toMap(application.get("configuration")); - Map vaultConfig = yamlUtil.readFile(fileUtil.getDataDir() + "/VaultConfig/vault.token.yml"); - Map client = (Map) jsonUtil.toMap(vaultConfig.get("client")); - when(vaultService.getLocalSecret("client.id")).thenReturn(client.get("id").toString()); - when(vaultService.getLocalSecret("client.secret")).thenReturn(client.get("secret").toString()); + String mockClientId="xynasdnsda12312"; + String mockClientTestReturn="212123asddsad54546"; + String mockApiKey="aqweas1230sad"; + String mockBpn="BPNL00000000000"; + + when(vaultService.getLocalSecret("client.id")).thenReturn(mockClientId); + when(vaultService.getLocalSecret("client.secret")).thenReturn(mockClientTestReturn); + + when(vaultService.getLocalSecret("edc.apiKey")).thenReturn(mockApiKey); + when(vaultService.getLocalSecret("edc.participantId")).thenReturn(mockBpn); env = initEnv(); irsConfig = initIrsConfig(); ProcessConfig processConfig = new ProcessConfig(); PassportConfig passportConfig = new PassportConfig(); - authenticationService = Mockito.spy(new AuthenticationService(vaultService, env, httpUtil, jsonUtil)); + authenticationService = Mockito.spy(new AuthenticationService(vaultService, env, httpUtil, jsonUtil, securityConfig)); processManager = Mockito.spy(new ProcessManager(httpUtil, jsonUtil, fileUtil, processConfig)); treeManager = new TreeManager(fileUtil, jsonUtil, processManager, irsConfig, passportConfig); irsService = new IrsService(env, processManager, irsConfig, treeManager, httpUtil, vaultService, jsonUtil, authenticationService); - mockedToken = (JwtToken) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + mockedTokenPath, JwtToken.class); + mockedToken = (JwtToken) jsonUtil.fromJsonFileToObject(Paths.get(fileUtil.getBaseClassDir(this.getClass()), mockedTokenPath).toString() , JwtToken.class); doReturn(mockedToken).when(authenticationService).getToken(); } @@ -113,10 +129,10 @@ private MockEnvironment initEnv() { @BeforeEach void setUp() { - doReturn(new ResponseEntity<>(jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testStartJobResposnsePath, JsonNode.class), HttpStatus.OK)) + doReturn(new ResponseEntity<>(jsonUtil.fromJsonFileToObject(Paths.get(fileUtil.getBaseClassDir(this.getClass()), testStartJobResposnsePath).toString() , JsonNode.class), HttpStatus.OK)) .when(httpUtil).doPost(anyString(), any(Class.class), any(HttpHeaders.class), any(Map.class), any(JobRequest.class), eq(false), eq(false)); - doReturn(new ResponseEntity<>(jsonUtil.toJson(jsonUtil.fromJsonFile(FileUtil.getWorkdirPath() + testJobResposnsePath), true), HttpStatus.OK)) + doReturn(new ResponseEntity<>(jsonUtil.toJson(jsonUtil.fromJsonFile(Paths.get(fileUtil.getBaseClassDir(this.getClass()), testJobResposnsePath).toString() ), true), HttpStatus.OK)) .when(httpUtil).doGet(anyString(), any(Class.class), any(HttpHeaders.class), any(Map.class), eq(true), eq(false)); doReturn("TEST_PATH").when(processManager).setJobHistory(anyString(), any(JobHistory.class)); @@ -150,7 +166,7 @@ void getChildren() { @Test void getJob() { - JobResponse test = (JobResponse) jsonUtil.fromJsonFileToObject(FileUtil.getWorkdirPath() + testJobResposnsePath, JobResponse.class); + JobResponse test = (JobResponse) jsonUtil.fromJsonFileToObject(Paths.get(fileUtil.getBaseClassDir(this.getClass()), testJobResposnsePath).toString() , JobResponse.class); String jobId = "0bbc712b-17a1-4c9d-9c9c-a7fae8082841"; JobResponse jobResponse = irsService.getJob(jobId); diff --git a/dpp-backend/digitalproductpass/src/test/resources/application-test.yml b/dpp-backend/digitalproductpass/src/test/resources/application-test.yml new file mode 100644 index 000000000..200fe7627 --- /dev/null +++ b/dpp-backend/digitalproductpass/src/test/resources/application-test.yml @@ -0,0 +1,144 @@ +################################################################################# +# Catena-X - Digital Product Pass Backend +# +# Copyright (c) 2022, 2024 BASF SE, BMW AG, Henkel AG & Co. KGaA +# Copyright (c) 2022, 2024 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Apache License, Version 2.0 which is available at +# https://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 govern in permissions and limitations +# under the License. +# +# SPDX-License-Identifier: Apache-2.0 +################################################################################# + + +spring: + name: 'Catena-X Digital Product Passport Consumer Backend' + main: + allow-bean-definition-overriding: true + devtools: + add-properties: false + jackson: + serialization: + indent_output: true + +logging: + level: + root: INFO + utils: INFO + +configuration: + maxRetries: 5 + + keycloak: + realm: CX-Central + resource: Cl13-CX-Battery + tokenUri: 'https://centralidp.int.demo.catena-x.net/auth/realms/CX-Central/protocol/openid-connect/token' + userInfoUri: 'https://centralidp.int.demo.catena-x.net/auth/realms/CX-Central/protocol/openid-connect/userinfo' + + edc: + endpoint: 'https://materialpass.int.demo.catena-x.net/consumer' + management: '/management/v2' + catalog: '/catalog/request' + negotiation: '/contractnegotiations' + transfer: '/transferprocesses' + receiverEndpoint: 'https://materialpass.int.demo.catena-x.net/endpoint' + delay: 100 # -- Negotiation status Delay in milliseconds in between async requests [<= 500] + + security: + authorization: + bpnAuth: false + roleAuth: false + startUpChecks: + bpnCheck: false + edcCheck: false + + irs: + enabled: true + endpoint: "https://materialpass-irs.int.demo.catena-x.net" + paths: + job: "/irs/jobs" + tree: + fileName: "treeDataModel" + indent: true + callbackUrl: "https://materialpass.int.demo.catena-x.net/api/irs" + + dtr: + assetType: 'data.core.digitalTwinRegistry' + endpointInterface: 'SUBMODEL-3.0' + dspEndpointKey: 'dspEndpoint' + semanticIdTypeKey: 'Submodel' + decentralApis: + search: "/lookup/shells" + digitalTwin: "/shell-descriptors" + subModel: "/submodel-descriptors" + timeouts: + search: 10 + negotiation: 10 + dtrRequestProcess: 40 + transfer: 10 + digitalTwin: 20 + temporaryStorage: + enabled: true + lifetime: 12 # -- Hours + + discovery: + endpoint: "https://semantics.int.demo.catena-x.net/discoveryfinder/api/v1.0/administration/connectors/discovery/search" + bpn: + key: "manufacturerPartId" + searchPath: "/api/v1.0/administration/connectors/bpnDiscovery/search" + timeout: 1500 + edc: + key: "bpn" + timeout: 1500 + + + process: + store: true + dir: 'process' + indent: true + signKey: 'c55e3f35200f6afedbce37cefdaf40eadd15c92814edfdbc4d6ab0eacdcdd56dbcd5a2a34ca4b675084d33f9f479d7d79347795148aaf4443e1b47ab96b27e72' + + passport: + searchIdSchema: "CX::" + dataTransfer: + encrypt: true + indent: true + dir: "data/transfer" + aspects: + - "urn:bamm:io.catenax.generic.digital_product_passport:1.0.0#DigitalProductPassport" + - "urn:bamm:io.catenax.battery.battery_pass:3.0.1#BatteryPass" + + vault: + type: 'local' + file: 'vault.token.yml' + pathSep: "." + prettyPrint: true + indent: 2 + defaultValue: '' + attributes: + - "appId" + - "client.id" + - "client.secret" + - "edc.apiKey" + - "edc.participantId" + +server: + error: + include-message: ALWAYS + include-binding-errors: ALWAYS + include-stacktrace: ON_PARAM + include-exception: false + port: 8888 + tomcat: + max-connections: 10000 diff --git a/consumer-backend/productpass/src/test/resources/dpp/assets/TestAsset.json b/dpp-backend/digitalproductpass/src/test/resources/dpp/assets/TestAsset.json similarity index 100% rename from consumer-backend/productpass/src/test/resources/dpp/assets/TestAsset.json rename to dpp-backend/digitalproductpass/src/test/resources/dpp/assets/TestAsset.json diff --git a/consumer-backend/productpass/src/test/resources/dpp/catalogs/TestContractOfferCatalog.json b/dpp-backend/digitalproductpass/src/test/resources/dpp/catalogs/TestContractOfferCatalog.json similarity index 97% rename from consumer-backend/productpass/src/test/resources/dpp/catalogs/TestContractOfferCatalog.json rename to dpp-backend/digitalproductpass/src/test/resources/dpp/catalogs/TestContractOfferCatalog.json index f617eb955..435832e2d 100644 --- a/consumer-backend/productpass/src/test/resources/dpp/catalogs/TestContractOfferCatalog.json +++ b/dpp-backend/digitalproductpass/src/test/resources/dpp/catalogs/TestContractOfferCatalog.json @@ -51,7 +51,7 @@ "dct:terms": "connector", "dct:endpointUrl": "https://materialpass.int.demo.catena-x.net/BPNL000000000000/api/v1/dsp" }, - "edc:participantId": "BPNL00000000CBA5", + "edc:participantId": "BPNL00000000000", "@context": { "dct": "https://purl.org/dc/terms/", "tx": "https://w3id.org/tractusx/v0.0.1/ns/", diff --git a/consumer-backend/productpass/src/test/resources/dpp/catalogs/TestDigitalTwinCatalog.json b/dpp-backend/digitalproductpass/src/test/resources/dpp/catalogs/TestDigitalTwinCatalog.json similarity index 97% rename from consumer-backend/productpass/src/test/resources/dpp/catalogs/TestDigitalTwinCatalog.json rename to dpp-backend/digitalproductpass/src/test/resources/dpp/catalogs/TestDigitalTwinCatalog.json index d54febe7f..99b4da7bc 100644 --- a/consumer-backend/productpass/src/test/resources/dpp/catalogs/TestDigitalTwinCatalog.json +++ b/dpp-backend/digitalproductpass/src/test/resources/dpp/catalogs/TestDigitalTwinCatalog.json @@ -39,7 +39,7 @@ "dct:terms": "connector", "dct:endpointUrl": "https://materialpass.int.demo.catena-x.net/BPNL000000000000/api/v1/dsp" }, - "edc:participantId": "BPNL00000000CBA5", + "edc:participantId": "BPNL00000000000", "@context": { "dct": "https://purl.org/dc/terms/", "tx": "https://w3id.org/tractusx/v0.0.1/ns/", diff --git a/consumer-backend/productpass/src/test/resources/dpp/contractpolicies/TestPolicy.json b/dpp-backend/digitalproductpass/src/test/resources/dpp/contractpolicies/TestPolicy.json similarity index 100% rename from consumer-backend/productpass/src/test/resources/dpp/contractpolicies/TestPolicy.json rename to dpp-backend/digitalproductpass/src/test/resources/dpp/contractpolicies/TestPolicy.json diff --git a/consumer-backend/productpass/src/test/resources/dpp/digitaltwins/TestDigitalTwin.json b/dpp-backend/digitalproductpass/src/test/resources/dpp/digitaltwins/TestDigitalTwin.json similarity index 100% rename from consumer-backend/productpass/src/test/resources/dpp/digitaltwins/TestDigitalTwin.json rename to dpp-backend/digitalproductpass/src/test/resources/dpp/digitaltwins/TestDigitalTwin.json diff --git a/consumer-backend/productpass/src/test/resources/dpp/discovery/MockedDiscoveryEndpoints.json b/dpp-backend/digitalproductpass/src/test/resources/dpp/discovery/MockedDiscoveryEndpoints.json similarity index 100% rename from consumer-backend/productpass/src/test/resources/dpp/discovery/MockedDiscoveryEndpoints.json rename to dpp-backend/digitalproductpass/src/test/resources/dpp/discovery/MockedDiscoveryEndpoints.json diff --git a/consumer-backend/productpass/src/test/resources/dpp/irs/TestJobHistory.json b/dpp-backend/digitalproductpass/src/test/resources/dpp/irs/TestJobHistory.json similarity index 100% rename from consumer-backend/productpass/src/test/resources/dpp/irs/TestJobHistory.json rename to dpp-backend/digitalproductpass/src/test/resources/dpp/irs/TestJobHistory.json diff --git a/consumer-backend/productpass/src/test/resources/dpp/irs/TestJobResponse.json b/dpp-backend/digitalproductpass/src/test/resources/dpp/irs/TestJobResponse.json similarity index 100% rename from consumer-backend/productpass/src/test/resources/dpp/irs/TestJobResponse.json rename to dpp-backend/digitalproductpass/src/test/resources/dpp/irs/TestJobResponse.json diff --git a/consumer-backend/productpass/src/test/resources/dpp/irs/TestStartJobResponse.json b/dpp-backend/digitalproductpass/src/test/resources/dpp/irs/TestStartJobResponse.json similarity index 100% rename from consumer-backend/productpass/src/test/resources/dpp/irs/TestStartJobResponse.json rename to dpp-backend/digitalproductpass/src/test/resources/dpp/irs/TestStartJobResponse.json diff --git a/consumer-backend/productpass/src/test/resources/dpp/irs/TestTreeDataModel.json b/dpp-backend/digitalproductpass/src/test/resources/dpp/irs/TestTreeDataModel.json similarity index 100% rename from consumer-backend/productpass/src/test/resources/dpp/irs/TestTreeDataModel.json rename to dpp-backend/digitalproductpass/src/test/resources/dpp/irs/TestTreeDataModel.json diff --git a/consumer-backend/productpass/src/test/resources/dpp/negotiation/TestResponseInitNegotiation.json b/dpp-backend/digitalproductpass/src/test/resources/dpp/negotiation/TestResponseInitNegotiation.json similarity index 100% rename from consumer-backend/productpass/src/test/resources/dpp/negotiation/TestResponseInitNegotiation.json rename to dpp-backend/digitalproductpass/src/test/resources/dpp/negotiation/TestResponseInitNegotiation.json diff --git a/consumer-backend/productpass/src/test/resources/dpp/negotiation/TestResponseNegotiation.json b/dpp-backend/digitalproductpass/src/test/resources/dpp/negotiation/TestResponseNegotiation.json similarity index 100% rename from consumer-backend/productpass/src/test/resources/dpp/negotiation/TestResponseNegotiation.json rename to dpp-backend/digitalproductpass/src/test/resources/dpp/negotiation/TestResponseNegotiation.json diff --git a/consumer-backend/productpass/src/test/resources/dpp/payloads/TestPassport.json b/dpp-backend/digitalproductpass/src/test/resources/dpp/payloads/TestPassport.json similarity index 100% rename from consumer-backend/productpass/src/test/resources/dpp/payloads/TestPassport.json rename to dpp-backend/digitalproductpass/src/test/resources/dpp/payloads/TestPassport.json diff --git a/consumer-backend/productpass/src/test/resources/dpp/token/MockedToken.json b/dpp-backend/digitalproductpass/src/test/resources/dpp/token/MockedToken.json similarity index 100% rename from consumer-backend/productpass/src/test/resources/dpp/token/MockedToken.json rename to dpp-backend/digitalproductpass/src/test/resources/dpp/token/MockedToken.json diff --git a/consumer-backend/productpass/src/test/resources/dpp/token/MockedUserInfo.json b/dpp-backend/digitalproductpass/src/test/resources/dpp/token/MockedUserInfo.json similarity index 100% rename from consumer-backend/productpass/src/test/resources/dpp/token/MockedUserInfo.json rename to dpp-backend/digitalproductpass/src/test/resources/dpp/token/MockedUserInfo.json diff --git a/consumer-backend/productpass/src/test/resources/dpp/transfer/TestResponseInitTransfer.json b/dpp-backend/digitalproductpass/src/test/resources/dpp/transfer/TestResponseInitTransfer.json similarity index 100% rename from consumer-backend/productpass/src/test/resources/dpp/transfer/TestResponseInitTransfer.json rename to dpp-backend/digitalproductpass/src/test/resources/dpp/transfer/TestResponseInitTransfer.json diff --git a/consumer-backend/productpass/src/test/resources/dpp/transfer/TestResponseTransfer.json b/dpp-backend/digitalproductpass/src/test/resources/dpp/transfer/TestResponseTransfer.json similarity index 100% rename from consumer-backend/productpass/src/test/resources/dpp/transfer/TestResponseTransfer.json rename to dpp-backend/digitalproductpass/src/test/resources/dpp/transfer/TestResponseTransfer.json From 5d67e28ae48abf73fba0b75b01d2e12d61819ff7 Mon Sep 17 00:00:00 2001 From: Mathias Brunkow Moser Date: Mon, 8 Jan 2024 18:08:50 +0100 Subject: [PATCH 5/6] feat: removed improper prints and imports --- .../java/managers/DtrSearchManagerTest.java | 57 ++----------------- .../java/managers/ProcessDataModelTest.java | 1 - .../java/managers/ProcessManagerTest.java | 8 +-- .../test/java/mocks/MockedHttpSession.java | 5 +- .../test/java/services/AasServiceTest.java | 11 ++-- .../services/AuthenticationServiceTest.java | 8 +-- .../java/services/CatenaXServiceTest.java | 5 +- .../java/services/DataPlaneServiceTest.java | 5 +- .../test/java/services/IrsServiceTest.java | 8 +-- .../src/test/java/utils/CrypUtilTest.java | 4 +- .../src/test/java/utils/JsonUtilTest.java | 2 - .../src/test/java/utils/LogUtilTest.java | 6 +- .../src/test/java/utils/SystemUtilTest.java | 5 +- .../src/test/java/utils/YamlUtilTest.java | 6 -- 14 files changed, 34 insertions(+), 97 deletions(-) diff --git a/dpp-backend/digitalproductpass/src/test/java/managers/DtrSearchManagerTest.java b/dpp-backend/digitalproductpass/src/test/java/managers/DtrSearchManagerTest.java index 827453f64..07354c928 100644 --- a/dpp-backend/digitalproductpass/src/test/java/managers/DtrSearchManagerTest.java +++ b/dpp-backend/digitalproductpass/src/test/java/managers/DtrSearchManagerTest.java @@ -1,38 +1,22 @@ package managers; -import org.eclipse.tractusx.digitalproductpass.Application; import org.eclipse.tractusx.digitalproductpass.config.DtrConfig; import org.eclipse.tractusx.digitalproductpass.config.ProcessConfig; -import org.eclipse.tractusx.digitalproductpass.config.VaultConfig; -import org.eclipse.tractusx.digitalproductpass.exceptions.ServiceInitializationException; import org.eclipse.tractusx.digitalproductpass.managers.DtrSearchManager; import org.eclipse.tractusx.digitalproductpass.managers.ProcessManager; import org.eclipse.tractusx.digitalproductpass.models.catenax.Dtr; -import org.eclipse.tractusx.digitalproductpass.models.manager.SearchStatus; -import org.eclipse.tractusx.digitalproductpass.models.negotiation.Catalog; import org.eclipse.tractusx.digitalproductpass.services.DataTransferService; -import org.eclipse.tractusx.digitalproductpass.services.VaultService; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; -import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.env.Environment; -import org.springframework.mock.env.MockEnvironment; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.util.ReflectionTestUtils; -import utils.*; - -import java.io.InputStream; -import java.nio.file.Paths; +import utils.DateTimeUtil; +import utils.FileUtil; +import utils.HttpUtil; +import utils.JsonUtil; + import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -198,35 +182,4 @@ void saveAndLoadDataModel() { dtrSearchManager.deleteBpns(dtrSearchManager.getDtrDataModel(), List.of(bpn1, bpn2)); dtrSearchManager.saveDtrDataModel(); } - - @Test - void updateProcess() { //TODO - String bpn1 = "BPN001"; - String contractId1 = UUID.randomUUID().toString(); - String assetId1 = UUID.randomUUID().toString(); - String endpoint1 = "dtr.endpoint1"; - Long validUntil1 = DateTimeUtil.getTimestamp(); - Dtr dtr1 = new Dtr(contractId1, endpoint1, assetId1, bpn1, validUntil1); - - } - - @Test - void searchEndpoint() { //TODO - String file = Paths.get(fileUtil.getBaseClassDir(this.getClass()), testAssetPath).toString(); - Object contractOffer = jsonUtil.fromJsonFileToObject(file, Object.class); - assertNotNull(contractOffer); - Catalog catalog = new Catalog(); - catalog.setContractOffer(contractOffer); - String connectionUrl = "test.connection.url"; - when(dataTransferService.searchDigitalTwinCatalog(connectionUrl)).thenReturn(catalog); - String bpn = "BPN000001"; - String testProcessId = processManager.initProcess(); - - dtrSearchManager.searchEndpoint(testProcessId, bpn, connectionUrl); - - SearchStatus searchStatus = processManager.getSearchStatus(testProcessId); - - // assertEquals(bpn, searchStatus.getDtrs().get(0).getBpn()); - // assertEquals(connectionUrl, searchStatus.getDtrs().get(0).getEndpoint()); - } } diff --git a/dpp-backend/digitalproductpass/src/test/java/managers/ProcessDataModelTest.java b/dpp-backend/digitalproductpass/src/test/java/managers/ProcessDataModelTest.java index 2a678792e..9195a86a2 100644 --- a/dpp-backend/digitalproductpass/src/test/java/managers/ProcessDataModelTest.java +++ b/dpp-backend/digitalproductpass/src/test/java/managers/ProcessDataModelTest.java @@ -7,7 +7,6 @@ import org.junit.jupiter.api.Test; import org.mockito.Mock; -import java.lang.reflect.UndeclaredThrowableException; import java.util.HashMap; import java.util.Map; diff --git a/dpp-backend/digitalproductpass/src/test/java/managers/ProcessManagerTest.java b/dpp-backend/digitalproductpass/src/test/java/managers/ProcessManagerTest.java index 4638c967a..5a2c5d458 100644 --- a/dpp-backend/digitalproductpass/src/test/java/managers/ProcessManagerTest.java +++ b/dpp-backend/digitalproductpass/src/test/java/managers/ProcessManagerTest.java @@ -486,8 +486,6 @@ void saveNegotiationRequestAndNegotiation() { assertFalse(updatedNegotiation.isEmpty()); assertEquals(2, updatedNegotiation.size()); - LogUtil.printTest("NEGOTIATION: " + jsonUtil.toJson(updatedNegotiation, true)); - Map init = (Map) updatedNegotiation.get("init"); NegotiationRequest updatedNegotiationRequest = (NegotiationRequest) jsonUtil.bindObject(init.get("request"), NegotiationRequest.class); @@ -511,11 +509,11 @@ void cancelProcessAndSetDecline() { public void run() { try { while(true) { - LogUtil.printMessage("NEGOTIATING....!"); + LogUtil.printTest("NEGOTIATING....!"); sleep(1); } } catch (InterruptedException e) { - LogUtil.printMessage("PROCESS STOPED!"); + LogUtil.printTest("PROCESS STOPED!"); } } }); @@ -604,8 +602,6 @@ void saveTransferRequestAndTransfer() { assertFalse(updatedTransfer.isEmpty()); assertEquals(2, updatedTransfer.size()); - LogUtil.printTest("TRANSFER: " + jsonUtil.toJson(updatedTransfer, true)); - Map init = (Map) updatedTransfer.get("init"); TransferRequest updatedTransferRequest = (TransferRequest) jsonUtil.bindObject(init.get("request"), TransferRequest.class); diff --git a/dpp-backend/digitalproductpass/src/test/java/mocks/MockedHttpSession.java b/dpp-backend/digitalproductpass/src/test/java/mocks/MockedHttpSession.java index 9f79688c1..8a1dbe2b6 100644 --- a/dpp-backend/digitalproductpass/src/test/java/mocks/MockedHttpSession.java +++ b/dpp-backend/digitalproductpass/src/test/java/mocks/MockedHttpSession.java @@ -4,7 +4,10 @@ import jakarta.servlet.http.HttpSession; import utils.DateTimeUtil; -import java.util.*; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; import java.util.stream.Collectors; public class MockedHttpSession implements HttpSession { diff --git a/dpp-backend/digitalproductpass/src/test/java/services/AasServiceTest.java b/dpp-backend/digitalproductpass/src/test/java/services/AasServiceTest.java index 11a6b8350..8eb82e0a5 100644 --- a/dpp-backend/digitalproductpass/src/test/java/services/AasServiceTest.java +++ b/dpp-backend/digitalproductpass/src/test/java/services/AasServiceTest.java @@ -3,7 +3,6 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import mocks.MockedHttpSession; -import org.bouncycastle.asn1.x509.GeneralName; import org.eclipse.tractusx.digitalproductpass.config.DtrConfig; import org.eclipse.tractusx.digitalproductpass.config.PassportConfig; import org.eclipse.tractusx.digitalproductpass.config.ProcessConfig; @@ -12,14 +11,11 @@ import org.eclipse.tractusx.digitalproductpass.managers.DtrSearchManager; import org.eclipse.tractusx.digitalproductpass.managers.ProcessManager; import org.eclipse.tractusx.digitalproductpass.models.auth.JwtToken; -import org.eclipse.tractusx.digitalproductpass.models.catenax.Discovery; import org.eclipse.tractusx.digitalproductpass.models.dtregistry.DigitalTwin; import org.eclipse.tractusx.digitalproductpass.models.dtregistry.SubModel; import org.eclipse.tractusx.digitalproductpass.models.edc.AssetSearch; -import org.eclipse.tractusx.digitalproductpass.models.edc.DataPlaneEndpoint; import org.eclipse.tractusx.digitalproductpass.models.http.requests.Search; import org.eclipse.tractusx.digitalproductpass.models.manager.History; -import org.eclipse.tractusx.digitalproductpass.models.manager.Status; import org.eclipse.tractusx.digitalproductpass.services.AasService; import org.eclipse.tractusx.digitalproductpass.services.AuthenticationService; import org.eclipse.tractusx.digitalproductpass.services.DataTransferService; @@ -31,19 +27,20 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import org.mockito.Spy; import org.springframework.core.env.Environment; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.mock.env.MockEnvironment; -import utils.*; +import utils.FileUtil; +import utils.HttpUtil; +import utils.JsonUtil; +import utils.YamlUtil; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Map; -import java.util.UUID; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.*; diff --git a/dpp-backend/digitalproductpass/src/test/java/services/AuthenticationServiceTest.java b/dpp-backend/digitalproductpass/src/test/java/services/AuthenticationServiceTest.java index dcfcc0107..0d1d845e8 100644 --- a/dpp-backend/digitalproductpass/src/test/java/services/AuthenticationServiceTest.java +++ b/dpp-backend/digitalproductpass/src/test/java/services/AuthenticationServiceTest.java @@ -1,6 +1,5 @@ package services; -import com.fasterxml.jackson.databind.JsonNode; import jakarta.servlet.http.HttpServletRequest; import org.eclipse.tractusx.digitalproductpass.config.SecurityConfig; import org.eclipse.tractusx.digitalproductpass.exceptions.ServiceInitializationException; @@ -9,18 +8,19 @@ import org.eclipse.tractusx.digitalproductpass.services.AuthenticationService; import org.eclipse.tractusx.digitalproductpass.services.VaultService; import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.core.env.Environment; -import utils.*; +import utils.FileUtil; +import utils.HttpUtil; +import utils.JsonUtil; +import utils.YamlUtil; import java.nio.file.Paths; import java.util.Map; -import java.util.UUID; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.doReturn; diff --git a/dpp-backend/digitalproductpass/src/test/java/services/CatenaXServiceTest.java b/dpp-backend/digitalproductpass/src/test/java/services/CatenaXServiceTest.java index e4b13b352..d43ece639 100644 --- a/dpp-backend/digitalproductpass/src/test/java/services/CatenaXServiceTest.java +++ b/dpp-backend/digitalproductpass/src/test/java/services/CatenaXServiceTest.java @@ -28,7 +28,10 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.mock.env.MockEnvironment; -import utils.*; +import utils.FileUtil; +import utils.HttpUtil; +import utils.JsonUtil; +import utils.YamlUtil; import java.nio.file.Paths; import java.util.ArrayList; diff --git a/dpp-backend/digitalproductpass/src/test/java/services/DataPlaneServiceTest.java b/dpp-backend/digitalproductpass/src/test/java/services/DataPlaneServiceTest.java index 9ad8fa995..6a7938ac6 100644 --- a/dpp-backend/digitalproductpass/src/test/java/services/DataPlaneServiceTest.java +++ b/dpp-backend/digitalproductpass/src/test/java/services/DataPlaneServiceTest.java @@ -7,10 +7,8 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; -import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.springframework.core.env.Environment; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -23,7 +21,8 @@ import java.util.HashMap; import java.util.UUID; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.when; diff --git a/dpp-backend/digitalproductpass/src/test/java/services/IrsServiceTest.java b/dpp-backend/digitalproductpass/src/test/java/services/IrsServiceTest.java index 6d5521243..821d1838b 100644 --- a/dpp-backend/digitalproductpass/src/test/java/services/IrsServiceTest.java +++ b/dpp-backend/digitalproductpass/src/test/java/services/IrsServiceTest.java @@ -15,7 +15,10 @@ import org.eclipse.tractusx.digitalproductpass.services.AuthenticationService; import org.eclipse.tractusx.digitalproductpass.services.IrsService; import org.eclipse.tractusx.digitalproductpass.services.VaultService; -import org.junit.jupiter.api.*; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; @@ -29,10 +32,7 @@ import utils.JsonUtil; import utils.YamlUtil; -import java.nio.file.Path; import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.List; import java.util.Map; import java.util.UUID; diff --git a/dpp-backend/digitalproductpass/src/test/java/utils/CrypUtilTest.java b/dpp-backend/digitalproductpass/src/test/java/utils/CrypUtilTest.java index e43627b32..7e69e01c9 100644 --- a/dpp-backend/digitalproductpass/src/test/java/utils/CrypUtilTest.java +++ b/dpp-backend/digitalproductpass/src/test/java/utils/CrypUtilTest.java @@ -23,10 +23,10 @@ package utils; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; class CrypUtilTest { diff --git a/dpp-backend/digitalproductpass/src/test/java/utils/JsonUtilTest.java b/dpp-backend/digitalproductpass/src/test/java/utils/JsonUtilTest.java index e3d53c413..dc750163a 100644 --- a/dpp-backend/digitalproductpass/src/test/java/utils/JsonUtilTest.java +++ b/dpp-backend/digitalproductpass/src/test/java/utils/JsonUtilTest.java @@ -28,10 +28,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; -import org.sonarsource.scanner.api.internal.shaded.minimaljson.Json; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.stereotype.Component; import org.springframework.test.context.junit4.SpringRunner; import java.util.HashMap; diff --git a/dpp-backend/digitalproductpass/src/test/java/utils/LogUtilTest.java b/dpp-backend/digitalproductpass/src/test/java/utils/LogUtilTest.java index b444329fe..8783b6b2a 100644 --- a/dpp-backend/digitalproductpass/src/test/java/utils/LogUtilTest.java +++ b/dpp-backend/digitalproductpass/src/test/java/utils/LogUtilTest.java @@ -24,12 +24,8 @@ package utils; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.stereotype.Component; -import static org.junit.Assert.assertThat; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.fail; class LogUtilTest { @Test diff --git a/dpp-backend/digitalproductpass/src/test/java/utils/SystemUtilTest.java b/dpp-backend/digitalproductpass/src/test/java/utils/SystemUtilTest.java index 87e62b5f8..75c584622 100644 --- a/dpp-backend/digitalproductpass/src/test/java/utils/SystemUtilTest.java +++ b/dpp-backend/digitalproductpass/src/test/java/utils/SystemUtilTest.java @@ -24,10 +24,9 @@ package utils; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; class SystemUtilTest { diff --git a/dpp-backend/digitalproductpass/src/test/java/utils/YamlUtilTest.java b/dpp-backend/digitalproductpass/src/test/java/utils/YamlUtilTest.java index a6d64a24a..2676d9620 100644 --- a/dpp-backend/digitalproductpass/src/test/java/utils/YamlUtilTest.java +++ b/dpp-backend/digitalproductpass/src/test/java/utils/YamlUtilTest.java @@ -27,15 +27,9 @@ import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.AutoConfigureOrder; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.stereotype.Component; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringRunner; -import org.yaml.snakeyaml.Yaml; -import java.util.HashMap; import java.util.Map; import static org.junit.jupiter.api.Assertions.*; From 2ce9c4695599c6510f3f0a487be079684b1c542f Mon Sep 17 00:00:00 2001 From: Mathias Brunkow Moser Date: Mon, 8 Jan 2024 18:16:23 +0100 Subject: [PATCH 6/6] fix: fixed property get naming to map --- .../http/controllers/api/ContractController.java | 2 +- .../digitalproductpass/models/catenax/BpnDiscovery.java | 6 ++---- .../src/test/java/services/CatenaXServiceTest.java | 2 +- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/dpp-backend/digitalproductpass/src/main/java/org/eclipse/tractusx/digitalproductpass/http/controllers/api/ContractController.java b/dpp-backend/digitalproductpass/src/main/java/org/eclipse/tractusx/digitalproductpass/http/controllers/api/ContractController.java index 8adf6b3bd..4eb8855cd 100644 --- a/dpp-backend/digitalproductpass/src/main/java/org/eclipse/tractusx/digitalproductpass/http/controllers/api/ContractController.java +++ b/dpp-backend/digitalproductpass/src/main/java/org/eclipse/tractusx/digitalproductpass/http/controllers/api/ContractController.java @@ -148,7 +148,7 @@ public Response create(@Valid @RequestBody DiscoverySearch searchBody) { } List bpnList = new ArrayList<>(); for(BpnDiscovery bpnDiscovery : bpnDiscoveries){ - bpnList.addAll(bpnDiscovery.getBpnNumbers()); + bpnList.addAll(bpnDiscovery.mapBpnNumbers()); } if(bpnList.size() == 0){ response.message = "The asset was not found in the BPN Discovery!"; diff --git a/dpp-backend/digitalproductpass/src/main/java/org/eclipse/tractusx/digitalproductpass/models/catenax/BpnDiscovery.java b/dpp-backend/digitalproductpass/src/main/java/org/eclipse/tractusx/digitalproductpass/models/catenax/BpnDiscovery.java index 0aa6abc5c..5a8568b73 100644 --- a/dpp-backend/digitalproductpass/src/main/java/org/eclipse/tractusx/digitalproductpass/models/catenax/BpnDiscovery.java +++ b/dpp-backend/digitalproductpass/src/main/java/org/eclipse/tractusx/digitalproductpass/models/catenax/BpnDiscovery.java @@ -45,9 +45,6 @@ public class BpnDiscovery { @JsonProperty("bpns") List bpns; - @JsonProperty("bpnNumbers") - List bpnNumbers; - /** CONSTRUCTOR(S) **/ @SuppressWarnings("Unused") public BpnDiscovery(List bpns) { @@ -68,7 +65,8 @@ public void setBpns(List bpns) { } /** METHODS **/ - public List getBpnNumbers(){ + + public List mapBpnNumbers(){ return bpns.stream().map( BpnEndpoint::getValue ).collect(Collectors.toList()); diff --git a/dpp-backend/digitalproductpass/src/test/java/services/CatenaXServiceTest.java b/dpp-backend/digitalproductpass/src/test/java/services/CatenaXServiceTest.java index d43ece639..324bfe592 100644 --- a/dpp-backend/digitalproductpass/src/test/java/services/CatenaXServiceTest.java +++ b/dpp-backend/digitalproductpass/src/test/java/services/CatenaXServiceTest.java @@ -261,7 +261,7 @@ void getBpnDiscovery() { BpnDiscovery bpnDiscoveryEndpoint = (BpnDiscovery) jsonUtil.bindObject(bpnDiscoveryList.get(0), BpnDiscovery.class); assertEquals(1, bpnDiscoveryList.size()); - assertTrue(bpnDiscoveryEndpoint.getBpnNumbers().contains(bpn)); + assertTrue(bpnDiscoveryEndpoint.mapBpnNumbers().contains(bpn)); assertEquals(bpnResourceId, bpnDiscoveryEndpoint.getBpns().get(0).getResourceId()); }