Best Python code snippet using Airtest
test_oauth2maker_cmd.py
Source:test_oauth2maker_cmd.py
1"""2Test cases for the `oauth2_app_maker` abstract django parent command.3Use `tests.app_maker_testing.py` as a simple test-only extension, to turn an4abstract command into a specific one for testing. Test models are defined in5`tests.models.py`, to decouple test logic of the abstract command from specific6Application classes that are used in production.7"""8from datetime import datetime9import six10from django.core.exceptions import ValidationError11from django.core.management import call_command12from faker import Factory13from pytz import timezone14from testfixtures import LogCapture15from test_case import StandaloneAppTestCase16from tests.management.commands.app_maker_testing import Command as TestedCommand17from tests.test_compat import patch18faker = Factory.create()19def command_type_with_model(model_type):20 """21 Convenience function for testing. Create `oauth2_app_maker` extension22 class bound to the specified model type.23 """24 from tests.ide_test_compat import AbstractAppMaker25 class Command(AbstractAppMaker):26 @classmethod27 def app_model(cls):28 return model_type29 return Command30class TestOauth2AppMakerCmd(StandaloneAppTestCase):31 """32 Test cases for the `oauth2_app_maker` abstract django parent command.33 """34 def test_model_validation_bad_type(self):35 """36 Test validation: model type is as expected.37 """38 class BadAppModel:39 pass40 cmd = command_type_with_model(BadAppModel)()41 with six.assertRaisesRegex(self, ValidationError, "must extend django.db.models.Model"):42 cmd.handle()43 def test_model_validation_no_fields(self):44 """45 Test validation: model provides required fields.46 """47 from tests.ide_test_compat import NoRequiredFieldsApp48 cmd = command_type_with_model(NoRequiredFieldsApp)()49 with six.assertRaisesRegex(50 self, ValidationError, "Your app model does not provide all required fields"51 ):52 cmd.handle()53 @patch('oauth2_client.fetcher.timezone.now')54 @patch.object(TestedCommand, 'app_model')55 def test_create(self, model_mock, now_mock):56 """57 Ensure Application gets created in the DB.58 """59 from tests.ide_test_compat import fake_app_name, TestApplication60 model_mock.return_value = TestApplication61 now = datetime(2020, 1, 1, tzinfo=timezone('CET')) # arbitrary datetime62 now_mock.return_value = now63 app_name = fake_app_name()64 cmd_args = [65 'app_maker_testing',66 '--name=%s' % app_name,67 '--required-property=hello',68 '--optional-property=world',69 ]70 call_command(*cmd_args)71 check_app = TestApplication.objects.get(name=app_name)72 self.assertEqual(check_app.required_property, "hello")73 self.assertEqual(check_app.optional_property, "world")74 self.assertEqual(check_app.created, now)75 self.assertEqual(check_app.updated, now)76 @patch.object(TestedCommand, 'app_model')77 def test_create_validation(self, model_mock):78 """79 Ensure model validation works when creating an application.80 Creation should be aborted upon validation error.81 """82 from tests.ide_test_compat import fake_app_name, TestApplication83 model_mock.return_value = TestApplication84 app_name = fake_app_name()85 # one required property is missing86 cmd_args = [87 'app_maker_testing',88 '--name=%s' % app_name,89 ]90 with LogCapture() as logs:91 with self.assertRaises(ValidationError):92 call_command(*cmd_args)93 check_app = TestApplication.objects.filter(name=app_name).first()94 self.assertFalse(check_app)95 self.assertIn("Please correct the following validation errors", str(logs))96 @patch.object(TestedCommand, 'app_model')97 def test_cannot_update_nonexistent_app(self, model_mock):98 """99 Ensure we can't update a nonexistent application.100 """101 from tests.ide_test_compat import fake_app_name, TestApplication102 model_mock.return_value = TestApplication103 app_name = fake_app_name()104 cmd_args = [105 'app_maker_testing',106 '--update',107 '--name=%s' % app_name,108 '--required-property=some_value',109 ]110 with LogCapture() as logs:111 with self.assertRaises(ValidationError):112 call_command(*cmd_args)113 self.assertIn("must exist to be updated", str(logs))114 @patch.object(TestedCommand, 'app_model')115 def test_update(self, model_mock):116 """117 Ensure update functionality works fine.118 """119 from tests.ide_test_compat import fake_app_name, TestApplication120 model_mock.return_value = TestApplication121 app_name = fake_app_name()122 initial_value = 'good morning'123 cmd_args = [124 'app_maker_testing',125 '--name=%s' % app_name,126 '--required-property=%s' % initial_value,127 '--optional-property=opt'128 ]129 call_command(*cmd_args)130 check_app = TestApplication.objects.get(name=app_name)131 upd_time_1 = check_app.updated132 create_time_1 = check_app.created133 self.assertEqual(check_app.required_property, initial_value)134 updated_value = 'good bye'135 cmd_args = [136 'app_maker_testing',137 '--update',138 '--name=%s' % app_name,139 '--required-property=%s' % updated_value,140 ]141 call_command(*cmd_args)142 check_app.refresh_from_db()143 upd_time_2 = check_app.updated144 create_time_2 = check_app.created145 self.assertEqual(check_app.required_property, updated_value)146 self.assertEqual(check_app.optional_property, 'opt')147 self.assertGreater(upd_time_2, upd_time_1)148 self.assertEqual(create_time_1, create_time_2)149 @patch.object(TestedCommand, 'app_model')150 def test_update_validation(self, model_mock):151 """152 Check if update functionality validates the data in update mode.153 Update should be aborted upon validation errors.154 """155 from tests.ide_test_compat import fake_app_name, TestApplication156 model_mock.return_value = TestApplication157 app_name = fake_app_name()158 cmd_args = [159 'app_maker_testing',160 '--name=%s' % app_name,161 '--required-property=hello',162 '--optional-property=opt',163 ]164 call_command(*cmd_args)165 check_app = TestApplication.objects.get(name=app_name)166 upd_time_1 = check_app.updated167 create_time_1 = check_app.created168 # attempt to make a forbidden change169 cmd_args = [170 'app_maker_testing',171 '--update',172 '--name=%s' % app_name,173 '--required-property='174 ]175 with LogCapture() as logs:176 with self.assertRaises(ValidationError):177 call_command(*cmd_args)178 self.assertIn("Please correct the following validation errors", str(logs))179 # make sure values didn't change (update aborted)180 check_app.refresh_from_db()181 self.assertEqual(check_app.required_property, "hello")182 self.assertEqual(check_app.optional_property, "opt")183 self.assertEqual(upd_time_1, check_app.updated)184 self.assertEqual(create_time_1, check_app.created)185 @patch.object(TestedCommand, 'app_model')186 def test_create_enforce_unique_name(self, model_mock):187 """188 Ensure name uniqueness is enforced upon Application creation, even when189 not defined on the model.190 """191 from tests.ide_test_compat import fake_app_name, TestApplicationNoUnique192 model_mock.return_value = TestApplicationNoUnique193 app_name = fake_app_name()194 cmd_args = [195 'app_maker_testing',196 '--name=%s' % app_name,197 '--required-property=hello'198 ]199 call_command(*cmd_args)200 # try to create same thing again201 with LogCapture() as logs:202 with self.assertRaises(ValidationError):203 call_command(*cmd_args)204 self.assertIn("Application already exists", str(logs))205 self.assertIn(app_name, str(logs))206 @patch.object(TestedCommand, 'app_model')207 def test_model_with_name_blank(self, model_mock):208 """209 Ensure an Application object without name won't get created.210 """211 from tests.ide_test_compat import NameNotMandatoryApp212 model_mock.return_value = NameNotMandatoryApp213 cmd_args = [214 'app_maker_testing',215 '--name=',216 ]217 with six.assertRaisesRegex(self, ValidationError, "This field cannot be blank"):...
views.py
Source:views.py
1import json2from django.http import JsonResponse3from django.shortcuts import render4from mypro.models import *5from rest_framework import response, serializers6from rest_framework.pagination import PageNumberPagination7from rest_framework.views import APIView8import time9class AppSerializers(serializers.ModelSerializer):10 class Meta:11 model = App12 # fields = "__all__"13 fields = ["product_id", "product_name"]14class Paginator(PageNumberPagination):15 16 # é»è®¤æ¯é¡µæ¾ç¤ºçæ°æ®æ¡æ°17 page_size = 1018 19 # è·åURLåæ°ä¸ç设置页æ°20 page_query_param = 'page_number'21 # è·åURLåæ°ä¸ç设置çæ¯é¡µæ¾ç¤ºæ°æ®æ¡æ°22 page_size_query_param = 'page_size'23 # æ大æ¯æçæ¯é¡µæ¾ç¤ºçæ¡æ°24 max_page_size = 2025class Apps(APIView):26 27 def get(self, request, *args, **kwargs):28 # è·åææç产å线29 app_list = App.objects.filter(is_delete=0).order_by("create_time")30 # 计ç®äº§å线个æ°31 total = app_list.count()32 # å建å页对象å®ä¾33 paginator = Paginator()34 page_app_list = paginator.paginate_queryset(app_list, self.request, view=self)35 page_number = request.GET.get("page_number", 1)36 page_size = request.GET.get("page_size", paginator.page_size)37 # 对æ°æ®åºåå38 # result = AppSerializers(instance=page_app_list, many=True)39 result = AppSerializers(instance=page_app_list, many=True)40 return response.Response({41 "code": 1000,42 "success": True,43 "page_number": page_number,44 "page_size": page_size,45 "total": total,46 "data": result.data47 })48 49 def post(self, request, *args, **kwargs):50 req_data = json.loads(request.body)51 req_data["product_id"] = str(round(time.time()))[::-1][:-3]52 app = AppSerializers(data=req_data)53 if app.is_valid():54 app.save()55 return JsonResponse({56 "code": 10000,57 "success": True,58 "data": req_data59 })60 else:61 return JsonResponse({62 "code": 90000,63 "success": False,64 "msg": app.errors65 })66 def put(self, request, *args, **kwargs):67 req_data = json.loads(request.body)68 app = App.objects.filter(pk=req_data.get("product_id"), is_delete=0).first()69 if not app:70 return JsonResponse({71 "code": 90000,72 "success": False,73 "msg": "请确认该产å线æ¯å¦åå¨ï¼"74 })75 check_app = AppSerializers(instance=app, data=req_data)76 if check_app.is_valid():77 check_app.save()78 return JsonResponse({79 "code": 10000,80 "success": True,81 "data": req_data82 })83 else:84 return JsonResponse({85 "code": 90000,86 "success": False,87 "msg": check_app.errors88 })89 90 def delete(self, request, *args, **kwargs):91 req_data = json.loads(request.body)92 app = App.objects.filter(pk=req_data.get("product_id"), is_delete=0).first()93 if not app:94 return JsonResponse({95 "code": 90000,96 "success": False,97 "msg": "请确认该产å线æ¯å¦åå¨!"98 })99 else:100 app.is_delete = 1101 app.save()102 return response.Response({103 "code": 10000,104 "success": True,105 "msg": "产å线å é¤æå!"...
test_oauth2client_cmd.py
Source:test_oauth2client_cmd.py
1"""2Test cases for `oauth2client_app` django command.3"""4from django.core.exceptions import ValidationError5from django.core.management import call_command6from faker import Factory7from testfixtures import LogCapture8from test_case import StandaloneAppTestCase9faker = Factory.create()10class TestClientAppMakerCommand(StandaloneAppTestCase):11 """12 Test cases for the `oauth2client_app` django command.13 """14 def test_app_create(self):15 """16 Test creating various oauth applications with different parameters.17 Not using ddt here to be able to run this in IDE (model imports)18 """19 from .ide_test_compat import Application, fake_app_name, fake_client_id, fake_client_secret20 for grant_type in [grant[0] for grant in Application.GRANT_TYPES]:21 app_name = fake_app_name()22 service_host = faker.url()23 token_uri = faker.url()24 client_id = fake_client_id()25 client_secret = fake_client_secret()26 test_email = faker.email()27 cmd_args = [28 'oauth2client_app',29 '--name=%s' % app_name,30 '--authorization-grant-type=%s' % grant_type,31 '--service-host=%s' % service_host,32 '--client-id=%s' % client_id,33 '--token-uri=%s' % token_uri,34 '--scope=read write',35 '--client-secret=%s' % client_secret,36 '--extra-settings={"subject": "%s"}' % test_email,37 '-v 2'38 ]39 call_command(*cmd_args)40 check_app = Application.objects.get(name=app_name)41 self.assertEqual(check_app.authorization_grant_type, grant_type)42 self.assertEqual(check_app.service_host, service_host)43 self.assertEqual(check_app.token_uri, token_uri)44 self.assertEqual(check_app.client_id, client_id)45 self.assertEqual(check_app.client_secret, client_secret)46 self.assertEqual(check_app.extra_settings['subject'], test_email)47 self.assertEqual(check_app.scope, "read write")48 def test_jwt_flow_validation(self):49 """50 Make sure creating JWT_BEARER application fails, if no subject provided51 """52 from .ide_test_compat import Application, fake_app_name, fake_client_id, fake_client_secret53 app_name = fake_app_name()54 token_uri = faker.url()55 service_host = faker.url()56 client_id = fake_client_id()57 client_secret = fake_client_secret()58 cmd_args = [59 'oauth2client_app',60 '--name=%s' % app_name,61 '--authorization-grant-type=%s' % Application.GRANT_JWT_BEARER,62 '--token-uri=%s' % token_uri,63 '--service-host=%s' % service_host,64 '--client-id=%s' % client_id,65 '--client-secret=%s' % client_secret,66 '-v 2'67 ]68 with LogCapture() as logs:69 with self.assertRaises(ValidationError):70 call_command(*cmd_args)71 check_app = Application.objects.filter(name=app_name).first()72 self.assertFalse(check_app)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!