File: test_request.py

package info (click to toggle)
python-telegram-bot 22.3-1
  • links: PTS
  • area: main
  • in suites: sid
  • size: 11,060 kB
  • sloc: python: 90,298; makefile: 176; sh: 4
file content (806 lines) | stat: -rw-r--r-- 30,664 bytes parent folder | download
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program.  If not, see [http://www.gnu.org/licenses/].
"""Here we run tests directly with HTTPXRequest because that's easier than providing dummy
implementations for BaseRequest and we want to test HTTPXRequest anyway."""
import asyncio
import datetime as dtm
import json
import logging
from collections import defaultdict
from collections.abc import Coroutine
from dataclasses import dataclass
from http import HTTPStatus
from typing import Any, Callable

import httpx
import pytest
from httpx import AsyncHTTPTransport

from telegram import InputFile
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.strings import TextEncoding
from telegram.error import (
    BadRequest,
    ChatMigrated,
    Conflict,
    Forbidden,
    InvalidToken,
    NetworkError,
    RetryAfter,
    TelegramError,
    TimedOut,
)
from telegram.request import RequestData
from telegram.request._httpxrequest import HTTPXRequest
from telegram.request._requestparameter import RequestParameter
from tests.auxil.envvars import TEST_WITH_OPT_DEPS
from tests.auxil.files import data_file
from tests.auxil.networking import NonchalantHttpxRequest
from tests.auxil.slots import mro_slots

# We only need mixed_rqs fixture, but it uses the others, so pytest needs us to import them as well
from .test_requestdata import (  # noqa: F401
    file_params,
    input_media_photo,
    input_media_video,
    inputfiles,
    mixed_params,
    mixed_rqs,
    simple_params,
)


def mocker_factory(
    response: bytes, return_code: int = HTTPStatus.OK
) -> Callable[[tuple[Any]], Coroutine[Any, Any, tuple[int, bytes]]]:
    async def make_assertion(*args, **kwargs):
        return return_code, response

    return make_assertion


@pytest.fixture
async def httpx_request():
    async with NonchalantHttpxRequest() as rq:
        yield rq


@pytest.mark.skipif(
    TEST_WITH_OPT_DEPS, reason="Only relevant if the optional dependency is not installed"
)
class TestNoSocksHTTP2WithoutRequest:
    async def test_init(self, offline_bot):
        with pytest.raises(RuntimeError, match=r"python-telegram-bot\[socks\]"):
            HTTPXRequest(proxy="socks5://foo")
        with pytest.raises(RuntimeError, match=r"python-telegram-bot\[http2\]"):
            HTTPXRequest(http_version="2")


@pytest.mark.skipif(not TEST_WITH_OPT_DEPS, reason="Optional dependencies not installed")
class TestHTTP2WithRequest:
    @pytest.mark.parametrize("http_version", ["2", "2.0"])
    async def test_http_2_response(self, http_version):
        httpx_request = HTTPXRequest(http_version=http_version)
        async with httpx_request:
            resp = await httpx_request._client.request(
                url="https://python-telegram-bot.org",
                method="GET",
                headers={"User-Agent": httpx_request.USER_AGENT},
            )
            assert resp.http_version == "HTTP/2"


# I picked not TEST_XXX because that's the default, meaning it will run by default for an end-user
# who runs pytest.
@pytest.mark.skipif(not TEST_WITH_OPT_DEPS, reason="No need to run this twice")
class TestRequestWithoutRequest:
    test_flag = None

    @pytest.fixture(autouse=True)
    def _reset(self):
        self.test_flag = None

    async def test_init_import_errors(self, monkeypatch):
        """Makes sure that import errors are forwarded - related to TestNoSocks above"""

        def __init__(self, *args, **kwargs):
            raise ImportError("Other Error Message")

        monkeypatch.setattr(httpx.AsyncClient, "__init__", __init__)

        # Make sure that other exceptions are forwarded
        with pytest.raises(ImportError, match=r"Other Error Message"):
            HTTPXRequest(proxy="socks5://foo")

    def test_slot_behaviour(self):
        inst = HTTPXRequest()
        for attr in inst.__slots__:
            at = f"_{inst.__class__.__name__}{attr}" if attr.startswith("__") else attr
            assert getattr(inst, at, "err") != "err", f"got extra slot '{at}'"
        assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"

    def test_httpx_kwargs(self, monkeypatch):
        self.test_flag = {}

        orig_init = httpx.AsyncClient.__init__

        class Client(httpx.AsyncClient):
            def __init__(*args, **kwargs):
                orig_init(*args, **kwargs)
                self.test_flag["args"] = args
                self.test_flag["kwargs"] = kwargs

        monkeypatch.setattr(httpx, "AsyncClient", Client)

        HTTPXRequest(
            connect_timeout=1,
            connection_pool_size=42,
            http_version="2",
            httpx_kwargs={
                "timeout": httpx.Timeout(7),
                "limits": httpx.Limits(max_connections=7),
                "http1": True,
                "verify": False,
            },
        )
        kwargs = self.test_flag["kwargs"]

        assert kwargs["timeout"].connect == 7
        assert kwargs["limits"].max_connections == 7
        assert kwargs["http1"] is True
        assert kwargs["verify"] is False

    async def test_context_manager(self, monkeypatch):
        async def initialize():
            self.test_flag = ["initialize"]

        async def shutdown():
            self.test_flag.append("stop")

        httpx_request = NonchalantHttpxRequest()

        monkeypatch.setattr(httpx_request, "initialize", initialize)
        monkeypatch.setattr(httpx_request, "shutdown", shutdown)

        async with httpx_request:
            pass

        assert self.test_flag == ["initialize", "stop"]

    async def test_context_manager_exception_on_init(self, monkeypatch):
        async def initialize():
            raise RuntimeError("initialize")

        async def shutdown():
            self.test_flag = "stop"

        httpx_request = NonchalantHttpxRequest()

        monkeypatch.setattr(httpx_request, "initialize", initialize)
        monkeypatch.setattr(httpx_request, "shutdown", shutdown)

        with pytest.raises(RuntimeError, match="initialize"):
            async with httpx_request:
                pass

        assert self.test_flag == "stop"

    async def test_replaced_unprintable_char(self, monkeypatch, httpx_request):
        """Clients can send arbitrary bytes in callback data. Make sure that we just replace
        those
        """
        server_response = b'{"result": "test_string\x80"}'

        monkeypatch.setattr(httpx_request, "do_request", mocker_factory(response=server_response))

        assert await httpx_request.post(None, None, None) == "test_string�"
        # Explicitly call `parse_json_payload` here is well so that this public method is covered
        # not only implicitly.
        assert httpx_request.parse_json_payload(server_response) == {"result": "test_string�"}

    async def test_illegal_json_response(self, monkeypatch, httpx_request: HTTPXRequest, caplog):
        # for proper JSON it should be `"result":` instead of `result:`
        server_response = b'{result: "test_string"}'

        monkeypatch.setattr(httpx_request, "do_request", mocker_factory(response=server_response))

        with (
            pytest.raises(TelegramError, match="Invalid server response"),
            caplog.at_level(logging.ERROR),
        ):
            await httpx_request.post(None, None, None)

        assert len(caplog.records) == 1
        record = caplog.records[0]
        assert record.name == "telegram.request.BaseRequest"
        assert record.getMessage().endswith(f'invalid JSON data: "{server_response.decode()}"')

    async def test_chat_migrated(self, monkeypatch, httpx_request: HTTPXRequest):
        server_response = b'{"ok": "False", "parameters": {"migrate_to_chat_id": 123}}'

        monkeypatch.setattr(
            httpx_request,
            "do_request",
            mocker_factory(response=server_response, return_code=HTTPStatus.BAD_REQUEST),
        )

        with pytest.raises(ChatMigrated, match="New chat id: 123") as exc_info:
            await httpx_request.post(None, None, None)

        assert exc_info.value.new_chat_id == 123

    async def test_retry_after(self, monkeypatch, httpx_request: HTTPXRequest, PTB_TIMEDELTA):
        server_response = b'{"ok": "False", "parameters": {"retry_after": 42}}'

        monkeypatch.setattr(
            httpx_request,
            "do_request",
            mocker_factory(response=server_response, return_code=HTTPStatus.BAD_REQUEST),
        )

        with pytest.raises(
            RetryAfter, match="Retry in " + "0:00:42" if PTB_TIMEDELTA else "42"
        ) as exc_info:
            await httpx_request.post(None, None, None)

        assert exc_info.value.retry_after == (dtm.timdelta(seconds=42) if PTB_TIMEDELTA else 42)

    async def test_unknown_request_params(self, monkeypatch, httpx_request: HTTPXRequest):
        server_response = b'{"ok": "False", "parameters": {"unknown": "42"}}'

        monkeypatch.setattr(
            httpx_request,
            "do_request",
            mocker_factory(response=server_response, return_code=HTTPStatus.BAD_REQUEST),
        )

        with pytest.raises(
            BadRequest,
            match="{'unknown': '42'}",
        ):
            await httpx_request.post(None, None, None)

    @pytest.mark.parametrize("description", [True, False])
    async def test_error_description(self, monkeypatch, httpx_request: HTTPXRequest, description):
        response_data = {"ok": "False"}
        if description:
            match = "ErrorDescription"
            response_data["description"] = match
        else:
            match = "Unknown HTTPError"

        server_response = json.dumps(response_data).encode(TextEncoding.UTF_8)

        monkeypatch.setattr(
            httpx_request,
            "do_request",
            mocker_factory(response=server_response, return_code=-1),
        )

        with pytest.raises(NetworkError, match=match):
            await httpx_request.post(None, None, None)

        # Special casing for bad gateway
        if not description:
            monkeypatch.setattr(
                httpx_request,
                "do_request",
                mocker_factory(response=server_response, return_code=HTTPStatus.BAD_GATEWAY),
            )

            with pytest.raises(NetworkError, match="Bad Gateway"):
                await httpx_request.post(None, None, None)

    @pytest.mark.parametrize(
        ("code", "exception_class"),
        [
            (HTTPStatus.FORBIDDEN, Forbidden),
            (HTTPStatus.NOT_FOUND, InvalidToken),
            (HTTPStatus.UNAUTHORIZED, InvalidToken),
            (HTTPStatus.BAD_REQUEST, BadRequest),
            (HTTPStatus.CONFLICT, Conflict),
            (HTTPStatus.BAD_GATEWAY, NetworkError),
            (-1, NetworkError),
        ],
    )
    @pytest.mark.parametrize("description", ["Test Message", None])
    async def test_special_errors(
        self, monkeypatch, httpx_request: HTTPXRequest, code, exception_class, description
    ):
        server_response_json = {"ok": False}
        if description:
            server_response_json["description"] = description
        server_response = json.dumps(server_response_json).encode(TextEncoding.UTF_8)

        monkeypatch.setattr(
            httpx_request,
            "do_request",
            mocker_factory(response=server_response, return_code=code),
        )

        if not description and code not in list(HTTPStatus):
            match = f"Unknown HTTPError.*{code}"
        else:
            match = description or str(code.value)

        with pytest.raises(exception_class, match=match):
            await httpx_request.post("", None, None)

    async def test_error_parsing_payload(self, monkeypatch, httpx_request: HTTPXRequest):
        """Test that we raise an error if the payload is not a valid JSON."""
        server_response = b"invalid_json"

        monkeypatch.setattr(
            httpx_request,
            "do_request",
            mocker_factory(response=server_response, return_code=HTTPStatus.BAD_GATEWAY),
        )

        with pytest.raises(TelegramError, match=r"502.*\. Parsing.*b'invalid_json' failed"):
            await httpx_request.post("", None, None)

    @pytest.mark.parametrize(
        ("exception", "catch_class", "match"),
        [
            (TelegramError("TelegramError"), TelegramError, "TelegramError"),
            (
                RuntimeError("CustomError"),
                NetworkError,
                r"HTTP implementation: RuntimeError\('CustomError'\)",
            ),
        ],
    )
    async def test_exceptions_in_do_request(
        self, monkeypatch, httpx_request: HTTPXRequest, exception, catch_class, match
    ):
        async def do_request(*args, **kwargs):
            raise exception

        monkeypatch.setattr(
            httpx_request,
            "do_request",
            do_request,
        )

        with pytest.raises(catch_class, match=match) as exc_info:
            await httpx_request.post(None, None, None)

        if catch_class is NetworkError:
            assert exc_info.value.__cause__ is exception

    async def test_retrieve(self, monkeypatch, httpx_request):
        """Here we just test that retrieve gives us the raw bytes instead of trying to parse them
        as json
        """
        server_response = b'{"result": "test_string\x80"}'

        monkeypatch.setattr(httpx_request, "do_request", mocker_factory(response=server_response))

        assert await httpx_request.retrieve(None, None) == server_response

    async def test_timeout_propagation_to_do_request(self, monkeypatch, httpx_request):
        async def make_assertion(*args, **kwargs):
            self.test_flag = (
                kwargs.get("read_timeout"),
                kwargs.get("connect_timeout"),
                kwargs.get("write_timeout"),
                kwargs.get("pool_timeout"),
            )
            return HTTPStatus.OK, b'{"ok": "True", "result": {}}'

        monkeypatch.setattr(httpx_request, "do_request", make_assertion)

        await httpx_request.post("url", None)
        assert self.test_flag == (DEFAULT_NONE, DEFAULT_NONE, DEFAULT_NONE, DEFAULT_NONE)

        await httpx_request.post(
            "url", None, read_timeout=1, connect_timeout=2, write_timeout=3, pool_timeout=4
        )
        assert self.test_flag == (1, 2, 3, 4)


@pytest.mark.skipif(not TEST_WITH_OPT_DEPS, reason="No need to run this twice")
class TestHTTPXRequestWithoutRequest:
    test_flag = None

    @pytest.fixture(autouse=True)
    def _reset(self):
        self.test_flag = None

    def test_init(self, monkeypatch):
        @dataclass
        class Client:
            timeout: object
            proxy: object
            limits: object
            http1: object
            http2: object
            transport: object = None

        monkeypatch.setattr(httpx, "AsyncClient", Client)

        request = HTTPXRequest()
        assert request._client.timeout == httpx.Timeout(connect=5.0, read=5.0, write=5.0, pool=1.0)
        assert request._client.proxy is None
        assert request._client.limits == httpx.Limits(
            max_connections=1, max_keepalive_connections=1
        )
        assert request._client.http1 is True
        assert not request._client.http2

        request = HTTPXRequest(
            connection_pool_size=42,
            proxy="proxy",
            connect_timeout=43,
            read_timeout=44,
            write_timeout=45,
            pool_timeout=46,
        )
        assert request._client.proxy == "proxy"
        assert request._client.limits == httpx.Limits(
            max_connections=42, max_keepalive_connections=42
        )
        assert request._client.timeout == httpx.Timeout(connect=43, read=44, write=45, pool=46)

    async def test_multiple_inits_and_shutdowns(self, monkeypatch):
        self.test_flag = defaultdict(int)

        orig_init = httpx.AsyncClient.__init__
        orig_aclose = httpx.AsyncClient.aclose

        class Client(httpx.AsyncClient):
            def __init__(*args, **kwargs):
                orig_init(*args, **kwargs)
                self.test_flag["init"] += 1

            async def aclose(*args, **kwargs):
                await orig_aclose(*args, **kwargs)
                self.test_flag["shutdown"] += 1

        monkeypatch.setattr(httpx, "AsyncClient", Client)

        # Create a new one instead of using the fixture so that the mocking can work
        httpx_request = HTTPXRequest()

        await httpx_request.initialize()
        await httpx_request.initialize()
        await httpx_request.initialize()
        await httpx_request.shutdown()
        await httpx_request.shutdown()
        await httpx_request.shutdown()

        assert self.test_flag["init"] == 1
        assert self.test_flag["shutdown"] == 1

    async def test_http_version_error(self):
        with pytest.raises(ValueError, match="`http_version` must be either"):
            HTTPXRequest(http_version="1.0")

    async def test_do_request_after_shutdown(self, httpx_request):
        await httpx_request.shutdown()
        with pytest.raises(RuntimeError, match="not initialized"):
            await httpx_request.do_request(url="url", method="GET")

    async def test_context_manager(self, monkeypatch):
        async def initialize():
            self.test_flag = ["initialize"]

        async def aclose(*args):
            self.test_flag.append("stop")

        httpx_request = NonchalantHttpxRequest()

        monkeypatch.setattr(httpx_request, "initialize", initialize)
        monkeypatch.setattr(httpx.AsyncClient, "aclose", aclose)

        async with httpx_request:
            pass

        assert self.test_flag == ["initialize", "stop"]

    async def test_context_manager_exception_on_init(self, monkeypatch):
        async def initialize():
            raise RuntimeError("initialize")

        async def aclose(*args):
            self.test_flag = "stop"

        httpx_request = NonchalantHttpxRequest()

        monkeypatch.setattr(httpx_request, "initialize", initialize)
        monkeypatch.setattr(httpx.AsyncClient, "aclose", aclose)

        with pytest.raises(RuntimeError, match="initialize"):
            async with httpx_request:
                pass

        assert self.test_flag == "stop"

    async def test_do_request_default_timeouts(self, monkeypatch):
        default_timeouts = httpx.Timeout(connect=42, read=43, write=44, pool=45)

        async def make_assertion(_, **kwargs):
            self.test_flag = kwargs.get("timeout") == default_timeouts
            return httpx.Response(HTTPStatus.OK)

        async with HTTPXRequest(
            connect_timeout=default_timeouts.connect,
            read_timeout=default_timeouts.read,
            write_timeout=default_timeouts.write,
            pool_timeout=default_timeouts.pool,
        ) as httpx_request:
            monkeypatch.setattr(httpx.AsyncClient, "request", make_assertion)
            await httpx_request.do_request(method="GET", url="URL")

        assert self.test_flag

    async def test_do_request_manual_timeouts(self, monkeypatch, httpx_request):
        default_timeouts = httpx.Timeout(connect=42, read=43, write=44, pool=45)
        manual_timeouts = httpx.Timeout(connect=52, read=53, write=54, pool=55)

        async def make_assertion(_, **kwargs):
            self.test_flag = kwargs.get("timeout") == manual_timeouts
            return httpx.Response(HTTPStatus.OK)

        async with HTTPXRequest(
            connect_timeout=default_timeouts.connect,
            read_timeout=default_timeouts.read,
            write_timeout=default_timeouts.write,
            pool_timeout=default_timeouts.pool,
        ) as httpx_request_ctx:
            monkeypatch.setattr(httpx.AsyncClient, "request", make_assertion)
            await httpx_request_ctx.do_request(
                method="GET",
                url="URL",
                connect_timeout=manual_timeouts.connect,
                read_timeout=manual_timeouts.read,
                write_timeout=manual_timeouts.write,
                pool_timeout=manual_timeouts.pool,
            )

        assert self.test_flag

    async def test_do_request_params_no_data(self, monkeypatch, httpx_request):
        async def make_assertion(self, **kwargs):
            method_assertion = kwargs.get("method") == "method"
            url_assertion = kwargs.get("url") == "url"
            files_assertion = kwargs.get("files") is None
            data_assertion = kwargs.get("data") is None
            if method_assertion and url_assertion and files_assertion and data_assertion:
                return httpx.Response(HTTPStatus.OK)
            return httpx.Response(HTTPStatus.BAD_REQUEST)

        monkeypatch.setattr(httpx.AsyncClient, "request", make_assertion)
        code, _ = await httpx_request.do_request(method="method", url="url")
        assert code == HTTPStatus.OK

    async def test_do_request_params_with_data(
        self, monkeypatch, httpx_request, mixed_rqs  # noqa: F811
    ):
        async def make_assertion(self, **kwargs):
            method_assertion = kwargs.get("method") == "method"
            url_assertion = kwargs.get("url") == "url"
            files_assertion = kwargs.get("files") == mixed_rqs.multipart_data
            data_assertion = kwargs.get("data") == mixed_rqs.json_parameters
            if method_assertion and url_assertion and files_assertion and data_assertion:
                return httpx.Response(HTTPStatus.OK)
            return httpx.Response(HTTPStatus.BAD_REQUEST)

        monkeypatch.setattr(httpx.AsyncClient, "request", make_assertion)
        code, _ = await httpx_request.do_request(
            method="method",
            url="url",
            request_data=mixed_rqs,
        )
        assert code == HTTPStatus.OK

    async def test_do_request_return_value(self, monkeypatch, httpx_request):
        async def make_assertion(self, method, url, headers, timeout, files, data):
            return httpx.Response(123, content=b"content")

        monkeypatch.setattr(httpx.AsyncClient, "request", make_assertion)
        code, content = await httpx_request.do_request(
            "method",
            "url",
        )
        assert code == 123
        assert content == b"content"

    @pytest.mark.parametrize(
        ("raised_exception", "expected_class", "expected_message"),
        [
            (httpx.TimeoutException("timeout"), TimedOut, "Timed out"),
            (httpx.ReadError("read_error"), NetworkError, "httpx.ReadError: read_error"),
        ],
    )
    async def test_do_request_exceptions(
        self, monkeypatch, httpx_request, raised_exception, expected_class, expected_message
    ):
        async def make_assertion(self, method, url, headers, timeout, files, data):
            raise raised_exception

        monkeypatch.setattr(httpx.AsyncClient, "request", make_assertion)

        with pytest.raises(expected_class, match=expected_message) as exc_info:
            await httpx_request.do_request(
                "method",
                "url",
            )

        assert exc_info.value.__cause__ is raised_exception

    async def test_do_request_pool_timeout(self, monkeypatch):
        pool_timeout = httpx.PoolTimeout("pool timeout")

        async def request(_, **kwargs):
            if self.test_flag is None:
                self.test_flag = True
            else:
                raise pool_timeout
            return httpx.Response(HTTPStatus.OK)

        monkeypatch.setattr(httpx.AsyncClient, "request", request)

        async with HTTPXRequest(pool_timeout=0.02) as httpx_request:
            with pytest.raises(TimedOut, match="Pool timeout") as exc_info:
                await asyncio.gather(
                    httpx_request.do_request(method="GET", url="URL"),
                    httpx_request.do_request(method="GET", url="URL"),
                )

            assert exc_info.value.__cause__ is pool_timeout

    @pytest.mark.parametrize("media", [True, False])
    async def test_do_request_write_timeout(
        self, monkeypatch, media, httpx_request, input_media_photo  # noqa: F811
    ):
        async def request(_, **kwargs):
            self.test_flag = kwargs.get("timeout")
            return httpx.Response(HTTPStatus.OK, content=b'{"ok": "True", "result": {}}')

        monkeypatch.setattr(httpx.AsyncClient, "request", request)

        data = {"string": "string", "int": 1, "float": 1.0}
        if media:
            data["media"] = input_media_photo
        request_data = RequestData(
            parameters=[RequestParameter.from_input(key, value) for key, value in data.items()],
        )

        # First make sure that custom timeouts are always respected
        await httpx_request.post(
            "url", request_data, read_timeout=1, connect_timeout=2, write_timeout=3, pool_timeout=4
        )
        assert self.test_flag == httpx.Timeout(read=1, connect=2, write=3, pool=4)

        # Now also ensure that the default timeout for media requests is 20 seconds
        await httpx_request.post("url", request_data)
        assert self.test_flag == httpx.Timeout(read=5, connect=5, write=20 if media else 5, pool=1)

    @pytest.mark.parametrize("init", [True, False])
    async def test_setting_media_write_timeout(
        self, monkeypatch, init, input_media_photo, recwarn  # noqa: F811
    ):
        httpx_request = HTTPXRequest(media_write_timeout=42) if init else HTTPXRequest()

        async def request(_, **kwargs):
            self.test_flag = kwargs["timeout"].write
            return httpx.Response(HTTPStatus.OK, content=b'{"ok": "True", "result": {}}')

        monkeypatch.setattr(httpx.AsyncClient, "request", request)

        data = {"string": "string", "int": 1, "float": 1.0, "media": input_media_photo}
        request_data = RequestData(
            parameters=[RequestParameter.from_input(key, value) for key, value in data.items()],
        )

        # First make sure that custom timeouts are always respected
        await httpx_request.post(
            "url",
            request_data,
            write_timeout=43,
        )
        assert self.test_flag == 43

        # Now also ensure that the init value is respected
        await httpx_request.post("url", request_data)
        assert self.test_flag == 42 if init else 20

        # Just for double-checking, since warnings are issued for implementations of BaseRequest
        # other than HTTPXRequest
        assert len(recwarn) == 0

    async def test_socket_opts(self, monkeypatch):
        transport_kwargs = {}
        transport_init = AsyncHTTPTransport.__init__

        def init_transport(*args, **kwargs):
            nonlocal transport_kwargs
            transport_kwargs = kwargs.copy()
            transport_init(*args, **kwargs)

        monkeypatch.setattr(AsyncHTTPTransport, "__init__", init_transport)

        HTTPXRequest()
        assert "socket_options" not in transport_kwargs

        transport_kwargs = {}
        HTTPXRequest(socket_options=((1, 2, 3),))
        assert transport_kwargs["socket_options"] == ((1, 2, 3),)

    @pytest.mark.parametrize("read_timeout", [None, 1, 2, 3])
    async def test_read_timeout_property(self, read_timeout):
        assert HTTPXRequest(read_timeout=read_timeout).read_timeout == read_timeout


@pytest.mark.skipif(not TEST_WITH_OPT_DEPS, reason="No need to run this twice")
class TestHTTPXRequestWithRequest:
    async def test_multiple_init_cycles(self):
        # nothing really to assert - this should just not fail
        httpx_request = HTTPXRequest()
        async with httpx_request:
            await httpx_request.do_request(url="https://python-telegram-bot.org", method="GET")
        async with httpx_request:
            await httpx_request.do_request(url="https://python-telegram-bot.org", method="GET")

    async def test_http_1_response(self):
        httpx_request = HTTPXRequest(http_version="1.1")
        async with httpx_request:
            resp = await httpx_request._client.request(
                url="https://python-telegram-bot.org",
                method="GET",
                headers={"User-Agent": httpx_request.USER_AGENT},
            )
            assert resp.http_version == "HTTP/1.1"

    async def test_do_request_wait_for_pool(self, httpx_request):
        """The pool logic is buried rather deeply in httpxcore, so we make actual requests here
        instead of mocking"""
        task_1 = asyncio.create_task(
            httpx_request.do_request(
                method="GET", url="https://python-telegram-bot.org/static/testfiles/telegram.mp4"
            )
        )
        task_2 = asyncio.create_task(
            httpx_request.do_request(
                method="GET", url="https://python-telegram-bot.org/static/testfiles/telegram.mp4"
            )
        )
        done, pending = await asyncio.wait({task_1, task_2}, return_when=asyncio.FIRST_COMPLETED)
        assert len(done) == len(pending) == 1
        done, pending = await asyncio.wait({task_1, task_2}, return_when=asyncio.ALL_COMPLETED)
        assert len(done) == 2
        assert len(pending) == 0
        try:  # retrieve exceptions from tasks
            task_1.exception()
            task_2.exception()
        except (asyncio.CancelledError, asyncio.InvalidStateError):
            pass

    async def test_input_file_postponed_read(self, bot, chat_id):
        """Here we test that `read_file_handle=False` is correctly handled by HTTPXRequest.
        Since manually building the RequestData object has no real benefit, we simply use the Bot
        for that.
        """
        message = await bot.send_document(
            document=InputFile(data_file("telegram.jpg").open("rb"), read_file_handle=False),
            chat_id=chat_id,
        )
        assert message.document
        assert message.document.file_name == "telegram.jpg"