Skip to content

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

Add custom app installation error message (#10513)

Przemysław Ładabd27a4591f35
diff --git a/saleor/app/installation_utils.py b/saleor/app/installation_utils.py
index 179107e023..91d829c6a6 100644
--- a/saleor/app/installation_utils.py
+++ b/saleor/app/installation_utils.py
@@ -1,6 +1,7 @@
import requests
from django.conf import settings
from django.contrib.sites.models import Site
+from requests import HTTPError, Response
from ..core.permissions import get_permission_names
from ..plugins.manager import PluginsManager
@@ -12,6 +13,21 @@ from .types import AppExtensionTarget, AppType
REQUEST_TIMEOUT = 25
+class AppInstallationError(HTTPError):
+ pass
+
+
+def validate_app_install_response(response: Response):
+ try:
+ response.raise_for_status()
+ except HTTPError as err:
+ try:
+ error_msg = str(response.json()["error"]["message"])
+ except Exception:
+ raise err
+ raise AppInstallationError(error_msg, response=response)
+
+
def send_app_token(target_url: str, token: str):
domain = Site.objects.get_current().domain
headers = {
@@ -24,7 +40,7 @@ def send_app_token(target_url: str, token: str):
response = requests.post(
target_url, json=json_data, headers=headers, timeout=REQUEST_TIMEOUT
)
- response.raise_for_status()
+ validate_app_install_response(response)
def install_app(app_installation: AppInstallation, activate: bool = False):
diff --git a/saleor/app/models.py b/saleor/app/models.py
index 1f8091c8ce..e163961686 100644
--- a/saleor/app/models.py
+++ b/saleor/app/models.py
@@ -3,6 +3,7 @@ from typing import Collection, Set, Tuple, Union
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import Permission
from django.db import models
+from django.utils.text import Truncator
from oauthlib.common import generate_token
from saleor.core.permissions.enums import BasePermissionEnum
@@ -163,3 +164,9 @@ class AppInstallation(Job):
related_name="app_installation_set",
related_query_name="app_installation",
)
+
+ def set_message(self, message: str, truncate=True):
+ if truncate:
+ max_length = self._meta.get_field("message").max_length
+ message = Truncator(message).chars(max_length)
+ self.message = message
diff --git a/saleor/app/tasks.py b/saleor/app/tasks.py
index 7ec19ca998..b36a47fa15 100644
--- a/saleor/app/tasks.py
+++ b/saleor/app/tasks.py
@@ -5,7 +5,7 @@ from requests import HTTPError, RequestException
from .. import celeryconf
from ..core import JobStatus
-from .installation_utils import install_app
+from .installation_utils import AppInstallationError, install_app
from .models import AppInstallation
logger = logging.getLogger(__name__)
@@ -21,13 +21,26 @@ def install_app_task(job_id, activate=False):
except ValidationError as e:
msg = ", ".join([f"{name}: {err}" for name, err in e.message_dict.items()])
app_installation.message = msg
- except (RequestException, HTTPError) as e:
- logger.warning("Failed to install an app. error: %s", e)
+ except AppInstallationError as e:
+ logger.warning("Failed to install app. Error: %s", e)
+ app_installation.set_message(str(e))
+ except HTTPError as e:
+ logger.warning(
+ "Failed to install app. Response structure incorrect: missing error field."
+ " Error: %s",
+ e,
+ )
+ app_installation.message = (
+ f"App internal error ({e.response.status_code}). "
+ "Try later or contact with app support."
+ )
+ except RequestException as e:
+ logger.warning("Failed to install app. Error: %s", e)
app_installation.message = (
"Failed to connect to app. Try later or contact with app support."
)
except Exception as e:
- logger.warning("Failed to install app. error %s", e)
+ logger.warning("Failed to install app. Error: %s", e)
app_installation.message = "Unknown error. Contact with app support."
app_installation.status = JobStatus.FAILED
app_installation.save()
diff --git a/saleor/app/tests/test_app_tasks.py b/saleor/app/tests/test_app_tasks.py
index f41da99e02..e2a3da04b6 100644
--- a/saleor/app/tests/test_app_tasks.py
+++ b/saleor/app/tests/test_app_tasks.py
@@ -4,6 +4,7 @@ import pytest
from requests import RequestException
from ...core import JobStatus
+from ..installation_utils import AppInstallationError
from ..models import App, AppInstallation
from ..tasks import install_app_task
@@ -51,18 +52,33 @@ def test_install_app_task_wrong_response_code(monkeypatch):
app_name="External App",
manifest_url="http://localhost:3000/manifest-wrong1",
)
+ response_status_code = 404
mocked_post = Mock()
- mocked_post.status_code = 404
+ mocked_post.status_code = response_status_code
monkeypatch.setattr("saleor.app.installation_utils.requests.post", mocked_post)
+ message = (
+ f"App internal error ({response_status_code}). "
+ "Try later or contact with app support."
+ )
+
install_app_task(app_installation.pk, activate=True)
app_installation.refresh_from_db()
assert not App.objects.all().exists()
assert app_installation.status == JobStatus.FAILED
- assert (
- app_installation.message
- == "Failed to connect to app. Try later or contact with app support."
- )
+ assert app_installation.message == message
+
+
+def test_install_app_task_installation_error(monkeypatch, app_installation):
+ error_msg = "App installation error."
+ mock_install_app = Mock(side_effect=AppInstallationError(error_msg))
+ monkeypatch.setattr("saleor.app.tasks.install_app", mock_install_app)
+
+ install_app_task(app_installation.pk)
+
+ app_installation.refresh_from_db()
+ assert app_installation.status == JobStatus.FAILED
+ assert app_installation.message == error_msg
def test_install_app_task_undefined_error(monkeypatch, app_installation):
diff --git a/saleor/app/tests/test_installation_utils.py b/saleor/app/tests/test_installation_utils.py
index 28b70a64ef..725b88655c 100644
--- a/saleor/app/tests/test_installation_utils.py
+++ b/saleor/app/tests/test_installation_utils.py
@@ -10,11 +10,36 @@ from freezegun import freeze_time
from ...core.utils.json_serializer import CustomJsonEncoder
from ...webhook.event_types import WebhookEventAsyncType
from ...webhook.payloads import generate_meta, generate_requestor
-from ..installation_utils import install_app
+from ..installation_utils import (
+ AppInstallationError,
+ install_app,
+ validate_app_install_response,
+)
from ..models import App
from ..types import AppExtensionMount, AppExtensionTarget
+def test_validate_app_install_response():
+ error_message = "Test error msg"
+ response = Mock(spec=requests.Response)
+ response.raise_for_status.side_effect = requests.HTTPError
+ response.json.return_value = {"error": {"message": error_message}}
+
+ with pytest.raises(AppInstallationError) as error:
+ validate_app_install_response(response)
+ assert str(error.value) == error_message
+
+
[email protected]("json_response", ({}, {"error": {}}, Exception))
+def test_validate_app_install_response_when_wrong_error_message(json_response):
+ response = Mock(spec=requests.Response)
+ response.raise_for_status.side_effect = requests.HTTPError
+ response.json.side_effect = json_response
+
+ with pytest.raises(requests.HTTPError):
+ validate_app_install_response(response)
+
+
def test_install_app_created_app(
app_manifest, app_installation, monkeypatch, permission_manage_products
):
diff --git a/saleor/app/tests/test_models.py b/saleor/app/tests/test_models.py
index abb3d19026..e8fa521098 100644
--- a/saleor/app/tests/test_models.py
+++ b/saleor/app/tests/test_models.py
@@ -1,5 +1,6 @@
from ...app.models import App
from ...webhook.event_types import WebhookEventSyncType
+from ..models import AppInstallation
def test_qs_for_event_type(payment_app):
@@ -37,3 +38,14 @@ def test_qs_for_event_type_inactive_webhook(payment_app):
webhook.save()
qs = App.objects.for_event_type(WebhookEventSyncType.PAYMENT_AUTHORIZE)
assert len(qs) == 0
+
+
+def test_app_installation_set_message_truncates(app_installation):
+ max_length = AppInstallation._meta.get_field("message").max_length
+ too_long_message = "msg" * max_length
+
+ app_installation.set_message(too_long_message)
+ app_installation.save()
+ app_installation.refresh_from_db()
+
+ assert len(app_installation.message) <= max_length