How to use test_response_401 method in Django Test Plus

Best Python code snippet using django-test-plus_python

test_upgrade.py

Source:test_upgrade.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2import unittest3from pyopenapi.migration.versions.v2_0.scanner.upgrade import converters4from ....utils import get_test_data_folder, SampleApp5_APP = SampleApp.create(6 get_test_data_folder(version='2.0', which='upgrade'), to_spec_version='2.0')7class ExternalDocConverterTestCase(unittest.TestCase):8 """ test case for externalDoc converter """9 def test_external_doc(self):10 ex_doc, _ = _APP.resolve_obj('#/externalDocs', from_spec_version='2.0')11 obj = converters.to_external_docs(ex_doc, '')12 self.assertTrue('url' in obj)13 self.assertEqual(obj['url'], ex_doc.url)14 self.assertTrue('description' in obj)15 self.assertEqual(obj['description'], ex_doc.description)16class ItemsConverterTestCase(unittest.TestCase):17 """ test case for items converter """18 def test_with_type(self):19 items, _ = _APP.resolve_obj(20 '#/paths/~1p1/get/parameters/0/items', from_spec_version='2.0')21 obj = converters.from_items(items, '')22 self.assertEqual(obj['type'], getattr(items, 'type'))23 def test_with_ref(self):24 items, _ = _APP.resolve_obj(25 '#/paths/~1p1/get/responses/200/schema/items',26 from_spec_version='2.0')27 obj = converters.from_items(items, '')28 self.assertEqual(obj['$ref'], '#/definitions/pet')29class TagConverterTestCase(unittest.TestCase):30 """ test case for tag converter """31 def test_basic(self):32 tags, _ = _APP.resolve_obj('#/tags', from_spec_version='2.0')33 obj = converters.to_tag(tags[0], '')34 self.assertEqual(obj['name'], tags[0].name)35 self.assertEqual(obj['description'], tags[0].description)36 self.assertTrue('externalDocs' in obj)37 self.assertEqual(obj['externalDocs']['url'], tags[0].externalDocs.url)38class XMLConverterTestCase(unittest.TestCase):39 """ test case for XML converter """40 def test_basic(self):41 pet, _ = _APP.resolve_obj('#/definitions/pet', from_spec_version='2.0')42 x = pet.properties['photoUrls'].xml43 obj = converters.to_xml(x, '')44 self.assertEqual(obj['name'], x.name)45 self.assertEqual(obj['wrapped'], x.wrapped)46class SchemaConverterTestCase(unittest.TestCase):47 """ test case for schema converter """48 def test_basic(self):49 pet, _ = _APP.resolve_obj('#/definitions/pet', from_spec_version='2.0')50 obj = converters.to_schema(pet, '')51 self.assertEqual(obj['required'], pet.required)52 _id = obj['properties']['id']53 self.assertEqual(_id['type'], 'integer')54 self.assertEqual(_id['format'], 'int64')55 _category = obj['properties']['category']56 self.assertEqual(_category['$ref'], '#/definitions/category')57 _photo_urls = obj['properties']['photoUrls']58 self.assertEqual(_photo_urls['type'], 'array')59 self.assertEqual(_photo_urls['items']['type'], 'string')60 _status = obj['properties']['status']61 self.assertEqual(62 sorted(_status['enum']), sorted(['available', 'pending', 'sold']))63class SecuritySchemeConverterTestCase(unittest.TestCase):64 """ test case for security scheme """65 def test_basic(self):66 auth, _ = _APP.resolve_obj(67 '#/securityDefinitions/petstore_auth', from_spec_version='2.0')68 obj = converters.to_security_scheme(auth, '')69 self.assertEqual(obj['type'], 'oauth2')70 flows = obj['flows']['implicit']71 self.assertEqual(flows['authorizationUrl'],72 'http://petstore.swagger.io/api/oauth/dialog')73 self.assertTrue('write:pets' in flows['scopes'])74 self.assertTrue('read:pets' in flows['scopes'])75class HeaderConverterTestCase(unittest.TestCase):76 """ test case for header """77 def test_basic(self):78 header, _ = _APP.resolve_obj(79 '#/paths/~1p2/get/responses/200/headers/X-TEST',80 from_spec_version='2.0')81 obj = converters.to_header(header, '')82 self.assertEqual(obj['style'], 'simple')83 self.assertEqual(obj['schema']['type'], 'array')84 self.assertEqual(obj['schema']['items']['type'], 'string')85class ParameterConverterTestCase(unittest.TestCase):86 """ test case for parameter """87 def test_basic(self):88 param, _ = _APP.resolve_obj(89 '#/paths/~1p1/get/parameters/0', from_spec_version='2.0')90 obj, pctx = converters.from_parameter(param, None, [], '')91 self.assertFalse(pctx.is_body)92 self.assertFalse(pctx.is_file)93 self.assertEqual(obj['style'], 'form')94 self.assertEqual(obj['explode'], True)95 self.assertEqual(obj['in'], 'query')96 self.assertEqual(obj['name'], 'status')97 _schema = obj['schema']98 self.assertEqual(_schema['default'], 'available')99 self.assertEqual(_schema['type'], 'array')100 _items = _schema['items']101 self.assertEqual(_items['type'], 'string')102 self.assertEqual(103 sorted(_items['enum']), sorted(['available', 'pending', 'sold']))104 def test_file_in_form(self):105 param, _ = _APP.resolve_obj(106 '#/parameters/form_file', from_spec_version='2.0')107 obj, pctx = converters.from_parameter(108 param, None, ['application/x-www-form-urlencoded'], '')109 self.assertTrue(pctx.is_body)110 self.assertTrue(pctx.is_file)111 _schema = obj['content']['application/x-www-form-urlencoded']['schema'][112 'properties']['form_file']113 self.assertEqual(_schema['type'], 'string')114 self.assertEqual(_schema['format'], 'binary')115 def test_file_in_body(self):116 """ this is not a valid usage in 2.0, but someone suffer from that:117 https://github.com/OAI/OpenAPI-Specification/issues/1226118 """119 # normal body parameter with file type120 param, _ = _APP.resolve_obj(121 '#/parameters/body_file', from_spec_version='2.0')122 obj, pctx = converters.from_parameter(123 param, None, ['application/x-www-form-urlencoded'], '')124 self.assertTrue(pctx.is_body)125 self.assertTrue(pctx.is_file)126 _schema = obj['content']['application/x-www-form-urlencoded']['schema'][127 'properties']['body_file']128 self.assertEqual(_schema['type'], 'string')129 self.assertEqual(_schema['format'], 'binary')130 # body parameter with $ref to schema with file type131 param, _ = _APP.resolve_obj(132 '#/parameters/body_file_ref', from_spec_version='2.0')133 obj, pctx = converters.from_parameter(134 param, None, ['application/x-www-form-urlencoded'], '')135 self.assertTrue(pctx.is_body)136 self.assertTrue(pctx.is_file)137 _schema = obj['content']['application/x-www-form-urlencoded']['schema'][138 'properties']['body_file_ref']139 self.assertEqual(_schema['$ref'], '#/definitions/some_file')140class ResponseConverterTestCase(unittest.TestCase):141 """ test case for response """142 def test_basic(self):143 operation, _ = _APP.resolve_obj(144 '#/paths/~1p1/get', from_spec_version='2.0')145 obj = converters.to_response(operation.responses['200'],146 operation.produces, '')147 self.assertEqual(obj['description'], 'successful operation')148 self.assertTrue('content' in obj)149 _content = obj['content']150 self.assertTrue('application/json' in _content)151 self.assertTrue(_content['application/json']['schema']['items']['$ref'],152 '#/components/schemas/pet')153 self.assertTrue(_content['application/json']['schema']['type'], 'array')154 def test_with_header(self):155 operation, _ = _APP.resolve_obj(156 '#/paths/~1p2/get', from_spec_version='2.0')157 obj = converters.to_response(operation.responses['200'], [], '')158 self.assertEqual(obj['description'], 'test for header')159 self.assertTrue('headers' in obj and 'X-TEST' in obj['headers'])160 _header = obj['headers']['X-TEST']161 self.assertEqual(_header['style'], 'simple')162 self.assertEqual(_header['schema']['items']['type'], 'string')163 self.assertEqual(_header['schema']['type'], 'array')164 def test_with_ref(self):165 operation, _ = _APP.resolve_obj(166 '#/paths/~1p4/post', from_spec_version='2.0')167 # without 'schema', just keep $ref168 obj = converters.to_response(operation.responses['default'],169 operation.produces,170 'test_response_default')171 self.assertEqual(obj['$ref'], '#/responses/void')172 # with 'schema', should inline it173 obj = converters.to_response(operation.responses['401'],174 operation.produces, 'test_response_401')175 self.assertEqual(obj['description'], 'unauthorized')176 self.assertTrue('application/json' in obj['content'])177 media = obj['content']['application/json']178 self.assertEqual(media['schema']['$ref'],179 '#/definitions/generic_response')180 self.assertTrue('application/xml' in obj['content'])181 media = obj['content']['application/xml']182 self.assertEqual(media['schema']['$ref'],183 '#/definitions/generic_response')184 # with 'schema', and without content-types as 'produces'185 obj = converters.to_response(operation.responses['401'],186 operation.produces, 'test_response_401')187 self.assertTrue('application/json' in obj['content'])188 media = obj['content']['application/json']189 self.assertEqual(media['schema']['$ref'],190 '#/definitions/generic_response')191class OperationConverterTestCase(unittest.TestCase):192 """ test case for operation """193 def test_basic(self):194 operation, _ = _APP.resolve_obj(195 '#/paths/~1p1/get', from_spec_version='2.0')196 obj = converters.to_operation(operation, None, 'test_root', '')197 self.assertTrue('responses' in obj and '200' in obj['responses'])198 _response = obj['responses']['200']199 self.assertEqual(_response['description'], 'successful operation')200 self.assertTrue(201 'content' in _response202 and 'application/json' in _response['content']203 and 'schema' in _response['content']['application/json'])204 _schema = _response['content']['application/json']['schema']205 self.assertEqual(_schema['items']['$ref'], '#/definitions/pet')206 self.assertEqual(_schema['type'], 'array')207 self.assertTrue('parameters' in obj and len(obj['parameters']) > 0)208 _parameter = obj['parameters'][0]209 self.assertEqual(_parameter['style'], 'form')210 self.assertEqual(_parameter['explode'], True)211 self.assertEqual(_parameter['in'], 'query')212 self.assertEqual(_parameter['name'], 'status')213 _schema = _parameter['schema']214 self.assertEqual(_schema['default'], 'available')215 self.assertEqual(_schema['type'], 'array')216 self.assertEqual(217 sorted(_schema['items']['enum']),218 sorted(['available', 'pending', 'sold']))219 self.assertEqual(_schema['items']['type'], 'string')220 def test_multiple_file(self):221 operation, _ = _APP.resolve_obj(222 '#/paths/~1p1/post', from_spec_version='2.0')223 obj = converters.to_operation(operation, None, 'test_root', '')224 # requestBody225 self.assertEqual(obj['requestBody']['required'], True)226 _media_type = obj['requestBody']['content']['multipart/form-data']227 _encoding = _media_type['encoding']228 self.assertEqual(_encoding['picture'],229 {'contentType': 'application/octet-stream'})230 self.assertEqual(_encoding['description'],231 {'contentType': 'text/plain'})232 self.assertEqual(_encoding['thumbnail'],233 {'contentType': 'application/octet-stream'})234 _properties = _media_type['schema']['properties']235 self.assertEqual(_properties['picture'], {236 'type': 'string',237 'format': 'binary'238 })239 self.assertEqual(_properties['description'], {'type': 'string'})240 self.assertEqual(_properties['thumbnail'], {241 'type': 'string',242 'format': 'binary'243 })244 # response245 self.assertEqual(obj['responses']['200']['description'],246 'successful operation')247 def test_parameter_ref(self):248 """ test parameters declared with '$ref'249 """250 operation, _ = _APP.resolve_obj(251 '#/paths/~1p2/post', from_spec_version='2.0')252 obj = converters.to_operation(operation, None, 'test_root', '')253 _content = obj['requestBody']['content']254 self.assertTrue('application/x-www-form-urlencoded' in _content)255 _properties = _content['application/x-www-form-urlencoded']['schema'][256 'properties']257 self.assertTrue('form_file' in _properties)258 self.assertEqual(_properties['form_file']['$ref'],259 '#/parameters/form_file')260 self.assertTrue('description' in _properties)261 self.assertEqual(_properties['description']['$ref'],262 '#/parameters/form_string')263 _encoding = _content['application/x-www-form-urlencoded']['encoding']264 self.assertTrue('form_file' in _encoding)265 self.assertEqual(_encoding['form_file']['contentType'],266 'application/octet-stream')267 self.assertTrue('description' in _encoding)268 self.assertEqual(_encoding['description']['contentType'], 'text/plain')269 _parameter = obj['parameters'][0]270 self.assertEqual(_parameter['$ref'], '#/parameters/query_string')271class InfoConverterTestCase(unittest.TestCase):272 """ test case for info """273 def test_basic(self):274 info, _ = _APP.resolve_obj('#/info', from_spec_version='2.0')275 obj = converters.to_info(info, '')276 self.assertEqual(obj['title'], 'Swagger Petstore')277 self.assertEqual(obj['version'], '1.0.0')278 self.assertEqual(obj['termsOfService'], 'http://helloreverb.com/terms/')279 self.assertEqual(obj['description'],280 'This is a sample server Petstore server.')281 _license = obj['license']282 self.assertEqual(_license['url'],283 'http://www.apache.org/licenses/LICENSE-2.0.html')284 self.assertEqual(_license['name'], 'Apache 2.0')285 _contact = obj['contact']286 self.assertEqual(_contact['email'], 'apiteam@wordnik.com')287class PathItemConverterTestCase(unittest.TestCase):288 """ test case for path item """289 def test_basic(self):290 path_item, _ = _APP.resolve_obj('#/paths/~1p1', from_spec_version='2.0')291 obj, reloc = converters.to_path_item(path_item, 'test_root', '')292 self.assertTrue('get' in obj)293 self.assertTrue('post' in obj)294 self.assertFalse('options' in obj)295 self.assertEqual(reloc, {})296 def test_path_item_parameters(self):297 """ make sure PathItem.parameters are correctly handled:298 - request-body: inline all 'body' or 'file' parameter299 to each operation300 - other parameter: let them stay in PathItem.parameters301 """302 path_item, _ = _APP.resolve_obj(303 '#/paths/~1p3~1{user_name}', from_spec_version='2.0')304 obj, reloc = converters.to_path_item(path_item, 'test_root', '')305 self.assertTrue('post' in obj)306 _post = obj['post']307 self.assertFalse('parameters' in _post)308 self.assertTrue('requestBody' in _post)309 media = _post['requestBody']['content']['multipart/form-data']310 self.assertTrue('encoding' in media)311 self.assertEqual(media['encoding']['form_file']['contentType'],312 'application/octet-stream')313 self.assertTrue('schema' in media)314 self.assertEqual(media['schema']['properties']['form_file']['$ref'],315 '#/parameters/form_file')316 media = _post['requestBody']['content'][317 'application/x-www-form-urlencoded']318 self.assertTrue('encoding' in media)319 self.assertEqual(media['encoding']['description']['contentType'],320 'text/plain')321 self.assertTrue('schema' in media)322 self.assertEqual(media['schema']['required'], ['description'])323 self.assertEqual(media['schema']['properties']['description']['$ref'],324 '#/parameters/form_string')325 self.assertTrue('parameters' in obj)326 _parameters = obj['parameters']327 for param in _parameters:328 if '$ref' in param:329 self.assertEqual(param['$ref'], '#/parameters/query_string')330 elif 'name' in param:331 self.assertEqual(param['name'], 'user_name')332 else:333 self.fail('either "name" or "$ref" should be in param')334 # check object relocation335 self.assertEqual(reloc['parameters/0'],336 'x-pyopenapi_internal_request_body')337 self.assertEqual(reloc['parameters/1'],338 'x-pyopenapi_internal_request_body')339class ServerTestCase(unittest.TestCase):340 """ test case for server """341 def test_from_swagger(self):342 obj = converters.from_swagger_to_server(_APP.root, '')343 self.assertTrue('url' in obj)344 self.assertEqual(obj['url'], '/')345class OpenAPITestCase(unittest.TestCase):346 """ test case for OpenAPI """347 @classmethod348 def setUpClass(cls):349 cls.from_upgrade, cls.upgrade_reloc = converters.to_openapi(350 _APP.root, '')351 def test_basic(self):352 obj = self.from_upgrade353 self.assertTrue('info' in obj)354 self.assertTrue('servers' in obj)355 self.assertTrue('paths' in obj)356 _paths = obj['paths']357 self.assertTrue('/p1' in _paths)358 self.assertTrue('/p2' in _paths)359 self.assertTrue('components' in obj)360 _components = obj['components']361 self.assertTrue('securitySchemes' in _components)362 self.assertTrue('schemas' in _components)363 self.assertTrue('externalDocs' in obj)364 def test_reloc(self):365 """ make sure the object relocation map is correct366 """367 reloc = self.upgrade_reloc368 self.assertEqual(reloc['paths']['~1p3~1{user_name}']['parameters/0'],369 'x-pyopenapi_internal_request_body')370 self.assertEqual(reloc['paths']['~1p3~1{user_name}']['parameters/1'],371 'x-pyopenapi_internal_request_body')372 self.assertEqual(reloc['securityDefinitions'],373 'components/securitySchemes')374 self.assertEqual(reloc['responses'], 'components/responses')375 self.assertEqual(reloc['definitions'], 'components/schemas')376 self.assertEqual(reloc['parameters'][''], '#/components/parameters')377 self.assertEqual(reloc['parameters']['body_ref_pet'],378 '#/components/requestBodies/body_ref_pet')379 self.assertEqual(reloc['parameters']['form_string'],380 '#/components/requestBodies/form_string')381 self.assertEqual(reloc['parameters']['body_file_ref'],382 '#/components/requestBodies/body_file_ref')383 self.assertEqual(reloc['parameters']['body_obj_simple'],384 '#/components/requestBodies/body_obj_simple')385 self.assertEqual(reloc['parameters']['body_file'],386 '#/components/requestBodies/body_file')387 self.assertEqual(reloc['parameters']['form_file'],388 '#/components/requestBodies/form_file')389 def test_request_bodies(self):390 """ make sure we create requestBodies with391 reasonable content types392 """393 _request_bodies = self.from_upgrade['components']['requestBodies']394 _form_file = _request_bodies['form_file']395 self.assertTrue('multipart/form-data' in _form_file['content'])396 _body_file = _request_bodies['body_file']397 self.assertTrue('multipart/form-data' in _body_file['content'])398 _body_file_ref = _request_bodies['body_file_ref']399 self.assertTrue('multipart/form-data' in _body_file_ref['content'])400 _form_string = _request_bodies['form_string']401 self.assertTrue(402 'application/x-www-form-urlencoded' in _form_string['content'])403 _body_obj_simple = _request_bodies['body_obj_simple']404 self.assertTrue('application/json' in _body_obj_simple['content'])405 _schema_properties = _body_obj_simple['content']['application/json'][406 'schema']['properties']407 self.assertTrue('phone' in _schema_properties)408 self.assertEqual(_schema_properties['phone']['type'], 'string')409 self.assertTrue('email' in _schema_properties)410 self.assertEqual(_schema_properties['email']['type'], 'string')411 _body_ref_pet = _request_bodies['body_ref_pet']412 self.assertTrue('application/json' in _body_ref_pet['content'])413 _schema = _body_ref_pet['content']['application/json']['schema']...

Full Screen

Full Screen

test_coffeeconnection.py

Source:test_coffeeconnection.py Github

copy

Full Screen

...251 with pytest.raises(Exception) as error:252 coffeeconnection.check_response(resp)253 assert error.value.args[0] == "Bad request: error"254@responses.activate255def test_response_401():256 responses.add(responses.POST, "http://url", status=401, body="error")257 resp = requests.post("http://url")258 with pytest.raises(Exception) as error:259 coffeeconnection.check_response(resp)260 assert error.value.args[0] == "Unauthorized: error"261@responses.activate262def test_response_bad_json():263 responses.add(264 responses.POST,265 "http://url",266 status=200,267 content_type="application/json",268 body='{"ok": True}', # Title case boolean269 )...

Full Screen

Full Screen

test_authorization.py

Source:test_authorization.py Github

copy

Full Screen

...53 result = am._response_400('TEST')54 self.assertIsInstance(result, HttpResponseBadRequest)55 self.assertEqual(result._headers['www-authenticate'],56 ('WWW-Authenticate', 'Bearer realm="TEST"'))57 def test_response_401(self):58 am = AuthorizationMiddleware(Mock())59 result = am._response_401('TEST')60 self.assertIsInstance(result, HttpResponseUnauthorized)61 self.assertEqual(result._headers['www-authenticate'],62 ('WWW-Authenticate', 'Bearer realm="TEST"'))63 @patch('app.middleware.authorization.settings')64 def test_process_view_with_valid_authorization(self, m_settings):65 m_settings.RUN_MODE_PRODUCTION = settings.RUN_MODE_PRODUCTION66 m_settings.RUN_MODE = settings.RUN_MODE_PRODUCTION67 view_func = Mock(__name__='api_jobs_fetchrss')68 request = HttpRequest()69 request.META = {70 'HTTP_AUTHORIZATION': 'Bearer API_TOKEN',71 }...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Django Test Plus automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful