Best Python code snippet using autotest_python
test_serializer_lists.py
Source:test_serializer_lists.py
1import sys2import pytest3from django.http import QueryDict4from django.utils.datastructures import MultiValueDict5from rest_framework import serializers6from rest_framework.exceptions import ErrorDetail7class BasicObject:8 """9 A mock object for testing serializer save behavior.10 """11 def __init__(self, **kwargs):12 self._data = kwargs13 for key, value in kwargs.items():14 setattr(self, key, value)15 def __eq__(self, other):16 if self._data.keys() != other._data.keys():17 return False18 for key in self._data:19 if self._data[key] != other._data[key]:20 return False21 return True22class TestListSerializer:23 """24 Tests for using a ListSerializer as a top-level serializer.25 Note that this is in contrast to using ListSerializer as a field.26 """27 def setup(self):28 class IntegerListSerializer(serializers.ListSerializer):29 child = serializers.IntegerField()30 self.Serializer = IntegerListSerializer31 def test_validate(self):32 """33 Validating a list of items should return a list of validated items.34 """35 input_data = ["123", "456"]36 expected_output = [123, 456]37 serializer = self.Serializer(data=input_data)38 assert serializer.is_valid()39 assert serializer.validated_data == expected_output40 def test_validate_html_input(self):41 """42 HTML input should be able to mock list structures using [x] style ids.43 """44 input_data = MultiValueDict({"[0]": ["123"], "[1]": ["456"]})45 expected_output = [123, 456]46 serializer = self.Serializer(data=input_data)47 assert serializer.is_valid()48 assert serializer.validated_data == expected_output49 @pytest.mark.skipif(50 sys.version_info < (3, 7),51 reason="subscriptable classes requires Python 3.7 or higher",52 )53 def test_list_serializer_is_subscriptable(self):54 assert serializers.ListSerializer is serializers.ListSerializer["foo"]55class TestListSerializerContainingNestedSerializer:56 """57 Tests for using a ListSerializer containing another serializer.58 """59 def setup(self):60 class TestSerializer(serializers.Serializer):61 integer = serializers.IntegerField()62 boolean = serializers.BooleanField()63 def create(self, validated_data):64 return BasicObject(**validated_data)65 class ObjectListSerializer(serializers.ListSerializer):66 child = TestSerializer()67 self.Serializer = ObjectListSerializer68 def test_validate(self):69 """70 Validating a list of dictionaries should return a list of71 validated dictionaries.72 """73 input_data = [74 {"integer": "123", "boolean": "true"},75 {"integer": "456", "boolean": "false"}76 ]77 expected_output = [78 {"integer": 123, "boolean": True},79 {"integer": 456, "boolean": False}80 ]81 serializer = self.Serializer(data=input_data)82 assert serializer.is_valid()83 assert serializer.validated_data == expected_output84 def test_create(self):85 """86 Creating from a list of dictionaries should return a list of objects.87 """88 input_data = [89 {"integer": "123", "boolean": "true"},90 {"integer": "456", "boolean": "false"}91 ]92 expected_output = [93 BasicObject(integer=123, boolean=True),94 BasicObject(integer=456, boolean=False),95 ]96 serializer = self.Serializer(data=input_data)97 assert serializer.is_valid()98 assert serializer.save() == expected_output99 def test_serialize(self):100 """101 Serialization of a list of objects should return a list of dictionaries.102 """103 input_objects = [104 BasicObject(integer=123, boolean=True),105 BasicObject(integer=456, boolean=False)106 ]107 expected_output = [108 {"integer": 123, "boolean": True},109 {"integer": 456, "boolean": False}110 ]111 serializer = self.Serializer(input_objects)112 assert serializer.data == expected_output113 def test_validate_html_input(self):114 """115 HTML input should be able to mock list structures using [x]116 style prefixes.117 """118 input_data = MultiValueDict({119 "[0]integer": ["123"],120 "[0]boolean": ["true"],121 "[1]integer": ["456"],122 "[1]boolean": ["false"]123 })124 expected_output = [125 {"integer": 123, "boolean": True},126 {"integer": 456, "boolean": False}127 ]128 serializer = self.Serializer(data=input_data)129 assert serializer.is_valid()130 assert serializer.validated_data == expected_output131class TestNestedListSerializer:132 """133 Tests for using a ListSerializer as a field.134 """135 def setup(self):136 class TestSerializer(serializers.Serializer):137 integers = serializers.ListSerializer(child=serializers.IntegerField())138 booleans = serializers.ListSerializer(child=serializers.BooleanField())139 def create(self, validated_data):140 return BasicObject(**validated_data)141 self.Serializer = TestSerializer142 def test_validate(self):143 """144 Validating a list of items should return a list of validated items.145 """146 input_data = {147 "integers": ["123", "456"],148 "booleans": ["true", "false"]149 }150 expected_output = {151 "integers": [123, 456],152 "booleans": [True, False]153 }154 serializer = self.Serializer(data=input_data)155 assert serializer.is_valid()156 assert serializer.validated_data == expected_output157 def test_create(self):158 """159 Creation with a list of items return an object with an attribute that160 is a list of items.161 """162 input_data = {163 "integers": ["123", "456"],164 "booleans": ["true", "false"]165 }166 expected_output = BasicObject(167 integers=[123, 456],168 booleans=[True, False]169 )170 serializer = self.Serializer(data=input_data)171 assert serializer.is_valid()172 assert serializer.save() == expected_output173 def test_serialize(self):174 """175 Serialization of a list of items should return a list of items.176 """177 input_object = BasicObject(178 integers=[123, 456],179 booleans=[True, False]180 )181 expected_output = {182 "integers": [123, 456],183 "booleans": [True, False]184 }185 serializer = self.Serializer(input_object)186 assert serializer.data == expected_output187 def test_validate_html_input(self):188 """189 HTML input should be able to mock list structures using [x]190 style prefixes.191 """192 input_data = MultiValueDict({193 "integers[0]": ["123"],194 "integers[1]": ["456"],195 "booleans[0]": ["true"],196 "booleans[1]": ["false"]197 })198 expected_output = {199 "integers": [123, 456],200 "booleans": [True, False]201 }202 serializer = self.Serializer(data=input_data)203 assert serializer.is_valid()204 assert serializer.validated_data == expected_output205class TestNestedListSerializerAllowEmpty:206 """Tests the behaviour of allow_empty=False when a ListSerializer is used as a field."""207 @pytest.mark.parametrize('partial', (False, True))208 def test_allow_empty_true(self, partial):209 """210 If allow_empty is True, empty lists should be allowed regardless of the value211 of partial on the parent serializer.212 """213 class ChildSerializer(serializers.Serializer):214 id = serializers.IntegerField()215 class ParentSerializer(serializers.Serializer):216 ids = ChildSerializer(many=True, allow_empty=True)217 serializer = ParentSerializer(data={'ids': []}, partial=partial)218 assert serializer.is_valid()219 assert serializer.validated_data == {220 'ids': [],221 }222 @pytest.mark.parametrize('partial', (False, True))223 def test_allow_empty_false(self, partial):224 """225 If allow_empty is False, empty lists should fail validation regardless of the value226 of partial on the parent serializer.227 """228 class ChildSerializer(serializers.Serializer):229 id = serializers.IntegerField()230 class ParentSerializer(serializers.Serializer):231 ids = ChildSerializer(many=True, allow_empty=False)232 serializer = ParentSerializer(data={'ids': []}, partial=partial)233 assert not serializer.is_valid()234 assert serializer.errors == {235 'ids': {236 'non_field_errors': [237 ErrorDetail(string='This list may not be empty.', code='empty')],238 }239 }240class TestNestedListOfListsSerializer:241 def setup(self):242 class TestSerializer(serializers.Serializer):243 integers = serializers.ListSerializer(244 child=serializers.ListSerializer(245 child=serializers.IntegerField()246 )247 )248 booleans = serializers.ListSerializer(249 child=serializers.ListSerializer(250 child=serializers.BooleanField()251 )252 )253 self.Serializer = TestSerializer254 def test_validate(self):255 input_data = {256 'integers': [['123', '456'], ['789', '0']],257 'booleans': [['true', 'true'], ['false', 'true']]258 }259 expected_output = {260 "integers": [[123, 456], [789, 0]],261 "booleans": [[True, True], [False, True]]262 }263 serializer = self.Serializer(data=input_data)264 assert serializer.is_valid()265 assert serializer.validated_data == expected_output266 def test_validate_html_input(self):267 """268 HTML input should be able to mock lists of lists using [x][y]269 style prefixes.270 """271 input_data = MultiValueDict({272 "integers[0][0]": ["123"],273 "integers[0][1]": ["456"],274 "integers[1][0]": ["789"],275 "integers[1][1]": ["000"],276 "booleans[0][0]": ["true"],277 "booleans[0][1]": ["true"],278 "booleans[1][0]": ["false"],279 "booleans[1][1]": ["true"]280 })281 expected_output = {282 "integers": [[123, 456], [789, 0]],283 "booleans": [[True, True], [False, True]]284 }285 serializer = self.Serializer(data=input_data)286 assert serializer.is_valid()287 assert serializer.validated_data == expected_output288class TestListSerializerClass:289 """Tests for a custom list_serializer_class."""290 def test_list_serializer_class_validate(self):291 class CustomListSerializer(serializers.ListSerializer):292 def validate(self, attrs):293 raise serializers.ValidationError('Non field error')294 class TestSerializer(serializers.Serializer):295 class Meta:296 list_serializer_class = CustomListSerializer297 serializer = TestSerializer(data=[], many=True)298 assert not serializer.is_valid()299 assert serializer.errors == {'non_field_errors': ['Non field error']}300class TestSerializerPartialUsage:301 """302 When not submitting key for list fields or multiple choice, partial303 serialization should result in an empty state (key not there), not304 an empty list.305 Regression test for Github issue #2761.306 """307 def test_partial_listfield(self):308 class ListSerializer(serializers.Serializer):309 listdata = serializers.ListField()310 serializer = ListSerializer(data=MultiValueDict(), partial=True)311 result = serializer.to_internal_value(data={})312 assert "listdata" not in result313 assert serializer.is_valid()314 assert serializer.validated_data == {}315 assert serializer.errors == {}316 def test_partial_multiplechoice(self):317 class MultipleChoiceSerializer(serializers.Serializer):318 multiplechoice = serializers.MultipleChoiceField(choices=[1, 2, 3])319 serializer = MultipleChoiceSerializer(data=MultiValueDict(), partial=True)320 result = serializer.to_internal_value(data={})321 assert "multiplechoice" not in result322 assert serializer.is_valid()323 assert serializer.validated_data == {}324 assert serializer.errors == {}325 def test_allow_empty_true(self):326 class ListSerializer(serializers.Serializer):327 update_field = serializers.IntegerField()328 store_field = serializers.IntegerField()329 instance = [330 {'update_field': 11, 'store_field': 12},331 {'update_field': 21, 'store_field': 22},332 ]333 serializer = ListSerializer(instance, data=[], partial=True, many=True)334 assert serializer.is_valid()335 assert serializer.validated_data == []336 assert serializer.errors == []337 def test_update_allow_empty_true(self):338 class ListSerializer(serializers.Serializer):339 update_field = serializers.IntegerField()340 store_field = serializers.IntegerField()341 instance = [342 {'update_field': 11, 'store_field': 12},343 {'update_field': 21, 'store_field': 22},344 ]345 input_data = [{'update_field': 31}, {'update_field': 41}]346 updated_data_list = [347 {'update_field': 31, 'store_field': 12},348 {'update_field': 41, 'store_field': 22},349 ]350 serializer = ListSerializer(351 instance, data=input_data, partial=True, many=True)352 assert serializer.is_valid()353 for index, data in enumerate(serializer.validated_data):354 for key, value in data.items():355 assert value == updated_data_list[index][key]356 assert serializer.errors == []357 def test_allow_empty_false(self):358 class ListSerializer(serializers.Serializer):359 update_field = serializers.IntegerField()360 store_field = serializers.IntegerField()361 instance = [362 {'update_field': 11, 'store_field': 12},363 {'update_field': 21, 'store_field': 22},364 ]365 serializer = ListSerializer(366 instance, data=[], allow_empty=False, partial=True, many=True)367 assert not serializer.is_valid()368 assert serializer.validated_data == []369 assert len(serializer.errors) == 1370 assert serializer.errors['non_field_errors'][0] == 'This list may not be empty.'371 def test_update_allow_empty_false(self):372 class ListSerializer(serializers.Serializer):373 update_field = serializers.IntegerField()374 store_field = serializers.IntegerField()375 instance = [376 {'update_field': 11, 'store_field': 12},377 {'update_field': 21, 'store_field': 22},378 ]379 input_data = [{'update_field': 31}, {'update_field': 41}]380 updated_data_list = [381 {'update_field': 31, 'store_field': 12},382 {'update_field': 41, 'store_field': 22},383 ]384 serializer = ListSerializer(385 instance, data=input_data, allow_empty=False, partial=True, many=True)386 assert serializer.is_valid()387 for index, data in enumerate(serializer.validated_data):388 for key, value in data.items():389 assert value == updated_data_list[index][key]390 assert serializer.errors == []391 def test_as_field_allow_empty_true(self):392 class ListSerializer(serializers.Serializer):393 update_field = serializers.IntegerField()394 store_field = serializers.IntegerField()395 class Serializer(serializers.Serializer):396 extra_field = serializers.IntegerField()397 list_field = ListSerializer(many=True)398 instance = {399 'extra_field': 1,400 'list_field': [401 {'update_field': 11, 'store_field': 12},402 {'update_field': 21, 'store_field': 22},403 ]404 }405 serializer = Serializer(instance, data={}, partial=True)406 assert serializer.is_valid()407 assert serializer.validated_data == {}408 assert serializer.errors == {}409 def test_udate_as_field_allow_empty_true(self):410 class ListSerializer(serializers.Serializer):411 update_field = serializers.IntegerField()412 store_field = serializers.IntegerField()413 class Serializer(serializers.Serializer):414 extra_field = serializers.IntegerField()415 list_field = ListSerializer(many=True)416 instance = {417 'extra_field': 1,418 'list_field': [419 {'update_field': 11, 'store_field': 12},420 {'update_field': 21, 'store_field': 22},421 ]422 }423 input_data_1 = {'extra_field': 2}424 input_data_2 = {425 'list_field': [426 {'update_field': 31},427 {'update_field': 41},428 ]429 }430 # data_1431 serializer = Serializer(instance, data=input_data_1, partial=True)432 assert serializer.is_valid()433 assert len(serializer.validated_data) == 1434 assert serializer.validated_data['extra_field'] == 2435 assert serializer.errors == {}436 # data_2437 serializer = Serializer(instance, data=input_data_2, partial=True)438 assert serializer.is_valid()439 updated_data_list = [440 {'update_field': 31, 'store_field': 12},441 {'update_field': 41, 'store_field': 22},442 ]443 for index, data in enumerate(serializer.validated_data['list_field']):444 for key, value in data.items():445 assert value == updated_data_list[index][key]446 assert serializer.errors == {}447 def test_as_field_allow_empty_false(self):448 class ListSerializer(serializers.Serializer):449 update_field = serializers.IntegerField()450 store_field = serializers.IntegerField()451 class Serializer(serializers.Serializer):452 extra_field = serializers.IntegerField()453 list_field = ListSerializer(many=True, allow_empty=False)454 instance = {455 'extra_field': 1,456 'list_field': [457 {'update_field': 11, 'store_field': 12},458 {'update_field': 21, 'store_field': 22},459 ]460 }461 serializer = Serializer(instance, data={}, partial=True)462 assert serializer.is_valid()463 assert serializer.validated_data == {}464 assert serializer.errors == {}465 def test_update_as_field_allow_empty_false(self):466 class ListSerializer(serializers.Serializer):467 update_field = serializers.IntegerField()468 store_field = serializers.IntegerField()469 class Serializer(serializers.Serializer):470 extra_field = serializers.IntegerField()471 list_field = ListSerializer(many=True, allow_empty=False)472 instance = {473 'extra_field': 1,474 'list_field': [475 {'update_field': 11, 'store_field': 12},476 {'update_field': 21, 'store_field': 22},477 ]478 }479 input_data_1 = {'extra_field': 2}480 input_data_2 = {481 'list_field': [482 {'update_field': 31},483 {'update_field': 41},484 ]485 }486 updated_data_list = [487 {'update_field': 31, 'store_field': 12},488 {'update_field': 41, 'store_field': 22},489 ]490 # data_1491 serializer = Serializer(instance, data=input_data_1, partial=True)492 assert serializer.is_valid()493 assert serializer.errors == {}494 # data_2495 serializer = Serializer(instance, data=input_data_2, partial=True)496 assert serializer.is_valid()497 for index, data in enumerate(serializer.validated_data['list_field']):498 for key, value in data.items():499 assert value == updated_data_list[index][key]500 assert serializer.errors == {}501class TestEmptyListSerializer:502 """503 Tests the behaviour of ListSerializers when there is no data passed to it504 """505 def setup(self):506 class ExampleListSerializer(serializers.ListSerializer):507 child = serializers.IntegerField()508 self.Serializer = ExampleListSerializer509 def test_nested_serializer_with_list_json(self):510 # pass an empty array to the serializer511 input_data = []512 serializer = self.Serializer(data=input_data)513 assert serializer.is_valid()514 assert serializer.validated_data == []515 def test_nested_serializer_with_list_multipart(self):516 # pass an "empty" QueryDict to the serializer (should be the same as an empty array)517 input_data = QueryDict('')518 serializer = self.Serializer(data=input_data)519 assert serializer.is_valid()...
upgrade.py
Source:upgrade.py
...17import six18def update_type_and_ref(dst, src, scope, sep, app):19 ref = getattr(src, '$ref')20 if ref:21 dst.update_field('$ref', '#/definitions/' + scope_compose(scope, ref, sep=sep))22 if app.prim_factory.is_primitive(getattr(src, 'type', None)):23 dst.update_field('type', src.type.lower())24 elif src.type:25 dst.update_field('$ref', '#/definitions/' + scope_compose(scope, src.type, sep=sep))26def convert_min_max(dst, src):27 def _from_str(name):28 v = getattr(src, name, None)29 if v:30 if src.type == 'integer':31 # we need to handle 1.0 when converting to int32 # that's why we need to convert to float first33 dst.update_field(name, int(float(v)))34 elif src.type == 'number':35 dst.update_field(name, float(v))36 else:37 raise SchemaError('minimum/maximum is only allowed on integer/number, not {0}'.format(src.type))38 else:39 dst.update_field(name, None)40 _from_str('minimum')41 _from_str('maximum')42def convert_schema_from_datatype(obj, scope, sep, app):43 if obj == None:44 return None45 s = objects.Schema(NullContext())46 update_type_and_ref(s, obj, scope, sep, app)47 s.update_field('format', obj.format)48 if obj.is_set('defaultValue'):49 s.update_field('default', obj.defaultValue)50 convert_min_max(s, obj)51 s.update_field('uniqueItems', obj.uniqueItems)52 s.update_field('enum', obj.enum)53 if obj.items:54 i = objects.Schema(NullContext())55 update_type_and_ref(i, obj.items, scope, sep, app)56 i.update_field('format', obj.items.format)57 s.update_field('items', i)58 return s59def convert_items(o, app):60 item = objects.Items(NullContext())61 if getattr(o, '$ref'):62 raise SchemaError('Can\'t have $ref for Items')63 if not app.prim_factory.is_primitive(getattr(o, 'type', None)):64 raise SchemaError('Non primitive type is not allowed for Items')65 item.update_field('type', o.type.lower())66 item.update_field('format', o.format)67 return item68class Upgrade(object):69 """ convert 1.2 object to 2.0 object70 """71 class Disp(Dispatcher): pass72 def __init__(self, sep=private.SCOPE_SEPARATOR):73 self.__swagger = None74 self.__sep = sep75 @Disp.register([ResourceList])76 def _resource_list(self, path, obj, app):77 o = objects.Swagger(NullContext())78 # Info Object79 info = objects.Info(NullContext())80 info.update_field('version', obj.apiVersion)81 info.update_field('title', get_or_none(obj, 'info','title'))82 info.update_field('description', get_or_none(obj, 'info', 'description'))83 info.update_field('termsOfService', get_or_none(obj, 'info', 'termsOfServiceUrl'))84 # Contact Object85 if obj.info.contact:86 contact = objects.Contact(NullContext())87 contact.update_field('email', get_or_none(obj, 'info', 'contact'))88 info.update_field('contact', contact)89 # License Object90 if obj.info.license or obj.info.licenseUrl:91 license = objects.License(NullContext())92 license.update_field('name', get_or_none(obj, 'info', 'license'))93 license.update_field('url', get_or_none(obj, 'info', 'licenseUrl'))94 info.update_field('license', license)95 o.update_field('info', info)96 o.update_field('swagger', '2.0')97 o.update_field('schemes', ['http', 'https'])98 o.update_field('host', '')99 o.update_field('basePath', '')100 o.update_field('tags', [])101 o.update_field('definitions', {})102 o.update_field('parameters', {})103 o.update_field('responses', {})104 o.update_field('paths', {})105 o.update_field('security', [])106 o.update_field('securityDefinitions', {})107 o.update_field('consumes', [])108 o.update_field('produces', [])109 self.__swagger = o110 @Disp.register([Resource])111 def _resource(self, path, obj, app):112 name = obj.get_name(path)113 for t in self.__swagger.tags:114 if t.name == name:115 break116 else:117 tt = objects.Tag(NullContext())118 tt.update_field('name', name)119 self.__swagger.tags.append(tt)120 @Disp.register([Operation])121 def _operation(self, path, obj, app):122 o = objects.Operation(NullContext())123 scope = obj._parent_.get_name(path)124 o.update_field('tags', [scope])125 o.update_field('operationId', obj.nickname)126 o.update_field('summary', obj.summary)127 o.update_field('description', obj.notes)128 o.update_field('deprecated', obj.deprecated == 'true')129 c = obj.consumes if obj.consumes and len(obj.consumes) > 0 else obj._parent_.consumes130 o.update_field('consumes', c if c else [])131 p = obj.produces if obj.produces and len(obj.produces) > 0 else obj._parent_.produces132 o.update_field('produces', p if p else [])133 o.update_field('parameters', [])134 o.update_field('security', [])135 # if there is not authorizations in this operation,136 # looking for it in resource object.137 _auth = obj.authorizations if obj.authorizations and len(obj.authorizations) > 0 else obj._parent_.authorizations138 if _auth:139 for name, scopes in six.iteritems(_auth):140 o.security.append({name: [v.scope for v in scopes]})141 # Operation return value142 o.update_field('responses', {})143 resp = objects.Response(NullContext())144 if obj.type != 'void':145 resp.update_field('schema', convert_schema_from_datatype(obj, scope, self.__sep, app))146 o.responses['default'] = resp147 path = obj._parent_.basePath + obj.path148 if path not in self.__swagger.paths:149 self.__swagger.paths[path] = objects.PathItem(NullContext())150 method = obj.method.lower()151 self.__swagger.paths[path].update_field(method, o)152 @Disp.register([Authorization])153 def _authorization(self, path, obj, app):154 o = objects.SecurityScheme(NullContext())155 if obj.type == 'basicAuth':156 o.update_field('type', 'basic')157 else:158 o.update_field('type', obj.type)159 o.update_field('scopes', {})160 for s in obj.scopes or []:161 o.scopes[s.scope] = s.description162 if o.type == 'oauth2':163 o.update_field('authorizationUrl', get_or_none(obj, 'grantTypes', 'implicit', 'loginEndpoint', 'url'))164 o.update_field('tokenUrl', get_or_none(obj, 'grantTypes', 'authorization_code', 'tokenEndpoint', 'url'))165 if o.authorizationUrl:166 o.update_field('flow', 'implicit')167 elif o.tokenUrl:168 o.update_field('flow', 'access_code')169 elif o.type == 'apiKey':170 o.update_field('name', obj.keyname)171 o.update_field('in', obj.passAs)172 self.__swagger.securityDefinitions[obj.get_name(path)] = o173 @Disp.register([Parameter])174 def _parameter(self, path, obj, app):175 o = objects.Parameter(NullContext())176 scope = obj._parent_._parent_.get_name(path)177 o.update_field('name', obj.name)178 o.update_field('required', obj.required)179 o.update_field('description', obj.description)180 if obj.paramType == 'form':181 o.update_field('in', 'formData')182 else:183 o.update_field('in', obj.paramType)184 if 'body' == getattr(o, 'in'):185 o.update_field('schema', convert_schema_from_datatype(obj, scope, self.__sep, app))186 else:187 if getattr(obj, '$ref'):188 raise SchemaError('Can\'t have $ref in non-body Parameters')189 if obj.allowMultiple == True and obj.items == None:190 o.update_field('type', 'array')191 o.update_field('collectionFormat', 'csv')192 o.update_field('uniqueItems', obj.uniqueItems)193 o.update_field('items', convert_items(obj, app))194 if obj.is_set("defaultValue"):195 o.update_field('default', [obj.defaultValue])196 o.items.update_field('enum', obj.enum)197 else:198 o.update_field('type', obj.type.lower())199 o.update_field('format', obj.format)200 if obj.is_set("defaultValue"):201 o.update_field('default', obj.defaultValue)202 convert_min_max(o, obj)203 o.update_field('enum', obj.enum)204 if obj.items:205 o.update_field('collectionFormat', 'csv')206 o.update_field('uniqueItems', obj.uniqueItems)207 o.update_field('items', convert_items(obj.items, app))208 path = obj._parent_._parent_.basePath + obj._parent_.path209 method = obj._parent_.method.lower()210 op = getattr(self.__swagger.paths[path], method)211 op.parameters.append(o)212 @Disp.register([Model])213 def _model(self, path, obj, app):214 scope = obj._parent_.get_name(path)215 s = scope_compose(scope, obj.get_name(path), sep=self.__sep)216 o = self.__swagger.definitions.get(s, None)217 if not o:218 o = objects.Schema(NullContext())219 self.__swagger.definitions[s] = o220 props = {}221 for name, prop in six.iteritems(obj.properties):222 props[name] = convert_schema_from_datatype(prop, scope, self.__sep, app)223 props[name].update_field('description', prop.description)224 o.update_field('properties', props)225 o.update_field('required', obj.required)226 o.update_field('discriminator', obj.discriminator)227 o.update_field('description', obj.description)228 for t in obj.subTypes or []:229 # here we assume those child models belongs to230 # the same resource.231 sub_s = scope_compose(scope, t, sep=self.__sep)232 sub_o = self.__swagger.definitions.get(sub_s, None)233 if not sub_o:234 sub_o = objects.Schema(NullContext())235 self.__swagger.definitions[sub_s] = sub_o236 new_ref = objects.Schema(NullContext())237 new_ref.update_field('$ref', '#/definitions/' + s)238 sub_o.allOf.append(new_ref)239 @property240 def swagger(self):241 """ some preparation before returning Swagger object242 """243 # prepare Swagger.host & Swagger.basePath244 if not self.__swagger:245 return None246 common_path = os.path.commonprefix(list(self.__swagger.paths))247 # remove tailing slash,248 # because all paths in Paths Object would prefixed with slah.249 common_path = common_path[:-1] if common_path[-1] == '/' else common_path250 if len(common_path) > 0:251 p = six.moves.urllib.parse.urlparse(common_path)252 self.__swagger.update_field('host', p.netloc)253 new_common_path = six.moves.urllib.parse.urlunparse((254 p.scheme, p.netloc, '', '', '', ''))255 new_path = {}256 for k in self.__swagger.paths.keys():257 new_path[k[len(new_common_path):]] = self.__swagger.paths[k]258 self.__swagger.update_field('paths', new_path)...
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!!