Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Unit tests

Tomasz Szymanskib4e6a0dc2494
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index c9f2193073..4acafbfd7a 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -3,6 +3,7 @@ from uuid import uuid4
from django.conf import settings
from django.contrib.staticfiles import finders as static_finders
+from django.core.exceptions import ValidationError
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from django.db import transaction
@@ -11,6 +12,9 @@ from django.utils import timezone
from prices import Money, TaxedMoney
from weasyprint import HTML
+from saleor.graphql.order.enums import InvoiceStatus
+from saleor.order.error_codes import InvoiceErrorCode
+
from ..account.models import User
from ..core.taxes import zero_money
from ..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 = 3
MAX_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.py
index 1dde202e64..da5d87459f 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -8,6 +8,7 @@ from typing import List, Optional
from unittest.mock import MagicMock, Mock
import pytest
+import pytz
from django.conf import settings
from django.contrib.auth.models import Group, Permission
from 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.py
index b197d2a844..8f753aa158 100644
--- a/tests/test_order.py
+++ b/tests/test_order.py
@@ -1,7 +1,10 @@
+from datetime import datetime
from decimal import Decimal
from unittest.mock import MagicMock, Mock, patch
+from uuid import UUID
import pytest
+from django.core.exceptions import ValidationError
from prices import Money, TaxedMoney
from 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 InvoiceStatus
from saleor.order import OrderEvents, OrderStatus, models
from saleor.order.emails import send_fulfillment_confirmation_to_customer
from 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."]}