Skip to content

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

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.py
new file mode 100644
index 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.py
index 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.graphql
index 782f644bb3..a0a27b06f7 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1569,6 +1569,7 @@ type EventDeliveryAttempt implements Node {
duration: Float
response: String
responseHeaders: String
+ responseStatusCode: Int
requestHeaders: 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.py
index 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 = """
response
requestHeaders
responseHeaders
+ 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.py
index 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=True
diff --git a/saleor/plugins/webhook/tasks.py b/saleor/plugins/webhook/tasks.py
index 677f477b32..bbdc1861e6 100644
--- a/saleor/plugins/webhook/tasks.py
+++ b/saleor/plugins/webhook/tasks.py
@@ -61,6 +61,7 @@ class WebhookResponse:
content: str
request_headers: Optional[Dict] = None
response_headers: Optional[Dict] = None
+ response_status_code: Optional[int] = None
status: str = EventDeliveryStatus.SUCCESS
duration: 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.text
response.response_headers = dict(e.response.headers)
+ response.response_status_code = e.response.status_code
except JSONDecodeError as e:
logger.warning(
diff --git a/saleor/plugins/webhook/tests/test_payment_webhook.py b/saleor/plugins/webhook/tests/test_payment_webhook.py
index 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_delivery
expected_data = {
"content": '{"key": "response_text"}',
"headers": {"header_key": "header_val"},
+ "status_code": 500,
"duration": datetime.timedelta(seconds=2),
}
mock_post().ok = False
mock_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"]
# when
response_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_delivery
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 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 = True
mock_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"]
# when
response_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_deliv
assert attempt.duration == 0.0
assert attempt.response == ""
assert attempt.response_headers == "null"
+ assert attempt.response_status_code is None
assert 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 = 302
mock_post.side_effect = TooManyRedirects(response=mock_response)
# when
send_webhook_request_sync(app.name, event_delivery)
@@ -167,6 +175,7 @@ def test_send_webhook_request_sync_when_exception_with_response(
# then
assert 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"]
# when
response_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_deli
assert 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, app
mock_post().text = '{"key": "response_text"}'
mock_post().headers = {"header_key": "header_val"}
mock_post().elapsed = datetime.timedelta(seconds=1)
+ mock_post().status_code = 200
send_webhook_request_sync(app.name, event_delivery)
assert mock_post.call_args.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUT
diff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.py
index 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 urlencode
import boto3
import graphene
import pytest
+from celery.exceptions import MaxRetriesExceededError
+from celery.exceptions import Retry as CeleryTaskRetryError
from django.contrib.auth.tokens import default_token_generator
from django.core.serializers import serialize
from 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_async
first_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_response
send_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.duration
assert 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.FAILED
diff --git a/saleor/plugins/webhook/tests/test_webhook_protocols.py b/saleor/plugins/webhook/tests/test_webhook_protocols.py
index 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 timedelta
from unittest.mock import MagicMock, patch
import boto3
import pytest
-import requests
from django.core.serializers import serialize
from google.cloud.pubsub_v1 import PublisherClient
from 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.py
index 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.duration
attempt.response = webhook_response.content
attempt.response_headers = json.dumps(webhook_response.response_headers)
+ attempt.response_status_code = webhook_response.response_status_code
attempt.request_headers = json.dumps(webhook_response.request_headers)
attempt.status = webhook_response.status
attempt.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.py
index 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_instance
from ..checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ..checkout.models import Checkout, CheckoutLine
from ..checkout.utils import add_variant_to_checkout
-from ..core import JobStatus, TimePeriodType
+from ..core import EventDeliveryStatus, JobStatus, TimePeriodType
from ..core.models import EventDelivery, EventDeliveryAttempt, EventPayload
from ..core.payments import PaymentInterface
from ..core.units import MeasurementUnits
@@ -5713,8 +5713,25 @@ def event_attempt(event_delivery):
@pytest.fixture
def 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,
)