Skip to content

Commit

Permalink
add support and tests for anything (#946)
Browse files Browse the repository at this point in the history
  • Loading branch information
iscai-msft authored May 17, 2021
1 parent 6f54c97 commit 6b12df5
Show file tree
Hide file tree
Showing 28 changed files with 1,072 additions and 41 deletions.
10 changes: 10 additions & 0 deletions ChangeLog.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
# Change Log

### 2021-05-17 - 5.8.0

min Autorest core version: 3.3.0

min Modelerfour version: 4.19.1

**New Features**

- Add support for parameters and properties that can be of type "Anything". #946

### 2021-04-20 - 5.7.0

min Autorest core version: 3.1.0
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ contact [[email protected]](mailto:[email protected]) with any additio
pass-thru:
- model-deduplicator
- subset-reducer
version: ^3.1.0
version: ~3.3.0
use-extension:
"@autorest/modelerfour": ^4.15.456
"@autorest/modelerfour": ~4.19.1

modelerfour:
group-parameters: true
Expand Down
1 change: 1 addition & 0 deletions autorest/codegen/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@

__all__ = [
"AzureKeyCredentialSchema",
"AnySchema",
"BaseModel",
"BaseSchema",
"CodeModel",
Expand Down
12 changes: 11 additions & 1 deletion autorest/codegen/models/primitive_schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,16 @@ def serialization_type(self) -> str:

@property
def docstring_type(self) -> str:
return "object"
return "any"

@property
def type_annotation(self) -> str:
return "Any"

def imports(self) -> FileImport:
file_import = FileImport()
file_import.add_from_import("typing", "Any", ImportType.STDLIB, TypingSection.CONDITIONAL)
return file_import


class NumberSchema(PrimitiveSchema):
Expand Down Expand Up @@ -374,6 +383,7 @@ def get_primitive_schema(namespace: str, yaml_data: Dict[str, Any]) -> "Primitiv
"duration": DurationSchema,
"byte-array": ByteArraySchema,
"any": AnySchema,
"any-object": AnySchema,
"binary": IOSchema
}
schema_type = yaml_data["type"]
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@autorest/python",
"version": "5.7.0",
"version": "5.8.0",
"description": "The Python extension for generators in AutoRest.",
"scripts": {
"prepare": "node run-python3.js prepare.py",
Expand Down Expand Up @@ -28,7 +28,7 @@
},
"devDependencies": {
"@autorest/autorest": "^3.0.0",
"@microsoft.azure/autorest.testserver": "^3.0.20"
"@microsoft.azure/autorest.testserver": "^3.0.23"
},
"files": [
"autorest/**/*.py",
Expand Down
1 change: 1 addition & 0 deletions tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ class _SwaggerGroup(Enum):

_VANILLA_SWAGGER_MAPPINGS = {
'AdditionalProperties': 'additionalProperties.json',
'Anything': 'any-type.json',
'ParameterFlattening': 'parameter-flattening.json',
'BodyArray': 'body-array.json',
'BodyBoolean': 'body-boolean.json',
Expand Down
58 changes: 58 additions & 0 deletions test/vanilla/AcceptanceTests/asynctests/test_anything.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# --------------------------------------------------------------------------
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the ""Software""), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
# --------------------------------------------------------------------------
import pytest
from async_generator import yield_, async_generator
from anything.aio import AnythingClient

@pytest.fixture
@async_generator
async def client():
async with AnythingClient(base_url="http://localhost:3000") as client:
await yield_(client)

@pytest.mark.asyncio
async def test_get_string(client):
assert await client.get_string() == 'anything'

@pytest.mark.asyncio
async def test_put_string(client):
await client.put_string(input="anything")

@pytest.mark.asyncio
async def test_get_object(client):
assert await client.get_object() == {"message": "An object was successfully returned"}

@pytest.mark.asyncio
async def test_put_object(client):
await client.put_object({'foo': 'bar'})

@pytest.mark.asyncio
async def test_get_array(client):
assert await client.get_array() == ['foo', 'bar']

@pytest.mark.asyncio
async def test_put_array(client):
await client.put_array(['foo', 'bar'])
50 changes: 50 additions & 0 deletions test/vanilla/AcceptanceTests/test_anything.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# --------------------------------------------------------------------------
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the ""Software""), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
# --------------------------------------------------------------------------
import pytest
from anything import AnythingClient

@pytest.fixture
def client():
with AnythingClient(base_url="http://localhost:3000") as client:
yield client

def test_get_string(client):
assert client.get_string() == 'anything'

def test_put_string(client):
client.put_string(input="anything")

def test_get_object(client):
assert client.get_object() == {"message": "An object was successfully returned"}

def test_put_object(client):
client.put_object({'foo': 'bar'})

def test_get_array(client):
assert client.get_array() == ['foo', 'bar']

def test_put_array(client):
client.put_array(['foo', 'bar'])
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class PetAPTrue(msrest.serialization.Model):
:param additional_properties: Unmatched properties from the message are deserialized to this
collection.
:type additional_properties: dict[str, object]
:type additional_properties: dict[str, any]
:param id: Required.
:type id: int
:param name:
Expand Down Expand Up @@ -57,7 +57,7 @@ class CatAPTrue(PetAPTrue):
:param additional_properties: Unmatched properties from the message are deserialized to this
collection.
:type additional_properties: dict[str, object]
:type additional_properties: dict[str, any]
:param id: Required.
:type id: int
:param name:
Expand Down Expand Up @@ -199,7 +199,7 @@ class PetAPObject(msrest.serialization.Model):
:param additional_properties: Unmatched properties from the message are deserialized to this
collection.
:type additional_properties: dict[str, object]
:type additional_properties: dict[str, any]
:param id: Required.
:type id: int
:param name:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------

from typing import Dict, Optional
from typing import Any, Dict, Optional

from azure.core.exceptions import HttpResponseError
import msrest.serialization
Expand All @@ -21,7 +21,7 @@ class PetAPTrue(msrest.serialization.Model):
:param additional_properties: Unmatched properties from the message are deserialized to this
collection.
:type additional_properties: dict[str, object]
:type additional_properties: dict[str, any]
:param id: Required.
:type id: int
:param name:
Expand All @@ -43,12 +43,7 @@ class PetAPTrue(msrest.serialization.Model):
}

def __init__(
self,
*,
id: int,
additional_properties: Optional[Dict[str, object]] = None,
name: Optional[str] = None,
**kwargs
self, *, id: int, additional_properties: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs
):
super(PetAPTrue, self).__init__(**kwargs)
self.additional_properties = additional_properties
Expand All @@ -66,7 +61,7 @@ class CatAPTrue(PetAPTrue):
:param additional_properties: Unmatched properties from the message are deserialized to this
collection.
:type additional_properties: dict[str, object]
:type additional_properties: dict[str, any]
:param id: Required.
:type id: int
:param name:
Expand Down Expand Up @@ -94,7 +89,7 @@ def __init__(
self,
*,
id: int,
additional_properties: Optional[Dict[str, object]] = None,
additional_properties: Optional[Dict[str, Any]] = None,
name: Optional[str] = None,
friendly: Optional[bool] = None,
**kwargs
Expand Down Expand Up @@ -227,7 +222,7 @@ class PetAPObject(msrest.serialization.Model):
:param additional_properties: Unmatched properties from the message are deserialized to this
collection.
:type additional_properties: dict[str, object]
:type additional_properties: dict[str, any]
:param id: Required.
:type id: int
:param name:
Expand All @@ -249,12 +244,7 @@ class PetAPObject(msrest.serialization.Model):
}

def __init__(
self,
*,
id: int,
additional_properties: Optional[Dict[str, object]] = None,
name: Optional[str] = None,
**kwargs
self, *, id: int, additional_properties: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs
):
super(PetAPObject, self).__init__(**kwargs)
self.additional_properties = additional_properties
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------

from ._anything_client import AnythingClient
from ._version import VERSION

__version__ = VERSION
__all__ = ["AnythingClient"]

try:
from ._patch import patch_sdk # type: ignore

patch_sdk()
except ImportError:
pass
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------

from typing import TYPE_CHECKING

from azure.core import PipelineClient
from msrest import Deserializer, Serializer

if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any, Dict, Optional

from azure.core.pipeline.transport import HttpRequest, HttpResponse

from ._configuration import AnythingClientConfiguration
from .operations import AnythingClientOperationsMixin


class AnythingClient(AnythingClientOperationsMixin):
"""Service client for testing basic anything types. Those schemas without types can be anything: primitive, object, array.
:param str base_url: Service URL
"""

def __init__(
self,
base_url=None, # type: Optional[str]
**kwargs # type: Any
):
# type: (...) -> None
if not base_url:
base_url = "http://localhost:3000"
self._config = AnythingClientConfiguration(**kwargs)
self._client = PipelineClient(base_url=base_url, config=self._config, **kwargs)

client_models = {} # type: Dict[str, Any]
self._serialize = Serializer(client_models)
self._serialize.client_side_validation = False
self._deserialize = Deserializer(client_models)

def _send_request(self, http_request, **kwargs):
# type: (HttpRequest, Any) -> HttpResponse
"""Runs the network request through the client's chained policies.
:param http_request: The network request you want to make. Required.
:type http_request: ~azure.core.pipeline.transport.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to True.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.pipeline.transport.HttpResponse
"""
http_request.url = self._client.format_url(http_request.url)
stream = kwargs.pop("stream", True)
pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs)
return pipeline_response.http_response

def close(self):
# type: () -> None
self._client.close()

def __enter__(self):
# type: () -> AnythingClient
self._client.__enter__()
return self

def __exit__(self, *exc_details):
# type: (Any) -> None
self._client.__exit__(*exc_details)
Loading

0 comments on commit 6b12df5

Please sign in to comment.