| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142 | # This module is a copy paste of test_api_provider.pyfrom http import HTTPStatusfrom unittest import mockimport pytestfrom clean_python import ctxfrom clean_python import Tenantfrom clean_python.api_client import ApiExceptionfrom clean_python.api_client import SyncApiProviderMODULE = "clean_python.api_client.sync_api_provider"@pytest.fixturedef tenant() -> Tenant:    ctx.tenant = Tenant(id=2, name="")    yield ctx.tenant    ctx.tenant = None@pytest.fixturedef response():    response = mock.Mock()    response.status = int(HTTPStatus.OK)    response.headers = {"Content-Type": "application/json"}    response.data = b'{"foo": 2}'    return response@pytest.fixturedef api_provider(tenant, response) -> SyncApiProvider:    with mock.patch(MODULE + ".PoolManager"):        api_provider = SyncApiProvider(            url="http://testserver/foo/",            fetch_token=lambda: {"Authorization": f"Bearer tenant-{ctx.tenant.id}"},        )        api_provider._pool.request.return_value = response        yield api_providerdef test_get(api_provider: SyncApiProvider, response):    actual = api_provider.request("GET", "")    assert api_provider._pool.request.call_count == 1    assert api_provider._pool.request.call_args[1] == dict(        method="GET",        url="http://testserver/foo",        headers={"Authorization": "Bearer tenant-2"},        timeout=5.0,    )    assert actual == {"foo": 2}def test_post_json(api_provider: SyncApiProvider, response):    response.status == int(HTTPStatus.CREATED)    api_provider._pool.request.return_value = response    actual = api_provider.request("POST", "bar", json={"foo": 2})    assert api_provider._pool.request.call_count == 1    assert api_provider._pool.request.call_args[1] == dict(        method="POST",        url="http://testserver/foo/bar",        body=b'{"foo": 2}',        headers={            "Content-Type": "application/json",            "Authorization": "Bearer tenant-2",        },        timeout=5.0,    )    assert actual == {"foo": 2}@pytest.mark.parametrize(    "path,params,expected_url",    [        ("", None, "http://testserver/foo"),        ("bar", None, "http://testserver/foo/bar"),        ("bar/", None, "http://testserver/foo/bar"),        ("", {"a": 2}, "http://testserver/foo?a=2"),        ("bar", {"a": 2}, "http://testserver/foo/bar?a=2"),        ("bar/", {"a": 2}, "http://testserver/foo/bar?a=2"),        ("", {"a": [1, 2]}, "http://testserver/foo?a=1&a=2"),        ("", {"a": 1, "b": "foo"}, "http://testserver/foo?a=1&b=foo"),    ],)def test_url(api_provider: SyncApiProvider, path, params, expected_url):    api_provider.request("GET", path, params=params)    assert api_provider._pool.request.call_args[1]["url"] == expected_urldef test_timeout(api_provider: SyncApiProvider):    api_provider.request("POST", "bar", timeout=2.1)    assert api_provider._pool.request.call_args[1]["timeout"] == 2.1@pytest.mark.parametrize(    "status", [HTTPStatus.OK, HTTPStatus.NOT_FOUND, HTTPStatus.INTERNAL_SERVER_ERROR])def test_unexpected_content_type(api_provider: SyncApiProvider, response, status):    response.status = int(status)    response.headers["Content-Type"] = "text/plain"    with pytest.raises(ApiException) as e:        api_provider.request("GET", "bar")    assert e.value.status is status    assert str(e.value) == f"{status}: Unexpected content type 'text/plain'"def test_json_variant_content_type(api_provider: SyncApiProvider, response):    response.headers["Content-Type"] = "application/something+json"    actual = api_provider.request("GET", "bar")    assert actual == {"foo": 2}def test_no_content(api_provider: SyncApiProvider, response):    response.status = int(HTTPStatus.NO_CONTENT)    response.headers = {}    actual = api_provider.request("DELETE", "bar/2")    assert actual is None@pytest.mark.parametrize("status", [HTTPStatus.BAD_REQUEST, HTTPStatus.NOT_FOUND])def test_error_response(api_provider: SyncApiProvider, response, status):    response.status = int(status)    with pytest.raises(ApiException) as e:        api_provider.request("GET", "bar")    assert e.value.status is status    assert str(e.value) == str(int(status)) + ": {'foo': 2}"@mock.patch(MODULE + ".PoolManager", new=mock.Mock())def test_no_token(response, tenant):    api_provider = SyncApiProvider(url="http://testserver/foo/", fetch_token=lambda: {})    api_provider._pool.request.return_value = response    api_provider.request("GET", "")    assert api_provider._pool.request.call_args[1]["headers"] == {}
 |