Skip to content

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

Added possibility to filter out db queries tests assertions

Mikail KOCAK43f7a918e3a9
diff --git a/tests/api/test_core_reordering.py b/tests/api/test_core_reordering.py
index c93484b352..c033f4d305 100644
--- a/tests/api/test_core_reordering.py
+++ b/tests/api/test_core_reordering.py
@@ -211,7 +211,7 @@ def test_reordering_null_sort_orders(dummy_attribute):
assert actual == expected
-def test_reordering_nothing(sorted_entries_seq, django_assert_num_queries):
+def test_reordering_nothing(sorted_entries_seq, assert_num_queries):
"""
Ensures giving operations that does nothing, are skipped. Thus only one query should
have been made: fetching the nodes.
@@ -220,24 +220,22 @@ def test_reordering_nothing(sorted_entries_seq, django_assert_num_queries):
pk = sorted_entries_seq[0].pk
operations = {pk: 0}
- with django_assert_num_queries(1) as ctx:
+ with assert_num_queries(1) as ctx:
perform_reordering(qs, operations)
assert ctx[0]["sql"].startswith("SELECT "), "Should only have done a SELECT"
-def test_giving_no_operation_does_no_query(
- sorted_entries_seq, django_assert_num_queries
-):
+def test_giving_no_operation_does_no_query(sorted_entries_seq, assert_num_queries):
"""Ensures giving no operations runs no queries at all."""
qs = SortedModel.objects
- with django_assert_num_queries(0):
+ with assert_num_queries(0):
perform_reordering(qs, {})
-def test_reordering_concurrently(dummy_attribute, django_assert_num_queries):
+def test_reordering_concurrently(dummy_attribute, assert_num_queries):
"""
Ensures users cannot concurrently reorder, they need to wait for the other one
to achieve.
@@ -264,7 +262,7 @@ def test_reordering_concurrently(dummy_attribute, django_assert_num_queries):
operations = {entries[0].pk: +1}
- with django_assert_num_queries(2) as ctx:
+ with assert_num_queries(2) as ctx:
perform_reordering(qs, operations)
assert ctx[0]["sql"] == (
@@ -283,9 +281,7 @@ def test_reordering_concurrently(dummy_attribute, django_assert_num_queries):
)
-def test_reordering_deleted_node_from_concurrent(
- dummy_attribute, django_assert_num_queries
-):
+def test_reordering_deleted_node_from_concurrent(dummy_attribute, assert_num_queries):
"""
Ensures if a node was deleted before locking, it just skip it instead of
raising an error.
@@ -309,7 +305,7 @@ def test_reordering_deleted_node_from_concurrent(
operations = {-1: +1, entries[0].pk: +1}
- with django_assert_num_queries(2) as ctx:
+ with assert_num_queries(2) as ctx:
perform_reordering(qs, operations)
assert ctx[1]["sql"] == (
diff --git a/tests/api/test_graphql.py b/tests/api/test_graphql.py
index 9757b91eaf..ca633b63d4 100644
--- a/tests/api/test_graphql.py
+++ b/tests/api/test_graphql.py
@@ -20,16 +20,14 @@ from saleor.graphql.utils import (
from tests.api.utils import get_graphql_content
-def test_middleware_dont_generate_sql_requests(
- client, settings, django_assert_num_queries
-):
+def test_middleware_dont_generate_sql_requests(client, settings, assert_num_queries):
"""When requesting on the GraphQL API endpoint, no SQL request should happen
indirectly. This test ensures that."""
# Enables the Graphql playground
settings.DEBUG = True
- with django_assert_num_queries(0):
+ with assert_num_queries(0):
response = client.get(reverse("api"))
assert response.status_code == 200
diff --git a/tests/conftest.py b/tests/conftest.py
index d7d8e21b7c..f85262f283 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1,16 +1,21 @@
import uuid
+from contextlib import contextmanager
from decimal import Decimal
+from functools import partial
from io import BytesIO
-from typing import List
+from typing import List, Optional
from unittest.mock import MagicMock, Mock
import pytest
+from django.conf import settings
from django.contrib.auth.models import Permission
from django.contrib.sites.models import Site
from django.core.files import File
from django.core.files.uploadedfile import SimpleUploadedFile
+from django.db import connection
from django.forms import ModelForm
from django.test.client import Client
+from django.test.utils import CaptureQueriesContext as BaseCaptureQueriesContext
from django_countries import countries
from PIL import Image
from prices import Money, TaxedMoney
@@ -58,6 +63,91 @@ from saleor.webhook.models import Webhook
from tests.utils import create_image
+class CaptureQueriesContext(BaseCaptureQueriesContext):
+ IGNORED_QUERIES = settings.PATTERNS_IGNORED_IN_QUERY_CAPTURES
+
+ @property
+ def captured_queries(self):
+ # flake8: noqa
+ base_queries = self.connection.queries[
+ self.initial_queries : self.final_queries
+ ]
+ new_queries = []
+
+ def is_query_ignored(sql):
+ for pattern in self.IGNORED_QUERIES:
+ # Ignore the query if matches
+ if pattern.match(sql):
+ return True
+ return False
+
+ for query in base_queries:
+ if not is_query_ignored(query["sql"]):
+ new_queries.append(query)
+
+ return new_queries
+
+
+def _assert_num_queries(context, *, config, num, exact=True, info=None):
+ """
+ Extracted from pytest_django.fixtures._assert_num_queries
+ """
+ yield context
+
+ verbose = config.getoption("verbose") > 0
+ num_performed = len(context)
+
+ if exact:
+ failed = num != num_performed
+ else:
+ failed = num_performed > num
+
+ if not failed:
+ return
+
+ msg = "Expected to perform {} queries {}{}".format(
+ num,
+ "" if exact else "or less ",
+ "but {} done".format(
+ num_performed == 1 and "1 was" or "%d were" % (num_performed,)
+ ),
+ )
+ if info:
+ msg += "\n{}".format(info)
+ if verbose:
+ sqls = (q["sql"] for q in context.captured_queries)
+ msg += "\n\nQueries:\n========\n\n%s" % "\n\n".join(sqls)
+ else:
+ msg += " (add -v option to show queries)"
+ pytest.fail(msg)
+
+
+def capture_queries(pytestconfig):
+ cfg = pytestconfig
+
+ @contextmanager
+ def _capture_queries(
+ num: Optional[int] = None, msg: Optional[str] = None, exact=False
+ ):
+ with CaptureQueriesContext(connection) as ctx:
+ yield ctx
+ if num is not None:
+ _assert_num_queries(ctx, config=cfg, num=num, exact=exact, info=msg)
+
+ return _capture_queries
+
+
+def assert_num_queries(capture_queries):
+ return partial(capture_queries, exact=True)
+
+
+def assert_max_num_queries(capture_queries):
+ return partial(capture_queries, exact=False)
+
+
@pytest.fixture(autouse=True)
def setup_dummy_gateway(settings):
settings.PLUGINS = ["saleor.payment.gateways.dummy.plugin.DummyGatewayPlugin"]
@@ -793,7 +883,7 @@ def voucher_customer(voucher, customer_user):
return VoucherCustomer.objects.create(voucher=voucher, customer_email=email)
def order_line(order, variant):
net = variant.get_price()
gross = Money(amount=net.amount * Decimal(1.23), currency=net.currency)
@@ -837,7 +927,7 @@ def gift_card_created_by_staff(staff_user):
)
def order_with_lines(order, product_type, category, shipping_zone):
product = Product.objects.create(
name="Test product",
diff --git a/tests/settings.py b/tests/settings.py
index afb8bba23b..30bb31adda 100644
--- a/tests/settings.py
+++ b/tests/settings.py
@@ -1,7 +1,27 @@
+import re
+
+from django.utils.functional import SimpleLazyObject
+from typing import List, Pattern, Union
+
# pylint: disable=W0401, W0614
# flake8: noqa
from saleor.settings import * # noqa
+
+def lazy_re_compile(regex, flags=0):
+ """Lazily compile a regex with flags."""
+
+ def _compile():
+ # Compile the regex if it was not passed pre-compiled.
+ if isinstance(regex, str):
+ return re.compile(regex, flags)
+ else:
+ assert not flags, "flags must be empty if regex is passed pre-compiled"
+ return regex
+
+ return SimpleLazyObject(_compile)
+
+
CELERY_TASK_ALWAYS_EAGER = True
SECRET_KEY = "NOTREALLY"
@@ -44,3 +64,7 @@ PASSWORD_HASHERS = ["tests.dummy_password_hasher.DummyHasher"]
EXTENSIONS_MANAGER = "saleor.extensions.manager.ExtensionsManager"
PLUGINS = []
+
+PATTERNS_IGNORED_IN_QUERY_CAPTURES: List[Union[Pattern, SimpleLazyObject]] = [
+ lazy_re_compile(r"^SET\s+")
+]