|
| 1 | +# Copyright 2026 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 | +import inspect |
| 16 | + |
| 17 | +import aiohttp |
| 18 | +from aioresponses.core import RequestMatch # type: ignore |
| 19 | + |
| 20 | + |
| 21 | +class _DummyWriter: |
| 22 | + output_size = 0 |
| 23 | + |
| 24 | + def done(self): |
| 25 | + return True |
| 26 | + |
| 27 | + def add_done_callback(self, fn, *args, **kwargs): |
| 28 | + pass |
| 29 | + |
| 30 | + def remove_done_callback(self, fn): |
| 31 | + pass |
| 32 | + |
| 33 | + def __await__(self): |
| 34 | + if False: |
| 35 | + yield |
| 36 | + return None |
| 37 | + |
| 38 | + |
| 39 | +class _CompatClientResponse(aiohttp.ClientResponse): |
| 40 | + """ClientResponse subclass for aioresponses compatibility across all aiohttp versions.""" |
| 41 | + |
| 42 | + def __init__(self, *args, **kwargs): |
| 43 | + writer = kwargs.pop("writer", None) |
| 44 | + stream_writer = kwargs.pop("stream_writer", None) |
| 45 | + writer_obj = stream_writer or writer or _DummyWriter() |
| 46 | + sig = inspect.signature(super().__init__) |
| 47 | + if "stream_writer" in sig.parameters: |
| 48 | + kwargs["stream_writer"] = writer_obj |
| 49 | + if "writer" in sig.parameters: |
| 50 | + kwargs["writer"] = writer_obj |
| 51 | + super().__init__(*args, **kwargs) |
| 52 | + |
| 53 | + |
| 54 | +def patch_aioresponses(): |
| 55 | + """Patch RequestMatch.__init__ to use _CompatClientResponse by default.""" |
| 56 | + if getattr(RequestMatch, "_is_compat_patched", False): |
| 57 | + return |
| 58 | + orig_init = RequestMatch.__init__ |
| 59 | + |
| 60 | + def _request_match_init(self, *args, **kwargs): |
| 61 | + if kwargs.get("response_class") is None: |
| 62 | + kwargs["response_class"] = _CompatClientResponse |
| 63 | + orig_init(self, *args, **kwargs) |
| 64 | + |
| 65 | + RequestMatch.__init__ = _request_match_init |
| 66 | + RequestMatch._is_compat_patched = True |
0 commit comments