Skip to content

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

Prevent from installing two apps with the same `App.identifier` (#16272) (#16322)

Arturc908c33c0560
diff --git a/saleor/app/manifest_validations.py b/saleor/app/manifest_validations.py
index f76c5e8357..2c0b8d2719 100644
--- a/saleor/app/manifest_validations.py
+++ b/saleor/app/manifest_validations.py
@@ -21,6 +21,7 @@ from ..permission.models import Permission
from ..webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ..webhook.validators import custom_headers_validator
from .error_codes import AppErrorCode
+from .models import App
from .types import AppExtensionMount, AppExtensionTarget
from .validators import AppURLValidator, brand_validator
@@ -111,6 +112,7 @@ def clean_manifest_data(manifest_data, raise_for_saleor_version=False):
errors: T_ERRORS = defaultdict(list)
validate_required_fields(manifest_data, errors)
+
try:
if "tokenTargetUrl" in manifest_data:
_clean_app_url(manifest_data["tokenTargetUrl"])
@@ -152,6 +154,12 @@ def clean_manifest_data(manifest_data, raise_for_saleor_version=False):
manifest_data["permissions"] = app_permissions
+ if app := App.objects.filter(identifier=manifest_data.get("id")).first():
+ errors["identifier"].append(
+ ValidationError(
+ f"App with the same identifier is already installed: {app.name}"
+ )
+ )
if not errors:
clean_extensions(manifest_data, app_permissions, errors)
clean_webhooks(manifest_data, errors)
diff --git a/saleor/graphql/app/mutations/app_install.py b/saleor/graphql/app/mutations/app_install.py
index 73420fd169..7c950f98dd 100644
--- a/saleor/graphql/app/mutations/app_install.py
+++ b/saleor/graphql/app/mutations/app_install.py
@@ -62,7 +62,6 @@ class AppInstall(ModelMutation):
def clean_input(cls, info, instance, data, **kwargs):
manifest_url = data.get("manifest_url")
clean_manifest_url(manifest_url)
-
cleaned_input = super().clean_input(info, instance, data, **kwargs)
# clean and prepare permissions
diff --git a/saleor/graphql/app/tests/mutations/cassettes/test_app_fetch_manifest/test_fetch_manifest_fail_when_app_with_same_identifier_already_installed.yaml b/saleor/graphql/app/tests/mutations/cassettes/test_app_fetch_manifest/test_fetch_manifest_fail_when_app_with_same_identifier_already_installed.yaml
new file mode 100644
index 0000000000..ffa9cc76d3
--- /dev/null
+++ b/saleor/graphql/app/tests/mutations/cassettes/test_app_fetch_manifest/test_fetch_manifest_fail_when_app_with_same_identifier_already_installed.yaml
@@ -0,0 +1,95 @@
+interactions:
+- request:
+ body: null
+ headers:
+ Accept:
+ - application/json
+ Accept-Encoding:
+ - identity
+ Connection:
+ - keep-alive
+ Saleor-Schema-Version:
+ - '3.19'
+ User-Agent:
+ - Saleor/3.19
+ method: GET
+ uri: http://localhost:3000/api/manifest
+ response:
+ body:
+ string: '{"about":"App connects with Avatax to dynamically calculate taxes","appUrl":"http://localhost:3000","author":"Saleor
+ Commerce","brand":{"logo":{"default":"http://localhost:3000/logo.png"}},"dataPrivacyUrl":"https://saleor.io/legal/privacy/","extensions":[],"homepageUrl":"https://github.com/saleor/apps","id":"saleor.app.avatax","name":"Avatax","permissions":["HANDLE_TAXES","MANAGE_ORDERS"],"requiredSaleorVersion":">=3.18
+ <4","supportUrl":"https://github.com/saleor/apps/discussions","tokenTargetUrl":"http://localhost:3000/api/register","version":"1.5.2","webhooks":[{"query":"subscription
+ CalculateTaxes { event { ...CalculateTaxesEvent }}fragment CalculateTaxesEvent
+ on Event { __typename ...WebhookMetadata ... on CalculateTaxes { taxBase {
+ ...TaxBase } recipient { privateMetadata { key value } } }}fragment WebhookMetadata
+ on Event { issuedAt version}fragment TaxBase on TaxableObject { pricesEnteredWithTax
+ currency channel { slug } address { ...Address } shippingPrice { amount }
+ lines { ...TaxBaseLine } sourceObject { __typename ... on Checkout { id avataxEntityCode:
+ metafield(key: \"avataxEntityCode\") avataxCustomerCode: metafield(key: \"avataxCustomerCode\")
+ user { ...User } } ... on Order { id avataxEntityCode: metafield(key: \"avataxEntityCode\")
+ avataxCustomerCode: metafield(key: \"avataxCustomerCode\") user { ...User
+ } } }}fragment Address on Address { streetAddress1 streetAddress2 city countryArea
+ postalCode country { code }}fragment TaxBaseLine on TaxableObjectLine { sourceLine
+ { __typename ... on CheckoutLine { id checkoutProductVariant: variant { id
+ product { taxClass { id name } } } } ... on OrderLine { id orderProductVariant:
+ variant { id product { taxClass { id name } } } } } quantity unitPrice { amount
+ } totalPrice { amount }}fragment User on User { id email avataxCustomerCode:
+ metafield(key: \"avataxCustomerCode\")}","name":"CheckoutCalculateTaxes","targetUrl":"http://localhost:3000/api/webhooks/checkout-calculate-taxes","isActive":true,"syncEvents":["CHECKOUT_CALCULATE_TAXES"]},{"query":"subscription
+ CalculateTaxes { event { ...CalculateTaxesEvent }}fragment CalculateTaxesEvent
+ on Event { __typename ...WebhookMetadata ... on CalculateTaxes { taxBase {
+ ...TaxBase } recipient { privateMetadata { key value } } }}fragment WebhookMetadata
+ on Event { issuedAt version}fragment TaxBase on TaxableObject { pricesEnteredWithTax
+ currency channel { slug } address { ...Address } shippingPrice { amount }
+ lines { ...TaxBaseLine } sourceObject { __typename ... on Checkout { id avataxEntityCode:
+ metafield(key: \"avataxEntityCode\") avataxCustomerCode: metafield(key: \"avataxCustomerCode\")
+ user { ...User } } ... on Order { id avataxEntityCode: metafield(key: \"avataxEntityCode\")
+ avataxCustomerCode: metafield(key: \"avataxCustomerCode\") user { ...User
+ } } }}fragment Address on Address { streetAddress1 streetAddress2 city countryArea
+ postalCode country { code }}fragment TaxBaseLine on TaxableObjectLine { sourceLine
+ { __typename ... on CheckoutLine { id checkoutProductVariant: variant { id
+ product { taxClass { id name } } } } ... on OrderLine { id orderProductVariant:
+ variant { id product { taxClass { id name } } } } } quantity unitPrice { amount
+ } totalPrice { amount }}fragment User on User { id email avataxCustomerCode:
+ metafield(key: \"avataxCustomerCode\")}","name":"OrderCalculateTaxes","targetUrl":"http://localhost:3000/api/webhooks/order-calculate-taxes","isActive":true,"syncEvents":["ORDER_CALCULATE_TAXES"]},{"query":"subscription
+ OrderCancelledSubscription { event { ...OrderCancelledEventSubscription }}fragment
+ OrderCancelledEventSubscription on Event { __typename ...WebhookMetadata ...
+ on OrderCancelled { order { ...OrderCancelledSubscription } recipient { privateMetadata
+ { key value } } }}fragment WebhookMetadata on Event { issuedAt version}fragment
+ OrderCancelledSubscription on Order { id avataxId: metafield(key: \"avataxId\")
+ channel { id slug }}","name":"OrderCancelled","targetUrl":"http://localhost:3000/api/webhooks/order-cancelled","isActive":true,"asyncEvents":["ORDER_CANCELLED"]},{"query":"subscription
+ OrderConfirmedSubscription { event { ...OrderConfirmedEventSubscription }}fragment
+ OrderConfirmedEventSubscription on Event { __typename ...WebhookMetadata ...
+ on OrderConfirmed { order { ...OrderConfirmedSubscription } } recipient {
+ privateMetadata { key value } }}fragment WebhookMetadata on Event { issuedAt
+ version}fragment OrderConfirmedSubscription on Order { id number userEmail
+ user { ...User } avataxCustomerCode: metafield(key: \"avataxCustomerCode\")
+ created status channel { id slug taxConfiguration { pricesEnteredWithTax taxCalculationStrategy
+ } } shippingAddress { ...Address } billingAddress { ...Address } total { currency
+ net { amount } tax { amount } } shippingPrice { gross { amount } net { amount
+ } } lines { ...OrderLine } avataxEntityCode: metafield(key: \"avataxEntityCode\")
+ avataxTaxCalculationDate: metafield(key: \"avataxTaxCalculationDate\") avataxDocumentCode:
+ metafield(key: \"avataxDocumentCode\")}fragment User on User { id email avataxCustomerCode:
+ metafield(key: \"avataxCustomerCode\")}fragment Address on Address { streetAddress1
+ streetAddress2 city countryArea postalCode country { code }}fragment OrderLine
+ on OrderLine { productSku productVariantId productName quantity taxClass {
+ id } unitPrice { net { amount } } totalPrice { net { amount } tax { amount
+ } gross { amount } }}","name":"OrderConfirmed","targetUrl":"http://localhost:3000/api/webhooks/order-confirmed","isActive":true,"asyncEvents":["ORDER_CONFIRMED"]}]}'
+ headers:
+ Connection:
+ - keep-alive
+ Content-Length:
+ - '5549'
+ Content-Type:
+ - application/json; charset=utf-8
+ Date:
+ - Mon, 15 Jul 2024 08:06:12 GMT
+ ETag:
+ - '"16l6t5qo2d34a5"'
+ Keep-Alive:
+ - timeout=5
+ Vary:
+ - Accept-Encoding
+ status:
+ code: 200
+ message: OK
+version: 1
diff --git a/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py b/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py
index e750395ff3..75bd0e0d17 100644
--- a/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py
+++ b/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py
@@ -851,3 +851,37 @@ def test_app_fetch_manifest_with_invalid_brand_data(
assert len(errors) == 1
assert errors[0]["field"] == "brand"
assert errors[0]["code"] == AppErrorCode.INVALID_URL_FORMAT.name
+
+
+def test_fetch_manifest_fail_when_app_with_same_identifier_already_installed(
+ staff_api_client,
+ staff_user,
+ permission_manage_apps,
+ app,
+):
+ # given
+ app.identifier = "saleor.app.avatax"
+ app.save()
+ manifest_url = "http://localhost:3000/api/manifest"
+
+ query = APP_FETCH_MANIFEST_MUTATION
+ variables = {"manifest_url": manifest_url}
+ staff_user.user_permissions.set([permission_manage_apps])
+
+ # when
+ response = staff_api_client.post_graphql(
+ query,
+ variables=variables,
+ )
+ content = get_graphql_content(response)
+
+ errors = content["data"]["appFetchManifest"]["errors"]
+
+ # then
+ assert len(errors) == 1
+ assert errors[0]["field"] == "identifier"
+ assert errors[0]["code"] == "INVALID"
+ assert errors[0]["message"] == (
+ f"App with the same identifier is already installed: {app.name}"
+ )
diff --git a/saleor/graphql/app/tests/mutations/test_app_install.py b/saleor/graphql/app/tests/mutations/test_app_install.py
index 01871f0189..06fd83d592 100644
--- a/saleor/graphql/app/tests/mutations/test_app_install.py
+++ b/saleor/graphql/app/tests/mutations/test_app_install.py
@@ -1,11 +1,12 @@
-from unittest.mock import Mock
+from unittest.mock import Mock, patch
import graphene
-from .....app.models import AppInstallation
+from .....app.models import App, AppInstallation
+from .....app.tasks import install_app_task
from .....core import JobStatus
from ....core.enums import AppErrorCode, PermissionEnum
-from ....tests.utils import assert_no_permission, get_graphql_content
+from ....tests.utils import get_graphql_content
INSTALL_APP_MUTATION = """
mutation AppInstall(
@@ -30,6 +31,12 @@ INSTALL_APP_MUTATION = """
"""
+def _mutate_app_install(client, variables, ignore_errors=False):
+ response = client.post_graphql(INSTALL_APP_MUTATION, variables)
+ content = get_graphql_content(response, ignore_errors=True)
+ return content["data"]["appInstall"]
+
+
def test_install_app_mutation(
permission_manage_apps,
permission_manage_orders,
@@ -37,24 +44,23 @@ def test_install_app_mutation(
staff_user,
monkeypatch,
):
+ # given
mocked_task = Mock()
monkeypatch.setattr(
"saleor.graphql.app.mutations.app_install.install_app_task.delay", mocked_task
)
- query = INSTALL_APP_MUTATION
staff_user.user_permissions.set([permission_manage_apps, permission_manage_orders])
variables = {
"app_name": "New external integration",
"manifest_url": "http://localhost:3000/manifest",
"permissions": [PermissionEnum.MANAGE_ORDERS.name],
}
- response = staff_api_client.post_graphql(
- query,
- variables=variables,
- )
- content = get_graphql_content(response)
+ # when
+ data = _mutate_app_install(staff_api_client, variables)
+
+ # then
app_installation = AppInstallation.objects.get()
- app_installation_data = content["data"]["appInstall"]["appInstallation"]
+ app_installation_data = data["appInstallation"]
_, app_id = graphene.Node.from_global_id(app_installation_data["id"])
assert int(app_id) == app_installation.id
assert app_installation_data["status"] == JobStatus.PENDING.upper()
@@ -67,7 +73,6 @@ def test_app_is_not_allowed_to_install_app(
permission_manage_apps, permission_manage_orders, app_api_client, monkeypatch
):
# given
- query = INSTALL_APP_MUTATION
app_api_client.app.permissions.set(
[permission_manage_apps, permission_manage_orders]
)
@@ -78,32 +83,26 @@ def test_app_is_not_allowed_to_install_app(
}
# when
- response = app_api_client.post_graphql(
- query,
- variables=variables,
- )
+ data = _mutate_app_install(app_api_client, variables)
# then
- assert_no_permission(response)
+ assert data is None
def test_app_install_mutation_out_of_scope_permissions(
permission_manage_apps, staff_api_client, staff_user
):
- query = INSTALL_APP_MUTATION
+ # given
staff_user.user_permissions.set([permission_manage_apps])
variables = {
"app_name": "New external integration",
"manifest_url": "http://localhost:3000/manifest",
"permissions": [PermissionEnum.MANAGE_ORDERS.name],
}
- response = staff_api_client.post_graphql(
- query,
- variables=variables,
- )
- content = get_graphql_content(response)
- data = content["data"]["appInstall"]
+ # when
+ data = _mutate_app_install(staff_api_client, variables)
+ # then
errors = data["errors"]
assert not data["appInstallation"]
assert len(errors) == 1
@@ -111,3 +110,48 @@ def test_app_install_mutation_out_of_scope_permissions(
assert error["field"] == "permissions"
assert error["code"] == AppErrorCode.OUT_OF_SCOPE_PERMISSION.name
assert error["permissions"] == [PermissionEnum.MANAGE_ORDERS.name]
+
+
+@patch("saleor.app.installation_utils.send_app_token", Mock())
+@patch(
+ "saleor.graphql.app.mutations.app_install.install_app_task.delay", install_app_task
+)
+def test_install_app_mutation_with_the_same_identifier_twice(
+ permission_manage_apps,
+ permission_manage_orders,
+ staff_api_client,
+ staff_user,
+ monkeypatch,
+ app,
+):
+ # given
+ staff_user.user_permissions.set([permission_manage_apps, permission_manage_orders])
+ variables = {
+ "app_name": "New external integration",
+ "manifest_url": app.manifest_url,
+ "permissions": [PermissionEnum.MANAGE_ORDERS.name],
+ }
+
+ # when
+ with patch("saleor.app.installation_utils.fetch_manifest") as mocked_fetch:
+ mocked_fetch.return_value = {
+ "id": app.identifier,
+ "tokenTargetUrl": "http://localhost:3000/register",
+ "name": "app",
+ "version": "1.0.0",
+ }
+ data = _mutate_app_install(staff_api_client, variables)
+
+ # then
+ # Installation is done in celery task - response shows that app is being installed
+ assert not data["errors"]
+ assert data["appInstallation"]["status"] == JobStatus.PENDING.upper()
+ assert data["appInstallation"]["manifestUrl"] == app.manifest_url
+ assert App.objects.count() == 1
+ # Celery bypassed, AppInstallation instance failed to install app
+ app_installation = AppInstallation.objects.first()
+ assert app_installation.status == JobStatus.FAILED
+ assert app_installation.message == (
+ "identifier: "
+ "['App with the same identifier is already installed: Sample app objects']"
+ )
diff --git a/saleor/graphql/app/tests/mutations/test_app_retry_install.py b/saleor/graphql/app/tests/mutations/test_app_retry_install.py
index 9c2d39bf9f..f8c0d91a07 100644
--- a/saleor/graphql/app/tests/mutations/test_app_retry_install.py
+++ b/saleor/graphql/app/tests/mutations/test_app_retry_install.py
@@ -1,8 +1,9 @@
-from unittest.mock import Mock
+from unittest.mock import Mock, patch
import graphene
-from .....app.models import AppInstallation
+from .....app.models import App, AppInstallation
+from .....app.tasks import install_app_task
from .....core import JobStatus
from ....core.enums import AppErrorCode
from ....tests.utils import get_graphql_content
@@ -28,6 +29,12 @@ RETRY_INSTALL_APP_MUTATION = """
"""
+def _mutate_app_install_retry(client, variables, ignore_errors=False):
+ response = client.post_graphql(RETRY_INSTALL_APP_MUTATION, variables)
+ content = get_graphql_content(response, ignore_errors=True)
+ return content["data"]["appRetryInstall"]
+
+
def test_retry_install_app_mutation(
monkeypatch,
app_installation,
@@ -36,6 +43,7 @@ def test_retry_install_app_mutation(
permission_manage_orders,
staff_user,
):
+ # given
app_installation.status = JobStatus.FAILED
app_installation.save()
mocked_task = Mock()
@@ -43,24 +51,21 @@ def test_retry_install_app_mutation(
"saleor.graphql.app.mutations.app_retry_install.install_app_task.delay",
mocked_task,
)
- query = RETRY_INSTALL_APP_MUTATION
staff_user.user_permissions.set([permission_manage_apps, permission_manage_orders])
- id = graphene.Node.to_global_id("AppInstallation", app_installation.id)
variables = {
- "id": id,
+ "id": graphene.Node.to_global_id("AppInstallation", app_installation.id),
"activate_after_installation": True,
}
- response = staff_api_client.post_graphql(
- query,
- variables=variables,
- )
- content = get_graphql_content(response)
+
+ # when
+ data = _mutate_app_install_retry(staff_api_client, variables)
+
+ # then
app_installation = AppInstallation.objects.get()
- app_installation_data = content["data"]["appRetryInstall"]["appInstallation"]
- _, app_id = graphene.Node.from_global_id(app_installation_data["id"])
+ _, app_id = graphene.Node.from_global_id(data["appInstallation"]["id"])
assert int(app_id) == app_installation.id
- assert app_installation_data["status"] == JobStatus.PENDING.upper()
- assert app_installation_data["manifestUrl"] == app_installation.manifest_url
+ assert data["appInstallation"]["status"] == JobStatus.PENDING.upper()
+ assert data["appInstallation"]["manifestUrl"] == app_installation.manifest_url
mocked_task.assert_called_with(app_installation.pk, True)
@@ -71,6 +76,7 @@ def test_retry_install_app_mutation_by_app(
monkeypatch,
app_installation,
):
+ # given
app_installation.status = JobStatus.FAILED
app_installation.save()
mocked_task = Mock()
@@ -78,26 +84,23 @@ def test_retry_install_app_mutation_by_app(
"saleor.graphql.app.mutations.app_retry_install.install_app_task.delay",
mocked_task,
)
- id = graphene.Node.to_global_id("AppInstallation", app_installation.id)
- query = RETRY_INSTALL_APP_MUTATION
app_api_client.app.permissions.set(
[permission_manage_apps, permission_manage_orders]
)
variables = {
- "id": id,
+ "id": graphene.Node.to_global_id("AppInstallation", app_installation.id),
"activate_after_installation": False,
}
- response = app_api_client.post_graphql(
- query,
- variables=variables,
- )
- content = get_graphql_content(response)
+
+ # when
+ data = _mutate_app_install_retry(app_api_client, variables)
+
+ # then
app_installation = AppInstallation.objects.get()
- app_installation_data = content["data"]["appRetryInstall"]["appInstallation"]
- _, app_id = graphene.Node.from_global_id(app_installation_data["id"])
+ _, app_id = graphene.Node.from_global_id(data["appInstallation"]["id"])
assert int(app_id) == app_installation.id
- assert app_installation_data["status"] == JobStatus.PENDING.upper()
- assert app_installation_data["manifestUrl"] == app_installation.manifest_url
+ assert data["appInstallation"]["status"] == JobStatus.PENDING.upper()
+ assert data["appInstallation"]["manifestUrl"] == app_installation.manifest_url
mocked_task.assert_called_with(app_installation.pk, False)
@@ -109,6 +112,7 @@ def test_retry_install_app_mutation_app_has_more_permission_than_user_requestor(
permission_manage_orders,
monkeypatch,
):
+ # given
app_installation.status = JobStatus.FAILED
app_installation.permissions.add(permission_manage_orders)
app_installation.save()
@@ -118,31 +122,24 @@ def test_retry_install_app_mutation_app_has_more_permission_than_user_requestor(
"saleor.graphql.app.mutations.app_retry_install.install_app_task.delay",
mocked_task,
)
-
- query = RETRY_INSTALL_APP_MUTATION
-
staff_user.user_permissions.set([permission_manage_apps])
-
- id = graphene.Node.to_global_id("AppInstallation", app_installation.id)
variables = {
- "id": id,
+ "id": graphene.Node.to_global_id("AppInstallation", app_installation.id)
}
- response = staff_api_client.post_graphql(
- query,
- variables=variables,
- )
- content = get_graphql_content(response)
- data = content["data"]["appRetryInstall"]
+
+ # when
+ data = _mutate_app_install_retry(staff_api_client, variables)
+
+ # then
errors = data["errors"]
assert not errors
app_installation = AppInstallation.objects.get()
- app_installation_data = content["data"]["appRetryInstall"]["appInstallation"]
- _, app_id = graphene.Node.from_global_id(app_installation_data["id"])
+ _, app_id = graphene.Node.from_global_id(data["appInstallation"]["id"])
assert int(app_id) == app_installation.id
- assert app_installation_data["status"] == JobStatus.PENDING.upper()
- assert app_installation_data["manifestUrl"] == app_installation.manifest_url
+ assert data["appInstallation"]["status"] == JobStatus.PENDING.upper()
+ assert data["appInstallation"]["manifestUrl"] == app_installation.manifest_url
mocked_task.assert_called_with(app_installation.pk, True)
@@ -153,6 +150,7 @@ def test_retry_install_app_mutation_app_has_more_permission_than_app_requestor(
permission_manage_orders,
monkeypatch,
):
+ # given
app_installation.status = JobStatus.FAILED
app_installation.permissions.add(permission_manage_orders)
app_installation.save()
@@ -163,29 +161,23 @@ def test_retry_install_app_mutation_app_has_more_permission_than_app_requestor(
mocked_task,
)
- query = RETRY_INSTALL_APP_MUTATION
app_api_client.app.permissions.set([permission_manage_apps])
- id = graphene.Node.to_global_id("AppInstallation", app_installation.id)
variables = {
- "id": id,
+ "id": graphene.Node.to_global_id("AppInstallation", app_installation.id)
}
- response = app_api_client.post_graphql(
- query,
- variables=variables,
- )
- content = get_graphql_content(response)
- data = content["data"]["appRetryInstall"]
+ # when
+ data = _mutate_app_install_retry(app_api_client, variables)
+ # then
errors = data["errors"]
assert not errors
app_installation = AppInstallation.objects.get()
- app_installation_data = content["data"]["appRetryInstall"]["appInstallation"]
- _, app_id = graphene.Node.from_global_id(app_installation_data["id"])
+ _, app_id = graphene.Node.from_global_id(data["appInstallation"]["id"])
assert int(app_id) == app_installation.id
- assert app_installation_data["status"] == JobStatus.PENDING.upper()
- assert app_installation_data["manifestUrl"] == app_installation.manifest_url
+ assert data["appInstallation"]["status"] == JobStatus.PENDING.upper()
+ assert data["appInstallation"]["manifestUrl"] == app_installation.manifest_url
mocked_task.assert_called_with(app_installation.pk, True)
@@ -205,25 +197,70 @@ def test_cannot_retry_installation_if_status_is_different_than_failed(
"saleor.graphql.app.mutations.app_retry_install.install_app_task.delay",
mocked_task,
)
- query = RETRY_INSTALL_APP_MUTATION
staff_user.user_permissions.set([permission_manage_apps, permission_manage_orders])
- id = graphene.Node.to_global_id("AppInstallation", app_installation.id)
variables = {
- "id": id,
+ "id": graphene.Node.to_global_id("AppInstallation", app_installation.id),
"activate_after_installation": True,
}
- response = staff_api_client.post_graphql(
- query,
- variables=variables,
- )
- content = get_graphql_content(response)
+ # when
+ data = _mutate_app_install_retry(staff_api_client, variables)
+
+ # then
AppInstallation.objects.get()
- app_installation_data = content["data"]["appRetryInstall"]["appInstallation"]
- app_installation_errors = content["data"]["appRetryInstall"]["errors"]
- assert not app_installation_data
+ app_installation_errors = data["errors"]
+ assert not data["appInstallation"]
assert len(app_installation_errors) == 1
assert app_installation_errors[0]["field"] == "id"
assert app_installation_errors[0]["code"] == AppErrorCode.INVALID_STATUS.name
assert not mocked_task.called
+
+
+@patch("saleor.app.installation_utils.send_app_token", Mock())
+@patch(
+ "saleor.graphql.app.mutations.app_retry_install.install_app_task.delay",
+ install_app_task,
+)
+def test_install_retry_app_mutation_with_the_same_identifier_twice(
+ permission_manage_apps,
+ permission_manage_orders,
+ staff_api_client,
+ app_installation,
+ staff_user,
+ monkeypatch,
+ app,
+):
+ # given
+ app_installation.status = JobStatus.FAILED
+ app_installation.save()
+ staff_user.user_permissions.set([permission_manage_apps, permission_manage_orders])
+
+ variables = {
+ "id": graphene.Node.to_global_id("AppInstallation", app_installation.id),
+ "activate_after_installation": True,
+ }
+
+ # when
+ with patch("saleor.app.installation_utils.fetch_manifest") as mocked_fetch:
+ mocked_fetch.return_value = {
+ "id": app.identifier,
+ "tokenTargetUrl": "http://localhost:3000/register",
+ "name": "app",
+ "version": "1.0.0",
+ }
+ data = _mutate_app_install_retry(staff_api_client, variables)
+
+ # then
+ # Installation is done in celery task - response shows that app is being installed
+ assert not data["errors"]
+ assert data["appInstallation"]["status"] == "PENDING"
+ assert data["appInstallation"]["manifestUrl"] == app.manifest_url
+ assert App.objects.count() == 1
+ # Celery bypassed, AppInstallation instance failed to install app
+ app_installation = AppInstallation.objects.first()
+ assert app_installation.status == JobStatus.FAILED
+ assert app_installation.message == (
+ "identifier: "
+ "['App with the same identifier is already installed: Sample app objects']"
+ )
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index b60359e862..817bbcc32b 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -7445,6 +7445,7 @@ def app(db):
name="Sample app objects",
is_active=True,
identifier="saleor.app.test",
+ manifest_url="http://localhost:3000/manifest",
)
return app