|
| 1 | +# Copyright 2024 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +# TODO: set random.seed explicitly in each test function. |
| 16 | +# See related issue: https://github.com/googleapis/python-api-core/issues/689. |
| 17 | + |
| 18 | +import pytest # noqa: I202 |
| 19 | +import mock |
| 20 | + |
| 21 | +import datetime |
| 22 | +import logging |
| 23 | +import random |
| 24 | +import time |
| 25 | +from typing import List, AsyncIterator |
| 26 | + |
| 27 | +import proto |
| 28 | + |
| 29 | +try: |
| 30 | + from google.auth.aio.transport import Response |
| 31 | + |
| 32 | + AUTH_AIO_INSTALLED = True |
| 33 | +except ImportError: |
| 34 | + AUTH_AIO_INSTALLED = False |
| 35 | + |
| 36 | +if not AUTH_AIO_INSTALLED: # pragma: NO COVER |
| 37 | + pytest.skip( |
| 38 | + "google-auth>=2.35.0 is required to use asynchronous rest streaming.", |
| 39 | + allow_module_level=True, |
| 40 | + ) |
| 41 | + |
| 42 | +from google.api_core import rest_streaming_async |
| 43 | +from google.api import http_pb2 |
| 44 | +from google.api import httpbody_pb2 |
| 45 | + |
| 46 | + |
| 47 | +from ..helpers import Composer, Song, EchoResponse, parse_responses |
| 48 | + |
| 49 | + |
| 50 | +__protobuf__ = proto.module(package=__name__) |
| 51 | +SEED = int(time.time()) |
| 52 | +logging.info(f"Starting async rest streaming tests with random seed: {SEED}") |
| 53 | +random.seed(SEED) |
| 54 | + |
| 55 | + |
| 56 | +async def mock_async_gen(data, chunk_size=1): |
| 57 | + for i in range(0, len(data)): # pragma: NO COVER |
| 58 | + chunk = data[i : i + chunk_size] |
| 59 | + yield chunk.encode("utf-8") |
| 60 | + |
| 61 | + |
| 62 | +class ResponseMock(Response): |
| 63 | + class _ResponseItr(AsyncIterator[bytes]): |
| 64 | + def __init__(self, _response_bytes: bytes, random_split=False): |
| 65 | + self._responses_bytes = _response_bytes |
| 66 | + self._idx = 0 |
| 67 | + self._random_split = random_split |
| 68 | + |
| 69 | + def __aiter__(self): |
| 70 | + return self |
| 71 | + |
| 72 | + async def __anext__(self): |
| 73 | + if self._idx >= len(self._responses_bytes): |
| 74 | + raise StopAsyncIteration |
| 75 | + if self._random_split: |
| 76 | + n = random.randint(1, len(self._responses_bytes[self._idx :])) |
| 77 | + else: |
| 78 | + n = 1 |
| 79 | + x = self._responses_bytes[self._idx : self._idx + n] |
| 80 | + self._idx += n |
| 81 | + return x |
| 82 | + |
| 83 | + def __init__( |
| 84 | + self, |
| 85 | + responses: List[proto.Message], |
| 86 | + response_cls, |
| 87 | + random_split=False, |
| 88 | + ): |
| 89 | + self._responses = responses |
| 90 | + self._random_split = random_split |
| 91 | + self._response_message_cls = response_cls |
| 92 | + |
| 93 | + def _parse_responses(self): |
| 94 | + return parse_responses(self._response_message_cls, self._responses) |
| 95 | + |
| 96 | + @property |
| 97 | + async def headers(self): |
| 98 | + raise NotImplementedError() |
| 99 | + |
| 100 | + @property |
| 101 | + async def status_code(self): |
| 102 | + raise NotImplementedError() |
| 103 | + |
| 104 | + async def close(self): |
| 105 | + raise NotImplementedError() |
| 106 | + |
| 107 | + async def content(self, chunk_size=None): |
| 108 | + itr = self._ResponseItr( |
| 109 | + self._parse_responses(), random_split=self._random_split |
| 110 | + ) |
| 111 | + async for chunk in itr: |
| 112 | + yield chunk |
| 113 | + |
| 114 | + async def read(self): |
| 115 | + raise NotImplementedError() |
| 116 | + |
| 117 | + |
| 118 | +@pytest.mark.asyncio |
| 119 | +@pytest.mark.parametrize( |
| 120 | + "random_split,resp_message_is_proto_plus", |
| 121 | + [(False, True), (False, False)], |
| 122 | +) |
| 123 | +async def test_next_simple(random_split, resp_message_is_proto_plus): |
| 124 | + if resp_message_is_proto_plus: |
| 125 | + response_type = EchoResponse |
| 126 | + responses = [EchoResponse(content="hello world"), EchoResponse(content="yes")] |
| 127 | + else: |
| 128 | + response_type = httpbody_pb2.HttpBody |
| 129 | + responses = [ |
| 130 | + httpbody_pb2.HttpBody(content_type="hello world"), |
| 131 | + httpbody_pb2.HttpBody(content_type="yes"), |
| 132 | + ] |
| 133 | + |
| 134 | + resp = ResponseMock( |
| 135 | + responses=responses, random_split=random_split, response_cls=response_type |
| 136 | + ) |
| 137 | + itr = rest_streaming_async.AsyncResponseIterator(resp, response_type) |
| 138 | + idx = 0 |
| 139 | + async for response in itr: |
| 140 | + assert response == responses[idx] |
| 141 | + idx += 1 |
| 142 | + |
| 143 | + |
| 144 | +@pytest.mark.asyncio |
| 145 | +@pytest.mark.parametrize( |
| 146 | + "random_split,resp_message_is_proto_plus", |
| 147 | + [ |
| 148 | + (True, True), |
| 149 | + (False, True), |
| 150 | + (True, False), |
| 151 | + (False, False), |
| 152 | + ], |
| 153 | +) |
| 154 | +async def test_next_nested(random_split, resp_message_is_proto_plus): |
| 155 | + if resp_message_is_proto_plus: |
| 156 | + response_type = Song |
| 157 | + responses = [ |
| 158 | + Song(title="some song", composer=Composer(given_name="some name")), |
| 159 | + Song(title="another song", date_added=datetime.datetime(2021, 12, 17)), |
| 160 | + ] |
| 161 | + else: |
| 162 | + # Although `http_pb2.HttpRule`` is used in the response, any response message |
| 163 | + # can be used which meets this criteria for the test of having a nested field. |
| 164 | + response_type = http_pb2.HttpRule |
| 165 | + responses = [ |
| 166 | + http_pb2.HttpRule( |
| 167 | + selector="some selector", |
| 168 | + custom=http_pb2.CustomHttpPattern(kind="some kind"), |
| 169 | + ), |
| 170 | + http_pb2.HttpRule( |
| 171 | + selector="another selector", |
| 172 | + custom=http_pb2.CustomHttpPattern(path="some path"), |
| 173 | + ), |
| 174 | + ] |
| 175 | + resp = ResponseMock( |
| 176 | + responses=responses, random_split=random_split, response_cls=response_type |
| 177 | + ) |
| 178 | + itr = rest_streaming_async.AsyncResponseIterator(resp, response_type) |
| 179 | + idx = 0 |
| 180 | + async for response in itr: |
| 181 | + assert response == responses[idx] |
| 182 | + idx += 1 |
| 183 | + assert idx == len(responses) |
| 184 | + |
| 185 | + |
| 186 | +@pytest.mark.asyncio |
| 187 | +@pytest.mark.parametrize( |
| 188 | + "random_split,resp_message_is_proto_plus", |
| 189 | + [ |
| 190 | + (True, True), |
| 191 | + (False, True), |
| 192 | + (True, False), |
| 193 | + (False, False), |
| 194 | + ], |
| 195 | +) |
| 196 | +async def test_next_stress(random_split, resp_message_is_proto_plus): |
| 197 | + n = 50 |
| 198 | + if resp_message_is_proto_plus: |
| 199 | + response_type = Song |
| 200 | + responses = [ |
| 201 | + Song(title="title_%d" % i, composer=Composer(given_name="name_%d" % i)) |
| 202 | + for i in range(n) |
| 203 | + ] |
| 204 | + else: |
| 205 | + response_type = http_pb2.HttpRule |
| 206 | + responses = [ |
| 207 | + http_pb2.HttpRule( |
| 208 | + selector="selector_%d" % i, |
| 209 | + custom=http_pb2.CustomHttpPattern(path="path_%d" % i), |
| 210 | + ) |
| 211 | + for i in range(n) |
| 212 | + ] |
| 213 | + resp = ResponseMock( |
| 214 | + responses=responses, random_split=random_split, response_cls=response_type |
| 215 | + ) |
| 216 | + itr = rest_streaming_async.AsyncResponseIterator(resp, response_type) |
| 217 | + idx = 0 |
| 218 | + async for response in itr: |
| 219 | + assert response == responses[idx] |
| 220 | + idx += 1 |
| 221 | + assert idx == n |
| 222 | + |
| 223 | + |
| 224 | +@pytest.mark.asyncio |
| 225 | +@pytest.mark.parametrize( |
| 226 | + "random_split,resp_message_is_proto_plus", |
| 227 | + [ |
| 228 | + (True, True), |
| 229 | + (False, True), |
| 230 | + (True, False), |
| 231 | + (False, False), |
| 232 | + ], |
| 233 | +) |
| 234 | +async def test_next_escaped_characters_in_string( |
| 235 | + random_split, resp_message_is_proto_plus |
| 236 | +): |
| 237 | + if resp_message_is_proto_plus: |
| 238 | + response_type = Song |
| 239 | + composer_with_relateds = Composer() |
| 240 | + relateds = ["Artist A", "Artist B"] |
| 241 | + composer_with_relateds.relateds = relateds |
| 242 | + |
| 243 | + responses = [ |
| 244 | + Song( |
| 245 | + title='ti"tle\nfoo\tbar{}', composer=Composer(given_name="name\n\n\n") |
| 246 | + ), |
| 247 | + Song( |
| 248 | + title='{"this is weird": "totally"}', |
| 249 | + composer=Composer(given_name="\\{}\\"), |
| 250 | + ), |
| 251 | + Song(title='\\{"key": ["value",]}\\', composer=composer_with_relateds), |
| 252 | + ] |
| 253 | + else: |
| 254 | + response_type = http_pb2.Http |
| 255 | + responses = [ |
| 256 | + http_pb2.Http( |
| 257 | + rules=[ |
| 258 | + http_pb2.HttpRule( |
| 259 | + selector='ti"tle\nfoo\tbar{}', |
| 260 | + custom=http_pb2.CustomHttpPattern(kind="name\n\n\n"), |
| 261 | + ) |
| 262 | + ] |
| 263 | + ), |
| 264 | + http_pb2.Http( |
| 265 | + rules=[ |
| 266 | + http_pb2.HttpRule( |
| 267 | + selector='{"this is weird": "totally"}', |
| 268 | + custom=http_pb2.CustomHttpPattern(kind="\\{}\\"), |
| 269 | + ) |
| 270 | + ] |
| 271 | + ), |
| 272 | + http_pb2.Http( |
| 273 | + rules=[ |
| 274 | + http_pb2.HttpRule( |
| 275 | + selector='\\{"key": ["value",]}\\', |
| 276 | + custom=http_pb2.CustomHttpPattern(kind="\\{}\\"), |
| 277 | + ) |
| 278 | + ] |
| 279 | + ), |
| 280 | + ] |
| 281 | + resp = ResponseMock( |
| 282 | + responses=responses, random_split=random_split, response_cls=response_type |
| 283 | + ) |
| 284 | + itr = rest_streaming_async.AsyncResponseIterator(resp, response_type) |
| 285 | + idx = 0 |
| 286 | + async for response in itr: |
| 287 | + assert response == responses[idx] |
| 288 | + idx += 1 |
| 289 | + assert idx == len(responses) |
| 290 | + |
| 291 | + |
| 292 | +@pytest.mark.asyncio |
| 293 | +@pytest.mark.parametrize("response_type", [EchoResponse, httpbody_pb2.HttpBody]) |
| 294 | +async def test_next_not_array(response_type): |
| 295 | + |
| 296 | + data = '{"hello": 0}' |
| 297 | + with mock.patch.object( |
| 298 | + ResponseMock, "content", return_value=mock_async_gen(data) |
| 299 | + ) as mock_method: |
| 300 | + resp = ResponseMock(responses=[], response_cls=response_type) |
| 301 | + itr = rest_streaming_async.AsyncResponseIterator(resp, response_type) |
| 302 | + with pytest.raises(ValueError): |
| 303 | + await itr.__anext__() |
| 304 | + mock_method.assert_called_once() |
| 305 | + |
| 306 | + |
| 307 | +@pytest.mark.asyncio |
| 308 | +@pytest.mark.parametrize("response_type", [EchoResponse, httpbody_pb2.HttpBody]) |
| 309 | +async def test_cancel(response_type): |
| 310 | + with mock.patch.object( |
| 311 | + ResponseMock, "close", new_callable=mock.AsyncMock |
| 312 | + ) as mock_method: |
| 313 | + resp = ResponseMock(responses=[], response_cls=response_type) |
| 314 | + itr = rest_streaming_async.AsyncResponseIterator(resp, response_type) |
| 315 | + await itr.cancel() |
| 316 | + mock_method.assert_called_once() |
| 317 | + |
| 318 | + |
| 319 | +@pytest.mark.asyncio |
| 320 | +@pytest.mark.parametrize("response_type", [EchoResponse, httpbody_pb2.HttpBody]) |
| 321 | +async def test_iterator_as_context_manager(response_type): |
| 322 | + with mock.patch.object( |
| 323 | + ResponseMock, "close", new_callable=mock.AsyncMock |
| 324 | + ) as mock_method: |
| 325 | + resp = ResponseMock(responses=[], response_cls=response_type) |
| 326 | + async with rest_streaming_async.AsyncResponseIterator(resp, response_type): |
| 327 | + pass |
| 328 | + mock_method.assert_called_once() |
| 329 | + |
| 330 | + |
| 331 | +@pytest.mark.asyncio |
| 332 | +@pytest.mark.parametrize( |
| 333 | + "response_type,return_value", |
| 334 | + [ |
| 335 | + (EchoResponse, bytes('[{"content": "hello"}, {', "utf-8")), |
| 336 | + (httpbody_pb2.HttpBody, bytes('[{"content_type": "hello"}, {', "utf-8")), |
| 337 | + ], |
| 338 | +) |
| 339 | +async def test_check_buffer(response_type, return_value): |
| 340 | + with mock.patch.object( |
| 341 | + ResponseMock, |
| 342 | + "_parse_responses", |
| 343 | + return_value=return_value, |
| 344 | + ): |
| 345 | + resp = ResponseMock(responses=[], response_cls=response_type) |
| 346 | + itr = rest_streaming_async.AsyncResponseIterator(resp, response_type) |
| 347 | + with pytest.raises(ValueError): |
| 348 | + await itr.__anext__() |
| 349 | + await itr.__anext__() |
| 350 | + |
| 351 | + |
| 352 | +@pytest.mark.asyncio |
| 353 | +@pytest.mark.parametrize("response_type", [EchoResponse, httpbody_pb2.HttpBody]) |
| 354 | +async def test_next_html(response_type): |
| 355 | + |
| 356 | + data = "<!DOCTYPE html><html></html>" |
| 357 | + with mock.patch.object( |
| 358 | + ResponseMock, "content", return_value=mock_async_gen(data) |
| 359 | + ) as mock_method: |
| 360 | + resp = ResponseMock(responses=[], response_cls=response_type) |
| 361 | + |
| 362 | + itr = rest_streaming_async.AsyncResponseIterator(resp, response_type) |
| 363 | + with pytest.raises(ValueError): |
| 364 | + await itr.__anext__() |
| 365 | + mock_method.assert_called_once() |
| 366 | + |
| 367 | + |
| 368 | +@pytest.mark.asyncio |
| 369 | +async def test_invalid_response_class(): |
| 370 | + class SomeClass: |
| 371 | + pass |
| 372 | + |
| 373 | + resp = ResponseMock(responses=[], response_cls=SomeClass) |
| 374 | + with pytest.raises( |
| 375 | + ValueError, |
| 376 | + match="Response message class must be a subclass of proto.Message or google.protobuf.message.Message", |
| 377 | + ): |
| 378 | + rest_streaming_async.AsyncResponseIterator(resp, SomeClass) |
0 commit comments