From e3b0705928c449dac0de35e9a490d43da882f5c1 Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Fri, 17 Jan 2025 13:28:53 +0100 Subject: [PATCH 01/35] unittests items 2 nieuwe functies toegevoegd. testgetrow, testgetrownotexist. --- CargoHub.sln | 20 ++--- Tests/Test_locations.py | 70 +++++++++------ Tests/Test_orders.py | 66 +++++++++----- Tests/Test_shipments.py | 62 +++++++++----- UnitTest/Test_Items.cs | 186 ++++++++++++++++++++++++---------------- 5 files changed, 249 insertions(+), 155 deletions(-) diff --git a/CargoHub.sln b/CargoHub.sln index f5efc45..e04dc92 100644 --- a/CargoHub.sln +++ b/CargoHub.sln @@ -3,9 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.31903.59 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CargoHub", "CargoHub\CargoHub.csproj", "{DF5C2A7E-1DF9-42A8-B3B9-D6552BDB3BE3}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CargoHub", "CargoHub\CargoHub.csproj", "{707A660E-C336-4B57-8EB1-E5C95CD99244}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CargoHub.Tests", "UnitTest\CargoHub.Tests.csproj", "{08CCD5C8-5AE7-4908-843D-884E2BAC774D}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CargoHub.Tests", "UnitTest\CargoHub.Tests.csproj", "{4A32A713-E27F-4CB7-BDB7-4157A68C2A71}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -16,13 +16,13 @@ Global HideSolutionNode = FALSE EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {DF5C2A7E-1DF9-42A8-B3B9-D6552BDB3BE3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {DF5C2A7E-1DF9-42A8-B3B9-D6552BDB3BE3}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DF5C2A7E-1DF9-42A8-B3B9-D6552BDB3BE3}.Release|Any CPU.ActiveCfg = Release|Any CPU - {DF5C2A7E-1DF9-42A8-B3B9-D6552BDB3BE3}.Release|Any CPU.Build.0 = Release|Any CPU - {08CCD5C8-5AE7-4908-843D-884E2BAC774D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {08CCD5C8-5AE7-4908-843D-884E2BAC774D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {08CCD5C8-5AE7-4908-843D-884E2BAC774D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {08CCD5C8-5AE7-4908-843D-884E2BAC774D}.Release|Any CPU.Build.0 = Release|Any CPU + {707A660E-C336-4B57-8EB1-E5C95CD99244}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {707A660E-C336-4B57-8EB1-E5C95CD99244}.Debug|Any CPU.Build.0 = Debug|Any CPU + {707A660E-C336-4B57-8EB1-E5C95CD99244}.Release|Any CPU.ActiveCfg = Release|Any CPU + {707A660E-C336-4B57-8EB1-E5C95CD99244}.Release|Any CPU.Build.0 = Release|Any CPU + {4A32A713-E27F-4CB7-BDB7-4157A68C2A71}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4A32A713-E27F-4CB7-BDB7-4157A68C2A71}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4A32A713-E27F-4CB7-BDB7-4157A68C2A71}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4A32A713-E27F-4CB7-BDB7-4157A68C2A71}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection EndGlobal diff --git a/Tests/Test_locations.py b/Tests/Test_locations.py index 19516ba..53b6343 100644 --- a/Tests/Test_locations.py +++ b/Tests/Test_locations.py @@ -1,8 +1,8 @@ import requests import pytest -BASE_URL = "http://localhost:3000/api/v1/Locations" -headers = {'APIKEY': "Admin"} +BASE_URL = "http://localhost:3000/api/v1/Locations" +headers = {'APIKEY': "Admin"} # Helper function to clean up test data by deleting any locations with "Test" in their name or code "TST" @@ -13,14 +13,18 @@ def cleanup_test_data(test_name): for location in locations: # Check if the location is test data based on its name or code if "Test" in location["name"] or location["code"] == "TST": - delete_response = requests.delete(f"{BASE_URL}/{location['id']}", headers=headers) # Delete the test location - assert delete_response.status_code in [200, 204], f"Cleanup failed in {test_name}" # Assert that the delete was successful + delete_response = requests.delete( + f"{BASE_URL}/{location['id']}", headers=headers) # Delete the test location + assert delete_response.status_code in [ + 200, 204], f"Cleanup failed in {test_name}" # Test to get all locations def test_get_all_locations(): - response = requests.get(BASE_URL, headers=headers) # Send GET request to fetch all locations - assert response.status_code == 200 # Assert that the response status is 200 (OK) + # Send GET request to fetch all locations + response = requests.get(BASE_URL, headers=headers) + # Assert that the response status is 200 (OK) + assert response.status_code == 200 locations = response.json() # Parse the response as JSON assert isinstance(locations, list) # Assert that the response is a list assert len(locations) > 0 # Assert that the list of locations is not empty @@ -28,22 +32,27 @@ def test_get_all_locations(): # Test to get a location by ID def test_get_location_by_id(): - location_id = 1 - response = requests.get(f"{BASE_URL}/{location_id}") # Send GET request to fetch location by ID - assert response.status_code == 200 # Assert that the response status is 200 (OK) + location_id = 1 + # Send GET request to fetch location by ID + response = requests.get(f"{BASE_URL}/{location_id}") + # Assert that the response status is 200 (OK) + assert response.status_code == 200 location = response.json() # Parse the response as JSON - assert location["id"] == location_id # Assert that the location's ID matches the requested ID + # Assert that the location's ID matches the requested ID + assert location["id"] == location_id # Test to add a new location def test_add_location(): new_location = { - "name": "Test Location", - "code": "TST", - "warehouseId": 1, + "name": "Test Location", + "code": "TST", + "warehouseId": 1, } - response = requests.post(BASE_URL, json=new_location, headers=headers) # Send POST request to create a new location - assert response.status_code == 200 # Assert that the response status is 200 (OK) + # Send POST request to create a new location + response = requests.post(BASE_URL, json=new_location, headers=headers) + # Assert that the response status is 200 (OK) + assert response.status_code == 200 # Check if the response is JSON or plain text if response.headers.get('Content-Type') == 'application/json': @@ -59,7 +68,8 @@ def test_add_location(): # Test to update an existing location def test_update_location(): - response = requests.get(BASE_URL, headers=headers) # Fetch all locations to find one to update + # Fetch all locations to find one to update + response = requests.get(BASE_URL, headers=headers) assert response.status_code == 200, f"Failed to fetch locations: {response.text}" locations = response.json() # Parse the response as JSON @@ -71,15 +81,19 @@ def test_update_location(): location_id = location["id"] break - assert location_id is not None, "No test location found to update." # Assert that a test location was found + # Assert that a test location was found + assert location_id is not None, "No test location found to update." updated_location = { - "name": "Test Location Updated", + "name": "Test Location Updated", "code": "TST", "warehouseId": 1, } - response = requests.put(f"{BASE_URL}/{location_id}", json=updated_location, headers=headers) # Send PUT request to update the location - assert response.status_code == 200 # Assert that the response status is 200 (OK) + # Send PUT request to update the location + response = requests.put(f"{BASE_URL}/{location_id}", + json=updated_location, headers=headers) + # Assert that the response status is 200 (OK) + assert response.status_code == 200 # Check if the response is JSON or plain text if response.headers.get('Content-Type') == 'application/json': @@ -98,13 +112,17 @@ def test_update_location(): # Test to get a location by an invalid ID def test_get_location_by_invalid_id(): - invalid_id = 9999 - response = requests.get(f"{BASE_URL}/{invalid_id}") # Send GET request to fetch location by invalid ID - assert response.status_code == 404 # Assert that the response status is 404 (Not Found) + invalid_id = 9999 + # Send GET request to fetch location by invalid ID + response = requests.get(f"{BASE_URL}/{invalid_id}") + # Assert that the response status is 404 (Not Found) + assert response.status_code == 404 # Test to remove a location by an invalid ID def test_remove_location_invalid_id(): - invalid_id = 9999 - response = requests.delete(f"{BASE_URL}/{invalid_id}") # Send DELETE request to remove location by invalid ID - assert response.status_code == 404 # Assert that the response status is 404 (Not Found) + invalid_id = 9999 + # Send DELETE request to remove location by invalid ID + response = requests.delete(f"{BASE_URL}/{invalid_id}") + # Assert that the response status is 404 (Not Found) + assert response.status_code == 404 diff --git a/Tests/Test_orders.py b/Tests/Test_orders.py index ce29307..927dc95 100644 --- a/Tests/Test_orders.py +++ b/Tests/Test_orders.py @@ -1,38 +1,48 @@ import requests import pytest -BASE_URL = "http://localhost:3000/api/v1/orders" +BASE_URL = "http://localhost:3000/api/v1/orders" headers = {'APIKEY': "Admin"} # Helper function to clean up test data by deleting any orders with "Test" in their reference def cleanup_test_data(test_name): - response = requests.get(BASE_URL, headers=headers) # Send GET request to fetch all orders + # Send GET request to fetch all orders + response = requests.get(BASE_URL, headers=headers) if response.status_code == 200: orders = response.json() # Parse the response as JSON to get the list of orders for order in orders: # Check if the order is test data based on its reference (contains "Test") if "Test" in order["reference"]: - delete_response = requests.delete(f"{BASE_URL}/{order['id']}", headers=headers) # Send DELETE request to remove the order by ID - assert delete_response.status_code in [200, 204], f"Cleanup failed in {test_name}" # Assert successful deletion + # Send DELETE request to remove the order by ID + delete_response = requests.delete( + f"{BASE_URL}/{order['id']}", headers=headers) + assert delete_response.status_code in [ + 200, 204], f"Cleanup failed in {test_name}" # Assert successful deletion # Test to retrieve all orders def test_get_all_orders(): - response = requests.get(BASE_URL, headers=headers) # Send GET request to fetch all orders - assert response.status_code == 200, f"Failed to fetch orders: {response.text}" # Assert that the response status is 200 (OK) + # Send GET request to fetch all orders + response = requests.get(BASE_URL, headers=headers) + # Assert that the response status is 200 (OK) + assert response.status_code == 200, f"Failed to fetch orders: {response.text}" orders = response.json() # Parse the response as JSON to get the list of orders - assert isinstance(orders, list) # Assert that the response is a list of orders + # Assert that the response is a list of orders + assert isinstance(orders, list) assert len(orders) > 0 # Assert that the list of orders is not empty # Test to retrieve a specific order by ID def test_get_order_by_id(): order_id = 1 # Set a valid order ID for testing - response = requests.get(f"{BASE_URL}/{order_id}", headers=headers) # Send GET request to fetch the order by ID - assert response.status_code == 200, f"Failed to fetch order: {response.text}" # Assert that the response status is 200 (OK) + # Send GET request to fetch the order by ID + response = requests.get(f"{BASE_URL}/{order_id}", headers=headers) + # Assert that the response status is 200 (OK) + assert response.status_code == 200, f"Failed to fetch order: {response.text}" order = response.json() # Parse the response as JSON - assert order["id"] == order_id # Assert that the order's ID matches the requested ID + # Assert that the order's ID matches the requested ID + assert order["id"] == order_id # Test to add a new order @@ -45,44 +55,54 @@ def test_add_order(): "orderStatus": "TEST", "totalAmount": 100.0, "totalDiscount": 0.0, - "totalTax": 0.0, + "totalTax": 0.0, "totalSurcharge": 0.0, "notes": "Test notes", "pickingNotes": "Test picking notes", "shippingNotes": "Test shipping notes", "items": [ - {"itemId": "TEST_ITEM_001", "amount": 2}, - {"itemId": "TEST_ITEM_002", "amount": 1} + {"itemId": "TEST_ITEM_001", "amount": 2}, + {"itemId": "TEST_ITEM_002", "amount": 1} ] } - response = requests.post(BASE_URL, json=new_order, headers=headers) # Send POST request to create a new order - assert response.status_code == 201, f"Failed to add order: {response.text}" # Assert that the response status is 201 (Created) + # Send POST request to create a new order + response = requests.post(BASE_URL, json=new_order, headers=headers) + # Assert that the response status is 201 + assert response.status_code == 201, f"Failed to add order: {response.text}" # Print the response JSON for debugging purposes print(response.json()) # Verify that the response contains the added order order = response.json() - assert order["reference"] == new_order["reference"] # Assert that the reference matches the new order's reference + # Assert that the reference matches the new order's reference + assert order["reference"] == new_order["reference"] # Check if 'items' key exists in the response if "items" in order: - assert len(order["items"]) == len(new_order["items"]) # Assert that the number of items in the response matches the input + # Assert that the number of items in the response matches the input + assert len(order["items"]) == len(new_order["items"]) else: - print("Warning: 'items' key not found in the response") # If no items are found, print a warning message + # If no items are found, print a warning message + print("Warning: 'items' key not found in the response") - cleanup_test_data("test_add_order") # Clean up the test data after the test + # Clean up the test data after the test + cleanup_test_data("test_add_order") # Test to get an order by an invalid ID def test_get_order_by_invalid_id(): invalid_id = 9999 - response = requests.get(f"{BASE_URL}/{invalid_id}", headers=headers) # Send GET request to fetch the order by invalid ID - assert response.status_code == 404 # Assert that the response status is 404 (Not Found) + # Send GET request to fetch the order by invalid ID + response = requests.get(f"{BASE_URL}/{invalid_id}", headers=headers) + # Assert that the response status is 404 (Not Found) + assert response.status_code == 404 # Test to remove an order by an invalid ID def test_remove_order_invalid_id(): invalid_id = 9999 - response = requests.delete(f"{BASE_URL}/{invalid_id}", headers=headers) # Send DELETE request to remove the order by invalid ID - assert response.status_code == 404 # Assert that the response status is 404 (Not Found) + # Send DELETE request to remove the order by invalid ID + response = requests.delete(f"{BASE_URL}/{invalid_id}", headers=headers) + # Assert that the response status is 404 (Not Found) + assert response.status_code == 404 diff --git a/Tests/Test_shipments.py b/Tests/Test_shipments.py index 573c54b..dc12353 100644 --- a/Tests/Test_shipments.py +++ b/Tests/Test_shipments.py @@ -5,61 +5,77 @@ headers = {'APIKEY': "Admin"} # Helper function to clean up test data by deleting shipments with "Test" in their shipmentType + + def cleanup_test_data(test_name): - response = requests.get(BASE_URL, headers=headers) # Send GET request to fetch all shipments + # Send GET request to fetch all shipments + response = requests.get(BASE_URL, headers=headers) if response.status_code == 200: shipments = response.json() # Parse the response as JSON to get the list of shipments for shipment in shipments: # Check if the shipment is test data based on its shipmentType (contains "Test") if "Test" in shipment["shipmentType"]: - delete_response = requests.delete(f"{BASE_URL}/{shipment['id']}", headers=headers) # Send DELETE request to remove the shipment by ID - assert delete_response.status_code in [200, 204], f"Cleanup failed in {test_name}" # Assert successful deletion + # Send DELETE request to remove the shipment by ID + delete_response = requests.delete( + f"{BASE_URL}/{shipment['id']}", headers=headers) + assert delete_response.status_code in [ + 200, 204], f"Cleanup failed in {test_name}" # Assert successful deletion # Test to retrieve all shipments def test_get_all_shipments(): - response = requests.get(BASE_URL, headers=headers) # Send GET request to fetch all shipments - assert response.status_code == 200 # Assert that the response status is 200 (OK) + # Send GET request to fetch all shipments + response = requests.get(BASE_URL, headers=headers) + # Assert that the response status is 200 (OK) + assert response.status_code == 200 shipments = response.json() # Parse the response as JSON - assert isinstance(shipments, list) # Assert that the response is a list of shipments + # Assert that the response is a list of shipments + assert isinstance(shipments, list) assert len(shipments) > 0 # Assert that the list of shipments is not empty # Test to retrieve a specific shipment by ID def test_get_shipment_by_id(): shipment_id = 1 - response = requests.get(f"{BASE_URL}/{shipment_id}", headers=headers) # Send GET request to fetch the shipment by ID - assert response.status_code == 200 # Assert that the response status is 200 (OK) + # Send GET request to fetch the shipment by ID + response = requests.get(f"{BASE_URL}/{shipment_id}", headers=headers) + # Assert that the response status is 200 (OK) + assert response.status_code == 200 shipment = response.json() # Parse the response as JSON - assert shipment["id"] == shipment_id # Assert that the shipment's ID matches the requested ID + # Assert that the shipment's ID matches the requested ID + assert shipment["id"] == shipment_id # Test to add a new shipment def test_add_shipment(): new_shipment = { - "sourceId": 999, + "sourceId": 999, "orderDate": "2024-12-01T00:00:00Z", - "requestDate": "2024-12-10T00:00:00Z", + "requestDate": "2024-12-10T00:00:00Z", "shipmentDate": "2024-12-15T00:00:00Z", "shipmentType": "Test Shipment", - "shipmentStatus": "TEST", + "shipmentStatus": "TEST", "notes": "Test notes", - "carrierCode": "TEST_CARRIER", - "carrierDescription": "Test Carrier Description", - "serviceCode": "TEST_SERVICE", - "paymentType": "Prepaid", - "transferMode": "Air", - "totalPackageCount": 5, - "totalPackageWeight": 50.0 + "carrierCode": "TEST_CARRIER", + "carrierDescription": "Test Carrier Description", + "serviceCode": "TEST_SERVICE", + "paymentType": "Prepaid", + "transferMode": "Air", + "totalPackageCount": 5, + "totalPackageWeight": 50.0 } - response = requests.post(BASE_URL, json=new_shipment, headers=headers) # Send POST request to create a new shipment - assert response.status_code == 201, f"Failed to add shipment: {response.text}" # Assert that the response status is 201 (Created) + # Send POST request to create a new shipment + response = requests.post(BASE_URL, json=new_shipment, headers=headers) + # Assert that the response status is 201 (Created) + assert response.status_code == 201, f"Failed to add shipment: {response.text}" # Print the response JSON for debugging purposes print(response.json()) # Verify that the response contains the added shipment shipment = response.json() - assert shipment["shipmentType"] == new_shipment["shipmentType"] # Assert that the shipment type matches the new shipment's shipmentType + # Assert that the shipment type matches the new shipment's shipmentType + assert shipment["shipmentType"] == new_shipment["shipmentType"] - cleanup_test_data("test_add_shipment") # Clean up the test data after the test + # Clean up the test data after the test + cleanup_test_data("test_add_shipment") diff --git a/UnitTest/Test_Items.cs b/UnitTest/Test_Items.cs index a9a3bad..66d1b53 100644 --- a/UnitTest/Test_Items.cs +++ b/UnitTest/Test_Items.cs @@ -1,88 +1,128 @@ -// using Microsoft.VisualStudio.TestTools.UnitTesting; -// using Microsoft.EntityFrameworkCore; -// using System.Collections.Generic; -// using System.Threading.Tasks; -// using CargoHub.Models; -// using CargoHub.Services; - -// namespace CargoHub.Tests +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Microsoft.EntityFrameworkCore; +using System.Collections.Generic; +using System.Threading.Tasks; +using CargoHub.Models; +using CargoHub.Services; + +namespace CargoHub.Tests +{ + [TestClass] + public class ItemStorageServiceTest + { + private BaseStorageService _baseStorageService; + private AppDbContext _dbContext; + + [TestInitialize] + public void Setup() + { + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: "TestDatabase") + .Options; + + _dbContext = new AppDbContext(options); + _baseStorageService = new BaseStorageService(_dbContext); + } + + [TestCleanup] + public void Cleanup() + { + _dbContext.Database.EnsureDeleted(); + _dbContext.Dispose(); + } + + [TestMethod] + public async Task TestGetRowItems() + { + var item = new Item + { + Uid = "P000001", + Code = "XLE77785i", + Description = "test item", + ShortDescription = "short test", + UpcCode = "7946503676171", + ModelNumber = "fM-605648-lbu", + CommodityCode = "qB-2533", + ItemLine = 92, + ItemGroup = 82, + ItemType = 23, + UnitPurchaseQuantity = 23, + UnitOrderQuantity = 43, + PackOrderQuantity = 65, + SupplierId = 65, + SupplierCode = "SUP127", + SupplierPartNumber = "Ay-062669-VVl", + }; + // _baseStorageService.AddRow(item); + _dbContext.Set().Add(item); + await _dbContext.SaveChangesAsync(); + + var result = await _baseStorageService.GetRow(item.Id); + Assert.AreEqual("P000001", result.Uid); + Assert.AreEqual("XLE77785i", result.Code); + Assert.AreEqual("test item", result.Description); + Assert.AreEqual("short test", result.ShortDescription); + Assert.AreEqual("7946503676171", result.UpcCode); + Assert.AreEqual("fM-605648-lbu", result.ModelNumber); + Assert.AreEqual("qB-2533", result.CommodityCode); + Assert.AreEqual(92, result.ItemLine); + Assert.AreEqual(82, result.ItemGroup); + Assert.AreEqual(23, result.ItemType); + Assert.AreEqual(23, result.UnitPurchaseQuantity); + Assert.AreEqual(43, result.UnitOrderQuantity); + Assert.AreEqual(65, result.SupplierId); + Assert.AreEqual("SUP127", result.SupplierCode); + Assert.AreEqual("Ay-062669-VVl", result.SupplierPartNumber); + } + + [TestMethod] // checkt null if does not exst + public async Task TestGetRowNotExistItems() + { + var result = await _baseStorageService.GetRow(999); + Assert.IsNull(result); + } + + + } +} +// [TestMethod] +// public async Task TestGetAllItems() // { -// [TestClass] -// public class ItemStorageServiceTest -// { -// private BaseStorageService _baseStorageService; -// private AppDbContext _dbContext; -// [TestInitialize] -// public void Setup() -// { -// var options = new DbContextOptionsBuilder() -// .UseInMemoryDatabase(databaseName: "TestDatabase") -// .Options; - -// _dbContext = new AppDbContext(options); -// _baseStorageService = new BaseStorageService(_dbContext); -// } - -// [TestCleanup] -// public void Cleanup() -// { -// _dbContext.Database.EnsureDeleted(); -// _dbContext.Dispose(); -// } - -// [TestMethod] -// public async Task TestGetRowItems() -// { - -// } - -// [TestMethod] // checkt null if does not exst -// public async Task TestGetRowNotExistItems() -// { - -// } - -// [TestMethod] -// public async Task TestGetAllItems() -// { - -// } +// } -// [TestMethod] -// public async Task TestPostItems() -// { +// [TestMethod] +// public async Task TestPostItems() +// { -// } +// } -// [TestMethod] -// public async Task TestPostRowNotExistItems() -// { +// [TestMethod] +// public async Task TestPostRowNotExistItems() +// { -// } +// } -// [TestMethod] -// public async Task TestPutItems() -// { +// [TestMethod] +// public async Task TestPutItems() +// { -// } +// } -// [TestMethod] -// public async Task TestPutNotExistItems() -// { +// [TestMethod] +// public async Task TestPutNotExistItems() +// { -// } +// } -// [TestMethod] -// public async Task TestDeleteRowItems() -// { +// [TestMethod] +// public async Task TestDeleteRowItems() +// { -// } +// } -// [TestMethod] -// public async Task TestDeleteRowNotExistItems() -// { +// [TestMethod] +// public async Task TestDeleteRowNotExistItems() +// { -// } -// } // } From 5eb0064199843abeecaccd6ee6ad094f9062c416 Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Fri, 17 Jan 2025 13:41:44 +0100 Subject: [PATCH 02/35] small change test location --- Tests/Test_locations.py | 86 ++++++++++++++++++++++++----------------- 1 file changed, 50 insertions(+), 36 deletions(-) diff --git a/Tests/Test_locations.py b/Tests/Test_locations.py index ae92903..5799a25 100644 --- a/Tests/Test_locations.py +++ b/Tests/Test_locations.py @@ -3,23 +3,29 @@ BASE_URL = "http://localhost:3000/api/v1/Locations" WAREHOUSE_URL = "http://localhost:3000/api/v1/warehouses" -headers = {'APIKEY': "Admin"} +headers = {'APIKEY': "Admin"} + def cleanup_test_data(test_name): - response = requests.get(BASE_URL, headers=headers) + response = requests.get(BASE_URL, headers=headers) if response.status_code == 200: - locations = response.json() + locations = response.json() for location in locations: if "Test" in location["name"] or location["code"] == "TST": - delete_response = requests.delete(f"{BASE_URL}/{location['id']}", headers=headers) - assert delete_response.status_code in [200, 204], f"Cleanup failed in {test_name}" - response = requests.get(WAREHOUSE_URL, headers=headers) + delete_response = requests.delete( + f"{BASE_URL}/{location['id']}", headers=headers) + assert delete_response.status_code in [ + 200, 204], f"Cleanup failed in {test_name}" + response = requests.get(WAREHOUSE_URL, headers=headers) if response.status_code == 200: warehouses = response.json() for warehouse in warehouses: if warehouse["code"] == "TST": - delete_response = requests.delete(f"{WAREHOUSE_URL}/{warehouse['id']}", headers=headers) - assert delete_response.status_code in [200, 204], f"Cleanup failed in {test_name}" + delete_response = requests.delete( + f"{WAREHOUSE_URL}/{warehouse['id']}", headers=headers) + assert delete_response.status_code in [ + 200, 204], f"Cleanup failed in {test_name}" + def Create_test_warehouse(): new_warehouse = { @@ -34,70 +40,76 @@ def Create_test_warehouse(): "contactEmail": "test", } - response = requests.post(WAREHOUSE_URL, json=new_warehouse, headers=headers) + response = requests.post( + WAREHOUSE_URL, json=new_warehouse, headers=headers) assert response.status_code in [201, 204] - response = requests.get(WAREHOUSE_URL, headers=headers) + response = requests.get(WAREHOUSE_URL, headers=headers) for warehouse in response.json(): if warehouse["code"] == "TST": return warehouse["id"] + def test_get_all_locations(): - response = requests.get(BASE_URL, headers=headers) - assert response.status_code == 200 - locations = response.json() - assert isinstance(locations, list) - assert len(locations) > 0 + response = requests.get(BASE_URL, headers=headers) + assert response.status_code == 200 + locations = response.json() + assert isinstance(locations, list) + assert len(locations) > 0 + def test_get_location_by_id(): - location_id = 1 - response = requests.get(f"{BASE_URL}/{location_id}") - assert response.status_code == 200 - location = response.json() - assert location["id"] == location_id + location_id = 1 + response = requests.get(f"{BASE_URL}/{location_id}") + assert response.status_code == 200 + location = response.json() + assert location["id"] == location_id + def test_add_location(): warehouse_id = Create_test_warehouse() new_location = { - "name": "Test Location", - "code": "TST", + "name": "Test Location", + "code": "TST", "warehouseId": warehouse_id, } - response = requests.post(BASE_URL, json=new_location, headers=headers) - assert response.status_code == 200 + response = requests.post(BASE_URL, json=new_location, headers=headers) + assert response.status_code == 200 if response.headers.get('Content-Type') == 'application/json': - location = response.json() + location = response.json() assert location["name"] == new_location["name"] assert location["code"] == new_location["code"] assert location["warehouseId"] == new_location["warehouseId"] else: assert response.text == "Locatie succesvol toegevoegd." + def test_update_location(): - response = requests.get(BASE_URL, headers=headers) + response = requests.get(BASE_URL, headers=headers) assert response.status_code == 200, f"Failed to fetch locations: {response.text}" - locations = response.json() - location_id = None + locations = response.json() + location_id = None for location in locations: if "Test" in location["name"] or location["code"] == "TST": location_id = location["id"] break - assert location_id is not None, "No test location found to update." + assert location_id is not None, "No test location found to update." updated_location = { - "name": "Test Location Updated", + "name": "Test Location Updated", "code": "TST", "warehouseId": 1, } - response = requests.put(f"{BASE_URL}/{location_id}", json=updated_location, headers=headers) - assert response.status_code == 200 + response = requests.put(f"{BASE_URL}/{location_id}", + json=updated_location, headers=headers) + assert response.status_code == 200 if response.headers.get('Content-Type') == 'application/json': - location = response.json() + location = response.json() assert location["name"] == updated_location["name"] assert location["code"] == updated_location["code"] assert location["warehouseId"] == updated_location["warehouseId"] @@ -106,13 +118,15 @@ def test_update_location(): cleanup_test_data("test_update_location") + def test_get_location_by_invalid_id(): invalid_id = 9999 response = requests.get(f"{BASE_URL}/{invalid_id}") print(response.text) assert response.status_code == 404 + def test_remove_location_invalid_id(): - invalid_id = 9999 - response = requests.delete(f"{BASE_URL}/{invalid_id}") - assert response.status_code == 404 \ No newline at end of file + invalid_id = 9999 + response = requests.delete(f"{BASE_URL}/{invalid_id}") + assert response.status_code == 404 From 2a1a8c06295331c6233060db8e091ad91153f3c1 Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Fri, 17 Jan 2025 13:46:07 +0100 Subject: [PATCH 03/35] test helper new version --- UnitTest/TestHelper.cs | 142 ++++++++++++++++++++--------------------- 1 file changed, 71 insertions(+), 71 deletions(-) diff --git a/UnitTest/TestHelper.cs b/UnitTest/TestHelper.cs index 14e2b8a..6ab54f9 100644 --- a/UnitTest/TestHelper.cs +++ b/UnitTest/TestHelper.cs @@ -1,81 +1,81 @@ -// using CargoHub.Models; -// using Moq; -// namespace CargoHub.Test; -// public static class TestHelper -// { -// public static bool HaveSameDates(DateTime d1, DateTime d2, TimeSpan tolerance) -// { -// return d1.Date - d2.Date <= tolerance; +using CargoHub.Models; +using Moq; +namespace CargoHub.Test; +public static class TestHelper +{ + public static bool HaveSameDates(DateTime d1, DateTime d2, TimeSpan tolerance) + { + return d1.Date - d2.Date <= tolerance; -// } + } -// public static Client CreateRandomClient() -// { -// return new Client -// { -// Name = Guid.NewGuid().ToString(), -// Description = Guid.NewGuid().ToString() -// }; -// } + public static ItemGroup CreateRandomItemGroup() + { + return new ItemGroup + { + Name = Guid.NewGuid().ToString(), + Description = Guid.NewGuid().ToString() + }; + } -// public static ItemLine CreateRandomItemLine() -// { -// return new ItemLine -// { -// Name = Guid.NewGuid().ToString(), -// Description = Guid.NewGuid().ToString() -// }; -// } + public static ItemLine CreateRandomItemLine() + { + return new ItemLine + { + Name = Guid.NewGuid().ToString(), + Description = Guid.NewGuid().ToString() + }; + } -// public static Client TestClient1 = new Client -// { -// Name = "Test Name", -// Description = "Test Description" -// }; -// public static Client TestClient2 = new Client -// { -// Name = "Updated Name", -// Description = "Updated Description" + public static ItemGroup TestItemGroup1 = new ItemGroup + { + Name = "Test Name", + Description = "Test Description" + }; + public static ItemGroup TestItemGroup2 = new ItemGroup + { + Name = "Updated Name", + Description = "Updated Description" -// }; -// public static Client InvalidClient = new Client -// { -// Name = null, -// Description = null -// }; -// public static Client InvalidName_IG = new Client -// { -// Name = null, -// Description = "Valid Description" -// }; + }; + public static ItemGroup InvalidItemGroup = new ItemGroup + { + Name = null, + Description = null + }; + public static ItemGroup InvalidName_IG = new ItemGroup + { + Name = null, + Description = "Valid Description" + }; -// public static ItemLine TestItemLine1 = new ItemLine -// { -// Name = "Test Name", -// Description = "Test Description" -// }; -// public static ItemLine TestItemLine2 = new ItemLine -// { -// Name = "Updated Name", -// Description = "Updated Description" + public static ItemLine TestItemLine1 = new ItemLine + { + Name = "Test Name", + Description = "Test Description" + }; + public static ItemLine TestItemLine2 = new ItemLine + { + Name = "Updated Name", + Description = "Updated Description" -// }; -// public static ItemLine InvalidItemLine = new ItemLine -// { -// Name = null, -// Description = null -// }; -// public static ItemLine InvalidName_IL = new ItemLine -// { -// Name = null, -// Description = "Valid Description" -// }; -// public static ItemLine InvalidDescription_IL = new ItemLine -// { -// Name = "Valid Name", -// Description = null -// }; + }; + public static ItemLine InvalidItemLine = new ItemLine + { + Name = null, + Description = null + }; + public static ItemLine InvalidName_IL = new ItemLine + { + Name = null, + Description = "Valid Description" + }; + public static ItemLine InvalidDescription_IL = new ItemLine + { + Name = "Valid Name", + Description = null + }; -// } \ No newline at end of file +} \ No newline at end of file From aaf2910f348be5b7cb6c3081c66e8a35eba1e22c Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Fri, 17 Jan 2025 14:58:09 +0100 Subject: [PATCH 04/35] unittest item types ik maak nu gebruik van de testhelper waar ik de body zet van het gene dat ik test. Hierbij heb ik test get all gemaakt --- UnitTest/TestHelper.cs | 18 +++ UnitTest/Test_ItemTypes.cs | 226 ++++++++++++++++++------------------- 2 files changed, 129 insertions(+), 115 deletions(-) diff --git a/UnitTest/TestHelper.cs b/UnitTest/TestHelper.cs index 6ab54f9..bcdbbec 100644 --- a/UnitTest/TestHelper.cs +++ b/UnitTest/TestHelper.cs @@ -77,5 +77,23 @@ public static ItemLine CreateRandomItemLine() Description = null }; + public static ItemType TestItemType1 = new ItemType + { + Name = "Test Name", + Description = "Test Description" + }; + + public static ItemType TestItemType2 = new ItemType + { + Name = "Test Name2", + Description = "Test Description2" + }; + + public static ItemType TestupdateItemType = new ItemType + { + Name = "updated Name", + Description = "updated Description" + }; + } \ No newline at end of file diff --git a/UnitTest/Test_ItemTypes.cs b/UnitTest/Test_ItemTypes.cs index 9dde795..1d58e19 100644 --- a/UnitTest/Test_ItemTypes.cs +++ b/UnitTest/Test_ItemTypes.cs @@ -1,140 +1,136 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Microsoft.EntityFrameworkCore; -using System.Collections.Generic; -using System.Threading.Tasks; -using CargoHub.Models; -using CargoHub.Services; - -namespace CargoHub.Tests +namespace CargoHub.Test; + +[TestClass] +public class ItemTypeServiceTests { - [TestClass] - public class ItemTypeServiceTests + private BaseStorageService _baseStorageService; + private AppDbContext _dbContext; + + [TestInitialize] + public void Setup() { - private BaseStorageService _baseStorageService; - private AppDbContext _dbContext; + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: "TestDatabase") + .Options; - [TestInitialize] - public void Setup() - { - var options = new DbContextOptionsBuilder() - .UseInMemoryDatabase(databaseName: "TestDatabase") - .Options; + _dbContext = new AppDbContext(options); + _baseStorageService = new BaseStorageService(_dbContext); + } - _dbContext = new AppDbContext(options); - _baseStorageService = new BaseStorageService(_dbContext); - } + [TestCleanup] + public void Cleanup() + { + _dbContext.Database.EnsureDeleted(); + _dbContext.Dispose(); + } - [TestCleanup] - public void Cleanup() - { - _dbContext.Database.EnsureDeleted(); - _dbContext.Dispose(); - } + [TestMethod] + public async Task TestGetRowItemType() + { + // Arrange + ItemType itemType = TestHelper.TestItemType1; - [TestMethod] - public async Task TestGetRowItemType() - { - // Arrange - var itemType = new ItemType { Name = "Test Item", Description = "Description" }; - _dbContext.Set().Add(itemType); - await _dbContext.SaveChangesAsync(); - - // Act - var result = await _baseStorageService.GetRow(itemType.Id); - - // Assert - Assert.IsNotNull(result); - Assert.AreEqual("Test Item", result.Name); - Assert.AreEqual("Description", result.Description); - } - - [TestMethod] // checkt null if does not exst - public async Task TestGetRowNotExist() - { - var result = await _baseStorageService.GetRow(999); - Assert.IsNull(result); - } + _dbContext.Set().Add(itemType); // Add the test item type to the in-memory database + await _dbContext.SaveChangesAsync(); // Save changes to simulate a real database operation - [TestMethod] - public async Task TestGetAllItemTypes() - { - _dbContext.ItemTypes.AddRange(new List - { - new ItemType { Name = "Test ItemType 1", Description = "Test ItemType 1"}, - new ItemType { Name = "Test ItemType 2", Description = "Test ItemType 2"} - }); - await _dbContext.SaveChangesAsync(); + // Act + var result = await _baseStorageService.GetRow(itemType.Id); // Retrieve the item type by its Id - var result = await _baseStorageService.GetAllRows(); + // Assert + Assert.IsNotNull(result); + Assert.AreEqual("Test Name", result.Name); + Assert.AreEqual("Test Description", result.Description); + } - Assert.AreEqual(2, result.Count); - } - [TestMethod] - public async Task TestPostItemTypes() - { - var newItemType = new ItemType { Name = "Test ItemType", Description = "Test ItemType" }; - var result = await _baseStorageService.AddRow(newItemType); + [TestMethod] // checkt null if does not exst + public async Task TestGetRowNotExist() + { + var result = await _baseStorageService.GetRow(999); + Assert.IsNull(result); + } - Assert.IsNotNull(result); - } + [TestMethod] + public async Task TestGetAllItemTypes() + { + ItemType itemType = TestHelper.TestItemType1; + ItemType itemType2 = TestHelper.TestItemType2; - [TestMethod] - public async Task TestPostRowNotExist() + _dbContext.ItemTypes.AddRange(new List { - var result = await _baseStorageService.AddRow(null); - Assert.IsNull(result); - } + itemType, itemType2 + }); + await _dbContext.SaveChangesAsync(); - [TestMethod] - public async Task TestPutItemType() - { - // Arrange - var itemType = new ItemType { Name = "Old Name", Description = "Old Description" }; - _dbContext.Set().Add(itemType); - await _dbContext.SaveChangesAsync(); + var result = await _baseStorageService.GetAllRows(); - var updatedItem = new ItemType { Id = itemType.Id, Name = "New Name", Description = "New Description" }; + Assert.AreEqual(2, result.Count); + } - // Act - var result = await _baseStorageService.UpdateRow(itemType.Id, updatedItem); + [TestMethod] + public async Task TestPostItemTypes() + { + ItemType newItemType = TestHelper.TestItemType1; + var result = await _baseStorageService.AddRow(newItemType); - // Assert - Assert.IsTrue(result); + Assert.IsNotNull(result); + } - var updated = await _dbContext.Set().FindAsync(itemType.Id); - Assert.AreEqual("New Name", updated.Name); - Assert.AreEqual("New Description", updated.Description); - } + [TestMethod] + public async Task TestPostRowNotExist() + { + var result = await _baseStorageService.AddRow(null); + Assert.IsNull(result); + } - [TestMethod] - public async Task TestPutNotExist() - { - var updatedItem = new ItemType { Name = "New Name", Description = "New Description" }; - var result = await _baseStorageService.UpdateRow(999, updatedItem); - Assert.IsFalse(result); - } + [TestMethod] + public async Task TestPutItemType() + { + // Arrange + var itemType = new ItemType { Name = "Old Name", Description = "Old Description" }; + _dbContext.Set().Add(itemType); + await _dbContext.SaveChangesAsync(); - [TestMethod] - public async Task TestDeleteRow() - { - var deleteItemType = new ItemType { Name = "Delete name", Description = "Delete Description" }; - _dbContext.Set().Add(deleteItemType); - await _dbContext.SaveChangesAsync(); + var updatedItem = new ItemType { Id = itemType.Id, Name = "New Name", Description = "New Description" }; - var result = await _baseStorageService.DeleteRow(deleteItemType.Id); + // Act + var result = await _baseStorageService.UpdateRow(itemType.Id, updatedItem); - Assert.IsTrue(result); + // Assert + Assert.IsTrue(result); - var deletedItem = await _dbContext.Set().FindAsync(deleteItemType.Id); - Assert.IsNull(deletedItem); - } + var updated = await _dbContext.Set().FindAsync(itemType.Id); + Assert.AreEqual("New Name", updated.Name); + Assert.AreEqual("New Description", updated.Description); + } - [TestMethod] - public async Task TestDeleteRowNotExist() - { - var itemType = await _baseStorageService.GetRow(999); - Assert.IsNull(itemType); - } + [TestMethod] + public async Task TestPutNotExist() + { + var updatedItem = new ItemType { Name = "New Name", Description = "New Description" }; + var result = await _baseStorageService.UpdateRow(999, updatedItem); + Assert.IsFalse(result); + } + + [TestMethod] + public async Task TestDeleteRow() + { + var deleteItemType = new ItemType { Name = "Delete name", Description = "Delete Description" }; + _dbContext.Set().Add(deleteItemType); + await _dbContext.SaveChangesAsync(); + + var result = await _baseStorageService.DeleteRow(deleteItemType.Id); + + Assert.IsTrue(result); + + var deletedItem = await _dbContext.Set().FindAsync(deleteItemType.Id); + Assert.IsNull(deletedItem); + } + + [TestMethod] + public async Task TestDeleteRowNotExist() + { + var itemType = await _baseStorageService.GetRow(999); + Assert.IsNull(itemType); } -} \ No newline at end of file +} From 1d3486d58d931fcfa6b74b7fdac5c97ead98368f Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Fri, 17 Jan 2025 15:22:06 +0100 Subject: [PATCH 05/35] unittest itemtypes test post aangemaakt en test null post aangemaakt --- UnitTest/Test_ItemTypes.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/UnitTest/Test_ItemTypes.cs b/UnitTest/Test_ItemTypes.cs index 1d58e19..f15146b 100644 --- a/UnitTest/Test_ItemTypes.cs +++ b/UnitTest/Test_ItemTypes.cs @@ -77,7 +77,7 @@ public async Task TestPostItemTypes() } [TestMethod] - public async Task TestPostRowNotExist() + public async Task TestPostNullItemTypes() { var result = await _baseStorageService.AddRow(null); Assert.IsNull(result); From 89a406d6325fbb3ca88d5338cab25ddc56b231b6 Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Fri, 17 Jan 2025 15:50:28 +0100 Subject: [PATCH 06/35] Unittest itemtype Testputitemtype maakt nu gebruik van de testhelper --- UnitTest/Test_ItemTypes.cs | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/UnitTest/Test_ItemTypes.cs b/UnitTest/Test_ItemTypes.cs index f15146b..e2fa213 100644 --- a/UnitTest/Test_ItemTypes.cs +++ b/UnitTest/Test_ItemTypes.cs @@ -87,27 +87,25 @@ public async Task TestPostNullItemTypes() public async Task TestPutItemType() { // Arrange - var itemType = new ItemType { Name = "Old Name", Description = "Old Description" }; + ItemType itemType = TestHelper.TestItemType1; _dbContext.Set().Add(itemType); await _dbContext.SaveChangesAsync(); - var updatedItem = new ItemType { Id = itemType.Id, Name = "New Name", Description = "New Description" }; + ItemType updatedItem = TestHelper.TestupdateItemType; + updatedItem.Id = itemType.Id; - // Act var result = await _baseStorageService.UpdateRow(itemType.Id, updatedItem); - - // Assert Assert.IsTrue(result); - var updated = await _dbContext.Set().FindAsync(itemType.Id); - Assert.AreEqual("New Name", updated.Name); - Assert.AreEqual("New Description", updated.Description); + var updated = await _baseStorageService.GetRow(itemType.Id); + Assert.AreEqual("updated Name", updated.Name); + Assert.AreEqual("updated Description", updated.Description); } [TestMethod] public async Task TestPutNotExist() { - var updatedItem = new ItemType { Name = "New Name", Description = "New Description" }; + ItemType updatedItem = new ItemType { Name = "New Name", Description = "New Description" }; var result = await _baseStorageService.UpdateRow(999, updatedItem); Assert.IsFalse(result); } From 5ba44cbf3a082f0091c02febd23a0a9f859e1be8 Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Fri, 17 Jan 2025 15:55:28 +0100 Subject: [PATCH 07/35] unittest itemtype Testputnotexist gebruikt nu ook testhelper Deze test kijkt wat er gebeurt wanneer je een itemtype probeerd te wijzigen die niet bestaat --- UnitTest/Test_ItemTypes.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/UnitTest/Test_ItemTypes.cs b/UnitTest/Test_ItemTypes.cs index e2fa213..5c4d29c 100644 --- a/UnitTest/Test_ItemTypes.cs +++ b/UnitTest/Test_ItemTypes.cs @@ -105,7 +105,7 @@ public async Task TestPutItemType() [TestMethod] public async Task TestPutNotExist() { - ItemType updatedItem = new ItemType { Name = "New Name", Description = "New Description" }; + ItemType updatedItem = TestHelper.TestupdateItemType; var result = await _baseStorageService.UpdateRow(999, updatedItem); Assert.IsFalse(result); } From 0f4555f60c7872fc557923972cf67c0c00be46a7 Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Fri, 17 Jan 2025 16:03:16 +0100 Subject: [PATCH 08/35] Unittest itemType De testdeleterow gebruikt nu de testhelper. in testdeleterownotexist was er het verkeerde methode aangeroepen deze is nou gewijzigd --- UnitTest/Test_ItemTypes.cs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/UnitTest/Test_ItemTypes.cs b/UnitTest/Test_ItemTypes.cs index 5c4d29c..293fbb4 100644 --- a/UnitTest/Test_ItemTypes.cs +++ b/UnitTest/Test_ItemTypes.cs @@ -113,9 +113,8 @@ public async Task TestPutNotExist() [TestMethod] public async Task TestDeleteRow() { - var deleteItemType = new ItemType { Name = "Delete name", Description = "Delete Description" }; - _dbContext.Set().Add(deleteItemType); - await _dbContext.SaveChangesAsync(); + var deleteItemType = TestHelper.TestItemType1; + await _baseStorageService.AddRow(deleteItemType); var result = await _baseStorageService.DeleteRow(deleteItemType.Id); @@ -128,7 +127,7 @@ public async Task TestDeleteRow() [TestMethod] public async Task TestDeleteRowNotExist() { - var itemType = await _baseStorageService.GetRow(999); - Assert.IsNull(itemType); + var itemType = await _baseStorageService.DeleteRow(999); + Assert.IsFalse(itemType); } } From 2ca26437ede3f8abd6d13a05e88bf231f758e987 Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Fri, 17 Jan 2025 16:11:54 +0100 Subject: [PATCH 09/35] Unittest Items TestGetRowItems maakt nu gebruik van Testhelper --- UnitTest/TestHelper.cs | 20 ++++++++++++++++++++ UnitTest/Test_Items.cs | 24 +++--------------------- 2 files changed, 23 insertions(+), 21 deletions(-) diff --git a/UnitTest/TestHelper.cs b/UnitTest/TestHelper.cs index bcdbbec..8f730fa 100644 --- a/UnitTest/TestHelper.cs +++ b/UnitTest/TestHelper.cs @@ -95,5 +95,25 @@ public static ItemLine CreateRandomItemLine() Description = "updated Description" }; + public static Item TestItem1 = new Item + { + Uid = "P000001", + Code = "XLE77785i", + Description = "test item", + ShortDescription = "short test", + UpcCode = "7946503676171", + ModelNumber = "fM-605648-lbu", + CommodityCode = "qB-2533", + ItemLine = 92, + ItemGroup = 82, + ItemType = 23, + UnitPurchaseQuantity = 23, + UnitOrderQuantity = 43, + PackOrderQuantity = 65, + SupplierId = 65, + SupplierCode = "SUP127", + SupplierPartNumber = "Ay-062669-VVl", + }; + } \ No newline at end of file diff --git a/UnitTest/Test_Items.cs b/UnitTest/Test_Items.cs index 66d1b53..b3c7717 100644 --- a/UnitTest/Test_Items.cs +++ b/UnitTest/Test_Items.cs @@ -4,6 +4,7 @@ using System.Threading.Tasks; using CargoHub.Models; using CargoHub.Services; +using CargoHub.Test; namespace CargoHub.Tests { @@ -34,25 +35,8 @@ public void Cleanup() [TestMethod] public async Task TestGetRowItems() { - var item = new Item - { - Uid = "P000001", - Code = "XLE77785i", - Description = "test item", - ShortDescription = "short test", - UpcCode = "7946503676171", - ModelNumber = "fM-605648-lbu", - CommodityCode = "qB-2533", - ItemLine = 92, - ItemGroup = 82, - ItemType = 23, - UnitPurchaseQuantity = 23, - UnitOrderQuantity = 43, - PackOrderQuantity = 65, - SupplierId = 65, - SupplierCode = "SUP127", - SupplierPartNumber = "Ay-062669-VVl", - }; + var item = TestHelper.TestItem1; + // _baseStorageService.AddRow(item); _dbContext.Set().Add(item); await _dbContext.SaveChangesAsync(); @@ -81,8 +65,6 @@ public async Task TestGetRowNotExistItems() var result = await _baseStorageService.GetRow(999); Assert.IsNull(result); } - - } } // [TestMethod] From 4981ba73691af939b67b11ca75740bf6b9dcdd45 Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Fri, 17 Jan 2025 16:29:38 +0100 Subject: [PATCH 10/35] Unittest TestGetAllItems TestGetAllItems aangemaakt --- UnitTest/TestHelper.cs | 19 +++++++++++++++++++ UnitTest/Test_Items.cs | 27 +++++++++++++++++++-------- 2 files changed, 38 insertions(+), 8 deletions(-) diff --git a/UnitTest/TestHelper.cs b/UnitTest/TestHelper.cs index 8f730fa..be27b25 100644 --- a/UnitTest/TestHelper.cs +++ b/UnitTest/TestHelper.cs @@ -115,5 +115,24 @@ public static ItemLine CreateRandomItemLine() SupplierPartNumber = "Ay-062669-VVl", }; + public static Item TestItem2 = new Item + { + Uid = "P000002", + Code = "XLE77785i", + Description = "test item2", + ShortDescription = "short test2", + UpcCode = "7946503676171", + ModelNumber = "fM-605648-lbu", + CommodityCode = "qB-2533", + ItemLine = 92, + ItemGroup = 82, + ItemType = 23, + UnitPurchaseQuantity = 23, + UnitOrderQuantity = 43, + PackOrderQuantity = 65, + SupplierId = 65, + SupplierCode = "SUP127", + SupplierPartNumber = "Ay-062669-VVl", + }; } \ No newline at end of file diff --git a/UnitTest/Test_Items.cs b/UnitTest/Test_Items.cs index b3c7717..2d2ab8a 100644 --- a/UnitTest/Test_Items.cs +++ b/UnitTest/Test_Items.cs @@ -1,9 +1,3 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Microsoft.EntityFrameworkCore; -using System.Collections.Generic; -using System.Threading.Tasks; -using CargoHub.Models; -using CargoHub.Services; using CargoHub.Test; namespace CargoHub.Tests @@ -35,7 +29,7 @@ public void Cleanup() [TestMethod] public async Task TestGetRowItems() { - var item = TestHelper.TestItem1; + Item item = TestHelper.TestItem1; // _baseStorageService.AddRow(item); _dbContext.Set().Add(item); @@ -62,9 +56,26 @@ public async Task TestGetRowItems() [TestMethod] // checkt null if does not exst public async Task TestGetRowNotExistItems() { - var result = await _baseStorageService.GetRow(999); + Item result = await _baseStorageService.GetRow(999); Assert.IsNull(result); } + + [TestMethod] + public async Task TestGetAllItems() + { + Item item1 = TestHelper.TestItem1; + Item item2 = TestHelper.TestItem2; + + _dbContext.Items.AddRange(new List + { + item1, item2 + }); + await _dbContext.SaveChangesAsync(); + + var result = await _baseStorageService.GetAllRows(); + + Assert.AreEqual(2, result.Count); + } } } // [TestMethod] From 831eea324beec8bac4cfe59070d9989b23b1c872 Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Fri, 17 Jan 2025 16:31:30 +0100 Subject: [PATCH 11/35] Unittest TestPostItem TestPostItem aangemaakt --- UnitTest/Test_Items.cs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/UnitTest/Test_Items.cs b/UnitTest/Test_Items.cs index 2d2ab8a..ff2e7a3 100644 --- a/UnitTest/Test_Items.cs +++ b/UnitTest/Test_Items.cs @@ -76,6 +76,15 @@ public async Task TestGetAllItems() Assert.AreEqual(2, result.Count); } + + [TestMethod] + public async Task TestPostItem() + { + Item newItem = TestHelper.TestItem1; + var result = await _baseStorageService.AddRow(newItem); + + Assert.IsNotNull(result); + } } } // [TestMethod] From 87097edbf07fcd8012f3951c75ff539c48d302f2 Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Fri, 17 Jan 2025 16:35:33 +0100 Subject: [PATCH 12/35] Unittest TestPostNullItem TestPostNullItem aangemaakt. hij test wat er gebeurt als je een Post request maakt met een item die null is --- UnitTest/Test_Items.cs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/UnitTest/Test_Items.cs b/UnitTest/Test_Items.cs index ff2e7a3..2502dd4 100644 --- a/UnitTest/Test_Items.cs +++ b/UnitTest/Test_Items.cs @@ -85,6 +85,13 @@ public async Task TestPostItem() Assert.IsNotNull(result); } + + [TestMethod] + public async Task TestPostNullItem() + { + var result = await _baseStorageService.AddRow(null); + Assert.IsNull(result); + } } } // [TestMethod] From f3569d576088ea02138c0f2ac17ddc2d7e95bcbe Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Fri, 17 Jan 2025 16:43:11 +0100 Subject: [PATCH 13/35] Unittest TestPutItem TestputItem aangemaakt. --- UnitTest/TestHelper.cs | 20 ++++++++++++++++++++ UnitTest/Test_Items.cs | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/UnitTest/TestHelper.cs b/UnitTest/TestHelper.cs index be27b25..0a0e383 100644 --- a/UnitTest/TestHelper.cs +++ b/UnitTest/TestHelper.cs @@ -135,4 +135,24 @@ public static ItemLine CreateRandomItemLine() SupplierPartNumber = "Ay-062669-VVl", }; + public static Item TestUpdatedItem = new Item + { + Uid = "P000001", + Code = "XLE77785i", + Description = "test Updated", + ShortDescription = "short Updated", + UpcCode = "7946503676171", + ModelNumber = "fM-605648-lbu", + CommodityCode = "qB-2533", + ItemLine = 92, + ItemGroup = 82, + ItemType = 23, + UnitPurchaseQuantity = 23, + UnitOrderQuantity = 43, + PackOrderQuantity = 65, + SupplierId = 65, + SupplierCode = "SUP127", + SupplierPartNumber = "Ay-062669-VVl", + }; + } \ No newline at end of file diff --git a/UnitTest/Test_Items.cs b/UnitTest/Test_Items.cs index 2502dd4..5ca0c84 100644 --- a/UnitTest/Test_Items.cs +++ b/UnitTest/Test_Items.cs @@ -92,6 +92,39 @@ public async Task TestPostNullItem() var result = await _baseStorageService.AddRow(null); Assert.IsNull(result); } + + [TestMethod] + public async Task TestPutItem() + { + // Arrange + Item item = TestHelper.TestItem1; + await _baseStorageService.AddRow(item); // Gebruik de service om data toe te voegen + + Item updatedItem = TestHelper.TestUpdatedItem; + updatedItem.Id = item.Id; // Zorg dat het juiste ID wordt ingesteld + + // Act + var result = await _baseStorageService.UpdateRow(item.Id, updatedItem); + Assert.IsTrue(result); + + var updated = await _baseStorageService.GetRow(item.Id); // Haal het geüpdatete record op + Assert.AreEqual("P000001", updated.Uid); + Assert.AreEqual("XLE77785i", updated.Code); + Assert.AreEqual("test Updated", updated.Description); + Assert.AreEqual("short Updated", updated.ShortDescription); + Assert.AreEqual("7946503676171", updated.UpcCode); + Assert.AreEqual("fM-605648-lbu", updated.ModelNumber); + Assert.AreEqual("qB-2533", updated.CommodityCode); + Assert.AreEqual(92, updated.ItemLine); + Assert.AreEqual(82, updated.ItemGroup); + Assert.AreEqual(23, updated.ItemType); + Assert.AreEqual(23, updated.UnitPurchaseQuantity); + Assert.AreEqual(43, updated.UnitOrderQuantity); + Assert.AreEqual(65, updated.SupplierId); + Assert.AreEqual("SUP127", updated.SupplierCode); + Assert.AreEqual("Ay-062669-VVl", updated.SupplierPartNumber); + } + } } // [TestMethod] From 81633364b5ab35a68f8029358741efc0b7a83ae4 Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Fri, 17 Jan 2025 17:00:37 +0100 Subject: [PATCH 14/35] Unittest Test Delete Item gemaakt --- UnitTest/ItemStorageServiceTest.cs | 190 ++++++++++++++++++ ..._ItemTypes.cs => ItemTypesServiceTests.cs} | 2 +- UnitTest/Test_Items.cs | 170 ---------------- 3 files changed, 191 insertions(+), 171 deletions(-) create mode 100644 UnitTest/ItemStorageServiceTest.cs rename UnitTest/{Test_ItemTypes.cs => ItemTypesServiceTests.cs} (99%) delete mode 100644 UnitTest/Test_Items.cs diff --git a/UnitTest/ItemStorageServiceTest.cs b/UnitTest/ItemStorageServiceTest.cs new file mode 100644 index 0000000..e252d99 --- /dev/null +++ b/UnitTest/ItemStorageServiceTest.cs @@ -0,0 +1,190 @@ +namespace CargoHub.Test; + +[TestClass] +public class ItemStorageServiceTest +{ + private BaseStorageService _baseStorageService; + private AppDbContext _dbContext; + + [TestInitialize] + public void Setup() + { + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: "TestDatabase") + .Options; + + _dbContext = new AppDbContext(options); + _baseStorageService = new BaseStorageService(_dbContext); + } + + [TestCleanup] + public void Cleanup() + { + _dbContext.Database.EnsureDeleted(); + _dbContext.Dispose(); + } + + [TestMethod] + public async Task TestGetRowItems() + { + Item item = TestHelper.TestItem1; + + // _baseStorageService.AddRow(item); + _dbContext.Set().Add(item); + await _dbContext.SaveChangesAsync(); + + var result = await _baseStorageService.GetRow(item.Id); + Assert.AreEqual("P000001", result.Uid); + Assert.AreEqual("XLE77785i", result.Code); + Assert.AreEqual("test item", result.Description); + Assert.AreEqual("short test", result.ShortDescription); + Assert.AreEqual("7946503676171", result.UpcCode); + Assert.AreEqual("fM-605648-lbu", result.ModelNumber); + Assert.AreEqual("qB-2533", result.CommodityCode); + Assert.AreEqual(92, result.ItemLine); + Assert.AreEqual(82, result.ItemGroup); + Assert.AreEqual(23, result.ItemType); + Assert.AreEqual(23, result.UnitPurchaseQuantity); + Assert.AreEqual(43, result.UnitOrderQuantity); + Assert.AreEqual(65, result.SupplierId); + Assert.AreEqual("SUP127", result.SupplierCode); + Assert.AreEqual("Ay-062669-VVl", result.SupplierPartNumber); + } + + [TestMethod] // checkt null if does not exst + public async Task TestGetRowNotExistItems() + { + Item result = await _baseStorageService.GetRow(999); + Assert.IsNull(result); + } + + [TestMethod] + public async Task TestGetAllItems() + { + Item item1 = TestHelper.TestItem1; + Item item2 = TestHelper.TestItem2; + + _dbContext.Items.AddRange(new List + { + item1, item2 + }); + await _dbContext.SaveChangesAsync(); + + var result = await _baseStorageService.GetAllRows(); + + Assert.AreEqual(2, result.Count); + } + + [TestMethod] + public async Task TestPostItem() + { + Item newItem = TestHelper.TestItem1; + var result = await _baseStorageService.AddRow(newItem); + + Assert.IsNotNull(result); + } + + [TestMethod] + public async Task TestPostNullItem() + { + var result = await _baseStorageService.AddRow(null); + Assert.IsNull(result); + } + + [TestMethod] + public async Task TestPutItem() + { + // Arrange + Item item = TestHelper.TestItem1; + await _baseStorageService.AddRow(item); // Gebruik de service om data toe te voegen + + Item updatedItem = TestHelper.TestUpdatedItem; + updatedItem.Id = item.Id; // Zorg dat het juiste ID wordt ingesteld + + // Act + var result = await _baseStorageService.UpdateRow(item.Id, updatedItem); + Assert.IsTrue(result); + + var updated = await _baseStorageService.GetRow(item.Id); // Haal het geüpdatete record op + Assert.AreEqual("P000001", updated.Uid); + Assert.AreEqual("XLE77785i", updated.Code); + Assert.AreEqual("test Updated", updated.Description); + Assert.AreEqual("short Updated", updated.ShortDescription); + Assert.AreEqual("7946503676171", updated.UpcCode); + Assert.AreEqual("fM-605648-lbu", updated.ModelNumber); + Assert.AreEqual("qB-2533", updated.CommodityCode); + Assert.AreEqual(92, updated.ItemLine); + Assert.AreEqual(82, updated.ItemGroup); + Assert.AreEqual(23, updated.ItemType); + Assert.AreEqual(23, updated.UnitPurchaseQuantity); + Assert.AreEqual(43, updated.UnitOrderQuantity); + Assert.AreEqual(65, updated.SupplierId); + Assert.AreEqual("SUP127", updated.SupplierCode); + Assert.AreEqual("Ay-062669-VVl", updated.SupplierPartNumber); + } + + [TestMethod] + public async Task TestPutNotExist() + { + Item updatedItem = TestHelper.TestUpdatedItem; + var result = await _baseStorageService.UpdateRow(999, updatedItem); + Assert.IsFalse(result); + } + + [TestMethod] + public async Task TestDeleteRow() + { + // Arrange + Item deleteItem = TestHelper.TestItem1; + + var addedId = await _baseStorageService.AddRow(deleteItem); + Assert.IsNotNull(addedId); + deleteItem.Id = (int)addedId; + + var result = await _baseStorageService.DeleteRow(deleteItem.Id); + + Assert.IsTrue(result); + } +} + +// [TestMethod] +// public async Task TestGetAllItems() +// { + +// } + +// [TestMethod] +// public async Task TestPostItems() +// { + +// } + +// [TestMethod] +// public async Task TestPostRowNotExistItems() +// { + +// } + +// [TestMethod] +// public async Task TestPutItems() +// { + +// } + +// [TestMethod] +// public async Task TestPutNotExistItems() +// { + +// } + +// [TestMethod] +// public async Task TestDeleteRowItems() +// { + +// } + +// [TestMethod] +// public async Task TestDeleteRowNotExistItems() +// { + +// } diff --git a/UnitTest/Test_ItemTypes.cs b/UnitTest/ItemTypesServiceTests.cs similarity index 99% rename from UnitTest/Test_ItemTypes.cs rename to UnitTest/ItemTypesServiceTests.cs index 293fbb4..ced934b 100644 --- a/UnitTest/Test_ItemTypes.cs +++ b/UnitTest/ItemTypesServiceTests.cs @@ -1,7 +1,7 @@ namespace CargoHub.Test; [TestClass] -public class ItemTypeServiceTests +public class ItemTypesServiceTests { private BaseStorageService _baseStorageService; private AppDbContext _dbContext; diff --git a/UnitTest/Test_Items.cs b/UnitTest/Test_Items.cs deleted file mode 100644 index 5ca0c84..0000000 --- a/UnitTest/Test_Items.cs +++ /dev/null @@ -1,170 +0,0 @@ -using CargoHub.Test; - -namespace CargoHub.Tests -{ - [TestClass] - public class ItemStorageServiceTest - { - private BaseStorageService _baseStorageService; - private AppDbContext _dbContext; - - [TestInitialize] - public void Setup() - { - var options = new DbContextOptionsBuilder() - .UseInMemoryDatabase(databaseName: "TestDatabase") - .Options; - - _dbContext = new AppDbContext(options); - _baseStorageService = new BaseStorageService(_dbContext); - } - - [TestCleanup] - public void Cleanup() - { - _dbContext.Database.EnsureDeleted(); - _dbContext.Dispose(); - } - - [TestMethod] - public async Task TestGetRowItems() - { - Item item = TestHelper.TestItem1; - - // _baseStorageService.AddRow(item); - _dbContext.Set().Add(item); - await _dbContext.SaveChangesAsync(); - - var result = await _baseStorageService.GetRow(item.Id); - Assert.AreEqual("P000001", result.Uid); - Assert.AreEqual("XLE77785i", result.Code); - Assert.AreEqual("test item", result.Description); - Assert.AreEqual("short test", result.ShortDescription); - Assert.AreEqual("7946503676171", result.UpcCode); - Assert.AreEqual("fM-605648-lbu", result.ModelNumber); - Assert.AreEqual("qB-2533", result.CommodityCode); - Assert.AreEqual(92, result.ItemLine); - Assert.AreEqual(82, result.ItemGroup); - Assert.AreEqual(23, result.ItemType); - Assert.AreEqual(23, result.UnitPurchaseQuantity); - Assert.AreEqual(43, result.UnitOrderQuantity); - Assert.AreEqual(65, result.SupplierId); - Assert.AreEqual("SUP127", result.SupplierCode); - Assert.AreEqual("Ay-062669-VVl", result.SupplierPartNumber); - } - - [TestMethod] // checkt null if does not exst - public async Task TestGetRowNotExistItems() - { - Item result = await _baseStorageService.GetRow(999); - Assert.IsNull(result); - } - - [TestMethod] - public async Task TestGetAllItems() - { - Item item1 = TestHelper.TestItem1; - Item item2 = TestHelper.TestItem2; - - _dbContext.Items.AddRange(new List - { - item1, item2 - }); - await _dbContext.SaveChangesAsync(); - - var result = await _baseStorageService.GetAllRows(); - - Assert.AreEqual(2, result.Count); - } - - [TestMethod] - public async Task TestPostItem() - { - Item newItem = TestHelper.TestItem1; - var result = await _baseStorageService.AddRow(newItem); - - Assert.IsNotNull(result); - } - - [TestMethod] - public async Task TestPostNullItem() - { - var result = await _baseStorageService.AddRow(null); - Assert.IsNull(result); - } - - [TestMethod] - public async Task TestPutItem() - { - // Arrange - Item item = TestHelper.TestItem1; - await _baseStorageService.AddRow(item); // Gebruik de service om data toe te voegen - - Item updatedItem = TestHelper.TestUpdatedItem; - updatedItem.Id = item.Id; // Zorg dat het juiste ID wordt ingesteld - - // Act - var result = await _baseStorageService.UpdateRow(item.Id, updatedItem); - Assert.IsTrue(result); - - var updated = await _baseStorageService.GetRow(item.Id); // Haal het geüpdatete record op - Assert.AreEqual("P000001", updated.Uid); - Assert.AreEqual("XLE77785i", updated.Code); - Assert.AreEqual("test Updated", updated.Description); - Assert.AreEqual("short Updated", updated.ShortDescription); - Assert.AreEqual("7946503676171", updated.UpcCode); - Assert.AreEqual("fM-605648-lbu", updated.ModelNumber); - Assert.AreEqual("qB-2533", updated.CommodityCode); - Assert.AreEqual(92, updated.ItemLine); - Assert.AreEqual(82, updated.ItemGroup); - Assert.AreEqual(23, updated.ItemType); - Assert.AreEqual(23, updated.UnitPurchaseQuantity); - Assert.AreEqual(43, updated.UnitOrderQuantity); - Assert.AreEqual(65, updated.SupplierId); - Assert.AreEqual("SUP127", updated.SupplierCode); - Assert.AreEqual("Ay-062669-VVl", updated.SupplierPartNumber); - } - - } -} -// [TestMethod] -// public async Task TestGetAllItems() -// { - -// } - -// [TestMethod] -// public async Task TestPostItems() -// { - -// } - -// [TestMethod] -// public async Task TestPostRowNotExistItems() -// { - -// } - -// [TestMethod] -// public async Task TestPutItems() -// { - -// } - -// [TestMethod] -// public async Task TestPutNotExistItems() -// { - -// } - -// [TestMethod] -// public async Task TestDeleteRowItems() -// { - -// } - -// [TestMethod] -// public async Task TestDeleteRowNotExistItems() -// { - -// } From 7ee08de21d5085414427d3873008fefffab8a247 Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Fri, 17 Jan 2025 17:28:05 +0100 Subject: [PATCH 15/35] Unittest Items TestDeleteRowNotExist kijkt wat er gebeurt wanneer je iets verwijderd dat niet bestaat --- UnitTest/ItemStorageServiceTest.cs | 49 +++++------------------------- 1 file changed, 7 insertions(+), 42 deletions(-) diff --git a/UnitTest/ItemStorageServiceTest.cs b/UnitTest/ItemStorageServiceTest.cs index e252d99..d02e9da 100644 --- a/UnitTest/ItemStorageServiceTest.cs +++ b/UnitTest/ItemStorageServiceTest.cs @@ -145,46 +145,11 @@ public async Task TestDeleteRow() Assert.IsTrue(result); } -} -// [TestMethod] -// public async Task TestGetAllItems() -// { - -// } - -// [TestMethod] -// public async Task TestPostItems() -// { - -// } - -// [TestMethod] -// public async Task TestPostRowNotExistItems() -// { - -// } - -// [TestMethod] -// public async Task TestPutItems() -// { - -// } - -// [TestMethod] -// public async Task TestPutNotExistItems() -// { - -// } - -// [TestMethod] -// public async Task TestDeleteRowItems() -// { - -// } - -// [TestMethod] -// public async Task TestDeleteRowNotExistItems() -// { - -// } + [TestMethod] + public async Task TestDeleteRowNotExist() + { + var item = await _baseStorageService.DeleteRow(999); + Assert.IsFalse(item); + } +} \ No newline at end of file From 5423331bb6dc7a5890a197ff3570d0b0665d36ef Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Fri, 17 Jan 2025 18:02:43 +0100 Subject: [PATCH 16/35] Items validation ItemsStorage service addrows aangepast ItemsController postitems aangepast Storage heeft een functie gekregen ValidateItems --- CargoHub/Controllers/ItemsController.cs | 15 +++++++++++---- CargoHub/Services/ItemStorageService.cs | 19 ++++++++++++++++++- Tests/test_item_groups.py | 2 +- 3 files changed, 30 insertions(+), 6 deletions(-) diff --git a/CargoHub/Controllers/ItemsController.cs b/CargoHub/Controllers/ItemsController.cs index 6e64308..c1f237e 100644 --- a/CargoHub/Controllers/ItemsController.cs +++ b/CargoHub/Controllers/ItemsController.cs @@ -5,7 +5,7 @@ namespace CargoHub.Controllers { - [Route("api/v2/[Controller]")] + [Route("api/v2/[Controller]")] public class ItemsController(ItemStorageService storage, InventoryStorageService inventoryStorageService, ErrorHandler error) : BaseController(storage, error) { public override async Task PostRow([FromBody] Item row) @@ -13,11 +13,18 @@ public override async Task PostRow([FromBody] Item row) if (row == null) return error.CantBeNull(base.Name); - var rowId = await storage.AddRowUid(row); - return CreatedAtAction(nameof(GetRow), new { id = rowId }, rowId); + try + { + var rowId = await storage.AddRowUid(row); + return CreatedAtAction(nameof(GetRow), new { id = rowId }, rowId); + } + catch (InvalidOperationException ex) + { + return BadRequest(ex.Message); + } } - + [HttpGet("{itemId}/inventory")] public async Task GetInventoriesForItem(string itemId) { diff --git a/CargoHub/Services/ItemStorageService.cs b/CargoHub/Services/ItemStorageService.cs index 8ffdf15..8444b56 100644 --- a/CargoHub/Services/ItemStorageService.cs +++ b/CargoHub/Services/ItemStorageService.cs @@ -20,12 +20,19 @@ private static string IdToUid(int id) public async Task AddRowUid(T row) where T : Item { + // Valideer de item IDs + var isValid = await ValidateItems(row.ItemType, row.ItemGroup, row.ItemLine); + if (!isValid) + { + throw new InvalidOperationException("Invalid item type, group, or line."); + } + row.Id = appDbContext.Set().Any() ? appDbContext.Set().Max(_ => _.Id) + 1 : 1; row.Uid = IdToUid(row.Id); if (await base.AddRow(row) is null) return null; - + return row.Uid; } @@ -65,5 +72,15 @@ public async Task> GetItemsforSupplier(int supplierId) return items; } + + public async Task ValidateItems(int itemTypeId, int itemGroupId, int itemLineId) + { + bool isItemTypeValid = await appDbContext.ItemTypes.AnyAsync(it => it.Id == itemTypeId); + bool isItemGroupValid = await appDbContext.ItemGroups.AnyAsync(ig => ig.Id == itemGroupId); + bool isItemLineValid = await appDbContext.ItemLines.AnyAsync(il => il.Id == itemLineId); + + // Return true only if all validations pass + return isItemTypeValid && isItemGroupValid && isItemLineValid; + } } } \ No newline at end of file diff --git a/Tests/test_item_groups.py b/Tests/test_item_groups.py index 5ac485d..de41315 100644 --- a/Tests/test_item_groups.py +++ b/Tests/test_item_groups.py @@ -63,5 +63,5 @@ def test_put(): generated_id = match.group() # modify the added item group put_response = requests.put( - BASE_URL + f"/{generated_id}", headers=HEADERS, json=UPDATED_ITEM_GROUP ) + BASE_URL + f"/{generated_id}", headers=HEADERS, json=UPDATED_ITEM_GROUP) assert put_response.status_code == 200 From 8398979e2f8f1a01087828e26291822a701283a8 Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Sat, 18 Jan 2025 18:01:34 +0100 Subject: [PATCH 17/35] ItemStorageService unittest 1.0 Testaddrowuid aangemaakt hierword getest of een item kan worden toegevoegd en of deze uid word aangemaakt op de manier zoals het bij de controller staat. --- ...ServiceTest.cs => BaseItemStorageTests.cs} | 2 +- UnitTest/ItemStorageTests.cs | 45 +++++++++++++++++++ UnitTest/TestHelper.cs | 25 +++++++++-- 3 files changed, 68 insertions(+), 4 deletions(-) rename UnitTest/{ItemStorageServiceTest.cs => BaseItemStorageTests.cs} (99%) create mode 100644 UnitTest/ItemStorageTests.cs diff --git a/UnitTest/ItemStorageServiceTest.cs b/UnitTest/BaseItemStorageTests.cs similarity index 99% rename from UnitTest/ItemStorageServiceTest.cs rename to UnitTest/BaseItemStorageTests.cs index d02e9da..ef4cd15 100644 --- a/UnitTest/ItemStorageServiceTest.cs +++ b/UnitTest/BaseItemStorageTests.cs @@ -1,7 +1,7 @@ namespace CargoHub.Test; [TestClass] -public class ItemStorageServiceTest +public class BaseItemStorageTests { private BaseStorageService _baseStorageService; private AppDbContext _dbContext; diff --git a/UnitTest/ItemStorageTests.cs b/UnitTest/ItemStorageTests.cs new file mode 100644 index 0000000..2d6915c --- /dev/null +++ b/UnitTest/ItemStorageTests.cs @@ -0,0 +1,45 @@ +namespace CargoHub.Test; + +[TestClass] +public class ItemStorageServiceTests +{ + private ItemStorageService _itemStorageService; + private AppDbContext _dbContext; + + [TestInitialize] + public void Setup() + { + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: "TestDatabase") + .Options; + + _dbContext = new AppDbContext(options); + _itemStorageService = new ItemStorageService(_dbContext); + } + + [TestCleanup] + public void Cleanup() + { + _dbContext.Database.EnsureDeleted(); + _dbContext.Dispose(); + } + + [TestMethod] + public async Task TestAddRowUid() + { + // Arrange + Item item = TestHelper.TestItem1; + + await _dbContext.ItemTypes.AddAsync(TestHelper.TestItemType1WithId); + await _dbContext.ItemGroups.AddAsync(TestHelper.TestItemGroup1WithId); + await _dbContext.ItemLines.AddAsync(TestHelper.TestItemLine1WithId); + await _dbContext.SaveChangesAsync(); + + // Act + var uid = await _itemStorageService.AddRowUid(item); + + // Assert + Assert.IsNotNull(uid); + Assert.AreEqual("P000001", uid); + } +} diff --git a/UnitTest/TestHelper.cs b/UnitTest/TestHelper.cs index 0a0e383..fad98b3 100644 --- a/UnitTest/TestHelper.cs +++ b/UnitTest/TestHelper.cs @@ -104,9 +104,9 @@ public static ItemLine CreateRandomItemLine() UpcCode = "7946503676171", ModelNumber = "fM-605648-lbu", CommodityCode = "qB-2533", - ItemLine = 92, - ItemGroup = 82, - ItemType = 23, + ItemLine = 1, + ItemGroup = 1, + ItemType = 1, UnitPurchaseQuantity = 23, UnitOrderQuantity = 43, PackOrderQuantity = 65, @@ -154,5 +154,24 @@ public static ItemLine CreateRandomItemLine() SupplierCode = "SUP127", SupplierPartNumber = "Ay-062669-VVl", }; + public static ItemType TestItemType1WithId = new ItemType + { + Id = 1, + Name = "Test Name", + Description = "Test Description" + }; + + public static ItemGroup TestItemGroup1WithId = new ItemGroup + { + Id = 1, + Name = "Test Group", + Description = "Group Description" + }; + public static ItemLine TestItemLine1WithId = new ItemLine + { + Id = 1, + Name = "Test Line", + Description = "Line Description" + }; } \ No newline at end of file From 0bb33be3ec69bbb7ba87ffdc0602e6fd1a89e113 Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Sat, 18 Jan 2025 18:17:08 +0100 Subject: [PATCH 18/35] ItemStorageTests TestAddRowUid 1.1 Omdat ik de IdToUid niet direct kan testen omdat deze een private method is. heb ik in deze test 2 items aangemaakt er zeker van te zijn de de numering van de uids goed gaan --- UnitTest/ItemStorageTests.cs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/UnitTest/ItemStorageTests.cs b/UnitTest/ItemStorageTests.cs index 2d6915c..88941fb 100644 --- a/UnitTest/ItemStorageTests.cs +++ b/UnitTest/ItemStorageTests.cs @@ -28,7 +28,8 @@ public void Cleanup() public async Task TestAddRowUid() { // Arrange - Item item = TestHelper.TestItem1; + Item firstItem = TestHelper.TestItem1; + Item secondItem = TestHelper.TestItem2; await _dbContext.ItemTypes.AddAsync(TestHelper.TestItemType1WithId); await _dbContext.ItemGroups.AddAsync(TestHelper.TestItemGroup1WithId); @@ -36,10 +37,13 @@ public async Task TestAddRowUid() await _dbContext.SaveChangesAsync(); // Act - var uid = await _itemStorageService.AddRowUid(item); + var firstUid = await _itemStorageService.AddRowUid(firstItem); + var secondUid = await _itemStorageService.AddRowUid(secondItem); // Assert - Assert.IsNotNull(uid); - Assert.AreEqual("P000001", uid); + Assert.IsNotNull(firstUid); + Assert.IsNotNull(secondUid); + Assert.AreEqual("P000001", firstUid); + Assert.AreEqual("P000002", secondUid); } } From 2b080431fa005edcd17012dced0ce860acd0f250 Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Sat, 18 Jan 2025 19:12:58 +0100 Subject: [PATCH 19/35] Unittest ItemServiceTests de tests runnen niet in een keer doordat ik de zelfde variabelen uit de testhelper gebruikte en door dat deze testen tegelijkertijd worden gerunt gaat het fout --- UnitTest/ItemTypesServiceTests.cs | 4 ++-- UnitTest/TestHelper.cs | 12 ++++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/UnitTest/ItemTypesServiceTests.cs b/UnitTest/ItemTypesServiceTests.cs index ced934b..b77309b 100644 --- a/UnitTest/ItemTypesServiceTests.cs +++ b/UnitTest/ItemTypesServiceTests.cs @@ -53,8 +53,8 @@ public async Task TestGetRowNotExist() [TestMethod] public async Task TestGetAllItemTypes() { - ItemType itemType = TestHelper.TestItemType1; - ItemType itemType2 = TestHelper.TestItemType2; + ItemType itemType = TestHelper.TestItemType1Getall; + ItemType itemType2 = TestHelper.TestItemType2Getall; _dbContext.ItemTypes.AddRange(new List { diff --git a/UnitTest/TestHelper.cs b/UnitTest/TestHelper.cs index fad98b3..a945bbb 100644 --- a/UnitTest/TestHelper.cs +++ b/UnitTest/TestHelper.cs @@ -89,6 +89,18 @@ public static ItemLine CreateRandomItemLine() Description = "Test Description2" }; + public static ItemType TestItemType1Getall = new ItemType + { + Name = "Test Name", + Description = "Test Description" + }; + + public static ItemType TestItemType2Getall = new ItemType + { + Name = "Test Name2", + Description = "Test Description2" + }; + public static ItemType TestupdateItemType = new ItemType { Name = "updated Name", From 4a89ac56954782bf18a291a0e318f8bb4e1fee4d Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Sat, 18 Jan 2025 20:58:44 +0100 Subject: [PATCH 20/35] Before merge met sidney branch --- CargoHub/Services/ItemStorageService.cs | 1 - UnitTest/BaseItemStorageTests.cs | 6 +++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/CargoHub/Services/ItemStorageService.cs b/CargoHub/Services/ItemStorageService.cs index 8444b56..cf39681 100644 --- a/CargoHub/Services/ItemStorageService.cs +++ b/CargoHub/Services/ItemStorageService.cs @@ -20,7 +20,6 @@ private static string IdToUid(int id) public async Task AddRowUid(T row) where T : Item { - // Valideer de item IDs var isValid = await ValidateItems(row.ItemType, row.ItemGroup, row.ItemLine); if (!isValid) { diff --git a/UnitTest/BaseItemStorageTests.cs b/UnitTest/BaseItemStorageTests.cs index ef4cd15..eb35652 100644 --- a/UnitTest/BaseItemStorageTests.cs +++ b/UnitTest/BaseItemStorageTests.cs @@ -41,9 +41,9 @@ public async Task TestGetRowItems() Assert.AreEqual("7946503676171", result.UpcCode); Assert.AreEqual("fM-605648-lbu", result.ModelNumber); Assert.AreEqual("qB-2533", result.CommodityCode); - Assert.AreEqual(92, result.ItemLine); - Assert.AreEqual(82, result.ItemGroup); - Assert.AreEqual(23, result.ItemType); + Assert.AreEqual(1, result.ItemLine); + Assert.AreEqual(1, result.ItemGroup); + Assert.AreEqual(1, result.ItemType); Assert.AreEqual(23, result.UnitPurchaseQuantity); Assert.AreEqual(43, result.UnitOrderQuantity); Assert.AreEqual(65, result.SupplierId); From d7a95a0ca7c4930d58d4de2eaecafffb620f3253 Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Sun, 19 Jan 2025 14:36:55 +0100 Subject: [PATCH 21/35] Items controller small change --- CargoHub/Controllers/ItemLinesController.cs | 1 - CargoHub/Controllers/ItemsController.cs | 11 ++--------- 2 files changed, 2 insertions(+), 10 deletions(-) diff --git a/CargoHub/Controllers/ItemLinesController.cs b/CargoHub/Controllers/ItemLinesController.cs index 5a4b4ce..6bd7dd0 100644 --- a/CargoHub/Controllers/ItemLinesController.cs +++ b/CargoHub/Controllers/ItemLinesController.cs @@ -16,5 +16,4 @@ public async Task GetItemsForSupplier(int itemLineId) return Ok(items); } } - } \ No newline at end of file diff --git a/CargoHub/Controllers/ItemsController.cs b/CargoHub/Controllers/ItemsController.cs index c1f237e..d444395 100644 --- a/CargoHub/Controllers/ItemsController.cs +++ b/CargoHub/Controllers/ItemsController.cs @@ -13,15 +13,8 @@ public override async Task PostRow([FromBody] Item row) if (row == null) return error.CantBeNull(base.Name); - try - { - var rowId = await storage.AddRowUid(row); - return CreatedAtAction(nameof(GetRow), new { id = rowId }, rowId); - } - catch (InvalidOperationException ex) - { - return BadRequest(ex.Message); - } + var rowId = await storage.AddRowUid(row); + return CreatedAtAction(nameof(GetRow), new { id = rowId }, rowId); } From 3c8f9d42d6d13ba73c19e60d5234d86150f3c86a Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Mon, 20 Jan 2025 10:22:05 +0100 Subject: [PATCH 22/35] GetItemsForItemLine ik zag dat deze method is aangemaakt bij de itemstorageservice, maar dat hij nog niet is toegepast in de controllers. deze heb ik nou aangemaakt en kun je nu hiermee items returnen op basis van de itemline id die ze hebben --- CargoHub/Controllers/ItemLinesController.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CargoHub/Controllers/ItemLinesController.cs b/CargoHub/Controllers/ItemLinesController.cs index 6bd7dd0..41b0edb 100644 --- a/CargoHub/Controllers/ItemLinesController.cs +++ b/CargoHub/Controllers/ItemLinesController.cs @@ -15,5 +15,13 @@ public async Task GetItemsForSupplier(int itemLineId) var items = await itemStorageService.GetItemsforSupplier(itemLineId); return Ok(items); } + + [HttpGet("itemline/{itemLineId}")] + public async Task GetItemsForItemLine(int itemLineId) + { + // Haal de items op die gekoppeld zijn aan de opgegeven itemLineId + var items = await itemStorageService.GetItemsforItemLine(itemLineId); + return Ok(items); + } } } \ No newline at end of file From 56c0729302a50c7ffb983bdd886fadb43c8cc202 Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Mon, 20 Jan 2025 10:22:49 +0100 Subject: [PATCH 23/35] GetItemsForItemLine ik zag dat deze method is aangemaakt bij de itemstorageservice, maar dat hij nog niet is toegepast in de controllers. deze heb ik nou aangemaakt en kun je nu hiermee items returnen op basis van de itemline id die ze hebben --- CargoHub/Controllers/ItemLinesController.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/CargoHub/Controllers/ItemLinesController.cs b/CargoHub/Controllers/ItemLinesController.cs index 41b0edb..9ac89d6 100644 --- a/CargoHub/Controllers/ItemLinesController.cs +++ b/CargoHub/Controllers/ItemLinesController.cs @@ -19,7 +19,6 @@ public async Task GetItemsForSupplier(int itemLineId) [HttpGet("itemline/{itemLineId}")] public async Task GetItemsForItemLine(int itemLineId) { - // Haal de items op die gekoppeld zijn aan de opgegeven itemLineId var items = await itemStorageService.GetItemsforItemLine(itemLineId); return Ok(items); } From 95956a9690f31cfb27c893253722deae7f096762 Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Mon, 20 Jan 2025 10:30:17 +0100 Subject: [PATCH 24/35] GetItemforItemLine het zelfde aangemaakt voor de ItemLine controller, en een foutmelding toegevoegd voor als je een itemline/group id invult die niet bestaat in de database --- CargoHub/Controllers/ItemGroupsController.cs | 11 +++++++++++ CargoHub/Controllers/ItemLinesController.cs | 4 ++++ 2 files changed, 15 insertions(+) diff --git a/CargoHub/Controllers/ItemGroupsController.cs b/CargoHub/Controllers/ItemGroupsController.cs index e1bd040..60afbcf 100644 --- a/CargoHub/Controllers/ItemGroupsController.cs +++ b/CargoHub/Controllers/ItemGroupsController.cs @@ -14,5 +14,16 @@ public async Task GetItemsForSupplier(int itemGroupId) var items = await itemStorageService.GetItemsforSupplier(itemGroupId); return Ok(items); } + + [HttpGet("itemgroup/{itemGroupId}")] + public async Task GetItemsforItemGroup(int itemGroupId) + { + var items = await itemStorageService.GetItemsforItemGroup(itemGroupId); + if (items == null || items.Count == 0) + { + return NotFound($"No items found for this ItemGroup ID {itemGroupId}"); + } + return Ok(items); + } } } \ No newline at end of file diff --git a/CargoHub/Controllers/ItemLinesController.cs b/CargoHub/Controllers/ItemLinesController.cs index 9ac89d6..4a9c57e 100644 --- a/CargoHub/Controllers/ItemLinesController.cs +++ b/CargoHub/Controllers/ItemLinesController.cs @@ -20,6 +20,10 @@ public async Task GetItemsForSupplier(int itemLineId) public async Task GetItemsForItemLine(int itemLineId) { var items = await itemStorageService.GetItemsforItemLine(itemLineId); + if (items == null || items.Count == 0) + { + return NotFound($"No items found for ItemLine ID {itemLineId}"); + } return Ok(items); } } From 519f12ebaf55f0db397c70bd3bf653c18bc67db6 Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Mon, 20 Jan 2025 10:32:38 +0100 Subject: [PATCH 25/35] GetItemsforItemType Nu kun je ook items getten met de id van itemtype. ook deze geeft een foutmelding als je een id invult die niet bestaat --- CargoHub/Controllers/ItemTypesController.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/CargoHub/Controllers/ItemTypesController.cs b/CargoHub/Controllers/ItemTypesController.cs index afd6fc1..c8b2a2b 100644 --- a/CargoHub/Controllers/ItemTypesController.cs +++ b/CargoHub/Controllers/ItemTypesController.cs @@ -14,5 +14,16 @@ public async Task GetItemsForSupplier(int itemTypeId) var items = await itemStorageService.GetItemsforSupplier(itemTypeId); return Ok(items); } + + [HttpGet("itemtype/{itemTypeId}")] + public async Task GetItemsforItemType(int itemTypeId) + { + var items = await itemStorageService.GetItemsforItemType(itemTypeId); + if (items == null || items.Count == 0) + { + return NotFound($"No items found for this ItemLine ID {itemTypeId}"); + } + return Ok(items); + } } } \ No newline at end of file From 79a5b4ac3819bebfaa972f41388ca449a375578c Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Mon, 20 Jan 2025 10:50:25 +0100 Subject: [PATCH 26/35] TestGetItemsForItemLine Met deze test test je de functie getitemsforitemline. hierbij word er gekeken of je daadwerkelijk de items krijgt zodra zij de itemline id hebben die jij invoert. --- CargoHub/Controllers/ItemLinesController.cs | 2 +- UnitTest/ItemStorageTests.cs | 13 +++++++ UnitTest/TestHelper.cs | 41 +++++++++++++++++++++ 3 files changed, 55 insertions(+), 1 deletion(-) diff --git a/CargoHub/Controllers/ItemLinesController.cs b/CargoHub/Controllers/ItemLinesController.cs index 4a9c57e..998668b 100644 --- a/CargoHub/Controllers/ItemLinesController.cs +++ b/CargoHub/Controllers/ItemLinesController.cs @@ -22,7 +22,7 @@ public async Task GetItemsForItemLine(int itemLineId) var items = await itemStorageService.GetItemsforItemLine(itemLineId); if (items == null || items.Count == 0) { - return NotFound($"No items found for ItemLine ID {itemLineId}"); + return NotFound($"No items found for this ItemLine ID {itemLineId}"); } return Ok(items); } diff --git a/UnitTest/ItemStorageTests.cs b/UnitTest/ItemStorageTests.cs index 88941fb..0aa58cb 100644 --- a/UnitTest/ItemStorageTests.cs +++ b/UnitTest/ItemStorageTests.cs @@ -46,4 +46,17 @@ public async Task TestAddRowUid() Assert.AreEqual("P000001", firstUid); Assert.AreEqual("P000002", secondUid); } + + [TestMethod] + public async Task TestGetItemsForItemLine() + { + await _dbContext.AddRangeAsync(TestHelper.TestGetItemLine1, TestHelper.TestGetItemLine2); + await _dbContext.SaveChangesAsync(); + + var result = await _itemStorageService.GetItemsforItemLine(1); + + Assert.IsNotNull(result); + Assert.AreEqual(2, result.Count); + Assert.IsTrue(result.All(item => item.ItemLine == 1)); + } } diff --git a/UnitTest/TestHelper.cs b/UnitTest/TestHelper.cs index a945bbb..9e06d9b 100644 --- a/UnitTest/TestHelper.cs +++ b/UnitTest/TestHelper.cs @@ -166,6 +166,47 @@ public static ItemLine CreateRandomItemLine() SupplierCode = "SUP127", SupplierPartNumber = "Ay-062669-VVl", }; + + public static Item TestGetItemLine1 = new Item + { + Uid = "P000001", + Code = "XLE77785i", + Description = "test Updated", + ShortDescription = "short Updated", + UpcCode = "7946503676171", + ModelNumber = "fM-605648-lbu", + CommodityCode = "qB-2533", + ItemLine = 1, + ItemGroup = 2, + ItemType = 2, + UnitPurchaseQuantity = 23, + UnitOrderQuantity = 43, + PackOrderQuantity = 65, + SupplierId = 65, + SupplierCode = "SUP127", + SupplierPartNumber = "Ay-062669-VVl", + }; + + public static Item TestGetItemLine2 = new Item + { + Uid = "P000002", + Code = "XLE77785i", + Description = "test Updated", + ShortDescription = "short Updated", + UpcCode = "7946503676171", + ModelNumber = "fM-605648-lbu", + CommodityCode = "qB-2533", + ItemLine = 1, + ItemGroup = 2, + ItemType = 1, + UnitPurchaseQuantity = 23, + UnitOrderQuantity = 43, + PackOrderQuantity = 65, + SupplierId = 65, + SupplierCode = "SUP127", + SupplierPartNumber = "Ay-062669-VVl", + }; + public static ItemType TestItemType1WithId = new ItemType { Id = 1, From 4ee7664c87d59ce1bf6663481217312700b69fa9 Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Mon, 20 Jan 2025 10:58:16 +0100 Subject: [PATCH 27/35] TestGetItemsForItemType Met deze test test je de functie getitemsforitemtype. hierbij word er gekeken of je daadwerkelijk de items krijgt zodra zij de itemtype id hebben die jij invoert. --- UnitTest/ItemStorageTests.cs | 15 ++++++++++++++- UnitTest/ItemTypesServiceTests.cs | 8 ++++---- UnitTest/TestHelper.cs | 8 ++++---- 3 files changed, 22 insertions(+), 9 deletions(-) diff --git a/UnitTest/ItemStorageTests.cs b/UnitTest/ItemStorageTests.cs index 0aa58cb..8badeb2 100644 --- a/UnitTest/ItemStorageTests.cs +++ b/UnitTest/ItemStorageTests.cs @@ -50,7 +50,7 @@ public async Task TestAddRowUid() [TestMethod] public async Task TestGetItemsForItemLine() { - await _dbContext.AddRangeAsync(TestHelper.TestGetItemLine1, TestHelper.TestGetItemLine2); + await _dbContext.AddRangeAsync(TestHelper.TestGetItemLTG1, TestHelper.TestGetItemLTG2); await _dbContext.SaveChangesAsync(); var result = await _itemStorageService.GetItemsforItemLine(1); @@ -59,4 +59,17 @@ public async Task TestGetItemsForItemLine() Assert.AreEqual(2, result.Count); Assert.IsTrue(result.All(item => item.ItemLine == 1)); } + + [TestMethod] + public async Task TestGetItemsForItemType() + { + await _dbContext.AddRangeAsync(TestHelper.TestGetItemLTG1, TestHelper.TestGetItemLTG2); + await _dbContext.SaveChangesAsync(); + + var result = await _itemStorageService.GetItemsforItemType(3); + + Assert.IsNotNull(result); + Assert.AreEqual(2, result.Count); + Assert.IsTrue(result.All(item => item.ItemType == 3)); + } } diff --git a/UnitTest/ItemTypesServiceTests.cs b/UnitTest/ItemTypesServiceTests.cs index b77309b..285bdf9 100644 --- a/UnitTest/ItemTypesServiceTests.cs +++ b/UnitTest/ItemTypesServiceTests.cs @@ -30,11 +30,11 @@ public async Task TestGetRowItemType() // Arrange ItemType itemType = TestHelper.TestItemType1; - _dbContext.Set().Add(itemType); // Add the test item type to the in-memory database - await _dbContext.SaveChangesAsync(); // Save changes to simulate a real database operation + _dbContext.Set().Add(itemType); + await _dbContext.SaveChangesAsync(); // Act - var result = await _baseStorageService.GetRow(itemType.Id); // Retrieve the item type by its Id + var result = await _baseStorageService.GetRow(itemType.Id); // Assert Assert.IsNotNull(result); @@ -43,7 +43,7 @@ public async Task TestGetRowItemType() } - [TestMethod] // checkt null if does not exst + [TestMethod] public async Task TestGetRowNotExist() { var result = await _baseStorageService.GetRow(999); diff --git a/UnitTest/TestHelper.cs b/UnitTest/TestHelper.cs index 9e06d9b..472dffb 100644 --- a/UnitTest/TestHelper.cs +++ b/UnitTest/TestHelper.cs @@ -167,7 +167,7 @@ public static ItemLine CreateRandomItemLine() SupplierPartNumber = "Ay-062669-VVl", }; - public static Item TestGetItemLine1 = new Item + public static Item TestGetItemLTG1 = new Item { Uid = "P000001", Code = "XLE77785i", @@ -178,7 +178,7 @@ public static ItemLine CreateRandomItemLine() CommodityCode = "qB-2533", ItemLine = 1, ItemGroup = 2, - ItemType = 2, + ItemType = 3, UnitPurchaseQuantity = 23, UnitOrderQuantity = 43, PackOrderQuantity = 65, @@ -187,7 +187,7 @@ public static ItemLine CreateRandomItemLine() SupplierPartNumber = "Ay-062669-VVl", }; - public static Item TestGetItemLine2 = new Item + public static Item TestGetItemLTG2 = new Item { Uid = "P000002", Code = "XLE77785i", @@ -198,7 +198,7 @@ public static ItemLine CreateRandomItemLine() CommodityCode = "qB-2533", ItemLine = 1, ItemGroup = 2, - ItemType = 1, + ItemType = 3, UnitPurchaseQuantity = 23, UnitOrderQuantity = 43, PackOrderQuantity = 65, From ea8837f50c4264819e30a04e6fea8a07d5e4c3a1 Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Mon, 20 Jan 2025 11:01:59 +0100 Subject: [PATCH 28/35] TestGetItemsForItemGroup Met deze test test je de functie getitemsforitemGroup. hierbij word er gekeken of je daadwerkelijk de items krijgt zodra zij de itemGroup id hebben die jij invoert. --- UnitTest/ItemStorageTests.cs | 13 +++++++++++++ UnitTest/TestHelper.cs | 6 +++--- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/UnitTest/ItemStorageTests.cs b/UnitTest/ItemStorageTests.cs index 8badeb2..ba1cce5 100644 --- a/UnitTest/ItemStorageTests.cs +++ b/UnitTest/ItemStorageTests.cs @@ -72,4 +72,17 @@ public async Task TestGetItemsForItemType() Assert.AreEqual(2, result.Count); Assert.IsTrue(result.All(item => item.ItemType == 3)); } + + [TestMethod] + public async Task TestGetItemsForItemGroup() + { + await _dbContext.AddRangeAsync(TestHelper.TestGetItemLTG1, TestHelper.TestGetItemLTG2); + await _dbContext.SaveChangesAsync(); + + var result = await _itemStorageService.GetItemsforItemGroup(2); + + Assert.IsNotNull(result); + Assert.AreEqual(2, result.Count); + Assert.IsTrue(result.All(item => item.ItemGroup == 2)); + } } diff --git a/UnitTest/TestHelper.cs b/UnitTest/TestHelper.cs index 472dffb..ef01d53 100644 --- a/UnitTest/TestHelper.cs +++ b/UnitTest/TestHelper.cs @@ -136,9 +136,9 @@ public static ItemLine CreateRandomItemLine() UpcCode = "7946503676171", ModelNumber = "fM-605648-lbu", CommodityCode = "qB-2533", - ItemLine = 92, - ItemGroup = 82, - ItemType = 23, + ItemLine = 1, + ItemGroup = 1, + ItemType = 1, UnitPurchaseQuantity = 23, UnitOrderQuantity = 43, PackOrderQuantity = 65, From 0334435d21c997b8e12c2523b224135bb2a35f29 Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Mon, 20 Jan 2025 11:52:25 +0100 Subject: [PATCH 29/35] Validation tests Hierbij word er naar verschillende scenarios gekeken wat ergebeurt als je een verkeerde id meegeeft voor itemtype/line/group --- CargoHub/Services/ItemStorageService.cs | 1 - UnitTest/ItemStorageTests.cs | 64 +++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 1 deletion(-) diff --git a/CargoHub/Services/ItemStorageService.cs b/CargoHub/Services/ItemStorageService.cs index cf39681..bef3e30 100644 --- a/CargoHub/Services/ItemStorageService.cs +++ b/CargoHub/Services/ItemStorageService.cs @@ -78,7 +78,6 @@ public async Task ValidateItems(int itemTypeId, int itemGroupId, int itemL bool isItemGroupValid = await appDbContext.ItemGroups.AnyAsync(ig => ig.Id == itemGroupId); bool isItemLineValid = await appDbContext.ItemLines.AnyAsync(il => il.Id == itemLineId); - // Return true only if all validations pass return isItemTypeValid && isItemGroupValid && isItemLineValid; } } diff --git a/UnitTest/ItemStorageTests.cs b/UnitTest/ItemStorageTests.cs index ba1cce5..30e89d6 100644 --- a/UnitTest/ItemStorageTests.cs +++ b/UnitTest/ItemStorageTests.cs @@ -85,4 +85,68 @@ public async Task TestGetItemsForItemGroup() Assert.AreEqual(2, result.Count); Assert.IsTrue(result.All(item => item.ItemGroup == 2)); } + + [TestMethod] + public async Task TestValidateItems_AllValid() + { + // Arrange + await _dbContext.ItemTypes.AddAsync(TestHelper.TestItemType1WithId); + await _dbContext.ItemGroups.AddAsync(TestHelper.TestItemGroup1WithId); + await _dbContext.ItemLines.AddAsync(TestHelper.TestItemLine1WithId); + await _dbContext.SaveChangesAsync(); + + // Act + var isValid = await _itemStorageService.ValidateItems(1, 1, 1); + + // Assert + Assert.IsTrue(isValid, "Validation should pass when all IDs are valid."); + } + + [TestMethod] + public async Task ValidateItems_ItemType_False() + { + // Arrange + await _dbContext.ItemTypes.AddAsync(TestHelper.TestItemType1WithId); + await _dbContext.ItemGroups.AddAsync(TestHelper.TestItemGroup1WithId); + await _dbContext.ItemLines.AddAsync(TestHelper.TestItemLine1WithId); + await _dbContext.SaveChangesAsync(); + + // Act + var isNotValid = await _itemStorageService.ValidateItems(2, 1, 1); + + // Assert + Assert.IsFalse(isNotValid); + } + + [TestMethod] + public async Task ValidateItems_ItemLine_False() + { + // Arrange + await _dbContext.ItemTypes.AddAsync(TestHelper.TestItemType1WithId); + await _dbContext.ItemGroups.AddAsync(TestHelper.TestItemGroup1WithId); + await _dbContext.ItemLines.AddAsync(TestHelper.TestItemLine1WithId); + await _dbContext.SaveChangesAsync(); + + // Act + var isNotValid = await _itemStorageService.ValidateItems(1, 1, 2); + + // Assert + Assert.IsFalse(isNotValid); + } + + [TestMethod] + public async Task ValidateItems_ItemGroup_False() + { + // Arrange + await _dbContext.ItemTypes.AddAsync(TestHelper.TestItemType1WithId); + await _dbContext.ItemGroups.AddAsync(TestHelper.TestItemGroup1WithId); + await _dbContext.ItemLines.AddAsync(TestHelper.TestItemLine1WithId); + await _dbContext.SaveChangesAsync(); + + // Act + var isNotValid = await _itemStorageService.ValidateItems(1, 2, 1); + + // Assert + Assert.IsFalse(isNotValid); + } } From 5541cd37b3a0ab6755e4f751ff5f4776570f74e8 Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Mon, 20 Jan 2025 11:58:03 +0100 Subject: [PATCH 30/35] Validation tests 1.1 Verbeterde versie. nu worden ze allemaal getest in een testmethod --- UnitTest/ItemStorageTests.cs | 41 +++++++----------------------------- 1 file changed, 8 insertions(+), 33 deletions(-) diff --git a/UnitTest/ItemStorageTests.cs b/UnitTest/ItemStorageTests.cs index 30e89d6..c4028e5 100644 --- a/UnitTest/ItemStorageTests.cs +++ b/UnitTest/ItemStorageTests.cs @@ -99,27 +99,11 @@ public async Task TestValidateItems_AllValid() var isValid = await _itemStorageService.ValidateItems(1, 1, 1); // Assert - Assert.IsTrue(isValid, "Validation should pass when all IDs are valid."); + Assert.IsTrue(isValid); } [TestMethod] - public async Task ValidateItems_ItemType_False() - { - // Arrange - await _dbContext.ItemTypes.AddAsync(TestHelper.TestItemType1WithId); - await _dbContext.ItemGroups.AddAsync(TestHelper.TestItemGroup1WithId); - await _dbContext.ItemLines.AddAsync(TestHelper.TestItemLine1WithId); - await _dbContext.SaveChangesAsync(); - - // Act - var isNotValid = await _itemStorageService.ValidateItems(2, 1, 1); - - // Assert - Assert.IsFalse(isNotValid); - } - - [TestMethod] - public async Task ValidateItems_ItemLine_False() + public async Task ValidateItems_False() { // Arrange await _dbContext.ItemTypes.AddAsync(TestHelper.TestItemType1WithId); @@ -129,24 +113,15 @@ public async Task ValidateItems_ItemLine_False() // Act var isNotValid = await _itemStorageService.ValidateItems(1, 1, 2); + var isNotValid2 = await _itemStorageService.ValidateItems(1, 2, 1); + var isNotValid3 = await _itemStorageService.ValidateItems(2, 1, 1); + var isNotValid4 = await _itemStorageService.ValidateItems(2, 2, 2); - // Assert - Assert.IsFalse(isNotValid); - } - - [TestMethod] - public async Task ValidateItems_ItemGroup_False() - { - // Arrange - await _dbContext.ItemTypes.AddAsync(TestHelper.TestItemType1WithId); - await _dbContext.ItemGroups.AddAsync(TestHelper.TestItemGroup1WithId); - await _dbContext.ItemLines.AddAsync(TestHelper.TestItemLine1WithId); - await _dbContext.SaveChangesAsync(); - - // Act - var isNotValid = await _itemStorageService.ValidateItems(1, 2, 1); // Assert Assert.IsFalse(isNotValid); + Assert.IsFalse(isNotValid2); + Assert.IsFalse(isNotValid3); + Assert.IsFalse(isNotValid4); } } From 9603969405adaa99df60c8d055d29c8fb369a385 Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Mon, 20 Jan 2025 12:02:35 +0100 Subject: [PATCH 31/35] Validation tests 1.2 Verbeterde versie van de vorige code. validation tests worden nu allemaal uitgevoerd uit een testmethod --- UnitTest/ItemStorageTests.cs | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/UnitTest/ItemStorageTests.cs b/UnitTest/ItemStorageTests.cs index c4028e5..792a5e6 100644 --- a/UnitTest/ItemStorageTests.cs +++ b/UnitTest/ItemStorageTests.cs @@ -105,23 +105,14 @@ public async Task TestValidateItems_AllValid() [TestMethod] public async Task ValidateItems_False() { - // Arrange await _dbContext.ItemTypes.AddAsync(TestHelper.TestItemType1WithId); await _dbContext.ItemGroups.AddAsync(TestHelper.TestItemGroup1WithId); await _dbContext.ItemLines.AddAsync(TestHelper.TestItemLine1WithId); await _dbContext.SaveChangesAsync(); - // Act - var isNotValid = await _itemStorageService.ValidateItems(1, 1, 2); - var isNotValid2 = await _itemStorageService.ValidateItems(1, 2, 1); - var isNotValid3 = await _itemStorageService.ValidateItems(2, 1, 1); - var isNotValid4 = await _itemStorageService.ValidateItems(2, 2, 2); - - - // Assert - Assert.IsFalse(isNotValid); - Assert.IsFalse(isNotValid2); - Assert.IsFalse(isNotValid3); - Assert.IsFalse(isNotValid4); + Assert.IsFalse(await _itemStorageService.ValidateItems(1, 1, 2)); //itemLine + Assert.IsFalse(await _itemStorageService.ValidateItems(1, 2, 1)); //itemGroup + Assert.IsFalse(await _itemStorageService.ValidateItems(2, 1, 1)); //itemType + Assert.IsFalse(await _itemStorageService.ValidateItems(2, 2, 2)); //All fail } } From 3f3e0939736c1085944d55291547372e30b10df0 Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Mon, 20 Jan 2025 17:13:40 +0100 Subject: [PATCH 32/35] Unittesten De testen die ik had geschreven voor de merg doen sommige niet die ga ik hierbij proberen op te lossen --- CargoHub.sln | 20 ++--- CargoHub/Controllers/ItemsController.cs | 2 +- UnitTest/BaseItemStorageTests.cs | 20 ++--- UnitTest/ItemTypesServiceTests.cs | 102 +++++++++++++++++------- UnitTest/TestHelper.cs | 9 +++ 5 files changed, 102 insertions(+), 51 deletions(-) diff --git a/CargoHub.sln b/CargoHub.sln index e04dc92..5b429ad 100644 --- a/CargoHub.sln +++ b/CargoHub.sln @@ -3,9 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.31903.59 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CargoHub", "CargoHub\CargoHub.csproj", "{707A660E-C336-4B57-8EB1-E5C95CD99244}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CargoHub", "CargoHub\CargoHub.csproj", "{D287ADFD-E9BA-4787-9B63-F0EAACE63FE9}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CargoHub.Tests", "UnitTest\CargoHub.Tests.csproj", "{4A32A713-E27F-4CB7-BDB7-4157A68C2A71}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CargoHub.Test", "UnitTest\CargoHub.Test.csproj", "{537592E6-925A-45C2-AF47-B1F001267F77}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -16,13 +16,13 @@ Global HideSolutionNode = FALSE EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {707A660E-C336-4B57-8EB1-E5C95CD99244}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {707A660E-C336-4B57-8EB1-E5C95CD99244}.Debug|Any CPU.Build.0 = Debug|Any CPU - {707A660E-C336-4B57-8EB1-E5C95CD99244}.Release|Any CPU.ActiveCfg = Release|Any CPU - {707A660E-C336-4B57-8EB1-E5C95CD99244}.Release|Any CPU.Build.0 = Release|Any CPU - {4A32A713-E27F-4CB7-BDB7-4157A68C2A71}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {4A32A713-E27F-4CB7-BDB7-4157A68C2A71}.Debug|Any CPU.Build.0 = Debug|Any CPU - {4A32A713-E27F-4CB7-BDB7-4157A68C2A71}.Release|Any CPU.ActiveCfg = Release|Any CPU - {4A32A713-E27F-4CB7-BDB7-4157A68C2A71}.Release|Any CPU.Build.0 = Release|Any CPU + {D287ADFD-E9BA-4787-9B63-F0EAACE63FE9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D287ADFD-E9BA-4787-9B63-F0EAACE63FE9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D287ADFD-E9BA-4787-9B63-F0EAACE63FE9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D287ADFD-E9BA-4787-9B63-F0EAACE63FE9}.Release|Any CPU.Build.0 = Release|Any CPU + {537592E6-925A-45C2-AF47-B1F001267F77}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {537592E6-925A-45C2-AF47-B1F001267F77}.Debug|Any CPU.Build.0 = Debug|Any CPU + {537592E6-925A-45C2-AF47-B1F001267F77}.Release|Any CPU.ActiveCfg = Release|Any CPU + {537592E6-925A-45C2-AF47-B1F001267F77}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection EndGlobal diff --git a/CargoHub/Controllers/ItemsController.cs b/CargoHub/Controllers/ItemsController.cs index de4490b..b02cd2f 100644 --- a/CargoHub/Controllers/ItemsController.cs +++ b/CargoHub/Controllers/ItemsController.cs @@ -18,7 +18,7 @@ public override async Task PostRow([FromBody] Item row) var rowId = await storage.AddRowUid(row); return CreatedAtAction(nameof(GetRow), new { id = rowId }, rowId); } - + return error.ModelInvalid(base.Name, ModelState); } diff --git a/UnitTest/BaseItemStorageTests.cs b/UnitTest/BaseItemStorageTests.cs index eb35652..874c05c 100644 --- a/UnitTest/BaseItemStorageTests.cs +++ b/UnitTest/BaseItemStorageTests.cs @@ -3,7 +3,7 @@ namespace CargoHub.Test; [TestClass] public class BaseItemStorageTests { - private BaseStorageService _baseStorageService; + private BaseStorageService _baseStorageService; private AppDbContext _dbContext; [TestInitialize] @@ -14,7 +14,7 @@ public void Setup() .Options; _dbContext = new AppDbContext(options); - _baseStorageService = new BaseStorageService(_dbContext); + _baseStorageService = new BaseStorageService(_dbContext); } [TestCleanup] @@ -33,7 +33,7 @@ public async Task TestGetRowItems() _dbContext.Set().Add(item); await _dbContext.SaveChangesAsync(); - var result = await _baseStorageService.GetRow(item.Id); + var result = await _baseStorageService.GetRow(item.Id); Assert.AreEqual("P000001", result.Uid); Assert.AreEqual("XLE77785i", result.Code); Assert.AreEqual("test item", result.Description); @@ -46,6 +46,7 @@ public async Task TestGetRowItems() Assert.AreEqual(1, result.ItemType); Assert.AreEqual(23, result.UnitPurchaseQuantity); Assert.AreEqual(43, result.UnitOrderQuantity); + Assert.AreEqual(65, result.PackOrderQuantity); Assert.AreEqual(65, result.SupplierId); Assert.AreEqual("SUP127", result.SupplierCode); Assert.AreEqual("Ay-062669-VVl", result.SupplierPartNumber); @@ -54,7 +55,7 @@ public async Task TestGetRowItems() [TestMethod] // checkt null if does not exst public async Task TestGetRowNotExistItems() { - Item result = await _baseStorageService.GetRow(999); + Item result = await _baseStorageService.GetRow(999); Assert.IsNull(result); } @@ -70,7 +71,7 @@ public async Task TestGetAllItems() }); await _dbContext.SaveChangesAsync(); - var result = await _baseStorageService.GetAllRows(); + var result = await _baseStorageService.GetAllRows(); Assert.AreEqual(2, result.Count); } @@ -87,7 +88,7 @@ public async Task TestPostItem() [TestMethod] public async Task TestPostNullItem() { - var result = await _baseStorageService.AddRow(null); + var result = await _baseStorageService.AddRow(null); Assert.IsNull(result); } @@ -105,7 +106,7 @@ public async Task TestPutItem() var result = await _baseStorageService.UpdateRow(item.Id, updatedItem); Assert.IsTrue(result); - var updated = await _baseStorageService.GetRow(item.Id); // Haal het geüpdatete record op + var updated = await _baseStorageService.GetRow(item.Id); // Haal het geüpdatete record op Assert.AreEqual("P000001", updated.Uid); Assert.AreEqual("XLE77785i", updated.Code); Assert.AreEqual("test Updated", updated.Description); @@ -123,6 +124,7 @@ public async Task TestPutItem() Assert.AreEqual("Ay-062669-VVl", updated.SupplierPartNumber); } + [TestMethod] public async Task TestPutNotExist() { @@ -141,7 +143,7 @@ public async Task TestDeleteRow() Assert.IsNotNull(addedId); deleteItem.Id = (int)addedId; - var result = await _baseStorageService.DeleteRow(deleteItem.Id); + var result = await _baseStorageService.DeleteRow(deleteItem.Id); Assert.IsTrue(result); } @@ -149,7 +151,7 @@ public async Task TestDeleteRow() [TestMethod] public async Task TestDeleteRowNotExist() { - var item = await _baseStorageService.DeleteRow(999); + var item = await _baseStorageService.DeleteRow(999); Assert.IsFalse(item); } } \ No newline at end of file diff --git a/UnitTest/ItemTypesServiceTests.cs b/UnitTest/ItemTypesServiceTests.cs index 285bdf9..b080c31 100644 --- a/UnitTest/ItemTypesServiceTests.cs +++ b/UnitTest/ItemTypesServiceTests.cs @@ -3,7 +3,7 @@ namespace CargoHub.Test; [TestClass] public class ItemTypesServiceTests { - private BaseStorageService _baseStorageService; + private BaseStorageService _baseStorageService; private AppDbContext _dbContext; [TestInitialize] @@ -14,7 +14,7 @@ public void Setup() .Options; _dbContext = new AppDbContext(options); - _baseStorageService = new BaseStorageService(_dbContext); + _baseStorageService = new BaseStorageService(_dbContext); } [TestCleanup] @@ -27,16 +27,13 @@ public void Cleanup() [TestMethod] public async Task TestGetRowItemType() { - // Arrange ItemType itemType = TestHelper.TestItemType1; _dbContext.Set().Add(itemType); await _dbContext.SaveChangesAsync(); - // Act - var result = await _baseStorageService.GetRow(itemType.Id); + var result = await _baseStorageService.GetRow(itemType.Id); - // Assert Assert.IsNotNull(result); Assert.AreEqual("Test Name", result.Name); Assert.AreEqual("Test Description", result.Description); @@ -46,7 +43,7 @@ public async Task TestGetRowItemType() [TestMethod] public async Task TestGetRowNotExist() { - var result = await _baseStorageService.GetRow(999); + var result = await _baseStorageService.GetRow(999); Assert.IsNull(result); } @@ -62,11 +59,26 @@ public async Task TestGetAllItemTypes() }); await _dbContext.SaveChangesAsync(); - var result = await _baseStorageService.GetAllRows(); + var result = await _baseStorageService.GetAllRows(); Assert.AreEqual(2, result.Count); } + [TestMethod] + public async Task TestGetAllMax() + { + for (int i = 0; i < 300; i++) + { + ItemType randomType = TestHelper.CreateRandomItemType(); + await _dbContext.ItemTypes.AddAsync(randomType); + } + await _dbContext.SaveChangesAsync(); + + var result = await _baseStorageService.GetAllRows(1, 100); + Assert.AreEqual(100, result.Count); + Assert.IsTrue(result.All(type => type.Id <= 100)); + } + [TestMethod] public async Task TestPostItemTypes() { @@ -79,27 +91,41 @@ public async Task TestPostItemTypes() [TestMethod] public async Task TestPostNullItemTypes() { - var result = await _baseStorageService.AddRow(null); + var result = await _baseStorageService.AddRow(null); Assert.IsNull(result); } + // [TestMethod] + // public async Task TestPutItemType() + // { + // ItemType itemType = TestHelper.TestItemType1; + // _dbContext.ItemTypes.Add(itemType); + // await _dbContext.SaveChangesAsync(); + + // ItemType updatedItem = TestHelper.TestupdateItemType; + // updatedItem.Id = itemType.Id; + + // var result = await _baseStorageService.UpdateRow(itemType.Id, updatedItem); + // Assert.IsTrue(result); + + // var updated = await _baseStorageService.GetRow(itemType.Id); + // Assert.AreEqual("updated Name", updated.Name); + // Assert.AreEqual("updated Description", updated.Description); + // } + [TestMethod] - public async Task TestPutItemType() + public async Task TestUpdateItemType() { - // Arrange - ItemType itemType = TestHelper.TestItemType1; - _dbContext.Set().Add(itemType); + // Add an item group object to the db + ItemType itemtype = TestHelper.TestItemType1; + await _dbContext.ItemTypes.AddAsync(itemtype); await _dbContext.SaveChangesAsync(); - ItemType updatedItem = TestHelper.TestupdateItemType; - updatedItem.Id = itemType.Id; - - var result = await _baseStorageService.UpdateRow(itemType.Id, updatedItem); + // Update the inserted item group + ItemType UpdatedItemType = TestHelper.TestupdateItemType; + bool result = await _baseStorageService.UpdateRow(itemtype.Id, UpdatedItemType); Assert.IsTrue(result); - - var updated = await _baseStorageService.GetRow(itemType.Id); - Assert.AreEqual("updated Name", updated.Name); - Assert.AreEqual("updated Description", updated.Description); + Assert.IsTrue(itemtype.UpdatedAt > itemtype.CreatedAt); } [TestMethod] @@ -110,24 +136,38 @@ public async Task TestPutNotExist() Assert.IsFalse(result); } - [TestMethod] - public async Task TestDeleteRow() - { - var deleteItemType = TestHelper.TestItemType1; - await _baseStorageService.AddRow(deleteItemType); + // [TestMethod] + // public async Task TestDeleteRow() + // { + // var deleteItemType = TestHelper.TestItemType1; + // await _baseStorageService.AddRow(deleteItemType); - var result = await _baseStorageService.DeleteRow(deleteItemType.Id); + // var result = await _baseStorageService.DeleteRow(deleteItemType.Id); - Assert.IsTrue(result); + // Assert.IsTrue(result); + + // var deletedItem = await _dbContext.ItemTypes.FindAsync(deleteItemType.Id); + // Assert.IsNull(deletedItem); + // } + + [TestMethod] + public async Task TestDeleteItemType() + { + // try deleting an entity that doesn't exist + bool Result1 = await _baseStorageService.DeleteRow(1); + Assert.IsFalse(Result1); - var deletedItem = await _dbContext.Set().FindAsync(deleteItemType.Id); - Assert.IsNull(deletedItem); + ItemType itemtype = TestHelper.TestItemType1; + await _dbContext.ItemTypes.AddAsync(itemtype); + await _dbContext.SaveChangesAsync(); + bool Result2 = await _baseStorageService.DeleteRow(1); + Assert.IsTrue(Result2); } [TestMethod] public async Task TestDeleteRowNotExist() { - var itemType = await _baseStorageService.DeleteRow(999); + var itemType = await _baseStorageService.DeleteRow(999); Assert.IsFalse(itemType); } } diff --git a/UnitTest/TestHelper.cs b/UnitTest/TestHelper.cs index ef01d53..b557a8f 100644 --- a/UnitTest/TestHelper.cs +++ b/UnitTest/TestHelper.cs @@ -227,4 +227,13 @@ public static ItemLine CreateRandomItemLine() Name = "Test Line", Description = "Line Description" }; + + public static ItemType CreateRandomItemType() + { + return new ItemType + { + Name = Guid.NewGuid().ToString(), + Description = Guid.NewGuid().ToString() + }; + } } \ No newline at end of file From 07d96a6d0121df60db51df8c05da3f8c95c03e17 Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Mon, 20 Jan 2025 20:15:13 +0100 Subject: [PATCH 33/35] Unittests na merge met main De dev branch was gewijzigd vandaag waardoor er sommige services er anders uit zagen dit zorgde voor paar problemen in mijn services. deze zijn opgelost en nu werken mijn unittests items/baseitemsstorage/itemtypes --- Tests/test_item_types.py | 89 +++++++++++++++++++++++++++++++ UnitTest/BaseItemStorageTests.cs | 26 ++++----- UnitTest/ItemTypesServiceTests.cs | 83 ++++++++-------------------- UnitTest/TestHelper.cs | 86 +++++++++++++++++++++++++++++ 4 files changed, 206 insertions(+), 78 deletions(-) create mode 100644 Tests/test_item_types.py diff --git a/Tests/test_item_types.py b/Tests/test_item_types.py new file mode 100644 index 0000000..8de3689 --- /dev/null +++ b/Tests/test_item_types.py @@ -0,0 +1,89 @@ +import requests +import test_helper + + +BASE_URL = "http://localhost:3000/api/v2/ItemTypes" + +VALID_ITEM_TYPE = { + "Name": "Test Name", + "Description": "Test Description" +} + +INVALID_ITEM_TYPE_1 = {} +HEADERS = {"Content-Type": "application/json"} + +UPDATED_ITEM_TYPE = { + "id": 1, + "Name": "Updated test name", + "Description": "Updated test description" +} + + +def test_Post(): + # post the test body + post_response = requests.post( + BASE_URL, headers=HEADERS, json=VALID_ITEM_TYPE) + # convert the json response to a string and look for the id of the created Entity + json = str(post_response.json()) + # look here for an integer (digit) + + generated_id = test_helper.get_integer_from_json_string(json) + assert generated_id != 0 + + # get the same entity that has been posted + get_response = requests.get(BASE_URL + f"/{generated_id}") + json = get_response.json() + assert get_response.status_code == 200 + assert json["name"] == VALID_ITEM_TYPE["Name"] + assert json["description"] == VALID_ITEM_TYPE["Description"] + assert "created_at" in json, "created_at key was not created" + assert "updated_at" in json, "updated_at key was not created" + + delete_response = requests.delete( + BASE_URL+f"/{generated_id}") + + assert delete_response.status_code == 200 + + +def test_invalid_post(): + # post an item TYPE with an empty body + post_response = requests.post( + BASE_URL, headers=HEADERS, json=INVALID_ITEM_TYPE_1) + # the response should return a bad request + assert post_response.status_code == 400 + + +# def test_put(): +# # post an item TYPE +# post_response = requests.post( +# BASE_URL, headers=HEADERS, json=VALID_ITEM_TYPE) +# # convert the json response to a string and look for the id of the created Entity +# json = str(post_response.json()) +# # look here for an integer (digit) +# generated_id = test_helper.get_integer_from_json_string(json) +# assert generated_id != 0 +# # modify the added item TYPE +# put_response = requests.put( +# BASE_URL + f"/{generated_id}", headers=HEADERS, json=UPDATED_ITEM_TYPE) +# assert put_response.status_code == 200 + + +def test_put_Item_type_that_does_not_exist(): + put_response = requests.put( + BASE_URL + "999999999999", json=VALID_ITEM_TYPE) + assert put_response.status_code == 404 + + +def test_delete(): + post_response = requests.post(BASE_URL, json=VALID_ITEM_TYPE) + json = str(post_response.json()) + generated_id = test_helper.get_integer_from_json_string(json) + assert generated_id != 0 + + delete_response = requests.delete( + BASE_URL+f"/{generated_id}") + + assert delete_response.status_code == 200 + + get_response = requests.get(BASE_URL + str(generated_id)) + assert get_response.status_code == 404 diff --git a/UnitTest/BaseItemStorageTests.cs b/UnitTest/BaseItemStorageTests.cs index 874c05c..500ea92 100644 --- a/UnitTest/BaseItemStorageTests.cs +++ b/UnitTest/BaseItemStorageTests.cs @@ -27,9 +27,8 @@ public void Cleanup() [TestMethod] public async Task TestGetRowItems() { - Item item = TestHelper.TestItem1; + Item item = TestHelper.TestItemGet; - // _baseStorageService.AddRow(item); _dbContext.Set().Add(item); await _dbContext.SaveChangesAsync(); @@ -52,7 +51,7 @@ public async Task TestGetRowItems() Assert.AreEqual("Ay-062669-VVl", result.SupplierPartNumber); } - [TestMethod] // checkt null if does not exst + [TestMethod] public async Task TestGetRowNotExistItems() { Item result = await _baseStorageService.GetRow(999); @@ -62,20 +61,17 @@ public async Task TestGetRowNotExistItems() [TestMethod] public async Task TestGetAllItems() { - Item item1 = TestHelper.TestItem1; - Item item2 = TestHelper.TestItem2; + Item item1 = TestHelper.TestItemGetAll1; + Item item2 = TestHelper.TestItemGetAll2; - _dbContext.Items.AddRange(new List - { - item1, item2 - }); + _dbContext.Items.AddRange(new List { item1, item2 }); await _dbContext.SaveChangesAsync(); var result = await _baseStorageService.GetAllRows(); - Assert.AreEqual(2, result.Count); } + [TestMethod] public async Task TestPostItem() { @@ -95,18 +91,16 @@ public async Task TestPostNullItem() [TestMethod] public async Task TestPutItem() { - // Arrange - Item item = TestHelper.TestItem1; - await _baseStorageService.AddRow(item); // Gebruik de service om data toe te voegen + Item item = TestHelper.TestItemPut; + await _baseStorageService.AddRow(item); Item updatedItem = TestHelper.TestUpdatedItem; - updatedItem.Id = item.Id; // Zorg dat het juiste ID wordt ingesteld + updatedItem.Id = item.Id; - // Act var result = await _baseStorageService.UpdateRow(item.Id, updatedItem); Assert.IsTrue(result); - var updated = await _baseStorageService.GetRow(item.Id); // Haal het geüpdatete record op + var updated = await _baseStorageService.GetRow(item.Id); Assert.AreEqual("P000001", updated.Uid); Assert.AreEqual("XLE77785i", updated.Code); Assert.AreEqual("test Updated", updated.Description); diff --git a/UnitTest/ItemTypesServiceTests.cs b/UnitTest/ItemTypesServiceTests.cs index b080c31..7ec6f6c 100644 --- a/UnitTest/ItemTypesServiceTests.cs +++ b/UnitTest/ItemTypesServiceTests.cs @@ -27,19 +27,20 @@ public void Cleanup() [TestMethod] public async Task TestGetRowItemType() { - ItemType itemType = TestHelper.TestItemType1; - - _dbContext.Set().Add(itemType); + // Arrange + ItemType itemType = TestHelper.TestItemTypeGet; + await _dbContext.ItemTypes.AddAsync(itemType); await _dbContext.SaveChangesAsync(); - var result = await _baseStorageService.GetRow(itemType.Id); + // Act + ItemType? result = await _baseStorageService.GetRow(itemType.Id); + // Assert Assert.IsNotNull(result); - Assert.AreEqual("Test Name", result.Name); - Assert.AreEqual("Test Description", result.Description); + Assert.AreEqual(itemType.Name, result.Name); + Assert.AreEqual(itemType.Description, result.Description); } - [TestMethod] public async Task TestGetRowNotExist() { @@ -95,39 +96,25 @@ public async Task TestPostNullItemTypes() Assert.IsNull(result); } - // [TestMethod] - // public async Task TestPutItemType() - // { - // ItemType itemType = TestHelper.TestItemType1; - // _dbContext.ItemTypes.Add(itemType); - // await _dbContext.SaveChangesAsync(); - - // ItemType updatedItem = TestHelper.TestupdateItemType; - // updatedItem.Id = itemType.Id; - - // var result = await _baseStorageService.UpdateRow(itemType.Id, updatedItem); - // Assert.IsTrue(result); - - // var updated = await _baseStorageService.GetRow(itemType.Id); - // Assert.AreEqual("updated Name", updated.Name); - // Assert.AreEqual("updated Description", updated.Description); - // } - [TestMethod] - public async Task TestUpdateItemType() + public async Task TestDeleteItemType() { - // Add an item group object to the db - ItemType itemtype = TestHelper.TestItemType1; - await _dbContext.ItemTypes.AddAsync(itemtype); + // Try deleting an entity that doesn't exist + bool result1 = await _baseStorageService.DeleteRow(1); + Assert.IsFalse(result1); + + // Add an ItemType to the database + ItemType itemType = TestHelper.TestItemType1; + await _dbContext.ItemTypes.AddAsync(itemType); await _dbContext.SaveChangesAsync(); - // Update the inserted item group - ItemType UpdatedItemType = TestHelper.TestupdateItemType; - bool result = await _baseStorageService.UpdateRow(itemtype.Id, UpdatedItemType); - Assert.IsTrue(result); - Assert.IsTrue(itemtype.UpdatedAt > itemtype.CreatedAt); + // Try deleting the added ItemType + bool result2 = await _baseStorageService.DeleteRow(itemType.Id); // No type argument needed + Assert.IsTrue(result2); } + + [TestMethod] public async Task TestPutNotExist() { @@ -136,34 +123,6 @@ public async Task TestPutNotExist() Assert.IsFalse(result); } - // [TestMethod] - // public async Task TestDeleteRow() - // { - // var deleteItemType = TestHelper.TestItemType1; - // await _baseStorageService.AddRow(deleteItemType); - - // var result = await _baseStorageService.DeleteRow(deleteItemType.Id); - - // Assert.IsTrue(result); - - // var deletedItem = await _dbContext.ItemTypes.FindAsync(deleteItemType.Id); - // Assert.IsNull(deletedItem); - // } - - [TestMethod] - public async Task TestDeleteItemType() - { - // try deleting an entity that doesn't exist - bool Result1 = await _baseStorageService.DeleteRow(1); - Assert.IsFalse(Result1); - - ItemType itemtype = TestHelper.TestItemType1; - await _dbContext.ItemTypes.AddAsync(itemtype); - await _dbContext.SaveChangesAsync(); - bool Result2 = await _baseStorageService.DeleteRow(1); - Assert.IsTrue(Result2); - } - [TestMethod] public async Task TestDeleteRowNotExist() { diff --git a/UnitTest/TestHelper.cs b/UnitTest/TestHelper.cs index b557a8f..28f224f 100644 --- a/UnitTest/TestHelper.cs +++ b/UnitTest/TestHelper.cs @@ -236,4 +236,90 @@ public static ItemType CreateRandomItemType() Description = Guid.NewGuid().ToString() }; } + + public static Item TestItemGet = new Item + { + Uid = "P000001", + Code = "XLE77785i", + Description = "test item", + ShortDescription = "short test", + UpcCode = "7946503676171", + ModelNumber = "fM-605648-lbu", + CommodityCode = "qB-2533", + ItemLine = 1, + ItemGroup = 1, + ItemType = 1, + UnitPurchaseQuantity = 23, + UnitOrderQuantity = 43, + PackOrderQuantity = 65, + SupplierId = 65, + SupplierCode = "SUP127", + SupplierPartNumber = "Ay-062669-VVl", + }; + + public static ItemType TestItemTypeGet = new ItemType + { + Name = "Test Name", + Description = "Test Description" + }; + + public static Item TestItemGetAll1 = new Item + { + Uid = "P000001", + Code = "XLE77785i", + Description = "test item", + ShortDescription = "short test", + UpcCode = "7946503676171", + ModelNumber = "fM-605648-lbu", + CommodityCode = "qB-2533", + ItemLine = 1, + ItemGroup = 1, + ItemType = 1, + UnitPurchaseQuantity = 23, + UnitOrderQuantity = 43, + PackOrderQuantity = 65, + SupplierId = 65, + SupplierCode = "SUP127", + SupplierPartNumber = "Ay-062669-VVl", + }; + + public static Item TestItemGetAll2 = new Item + { + Uid = "P000002", + Code = "XLE77785i", + Description = "test item", + ShortDescription = "short test", + UpcCode = "7946503676171", + ModelNumber = "fM-605648-lbu", + CommodityCode = "qB-2533", + ItemLine = 1, + ItemGroup = 1, + ItemType = 1, + UnitPurchaseQuantity = 23, + UnitOrderQuantity = 43, + PackOrderQuantity = 65, + SupplierId = 65, + SupplierCode = "SUP127", + SupplierPartNumber = "Ay-062669-VVl", + }; + + public static Item TestItemPut = new Item + { + Uid = "P000001", + Code = "XLE77785i", + Description = "test item", + ShortDescription = "short test", + UpcCode = "7946503676171", + ModelNumber = "fM-605648-lbu", + CommodityCode = "qB-2533", + ItemLine = 1, + ItemGroup = 1, + ItemType = 1, + UnitPurchaseQuantity = 23, + UnitOrderQuantity = 43, + PackOrderQuantity = 65, + SupplierId = 65, + SupplierCode = "SUP127", + SupplierPartNumber = "Ay-062669-VVl", + }; } \ No newline at end of file From 3fd847e6a5f58a08e8d05a488dfd16783188358e Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Mon, 20 Jan 2025 21:31:43 +0100 Subject: [PATCH 34/35] Integrations tests items Changes in de code --- Tests/test_helper.py | 15 ++++++--------- Tests/test_items.py | 45 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 9 deletions(-) create mode 100644 Tests/test_items.py diff --git a/Tests/test_helper.py b/Tests/test_helper.py index cbd65f0..b4acfbe 100644 --- a/Tests/test_helper.py +++ b/Tests/test_helper.py @@ -45,7 +45,6 @@ def get_integer_from_json_string(json_string): } template_item = { - "uid": "", "code": "", "description": "", "short_description": "", @@ -64,16 +63,15 @@ def get_integer_from_json_string(json_string): } item_1 = { - "uid": "P000001", "code": "sjQ23408K", "description": "Face-to-face clear-thinking complexity", "short_description": "must", "upc_code": "6523540947122", "model_number": "63-OFFTq0T", "commodity_code": "oTo304", - "item_line": 11, - "item_group": 73, - "item_type": 14, + "item_line": 1, + "item_group": 1, + "item_type": 1, "unit_purchase_quantity": 47, "unit_order_quantity": 13, "pack_order_quantity": 11, @@ -83,16 +81,15 @@ def get_integer_from_json_string(json_string): } item_1_updated = { - "uid": "P000001", "code": "sjQ23408K", "description": "Changed", "short_description": "must", "upc_code": "6523540947122", "model_number": "63-OFFTq0T", "commodity_code": "oTo304", - "item_line": 11, - "item_group": 73, - "item_type": 14, + "item_line": 1, + "item_group": 1, + "item_type": 1, "unit_purchase_quantity": 47, "unit_order_quantity": 13, "pack_order_quantity": 11, diff --git a/Tests/test_items.py b/Tests/test_items.py new file mode 100644 index 0000000..7f598c9 --- /dev/null +++ b/Tests/test_items.py @@ -0,0 +1,45 @@ +import requests +import test_helper + + +BASE_URL = "http://localhost:3000/api/v2/items" + +VALID_ITEM = { + "Name": "Test Name", + "Description": "Test Description" +} + +INVALID_ITEM_1 = {} +HEADERS = {"Content-Type": "application/json"} + +UPDATED_ITEM = { + "code": "XLE77785i", + "description": "Focused human-resource implementation", + "short_description": "offer", + "upc_code": "7946503676171", + "model_number": "fM-605648-lbu", + "commodity_code": "qB-2533", + "item_line": 1, + "item_group": 1, + "item_type": 1, + "unit_purchase_quantity": 27, + "unit_order_quantity": 20, + "pack_order_quantity": 16, + "supplier_id": 45, + "supplier_code": "SUP127", + "supplier_part_number": "Ay-062669-VVl" +} + + +def test_invalid_post(): + # post an item TYPE with an empty body + post_response = requests.post( + BASE_URL, headers=HEADERS, json=INVALID_ITEM_1) + # the response should return a bad request + assert post_response.status_code == 400 + + +def test_put_Item_that_does_not_exist(): + put_response = requests.put( + BASE_URL + "999999999999", json=VALID_ITEM) + assert put_response.status_code == 404 From c54843b80be4f9549c6e928aedcc5f4fe7956af8 Mon Sep 17 00:00:00 2001 From: Alihanbaba31 <1060496@hr.nl> Date: Mon, 20 Jan 2025 21:52:44 +0100 Subject: [PATCH 35/35] ItemStorageService Foutmelding gewijzigd --- CargoHub/Services/ItemStorageService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CargoHub/Services/ItemStorageService.cs b/CargoHub/Services/ItemStorageService.cs index 68f2d8e..6f93241 100644 --- a/CargoHub/Services/ItemStorageService.cs +++ b/CargoHub/Services/ItemStorageService.cs @@ -23,7 +23,7 @@ private static string IdToUid(int id) var isValid = await ValidateItems(row.ItemType, row.ItemGroup, row.ItemLine); if (!isValid) { - throw new InvalidOperationException("Invalid item type, group, or line."); + return null; } row.Id = appDbContext.Set().Any() ? appDbContext.Set().Max(_ => _.Id) + 1 : 1;