How to use from_raw method in lisa

Best Python code snippet using lisa_python

test_factories.py

Source:test_factories.py Github

copy

Full Screen

...44 ]45 }46 }47 }48 schema = Object.from_raw(Schema, spec)49 prop = PropertyFactory.generate(schema)50 cat_payload = {51 'pet': {52 'name': 'Misty'53 }54 }55 cat = prop.unmarshal(Cursor.from_raw(cat_payload))56 self.assertEqual(cat['pet']['name'], 'Misty')57 dog_payload = {58 'pet': {59 'nickname': 'Max'60 }61 }62 dog = prop.unmarshal(Cursor.from_raw(dog_payload))63 self.assertEqual(dog['pet']['nickname'], 'Max')64 # Implicit discriminator65 spec = {66 'schemas': {67 'Cat': {68 'type': 'object',69 'required': [70 'pet_type'71 ],72 'properties': {73 'pet_type': {74 'type': 'string'75 },76 'name': {77 'type': 'string'78 }79 }80 },81 'Dog': {82 'type': 'object',83 'additionalProperties': False,84 'required': [85 'pet_type'86 ],87 'properties': {88 'pet_type': {89 'type': 'string'90 },91 'nickname': {92 'type': 'string'93 }94 }95 },96 'Pet': {97 'type': 'object',98 'properties': {99 'pet': {100 'oneOf': [101 {102 '$ref': '#/schemas/Cat'103 },104 {105 '$ref': '#/schemas/Dog'106 }107 ],108 'discriminator': {109 'propertyName': 'pet_type'110 }111 }112 }113 }114 }115 }116 schema = Object.from_raw(Components, spec)117 prop = PropertyFactory.generate(schema['schemas']['Pet'])118 cat_payload = {119 'pet': {120 'pet_type': 'Cat',121 'name': 'Misty'122 }123 }124 cat = prop.unmarshal(Cursor.from_raw(cat_payload))125 self.assertEqual(cat['pet']['name'], 'Misty')126 self.assertEqual(cat['pet']['pet_type'], 'Cat')127 ambiguous_cat_payload = {128 'pet': {129 'pet_type': '',130 'name': 'Misty'131 }132 }133 try:134 prop.unmarshal(Cursor.from_raw(ambiguous_cat_payload))135 except SchemaError as e:136 self.assertTrue("No one of property types are not matched to discriminator value" in str(e))137 else:138 self.fail("MUST failed because pet type not specified")139 dog_with_cat_properties = {140 'pet': {141 'pet_type': 'Dog',142 'name': 'Misty'143 }144 }145 try:146 prop.unmarshal(Cursor.from_raw(dog_with_cat_properties))147 except SchemaError as e:148 self.assertTrue("Unexpected additional property" in str(e))149 else:150 self.fail("MUST failed because Dog not accept additional properties")151 # Semi explicit discriminator152 spec = {153 'schemas': {154 'Cat': {155 'type': 'object',156 'additionalProperties': False,157 'required': [158 'pet_type'159 ],160 'properties': {161 'pet_type': {162 'type': 'string'163 },164 'name': {165 'type': 'string'166 }167 }168 },169 'Dog': {170 'type': 'object',171 'additionalProperties': False,172 'required': [173 'pet_type'174 ],175 'properties': {176 'pet_type': {177 'type': 'string'178 },179 'nickname': {180 'type': 'string'181 }182 }183 },184 'Pet': {185 'type': 'object',186 'properties': {187 'pet': {188 'oneOf': [189 {190 '$ref': '#/schemas/Cat'191 },192 {193 '$ref': '#/schemas/Dog'194 }195 ],196 'discriminator': {197 'propertyName': 'pet_type',198 'mapping': {199 '1': '#/schemas/Cat',200 }201 }202 }203 }204 }205 }206 }207 schema = Object.from_raw(Components, spec)208 prop = PropertyFactory.generate(schema['schemas']['Pet'])209 cat_payload = {210 'pet': {211 'pet_type': '1',212 'name': 'Misty'213 }214 }215 cat = prop.unmarshal(Cursor.from_raw(cat_payload))216 self.assertEqual(cat['pet']['name'], 'Misty')217 dog_payload = {218 'pet': {219 'pet_type': 'Dog',220 'nickname': 'Max'221 }222 }223 dog = prop.unmarshal(Cursor.from_raw(dog_payload))224 self.assertEqual(dog['pet']['nickname'], 'Max')225 unknown_payload = {226 'pet': {227 'pet_type': '2',228 'nickname': 'Max'229 }230 }231 try:232 prop.unmarshal(Cursor.from_raw(unknown_payload))233 except SchemaError as e:234 self.assertTrue("No one of property types are not matched to discriminator value" in str(e))235 else:236 self.fail("MUST failed because object has unknown pet type")237 # Discriminator with inline schemas238 spec = {239 'x-schemas': {240 'Cat': {241 'type': 'object',242 'additionalProperties': False,243 'required': [244 'pet_type'245 ],246 'properties': {247 'pet_type': {248 'type': 'string'249 },250 'name': {251 'type': 'string'252 }253 }254 },255 'Dog': {256 'type': 'object',257 'additionalProperties': False,258 'required': [259 'pet_type'260 ],261 'properties': {262 'pet_type': {263 'type': 'string'264 },265 'nickname': {266 'type': 'string'267 }268 }269 }270 },271 'type': 'object',272 'properties': {273 'pet': {274 'oneOf': [275 {276 '$ref': '#/x-schemas/Cat'277 },278 {279 '$ref': '#/x-schemas/Dog'280 },281 {282 'type': 'object',283 'additionalProperties': False,284 'required': [285 'pet_type'286 ],287 'properties': {288 'pet_type': {289 'type': 'string'290 },291 'last_name': {292 'type': 'string'293 }294 }295 }296 ],297 'discriminator': {298 'propertyName': 'pet_type'299 }300 }301 }302 }303 schema = Object.from_raw(Schema, spec)304 prop = PropertyFactory.generate(schema)305 inline_payload = {306 'pet': {307 'pet_type': 'Inline',308 'last_name': 'Misty'309 }310 }311 try:312 prop.unmarshal(Cursor.from_raw(inline_payload))313 except SchemaError as e:314 self.assertTrue("No one of property types are not matched to discriminator value" in str(e))315 else:316 self.fail("MUST failed because inline schema in oneOf not considered")317 def test_generate_anyOf(self):318 spec = {319 'x-schemas': {320 'Cat': {321 'type': 'object',322 'additionalProperties': False,323 'properties': {324 'name': {325 'type': 'string'326 }327 }328 },329 'Dog': {330 'type': 'object',331 'additionalProperties': False,332 'properties': {333 'nickname': {334 'type': 'string'335 }336 }337 }338 },339 'type': 'object',340 'properties': {341 'pet': {342 'anyOf': [343 {344 '$ref': '#/x-schemas/Cat'345 },346 {347 '$ref': '#/x-schemas/Dog'348 }349 ]350 }351 }352 }353 schema = Object.from_raw(Schema, spec)354 prop = PropertyFactory.generate(schema)355 cat_payload = {356 'pet': {357 'name': 'Misty'358 }359 }360 cat = prop.unmarshal(Cursor.from_raw(cat_payload))361 self.assertEqual(cat['pet']['name'], 'Misty')362 dog_payload = {363 'pet': {364 'nickname': 'Max'365 }366 }367 dog = prop.unmarshal(Cursor.from_raw(dog_payload))368 self.assertEqual(dog['pet']['nickname'], 'Max')369 not_any_payload = {370 'pet': {371 'weight': '10kg'372 }373 }374 try:375 prop.unmarshal(Cursor.from_raw(not_any_payload))376 except SchemaError as e:377 self.assertEqual(378 e.errors,379 {380 "pet": {381 "__any__": [382 {"weight": "Unexpected additional property"},383 {"weight": "Unexpected additional property"}384 ]385 }386 }387 )388 else:389 self.fail("MUST failed because payload not match for all of schemas")390 spec = {391 'x-schemas': {392 'Cat': {393 'type': 'object',394 'properties': {395 'name': {396 'type': 'string'397 }398 }399 },400 'Dog': {401 'type': 'object',402 'properties': {403 'nickname': {404 'type': 'string'405 }406 }407 }408 },409 'type': 'object',410 'properties': {411 'pet': {412 'anyOf': [413 {414 '$ref': '#/x-schemas/Cat'415 },416 {417 '$ref': '#/x-schemas/Dog'418 }419 ]420 }421 }422 }423 schema = Object.from_raw(Schema, spec)424 prop = PropertyFactory.generate(schema)425 cat_dog_payload = {426 'pet': {427 'name': 'Misty',428 'nickname': 'Max'429 }430 }431 cat_dog = prop.unmarshal(Cursor.from_raw(cat_dog_payload))432 self.assertEqual(cat_dog['pet']['name'], 'Misty')433 self.assertEqual(cat_dog['pet']['nickname'], 'Max')434 def test_generate_allOf(self):435 spec = {436 'x-schemas': {437 'Cat': {438 'type': 'object',439 'properties': {440 'name': {441 'type': 'string'442 },443 's': {444 'type': 'integer'445 }446 }447 },448 'Dog': {449 'type': 'object',450 'properties': {451 'nickname': {452 'type': 'string'453 }454 }455 }456 },457 'type': 'object',458 'properties': {459 'pet': {460 'allOf': [461 {462 '$ref': '#/x-schemas/Cat'463 },464 {465 '$ref': '#/x-schemas/Dog'466 }467 ]468 }469 }470 }471 schema = Object.from_raw(Schema, spec)472 prop = PropertyFactory.generate(schema)473 cat_dog_payload = {474 'pet': {475 'name': 'Misty',476 'nickname': 'Max',477 's': '45'478 }479 }480 cat_dog = prop.unmarshal(Cursor.from_raw(cat_dog_payload), context=Context(strict=False))481 self.assertEqual(cat_dog['pet']['name'], 'Misty')482 self.assertEqual(cat_dog['pet']['nickname'], 'Max')483 self.assertTrue(isinstance(cat_dog['pet']['s'], int))484 def test_generate_recursive_property(self):485 spec = {486 'properties': {487 'payload': {},488 'nested_nodes': {489 'type': 'array',490 'items': {491 '$ref': '#/'492 }493 }494 }495 }496 schema = Object.from_raw(Schema, spec)497 prop = PropertyFactory.generate(schema)498 payload = {499 'adsad': 'sdsd',500 'payload': {501 'ddd': 34502 },503 'nested_nodes': [504 {505 'payload': {},506 'nested_nodes': [507 {508 'payload': {509 'fdf': 54510 }511 }512 ]513 },514 {515 'payload': {516 'ff': 'dd'517 }518 }519 ]520 }521 root = prop.unmarshal(Cursor.from_raw(payload))522 self.assertEqual(root['adsad'], 'sdsd')523 def test_defaults(self):524 spec = {525 'properties': {526 'with_default': {527 'type': 'integer',528 'default': 5529 }530 }531 }532 schema = Object.from_raw(Schema, spec)533 prop = PropertyFactory.generate(schema)534 payload = {}535 obj = prop.unmarshal(Cursor.from_raw(payload))536 self.assertEqual(obj['with_default'], 5)537 spec = {538 'properties': {539 'with_default': {540 'type': 'string',541 'pattern': '^\+?\d{7,20}$',542 'default': 'sdfdf'543 }544 }545 }546 schema = Object.from_raw(Schema, spec)547 prop = PropertyFactory.generate(schema)548 payload = {}549 try:550 prop.unmarshal(Cursor.from_raw(payload))551 except SchemaError as e:552 self.assertEqual(e.errors, {"with_default": ["Value did not match to pattern"]})553 else:554 self.fail("MUST failed because default value doesn't match to pattern")555 def test_enum_primitive(self):556 spec = {557 'properties': {558 'prop': {559 'type': 'integer',560 'enum': [5, 'ret', '56']561 }562 }563 }564 schema = Object.from_raw(Schema, spec)565 prop = PropertyFactory.generate(schema)566 payload = {567 'prop': 5568 }569 obj = prop.unmarshal(Cursor.from_raw(payload))570 self.assertEqual(obj['prop'], 5)571 payload = {572 'prop': 45573 }574 try:575 prop.unmarshal(Cursor.from_raw(payload))576 except SchemaError as e:577 self.assertEqual(e.errors, {"prop": ["Value is invalid. Expected one of: 5, ret, 56"]})578 else:579 self.fail("MUST failed because property value doesn't match to enumerated values")580 spec = {581 'properties': {582 'prop': {583 'type': 'string',584 'enum': ['5', 'ret', '56']585 }586 }587 }588 schema = Object.from_raw(Schema, spec)589 prop = PropertyFactory.generate(schema)590 payload = {591 'prop': '5'592 }593 obj = prop.unmarshal(Cursor.from_raw(payload))594 self.assertEqual(obj['prop'], '5')595 spec = {596 'properties': {597 'prop': {598 'type': 'boolean',599 'enum': [True]600 }601 }602 }603 schema = Object.from_raw(Schema, spec)604 prop = PropertyFactory.generate(schema)605 payload = {606 'prop': True607 }608 obj = prop.unmarshal(Cursor.from_raw(payload))609 self.assertEqual(obj['prop'], True)610 def test_enum_list(self):611 spec = {612 'properties': {613 'prop': {614 'type': 'array',615 'items': {616 'type': 'integer'617 },618 'enum': [[3], [1, 4]]619 }620 }621 }622 schema = Object.from_raw(Schema, spec)623 prop = PropertyFactory.generate(schema)624 payload = {625 'prop': [3]626 }627 obj = prop.unmarshal(Cursor.from_raw(payload))628 self.assertEqual(obj['prop'], [3])629 payload = {630 'prop': [1, 4]631 }632 obj = prop.unmarshal(Cursor.from_raw(payload))633 self.assertEqual(obj['prop'], [1, 4])634 payload = {635 'prop': [1, 45]636 }637 try:638 prop.unmarshal(Cursor.from_raw(payload))639 except SchemaError as e:640 self.assertEqual(e.errors, {"prop": ["Value is invalid. Expected one of: [3], [1, 4]"]})641 else:642 self.fail("MUST failed because property value doesn't match to enumerated values")643 def test_enum_object(self):644 spec = {645 'properties': {646 'prop': {647 'type': 'object',648 'additionalProperties': False,649 'properties': {650 'type': {651 'type': 'integer',652 'nullable': True653 }654 },655 'enum': [{'type': 0}, {'type': None}]656 }657 }658 }659 schema = Object.from_raw(Schema, spec)660 prop = PropertyFactory.generate(schema)661 payload = {662 'prop': {663 'type': 0664 }665 }666 obj = prop.unmarshal(Cursor.from_raw(payload))667 self.assertEqual(obj['prop']['type'], 0)668 payload = {669 'prop': {670 'type': None671 }672 }673 obj = prop.unmarshal(Cursor.from_raw(payload))674 self.assertEqual(obj['prop']['type'], None)675 payload = {676 'prop': {677 'type': 1678 }679 }680 try:681 prop.unmarshal(Cursor.from_raw(payload))682 except SchemaError as e:683 self.assertTrue('Expected one of' in str(e))684 else:685 self.fail("MUST failed because property value doesn't match to enumerated values")686 def test_required(self):687 spec = {688 'required': ['prop'],689 'properties': {690 'prop': {691 'type': 'object',692 'required': ['subprop'],693 'properties': {694 'subprop': {695 'type': 'integer'696 }697 }698 }699 }700 }701 schema = Object.from_raw(Schema, spec)702 prop = PropertyFactory.generate(schema)703 payload = {704 'prop': {705 'subprop': 314706 }707 }708 obj = prop.unmarshal(Cursor.from_raw(payload))709 self.assertEqual(obj['prop']['subprop'], 314)710 payload = {711 }712 try:713 prop.unmarshal(Cursor.from_raw(payload))714 except SchemaError as e:715 self.assertEqual(e.errors, {"prop": ["Missing value of required property"]})716 else:717 self.fail("MUST failed because property is required")718 payload = {719 'prop': {}720 }721 try:722 prop.unmarshal(Cursor.from_raw(payload))723 except SchemaError as e:724 self.assertEqual(e.errors, {"prop": {"subprop": ["Missing value of required property"]}})725 else:726 self.fail("MUST failed because sub property is required")727 def test_nullable(self):728 spec = {729 'properties': {730 'prop': {731 'type': 'integer',732 'nullable': True733 }734 }735 }736 schema = Object.from_raw(Schema, spec)737 prop = PropertyFactory.generate(schema)738 payload = {739 'prop': None740 }741 obj = prop.unmarshal(Cursor.from_raw(payload))742 self.assertEqual(obj['prop'], None)743 spec = {744 'properties': {745 'prop': {746 'type': 'integer',747 'nullable': False748 }749 }750 }751 schema = Object.from_raw(Schema, spec)752 prop = PropertyFactory.generate(schema)753 payload = {754 'prop': None755 }756 try:757 prop.unmarshal(Cursor.from_raw(payload))758 except SchemaError as e:759 self.assertTrue("Property not allow null values" in str(e))760 else:761 self.fail("MUST failed because null values not allowed")762 def test_strict(self):763 spec = {764 'allOf': [765 {'type': 'integer'},766 {'type': 'string'}767 ]768 }769 schema = Object.from_raw(Schema, spec)770 prop = PropertyFactory.generate(schema)771 payload = 5772 try:773 prop.unmarshal(Cursor.from_raw(payload))774 except SchemaError as e:775 self.assertEqual(776 e.errors,777 {"__all__": [["Couldn't interpret value as string"]]}778 )779 else:780 self.fail("MUST failed because payload is not string")781 payload = 5782 obj = prop.unmarshal(Cursor.from_raw(payload), context=Context(strict=False))783 self.assertEqual(obj, '5')784 def test_date(self):785 today = datetime.datetime.now().date()786 spec = {787 'properties': {788 'date': {789 'type': 'string',790 'format': 'date',791 }792 }793 }794 schema = Object.from_raw(Schema, spec)795 prop = PropertyFactory.generate(schema)796 payload = {797 'date': today.isoformat()798 }799 obj = prop.unmarshal(Cursor.from_raw(payload))800 self.assertEqual(obj['date'], today)801 def test_datetime(self):802 now = datetime.datetime.now().replace(microsecond=0)803 spec = {804 'properties': {805 'datetime': {806 'type': 'string',807 'format': 'date-time',808 }809 }810 }811 schema = Object.from_raw(Schema, spec)812 prop = PropertyFactory.generate(schema)813 payload = {814 'datetime': rfc3339.rfc3339(now)815 }816 obj = prop.unmarshal(Cursor.from_raw(payload))817 self.assertEqual(obj['datetime'], now)818 def test_min_max_properties(self):819 spec = {820 'additionalProperties': True,821 'minProperties': 2,822 'maxProperties': 4,823 'properties': {824 'prop1': {'type': 'string'}825 }826 }827 schema = Object.from_raw(Schema, spec)828 prop = PropertyFactory.generate(schema)829 payload = {830 'prop1': 'abracadabra',831 'prop2': 2832 }833 obj = prop.unmarshal(Cursor.from_raw(payload))834 self.assertEqual(obj['prop1'], 'abracadabra')835 self.assertEqual(obj['prop2'], 2)836 payload = {837 'prop1': 'abracadabra'838 }839 try:840 prop.unmarshal(Cursor.from_raw(payload))841 except SchemaError as e:842 self.assertEqual(e.errors, ["Object does not have enough properties"])843 else:844 self.fail("MUST failed because properties count less than specified in `minProperties`")845 payload = {846 'prop1': 'abracadabra',847 'prop2': 2,848 'prop3': 3,849 'prop4': 4,850 'prop5': 5851 }852 try:853 prop.unmarshal(Cursor.from_raw(payload))854 except SchemaError as e:855 self.assertEqual(e.errors, ["Object has too many properties"])856 else:857 self.fail("MUST failed because properties count more than specified in `maxProperties`")858 def test_styles(self):859 primitive = '5'860 lst = ['3', '4', '5']861 obj = {'role': 'admin', 'firstName': 'Alex'}862 self.assertEqual(factories.style_simple_primitive('5', True), primitive)863 self.assertEqual(factories.style_simple_primitive('5', False), primitive)864 self.assertEqual(factories.style_simple_array('3,4,5', True), lst)865 self.assertEqual(factories.style_simple_array('3,4,5', False), lst)866 self.assertEqual(factories.style_simple_objects('role,admin,firstName,Alex', False), obj)867 self.assertEqual(factories.style_simple_objects('role=admin,firstName=Alex', True), obj)868 self.assertEqual(factories.style_label_primitive('.5', True), primitive)869 self.assertEqual(factories.style_label_primitive('.5', False), primitive)870 self.assertEqual(factories.style_label_array('.3.4.5', True), lst)871 self.assertEqual(factories.style_label_array('.3,4,5', False), lst)872 self.assertEqual(factories.style_label_object('.role=admin.firstName=Alex', True), obj)873 self.assertEqual(factories.style_label_object('.role,admin,firstName,Alex', False), obj)874 self.assertEqual(factories.style_matrix_primitive(';id=5', True), primitive)875 self.assertEqual(factories.style_matrix_primitive(';id=5', False), primitive)876 self.assertEqual(factories.style_matrix_array(';id=3;id=4;id=5', True), lst)877 self.assertEqual(factories.style_matrix_array(';id=3,4,5', False), lst)878 self.assertEqual(factories.style_matrix_object(';role=admin;firstName=Alex', True), obj)879 self.assertEqual(factories.style_matrix_object(';id=role,admin,firstName,Alex', False), obj)880 self.assertEqual(factories.style_form_primitive('5', True), primitive)881 self.assertEqual(factories.style_form_primitive('5', False), primitive)882 self.assertEqual(factories.style_form_array(lst, True), lst)883 self.assertEqual(factories.style_form_array('3,4,5', False), lst)884 self.assertEqual(factories.style_form_object('role,admin,firstName,Alex', False), obj)885 self.assertEqual(factories.style_space_delimited_array('3 4 5', False), lst)886 self.assertEqual(factories.style_pipe_delimited_array('3|4|5', False), lst)887 def test_polymorphic(self):888 spec = {889 "schemas": {890 "Pet": {891 "type": "object",892 "discriminator": {893 "propertyName": "petType"894 },895 "properties": {896 "name": {897 "type": "string"898 },899 "petType": {900 "type": "string"901 }902 },903 "required": [904 "name",905 "petType"906 ]907 },908 "Cat": {909 "description": (910 "A representation of a cat. Note that `Cat` will be used as the discriminator value."),911 "allOf": [912 {913 "$ref": "#/schemas/Pet"914 },915 {916 "type": "object",917 "properties": {918 "huntingSkill": {919 "type": "string",920 "description": "The measured skill for hunting",921 "default": "lazy",922 "enum": [923 "clueless",924 "lazy",925 "adventurous",926 "aggressive"927 ]928 }929 },930 "required": [931 "huntingSkill"932 ]933 }934 ]935 },936 "Dog": {937 "description": (938 "A representation of a dog. Note that `Dog` will be used as the discriminator value."),939 "allOf": [940 {941 "$ref": "#/schemas/Pet"942 },943 {944 "type": "object",945 "properties": {946 "packSize": {947 "type": "integer",948 "format": "int32",949 "description": "the size of the pack the dog is from",950 "default": 0,951 "minimum": 0952 }953 },954 "required": [955 "packSize"956 ]957 }958 ]959 }960 }961 }962 schema = Object.from_raw(Components, spec)963 prop = PropertyFactory.generate(schema['schemas']['Pet'])964 payload = {965 "petType": "Cat",966 "name": "Misty",967 "huntingSkill": "adventurous",968 "age": 3969 }970 cat = prop.unmarshal(Cursor.from_raw(payload))971 self.assertEqual(cat['age'], 3)972 self.assertEqual(cat['name'], "Misty")973 self.assertEqual(cat['huntingSkill'], "adventurous")974 payload = {975 "petType": "Dog",976 "name": "Max",977 "packSize": 314,978 "age": 2979 }980 dog = prop.unmarshal(Cursor.from_raw(payload))981 self.assertEqual(dog['age'], 2)982 self.assertEqual(dog['name'], "Max")983 self.assertEqual(dog['packSize'], 314)984 payload = {985 "age": 3986 }987 try:988 prop.unmarshal(Cursor.from_raw(payload))989 except SchemaError as e:990 self.assertEqual(e.errors, ["Could't discriminate type. Property with name `petType` not found"])991 else:992 self.fail("MUST failed because `petType` not specified")993 payload = {994 "petType": "Cat",995 "name": "Misty"996 }997 try:998 prop.unmarshal(Cursor.from_raw(payload))999 except SchemaError as e:1000 self.assertEqual(1001 e.errors,1002 {"__all__": [{"huntingSkill": ["Missing value of required property"]}]}1003 )1004 else:1005 self.fail("MUST failed because `huntingSkill` property of `Cat` schema is not specified")1006if __name__ == '__main__':...

Full Screen

Full Screen

test_field.py

Source:test_field.py Github

copy

Full Screen

...4from jumpscale.core.base import fields, ValidationError5class TestFields(unittest.TestCase):6 def test_bool(self):7 field = fields.Boolean()8 self.assertEqual(field.from_raw("yes"), True)9 self.assertEqual(field.from_raw("off"), False)10 self.assertEqual(field.from_raw(complex(1, 2)), True)11 self.assertEqual(field.from_raw(0), False)12 with self.assertRaises(ValidationError):13 field.validate("habd kteer")14 def test_int(self):15 field = fields.Integer()16 self.assertEqual(field.from_raw("1212"), 1212)17 self.assertEqual(field.from_raw(" 12"), 12)18 with self.assertRaises(ValidationError):19 field.validate(1.4)20 with self.assertRaises(ValidationError):21 field.validate("hbd akter")22 def test_int(self):23 field = fields.Float()24 self.assertEqual(field.from_raw("1212.2"), 1212.2)25 self.assertEqual(field.from_raw(" 12.2"), 12.2)26 with self.assertRaises(ValidationError):27 field.validate(1)28 with self.assertRaises(ValidationError):29 field.validate("more hbd here")30 # Email tests31 def test_email(self):32 email = fields.Email(default="test@gmail.com")33 self.assertEqual(email.default, "test@gmail.com")34 email.validate("test@gmail.com")35 with self.assertRaises(ValidationError):36 email.validate("test")37 # Path tests38 def test_url(self):39 """Success scenario for path validation"""40 path = fields.Path("/home")41 self.assertEqual(path.default, "/home")42 self.assertIsNone(path.validate("/home"))43 path = fields.Path("/home")44 self.assertEqual(path.default, "/home")45 with self.assertRaises(ValidationError):46 path.validate("test")47 # URL tests48 def test_url(self):49 """Success scenario for URL validation"""50 url = fields.URL("https://www.test.com")51 self.assertEqual(url.default, "https://www.test.com")52 self.assertIsNone(url.validate("https://www.test.com"))53 """Failure scenario for URL validation"""54 url = fields.URL("https://www.test.com")55 self.assertEqual(url.default, "https://www.test.com")56 with self.assertRaises(ValidationError):57 url.validate("test")58 # Tel tests59 def test_tel(self):60 """Success scenario for tel validation"""61 tel = fields.Tel(default="01222222222")62 self.assertEqual(tel.default, "01222222222")63 """Failure scenario for tel validation"""64 tel = fields.Tel(default="012-222-22222")65 self.assertEqual(tel.from_raw(tel.default), "01222222222")66 with self.assertRaises(ValidationError):67 tel.validate("test")68 # IPaddress tests69 def test_ipaddress_v4(self):70 """Success scenario for ipaddress ipv4 validation"""71 ipaddress = fields.IPAddress("192.168.0.1")72 self.assertEqual(ipaddress.default, "192.168.0.1")73 self.assertIsNone(ipaddress.validate("192.168.0.1"))74 """Failure scenario for ipaddress validation"""75 ipaddress = fields.IPAddress("192.168.0.1")76 self.assertEqual(ipaddress.default, "192.168.0.1")77 with self.assertRaises(ValidationError):78 ipaddress.validate("test")79 def test_ipaddress_v6(self):80 """Success scenario for ipaddress ipv6 validation"""81 ipaddress = fields.IPAddress("2001:db8::")82 self.assertEqual(ipaddress.default, "2001:db8::")83 self.assertIsNone(ipaddress.validate("2001:db8::"))84 def test_ipaddress_network(self):85 """Success scenario for ipaddress network validation"""86 ipaddress = fields.IPRange("192.168.0.0/28")87 self.assertEqual(ipaddress.default, "192.168.0.0/28")88 self.assertIsNone(ipaddress.validate("192.168.0.0/28"))89 # Datetime tests90 def test_datetime(self):91 """Success scenario for datetime validation"""92 value = "2020-12-03 12:30"93 dt_field = fields.DateTime(default=value)94 from_raw = dt_field.from_raw(dt_field.default)95 dt_obj = datetime.datetime.strptime(value, dt_field.format).replace(tzinfo=datetime.timezone.utc)96 self.assertEqual(from_raw, dt_obj)97 # check conversion (utc)98 self.assertEqual(dt_field.to_raw(dt_obj), 1606998600.0)99 self.assertEqual(dt_field.from_raw(1606998600.0), dt_obj)100 """Failure scenario for DateTime validation"""101 with self.assertRaises(ValidationError):102 dt_field.validate("1992/2/22")103 # Date tests104 def testest_date(self):105 """Success scenario for date validation"""106 value = "2020-12-03"107 timestamp = 1606953600108 dt_field = fields.Date(default=value)109 from_raw = dt_field.from_raw(dt_field.default)110 dt_obj = datetime.datetime.strptime(value, dt_field.format).replace(tzinfo=datetime.timezone.utc)111 dt_obj = dt_obj.date()112 self.assertEqual(from_raw, dt_obj)113 # check conversion114 self.assertEqual(dt_field.to_raw(dt_obj), timestamp)115 self.assertEqual(dt_field.from_raw(timestamp), dt_obj)116 """Failure scenario for Date validation"""117 date = fields.Date("2020-12-03")118 with self.assertRaises(ValidationError):119 date.validate("12:30")120 # Time tests121 def test_time(self):122 """Success scenario for time validation"""123 value = "12:30"124 t_field = fields.Time(default=value)125 from_raw = t_field.from_raw(t_field.default)126 t_obj = datetime.datetime.strptime(value, t_field.format).replace(tzinfo=datetime.timezone.utc).time()127 self.assertEqual(from_raw, t_obj)128 # check conversion129 # -2208943800 => 1/1/1 12:30:00130 # arrow does this to deal with time only, sets 1/1/1 as a date if time only us given)131 self.assertEqual(t_field.to_raw(t_obj), -2208943800)132 self.assertEqual(t_field.from_raw(-2208943800), t_obj)133 """Failure scenario for time validation"""134 time = fields.Time("12:30")135 self.assertEqual(time.default, "12:30")136 with self.assertRaises(ValidationError):137 time.validate("2020-12-03")138 def test_required_and_empty(self):139 field1 = fields.Json(required=True)140 field2 = fields.Json(required=True, allow_empty=True)141 field3 = fields.Json(required=True, allow_empty=False)142 field4 = fields.Json(required=False, allow_empty=False)143 with self.assertRaises(ValidationError):144 field1.validate(None)145 field2.validate("")146 field3.validate("null")...

Full Screen

Full Screen

commons.py

Source:commons.py Github

copy

Full Screen

1import torch2import torch.nn as nn3class GlobalAverage(nn.Module):4 def __init__(self, rank=2, keepdims=False):5 """6 :param rank: dimension of image7 :param keepdims: whether to preserve shape after averaging8 """9 super().__init__()10 self.axes = list(range(2, 2 + rank))11 self.keepdims = keepdims12 def forward(self, x):13 return torch.mean(x, dim=self.axes, keepdim=self.keepdims)14 def extra_repr(self):15 return f"axes={self.axes}, keepdims={self.keepdims}"16class Reshape(nn.Module):17 def __init__(self, *shape):18 """19 final tensor forward result (B, *shape)20 :param shape: shape to resize to except batch dimension21 """22 super().__init__()23 self.shape = shape24 def forward(self, x):25 return x.reshape([x.shape[0], *self.shape])26 def extra_repr(self):27 return f"shape={self.shape}"28class Identity(nn.Module):29 def forward(self, x):30 return x31class ImagenetNorm(nn.Module):32 def __init__(self, from_raw=True):33 """34 :param from_raw: whether the input image lies in the range of [0, 255]35 """36 super().__init__()37 self.from_raw = from_raw38 self.mean = nn.Parameter(torch.tensor([0.485, 0.456, 0.406]), requires_grad=False)39 self.std = nn.Parameter(torch.tensor([0.229, 0.224, 0.225]), requires_grad=False)40 def forward(self, x: torch.Tensor):41 if x.dtype != torch.float:42 x = x.float()43 x = x / 255 if self.from_raw else x44 mean = self.mean.view(1, 3, 1, 1)45 std = self.std.view(1, 3, 1, 1)46 return (x - mean) / std47 def extra_repr(self):48 return f"from_raw={self.from_raw}"49class Normalization(nn.Module):50 def __init__(self, from_raw=True):51 """52 :param from_raw: whether the input image lies in the range of [0, 255]53 """54 super().__init__()55 self.from_raw = from_raw56 def forward(self, x):57 if x.dtype != torch.float:58 x = x.float()59 if self.from_raw:60 return x / 127.5 - 161 else:62 return x * 2 - 163 def extra_repr(self):...

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 lisa 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