Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Unit tests
Tomasz Szymanskib4e6a0dc2494
diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex c9f2193073..4acafbfd7a 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -3,6 +3,7 @@ from uuid import uuid4from django.conf import settingsfrom django.contrib.staticfiles import finders as static_finders+from django.core.exceptions import ValidationErrorfrom django.core.files.base import ContentFilefrom django.core.files.storage import default_storagefrom django.db import transaction@@ -11,6 +12,9 @@ from django.utils import timezonefrom prices import Money, TaxedMoneyfrom weasyprint import HTML+from saleor.graphql.order.enums import InvoiceStatus+from saleor.order.error_codes import InvoiceErrorCode+from ..account.models import Userfrom ..core.taxes import zero_moneyfrom ..core.weight import zero_weight@@ -343,7 +347,7 @@ def match_orders_with_new_user(user: User) -> None:Order.objects.confirmed().filter(user_email=user.email, user=None).update(user=user)-def _chunk_products(products, product_limit):+def chunk_products(products, product_limit):"""Split products to list of chunks.Each chunk represents products per page, product_limit defines chunk size.@@ -355,7 +359,7 @@ def _chunk_products(products, product_limit):return chunks-def _get_product_limit_first_page(products):+def get_product_limit_first_page(products):MAX_PRODUCTS_WITH_TABLE = 3MAX_PRODUCTS_WITHOUT_TABLE = 4@@ -369,12 +373,29 @@ def generate_invoice_pdf_for_order(invoice):logo_path = static_finders.find("images/logo.svg")MAX_PRODUCTS_PER_PAGE = 13+ if not getattr(invoice, "order"):+ raise ValidationError(+ {+ "order": ValidationError(+ "Invice order is invalid.", code=InvoiceErrorCode.REQUIRED+ )+ }+ )+ if invoice.status != InvoiceStatus.READY:+ raise ValidationError(+ {+ "status": ValidationError(+ "Invoice is not ready.", code=InvoiceErrorCode.NOT_READY+ )+ }+ )+all_products = invoice.order.lines.all()- product_limit_first_page = _get_product_limit_first_page(all_products)+ product_limit_first_page = get_product_limit_first_page(all_products)products_first_page = all_products[:product_limit_first_page]- rest_of_products = _chunk_products(+ rest_of_products = chunk_products(all_products[product_limit_first_page:], MAX_PRODUCTS_PER_PAGE)diff --git a/tests/conftest.py b/tests/conftest.pyindex 1dde202e64..da5d87459f 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -8,6 +8,7 @@ from typing import List, Optionalfrom unittest.mock import MagicMock, Mockimport pytest+import pytzfrom django.conf import settingsfrom django.contrib.auth.models import Group, Permissionfrom django.contrib.sites.models import Site@@ -1265,6 +1266,7 @@ def fulfilled_order(order_with_lines):url="http://www.example.com/invoice.pdf",number="01/12/2020/TEST",status=InvoiceStatus.READY,+ created=datetime.datetime.now(tz=pytz.utc),)fulfillment = order.fulfillments.create(tracking_number="123")line_1 = order.lines.first()diff --git a/tests/test_order.py b/tests/test_order.pyindex b197d2a844..8f753aa158 100644--- a/tests/test_order.py+++ b/tests/test_order.py@@ -1,7 +1,10 @@+from datetime import datetimefrom decimal import Decimalfrom unittest.mock import MagicMock, Mock, patch+from uuid import UUIDimport pytest+from django.core.exceptions import ValidationErrorfrom prices import Money, TaxedMoneyfrom saleor.core.weight import zero_weight@@ -12,6 +15,7 @@ from saleor.discount.models import (VoucherType,)from saleor.discount.utils import validate_voucher_in_order+from saleor.graphql.order.enums import InvoiceStatusfrom saleor.order import OrderEvents, OrderStatus, modelsfrom saleor.order.emails import send_fulfillment_confirmation_to_customerfrom saleor.order.events import OrderEvent, OrderEventsEmails, email_sent_event@@ -20,7 +24,10 @@ from saleor.order.templatetags.order_lines import display_translated_order_line_from saleor.order.utils import (add_variant_to_draft_order,change_order_line_quantity,+ chunk_products,delete_order_line,+ generate_invoice_pdf_for_order,+ get_product_limit_first_page,get_voucher_discount_for_order,recalculate_order,restock_fulfillment_lines,@@ -725,3 +732,68 @@ def test_email_sent_event_without_user_and_user_pk(order):"email": order.get_customer_email(),"email_type": email_type,}+++def test_chunk_products(product):+ assert chunk_products([product] * 3, 3) == [[product] * 3]+ assert chunk_products([product] * 5, 3) == [[product] * 3, [product] * 2]+ assert chunk_products([product] * 8, 3) == [+ [product] * 3,+ [product] * 3,+ [product] * 2,+ ]+++def test_get_product_limit_first_page(product):+ assert get_product_limit_first_page([product] * 3) == 3+ assert get_product_limit_first_page([product] * 4) == 4+ assert get_product_limit_first_page([product] * 16) == 4+++@patch("saleor.order.utils.static_finders")+@patch("saleor.order.utils.get_template")+@patch("saleor.order.utils.default_storage")+def test_generate_invoice_pdf_for_order(+ storage_mock, get_template_mock, static_mock, fulfilled_order+):+ file_path = "/dev/null"+ static_mock.find.return_value = file_path+ storage_mock.save = Mock()+ get_template_mock.return_value.render = Mock(return_value="<html></html>")++ generate_invoice_pdf_for_order(fulfilled_order.invoices.first())++ get_template_mock.return_value.render.assert_called_once_with(+ {+ "invoice": fulfilled_order.invoices.first(),+ "creation_date": datetime.today().strftime("%d %b %Y"),+ "order": fulfilled_order,+ "logo_path": f"file://{file_path}",+ "products_first_page": list(fulfilled_order.lines.all()),+ "rest_of_products": [],+ }+ )++ file_name, extension = storage_mock.save.call_args[0][0].split(".")+ assert UUID(file_name, version=4)+ assert extension == "pdf"+++def test_generate_invoice_pdf_for_invalid_order(fulfilled_order):+ invoice = fulfilled_order.invoices.first()+ invoice.order = None++ with pytest.raises(ValidationError) as error:+ generate_invoice_pdf_for_order(invoice)++ assert error.value.message_dict == {"order": ["Invice order is invalid."]}+++def test_generate_invoice_pdf_for_pending_invoice(fulfilled_order):+ invoice = fulfilled_order.invoices.first()+ invoice.status = InvoiceStatus.PENDING++ with pytest.raises(ValidationError) as error:+ generate_invoice_pdf_for_order(invoice)++ assert error.value.message_dict == {"status": ["Invoice is not ready."]}