Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add check stock quantity function
Mira Szewczykf1494e506a4e
diff --git a/saleor/stock/stock_management.py b/saleor/stock/stock_management.pynew file mode 100644index 0000000000..e15e994d8e--- /dev/null+++ b/saleor/stock/stock_management.py@@ -0,0 +1,17 @@+from typing import TYPE_CHECKING++from ..core.exceptions import InsufficientStock+from .models import Stock++if TYPE_CHECKING:+ from ..product.models import ProductVariant+++def check_stock_quantity(variant: "ProductVariant", country_code: str, quantity: int):+ try:+ stock = Stock.objects.for_country(country_code).get(product_variant=variant)+ except Stock.DoesNotExist:+ raise InsufficientStock++ if variant.track_inventory and quantity > stock.quantity_available:+ raise InsufficientStock(variant)diff --git a/tests/test_stock.py b/tests/test_stock.pyindex ed189d3c4f..a972b4dbb9 100644--- a/tests/test_stock.py+++ b/tests/test_stock.py@@ -1,13 +1,40 @@+import pytest++from saleor.core.exceptions import InsufficientStockfrom saleor.stock.models import Stock+from saleor.stock.stock_management import check_stock_quantity++COUNTRY_CODE = "US"def test_stock_for_country(product):- country_code = "US"stock = Stock.objects.get()warehouse = stock.warehouse- assert country_code in warehouse.countries+ assert COUNTRY_CODE in warehouse.countriesassert stock.warehouse == warehouse- stock_qs = Stock.objects.for_country(country_code)+ stock_qs = Stock.objects.for_country(COUNTRY_CODE)assert stock_qs.count() == 1assert stock_qs.first() == stock+++def test_stock_for_country_does_not_exists(product, warehouse):+ fake_country_code = "OO"+ assert fake_country_code not in warehouse.countries+ stock_qs = Stock.objects.for_country(fake_country_code)+ assert not stock_qs.exists()+++def test_check_stock_quantity_is_lower_than_available(product):+ stock = Stock.objects.get()+ variant = stock.product_variant+ new_quantity = stock.quantity_available+ assert check_stock_quantity(variant, COUNTRY_CODE, new_quantity) is None+++def test_check_stock_quantity_is_not_sufficient(product):+ stock = Stock.objects.get()+ variant = stock.product_variant+ new_quantity = stock.quantity_available + 1+ with pytest.raises(InsufficientStock):+ check_stock_quantity(variant, COUNTRY_CODE, new_quantity)