Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add tests for installation tasks
Maciej Korycinski0215ccd68438
diff --git a/saleor/app/installation_utils.py b/saleor/app/installation_utils.pyindex 2faee6b4c4..b57a6d6f57 100644--- a/saleor/app/installation_utils.py+++ b/saleor/app/installation_utils.py@@ -1,12 +1,10 @@-from typing import Iterable-import requests-from django.contrib.auth.models import Permissionfrom django.contrib.sites.models import Site+from django.core.exceptions import ValidationErrorfrom django.core.validators import URLValidatorfrom django.db import transaction-from .models import App+from .models import App, AppJobfrom .types import AppTypeREQUEST_TIMEOUT = 30@@ -23,24 +21,27 @@ def send_app_token(target_url: str, token: str):def validate_manifest_fields(manifest_data):- pass+ token_target_url = manifest_data.get("token_target_url")++ try:+ url_validator = URLValidator()+ url_validator(token_target_url)+ except ValidationError:+ raise ValidationError({"token_target_url": "Incorrect format."})@transaction.atomicdef install_app(- manifest_url: str,- required_permissions: Iterable[Permission],- activate: bool = False,+ app_job: AppJob, activate: bool = False,):- manifest_data = requests.get(manifest_url, timeout=REQUEST_TIMEOUT).json()- validate_manifest_fields(manifest_data)+ response = requests.get(app_job.manifest_url, timeout=REQUEST_TIMEOUT)+ response.raise_for_status()+ manifest_data = response.json()- token_target_url = manifest_data.get("token_target_url")- url_validator = URLValidator()- url_validator(token_target_url)+ validate_manifest_fields(manifest_data)app = App.objects.create(- name=manifest_data.get("name"),+ name=app_job.name,is_active=activate,identificator=manifest_data.get("identificator"),about_app=manifest_data.get("about_app"),@@ -50,9 +51,11 @@ def install_app(support_url=manifest_data.get("support_url"),configuration_url=manifest_data.get("configuration_url"),app_url=manifest_data.get("app_url"),- type=AppType.FROM_MARKETPLACE,+ type=AppType.EXTERNAL,)- app.permissions.set(required_permissions)+ app.permissions.set(app_job.permissions.all())token = app.tokens.create(name="Default token")- send_app_token(target_url=token_target_url, token=token.auth_token)+ send_app_token(+ target_url=manifest_data.get("token_target_url"), token=token.auth_token+ )return appdiff --git a/saleor/app/migrations/0002_auto_20200430_0701.py b/saleor/app/migrations/0002_auto_20200507_0514.pysimilarity index 91%rename from saleor/app/migrations/0002_auto_20200430_0701.pyrename to saleor/app/migrations/0002_auto_20200507_0514.pyindex 74614dd654..d889cdd7bc 100644--- a/saleor/app/migrations/0002_auto_20200430_0701.py+++ b/saleor/app/migrations/0002_auto_20200507_0514.py@@ -1,4 +1,4 @@-# Generated by Django 3.0.5 on 2020-04-30 12:01+# Generated by Django 3.0.5 on 2020-05-07 10:14from django.db import migrations, models@@ -36,8 +36,7 @@ class Migration(migrations.Migration):migrations.AddField(model_name="app",name="identificator",- field=models.CharField(blank=True, null=True, max_length=256),- preserve_default=False,+ field=models.CharField(blank=True, max_length=256, null=True),),migrations.AddField(model_name="app", name="support_url", field=models.URLField(blank=True),@@ -46,10 +45,7 @@ class Migration(migrations.Migration):model_name="app",name="type",field=models.CharField(- choices=[- ("custom", "custom"),- ("from_marketplace", "from_marketplace"),- ],+ choices=[("custom", "custom"), ("external", "EXTERNAL")],default="custom",max_length=60,),diff --git a/saleor/app/tasks.py b/saleor/app/tasks.pyindex 8f656195c2..fbe41cdcfa 100644--- a/saleor/app/tasks.py+++ b/saleor/app/tasks.py@@ -1,5 +1,5 @@from django.core.exceptions import ValidationError-from requests import RequestException+from requests import HTTPError, RequestExceptionfrom .. import celeryconffrom ..core import JobStatus@@ -11,18 +11,17 @@ from .models import AppJobdef install_app_task(job_id, activate=False):app_job = AppJob.objects.get(id=job_id)try:- install_app(app_job.manifest_url, app_job.permissions.all(), activate=activate)+ install_app(app_job, activate=activate)app_job.delete()return- except ValidationError:- app_job.message = (- "token_target_url has inccorrect format. Contact with app support."- )- except RequestException:+ except ValidationError as e:+ msg = ", ".join([f"{name}: {err}" for name, err in e.message_dict.items()])+ app_job.message = msg+ except (RequestException, HTTPError):app_job.message = ("Failed to connect to app. Try later or contact with app support.")except Exception:- app_job.message = "Unknow error. Concact with app support."+ app_job.message = "Unknow error. Contact with app support."app_job.status = JobStatus.FAILEDapp_job.save()diff --git a/saleor/app/types.py b/saleor/app/types.pyindex 603ca5ceca..7458767f3a 100644--- a/saleor/app/types.py+++ b/saleor/app/types.py@@ -1,5 +1,5 @@class AppType:CUSTOM = "custom"- FROM_MARKETPLACE = "from_marketplace"+ EXTERNAL = "external"- CHOICES = [(CUSTOM, "custom"), (FROM_MARKETPLACE, "from_marketplace")]+ CHOICES = [(CUSTOM, "custom"), (EXTERNAL, "EXTERNAL")]diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex a08f1e12c9..341703af30 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -307,7 +307,7 @@ input AppTokenInput {enum AppTypeEnum {CUSTOM- FROM_MARKETPLACE+ EXTERNAL}type AppUpdate {diff --git a/tests/cassettes/test_install_app_task.yaml b/tests/cassettes/test_install_app_task.yamlnew file mode 100644index 0000000000..2bb0b83361--- /dev/null+++ b/tests/cassettes/test_install_app_task.yaml@@ -0,0 +1,107 @@+interactions:+- request:+ body: null+ headers:+ Accept:+ - '*/*'+ Accept-Encoding:+ - gzip, deflate+ Connection:+ - keep-alive+ User-Agent:+ - python-requests/2.23.0+ method: GET+ uri: http://localhost:3000/manifest+ response:+ body:+ string: "{\n \"name\": \"app\",\n \"version\": \"1.0.0\",\n \"about_app\"\+ : \"Lorem ipsum\",\n \"data_privacy\": \"Lorem ipsum\",\n \"data_privacy_url\"\+ : \"http://localhost:8888/app-data-privacy\",\n \"homepage_url\": \"http://localhost:8888/homepage\"\+ ,\n \"support_url\": \"http://localhost:8888/support\",\n \"configuration_url\"\+ : \"htpp://localhost:8888/configuration\",\n \"app_url\": \"http://localhost:8888/app\"\+ ,\n \"token_target_url\": \"http://localhost:3000/register\",\n \"identificator\"\+ : \"app1\"\n}"+ headers:+ Access-Control-Allow-Credentials:+ - 'true'+ Cache-Control:+ - no-cache+ Connection:+ - keep-alive+ Content-Length:+ - '457'+ Content-Type:+ - application/json; charset=utf-8+ Date:+ - Thu, 07 May 2020 07:55:46 GMT+ ETag:+ - W/"1c9-8xRk1lVv4obFp1NpaAqOhbFNhyU"+ Expires:+ - '-1'+ Pragma:+ - no-cache+ Vary:+ - Origin, Accept-Encoding+ X-Content-Type-Options:+ - nosniff+ X-Powered-By:+ - Express+ status:+ code: 200+ message: OK+- request:+ body: '{"auth_token": "WeYRSINjjQV3IEcJVgk0IE7OxeoLuj"}'+ headers:+ Accept:+ - '*/*'+ Accept-Encoding:+ - gzip, deflate+ Connection:+ - keep-alive+ Content-Length:+ - '48'+ Content-Type:+ - application/json+ User-Agent:+ - python-requests/2.23.0+ x-saleor-domain:+ - mirumee.com+ method: POST+ uri: http://localhost:3000/register+ response:+ body:+ string: "{\n \"auth_token\": \"WeYRSINjjQV3IEcJVgk0IE7OxeoLuj\",\n \"id\"\+ : 8\n}"+ headers:+ Access-Control-Allow-Credentials:+ - 'true'+ Access-Control-Expose-Headers:+ - Location+ Cache-Control:+ - no-cache+ Connection:+ - keep-alive+ Content-Length:+ - '63'+ Content-Type:+ - application/json; charset=utf-8+ Date:+ - Thu, 07 May 2020 07:55:46 GMT+ ETag:+ - W/"3f-rrHlPsVQDlQJanMe/Ngzy/3zZao"+ Expires:+ - '-1'+ Location:+ - http://localhost:3000/register/8+ Pragma:+ - no-cache+ Vary:+ - Origin, X-HTTP-Method-Override, Accept-Encoding+ X-Content-Type-Options:+ - nosniff+ X-Powered-By:+ - Express+ status:+ code: 201+ message: Created+version: 1diff --git a/tests/cassettes/test_install_app_task_request_timeout.yaml b/tests/cassettes/test_install_app_task_request_timeout.yamlnew file mode 100644index 0000000000..e5725928eb--- /dev/null+++ b/tests/cassettes/test_install_app_task_request_timeout.yaml@@ -0,0 +1,52 @@+interactions:+- request:+ body: null+ headers:+ Accept:+ - '*/*'+ Accept-Encoding:+ - gzip, deflate+ Connection:+ - keep-alive+ User-Agent:+ - python-requests/2.23.0+ method: GET+ uri: http://localhost:3000/manifest+ response:+ body:+ string: "{\n \"name\": \"app\",\n \"version\": \"1.0.0\",\n \"about_app\"\+ : \"Lorem ipsum\",\n \"data_privacy\": \"Lorem ipsum\",\n \"data_privacy_url\"\+ : \"http://localhost:8888/app-data-privacy\",\n \"homepage_url\": \"http://localhost:8888/homepage\"\+ ,\n \"support_url\": \"http://localhost:8888/support\",\n \"configuration_url\"\+ : \"htpp://localhost:8888/configuration\",\n \"app_url\": \"http://localhost:8888/app\"\+ ,\n \"token_target_url\": \"http://localhost:3000/register\",\n \"identificator\"\+ : \"app1\"\n}"+ headers:+ Access-Control-Allow-Credentials:+ - 'true'+ Cache-Control:+ - no-cache+ Connection:+ - keep-alive+ Content-Length:+ - '457'+ Content-Type:+ - application/json; charset=utf-8+ Date:+ - Thu, 07 May 2020 08:49:14 GMT+ ETag:+ - W/"1c9-8xRk1lVv4obFp1NpaAqOhbFNhyU"+ Expires:+ - '-1'+ Pragma:+ - no-cache+ Vary:+ - Origin, Accept-Encoding+ X-Content-Type-Options:+ - nosniff+ X-Powered-By:+ - Express+ status:+ code: 200+ message: OK+version: 1diff --git a/tests/cassettes/test_install_app_task_wrong_format_of_target_token_url.yaml b/tests/cassettes/test_install_app_task_wrong_format_of_target_token_url.yamlnew file mode 100644index 0000000000..af98ca7b24--- /dev/null+++ b/tests/cassettes/test_install_app_task_wrong_format_of_target_token_url.yaml@@ -0,0 +1,52 @@+interactions:+- request:+ body: null+ headers:+ Accept:+ - '*/*'+ Accept-Encoding:+ - gzip, deflate+ Connection:+ - keep-alive+ User-Agent:+ - python-requests/2.23.0+ method: GET+ uri: http://localhost:3000/manifest-wrong+ response:+ body:+ string: "{\n \"name\": \"app\",\n \"version\": \"1.0.0\",\n \"about_app\"\+ : \"Lorem ipsum\",\n \"data_privacy\": \"Lorem ipsum\",\n \"data_privacy_url\"\+ : \"http://localhost:8888/app-data-privacy\",\n \"homepage_url\": \"http://localhost:8888/homepage\"\+ ,\n \"support_url\": \"http://localhost:8888/support\",\n \"configuration_url\"\+ : \"htpp://localhost:8888/configuration\",\n \"app_url\": \"http://localhost:8888/app\"\+ ,\n \"token_target_url\": \"register-wrong-format\",\n \"identificator\"\+ : \"app2\"\n}"+ headers:+ Access-Control-Allow-Credentials:+ - 'true'+ Cache-Control:+ - no-cache+ Connection:+ - keep-alive+ Content-Length:+ - '448'+ Content-Type:+ - application/json; charset=utf-8+ Date:+ - Thu, 07 May 2020 08:21:20 GMT+ ETag:+ - W/"1c0-JJiYGAsB1lIohC/29ugFSHRYbSM"+ Expires:+ - '-1'+ Pragma:+ - no-cache+ Vary:+ - Origin, Accept-Encoding+ X-Content-Type-Options:+ - nosniff+ X-Powered-By:+ - Express+ status:+ code: 200+ message: OK+version: 1diff --git a/tests/cassettes/test_install_app_task_wrong_response_code.yaml b/tests/cassettes/test_install_app_task_wrong_response_code.yamlnew file mode 100644index 0000000000..74f30be6ea--- /dev/null+++ b/tests/cassettes/test_install_app_task_wrong_response_code.yaml@@ -0,0 +1,46 @@+interactions:+- request:+ body: null+ headers:+ Accept:+ - '*/*'+ Accept-Encoding:+ - gzip, deflate+ Connection:+ - keep-alive+ User-Agent:+ - python-requests/2.23.0+ method: GET+ uri: http://localhost:3000/manifest-wrong1+ response:+ body:+ string: '{}'+ headers:+ Access-Control-Allow-Credentials:+ - 'true'+ Cache-Control:+ - no-cache+ Connection:+ - keep-alive+ Content-Length:+ - '2'+ Content-Type:+ - application/json; charset=utf-8+ Date:+ - Thu, 07 May 2020 09:49:45 GMT+ ETag:+ - W/"2-vyGp6PvFo4RvsFtPoIWeCReyIC8"+ Expires:+ - '-1'+ Pragma:+ - no-cache+ Vary:+ - Origin, Accept-Encoding+ X-Content-Type-Options:+ - nosniff+ X-Powered-By:+ - Express+ status:+ code: 404+ message: Not Found+version: 1diff --git a/tests/conftest.py b/tests/conftest.pyindex 542714ccf8..0b44a45e80 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -1866,7 +1866,7 @@ def external_app(db):app = App.objects.create(name="External App",is_active=True,- type=AppType.FROM_MARKETPLACE,+ type=AppType.EXTERNAL,identificator="mirumee.app.sample",about_app="About app text.",data_privacy="Data privacy text.",diff --git a/tests/test_app_tasks.py b/tests/test_app_tasks.pynew file mode 100644index 0000000000..07f634e911--- /dev/null+++ b/tests/test_app_tasks.py@@ -0,0 +1,81 @@+from unittest.mock import Mock++import pytest+from requests import RequestException++from saleor.app.models import App, AppJob+from saleor.app.tasks import install_app_task+from saleor.core import JobStatus+++def app_job():+ app_job = AppJob.objects.create(+ name="External App", manifest_url="http://localhost:3000/manifest",+ )+ return app_job+++def test_install_app_task(app_job):+ install_app_task(app_job.id, activate=False)+ assert not AppJob.objects.all().exists()+ app = App.objects.filter(name=app_job.name).first()+ assert app+ assert app.is_active is False+++def test_install_app_task_wrong_format_of_target_token_url():+ app_job = AppJob.objects.create(+ name="External App", manifest_url="http://localhost:3000/manifest-wrong",+ )+ install_app_task(app_job.id, activate=False)+ app_job.refresh_from_db()+ assert app_job.status == JobStatus.FAILED+ assert app_job.message == "token_target_url: ['Incorrect format.']"+ assert not App.objects.all()+++def test_install_app_task_request_timeout(monkeypatch, app_job):+ mocked_post = Mock(side_effect=RequestException("Timeout"))+ monkeypatch.setattr("saleor.app.installation_utils.requests.post", mocked_post)+ install_app_task(app_job.pk, activate=True)+ app_job.refresh_from_db()++ assert not App.objects.all().exists()+ assert app_job.status == JobStatus.FAILED+ assert (+ app_job.message+ == "Failed to connect to app. Try later or contact with app support."+ )+++def test_install_app_task_wrong_response_code(monkeypatch, app_job):+ app_job = AppJob.objects.create(+ name="External App", manifest_url="http://localhost:3000/manifest-wrong1",+ )+ mocked_post = Mock()+ mocked_post.status_code = 404+ monkeypatch.setattr("saleor.app.installation_utils.requests.post", mocked_post)+ install_app_task(app_job.pk, activate=True)+ app_job.refresh_from_db()++ assert not App.objects.all().exists()+ assert app_job.status == JobStatus.FAILED+ assert (+ app_job.message+ == "Failed to connect to app. Try later or contact with app support."+ )+++def test_install_app_task_undefined_error(monkeypatch, app_job):+ mock_install_app = Mock(side_effect=Exception("Unknow"))++ monkeypatch.setattr("saleor.app.tasks.install_app", mock_install_app)+ install_app_task(app_job.pk)+ app_job.refresh_from_db()+ assert app_job.status == JobStatus.FAILED+ assert app_job.message == "Unknow error. Contact with app support."