From cd8ddc4905f7c424c689dd806ad24b3708031e0e Mon Sep 17 00:00:00 2001 From: --show-origin Date: Wed, 1 Nov 2023 10:36:10 -0700 Subject: [PATCH 01/19] refactor: moved request logic from controller to service --- .../ProductStockRequestApiController.java | 6 +- .../stock/controller/StockController.java | 154 ++---------------- .../ProductStockRequestApiService.java | 52 ++++++ .../ProductStockRequestApiServiceImpl.java | 109 +++++++++++-- 4 files changed, 164 insertions(+), 157 deletions(-) create mode 100644 backend/src/main/java/org/eclipse/tractusx/puris/backend/stock/logic/service/ProductStockRequestApiService.java diff --git a/backend/src/main/java/org/eclipse/tractusx/puris/backend/stock/controller/ProductStockRequestApiController.java b/backend/src/main/java/org/eclipse/tractusx/puris/backend/stock/controller/ProductStockRequestApiController.java index 65d03c4c..759bb380 100644 --- a/backend/src/main/java/org/eclipse/tractusx/puris/backend/stock/controller/ProductStockRequestApiController.java +++ b/backend/src/main/java/org/eclipse/tractusx/puris/backend/stock/controller/ProductStockRequestApiController.java @@ -31,13 +31,12 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import lombok.extern.slf4j.Slf4j; -import org.eclipse.tractusx.puris.backend.stock.domain.model.ProductStockRequest; import org.eclipse.tractusx.puris.backend.common.api.domain.model.datatype.DT_RequestStateEnum; import org.eclipse.tractusx.puris.backend.common.api.logic.dto.MessageHeaderDto; import org.eclipse.tractusx.puris.backend.common.api.logic.dto.SuccessfulRequestDto; +import org.eclipse.tractusx.puris.backend.stock.domain.model.ProductStockRequest; import org.eclipse.tractusx.puris.backend.stock.logic.service.ProductStockRequestApiServiceImpl; import org.eclipse.tractusx.puris.backend.stock.logic.service.ProductStockRequestService; -import org.eclipse.tractusx.puris.backend.common.edc.logic.service.EdcAdapterService; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatusCode; @@ -66,9 +65,6 @@ public class ProductStockRequestApiController { @Autowired ProductStockRequestApiServiceImpl requestApiService; - @Autowired - EdcAdapterService edcAdapterService; - @PostMapping("request") @Operation(summary = "This endpoint receives the product stock requests from a consumer.", requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody( diff --git a/backend/src/main/java/org/eclipse/tractusx/puris/backend/stock/controller/StockController.java b/backend/src/main/java/org/eclipse/tractusx/puris/backend/stock/controller/StockController.java index 562a1b97..8d7ede04 100644 --- a/backend/src/main/java/org/eclipse/tractusx/puris/backend/stock/controller/StockController.java +++ b/backend/src/main/java/org/eclipse/tractusx/puris/backend/stock/controller/StockController.java @@ -21,44 +21,37 @@ */ package org.eclipse.tractusx.puris.backend.stock.controller; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.squareup.okhttp.Response; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.ExampleObject; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import lombok.extern.slf4j.Slf4j; -import org.eclipse.tractusx.puris.backend.common.api.domain.model.MessageHeader; -import org.eclipse.tractusx.puris.backend.common.api.domain.model.datatype.DT_RequestStateEnum; -import org.eclipse.tractusx.puris.backend.common.api.domain.model.datatype.DT_UseCaseEnum; -import org.eclipse.tractusx.puris.backend.common.api.logic.service.VariablesService; -import org.eclipse.tractusx.puris.backend.common.edc.logic.service.EdcAdapterService; import org.eclipse.tractusx.puris.backend.masterdata.domain.model.Material; -import org.eclipse.tractusx.puris.backend.masterdata.domain.model.MaterialPartnerRelation; import org.eclipse.tractusx.puris.backend.masterdata.domain.model.Partner; import org.eclipse.tractusx.puris.backend.masterdata.logic.dto.PartnerDto; import org.eclipse.tractusx.puris.backend.masterdata.logic.service.MaterialPartnerRelationService; import org.eclipse.tractusx.puris.backend.masterdata.logic.service.MaterialService; import org.eclipse.tractusx.puris.backend.masterdata.logic.service.PartnerService; -import org.eclipse.tractusx.puris.backend.stock.domain.model.*; +import org.eclipse.tractusx.puris.backend.stock.domain.model.MaterialStock; +import org.eclipse.tractusx.puris.backend.stock.domain.model.PartnerProductStock; +import org.eclipse.tractusx.puris.backend.stock.domain.model.ProductStock; import org.eclipse.tractusx.puris.backend.stock.logic.dto.FrontendMaterialDto; import org.eclipse.tractusx.puris.backend.stock.logic.dto.MaterialStockDto; import org.eclipse.tractusx.puris.backend.stock.logic.dto.PartnerProductStockDto; import org.eclipse.tractusx.puris.backend.stock.logic.dto.ProductStockDto; import org.eclipse.tractusx.puris.backend.stock.logic.service.MaterialStockService; import org.eclipse.tractusx.puris.backend.stock.logic.service.PartnerProductStockService; -import org.eclipse.tractusx.puris.backend.stock.logic.service.ProductStockRequestService; +import org.eclipse.tractusx.puris.backend.stock.logic.service.ProductStockRequestApiService; import org.eclipse.tractusx.puris.backend.stock.logic.service.ProductStockService; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.*; import java.util.Date; import java.util.List; import java.util.Map; -import java.util.UUID; import java.util.stream.Collectors; /** @@ -70,15 +63,6 @@ @Slf4j public class StockController { - @Value("${edc.dataplane.public.port}") - private String dataPlanePort; - - @Value("${edc.controlplane.host}") - private String dataPlaneHost; - - @Value("${edc.applydataplaneworkaround}") - private boolean applyDataplaneWorkaround; - @Autowired private ProductStockService productStockService; @@ -88,6 +72,9 @@ public class StockController { @Autowired private PartnerProductStockService partnerProductStockService; + @Autowired + private ProductStockRequestApiService productStockRequestApiService; + @Autowired private MaterialService materialService; @@ -97,23 +84,9 @@ public class StockController { @Autowired private MaterialPartnerRelationService mprService; - @Autowired - private ProductStockRequestService productStockRequestService; - @Autowired private ModelMapper modelMapper; - @Autowired - private ObjectMapper objectMapper; - - @Autowired - private EdcAdapterService edcAdapterService; - - @Autowired - private VariablesService variablesService; - - - @CrossOrigin @GetMapping("materials") @ResponseBody @@ -155,11 +128,9 @@ public List getProducts() { @ResponseBody @Operation(description = "Returns a list of all product-stocks") public List getProductStocks() { - List allProductStocks = productStockService.findAll().stream() + return productStockService.findAll().stream() .map(this::convertToDto) .collect(Collectors.toList()); - - return allProductStocks; } @CrossOrigin @@ -178,9 +149,7 @@ public ProductStockDto createProductStocks(@RequestBody ProductStockDto productS } log.info("Created product-stock: " + createdProductStock); - ProductStockDto productStockToReturn = convertToDto(createdProductStock); - - return productStockToReturn; + return convertToDto(createdProductStock); } @CrossOrigin @@ -199,9 +168,7 @@ public ProductStockDto updateProductStocks(@RequestBody ProductStockDto productS existingProductStock = productStockService.update(existingProductStock); log.info("Updated product-stock: " + existingProductStock); - ProductStockDto productStockToReturn = convertToDto(existingProductStock); - - return productStockToReturn; + return convertToDto(existingProductStock); } private ProductStockDto convertToDto(ProductStock entity) { @@ -243,9 +210,7 @@ public MaterialStockDto createMaterialStocks(@RequestBody MaterialStockDto mater MaterialStock createdMaterialStock = materialStockService.create(materialStockToCreate); - MaterialStockDto materialStockToReturn = convertToDto(createdMaterialStock); - - return materialStockToReturn; + return convertToDto(createdMaterialStock); } @CrossOrigin @@ -264,9 +229,7 @@ public MaterialStockDto updateMaterialStocks(@RequestBody MaterialStockDto mater existingMaterialStock = materialStockService.update(existingMaterialStock); - MaterialStockDto productStockToReturn = convertToDto(existingMaterialStock); - - return productStockToReturn; + return convertToDto(existingMaterialStock); } private MaterialStockDto convertToDto(MaterialStock entity) { @@ -310,10 +273,9 @@ private PartnerProductStockDto convertToDto(PartnerProductStock entity) { @ResponseBody @Operation(description = "Returns a list of all Partners that are ordering the given material") public List getCustomerPartnersOrderingMaterial(@RequestParam String ownMaterialNumber) { - List allCustomerPartners = partnerService.findAllCustomerPartnersForMaterialId(ownMaterialNumber).stream() + return partnerService.findAllCustomerPartnersForMaterialId(ownMaterialNumber).stream() .map(this::convertToDto) .collect(Collectors.toList()); - return allCustomerPartners; } @CrossOrigin @@ -333,96 +295,12 @@ public List triggerPartnerProductStockUpdateForMaterial(@RequestPara for (Partner supplierPartner : allSupplierPartnerEntities) { - ProductStockRequest productStockRequest = new ProductStockRequest(); - - MaterialPartnerRelation materialPartnerRelation = mprService.find(materialEntity, supplierPartner); - - if (materialPartnerRelation == null) { - log.error("Missing material-partner-relation for " + materialEntity.getOwnMaterialNumber() - + " and " + supplierPartner.getBpnl()); - continue; - } - - ProductStockRequestForMaterial material = new ProductStockRequestForMaterial( - materialEntity.getOwnMaterialNumber(), - materialEntity.getMaterialNumberCx(), - materialPartnerRelation.getPartnerMaterialNumber() - ); - productStockRequest.getContent().getProductStock().add(material); - - String [] data = edcAdapterService.getContractForRequestApi(supplierPartner.getEdcUrl()); - if(data == null) { - log.error("failed to obtain request api from " + supplierPartner.getEdcUrl()); - continue; - } - String authKey = data[0]; - String authCode = data[1]; - String endpoint = data[2]; - if (applyDataplaneWorkaround) { - log.info("Applying Dataplane Address Workaround"); - endpoint = "http://" + dataPlaneHost + ":" + dataPlanePort + "/api/public"; - } - - String cid = data[3]; - MessageHeader messageHeader = new MessageHeader(); - UUID randomUuid = UUID.randomUUID(); - - // Avoid randomly choosing a UUID that was already used by this customer. - while (productStockRequestService.findRequestByHeaderUuid(randomUuid) != null) { - randomUuid = UUID.randomUUID(); - } - messageHeader.setRequestId(randomUuid); - messageHeader.setRespondAssetId(variablesService.getResponseApiAssetId()); - messageHeader.setContractAgreementId(cid); - messageHeader.setSender(variablesService.getOwnBpnl()); - messageHeader.setSenderEdc(variablesService.getOwnEdcIdsUrl()); - // set receiver per partner - messageHeader.setReceiver(supplierPartner.getBpnl()); - messageHeader.setUseCase(DT_UseCaseEnum.PURIS); - messageHeader.setCreationDate(new Date()); - - - productStockRequest.setHeader(messageHeader); - productStockRequest.setState(DT_RequestStateEnum.Working); - productStockRequest = productStockRequestService.createRequest(productStockRequest); - var test = productStockRequestService.findRequestByHeaderUuid(productStockRequest.getHeader().getRequestId()); - log.debug("Stored in Database " + (test != null) + " " + productStockRequest.getHeader().getRequestId()); - Response response = null; - try { - String requestBody = objectMapper.writeValueAsString(productStockRequest); - response = edcAdapterService.sendDataPullRequest(endpoint, authKey, authCode, requestBody); - log.debug(response.body().string()); - if(response.code() < 400) { - productStockRequest = productStockRequestService.updateState(productStockRequest, DT_RequestStateEnum.Requested); - log.debug("Sent request and received HTTP Status code " + response.code()); - log.debug("Setting request state to " + DT_RequestStateEnum.Requested); - productStockRequestService.updateState(productStockRequest, DT_RequestStateEnum.Requested); - } else { - log.warn("Received HTTP Status Code " + response.code() + " for request " + productStockRequest.getHeader().getRequestId() - + " from " + productStockRequest.getHeader().getReceiver()); - productStockRequest = productStockRequestService.updateState(productStockRequest, DT_RequestStateEnum.Error); - } - - } catch (Exception e) { - log.error("Failed to send data pull request to " + supplierPartner.getEdcUrl(), e); - productStockRequest = productStockRequestService.updateState(productStockRequest, DT_RequestStateEnum.Error); - } finally { - try { - if(response != null) { - response.body().close(); - } - } catch (Exception e) { - log.warn("Failed to close response body"); - } - } + productStockRequestApiService.request(materialEntity, supplierPartner); } - List allSupplierPartners = allSupplierPartnerEntities.stream() + return allSupplierPartnerEntities.stream() .map(this::convertToDto) .collect(Collectors.toList()); - - - return allSupplierPartners; } private PartnerDto convertToDto(Partner entity) { diff --git a/backend/src/main/java/org/eclipse/tractusx/puris/backend/stock/logic/service/ProductStockRequestApiService.java b/backend/src/main/java/org/eclipse/tractusx/puris/backend/stock/logic/service/ProductStockRequestApiService.java new file mode 100644 index 00000000..8b342822 --- /dev/null +++ b/backend/src/main/java/org/eclipse/tractusx/puris/backend/stock/logic/service/ProductStockRequestApiService.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2023 Volkswagen AG + * Copyright (c) 2023 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 governing permissions and limitations + * under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ +package org.eclipse.tractusx.puris.backend.stock.logic.service; + +import org.eclipse.tractusx.puris.backend.masterdata.domain.model.Material; +import org.eclipse.tractusx.puris.backend.masterdata.domain.model.Partner; +import org.eclipse.tractusx.puris.backend.stock.domain.model.ProductStockRequest; + +/** + * Interface provides the API capabilities to request ProductStock information and to handle requests. + */ +public interface ProductStockRequestApiService { + + /** + * This method should be called in a separate Thread. + * + * It will evaluate the given ProductStockRequest and check, whether this Partner is + * currently known as a customer for the given products. Then this method will assemble + * all necessary information from database, generate ProductStockSammDto's and then send + * them to the Partner via his product-stock-response-api. + * + *

Please note that this method currently does not support multple BPNS's/BPNA's per Partner.

+ * + * @param productStockRequest a ProductStockRequest you received from a Customer Partner + */ + void handleRequest(ProductStockRequest productStockRequest); + + /** + * requests an update for the stock of the material for the given supplierPartner + * + * @param material material to get the latest stock quantity for + * @param supplierPartner partner to get the update from + */ + void request(Material material, Partner supplierPartner); +} diff --git a/backend/src/main/java/org/eclipse/tractusx/puris/backend/stock/logic/service/ProductStockRequestApiServiceImpl.java b/backend/src/main/java/org/eclipse/tractusx/puris/backend/stock/logic/service/ProductStockRequestApiServiceImpl.java index c1f3a2ed..82b3dc0d 100644 --- a/backend/src/main/java/org/eclipse/tractusx/puris/backend/stock/logic/service/ProductStockRequestApiServiceImpl.java +++ b/backend/src/main/java/org/eclipse/tractusx/puris/backend/stock/logic/service/ProductStockRequestApiServiceImpl.java @@ -22,26 +22,25 @@ package org.eclipse.tractusx.puris.backend.stock.logic.service; import com.fasterxml.jackson.databind.ObjectMapper; +import com.squareup.okhttp.Response; import lombok.extern.slf4j.Slf4j; import org.eclipse.tractusx.puris.backend.common.api.domain.model.MessageHeader; -import org.eclipse.tractusx.puris.backend.stock.domain.model.ProductStockRequest; import org.eclipse.tractusx.puris.backend.common.api.domain.model.datatype.DT_RequestStateEnum; import org.eclipse.tractusx.puris.backend.common.api.domain.model.datatype.DT_UseCaseEnum; +import org.eclipse.tractusx.puris.backend.common.api.logic.service.VariablesService; import org.eclipse.tractusx.puris.backend.common.edc.logic.service.EdcAdapterService; import org.eclipse.tractusx.puris.backend.masterdata.domain.model.Material; +import org.eclipse.tractusx.puris.backend.masterdata.domain.model.MaterialPartnerRelation; import org.eclipse.tractusx.puris.backend.masterdata.domain.model.Partner; import org.eclipse.tractusx.puris.backend.masterdata.logic.service.MaterialPartnerRelationService; import org.eclipse.tractusx.puris.backend.masterdata.logic.service.MaterialService; import org.eclipse.tractusx.puris.backend.masterdata.logic.service.PartnerService; -import org.eclipse.tractusx.puris.backend.stock.domain.model.ProductStock; -import org.eclipse.tractusx.puris.backend.stock.domain.model.ProductStockRequestForMaterial; -import org.eclipse.tractusx.puris.backend.stock.domain.model.ProductStockResponse; +import org.eclipse.tractusx.puris.backend.stock.domain.model.*; import org.eclipse.tractusx.puris.backend.stock.logic.adapter.ProductStockSammMapper; import org.eclipse.tractusx.puris.backend.stock.logic.dto.samm.ProductStockSammDto; -import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; +import org.springframework.stereotype.Service; import java.util.*; import java.util.concurrent.ConcurrentHashMap; @@ -56,9 +55,9 @@ * {@link org.eclipse.tractusx.puris.backend.stock.domain.model.ProductStock} and return it * according to the API specification. */ -@Component +@Service @Slf4j -public class ProductStockRequestApiServiceImpl { +public class ProductStockRequestApiServiceImpl implements ProductStockRequestApiService{ @Autowired private ProductStockRequestService productStockRequestService; @@ -81,9 +80,6 @@ public class ProductStockRequestApiServiceImpl { @Autowired private EdcAdapterService edcAdapterService; - @Autowired - private ModelMapper modelMapper; - @Autowired private ObjectMapper objectMapper; @@ -102,7 +98,8 @@ public class ProductStockRequestApiServiceImpl { @Value("${edc.applydataplaneworkaround}") private boolean applyDataplaneWorkaround; - + @Autowired + private VariablesService variablesService; public static Predicate distinctByKey( Function keyExtractor) { @@ -214,7 +211,7 @@ public void handleRequest(ProductStockRequest productStockRequest) { if (productStocks.size() > 1) { List distinctProductStocks = productStocks.stream() - .filter(distinctByKey(p -> p.getLocationId())) + .filter(distinctByKey(Stock::getLocationId)) .collect(Collectors.toList()); if (distinctProductStocks.size() > 1) { log.warn(String.format("More than one site is not yet supported per " + @@ -225,7 +222,7 @@ public void handleRequest(ProductStockRequest productStockRequest) { } double quantity = productStocks.stream(). - mapToDouble(stock -> stock.getQuantity()).sum(); + mapToDouble(Stock::getQuantity).sum(); productStock.setQuantity(quantity); } @@ -281,4 +278,88 @@ public void handleRequest(ProductStockRequest productStockRequest) { } } + + public void request(Material material, Partner supplierPartner){ + ProductStockRequest productStockRequest = new ProductStockRequest(); + + MaterialPartnerRelation materialPartnerRelation = mprService.find(material, supplierPartner); + + if (materialPartnerRelation == null) { + log.error("Missing material-partner-relation for " + material.getOwnMaterialNumber() + + " and " + supplierPartner.getBpnl()); + return; + } + + ProductStockRequestForMaterial materialToRequest = new ProductStockRequestForMaterial( + material.getOwnMaterialNumber(), + material.getMaterialNumberCx(), + materialPartnerRelation.getPartnerMaterialNumber() + ); + productStockRequest.getContent().getProductStock().add(materialToRequest); + + String [] data = edcAdapterService.getContractForRequestApi(supplierPartner.getEdcUrl()); + if(data == null) { + log.error("failed to obtain request api from " + supplierPartner.getEdcUrl()); + return; + } + String authKey = data[0]; + String authCode = data[1]; + String endpoint = data[2]; + if (applyDataplaneWorkaround) { + log.info("Applying Dataplane Address Workaround"); + endpoint = "http://" + dataPlaneHost + ":" + dataPlanePort + "/api/public"; + } + + String cid = data[3]; + MessageHeader messageHeader = new MessageHeader(); + UUID randomUuid = UUID.randomUUID(); + + // Avoid randomly choosing a UUID that was already used by this customer. + while (productStockRequestService.findRequestByHeaderUuid(randomUuid) != null) { + randomUuid = UUID.randomUUID(); + } + messageHeader.setRequestId(randomUuid); + messageHeader.setRespondAssetId(variablesService.getResponseApiAssetId()); + messageHeader.setContractAgreementId(cid); + messageHeader.setSender(variablesService.getOwnBpnl()); + messageHeader.setSenderEdc(variablesService.getOwnEdcIdsUrl()); + // set receiver per partner + messageHeader.setReceiver(supplierPartner.getBpnl()); + messageHeader.setUseCase(DT_UseCaseEnum.PURIS); + messageHeader.setCreationDate(new Date()); + + productStockRequest.setHeader(messageHeader); + productStockRequest.setState(DT_RequestStateEnum.Working); + productStockRequest = productStockRequestService.createRequest(productStockRequest); + var test = productStockRequestService.findRequestByHeaderUuid(productStockRequest.getHeader().getRequestId()); + log.debug("Stored in Database " + (test != null) + " " + productStockRequest.getHeader().getRequestId()); + Response response = null; + try { + String requestBody = objectMapper.writeValueAsString(productStockRequest); + response = edcAdapterService.sendDataPullRequest(endpoint, authKey, authCode, requestBody); + log.debug(response.body().string()); + if(response.code() < 400) { + productStockRequest = productStockRequestService.updateState(productStockRequest, DT_RequestStateEnum.Requested); + log.debug("Sent request and received HTTP Status code " + response.code()); + log.debug("Setting request state to " + DT_RequestStateEnum.Requested); + productStockRequestService.updateState(productStockRequest, DT_RequestStateEnum.Requested); + } else { + log.warn("Received HTTP Status Code " + response.code() + " for request " + productStockRequest.getHeader().getRequestId() + + " from " + productStockRequest.getHeader().getReceiver()); + productStockRequest = productStockRequestService.updateState(productStockRequest, DT_RequestStateEnum.Error); + } + + } catch (Exception e) { + log.error("Failed to send data pull request to " + supplierPartner.getEdcUrl(), e); + productStockRequestService.updateState(productStockRequest, DT_RequestStateEnum.Error); + } finally { + try { + if(response != null) { + response.body().close(); + } + } catch (Exception e) { + log.warn("Failed to close response body"); + } + } + } } From 4a7b0f3ef00b49ec899388836ec8b7fc60188311 Mon Sep 17 00:00:00 2001 From: --show-origin Date: Wed, 1 Nov 2023 10:38:20 -0700 Subject: [PATCH 02/19] refactor: remove unused interfaces --- .../api/logic/service/RequestApiService.java | 43 ------------------- .../api/logic/service/ResponseApiService.java | 40 ----------------- 2 files changed, 83 deletions(-) delete mode 100644 backend/src/main/java/org/eclipse/tractusx/puris/backend/common/api/logic/service/RequestApiService.java delete mode 100644 backend/src/main/java/org/eclipse/tractusx/puris/backend/common/api/logic/service/ResponseApiService.java diff --git a/backend/src/main/java/org/eclipse/tractusx/puris/backend/common/api/logic/service/RequestApiService.java b/backend/src/main/java/org/eclipse/tractusx/puris/backend/common/api/logic/service/RequestApiService.java deleted file mode 100644 index af232d73..00000000 --- a/backend/src/main/java/org/eclipse/tractusx/puris/backend/common/api/logic/service/RequestApiService.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2023 Volkswagen AG - * Copyright (c) 2023 Fraunhofer-Gesellschaft zur Foerderung der angewandten Forschung e.V. (represented by Fraunhofer ISST) - * Copyright (c) 2023 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 governing permissions and limitations - * under the License. - * - * SPDX-License-Identifier: Apache-2.0 - */ -package org.eclipse.tractusx.puris.backend.common.api.logic.service; - -import org.eclipse.tractusx.puris.backend.common.api.domain.model.MessageContent; -import org.eclipse.tractusx.puris.backend.common.api.logic.dto.RequestDto; - -/** - * Service receives performs the tasks associated with the Request API. - */ -public interface RequestApiService { - - /** - * handle the received request and respond to it - *

- * Commonly this involves: - *

  • find the data requested in {@link MessageContent}
  • - *
  • find the Response Api at partner via {@link org.eclipse.tractusx.puris.backend.common.api.domain.model.MessageHeader}
  • - *
  • send the Response to the Response Api
  • - * - * @param requestDto request received - */ - public void handleRequest(RequestDto requestDto); - -} diff --git a/backend/src/main/java/org/eclipse/tractusx/puris/backend/common/api/logic/service/ResponseApiService.java b/backend/src/main/java/org/eclipse/tractusx/puris/backend/common/api/logic/service/ResponseApiService.java deleted file mode 100644 index e3b1929e..00000000 --- a/backend/src/main/java/org/eclipse/tractusx/puris/backend/common/api/logic/service/ResponseApiService.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2023 Volkswagen AG - * Copyright (c) 2023 Fraunhofer-Gesellschaft zur Foerderung der angewandten Forschung e.V. (represented by Fraunhofer ISST) - * Copyright (c) 2023 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 governing permissions and limitations - * under the License. - * - * SPDX-License-Identifier: Apache-2.0 - */ -package org.eclipse.tractusx.puris.backend.common.api.logic.service; - -import org.eclipse.tractusx.puris.backend.common.api.logic.dto.ResponseDto; - -/** - * Service receives performs the tasks associated with the Response API. - */ -public interface ResponseApiService { - - /** - * Consume the response - *

    - * Commonly this involves: - *

  • validate the data
  • - *
  • store the data
  • - * - * @param responseDto response to consume - */ - public void consumeResponse(ResponseDto responseDto); -} From 21e6851450e4aa3aa43135d9380dabcc5841e9c7 Mon Sep 17 00:00:00 2001 From: --show-origin Date: Wed, 1 Nov 2023 11:07:16 -0700 Subject: [PATCH 03/19] feat: added builder to Material --- .../puris/backend/masterdata/domain/model/Material.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/backend/src/main/java/org/eclipse/tractusx/puris/backend/masterdata/domain/model/Material.java b/backend/src/main/java/org/eclipse/tractusx/puris/backend/masterdata/domain/model/Material.java index 614e2d47..cecf869f 100644 --- a/backend/src/main/java/org/eclipse/tractusx/puris/backend/masterdata/domain/model/Material.java +++ b/backend/src/main/java/org/eclipse/tractusx/puris/backend/masterdata/domain/model/Material.java @@ -25,10 +25,7 @@ import jakarta.persistence.Id; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import lombok.ToString; +import lombok.*; import java.util.Objects; import java.util.Set; @@ -70,6 +67,8 @@ @Setter @ToString @NoArgsConstructor +@AllArgsConstructor +@Builder public class Material { /** From 84ba7157e25cae61b1f15448e484e7597fabc7a5 Mon Sep 17 00:00:00 2001 From: --show-origin Date: Wed, 1 Nov 2023 11:08:16 -0700 Subject: [PATCH 04/19] feat: added draft for StockControllerTest --- .../stock/controller/StockControllerTest.java | 170 ++++++++++++++++++ 1 file changed, 170 insertions(+) create mode 100644 backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java diff --git a/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java b/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java new file mode 100644 index 00000000..a362d4bf --- /dev/null +++ b/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java @@ -0,0 +1,170 @@ +package org.eclipse.tractusx.puris.backend.stock.controller; + +import org.eclipse.tractusx.puris.backend.masterdata.domain.model.Material; +import org.eclipse.tractusx.puris.backend.masterdata.logic.service.MaterialPartnerRelationService; +import org.eclipse.tractusx.puris.backend.masterdata.logic.service.MaterialService; +import org.eclipse.tractusx.puris.backend.masterdata.logic.service.PartnerService; +import org.eclipse.tractusx.puris.backend.stock.logic.dto.FrontendMaterialDto; +import org.eclipse.tractusx.puris.backend.stock.logic.service.MaterialStockService; +import org.eclipse.tractusx.puris.backend.stock.logic.service.PartnerProductStockService; +import org.eclipse.tractusx.puris.backend.stock.logic.service.ProductStockRequestApiService; +import org.eclipse.tractusx.puris.backend.stock.logic.service.ProductStockService; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.modelmapper.ModelMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +//@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@WebMvcTest(StockController.class) +class StockControllerTest { + +// @LocalServerPort +// private int port; + +// @Autowired +// private TestRestTemplate restTemplate; + + @Autowired + private MockMvc mockMvc; + + @MockBean + private MaterialService materialService; + + @MockBean + private ProductStockService productStockService; + + @MockBean + private MaterialStockService materialStockService; + + @MockBean + private PartnerProductStockService partnerProductStockService; + + @MockBean + private ProductStockRequestApiService productStockRequestApiService; + + @MockBean + private PartnerService partnerService; + + @MockBean + private MaterialPartnerRelationService mprService; + + @MockBean + private ModelMapper modelMapper; + + @InjectMocks + StockController underTest; + +// @BeforeEach +// void setUp() { +// } +// +// @AfterEach +// void tearDown() { +// } + + @Test + void getMaterials() throws Exception{ + + // given + Material material1 = Material.builder() + .ownMaterialNumber("MNR-4711") + .materialFlag(true) + .name("Test Material 1") + .materialNumberCx("urn:uuid:ccfffbba-cfa0-49c4-bc9c-4e13d7a4ac7a") + .build(); + Material material2 = Material.builder() + .ownMaterialNumber("MNR-4712") + .materialFlag(true) + .name("Test Material 2") + .build(); + List allMaterials = new ArrayList<>(); + allMaterials.add(material1); + allMaterials.add(material2); + when(materialService.findAllMaterials()).thenReturn(allMaterials); + + // when + // todo solve mocking in this case as @InjectMock seems not to work + // maybe mockito? + List returnedMaterials = underTest.getMaterials(); + + this.mockMvc.perform( + get("/materials") + ).andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)); + + // then + assertAll( + () -> assertNotNull(returnedMaterials), + () -> assertEquals(2, returnedMaterials.size()) + ); + + FrontendMaterialDto returnedMaterial = returnedMaterials.stream().filter( + frontendMaterialDto -> frontendMaterialDto.getOwnMaterialNumber().equals("MNR-4711") + ).findFirst().get(); + assertAll( + () -> assertEquals("MNR-4711", returnedMaterial.getOwnMaterialNumber()), + () -> assertEquals("Test Material 1", returnedMaterial.getDescription()) + ); + + + //this.mockMvc.perform(get("/materials")).andDo(print()).andExpect(status().isOk()) + // .andExpect(content().contentType().); + } +// +// @Test +// void getMaterialNumbers() { +// } +// +// @Test +// void getProducts() { +// } +// +// @Test +// void getProductStocks() { +// } +// +// @Test +// void createProductStocks() { +// } +// +// @Test +// void updateProductStocks() { +// } +// +// @Test +// void getMaterialStocks() { +// } +// +// @Test +// void createMaterialStocks() { +// } +// +// @Test +// void updateMaterialStocks() { +// } +// +// @Test +// void getPartnerProductStocks() { +// } +// +// @Test +// void getCustomerPartnersOrderingMaterial() { +// } +// +// @Test +// void triggerPartnerProductStockUpdateForMaterial() { +// } +} From 9deb2de029762ed9afecd40777ec8797c5687ed1 Mon Sep 17 00:00:00 2001 From: --show-origin Date: Tue, 14 Nov 2023 00:56:48 -0800 Subject: [PATCH 05/19] feat: move fully to webMvc --- .../stock/controller/StockControllerTest.java | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java b/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java index a362d4bf..f88a5f19 100644 --- a/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java +++ b/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java @@ -4,13 +4,11 @@ import org.eclipse.tractusx.puris.backend.masterdata.logic.service.MaterialPartnerRelationService; import org.eclipse.tractusx.puris.backend.masterdata.logic.service.MaterialService; import org.eclipse.tractusx.puris.backend.masterdata.logic.service.PartnerService; -import org.eclipse.tractusx.puris.backend.stock.logic.dto.FrontendMaterialDto; import org.eclipse.tractusx.puris.backend.stock.logic.service.MaterialStockService; import org.eclipse.tractusx.puris.backend.stock.logic.service.PartnerProductStockService; import org.eclipse.tractusx.puris.backend.stock.logic.service.ProductStockRequestApiService; import org.eclipse.tractusx.puris.backend.stock.logic.service.ProductStockService; import org.junit.jupiter.api.Test; -import org.mockito.InjectMocks; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; @@ -21,7 +19,6 @@ import java.util.ArrayList; import java.util.List; -import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; @@ -64,8 +61,9 @@ class StockControllerTest { @MockBean private ModelMapper modelMapper; - @InjectMocks - StockController underTest; + //@InjectMocks + //@MockBean + //StockController underTest; // @BeforeEach // void setUp() { @@ -98,26 +96,28 @@ void getMaterials() throws Exception{ // when // todo solve mocking in this case as @InjectMock seems not to work // maybe mockito? - List returnedMaterials = underTest.getMaterials(); + //List returnedMaterials = underTest.getMaterials(); + // 401 returned due to https://stackoverflow.com/questions/39554285/spring-test-returning-401-for-unsecured-urls + // problem: we need security this.mockMvc.perform( - get("/materials") + get("/catena/stockView/materials") ).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)); // then - assertAll( - () -> assertNotNull(returnedMaterials), - () -> assertEquals(2, returnedMaterials.size()) - ); - - FrontendMaterialDto returnedMaterial = returnedMaterials.stream().filter( - frontendMaterialDto -> frontendMaterialDto.getOwnMaterialNumber().equals("MNR-4711") - ).findFirst().get(); - assertAll( - () -> assertEquals("MNR-4711", returnedMaterial.getOwnMaterialNumber()), - () -> assertEquals("Test Material 1", returnedMaterial.getDescription()) - ); +// assertAll( +// () -> assertNotNull(returnedMaterials), +// () -> assertEquals(2, returnedMaterials.size()) +// ); +// +// FrontendMaterialDto returnedMaterial = returnedMaterials.stream().filter( +// frontendMaterialDto -> frontendMaterialDto.getOwnMaterialNumber().equals("MNR-4711") +// ).findFirst().get(); +// assertAll( +// () -> assertEquals("MNR-4711", returnedMaterial.getOwnMaterialNumber()), +// () -> assertEquals("Test Material 1", returnedMaterial.getDescription()) +// ); //this.mockMvc.perform(get("/materials")).andDo(print()).andExpect(status().isOk()) From de95f8c58e1aad8952adec03d08f05862de32a45 Mon Sep 17 00:00:00 2001 From: --show-origin Date: Wed, 15 Nov 2023 03:42:20 -0800 Subject: [PATCH 06/19] feat: understood that there is a problem with spring security --- .../backend/stock/controller/StockControllerTest.java | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java b/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java index f88a5f19..3265381c 100644 --- a/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java +++ b/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java @@ -25,7 +25,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; //@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@WebMvcTest(StockController.class) +@WebMvcTest(StockViewController.class) class StockControllerTest { // @LocalServerPort @@ -93,11 +93,6 @@ void getMaterials() throws Exception{ allMaterials.add(material2); when(materialService.findAllMaterials()).thenReturn(allMaterials); - // when - // todo solve mocking in this case as @InjectMock seems not to work - // maybe mockito? - //List returnedMaterials = underTest.getMaterials(); - // 401 returned due to https://stackoverflow.com/questions/39554285/spring-test-returning-401-for-unsecured-urls // problem: we need security this.mockMvc.perform( From 206d8af89b221ad9ea6ce930266022c0811e5682 Mon Sep 17 00:00:00 2001 From: --show-origin Date: Sun, 19 Nov 2023 11:46:49 -0800 Subject: [PATCH 07/19] feat: added ApiKeyTest - half working --- .../backend/common/security/ApiKeyTest.java | 49 +++++++++++++++++++ .../common/security/WithMockApiKey.java | 13 +++++ .../WithMockApiKeySecurityContextFactory.java | 18 +++++++ 3 files changed, 80 insertions(+) create mode 100644 backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java create mode 100644 backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/WithMockApiKey.java create mode 100644 backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/WithMockApiKeySecurityContextFactory.java diff --git a/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java new file mode 100644 index 00000000..46b2976f --- /dev/null +++ b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java @@ -0,0 +1,49 @@ +package org.eclipse.tractusx.puris.backend.common.security; + +import org.eclipse.tractusx.puris.backend.AssetCreatorCommandLineRunner; +import org.eclipse.tractusx.puris.backend.DataInjectionCommandLineRunner; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.web.servlet.MockMvc; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + + +@SpringBootTest +@AutoConfigureMockMvc +public class ApiKeyTest { + + @Autowired + private MockMvc mockMvc; + + @MockBean + private AssetCreatorCommandLineRunner assetCreatorCommandLineRunner; + + @MockBean + private DataInjectionCommandLineRunner dataInjectionCommandLineRunner; + + @Test + void stockViewShouldReturn403WithoutAuth() throws Exception { + this.mockMvc.perform( + get("/catena/stockView/materials")) + .andDo(print()) + .andExpect(status().is(403)); + } + + @Test + @WithMockApiKey + void stockViewShouldReturn200WithAuth() throws Exception { + this.mockMvc.perform( + get("/catena/stockView/materials") + .header("X-API-KEY", "test")) + //.andDo(print()) + .andExpect(status().is(200)); + // WTF?? + } + +} diff --git a/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/WithMockApiKey.java b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/WithMockApiKey.java new file mode 100644 index 00000000..227c3ebd --- /dev/null +++ b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/WithMockApiKey.java @@ -0,0 +1,13 @@ +package org.eclipse.tractusx.puris.backend.common.security; + +import org.springframework.security.test.context.support.WithSecurityContext; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +@Retention(RetentionPolicy.RUNTIME) +@WithSecurityContext(factory = WithMockApiKeySecurityContextFactory.class) +public @interface WithMockApiKey { + + String apiKey() default "test"; +} diff --git a/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/WithMockApiKeySecurityContextFactory.java b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/WithMockApiKeySecurityContextFactory.java new file mode 100644 index 00000000..43e1ca10 --- /dev/null +++ b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/WithMockApiKeySecurityContextFactory.java @@ -0,0 +1,18 @@ +package org.eclipse.tractusx.puris.backend.common.security; + +import org.eclipse.tractusx.puris.backend.common.security.domain.ApiKeyAuthentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.test.context.support.WithSecurityContextFactory; + +public class WithMockApiKeySecurityContextFactory implements WithSecurityContextFactory { + @Override + public SecurityContext createSecurityContext(WithMockApiKey annotation) { + SecurityContext context = SecurityContextHolder.createEmptyContext(); + + ApiKeyAuthentication auth = new ApiKeyAuthentication("test", true); + context.setAuthentication(auth); + + return context; + } +} From 83d99a5a61fce28de4118cde46a582b1c2fd31ea Mon Sep 17 00:00:00 2001 From: --show-origin Date: Mon, 20 Nov 2023 09:43:48 -0800 Subject: [PATCH 08/19] fix: removed context from mockMvc paths --- .../backend/common/security/ApiKeyTest.java | 20 +++++-------------- 1 file changed, 5 insertions(+), 15 deletions(-) diff --git a/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java index 46b2976f..57d63052 100644 --- a/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java +++ b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java @@ -1,12 +1,9 @@ package org.eclipse.tractusx.puris.backend.common.security; -import org.eclipse.tractusx.puris.backend.AssetCreatorCommandLineRunner; -import org.eclipse.tractusx.puris.backend.DataInjectionCommandLineRunner; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -21,29 +18,22 @@ public class ApiKeyTest { @Autowired private MockMvc mockMvc; - @MockBean - private AssetCreatorCommandLineRunner assetCreatorCommandLineRunner; - - @MockBean - private DataInjectionCommandLineRunner dataInjectionCommandLineRunner; - @Test void stockViewShouldReturn403WithoutAuth() throws Exception { this.mockMvc.perform( - get("/catena/stockView/materials")) + get("/stockView/materials")) .andDo(print()) .andExpect(status().is(403)); } @Test - @WithMockApiKey +// @WithMockApiKey // not yet working void stockViewShouldReturn200WithAuth() throws Exception { this.mockMvc.perform( - get("/catena/stockView/materials") - .header("X-API-KEY", "test")) - //.andDo(print()) + get("/stockView/materials") + .header("X-API-KEY", "test") + ) .andExpect(status().is(200)); - // WTF?? } } From 220763839e26428fb1a150870036d85f7dd3cde6 Mon Sep 17 00:00:00 2001 From: --show-origin Date: Mon, 20 Nov 2023 10:15:07 -0800 Subject: [PATCH 09/19] fix: got security included material service working --- .../stock/controller/StockControllerTest.java | 79 ++++++++++--------- 1 file changed, 40 insertions(+), 39 deletions(-) diff --git a/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java b/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java index 3265381c..50ed7c99 100644 --- a/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java +++ b/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java @@ -1,9 +1,14 @@ package org.eclipse.tractusx.puris.backend.stock.controller; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.eclipse.tractusx.puris.backend.common.security.SecurityConfig; +import org.eclipse.tractusx.puris.backend.common.security.logic.ApiKeyAuthenticationProvider; import org.eclipse.tractusx.puris.backend.masterdata.domain.model.Material; import org.eclipse.tractusx.puris.backend.masterdata.logic.service.MaterialPartnerRelationService; import org.eclipse.tractusx.puris.backend.masterdata.logic.service.MaterialService; import org.eclipse.tractusx.puris.backend.masterdata.logic.service.PartnerService; +import org.eclipse.tractusx.puris.backend.stock.logic.dto.FrontendMaterialDto; import org.eclipse.tractusx.puris.backend.stock.logic.service.MaterialStockService; import org.eclipse.tractusx.puris.backend.stock.logic.service.PartnerProductStockService; import org.eclipse.tractusx.puris.backend.stock.logic.service.ProductStockRequestApiService; @@ -13,27 +18,24 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import java.util.ArrayList; import java.util.List; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -//@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @WebMvcTest(StockViewController.class) +@Import({ SecurityConfig.class, ApiKeyAuthenticationProvider.class }) class StockControllerTest { -// @LocalServerPort -// private int port; - -// @Autowired -// private TestRestTemplate restTemplate; - @Autowired private MockMvc mockMvc; @@ -61,17 +63,6 @@ class StockControllerTest { @MockBean private ModelMapper modelMapper; - //@InjectMocks - //@MockBean - //StockController underTest; - -// @BeforeEach -// void setUp() { -// } -// -// @AfterEach -// void tearDown() { -// } @Test void getMaterials() throws Exception{ @@ -96,27 +87,37 @@ void getMaterials() throws Exception{ // 401 returned due to https://stackoverflow.com/questions/39554285/spring-test-returning-401-for-unsecured-urls // problem: we need security this.mockMvc.perform( - get("/catena/stockView/materials") - ).andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)); - - // then -// assertAll( -// () -> assertNotNull(returnedMaterials), -// () -> assertEquals(2, returnedMaterials.size()) -// ); -// -// FrontendMaterialDto returnedMaterial = returnedMaterials.stream().filter( -// frontendMaterialDto -> frontendMaterialDto.getOwnMaterialNumber().equals("MNR-4711") -// ).findFirst().get(); -// assertAll( -// () -> assertEquals("MNR-4711", returnedMaterial.getOwnMaterialNumber()), -// () -> assertEquals("Test Material 1", returnedMaterial.getDescription()) -// ); - - - //this.mockMvc.perform(get("/materials")).andDo(print()).andExpect(status().isOk()) - // .andExpect(content().contentType().); + get("/stockView/materials") + .header("X-API-KEY", "test") + ) + .andDo(print()) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andDo(result -> { + String jsonResponse = result.getResponse().getContentAsString(); + ObjectMapper objectMapper = new ObjectMapper(); + + List returnedMaterials = objectMapper.readValue(jsonResponse, new TypeReference<>() { + }); + + assertAll( + () -> assertNotNull(returnedMaterials), + () -> assertEquals(2, returnedMaterials.size()) + ); + + assertAll( + () -> assertNotNull(returnedMaterials), + () -> assertEquals(2, returnedMaterials.size()) + ); + + FrontendMaterialDto returnedMaterial = returnedMaterials.stream().filter( + frontendMaterialDto -> frontendMaterialDto.getOwnMaterialNumber().equals("MNR-4711") + ).findFirst().get(); + assertAll( + () -> assertEquals("MNR-4711", returnedMaterial.getOwnMaterialNumber()), + () -> assertEquals("Test Material 1", returnedMaterial.getDescription()) + ); + }); } // // @Test From 5725fcbf882f23f3ba908c3e0d7b5f4be5fcba96 Mon Sep 17 00:00:00 2001 From: --show-origin Date: Mon, 20 Nov 2023 22:31:43 -0800 Subject: [PATCH 10/19] fix: fixed WithMockApiKey annotation for testing --- .../backend/common/security/ApiKeyTest.java | 17 +++++++ .../WithMockApiKeySecurityContextFactory.java | 3 +- .../stock/controller/StockControllerTest.java | 51 ++----------------- 3 files changed, 22 insertions(+), 49 deletions(-) diff --git a/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java index 57d63052..05d42f74 100644 --- a/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java +++ b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java @@ -35,5 +35,22 @@ void stockViewShouldReturn200WithAuth() throws Exception { ) .andExpect(status().is(200)); } + @Test + @WithMockApiKey(apiKey = "test2") + void stockViewShouldReturn403WithWrongAuthBasedOnMockKeyAnnotation() throws Exception { + this.mockMvc.perform( + get("/stockView/materials") + ) + .andExpect(status().is(200)); + } + + @Test + @WithMockApiKey + void stockViewShouldReturn200WithWrongAuthBasedOnDefaultMockKeyAnnotation() throws Exception { + this.mockMvc.perform( + get("/stockView/materials") + ) + .andExpect(status().is(200)); + } } diff --git a/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/WithMockApiKeySecurityContextFactory.java b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/WithMockApiKeySecurityContextFactory.java index 43e1ca10..69979aea 100644 --- a/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/WithMockApiKeySecurityContextFactory.java +++ b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/WithMockApiKeySecurityContextFactory.java @@ -6,11 +6,12 @@ import org.springframework.security.test.context.support.WithSecurityContextFactory; public class WithMockApiKeySecurityContextFactory implements WithSecurityContextFactory { + @Override public SecurityContext createSecurityContext(WithMockApiKey annotation) { SecurityContext context = SecurityContextHolder.createEmptyContext(); - ApiKeyAuthentication auth = new ApiKeyAuthentication("test", true); + ApiKeyAuthentication auth = new ApiKeyAuthentication(annotation.apiKey(), true); context.setAuthentication(auth); return context; diff --git a/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java b/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java index 50ed7c99..95c26017 100644 --- a/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java +++ b/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java @@ -3,6 +3,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import org.eclipse.tractusx.puris.backend.common.security.SecurityConfig; +import org.eclipse.tractusx.puris.backend.common.security.WithMockApiKey; import org.eclipse.tractusx.puris.backend.common.security.logic.ApiKeyAuthenticationProvider; import org.eclipse.tractusx.puris.backend.masterdata.domain.model.Material; import org.eclipse.tractusx.puris.backend.masterdata.logic.service.MaterialPartnerRelationService; @@ -63,8 +64,8 @@ class StockControllerTest { @MockBean private ModelMapper modelMapper; - @Test + @WithMockApiKey void getMaterials() throws Exception{ // given @@ -84,11 +85,8 @@ void getMaterials() throws Exception{ allMaterials.add(material2); when(materialService.findAllMaterials()).thenReturn(allMaterials); - // 401 returned due to https://stackoverflow.com/questions/39554285/spring-test-returning-401-for-unsecured-urls - // problem: we need security this.mockMvc.perform( get("/stockView/materials") - .header("X-API-KEY", "test") ) .andDo(print()) .andExpect(status().isOk()) @@ -119,48 +117,5 @@ void getMaterials() throws Exception{ ); }); } -// -// @Test -// void getMaterialNumbers() { -// } -// -// @Test -// void getProducts() { -// } -// -// @Test -// void getProductStocks() { -// } -// -// @Test -// void createProductStocks() { -// } -// -// @Test -// void updateProductStocks() { -// } -// -// @Test -// void getMaterialStocks() { -// } -// -// @Test -// void createMaterialStocks() { -// } -// -// @Test -// void updateMaterialStocks() { -// } -// -// @Test -// void getPartnerProductStocks() { -// } -// -// @Test -// void getCustomerPartnersOrderingMaterial() { -// } -// -// @Test -// void triggerPartnerProductStockUpdateForMaterial() { -// } + } From 4c5ee1346a7110320fc50256000f95ce9321042a Mon Sep 17 00:00:00 2001 From: --show-origin Date: Mon, 20 Nov 2023 22:33:11 -0800 Subject: [PATCH 11/19] chore: added license header --- .../backend/common/security/ApiKeyTest.java | 19 +++++++++++++++++++ .../common/security/WithMockApiKey.java | 19 +++++++++++++++++++ .../WithMockApiKeySecurityContextFactory.java | 19 +++++++++++++++++++ .../stock/controller/StockControllerTest.java | 19 +++++++++++++++++++ 4 files changed, 76 insertions(+) diff --git a/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java index 05d42f74..ed3a7e88 100644 --- a/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java +++ b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java @@ -1,3 +1,22 @@ +/* + * Copyright (c) 2023 Volkswagen AG + * Copyright (c) 2023 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 governing permissions and limitations + * under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ package org.eclipse.tractusx.puris.backend.common.security; import org.junit.jupiter.api.Test; diff --git a/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/WithMockApiKey.java b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/WithMockApiKey.java index 227c3ebd..aba8dc0a 100644 --- a/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/WithMockApiKey.java +++ b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/WithMockApiKey.java @@ -1,3 +1,22 @@ +/* + * Copyright (c) 2023 Volkswagen AG + * Copyright (c) 2023 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 governing permissions and limitations + * under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ package org.eclipse.tractusx.puris.backend.common.security; import org.springframework.security.test.context.support.WithSecurityContext; diff --git a/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/WithMockApiKeySecurityContextFactory.java b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/WithMockApiKeySecurityContextFactory.java index 69979aea..449ce1e3 100644 --- a/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/WithMockApiKeySecurityContextFactory.java +++ b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/WithMockApiKeySecurityContextFactory.java @@ -1,3 +1,22 @@ +/* + * Copyright (c) 2023 Volkswagen AG + * Copyright (c) 2023 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 governing permissions and limitations + * under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ package org.eclipse.tractusx.puris.backend.common.security; import org.eclipse.tractusx.puris.backend.common.security.domain.ApiKeyAuthentication; diff --git a/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java b/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java index 95c26017..e13aefb0 100644 --- a/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java +++ b/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java @@ -1,3 +1,22 @@ +/* + * Copyright (c) 2023 Volkswagen AG + * Copyright (c) 2023 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 governing permissions and limitations + * under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ package org.eclipse.tractusx.puris.backend.stock.controller; import com.fasterxml.jackson.core.type.TypeReference; From a326bfd0eaa60eff56f98477cb0f2c7148bc5b65 Mon Sep 17 00:00:00 2001 From: --show-origin Date: Mon, 20 Nov 2023 22:34:32 -0800 Subject: [PATCH 12/19] refactor: moved annotation to subpackage --- .../tractusx/puris/backend/common/security/ApiKeyTest.java | 1 + .../common/security/{ => annotation}/WithMockApiKey.java | 2 +- .../{ => annotation}/WithMockApiKeySecurityContextFactory.java | 2 +- .../puris/backend/stock/controller/StockControllerTest.java | 2 +- 4 files changed, 4 insertions(+), 3 deletions(-) rename backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/{ => annotation}/WithMockApiKey.java (94%) rename backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/{ => annotation}/WithMockApiKeySecurityContextFactory.java (95%) diff --git a/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java index ed3a7e88..f6601829 100644 --- a/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java +++ b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java @@ -19,6 +19,7 @@ */ package org.eclipse.tractusx.puris.backend.common.security; +import org.eclipse.tractusx.puris.backend.common.security.annotation.WithMockApiKey; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; diff --git a/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/WithMockApiKey.java b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/annotation/WithMockApiKey.java similarity index 94% rename from backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/WithMockApiKey.java rename to backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/annotation/WithMockApiKey.java index aba8dc0a..43d17f94 100644 --- a/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/WithMockApiKey.java +++ b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/annotation/WithMockApiKey.java @@ -17,7 +17,7 @@ * * SPDX-License-Identifier: Apache-2.0 */ -package org.eclipse.tractusx.puris.backend.common.security; +package org.eclipse.tractusx.puris.backend.common.security.annotation; import org.springframework.security.test.context.support.WithSecurityContext; diff --git a/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/WithMockApiKeySecurityContextFactory.java b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/annotation/WithMockApiKeySecurityContextFactory.java similarity index 95% rename from backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/WithMockApiKeySecurityContextFactory.java rename to backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/annotation/WithMockApiKeySecurityContextFactory.java index 449ce1e3..0414b27b 100644 --- a/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/WithMockApiKeySecurityContextFactory.java +++ b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/annotation/WithMockApiKeySecurityContextFactory.java @@ -17,7 +17,7 @@ * * SPDX-License-Identifier: Apache-2.0 */ -package org.eclipse.tractusx.puris.backend.common.security; +package org.eclipse.tractusx.puris.backend.common.security.annotation; import org.eclipse.tractusx.puris.backend.common.security.domain.ApiKeyAuthentication; import org.springframework.security.core.context.SecurityContext; diff --git a/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java b/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java index e13aefb0..0650bcfd 100644 --- a/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java +++ b/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java @@ -22,7 +22,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import org.eclipse.tractusx.puris.backend.common.security.SecurityConfig; -import org.eclipse.tractusx.puris.backend.common.security.WithMockApiKey; +import org.eclipse.tractusx.puris.backend.common.security.annotation.WithMockApiKey; import org.eclipse.tractusx.puris.backend.common.security.logic.ApiKeyAuthenticationProvider; import org.eclipse.tractusx.puris.backend.masterdata.domain.model.Material; import org.eclipse.tractusx.puris.backend.masterdata.logic.service.MaterialPartnerRelationService; From 4a3f05c1d52518bbe9580d0478db35113cc53a4e Mon Sep 17 00:00:00 2001 From: --show-origin Date: Mon, 20 Nov 2023 22:35:18 -0800 Subject: [PATCH 13/19] chore: removed comment --- .../tractusx/puris/backend/common/security/ApiKeyTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java index f6601829..f3c443f2 100644 --- a/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java +++ b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java @@ -47,7 +47,6 @@ void stockViewShouldReturn403WithoutAuth() throws Exception { } @Test -// @WithMockApiKey // not yet working void stockViewShouldReturn200WithAuth() throws Exception { this.mockMvc.perform( get("/stockView/materials") @@ -55,6 +54,7 @@ void stockViewShouldReturn200WithAuth() throws Exception { ) .andExpect(status().is(200)); } + @Test @WithMockApiKey(apiKey = "test2") void stockViewShouldReturn403WithWrongAuthBasedOnMockKeyAnnotation() throws Exception { From a8e3403455c7172cf524336411031b00960b0213 Mon Sep 17 00:00:00 2001 From: --show-origin Date: Mon, 20 Nov 2023 22:35:48 -0800 Subject: [PATCH 14/19] chore: added blank line --- .../tractusx/puris/backend/common/security/ApiKeyTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java index f3c443f2..e4ae8e8f 100644 --- a/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java +++ b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java @@ -54,7 +54,7 @@ void stockViewShouldReturn200WithAuth() throws Exception { ) .andExpect(status().is(200)); } - + @Test @WithMockApiKey(apiKey = "test2") void stockViewShouldReturn403WithWrongAuthBasedOnMockKeyAnnotation() throws Exception { From fc0e00be1a4121fd10afc5b7e1096bb9f5d82780 Mon Sep 17 00:00:00 2001 From: --show-origin Date: Mon, 20 Nov 2023 22:36:37 -0800 Subject: [PATCH 15/19] refactor: renamed controller test --- .../{StockControllerTest.java => StockViewControllerTest.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/{StockControllerTest.java => StockViewControllerTest.java} (99%) diff --git a/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java b/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockViewControllerTest.java similarity index 99% rename from backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java rename to backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockViewControllerTest.java index 0650bcfd..d88a3a0d 100644 --- a/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockControllerTest.java +++ b/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockViewControllerTest.java @@ -54,7 +54,7 @@ @WebMvcTest(StockViewController.class) @Import({ SecurityConfig.class, ApiKeyAuthenticationProvider.class }) -class StockControllerTest { +class StockViewControllerTest { @Autowired private MockMvc mockMvc; From 65d494837c1ea0c66b1896eb3556f10fb5be0ce8 Mon Sep 17 00:00:00 2001 From: --show-origin Date: Mon, 20 Nov 2023 22:45:06 -0800 Subject: [PATCH 16/19] fix: included a check for value in Mock Annotation --- .../puris/backend/common/security/ApiKeyTest.java | 10 +++++----- .../WithMockApiKeySecurityContextFactory.java | 13 +++++++++++-- .../stock/controller/StockViewControllerTest.java | 2 +- 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java index e4ae8e8f..1cb4e878 100644 --- a/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java +++ b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/ApiKeyTest.java @@ -39,7 +39,7 @@ public class ApiKeyTest { private MockMvc mockMvc; @Test - void stockViewShouldReturn403WithoutAuth() throws Exception { + void StockViewController_MaterialsRequestWithoutAuthHeader_ShouldReturn403() throws Exception { this.mockMvc.perform( get("/stockView/materials")) .andDo(print()) @@ -47,7 +47,7 @@ void stockViewShouldReturn403WithoutAuth() throws Exception { } @Test - void stockViewShouldReturn200WithAuth() throws Exception { + void StockViewController_MaterialsRequestWithAuthHeader_ShouldReturn200() throws Exception { this.mockMvc.perform( get("/stockView/materials") .header("X-API-KEY", "test") @@ -57,16 +57,16 @@ void stockViewShouldReturn200WithAuth() throws Exception { @Test @WithMockApiKey(apiKey = "test2") - void stockViewShouldReturn403WithWrongAuthBasedOnMockKeyAnnotation() throws Exception { + void StockViewController_MaterialsRequestWithWrongAnnotationAuth_ShouldReturn403() throws Exception { this.mockMvc.perform( get("/stockView/materials") ) - .andExpect(status().is(200)); + .andExpect(status().is(403)); } @Test @WithMockApiKey - void stockViewShouldReturn200WithWrongAuthBasedOnDefaultMockKeyAnnotation() throws Exception { + void StockViewController_MaterialsRequestWithCorrectAnnotationAuth_ShouldReturn200() throws Exception { this.mockMvc.perform( get("/stockView/materials") ) diff --git a/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/annotation/WithMockApiKeySecurityContextFactory.java b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/annotation/WithMockApiKeySecurityContextFactory.java index 0414b27b..be141e56 100644 --- a/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/annotation/WithMockApiKeySecurityContextFactory.java +++ b/backend/src/test/java/org/eclipse/tractusx/puris/backend/common/security/annotation/WithMockApiKeySecurityContextFactory.java @@ -20,18 +20,27 @@ package org.eclipse.tractusx.puris.backend.common.security.annotation; import org.eclipse.tractusx.puris.backend.common.security.domain.ApiKeyAuthentication; +import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.test.context.support.WithSecurityContextFactory; public class WithMockApiKeySecurityContextFactory implements WithSecurityContextFactory { + @Value("${puris.api.key}") + String apiKeyConfig; + @Override public SecurityContext createSecurityContext(WithMockApiKey annotation) { SecurityContext context = SecurityContextHolder.createEmptyContext(); - ApiKeyAuthentication auth = new ApiKeyAuthentication(annotation.apiKey(), true); - context.setAuthentication(auth); + if (this.apiKeyConfig.equals((annotation.apiKey()))){ + ApiKeyAuthentication auth = new ApiKeyAuthentication(annotation.apiKey(), true); + context.setAuthentication(auth); + } else { + ApiKeyAuthentication auth = new ApiKeyAuthentication(annotation.apiKey(), false); + context.setAuthentication(auth); + } return context; } diff --git a/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockViewControllerTest.java b/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockViewControllerTest.java index d88a3a0d..1e95e9e6 100644 --- a/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockViewControllerTest.java +++ b/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockViewControllerTest.java @@ -85,7 +85,7 @@ class StockViewControllerTest { @Test @WithMockApiKey - void getMaterials() throws Exception{ + void getMaterials_ReturnsListOfMaterials() throws Exception{ // given Material material1 = Material.builder() From c2b85e2d5c426a4e7755d6b1d9591a333dc111c5 Mon Sep 17 00:00:00 2001 From: --show-origin Date: Mon, 20 Nov 2023 22:47:00 -0800 Subject: [PATCH 17/19] refactor: rename test --- .../puris/backend/stock/controller/StockViewControllerTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockViewControllerTest.java b/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockViewControllerTest.java index 1e95e9e6..5ff4fc9f 100644 --- a/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockViewControllerTest.java +++ b/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/controller/StockViewControllerTest.java @@ -85,7 +85,7 @@ class StockViewControllerTest { @Test @WithMockApiKey - void getMaterials_ReturnsListOfMaterials() throws Exception{ + void getMaterials_GivenTwoMaterials_ReturnsListOfMaterials() throws Exception{ // given Material material1 = Material.builder() From 6ff6e4eab5d78389f9a167e387f3a318b0d32da8 Mon Sep 17 00:00:00 2001 From: --show-origin Date: Mon, 20 Nov 2023 23:03:44 -0800 Subject: [PATCH 18/19] feat: added test example for MaterialService --- .../masterdata/logic/MaterialServiceTest.java | 83 +++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/masterdata/logic/MaterialServiceTest.java diff --git a/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/masterdata/logic/MaterialServiceTest.java b/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/masterdata/logic/MaterialServiceTest.java new file mode 100644 index 00000000..a8944774 --- /dev/null +++ b/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/masterdata/logic/MaterialServiceTest.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2023 Volkswagen AG + * Copyright (c) 2023 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 governing permissions and limitations + * under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ +package org.eclipse.tractusx.puris.backend.stock.masterdata.logic; + +import org.eclipse.tractusx.puris.backend.masterdata.domain.model.Material; +import org.eclipse.tractusx.puris.backend.masterdata.domain.repository.MaterialRepository; +import org.eclipse.tractusx.puris.backend.masterdata.logic.service.MaterialServiceImpl; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import java.util.HashSet; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +public class MaterialServiceTest { + + @Mock + private MaterialRepository materialRepository; + + @InjectMocks + private MaterialServiceImpl materialService; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + void create_WhenMaterialDoesNotExist_ReturnsCreatedMaterial() { + // Given + Material material = new Material(true, false, "MNR-123", "uuid-value", "Test Material", new HashSet<>()); + + // When + when(materialRepository.findById(material.getOwnMaterialNumber())).thenReturn(Optional.empty()); + when(materialRepository.save(material)).thenReturn(material); + + // Then + Material createdMaterial = materialService.create(material); + + assertNotNull(createdMaterial); + assertEquals(material, createdMaterial); + verify(materialRepository, times(1)).findById(material.getOwnMaterialNumber()); + verify(materialRepository, times(1)).save(material); + } + + @Test + void create_WhenMaterialExists_ReturnsNull() { + // Given + Material material = new Material(true, false, "MNR-123", "uuid-value", "Test Material", new HashSet<>()); + + // When + when(materialRepository.findById(material.getOwnMaterialNumber())).thenReturn(Optional.of(material)); + + // Then + Material createdMaterial = materialService.create(material); + + assertNull(createdMaterial); + verify(materialRepository, times(1)).findById(material.getOwnMaterialNumber()); + verify(materialRepository, never()).save(material); + } +} From 2ecd9b8a489eef03821c997fb40fddfbf31ddfee Mon Sep 17 00:00:00 2001 From: --show-origin Date: Mon, 20 Nov 2023 23:13:27 -0800 Subject: [PATCH 19/19] feat: added test example for MaterialRepository --- .../domain/MaterialRepositoryTest.java | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/masterdata/domain/MaterialRepositoryTest.java diff --git a/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/masterdata/domain/MaterialRepositoryTest.java b/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/masterdata/domain/MaterialRepositoryTest.java new file mode 100644 index 00000000..412c926a --- /dev/null +++ b/backend/src/test/java/org/eclipse/tractusx/puris/backend/stock/masterdata/domain/MaterialRepositoryTest.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2023 Volkswagen AG + * Copyright (c) 2023 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 governing permissions and limitations + * under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ +package org.eclipse.tractusx.puris.backend.stock.masterdata.domain; + +import org.eclipse.tractusx.puris.backend.masterdata.domain.model.Material; +import org.eclipse.tractusx.puris.backend.masterdata.domain.repository.MaterialRepository; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; + +import java.util.HashSet; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +@DataJpaTest +public class MaterialRepositoryTest { + + @Autowired + private MaterialRepository materialRepository; + + @Test + void findAllByMaterialFlagTrue_ReturnsListOfMaterials() { + // Given + Material material1 = new Material(true, false, "MNR-123", "uuid-value", "Test Material 1", new HashSet<>()); + + Material material2 = new Material(true, false, "MNR-234", "uuid-value-2", "Test Material 2", new HashSet<>()); + + // would be more realistic with relationship, but didn't add it here as we just want to test the MaterialRepo + Material product = new Material(false, true, "MNR-456", "uuid-value-2", "Test Product 1", new HashSet<>()); + + materialRepository.save(material1); + materialRepository.save(material2); + materialRepository.save(product); + + // When + List materials = materialRepository.findAllByMaterialFlagTrue(); + + // Then + assertNotNull(materials); + assertEquals(2, materials.size()); + assertTrue(materials.contains(material1)); + assertTrue(materials.contains(material2)); + } +}