Skip to content

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

Add unit tests

fowczrek16a085ba5cfd
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
index e43785cced..9c3f95f38f 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
@@ -19,10 +19,6 @@ from .....payment.model_helpers import get_subtotal
from .....plugins import PLUGIN_IDENTIFIER_PREFIX
from .....plugins.manager import get_plugins_manager
from .....plugins.tests.sample_plugins import PluginSample
-from .....plugins.webhook.conftest import ( # noqa: F401
- tax_data_response,
- tax_line_data_response,
-)
from .....webhook.event_types import WebhookEventSyncType
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
index ce7a610e27..7c5c1865d7 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
@@ -25,10 +25,6 @@ from .....payment.model_helpers import get_subtotal
from .....plugins import PLUGIN_IDENTIFIER_PREFIX
from .....plugins.base_plugin import ExcludedShippingMethod
from .....plugins.tests.sample_plugins import PluginSample
-from .....plugins.webhook.conftest import ( # noqa: F401
- tax_data_response,
- tax_line_data_response,
-)
from .....product.models import ProductVariant
from .....warehouse.models import Allocation, PreorderAllocation, Stock
from .....warehouse.tests.utils import get_available_quantity_for_stock
diff --git a/saleor/graphql/webhook/tests/pregenerated_subscription/__init__.py b/saleor/graphql/webhook/tests/pregenerated_subscription/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/webhook/tests/pregenerated_subscription/test_checkout_resolvers.py b/saleor/graphql/webhook/tests/pregenerated_subscription/test_checkout_resolvers.py
new file mode 100644
index 0000000000..2622e490ba
--- /dev/null
+++ b/saleor/graphql/webhook/tests/pregenerated_subscription/test_checkout_resolvers.py
@@ -0,0 +1,54 @@
+from datetime import timedelta
+from unittest import mock
+
+from django.test import override_settings
+from django.utils import timezone
+
+from ....core.utils import to_global_id_or_none
+from ....tests.utils import get_graphql_content
+
+
+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+ "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
+)
+def test_checkout_total_price_use_pregenerated_payload(
+ mock_generate_payload,
+ mock_request,
+ checkout,
+ api_client,
+ tax_data_response,
+ tax_app,
+):
+ # given
+ checkout.price_expiration = timezone.now() - timedelta(days=1)
+ checkout.save()
+ checkout_global_id = to_global_id_or_none(checkout)
+ checkout_total_price_query = """
+ query getCheckout($id: ID!) {
+ checkout(id: $id) {
+ id
+ totalPrice {
+ net {
+ amount
+ }
+ gross {
+ amount
+ }
+ }
+ }
+ }
+ """
+ variables = {"id": checkout_global_id}
+
+ mock_request.return_value = tax_data_response
+
+ # when
+ response = api_client.post_graphql(checkout_total_price_query, variables)
+ content = get_graphql_content(response)
+
+ # then
+ mock_generate_payload.assert_not_called()
+ mock_request.assert_called_once()
+ assert content["data"]["checkout"]["id"] == checkout_global_id
diff --git a/saleor/graphql/webhook/tests/pregenerated_subscription/test_tax_configurations_with_pregenerated_payloads.py b/saleor/graphql/webhook/tests/pregenerated_subscription/test_tax_configurations_with_pregenerated_payloads.py
new file mode 100644
index 0000000000..3c30fd4415
--- /dev/null
+++ b/saleor/graphql/webhook/tests/pregenerated_subscription/test_tax_configurations_with_pregenerated_payloads.py
@@ -0,0 +1,320 @@
+from datetime import timedelta
+from unittest import mock
+
+from django.test import override_settings
+from django.utils import timezone
+
+from .....tax import TaxCalculationStrategy
+from .....tax.models import TaxConfiguration
+from ....core.utils import to_global_id_or_none
+from ....tests.utils import get_graphql_content
+
+
+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+ "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
+)
+def test_pregenerated_payload_with_selected_tax_app_price_entered_with_tax(
+ mock_generate_payload,
+ mock_request,
+ checkout,
+ api_client,
+ tax_data_response,
+ tax_app,
+):
+ # given
+ tax_app_global_id = to_global_id_or_none(tax_app)
+ tax_configuration = TaxConfiguration.objects.get()
+ tax_configuration.tax_calculation_strategy = TaxCalculationStrategy.TAX_APP
+ tax_configuration.prices_entered_with_tax = True
+ tax_configuration.tax_app_id = tax_app_global_id
+ tax_configuration.save()
+ checkout.price_expiration = timezone.now() - timedelta(days=1)
+ checkout.save()
+ checkout_global_id = to_global_id_or_none(checkout)
+ checkout_total_price_query = """
+ query getCheckout($id: ID!) {
+ checkout(id: $id) {
+ id
+ totalPrice {
+ net {
+ amount
+ }
+ gross {
+ amount
+ }
+ }
+ }
+ }
+ """
+ variables = {"id": checkout_global_id}
+
+ mock_request.return_value = tax_data_response
+
+ # when
+ response = api_client.post_graphql(checkout_total_price_query, variables)
+ content = get_graphql_content(response)
+
+ # then
+ mock_generate_payload.assert_not_called()
+ mock_request.assert_called_once()
+ assert content["data"]["checkout"]["id"] == checkout_global_id
+
+
+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+ "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
+)
+def test_pregenerated_payload_with_selected_tax_app_price_entered_without_tax(
+ mock_generate_payload,
+ mock_request,
+ checkout,
+ api_client,
+ tax_data_response,
+ tax_app,
+):
+ # given
+ tax_app_global_id = to_global_id_or_none(tax_app)
+ tax_configuration = TaxConfiguration.objects.get()
+ tax_configuration.tax_calculation_strategy = TaxCalculationStrategy.TAX_APP
+ tax_configuration.prices_entered_with_tax = False
+ tax_configuration.tax_app_id = tax_app_global_id
+ tax_configuration.save()
+ checkout.price_expiration = timezone.now() - timedelta(days=1)
+ checkout.save()
+ checkout_global_id = to_global_id_or_none(checkout)
+ checkout_total_price_query = """
+ query getCheckout($id: ID!) {
+ checkout(id: $id) {
+ id
+ totalPrice {
+ net {
+ amount
+ }
+ gross {
+ amount
+ }
+ }
+ }
+ }
+ """
+ variables = {"id": checkout_global_id}
+
+ mock_request.return_value = tax_data_response
+
+ # when
+ response = api_client.post_graphql(checkout_total_price_query, variables)
+ content = get_graphql_content(response)
+
+ # then
+ mock_generate_payload.assert_not_called()
+ mock_request.assert_called_once()
+ assert content["data"]["checkout"]["id"] == checkout_global_id
+
+
+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+ "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
+)
+def test_pregenerated_payload_with_selected_external_tax_app_price_entered_without_tax(
+ mock_generate_payload,
+ mock_request,
+ checkout,
+ api_client,
+ tax_data_response,
+ external_tax_app,
+):
+ # given
+ tax_configuration = TaxConfiguration.objects.get()
+ tax_configuration.tax_calculation_strategy = TaxCalculationStrategy.TAX_APP
+ tax_configuration.prices_entered_with_tax = False
+ tax_configuration.tax_app_id = external_tax_app.identifier
+ tax_configuration.save()
+ checkout.price_expiration = timezone.now() - timedelta(days=1)
+ checkout.save()
+ checkout_global_id = to_global_id_or_none(checkout)
+ checkout_total_price_query = """
+ query getCheckout($id: ID!) {
+ checkout(id: $id) {
+ id
+ totalPrice {
+ net {
+ amount
+ }
+ gross {
+ amount
+ }
+ }
+ }
+ }
+ """
+ variables = {"id": checkout_global_id}
+
+ mock_request.return_value = tax_data_response
+
+ # when
+ response = api_client.post_graphql(checkout_total_price_query, variables)
+ content = get_graphql_content(response)
+
+ # then
+ mock_generate_payload.assert_not_called()
+ mock_request.assert_called_once()
+ assert content["data"]["checkout"]["id"] == checkout_global_id
+
+
+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+ "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
+)
+def test_pregenerated_payload_with_selected_external_tax_app_price_entered_with_tax(
+ mock_generate_payload,
+ mock_request,
+ checkout,
+ api_client,
+ tax_data_response,
+ external_tax_app,
+):
+ # given
+ tax_configuration = TaxConfiguration.objects.get()
+ tax_configuration.tax_calculation_strategy = TaxCalculationStrategy.TAX_APP
+ tax_configuration.prices_entered_with_tax = True
+ tax_configuration.tax_app_id = external_tax_app.identifier
+ tax_configuration.save()
+ checkout.price_expiration = timezone.now() - timedelta(days=1)
+ checkout.save()
+ checkout_global_id = to_global_id_or_none(checkout)
+ checkout_total_price_query = """
+ query getCheckout($id: ID!) {
+ checkout(id: $id) {
+ id
+ totalPrice {
+ net {
+ amount
+ }
+ gross {
+ amount
+ }
+ }
+ }
+ }
+ """
+ variables = {"id": checkout_global_id}
+
+ mock_request.return_value = tax_data_response
+
+ # when
+ response = api_client.post_graphql(checkout_total_price_query, variables)
+ content = get_graphql_content(response)
+
+ # then
+ mock_generate_payload.assert_not_called()
+ mock_request.assert_called_once()
+ assert content["data"]["checkout"]["id"] == checkout_global_id
+
+
+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+ "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
+)
+def test_pregenerated_payload_with_all_apps_price_entered_with_tax(
+ mock_generate_payload,
+ mock_request,
+ checkout,
+ api_client,
+ tax_data_response,
+ tax_app,
+ external_tax_app,
+):
+ # given
+ tax_configuration = TaxConfiguration.objects.get()
+ tax_configuration.tax_calculation_strategy = TaxCalculationStrategy.TAX_APP
+ tax_configuration.prices_entered_with_tax = True
+ tax_configuration.save()
+ checkout.price_expiration = timezone.now() - timedelta(days=1)
+ checkout.save()
+ checkout_global_id = to_global_id_or_none(checkout)
+ checkout_total_price_query = """
+ query getCheckout($id: ID!) {
+ checkout(id: $id) {
+ id
+ totalPrice {
+ net {
+ amount
+ }
+ gross {
+ amount
+ }
+ }
+ }
+ }
+ """
+ variables = {"id": checkout_global_id}
+
+ # Set response for tax calculation to None to ensure that all apps are called
+ mock_request.return_value = None
+
+ # when
+ response = api_client.post_graphql(checkout_total_price_query, variables)
+ content = get_graphql_content(response)
+
+ # then
+ mock_generate_payload.assert_not_called()
+ assert mock_request.call_count == 2
+ assert content["data"]["checkout"]["id"] == checkout_global_id
+
+
+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+ "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
+)
+def test_pregenerated_payload_with_all_apps_price_entered_without_tax(
+ mock_generate_payload,
+ mock_request,
+ checkout,
+ api_client,
+ tax_data_response,
+ tax_app,
+ external_tax_app,
+):
+ # given
+ tax_configuration = TaxConfiguration.objects.get()
+ tax_configuration.tax_calculation_strategy = TaxCalculationStrategy.TAX_APP
+ tax_configuration.prices_entered_with_tax = False
+ tax_configuration.save()
+ checkout.price_expiration = timezone.now() - timedelta(days=1)
+ checkout.save()
+ checkout_global_id = to_global_id_or_none(checkout)
+ checkout_total_price_query = """
+ query getCheckout($id: ID!) {
+ checkout(id: $id) {
+ id
+ totalPrice {
+ net {
+ amount
+ }
+ gross {
+ amount
+ }
+ }
+ }
+ }
+ """
+ variables = {"id": checkout_global_id}
+
+ # Set response for tax calculation to None to ensure that all apps are called
+ mock_request.return_value = None
+
+ # when
+ response = api_client.post_graphql(checkout_total_price_query, variables)
+ content = get_graphql_content(response)
+
+ # then
+ mock_generate_payload.assert_not_called()
+ assert mock_request.call_count == 2
+ assert content["data"]["checkout"]["id"] == checkout_global_id
diff --git a/saleor/graphql/webhook/tests/pregenerated_subscription/test_utils.py b/saleor/graphql/webhook/tests/pregenerated_subscription/test_utils.py
new file mode 100644
index 0000000000..2894c2195f
--- /dev/null
+++ b/saleor/graphql/webhook/tests/pregenerated_subscription/test_utils.py
@@ -0,0 +1,104 @@
+from .....webhook.models import Webhook
+from ...utils import get_pregenerated_subscription_payload, get_subscription_query_hash
+
+
+def test_get_subscription_query_hash():
+ # given
+ subscription_query = "subscription { orderCreated { id } }"
+
+ # when
+ query_hash = get_subscription_query_hash(subscription_query)
+
+ # then
+ assert query_hash == "6553179c22234d0b8e07d8db49ac9bd2"
+
+
+def test_get_pregenerated_subscription_payload(webhook_app):
+ # given
+ example_payload = {"payload": "example"}
+ subscription_query = "subscription { orderCreated { id } }"
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ target_url="http://www.example.com/any",
+ subscription_query=subscription_query,
+ )
+
+ pregenerated_subscription_payloads = {
+ webhook_app.pk: {"6553179c22234d0b8e07d8db49ac9bd2": example_payload}
+ }
+
+ # when
+ payload = get_pregenerated_subscription_payload(
+ webhook, pregenerated_subscription_payloads
+ )
+
+ # then
+ assert payload == example_payload
+
+
+def test_get_pregenerated_subscription_payload_payload_for_other_app(webhook_app):
+ # given
+ example_payload = {"payload": "example"}
+ subscription_query = "subscription { orderCreated { id } }"
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ target_url="http://www.example.com/any",
+ subscription_query=subscription_query,
+ )
+ invalid_app_id = webhook_app.pk + 1
+
+ pregenerated_subscription_payloads = {
+ invalid_app_id: {"6553179c22234d0b8e07d8db49ac9bd2": example_payload}
+ }
+
+ # when
+ payload = get_pregenerated_subscription_payload(
+ webhook, pregenerated_subscription_payloads
+ )
+
+ # then
+ assert payload is None
+
+
+def test_get_pregenerated_subscription_payload_empty_pregenerated_dict(webhook_app):
+ # given
+ subscription_query = "subscription { orderCreated { id } }"
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ target_url="http://www.example.com/any",
+ subscription_query=subscription_query,
+ )
+
+ pregenerated_subscription_payloads = {}
+
+ # when
+ payload = get_pregenerated_subscription_payload(
+ webhook, pregenerated_subscription_payloads
+ )
+
+ # then
+ assert payload is None
+
+
+def test_get_pregenerated_subscription_payload_webhook_without_subscription(
+ webhook_app,
+):
+ # given
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ target_url="http://www.example.com/any",
+ )
+
+ pregenerated_subscription_payloads = {}
+
+ # when
+ payload = get_pregenerated_subscription_payload(
+ webhook, pregenerated_subscription_payloads
+ )
+
+ # then
+ assert payload is None
diff --git a/saleor/graphql/webhook/utils.py b/saleor/graphql/webhook/utils.py
index e746b10784..61924a5d9b 100644
--- a/saleor/graphql/webhook/utils.py
+++ b/saleor/graphql/webhook/utils.py
@@ -13,18 +13,11 @@ def get_subscription_query_hash(subscription_query: str) -> str:
def get_pregenerated_subscription_payload(
webhook: Webhook,
- subscriptable_object,
pregenerated_subscription_payloads: Optional[dict] = {},
) -> Optional[dict]:
if webhook.subscription_query is None or pregenerated_subscription_payloads is None:
return None
- if not hasattr(subscriptable_object, "pk"):
- logger.warning(
- "Subscriptable object doesn't have a primary key. Skipping usage of pregenerated subscription payload."
- )
- return None
-
query_hash = get_subscription_query_hash(webhook.subscription_query)
return pregenerated_subscription_payloads.get(webhook.app_id, {}).get(
query_hash, None
diff --git a/saleor/plugins/webhook/conftest.py b/saleor/plugins/webhook/conftest.py
index 3ad3b31085..932f56c6c4 100644
--- a/saleor/plugins/webhook/conftest.py
+++ b/saleor/plugins/webhook/conftest.py
@@ -5,34 +5,6 @@ from ...webhook.models import Webhook
from ..manager import get_plugins_manager
-def tax_line_data_response():
- return {
- "id": "1234",
- "currency": "PLN",
- "unit_net_amount": 12.34,
- "unit_gross_amount": 12.34,
- "total_gross_amount": 12.34,
- "total_net_amount": 12.34,
- "tax_rate": 23,
- }
-
-
-def tax_data_response(tax_line_data_response):
- return {
- "currency": "PLN",
- "total_net_amount": 12.34,
- "total_gross_amount": 12.34,
- "subtotal_net_amount": 12.34,
- "subtotal_gross_amount": 12.34,
- "shipping_price_gross_amount": 12.34,
- "shipping_price_net_amount": 12.34,
- "shipping_tax_rate": 23,
- "lines": [tax_line_data_response] * 5,
- }
-
-
@pytest.fixture
def tax_app(app, permission_handle_taxes, webhook):
app.permissions.add(permission_handle_taxes)
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index c25d7d9f48..05cbd498bc 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -3036,7 +3036,8 @@ class WebhookPlugin(BasePlugin):
pregenerated_subscription_payloads: Optional[dict] = {},
):
app = (
- App.objects.filter(
+ App.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)
+ .filter(
identifier=app_identifier,
is_active=True,
)
@@ -3061,7 +3062,7 @@ class WebhookPlugin(BasePlugin):
)
pregenerated_subscription_payload = get_pregenerated_subscription_payload(
- webhook, subscriptable_object, pregenerated_subscription_payloads
+ webhook, pregenerated_subscription_payloads
)
response = trigger_webhook_sync(
event_type=event_type,
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py
index 8e0035c853..513eaba67b 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py
@@ -195,6 +195,37 @@ def test_checkout_calculate_taxes_with_free_shipping_voucher(
}
+@freeze_time("2020-03-18 12:00:00")
+def test_checkout_calculate_taxes_with_pregenerated_payload(
+ checkout_with_voucher_free_shipping,
+ webhook_app,
+ permission_handle_taxes,
+):
+ # given
+ checkout = checkout_with_voucher_free_shipping
+ webhook_app.permissions.add(permission_handle_taxes)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ target_url="http://www.example.com/any",
+ subscription_query=TAXES_SUBSCRIPTION_QUERY,
+ )
+ event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
+ webhook.events.create(event_type=event_type)
+ expected_payload = {"payload": "test"}
+
+ # when
+ deliveries = create_delivery_for_subscription_sync_event(
+ event_type,
+ checkout,
+ webhook,
+ pregenerated_payload=expected_payload,
+ )
+
+ # then
+ assert json.loads(deliveries.payload.payload) == expected_payload
+
+
@freeze_time("2020-03-18 12:00:00")
def test_checkout_calculate_taxes_with_entire_order_voucher(
checkout_with_voucher,
diff --git a/saleor/plugins/webhook/tests/test_tax_webhook.py b/saleor/plugins/webhook/tests/test_tax_webhook.py
index e945c33563..277b1e5999 100644
--- a/saleor/plugins/webhook/tests/test_tax_webhook.py
+++ b/saleor/plugins/webhook/tests/test_tax_webhook.py
@@ -1,6 +1,6 @@
import json
from unittest import mock
-from unittest.mock import sentinel
+from unittest.mock import ANY, sentinel
import pytest
from freezegun import freeze_time
@@ -9,6 +9,7 @@ from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ....core import EventDeliveryStatus
from ....core.models import EventDelivery, EventPayload
from ....core.taxes import TaxType
+from ....graphql.webhook.utils import get_subscription_query_hash
from ....webhook.event_types import WebhookEventSyncType
from ....webhook.models import Webhook
from ....webhook.payloads import generate_order_payload_for_tax_calculation
@@ -199,7 +200,11 @@ def test_get_taxes_for_order_with_sync_subscription(
@freeze_time()
@mock.patch("saleor.checkout.calculations.fetch_checkout_data")
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+ "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
+)
def test_get_taxes_for_checkout_with_sync_subscription(
+ mock_generate_payload,
mock_request,
mock_fetch,
webhook_plugin,
@@ -208,18 +213,19 @@ def test_get_taxes_for_checkout_with_sync_subscription(
tax_app,
):
# given
+ subscription_query = "subscription{event{... on CalculateTaxes{taxBase{currency}}}}"
+ expected_payload = {"taxBase": {"currency": "USD"}}
checkout_info = fetch_checkout_info(
checkout, [], get_plugins_manager(allow_replica=False)
)
mock_request.return_value = tax_data_response
+ mock_generate_payload.return_value = expected_payload
plugin = webhook_plugin()
webhook = Webhook.objects.create(
name="Tax checkout webhook",
app=tax_app,
target_url="https://localhost:8888/tax-order",
- subscription_query=(
- "subscription{event{... on CalculateTaxes{taxBase{currency}}}}"
- ),
+ subscription_query=subscription_query,
)
webhook.events.create(event_type=WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES)
app_identifier = None
@@ -228,8 +234,74 @@ def test_get_taxes_for_checkout_with_sync_subscription(
tax_data = plugin.get_taxes_for_checkout(checkout_info, [], app_identifier, None)
# then
+ mock_generate_payload.assert_called_once_with(
+ event_type=WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
+ subscribable_object=checkout,
+ subscription_query=subscription_query,
+ request=ANY, # SaleorContext,
+ app=tax_app,
+ )
payload = EventPayload.objects.get()
- assert payload.payload == json.dumps({"taxBase": {"currency": "USD"}})
+ assert payload.payload == json.dumps(expected_payload)
+ delivery = EventDelivery.objects.get()
+ assert delivery.status == EventDeliveryStatus.PENDING
+ assert delivery.event_type == WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
+ assert delivery.payload == payload
+ assert delivery.webhook == webhook
+ mock_request.assert_called_once_with(delivery)
+ mock_fetch.assert_not_called()
+ assert tax_data == parse_tax_data(tax_data_response)
+
+
+@freeze_time()
[email protected]("saleor.checkout.calculations.fetch_checkout_data")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+ "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
+)
+def test_get_taxes_for_checkout_with_sync_subscription_with_pregenerated_payload(
+ mock_generate_payload,
+ mock_request,
+ mock_fetch,
+ webhook_plugin,
+ tax_data_response,
+ checkout,
+ tax_app,
+):
+ # given
+ subscription_query = "subscription{event{... on CalculateTaxes{taxBase{currency}}}}"
+ subscription_query_hash = get_subscription_query_hash(subscription_query)
+ expected_payload = {"taxBase": {"currency": "USD"}}
+ checkout_info = fetch_checkout_info(
+ checkout, [], get_plugins_manager(allow_replica=False)
+ )
+ mock_request.return_value = tax_data_response
+ plugin = webhook_plugin()
+ webhook = Webhook.objects.create(
+ name="Tax checkout webhook",
+ app=tax_app,
+ target_url="https://localhost:8888/tax-order",
+ subscription_query=subscription_query,
+ )
+ webhook.events.create(event_type=WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES)
+ app_identifier = None
+ pregenerated_subscription_payloads = {
+ tax_app.id: {subscription_query_hash: expected_payload}
+ }
+
+ # when
+ tax_data = plugin.get_taxes_for_checkout(
+ checkout_info,
+ [],
+ app_identifier,
+ None,
+ pregenerated_subscription_payloads=pregenerated_subscription_payloads,
+ )
+
+ # then
+ mock_generate_payload.assert_not_called()
+ payload = EventPayload.objects.get()
+ assert payload.payload == json.dumps(expected_payload)
delivery = EventDelivery.objects.get()
assert delivery.status == EventDeliveryStatus.PENDING
assert delivery.event_type == WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index f457a6e827..3a52e65820 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -86,6 +86,7 @@ from ..discount.utils.voucher import (
)
from ..giftcard import GiftCardEvents
from ..giftcard.models import GiftCard, GiftCardEvent, GiftCardTag
+from ..graphql.core.utils import to_global_id_or_none
from ..menu.models import Menu, MenuItem, MenuItemTranslation
from ..order import OrderOrigin, OrderStatus
from ..order.actions import cancel_fulfillment, fulfill_order_lines
@@ -7759,6 +7760,8 @@ def payment_method_process_tokenization_app(db, permission_manage_payments):
@pytest.fixture
def tax_app(db, permission_handle_taxes):
app = App.objects.create(name="Tax App", is_active=True)
+ app.identifier = to_global_id_or_none(app)
+ app.save()
app.permissions.add(permission_handle_taxes)
webhook = Webhook.objects.create(
@@ -7779,6 +7782,70 @@ def tax_app(db, permission_handle_taxes):
return app
+def external_tax_app(db, permission_handle_taxes):
+ app = App.objects.create(
+ name="External App",
+ is_active=True,
+ type=AppType.THIRDPARTY,
+ identifier="mirumee.app.simple.tax",
+ about_app="About app text.",
+ data_privacy="Data privacy text.",
+ data_privacy_url="http://www.example.com/privacy/",
+ homepage_url="http://www.example.com/homepage/",
+ support_url="http://www.example.com/support/contact/",
+ configuration_url="http://www.example.com/app-configuration/",
+ app_url="http://www.example.com/app/",
+ )
+ app.tokens.create(name="Default")
+ app.permissions.add(permission_handle_taxes)
+
+ webhook = Webhook.objects.create(
+ name="external-tax-webhook-1",
+ app=app,
+ target_url="https://tax-app.example.com/api/",
+ subscription_query=CALCULATE_TAXES_SUBSCRIPTION_QUERY,
+ )
+ webhook.events.bulk_create(
+ [
+ WebhookEvent(event_type=event_type, webhook=webhook)
+ for event_type in [
+ WebhookEventSyncType.ORDER_CALCULATE_TAXES,
+ WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
+ ]
+ ]
+ )
+ return app
+
+
+def tax_line_data_response():
+ return {
+ "id": "1234",
+ "currency": "PLN",
+ "unit_net_amount": 12.34,
+ "unit_gross_amount": 12.34,
+ "total_gross_amount": 12.34,
+ "total_net_amount": 12.34,
+ "tax_rate": 23,
+ }
+
+
+def tax_data_response(tax_line_data_response):
+ return {
+ "currency": "PLN",
+ "total_net_amount": 12.34,
+ "total_gross_amount": 12.34,
+ "subtotal_net_amount": 12.34,
+ "subtotal_gross_amount": 12.34,
+ "shipping_price_gross_amount": 12.34,
+ "shipping_price_net_amount": 12.34,
+ "shipping_tax_rate": 23,
+ "lines": [tax_line_data_response] * 5,
+ }
+
+
@pytest.fixture
def tax_app_with_subscription_webhooks(db, permission_handle_taxes):
app = App.objects.create(name="Tax App with subscription", is_active=True)
diff --git a/saleor/webhook/transport/synchronous/transport.py b/saleor/webhook/transport/synchronous/transport.py
index dfc79f188c..d1f683a53b 100644
--- a/saleor/webhook/transport/synchronous/transport.py
+++ b/saleor/webhook/transport/synchronous/transport.py
@@ -345,7 +345,7 @@ def trigger_all_webhooks_sync(
)
pregenerated_payload = get_pregenerated_subscription_payload(
- webhook, subscribable_object, pregenerated_subscription_payloads
+ webhook, pregenerated_subscription_payloads
)
delivery = create_delivery_for_subscription_sync_event(