Skip to content

Test Client

Esmerald offers an extension of the Starlette TestClient called EsmeraldTestClient as well as a create_client that can be used for context testing.

from esmerald.testclient import EsmeraldTestClient

esmerald.testclient.EsmeraldTestClient

EsmeraldTestClient(app, base_url='http://testserver', raise_server_exceptions=True, root_path='', backend='asyncio', backend_options=None, cookies=None, headers=None)

Bases: TestClient

PARAMETER DESCRIPTION
app

TYPE: Esmerald

base_url

TYPE: str DEFAULT: 'http://testserver'

raise_server_exceptions

TYPE: bool DEFAULT: True

root_path

TYPE: str DEFAULT: ''

backend

TYPE: Literal['asyncio', 'trio'] DEFAULT: 'asyncio'

backend_options

TYPE: Optional[Dict[str, Any]] DEFAULT: None

cookies

TYPE: Optional[CookieTypes] DEFAULT: None

headers

TYPE: Dict[str, str] DEFAULT: None

Source code in esmerald/testclient.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
def __init__(
    self,
    app: Esmerald,
    base_url: str = "http://testserver",
    raise_server_exceptions: bool = True,
    root_path: str = "",
    backend: "Literal['asyncio', 'trio']" = "asyncio",
    backend_options: Optional[Dict[str, Any]] = None,
    cookies: Optional[CookieTypes] = None,
    headers: Dict[str, str] = None,
):
    super().__init__(
        app=app,
        base_url=base_url,
        raise_server_exceptions=raise_server_exceptions,
        root_path=root_path,
        backend=backend,
        backend_options=backend_options,
        cookies=cookies,
        headers=headers,
    )

headers property writable

headers

HTTP headers to include when sending requests.

follow_redirects instance-attribute

follow_redirects = follow_redirects

max_redirects instance-attribute

max_redirects = max_redirects

is_closed property

is_closed

Check if the client being closed

trust_env property

trust_env

timeout property writable

timeout

event_hooks property writable

event_hooks

auth property writable

auth

Authentication class used when none is passed at the request-level.

See also Authentication.

base_url property writable

base_url

Base URL to use when sending requests with relative URLs.

cookies property writable

cookies

Cookie values to include when sending requests.

params property writable

params

Query parameters to include in the URL when sending requests.

task instance-attribute

task

portal class-attribute instance-attribute

portal = None

async_backend instance-attribute

async_backend = _AsyncBackend(backend=backend, backend_options=backend_options or {})

app_state instance-attribute

app_state = {}

app instance-attribute

app

build_request

build_request(method, url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, timeout=USE_CLIENT_DEFAULT, extensions=None)

Build and return a request instance.

  • The params, headers and cookies arguments are merged with any values set on the client.
  • The url argument is merged with any base_url set on the client.

See also: Request instances

PARAMETER DESCRIPTION
method

TYPE: str

url

TYPE: URLTypes

content

TYPE: Optional[RequestContent] DEFAULT: None

data

TYPE: Optional[RequestData] DEFAULT: None

files

TYPE: Optional[RequestFiles] DEFAULT: None

json

TYPE: Optional[Any] DEFAULT: None

params

TYPE: Optional[QueryParamTypes] DEFAULT: None

headers

TYPE: Optional[HeaderTypes] DEFAULT: None

cookies

TYPE: Optional[CookieTypes] DEFAULT: None

timeout

TYPE: Union[TimeoutTypes, UseClientDefault] DEFAULT: USE_CLIENT_DEFAULT

extensions

TYPE: Optional[RequestExtensions] DEFAULT: None

Source code in .venv/lib/python3.8/site-packages/httpx/_client.py
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
def build_request(
    self,
    method: str,
    url: URLTypes,
    *,
    content: typing.Optional[RequestContent] = None,
    data: typing.Optional[RequestData] = None,
    files: typing.Optional[RequestFiles] = None,
    json: typing.Optional[typing.Any] = None,
    params: typing.Optional[QueryParamTypes] = None,
    headers: typing.Optional[HeaderTypes] = None,
    cookies: typing.Optional[CookieTypes] = None,
    timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT,
    extensions: typing.Optional[RequestExtensions] = None,
) -> Request:
    """
    Build and return a request instance.

    * The `params`, `headers` and `cookies` arguments
    are merged with any values set on the client.
    * The `url` argument is merged with any `base_url` set on the client.

    See also: [Request instances][0]

    [0]: /advanced/#request-instances
    """
    url = self._merge_url(url)
    headers = self._merge_headers(headers)
    cookies = self._merge_cookies(cookies)
    params = self._merge_queryparams(params)
    extensions = {} if extensions is None else extensions
    if "timeout" not in extensions:
        timeout = (
            self.timeout
            if isinstance(timeout, UseClientDefault)
            else Timeout(timeout)
        )
        extensions = dict(**extensions, timeout=timeout.as_dict())
    return Request(
        method,
        url,
        content=content,
        data=data,
        files=files,
        json=json,
        params=params,
        headers=headers,
        cookies=cookies,
        extensions=extensions,
    )

request

request(method, url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=httpx._client.USE_CLIENT_DEFAULT, follow_redirects=None, allow_redirects=None, timeout=httpx._client.USE_CLIENT_DEFAULT, extensions=None)
PARAMETER DESCRIPTION
method

TYPE: str

url

TYPE: URLTypes

content

TYPE: Optional[RequestContent] DEFAULT: None

data

TYPE: Optional[_RequestData] DEFAULT: None

files

TYPE: Optional[RequestFiles] DEFAULT: None

json

TYPE: Any DEFAULT: None

params

TYPE: Optional[QueryParamTypes] DEFAULT: None

headers

TYPE: Optional[HeaderTypes] DEFAULT: None

cookies

TYPE: Optional[CookieTypes] DEFAULT: None

auth

TYPE: Union[AuthTypes, UseClientDefault] DEFAULT: USE_CLIENT_DEFAULT

follow_redirects

TYPE: Optional[bool] DEFAULT: None

allow_redirects

TYPE: Optional[bool] DEFAULT: None

timeout

TYPE: Union[TimeoutTypes, UseClientDefault] DEFAULT: USE_CLIENT_DEFAULT

extensions

TYPE: Optional[Dict[str, Any]] DEFAULT: None

Source code in .venv/lib/python3.8/site-packages/starlette/testclient.py
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
def request(  # type: ignore[override]
    self,
    method: str,
    url: httpx._types.URLTypes,
    *,
    content: typing.Optional[httpx._types.RequestContent] = None,
    data: typing.Optional[_RequestData] = None,
    files: typing.Optional[httpx._types.RequestFiles] = None,
    json: typing.Any = None,
    params: typing.Optional[httpx._types.QueryParamTypes] = None,
    headers: typing.Optional[httpx._types.HeaderTypes] = None,
    cookies: typing.Optional[httpx._types.CookieTypes] = None,
    auth: typing.Union[
        httpx._types.AuthTypes, httpx._client.UseClientDefault
    ] = httpx._client.USE_CLIENT_DEFAULT,
    follow_redirects: typing.Optional[bool] = None,
    allow_redirects: typing.Optional[bool] = None,
    timeout: typing.Union[
        httpx._types.TimeoutTypes, httpx._client.UseClientDefault
    ] = httpx._client.USE_CLIENT_DEFAULT,
    extensions: typing.Optional[typing.Dict[str, typing.Any]] = None,
) -> httpx.Response:
    url = self.base_url.join(url)
    redirect = self._choose_redirect_arg(follow_redirects, allow_redirects)
    return super().request(
        method,
        url,
        content=content,
        data=data,
        files=files,
        json=json,
        params=params,
        headers=headers,
        cookies=cookies,
        auth=auth,
        follow_redirects=redirect,
        timeout=timeout,
        extensions=extensions,
    )

stream

stream(method, url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=USE_CLIENT_DEFAULT, follow_redirects=USE_CLIENT_DEFAULT, timeout=USE_CLIENT_DEFAULT, extensions=None)

Alternative to httpx.request() that streams the response body instead of loading it into memory at once.

Parameters: See httpx.request.

See also: Streaming Responses

PARAMETER DESCRIPTION
method

TYPE: str

url

TYPE: URLTypes

content

TYPE: Optional[RequestContent] DEFAULT: None

data

TYPE: Optional[RequestData] DEFAULT: None

files

TYPE: Optional[RequestFiles] DEFAULT: None

json

TYPE: Optional[Any] DEFAULT: None

params

TYPE: Optional[QueryParamTypes] DEFAULT: None

headers

TYPE: Optional[HeaderTypes] DEFAULT: None

cookies

TYPE: Optional[CookieTypes] DEFAULT: None

auth

TYPE: Union[AuthTypes, UseClientDefault, None] DEFAULT: USE_CLIENT_DEFAULT

follow_redirects

TYPE: Union[bool, UseClientDefault] DEFAULT: USE_CLIENT_DEFAULT

timeout

TYPE: Union[TimeoutTypes, UseClientDefault] DEFAULT: USE_CLIENT_DEFAULT

extensions

TYPE: Optional[RequestExtensions] DEFAULT: None

YIELDS DESCRIPTION
Response
Source code in .venv/lib/python3.8/site-packages/httpx/_client.py
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
@contextmanager
def stream(
    self,
    method: str,
    url: URLTypes,
    *,
    content: typing.Optional[RequestContent] = None,
    data: typing.Optional[RequestData] = None,
    files: typing.Optional[RequestFiles] = None,
    json: typing.Optional[typing.Any] = None,
    params: typing.Optional[QueryParamTypes] = None,
    headers: typing.Optional[HeaderTypes] = None,
    cookies: typing.Optional[CookieTypes] = None,
    auth: typing.Union[AuthTypes, UseClientDefault, None] = USE_CLIENT_DEFAULT,
    follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT,
    timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT,
    extensions: typing.Optional[RequestExtensions] = None,
) -> typing.Iterator[Response]:
    """
    Alternative to `httpx.request()` that streams the response body
    instead of loading it into memory at once.

    **Parameters**: See `httpx.request`.

    See also: [Streaming Responses][0]

    [0]: /quickstart#streaming-responses
    """
    request = self.build_request(
        method=method,
        url=url,
        content=content,
        data=data,
        files=files,
        json=json,
        params=params,
        headers=headers,
        cookies=cookies,
        timeout=timeout,
        extensions=extensions,
    )
    response = self.send(
        request=request,
        auth=auth,
        follow_redirects=follow_redirects,
        stream=True,
    )
    try:
        yield response
    finally:
        response.close()

send

send(request, *, stream=False, auth=USE_CLIENT_DEFAULT, follow_redirects=USE_CLIENT_DEFAULT)

Send a request.

The request is sent as-is, unmodified.

Typically you'll want to build one with Client.build_request() so that any client-level configuration is merged into the request, but passing an explicit httpx.Request() is supported as well.

See also: Request instances

PARAMETER DESCRIPTION
request

TYPE: Request

stream

TYPE: bool DEFAULT: False

auth

TYPE: Union[AuthTypes, UseClientDefault, None] DEFAULT: USE_CLIENT_DEFAULT

follow_redirects

TYPE: Union[bool, UseClientDefault] DEFAULT: USE_CLIENT_DEFAULT

Source code in .venv/lib/python3.8/site-packages/httpx/_client.py
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
def send(
    self,
    request: Request,
    *,
    stream: bool = False,
    auth: typing.Union[AuthTypes, UseClientDefault, None] = USE_CLIENT_DEFAULT,
    follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT,
) -> Response:
    """
    Send a request.

    The request is sent as-is, unmodified.

    Typically you'll want to build one with `Client.build_request()`
    so that any client-level configuration is merged into the request,
    but passing an explicit `httpx.Request()` is supported as well.

    See also: [Request instances][0]

    [0]: /advanced/#request-instances
    """
    if self._state == ClientState.CLOSED:
        raise RuntimeError("Cannot send a request, as the client has been closed.")

    self._state = ClientState.OPENED
    follow_redirects = (
        self.follow_redirects
        if isinstance(follow_redirects, UseClientDefault)
        else follow_redirects
    )

    auth = self._build_request_auth(request, auth)

    response = self._send_handling_auth(
        request,
        auth=auth,
        follow_redirects=follow_redirects,
        history=[],
    )
    try:
        if not stream:
            response.read()

        return response

    except BaseException as exc:
        response.close()
        raise exc

get

get(url, *, params=None, headers=None, cookies=None, auth=httpx._client.USE_CLIENT_DEFAULT, follow_redirects=None, allow_redirects=None, timeout=httpx._client.USE_CLIENT_DEFAULT, extensions=None)
PARAMETER DESCRIPTION
url

TYPE: URLTypes

params

TYPE: Optional[QueryParamTypes] DEFAULT: None

headers

TYPE: Optional[HeaderTypes] DEFAULT: None

cookies

TYPE: Optional[CookieTypes] DEFAULT: None

auth

TYPE: Union[AuthTypes, UseClientDefault] DEFAULT: USE_CLIENT_DEFAULT

follow_redirects

TYPE: Optional[bool] DEFAULT: None

allow_redirects

TYPE: Optional[bool] DEFAULT: None

timeout

TYPE: Union[TimeoutTypes, UseClientDefault] DEFAULT: USE_CLIENT_DEFAULT

extensions

TYPE: Optional[Dict[str, Any]] DEFAULT: None

Source code in .venv/lib/python3.8/site-packages/starlette/testclient.py
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
def get(  # type: ignore[override]
    self,
    url: httpx._types.URLTypes,
    *,
    params: typing.Optional[httpx._types.QueryParamTypes] = None,
    headers: typing.Optional[httpx._types.HeaderTypes] = None,
    cookies: typing.Optional[httpx._types.CookieTypes] = None,
    auth: typing.Union[
        httpx._types.AuthTypes, httpx._client.UseClientDefault
    ] = httpx._client.USE_CLIENT_DEFAULT,
    follow_redirects: typing.Optional[bool] = None,
    allow_redirects: typing.Optional[bool] = None,
    timeout: typing.Union[
        httpx._types.TimeoutTypes, httpx._client.UseClientDefault
    ] = httpx._client.USE_CLIENT_DEFAULT,
    extensions: typing.Optional[typing.Dict[str, typing.Any]] = None,
) -> httpx.Response:
    redirect = self._choose_redirect_arg(follow_redirects, allow_redirects)
    return super().get(
        url,
        params=params,
        headers=headers,
        cookies=cookies,
        auth=auth,
        follow_redirects=redirect,
        timeout=timeout,
        extensions=extensions,
    )

options

options(url, *, params=None, headers=None, cookies=None, auth=httpx._client.USE_CLIENT_DEFAULT, follow_redirects=None, allow_redirects=None, timeout=httpx._client.USE_CLIENT_DEFAULT, extensions=None)
PARAMETER DESCRIPTION
url

TYPE: URLTypes

params

TYPE: Optional[QueryParamTypes] DEFAULT: None

headers

TYPE: Optional[HeaderTypes] DEFAULT: None

cookies

TYPE: Optional[CookieTypes] DEFAULT: None

auth

TYPE: Union[AuthTypes, UseClientDefault] DEFAULT: USE_CLIENT_DEFAULT

follow_redirects

TYPE: Optional[bool] DEFAULT: None

allow_redirects

TYPE: Optional[bool] DEFAULT: None

timeout

TYPE: Union[TimeoutTypes, UseClientDefault] DEFAULT: USE_CLIENT_DEFAULT

extensions

TYPE: Optional[Dict[str, Any]] DEFAULT: None

Source code in .venv/lib/python3.8/site-packages/starlette/testclient.py
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
def options(  # type: ignore[override]
    self,
    url: httpx._types.URLTypes,
    *,
    params: typing.Optional[httpx._types.QueryParamTypes] = None,
    headers: typing.Optional[httpx._types.HeaderTypes] = None,
    cookies: typing.Optional[httpx._types.CookieTypes] = None,
    auth: typing.Union[
        httpx._types.AuthTypes, httpx._client.UseClientDefault
    ] = httpx._client.USE_CLIENT_DEFAULT,
    follow_redirects: typing.Optional[bool] = None,
    allow_redirects: typing.Optional[bool] = None,
    timeout: typing.Union[
        httpx._types.TimeoutTypes, httpx._client.UseClientDefault
    ] = httpx._client.USE_CLIENT_DEFAULT,
    extensions: typing.Optional[typing.Dict[str, typing.Any]] = None,
) -> httpx.Response:
    redirect = self._choose_redirect_arg(follow_redirects, allow_redirects)
    return super().options(
        url,
        params=params,
        headers=headers,
        cookies=cookies,
        auth=auth,
        follow_redirects=redirect,
        timeout=timeout,
        extensions=extensions,
    )

head

head(url, *, params=None, headers=None, cookies=None, auth=httpx._client.USE_CLIENT_DEFAULT, follow_redirects=None, allow_redirects=None, timeout=httpx._client.USE_CLIENT_DEFAULT, extensions=None)
PARAMETER DESCRIPTION
url

TYPE: URLTypes

params

TYPE: Optional[QueryParamTypes] DEFAULT: None

headers

TYPE: Optional[HeaderTypes] DEFAULT: None

cookies

TYPE: Optional[CookieTypes] DEFAULT: None

auth

TYPE: Union[AuthTypes, UseClientDefault] DEFAULT: USE_CLIENT_DEFAULT

follow_redirects

TYPE: Optional[bool] DEFAULT: None

allow_redirects

TYPE: Optional[bool] DEFAULT: None

timeout

TYPE: Union[TimeoutTypes, UseClientDefault] DEFAULT: USE_CLIENT_DEFAULT

extensions

TYPE: Optional[Dict[str, Any]] DEFAULT: None

Source code in .venv/lib/python3.8/site-packages/starlette/testclient.py
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
def head(  # type: ignore[override]
    self,
    url: httpx._types.URLTypes,
    *,
    params: typing.Optional[httpx._types.QueryParamTypes] = None,
    headers: typing.Optional[httpx._types.HeaderTypes] = None,
    cookies: typing.Optional[httpx._types.CookieTypes] = None,
    auth: typing.Union[
        httpx._types.AuthTypes, httpx._client.UseClientDefault
    ] = httpx._client.USE_CLIENT_DEFAULT,
    follow_redirects: typing.Optional[bool] = None,
    allow_redirects: typing.Optional[bool] = None,
    timeout: typing.Union[
        httpx._types.TimeoutTypes, httpx._client.UseClientDefault
    ] = httpx._client.USE_CLIENT_DEFAULT,
    extensions: typing.Optional[typing.Dict[str, typing.Any]] = None,
) -> httpx.Response:
    redirect = self._choose_redirect_arg(follow_redirects, allow_redirects)
    return super().head(
        url,
        params=params,
        headers=headers,
        cookies=cookies,
        auth=auth,
        follow_redirects=redirect,
        timeout=timeout,
        extensions=extensions,
    )

post

post(url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=httpx._client.USE_CLIENT_DEFAULT, follow_redirects=None, allow_redirects=None, timeout=httpx._client.USE_CLIENT_DEFAULT, extensions=None)
PARAMETER DESCRIPTION
url

TYPE: URLTypes

content

TYPE: Optional[RequestContent] DEFAULT: None

data

TYPE: Optional[_RequestData] DEFAULT: None

files

TYPE: Optional[RequestFiles] DEFAULT: None

json

TYPE: Any DEFAULT: None

params

TYPE: Optional[QueryParamTypes] DEFAULT: None

headers

TYPE: Optional[HeaderTypes] DEFAULT: None

cookies

TYPE: Optional[CookieTypes] DEFAULT: None

auth

TYPE: Union[AuthTypes, UseClientDefault] DEFAULT: USE_CLIENT_DEFAULT

follow_redirects

TYPE: Optional[bool] DEFAULT: None

allow_redirects

TYPE: Optional[bool] DEFAULT: None

timeout

TYPE: Union[TimeoutTypes, UseClientDefault] DEFAULT: USE_CLIENT_DEFAULT

extensions

TYPE: Optional[Dict[str, Any]] DEFAULT: None

Source code in .venv/lib/python3.8/site-packages/starlette/testclient.py
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
def post(  # type: ignore[override]
    self,
    url: httpx._types.URLTypes,
    *,
    content: typing.Optional[httpx._types.RequestContent] = None,
    data: typing.Optional[_RequestData] = None,
    files: typing.Optional[httpx._types.RequestFiles] = None,
    json: typing.Any = None,
    params: typing.Optional[httpx._types.QueryParamTypes] = None,
    headers: typing.Optional[httpx._types.HeaderTypes] = None,
    cookies: typing.Optional[httpx._types.CookieTypes] = None,
    auth: typing.Union[
        httpx._types.AuthTypes, httpx._client.UseClientDefault
    ] = httpx._client.USE_CLIENT_DEFAULT,
    follow_redirects: typing.Optional[bool] = None,
    allow_redirects: typing.Optional[bool] = None,
    timeout: typing.Union[
        httpx._types.TimeoutTypes, httpx._client.UseClientDefault
    ] = httpx._client.USE_CLIENT_DEFAULT,
    extensions: typing.Optional[typing.Dict[str, typing.Any]] = None,
) -> httpx.Response:
    redirect = self._choose_redirect_arg(follow_redirects, allow_redirects)
    return super().post(
        url,
        content=content,
        data=data,
        files=files,
        json=json,
        params=params,
        headers=headers,
        cookies=cookies,
        auth=auth,
        follow_redirects=redirect,
        timeout=timeout,
        extensions=extensions,
    )

put

put(url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=httpx._client.USE_CLIENT_DEFAULT, follow_redirects=None, allow_redirects=None, timeout=httpx._client.USE_CLIENT_DEFAULT, extensions=None)
PARAMETER DESCRIPTION
url

TYPE: URLTypes

content

TYPE: Optional[RequestContent] DEFAULT: None

data

TYPE: Optional[_RequestData] DEFAULT: None

files

TYPE: Optional[RequestFiles] DEFAULT: None

json

TYPE: Any DEFAULT: None

params

TYPE: Optional[QueryParamTypes] DEFAULT: None

headers

TYPE: Optional[HeaderTypes] DEFAULT: None

cookies

TYPE: Optional[CookieTypes] DEFAULT: None

auth

TYPE: Union[AuthTypes, UseClientDefault] DEFAULT: USE_CLIENT_DEFAULT

follow_redirects

TYPE: Optional[bool] DEFAULT: None

allow_redirects

TYPE: Optional[bool] DEFAULT: None

timeout

TYPE: Union[TimeoutTypes, UseClientDefault] DEFAULT: USE_CLIENT_DEFAULT

extensions

TYPE: Optional[Dict[str, Any]] DEFAULT: None

Source code in .venv/lib/python3.8/site-packages/starlette/testclient.py
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
def put(  # type: ignore[override]
    self,
    url: httpx._types.URLTypes,
    *,
    content: typing.Optional[httpx._types.RequestContent] = None,
    data: typing.Optional[_RequestData] = None,
    files: typing.Optional[httpx._types.RequestFiles] = None,
    json: typing.Any = None,
    params: typing.Optional[httpx._types.QueryParamTypes] = None,
    headers: typing.Optional[httpx._types.HeaderTypes] = None,
    cookies: typing.Optional[httpx._types.CookieTypes] = None,
    auth: typing.Union[
        httpx._types.AuthTypes, httpx._client.UseClientDefault
    ] = httpx._client.USE_CLIENT_DEFAULT,
    follow_redirects: typing.Optional[bool] = None,
    allow_redirects: typing.Optional[bool] = None,
    timeout: typing.Union[
        httpx._types.TimeoutTypes, httpx._client.UseClientDefault
    ] = httpx._client.USE_CLIENT_DEFAULT,
    extensions: typing.Optional[typing.Dict[str, typing.Any]] = None,
) -> httpx.Response:
    redirect = self._choose_redirect_arg(follow_redirects, allow_redirects)
    return super().put(
        url,
        content=content,
        data=data,
        files=files,
        json=json,
        params=params,
        headers=headers,
        cookies=cookies,
        auth=auth,
        follow_redirects=redirect,
        timeout=timeout,
        extensions=extensions,
    )

patch

patch(url, *, content=None, data=None, files=None, json=None, params=None, headers=None, cookies=None, auth=httpx._client.USE_CLIENT_DEFAULT, follow_redirects=None, allow_redirects=None, timeout=httpx._client.USE_CLIENT_DEFAULT, extensions=None)
PARAMETER DESCRIPTION
url

TYPE: URLTypes

content

TYPE: Optional[RequestContent] DEFAULT: None

data

TYPE: Optional[_RequestData] DEFAULT: None

files

TYPE: Optional[RequestFiles] DEFAULT: None

json

TYPE: Any DEFAULT: None

params

TYPE: Optional[QueryParamTypes] DEFAULT: None

headers

TYPE: Optional[HeaderTypes] DEFAULT: None

cookies

TYPE: Optional[CookieTypes] DEFAULT: None

auth

TYPE: Union[AuthTypes, UseClientDefault] DEFAULT: USE_CLIENT_DEFAULT

follow_redirects

TYPE: Optional[bool] DEFAULT: None

allow_redirects

TYPE: Optional[bool] DEFAULT: None

timeout

TYPE: Union[TimeoutTypes, UseClientDefault] DEFAULT: USE_CLIENT_DEFAULT

extensions

TYPE: Optional[Dict[str, Any]] DEFAULT: None

Source code in .venv/lib/python3.8/site-packages/starlette/testclient.py
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
def patch(  # type: ignore[override]
    self,
    url: httpx._types.URLTypes,
    *,
    content: typing.Optional[httpx._types.RequestContent] = None,
    data: typing.Optional[_RequestData] = None,
    files: typing.Optional[httpx._types.RequestFiles] = None,
    json: typing.Any = None,
    params: typing.Optional[httpx._types.QueryParamTypes] = None,
    headers: typing.Optional[httpx._types.HeaderTypes] = None,
    cookies: typing.Optional[httpx._types.CookieTypes] = None,
    auth: typing.Union[
        httpx._types.AuthTypes, httpx._client.UseClientDefault
    ] = httpx._client.USE_CLIENT_DEFAULT,
    follow_redirects: typing.Optional[bool] = None,
    allow_redirects: typing.Optional[bool] = None,
    timeout: typing.Union[
        httpx._types.TimeoutTypes, httpx._client.UseClientDefault
    ] = httpx._client.USE_CLIENT_DEFAULT,
    extensions: typing.Optional[typing.Dict[str, typing.Any]] = None,
) -> httpx.Response:
    redirect = self._choose_redirect_arg(follow_redirects, allow_redirects)
    return super().patch(
        url,
        content=content,
        data=data,
        files=files,
        json=json,
        params=params,
        headers=headers,
        cookies=cookies,
        auth=auth,
        follow_redirects=redirect,
        timeout=timeout,
        extensions=extensions,
    )

delete

delete(url, *, params=None, headers=None, cookies=None, auth=httpx._client.USE_CLIENT_DEFAULT, follow_redirects=None, allow_redirects=None, timeout=httpx._client.USE_CLIENT_DEFAULT, extensions=None)
PARAMETER DESCRIPTION
url

TYPE: URLTypes

params

TYPE: Optional[QueryParamTypes] DEFAULT: None

headers

TYPE: Optional[HeaderTypes] DEFAULT: None

cookies

TYPE: Optional[CookieTypes] DEFAULT: None

auth

TYPE: Union[AuthTypes, UseClientDefault] DEFAULT: USE_CLIENT_DEFAULT

follow_redirects

TYPE: Optional[bool] DEFAULT: None

allow_redirects

TYPE: Optional[bool] DEFAULT: None

timeout

TYPE: Union[TimeoutTypes, UseClientDefault] DEFAULT: USE_CLIENT_DEFAULT

extensions

TYPE: Optional[Dict[str, Any]] DEFAULT: None

Source code in .venv/lib/python3.8/site-packages/starlette/testclient.py
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
def delete(  # type: ignore[override]
    self,
    url: httpx._types.URLTypes,
    *,
    params: typing.Optional[httpx._types.QueryParamTypes] = None,
    headers: typing.Optional[httpx._types.HeaderTypes] = None,
    cookies: typing.Optional[httpx._types.CookieTypes] = None,
    auth: typing.Union[
        httpx._types.AuthTypes, httpx._client.UseClientDefault
    ] = httpx._client.USE_CLIENT_DEFAULT,
    follow_redirects: typing.Optional[bool] = None,
    allow_redirects: typing.Optional[bool] = None,
    timeout: typing.Union[
        httpx._types.TimeoutTypes, httpx._client.UseClientDefault
    ] = httpx._client.USE_CLIENT_DEFAULT,
    extensions: typing.Optional[typing.Dict[str, typing.Any]] = None,
) -> httpx.Response:
    redirect = self._choose_redirect_arg(follow_redirects, allow_redirects)
    return super().delete(
        url,
        params=params,
        headers=headers,
        cookies=cookies,
        auth=auth,
        follow_redirects=redirect,
        timeout=timeout,
        extensions=extensions,
    )

close

close()

Close transport and proxies.

Source code in .venv/lib/python3.8/site-packages/httpx/_client.py
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
def close(self) -> None:
    """
    Close transport and proxies.
    """
    if self._state != ClientState.CLOSED:
        self._state = ClientState.CLOSED

        self._transport.close()
        for transport in self._mounts.values():
            if transport is not None:
                transport.close()

websocket_connect

websocket_connect(url, subprotocols=None, **kwargs)
PARAMETER DESCRIPTION
url

TYPE: str

subprotocols

TYPE: Sequence[str] DEFAULT: None

**kwargs

TYPE: Any DEFAULT: {}

Source code in .venv/lib/python3.8/site-packages/starlette/testclient.py
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
def websocket_connect(
    self, url: str, subprotocols: typing.Sequence[str] = None, **kwargs: typing.Any
) -> "WebSocketTestSession":
    url = urljoin("ws://testserver", url)
    headers = kwargs.get("headers", {})
    headers.setdefault("connection", "upgrade")
    headers.setdefault("sec-websocket-key", "testserver==")
    headers.setdefault("sec-websocket-version", "13")
    if subprotocols is not None:
        headers.setdefault("sec-websocket-protocol", ", ".join(subprotocols))
    kwargs["headers"] = headers
    try:
        super().request("GET", url, **kwargs)
    except _Upgrade as exc:
        session = exc.session
    else:
        raise RuntimeError("Expected WebSocket upgrade")  # pragma: no cover

    return session

lifespan async

lifespan()
Source code in .venv/lib/python3.8/site-packages/starlette/testclient.py
767
768
769
770
771
772
async def lifespan(self) -> None:
    scope = {"type": "lifespan", "state": self.app_state}
    try:
        await self.app(scope, self.stream_receive.receive, self.stream_send.send)
    finally:
        await self.stream_send.send(None)

wait_startup async

wait_startup()
Source code in .venv/lib/python3.8/site-packages/starlette/testclient.py
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
async def wait_startup(self) -> None:
    await self.stream_receive.send({"type": "lifespan.startup"})

    async def receive() -> typing.Any:
        message = await self.stream_send.receive()
        if message is None:
            self.task.result()
        return message

    message = await receive()
    assert message["type"] in (
        "lifespan.startup.complete",
        "lifespan.startup.failed",
    )
    if message["type"] == "lifespan.startup.failed":
        await receive()

wait_shutdown async

wait_shutdown()
Source code in .venv/lib/python3.8/site-packages/starlette/testclient.py
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
async def wait_shutdown(self) -> None:
    async def receive() -> typing.Any:
        message = await self.stream_send.receive()
        if message is None:
            self.task.result()
        return message

    async with self.stream_send:
        await self.stream_receive.send({"type": "lifespan.shutdown"})
        message = await receive()
        assert message["type"] in (
            "lifespan.shutdown.complete",
            "lifespan.shutdown.failed",
        )
        if message["type"] == "lifespan.shutdown.failed":
            await receive()
from esmerald.testclient import create_client

You can learn more how to use it in the documentation.

esmerald.testclient.create_client

create_client(routes, *, settings_config=None, debug=None, app_name=None, title=None, version=None, summary=None, description=None, contact=None, terms_of_service=None, license=None, security=None, servers=None, secret_key=get_random_secret_key(), allowed_hosts=None, allow_origins=None, base_url='http://testserver', backend='asyncio', backend_options=None, interceptors=None, permissions=None, dependencies=None, middleware=None, csrf_config=None, exception_handlers=None, openapi_config=None, on_shutdown=None, on_startup=None, cors_config=None, session_config=None, scheduler_class=None, scheduler_tasks=None, scheduler_configurations=None, enable_scheduler=None, enable_openapi=True, include_in_schema=True, openapi_version='3.1.0', raise_server_exceptions=True, root_path='', static_files_config=None, template_config=None, lifespan=None, cookies=None, redirect_slashes=None, tags=None, webhooks=None)
PARAMETER DESCRIPTION
routes

TYPE: Union[APIGateHandler, List[APIGateHandler]]

settings_config

TYPE: Optional[SettingsType] DEFAULT: None

debug

TYPE: Optional[bool] DEFAULT: None

app_name

TYPE: Optional[str] DEFAULT: None

title

TYPE: Optional[str] DEFAULT: None

version

TYPE: Optional[str] DEFAULT: None

summary

TYPE: Optional[str] DEFAULT: None

description

TYPE: Optional[str] DEFAULT: None

contact

TYPE: Optional[Contact] DEFAULT: None

terms_of_service

TYPE: Optional[AnyUrl] DEFAULT: None

license

TYPE: Optional[License] DEFAULT: None

security

TYPE: Optional[List[SecurityScheme]] DEFAULT: None

servers

TYPE: Optional[List[Dict[str, Union[str, Any]]]] DEFAULT: None

secret_key

TYPE: Optional[str] DEFAULT: get_random_secret_key()

allowed_hosts

TYPE: Optional[List[str]] DEFAULT: None

allow_origins

TYPE: Optional[List[str]] DEFAULT: None

base_url

TYPE: str DEFAULT: 'http://testserver'

backend

TYPE: Literal['asyncio', 'trio'] DEFAULT: 'asyncio'

backend_options

TYPE: Optional[Dict[str, Any]] DEFAULT: None

interceptors

TYPE: Optional[List[Interceptor]] DEFAULT: None

permissions

TYPE: Optional[List[Permission]] DEFAULT: None

dependencies

TYPE: Optional[Dependencies] DEFAULT: None

middleware

TYPE: Optional[List[Middleware]] DEFAULT: None

csrf_config

TYPE: Optional[CSRFConfig] DEFAULT: None

exception_handlers

TYPE: Optional[ExceptionHandlerMap] DEFAULT: None

openapi_config

TYPE: Optional[OpenAPIConfig] DEFAULT: None

on_shutdown

TYPE: Optional[List[LifeSpanHandler]] DEFAULT: None

on_startup

TYPE: Optional[List[LifeSpanHandler]] DEFAULT: None

cors_config

TYPE: Optional[CORSConfig] DEFAULT: None

session_config

TYPE: Optional[SessionConfig] DEFAULT: None

scheduler_class

TYPE: Optional[SchedulerType] DEFAULT: None

scheduler_tasks

TYPE: Optional[Dict[str, str]] DEFAULT: None

scheduler_configurations

TYPE: Optional[Dict[str, Union[str, Dict[str, str]]]] DEFAULT: None

enable_scheduler

TYPE: bool DEFAULT: None

enable_openapi

TYPE: bool DEFAULT: True

include_in_schema

TYPE: bool DEFAULT: True

openapi_version

TYPE: Optional[str] DEFAULT: '3.1.0'

raise_server_exceptions

TYPE: bool DEFAULT: True

root_path

TYPE: str DEFAULT: ''

static_files_config

TYPE: Optional[StaticFilesConfig] DEFAULT: None

template_config

TYPE: Optional[TemplateConfig] DEFAULT: None

lifespan

TYPE: Optional[Callable[[Esmerald], AsyncContextManager]] DEFAULT: None

cookies

TYPE: Optional[CookieTypes] DEFAULT: None

redirect_slashes

TYPE: Optional[bool] DEFAULT: None

tags

TYPE: Optional[List[str]] DEFAULT: None

webhooks

TYPE: Optional[Sequence[WebhookGateway]] DEFAULT: None

Source code in esmerald/testclient.py
 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
def create_client(
    routes: Union["APIGateHandler", List["APIGateHandler"]],
    *,
    settings_config: Optional["SettingsType"] = None,
    debug: Optional[bool] = None,
    app_name: Optional[str] = None,
    title: Optional[str] = None,
    version: Optional[str] = None,
    summary: Optional[str] = None,
    description: Optional[str] = None,
    contact: Optional[Contact] = None,
    terms_of_service: Optional[AnyUrl] = None,
    license: Optional[License] = None,
    security: Optional[List[SecurityScheme]] = None,
    servers: Optional[List[Dict[str, Union[str, Any]]]] = None,
    secret_key: Optional[str] = get_random_secret_key(),
    allowed_hosts: Optional[List[str]] = None,
    allow_origins: Optional[List[str]] = None,
    base_url: str = "http://testserver",
    backend: "Literal['asyncio', 'trio']" = "asyncio",
    backend_options: Optional[Dict[str, Any]] = None,
    interceptors: Optional[List["Interceptor"]] = None,
    permissions: Optional[List["Permission"]] = None,
    dependencies: Optional["Dependencies"] = None,
    middleware: Optional[List["Middleware"]] = None,
    csrf_config: Optional["CSRFConfig"] = None,
    exception_handlers: Optional["ExceptionHandlerMap"] = None,
    openapi_config: Optional["OpenAPIConfig"] = None,
    on_shutdown: Optional[List["LifeSpanHandler"]] = None,
    on_startup: Optional[List["LifeSpanHandler"]] = None,
    cors_config: Optional["CORSConfig"] = None,
    session_config: Optional["SessionConfig"] = None,
    scheduler_class: Optional["SchedulerType"] = None,
    scheduler_tasks: Optional[Dict[str, str]] = None,
    scheduler_configurations: Optional[Dict[str, Union[str, Dict[str, str]]]] = None,
    enable_scheduler: bool = None,
    enable_openapi: bool = True,
    include_in_schema: bool = True,
    openapi_version: Optional[str] = "3.1.0",
    raise_server_exceptions: bool = True,
    root_path: str = "",
    static_files_config: Optional["StaticFilesConfig"] = None,
    template_config: Optional["TemplateConfig"] = None,
    lifespan: Optional[Callable[["Esmerald"], "AsyncContextManager"]] = None,
    cookies: Optional[CookieTypes] = None,
    redirect_slashes: Optional[bool] = None,
    tags: Optional[List[str]] = None,
    webhooks: Optional[Sequence["WebhookGateway"]] = None,
) -> EsmeraldTestClient:
    return EsmeraldTestClient(
        app=Esmerald(
            settings_config=settings_config,
            debug=debug,
            title=title,
            version=version,
            summary=summary,
            description=description,
            contact=contact,
            terms_of_service=terms_of_service,
            license=license,
            security=security,
            servers=servers,
            routes=cast("Any", routes if isinstance(routes, list) else [routes]),
            app_name=app_name,
            secret_key=secret_key,
            allowed_hosts=allowed_hosts,
            allow_origins=allow_origins,
            interceptors=interceptors,
            permissions=permissions,
            dependencies=dependencies,
            middleware=middleware,
            csrf_config=csrf_config,
            exception_handlers=exception_handlers,
            openapi_config=openapi_config,
            on_shutdown=on_shutdown,
            on_startup=on_startup,
            cors_config=cors_config,
            scheduler_class=scheduler_class,
            scheduler_tasks=scheduler_tasks,
            scheduler_configurations=scheduler_configurations,
            enable_scheduler=enable_scheduler,
            static_files_config=static_files_config,
            template_config=template_config,
            session_config=session_config,
            lifespan=lifespan,
            redirect_slashes=redirect_slashes,
            enable_openapi=enable_openapi,
            openapi_version=openapi_version,
            include_in_schema=include_in_schema,
            tags=tags,
            webhooks=webhooks,
        ),
        base_url=base_url,
        backend=backend,
        backend_options=backend_options,
        root_path=root_path,
        raise_server_exceptions=raise_server_exceptions,
        cookies=cookies,
    )