Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add response status code to event delivery attempt (#9456)
Przemysław Ładaf64ad0393137
diff --git a/saleor/core/migrations/0003_eventdeliveryattempt_response_status_code.py b/saleor/core/migrations/0003_eventdeliveryattempt_response_status_code.pynew file mode 100644index 0000000000..872bcae783--- /dev/null+++ b/saleor/core/migrations/0003_eventdeliveryattempt_response_status_code.py@@ -0,0 +1,18 @@+# Generated by Django 3.2.12 on 2022-04-01 10:32++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("core", "0002_initial"),+ ]++ operations = [+ migrations.AddField(+ model_name="eventdeliveryattempt",+ name="response_status_code",+ field=models.PositiveSmallIntegerField(null=True),+ ),+ ]diff --git a/saleor/core/models.py b/saleor/core/models.pyindex 37c4f69195..02f57ea4fc 100644--- a/saleor/core/models.py+++ b/saleor/core/models.py@@ -154,6 +154,7 @@ class EventDeliveryAttempt(models.Model):duration = models.FloatField(null=True)response = models.TextField(null=True)response_headers = models.TextField(null=True)+ response_status_code = models.PositiveSmallIntegerField(null=True)request_headers = models.TextField(null=True)status = models.CharField(max_length=255,diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 782f644bb3..a0a27b06f7 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -1569,6 +1569,7 @@ type EventDeliveryAttempt implements Node {duration: Floatresponse: StringresponseHeaders: String+ responseStatusCode: IntrequestHeaders: String"""Event delivery status."""diff --git a/saleor/graphql/webhook/tests/queries/test_event_delivery_query.py b/saleor/graphql/webhook/tests/queries/test_event_delivery_query.pyindex 1f5ca7310f..e7dad9b0d7 100644--- a/saleor/graphql/webhook/tests/queries/test_event_delivery_query.py+++ b/saleor/graphql/webhook/tests/queries/test_event_delivery_query.py@@ -27,6 +27,7 @@ EVENT_DELIVERY_QUERY = """responserequestHeadersresponseHeaders+ responseStatusCode}}}@@ -73,3 +74,7 @@ def test_webhook_delivery_attempt_query(attempts_response[0]["node"]["responseHeaders"]== event_attempt.response_headers)+ assert (+ attempts_response[0]["node"]["responseStatusCode"]+ == event_attempt.response_status_code+ )diff --git a/saleor/graphql/webhook/types.py b/saleor/graphql/webhook/types.pyindex 333bd27932..bfc14c1a8b 100644--- a/saleor/graphql/webhook/types.py+++ b/saleor/graphql/webhook/types.py@@ -80,6 +80,7 @@ class EventDeliveryAttempt(ModelObjectType):duration = graphene.Float()response = graphene.String()response_headers = graphene.String()+ response_status_code = graphene.Int()request_headers = graphene.String()status = EventDeliveryStatusEnum(description="Event delivery status.", required=Truediff --git a/saleor/plugins/webhook/tasks.py b/saleor/plugins/webhook/tasks.pyindex 677f477b32..bbdc1861e6 100644--- a/saleor/plugins/webhook/tasks.py+++ b/saleor/plugins/webhook/tasks.py@@ -61,6 +61,7 @@ class WebhookResponse:content: strrequest_headers: Optional[Dict] = Noneresponse_headers: Optional[Dict] = None+ response_status_code: Optional[int] = Nonestatus: str = EventDeliveryStatus.SUCCESSduration: float = 0.0@@ -239,6 +240,7 @@ def send_webhook_using_http(content=response.text,request_headers=headers,response_headers=dict(response.headers),+ response_status_code=response.status_code,duration=response.elapsed.total_seconds(),status=(EventDeliveryStatus.SUCCESS if response.ok else EventDeliveryStatus.FAILED@@ -450,6 +452,7 @@ def send_webhook_request_sync(if e.response:response.content = e.response.textresponse.response_headers = dict(e.response.headers)+ response.response_status_code = e.response.status_codeexcept JSONDecodeError as e:logger.warning(diff --git a/saleor/plugins/webhook/tests/test_payment_webhook.py b/saleor/plugins/webhook/tests/test_payment_webhook.pyindex 2ba73fab14..26f23455fd 100644--- a/saleor/plugins/webhook/tests/test_payment_webhook.py+++ b/saleor/plugins/webhook/tests/test_payment_webhook.py@@ -87,11 +87,13 @@ def test_send_webhook_request_sync_failed_attempt(mock_post, app, event_deliveryexpected_data = {"content": '{"key": "response_text"}',"headers": {"header_key": "header_val"},+ "status_code": 500,"duration": datetime.timedelta(seconds=2),}mock_post().ok = Falsemock_post().text = expected_data["content"]mock_post().headers = expected_data["headers"]+ mock_post().status_code = expected_data["status_code"]mock_post().elapsed = expected_data["duration"]# whenresponse_data = send_webhook_request_sync(app.name, event_delivery)@@ -103,6 +105,7 @@ def test_send_webhook_request_sync_failed_attempt(mock_post, app, event_deliveryassert attempt.duration == expected_data["duration"].total_seconds()assert attempt.response == expected_data["content"]assert attempt.response_headers == json.dumps(expected_data["headers"])+ assert attempt.response_status_code == expected_data["status_code"]assert response_data is None@@ -115,11 +118,13 @@ def test_send_webhook_request_sync_successful_attempt(expected_data = {"content": '{"key": "response_text"}',"headers": {"header_key": "header_val"},+ "status_code": 200,"duration": datetime.timedelta(seconds=2),}mock_post().ok = Truemock_post().text = expected_data["content"]mock_post().headers = expected_data["headers"]+ mock_post().status_code = expected_data["status_code"]mock_post().elapsed = expected_data["duration"]# whenresponse_data = send_webhook_request_sync(app.name, event_delivery)@@ -133,6 +138,7 @@ def test_send_webhook_request_sync_successful_attempt(assert attempt.duration == expected_data["duration"].total_seconds()assert attempt.response == expected_data["content"]assert attempt.response_headers == json.dumps(expected_data["headers"])+ assert attempt.response_status_code == expected_data["status_code"]assert response_data == json.loads(expected_data["content"])@@ -148,6 +154,7 @@ def test_send_webhook_request_sync_request_exception(mock_post, app, event_delivassert attempt.duration == 0.0assert attempt.response == ""assert attempt.response_headers == "null"+ assert attempt.response_status_code is Noneassert attempt.request_headers == "null"assert response_data is None@@ -159,6 +166,7 @@ def test_send_webhook_request_sync_when_exception_with_response(mock_response = mock.Mock()mock_response.text = "response_content"mock_response.headers = {"response": "headers"}+ mock_response.status_code = 302mock_post.side_effect = TooManyRedirects(response=mock_response)# whensend_webhook_request_sync(app.name, event_delivery)@@ -167,6 +175,7 @@ def test_send_webhook_request_sync_when_exception_with_response(# thenassert attempt.response == "response_content"assert attempt.response_headers == '{"response": "headers"}'+ assert attempt.response_status_code == 302@mock.patch("saleor.plugins.webhook.tasks.requests.post")@@ -176,10 +185,12 @@ def test_send_webhook_request_sync_json_parsing_error(mock_post, app, event_deli"incorrect_content": "{key: response}","response_headers": {"header_key": "header_val"},"duration": datetime.timedelta(seconds=2),+ "status_code": 200,}mock_post().text = expected_data["incorrect_content"]mock_post().headers = expected_data["response_headers"]mock_post().elapsed = expected_data["duration"]+ mock_post().status_code = expected_data["status_code"]# whenresponse_data = send_webhook_request_sync(app.name, event_delivery)@@ -191,6 +202,7 @@ def test_send_webhook_request_sync_json_parsing_error(mock_post, app, event_deliassert attempt.duration == expected_data["duration"].total_seconds()assert attempt.response == expected_data["incorrect_content"]assert attempt.response_headers == json.dumps(expected_data["response_headers"])+ assert attempt.response_status_code == expected_data["status_code"]assert response_data is None@@ -199,6 +211,7 @@ def test_send_webhook_request_with_proper_timeout(mock_post, event_delivery, appmock_post().text = '{"key": "response_text"}'mock_post().headers = {"header_key": "header_val"}mock_post().elapsed = datetime.timedelta(seconds=1)+ mock_post().status_code = 200send_webhook_request_sync(app.name, event_delivery)assert mock_post.call_args.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUTdiff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.pyindex f11ca67c51..4032206f17 100644--- a/saleor/plugins/webhook/tests/test_webhook.py+++ b/saleor/plugins/webhook/tests/test_webhook.py@@ -8,6 +8,8 @@ from urllib.parse import urlencodeimport boto3import grapheneimport pytest+from celery.exceptions import MaxRetriesExceededError+from celery.exceptions import Retry as CeleryTaskRetryErrorfrom django.contrib.auth.tokens import default_token_generatorfrom django.core.serializers import serializefrom django.utils import timezone@@ -43,11 +45,7 @@ from ....webhook.payloads import (generate_sale_payload,)from ...manager import get_plugins_manager-from ...webhook.tasks import (- WebhookResponse,- send_webhook_request_async,- trigger_webhooks_async,-)+from ...webhook.tasks import send_webhook_request_async, trigger_webhooks_asyncfirst_url = "http://www.example.com/first/"third_url = "http://www.example.com/third/"@@ -1032,23 +1030,12 @@ def test_event_delivery_retry(mocked_webhook_send, event_delivery, settings):mocked_webhook_send.assert_called_once_with(event_delivery.pk)-TEST_WEBHOOK_RESPONSE = WebhookResponse(- content="test_content",- request_headers={"headers": "test_request"},- response_headers={"headers": "test_response"},- duration=2.0,- status=EventDeliveryStatus.SUCCESS,-)--@mock.patch("saleor.plugins.webhook.tasks.clear_successful_delivery")- "saleor.plugins.webhook.tasks.send_webhook_using_scheme_method",- return_value=TEST_WEBHOOK_RESPONSE,-)[email protected]("saleor.plugins.webhook.tasks.send_webhook_using_scheme_method")def test_send_webhook_request_async(- mocked_send_response, mocked_clear_delivery, event_delivery+ mocked_send_response, mocked_clear_delivery, event_delivery, webhook_response):+ mocked_send_response.return_value = webhook_responsesend_webhook_request_async(event_delivery.pk)mocked_send_response.assert_called_once_with(@@ -1062,10 +1049,46 @@ def test_send_webhook_request_async(attempt = EventDeliveryAttempt.objects.filter(delivery=event_delivery).first()delivery = EventDelivery.objects.get(id=event_delivery.pk)assert attempt.status == EventDeliveryStatus.SUCCESS- assert attempt.response == TEST_WEBHOOK_RESPONSE.content- assert attempt.response_headers == json.dumps(- TEST_WEBHOOK_RESPONSE.response_headers- )- assert attempt.request_headers == json.dumps(TEST_WEBHOOK_RESPONSE.request_headers)- assert attempt.duration == TEST_WEBHOOK_RESPONSE.duration+ assert attempt.response == webhook_response.content+ assert attempt.response_headers == json.dumps(webhook_response.response_headers)+ assert attempt.response_status_code == webhook_response.response_status_code+ assert attempt.request_headers == json.dumps(webhook_response.request_headers)+ assert attempt.duration == webhook_response.durationassert delivery.status == EventDeliveryStatus.SUCCESS++[email protected]("saleor.plugins.webhook.tasks.send_webhook_using_scheme_method")+def test_send_webhook_request_async_when_delivery_attempt_failed(+ mocked_send_response,+ event_delivery,+ webhook_response_failed,+):+ mocked_send_response.return_value = webhook_response_failed++ with pytest.raises(CeleryTaskRetryError):+ send_webhook_request_async(event_delivery.pk)++ attempt = EventDeliveryAttempt.objects.filter(delivery=event_delivery).first()+ delivery = EventDelivery.objects.get(id=event_delivery.pk)+ assert attempt.status == EventDeliveryStatus.FAILED+ assert attempt.response_status_code == webhook_response_failed.response_status_code+ assert delivery.status == EventDeliveryStatus.PENDING++[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_async.retry")[email protected]("saleor.plugins.webhook.tasks.send_webhook_using_scheme_method")+def test_send_webhook_request_async_when_max_retries_exceeded(+ mocked_send_response,+ mocked_task_retry,+ event_delivery,+ webhook_response_failed,+):+ mocked_send_response.return_value = webhook_response_failed+ mocked_task_retry.side_effect = MaxRetriesExceededError()++ send_webhook_request_async(event_delivery.pk)++ attempt = EventDeliveryAttempt.objects.filter(delivery=event_delivery).first()+ delivery = EventDelivery.objects.get(id=event_delivery.pk)+ assert attempt.status == EventDeliveryStatus.FAILED+ assert delivery.status == EventDeliveryStatus.FAILEDdiff --git a/saleor/plugins/webhook/tests/test_webhook_protocols.py b/saleor/plugins/webhook/tests/test_webhook_protocols.pyindex 20356c0e3a..093c864a8c 100644--- a/saleor/plugins/webhook/tests/test_webhook_protocols.py+++ b/saleor/plugins/webhook/tests/test_webhook_protocols.py@@ -1,8 +1,8 @@+from datetime import timedeltafrom unittest.mock import MagicMock, patchimport boto3import pytest-import requestsfrom django.core.serializers import serializefrom google.cloud.pubsub_v1 import PublisherClientfrom kombu.asynchronous.aws.sqs.connection import AsyncSQSConnection@@ -27,6 +27,7 @@ def test_trigger_webhooks_with_aws_sqs(monkeypatch,):mocked_client = MagicMock(spec=AsyncSQSConnection)+ mocked_client.send_message.return_value = {"example": "response"}mocked_client_constructor = MagicMock(spec=boto3.client, return_value=mocked_client)monkeypatch.setattr(@@ -77,6 +78,7 @@ def test_trigger_webhooks_with_aws_sqs_and_secret_key(monkeypatch,):mocked_client = MagicMock(spec=AsyncSQSConnection)+ mocked_client.send_message.return_value = {"example": "response"}mocked_client_constructor = MagicMock(spec=boto3.client, return_value=mocked_client)monkeypatch.setattr(@@ -131,6 +133,7 @@ def test_trigger_webhooks_with_google_pub_sub(monkeypatch,):mocked_publisher = MagicMock(spec=PublisherClient)+ mocked_publisher.publish.return_value.result.return_value = "message_id"monkeypatch.setattr("saleor.plugins.webhook.tasks.pubsub_v1.PublisherClient",lambda: mocked_publisher,@@ -161,6 +164,7 @@ def test_trigger_webhooks_with_google_pub_sub_and_secret_key(monkeypatch,):mocked_publisher = MagicMock(spec=PublisherClient)+ mocked_publisher.publish.return_value.result.return_value = "message_id"monkeypatch.setattr("saleor.plugins.webhook.tasks.pubsub_v1.PublisherClient",lambda: mocked_publisher,@@ -187,8 +191,7 @@ def test_trigger_webhooks_with_google_pub_sub_and_secret_key()-@patch("saleor.plugins.webhook.tasks.requests.post", wraps=requests.post)+@patch("saleor.plugins.webhook.tasks.requests.post")def test_trigger_webhooks_with_http(mock_request,webhook,@@ -197,6 +200,13 @@ def test_trigger_webhooks_with_http(permission_manage_users,permission_manage_products,):+ mock_request.return_value = MagicMock(+ text="{response: body}",+ headers={"response": "header"},+ elapsed=timedelta(seconds=2),+ status_code=200,+ ok=True,+ )webhook.app.permissions.add(permission_manage_orders)webhook.target_url = "https://webhook.site/48978b64-4efb-43d5-a334-451a1d164009"webhook.save()@@ -226,11 +236,17 @@ def test_trigger_webhooks_with_http()-@patch("saleor.plugins.webhook.tasks.requests.post", wraps=requests.post)+@patch("saleor.plugins.webhook.tasks.requests.post")def test_trigger_webhooks_with_http_and_secret_key(mock_request, webhook, order_with_lines, permission_manage_orders):+ mock_request.return_value = MagicMock(+ text="{response: body}",+ headers={"response": "header"},+ elapsed=timedelta(seconds=2),+ status_code=200,+ ok=True,+ )webhook.app.permissions.add(permission_manage_orders)webhook.target_url = "https://webhook.site/48978b64-4efb-43d5-a334-451a1d164009"webhook.secret_key = "secret_key"diff --git a/saleor/plugins/webhook/utils.py b/saleor/plugins/webhook/utils.pyindex 009c708c06..b949450c4e 100644--- a/saleor/plugins/webhook/utils.py+++ b/saleor/plugins/webhook/utils.py@@ -175,6 +175,7 @@ def attempt_update(attempt.duration = webhook_response.durationattempt.response = webhook_response.contentattempt.response_headers = json.dumps(webhook_response.response_headers)+ attempt.response_status_code = webhook_response.response_status_codeattempt.request_headers = json.dumps(webhook_response.request_headers)attempt.status = webhook_response.statusattempt.save(@@ -182,6 +183,7 @@ def attempt_update("duration","response","response_headers",+ "response_status_code","request_headers","status",]diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 0ee83fefbd..59ce7b1ac5 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -41,7 +41,7 @@ from ..attribute.utils import associate_attribute_values_to_instancefrom ..checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom ..checkout.models import Checkout, CheckoutLinefrom ..checkout.utils import add_variant_to_checkout-from ..core import JobStatus, TimePeriodType+from ..core import EventDeliveryStatus, JobStatus, TimePeriodTypefrom ..core.models import EventDelivery, EventDeliveryAttempt, EventPayloadfrom ..core.payments import PaymentInterfacefrom ..core.units import MeasurementUnits@@ -5713,8 +5713,25 @@ def event_attempt(event_delivery):@pytest.fixturedef webhook_response():+ return WebhookResponse(+ content="test_content",+ request_headers={"headers": "test_request"},+ response_headers={"headers": "test_response"},+ response_status_code=200,+ duration=2.0,+ status=EventDeliveryStatus.SUCCESS,+ )+++def webhook_response_failed():return WebhookResponse(content="example_content_response",+ request_headers={"headers": "test_request"},+ response_headers={"headers": "test_response"},+ response_status_code=500,+ duration=2.0,+ status=EventDeliveryStatus.FAILED,)