Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
fix: dev dependencies required to run HTTP server (#19923)
Mikail0c0e2697cc72
diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yamlindex 7502523bfe..253d6c5b33 100644--- a/.github/workflows/tests.yaml+++ b/.github/workflows/tests.yaml@@ -226,6 +226,32 @@ jobs:path: ${{ env.BENCH_PATH }}if-no-files-found: error+ - if: steps.changes.outputs.changed == 'true'+ name: Prepare `--no-dev` tests+ timeout-minutes: 5+ run: |+ # Reuse DB generated during `pytest` run in order to avoid having+ # to run `./manage.py migrate` (slow)+ echo "DATABASE_URL=postgres://saleor:saleor@postgres:5432/test_saleor_gw0" >> "$GITHUB_ENV"+ # Uninstall dev dependencies+ uv sync --locked --no-dev++ # Ensure Saleor & uvicorn can run without development dependencies+ - if: steps.changes.outputs.changed == 'true'+ name: Run Unicorn (with --no-dev)+ timeout-minutes: 2+ run: |+ DEBUG=true uv run --no-dev -m saleor.asgi.tests.checks.check_uvicorn_starts++ # Ensure Celery and Beat boot properly without dev dependencies+ - if: steps.changes.outputs.changed == 'true'+ name: Run Celery & Beat (with --no-dev)+ timeout-minutes: 2+ env:+ CELERY_BROKER_URL: redis://cache:6379/1+ run: |+ DEBUG=true uv run --no-dev -m saleor.core.tests.checks.check_celery_starts+# Uploads the SQL count report for base branchesupload-query-count-base-branch:if: github.event_name == 'push' && github.repository == 'saleor/saleor'diff --git a/AGENTS.md b/AGENTS.mdindex 54c0a45b12..e1ea8766b1 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -284,6 +284,12 @@ def test_authorization(comments. Run short-circuit / global checks first, before fetching data.- Remove code a refactor made dead (unused validators, unreachable guards added only to satisfy mypy).Fix the type at its source instead of adding a `cast()` around a wrong upstream annotation.+- Never import `saleor.core.development.*` module(s) outside tests, or outside non-development-only logics.++ This can only be used in such locations:+ - `./manage.py populatedb` (development only command, requires `uv sync --group dev`)+ - pytest (`test_*.py`, `conftest.py`, `tests/**`)+ - Any other development-only helpers or locations# Namingdiff --git a/saleor/asgi/tests/checks/__init__.py b/saleor/asgi/tests/checks/__init__.pynew file mode 100644index 0000000000..3c78c6ac5b--- /dev/null+++ b/saleor/asgi/tests/checks/__init__.py@@ -0,0 +1,6 @@+"""Module containing check scripts to assert specific behaviors.++The ``checks`` module contains independent check scripts that are not+intended for pytest to run. Instead, they are only expected to be invoked+in certain configurations (either manually, or in CI/CDs)+"""diff --git a/saleor/asgi/tests/checks/check_uvicorn_starts.py b/saleor/asgi/tests/checks/check_uvicorn_starts.pynew file mode 100644index 0000000000..9ba4327f80--- /dev/null+++ b/saleor/asgi/tests/checks/check_uvicorn_starts.py@@ -0,0 +1,115 @@+"""Ensures that uvicorn and Saleor are able to start.++This is done by starting uvicorn in a subprocess, and then trying to send+a simple GraphQL query once the server is up (determined using ``/health/``)+"""++import multiprocessing+import os+import socket+import time++import django+import requests+import uvicorn+from django.conf import settings+from django.contrib.sites.models import Site++STARTUP_TIMEOUT_SECONDS = 30+++def initialize_site() -> None:+ """Recreates the site if it's not available.++ This allows to repair the database when tests delete the site+ (when reusing the DB from `pytest --reuse-db`).+ """++ if settings.DEBUG is not True:+ raise AssertionError("Cannot run this file without DEBUG=true")++ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "saleor.settings")+ django.setup()++ from saleor.site.models import SiteSettings++ site, _ = Site.objects.get_or_create(+ pk=settings.SITE_ID,+ defaults={"name": "example.com", "domain": "example.com"},+ )+ SiteSettings.objects.get_or_create(site=site)+ Site.objects.clear_cache()+++def run_uvicorn(server_socket: socket.socket) -> None:+ config = uvicorn.Config("saleor.asgi:application", log_level="info")+ instance = uvicorn.Server(config).run(sockets=[server_socket])+ assert instance is None+++def wait_until_healthy(+ server_process: multiprocessing.Process, health_url: str+) -> None:+ deadline = time.monotonic() + STARTUP_TIMEOUT_SECONDS+ while time.monotonic() < deadline:+ if not server_process.is_alive():+ raise RuntimeError("Uvicorn stopped before it became healthy.")++ try:+ # nosemgrep: no-requests-lib+ response = requests.get(health_url, timeout=(2, 2))+ except requests.RequestException:+ time.sleep(0.1)+ continue++ if response.status_code == 200:+ return++ time.sleep(0.1)++ raise TimeoutError("Uvicorn did not become healthy within 30 seconds.")+++def check_response(resp: requests.Response) -> None:+ if resp.status_code != 200:+ raise AssertionError(f"Unexpected status: {resp.status_code}")++ try:+ content = resp.json()+ except requests.exceptions.JSONDecodeError as exc:+ raise AssertionError("Unexpected response body") from exc++ if not isinstance(content, dict) or content.get("data") != {"__typename": "Query"}:+ raise AssertionError(f"Unexpected response: {content}")+++def main() -> None:+ initialize_site()++ server_socket = socket.create_server(("127.0.0.1", 0))+ addr, port = server_socket.getsockname()++ server_process = multiprocessing.Process(target=run_uvicorn, args=(server_socket,))+ server_process.start()+ server_socket.close()++ try:+ wait_until_healthy(server_process, f"http://{addr}:{port}/health/")++ # nosemgrep: no-requests-lib # this is an internal CI/CD check+ response = requests.post(+ f"http://{addr}:{port}/graphql/",+ json={"query": "{__typename}"},+ timeout=(2, 2),+ )+ check_response(response)+ finally:+ server_process.terminate()+ server_process.join(timeout=5)+ if server_process.is_alive():+ server_process.kill()+ server_process.join()+++if __name__ == "__main__":+ main()diff --git a/saleor/asgi/tests/checks/test_check_uvicorn_starts.py b/saleor/asgi/tests/checks/test_check_uvicorn_starts.pynew file mode 100644index 0000000000..86a3aa848c--- /dev/null+++ b/saleor/asgi/tests/checks/test_check_uvicorn_starts.py@@ -0,0 +1,102 @@+import re+from unittest.mock import Mock++import pytest+import requests+from django.contrib.sites.models import Site++from saleor.site.models import SiteSettings++from .check_uvicorn_starts import check_response, initialize_site+++def test_initialize_site_rejects_when_debug_mode_disabled(settings):+ # given+ settings.DEBUG = False++ # when/when+ with pytest.raises(AssertionError, match="Cannot run this file without DEBUG=true"):+ initialize_site()++ # Sanity check: should work fine when `True`+ settings.DEBUG = True+ initialize_site()+++def test_initialize_site_recreates_site_and_settings(settings):+ """When Site is deleted, then it should recreate it.++ This is needed due to some test cases deleting the Site object which means+ the GitHub Workflow that run `check_uvicorn_starts` must recreate it.+ """+ settings.DEBUG = True++ # given+ qs_site = Site.objects.filter(pk=settings.SITE_ID)+ qs_site_settings = SiteSettings.objects.filter(site_id=settings.SITE_ID)+ assert qs_site.delete()++ Site.objects.clear_cache()+ assert qs_site.exists() is False+ assert qs_site_settings.exists() is False++ # when+ initialize_site()++ # then+ site = qs_site.get()+ site_settings = qs_site_settings.get()+ assert site.domain == "example.com"+ assert site_settings.site_id == site.pk+++def test_initialize_site_does_not_recreate_when_exists(settings):+ """When Site is exists, then it should not attempt to recreate it."""+ settings.DEBUG = True++ # given+ qs_site = Site.objects.filter(pk=settings.SITE_ID)+ qs_site_settings = SiteSettings.objects.filter(site_id=settings.SITE_ID)+ assert qs_site.exists() is True++ Site.objects.clear_cache()++ # when+ initialize_site()++ # then (unchanged)+ site = qs_site.get()+ site_settings = qs_site_settings.get()+ assert site.domain == "example.com"+ assert site_settings.site_id == site.pk+++ ("status_code", "content", "json_error", "expected_message"),+ [+ (500, {"data": {"__typename": "Query"}}, False, "Unexpected status: 500"),+ (200, None, True, "Unexpected response body"),+ (200, {}, False, "Unexpected response: {}"),+ (+ 200,+ {"data": {"__typename": "Product"}},+ False,+ "Unexpected response: {'data': {'__typename': 'Product'}}",+ ),+ ],+)+def test_check_response_rejects_invalid_response(+ status_code, content, json_error, expected_message+):+ # given+ response = Mock(status_code=status_code)+ if json_error:+ response.json.side_effect = requests.exceptions.JSONDecodeError(+ "Expecting value", "", 0+ )+ else:+ response.json.return_value = content++ # when/then+ with pytest.raises(AssertionError, match=re.escape(expected_message)):+ check_response(response)diff --git a/saleor/core/development/__init__.py b/saleor/core/development/__init__.pynew file mode 100644index 0000000000..34c9a1e0b2--- /dev/null+++ b/saleor/core/development/__init__.py@@ -0,0 +1,7 @@+"""Development-only module. Should not be used inside production/live code paths.++This should only be used in such locations:+- `./manage.py populatedb` (development only command, requires ``uv sync --group dev``)+- pytest (`test_*.py`, `conftest.py`, `tests/**`)+- Any other development-only helpers or locations+"""diff --git a/saleor/core/utils/random_data.py b/saleor/core/development/random_data.pysimilarity index 97%rename from saleor/core/utils/random_data.pyrename to saleor/core/development/random_data.pyindex b5041fa747..f91bfe669d 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/development/random_data.py@@ -3,7 +3,6 @@ import itertoolsimport jsonimport osimport random-import unicodedataimport uuidfrom collections import defaultdictfrom decimal import Decimal@@ -17,7 +16,7 @@ from django.conf import settingsfrom django.contrib.auth import password_validationfrom django.core.files import Filefrom django.core.files.storage import default_storage-from django.db import connection, transaction+from django.db import transactionfrom django.db.models import Ffrom django.utils import timezonefrom django.utils.text import slugify@@ -26,7 +25,7 @@ from faker.providers import BaseProviderfrom measurement.measures import Weightfrom prices import Money, TaxedMoney-from ...account.models import Address, Group, User+from ...account.models import Group, Userfrom ...account.search import (update_user_search_vector,)@@ -119,6 +118,15 @@ from ...warehouse import WarehouseClickAndCollectOptionfrom ...warehouse.management import increase_stockfrom ...warehouse.models import PreorderAllocation, Stock, Warehousefrom ..postgres import FlatConcatSearchVector+from ..utils.anonymization import (+ generate_fake_address as base_generate_fake_address,+)+from ..utils.anonymization import (+ generate_fake_user as base_generate_fake_user,+)+from ..utils.anonymization import (+ get_email,+)fake = cast(Any, Factory.create())fake.seed(0)@@ -870,14 +878,6 @@ class SaleorProvider(BaseProvider):fake.add_provider(SaleorProvider)-def get_email(first_name, last_name):- _first = unicodedata.normalize("NFD", first_name).encode("ascii", "ignore")- _last = unicodedata.normalize("NFD", last_name).encode("ascii", "ignore")- decoded_first = _first.lower().decode("utf-8")- decoded_last = _last.lower().decode("utf-8")- return f"{decoded_first}.{decoded_last}@example.com"--def create_product_image(product, placeholder_dir, image_name):image = get_image(placeholder_dir, image_name)product_image = ProductMedia(product=product, image=image)@@ -885,70 +885,29 @@ def create_product_image(product, placeholder_dir, image_name):return product_image-def create_address(save=True, **kwargs):- address = Address(- first_name=fake.first_name(),- last_name=fake.last_name(),- street_address_1=fake.street_address(),- city=fake.city(),- country=settings.DEFAULT_COUNTRY,- **kwargs,- )-- if address.country == "US":- state = fake.state_abbr(include_territories=False)- address.country_area = state- address.postal_code = fake.postalcode_in_state(state)- else:- address.postal_code = fake.postalcode()-- if save:- address.save()- return address--def create_fake_user(user_password, save=True, generate_id=False, customer_type=None):- address = create_address(save=save)- email = get_email(address.first_name, address.last_name)+ fake_user, fake_address = base_generate_fake_user(+ generate_id=generate_id, with_fake_save=False+ )# Skip the email if it already existstry:- return User.objects.get(email=email)+ return User.objects.get(email=fake_user.email)except User.DoesNotExist:pass- user_params = {- "first_name": address.first_name,- "last_name": address.last_name,- "email": email,- "default_billing_address": address,- "default_shipping_address": address,- "is_active": True,- "note": fake.paragraph(),- "date_joined": fake.date_time(tzinfo=datetime.UTC),- }-- if generate_id:- _, max_user_id = connection.ops.integer_field_range(- User.id.field.get_internal_type()- )- user_params["id"] = fake.random_int(min=1, max=max_user_id)-- user = User(- **user_params,- )-if save:- user.customer_type = customer_type or get_default_customer_type()- password_validation.validate_password(user_password, user)- user.set_password(user_password)- user.save()- user.addresses.add(address)- update_user_search_vector(user)+ fake_address.save()+ fake_user.customer_type = customer_type or get_default_customer_type()+ password_validation.validate_password(user_password, fake_user)+ fake_user.set_password(user_password)+ fake_user.save()+ fake_user.addresses.add(fake_address)+ update_user_search_vector(fake_user)else:- update_user_search_vector(user, attach_addresses_data=False, save=False)+ update_user_search_vector(fake_user, attach_addresses_data=False, save=False)- return user+ return fake_user# We don't want to spam the console with payment confirmations sent to@@ -1337,7 +1296,8 @@ def create_fake_order(max_order_lines=5, create_preorder_lines=False):if customer and customer.default_shipping_address:address = customer.default_shipping_addresselse:- address = create_address()+ address = base_generate_fake_address(with_fake_save=False)+ address.save()if customer and customer.default_billing_address:billing_address = customer.default_billing_addresselse:@@ -1589,7 +1549,7 @@ def create_group(name, permissions, users):def _create_staff_user(staff_password, email=None, superuser=False, customer_type=None):- address = create_address()+ address = base_generate_fake_address(with_fake_save=False)first_name = address.first_namelast_name = address.last_nameif not email:@@ -1599,6 +1559,7 @@ def _create_staff_user(staff_password, email=None, superuser=False, customer_typif staff_user:return staff_user+ address.save()staff_user = dangerously_create_test_user(first_name=first_name,last_name=last_name,@@ -2028,12 +1989,14 @@ def create_additional_cc_warehouse():shipping_zone = ShippingZone.objects.first()if not shipping_zone:raise Exception("No shipping zones found")+ address = base_generate_fake_address(with_fake_save=False)+ address.save()warehouse_name = f"{shipping_zone.name} for click and collect"warehouse, _ = Warehouse.objects.update_or_create(name=warehouse_name,slug=slugify(warehouse_name),defaults={- "address": create_address(),+ "address": address,"is_private": False,"click_and_collect_option": WarehouseClickAndCollectOption.LOCAL_STOCK,},@@ -2056,11 +2019,15 @@ def create_warehouses():)])+ address = base_generate_fake_address(+ with_fake_save=False, company_name=fake.company()+ )+ address.save()warehouse, _ = Warehouse.objects.update_or_create(name=shipping_zone_name,slug=slugify(shipping_zone_name),defaults={- "address": create_address(company_name=fake.company()),+ "address": address,"is_private": is_private,"click_and_collect_option": cc_option,},@@ -2224,7 +2191,8 @@ def create_gift_cards(how_many=5):def add_address_to_admin(email):- address = create_address()+ address = base_generate_fake_address(with_fake_save=False)+ address.save()user = User.objects.get(email=email)manager = get_plugins_manager(allow_replica=False)store_user_address(user, address, AddressType.BILLING, manager)diff --git a/saleor/core/development/tests/__init__.py b/saleor/core/development/tests/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/core/development/tests/test_random_data.py b/saleor/core/development/tests/test_random_data.pynew file mode 100644index 0000000000..5681ef6c22--- /dev/null+++ b/saleor/core/development/tests/test_random_data.py@@ -0,0 +1,448 @@+from decimal import Decimal+from unittest.mock import Mock++import pytest+from django.core.files.storage import default_storage+from django.db.models import Count+from django.test import override_settings+from django.utils.crypto import get_random_string++from ....account.models import Address, User+from ....account.tests.fixtures.user import dangerously_get_or_create_superuser+from ....attribute.models import AttributeValue+from ....channel.models import Channel+from ....discount.models import (+ Promotion,+ PromotionRule,+ Voucher,+ VoucherChannelListing,+ VoucherCode,+)+from ....giftcard.models import GiftCard, GiftCardEvent+from ....order import OrderOrigin+from ....order.models import Order+from ....product import ProductTypeKind+from ....product.models import Product, ProductMedia, ProductType, VariantMedia+from ....shipping.models import ShippingZone+from ....tax.models import TaxClass, TaxClassCountryRate+from .. import random_data+++def test_create_superuser(db, client, media_root):+ credentials = {+ "email": "[email protected]",+ "password": get_random_string(length=50),+ }+ # Test admin creation+ assert User.objects.all().count() == 0+ dangerously_get_or_create_superuser(**credentials)+ assert User.objects.all().count() == 1+ admin = User.objects.all().first()+ assert admin.is_superuser+ assert not admin.avatar+ # Test duplicating+ dangerously_get_or_create_superuser(**credentials)+ assert User.objects.all().count() == 1+++def test_create_shipping_zones(db):+ assert ShippingZone.objects.all().count() == 0+ for _ in random_data.create_shipping_zones():+ pass+ assert ShippingZone.objects.all().count() == 5+++def test_create_channels(db):+ assert Channel.objects.all().count() == 0+ for _ in random_data.create_channels():+ pass+ assert Channel.objects.all().count() == 2+ assert Channel.objects.get(slug="channel-pln")+++@override_settings(DEFAULT_CHANNEL_SLUG="test-slug")+def test_create_channels_with_default_channel_slug(db):+ assert Channel.objects.all().count() == 0+ for _ in random_data.create_channels():+ pass+ assert Channel.objects.all().count() == 2+ assert Channel.objects.get(slug="test-slug")+++def test_create_fake_user(db):+ assert not Address.objects.exists()++ assert User.objects.all().count() == 0+ random_data.create_fake_user(get_random_string(length=50))+ assert User.objects.all().count() == 1+ user = User.objects.all().first()+ assert not user.is_superuser++ assert Address.objects.all().count() == 1+ assert user.addresses.count() == 1+++def test_create_fake_users(db):+ how_many = 5+ for _ in random_data.create_users(get_random_string(length=50), how_many):+ pass+ assert User.objects.all().count() == 5+++def test_create_fake_order(db, monkeypatch, image, media_root, warehouse):+ # Tests shouldn't depend on images present in placeholder folder+ monkeypatch.setattr(+ "saleor.core.development.random_data.get_image", Mock(return_value=image)+ )+ for _ in random_data.create_channels():+ pass+ for _ in random_data.create_shipping_zones():+ pass+ for _ in random_data.create_users(get_random_string(length=50), 3):+ pass+ for _ in random_data.create_page_type():+ pass+ for _ in random_data.create_pages():+ pass+ random_data.create_products_by_schema("/", False)+ how_many_orders = 2+ for _ in random_data.create_orders(how_many_orders):+ pass+ assert Order.objects.all().count() == how_many_orders+ assert (+ list(Order.objects.values_list("origin", flat=True))+ == [OrderOrigin.CHECKOUT] * how_many_orders+ )+++def test_create_products_deletes_retired_products(product_type, category):+ retired_product_pks = (127, 132, 133)+ Product.objects.bulk_create(+ [+ Product(+ pk=product_pk,+ name=f"Retired product {product_pk}",+ slug=f"retired-product-{product_pk}",+ product_type=product_type,+ category=category,+ )+ for product_pk in retired_product_pks+ ]+ )+ current_product = Product.objects.create(+ name="Current product",+ slug="current-product",+ product_type=product_type,+ category=category,+ )+ assert set(+ Product.objects.filter(pk__in=retired_product_pks).values_list("pk", flat=True)+ ) == set(retired_product_pks)++ random_data.create_products([], "/", False)++ assert Product.objects.filter(pk__in=retired_product_pks).exists() is False+ assert Product.objects.get(pk=current_product.pk) == current_product+++def test_create_missing_product_images_does_not_duplicate_images(product, monkeypatch):+ placeholder_dir = "/placeholder"+ existing_image_name = "existing.png"+ missing_image_name = "missing.png"+ image_names = (existing_image_name, missing_image_name)+ ProductMedia.objects.create(+ product=product, image=f"products/{existing_image_name}"+ )++ def create_product_image(product, _placeholder_dir, image_name):+ return ProductMedia.objects.create(+ product=product, image=f"products/{image_name}"+ )++ create_product_image_mock = Mock(side_effect=create_product_image)+ monkeypatch.setattr(random_data, "create_product_image", create_product_image_mock)++ random_data.create_missing_product_images(product, placeholder_dir, image_names)+ random_data.create_missing_product_images(product, placeholder_dir, image_names)++ assert set(product.media.values_list("image", flat=True)) == {+ f"products/{existing_image_name}",+ f"products/{missing_image_name}",+ }+ create_product_image_mock.assert_called_once_with(+ product, placeholder_dir, missing_image_name+ )+++def test_get_matching_placeholder_image_name_with_storage_suffix():+ image_name = "sample.png"+ stored_image_name = "products/sample_8f3a1.png"++ result = random_data.get_matching_placeholder_image_name(+ stored_image_name, (image_name, "other.png")+ )++ assert result == image_name+++def test_assign_media_to_product_variants_removes_stale_relations(variant, monkeypatch):+ expected_image_name = "expected.png"+ expected_media = ProductMedia.objects.create(+ product=variant.product, image=f"products/{expected_image_name}"+ )+ stale_media = ProductMedia.objects.create(+ product=variant.product, image="products/stale.png"+ )+ VariantMedia.objects.bulk_create(+ [+ VariantMedia(variant=variant, media=expected_media),+ VariantMedia(variant=variant, media=stale_media),+ ]+ )+ monkeypatch.setattr(+ random_data,+ "IMAGES_MAPPING",+ {variant.product_id: [expected_image_name]},+ )+ monkeypatch.setattr(+ random_data,+ "VARIANT_IMAGES_MAPPING",+ {variant.pk: (expected_image_name,)},+ )++ random_data.assign_media_to_product_variants()++ assert list(+ VariantMedia.objects.filter(variant=variant).values_list("media_id", flat=True)+ ) == [expected_media.pk]+++def test_create_tax_classes_is_idempotent(db):+ juice_product_type = ProductType.objects.create(+ name="Juice",+ slug="juice",+ kind=ProductTypeKind.NORMAL,+ )+ expected_tax_classes = {+ 1: "Groceries",+ 2: "Books",+ 3: "No taxes",+ }+ expected_default_rate_count = 9+ expected_tax_class_rate_count = 25+ assert juice_product_type.tax_class_id is None++ for _ in random_data.create_tax_classes():+ pass+ for _ in random_data.create_tax_classes():+ pass++ assert (+ dict(+ TaxClass.objects.filter(pk__in=expected_tax_classes).values_list(+ "pk", "name"+ )+ )+ == expected_tax_classes+ )+ assert (+ TaxClassCountryRate.objects.filter(tax_class=None).count()+ == expected_default_rate_count+ )+ assert (+ TaxClassCountryRate.objects.filter(+ tax_class_id__in=expected_tax_classes+ ).count()+ == expected_tax_class_rate_count+ )+ books_france_rate = TaxClassCountryRate.objects.get(+ tax_class_id=random_data.BOOKS_TAX_CLASS_PK,+ country="FR",+ )+ assert books_france_rate.rate == Decimal("5.5")+ juice_product_type.refresh_from_db(fields=("tax_class",))+ assert juice_product_type.tax_class_id == random_data.GROCERIES_TAX_CLASS_PK+++def test_create_attribute_file_values_is_idempotent(+ file_attribute, icon_image, media_root, monkeypatch, tmp_path+):+ file_name = "sample.png"+ content_type = "image/png"+ source_dir = tmp_path / random_data.ATTRIBUTE_FILES_DIR+ source_dir.mkdir()+ (source_dir / file_name).write_bytes(icon_image.read())+ attribute_value = AttributeValue.objects.create(+ attribute=file_attribute,+ name=file_name,+ slug="sample-file",+ )+ monkeypatch.setattr(+ random_data,+ "ATTRIBUTE_FILE_MAPPING",+ {attribute_value.pk: (file_name, content_type)},+ )+ expected_storage_path = f"file_upload/{file_name}"++ random_data.create_attribute_file_values(str(tmp_path))+ random_data.create_attribute_file_values(str(tmp_path))++ attribute_value.refresh_from_db(fields=("file_url", "content_type"))+ assert attribute_value.file_url == expected_storage_path+ assert attribute_value.content_type == content_type+ assert default_storage.exists(expected_storage_path) is True+ assert default_storage.listdir("file_upload") == ([], [file_name])+++def test_create_attribute_file_values_rejects_invalid_mime_type(+ file_attribute, media_root, monkeypatch, tmp_path+):+ file_name = "invalid.png"+ content_type = "image/png"+ source_dir = tmp_path / random_data.ATTRIBUTE_FILES_DIR+ source_dir.mkdir()+ (source_dir / file_name).write_bytes(b"invalid image content")+ attribute_value = AttributeValue.objects.create(+ attribute=file_attribute,+ name=file_name,+ slug="invalid-file",+ )+ monkeypatch.setattr(+ random_data,+ "ATTRIBUTE_FILE_MAPPING",+ {attribute_value.pk: (file_name, content_type)},+ )+ expected_storage_path = f"file_upload/{file_name}"++ with pytest.raises(+ ValueError,+ match="does not match its allowed content type image/png",+ ):+ random_data.create_attribute_file_values(str(tmp_path))++ attribute_value.refresh_from_db(fields=("file_url", "content_type"))+ assert attribute_value.file_url is None+ assert attribute_value.content_type is None+ assert default_storage.exists(expected_storage_path) is False+++def test_create_catalogue_promotions(db):+ how_many = 5+ for _ in random_data.create_channels():+ pass+ channel_count = Channel.objects.count()+ expected_rule_count = how_many * 2++ for _ in random_data.create_catalogue_promotions(how_many):+ pass++ assert Promotion.objects.all().count() == how_many+ assert PromotionRule.objects.all().count() == expected_rule_count+ assert (+ list(+ PromotionRule.objects.annotate(channel_count=Count("channels"))+ .order_by("pk")+ .values_list("channel_count", flat=True)+ )+ == [channel_count] * expected_rule_count+ )++ for _ in random_data.create_catalogue_promotions(how_many):+ pass++ assert Promotion.objects.all().count() == how_many+ assert PromotionRule.objects.all().count() == expected_rule_count+ assert (+ list(+ PromotionRule.objects.annotate(channel_count=Count("channels"))+ .order_by("pk")+ .values_list("channel_count", flat=True)+ )+ == [channel_count] * expected_rule_count+ )+++def test_create_order_promotions(db):+ how_many = 5+ for _ in random_data.create_channels():+ pass+ channel_count = Channel.objects.count()+ expected_rule_count = how_many * 2++ for _ in random_data.create_order_promotions(how_many):+ pass++ assert Promotion.objects.all().count() == how_many+ assert PromotionRule.objects.all().count() == expected_rule_count+ assert (+ list(+ PromotionRule.objects.annotate(channel_count=Count("channels"))+ .order_by("pk")+ .values_list("channel_count", flat=True)+ )+ == [channel_count] * expected_rule_count+ )++ for _ in random_data.create_order_promotions(how_many):+ pass++ assert Promotion.objects.all().count() == how_many+ assert PromotionRule.objects.all().count() == expected_rule_count+ assert (+ list(+ PromotionRule.objects.annotate(channel_count=Count("channels"))+ .order_by("pk")+ .values_list("channel_count", flat=True)+ )+ == [channel_count] * expected_rule_count+ )+++def test_create_vouchers(db):+ voucher_count = 4+ single_use_voucher_name = "Single Use Vouchers"+ single_use_code_count = 50+ single_use_codes = {+ f"SINGLE-USE-{index:03}" for index in range(1, single_use_code_count + 1)+ }+ expected_code_count = single_use_code_count + voucher_count - 1+ channel_count = 0+ for _ in random_data.create_channels():+ channel_count += 1+ assert Voucher.objects.all().count() == 0+ for _ in random_data.create_vouchers():+ pass+ assert Voucher.objects.all().count() == voucher_count+ assert VoucherCode.objects.all().count() == expected_code_count+ assert VoucherChannelListing.objects.all().count() == voucher_count * channel_count+ single_use_voucher = Voucher.objects.get(name=single_use_voucher_name)+ assert (+ set(single_use_voucher.codes.values_list("code", flat=True)) == single_use_codes+ )++ for _ in random_data.create_vouchers():+ pass++ assert Voucher.objects.all().count() == voucher_count+ assert VoucherCode.objects.all().count() == expected_code_count+ assert VoucherChannelListing.objects.all().count() == voucher_count * channel_count+ single_use_voucher = Voucher.objects.get(name=single_use_voucher_name)+ assert (+ set(single_use_voucher.codes.values_list("code", flat=True)) == single_use_codes+ )+++def test_create_gift_card(+ db, product, shippable_gift_card_product, customer_user, staff_user, order+):+ product = shippable_gift_card_product+ product.name = "Gift card 100"+ product.save(update_fields=["name"])++ amount = 5+ assert GiftCard.objects.count() == 0+ assert GiftCardEvent.objects.count() == 0+ for _ in random_data.create_gift_cards(amount):+ pass+ assert GiftCard.objects.count() == amount * 2+ assert GiftCardEvent.objects.count() == amount * 2diff --git a/saleor/core/management/commands/populatedb.py b/saleor/core/management/commands/populatedb.pyindex e7294e4c49..dec10b1495 100644--- a/saleor/core/management/commands/populatedb.py+++ b/saleor/core/management/commands/populatedb.py@@ -6,7 +6,7 @@ from django.core.management.base import BaseCommandfrom django.db import connectionfrom ....account.tests.fixtures.user import dangerously_get_or_create_superuser-from ...utils.random_data import (+from ...development.random_data import (add_address_to_admin,create_catalogue_promotions,create_channels,diff --git a/saleor/core/tests/checks/__init__.py b/saleor/core/tests/checks/__init__.pynew file mode 100644index 0000000000..3c78c6ac5b--- /dev/null+++ b/saleor/core/tests/checks/__init__.py@@ -0,0 +1,6 @@+"""Module containing check scripts to assert specific behaviors.++The ``checks`` module contains independent check scripts that are not+intended for pytest to run. Instead, they are only expected to be invoked+in certain configurations (either manually, or in CI/CDs)+"""diff --git a/saleor/core/tests/checks/check_celery_starts.py b/saleor/core/tests/checks/check_celery_starts.pynew file mode 100644index 0000000000..d8294ddac5--- /dev/null+++ b/saleor/core/tests/checks/check_celery_starts.py@@ -0,0 +1,73 @@+"""Ensures Celery worker and Celery beat are both able to boot."""++import multiprocessing+import os.path+import socket+import tempfile+import time++from saleor.celeryconf import app++STARTUP_TIMEOUT_SECONDS = 30+PING_TIMEOUT_SECONDS = 1+WORKER_NAME = f"celery-start-check@{socket.gethostname()}"+++def run_celery_worker(schedule_filename: str) -> None:+ app.worker_main(+ [+ "worker",+ "--loglevel=info",+ f"--hostname={WORKER_NAME}",+ # Run beat alongside the Celery worker so we can test both+ "--beat",+ # Create a state file for schedules+ f"--schedule={schedule_filename}",+ ]+ )+++def wait_until_ready(worker_process: multiprocessing.Process) -> None:+ deadline = time.monotonic() + STARTUP_TIMEOUT_SECONDS+ while time.monotonic() < deadline:+ if not worker_process.is_alive():+ raise RuntimeError("Celery worker stopped before it became ready.")++ responses = app.control.inspect(+ destination=[WORKER_NAME], timeout=PING_TIMEOUT_SECONDS+ ).ping()+ if responses is not None:+ assert responses == {WORKER_NAME: {"ok": "pong"}}+ return++ time.sleep(0.1)++ raise TimeoutError(+ f"Celery worker did not become ready within {STARTUP_TIMEOUT_SECONDS}s."+ )+++def main() -> None:+ if not app.conf.broker_url:+ raise RuntimeError("CELERY_BROKER_URL must be configured to run this check.")++ with tempfile.TemporaryDirectory() as tmp_dir:+ schedule_filename = os.path.join(tmp_dir, "celerybeat-schedule")+ worker_process = multiprocessing.Process(+ target=run_celery_worker,+ args=(schedule_filename,),+ )+ worker_process.start()++ try:+ wait_until_ready(worker_process)+ finally:+ worker_process.terminate()+ worker_process.join(timeout=PING_TIMEOUT_SECONDS)+ if worker_process.is_alive():+ worker_process.kill()+ worker_process.join()+++if __name__ == "__main__":+ main()diff --git a/saleor/core/tests/test_core.py b/saleor/core/tests/test_core.pyindex af89a0eea5..5ab5505560 100644--- a/saleor/core/tests/test_core.py+++ b/saleor/core/tests/test_core.py@@ -1,35 +1,18 @@-from decimal import Decimal-from unittest.mock import Mock, patch+from unittest.mock import patchfrom urllib.parse import urljoinimport pytest-from django.core.files.storage import default_storagefrom django.core.management import CommandError, call_command-from django.db.models import Countfrom django.db.utils import DataErrorfrom django.templatetags.static import staticfrom django.test import RequestFactory, override_settings-from django.utils.crypto import get_random_string-from ...account.models import Address, User-from ...account.tests.fixtures.user import dangerously_get_or_create_superuser+from ...account.models import Userfrom ...attribute.models import AttributeValue-from ...channel.models import Channel-from ...discount.models import (- Promotion,- PromotionRule,- Voucher,- VoucherChannelListing,- VoucherCode,-)-from ...giftcard.models import GiftCard, GiftCardEvent-from ...order import OrderOriginfrom ...order.models import Orderfrom ...payment.models import TransactionItemfrom ...product import ProductTypeKind-from ...product.models import Product, ProductMedia, ProductType, VariantMedia-from ...shipping.models import ShippingZone-from ...tax.models import TaxClass, TaxClassCountryRate+from ...product.models import ProductTypefrom ..storages import S3MediaStoragefrom ..utils import (build_absolute_uri,@@ -38,7 +21,6 @@ from ..utils import (get_domain,is_ssl_enabled,prepare_unique_attribute_value_slug,- random_data,)type_schema = {@@ -73,427 +55,6 @@ def test_get_client_ip(ip_address, expected_ip):assert get_client_ip(request) == expected_ip-def test_create_superuser(db, client, media_root):- credentials = {- "email": "[email protected]",- "password": get_random_string(length=50),- }- # Test admin creation- assert User.objects.all().count() == 0- dangerously_get_or_create_superuser(**credentials)- assert User.objects.all().count() == 1- admin = User.objects.all().first()- assert admin.is_superuser- assert not admin.avatar- # Test duplicating- dangerously_get_or_create_superuser(**credentials)- assert User.objects.all().count() == 1---def test_create_shipping_zones(db):- assert ShippingZone.objects.all().count() == 0- for _ in random_data.create_shipping_zones():- pass- assert ShippingZone.objects.all().count() == 5---def test_create_channels(db):- assert Channel.objects.all().count() == 0- for _ in random_data.create_channels():- pass- assert Channel.objects.all().count() == 2- assert Channel.objects.get(slug="channel-pln")---@override_settings(DEFAULT_CHANNEL_SLUG="test-slug")-def test_create_channels_with_default_channel_slug(db):- assert Channel.objects.all().count() == 0- for _ in random_data.create_channels():- pass- assert Channel.objects.all().count() == 2- assert Channel.objects.get(slug="test-slug")---def test_create_fake_user(db):- assert User.objects.all().count() == 0- random_data.create_fake_user(get_random_string(length=50))- assert User.objects.all().count() == 1- user = User.objects.all().first()- assert not user.is_superuser---def test_create_fake_users(db):- how_many = 5- for _ in random_data.create_users(get_random_string(length=50), how_many):- pass- assert User.objects.all().count() == 5---def test_create_address(db):- assert not Address.objects.exists()- random_data.create_address()- assert Address.objects.all().count() == 1---def test_create_fake_order(db, monkeypatch, image, media_root, warehouse):- # Tests shouldn't depend on images present in placeholder folder- monkeypatch.setattr(- "saleor.core.utils.random_data.get_image", Mock(return_value=image)- )- for _ in random_data.create_channels():- pass- for _ in random_data.create_shipping_zones():- pass- for _ in random_data.create_users(get_random_string(length=50), 3):- pass- for _ in random_data.create_page_type():- pass- for _ in random_data.create_pages():- pass- random_data.create_products_by_schema("/", False)- how_many_orders = 2- for _ in random_data.create_orders(how_many_orders):- pass- assert Order.objects.all().count() == how_many_orders- assert (- list(Order.objects.values_list("origin", flat=True))- == [OrderOrigin.CHECKOUT] * how_many_orders- )---def test_create_products_deletes_retired_products(product_type, category):- retired_product_pks = (127, 132, 133)- Product.objects.bulk_create(- [- Product(- pk=product_pk,- name=f"Retired product {product_pk}",- slug=f"retired-product-{product_pk}",- product_type=product_type,- category=category,- )- for product_pk in retired_product_pks- ]- )- current_product = Product.objects.create(- name="Current product",- slug="current-product",- product_type=product_type,- category=category,- )- assert set(- Product.objects.filter(pk__in=retired_product_pks).values_list("pk", flat=True)- ) == set(retired_product_pks)-- random_data.create_products([], "/", False)-- assert Product.objects.filter(pk__in=retired_product_pks).exists() is False- assert Product.objects.get(pk=current_product.pk) == current_product---def test_create_missing_product_images_does_not_duplicate_images(product, monkeypatch):- placeholder_dir = "/placeholder"- existing_image_name = "existing.png"- missing_image_name = "missing.png"- image_names = (existing_image_name, missing_image_name)- ProductMedia.objects.create(- product=product, image=f"products/{existing_image_name}"- )-- def create_product_image(product, _placeholder_dir, image_name):- return ProductMedia.objects.create(- product=product, image=f"products/{image_name}"- )-- create_product_image_mock = Mock(side_effect=create_product_image)- monkeypatch.setattr(random_data, "create_product_image", create_product_image_mock)-- random_data.create_missing_product_images(product, placeholder_dir, image_names)- random_data.create_missing_product_images(product, placeholder_dir, image_names)-- assert set(product.media.values_list("image", flat=True)) == {- f"products/{existing_image_name}",- f"products/{missing_image_name}",- }- create_product_image_mock.assert_called_once_with(- product, placeholder_dir, missing_image_name- )---def test_get_matching_placeholder_image_name_with_storage_suffix():- image_name = "sample.png"- stored_image_name = "products/sample_8f3a1.png"-- result = random_data.get_matching_placeholder_image_name(- stored_image_name, (image_name, "other.png")- )-- assert result == image_name---def test_assign_media_to_product_variants_removes_stale_relations(variant, monkeypatch):- expected_image_name = "expected.png"- expected_media = ProductMedia.objects.create(- product=variant.product, image=f"products/{expected_image_name}"- )- stale_media = ProductMedia.objects.create(- product=variant.product, image="products/stale.png"- )- VariantMedia.objects.bulk_create(- [- VariantMedia(variant=variant, media=expected_media),- VariantMedia(variant=variant, media=stale_media),- ]- )- monkeypatch.setattr(- random_data,- "IMAGES_MAPPING",- {variant.product_id: [expected_image_name]},- )- monkeypatch.setattr(- random_data,- "VARIANT_IMAGES_MAPPING",- {variant.pk: (expected_image_name,)},- )-- random_data.assign_media_to_product_variants()-- assert list(- VariantMedia.objects.filter(variant=variant).values_list("media_id", flat=True)- ) == [expected_media.pk]---def test_create_tax_classes_is_idempotent(db):- juice_product_type = ProductType.objects.create(- name="Juice",- slug="juice",- kind=ProductTypeKind.NORMAL,- )- expected_tax_classes = {- 1: "Groceries",- 2: "Books",- 3: "No taxes",- }- expected_default_rate_count = 9- expected_tax_class_rate_count = 25- assert juice_product_type.tax_class_id is None-- for _ in random_data.create_tax_classes():- pass- for _ in random_data.create_tax_classes():- pass-- assert (- dict(- TaxClass.objects.filter(pk__in=expected_tax_classes).values_list(- "pk", "name"- )- )- == expected_tax_classes- )- assert (- TaxClassCountryRate.objects.filter(tax_class=None).count()- == expected_default_rate_count- )- assert (- TaxClassCountryRate.objects.filter(- tax_class_id__in=expected_tax_classes- ).count()- == expected_tax_class_rate_count- )- books_france_rate = TaxClassCountryRate.objects.get(- tax_class_id=random_data.BOOKS_TAX_CLASS_PK,- country="FR",- )- assert books_france_rate.rate == Decimal("5.5")- juice_product_type.refresh_from_db(fields=("tax_class",))- assert juice_product_type.tax_class_id == random_data.GROCERIES_TAX_CLASS_PK---def test_create_attribute_file_values_is_idempotent(- file_attribute, icon_image, media_root, monkeypatch, tmp_path-):- file_name = "sample.png"- content_type = "image/png"- source_dir = tmp_path / random_data.ATTRIBUTE_FILES_DIR- source_dir.mkdir()- (source_dir / file_name).write_bytes(icon_image.read())- attribute_value = AttributeValue.objects.create(- attribute=file_attribute,- name=file_name,- slug="sample-file",- )- monkeypatch.setattr(- random_data,- "ATTRIBUTE_FILE_MAPPING",- {attribute_value.pk: (file_name, content_type)},- )- expected_storage_path = f"file_upload/{file_name}"-- random_data.create_attribute_file_values(str(tmp_path))- random_data.create_attribute_file_values(str(tmp_path))-- attribute_value.refresh_from_db(fields=("file_url", "content_type"))- assert attribute_value.file_url == expected_storage_path- assert attribute_value.content_type == content_type- assert default_storage.exists(expected_storage_path) is True- assert default_storage.listdir("file_upload") == ([], [file_name])---def test_create_attribute_file_values_rejects_invalid_mime_type(- file_attribute, media_root, monkeypatch, tmp_path-):- file_name = "invalid.png"- content_type = "image/png"- source_dir = tmp_path / random_data.ATTRIBUTE_FILES_DIR- source_dir.mkdir()- (source_dir / file_name).write_bytes(b"invalid image content")- attribute_value = AttributeValue.objects.create(- attribute=file_attribute,- name=file_name,- slug="invalid-file",- )- monkeypatch.setattr(- random_data,- "ATTRIBUTE_FILE_MAPPING",- {attribute_value.pk: (file_name, content_type)},- )- expected_storage_path = f"file_upload/{file_name}"-- with pytest.raises(- ValueError,- match="does not match its allowed content type image/png",- ):- random_data.create_attribute_file_values(str(tmp_path))-- attribute_value.refresh_from_db(fields=("file_url", "content_type"))- assert attribute_value.file_url is None- assert attribute_value.content_type is None- assert default_storage.exists(expected_storage_path) is False---def test_create_catalogue_promotions(db):- how_many = 5- for _ in random_data.create_channels():- pass- channel_count = Channel.objects.count()- expected_rule_count = how_many * 2-- for _ in random_data.create_catalogue_promotions(how_many):- pass-- assert Promotion.objects.all().count() == how_many- assert PromotionRule.objects.all().count() == expected_rule_count- assert (- list(- PromotionRule.objects.annotate(channel_count=Count("channels"))- .order_by("pk")- .values_list("channel_count", flat=True)- )- == [channel_count] * expected_rule_count- )-- for _ in random_data.create_catalogue_promotions(how_many):- pass-- assert Promotion.objects.all().count() == how_many- assert PromotionRule.objects.all().count() == expected_rule_count- assert (- list(- PromotionRule.objects.annotate(channel_count=Count("channels"))- .order_by("pk")- .values_list("channel_count", flat=True)- )- == [channel_count] * expected_rule_count- )---def test_create_order_promotions(db):- how_many = 5- for _ in random_data.create_channels():- pass- channel_count = Channel.objects.count()- expected_rule_count = how_many * 2-- for _ in random_data.create_order_promotions(how_many):- pass-- assert Promotion.objects.all().count() == how_many- assert PromotionRule.objects.all().count() == expected_rule_count- assert (- list(- PromotionRule.objects.annotate(channel_count=Count("channels"))- .order_by("pk")- .values_list("channel_count", flat=True)- )- == [channel_count] * expected_rule_count- )-- for _ in random_data.create_order_promotions(how_many):- pass-- assert Promotion.objects.all().count() == how_many- assert PromotionRule.objects.all().count() == expected_rule_count- assert (- list(- PromotionRule.objects.annotate(channel_count=Count("channels"))- .order_by("pk")- .values_list("channel_count", flat=True)- )- == [channel_count] * expected_rule_count- )---def test_create_vouchers(db):- voucher_count = 4- single_use_voucher_name = "Single Use Vouchers"- single_use_code_count = 50- single_use_codes = {- f"SINGLE-USE-{index:03}" for index in range(1, single_use_code_count + 1)- }- expected_code_count = single_use_code_count + voucher_count - 1- channel_count = 0- for _ in random_data.create_channels():- channel_count += 1- assert Voucher.objects.all().count() == 0- for _ in random_data.create_vouchers():- pass- assert Voucher.objects.all().count() == voucher_count- assert VoucherCode.objects.all().count() == expected_code_count- assert VoucherChannelListing.objects.all().count() == voucher_count * channel_count- single_use_voucher = Voucher.objects.get(name=single_use_voucher_name)- assert (- set(single_use_voucher.codes.values_list("code", flat=True)) == single_use_codes- )-- for _ in random_data.create_vouchers():- pass-- assert Voucher.objects.all().count() == voucher_count- assert VoucherCode.objects.all().count() == expected_code_count- assert VoucherChannelListing.objects.all().count() == voucher_count * channel_count- single_use_voucher = Voucher.objects.get(name=single_use_voucher_name)- assert (- set(single_use_voucher.codes.values_list("code", flat=True)) == single_use_codes- )---def test_create_gift_card(- db, product, shippable_gift_card_product, customer_user, staff_user, order-):- product = shippable_gift_card_product- product.name = "Gift card 100"- product.save(update_fields=["name"])-- amount = 5- assert GiftCard.objects.count() == 0- assert GiftCardEvent.objects.count() == 0- for _ in random_data.create_gift_cards(amount):- pass- assert GiftCard.objects.count() == amount * 2- assert GiftCardEvent.objects.count() == amount * 2--@patch("storages.backends.s3boto3.S3Boto3Storage")def test_storages_set_s3_bucket_domain(storage, settings):settings.AWS_MEDIA_BUCKET_NAME = "media-bucket"diff --git a/saleor/core/utils/anonymization.py b/saleor/core/utils/anonymization.pyindex 995ec8703a..5be3fc94fa 100644--- a/saleor/core/utils/anonymization.py+++ b/saleor/core/utils/anonymization.py@@ -1,12 +1,15 @@import copy+import datetimeimport logging+import unicodedatafrom typing import TYPE_CHECKING+from django.conf import settings+from django.db import connectionfrom faker import Fakerfrom ...account.models import Address, Userfrom ...checkout.utils import get_or_create_checkout_metadata-from .random_data import create_address, create_fake_userif TYPE_CHECKING:from ...checkout.models import Checkout@@ -21,26 +24,77 @@ def _fake_save(*args, **kwargs):logger.error("Unable to save fake instance")-def generate_fake_address() -> "Address":+def get_email(first_name, last_name):+ _first = unicodedata.normalize("NFD", first_name).encode("ascii", "ignore")+ _last = unicodedata.normalize("NFD", last_name).encode("ascii", "ignore")+ decoded_first = _first.lower().decode("utf-8")+ decoded_last = _last.lower().decode("utf-8")+ return f"{decoded_first}.{decoded_last}@example.com"+++def generate_fake_address(*, with_fake_save: bool = True, **kwargs) -> Address:"""Generate a fake instance of the "Address" class.The instance cannot be saved"""- fake_address = create_address(save=False)++ address = Address(+ first_name=fake.first_name(),+ last_name=fake.last_name(),+ street_address_1=fake.street_address(),+ city=fake.city(),+ country=settings.DEFAULT_COUNTRY,+ **kwargs,+ )++ if address.country == "US":+ state = fake.state_abbr(include_territories=False)+ address.country_area = state+ address.postal_code = fake.postalcode_in_state(state)+ else:+ address.postal_code = fake.postalcode()+# Prevent accidental saving of the instance- fake_address.save = _fake_save- return fake_address+ if with_fake_save:+ address.save = _fake_save # type: ignore[method-assign]+ return address-def generate_fake_user() -> "User":+def generate_fake_user(+ *, with_fake_save: bool = True, generate_id: bool = True+) -> tuple[User, Address]:"""Generate a fake instance of the "User" class.The instance cannot be saved"""- fake_user = create_fake_user(user_password=None, save=False, generate_id=True)++ address = generate_fake_address(with_fake_save=with_fake_save)+ email = get_email(address.first_name, address.last_name)++ user_params = {+ "first_name": address.first_name,+ "last_name": address.last_name,+ "email": email,+ "default_billing_address": address,+ "default_shipping_address": address,+ "is_active": True,+ "note": fake.paragraph(),+ "date_joined": fake.date_time(tzinfo=datetime.UTC),+ }++ if generate_id:+ _, max_user_id = connection.ops.integer_field_range(+ User.id.field.get_internal_type()+ )+ user_params["id"] = fake.random_int(min=1, max=max_user_id)++ fake_user = User(**user_params)+ fake_user.set_unusable_password()+# Prevent accidental saving of the instance- fake_user.save = _fake_save- return fake_user+ if with_fake_save:+ fake_user.save = _fake_save # type: ignore[method-assign]+ return fake_user, addressdef generate_fake_metadata() -> dict[str, str]:@@ -56,7 +110,7 @@ def anonymize_order(order: "Order") -> "Order":anonymized_order = copy.deepcopy(order)# Prevent accidental saving of the instanceanonymized_order.save = _fake_save # type: ignore[method-assign]- fake_user = generate_fake_user()+ fake_user, _fake_address = generate_fake_user()anonymized_order.user = fake_useranonymized_order.user_email = fake_user.emailanonymized_order.shipping_address = generate_fake_address()@@ -75,7 +129,7 @@ def anonymize_checkout(checkout: "Checkout") -> "Checkout":anonymized_checkout = copy.deepcopy(checkout)# Prevent accidental saving of the instanceanonymized_checkout.save = _fake_save # type: ignore[method-assign]- fake_user = generate_fake_user()+ fake_user, _fake_address = generate_fake_user()anonymized_checkout.user = fake_useranonymized_checkout.email = fake_user.emailanonymized_checkout.shipping_address = generate_fake_address()diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.pyindex 401120eb97..76b8810d30 100644--- a/saleor/webhook/payloads.py+++ b/saleor/webhook/payloads.py@@ -914,18 +914,22 @@ def generate_fulfillment_lines_payload(fulfillment: Fulfillment):)),"total_price_net_amount": (- lambda fl: quantize_price(- fl.order_line.undiscounted_unit_price.net.amount,- fl.order_line.currency,+ lambda fl: (+ quantize_price(+ fl.order_line.undiscounted_unit_price.net.amount,+ fl.order_line.currency,+ )+ * fl.quantity)- * fl.quantity),"total_price_gross_amount": (- lambda fl: quantize_price(- fl.order_line.undiscounted_unit_price.gross.amount,- fl.order_line.currency,+ lambda fl: (+ quantize_price(+ fl.order_line.undiscounted_unit_price.gross.amount,+ fl.order_line.currency,+ )+ * fl.quantity)- * fl.quantity),"currency": lambda fl: fl.order_line.currency,"warehouse_id": lambda fl: (@@ -1137,7 +1141,7 @@ def generate_sample_payload(event_name: str) -> dict | None:]if event_name in user_events:- user = generate_fake_user()+ user, _fake_address = generate_fake_user()payload = generate_customer_payload(user)elif event_name == WebhookEventAsyncType.PRODUCT_CREATED:product = _get_sample_object(Product.objects.all())