From 03910c892543c006ac7a2a33f8368c895dd4083a Mon Sep 17 00:00:00 2001 From: iscai-msft <43154838+iscai-msft@users.noreply.github.com> Date: Thu, 2 May 2024 16:01:06 -0400 Subject: [PATCH] Cleanup tests (#2564) --- .../asynctests/test_authentication_async.py | 1 + .../asynctests/test_client_naming_async.py | 4 +- .../asynctests/test_client_structure_async.py | 4 + .../asynctests/test_encode_bytes_async.py | 22 +- .../asynctests/test_encode_datetime_async.py | 52 +- .../asynctests/test_encode_duration_async.py | 20 +- .../asynctests/test_headasboolean_async.py | 4 + .../test_parameters_spread_async.py | 4 +- .../test_payload_content_negotiation_async.py | 5 + .../test_payload_json_merge_patch_async.py | 138 +- .../test_payload_media_type_async.py | 3 + .../test_payload_multipart_async.py | 180 +- .../asynctests/test_payload_pageable_async.py | 1 + .../test_resiliency_srv_driven_async.py | 24 +- ...est_server_versions_not_versioned_async.py | 3 + .../test_server_versions_versioned_async.py | 4 + ...ecial_headers_conditional_request_async.py | 3 + ...est_special_headers_repeatability_async.py | 1 + .../asynctests/test_typetest_array_async.py | 88 +- .../test_typetest_dictionary_async.py | 99 +- .../test_typetest_enum_extensible_async.py | 3 + .../test_typetest_enum_fixed_async.py | 3 + .../test_typetest_model_flatten_async.py | 102 +- ...el_inheritance_enum_discriminator_async.py | 10 + ...del_inheritance_not_discriminated_async.py | 2 +- ...etest_model_inheritance_recursive_async.py | 20 +- .../test_typetest_model_usage_async.py | 30 +- .../test_typetest_model_visibility_async.py | 6 + ...est_property_additionalproperties_async.py | 317 +++- .../test_typetest_property_nullable_async.py | 109 +- .../test_typetest_property_optional_async.py | 168 +- ...test_typetest_property_valuetypes_async.py | 353 ++-- .../asynctests/test_typetest_scalar_async.py | 78 +- .../asynctests/test_typetest_union_async.py | 123 +- .../test/generic_mock_api_tests/conftest.py | 13 +- .../test_client_naming.py | 4 +- .../test_client_structure.py | 3 + .../test_encode_bytes.py | 21 +- .../test_encode_datetime.py | 53 +- .../test_encode_duration.py | 12 +- .../test_headasboolean.py | 4 + .../test_payload_content_negotiation.py | 4 + .../test_payload_json_merge_patch.py | 136 +- .../test_payload_media_type.py | 3 + .../test_payload_multipart.py | 216 +-- .../test_payload_pageable.py | 1 + .../test_resiliency_srv_driven.py | 25 +- .../test_serialization_encoded_name_json.py | 1 - .../test_server_versions_not_versioned.py | 2 + .../test_server_versions_versioned.py | 3 + ...est_special_headers_conditional_request.py | 3 + .../test_typetest_array.py | 81 +- .../test_typetest_dictionary.py | 89 +- .../test_typetest_enum_extensible.py | 3 + .../test_typetest_enum_fixed.py | 3 + .../test_typetest_model_flatten.py | 56 +- ...st_model_inheritance_enum_discriminator.py | 10 + ..._model_inheritance_nested_discriminator.py | 1 + ...est_model_inheritance_not_discriminated.py | 1 + ...st_typetest_model_inheritance_recursive.py | 20 +- .../test_typetest_model_usage.py | 28 +- .../test_typetest_model_visibility.py | 6 + ..._typetest_property_additionalproperties.py | 282 ++- .../test_typetest_property_nullable.py | 102 +- .../test_typetest_property_optional.py | 156 +- .../test_typetest_property_valuetypes.py | 320 ++-- .../test_typetest_scalar.py | 74 +- .../test_typetest_union.py | 112 +- .../test_model_base_serialization.py | 1642 +++++++---------- 69 files changed, 3185 insertions(+), 2289 deletions(-) diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_authentication_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_authentication_async.py index badd94eab4..57122ced7f 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_authentication_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_authentication_async.py @@ -25,6 +25,7 @@ def _build_client(client_type): if client: await client.close() + @pytest.fixture() def token_credential(core_library): class FakeCredential: diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_client_naming_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_client_naming_async.py index 9b68a0a36d..be84dfa956 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_client_naming_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_client_naming_async.py @@ -26,9 +26,7 @@ async def test_language(client: NamingClient): @pytest.mark.asyncio async def test_compatible_with_encoded_name(client: NamingClient): - await client.compatible_with_encoded_name( - models.ClientNameAndJsonEncodedNameModel(client_name=True) - ) + await client.compatible_with_encoded_name(models.ClientNameAndJsonEncodedNameModel(client_name=True)) @pytest.mark.asyncio diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_client_structure_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_client_structure_async.py index 551f8951ee..be39934d89 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_client_structure_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_client_structure_async.py @@ -10,6 +10,7 @@ from client.structure.renamedoperation.aio import RenamedOperationClient from client.structure.twooperationgroup.aio import TwoOperationGroupClient + @pytest.mark.asyncio async def test_structure_default(): client = ServiceClient(endpoint="http://localhost:3000", client=ClientType.DEFAULT) @@ -23,6 +24,7 @@ async def test_structure_default(): await client.qux.eight() await client.qux.bar.nine() + @pytest.mark.asyncio async def test_structure_multiclient(): client_a = ClientAClient(endpoint="http://localhost:3000", client=ClientType.MULTI_CLIENT) @@ -35,6 +37,7 @@ async def test_structure_multiclient(): await client_b.renamed_four() await client_b.renamed_six() + @pytest.mark.asyncio async def test_structure_renamed_operation(): client = RenamedOperationClient(endpoint="http://localhost:3000", client=ClientType.RENAMED_OPERATION) @@ -46,6 +49,7 @@ async def test_structure_renamed_operation(): await client.group.renamed_four() await client.group.renamed_six() + @pytest.mark.asyncio async def test_structure_two_operation_group(): client = TwoOperationGroupClient(endpoint="http://localhost:3000", client=ClientType.RENAMED_OPERATION) diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_encode_bytes_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_encode_bytes_async.py index 69ecee6a36..b7a32b31a1 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_encode_bytes_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_encode_bytes_async.py @@ -16,6 +16,7 @@ FILE_FOLDER = Path(__file__).parent.parent + @pytest.fixture async def client(): async with BytesClient() as client: @@ -105,11 +106,22 @@ def png_data() -> bytes: @pytest.mark.asyncio async def test_request_body(client: BytesClient, png_data: bytes): - await client.request_body.default(value=bytes("test", "utf-8"), ) - await client.request_body.octet_stream(value=png_data, ) - await client.request_body.custom_content_type(value=png_data, ) - await client.request_body.base64(value=bytes("test", "utf-8"), ) - await client.request_body.base64url(value=bytes("test", "utf-8"), ) + await client.request_body.default( + value=bytes("test", "utf-8"), + ) + await client.request_body.octet_stream( + value=png_data, + ) + await client.request_body.custom_content_type( + value=png_data, + ) + await client.request_body.base64( + value=bytes("test", "utf-8"), + ) + await client.request_body.base64url( + value=bytes("test", "utf-8"), + ) + @pytest.mark.asyncio async def test_response_body(client: BytesClient, png_data: bytes): diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_encode_datetime_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_encode_datetime_async.py index 33413b59bc..1249b8e8f3 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_encode_datetime_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_encode_datetime_async.py @@ -48,54 +48,36 @@ async def test_query(client: DatetimeClient): async def test_property(client: DatetimeClient): result = await client.property.default( DefaultDatetimeProperty( - value=datetime.datetime( - 2022, 8, 26, 18, 38, 0, tzinfo=datetime.timezone.utc - ), + value=datetime.datetime(2022, 8, 26, 18, 38, 0, tzinfo=datetime.timezone.utc), ) ) - assert result.value == datetime.datetime( - 2022, 8, 26, 18, 38, 0, tzinfo=datetime.timezone.utc - ) + assert result.value == datetime.datetime(2022, 8, 26, 18, 38, 0, tzinfo=datetime.timezone.utc) result = await client.property.rfc3339( Rfc3339DatetimeProperty( - value=datetime.datetime( - 2022, 8, 26, 18, 38, 0, tzinfo=datetime.timezone.utc - ), + value=datetime.datetime(2022, 8, 26, 18, 38, 0, tzinfo=datetime.timezone.utc), ) ) - assert result.value == datetime.datetime( - 2022, 8, 26, 18, 38, 0, tzinfo=datetime.timezone.utc - ) + assert result.value == datetime.datetime(2022, 8, 26, 18, 38, 0, tzinfo=datetime.timezone.utc) result = await client.property.rfc7231( Rfc7231DatetimeProperty( - value=datetime.datetime( - 2022, 8, 26, 14, 38, 0, tzinfo=datetime.timezone.utc - ), + value=datetime.datetime(2022, 8, 26, 14, 38, 0, tzinfo=datetime.timezone.utc), ) ) - assert result.value == datetime.datetime( - 2022, 8, 26, 14, 38, 0, tzinfo=datetime.timezone.utc - ) + assert result.value == datetime.datetime(2022, 8, 26, 14, 38, 0, tzinfo=datetime.timezone.utc) result = await client.property.unix_timestamp( UnixTimestampDatetimeProperty( - value=datetime.datetime( - 2023, 6, 12, 10, 47, 44, tzinfo=datetime.timezone.utc - ), + value=datetime.datetime(2023, 6, 12, 10, 47, 44, tzinfo=datetime.timezone.utc), ) ) - assert result.value == datetime.datetime( - 2023, 6, 12, 10, 47, 44, tzinfo=datetime.timezone.utc - ) + assert result.value == datetime.datetime(2023, 6, 12, 10, 47, 44, tzinfo=datetime.timezone.utc) result = await client.property.unix_timestamp_array( UnixTimestampArrayDatetimeProperty( value=[ - datetime.datetime( - 2023, 6, 12, 10, 47, 44, tzinfo=datetime.timezone.utc - ), + datetime.datetime(2023, 6, 12, 10, 47, 44, tzinfo=datetime.timezone.utc), datetime.datetime(2023, 6, 14, 9, 17, 36, tzinfo=datetime.timezone.utc), ], ) @@ -131,7 +113,15 @@ async def test_header(client: DatetimeClient): @pytest.mark.asyncio async def test_response_header(client: DatetimeClient): cls = lambda x, y, z: z - assert (await client.response_header.default(cls=cls))["value"] == datetime.datetime(2022, 8, 26, 14, 38, 0, tzinfo=datetime.timezone.utc) - assert (await client.response_header.rfc3339(cls=cls))["value"] == datetime.datetime(2022, 8, 26, 18, 38, 0, tzinfo=datetime.timezone.utc) - assert (await client.response_header.rfc7231(cls=cls))["value"] == datetime.datetime(2022, 8, 26, 14, 38, 0, tzinfo=datetime.timezone.utc) - assert (await client.response_header.unix_timestamp(cls=cls))["value"] == datetime.datetime(2023, 6, 12, 10, 47, 44, tzinfo=datetime.timezone.utc) + assert (await client.response_header.default(cls=cls))["value"] == datetime.datetime( + 2022, 8, 26, 14, 38, 0, tzinfo=datetime.timezone.utc + ) + assert (await client.response_header.rfc3339(cls=cls))["value"] == datetime.datetime( + 2022, 8, 26, 18, 38, 0, tzinfo=datetime.timezone.utc + ) + assert (await client.response_header.rfc7231(cls=cls))["value"] == datetime.datetime( + 2022, 8, 26, 14, 38, 0, tzinfo=datetime.timezone.utc + ) + assert (await client.response_header.unix_timestamp(cls=cls))["value"] == datetime.datetime( + 2023, 6, 12, 10, 47, 44, tzinfo=datetime.timezone.utc + ) diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_encode_duration_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_encode_duration_async.py index 521e03d83a..7a882ad651 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_encode_duration_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_encode_duration_async.py @@ -33,27 +33,19 @@ async def test_query(client: DurationClient): @pytest.mark.asyncio async def test_property(client: DurationClient): - result = await client.property.default( - DefaultDurationProperty(value=datetime.timedelta(days=40)) - ) + result = await client.property.default(DefaultDurationProperty(value=datetime.timedelta(days=40))) assert result.value == datetime.timedelta(days=40) result = await client.property.default(DefaultDurationProperty(value="P40D")) assert result.value == datetime.timedelta(days=40) - result = await client.property.iso8601( - ISO8601DurationProperty(value=datetime.timedelta(days=40)) - ) + result = await client.property.iso8601(ISO8601DurationProperty(value=datetime.timedelta(days=40))) assert result.value == datetime.timedelta(days=40) result = await client.property.iso8601(ISO8601DurationProperty(value="P40D")) assert result.value == datetime.timedelta(days=40) result = await client.property.int32_seconds(Int32SecondsDurationProperty(value=36)) assert result.value == 36 - result = await client.property.float_seconds( - FloatSecondsDurationProperty(value=35.621) - ) + result = await client.property.float_seconds(FloatSecondsDurationProperty(value=35.621)) assert abs(result.value - 35.621) < 0.0001 - result = await client.property.float_seconds_array( - FloatSecondsDurationArrayProperty(value=[35.621, 46.781]) - ) + result = await client.property.float_seconds_array(FloatSecondsDurationArrayProperty(value=[35.621, 46.781])) assert abs(result.value[0] - 35.621) < 0.0001 assert abs(result.value[1] - 46.781) < 0.0001 @@ -62,8 +54,6 @@ async def test_property(client: DurationClient): async def test_header(client: DurationClient): await client.header.default(duration=datetime.timedelta(days=40)) await client.header.iso8601(duration=datetime.timedelta(days=40)) - await client.header.iso8601_array( - duration=[datetime.timedelta(days=40), datetime.timedelta(days=50)] - ) + await client.header.iso8601_array(duration=[datetime.timedelta(days=40), datetime.timedelta(days=50)]) await client.header.int32_seconds(duration=36) await client.header.float_seconds(duration=35.621) diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_headasboolean_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_headasboolean_async.py index 7f9d57ec7b..0ec3574286 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_headasboolean_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_headasboolean_async.py @@ -10,21 +10,25 @@ from headasbooleanfalse.aio import VisibilityClient as HeadAsBooleanFalseClient from headasbooleanfalse import models as models_false + @pytest.fixture async def client_true(): async with HeadAsBooleanTrueClient() as client: yield client + @pytest.fixture async def client_false(): async with HeadAsBooleanFalseClient() as client: yield client + @pytest.mark.asyncio async def test_head_true(client_true): body = models_true.VisibilityModel(query_prop=123) assert await client_true.head_model(body) == True + @pytest.mark.asyncio async def test_head_false(client_false): body = models_false.VisibilityModel(query_prop=123) diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_parameters_spread_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_parameters_spread_async.py index dd2e4e51a9..4e447eba46 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_parameters_spread_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_parameters_spread_async.py @@ -26,9 +26,7 @@ async def test_alias_body(client: SpreadClient): @pytest.mark.asyncio async def test_alias_parameter(client: SpreadClient): - await client.alias.spread_as_request_parameter( - "1", x_ms_test_header="bar", name="foo" - ) + await client.alias.spread_as_request_parameter("1", x_ms_test_header="bar", name="foo") @pytest.mark.asyncio diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_payload_content_negotiation_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_payload_content_negotiation_async.py index a078b24883..4c2a11f61a 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_payload_content_negotiation_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_payload_content_negotiation_async.py @@ -8,23 +8,28 @@ from payload.contentnegotiation.aio import ContentNegotiationClient from payload.contentnegotiation.models import PngImageAsJson + @pytest.fixture async def client(): async with ContentNegotiationClient(endpoint="http://localhost:3000") as client: yield client + @pytest.mark.asyncio async def test_get_avatar_as_png(client: ContentNegotiationClient, png_data: bytes): assert b"".join([d async for d in (await client.same_body.get_avatar_as_png())]) == png_data + @pytest.mark.asyncio async def test_get_avatar_as_jpeg(client: ContentNegotiationClient, jpg_data: bytes): assert b"".join([d async for d in (await client.same_body.get_avatar_as_jpeg())]) == jpg_data + @pytest.mark.asyncio async def test_different_body_get_avatar_as_png(client: ContentNegotiationClient, png_data: bytes): assert b"".join([d async for d in (await client.different_body.get_avatar_as_png())]) == png_data + @pytest.mark.asyncio async def test_different_body_get_avatar_as_json(client: ContentNegotiationClient, png_data: bytes): result = await client.different_body.get_avatar_as_json() diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_payload_json_merge_patch_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_payload_json_merge_patch_async.py index f9fdb15c39..f507625c08 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_payload_json_merge_patch_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_payload_json_merge_patch_async.py @@ -8,9 +8,9 @@ from payload.jsonmergepatch.models import InnerModel, Resource, ResourcePatch try: - from azure.core.serialization import NULL as CoreNull + from azure.core.serialization import NULL except ImportError: - from corehttp.serialization import NULL as CoreNull + from corehttp.serialization import NULL @pytest.fixture @@ -19,68 +19,76 @@ async def client(): yield client -INNER_MADGE = InnerModel(name="InnerMadge", description="innerDesc") -CREATE_RESOURCE = Resource( - name="Madge", - description="desc", - map={"key": INNER_MADGE}, - array=[INNER_MADGE], - int_value=1, - float_value=1.1, - inner_model=INNER_MADGE, - int_array=[1, 2, 3], -) -UPDATE_RESOURCE_REQ = ResourcePatch( - description=CoreNull, - map={"key": InnerModel(description=CoreNull), "key2": CoreNull}, - array=CoreNull, - int_value=CoreNull, - float_value=CoreNull, - inner_model=CoreNull, - int_array=CoreNull, -) -UPDATE_RESOURCE_RAW_REQ = { - "description": None, - "map": {"key": {"description": None}, "key2": None}, - "array": None, - "intValue": None, - "floatValue": None, - "innerModel": None, - "intArray": None, -} -UPDATE_RESOURCE_EXPECTED = Resource( - name="Madge", - map={"key": InnerModel(name="InnerMadge")}, -) +@pytest.mark.asyncio +async def test_create_resource(client: JsonMergePatchClient): + inner_madge = InnerModel(name="InnerMadge", description="innerDesc") + create_resource = Resource( + name="Madge", + description="desc", + map={"key": inner_madge}, + array=[inner_madge], + int_value=1, + float_value=1.1, + inner_model=inner_madge, + int_array=[1, 2, 3], + ) + response = await client.create_resource(create_resource) + assert response == create_resource -@pytest.mark.parametrize( - "op,req,expected", - [ - ("create_resource", CREATE_RESOURCE, CREATE_RESOURCE), - ( - "update_resource", - UPDATE_RESOURCE_REQ, - UPDATE_RESOURCE_EXPECTED, - ), - ( - "update_resource", - UPDATE_RESOURCE_RAW_REQ, - UPDATE_RESOURCE_EXPECTED, - ), - ( - "update_optional_resource", - UPDATE_RESOURCE_REQ, - UPDATE_RESOURCE_EXPECTED, - ), - ( - "update_optional_resource", - UPDATE_RESOURCE_RAW_REQ, - UPDATE_RESOURCE_EXPECTED, - ), - ], -) -@pytest.mark.asyncio -async def test_json_merge_patch(client: JsonMergePatchClient, op, req, expected): - response = await getattr(client, op)(req) - assert response == expected +async def test_update_resource_model_input(client: JsonMergePatchClient): + update_resource = ResourcePatch( + description=NULL, + map={"key": InnerModel(description=NULL), "key2": NULL}, + array=NULL, + int_value=NULL, + float_value=NULL, + inner_model=NULL, + int_array=NULL, + ) + response = await client.update_resource(update_resource) + assert response == Resource(name="Madge", map={"key": InnerModel(name="InnerMadge")}) + + +async def test_update_resource_raw_input(client: JsonMergePatchClient): + response = await client.update_resource( + { + "description": None, + "map": {"key": {"description": None}, "key2": None}, + "array": None, + "intValue": None, + "floatValue": None, + "innerModel": None, + "intArray": None, + } + ) + assert response == Resource(name="Madge", map={"key": InnerModel(name="InnerMadge")}) + + +async def test_update_optional_resource_model_input(client: JsonMergePatchClient): + update_resource = ResourcePatch( + description=NULL, + map={"key": InnerModel(description=NULL), "key2": NULL}, + array=NULL, + int_value=NULL, + float_value=NULL, + inner_model=NULL, + int_array=NULL, + ) + response = await client.update_optional_resource(update_resource) + assert response == Resource(name="Madge", map={"key": InnerModel(name="InnerMadge")}) + + +async def test_update_optional_resource_raw_input(client: JsonMergePatchClient): + response = await client.update_optional_resource( + { + "description": None, + "map": {"key": {"description": None}, "key2": None}, + "array": None, + "intValue": None, + "floatValue": None, + "innerModel": None, + "intArray": None, + } + ) + assert response == Resource(name="Madge", map={"key": InnerModel(name="InnerMadge")}) diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_payload_media_type_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_payload_media_type_async.py index b9a3572968..d783e6ac61 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_payload_media_type_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_payload_media_type_async.py @@ -6,17 +6,20 @@ import pytest from payload.mediatype.aio import MediaTypeClient + @pytest.fixture async def client(): async with MediaTypeClient(endpoint="http://localhost:3000") as client: yield client + @pytest.mark.asyncio async def test_json(client: MediaTypeClient): data = "foo" await client.string_body.send_as_json(data) assert await client.string_body.get_as_json() == data + @pytest.mark.asyncio async def test_text(client: MediaTypeClient): data = "{cat}" diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_payload_multipart_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_payload_multipart_async.py index 4f993b97dc..9fe080c327 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_payload_multipart_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_payload_multipart_async.py @@ -3,13 +3,10 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- -import uuid -from typing import Dict, Any from pathlib import Path import pytest -from payload.multipart.aio import MultiPartClient from payload.multipart import models -from payload.multipart._model_base import Model +from payload.multipart.aio import MultiPartClient JPG = Path(__file__).parent.parent / "data/image.jpg" PNG = Path(__file__).parent.parent / "data/image.png" @@ -22,91 +19,90 @@ async def client(): @pytest.mark.asyncio -@pytest.mark.parametrize( - "op_name,model_class,data,file,file_info", - [ - ("basic", models.MultiPartRequest, {"id": "123"}, {"profileImage": JPG}, {}), - ( - "multi_binary_parts", - models.MultiBinaryPartsRequest, - {}, - {"profileImage": JPG, "picture": PNG}, - {} - ), - ( - "multi_binary_parts", - models.MultiBinaryPartsRequest, - {}, - {"profileImage": JPG}, - {} - ), - ( - "json_part", - models.JsonPartRequest, - {"address": models.Address(city="X")}, - {"profileImage": JPG}, - {}, - ), - ( - "json_array_parts", - models.JsonArrayPartsRequest, - {"previousAddresses": [models.Address(city="Y"), models.Address(city="Z")]}, - {"profileImage": JPG}, - {}, - ), - ( - "binary_array_parts", - models.BinaryArrayPartsRequest, - {"id": "123"}, - {"pictures": [PNG, PNG]}, - {}, - ), - ( - "complex", - models.ComplexPartsRequest, - {"id": "123", "previousAddresses": [models.Address(city="Y"), models.Address(city="Z")], "address": models.Address(city="X")}, - {"pictures": [PNG, PNG], "profileImage": JPG}, - {}, - ), - ( - "check_file_name_and_content_type", - models.MultiPartRequest, - {"id": "123"}, - {"profileImage": JPG}, - {"content_type": "image/jpg", "file_name": "hello.jpg"}, - ), - ( - "anonymous_model", - dict, - {}, - {"profileImage": JPG}, - {}, - ), - ], -) -async def test_multi_part(client: MultiPartClient, op_name, model_class, data, file, file_info): - def add_info(file_path, is_bytes): - file_content = open(str(file_path), "rb").read() if is_bytes else open(str(file_path), "rb") - name = str(uuid.uuid4()) if file_info.get("file_name") is None else file_info.get("file_name") - content_type = "application/octet-stream" if file_info.get("content_type") is None else file_info.get("content_type") - return (name, file_content, content_type) - def convert(is_bytes=False): - files_part = {k: ([add_info(vi, is_bytes) for vi in v] if isinstance(v, list) else add_info(v, is_bytes)) for k, v in file.items()} - files_part.update(data) - return files_part - op = getattr(client.form_data, op_name) - # test bytes (raw dict) - body = convert(True) - await op(body) - - # test io (raw dict) - body = convert() - await op(body) - - # test bytes (model) - body = convert(True) - await op(model_class(body)) - - # test io (model) - body = convert() - await op(model_class(body)) +async def test_anonymous_model(client: MultiPartClient): + await client.form_data.anonymous_model({"profileImage": open(str(JPG), "rb")}) + + +@pytest.mark.asyncio +async def test_basic(client: MultiPartClient): + await client.form_data.basic( + models.MultiPartRequest( + id="123", + profile_image=open(str(JPG), "rb"), + ) + ) + + +@pytest.mark.asyncio +async def test_binary_array_parts(client: MultiPartClient): + await client.form_data.binary_array_parts( + models.BinaryArrayPartsRequest( + id="123", + pictures=[ + open(str(PNG), "rb"), + open(str(PNG), "rb"), + ], + ) + ) + + +@pytest.mark.asyncio +async def test_check_file_name_and_content_type(client: MultiPartClient): + await client.form_data.check_file_name_and_content_type( + models.MultiPartRequest( + id="123", + profile_image=("hello.jpg", open(str(JPG), "rb"), "image/jpg"), + ) + ) + + +@pytest.mark.asyncio +async def test_complex(client: MultiPartClient): + await client.form_data.complex( + models.ComplexPartsRequest( + id="123", + previous_addresses=[ + models.Address(city="Y"), + models.Address(city="Z"), + ], + address=models.Address(city="X"), + pictures=[ + open(str(PNG), "rb"), + open(str(PNG), "rb"), + ], + profile_image=open(str(JPG), "rb"), + ) + ) + + +@pytest.mark.asyncio +async def test_json_array_parts(client: MultiPartClient): + await client.form_data.json_array_parts( + models.JsonArrayPartsRequest( + previous_addresses=[ + models.Address(city="Y"), + models.Address(city="Z"), + ], + profile_image=open(str(JPG), "rb"), + ) + ) + + +@pytest.mark.asyncio +async def test_json_part(client: MultiPartClient): + await client.form_data.json_part( + models.JsonPartRequest( + address=models.Address(city="X"), + profile_image=open(str(JPG), "rb"), + ) + ) + + +@pytest.mark.asyncio +async def test_multi_binary_parts(client: MultiPartClient): + await client.form_data.multi_binary_parts( + models.MultiBinaryPartsRequest( + profile_image=open(str(JPG), "rb"), + picture=open(str(PNG), "rb"), + ) + ) diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_payload_pageable_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_payload_pageable_async.py index af6ef136e1..b3b9c57c80 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_payload_pageable_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_payload_pageable_async.py @@ -12,6 +12,7 @@ async def client(): async with PageableClient(endpoint="http://localhost:3000") as client: yield client + @pytest.mark.asyncio async def test_list(client: PageableClient): result = [p async for p in client.list(maxpagesize=3)] diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_resiliency_srv_driven_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_resiliency_srv_driven_async.py index 8521b0e585..3ac2e70ce5 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_resiliency_srv_driven_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_resiliency_srv_driven_async.py @@ -7,11 +7,18 @@ from resiliency.srv.driven1.aio import ResiliencyServiceDrivenClient as V1Client from resiliency.srv.driven2.aio import ResiliencyServiceDrivenClient as V2Client + def get_v1_client(service_deployment_version: str, api_version: str = "v1") -> V1Client: - return V1Client(endpoint="http://localhost:3000", service_deployment_version=service_deployment_version, api_version=api_version) + return V1Client( + endpoint="http://localhost:3000", service_deployment_version=service_deployment_version, api_version=api_version + ) + def get_v2_client(service_deployment_version: str, api_version: str = "v2") -> V2Client: - return V2Client(endpoint="http://localhost:3000", service_deployment_version=service_deployment_version, api_version=api_version) + return V2Client( + endpoint="http://localhost:3000", service_deployment_version=service_deployment_version, api_version=api_version + ) + @pytest.mark.asyncio async def test_add_optional_param_from_none(): @@ -31,6 +38,7 @@ async def test_add_optional_param_from_none(): async with V2Client(endpoint="http://localhost:3000", service_deployment_version="v2") as client: await client.from_none(new_parameter="new") + @pytest.mark.asyncio async def test_add_optional_param_from_one_required(): # old client to old service with api version v1 @@ -49,6 +57,7 @@ async def test_add_optional_param_from_one_required(): async with V2Client(endpoint="http://localhost:3000", service_deployment_version="v2") as client: await client.from_one_required(parameter="required", new_parameter="new") + @pytest.mark.asyncio async def test_add_optional_param_from_one_optional(): # old client to old service with api version v1 @@ -67,15 +76,15 @@ async def test_add_optional_param_from_one_optional(): async with V2Client(endpoint="http://localhost:3000", service_deployment_version="v2") as client: await client.from_one_optional(parameter="optional", new_parameter="new") + @pytest.mark.asyncio async def test_break_the_glass(core_library): - request = core_library.rest.HttpRequest( - method="DELETE", url="/add-operation" - ) + request = core_library.rest.HttpRequest(method="DELETE", url="/add-operation") async with V1Client(endpoint="http://localhost:3000", service_deployment_version="v2", api_version="v2") as client: response = await client.send_request(request) response.raise_for_status() + @pytest.mark.asyncio async def test_add_operation(): async with V2Client(endpoint="http://localhost:3000", service_deployment_version="v2") as client: @@ -83,12 +92,13 @@ async def test_add_operation(): @pytest.mark.parametrize( - "func_name, params", [ + "func_name, params", + [ ("from_none", {"new_parameter": "new"}), ("from_one_optional", {"parameter": "optional", "new_parameter": "new"}), ("from_one_required", {"parameter": "required", "new_parameter": "new"}), ("add_operation", {}), - ] + ], ) @pytest.mark.asyncio async def test_new_client_with_old_apiversion_call_new_parameter(func_name, params): diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_server_versions_not_versioned_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_server_versions_not_versioned_async.py index 1e8ea2ce97..cc17b0f3f2 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_server_versions_not_versioned_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_server_versions_not_versioned_async.py @@ -12,14 +12,17 @@ async def client(): async with NotVersionedClient(endpoint="http://localhost:3000", api_version="v1.0") as client: yield client + @pytest.mark.asyncio async def test_without_api_version(client: NotVersionedClient): await client.without_api_version() + @pytest.mark.asyncio async def test_with_query_api_version(client: NotVersionedClient): await client.with_query_api_version() + @pytest.mark.asyncio async def test_with_path_api_version(client: NotVersionedClient): await client.with_path_api_version() diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_server_versions_versioned_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_server_versions_versioned_async.py index df33b1b890..53e7d194f4 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_server_versions_versioned_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_server_versions_versioned_async.py @@ -12,18 +12,22 @@ async def client(): async with VersionedClient(endpoint="http://localhost:3000") as client: yield client + @pytest.mark.asyncio async def test_without_api_version(client: VersionedClient): await client.without_api_version() + @pytest.mark.asyncio async def test_with_query_api_version(client: VersionedClient): await client.with_query_api_version() + @pytest.mark.asyncio async def test_with_path_api_version(client: VersionedClient): await client.with_path_api_version() + @pytest.mark.asyncio async def test_with_query_old_api_version(): async with VersionedClient(endpoint="http://localhost:3000", api_version="2021-01-01-preview") as client: diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_special_headers_conditional_request_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_special_headers_conditional_request_async.py index 989743c17a..5018e64c36 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_special_headers_conditional_request_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_special_headers_conditional_request_async.py @@ -6,15 +6,18 @@ import pytest from specialheaders.conditionalrequest.aio import ConditionalRequestClient + @pytest.fixture async def client(): async with ConditionalRequestClient() as client: yield client + @pytest.mark.asyncio async def test_post_if_match(core_library, client: ConditionalRequestClient): await client.post_if_match(etag="valid", match_condition=core_library.MatchConditions.IfNotModified) + @pytest.mark.asyncio async def test_post_if_none_match(core_library, client: ConditionalRequestClient): await client.post_if_none_match(etag="invalid", match_condition=core_library.MatchConditions.IfModified) diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_special_headers_repeatability_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_special_headers_repeatability_async.py index bed233de1c..dbf74414e1 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_special_headers_repeatability_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_special_headers_repeatability_async.py @@ -12,6 +12,7 @@ async def client(): async with RepeatabilityClient() as client: yield client + @pytest.mark.asyncio async def test_immediate_success(client: RepeatabilityClient): cls = lambda x, y, z: z diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_array_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_array_async.py index 772a31cd3e..89eb896cc3 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_array_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_array_async.py @@ -6,31 +6,79 @@ import pytest import isodate -from typetest.array import models, aio +from typetest.array.aio import ArrayClient +from typetest.array import models + @pytest.fixture async def client(): - async with aio.ArrayClient() as client: + async with ArrayClient() as client: yield client -@pytest.mark.parametrize( - "og_name,val", [ - ("int32_value", [1, 2]), - ("int64_value", [2**53-1, -(2**53-1)]), - ("boolean_value", [True, False]), - ("string_value", ["hello", ""]), - ("float32_value", [43.125]), - ("datetime_value", [isodate.parse_datetime("2022-08-26T18:38:00Z")]), - ("duration_value", [isodate.parse_duration("P123DT22H14M12.011S")]), - ("unknown_value", [1, "hello", None]), - ("model_value", [ + +@pytest.mark.asyncio +async def test_boolean_value(client: ArrayClient): + assert await client.boolean_value.get() == [True, False] + client.boolean_value.put([True, False]) + + +@pytest.mark.asyncio +async def test_datetime_value(client: ArrayClient): + assert await client.datetime_value.get() == [isodate.parse_datetime("2022-08-26T18:38:00Z")] + client.datetime_value.put([isodate.parse_datetime("2022-08-26T18:38:00Z")]) + + +@pytest.mark.asyncio +async def test_duration_value(client: ArrayClient): + assert await client.duration_value.get() == [isodate.parse_duration("P123DT22H14M12.011S")] + client.duration_value.put([isodate.parse_duration("P123DT22H14M12.011S")]) + + +@pytest.mark.asyncio +async def test_float32_value(client: ArrayClient): + assert await client.float32_value.get() == [43.125] + client.float32_value.put([43.125]) + + +@pytest.mark.asyncio +async def test_int32_value(client: ArrayClient): + assert await client.int32_value.get() == [1, 2] + client.int32_value.put([1, 2]) + + +@pytest.mark.asyncio +async def test_int64_value(client: ArrayClient): + assert await client.int64_value.get() == [2**53 - 1, -(2**53 - 1)] + client.int64_value.put([2**53 - 1, -(2**53 - 1)]) + + +@pytest.mark.asyncio +async def test_model_value(client: ArrayClient): + assert await client.model_value.get() == [ + models.InnerModel(property="hello"), + models.InnerModel(property="world"), + ] + client.model_value.put( + [ models.InnerModel(property="hello"), models.InnerModel(property="world"), - ]), - ] -) + ] + ) + + +@pytest.mark.asyncio +async def test_nullable_float_value(client: ArrayClient): + assert await client.nullable_float_value.get() == [1.25, None, 3.0] + client.nullable_float_value.put([1.25, None, 3.0]) + + +@pytest.mark.asyncio +async def test_string_value(client: ArrayClient): + assert await client.string_value.get() == ["hello", ""] + client.string_value.put(["hello", ""]) + + @pytest.mark.asyncio -async def test_array(client: aio.ArrayClient, og_name: str, val: dict): - og_group = getattr(client, og_name) - assert await og_group.get() == val - await og_group.put(val) +async def test_unknown_value(client: ArrayClient): + assert await client.unknown_value.get() == [1, "hello", None] + client.unknown_value.put([1, "hello", None]) diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_dictionary_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_dictionary_async.py index d097487d08..def81cc2e2 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_dictionary_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_dictionary_async.py @@ -8,34 +8,81 @@ from typetest.dictionary.aio import DictionaryClient import isodate + @pytest.fixture async def client(): async with DictionaryClient() as client: yield client -@pytest.mark.parametrize( - "og_name,val", [ - ("int32_value", {"k1": 1, "k2": 2}), - ("int64_value", {"k1": 2**53-1, "k2": -(2**53-1)}), - ("boolean_value", {"k1": True, "k2": False}), - ("string_value", {"k1": "hello", "k2": ""}), - ("float32_value", {"k1": 43.125}), - ("datetime_value", {"k1": isodate.parse_datetime("2022-08-26T18:38:00Z")}), - ("duration_value", {"k1": isodate.parse_duration("P123DT22H14M12.011S")}), - ("unknown_value", {"k1": 1, "k2": "hello", "k3": None}), - ("model_value", { - "k1": models.InnerModel(property="hello"), - "k2": models.InnerModel(property="world"), - }), - ("recursive_model_value", { - "k1": models.InnerModel(property="hello", children={}), - "k2": models.InnerModel(property="world", children={"k2.1": models.InnerModel(property="inner world")}), - }), - ("nullable_float_value", {"k1": 1.25, "k2": 0.5, "k3": None}), - ] -) -@pytest.mark.asyncio -async def test_dictionary(client: DictionaryClient, og_name: str, val: dict): - og_group = getattr(client, og_name) - assert await og_group.get() == val - await og_group.put(val) + +@pytest.mark.asyncio +async def test_boolean_value(client: DictionaryClient): + value = {"k1": True, "k2": False} + assert await client.boolean_value.get() == value + await client.boolean_value.put(value) + + +@pytest.mark.asyncio +async def test_datetime_value(client: DictionaryClient): + value = {"k1": isodate.parse_datetime("2022-08-26T18:38:00Z")} + assert await client.datetime_value.get() == value + await client.datetime_value.put(value) + + +@pytest.mark.asyncio +async def test_duration_value(client: DictionaryClient): + value = {"k1": isodate.parse_duration("P123DT22H14M12.011S")} + assert await client.duration_value.get() == value + await client.duration_value.put(value) + + +@pytest.mark.asyncio +async def test_float32_value(client: DictionaryClient): + value = {"k1": 43.125} + assert await client.float32_value.get() == value + await client.float32_value.put(value) + + +@pytest.mark.asyncio +async def test_int32_value(client: DictionaryClient): + value = {"k1": 1, "k2": 2} + assert await client.int32_value.get() == value + await client.int32_value.put(value) + + +@pytest.mark.asyncio +async def test_int64_value(client: DictionaryClient): + value = {"k1": 2**53 - 1, "k2": -(2**53 - 1)} + assert await client.int64_value.get() == value + await client.int64_value.put(value) + + +@pytest.mark.asyncio +async def test_model_value(client: DictionaryClient): + value = { + "k1": models.InnerModel(property="hello"), + "k2": models.InnerModel(property="world"), + } + assert await client.model_value.get() == value + await client.model_value.put(value) + + +@pytest.mark.asyncio +async def test_nullable_float_value(client: DictionaryClient): + value = {"k1": 1.25, "k2": 0.5, "k3": None} + assert await client.nullable_float_value.get() == value + await client.nullable_float_value.put(value) + + +@pytest.mark.asyncio +async def test_string_value(client: DictionaryClient): + value = {"k1": "hello", "k2": ""} + assert await client.string_value.get() == value + await client.string_value.put(value) + + +@pytest.mark.asyncio +async def test_unknown_value(client: DictionaryClient): + value = {"k1": 1, "k2": "hello", "k3": None} + assert await client.unknown_value.get() == value + await client.unknown_value.put(value) diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_enum_extensible_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_enum_extensible_async.py index 1a5876c385..75fca822dd 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_enum_extensible_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_enum_extensible_async.py @@ -6,16 +6,19 @@ import pytest from typetest.enum.extensible import models, aio + @pytest.fixture async def client(): async with aio.ExtensibleClient() as client: yield client + @pytest.mark.asyncio async def test_known_value(client): assert await client.string.get_known_value() == models.DaysOfWeekExtensibleEnum.MONDAY await client.string.put_known_value(models.DaysOfWeekExtensibleEnum.MONDAY) + @pytest.mark.asyncio async def test_unknown_value(client): assert await client.string.get_unknown_value() == "Weekend" diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_enum_fixed_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_enum_fixed_async.py index b5d20f8b82..de17f194b6 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_enum_fixed_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_enum_fixed_async.py @@ -6,16 +6,19 @@ import pytest from typetest.enum.fixed import aio, models + @pytest.fixture async def client(): async with aio.FixedClient() as client: yield client + @pytest.mark.asyncio async def test_known_value(client): assert await client.string.get_known_value() == models.DaysOfWeekEnum.MONDAY await client.string.put_known_value(models.DaysOfWeekEnum.MONDAY) + @pytest.mark.asyncio async def test_unknown_value(client: aio.FixedClient, core_library): try: diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_model_flatten_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_model_flatten_async.py index 94746ead4a..0f19a30ab6 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_model_flatten_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_model_flatten_async.py @@ -17,40 +17,70 @@ async def client(): # ========== test for cadl-ranch ========== -@pytest.mark.parametrize( - "op_name,reqs,reses", - [ - ( - "put_flatten_model", - [ - FlattenModel(name="foo", properties=ChildModel(age=10, description="bar")), - FlattenModel(name="foo", age=10, description="bar"), - ], - [ - FlattenModel(name="test", properties=ChildModel(age=1, description="test")), - FlattenModel(name="test", age=1, description="test"), - ], - ), - # python doesn't support nested flatten model - ( - "put_nested_flatten_model", - [ - NestedFlattenModel( - name="foo", - properties=ChildFlattenModel(summary="bar", properties=ChildModel(age=10, description="test")), - ), - ], - [ - NestedFlattenModel( - name="test", - properties=ChildFlattenModel(summary="test", properties=ChildModel(age=1, description="foo")), - ), - ], - ), - ], -) @pytest.mark.asyncio -async def test_flatten(client: FlattenClient, op_name, reqs, reses): - for req in reqs: - for res in reses: - assert await getattr(client, op_name)(req) == res +async def test_put_flatten_model(client: FlattenClient): + resp = FlattenModel(name="test", properties=ChildModel(age=1, description="test")) + assert ( + await client.put_flatten_model(FlattenModel(name="foo", properties=ChildModel(age=10, description="bar"))) + == resp + ) + assert await client.put_flatten_model(FlattenModel(name="foo", age=10, description="bar")) == resp + + +@pytest.mark.asyncio +async def test_put_nested_flatten_model(client: FlattenClient): + # python doesn't support nested flatten model + assert await client.put_nested_flatten_model( + NestedFlattenModel( + name="foo", properties=ChildFlattenModel(summary="bar", properties=ChildModel(age=10, description="test")) + ) + ) == NestedFlattenModel( + name="test", properties=ChildFlattenModel(summary="test", properties=ChildModel(age=1, description="foo")) + ) + + +@pytest.mark.asyncio # ============test for compatibility ============ +async def test_dpg_model_common(): + flatten_model = FlattenModel(name="hello", properties=ChildModel(age=0, description="test")) + assert flatten_model.name == "hello" + assert flatten_model.properties.age == 0 + assert flatten_model.properties.description == "test" + + +@pytest.mark.asyncio +async def test_dpg_model_none(): + flatten_model = FlattenModel() + assert flatten_model.name is None + assert flatten_model.properties is None + assert flatten_model.age is None + assert flatten_model.description is None + + +@pytest.mark.asyncio +async def test_dpg_model_compatility(): + flatten_model = FlattenModel(description="test", age=0) + assert flatten_model.description == "test" + assert flatten_model.age == 0 + assert flatten_model.properties.description == "test" + assert flatten_model.properties.age == 0 + + +@pytest.mark.asyncio +async def test_dpg_model_setattr(): + flatten_model = FlattenModel() + + flatten_model.age = 0 + assert flatten_model.properties.age == 0 + flatten_model.description = "test" + assert flatten_model.properties.description == "test" + + flatten_model.properties.age = 1 + assert flatten_model.age == 1 + flatten_model.properties.description = "test2" + assert flatten_model.description == "test2" + + +@pytest.mark.asyncio +async def test_dpg_model_exception(): + with pytest.raises(AttributeError): + FlattenModel().no_prop diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_model_inheritance_enum_discriminator_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_model_inheritance_enum_discriminator_async.py index af03ded369..62493919cb 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_model_inheritance_enum_discriminator_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_model_inheritance_enum_discriminator_async.py @@ -13,44 +13,54 @@ async def client(): async with EnumDiscriminatorClient() as client: yield client + @pytest.fixture def valid_body(): return models.Golden(weight=10) + @pytest.fixture def valid_fixed_body(): return models.Cobra(length=10) + @pytest.mark.asyncio async def test_get_extensible_model(client: EnumDiscriminatorClient, valid_body: models.Dog): assert await client.get_extensible_model() == valid_body assert isinstance(await client.get_extensible_model(), models.Golden) + @pytest.mark.asyncio async def test_put_extensible_model(client: EnumDiscriminatorClient, valid_body: models.Dog): await client.put_extensible_model(valid_body) + @pytest.mark.asyncio async def test_get_extensible_model_missing_discriminator(client: EnumDiscriminatorClient): assert await client.get_extensible_model_missing_discriminator() == models.Dog(weight=10) + @pytest.mark.asyncio async def test_get_extensible_model_wrong_discriminator(client: EnumDiscriminatorClient): assert await client.get_extensible_model_wrong_discriminator() == models.Dog(weight=8, kind="wrongKind") + @pytest.mark.asyncio async def test_get_fixed_model(client: EnumDiscriminatorClient, valid_fixed_body: models.Snake): assert await client.get_fixed_model() == valid_fixed_body assert isinstance(await client.get_fixed_model(), models.Cobra) + @pytest.mark.asyncio async def test_put_fixed_model(client: EnumDiscriminatorClient, valid_fixed_body: models.Snake): await client.put_fixed_model(valid_fixed_body) + @pytest.mark.asyncio async def test_get_fixed_model_missing_discriminator(client: EnumDiscriminatorClient): assert await client.get_fixed_model_missing_discriminator() == models.Snake(length=10) + @pytest.mark.asyncio async def test_get_fixed_model_wrong_discriminator(client: EnumDiscriminatorClient): assert await client.get_fixed_model_wrong_discriminator() == models.Snake(length=8, kind="wrongKind") diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_model_inheritance_not_discriminated_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_model_inheritance_not_discriminated_async.py index 45ddf4b2e8..cef776322c 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_model_inheritance_not_discriminated_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_model_inheritance_not_discriminated_async.py @@ -28,7 +28,7 @@ async def test_get_valid(client, valid_body): async def test_post_valid(client, valid_body): await client.post_valid(valid_body) + @pytest.mark.asyncio async def test_put_valid(client, valid_body): assert valid_body == await client.put_valid(valid_body) - diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_model_inheritance_recursive_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_model_inheritance_recursive_async.py index c157a09aa1..b1f8272d2a 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_model_inheritance_recursive_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_model_inheritance_recursive_async.py @@ -13,24 +13,11 @@ async def client(): async with RecursiveClient() as client: yield client + @pytest.fixture async def expected(): - return Extension({ - "level": 0, - "extension": [ - { - "level": 1, - "extension": [ - { - "level": 2 - } - ] - }, - { - "level": 1 - } - ] -}) + return Extension({"level": 0, "extension": [{"level": 1, "extension": [{"level": 2}]}, {"level": 1}]}) + @pytest.mark.asyncio async def test_put(client: RecursiveClient, expected: Extension): @@ -40,4 +27,3 @@ async def test_put(client: RecursiveClient, expected: Extension): @pytest.mark.asyncio async def test_get(client: RecursiveClient, expected: Extension): assert await client.get() == expected - diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_model_usage_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_model_usage_async.py index 700b5f1d05..bcebeaec20 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_model_usage_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_model_usage_async.py @@ -7,22 +7,26 @@ from typetest.model.usage import models from typetest.model.usage.aio import UsageClient + @pytest.fixture async def client(): async with UsageClient() as client: yield client + +@pytest.mark.asyncio +async def test_input(client: UsageClient): + input = models.InputRecord(required_prop="example-value") + assert await client.input(input) is None + + +@pytest.mark.asyncio +async def test_output(client: UsageClient): + output = models.OutputRecord(required_prop="example-value") + assert output == await client.output() + + @pytest.mark.asyncio -@pytest.mark.parametrize( -"op_name, input,output", [ - ("input", models.InputRecord(required_prop="example-value"), None), - ("output", None, models.OutputRecord(required_prop="example-value")), - ("input_and_output", models.InputOutputRecord(required_prop="example-value"), models.InputOutputRecord(required_prop="example-value")), -] -) -async def test_input_output(client, op_name, input, output): - op = getattr(client, op_name) - if input: - assert output == await op(input) - else: - assert output == await op() +async def test_input_and_output(client: UsageClient): + input_output = models.InputOutputRecord(required_prop="example-value") + assert input_output == await client.input_and_output(input_output) diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_model_visibility_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_model_visibility_async.py index 90b52a64fd..92c5a3894b 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_model_visibility_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_model_visibility_async.py @@ -7,28 +7,34 @@ from typetest.model.visibility.aio import VisibilityClient from typetest.model.visibility import models + @pytest.fixture async def client(): async with VisibilityClient() as client: yield client + @pytest.mark.asyncio async def test_get_model(client): result = await client.get_model(models.VisibilityModel(query_prop=123)) assert result == models.VisibilityModel(read_prop="abc") + @pytest.mark.asyncio async def test_put_model(client): await client.put_model(models.VisibilityModel(create_prop=["foo", "bar"], update_prop=[1, 2])) + @pytest.mark.asyncio async def test_patch_model(client): await client.patch_model(models.VisibilityModel(update_prop=[1, 2])) + @pytest.mark.asyncio async def test_post_model(client): await client.post_model(models.VisibilityModel(create_prop=["foo", "bar"])) + @pytest.mark.asyncio async def test_delete_model(client): await client.delete_model(models.VisibilityModel(delete_prop=True)) diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_property_additionalproperties_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_property_additionalproperties_async.py index 99f4f850c6..3877422139 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_property_additionalproperties_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_property_additionalproperties_async.py @@ -4,8 +4,8 @@ # license information. # -------------------------------------------------------------------------- import pytest -from typetest.property.additionalproperties.aio import AdditionalPropertiesClient from typetest.property.additionalproperties import models +from typetest.property.additionalproperties.aio import AdditionalPropertiesClient @pytest.fixture @@ -13,45 +13,276 @@ async def client(): async with AdditionalPropertiesClient() as client: yield client -@pytest.mark.parametrize( - "og_name,val, model_name", [ - ("extends_unknown", {'name': 'ExtendsUnknownAdditionalProperties', 'prop1': 32, 'prop2': True, 'prop3': 'abc'}, models.ExtendsUnknownAdditionalProperties), - ("extends_unknown_derived", {'name': 'ExtendsUnknownAdditionalProperties', 'index': 314, 'age': 2.71828, 'prop1': 32, 'prop2': True, 'prop3': 'abc'}, models.ExtendsUnknownAdditionalPropertiesDerived), - ("extends_unknown_discriminated", {'kind': 'derived', 'name': 'Derived', 'index': 314, 'age': 2.71828, 'prop1': 32, 'prop2': True, 'prop3': 'abc'}, models.ExtendsUnknownAdditionalPropertiesDiscriminatedDerived), - ("is_unknown", {'name': 'IsUnknownAdditionalProperties', 'prop1': 32, 'prop2': True, 'prop3': 'abc'}, models.IsUnknownAdditionalProperties), - ("is_unknown_derived", {'name': 'IsUnknownAdditionalProperties', 'index': 314, 'age': 2.71828, 'prop1': 32, 'prop2': True, 'prop3': 'abc'}, models.IsUnknownAdditionalPropertiesDerived), - ("is_unknown_discriminated", {'kind': 'derived', 'name': 'Derived', 'index': 314, 'age': 2.71828, 'prop1': 32, 'prop2': True, 'prop3': 'abc'}, models.IsUnknownAdditionalPropertiesDiscriminatedDerived), - ("extends_string", {'name': 'ExtendsStringAdditionalProperties', 'prop': 'abc'}, models.ExtendsStringAdditionalProperties), - ("is_string", {'name': 'IsStringAdditionalProperties', 'prop': 'abc'}, models.IsStringAdditionalProperties), - ("extends_float", {'id': 43.125, 'prop': 43.125}, models.ExtendsFloatAdditionalProperties), - ("is_float", {'id': 43.125, 'prop': 43.125}, models.IsFloatAdditionalProperties), - ("extends_model", {'knownProp': {'state': 'ok'}, 'prop': {'state': 'ok'}}, models.ExtendsModelAdditionalProperties), - ("is_model", {'knownProp': {'state': 'ok'}, 'prop': {'state': 'ok'}}, models.IsModelAdditionalProperties), - ("extends_model_array", {'knownProp': [{'state': 'ok'}, {'state': 'ok'}], 'prop': [{'state': 'ok'}, {'state': 'ok'}]}, models.ExtendsModelArrayAdditionalProperties), - ("is_model_array", {'knownProp': [{'state': 'ok'}, {'state': 'ok'}], 'prop': [{'state': 'ok'}, {'state': 'ok'}]}, models.IsModelArrayAdditionalProperties), - ("spread_string", {'name': 'SpreadSpringRecord', 'prop': 'abc'}, dict), - ("spread_float", {'id': 43.125, 'prop': 43.125}, dict), - ("spread_model", {'knownProp': {'state': 'ok'}, 'prop': {'state': 'ok'}}, dict), - ("spread_model_array", {'knownProp': [{'state': 'ok'}, {'state': 'ok'}], 'prop': [{'state': 'ok'}, {'state': 'ok'}]}, dict), - ("spread_different_string", {'id': 43.125, 'prop': 'abc'}, dict), - ("spread_different_float", {'name': 'abc', 'prop': 43.125}, dict), - ("spread_different_model", {'knownProp': 'abc', 'prop': {'state': 'ok'}}, dict), - ("spread_different_model_array", {'knownProp': 'abc', 'prop': [{'state': 'ok'}, {'state': 'ok'}]}, dict), - ("extends_different_spread_string", {'id': 43.125, 'prop': 'abc', 'derivedProp': 'abc'}, models.DifferentSpreadStringDerived), - ("extends_different_spread_float", {'name': 'abc', 'prop': 43.125, 'derivedProp': 43.125}, models.DifferentSpreadFloatDerived), - ("extends_different_spread_model", {'knownProp': 'abc', 'prop': {'state': 'ok'}, 'derivedProp': {'state': 'ok'}}, models.DifferentSpreadModelDerived), - ("extends_different_spread_model_array", {'knownProp': 'abc', 'prop': [{'state': 'ok'}, {'state': 'ok'}], 'derivedProp': [{'state': 'ok'}, {'state': 'ok'}]}, models.DifferentSpreadModelArrayDerived), - ("multiple_spread", {'flag': True, 'prop1': 'abc', 'prop2': 43.125}, dict), - ("spread_record_discriminated_union", {'name': 'abc', 'prop1': {'fooProp': 'abc', 'kind': 'kind0'}, 'prop2': {'end': '2021-01-02T00:00:00Z', 'kind': 'kind1', 'start': '2021-01-01T00:00:00Z'}}, dict), - ("spread_record_non_discriminated_union", {'name': 'abc', 'prop1': {'kind': 'kind0', 'fooProp': 'abc'}, 'prop2': {'kind': 'kind1', 'start': '2021-01-01T00:00:00Z', 'end': '2021-01-02T00:00:00Z'}}, dict), - ("spread_record_non_discriminated_union2", {'name': 'abc', 'prop1': {'kind': 'kind1', 'start': '2021-01-01T00:00:00Z'}, 'prop2': {'kind': 'kind1', 'start': '2021-01-01T00:00:00Z', 'end': '2021-01-02T00:00:00Z'}}, dict), - ("spread_record_non_discriminated_union3", {'name': 'abc', 'prop1': [{'kind': 'kind1', 'start': '2021-01-01T00:00:00Z'}, {'kind': 'kind1', 'start': '2021-01-01T00:00:00Z'}], 'prop2': {'kind': 'kind1', 'start': '2021-01-01T00:00:00Z', 'end': '2021-01-02T00:00:00Z'}}, dict), - ("spread_record_union", {'flag': True, 'prop1': 'abc', 'prop2': 43.125}, dict), - ] -) -@pytest.mark.asyncio -async def test_json(client, og_name, val, model_name): - body = model_name(val) - og_group = getattr(client, og_name) - assert await og_group.get() == body - await og_group.put(body) + +@pytest.mark.asyncio +async def test_extends_different_spread_float(client: AdditionalPropertiesClient): + body = models.DifferentSpreadFloatDerived({"name": "abc", "prop": 43.125, "derivedProp": 43.125}) + assert await client.extends_different_spread_float.get() == body + await client.extends_different_spread_float.put(body) + + +@pytest.mark.asyncio +async def test_extends_different_spread_model(client: AdditionalPropertiesClient): + body = models.DifferentSpreadModelDerived( + {"knownProp": "abc", "prop": {"state": "ok"}, "derivedProp": {"state": "ok"}} + ) + assert await client.extends_different_spread_model.get() == body + await client.extends_different_spread_model.put(body) + + +@pytest.mark.asyncio +async def test_extends_different_spread_model_array(client: AdditionalPropertiesClient): + body = models.DifferentSpreadModelArrayDerived( + { + "knownProp": "abc", + "prop": [{"state": "ok"}, {"state": "ok"}], + "derivedProp": [{"state": "ok"}, {"state": "ok"}], + } + ) + assert await client.extends_different_spread_model_array.get() == body + await client.extends_different_spread_model_array.put(body) + + +@pytest.mark.asyncio +async def test_extends_different_spread_string(client: AdditionalPropertiesClient): + body = models.DifferentSpreadStringDerived({"id": 43.125, "prop": "abc", "derivedProp": "abc"}) + assert await client.extends_different_spread_string.get() == body + await client.extends_different_spread_string.put(body) + + +@pytest.mark.asyncio +async def test_extends_float(client: AdditionalPropertiesClient): + body = models.ExtendsFloatAdditionalProperties({"id": 43.125, "prop": 43.125}) + assert await client.extends_float.get() == body + await client.extends_float.put(body) + + +@pytest.mark.asyncio +async def test_extends_model(client: AdditionalPropertiesClient): + body = models.ExtendsModelAdditionalProperties({"knownProp": {"state": "ok"}, "prop": {"state": "ok"}}) + assert await client.extends_model.get() == body + await client.extends_model.put(body) + + +@pytest.mark.asyncio +async def test_extends_model_array(client: AdditionalPropertiesClient): + body = models.ExtendsModelArrayAdditionalProperties( + {"knownProp": [{"state": "ok"}, {"state": "ok"}], "prop": [{"state": "ok"}, {"state": "ok"}]} + ) + assert await client.extends_model_array.get() == body + await client.extends_model_array.put(body) + + +@pytest.mark.asyncio +async def test_extends_string(client: AdditionalPropertiesClient): + body = models.ExtendsStringAdditionalProperties({"name": "ExtendsStringAdditionalProperties", "prop": "abc"}) + assert await client.extends_string.get() == body + await client.extends_string.put(body) + + +@pytest.mark.asyncio +async def test_extends_unknown(client: AdditionalPropertiesClient): + body = models.ExtendsUnknownAdditionalProperties( + {"name": "ExtendsUnknownAdditionalProperties", "prop1": 32, "prop2": True, "prop3": "abc"} + ) + assert await client.extends_unknown.get() == body + await client.extends_unknown.put(body) + + +@pytest.mark.asyncio +async def test_extends_unknown_derived(client: AdditionalPropertiesClient): + body = models.ExtendsUnknownAdditionalPropertiesDerived( + { + "name": "ExtendsUnknownAdditionalProperties", + "index": 314, + "age": 2.71828, + "prop1": 32, + "prop2": True, + "prop3": "abc", + } + ) + assert await client.extends_unknown_derived.get() == body + await client.extends_unknown_derived.put(body) + + +@pytest.mark.asyncio +async def test_extends_unknown_discriminated(client: AdditionalPropertiesClient): + body = models.ExtendsUnknownAdditionalPropertiesDiscriminatedDerived( + {"kind": "derived", "name": "Derived", "index": 314, "age": 2.71828, "prop1": 32, "prop2": True, "prop3": "abc"} + ) + assert await client.extends_unknown_discriminated.get() == body + await client.extends_unknown_discriminated.put(body) + + +@pytest.mark.asyncio +async def test_is_float(client: AdditionalPropertiesClient): + body = models.IsFloatAdditionalProperties({"id": 43.125, "prop": 43.125}) + assert await client.is_float.get() == body + await client.is_float.put(body) + + +@pytest.mark.asyncio +async def test_is_model(client: AdditionalPropertiesClient): + body = models.IsModelAdditionalProperties({"knownProp": {"state": "ok"}, "prop": {"state": "ok"}}) + assert await client.is_model.get() == body + await client.is_model.put(body) + + +@pytest.mark.asyncio +async def test_is_model_array(client: AdditionalPropertiesClient): + body = models.IsModelArrayAdditionalProperties( + {"knownProp": [{"state": "ok"}, {"state": "ok"}], "prop": [{"state": "ok"}, {"state": "ok"}]} + ) + assert await client.is_model_array.get() == body + await client.is_model_array.put(body) + + +@pytest.mark.asyncio +async def test_is_string(client: AdditionalPropertiesClient): + body = models.IsStringAdditionalProperties({"name": "IsStringAdditionalProperties", "prop": "abc"}) + assert await client.is_string.get() == body + await client.is_string.put(body) + + +@pytest.mark.asyncio +async def test_is_unknown(client: AdditionalPropertiesClient): + body = models.IsUnknownAdditionalProperties( + {"name": "IsUnknownAdditionalProperties", "prop1": 32, "prop2": True, "prop3": "abc"} + ) + assert await client.is_unknown.get() == body + await client.is_unknown.put(body) + + +@pytest.mark.asyncio +async def test_is_unknown_derived(client: AdditionalPropertiesClient): + body = models.IsUnknownAdditionalPropertiesDerived( + { + "name": "IsUnknownAdditionalProperties", + "index": 314, + "age": 2.71828, + "prop1": 32, + "prop2": True, + "prop3": "abc", + } + ) + assert await client.is_unknown_derived.get() == body + await client.is_unknown_derived.put(body) + + +@pytest.mark.asyncio +async def test_is_unknown_discriminated(client: AdditionalPropertiesClient): + body = models.IsUnknownAdditionalPropertiesDiscriminatedDerived( + {"kind": "derived", "name": "Derived", "index": 314, "age": 2.71828, "prop1": 32, "prop2": True, "prop3": "abc"} + ) + assert await client.is_unknown_discriminated.get() == body + await client.is_unknown_discriminated.put(body) + + +@pytest.mark.asyncio +async def test_multiple_spread(client: AdditionalPropertiesClient): + body = {"flag": True, "prop1": "abc", "prop2": 43.125} + assert await client.multiple_spread.get() == body + await client.multiple_spread.put(body) + + +@pytest.mark.asyncio +async def test_spread_different_float(client: AdditionalPropertiesClient): + body = {"name": "abc", "prop": 43.125} + assert await client.spread_different_float.get() == body + await client.spread_different_float.put(body) + + +@pytest.mark.asyncio +async def test_spread_different_model(client: AdditionalPropertiesClient): + body = {"knownProp": "abc", "prop": {"state": "ok"}} + assert await client.spread_different_model.get() == body + await client.spread_different_model.put(body) + + +@pytest.mark.asyncio +async def test_spread_different_model_array(client: AdditionalPropertiesClient): + body = {"knownProp": "abc", "prop": [{"state": "ok"}, {"state": "ok"}]} + assert await client.spread_different_model_array.get() == body + await client.spread_different_model_array.put(body) + + +@pytest.mark.asyncio +async def test_spread_different_string(client: AdditionalPropertiesClient): + body = {"id": 43.125, "prop": "abc"} + assert await client.spread_different_string.get() == body + await client.spread_different_string.put(body) + + +@pytest.mark.asyncio +async def test_spread_model(client: AdditionalPropertiesClient): + body = {"knownProp": {"state": "ok"}, "prop": {"state": "ok"}} + assert await client.spread_model.get() == body + await client.spread_model.put(body) + + +@pytest.mark.asyncio +async def test_spread_model_array(client: AdditionalPropertiesClient): + body = {"knownProp": [{"state": "ok"}, {"state": "ok"}], "prop": [{"state": "ok"}, {"state": "ok"}]} + assert await client.spread_model_array.get() == body + await client.spread_model_array.put(body) + + +@pytest.mark.asyncio +async def test_spread_record_discriminated_union(client: AdditionalPropertiesClient): + body = { + "name": "abc", + "prop1": {"fooProp": "abc", "kind": "kind0"}, + "prop2": {"end": "2021-01-02T00:00:00Z", "kind": "kind1", "start": "2021-01-01T00:00:00Z"}, + } + assert await client.spread_record_discriminated_union.get() == body + await client.spread_record_discriminated_union.put(body) + + +@pytest.mark.asyncio +async def test_spread_record_non_discriminated_union(client: AdditionalPropertiesClient): + body = { + "name": "abc", + "prop1": {"kind": "kind0", "fooProp": "abc"}, + "prop2": {"kind": "kind1", "start": "2021-01-01T00:00:00Z", "end": "2021-01-02T00:00:00Z"}, + } + assert await client.spread_record_non_discriminated_union.get() == body + await client.spread_record_non_discriminated_union.put(body) + + +@pytest.mark.asyncio +async def test_spread_record_non_discriminated_union2(client: AdditionalPropertiesClient): + body = { + "name": "abc", + "prop1": {"kind": "kind1", "start": "2021-01-01T00:00:00Z"}, + "prop2": {"kind": "kind1", "start": "2021-01-01T00:00:00Z", "end": "2021-01-02T00:00:00Z"}, + } + assert await client.spread_record_non_discriminated_union2.get() == body + await client.spread_record_non_discriminated_union2.put(body) + + +@pytest.mark.asyncio +async def test_spread_record_non_discriminated_union3(client: AdditionalPropertiesClient): + body = { + "name": "abc", + "prop1": [ + {"kind": "kind1", "start": "2021-01-01T00:00:00Z"}, + {"kind": "kind1", "start": "2021-01-01T00:00:00Z"}, + ], + "prop2": {"kind": "kind1", "start": "2021-01-01T00:00:00Z", "end": "2021-01-02T00:00:00Z"}, + } + assert await client.spread_record_non_discriminated_union3.get() == body + await client.spread_record_non_discriminated_union3.put(body) + + +@pytest.mark.asyncio +async def test_spread_record_union(client: AdditionalPropertiesClient): + body = {"flag": True, "prop1": "abc", "prop2": 43.125} + assert await client.spread_record_union.get() == body + await client.spread_record_union.put(body) + + +@pytest.mark.asyncio +async def test_spread_string(client: AdditionalPropertiesClient): + body = {"name": "SpreadSpringRecord", "prop": "abc"} + assert await client.spread_string.get() == body + await client.spread_string.put(body) diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_property_nullable_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_property_nullable_async.py index 9f3ed62461..d9f09eeb8b 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_property_nullable_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_property_nullable_async.py @@ -5,12 +5,17 @@ # -------------------------------------------------------------------------- import json import pytest -from typetest.property.nullable.aio import NullableClient from typetest.property.nullable import models +from typetest.property.nullable.aio import NullableClient from typetest.property.nullable._model_base import ( # pylint: disable=protected-access SdkJSONEncoder, ) +try: + from corehttp.serialization import NULL +except ImportError: + from azure.core.serialization import NULL + @pytest.fixture async def client(): @@ -18,37 +23,75 @@ async def client(): yield client -@pytest.mark.parametrize( - "og_name,model,val", - [ - ("string", models.StringProperty, "hello"), - ("bytes", models.BytesProperty, "aGVsbG8sIHdvcmxkIQ=="), - ("datetime", models.DatetimeProperty, "2022-08-26T18:38:00Z"), - ("duration", models.DurationProperty, "P123DT22H14M12.011S"), - ( - "collections_byte", - models.CollectionsByteProperty, - ["aGVsbG8sIHdvcmxkIQ==", "aGVsbG8sIHdvcmxkIQ=="], - ), - ( - "collections_model", - models.CollectionsModelProperty, - [ - models.InnerModel(property="hello"), - models.InnerModel(property="world"), - ], - ), - ], -) @pytest.mark.asyncio -async def test(client, og_name, model, val, core_library): - og_group = getattr(client, og_name) - non_null_model = model(required_property="foo", nullable_property=val) - non_model = model(required_property="foo", nullable_property=core_library.serialization.NULL) - assert '{"requiredProperty": "foo", "nullableProperty": null}' == json.dumps( - non_model, cls=SdkJSONEncoder +async def test_bytes(client: NullableClient): + non_null_model = models.BytesProperty(required_property="foo", nullable_property="aGVsbG8sIHdvcmxkIQ==") + non_model = models.BytesProperty(required_property="foo", nullable_property=NULL) + assert '{"requiredProperty": "foo", "nullableProperty": null}' == json.dumps(non_model, cls=SdkJSONEncoder) + assert await client.bytes.get_non_null() == non_null_model + assert (await client.bytes.get_null())["nullableProperty"] is None + await client.bytes.patch_non_null(body=non_null_model) + await client.bytes.patch_null(body=non_model) + + +@pytest.mark.asyncio +async def test_collections_byte(client: NullableClient): + non_null_model = models.CollectionsByteProperty( + required_property="foo", nullable_property=["aGVsbG8sIHdvcmxkIQ==", "aGVsbG8sIHdvcmxkIQ=="] + ) + non_model = models.CollectionsByteProperty(required_property="foo", nullable_property=NULL) + assert '{"requiredProperty": "foo", "nullableProperty": null}' == json.dumps(non_model, cls=SdkJSONEncoder) + assert await client.collections_byte.get_non_null() == non_null_model + assert (await client.collections_byte.get_null())["nullableProperty"] is None + await client.collections_byte.patch_non_null(body=non_null_model) + await client.collections_byte.patch_null(body=non_model) + + +@pytest.mark.asyncio +async def test_collections_model(client: NullableClient): + non_null_model = models.CollectionsModelProperty( + required_property="foo", + nullable_property=[ + models.InnerModel(property="hello"), + models.InnerModel(property="world"), + ], ) - assert await og_group.get_non_null() == non_null_model - assert (await og_group.get_null())["nullableProperty"] is None - await og_group.patch_non_null(body=non_null_model) - await og_group.patch_null(body=non_model) + non_model = models.CollectionsModelProperty(required_property="foo", nullable_property=NULL) + assert '{"requiredProperty": "foo", "nullableProperty": null}' == json.dumps(non_model, cls=SdkJSONEncoder) + assert await client.collections_model.get_non_null() == non_null_model + assert (await client.collections_model.get_null())["nullableProperty"] is None + await client.collections_model.patch_non_null(body=non_null_model) + await client.collections_model.patch_null(body=non_model) + + +@pytest.mark.asyncio +async def test_datetime(client: NullableClient): + non_null_model = models.DatetimeProperty(required_property="foo", nullable_property="2022-08-26T18:38:00Z") + non_model = models.DatetimeProperty(required_property="foo", nullable_property=NULL) + assert '{"requiredProperty": "foo", "nullableProperty": null}' == json.dumps(non_model, cls=SdkJSONEncoder) + assert await client.datetime.get_non_null() == non_null_model + assert (await client.datetime.get_null())["nullableProperty"] is None + await client.datetime.patch_non_null(body=non_null_model) + await client.datetime.patch_null(body=non_model) + + +@pytest.mark.asyncio +async def test_duration(client: NullableClient): + non_null_model = models.DurationProperty(required_property="foo", nullable_property="P123DT22H14M12.011S") + non_model = models.DurationProperty(required_property="foo", nullable_property=NULL) + assert '{"requiredProperty": "foo", "nullableProperty": null}' == json.dumps(non_model, cls=SdkJSONEncoder) + assert await client.duration.get_non_null() == non_null_model + assert (await client.duration.get_null())["nullableProperty"] is None + await client.duration.patch_non_null(body=non_null_model) + await client.duration.patch_null(body=non_model) + + +@pytest.mark.asyncio +async def test_string(client: NullableClient): + non_null_model = models.StringProperty(required_property="foo", nullable_property="hello") + non_model = models.StringProperty(required_property="foo", nullable_property=NULL) + assert '{"requiredProperty": "foo", "nullableProperty": null}' == json.dumps(non_model, cls=SdkJSONEncoder) + assert await client.string.get_non_null() == non_null_model + assert (await client.string.get_null())["nullableProperty"] is None + await client.string.patch_non_null(body=non_null_model) + await client.string.patch_null(body=non_model) diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_property_optional_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_property_optional_async.py index 60df0b042f..6725832854 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_property_optional_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_property_optional_async.py @@ -3,66 +3,91 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- +from typing import Any import pytest from typetest.property.optional import models from typetest.property.optional.aio import OptionalClient + @pytest.fixture async def client(): async with OptionalClient() as client: yield client -@pytest.mark.parametrize( -"og_name,val", [ - ("string", "hello"), - ("bytes", "aGVsbG8sIHdvcmxkIQ=="), - ("datetime", "2022-08-26T18:38:00Z"), - ("duration", "P123DT22H14M12.011S"), - ("collections_byte", ["aGVsbG8sIHdvcmxkIQ==", "aGVsbG8sIHdvcmxkIQ=="]), - ("collections_model", [{'property': 'hello'}, {'property': 'world'}]), - ("string_literal", "hello"), - ("int_literal", 1), - ("float_literal", 1.25), - ("boolean_literal", True), - ("union_string_literal", "world"), - ("union_int_literal", 2), - ("union_float_literal", 2.375), -] -) + +@pytest.mark.asyncio +async def test_boolean_literal(client): + body = models.BooleanLiteralProperty(property=True) + assert await client.boolean_literal.get_all() == body + assert await client.boolean_literal.get_default() == models.BooleanLiteralProperty() + await client.boolean_literal.put_all(body) + await client.boolean_literal.put_default(models.BooleanLiteralProperty()) + + +@pytest.mark.asyncio +async def test_bytes(client): + body = models.BytesProperty(property="aGVsbG8sIHdvcmxkIQ==") + assert await client.bytes.get_all() == body + assert await client.bytes.get_default() == models.BytesProperty() + await client.bytes.put_all(body) + await client.bytes.put_default(models.BytesProperty()) + + +@pytest.mark.asyncio +async def test_collections_byte(client): + body = models.CollectionsByteProperty(property=["aGVsbG8sIHdvcmxkIQ==", "aGVsbG8sIHdvcmxkIQ=="]) + assert await client.collections_byte.get_all() == body + assert await client.collections_byte.get_default() == models.CollectionsByteProperty() + await client.collections_byte.put_all(body) + await client.collections_byte.put_default(models.CollectionsByteProperty()) + + +@pytest.mark.asyncio +async def test_collections_model(client): + body = models.CollectionsModelProperty( + property=[models.StringProperty(property="hello"), models.StringProperty(property="world")] + ) + assert await client.collections_model.get_all() == body + assert await client.collections_model.get_default() == models.CollectionsModelProperty() + await client.collections_model.put_all(body) + await client.collections_model.put_default(models.CollectionsModelProperty()) + + +@pytest.mark.asyncio +async def test_datetime(client): + body = models.DatetimeProperty(property="2022-08-26T18:38:00Z") + assert await client.datetime.get_all() == body + assert await client.datetime.get_default() == models.DatetimeProperty() + await client.datetime.put_all(body) + await client.datetime.put_default(models.DatetimeProperty()) + + +@pytest.mark.asyncio +async def test_duration(client): + body = models.DurationProperty(property="P123DT22H14M12.011S") + assert await client.duration.get_all() == body + assert await client.duration.get_default() == models.DurationProperty() + await client.duration.put_all(body) + await client.duration.put_default(models.DurationProperty()) + + @pytest.mark.asyncio -async def test_json(client, og_name, val): - body = {"property": val} - og_group = getattr(client, og_name) - assert await og_group.get_all() == body - assert await og_group.get_default() == {} - await og_group.put_all(body) - await og_group.put_default({}) - -@pytest.mark.parametrize( -"og_name,model,val", [ - ("string", models.StringProperty, "hello"), - ("bytes", models.BytesProperty, "aGVsbG8sIHdvcmxkIQ=="), - ("datetime", models.DatetimeProperty, "2022-08-26T18:38:00Z"), - ("duration", models.DurationProperty, "P123DT22H14M12.011S"), - ("collections_byte", models.CollectionsByteProperty, ["aGVsbG8sIHdvcmxkIQ==", "aGVsbG8sIHdvcmxkIQ=="]), - ("collections_model", models.CollectionsModelProperty, [models.StringProperty(property="hello"), models.StringProperty(property="world")]), - ("string_literal", models.StringLiteralProperty, "hello"), - ("int_literal", models.IntLiteralProperty, 1), - ("float_literal", models.FloatLiteralProperty, 1.25), - ("boolean_literal", models.BooleanLiteralProperty, True), - ("union_string_literal", models.UnionStringLiteralProperty, "world"), - ("union_int_literal", models.UnionIntLiteralProperty, 2), - ("union_float_literal", models.UnionFloatLiteralProperty, 2.375), -] -) +async def test_float_literal(client): + body = models.FloatLiteralProperty(property=1.25) + assert await client.float_literal.get_all() == body + assert await client.float_literal.get_default() == models.FloatLiteralProperty() + await client.float_literal.put_all(body) + await client.float_literal.put_default(models.FloatLiteralProperty()) + + @pytest.mark.asyncio -async def test_model(client, og_name, model, val): - body = model(property=val) - og_group = getattr(client, og_name) - assert await og_group.get_all() == body - assert await og_group.get_default() == {} == model() - await og_group.put_all(body) - await og_group.put_default(model()) +async def test_int_literal(client): + body = models.IntLiteralProperty(property=1) + assert await client.int_literal.get_all() == body + assert await client.int_literal.get_default() == models.IntLiteralProperty() + await client.int_literal.put_all(body) + await client.int_literal.put_default(models.IntLiteralProperty()) + @pytest.mark.asyncio async def test_required_and_optional(client): @@ -77,3 +102,48 @@ async def test_required_and_optional(client): assert await client.required_and_optional.get_required_only() == required_only_body await client.required_and_optional.put_all(all_body) await client.required_and_optional.put_required_only(required_only_body) + + +@pytest.mark.asyncio +async def test_string(client): + body = models.StringProperty(property="hello") + assert await client.string.get_all() == body + assert await client.string.get_default() == models.StringProperty() + await client.string.put_all(body) + await client.string.put_default(models.StringProperty()) + + +@pytest.mark.asyncio +async def test_string_literal(client): + body = models.StringLiteralProperty(property="hello") + assert await client.string_literal.get_all() == body + assert await client.string_literal.get_default() == models.StringLiteralProperty() + await client.string_literal.put_all(body) + await client.string_literal.put_default(models.StringLiteralProperty()) + + +@pytest.mark.asyncio +async def test_union_float_literal(client): + body = models.UnionFloatLiteralProperty(property=2.375) + assert await client.union_float_literal.get_all() == body + assert await client.union_float_literal.get_default() == models.UnionFloatLiteralProperty() + await client.union_float_literal.put_all(body) + await client.union_float_literal.put_default(models.UnionFloatLiteralProperty()) + + +@pytest.mark.asyncio +async def test_union_int_literal(client): + body = models.UnionIntLiteralProperty(property=2) + assert await client.union_int_literal.get_all() == body + assert await client.union_int_literal.get_default() == models.UnionIntLiteralProperty() + await client.union_int_literal.put_all(body) + await client.union_int_literal.put_default(models.UnionIntLiteralProperty()) + + +@pytest.mark.asyncio +async def test_union_string_literal(client): + body = models.UnionStringLiteralProperty(property="world") + assert await client.union_string_literal.get_all() == body + assert await client.union_string_literal.get_default() == models.UnionStringLiteralProperty() + await client.union_string_literal.put_all(body) + await client.union_string_literal.put_default(models.UnionStringLiteralProperty()) diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_property_valuetypes_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_property_valuetypes_async.py index 16953703cc..16c3150d8c 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_property_valuetypes_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_property_valuetypes_async.py @@ -3,10 +3,10 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- -import datetime import decimal import pytest +import datetime from typetest.property.valuetypes import models from typetest.property.valuetypes.aio import ValueTypesClient @@ -18,100 +18,78 @@ async def client(): @pytest.mark.asyncio -@pytest.mark.parametrize( - "og_name,val", - [ - ("boolean", True), - ("string", "hello"), - ("bytes", "aGVsbG8sIHdvcmxkIQ=="), - ("int_operations", 42), - ("float", 43.125), - ("decimal", decimal.Decimal("0.33333")), - ("decimal128", decimal.Decimal("0.33333")), - ("datetime", "2022-08-26T18:38:00Z"), - ("duration", "P123DT22H14M12.011S"), - ("enum", "ValueOne"), - ("extensible_enum", "UnknownValue"), - ("model", {"property": "hello"}), - ("collections_string", ["hello", "world"]), - ("collections_int", [1, 2]), - ("collections_model", [{"property": "hello"}, {"property": "world"}]), - ("dictionary_string", {"k1": "hello", "k2": "world"}), - ("unknown_string", "hello"), - ("unknown_int", 42), - ("unknown_dict", {"k1": "hello", "k2": 42}), - ("unknown_array", ["hello", "world"]), - ("boolean_literal", True), - ("int_literal", 42), - ("string_literal", "hello"), - ("float_literal", 43.125), - ("union_string_literal", "world"), - ("union_float_literal", 46.875), - ("union_int_literal", 42), - ("union_enum_value", "value2"), - ], -) -async def test(client, og_name, val): - body = {"property": val} - og_group = getattr(client, og_name) - assert await og_group.get() == body - await og_group.put(body) - - -@pytest.mark.parametrize( - "og_name,model,val", - [ - ("boolean", models.BooleanProperty, True), - ("string", models.StringProperty, "hello"), - ("bytes", models.BytesProperty, b"hello, world!"), - ("int_operations", models.IntProperty, 42), - ("float", models.FloatProperty, 43.125), - ("decimal", models.DecimalProperty, decimal.Decimal("0.33333")), - ("decimal128", models.Decimal128Property, decimal.Decimal("0.33333")), - ("enum", models.EnumProperty, models.InnerEnum.VALUE_ONE), - ("extensible_enum", models.ExtensibleEnumProperty, "UnknownValue"), - ("model", models.ModelProperty, models.InnerModel(property="hello")), - ("collections_string", models.CollectionsStringProperty, ["hello", "world"]), - ("collections_int", models.CollectionsIntProperty, [1, 2]), - ( - "collections_model", - models.CollectionsModelProperty, - [{"property": "hello"}, {"property": "world"}], - ), - ( - "dictionary_string", - models.DictionaryStringProperty, - {"k1": "hello", "k2": "world"}, - ), - ("unknown_string", models.UnknownStringProperty, "hello"), - ("unknown_int", models.UnknownIntProperty, 42), - ("unknown_dict", models.UnknownDictProperty, {"k1": "hello", "k2": 42}), - ("unknown_array", models.UnknownArrayProperty, ["hello", "world"]), - ("boolean_literal", models.BooleanLiteralProperty, True), - ("int_literal", models.IntLiteralProperty, 42), - ("string_literal", models.StringLiteralProperty, "hello"), - ("float_literal", models.FloatLiteralProperty, 43.125), - ("union_string_literal", models.UnionStringLiteralProperty, "world"), - ("union_float_literal", models.UnionFloatLiteralProperty, 46.875), - ("union_int_literal", models.UnionIntLiteralProperty, 42), - ( - "union_enum_value", - models.UnionEnumValueProperty, - models.ExtendedEnum.ENUM_VALUE2, - ), - ], -) -@pytest.mark.asyncio -async def test_model(client, og_name, model, val): - body = model(property=val) - og_group = getattr(client, og_name) - assert await og_group.get() == body - assert (await og_group.get()).property == val - await og_group.put(body) - - -@pytest.mark.asyncio -async def test_datetime_model(client): +async def test_model_deserialization(client: ValueTypesClient): + body = models.ModelProperty(property={"property": "hello"}) + assert body.property.property == body["property"]["property"] + resp = await client.model.get() + assert resp.property.property == resp["property"]["property"] + + body = models.CollectionsModelProperty(property=[{"property": "hello"}, {"property": "world"}]) + assert body.property[0].property == body["property"][0]["property"] + resp = await client.collections_model.get() + assert resp.property[1].property == resp["property"][1]["property"] + + +@pytest.mark.asyncio +async def test_enum_property(): + for prop in ["ValueOne", models.FixedInnerEnum.VALUE_ONE]: + string_type = models.EnumProperty(property=prop) + assert isinstance(string_type.property, models.FixedInnerEnum) + assert isinstance(string_type["property"], str) + + +@pytest.mark.asyncio +async def test_boolean(client: ValueTypesClient): + body = models.BooleanProperty(property=True) + assert body.property == body["property"] + resp = await client.boolean.get() + assert resp.property == resp["property"] == True + + +@pytest.mark.asyncio +async def test_boolean_literal(client: ValueTypesClient): + body = models.BooleanLiteralProperty(property=True) + assert body.property == body["property"] + resp = await client.boolean_literal.get() + assert resp.property == resp["property"] == True + + +@pytest.mark.asyncio +async def test_bytes(client: ValueTypesClient): + body = models.BytesProperty(property=b"hello, world!") + assert body.property == b"hello, world!" + assert body["property"] == "aGVsbG8sIHdvcmxkIQ==" + resp = await client.bytes.get() + assert resp.property == b"hello, world!" + assert resp["property"] == "aGVsbG8sIHdvcmxkIQ==" + + +@pytest.mark.asyncio +async def test_collections_int(client: ValueTypesClient): + body = models.CollectionsIntProperty(property=[1, 2]) + assert body.property == body["property"] + resp = await client.collections_int.get() + assert resp.property == resp["property"] == [1, 2] + + +@pytest.mark.asyncio +async def test_collections_model(client: ValueTypesClient): + body = models.CollectionsModelProperty(property=[{"property": "hello"}, {"property": "world"}]) + assert body.property[0].property == body["property"][0]["property"] + resp = await client.collections_model.get() + assert resp.property[1].property == resp["property"][1]["property"] + + +@pytest.mark.asyncio +async def test_collections_string(client: ValueTypesClient): + body = models.CollectionsStringProperty(property=["hello", "world"]) + assert body.property == body["property"] + resp = await client.collections_string.get() + assert resp.property == resp["property"] == ["hello", "world"] + + +@pytest.mark.asyncio +async def test_datetime(client): received_body = await client.datetime.get() assert received_body == {"property": "2022-08-26T18:38:00Z"} assert received_body.property.year == 2022 @@ -119,29 +97,184 @@ async def test_datetime_model(client): assert received_body.property.day == 26 assert received_body.property.hour == 18 assert received_body.property.minute == 38 - await client.datetime.put( - models.DatetimeProperty( - property=datetime.datetime(2022, 8, 26, hour=18, minute=38) - ) - ) + await client.datetime.put(models.DatetimeProperty(property=datetime.datetime(2022, 8, 26, hour=18, minute=38))) @pytest.mark.asyncio -async def test_never_model(client: ValueTypesClient): - assert await client.never.get() == models.NeverProperty() - await client.never.put(models.NeverProperty()) +async def test_decimal(client: ValueTypesClient): + body = models.DecimalProperty(property=decimal.Decimal("0.33333")) + assert body.property == decimal.Decimal("0.33333") + assert body["property"] == 0.33333 + resp = await client.decimal.get() + assert resp.property == decimal.Decimal("0.33333") + assert resp["property"] == 0.33333 @pytest.mark.asyncio -async def test_model_deserialization(client: ValueTypesClient): +async def test_decimal128(client: ValueTypesClient): + body = models.Decimal128Property(property=decimal.Decimal("0.33333")) + assert body.property == decimal.Decimal("0.33333") + assert body["property"] == 0.33333 + resp = await client.decimal128.get() + assert resp.property == decimal.Decimal("0.33333") + assert resp["property"] == 0.33333 + + +@pytest.mark.asyncio +async def test_dictionary_string(client: ValueTypesClient): + body = models.DictionaryStringProperty(property={"k1": "hello", "k2": "world"}) + assert body.property == body["property"] + resp = await client.dictionary_string.get() + assert resp.property == resp["property"] == {"k1": "hello", "k2": "world"} + + +@pytest.mark.asyncio +async def test_duration(client: ValueTypesClient): + body = models.DurationProperty(property="P123DT22H14M12.011S") + assert body.property == datetime.timedelta(days=123, seconds=80052, microseconds=11000) + assert body["property"] == "P123DT22H14M12.011S" + resp = await client.duration.get() + assert resp.property == datetime.timedelta(days=123, seconds=80052, microseconds=11000) + assert resp["property"] == "P123DT22H14M12.011S" + + +@pytest.mark.asyncio +async def test_enum(client: ValueTypesClient): + body = models.EnumProperty(property=models.InnerEnum.VALUE_ONE) + assert body.property == body["property"] + resp = await client.enum.get() + assert resp.property == resp["property"] == "ValueOne" + + +@pytest.mark.asyncio +async def test_extensible_enum(client: ValueTypesClient): + body = models.ExtensibleEnumProperty(property="UnknownValue") + assert body.property == body["property"] + resp = await client.extensible_enum.get() + assert resp.property == resp["property"] == "UnknownValue" + + +@pytest.mark.asyncio +async def test_float(client: ValueTypesClient): + body = models.FloatProperty(property=43.125) + assert body.property == body["property"] + resp = await client.float.get() + assert resp.property == resp["property"] == 43.125 + + +@pytest.mark.asyncio +async def test_float_literal(client: ValueTypesClient): + body = models.FloatLiteralProperty(property=43.125) + assert body.property == body["property"] + resp = await client.float_literal.get() + assert resp.property == resp["property"] == 43.125 + + +@pytest.mark.asyncio +async def test_int(client: ValueTypesClient): + body = models.IntProperty(property=42) + assert body.property == body["property"] + resp = await client.int_operations.get() + assert resp.property == resp["property"] == 42 + + +@pytest.mark.asyncio +async def test_int_literal(client: ValueTypesClient): + body = models.IntLiteralProperty(property=42) + assert body.property == body["property"] + resp = await client.int_literal.get() + assert resp.property == resp["property"] == 42 + + +@pytest.mark.asyncio +async def test_model(client: ValueTypesClient): body = models.ModelProperty(property={"property": "hello"}) assert body.property.property == body["property"]["property"] resp = await client.model.get() assert resp.property.property == resp["property"]["property"] - body = models.CollectionsModelProperty( - property=[{"property": "hello"}, {"property": "world"}] - ) - assert body.property[0].property == body["property"][0]["property"] - resp = await client.collections_model.get() - assert resp.property[1].property == resp["property"][1]["property"] + +@pytest.mark.asyncio +async def test_never(client: ValueTypesClient): + assert await client.never.get() == models.NeverProperty() + await client.never.put(models.NeverProperty()) + + +@pytest.mark.asyncio +async def test_string(client: ValueTypesClient): + body = models.StringProperty(property="hello") + assert body.property == body["property"] + resp = await client.string.get() + assert resp.property == resp["property"] == "hello" + + +@pytest.mark.asyncio +async def test_string_literal(client: ValueTypesClient): + body = models.StringLiteralProperty(property="hello") + assert body.property == body["property"] + resp = await client.string_literal.get() + assert resp.property == resp["property"] == "hello" + + +@pytest.mark.asyncio +async def test_union_enum_value(client: ValueTypesClient): + body = models.UnionEnumValueProperty(property=models.ExtendedEnum.ENUM_VALUE2) + assert body.property == body["property"] + resp = await client.union_enum_value.get() + assert resp.property == resp["property"] == "value2" + + +@pytest.mark.asyncio +async def test_union_float_literal(client: ValueTypesClient): + body = models.UnionFloatLiteralProperty(property=46.875) + assert body.property == body["property"] + resp = await client.union_float_literal.get() + assert resp.property == resp["property"] == 46.875 + + +@pytest.mark.asyncio +async def test_union_int_literal(client: ValueTypesClient): + body = models.UnionIntLiteralProperty(property=42) + assert body.property == body["property"] + resp = await client.union_int_literal.get() + assert resp.property == resp["property"] == 42 + + +@pytest.mark.asyncio +async def test_union_string_literal(client: ValueTypesClient): + body = models.UnionStringLiteralProperty(property="world") + assert body.property == body["property"] + resp = await client.union_string_literal.get() + assert resp.property == resp["property"] == "world" + + +@pytest.mark.asyncio +async def test_unknown_array(client: ValueTypesClient): + body = models.UnknownArrayProperty(property=["hello", "world"]) + assert body.property == body["property"] + resp = await client.unknown_array.get() + assert resp.property == resp["property"] == ["hello", "world"] + + +@pytest.mark.asyncio +async def test_unknown_dict(client: ValueTypesClient): + body = models.UnknownDictProperty(property={"k1": "hello", "k2": 42}) + assert body.property == body["property"] + resp = await client.unknown_dict.get() + assert resp.property == resp["property"] == {"k1": "hello", "k2": 42} + + +@pytest.mark.asyncio +async def test_unknown_int(client: ValueTypesClient): + body = models.UnknownIntProperty(property=42) + assert body.property == body["property"] + resp = await client.unknown_int.get() + assert resp.property == resp["property"] == 42 + + +@pytest.mark.asyncio +async def test_unknown_string(client: ValueTypesClient): + body = models.UnknownStringProperty(property="hello") + assert body.property == body["property"] + resp = await client.unknown_string.get() + assert resp.property == resp["property"] == "hello" diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_scalar_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_scalar_async.py index 99f75c78f5..3e2b308f8b 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_scalar_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_scalar_async.py @@ -16,45 +16,45 @@ async def client(): yield client -@pytest.mark.parametrize( - "og_name,val", - [ - ("string", "test"), - ("boolean", True), - ("unknown", "test"), - ], -) @pytest.mark.asyncio -async def test_scalar(client: ScalarClient, og_name: str, val: dict): - og_group = getattr(client, og_name) - assert await og_group.get() == val - await og_group.put(val) - - -@pytest.mark.parametrize( - "og_name,val", - [ - ("decimal_type", decimal.Decimal("0.33333")), - ("decimal128_type", decimal.Decimal("0.33333")), - ], -) +async def test_scalar_string(client: ScalarClient): + assert await client.string.get() == "test" + await client.string.put("test") + + +@pytest.mark.asyncio +async def test_scalar_boolean(client: ScalarClient): + assert await client.boolean.get() == True + await client.boolean.put(True) + + +@pytest.mark.asyncio +async def test_scalar_unknown(client: ScalarClient): + assert await client.unknown.get() == "test" + await client.unknown.put("test") + + @pytest.mark.asyncio -async def test_type(client: ScalarClient, og_name: str, val): - og_group = getattr(client, og_name) - assert await og_group.response_body() == val - await og_group.request_body(val) - await og_group.request_parameter(value=val) - - -@pytest.mark.parametrize( - "og_name", - [ - "decimal_verify", - "decimal128_verify", - ], -) +async def test_decimal128_type(client: ScalarClient): + assert await client.decimal128_type.response_body() == decimal.Decimal("0.33333") + await client.decimal128_type.request_body(decimal.Decimal("0.33333")) + await client.decimal128_type.request_parameter(value=decimal.Decimal("0.33333")) + + +@pytest.mark.asyncio +async def test_decimal_type(client: ScalarClient): + assert await client.decimal_type.response_body() == decimal.Decimal("0.33333") + await client.decimal_type.request_body(decimal.Decimal("0.33333")) + await client.decimal_type.request_parameter(value=decimal.Decimal("0.33333")) + + +@pytest.mark.asyncio +async def test_decimal128_verify(client: ScalarClient): + prepare = await client.decimal128_verify.prepare_verify() + await client.decimal128_verify.verify(reduce(lambda x, y: x + y, prepare)) + + @pytest.mark.asyncio -async def test_verify(client: ScalarClient, og_name: str): - og_group = getattr(client, og_name) - prepare = await og_group.prepare_verify() - await og_group.verify(reduce(lambda x, y: x + y, prepare)) +async def test_decimal_verify(client: ScalarClient): + prepare = await client.decimal_verify.prepare_verify() + await client.decimal_verify.verify(reduce(lambda x, y: x + y, prepare)) diff --git a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_union_async.py b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_union_async.py index a526eb9a33..9e738701f4 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_union_async.py +++ b/packages/typespec-python/test/generic_mock_api_tests/asynctests/test_typetest_union_async.py @@ -3,7 +3,6 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- -from typing import Any, Type import pytest from typetest.union.aio import UnionClient from typetest.union import models @@ -15,53 +14,77 @@ async def client(): yield client -@pytest.mark.parametrize( - "og_name,value,res_model_type", - [ - ("strings_only", "b", models.GetResponse), - ("string_extensible", "custom", models.GetResponse1), - ("string_extensible_named", "custom", models.GetResponse2), - ("ints_only", 2, models.GetResponse3), - ("floats_only", 2.2, models.GetResponse4), - ("models_only", models.Cat(name="test"), models.GetResponse5), - ( - "enums_only", - models.EnumsOnlyCases(lr="right", ud="up"), - models.GetResponse6, - ), - ( - "string_and_array", - models.StringAndArrayCases(string="test", array=["test1", "test2"]), - models.GetResponse7, - ), - ( - "mixed_literals", - models.MixedLiteralsCases( - string_literal="a", - int_literal=2, - float_literal=3.3, - boolean_literal=True, - ), - models.GetResponse8, - ), - ( - "mixed_types", - models.MixedTypesCases( - model=models.Cat(name="test"), - literal="a", - int_property=2, - boolean=True, - array=[models.Cat(name="test"), "a", 2, True], - ), - models.GetResponse9, - ), - ], -) @pytest.mark.asyncio -async def test_union( - client: UnionClient, og_name: str, value: Any, res_model_type: Type -): - og_group = getattr(client, og_name) - assert await og_group.get() == res_model_type(prop=value) - await og_group.send(prop=value) - await og_group.send({"prop": value}) +async def test_enums_only(client: UnionClient): + value = models.EnumsOnlyCases(lr="right", ud="up") + assert (await client.enums_only.get()) == {"prop": value} + await client.enums_only.send(prop=value) + + +@pytest.mark.asyncio +async def test_floats_only(client: UnionClient): + value = 2.2 + assert (await client.floats_only.get()) == {"prop": value} + await client.floats_only.send(prop=value) + + +@pytest.mark.asyncio +async def test_ints_only(client: UnionClient): + value = 2 + assert (await client.ints_only.get()) == {"prop": value} + await client.ints_only.send(prop=value) + + +@pytest.mark.asyncio +async def test_mixed_literals(client: UnionClient): + value = models.MixedLiteralsCases(string_literal="a", int_literal=2, float_literal=3.3, boolean_literal=True) + assert (await client.mixed_literals.get()) == {"prop": value} + await client.mixed_literals.send(prop=value) + + +@pytest.mark.asyncio +async def test_mixed_types(client: UnionClient): + value = models.MixedTypesCases( + model=models.Cat(name="test"), + literal="a", + int_property=2, + boolean=True, + array=[models.Cat(name="test"), "a", 2, True], + ) + assert (await client.mixed_types.get()) == {"prop": value} + await client.mixed_types.send(prop=value) + + +@pytest.mark.asyncio +async def test_models_only(client: UnionClient): + value = models.Cat(name="test") + assert (await client.models_only.get()) == {"prop": value} + await client.models_only.send(prop=value) + + +@pytest.mark.asyncio +async def test_string_and_array(client: UnionClient): + value = models.StringAndArrayCases(string="test", array=["test1", "test2"]) + assert (await client.string_and_array.get()) == {"prop": value} + await client.string_and_array.send(prop=value) + + +@pytest.mark.asyncio +async def test_string_extensible(client: UnionClient): + value = "custom" + assert (await client.string_extensible.get()) == {"prop": value} + await client.string_extensible.send(prop=value) + + +@pytest.mark.asyncio +async def test_string_extensible_named(client: UnionClient): + value = "custom" + assert (await client.string_extensible_named.get()) == {"prop": value} + await client.string_extensible_named.send(prop=value) + + +@pytest.mark.asyncio +async def test_strings_only(client: UnionClient): + value = "b" + assert (await client.strings_only.get()) == {"prop": value} + await client.strings_only.send(prop=value) diff --git a/packages/typespec-python/test/generic_mock_api_tests/conftest.py b/packages/typespec-python/test/generic_mock_api_tests/conftest.py index 6d4f4bdfa6..53eb50e2bb 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/conftest.py +++ b/packages/typespec-python/test/generic_mock_api_tests/conftest.py @@ -13,6 +13,7 @@ FILE_FOLDER = Path(__file__).parent + def start_server_process(): path = Path(os.path.dirname(__file__)) / Path("../../node_modules/@azure-tools/cadl-ranch-specs") os.chdir(path.resolve()) @@ -21,12 +22,14 @@ def start_server_process(): return subprocess.Popen(cmd, shell=True) return subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid) + def terminate_server_process(process): - if os.name == 'nt': + if os.name == "nt": process.kill() else: os.killpg(os.getpgid(process.pid), signal.SIGTERM) # Send the signal to all the process groups + @pytest.fixture(scope="session", autouse=True) def testserver(): """Start cadl ranch mock api tests""" @@ -34,9 +37,12 @@ def testserver(): yield terminate_server_process(server) + """ Use to disambiguate the core library we use """ + + @pytest.fixture def core_library(): try: @@ -44,6 +50,7 @@ def core_library(): except ModuleNotFoundError: return importlib.import_module("corehttp") + @pytest.fixture def key_credential(core_library): try: @@ -51,6 +58,7 @@ def key_credential(core_library): except AttributeError: return core_library.credentials.ServiceKeyCredential + SPECIAL_WORDS = [ "and", "as", @@ -87,15 +95,18 @@ def key_credential(core_library): "yield", ] + @pytest.fixture def special_words() -> List[str]: return SPECIAL_WORDS + @pytest.fixture def png_data() -> bytes: with open(str(FILE_FOLDER / "data/image.png"), "rb") as file_in: return file_in.read() + @pytest.fixture def jpg_data() -> bytes: with open(str(FILE_FOLDER / "data/image.jpg"), "rb") as file_in: diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_client_naming.py b/packages/typespec-python/test/generic_mock_api_tests/test_client_naming.py index e745a623fb..e5e37fd20f 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_client_naming.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_client_naming.py @@ -22,9 +22,7 @@ def test_language(client: NamingClient): def test_compatible_with_encoded_name(client: NamingClient): - client.compatible_with_encoded_name( - models.ClientNameAndJsonEncodedNameModel(client_name=True) - ) + client.compatible_with_encoded_name(models.ClientNameAndJsonEncodedNameModel(client_name=True)) def test_operation(client: NamingClient): diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_client_structure.py b/packages/typespec-python/test/generic_mock_api_tests/test_client_structure.py index 8572d0f092..d28827376c 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_client_structure.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_client_structure.py @@ -22,6 +22,7 @@ def test_structure_default(): client.qux.eight() client.qux.bar.nine() + def test_structure_multiclient(): client_a = ClientAClient(endpoint="http://localhost:3000", client=ClientType.MULTI_CLIENT) client_a.renamed_one() @@ -33,6 +34,7 @@ def test_structure_multiclient(): client_b.renamed_four() client_b.renamed_six() + def test_structure_renamed_operation(): client = RenamedOperationClient(endpoint="http://localhost:3000", client=ClientType.RENAMED_OPERATION) client.renamed_one() @@ -43,6 +45,7 @@ def test_structure_renamed_operation(): client.group.renamed_four() client.group.renamed_six() + def test_structure_two_operation_group(): client = TwoOperationGroupClient(endpoint="http://localhost:3000", client=ClientType.TWO_OPERATION_GROUP) client.group1.one() diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_encode_bytes.py b/packages/typespec-python/test/generic_mock_api_tests/test_encode_bytes.py index f9277dd740..e818aa7690 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_encode_bytes.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_encode_bytes.py @@ -102,11 +102,22 @@ def png_data() -> bytes: def test_request_body(client: BytesClient, png_data: bytes): - client.request_body.default(value=bytes("test", "utf-8"), ) - client.request_body.octet_stream(value=png_data, ) - client.request_body.custom_content_type(value=png_data, ) - client.request_body.base64(value=bytes("test", "utf-8"), ) - client.request_body.base64url(value=bytes("test", "utf-8"), ) + client.request_body.default( + value=bytes("test", "utf-8"), + ) + client.request_body.octet_stream( + value=png_data, + ) + client.request_body.custom_content_type( + value=png_data, + ) + client.request_body.base64( + value=bytes("test", "utf-8"), + ) + client.request_body.base64url( + value=bytes("test", "utf-8"), + ) + def test_response_body(client: BytesClient, png_data: bytes): expected = b"test" diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_encode_datetime.py b/packages/typespec-python/test/generic_mock_api_tests/test_encode_datetime.py index 1819e1b5bc..46b32f9734 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_encode_datetime.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_encode_datetime.py @@ -46,54 +46,36 @@ def test_query(client: DatetimeClient): def test_property(client: DatetimeClient): result = client.property.default( DefaultDatetimeProperty( - value=datetime.datetime( - 2022, 8, 26, 18, 38, 0, tzinfo=datetime.timezone.utc - ), + value=datetime.datetime(2022, 8, 26, 18, 38, 0, tzinfo=datetime.timezone.utc), ) ) - assert result.value == datetime.datetime( - 2022, 8, 26, 18, 38, 0, tzinfo=datetime.timezone.utc - ) + assert result.value == datetime.datetime(2022, 8, 26, 18, 38, 0, tzinfo=datetime.timezone.utc) result = client.property.rfc3339( Rfc3339DatetimeProperty( - value=datetime.datetime( - 2022, 8, 26, 18, 38, 0, tzinfo=datetime.timezone.utc - ), + value=datetime.datetime(2022, 8, 26, 18, 38, 0, tzinfo=datetime.timezone.utc), ) ) - assert result.value == datetime.datetime( - 2022, 8, 26, 18, 38, 0, tzinfo=datetime.timezone.utc - ) + assert result.value == datetime.datetime(2022, 8, 26, 18, 38, 0, tzinfo=datetime.timezone.utc) result = client.property.rfc7231( Rfc7231DatetimeProperty( - value=datetime.datetime( - 2022, 8, 26, 14, 38, 0, tzinfo=datetime.timezone.utc - ), + value=datetime.datetime(2022, 8, 26, 14, 38, 0, tzinfo=datetime.timezone.utc), ) ) - assert result.value == datetime.datetime( - 2022, 8, 26, 14, 38, 0, tzinfo=datetime.timezone.utc - ) + assert result.value == datetime.datetime(2022, 8, 26, 14, 38, 0, tzinfo=datetime.timezone.utc) result = client.property.unix_timestamp( UnixTimestampDatetimeProperty( - value=datetime.datetime( - 2023, 6, 12, 10, 47, 44, tzinfo=datetime.timezone.utc - ), + value=datetime.datetime(2023, 6, 12, 10, 47, 44, tzinfo=datetime.timezone.utc), ) ) - assert result.value == datetime.datetime( - 2023, 6, 12, 10, 47, 44, tzinfo=datetime.timezone.utc - ) + assert result.value == datetime.datetime(2023, 6, 12, 10, 47, 44, tzinfo=datetime.timezone.utc) result = client.property.unix_timestamp_array( UnixTimestampArrayDatetimeProperty( value=[ - datetime.datetime( - 2023, 6, 12, 10, 47, 44, tzinfo=datetime.timezone.utc - ), + datetime.datetime(2023, 6, 12, 10, 47, 44, tzinfo=datetime.timezone.utc), datetime.datetime(2023, 6, 14, 9, 17, 36, tzinfo=datetime.timezone.utc), ], ) @@ -124,9 +106,18 @@ def test_header(client: DatetimeClient): ] ) + def test_response_header(client: DatetimeClient): cls = lambda x, y, z: z - assert client.response_header.default(cls=cls)["value"] == datetime.datetime(2022, 8, 26, 14, 38, 0, tzinfo=datetime.timezone.utc) - assert client.response_header.rfc3339(cls=cls)["value"] == datetime.datetime(2022, 8, 26, 18, 38, 0, tzinfo=datetime.timezone.utc) - assert client.response_header.rfc7231(cls=cls)["value"] == datetime.datetime(2022, 8, 26, 14, 38, 0, tzinfo=datetime.timezone.utc) - assert client.response_header.unix_timestamp(cls=cls)["value"] == datetime.datetime(2023, 6, 12, 10, 47, 44, tzinfo=datetime.timezone.utc) + assert client.response_header.default(cls=cls)["value"] == datetime.datetime( + 2022, 8, 26, 14, 38, 0, tzinfo=datetime.timezone.utc + ) + assert client.response_header.rfc3339(cls=cls)["value"] == datetime.datetime( + 2022, 8, 26, 18, 38, 0, tzinfo=datetime.timezone.utc + ) + assert client.response_header.rfc7231(cls=cls)["value"] == datetime.datetime( + 2022, 8, 26, 14, 38, 0, tzinfo=datetime.timezone.utc + ) + assert client.response_header.unix_timestamp(cls=cls)["value"] == datetime.datetime( + 2023, 6, 12, 10, 47, 44, tzinfo=datetime.timezone.utc + ) diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_encode_duration.py b/packages/typespec-python/test/generic_mock_api_tests/test_encode_duration.py index c56f40b19c..affb841462 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_encode_duration.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_encode_duration.py @@ -31,15 +31,11 @@ def test_query(client: DurationClient): def test_property(client: DurationClient): - result = client.property.default( - DefaultDurationProperty(value=datetime.timedelta(days=40)) - ) + result = client.property.default(DefaultDurationProperty(value=datetime.timedelta(days=40))) assert result.value == datetime.timedelta(days=40) result = client.property.default(DefaultDurationProperty(value="P40D")) assert result.value == datetime.timedelta(days=40) - result = client.property.iso8601( - ISO8601DurationProperty(value=datetime.timedelta(days=40)) - ) + result = client.property.iso8601(ISO8601DurationProperty(value=datetime.timedelta(days=40))) assert result.value == datetime.timedelta(days=40) result = client.property.iso8601(ISO8601DurationProperty(value="P40D")) assert result.value == datetime.timedelta(days=40) @@ -47,9 +43,7 @@ def test_property(client: DurationClient): assert result.value == 36 result = client.property.float_seconds(FloatSecondsDurationProperty(value=35.621)) assert abs(result.value - 35.621) < 0.0001 - result = client.property.float_seconds_array( - FloatSecondsDurationArrayProperty(value=[35.621, 46.781]) - ) + result = client.property.float_seconds_array(FloatSecondsDurationArrayProperty(value=[35.621, 46.781])) assert abs(result.value[0] - 35.621) < 0.0001 assert abs(result.value[1] - 46.781) < 0.0001 diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_headasboolean.py b/packages/typespec-python/test/generic_mock_api_tests/test_headasboolean.py index 7558507413..a8c5db102b 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_headasboolean.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_headasboolean.py @@ -10,20 +10,24 @@ from headasbooleanfalse import VisibilityClient as HeadAsBooleanFalseClient from headasbooleanfalse import models as models_false + @pytest.fixture def client_true(): with HeadAsBooleanTrueClient() as client: yield client + @pytest.fixture def client_false(): with HeadAsBooleanFalseClient() as client: yield client + def test_head_true(client_true): body = models_true.VisibilityModel(query_prop=123) assert client_true.head_model(body) == True + def test_head_false(client_false): body = models_false.VisibilityModel(query_prop=123) assert client_false.head_model(body) is None diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_payload_content_negotiation.py b/packages/typespec-python/test/generic_mock_api_tests/test_payload_content_negotiation.py index fb49830d81..27fa1ba25f 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_payload_content_negotiation.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_payload_content_negotiation.py @@ -14,15 +14,19 @@ def client(): with ContentNegotiationClient(endpoint="http://localhost:3000") as client: yield client + def test_get_avatar_as_png(client: ContentNegotiationClient, png_data: bytes): assert b"".join(client.same_body.get_avatar_as_png()) == png_data + def test_get_avatar_as_jpeg(client: ContentNegotiationClient, jpg_data: bytes): assert b"".join(client.same_body.get_avatar_as_jpeg()) == jpg_data + def test_different_body_get_avatar_as_png(client: ContentNegotiationClient, png_data: bytes): assert b"".join(client.different_body.get_avatar_as_png()) == png_data + def test_different_body_get_avatar_as_json(client: ContentNegotiationClient, png_data: bytes): result = client.different_body.get_avatar_as_json() expected = PngImageAsJson(content=base64.b64encode(png_data).decode()) diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_payload_json_merge_patch.py b/packages/typespec-python/test/generic_mock_api_tests/test_payload_json_merge_patch.py index 954c772081..af0a9afea8 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_payload_json_merge_patch.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_payload_json_merge_patch.py @@ -8,9 +8,9 @@ from payload.jsonmergepatch.models import InnerModel, Resource, ResourcePatch try: - from azure.core.serialization import NULL as CoreNull + from azure.core.serialization import NULL except ImportError: - from corehttp.serialization import NULL as CoreNull + from corehttp.serialization import NULL @pytest.fixture @@ -19,67 +19,75 @@ def client(): yield client -INNER_MADGE = InnerModel(name="InnerMadge", description="innerDesc") -CREATE_RESOURCE = Resource( - name="Madge", - description="desc", - map={"key": INNER_MADGE}, - array=[INNER_MADGE], - int_value=1, - float_value=1.1, - inner_model=INNER_MADGE, - int_array=[1, 2, 3], -) -UPDATE_RESOURCE_REQ = ResourcePatch( - description=CoreNull, - map={"key": InnerModel(description=CoreNull), "key2": CoreNull}, - array=CoreNull, - int_value=CoreNull, - float_value=CoreNull, - inner_model=CoreNull, - int_array=CoreNull, -) -UPDATE_RESOURCE_RAW_REQ = { - "description": None, - "map": {"key": {"description": None}, "key2": None}, - "array": None, - "intValue": None, - "floatValue": None, - "innerModel": None, - "intArray": None, -} -UPDATE_RESOURCE_EXPECTED = Resource( - name="Madge", - map={"key": InnerModel(name="InnerMadge")}, -) +def test_create_resource(client: JsonMergePatchClient): + inner_madge = InnerModel(name="InnerMadge", description="innerDesc") + create_resource = Resource( + name="Madge", + description="desc", + map={"key": inner_madge}, + array=[inner_madge], + int_value=1, + float_value=1.1, + inner_model=inner_madge, + int_array=[1, 2, 3], + ) + response = client.create_resource(create_resource) + assert response == create_resource -@pytest.mark.parametrize( - "op,req,expected", - [ - ("create_resource", CREATE_RESOURCE, CREATE_RESOURCE), - ( - "update_resource", - UPDATE_RESOURCE_REQ, - UPDATE_RESOURCE_EXPECTED, - ), - ( - "update_resource", - UPDATE_RESOURCE_RAW_REQ, - UPDATE_RESOURCE_EXPECTED, - ), - ( - "update_optional_resource", - UPDATE_RESOURCE_REQ, - UPDATE_RESOURCE_EXPECTED, - ), - ( - "update_optional_resource", - UPDATE_RESOURCE_RAW_REQ, - UPDATE_RESOURCE_EXPECTED, - ), - ], -) -def test_json_merge_patch(client: JsonMergePatchClient, op, req, expected): - response = getattr(client, op)(req) - assert response == expected +def test_update_resource_model_input(client: JsonMergePatchClient): + update_resource = ResourcePatch( + description=NULL, + map={"key": InnerModel(description=NULL), "key2": NULL}, + array=NULL, + int_value=NULL, + float_value=NULL, + inner_model=NULL, + int_array=NULL, + ) + response = client.update_resource(update_resource) + assert response == Resource(name="Madge", map={"key": InnerModel(name="InnerMadge")}) + + +def test_update_resource_raw_input(client: JsonMergePatchClient): + response = client.update_resource( + { + "description": None, + "map": {"key": {"description": None}, "key2": None}, + "array": None, + "intValue": None, + "floatValue": None, + "innerModel": None, + "intArray": None, + } + ) + assert response == Resource(name="Madge", map={"key": InnerModel(name="InnerMadge")}) + + +def test_update_optional_resource_model_input(client: JsonMergePatchClient): + update_resource = ResourcePatch( + description=NULL, + map={"key": InnerModel(description=NULL), "key2": NULL}, + array=NULL, + int_value=NULL, + float_value=NULL, + inner_model=NULL, + int_array=NULL, + ) + response = client.update_optional_resource(update_resource) + assert response == Resource(name="Madge", map={"key": InnerModel(name="InnerMadge")}) + + +def test_update_optional_resource_raw_input(client: JsonMergePatchClient): + response = client.update_optional_resource( + { + "description": None, + "map": {"key": {"description": None}, "key2": None}, + "array": None, + "intValue": None, + "floatValue": None, + "innerModel": None, + "intArray": None, + } + ) + assert response == Resource(name="Madge", map={"key": InnerModel(name="InnerMadge")}) diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_payload_media_type.py b/packages/typespec-python/test/generic_mock_api_tests/test_payload_media_type.py index b162cd83ff..72bc9425fc 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_payload_media_type.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_payload_media_type.py @@ -6,16 +6,19 @@ import pytest from payload.mediatype import MediaTypeClient + @pytest.fixture def client(): with MediaTypeClient(endpoint="http://localhost:3000") as client: yield client + def test_json(client: MediaTypeClient): data = "foo" client.string_body.send_as_json(data) assert client.string_body.get_as_json() == data + def test_text(client: MediaTypeClient): data = "{cat}" client.string_body.send_as_text(data) diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_payload_multipart.py b/packages/typespec-python/test/generic_mock_api_tests/test_payload_multipart.py index b54be07e1d..370a81ec63 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_payload_multipart.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_payload_multipart.py @@ -3,12 +3,9 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- -import uuid -from typing import Dict, Any, Type from pathlib import Path import pytest from payload.multipart import MultiPartClient, models -from payload.multipart._model_base import Model JPG = Path(__file__).parent / "data/image.jpg" PNG = Path(__file__).parent / "data/image.png" @@ -20,136 +17,83 @@ def client(): yield client -@pytest.mark.parametrize( - "op_name,model_class,data,file,file_info", - [ - ("basic", models.MultiPartRequest, {"id": "123"}, {"profileImage": JPG}, {}), - ( - "multi_binary_parts", - models.MultiBinaryPartsRequest, - {}, - {"profileImage": JPG, "picture": PNG}, - {} - ), - ( - "multi_binary_parts", - models.MultiBinaryPartsRequest, - {}, - {"profileImage": JPG}, - {} - ), - ( - "json_part", - models.JsonPartRequest, - {"address": models.Address(city="X")}, - {"profileImage": JPG}, - {}, - ), - ( - "json_array_parts", - models.JsonArrayPartsRequest, - {"previousAddresses": [models.Address(city="Y"), models.Address(city="Z")]}, - {"profileImage": JPG}, - {}, - ), - ( - "binary_array_parts", - models.BinaryArrayPartsRequest, - {"id": "123"}, - {"pictures": [PNG, PNG]}, - {}, - ), - ( - "complex", - models.ComplexPartsRequest, - {"id": "123", "previousAddresses": [models.Address(city="Y"), models.Address(city="Z")], "address": models.Address(city="X")}, - {"pictures": [PNG, PNG], "profileImage": JPG}, - {}, - ), - ( - "check_file_name_and_content_type", - models.MultiPartRequest, - {"id": "123"}, - {"profileImage": JPG}, - {"content_type": "image/jpg", "file_name": "hello.jpg"}, - ), - ( - "anonymous_model", - dict, - {}, - {"profileImage": JPG}, - {}, - ), - ], -) -def test_multi_part(client: MultiPartClient, op_name, model_class, data, file, file_info): - def add_info(file_path, is_bytes): - file_content = open(str(file_path), "rb").read() if is_bytes else open(str(file_path), "rb") - name = str(uuid.uuid4()) if file_info.get("file_name") is None else file_info.get("file_name") - content_type = "application/octet-stream" if file_info.get("content_type") is None else file_info.get("content_type") - return (name, file_content, content_type) - def convert(is_bytes=False): - files_part = {k: ([add_info(vi, is_bytes) for vi in v] if isinstance(v, list) else add_info(v, is_bytes)) for k, v in file.items()} - files_part.update(data) - return files_part - op = getattr(client.form_data, op_name) - # test bytes (raw dict) - body = convert(True) - op(body) - - # test io (raw dict) - body = convert() - op(body) - - # test bytes (model) - body = convert(True) - op(model_class(body)) - - # test io (model) - body = convert() - op(model_class(body)) - -def _test_sample_single_file(client: MultiPartClient): - # Python SDK support several kinds of file format for multipart/form-data and users can choose any of them - # 1. bytes - client.form_data.basic({"id": "123", "profileImage": open(str(PNG), "rb").read()}) - - # 2. file io - client.form_data.basic({"id": "123", "profileImage": open(str(PNG), "rb")}) - - # 3. file tuple (only set file name) - client.form_data.basic({"id": "123", "profileImage": ("my_image.jpg", open(str(JPG), "rb"))}) - # or - client.form_data.basic({"id": "123", "profileImage": ("my_image.jpg", open(str(JPG), "rb").read())}) - - # 4. file tuple (set file name and content type) - client.form_data.basic({"id": "123", "profileImage": ("my_image.jpg", open(str(JPG), "rb"), "image/jpeg")}) - # or - client.form_data.basic({"id": "123", "profileImage": ("my_image.jpg", open(str(JPG), "rb").read(), "image/jpeg")}) - -def _test_sample_array_file(client: MultiPartClient): - # If users want to upload array files for same field name, they can use list, and users can - # choose any of the above file format for each file. e.g. - - # List[bytes, io] - client.form_data.binary_array_parts({"id": "123", "pictures": [open(str(PNG), "rb").read(), open(str(PNG), "rb")]}) - - # List[bytes, tuple] - client.form_data.binary_array_parts({ - "id": "123", - "pictures": [open(str(PNG), "rb").read(), ("my_image.png", open(str(PNG), "rb"))] - }) - # or - client.form_data.binary_array_parts({ - "id": "123", - "pictures": [open(str(PNG), "rb").read(), ("my_image.png", open(str(PNG), "rb"), "image/png")] - }) - # List[io, bytes] - client.form_data.binary_array_parts({"id": "123", "pictures": [open(str(PNG), "rb"), open(str(PNG), "rb").read()]}) - - # List[tuple, tuple] - client.form_data.binary_array_parts({ - "id": "123", - "pictures": [("my_image1.png", open(str(PNG), "rb"), "image/png"), ("my_image2.png", open(str(PNG), "rb"), "image/png")] - }) - # ... +def test_anonymous_model(client: MultiPartClient): + client.form_data.anonymous_model({"profileImage": open(str(JPG), "rb")}) + + +def test_basic(client: MultiPartClient): + client.form_data.basic( + models.MultiPartRequest( + id="123", + profile_image=open(str(JPG), "rb"), + ) + ) + + +def test_binary_array_parts(client: MultiPartClient): + client.form_data.binary_array_parts( + models.BinaryArrayPartsRequest( + id="123", + pictures=[ + open(str(PNG), "rb"), + open(str(PNG), "rb"), + ], + ) + ) + + +def test_check_file_name_and_content_type(client: MultiPartClient): + client.form_data.check_file_name_and_content_type( + models.MultiPartRequest( + id="123", + profile_image=("hello.jpg", open(str(JPG), "rb"), "image/jpg"), + ) + ) + + +def test_complex(client: MultiPartClient): + client.form_data.complex( + models.ComplexPartsRequest( + id="123", + previous_addresses=[ + models.Address(city="Y"), + models.Address(city="Z"), + ], + address=models.Address(city="X"), + pictures=[ + open(str(PNG), "rb"), + open(str(PNG), "rb"), + ], + profile_image=open(str(JPG), "rb"), + ) + ) + + +def test_json_array_parts(client: MultiPartClient): + client.form_data.json_array_parts( + models.JsonArrayPartsRequest( + previous_addresses=[ + models.Address(city="Y"), + models.Address(city="Z"), + ], + profile_image=open(str(JPG), "rb"), + ) + ) + + +def test_json_part(client: MultiPartClient): + client.form_data.json_part( + models.JsonPartRequest( + address=models.Address(city="X"), + profile_image=open(str(JPG), "rb"), + ) + ) + + +def test_multi_binary_parts(client: MultiPartClient): + client.form_data.multi_binary_parts( + models.MultiBinaryPartsRequest( + profile_image=open(str(JPG), "rb"), + picture=open(str(PNG), "rb"), + ) + ) diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_payload_pageable.py b/packages/typespec-python/test/generic_mock_api_tests/test_payload_pageable.py index eb2f9b615e..a13109a38c 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_payload_pageable.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_payload_pageable.py @@ -12,6 +12,7 @@ def client(): with PageableClient(endpoint="http://localhost:3000") as client: yield client + def test_list(client: PageableClient): result = list(client.list(maxpagesize=3)) assert len(result) == 4 diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_resiliency_srv_driven.py b/packages/typespec-python/test/generic_mock_api_tests/test_resiliency_srv_driven.py index 03c7819bf0..f2a69c81d3 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_resiliency_srv_driven.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_resiliency_srv_driven.py @@ -7,11 +7,18 @@ from resiliency.srv.driven1 import ResiliencyServiceDrivenClient as V1Client from resiliency.srv.driven2 import ResiliencyServiceDrivenClient as V2Client + def get_v1_client(service_deployment_version: str, api_version: str = "v1") -> V1Client: - return V1Client(endpoint="http://localhost:3000", service_deployment_version=service_deployment_version, api_version=api_version) + return V1Client( + endpoint="http://localhost:3000", service_deployment_version=service_deployment_version, api_version=api_version + ) + def get_v2_client(service_deployment_version: str, api_version: str = "v2") -> V2Client: - return V2Client(endpoint="http://localhost:3000", service_deployment_version=service_deployment_version, api_version=api_version) + return V2Client( + endpoint="http://localhost:3000", service_deployment_version=service_deployment_version, api_version=api_version + ) + def test_add_optional_param_from_none(): # old client to old service with api version v1 @@ -30,6 +37,7 @@ def test_add_optional_param_from_none(): with V2Client(endpoint="http://localhost:3000", service_deployment_version="v2") as client: client.from_none(new_parameter="new") + def test_add_optional_param_from_one_required(): # old client to old service with api version v1 with V1Client(endpoint="http://localhost:3000", service_deployment_version="v1") as client: @@ -47,6 +55,7 @@ def test_add_optional_param_from_one_required(): with V2Client(endpoint="http://localhost:3000", service_deployment_version="v2") as client: client.from_one_required(parameter="required", new_parameter="new") + def test_add_optional_param_from_one_optional(): # old client to old service with api version v1 with V1Client(endpoint="http://localhost:3000", service_deployment_version="v1") as client: @@ -64,25 +73,27 @@ def test_add_optional_param_from_one_optional(): with V2Client(endpoint="http://localhost:3000", service_deployment_version="v2") as client: client.from_one_optional(parameter="optional", new_parameter="new") + def test_break_the_glass(core_library): - request = core_library.rest.HttpRequest( - method="DELETE", url="/add-operation" - ) + request = core_library.rest.HttpRequest(method="DELETE", url="/add-operation") with V1Client(endpoint="http://localhost:3000", service_deployment_version="v2", api_version="v2") as client: response = client.send_request(request) response.raise_for_status() + def test_add_operation(): with V2Client(endpoint="http://localhost:3000", service_deployment_version="v2") as client: client.add_operation() + @pytest.mark.parametrize( - "func_name, params", [ + "func_name, params", + [ ("from_none", {"new_parameter": "new"}), ("from_one_optional", {"parameter": "optional", "new_parameter": "new"}), ("from_one_required", {"parameter": "required", "new_parameter": "new"}), ("add_operation", {}), - ] + ], ) def test_new_client_with_old_apiversion_call_new_parameter(func_name, params): client = get_v2_client(service_deployment_version="v2", api_version="v1") diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_serialization_encoded_name_json.py b/packages/typespec-python/test/generic_mock_api_tests/test_serialization_encoded_name_json.py index f32be3ea13..0f61ce86f2 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_serialization_encoded_name_json.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_serialization_encoded_name_json.py @@ -19,4 +19,3 @@ def test_property_send(client: JsonClient): def test_property_get(client: JsonClient): assert client.property.get().default_name - diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_server_versions_not_versioned.py b/packages/typespec-python/test/generic_mock_api_tests/test_server_versions_not_versioned.py index aea7e6d88a..47528ab8fc 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_server_versions_not_versioned.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_server_versions_not_versioned.py @@ -16,8 +16,10 @@ def client(): def test_without_api_version(client: NotVersionedClient): client.without_api_version() + def test_with_query_api_version(client: NotVersionedClient): client.with_query_api_version() + def test_with_path_api_version(client: NotVersionedClient): client.with_path_api_version() diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_server_versions_versioned.py b/packages/typespec-python/test/generic_mock_api_tests/test_server_versions_versioned.py index addef6cb30..00b7fcd192 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_server_versions_versioned.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_server_versions_versioned.py @@ -16,12 +16,15 @@ def client(): def test_without_api_version(client: VersionedClient): client.without_api_version() + def test_with_query_api_version(client: VersionedClient): client.with_query_api_version() + def test_with_path_api_version(client: VersionedClient): client.with_path_api_version() + def test_with_query_old_api_version(): with VersionedClient(endpoint="http://localhost:3000", api_version="2021-01-01-preview") as client: client.with_query_old_api_version() diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_special_headers_conditional_request.py b/packages/typespec-python/test/generic_mock_api_tests/test_special_headers_conditional_request.py index 54c6659e8b..39da1083a8 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_special_headers_conditional_request.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_special_headers_conditional_request.py @@ -6,13 +6,16 @@ import pytest from specialheaders.conditionalrequest import ConditionalRequestClient + @pytest.fixture def client(): with ConditionalRequestClient() as client: yield client + def test_post_if_match(core_library, client: ConditionalRequestClient): client.post_if_match(etag="valid", match_condition=core_library.MatchConditions.IfNotModified) + def test_post_if_none_match(core_library, client: ConditionalRequestClient): client.post_if_none_match(etag="invalid", match_condition=core_library.MatchConditions.IfModified) diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_array.py b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_array.py index 8bcd0cf769..67288c76a5 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_array.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_array.py @@ -15,28 +15,59 @@ def client(): yield client -@pytest.mark.parametrize( - "og_name,val", - [ - ("int32_value", [1, 2]), - ("int64_value", [2**53 - 1, -(2**53 - 1)]), - ("boolean_value", [True, False]), - ("string_value", ["hello", ""]), - ("float32_value", [43.125]), - ("datetime_value", [isodate.parse_datetime("2022-08-26T18:38:00Z")]), - ("duration_value", [isodate.parse_duration("P123DT22H14M12.011S")]), - ("unknown_value", [1, "hello", None]), - ( - "model_value", - [ - models.InnerModel(property="hello"), - models.InnerModel(property="world"), - ], - ), - ("nullable_float_value", [1.25, None, 3.0]), - ], -) -def test_array(client: ArrayClient, og_name: str, val: dict): - og_group = getattr(client, og_name) - assert og_group.get() == val - og_group.put(val) +def test_boolean_value(client: ArrayClient): + assert client.boolean_value.get() == [True, False] + client.boolean_value.put([True, False]) + + +def test_datetime_value(client: ArrayClient): + assert client.datetime_value.get() == [isodate.parse_datetime("2022-08-26T18:38:00Z")] + client.datetime_value.put([isodate.parse_datetime("2022-08-26T18:38:00Z")]) + + +def test_duration_value(client: ArrayClient): + assert client.duration_value.get() == [isodate.parse_duration("P123DT22H14M12.011S")] + client.duration_value.put([isodate.parse_duration("P123DT22H14M12.011S")]) + + +def test_float32_value(client: ArrayClient): + assert client.float32_value.get() == [43.125] + client.float32_value.put([43.125]) + + +def test_int32_value(client: ArrayClient): + assert client.int32_value.get() == [1, 2] + client.int32_value.put([1, 2]) + + +def test_int64_value(client: ArrayClient): + assert client.int64_value.get() == [2**53 - 1, -(2**53 - 1)] + client.int64_value.put([2**53 - 1, -(2**53 - 1)]) + + +def test_model_value(client: ArrayClient): + assert client.model_value.get() == [ + models.InnerModel(property="hello"), + models.InnerModel(property="world"), + ] + client.model_value.put( + [ + models.InnerModel(property="hello"), + models.InnerModel(property="world"), + ] + ) + + +def test_nullable_float_value(client: ArrayClient): + assert client.nullable_float_value.get() == [1.25, None, 3.0] + client.nullable_float_value.put([1.25, None, 3.0]) + + +def test_string_value(client: ArrayClient): + assert client.string_value.get() == ["hello", ""] + client.string_value.put(["hello", ""]) + + +def test_unknown_value(client: ArrayClient): + assert client.unknown_value.get() == [1, "hello", None] + client.unknown_value.put([1, "hello", None]) diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_dictionary.py b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_dictionary.py index 9b75aaac88..f8704cf723 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_dictionary.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_dictionary.py @@ -6,33 +6,72 @@ import pytest from typetest.dictionary import DictionaryClient, models import isodate + + @pytest.fixture def client(): with DictionaryClient() as client: yield client -@pytest.mark.parametrize( - "og_name,val", [ - ("int32_value", {"k1": 1, "k2": 2}), - ("int64_value", {"k1": 2**53-1, "k2": -(2**53-1)}), - ("boolean_value", {"k1": True, "k2": False}), - ("string_value", {"k1": "hello", "k2": ""}), - ("float32_value", {"k1": 43.125}), - ("datetime_value", {"k1": isodate.parse_datetime("2022-08-26T18:38:00Z")}), - ("duration_value", {"k1": isodate.parse_duration("P123DT22H14M12.011S")}), - ("unknown_value", {"k1": 1, "k2": "hello", "k3": None}), - ("model_value", { - "k1": models.InnerModel(property="hello"), - "k2": models.InnerModel(property="world"), - }), - ("recursive_model_value", { - "k1": models.InnerModel(property="hello", children={}), - "k2": models.InnerModel(property="world", children={"k2.1": models.InnerModel(property="inner world")}), - }), - ("nullable_float_value", {"k1": 1.25, "k2": 0.5, "k3": None}), - ] -) -def test_dictionary(client: DictionaryClient, og_name: str, val: dict): - og_group = getattr(client, og_name) - assert og_group.get() == val - og_group.put(val) + +def test_boolean_value(client: DictionaryClient): + value = {"k1": True, "k2": False} + assert client.boolean_value.get() == value + client.boolean_value.put(value) + + +def test_datetime_value(client: DictionaryClient): + value = {"k1": isodate.parse_datetime("2022-08-26T18:38:00Z")} + assert client.datetime_value.get() == value + client.datetime_value.put(value) + + +def test_duration_value(client: DictionaryClient): + value = {"k1": isodate.parse_duration("P123DT22H14M12.011S")} + assert client.duration_value.get() == value + client.duration_value.put(value) + + +def test_float32_value(client: DictionaryClient): + value = {"k1": 43.125} + assert client.float32_value.get() == value + client.float32_value.put(value) + + +def test_int32_value(client: DictionaryClient): + value = {"k1": 1, "k2": 2} + assert client.int32_value.get() == value + client.int32_value.put(value) + + +def test_int64_value(client: DictionaryClient): + value = {"k1": 2**53 - 1, "k2": -(2**53 - 1)} + assert client.int64_value.get() == value + client.int64_value.put(value) + + +def test_model_value(client: DictionaryClient): + value = { + "k1": models.InnerModel(property="hello"), + "k2": models.InnerModel(property="world"), + } + assert client.model_value.get() == value + client.model_value.put(value) + + +def test_nullable_float_value(client: DictionaryClient): + value = {"k1": 1.25, "k2": 0.5, "k3": None} + assert client.nullable_float_value.get() == value + client.nullable_float_value.put(value) + + +def test_string_value(client: DictionaryClient): + value = {"k1": "hello", "k2": ""} + assert client.string_value.get() == value + client.string_value.put(value) + + +def test_unknown_value(client: DictionaryClient): + value = {"k1": 1, "k2": "hello", "k3": None} + assert client.unknown_value.get() == value + client.unknown_value.put(value) diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_enum_extensible.py b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_enum_extensible.py index 9427922d47..b6bcf593e6 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_enum_extensible.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_enum_extensible.py @@ -6,15 +6,18 @@ import pytest from typetest.enum.extensible import ExtensibleClient, models + @pytest.fixture def client(): with ExtensibleClient() as client: yield client + def test_known_value(client): assert client.string.get_known_value() == models.DaysOfWeekExtensibleEnum.MONDAY client.string.put_known_value(models.DaysOfWeekExtensibleEnum.MONDAY) + def test_unknown_value(client): assert client.string.get_unknown_value() == "Weekend" client.string.put_unknown_value("Weekend") diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_enum_fixed.py b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_enum_fixed.py index 5cf9491224..0d085d0200 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_enum_fixed.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_enum_fixed.py @@ -6,15 +6,18 @@ import pytest from typetest.enum.fixed import FixedClient, models + @pytest.fixture def client(): with FixedClient() as client: yield client + def test_known_value(client): assert client.string.get_known_value() == models.DaysOfWeekEnum.MONDAY client.string.put_known_value(models.DaysOfWeekEnum.MONDAY) + def test_unknown_value(client: FixedClient, core_library): try: client.string.put_unknown_value("Weekend") diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_model_flatten.py b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_model_flatten.py index d786635868..dcf2a642dd 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_model_flatten.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_model_flatten.py @@ -15,45 +15,23 @@ def client(): # ========== test for cadl-ranch ========== - - - -@pytest.mark.parametrize( - "op_name,reqs,reses", - [ - ( - "put_flatten_model", - [ - FlattenModel(name="foo", properties=ChildModel(age=10, description="bar")), - FlattenModel(name="foo", age=10, description="bar"), - ], - [ - FlattenModel(name="test", properties=ChildModel(age=1, description="test")), - FlattenModel(name="test", age=1, description="test"), - ], - ), - # python doesn't support nested flatten model - ( - "put_nested_flatten_model", - [ - NestedFlattenModel( - name="foo", - properties=ChildFlattenModel(summary="bar", properties=ChildModel(age=10, description="test")), - ), - ], - [ - NestedFlattenModel( - name="test", - properties=ChildFlattenModel(summary="test", properties=ChildModel(age=1, description="foo")), - ), - ], - ), - ], -) -def test_flatten(client: FlattenClient, op_name, reqs, reses): - for req in reqs: - for res in reses: - assert getattr(client, op_name)(req) == res + + +def test_put_flatten_model(client: FlattenClient): + resp = FlattenModel(name="test", properties=ChildModel(age=1, description="test")) + assert client.put_flatten_model(FlattenModel(name="foo", properties=ChildModel(age=10, description="bar"))) == resp + assert client.put_flatten_model(FlattenModel(name="foo", age=10, description="bar")) == resp + + +def test_put_nested_flatten_model(client: FlattenClient): + # python doesn't support nested flatten model + assert client.put_nested_flatten_model( + NestedFlattenModel( + name="foo", properties=ChildFlattenModel(summary="bar", properties=ChildModel(age=10, description="test")) + ) + ) == NestedFlattenModel( + name="test", properties=ChildFlattenModel(summary="test", properties=ChildModel(age=1, description="foo")) + ) # ============test for compatibility ============ diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_model_inheritance_enum_discriminator.py b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_model_inheritance_enum_discriminator.py index e284a2fbd6..b18200e0e8 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_model_inheritance_enum_discriminator.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_model_inheritance_enum_discriminator.py @@ -13,36 +13,46 @@ def client(): with EnumDiscriminatorClient() as client: yield client + @pytest.fixture def valid_body(): return models.Golden(weight=10) + @pytest.fixture def valid_fixed_body(): return models.Cobra(length=10) + def test_get_extensible_model(client: EnumDiscriminatorClient, valid_body: models.Dog): assert client.get_extensible_model() == valid_body assert isinstance(client.get_extensible_model(), models.Golden) + def test_put_extensible_model(client: EnumDiscriminatorClient, valid_body: models.Dog): client.put_extensible_model(valid_body) + def test_get_extensible_model_missing_discriminator(client: EnumDiscriminatorClient): assert client.get_extensible_model_missing_discriminator() == models.Dog(weight=10) + def test_get_extensible_model_wrong_discriminator(client: EnumDiscriminatorClient): assert client.get_extensible_model_wrong_discriminator() == models.Dog(weight=8, kind="wrongKind") + def test_get_fixed_model(client: EnumDiscriminatorClient, valid_fixed_body: models.Snake): assert client.get_fixed_model() == valid_fixed_body assert isinstance(client.get_fixed_model(), models.Cobra) + def test_put_fixed_model(client: EnumDiscriminatorClient, valid_fixed_body: models.Snake): client.put_fixed_model(valid_fixed_body) + def test_get_fixed_model_missing_discriminator(client: EnumDiscriminatorClient): assert client.get_fixed_model_missing_discriminator() == models.Snake(length=10) + def test_get_fixed_model_wrong_discriminator(client: EnumDiscriminatorClient): assert client.get_fixed_model_wrong_discriminator() == models.Snake(length=8, kind="wrongKind") diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_model_inheritance_nested_discriminator.py b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_model_inheritance_nested_discriminator.py index 9649e9fa1a..54bf5f74cf 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_model_inheritance_nested_discriminator.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_model_inheritance_nested_discriminator.py @@ -23,6 +23,7 @@ def test_get_model(client, valid_body): assert client.get_model() == valid_body assert isinstance(client.get_model(), GoblinShark) + def test_put_model(client, valid_body): client.put_model(valid_body) diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_model_inheritance_not_discriminated.py b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_model_inheritance_not_discriminated.py index e04fd57347..d21f55c20c 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_model_inheritance_not_discriminated.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_model_inheritance_not_discriminated.py @@ -26,5 +26,6 @@ def test_get_valid(client, valid_body): def test_post_valid(client, valid_body): client.post_valid(valid_body) + def test_put_valid(client, valid_body): assert valid_body == client.put_valid(valid_body) diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_model_inheritance_recursive.py b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_model_inheritance_recursive.py index e3b2e80b72..bd810ed036 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_model_inheritance_recursive.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_model_inheritance_recursive.py @@ -13,24 +13,11 @@ def client(): with RecursiveClient() as client: yield client + @pytest.fixture def expected(): - return Extension({ - "level": 0, - "extension": [ - { - "level": 1, - "extension": [ - { - "level": 2 - } - ] - }, - { - "level": 1 - } - ] -}) + return Extension({"level": 0, "extension": [{"level": 1, "extension": [{"level": 2}]}, {"level": 1}]}) + def test_put(client: RecursiveClient, expected: Extension): client.put(expected) @@ -38,4 +25,3 @@ def test_put(client: RecursiveClient, expected: Extension): def test_get(client: RecursiveClient, expected: Extension): assert client.get() == expected - diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_model_usage.py b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_model_usage.py index 23b6081bf3..c9ef0e63e7 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_model_usage.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_model_usage.py @@ -6,21 +6,23 @@ import pytest from typetest.model.usage import UsageClient, models + @pytest.fixture def client(): with UsageClient() as client: yield client -@pytest.mark.parametrize( -"op_name, input,output", [ - ("input", models.InputRecord(required_prop="example-value"), None), - ("output", None, models.OutputRecord(required_prop="example-value")), - ("input_and_output", models.InputOutputRecord(required_prop="example-value"), models.InputOutputRecord(required_prop="example-value")), -] -) -def test_input_output(client, op_name, input, output): - op = getattr(client, op_name) - if input: - assert output == op(input) - else: - assert output == op() + +def test_input(client: UsageClient): + input = models.InputRecord(required_prop="example-value") + assert client.input(input) is None + + +def test_output(client: UsageClient): + output = models.OutputRecord(required_prop="example-value") + assert output == client.output() + + +def test_input_and_output(client: UsageClient): + input_output = models.InputOutputRecord(required_prop="example-value") + assert input_output == client.input_and_output(input_output) diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_model_visibility.py b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_model_visibility.py index 54e845fa94..b44012f87e 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_model_visibility.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_model_visibility.py @@ -6,23 +6,29 @@ import pytest from typetest.model.visibility import VisibilityClient, models + @pytest.fixture def client(): with VisibilityClient() as client: yield client + def test_get_model(client): result = client.get_model(models.VisibilityModel(query_prop=123)) assert result == models.VisibilityModel(read_prop="abc") + def test_put_model(client): client.put_model(models.VisibilityModel(create_prop=["foo", "bar"], update_prop=[1, 2])) + def test_patch_model(client): client.patch_model(models.VisibilityModel(update_prop=[1, 2])) + def test_post_model(client): client.post_model(models.VisibilityModel(create_prop=["foo", "bar"])) + def test_delete_model(client): client.delete_model(models.VisibilityModel(delete_prop=True)) diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_property_additionalproperties.py b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_property_additionalproperties.py index b07a64ea21..8f1a26be4c 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_property_additionalproperties.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_property_additionalproperties.py @@ -13,44 +13,244 @@ def client(): yield client -@pytest.mark.parametrize( - "og_name,val, model_name", [ - ("extends_unknown", {'name': 'ExtendsUnknownAdditionalProperties', 'prop1': 32, 'prop2': True, 'prop3': 'abc'}, models.ExtendsUnknownAdditionalProperties), - ("extends_unknown_derived", {'name': 'ExtendsUnknownAdditionalProperties', 'index': 314, 'age': 2.71828, 'prop1': 32, 'prop2': True, 'prop3': 'abc'}, models.ExtendsUnknownAdditionalPropertiesDerived), - ("extends_unknown_discriminated", {'kind': 'derived', 'name': 'Derived', 'index': 314, 'age': 2.71828, 'prop1': 32, 'prop2': True, 'prop3': 'abc'}, models.ExtendsUnknownAdditionalPropertiesDiscriminatedDerived), - ("is_unknown", {'name': 'IsUnknownAdditionalProperties', 'prop1': 32, 'prop2': True, 'prop3': 'abc'}, models.IsUnknownAdditionalProperties), - ("is_unknown_derived", {'name': 'IsUnknownAdditionalProperties', 'index': 314, 'age': 2.71828, 'prop1': 32, 'prop2': True, 'prop3': 'abc'}, models.IsUnknownAdditionalPropertiesDerived), - ("is_unknown_discriminated", {'kind': 'derived', 'name': 'Derived', 'index': 314, 'age': 2.71828, 'prop1': 32, 'prop2': True, 'prop3': 'abc'}, models.IsUnknownAdditionalPropertiesDiscriminatedDerived), - ("extends_string", {'name': 'ExtendsStringAdditionalProperties', 'prop': 'abc'}, models.ExtendsStringAdditionalProperties), - ("is_string", {'name': 'IsStringAdditionalProperties', 'prop': 'abc'}, models.IsStringAdditionalProperties), - ("extends_float", {'id': 43.125, 'prop': 43.125}, models.ExtendsFloatAdditionalProperties), - ("is_float", {'id': 43.125, 'prop': 43.125}, models.IsFloatAdditionalProperties), - ("extends_model", {'knownProp': {'state': 'ok'}, 'prop': {'state': 'ok'}}, models.ExtendsModelAdditionalProperties), - ("is_model", {'knownProp': {'state': 'ok'}, 'prop': {'state': 'ok'}}, models.IsModelAdditionalProperties), - ("extends_model_array", {'knownProp': [{'state': 'ok'}, {'state': 'ok'}], 'prop': [{'state': 'ok'}, {'state': 'ok'}]}, models.ExtendsModelArrayAdditionalProperties), - ("is_model_array", {'knownProp': [{'state': 'ok'}, {'state': 'ok'}], 'prop': [{'state': 'ok'}, {'state': 'ok'}]}, models.IsModelArrayAdditionalProperties), - ("spread_string", {'name': 'SpreadSpringRecord', 'prop': 'abc'}, dict), - ("spread_float", {'id': 43.125, 'prop': 43.125}, dict), - ("spread_model", {'knownProp': {'state': 'ok'}, 'prop': {'state': 'ok'}}, dict), - ("spread_model_array", {'knownProp': [{'state': 'ok'}, {'state': 'ok'}], 'prop': [{'state': 'ok'}, {'state': 'ok'}]}, dict), - ("spread_different_string", {'id': 43.125, 'prop': 'abc'}, dict), - ("spread_different_float", {'name': 'abc', 'prop': 43.125}, dict), - ("spread_different_model", {'knownProp': 'abc', 'prop': {'state': 'ok'}}, dict), - ("spread_different_model_array", {'knownProp': 'abc', 'prop': [{'state': 'ok'}, {'state': 'ok'}]}, dict), - ("extends_different_spread_string", {'id': 43.125, 'prop': 'abc', 'derivedProp': 'abc'}, models.DifferentSpreadStringDerived), - ("extends_different_spread_float", {'name': 'abc', 'prop': 43.125, 'derivedProp': 43.125}, models.DifferentSpreadFloatDerived), - ("extends_different_spread_model", {'knownProp': 'abc', 'prop': {'state': 'ok'}, 'derivedProp': {'state': 'ok'}}, models.DifferentSpreadModelDerived), - ("extends_different_spread_model_array", {'knownProp': 'abc', 'prop': [{'state': 'ok'}, {'state': 'ok'}], 'derivedProp': [{'state': 'ok'}, {'state': 'ok'}]}, models.DifferentSpreadModelArrayDerived), - ("multiple_spread", {'flag': True, 'prop1': 'abc', 'prop2': 43.125}, dict), - ("spread_record_discriminated_union", {'name': 'abc', 'prop1': {'fooProp': 'abc', 'kind': 'kind0'}, 'prop2': {'end': '2021-01-02T00:00:00Z', 'kind': 'kind1', 'start': '2021-01-01T00:00:00Z'}}, dict), - ("spread_record_non_discriminated_union", {'name': 'abc', 'prop1': {'kind': 'kind0', 'fooProp': 'abc'}, 'prop2': {'kind': 'kind1', 'start': '2021-01-01T00:00:00Z', 'end': '2021-01-02T00:00:00Z'}}, dict), - ("spread_record_non_discriminated_union2", {'name': 'abc', 'prop1': {'kind': 'kind1', 'start': '2021-01-01T00:00:00Z'}, 'prop2': {'kind': 'kind1', 'start': '2021-01-01T00:00:00Z', 'end': '2021-01-02T00:00:00Z'}}, dict), - ("spread_record_non_discriminated_union3", {'name': 'abc', 'prop1': [{'kind': 'kind1', 'start': '2021-01-01T00:00:00Z'}, {'kind': 'kind1', 'start': '2021-01-01T00:00:00Z'}], 'prop2': {'kind': 'kind1', 'start': '2021-01-01T00:00:00Z', 'end': '2021-01-02T00:00:00Z'}}, dict), - ("spread_record_union", {'flag': True, 'prop1': 'abc', 'prop2': 43.125}, dict), - ] -) -def test_json(client, og_name, val, model_name): - body = model_name(val) - og_group = getattr(client, og_name) - assert og_group.get() == body - og_group.put(body) +def test_extends_different_spread_float(client: AdditionalPropertiesClient): + body = models.DifferentSpreadFloatDerived({"name": "abc", "prop": 43.125, "derivedProp": 43.125}) + assert client.extends_different_spread_float.get() == body + client.extends_different_spread_float.put(body) + + +def test_extends_different_spread_model(client: AdditionalPropertiesClient): + body = models.DifferentSpreadModelDerived( + {"knownProp": "abc", "prop": {"state": "ok"}, "derivedProp": {"state": "ok"}} + ) + assert client.extends_different_spread_model.get() == body + client.extends_different_spread_model.put(body) + + +def test_extends_different_spread_model_array(client: AdditionalPropertiesClient): + body = models.DifferentSpreadModelArrayDerived( + { + "knownProp": "abc", + "prop": [{"state": "ok"}, {"state": "ok"}], + "derivedProp": [{"state": "ok"}, {"state": "ok"}], + } + ) + assert client.extends_different_spread_model_array.get() == body + client.extends_different_spread_model_array.put(body) + + +def test_extends_different_spread_string(client: AdditionalPropertiesClient): + body = models.DifferentSpreadStringDerived({"id": 43.125, "prop": "abc", "derivedProp": "abc"}) + assert client.extends_different_spread_string.get() == body + client.extends_different_spread_string.put(body) + + +def test_extends_float(client: AdditionalPropertiesClient): + body = models.ExtendsFloatAdditionalProperties({"id": 43.125, "prop": 43.125}) + assert client.extends_float.get() == body + client.extends_float.put(body) + + +def test_extends_model(client: AdditionalPropertiesClient): + body = models.ExtendsModelAdditionalProperties({"knownProp": {"state": "ok"}, "prop": {"state": "ok"}}) + assert client.extends_model.get() == body + client.extends_model.put(body) + + +def test_extends_model_array(client: AdditionalPropertiesClient): + body = models.ExtendsModelArrayAdditionalProperties( + {"knownProp": [{"state": "ok"}, {"state": "ok"}], "prop": [{"state": "ok"}, {"state": "ok"}]} + ) + assert client.extends_model_array.get() == body + client.extends_model_array.put(body) + + +def test_extends_string(client: AdditionalPropertiesClient): + body = models.ExtendsStringAdditionalProperties({"name": "ExtendsStringAdditionalProperties", "prop": "abc"}) + assert client.extends_string.get() == body + client.extends_string.put(body) + + +def test_extends_unknown(client: AdditionalPropertiesClient): + body = models.ExtendsUnknownAdditionalProperties( + {"name": "ExtendsUnknownAdditionalProperties", "prop1": 32, "prop2": True, "prop3": "abc"} + ) + assert client.extends_unknown.get() == body + client.extends_unknown.put(body) + + +def test_extends_unknown_derived(client: AdditionalPropertiesClient): + body = models.ExtendsUnknownAdditionalPropertiesDerived( + { + "name": "ExtendsUnknownAdditionalProperties", + "index": 314, + "age": 2.71828, + "prop1": 32, + "prop2": True, + "prop3": "abc", + } + ) + assert client.extends_unknown_derived.get() == body + client.extends_unknown_derived.put(body) + + +def test_extends_unknown_discriminated(client: AdditionalPropertiesClient): + body = models.ExtendsUnknownAdditionalPropertiesDiscriminatedDerived( + {"kind": "derived", "name": "Derived", "index": 314, "age": 2.71828, "prop1": 32, "prop2": True, "prop3": "abc"} + ) + assert client.extends_unknown_discriminated.get() == body + client.extends_unknown_discriminated.put(body) + + +def test_is_float(client: AdditionalPropertiesClient): + body = models.IsFloatAdditionalProperties({"id": 43.125, "prop": 43.125}) + assert client.is_float.get() == body + client.is_float.put(body) + + +def test_is_model(client: AdditionalPropertiesClient): + body = models.IsModelAdditionalProperties({"knownProp": {"state": "ok"}, "prop": {"state": "ok"}}) + assert client.is_model.get() == body + client.is_model.put(body) + + +def test_is_model_array(client: AdditionalPropertiesClient): + body = models.IsModelArrayAdditionalProperties( + {"knownProp": [{"state": "ok"}, {"state": "ok"}], "prop": [{"state": "ok"}, {"state": "ok"}]} + ) + assert client.is_model_array.get() == body + client.is_model_array.put(body) + + +def test_is_string(client: AdditionalPropertiesClient): + body = models.IsStringAdditionalProperties({"name": "IsStringAdditionalProperties", "prop": "abc"}) + assert client.is_string.get() == body + client.is_string.put(body) + + +def test_is_unknown(client: AdditionalPropertiesClient): + body = models.IsUnknownAdditionalProperties( + {"name": "IsUnknownAdditionalProperties", "prop1": 32, "prop2": True, "prop3": "abc"} + ) + assert client.is_unknown.get() == body + client.is_unknown.put(body) + + +def test_is_unknown_derived(client: AdditionalPropertiesClient): + body = models.IsUnknownAdditionalPropertiesDerived( + { + "name": "IsUnknownAdditionalProperties", + "index": 314, + "age": 2.71828, + "prop1": 32, + "prop2": True, + "prop3": "abc", + } + ) + assert client.is_unknown_derived.get() == body + client.is_unknown_derived.put(body) + + +def test_is_unknown_discriminated(client: AdditionalPropertiesClient): + body = models.IsUnknownAdditionalPropertiesDiscriminatedDerived( + {"kind": "derived", "name": "Derived", "index": 314, "age": 2.71828, "prop1": 32, "prop2": True, "prop3": "abc"} + ) + assert client.is_unknown_discriminated.get() == body + client.is_unknown_discriminated.put(body) + + +def test_multiple_spread(client: AdditionalPropertiesClient): + body = {"flag": True, "prop1": "abc", "prop2": 43.125} + assert client.multiple_spread.get() == body + client.multiple_spread.put(body) + + +def test_spread_different_float(client: AdditionalPropertiesClient): + body = {"name": "abc", "prop": 43.125} + assert client.spread_different_float.get() == body + client.spread_different_float.put(body) + + +def test_spread_different_model(client: AdditionalPropertiesClient): + body = {"knownProp": "abc", "prop": {"state": "ok"}} + assert client.spread_different_model.get() == body + client.spread_different_model.put(body) + + +def test_spread_different_model_array(client: AdditionalPropertiesClient): + body = {"knownProp": "abc", "prop": [{"state": "ok"}, {"state": "ok"}]} + assert client.spread_different_model_array.get() == body + client.spread_different_model_array.put(body) + + +def test_spread_different_string(client: AdditionalPropertiesClient): + body = {"id": 43.125, "prop": "abc"} + assert client.spread_different_string.get() == body + client.spread_different_string.put(body) + + +def test_spread_model(client: AdditionalPropertiesClient): + body = {"knownProp": {"state": "ok"}, "prop": {"state": "ok"}} + assert client.spread_model.get() == body + client.spread_model.put(body) + + +def test_spread_model_array(client: AdditionalPropertiesClient): + body = {"knownProp": [{"state": "ok"}, {"state": "ok"}], "prop": [{"state": "ok"}, {"state": "ok"}]} + assert client.spread_model_array.get() == body + client.spread_model_array.put(body) + + +def test_spread_record_discriminated_union(client: AdditionalPropertiesClient): + body = { + "name": "abc", + "prop1": {"fooProp": "abc", "kind": "kind0"}, + "prop2": {"end": "2021-01-02T00:00:00Z", "kind": "kind1", "start": "2021-01-01T00:00:00Z"}, + } + assert client.spread_record_discriminated_union.get() == body + client.spread_record_discriminated_union.put(body) + + +def test_spread_record_non_discriminated_union(client: AdditionalPropertiesClient): + body = { + "name": "abc", + "prop1": {"kind": "kind0", "fooProp": "abc"}, + "prop2": {"kind": "kind1", "start": "2021-01-01T00:00:00Z", "end": "2021-01-02T00:00:00Z"}, + } + assert client.spread_record_non_discriminated_union.get() == body + client.spread_record_non_discriminated_union.put(body) + + +def test_spread_record_non_discriminated_union2(client: AdditionalPropertiesClient): + body = { + "name": "abc", + "prop1": {"kind": "kind1", "start": "2021-01-01T00:00:00Z"}, + "prop2": {"kind": "kind1", "start": "2021-01-01T00:00:00Z", "end": "2021-01-02T00:00:00Z"}, + } + assert client.spread_record_non_discriminated_union2.get() == body + client.spread_record_non_discriminated_union2.put(body) + + +def test_spread_record_non_discriminated_union3(client: AdditionalPropertiesClient): + body = { + "name": "abc", + "prop1": [ + {"kind": "kind1", "start": "2021-01-01T00:00:00Z"}, + {"kind": "kind1", "start": "2021-01-01T00:00:00Z"}, + ], + "prop2": {"kind": "kind1", "start": "2021-01-01T00:00:00Z", "end": "2021-01-02T00:00:00Z"}, + } + assert client.spread_record_non_discriminated_union3.get() == body + client.spread_record_non_discriminated_union3.put(body) + + +def test_spread_record_union(client: AdditionalPropertiesClient): + body = {"flag": True, "prop1": "abc", "prop2": 43.125} + assert client.spread_record_union.get() == body + client.spread_record_union.put(body) + + +def test_spread_string(client: AdditionalPropertiesClient): + body = {"name": "SpreadSpringRecord", "prop": "abc"} + assert client.spread_string.get() == body + client.spread_string.put(body) diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_property_nullable.py b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_property_nullable.py index 0cf671df5c..ef784a9cb9 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_property_nullable.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_property_nullable.py @@ -10,6 +10,11 @@ SdkJSONEncoder, ) +try: + from corehttp.serialization import NULL +except ImportError: + from azure.core.serialization import NULL + @pytest.fixture def client(): @@ -17,36 +22,69 @@ def client(): yield client -@pytest.mark.parametrize( - "og_name,model,val", - [ - ("string", models.StringProperty, "hello"), - ("bytes", models.BytesProperty, "aGVsbG8sIHdvcmxkIQ=="), - ("datetime", models.DatetimeProperty, "2022-08-26T18:38:00Z"), - ("duration", models.DurationProperty, "P123DT22H14M12.011S"), - ( - "collections_byte", - models.CollectionsByteProperty, - ["aGVsbG8sIHdvcmxkIQ==", "aGVsbG8sIHdvcmxkIQ=="], - ), - ( - "collections_model", - models.CollectionsModelProperty, - [ - models.InnerModel(property="hello"), - models.InnerModel(property="world"), - ], - ), - ], -) -def test(client, og_name, model, val, core_library): - og_group = getattr(client, og_name) - non_null_model = model(required_property="foo", nullable_property=val) - non_model = model(required_property="foo", nullable_property=core_library.serialization.NULL) - assert '{"requiredProperty": "foo", "nullableProperty": null}' == json.dumps( - non_model, cls=SdkJSONEncoder +def test_bytes(client: NullableClient): + non_null_model = models.BytesProperty(required_property="foo", nullable_property="aGVsbG8sIHdvcmxkIQ==") + non_model = models.BytesProperty(required_property="foo", nullable_property=NULL) + assert '{"requiredProperty": "foo", "nullableProperty": null}' == json.dumps(non_model, cls=SdkJSONEncoder) + assert client.bytes.get_non_null() == non_null_model + assert client.bytes.get_null()["nullableProperty"] is None + client.bytes.patch_non_null(body=non_null_model) + client.bytes.patch_null(body=non_model) + + +def test_collections_byte(client: NullableClient): + non_null_model = models.CollectionsByteProperty( + required_property="foo", nullable_property=["aGVsbG8sIHdvcmxkIQ==", "aGVsbG8sIHdvcmxkIQ=="] + ) + non_model = models.CollectionsByteProperty(required_property="foo", nullable_property=NULL) + assert '{"requiredProperty": "foo", "nullableProperty": null}' == json.dumps(non_model, cls=SdkJSONEncoder) + assert client.collections_byte.get_non_null() == non_null_model + assert client.collections_byte.get_null()["nullableProperty"] is None + client.collections_byte.patch_non_null(body=non_null_model) + client.collections_byte.patch_null(body=non_model) + + +def test_collections_model(client: NullableClient): + non_null_model = models.CollectionsModelProperty( + required_property="foo", + nullable_property=[ + models.InnerModel(property="hello"), + models.InnerModel(property="world"), + ], ) - assert og_group.get_non_null() == non_null_model - assert og_group.get_null()["nullableProperty"] is None - og_group.patch_non_null(body=non_null_model) - og_group.patch_null(body=non_model) + non_model = models.CollectionsModelProperty(required_property="foo", nullable_property=NULL) + assert '{"requiredProperty": "foo", "nullableProperty": null}' == json.dumps(non_model, cls=SdkJSONEncoder) + assert client.collections_model.get_non_null() == non_null_model + assert client.collections_model.get_null()["nullableProperty"] is None + client.collections_model.patch_non_null(body=non_null_model) + client.collections_model.patch_null(body=non_model) + + +def test_datetime(client: NullableClient): + non_null_model = models.DatetimeProperty(required_property="foo", nullable_property="2022-08-26T18:38:00Z") + non_model = models.DatetimeProperty(required_property="foo", nullable_property=NULL) + assert '{"requiredProperty": "foo", "nullableProperty": null}' == json.dumps(non_model, cls=SdkJSONEncoder) + assert client.datetime.get_non_null() == non_null_model + assert client.datetime.get_null()["nullableProperty"] is None + client.datetime.patch_non_null(body=non_null_model) + client.datetime.patch_null(body=non_model) + + +def test_duration(client: NullableClient): + non_null_model = models.DurationProperty(required_property="foo", nullable_property="P123DT22H14M12.011S") + non_model = models.DurationProperty(required_property="foo", nullable_property=NULL) + assert '{"requiredProperty": "foo", "nullableProperty": null}' == json.dumps(non_model, cls=SdkJSONEncoder) + assert client.duration.get_non_null() == non_null_model + assert client.duration.get_null()["nullableProperty"] is None + client.duration.patch_non_null(body=non_null_model) + client.duration.patch_null(body=non_model) + + +def test_string(client: NullableClient): + non_null_model = models.StringProperty(required_property="foo", nullable_property="hello") + non_model = models.StringProperty(required_property="foo", nullable_property=NULL) + assert '{"requiredProperty": "foo", "nullableProperty": null}' == json.dumps(non_model, cls=SdkJSONEncoder) + assert client.string.get_non_null() == non_null_model + assert client.string.get_null()["nullableProperty"] is None + client.string.patch_non_null(body=non_null_model) + client.string.patch_null(body=non_model) diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_property_optional.py b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_property_optional.py index aba0f36463..5cfe4b70f9 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_property_optional.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_property_optional.py @@ -7,60 +7,78 @@ import pytest from typetest.property.optional import OptionalClient, models + @pytest.fixture def client(): with OptionalClient() as client: yield client -@pytest.mark.parametrize( -"og_name,val", [ - ("string", "hello"), - ("bytes", "aGVsbG8sIHdvcmxkIQ=="), - ("datetime", "2022-08-26T18:38:00Z"), - ("duration", "P123DT22H14M12.011S"), - ("collections_byte", ["aGVsbG8sIHdvcmxkIQ==", "aGVsbG8sIHdvcmxkIQ=="]), - ("collections_model", [{'property': 'hello'}, {'property': 'world'}]), - ("string_literal", "hello"), - ("int_literal", 1), - ("float_literal", 1.25), - ("boolean_literal", True), - ("union_string_literal", "world"), - ("union_int_literal", 2), - ("union_float_literal", 2.375), -] -) -def test_json(client, og_name, val): - body = {"property": val} - og_group = getattr(client, og_name) - assert og_group.get_all() == body - assert og_group.get_default() == {} - og_group.put_all(body) - og_group.put_default({}) - -@pytest.mark.parametrize( -"og_name,model,val", [ - ("string", models.StringProperty, "hello"), - ("bytes", models.BytesProperty, "aGVsbG8sIHdvcmxkIQ=="), - ("datetime", models.DatetimeProperty, "2022-08-26T18:38:00Z"), - ("duration", models.DurationProperty, "P123DT22H14M12.011S"), - ("collections_byte", models.CollectionsByteProperty, ["aGVsbG8sIHdvcmxkIQ==", "aGVsbG8sIHdvcmxkIQ=="]), - ("collections_model", models.CollectionsModelProperty, [models.StringProperty(property="hello"), models.StringProperty(property="world")]), - ("string_literal", models.StringLiteralProperty, "hello"), - ("int_literal", models.IntLiteralProperty, 1), - ("float_literal", models.FloatLiteralProperty, 1.25), - ("boolean_literal", models.BooleanLiteralProperty, True), - ("union_string_literal", models.UnionStringLiteralProperty, "world"), - ("union_int_literal", models.UnionIntLiteralProperty, 2), - ("union_float_literal", models.UnionFloatLiteralProperty, 2.375), -] -) -def test_model(client, og_name, model, val): - body = model(property=val) - og_group = getattr(client, og_name) - assert og_group.get_all() == body - assert og_group.get_default() == {} == model() - og_group.put_all(body) - og_group.put_default(model()) + +def test_boolean_literal(client): + body = models.BooleanLiteralProperty(property=True) + assert client.boolean_literal.get_all() == body + assert client.boolean_literal.get_default() == models.BooleanLiteralProperty() + client.boolean_literal.put_all(body) + client.boolean_literal.put_default(models.BooleanLiteralProperty()) + + +def test_bytes(client): + body = models.BytesProperty(property="aGVsbG8sIHdvcmxkIQ==") + assert client.bytes.get_all() == body + assert client.bytes.get_default() == models.BytesProperty() + client.bytes.put_all(body) + client.bytes.put_default(models.BytesProperty()) + + +def test_collections_byte(client): + body = models.CollectionsByteProperty(property=["aGVsbG8sIHdvcmxkIQ==", "aGVsbG8sIHdvcmxkIQ=="]) + assert client.collections_byte.get_all() == body + assert client.collections_byte.get_default() == models.CollectionsByteProperty() + client.collections_byte.put_all(body) + client.collections_byte.put_default(models.CollectionsByteProperty()) + + +def test_collections_model(client): + body = models.CollectionsModelProperty( + property=[models.StringProperty(property="hello"), models.StringProperty(property="world")] + ) + assert client.collections_model.get_all() == body + assert client.collections_model.get_default() == models.CollectionsModelProperty() + client.collections_model.put_all(body) + client.collections_model.put_default(models.CollectionsModelProperty()) + + +def test_datetime(client): + body = models.DatetimeProperty(property="2022-08-26T18:38:00Z") + assert client.datetime.get_all() == body + assert client.datetime.get_default() == models.DatetimeProperty() + client.datetime.put_all(body) + client.datetime.put_default(models.DatetimeProperty()) + + +def test_duration(client): + body = models.DurationProperty(property="P123DT22H14M12.011S") + assert client.duration.get_all() == body + assert client.duration.get_default() == models.DurationProperty() + client.duration.put_all(body) + client.duration.put_default(models.DurationProperty()) + + +def test_float_literal(client): + body = models.FloatLiteralProperty(property=1.25) + assert client.float_literal.get_all() == body + assert client.float_literal.get_default() == models.FloatLiteralProperty() + client.float_literal.put_all(body) + client.float_literal.put_default(models.FloatLiteralProperty()) + + +def test_int_literal(client): + body = models.IntLiteralProperty(property=1) + assert client.int_literal.get_all() == body + assert client.int_literal.get_default() == models.IntLiteralProperty() + client.int_literal.put_all(body) + client.int_literal.put_default(models.IntLiteralProperty()) + def test_required_and_optional(client): all_body = { @@ -74,3 +92,43 @@ def test_required_and_optional(client): assert client.required_and_optional.get_required_only() == required_only_body client.required_and_optional.put_all(all_body) client.required_and_optional.put_required_only(required_only_body) + + +def test_string(client): + body = models.StringProperty(property="hello") + assert client.string.get_all() == body + assert client.string.get_default() == models.StringProperty() + client.string.put_all(body) + client.string.put_default(models.StringProperty()) + + +def test_string_literal(client): + body = models.StringLiteralProperty(property="hello") + assert client.string_literal.get_all() == body + assert client.string_literal.get_default() == models.StringLiteralProperty() + client.string_literal.put_all(body) + client.string_literal.put_default(models.StringLiteralProperty()) + + +def test_union_float_literal(client): + body = models.UnionFloatLiteralProperty(property=2.375) + assert client.union_float_literal.get_all() == body + assert client.union_float_literal.get_default() == models.UnionFloatLiteralProperty() + client.union_float_literal.put_all(body) + client.union_float_literal.put_default(models.UnionFloatLiteralProperty()) + + +def test_union_int_literal(client): + body = models.UnionIntLiteralProperty(property=2) + assert client.union_int_literal.get_all() == body + assert client.union_int_literal.get_default() == models.UnionIntLiteralProperty() + client.union_int_literal.put_all(body) + client.union_int_literal.put_default(models.UnionIntLiteralProperty()) + + +def test_union_string_literal(client): + body = models.UnionStringLiteralProperty(property="world") + assert client.union_string_literal.get_all() == body + assert client.union_string_literal.get_default() == models.UnionStringLiteralProperty() + client.union_string_literal.put_all(body) + client.union_string_literal.put_default(models.UnionStringLiteralProperty()) diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_property_valuetypes.py b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_property_valuetypes.py index 35ca484455..c9b19bbc6c 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_property_valuetypes.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_property_valuetypes.py @@ -16,94 +16,70 @@ def client(): yield client -@pytest.mark.parametrize( - "og_name,val", - [ - ("boolean", True), - ("string", "hello"), - ("bytes", "aGVsbG8sIHdvcmxkIQ=="), - ("int_operations", 42), - ("float", 43.125), - ("decimal", decimal.Decimal("0.33333")), - ("decimal128", decimal.Decimal("0.33333")), - ("datetime", "2022-08-26T18:38:00Z"), - ("duration", "P123DT22H14M12.011S"), - ("enum", "ValueOne"), - ("extensible_enum", "UnknownValue"), - ("model", {"property": "hello"}), - ("collections_string", ["hello", "world"]), - ("collections_int", [1, 2]), - ("collections_model", [{"property": "hello"}, {"property": "world"}]), - ("dictionary_string", {"k1": "hello", "k2": "world"}), - ("unknown_string", "hello"), - ("unknown_int", 42), - ("unknown_dict", {"k1": "hello", "k2": 42}), - ("unknown_array", ["hello", "world"]), - ("boolean_literal", True), - ("int_literal", 42), - ("string_literal", "hello"), - ("float_literal", 43.125), - ("union_string_literal", "world"), - ("union_float_literal", 46.875), - ("union_int_literal", 42), - ("union_enum_value", "value2"), - ], -) -def test_json(client, og_name, val): - body = {"property": val} - og_group = getattr(client, og_name) - assert og_group.get() == body - og_group.put(body) - - -@pytest.mark.parametrize( - "og_name,model,val", - [ - ("boolean", models.BooleanProperty, True), - ("string", models.StringProperty, "hello"), - ("bytes", models.BytesProperty, b"hello, world!"), - ("int_operations", models.IntProperty, 42), - ("float", models.FloatProperty, 43.125), - ("decimal", models.DecimalProperty, decimal.Decimal("0.33333")), - ("decimal128", models.Decimal128Property, decimal.Decimal("0.33333")), - ("enum", models.EnumProperty, models.InnerEnum.VALUE_ONE), - ("extensible_enum", models.ExtensibleEnumProperty, "UnknownValue"), - ("model", models.ModelProperty, models.InnerModel(property="hello")), - ("collections_string", models.CollectionsStringProperty, ["hello", "world"]), - ("collections_int", models.CollectionsIntProperty, [1, 2]), - ( - "collections_model", - models.CollectionsModelProperty, - [{"property": "hello"}, {"property": "world"}], - ), - ( - "dictionary_string", - models.DictionaryStringProperty, - {"k1": "hello", "k2": "world"}, - ), - ("unknown_string", models.UnknownStringProperty, "hello"), - ("unknown_int", models.UnknownIntProperty, 42), - ("unknown_dict", models.UnknownDictProperty, {"k1": "hello", "k2": 42}), - ("unknown_array", models.UnknownArrayProperty, ["hello", "world"]), - ("boolean_literal", models.BooleanLiteralProperty, True), - ("int_literal", models.IntLiteralProperty, 42), - ("string_literal", models.StringLiteralProperty, "hello"), - ("float_literal", models.FloatLiteralProperty, 43.125), - ("union_string_literal", models.UnionStringLiteralProperty, "world"), - ("union_float_literal", models.UnionFloatLiteralProperty, 46.875), - ("union_int_literal", models.UnionIntLiteralProperty, 42), - ("union_enum_value", models.UnionEnumValueProperty, models.ExtendedEnum.ENUM_VALUE2), - ], -) -def test_model(client, og_name, model, val): - body = model(property=val) - og_group = getattr(client, og_name) - assert og_group.get() == body - assert og_group.get().property == val - og_group.put(body) - - -def test_datetime_model(client): +def test_model_deserialization(client: ValueTypesClient): + body = models.ModelProperty(property={"property": "hello"}) + assert body.property.property == body["property"]["property"] + resp = client.model.get() + assert resp.property.property == resp["property"]["property"] + + body = models.CollectionsModelProperty(property=[{"property": "hello"}, {"property": "world"}]) + assert body.property[0].property == body["property"][0]["property"] + resp = client.collections_model.get() + assert resp.property[1].property == resp["property"][1]["property"] + + +def test_enum_property(): + for prop in ["ValueOne", models.FixedInnerEnum.VALUE_ONE]: + string_type = models.EnumProperty(property=prop) + assert isinstance(string_type.property, models.FixedInnerEnum) + assert isinstance(string_type["property"], str) + + +def test_boolean(client: ValueTypesClient): + body = models.BooleanProperty(property=True) + assert body.property == body["property"] + resp = client.boolean.get() + assert resp.property == resp["property"] == True + + +def test_boolean_literal(client: ValueTypesClient): + body = models.BooleanLiteralProperty(property=True) + assert body.property == body["property"] + resp = client.boolean_literal.get() + assert resp.property == resp["property"] == True + + +def test_bytes(client: ValueTypesClient): + body = models.BytesProperty(property=b"hello, world!") + assert body.property == b"hello, world!" + assert body["property"] == "aGVsbG8sIHdvcmxkIQ==" + resp = client.bytes.get() + assert resp.property == b"hello, world!" + assert resp["property"] == "aGVsbG8sIHdvcmxkIQ==" + + +def test_collections_int(client: ValueTypesClient): + body = models.CollectionsIntProperty(property=[1, 2]) + assert body.property == body["property"] + resp = client.collections_int.get() + assert resp.property == resp["property"] == [1, 2] + + +def test_collections_model(client: ValueTypesClient): + body = models.CollectionsModelProperty(property=[{"property": "hello"}, {"property": "world"}]) + assert body.property[0].property == body["property"][0]["property"] + resp = client.collections_model.get() + assert resp.property[1].property == resp["property"][1]["property"] + + +def test_collections_string(client: ValueTypesClient): + body = models.CollectionsStringProperty(property=["hello", "world"]) + assert body.property == body["property"] + resp = client.collections_string.get() + assert resp.property == resp["property"] == ["hello", "world"] + + +def test_datetime(client): received_body = client.datetime.get() assert received_body == {"property": "2022-08-26T18:38:00Z"} assert received_body.property.year == 2022 @@ -111,34 +87,162 @@ def test_datetime_model(client): assert received_body.property.day == 26 assert received_body.property.hour == 18 assert received_body.property.minute == 38 - client.datetime.put( - models.DatetimeProperty( - property=datetime.datetime(2022, 8, 26, hour=18, minute=38) - ) - ) + client.datetime.put(models.DatetimeProperty(property=datetime.datetime(2022, 8, 26, hour=18, minute=38))) -def test_never_model(client: ValueTypesClient): - assert client.never.get() == models.NeverProperty() - client.never.put(models.NeverProperty()) +def test_decimal(client: ValueTypesClient): + body = models.DecimalProperty(property=decimal.Decimal("0.33333")) + assert body.property == decimal.Decimal("0.33333") + assert body["property"] == 0.33333 + resp = client.decimal.get() + assert resp.property == decimal.Decimal("0.33333") + assert resp["property"] == 0.33333 -def test_model_deserialization(client: ValueTypesClient): +def test_decimal128(client: ValueTypesClient): + body = models.Decimal128Property(property=decimal.Decimal("0.33333")) + assert body.property == decimal.Decimal("0.33333") + assert body["property"] == 0.33333 + resp = client.decimal128.get() + assert resp.property == decimal.Decimal("0.33333") + assert resp["property"] == 0.33333 + + +def test_dictionary_string(client: ValueTypesClient): + body = models.DictionaryStringProperty(property={"k1": "hello", "k2": "world"}) + assert body.property == body["property"] + resp = client.dictionary_string.get() + assert resp.property == resp["property"] == {"k1": "hello", "k2": "world"} + + +def test_duration(client: ValueTypesClient): + body = models.DurationProperty(property="P123DT22H14M12.011S") + assert body.property == datetime.timedelta(days=123, seconds=80052, microseconds=11000) + assert body["property"] == "P123DT22H14M12.011S" + resp = client.duration.get() + assert resp.property == datetime.timedelta(days=123, seconds=80052, microseconds=11000) + assert resp["property"] == "P123DT22H14M12.011S" + + +def test_enum(client: ValueTypesClient): + body = models.EnumProperty(property=models.InnerEnum.VALUE_ONE) + assert body.property == body["property"] + resp = client.enum.get() + assert resp.property == resp["property"] == "ValueOne" + + +def test_extensible_enum(client: ValueTypesClient): + body = models.ExtensibleEnumProperty(property="UnknownValue") + assert body.property == body["property"] + resp = client.extensible_enum.get() + assert resp.property == resp["property"] == "UnknownValue" + + +def test_float(client: ValueTypesClient): + body = models.FloatProperty(property=43.125) + assert body.property == body["property"] + resp = client.float.get() + assert resp.property == resp["property"] == 43.125 + + +def test_float_literal(client: ValueTypesClient): + body = models.FloatLiteralProperty(property=43.125) + assert body.property == body["property"] + resp = client.float_literal.get() + assert resp.property == resp["property"] == 43.125 + + +def test_int(client: ValueTypesClient): + body = models.IntProperty(property=42) + assert body.property == body["property"] + resp = client.int_operations.get() + assert resp.property == resp["property"] == 42 + + +def test_int_literal(client: ValueTypesClient): + body = models.IntLiteralProperty(property=42) + assert body.property == body["property"] + resp = client.int_literal.get() + assert resp.property == resp["property"] == 42 + + +def test_model(client: ValueTypesClient): body = models.ModelProperty(property={"property": "hello"}) assert body.property.property == body["property"]["property"] resp = client.model.get() assert resp.property.property == resp["property"]["property"] - body = models.CollectionsModelProperty( - property=[{"property": "hello"}, {"property": "world"}] - ) - assert body.property[0].property == body["property"][0]["property"] - resp = client.collections_model.get() - assert resp.property[1].property == resp["property"][1]["property"] +def test_never(client: ValueTypesClient): + assert client.never.get() == models.NeverProperty() + client.never.put(models.NeverProperty()) -def test_enum_property(): - for prop in ["ValueOne", models.FixedInnerEnum.VALUE_ONE]: - string_type = models.EnumProperty(property=prop) - assert isinstance(string_type.property, models.FixedInnerEnum) - assert isinstance(string_type["property"], str) + +def test_string(client: ValueTypesClient): + body = models.StringProperty(property="hello") + assert body.property == body["property"] + resp = client.string.get() + assert resp.property == resp["property"] == "hello" + + +def test_string_literal(client: ValueTypesClient): + body = models.StringLiteralProperty(property="hello") + assert body.property == body["property"] + resp = client.string_literal.get() + assert resp.property == resp["property"] == "hello" + + +def test_union_enum_value(client: ValueTypesClient): + body = models.UnionEnumValueProperty(property=models.ExtendedEnum.ENUM_VALUE2) + assert body.property == body["property"] + resp = client.union_enum_value.get() + assert resp.property == resp["property"] == "value2" + + +def test_union_float_literal(client: ValueTypesClient): + body = models.UnionFloatLiteralProperty(property=46.875) + assert body.property == body["property"] + resp = client.union_float_literal.get() + assert resp.property == resp["property"] == 46.875 + + +def test_union_int_literal(client: ValueTypesClient): + body = models.UnionIntLiteralProperty(property=42) + assert body.property == body["property"] + resp = client.union_int_literal.get() + assert resp.property == resp["property"] == 42 + + +def test_union_string_literal(client: ValueTypesClient): + body = models.UnionStringLiteralProperty(property="world") + assert body.property == body["property"] + resp = client.union_string_literal.get() + assert resp.property == resp["property"] == "world" + + +def test_unknown_array(client: ValueTypesClient): + body = models.UnknownArrayProperty(property=["hello", "world"]) + assert body.property == body["property"] + resp = client.unknown_array.get() + assert resp.property == resp["property"] == ["hello", "world"] + + +def test_unknown_dict(client: ValueTypesClient): + body = models.UnknownDictProperty(property={"k1": "hello", "k2": 42}) + assert body.property == body["property"] + resp = client.unknown_dict.get() + assert resp.property == resp["property"] == {"k1": "hello", "k2": 42} + + +def test_unknown_int(client: ValueTypesClient): + body = models.UnknownIntProperty(property=42) + assert body.property == body["property"] + resp = client.unknown_int.get() + assert resp.property == resp["property"] == 42 + + +def test_unknown_string(client: ValueTypesClient): + body = models.UnknownStringProperty(property="hello") + assert body.property == body["property"] + resp = client.unknown_string.get() + assert resp.property == resp["property"] == "hello" diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_scalar.py b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_scalar.py index 1f1b362be2..32a1583ac1 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_scalar.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_scalar.py @@ -16,42 +16,38 @@ def client(): yield client -@pytest.mark.parametrize( - "og_name,val", - [ - ("string", "test"), - ("boolean", True), - ("unknown", "test"), - ], -) -def test_scalar(client: ScalarClient, og_name: str, val): - og_group = getattr(client, og_name) - assert og_group.get() == val - og_group.put(val) - - -@pytest.mark.parametrize( - "og_name,val", - [ - ("decimal_type", decimal.Decimal("0.33333")), - ("decimal128_type", decimal.Decimal("0.33333")), - ], -) -def test_type(client: ScalarClient, og_name: str, val): - og_group = getattr(client, og_name) - assert og_group.response_body() == val - og_group.request_body(val) - og_group.request_parameter(value=val) - - -@pytest.mark.parametrize( - "og_name", - [ - "decimal_verify", - "decimal128_verify", - ], -) -def test_verify(client: ScalarClient, og_name: str): - og_group = getattr(client, og_name) - prepare = og_group.prepare_verify() - og_group.verify(reduce(lambda x, y: x + y, prepare)) +def test_scalar_string(client: ScalarClient): + assert client.string.get() == "test" + client.string.put("test") + + +def test_scalar_boolean(client: ScalarClient): + assert client.boolean.get() == True + client.boolean.put(True) + + +def test_scalar_unknown(client: ScalarClient): + assert client.unknown.get() == "test" + client.unknown.put("test") + + +def test_decimal128_type(client: ScalarClient): + assert client.decimal128_type.response_body() == decimal.Decimal("0.33333") + client.decimal128_type.request_body(decimal.Decimal("0.33333")) + client.decimal128_type.request_parameter(value=decimal.Decimal("0.33333")) + + +def test_decimal_type(client: ScalarClient): + assert client.decimal_type.response_body() == decimal.Decimal("0.33333") + client.decimal_type.request_body(decimal.Decimal("0.33333")) + client.decimal_type.request_parameter(value=decimal.Decimal("0.33333")) + + +def test_decimal128_verify(client: ScalarClient): + prepare = client.decimal128_verify.prepare_verify() + client.decimal128_verify.verify(reduce(lambda x, y: x + y, prepare)) + + +def test_decimal_verify(client: ScalarClient): + prepare = client.decimal_verify.prepare_verify() + client.decimal_verify.verify(reduce(lambda x, y: x + y, prepare)) diff --git a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_union.py b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_union.py index 944df3371a..3ca676d10a 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/test_typetest_union.py +++ b/packages/typespec-python/test/generic_mock_api_tests/test_typetest_union.py @@ -3,7 +3,6 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- -from typing import Any, Type import pytest from typetest.union import UnionClient from typetest.union import models @@ -15,50 +14,67 @@ def client(): yield client -@pytest.mark.parametrize( - "og_name,value,res_model_type", - [ - ("strings_only", "b", models.GetResponse), - ("string_extensible", "custom", models.GetResponse1), - ("string_extensible_named", "custom", models.GetResponse2), - ("ints_only", 2, models.GetResponse3), - ("floats_only", 2.2, models.GetResponse4), - ("models_only", models.Cat(name="test"), models.GetResponse5), - ( - "enums_only", - models.EnumsOnlyCases(lr="right", ud="up"), - models.GetResponse6, - ), - ( - "string_and_array", - models.StringAndArrayCases(string="test", array=["test1", "test2"]), - models.GetResponse7, - ), - ( - "mixed_literals", - models.MixedLiteralsCases( - string_literal="a", - int_literal=2, - float_literal=3.3, - boolean_literal=True, - ), - models.GetResponse8, - ), - ( - "mixed_types", - models.MixedTypesCases( - model=models.Cat(name="test"), - literal="a", - int_property=2, - boolean=True, - array=[models.Cat(name="test"), "a", 2, True], - ), - models.GetResponse9, - ), - ], -) -def test_union(client: UnionClient, og_name: str, value: Any, res_model_type: Type): - og_group = getattr(client, og_name) - assert og_group.get() == res_model_type(prop=value) - og_group.send(prop=value) - og_group.send({"prop": value}) +def test_enums_only(client: UnionClient): + value = models.EnumsOnlyCases(lr="right", ud="up") + assert client.enums_only.get() == {"prop": value} + client.enums_only.send(prop=value) + + +def test_floats_only(client: UnionClient): + value = 2.2 + assert client.floats_only.get() == {"prop": value} + client.floats_only.send(prop=value) + + +def test_ints_only(client: UnionClient): + value = 2 + assert client.ints_only.get() == {"prop": value} + client.ints_only.send(prop=value) + + +def test_mixed_literals(client: UnionClient): + value = models.MixedLiteralsCases(string_literal="a", int_literal=2, float_literal=3.3, boolean_literal=True) + assert client.mixed_literals.get() == {"prop": value} + client.mixed_literals.send(prop=value) + + +def test_mixed_types(client: UnionClient): + value = models.MixedTypesCases( + model=models.Cat(name="test"), + literal="a", + int_property=2, + boolean=True, + array=[models.Cat(name="test"), "a", 2, True], + ) + assert client.mixed_types.get() == {"prop": value} + client.mixed_types.send(prop=value) + + +def test_models_only(client: UnionClient): + value = models.Cat(name="test") + assert client.models_only.get() == {"prop": value} + client.models_only.send(prop=value) + + +def test_string_and_array(client: UnionClient): + value = models.StringAndArrayCases(string="test", array=["test1", "test2"]) + assert client.string_and_array.get() == {"prop": value} + client.string_and_array.send(prop=value) + + +def test_string_extensible(client: UnionClient): + value = "custom" + assert client.string_extensible.get() == {"prop": value} + client.string_extensible.send(prop=value) + + +def test_string_extensible_named(client: UnionClient): + value = "custom" + assert client.string_extensible_named.get() == {"prop": value} + client.string_extensible_named.send(prop=value) + + +def test_strings_only(client: UnionClient): + value = "b" + assert client.strings_only.get() == {"prop": value} + client.strings_only.send(prop=value) diff --git a/packages/typespec-python/test/generic_mock_api_tests/unittests/test_model_base_serialization.py b/packages/typespec-python/test/generic_mock_api_tests/unittests/test_model_base_serialization.py index d62e1e53ee..7a00f45c8a 100644 --- a/packages/typespec-python/test/generic_mock_api_tests/unittests/test_model_base_serialization.py +++ b/packages/typespec-python/test/generic_mock_api_tests/unittests/test_model_base_serialization.py @@ -24,9 +24,11 @@ class BasicResource(Model): platform_update_domain_count: int = rest_field( - name="platformUpdateDomainCount") # How many times the platform update domain has been counted + name="platformUpdateDomainCount" + ) # How many times the platform update domain has been counted platform_fault_domain_count: int = rest_field( - name="platformFaultDomainCount") # How many times the platform fault domain has been counted + name="platformFaultDomainCount" + ) # How many times the platform fault domain has been counted virtual_machines: List[Any] = rest_field(name="virtualMachines") # List of virtual machines @overload @@ -36,12 +38,10 @@ def __init__( platform_update_domain_count: int, platform_fault_domain_count: int, virtual_machines: List[Any], - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -52,55 +52,44 @@ class Pet(Model): species: str = rest_field() # my species @overload - def __init__(self, *, name: str, species: str): - ... + def __init__(self, *, name: str, species: str): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def test_model_and_dict_equal(): - dict_response = { - "platformUpdateDomainCount": 5, - "platformFaultDomainCount": 3, - "virtualMachines": [] - } + dict_response = {"platformUpdateDomainCount": 5, "platformFaultDomainCount": 3, "virtualMachines": []} model = BasicResource(platform_update_domain_count=5, platform_fault_domain_count=3, virtual_machines=[]) assert model == dict_response assert ( - model.platform_update_domain_count == - model["platformUpdateDomainCount"] == - dict_response["platformUpdateDomainCount"] == - 5 + model.platform_update_domain_count + == model["platformUpdateDomainCount"] + == dict_response["platformUpdateDomainCount"] + == 5 ) assert ( - model.platform_fault_domain_count == - model['platformFaultDomainCount'] == - dict_response['platformFaultDomainCount'] == - 3 + model.platform_fault_domain_count + == model["platformFaultDomainCount"] + == dict_response["platformFaultDomainCount"] + == 3 ) - assert ( - model.virtual_machines == - model['virtualMachines'] == - dict_response['virtualMachines']) + assert model.virtual_machines == model["virtualMachines"] == dict_response["virtualMachines"] def test_json_roundtrip(): - dict_response = { - "platformUpdateDomainCount": 5, - "platformFaultDomainCount": 3, - "virtualMachines": [] - } + dict_response = {"platformUpdateDomainCount": 5, "platformFaultDomainCount": 3, "virtualMachines": []} model = BasicResource(platform_update_domain_count=5, platform_fault_domain_count=3, virtual_machines=[]) with pytest.raises(TypeError): json.dumps(model) - assert json.dumps( - dict(model)) == '{"platformUpdateDomainCount": 5, "platformFaultDomainCount": 3, "virtualMachines": []}' + assert ( + json.dumps(dict(model)) + == '{"platformUpdateDomainCount": 5, "platformFaultDomainCount": 3, "virtualMachines": []}' + ) assert json.loads(json.dumps(dict(model))) == model == dict_response @@ -109,14 +98,14 @@ def test_has_no_property(): "platformUpdateDomainCount": 5, "platformFaultDomainCount": 3, "virtualMachines": [], - "noprop": "bonjour!" + "noprop": "bonjour!", } model = BasicResource(dict_response) assert ( - model.platform_update_domain_count == - model["platformUpdateDomainCount"] == - dict_response["platformUpdateDomainCount"] == - 5 + model.platform_update_domain_count + == model["platformUpdateDomainCount"] + == dict_response["platformUpdateDomainCount"] + == 5 ) assert not hasattr(model, "no_prop") with pytest.raises(AttributeError) as ex: @@ -131,17 +120,9 @@ class BasicResourceWithProperty(BasicResource): no_prop: str = rest_field(name="noprop") model = BasicResourceWithProperty( - platform_update_domain_count=5, - platform_fault_domain_count=3, - virtual_machines=[], - no_prop="bonjour!" - ) - assert ( - model.no_prop == - model["noprop"] == - dict_response["noprop"] == - "bonjour!" + platform_update_domain_count=5, platform_fault_domain_count=3, virtual_machines=[], no_prop="bonjour!" ) + assert model.no_prop == model["noprop"] == dict_response["noprop"] == "bonjour!" def test_original_and_attr_name_same(): @@ -149,12 +130,10 @@ class MyModel(Model): hello: str = rest_field() @overload - def __init__(self, *, hello: str): - ... + def __init__(self, *, hello: str): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -179,12 +158,10 @@ def __init__( optional_time: Optional[datetime.time] = None, optional_dict: Optional[Dict[str, Optional[Pet]]] = None, optional_myself: Optional["OptionalModel"] = None, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -204,40 +181,42 @@ def test_optional_property(): "optional_model": None, "optional_myself": { "optional_str": None, - "optional_time": '11:34:56', + "optional_time": "11:34:56", "optionalDict": None, - "optional_model": { - "name": "Lady", - "species": "Newt" - }, - "optional_myself": None - } + "optional_model": {"name": "Lady", "species": "Newt"}, + "optional_myself": None, + }, } model = OptionalModel(dict_response) assert model.optional_str == model["optional_str"] == "hello!" assert model.optional_time == model["optional_time"] == None - assert model.optional_dict == model["optionalDict"] == { - "Eugene": { - "name": "Eugene", - "species": "Dog", - }, - "Lady": None, - } + assert ( + model.optional_dict + == model["optionalDict"] + == { + "Eugene": { + "name": "Eugene", + "species": "Dog", + }, + "Lady": None, + } + ) assert model.optional_dict assert model.optional_dict["Eugene"].name == model.optional_dict["Eugene"]["name"] == "Eugene" assert model.optional_dict["Lady"] is None - assert model.optional_myself == model["optional_myself"] == { - "optional_str": None, - "optional_time": '11:34:56', - "optionalDict": None, - "optional_model": { - "name": "Lady", - "species": "Newt" - }, - "optional_myself": None - } + assert ( + model.optional_myself + == model["optional_myself"] + == { + "optional_str": None, + "optional_time": "11:34:56", + "optionalDict": None, + "optional_model": {"name": "Lady", "species": "Newt"}, + "optional_myself": None, + } + ) assert model.optional_myself assert model.optional_myself.optional_str is None assert model.optional_myself.optional_time == datetime.time(11, 34, 56) @@ -256,11 +235,7 @@ def test_model_pass_in_none(): def test_modify_dict(): - model = BasicResource( - platform_update_domain_count=5, - platform_fault_domain_count=3, - virtual_machines=[] - ) + model = BasicResource(platform_update_domain_count=5, platform_fault_domain_count=3, virtual_machines=[]) # now let's modify the model as a dict model["platformUpdateDomainCount"] = 100 @@ -268,35 +243,25 @@ def test_modify_dict(): def test_modify_property(): - dict_response = { - "platformUpdateDomainCount": 5, - "platformFaultDomainCount": 3, - "virtualMachines": [] - } - model = BasicResource( - platform_update_domain_count=5, - platform_fault_domain_count=3, - virtual_machines=[] - ) + dict_response = {"platformUpdateDomainCount": 5, "platformFaultDomainCount": 3, "virtualMachines": []} + model = BasicResource(platform_update_domain_count=5, platform_fault_domain_count=3, virtual_machines=[]) # now let's modify the model through it's properties model.platform_fault_domain_count = 2000 - model['platformFaultDomainCount'] + model["platformFaultDomainCount"] assert model.platform_fault_domain_count == model["platformFaultDomainCount"] == 2000 def test_property_is_a_type(): class Fish(Model): name: str = rest_field() - species: Literal['Salmon', 'Halibut'] = rest_field() + species: Literal["Salmon", "Halibut"] = rest_field() @overload - def __init__(self, *, name: str, species: Literal['Salmon', 'Halibut']): - ... + def __init__(self, *, name: str, species: Literal["Salmon", "Halibut"]): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -305,20 +270,18 @@ class Fishery(Model): fish: Fish = rest_field() @overload - def __init__(self, *, fish: Fish): - ... + def __init__(self, *, fish: Fish): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) fishery = Fishery({"fish": {"name": "Benjamin", "species": "Salmon"}}) assert isinstance(fishery.fish, Fish) - assert fishery.fish.name == fishery.fish['name'] == fishery['fish']['name'] == "Benjamin" - assert fishery.fish.species == fishery.fish['species'] == fishery['fish']['species'] == "Salmon" + assert fishery.fish.name == fishery.fish["name"] == fishery["fish"]["name"] == "Benjamin" + assert fishery.fish.species == fishery.fish["species"] == fishery["fish"]["species"] == "Salmon" def test_datetime_deserialization(): @@ -326,12 +289,10 @@ class DatetimeModel(Model): datetime_value: datetime.datetime = rest_field(name="datetimeValue") @overload - def __init__(self, *, datetime_value: datetime.datetime): - ... + def __init__(self, *, datetime_value: datetime.datetime): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -339,7 +300,7 @@ def __init__(self, *args, **kwargs): val_str = "9999-12-31T23:59:59.999Z" val = isodate.parse_datetime(val_str) model = DatetimeModel({"datetimeValue": val_str}) - assert model['datetimeValue'] == val_str + assert model["datetimeValue"] == val_str assert model.datetime_value == val class BaseModel(Model): @@ -347,8 +308,8 @@ class BaseModel(Model): model = BaseModel({"myProp": {"datetimeValue": val_str}}) assert isinstance(model.my_prop, DatetimeModel) - model.my_prop['datetimeValue'] - assert model.my_prop['datetimeValue'] == model['myProp']['datetimeValue'] == val_str + model.my_prop["datetimeValue"] + assert model.my_prop["datetimeValue"] == model["myProp"]["datetimeValue"] == val_str assert model.my_prop.datetime_value == val @@ -357,12 +318,10 @@ class DateModel(Model): date_value: datetime.date = rest_field(name="dateValue") @overload - def __init__(self, *, date_value: datetime.date): - ... + def __init__(self, *, date_value: datetime.date): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -370,7 +329,7 @@ def __init__(self, *args, **kwargs): val_str = "2016-02-29" val = isodate.parse_date(val_str) model = DateModel({"dateValue": val_str}) - assert model['dateValue'] == val_str + assert model["dateValue"] == val_str assert model.date_value == val class BaseModel(Model): @@ -378,7 +337,7 @@ class BaseModel(Model): model = BaseModel({"myProp": {"dateValue": val_str}}) assert isinstance(model.my_prop, DateModel) - assert model.my_prop['dateValue'] == model['myProp']['dateValue'] == val_str + assert model.my_prop["dateValue"] == model["myProp"]["dateValue"] == val_str assert model.my_prop.date_value == val @@ -387,20 +346,18 @@ class TimeModel(Model): time_value: datetime.time = rest_field(name="timeValue") @overload - def __init__(self, *, time_value: datetime.time): - ... + def __init__(self, *, time_value: datetime.time): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) - val_str = '11:34:56' + val_str = "11:34:56" val = datetime.time(11, 34, 56) model = TimeModel({"timeValue": val_str}) - assert model['timeValue'] == val_str + assert model["timeValue"] == val_str assert model.time_value == val class BaseModel(Model): @@ -408,7 +365,7 @@ class BaseModel(Model): model = BaseModel({"myProp": {"timeValue": val_str}}) assert isinstance(model.my_prop, TimeModel) - assert model.my_prop['timeValue'] == model['myProp']['timeValue'] == val_str + assert model.my_prop["timeValue"] == model["myProp"]["timeValue"] == val_str assert model.my_prop.time_value == val @@ -417,39 +374,24 @@ class SimpleRecursiveModel(Model): me: "SimpleRecursiveModel" = rest_field() @overload - def __init__(self, *, name: str, me: "SimpleRecursiveModel"): - ... + def __init__(self, *, name: str, me: "SimpleRecursiveModel"): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def test_model_recursion(): - dict_response = { - "name": "Snoopy", - "me": { - "name": "Egg", - "me": { - "name": "Chicken" - } - } - } + dict_response = {"name": "Snoopy", "me": {"name": "Egg", "me": {"name": "Chicken"}}} model = SimpleRecursiveModel(dict_response) - assert model['name'] == model.name == "Snoopy" - assert model['me'] == { - "name": "Egg", - "me": { - "name": "Chicken" - } - } + assert model["name"] == model.name == "Snoopy" + assert model["me"] == {"name": "Egg", "me": {"name": "Chicken"}} assert isinstance(model.me, SimpleRecursiveModel) - assert model.me['name'] == model.me.name == "Egg" - assert model.me['me'] == {"name": "Chicken"} + assert model.me["name"] == model.me.name == "Egg" + assert model.me["me"] == {"name": "Chicken"} assert model.me.me.name == "Chicken" @@ -458,25 +400,19 @@ class DictionaryModel(Model): prop: Dict[str, datetime.datetime] = rest_field() @overload - def __init__(self, *, prop: datetime.datetime): - ... + def __init__(self, *, prop: datetime.datetime): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) val_str = "9999-12-31T23:59:59.999Z" val = isodate.parse_datetime(val_str) - dict_response = { - "prop": { - "datetime": val_str - } - } + dict_response = {"prop": {"datetime": val_str}} model = DictionaryModel(dict_response) - assert model['prop'] == {"datetime": val_str} + assert model["prop"] == {"datetime": val_str} assert model.prop == {"datetime": val} @@ -485,12 +421,10 @@ class ModelTest(Model): our_attr: str = rest_field(name="ourAttr") @overload - def __init__(self, *, our_attr: str): - ... + def __init__(self, *, our_attr: str): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -502,7 +436,7 @@ def __init__(self, *args, **kwargs): assert test_model.our_attr == test_model["ourAttr"] == "camel" test_model = ModelTest(our_attr="snake") - assert test_model.our_attr == test_model['ourAttr'] == "snake" + assert test_model.our_attr == test_model["ourAttr"] == "snake" def test_dictionary_deserialization_model(): @@ -510,12 +444,10 @@ class DictionaryModel(Model): prop: Dict[str, Pet] = rest_field() @overload - def __init__(self, *, prop: Dict[str, Pet]): - ... + def __init__(self, *, prop: Dict[str, Pet]): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -529,12 +461,12 @@ def __init__(self, *args, **kwargs): "Lady": { "name": "Lady", "species": "Newt", - } + }, } } model = DictionaryModel(dict_response) - assert model['prop'] == { + assert model["prop"] == { "Eugene": { "name": "Eugene", "species": "Dog", @@ -542,11 +474,11 @@ def __init__(self, *args, **kwargs): "Lady": { "name": "Lady", "species": "Newt", - } + }, } assert model.prop == { "Eugene": Pet({"name": "Eugene", "species": "Dog"}), - "Lady": Pet({"name": "Lady", "species": "Newt"}) + "Lady": Pet({"name": "Lady", "species": "Newt"}), } assert model.prop["Eugene"].name == model.prop["Eugene"]["name"] == "Eugene" assert model.prop["Eugene"].species == model.prop["Eugene"]["species"] == "Dog" @@ -559,23 +491,19 @@ class ListModel(Model): prop: List[datetime.datetime] = rest_field() @overload - def __init__(self, *, prop: List[datetime.datetime]): - ... + def __init__(self, *, prop: List[datetime.datetime]): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) val_str = "9999-12-31T23:59:59.999Z" val = isodate.parse_datetime(val_str) - dict_response = { - "prop": [val_str, val_str] - } + dict_response = {"prop": [val_str, val_str]} model = ListModel(dict_response) - assert model['prop'] == [val_str, val_str] + assert model["prop"] == [val_str, val_str] assert model.prop == [val, val] @@ -584,31 +512,18 @@ class ListModel(Model): prop: List[Pet] = rest_field() @overload - def __init__(self, *, prop: List[Pet]): - ... + def __init__(self, *, prop: List[Pet]): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) - dict_response = { - "prop": [ - {"name": "Eugene", "species": "Dog"}, - {"name": "Lady", "species": "Newt"} - ] - } + dict_response = {"prop": [{"name": "Eugene", "species": "Dog"}, {"name": "Lady", "species": "Newt"}]} model = ListModel(dict_response) - assert model["prop"] == [ - {"name": "Eugene", "species": "Dog"}, - {"name": "Lady", "species": "Newt"} - ] - assert model.prop == [ - Pet({"name": "Eugene", "species": "Dog"}), - Pet({"name": "Lady", "species": "Newt"}) - ] + assert model["prop"] == [{"name": "Eugene", "species": "Dog"}, {"name": "Lady", "species": "Newt"}] + assert model.prop == [Pet({"name": "Eugene", "species": "Dog"}), Pet({"name": "Lady", "species": "Newt"})] assert len(model.prop) == 2 assert model.prop[0].name == model.prop[0]["name"] == "Eugene" assert model.prop[0].species == model.prop[0]["species"] == "Dog" @@ -621,23 +536,19 @@ class SetModel(Model): prop: Set[datetime.datetime] = rest_field() @overload - def __init__(self, *, prop: Set[datetime.datetime]): - ... + def __init__(self, *, prop: Set[datetime.datetime]): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) val_str = "9999-12-31T23:59:59.999Z" val = isodate.parse_datetime(val_str) - dict_response = { - "prop": set([val_str, val_str]) - } + dict_response = {"prop": set([val_str, val_str])} model = SetModel(dict_response) - assert model['prop'] == set([val_str, val_str]) + assert model["prop"] == set([val_str, val_str]) assert model.prop == set([val, val]) @@ -646,23 +557,19 @@ class TupleModel(Model): prop: Tuple[str, datetime.datetime] = rest_field() @overload - def __init__(self, *, prop: Tuple[str, datetime.datetime]): - ... + def __init__(self, *, prop: Tuple[str, datetime.datetime]): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) val_str = "9999-12-31T23:59:59.999Z" val = isodate.parse_datetime(val_str) - dict_response = { - "prop": (val_str, val_str) - } + dict_response = {"prop": (val_str, val_str)} model = TupleModel(dict_response) - assert model['prop'] == (val_str, val_str) + assert model["prop"] == (val_str, val_str) assert model.prop == (val_str, val) @@ -672,12 +579,10 @@ class Owner(Model): pet: Pet = rest_field() @overload - def __init__(self, *, name: str, pet: Pet): - ... + def __init__(self, *, name: str, pet: Pet): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -686,12 +591,10 @@ class ListOfTupleModel(Model): prop: List[Tuple[Pet, Owner]] = rest_field() @overload - def __init__(self, *, prop: List[Tuple[Pet, Owner]]): - ... + def __init__(self, *, prop: List[Tuple[Pet, Owner]]): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -701,19 +604,17 @@ def __init__(self, *args, **kwargs): giacamo = {"name": "Giacamo", "pet": eugene} elizabeth = {"name": "Elizabeth", "pet": lady} - dict_response: Dict[str, Any] = { - "prop": [(eugene, giacamo), (lady, elizabeth)] - } + dict_response: Dict[str, Any] = {"prop": [(eugene, giacamo), (lady, elizabeth)]} model = ListOfTupleModel(dict_response) assert ( - model['prop'] == - model.prop == - [(eugene, giacamo), (lady, elizabeth)] == - [(Pet(eugene), Owner(giacamo)), (Pet(lady), Owner(elizabeth))] + model["prop"] + == model.prop + == [(eugene, giacamo), (lady, elizabeth)] + == [(Pet(eugene), Owner(giacamo)), (Pet(lady), Owner(elizabeth))] ) - assert len(model.prop[0]) == len(model['prop'][0]) == 2 - assert model.prop[0][0].name == model.prop[0][0]['name'] == "Eugene" - assert model.prop[0][0].species == model.prop[0][0]['species'] == "Dog" + assert len(model.prop[0]) == len(model["prop"][0]) == 2 + assert model.prop[0][0].name == model.prop[0][0]["name"] == "Eugene" + assert model.prop[0][0].species == model.prop[0][0]["species"] == "Dog" assert model.prop[0][1].name == "Giacamo" assert model.prop[0][1].pet == model.prop[0][0] assert model.prop[0][1].pet.name == model.prop[0][1]["pet"]["name"] == "Eugene" @@ -736,12 +637,10 @@ def __init__( dict_of_me: Optional[Dict[str, "RecursiveModel"]] = None, dict_of_list_of_me: Optional[Dict[str, List["RecursiveModel"]]] = None, list_of_dict_of_me: Optional[List[Dict[str, "RecursiveModel"]]] = None, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -780,20 +679,21 @@ def test_model_recursion_complex(): ] }, "listOfDictOfMe": [ - {"me": { - "name": "it's me!", - "listOfMe": None, - "dictOfMe": None, - "dictOfListOfMe": None, - "listOfDictOfMe": None, - } + { + "me": { + "name": "it's me!", + "listOfMe": None, + "dictOfMe": None, + "dictOfListOfMe": None, + "listOfDictOfMe": None, + } } - ] + ], } model = RecursiveModel(dict_response) - assert model.name == model['name'] == "it's me!" - assert model['listOfMe'] == [ + assert model.name == model["name"] == "it's me!" + assert model["listOfMe"] == [ { "name": "it's me!", "listOfMe": None, @@ -802,20 +702,24 @@ def test_model_recursion_complex(): "listOfDictOfMe": None, } ] - assert model.list_of_me == [RecursiveModel({ - "name": "it's me!", - "listOfMe": None, - "dictOfMe": None, - "dictOfListOfMe": None, - "listOfDictOfMe": None, - })] + assert model.list_of_me == [ + RecursiveModel( + { + "name": "it's me!", + "listOfMe": None, + "dictOfMe": None, + "dictOfListOfMe": None, + "listOfDictOfMe": None, + } + ) + ] assert model.list_of_me assert model.list_of_me[0].name == "it's me!" assert model.list_of_me[0].list_of_me is None assert isinstance(model.list_of_me, List) assert isinstance(model.list_of_me[0], RecursiveModel) - assert model['dictOfMe'] == { + assert model["dictOfMe"] == { "me": { "name": "it's me!", "listOfMe": None, @@ -824,18 +728,22 @@ def test_model_recursion_complex(): "listOfDictOfMe": None, } } - assert model.dict_of_me == {"me": RecursiveModel({ - "name": "it's me!", - "listOfMe": None, - "dictOfMe": None, - "dictOfListOfMe": None, - "listOfDictOfMe": None, - })} + assert model.dict_of_me == { + "me": RecursiveModel( + { + "name": "it's me!", + "listOfMe": None, + "dictOfMe": None, + "dictOfListOfMe": None, + "listOfDictOfMe": None, + } + ) + } assert isinstance(model.dict_of_me, Dict) assert isinstance(model.dict_of_me["me"], RecursiveModel) - assert model['dictOfListOfMe'] == { + assert model["dictOfListOfMe"] == { "many mes": [ { "name": "it's me!", @@ -848,38 +756,45 @@ def test_model_recursion_complex(): } assert model.dict_of_list_of_me == { "many mes": [ - RecursiveModel({ - "name": "it's me!", - "listOfMe": None, - "dictOfMe": None, - "dictOfListOfMe": None, - "listOfDictOfMe": None, - }) + RecursiveModel( + { + "name": "it's me!", + "listOfMe": None, + "dictOfMe": None, + "dictOfListOfMe": None, + "listOfDictOfMe": None, + } + ) ] } assert isinstance(model.dict_of_list_of_me, Dict) assert isinstance(model.dict_of_list_of_me["many mes"], List) assert isinstance(model.dict_of_list_of_me["many mes"][0], RecursiveModel) - assert model['listOfDictOfMe'] == [ - {"me": { - "name": "it's me!", - "listOfMe": None, - "dictOfMe": None, - "dictOfListOfMe": None, - "listOfDictOfMe": None, + assert model["listOfDictOfMe"] == [ + { + "me": { + "name": "it's me!", + "listOfMe": None, + "dictOfMe": None, + "dictOfListOfMe": None, + "listOfDictOfMe": None, + } } + ] + assert model.list_of_dict_of_me == [ + { + "me": RecursiveModel( + { + "name": "it's me!", + "listOfMe": None, + "dictOfMe": None, + "dictOfListOfMe": None, + "listOfDictOfMe": None, + } + ) } ] - assert model.list_of_dict_of_me == [{ - "me": RecursiveModel({ - "name": "it's me!", - "listOfMe": None, - "dictOfMe": None, - "dictOfListOfMe": None, - "listOfDictOfMe": None, - }) - }] assert isinstance(model.list_of_dict_of_me, List) assert isinstance(model.list_of_dict_of_me[0], Dict) assert isinstance(model.list_of_dict_of_me[0]["me"], RecursiveModel) @@ -893,28 +808,20 @@ class LiteralModel(Model): age: Literal[1, 2, 3] = rest_field() @overload - def __init__(self, *, species: Literal["Mongose", "Eagle", "Penguin"], age: Literal[1, 2, 3]): - ... + def __init__(self, *, species: Literal["Mongose", "Eagle", "Penguin"], age: Literal[1, 2, 3]): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) - dict_response = { - "species": "Mongoose", - "age": 3 - } + dict_response = {"species": "Mongoose", "age": 3} model = LiteralModel(dict_response) assert model.species == model["species"] == "Mongoose" assert model.age == model["age"] == 3 - dict_response = { - "species": "invalid", - "age": 5 - } + dict_response = {"species": "invalid", "age": 5} model = LiteralModel(dict_response) assert model["species"] == "invalid" assert model["age"] == 5 @@ -932,30 +839,26 @@ class MyModel(Model): prop: Sequence[int] = rest_field() @overload - def __init__(self, *, prop: Sequence[int]): - ... + def __init__(self, *, prop: Sequence[int]): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) model_without_callback = MyModel(prop=[1.3, 2.4, 3.5]) assert model_without_callback.prop == [1.3, 2.4, 3.5] - assert model_without_callback['prop'] == [1.3, 2.4, 3.5] + assert model_without_callback["prop"] == [1.3, 2.4, 3.5] class MyModel(Model): prop: Sequence[int] = rest_field(type=_callback) @overload - def __init__(self, *, prop: Any): - ... + def __init__(self, *, prop: Any): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -964,7 +867,7 @@ def __init__(self, *args, **kwargs): assert model_with_callback.prop == ["1.3", "2.4", "3.5"] # since the deserialize function is not roundtrippable, once we deserialize # the serialized version is the same - assert model_with_callback['prop'] == [1.3, 2.4, 3.5] + assert model_with_callback["prop"] == [1.3, 2.4, 3.5] def test_deserialization_callback_override_parent(): @@ -972,12 +875,10 @@ class ParentNoCallback(Model): prop: Sequence[float] = rest_field() @overload - def __init__(self, *, prop: Sequence[float]): - ... + def __init__(self, *, prop: Sequence[float]): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -989,12 +890,10 @@ class ChildWithCallback(ParentNoCallback): prop: Sequence[float] = rest_field(type=_callback) @overload - def __init__(self, *, prop: Sequence[float]): - ... + def __init__(self, *, prop: Sequence[float]): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1004,7 +903,7 @@ def __init__(self, *args, **kwargs): child_model = ChildWithCallback(prop=[1, 1, 2, 3]) assert child_model.prop == set(["1", "1", "2", "3"]) - assert child_model['prop'] == [1, 1, 2, 3] + assert child_model["prop"] == [1, 1, 2, 3] def test_inheritance_basic(): @@ -1016,12 +915,10 @@ class Parent(Model): prop: str = rest_field() @overload - def __init__(self, *, parent_prop: List[int], prop: str): - ... + def __init__(self, *, parent_prop: List[int], prop: str): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1039,12 +936,10 @@ class ParentA(Model): prop: int = rest_field() @overload - def __init__(self, *, prop: Any): - ... + def __init__(self, *, prop: Any): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1055,12 +950,10 @@ class ParentB(ParentA): bcd_prop: Optional[List["ParentB"]] = rest_field(name="bcdProp") @overload - def __init__(self, *, prop: Any, bcd_prop: Optional[List["ParentB"]] = None): - ... + def __init__(self, *, prop: Any, bcd_prop: Optional[List["ParentB"]] = None): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1071,19 +964,10 @@ class ParentC(ParentB): cd_prop: ParentA = rest_field(name="cdProp") @overload - def __init__( - self, - *, - prop: Any, - bcd_prop: List[ParentB], - cd_prop: ParentA, - **kwargs - ): - ... + def __init__(self, *, prop: Any, bcd_prop: List[ParentB], cd_prop: ParentA, **kwargs): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1100,12 +984,10 @@ def __init__( bcd_prop: List[ParentB], cd_prop: ParentA, d_prop: Tuple[ParentA, ParentB, ParentC, Optional["ChildD"]], - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1120,12 +1002,10 @@ def __init__( self, *, prop: str, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1138,12 +1018,10 @@ def __init__( self, *, inner: Inner, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1166,12 +1044,10 @@ def __init__( self, *, prop: str, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1184,19 +1060,22 @@ def __init__( self, *, inner: List[Inner], - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def _tests(outer): - assert outer.inner[0].prop == outer["inner"][0].prop == outer.inner[0]["prop"] == outer["inner"][0][ - "prop"] == "hello" + assert ( + outer.inner[0].prop + == outer["inner"][0].prop + == outer.inner[0]["prop"] + == outer["inner"][0]["prop"] + == "hello" + ) assert outer.inner == outer["inner"] == [{"prop": "hello"}] assert outer == {"inner": [{"prop": "hello"}]} @@ -1213,12 +1092,10 @@ def __init__( self, *, prop: str, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1231,19 +1108,22 @@ def __init__( self, *, inner: Dict[str, Inner], - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def _tests(outer): - assert outer.inner["key"].prop == outer["inner"]["key"].prop == outer.inner["key"]["prop"] == \ - outer["inner"]["key"]["prop"] == "hello" + assert ( + outer.inner["key"].prop + == outer["inner"]["key"].prop + == outer.inner["key"]["prop"] + == outer["inner"]["key"]["prop"] + == "hello" + ) assert outer.inner == outer["inner"] == {"key": {"prop": "hello"}} with pytest.raises(AttributeError): outer.inner.key @@ -1257,13 +1137,13 @@ def _tests(outer): def test_inheritance_4_levels(): a = ParentA(prop=3.4) assert a.prop == 3.4 - assert a['prop'] == 3.4 + assert a["prop"] == 3.4 assert a == {"prop": 3.4} assert isinstance(a, Model) b = ParentB(prop=3.4, bcd_prop=[ParentB(prop=4.3)]) assert b.prop == "3.4" - assert b['prop'] == 3.4 + assert b["prop"] == 3.4 assert b.bcd_prop == [ParentB(prop=4.3)] assert b["bcdProp"] != [{"prop": 4.3, "bcdProp": None}] assert b["bcdProp"] == [{"prop": 4.3}] @@ -1275,34 +1155,28 @@ def test_inheritance_4_levels(): assert isinstance(b, ParentA) c = ParentC(prop=3.4, bcd_prop=[b], cd_prop=a) - assert c.prop == c['prop'] == 3.4 + assert c.prop == c["prop"] == 3.4 assert c.bcd_prop == [b] assert c.bcd_prop assert isinstance(c.bcd_prop[0], ParentB) - assert c['bcdProp'] == [b] == [{"prop": 3.4, "bcdProp": [{"prop": 4.3}]}] + assert c["bcdProp"] == [b] == [{"prop": 3.4, "bcdProp": [{"prop": 4.3}]}] assert c.cd_prop == a - assert c['cdProp'] == a == {"prop": 3.4} + assert c["cdProp"] == a == {"prop": 3.4} assert isinstance(c.cd_prop, ParentA) - d = ChildD(prop=3.4, bcd_prop=[b], cd_prop=a, - d_prop=(a, b, c, ChildD(prop=3.4, bcd_prop=[b], cd_prop=a, d_prop=(a, b, c, None)))) + d = ChildD( + prop=3.4, + bcd_prop=[b], + cd_prop=a, + d_prop=(a, b, c, ChildD(prop=3.4, bcd_prop=[b], cd_prop=a, d_prop=(a, b, c, None))), + ) assert d == { - 'prop': 3.4, - 'bcdProp': [b], - 'cdProp': a, - 'dProp': ( - a, b, c, - { - 'prop': 3.4, - 'bcdProp': [b], - 'cdProp': a, - 'dProp': ( - a, b, c, None - ) - } - ) + "prop": 3.4, + "bcdProp": [b], + "cdProp": a, + "dProp": (a, b, c, {"prop": 3.4, "bcdProp": [b], "cdProp": a, "dProp": (a, b, c, None)}), } - assert d.prop == d['prop'] == 3.4 + assert d.prop == d["prop"] == 3.4 assert d.bcd_prop == [b] assert d.bcd_prop assert isinstance(d.bcd_prop[0], ParentB) @@ -1331,12 +1205,10 @@ def __init__( self, *, parent_one_prop: str, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1349,12 +1221,10 @@ def __init__( self, *, parent_two_prop: int, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1367,12 +1237,10 @@ def __init__( *, parent_one_prop: str, parent_two_prop: int, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1391,12 +1259,10 @@ class A(Model): prop: str = rest_field() @overload - def __init__(self, *, prop: str) -> None: - ... + def __init__(self, *, prop: str) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1405,12 +1271,10 @@ class B(Model): prop: int = rest_field(type=lambda x: int(x)) @overload - def __init__(self, *, prop: str) -> None: - ... + def __init__(self, *, prop: str) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1435,12 +1299,10 @@ def __init__( meows: bool, hisses: bool, siblings: Optional[List["Feline"]] = None, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1456,12 +1318,10 @@ def __init__( *, first_name: str, last_name: str, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1472,12 +1332,10 @@ class PetModel(Model): owner: Owner = rest_field() @overload - def __init__(self, *, name: str, owner: Owner): - ... + def __init__(self, *, name: str, owner: Owner): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1496,12 +1354,10 @@ def __init__( hisses: bool, likes_milk: bool, siblings: Optional[List[Feline]], - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1511,12 +1367,10 @@ class CuteThing(Model): how_cute_am_i: float = rest_field(name="howCuteAmI") @overload - def __init__(self, *, how_cute_am_i: float): - ... + def __init__(self, *, how_cute_am_i: float): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1537,12 +1391,10 @@ def __init__( siblings: Optional[List[Feline]], how_cute_am_i: float, eats_mice_yet: bool, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1555,7 +1407,7 @@ def test_multiple_inheritance_complex(): meows=True, hisses=True, likes_milk=False, # likes_milk will change to True on the attribute - siblings=[Feline(meows=True, hisses=False)] + siblings=[Feline(meows=True, hisses=False)], ) assert cat == { "name": "Stephanie", @@ -1566,10 +1418,12 @@ def test_multiple_inheritance_complex(): "meows": True, "hisses": True, "likesMilk": False, - "siblings": [{ - "meows": True, - "hisses": False, - }] + "siblings": [ + { + "meows": True, + "hisses": False, + } + ], } assert cat.name == "Stephanie" assert isinstance(cat.owner, Owner) @@ -1601,11 +1455,7 @@ def test_multiple_inheritance_complex(): "meows": True, "hisses": True, "likesMilk": False, - "siblings": [{ - "meows": True, - "hisses": False, - "siblings": None # we don't automatically set None here - }], + "siblings": [{"meows": True, "hisses": False, "siblings": None}], # we don't automatically set None here "howCuteAmI": 1.0, "eatsMiceYet": True, } @@ -1618,10 +1468,12 @@ def test_multiple_inheritance_complex(): "meows": True, "hisses": True, "likesMilk": False, - "siblings": [{ - "meows": True, - "hisses": False, - }], + "siblings": [ + { + "meows": True, + "hisses": False, + } + ], "howCuteAmI": 1.0, "eatsMiceYet": True, } @@ -1647,12 +1499,10 @@ class A(Model): b: "B" = rest_field() @overload - def __init__(self, b: "B"): - ... + def __init__(self, b: "B"): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1662,12 +1512,10 @@ class B(Model): c: "C" = rest_field() @overload - def __init__(self, *, c: "C"): - ... + def __init__(self, *, c: "C"): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1677,12 +1525,10 @@ class C(Model): d: str = rest_field() @overload - def __init__(self, *, d: str): - ... + def __init__(self, *, d: str): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1692,22 +1538,17 @@ def test_nested_creation(): a = A({"b": {"c": {"d": "hello"}}}) assert isinstance(a["b"], Model) assert isinstance(a["b"]["c"], Model) - assert ( - a["b"]["c"] == - a["b"].c == - a.b.c - == {"d": "hello"} - ) + assert a["b"]["c"] == a["b"].c == a.b.c == {"d": "hello"} assert ( - a["b"]["c"]["d"] == - a["b"].c.d == - a.b["c"].d == - a["b"]["c"].d == - a["b"].c["d"] == - a.b["c"]["d"] == - a.b.c.d == - "hello" + a["b"]["c"]["d"] + == a["b"].c.d + == a.b["c"].d + == a["b"]["c"].d + == a["b"].c["d"] + == a.b["c"]["d"] + == a.b.c.d + == "hello" ) @@ -1717,28 +1558,28 @@ def test_nested_setting(): # set with dict a["b"]["c"]["d"] = "setwithdict" assert ( - a["b"]["c"]["d"] == - a["b"].c.d == - a.b["c"].d == - a["b"]["c"].d == - a["b"].c["d"] == - a.b["c"]["d"] == - a.b.c.d == - "setwithdict" + a["b"]["c"]["d"] + == a["b"].c.d + == a.b["c"].d + == a["b"]["c"].d + == a["b"].c["d"] + == a.b["c"]["d"] + == a.b.c.d + == "setwithdict" ) # set with attr a.b.c.d = "setwithattr" assert a["b"]["c"]["d"] == "setwithattr" assert ( - a["b"]["c"]["d"] == - a["b"].c.d == - a.b["c"].d == - a["b"]["c"].d == - a["b"].c["d"] == - a.b["c"]["d"] == - a.b.c.d == - "setwithattr" + a["b"]["c"]["d"] + == a["b"].c.d + == a.b["c"].d + == a["b"]["c"].d + == a["b"].c["d"] + == a.b["c"]["d"] + == a.b.c.d + == "setwithattr" ) @@ -1746,12 +1587,10 @@ class BaseModel(Model): inner_model: "InnerModel" = rest_field(name="innerModel") @overload - def __init__(self, *, inner_model: "InnerModel"): - ... + def __init__(self, *, inner_model: "InnerModel"): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1761,12 +1600,10 @@ class InnerModel(Model): datetime_field: datetime.datetime = rest_field(name="datetimeField") @overload - def __init__(self, *, datetime_field: datetime.datetime): - ... + def __init__(self, *, datetime_field: datetime.datetime): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1777,24 +1614,25 @@ def test_nested_deserialization(): model = BaseModel({"innerModel": {"datetimeField": serialized_datetime}}) assert model.inner_model["datetimeField"] == model["innerModel"]["datetimeField"] == serialized_datetime - assert model.inner_model.datetime_field == model["innerModel"].datetime_field == isodate.parse_datetime( - serialized_datetime) + assert ( + model.inner_model.datetime_field + == model["innerModel"].datetime_field + == isodate.parse_datetime(serialized_datetime) + ) new_serialized_datetime = "2022-12-31T23:59:59.999Z" model.inner_model.datetime_field = isodate.parse_datetime(new_serialized_datetime) - assert model.inner_model["datetimeField"] == '2022-12-31T23:59:59.999000Z' + assert model.inner_model["datetimeField"] == "2022-12-31T23:59:59.999000Z" class X(Model): y: "Y" = rest_field() @overload - def __init__(self, *, y: "Y"): - ... + def __init__(self, *, y: "Y"): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1804,12 +1642,10 @@ class Y(Model): z: "Z" = rest_field() @overload - def __init__(self, *, z: "Z"): - ... + def __init__(self, *, z: "Z"): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1819,12 +1655,10 @@ class Z(Model): zval: datetime.datetime = rest_field() @overload - def __init__(self, *, zval: datetime.datetime): - ... + def __init__(self, *, zval: datetime.datetime): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1834,20 +1668,8 @@ def test_nested_update(): serialized_datetime = "9999-12-31T23:59:59.999Z" parsed_datetime = isodate.parse_datetime(serialized_datetime) x = X({"y": {"z": {"zval": serialized_datetime}}}) - assert ( - x.y.z.zval == - x["y"].z.zval == - x.y["z"].zval == - x["y"]["z"].zval == - parsed_datetime - ) - assert ( - x.y.z["zval"] == - x.y["z"]["zval"] == - x["y"].z["zval"] == - x["y"]["z"]["zval"] == - serialized_datetime - ) + assert x.y.z.zval == x["y"].z.zval == x.y["z"].zval == x["y"]["z"].zval == parsed_datetime + assert x.y.z["zval"] == x.y["z"]["zval"] == x["y"].z["zval"] == x["y"]["z"]["zval"] == serialized_datetime def test_deserialization_is(): @@ -1870,12 +1692,10 @@ class InnerModelWithReadonly(Model): readonly_property: str = rest_field(name="readonlyProperty", visibility=["read"]) @overload - def __init__(self, *, normal_property: str): - ... + def __init__(self, *, normal_property: str): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1887,12 +1707,10 @@ class ModelWithReadonly(Model): inner_model: InnerModelWithReadonly = rest_field(name="innerModel") @overload - def __init__(self, *, normal_property: str): - ... + def __init__(self, *, normal_property: str): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -1903,14 +1721,13 @@ def test_readonly(): value = { "normalProperty": "normal", "readonlyProperty": "readonly", - "innerModel": { - "normalProperty": "normal", - "readonlyProperty": "readonly" - } + "innerModel": {"normalProperty": "normal", "readonlyProperty": "readonly"}, } model = ModelWithReadonly(value) - assert model.as_dict(exclude_readonly=True) == {"normalProperty": "normal", - "innerModel": {"normalProperty": "normal"}} + assert model.as_dict(exclude_readonly=True) == { + "normalProperty": "normal", + "innerModel": {"normalProperty": "normal"}, + } assert json.loads(json.dumps(model, cls=SdkJSONEncoder)) == value assert model == value assert model["readonlyProperty"] == model.readonly_property == "readonly" @@ -1921,10 +1738,7 @@ def test_readonly_set(): value = { "normalProperty": "normal", "readonlyProperty": "readonly", - "innerModel": { - "normalProperty": "normal", - "readonlyProperty": "readonly" - } + "innerModel": {"normalProperty": "normal", "readonlyProperty": "readonly"}, } model = ModelWithReadonly(value) @@ -1933,8 +1747,10 @@ def test_readonly_set(): assert model.inner_model.normal_property == model.inner_model["normalProperty"] == "normal" assert model.inner_model.readonly_property == model.inner_model["readonlyProperty"] == "readonly" - assert model.as_dict(exclude_readonly=True) == {"normalProperty": "normal", - "innerModel": {"normalProperty": "normal"}} + assert model.as_dict(exclude_readonly=True) == { + "normalProperty": "normal", + "innerModel": {"normalProperty": "normal"}, + } assert json.loads(json.dumps(model, cls=SdkJSONEncoder)) == value model["normalProperty"] = "setWithDict" @@ -1946,15 +1762,14 @@ def test_readonly_set(): assert model.readonly_property == model["readonlyProperty"] == "setWithDict" assert model.inner_model.normal_property == model.inner_model["normalProperty"] == "setWithDict" assert model.inner_model.readonly_property == model.inner_model["readonlyProperty"] == "setWithDict" - assert model.as_dict(exclude_readonly=True) == {"normalProperty": "setWithDict", - "innerModel": {"normalProperty": "setWithDict"}} + assert model.as_dict(exclude_readonly=True) == { + "normalProperty": "setWithDict", + "innerModel": {"normalProperty": "setWithDict"}, + } assert json.loads(json.dumps(model, cls=SdkJSONEncoder)) == { "normalProperty": "setWithDict", "readonlyProperty": "setWithDict", - "innerModel": { - "normalProperty": "setWithDict", - "readonlyProperty": "setWithDict" - } + "innerModel": {"normalProperty": "setWithDict", "readonlyProperty": "setWithDict"}, } @@ -1964,12 +1779,15 @@ class MyModel(Model): field: str = rest_field() @overload - def __init__(self, *, id: int, field: str, ): - ... + def __init__( + self, + *, + id: int, + field: str, + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -2006,12 +1824,10 @@ class TestModel(Model): data: List[int] = rest_field() @overload - def __init__(self, *, data: List[int]): - ... + def __init__(self, *, data: List[int]): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -2029,12 +1845,10 @@ class InnerModel(Model): prop: str = rest_field(type=lambda x: x[::-1]) @overload - def __init__(self, *, prop: str): - ... + def __init__(self, *, prop: str): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -2043,12 +1857,10 @@ class OuterModel(Model): innie: InnerModel = rest_field() @overload - def __init__(self, *, innie: InnerModel): - ... + def __init__(self, *, innie: InnerModel): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -2073,12 +1885,10 @@ def __init__( prop_optional_str: Optional[str] = "propOptionalStr", prop_default_int: int = 1, prop_optional_int: Optional[int] = None, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -2092,7 +1902,7 @@ def __init__(self, *args, **kwargs): "propDefaultStr": "hello", "propOptionalStr": None, "propDefaultInt": 1, - "propOptionalInt": None + "propOptionalInt": None, } my_model = MyModel(prop_default_str="goodbye") @@ -2104,7 +1914,7 @@ def __init__(self, *args, **kwargs): "propDefaultStr": "goodbye", "propOptionalStr": None, "propDefaultInt": 1, - "propOptionalInt": None + "propOptionalInt": None, } my_model = MyModel(prop_optional_int=4) @@ -2112,12 +1922,7 @@ def __init__(self, *args, **kwargs): assert my_model.prop_optional_str is my_model["propOptionalStr"] is None assert my_model.prop_default_int == my_model["propDefaultInt"] == 1 assert my_model.prop_optional_int == my_model["propOptionalInt"] == 4 - assert my_model == { - "propDefaultStr": "hello", - "propOptionalStr": None, - "propDefaultInt": 1, - "propOptionalInt": 4 - } + assert my_model == {"propDefaultStr": "hello", "propOptionalStr": None, "propDefaultInt": 1, "propOptionalInt": 4} my_model = MyModel({"propDefaultInt": 5}) assert my_model.prop_default_str == my_model["propDefaultStr"] == "hello" @@ -2128,7 +1933,7 @@ def __init__(self, *args, **kwargs): "propDefaultStr": "hello", "propOptionalStr": None, "propDefaultInt": 5, - "propOptionalInt": None + "propOptionalInt": None, } @@ -2141,12 +1946,10 @@ def __init__( self, *, str_property: str, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -2159,27 +1962,25 @@ def __init__( self, *, inner_property: Inner, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def _tests(model: Outer): assert ( - {"innerProperty": {"strProperty": "hello"}} == - {"innerProperty": Inner(str_property="hello")} == - {"innerProperty": Inner({"strProperty": "hello"})} == - Outer(inner_property=Inner(str_property="hello")) == - Outer(inner_property=Inner({"strProperty": "hello"})) == - Outer({"innerProperty": {"strProperty": "hello"}}) == - Outer({"innerProperty": Inner(str_property="hello")}) == - Outer({"innerProperty": Inner({"strProperty": "hello"})}) == - model + {"innerProperty": {"strProperty": "hello"}} + == {"innerProperty": Inner(str_property="hello")} + == {"innerProperty": Inner({"strProperty": "hello"})} + == Outer(inner_property=Inner(str_property="hello")) + == Outer(inner_property=Inner({"strProperty": "hello"})) + == Outer({"innerProperty": {"strProperty": "hello"}}) + == Outer({"innerProperty": Inner(str_property="hello")}) + == Outer({"innerProperty": Inner({"strProperty": "hello"})}) + == model ) _tests(Outer(inner_property=Inner(str_property="hello"))) @@ -2198,12 +1999,10 @@ def __init__( self, *, str_property: str, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -2218,12 +2017,10 @@ def __init__( *, inner_property: List[Inner], prop: str, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -2236,12 +2033,10 @@ def __init__( self, *, middle_property: Model, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -2263,36 +2058,33 @@ def __init__(self, *args, **kwargs): assert model["middleProperty"]["prop"] == model.middle_property.prop == "newest" # modify innerproperty list + assert model["middleProperty"]["innerProperty"][0] is model.middle_property.inner_property[0] assert ( - model["middleProperty"]["innerProperty"][0] is - model.middle_property.inner_property[0] - ) - assert ( - model["middleProperty"]["innerProperty"][0] is - model.middle_property["innerProperty"][0] is - model["middleProperty"].inner_property[0] is - model.middle_property.inner_property[0] + model["middleProperty"]["innerProperty"][0] + is model.middle_property["innerProperty"][0] + is model["middleProperty"].inner_property[0] + is model.middle_property.inner_property[0] ) inner_property = model["middleProperty"]["innerProperty"][0] # set with dict syntax inner_property["strProperty"] = "nihao" assert ( - model["middleProperty"]["innerProperty"][0] is - model.middle_property["innerProperty"][0] is - model["middleProperty"].inner_property[0] is - model.middle_property.inner_property[0] + model["middleProperty"]["innerProperty"][0] + is model.middle_property["innerProperty"][0] + is model["middleProperty"].inner_property[0] + is model.middle_property.inner_property[0] ) assert ( - model["middleProperty"]["innerProperty"][0]["strProperty"] == - model.middle_property["innerProperty"][0]["strProperty"] == - model["middleProperty"].inner_property[0]["strProperty"] == - model.middle_property.inner_property[0]["strProperty"] == - model["middleProperty"]["innerProperty"][0].str_property == - model.middle_property["innerProperty"][0].str_property == - model["middleProperty"].inner_property[0].str_property == - model.middle_property.inner_property[0].str_property == - "nihao" + model["middleProperty"]["innerProperty"][0]["strProperty"] + == model.middle_property["innerProperty"][0]["strProperty"] + == model["middleProperty"].inner_property[0]["strProperty"] + == model.middle_property.inner_property[0]["strProperty"] + == model["middleProperty"]["innerProperty"][0].str_property + == model.middle_property["innerProperty"][0].str_property + == model["middleProperty"].inner_property[0].str_property + == model.middle_property.inner_property[0].str_property + == "nihao" ) @@ -2305,12 +2097,10 @@ def __init__( self, *, str_property: str, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -2325,12 +2115,10 @@ def __init__( *, inner_property: Dict[str, Inner], prop: str, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -2343,12 +2131,10 @@ def __init__( self, *, middle_property: Model, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -2363,11 +2149,11 @@ def __init__(self, *args, **kwargs): middle_property["prop"] = "new" assert model["middleProperty"] is model.middle_property is middle_property assert ( - model["middleProperty"]["prop"] == - model["middleProperty"].prop == - model.middle_property.prop == - model.middle_property["prop"] == - "new" + model["middleProperty"]["prop"] + == model["middleProperty"].prop + == model.middle_property.prop + == model.middle_property["prop"] + == "new" ) # set with attr syntax @@ -2376,36 +2162,33 @@ def __init__(self, *args, **kwargs): assert model["middleProperty"]["prop"] == model.middle_property.prop == "newest" # modify innerproperty list + assert model["middleProperty"]["innerProperty"]["inner"] is model.middle_property.inner_property["inner"] assert ( - model["middleProperty"]["innerProperty"]["inner"] is - model.middle_property.inner_property["inner"] - ) - assert ( - model["middleProperty"]["innerProperty"]["inner"] is - model.middle_property["innerProperty"]["inner"] is - model["middleProperty"].inner_property["inner"] is - model.middle_property.inner_property["inner"] + model["middleProperty"]["innerProperty"]["inner"] + is model.middle_property["innerProperty"]["inner"] + is model["middleProperty"].inner_property["inner"] + is model.middle_property.inner_property["inner"] ) inner_property = model["middleProperty"]["innerProperty"]["inner"] # set with dict syntax inner_property["strProperty"] = "nihao" assert ( - model["middleProperty"]["innerProperty"]["inner"] is - model.middle_property["innerProperty"]["inner"] is - model["middleProperty"].inner_property["inner"] is - model.middle_property.inner_property["inner"] + model["middleProperty"]["innerProperty"]["inner"] + is model.middle_property["innerProperty"]["inner"] + is model["middleProperty"].inner_property["inner"] + is model.middle_property.inner_property["inner"] ) assert ( - model["middleProperty"]["innerProperty"]["inner"]["strProperty"] == - model.middle_property["innerProperty"]["inner"]["strProperty"] == - model["middleProperty"].inner_property["inner"]["strProperty"] == - model.middle_property.inner_property["inner"]["strProperty"] == - model["middleProperty"]["innerProperty"]["inner"].str_property == - model.middle_property["innerProperty"]["inner"].str_property == - model["middleProperty"].inner_property["inner"].str_property == - model.middle_property.inner_property["inner"].str_property == - "nihao" + model["middleProperty"]["innerProperty"]["inner"]["strProperty"] + == model.middle_property["innerProperty"]["inner"]["strProperty"] + == model["middleProperty"].inner_property["inner"]["strProperty"] + == model.middle_property.inner_property["inner"]["strProperty"] + == model["middleProperty"]["innerProperty"]["inner"].str_property + == model.middle_property["innerProperty"]["inner"].str_property + == model["middleProperty"].inner_property["inner"].str_property + == model.middle_property.inner_property["inner"].str_property + == "nihao" ) @@ -2416,7 +2199,7 @@ class TestModel(Model): my_dict = {} my_dict["x"] = None - assert my_dict['x'] is None + assert my_dict["x"] is None my_model = TestModel({}) my_model["x"] = None @@ -2453,12 +2236,10 @@ def __init__( self, *, str_property: str, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -2473,12 +2254,10 @@ def __init__( *, inner_property: Dict[str, Inner], prop: str, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -2491,12 +2270,10 @@ def __init__( self, *, middle_property: Model, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -2507,10 +2284,10 @@ def __init__(self, *args, **kwargs): assert model_dict is not original_dict is not model_attr assert ( - original_dict["middleProperty"]["innerProperty"]["inner"].pop("strProperty") == - model_dict["middleProperty"]["innerProperty"]["inner"].pop("strProperty") == - model_attr.middle_property.inner_property["inner"].pop("strProperty") == - "hello" + original_dict["middleProperty"]["innerProperty"]["inner"].pop("strProperty") + == model_dict["middleProperty"]["innerProperty"]["inner"].pop("strProperty") + == model_attr.middle_property.inner_property["inner"].pop("strProperty") + == "hello" ) with pytest.raises(KeyError): @@ -2530,12 +2307,10 @@ def __init__( self, *, a_prop: str, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -2548,12 +2323,10 @@ def __init__( self, *, b_prop: str, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -2568,12 +2341,10 @@ def __init__( a_prop: str, b_prop: str, c_prop: str, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -2614,28 +2385,20 @@ def __init__(self, *args, **kwargs): def test_iter(): - dict_response = { - "platformUpdateDomainCount": 5, - "platformFaultDomainCount": 3, - "virtualMachines": [] - } + dict_response = {"platformUpdateDomainCount": 5, "platformFaultDomainCount": 3, "virtualMachines": []} assert isinstance(iter(dict_response), Iterable) model = BasicResource(dict_response) assert isinstance(iter(model), Iterable) assert ( - list(iter(dict_response)) == - list(iter(model)) == - ["platformUpdateDomainCount", "platformFaultDomainCount", "virtualMachines"] + list(iter(dict_response)) + == list(iter(model)) + == ["platformUpdateDomainCount", "platformFaultDomainCount", "virtualMachines"] ) def test_len(): - dict_response = { - "platformUpdateDomainCount": 5, - "platformFaultDomainCount": 3, - "virtualMachines": [] - } + dict_response = {"platformUpdateDomainCount": 5, "platformFaultDomainCount": 3, "virtualMachines": []} model = BasicResource(dict_response) assert len(dict_response) == len(model) == 3 @@ -2820,12 +2583,7 @@ def _tests(my_dict: Dict[str, Any], my_model: MainModel): _tests(my_dict, MainModel(my_dict)) _tests( - my_dict, - MainModel( - a_prop=ModelA(a_str_prop="a"), - b_prop=ModelB(b_str_prop="b"), - c_prop=ModelC(c_str_prop="c") - ) + my_dict, MainModel(a_prop=ModelA(a_str_prop="a"), b_prop=ModelB(b_str_prop="b"), c_prop=ModelC(c_str_prop="c")) ) @@ -2864,12 +2622,7 @@ def _tests(my_dict: Dict[str, Any], my_model: MainModel): _tests(my_dict, MainModel(my_dict)) _tests( - my_dict, - MainModel( - a_prop=ModelA(a_str_prop="a"), - b_prop=ModelB(b_str_prop="b"), - c_prop=ModelC(c_str_prop="c") - ) + my_dict, MainModel(a_prop=ModelA(a_str_prop="a"), b_prop=ModelB(b_str_prop="b"), c_prop=ModelC(c_str_prop="c")) ) @@ -2910,12 +2663,7 @@ def _tests(my_dict: Dict[str, Any], my_model: MainModel): _tests(my_dict, MainModel(my_dict)) _tests( - my_dict, - MainModel( - a_prop=ModelA(a_str_prop="a"), - b_prop=ModelB(b_str_prop="b"), - c_prop=ModelC(c_str_prop="c") - ) + my_dict, MainModel(a_prop=ModelA(a_str_prop="a"), b_prop=ModelB(b_str_prop="b"), c_prop=ModelC(c_str_prop="c")) ) @@ -2934,10 +2682,10 @@ class Outer(Model): assert og_dict["innerProp"] == og_model["innerProp"] == og_model.inner_prop == {"strProp": "actualDefault"} assert ( - og_dict["innerProp"].setdefault("strProp") == - og_model["innerProp"].setdefault("strProp") == - og_model.inner_prop.setdefault("strProp") == - "actualDefault" + og_dict["innerProp"].setdefault("strProp") + == og_model["innerProp"].setdefault("strProp") + == og_model.inner_prop.setdefault("strProp") + == "actualDefault" ) assert og_dict.setdefault("newProp") is og_model.setdefault("newProp") is None @@ -2966,6 +2714,7 @@ class MainModel(Model): ##### REWRITE BODY COMPLEX INTO THIS FILE ##### + def test_complex_basic(): class Basic(Model): id: Optional[int] = rest_field(default=None) @@ -2979,17 +2728,15 @@ def __init__( id: Optional[int] = None, name: Optional[str] = None, color: Optional[Literal["cyan", "Magenta", "YELLOW", "blacK"]] = None, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) - basic = Basic(id=2, name='abc', color="Magenta") + basic = Basic(id=2, name="abc", color="Magenta") assert basic == {"id": 2, "name": "abc", "color": "Magenta"} basic.id = 3 @@ -3016,12 +2763,10 @@ def __init__( *, field_true: Optional[bool] = None, field_false: Optional[bool] = None, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -3054,12 +2799,10 @@ def __init__( base64url: Optional[bytes] = None, list_base64: Optional[List[bytes]] = None, map_base64url: Optional[Dict[str, bytes]] = None, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -3126,12 +2869,10 @@ def __init__( base64url: Optional[bytearray] = None, list_base64: Optional[List[bytearray]] = None, map_base64url: Optional[Dict[str, bytearray]] = None, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -3159,20 +2900,26 @@ def _tests(model: ByteArrayWrapper): assert model["list_base64"] == [decoded, decoded] assert model["map_base64url"] == {"key1": decoded_urlsafe, "key2": decoded_urlsafe} - _tests(ByteArrayWrapper( - default=byte_array, - base64=byte_array, - base64url=byte_array, - list_base64=[byte_array, byte_array], - map_base64url={"key1": byte_array, "key2": byte_array} - )) - _tests(ByteArrayWrapper({ - "default": decoded, - "base64": decoded, - "base64url": decoded_urlsafe, - "list_base64": [decoded, decoded], - "map_base64url": {"key1": decoded_urlsafe, "key2": decoded_urlsafe} - })) + _tests( + ByteArrayWrapper( + default=byte_array, + base64=byte_array, + base64url=byte_array, + list_base64=[byte_array, byte_array], + map_base64url={"key1": byte_array, "key2": byte_array}, + ) + ) + _tests( + ByteArrayWrapper( + { + "default": decoded, + "base64": decoded, + "base64url": decoded_urlsafe, + "list_base64": [decoded, decoded], + "map_base64url": {"key1": decoded_urlsafe, "key2": decoded_urlsafe}, + } + ) + ) def test_complex_datetime_wrapper(): @@ -3194,12 +2941,10 @@ def __init__( unix: Optional[datetime.datetime] = None, list_rfc3339: Optional[List[datetime.datetime]] = None, dict_rfc7231: Optional[Dict[str, datetime.datetime]] = None, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -3220,22 +2965,23 @@ def _tests(model: DatetimeWrapper): assert model.list_rfc3339 == [dt, dt] assert model.dict_rfc7231 == {"key1": dt, "key2": dt} - _tests(DatetimeWrapper( - default=dt, - rfc3339=dt, - rfc7231=dt, - unix=dt, - list_rfc3339=[dt, dt], - dict_rfc7231={"key1": dt, "key2": dt} - )) - _tests(DatetimeWrapper({ - "default": rfc3339, - "rfc3339": rfc3339, - "rfc7231": rfc7231, - "unix": unix, - "list_rfc3339": [rfc3339, rfc3339], - "dict_rfc7231": {"key1": rfc7231, "key2": rfc7231} - })) + _tests( + DatetimeWrapper( + default=dt, rfc3339=dt, rfc7231=dt, unix=dt, list_rfc3339=[dt, dt], dict_rfc7231={"key1": dt, "key2": dt} + ) + ) + _tests( + DatetimeWrapper( + { + "default": rfc3339, + "rfc3339": rfc3339, + "rfc7231": rfc7231, + "unix": unix, + "list_rfc3339": [rfc3339, rfc3339], + "dict_rfc7231": {"key1": rfc7231, "key2": rfc7231}, + } + ) + ) def test_complex_date_wrapper(): @@ -3249,12 +2995,10 @@ def __init__( *, field: Optional[datetime.date] = None, leap: Optional[datetime.date] = None, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -3289,22 +3033,22 @@ def __init__( self, *, default_program: Optional[Dict[str, str]] = None, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) -default_program = {'txt': 'notepad', 'bmp': 'mspaint', 'xls': 'excel', 'exe': '', '': None} +default_program = {"txt": "notepad", "bmp": "mspaint", "xls": "excel", "exe": "", "": None} -@pytest.mark.parametrize("model", [DictionaryWrapper({"defaultProgram": default_program}), - DictionaryWrapper(default_program=default_program)]) +@pytest.mark.parametrize( + "model", + [DictionaryWrapper({"defaultProgram": default_program}), DictionaryWrapper(default_program=default_program)], +) def test_complex_dictionary_wrapper(model: DictionaryWrapper): assert model == {"defaultProgram": default_program} assert model.default_program == model["defaultProgram"] == default_program @@ -3316,8 +3060,9 @@ def test_complex_dictionary_wrapper_empty(model: DictionaryWrapper): assert model.default_program == model["defaultProgram"] == {} -@pytest.mark.parametrize("model", - [DictionaryWrapper({"defaultProgram": None}), DictionaryWrapper(default_program=None)]) +@pytest.mark.parametrize( + "model", [DictionaryWrapper({"defaultProgram": None}), DictionaryWrapper(default_program=None)] +) def test_complex_dictionary_wrapper_none(model: DictionaryWrapper): assert model == {"defaultProgram": None} assert model.default_program is None @@ -3331,12 +3076,10 @@ def __init__( self, *, array: Optional[List[str]] = None, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -3388,12 +3131,10 @@ def __init__( *, id: Optional[int] = None, name: Optional[str] = None, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -3409,12 +3150,10 @@ def __init__( id: Optional[int] = None, name: Optional[str] = None, food: Optional[str] = None, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -3433,12 +3172,10 @@ def __init__( food: Optional[str] = None, color: Optional[str] = None, hates: Optional[List[DogComplex]] = None, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -3447,19 +3184,31 @@ def __init__(self, *args, **kwargs): @pytest.mark.parametrize( "model", [ - CatComplex(id=2, name="Siameeee", hates=[ - DogComplex(id=1, name="Potato", food="tomato"), - DogComplex(id=-1, name="Tomato", food="french fries") - ]), - CatComplex(id=2, name="Siameeee", hates=[ - DogComplex(id=1, name="Potato", food="tomato"), - {"id": -1, "name": "Tomato", "food": "french fries"}, - ]), - CatComplex(id=2, name="Siameeee", hates=[ - {"id": 1, "name": "Potato", "food": "tomato"}, - {"id": -1, "name": "Tomato", "food": "french fries"}, - ]), - ] + CatComplex( + id=2, + name="Siameeee", + hates=[ + DogComplex(id=1, name="Potato", food="tomato"), + DogComplex(id=-1, name="Tomato", food="french fries"), + ], + ), + CatComplex( + id=2, + name="Siameeee", + hates=[ + DogComplex(id=1, name="Potato", food="tomato"), + {"id": -1, "name": "Tomato", "food": "french fries"}, + ], + ), + CatComplex( + id=2, + name="Siameeee", + hates=[ + {"id": 1, "name": "Potato", "food": "tomato"}, + {"id": -1, "name": "Tomato", "food": "french fries"}, + ], + ), + ], ) def test_complex_inheritance(model): assert model.id == model["id"] == 2 @@ -3471,12 +3220,14 @@ def test_complex_inheritance(model): with pytest.raises(AttributeError): model.breed assert model == { - 'id': 2, - 'name': "Siameeee", - 'color': "green", - 'breed': "persian", - 'hates': [DogComplex(id=1, name="Potato", food="tomato"), - DogComplex(id=-1, name="Tomato", food="french fries")] + "id": 2, + "name": "Siameeee", + "color": "green", + "breed": "persian", + "hates": [ + DogComplex(id=1, name="Potato", food="tomato"), + DogComplex(id=-1, name="Tomato", food="french fries"), + ], } @@ -3489,12 +3240,10 @@ def __init__( self, *, required_property: int, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -3530,7 +3279,7 @@ def test_null_serilization(core_library): } ] }, - "listOfDictOfMe": None + "listOfDictOfMe": None, } model = RecursiveModel(dict_response) assert json.loads(json.dumps(model, cls=SdkJSONEncoder)) == dict_response @@ -3569,7 +3318,7 @@ def test_null_serilization(core_library): "listOfMe": None, } } - ] + ], } assert model.as_dict() == { @@ -3590,7 +3339,7 @@ def test_null_serilization(core_library): "listOfMe": None, } } - ] + ], } @@ -3598,12 +3347,10 @@ class UnionBaseModel(Model): name: str = rest_field() @overload - def __init__(self, *, name: str): - ... + def __init__(self, *, name: str): ... @overload - def __init__(self, mapping: Mapping[str, Any]): - ... + def __init__(self, mapping: Mapping[str, Any]): ... def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) @@ -3613,12 +3360,10 @@ class UnionModel1(UnionBaseModel): prop1: int = rest_field() @overload - def __init__(self, *, name: str, prop1: int): - ... + def __init__(self, *, name: str, prop1: int): ... @overload - def __init__(self, mapping: Mapping[str, Any]): - ... + def __init__(self, mapping: Mapping[str, Any]): ... def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) @@ -3628,12 +3373,10 @@ class UnionModel2(UnionBaseModel): prop2: int = rest_field() @overload - def __init__(self, *, name: str, prop2: int): - ... + def __init__(self, *, name: str, prop2: int): ... @overload - def __init__(self, mapping: Mapping[str, Any]): - ... + def __init__(self, mapping: Mapping[str, Any]): ... def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) @@ -3646,12 +3389,10 @@ class ModelWithNamedUnionProperty(Model): named_union: "MyNamedUnion" = rest_field(name="namedUnion") @overload - def __init__(self, *, named_union: "MyNamedUnion"): - ... + def __init__(self, *, named_union: "MyNamedUnion"): ... @overload - def __init__(self, mapping: Mapping[str, Any]): - ... + def __init__(self, mapping: Mapping[str, Any]): ... def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) @@ -3661,12 +3402,10 @@ class ModelWithSimpleUnionProperty(Model): simple_union: Union[int, List[int]] = rest_field(name="simpleUnion") @overload - def __init__(self, *, simple_union: Union[int, List[int]]): - ... + def __init__(self, *, simple_union: Union[int, List[int]]): ... @overload - def __init__(self, mapping: Mapping[str, Any]): - ... + def __init__(self, mapping: Mapping[str, Any]): ... def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) @@ -3702,25 +3441,20 @@ def __init__( food: Optional[str] = None, color: Optional[str] = None, hates: Optional[List[DogComplex]] = None, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) - model = CatComplex(id=2, name="Siameeee", hates=[ - DogComplex(id=1, name="Potato", food="tomato"), - DogComplex(id=-1, name="Tomato", food="french fries") - ]) - assert model.as_dict(exclude_readonly=True) == { - "id": 2, - "name": "Siameeee", - "color": None - } + model = CatComplex( + id=2, + name="Siameeee", + hates=[DogComplex(id=1, name="Potato", food="tomato"), DogComplex(id=-1, name="Tomato", food="french fries")], + ) + assert model.as_dict(exclude_readonly=True) == {"id": 2, "name": "Siameeee", "color": None} class Fish(Model): @@ -3729,12 +3463,14 @@ class Fish(Model): kind: Literal[None] = rest_discriminator(name="kind") @overload - def __init__(self, *, age: int, ): - ... + def __init__( + self, + *, + age: int, + ): ... @overload - def __init__(self, mapping: Mapping[str, Any]): - ... + def __init__(self, mapping: Mapping[str, Any]): ... def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) @@ -3747,12 +3483,14 @@ class Shark(Fish, discriminator="shark"): sharktype: Literal[None] = rest_discriminator(name="sharktype") @overload - def __init__(self, *, age: int, ): - ... + def __init__( + self, + *, + age: int, + ): ... @overload - def __init__(self, mapping: Mapping[str, Any]): - ... + def __init__(self, mapping: Mapping[str, Any]): ... def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) @@ -3764,12 +3502,14 @@ class GoblinShark(Shark, discriminator="goblin"): sharktype: Literal["goblin"] = rest_discriminator(name="sharktype") @overload - def __init__(self, *, age: int, ): - ... + def __init__( + self, + *, + age: int, + ): ... @overload - def __init__(self, mapping: Mapping[str, Any]): - ... + def __init__(self, mapping: Mapping[str, Any]): ... def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) @@ -3790,12 +3530,10 @@ def __init__( friends: Optional[List["Fish"]] = None, hate: Optional[Dict[str, "Fish"]] = None, partner: Optional["Fish"] = None, - ): - ... + ): ... @overload - def __init__(self, mapping: Mapping[str, Any]): - ... + def __init__(self, mapping: Mapping[str, Any]): ... def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) @@ -3806,12 +3544,14 @@ class SawShark(Shark, discriminator="saw"): sharktype: Literal["saw"] = rest_discriminator(name="sharktype") @overload - def __init__(self, *, age: int, ): - ... + def __init__( + self, + *, + age: int, + ): ... @overload - def __init__(self, mapping: Mapping[str, Any]): - ... + def __init__(self, mapping: Mapping[str, Any]): ... def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) @@ -3892,31 +3632,58 @@ def test_body_bytes_format(): assert json.dumps(bytearray("test", "utf-8"), cls=SdkJSONEncoder, format="base64") == '"dGVzdA=="' assert json.dumps(bytearray("test", "utf-8"), cls=SdkJSONEncoder, format="base64url") == '"dGVzdA"' - assert json.dumps([bytes("test", "utf-8"), bytes("test", "utf-8")], - cls=SdkJSONEncoder) == '["dGVzdA==", "dGVzdA=="]' - assert json.dumps([bytearray("test", "utf-8"), bytearray("test", "utf-8")], - cls=SdkJSONEncoder) == '["dGVzdA==", "dGVzdA=="]' - assert json.dumps([bytes("test", "utf-8"), bytes("test", "utf-8")], cls=SdkJSONEncoder, - format="base64") == '["dGVzdA==", "dGVzdA=="]' - assert json.dumps([bytes("test", "utf-8"), bytes("test", "utf-8")], cls=SdkJSONEncoder, - format="base64url") == '["dGVzdA", "dGVzdA"]' - assert json.dumps([bytearray("test", "utf-8"), bytearray("test", "utf-8")], cls=SdkJSONEncoder, - format="base64") == '["dGVzdA==", "dGVzdA=="]' - assert json.dumps([bytearray("test", "utf-8"), bytearray("test", "utf-8")], cls=SdkJSONEncoder, - format="base64url") == '["dGVzdA", "dGVzdA"]' - - assert json.dumps({"a": bytes("test", "utf-8"), "b": bytes("test", "utf-8")}, - cls=SdkJSONEncoder) == '{"a": "dGVzdA==", "b": "dGVzdA=="}' - assert json.dumps({"a": bytearray("test", "utf-8"), "b": bytearray("test", "utf-8")}, - cls=SdkJSONEncoder) == '{"a": "dGVzdA==", "b": "dGVzdA=="}' - assert json.dumps({"a": bytes("test", "utf-8"), "b": bytes("test", "utf-8")}, cls=SdkJSONEncoder, - format="base64") == '{"a": "dGVzdA==", "b": "dGVzdA=="}' - assert json.dumps({"a": bytes("test", "utf-8"), "b": bytes("test", "utf-8")}, cls=SdkJSONEncoder, - format="base64url") == '{"a": "dGVzdA", "b": "dGVzdA"}' - assert json.dumps({"a": bytearray("test", "utf-8"), "b": bytearray("test", "utf-8")}, cls=SdkJSONEncoder, - format="base64") == '{"a": "dGVzdA==", "b": "dGVzdA=="}' - assert json.dumps({"a": bytearray("test", "utf-8"), "b": bytearray("test", "utf-8")}, cls=SdkJSONEncoder, - format="base64url") == '{"a": "dGVzdA", "b": "dGVzdA"}' + assert ( + json.dumps([bytes("test", "utf-8"), bytes("test", "utf-8")], cls=SdkJSONEncoder) == '["dGVzdA==", "dGVzdA=="]' + ) + assert ( + json.dumps([bytearray("test", "utf-8"), bytearray("test", "utf-8")], cls=SdkJSONEncoder) + == '["dGVzdA==", "dGVzdA=="]' + ) + assert ( + json.dumps([bytes("test", "utf-8"), bytes("test", "utf-8")], cls=SdkJSONEncoder, format="base64") + == '["dGVzdA==", "dGVzdA=="]' + ) + assert ( + json.dumps([bytes("test", "utf-8"), bytes("test", "utf-8")], cls=SdkJSONEncoder, format="base64url") + == '["dGVzdA", "dGVzdA"]' + ) + assert ( + json.dumps([bytearray("test", "utf-8"), bytearray("test", "utf-8")], cls=SdkJSONEncoder, format="base64") + == '["dGVzdA==", "dGVzdA=="]' + ) + assert ( + json.dumps([bytearray("test", "utf-8"), bytearray("test", "utf-8")], cls=SdkJSONEncoder, format="base64url") + == '["dGVzdA", "dGVzdA"]' + ) + + assert ( + json.dumps({"a": bytes("test", "utf-8"), "b": bytes("test", "utf-8")}, cls=SdkJSONEncoder) + == '{"a": "dGVzdA==", "b": "dGVzdA=="}' + ) + assert ( + json.dumps({"a": bytearray("test", "utf-8"), "b": bytearray("test", "utf-8")}, cls=SdkJSONEncoder) + == '{"a": "dGVzdA==", "b": "dGVzdA=="}' + ) + assert ( + json.dumps({"a": bytes("test", "utf-8"), "b": bytes("test", "utf-8")}, cls=SdkJSONEncoder, format="base64") + == '{"a": "dGVzdA==", "b": "dGVzdA=="}' + ) + assert ( + json.dumps({"a": bytes("test", "utf-8"), "b": bytes("test", "utf-8")}, cls=SdkJSONEncoder, format="base64url") + == '{"a": "dGVzdA", "b": "dGVzdA"}' + ) + assert ( + json.dumps( + {"a": bytearray("test", "utf-8"), "b": bytearray("test", "utf-8")}, cls=SdkJSONEncoder, format="base64" + ) + == '{"a": "dGVzdA==", "b": "dGVzdA=="}' + ) + assert ( + json.dumps( + {"a": bytearray("test", "utf-8"), "b": bytearray("test", "utf-8")}, cls=SdkJSONEncoder, format="base64url" + ) + == '{"a": "dGVzdA", "b": "dGVzdA"}' + ) def test_decimal_deserialization(): @@ -3924,18 +3691,16 @@ class DecimalModel(Model): decimal_value: decimal.Decimal = rest_field(name="decimalValue") @overload - def __init__(self, *, decimal_value: decimal.Decimal): - ... + def __init__(self, *, decimal_value: decimal.Decimal): ... @overload - def __init__(self, mapping: Mapping[str, Any], /): - ... + def __init__(self, mapping: Mapping[str, Any], /): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) model = DecimalModel({"decimalValue": 0.33333}) - assert model['decimalValue'] == 0.33333 + assert model["decimalValue"] == 0.33333 assert model.decimal_value == decimal.Decimal("0.33333") class BaseModel(Model): @@ -3943,16 +3708,19 @@ class BaseModel(Model): model = BaseModel({"myProp": {"decimalValue": 0.33333}}) assert isinstance(model.my_prop, DecimalModel) - assert model.my_prop['decimalValue'] == model['myProp']['decimalValue'] == 0.33333 + assert model.my_prop["decimalValue"] == model["myProp"]["decimalValue"] == 0.33333 assert model.my_prop.decimal_value == decimal.Decimal("0.33333") def test_decimal_serialization(): - assert json.dumps(decimal.Decimal("0.33333"), cls=SdkJSONEncoder) == '0.33333' - assert json.dumps([decimal.Decimal("0.33333"), decimal.Decimal("0.33333")], - cls=SdkJSONEncoder) == '[0.33333, 0.33333]' - assert json.dumps({"a": decimal.Decimal("0.33333"), "b": decimal.Decimal("0.33333")}, - cls=SdkJSONEncoder) == '{"a": 0.33333, "b": 0.33333}' + assert json.dumps(decimal.Decimal("0.33333"), cls=SdkJSONEncoder) == "0.33333" + assert ( + json.dumps([decimal.Decimal("0.33333"), decimal.Decimal("0.33333")], cls=SdkJSONEncoder) == "[0.33333, 0.33333]" + ) + assert ( + json.dumps({"a": decimal.Decimal("0.33333"), "b": decimal.Decimal("0.33333")}, cls=SdkJSONEncoder) + == '{"a": 0.33333, "b": 0.33333}' + ) def test_deserialize(): @@ -3986,7 +3754,7 @@ def check_func(target: ModelWithEnumProperty): assert target.enum_property_optional_none is None assert target["enumPropertyOptionalNone"] is None - + model = ModelWithEnumProperty(raw_input) check_func(model) @@ -4029,9 +3797,7 @@ class BytesModel(Model): def test_additional_properties_serialization(): value = { "name": "test", - "modelProp": { - "name": "test" - }, + "modelProp": {"name": "test"}, "stringProp": "string", "intProp": 1, "floatProp": 1.0, @@ -4040,7 +3806,7 @@ def test_additional_properties_serialization(): "dictProp": {"key": "value"}, "noneProp": None, "datetimeProp": "2023-06-27T06:11:09Z", - "durationProp": "P1D" + "durationProp": "P1D", } class NormalModel(Model):