1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
|
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import aiohttp # type: ignore
from aioresponses import aioresponses, core # type: ignore
import mock
import pytest # type: ignore
from tests_async.transport import async_compliance
import google.auth._credentials_async
from google.auth.transport import _aiohttp_requests as aiohttp_requests
import google.auth.transport._mtls_helper
class TestCombinedResponse:
@pytest.mark.asyncio
async def test__is_compressed(self):
response = core.CallbackResult(headers={"Content-Encoding": "gzip"})
combined_response = aiohttp_requests._CombinedResponse(response)
compressed = combined_response._is_compressed()
assert compressed
def test__is_compressed_not(self):
response = core.CallbackResult(headers={"Content-Encoding": "not"})
combined_response = aiohttp_requests._CombinedResponse(response)
compressed = combined_response._is_compressed()
assert not compressed
@pytest.mark.asyncio
async def test_raw_content(self):
mock_response = mock.AsyncMock()
mock_response.content.read.return_value = mock.sentinel.read
combined_response = aiohttp_requests._CombinedResponse(response=mock_response)
raw_content = await combined_response.raw_content()
assert raw_content == mock.sentinel.read
# Second call to validate the preconfigured path.
combined_response._raw_content = mock.sentinel.stored_raw
raw_content = await combined_response.raw_content()
assert raw_content == mock.sentinel.stored_raw
@pytest.mark.asyncio
async def test_content(self):
mock_response = mock.AsyncMock()
mock_response.content.read.return_value = mock.sentinel.read
combined_response = aiohttp_requests._CombinedResponse(response=mock_response)
content = await combined_response.content()
assert content == mock.sentinel.read
@mock.patch(
"google.auth.transport._aiohttp_requests.urllib3.response.MultiDecoder.decompress",
return_value="decompressed",
autospec=True,
)
@pytest.mark.asyncio
async def test_content_compressed(self, urllib3_mock):
rm = core.RequestMatch(
"url", headers={"Content-Encoding": "gzip"}, payload="compressed"
)
response = await rm.build_response(core.URL("url"))
combined_response = aiohttp_requests._CombinedResponse(response=response)
content = await combined_response.content()
urllib3_mock.assert_called_once()
assert content == "decompressed"
class TestResponse:
def test_ctor(self):
response = aiohttp_requests._Response(mock.sentinel.response)
assert response._response == mock.sentinel.response
@pytest.mark.asyncio
async def test_headers_prop(self):
rm = core.RequestMatch("url", headers={"Content-Encoding": "header prop"})
mock_response = await rm.build_response(core.URL("url"))
response = aiohttp_requests._Response(mock_response)
assert response.headers["Content-Encoding"] == "header prop"
@pytest.mark.asyncio
async def test_status_prop(self):
rm = core.RequestMatch("url", status=123)
mock_response = await rm.build_response(core.URL("url"))
response = aiohttp_requests._Response(mock_response)
assert response.status == 123
@pytest.mark.asyncio
async def test_data_prop(self):
mock_response = mock.AsyncMock()
mock_response.content.read.return_value = mock.sentinel.read
response = aiohttp_requests._Response(mock_response)
data = await response.data.read()
assert data == mock.sentinel.read
class TestRequestResponse(async_compliance.RequestResponseTests):
def make_request(self):
return aiohttp_requests.Request()
def make_with_parameter_request(self):
http = aiohttp.ClientSession(auto_decompress=False)
return aiohttp_requests.Request(http)
def test_unsupported_session(self):
http = aiohttp.ClientSession(auto_decompress=True)
with pytest.raises(ValueError):
aiohttp_requests.Request(http)
def test_timeout(self):
http = mock.create_autospec(
aiohttp.ClientSession, instance=True, _auto_decompress=False
)
request = aiohttp_requests.Request(http)
request(url="http://example.com", method="GET", timeout=5)
class CredentialsStub(google.auth._credentials_async.Credentials):
def __init__(self, token="token"):
super(CredentialsStub, self).__init__()
self.token = token
def apply(self, headers, token=None):
headers["authorization"] = self.token
def refresh(self, request):
self.token += "1"
class TestAuthorizedSession(object):
TEST_URL = "http://example.com/"
method = "GET"
def test_constructor(self):
authed_session = aiohttp_requests.AuthorizedSession(mock.sentinel.credentials)
assert authed_session.credentials == mock.sentinel.credentials
def test_constructor_with_auth_request(self):
http = mock.create_autospec(
aiohttp.ClientSession, instance=True, _auto_decompress=False
)
auth_request = aiohttp_requests.Request(http)
authed_session = aiohttp_requests.AuthorizedSession(
mock.sentinel.credentials, auth_request=auth_request
)
assert authed_session._auth_request == auth_request
@pytest.mark.asyncio
async def test_request(self):
with aioresponses() as mocked:
credentials = mock.Mock(wraps=CredentialsStub())
mocked.get(self.TEST_URL, status=200, body="test")
session = aiohttp_requests.AuthorizedSession(credentials)
resp = await session.request(
"GET",
"http://example.com/",
headers={"Keep-Alive": "timeout=5, max=1000", "fake": b"bytes"},
)
assert resp.status == 200
assert "test" == await resp.text()
await session.close()
@pytest.mark.asyncio
async def test_ctx(self):
with aioresponses() as mocked:
credentials = mock.Mock(wraps=CredentialsStub())
mocked.get("http://test.example.com", payload=dict(foo="bar"))
session = aiohttp_requests.AuthorizedSession(credentials)
resp = await session.request("GET", "http://test.example.com")
data = await resp.json()
assert dict(foo="bar") == data
await session.close()
@pytest.mark.asyncio
async def test_http_headers(self):
with aioresponses() as mocked:
credentials = mock.Mock(wraps=CredentialsStub())
mocked.post(
"http://example.com",
payload=dict(),
headers=dict(connection="keep-alive"),
)
session = aiohttp_requests.AuthorizedSession(credentials)
resp = await session.request("POST", "http://example.com")
assert resp.headers["Connection"] == "keep-alive"
await session.close()
@pytest.mark.asyncio
async def test_regexp_example(self):
with aioresponses() as mocked:
credentials = mock.Mock(wraps=CredentialsStub())
mocked.get("http://example.com", status=500)
mocked.get("http://example.com", status=200)
session1 = aiohttp_requests.AuthorizedSession(credentials)
resp1 = await session1.request("GET", "http://example.com")
session2 = aiohttp_requests.AuthorizedSession(credentials)
resp2 = await session2.request("GET", "http://example.com")
assert resp1.status == 500
assert resp2.status == 200
await session1.close()
await session2.close()
@pytest.mark.asyncio
async def test_request_no_refresh(self):
credentials = mock.Mock(wraps=CredentialsStub())
with aioresponses() as mocked:
mocked.get("http://example.com", status=200)
authed_session = aiohttp_requests.AuthorizedSession(credentials)
response = await authed_session.request("GET", "http://example.com")
assert response.status == 200
assert credentials.before_request.called
assert not credentials.refresh.called
await authed_session.close()
@pytest.mark.asyncio
async def test_request_refresh(self):
credentials = mock.Mock(wraps=CredentialsStub())
with aioresponses() as mocked:
mocked.get("http://example.com", status=401)
mocked.get("http://example.com", status=200)
authed_session = aiohttp_requests.AuthorizedSession(credentials)
response = await authed_session.request("GET", "http://example.com")
assert credentials.refresh.called
assert response.status == 200
await authed_session.close()
|