跳至內容

測試用戶端 - TestClient

您可以使用 TestClient 類別來測試 FastAPI 應用程式,而無需建立實際的 HTTP 和通訊端連線,只需直接與 FastAPI 程式碼通訊。

FastAPI 測試文件 中了解更多相關資訊。

您可以直接從 fastapi.testclient 匯入它

from fastapi.testclient import TestClient

fastapi.testclient.TestClient

TestClient(
    app,
    base_url="http://testserver",
    raise_server_exceptions=True,
    root_path="",
    backend="asyncio",
    backend_options=None,
    cookies=None,
    headers=None,
    follow_redirects=True,
)

基底: Client

參數 說明
app(應用程式)

類型: ASGIApp

base_url(基礎網址)

類型: str 預設值: 'http://testserver'

raise_server_exceptions(引發伺服器例外)

類型: bool 預設值: True

root_path(根路徑)

類型: str 預設值: ''

backend(後端)

類型: Literal['asyncio', 'trio'] 預設值: 'asyncio'

backend_options(後端選項)

類型: dict[str, Any] | None 預設值: None

cookies(Cookie)

類型: CookieTypes | None 預設值: None

headers(標頭)

類型: dict[str, str] | None 預設值: None

follow_redirects(跟隨重新導向)

類型: bool 預設值: True

原始碼位於 starlette/testclient.py
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
def __init__(
    self,
    app: ASGIApp,
    base_url: str = "http://testserver",
    raise_server_exceptions: bool = True,
    root_path: str = "",
    backend: typing.Literal["asyncio", "trio"] = "asyncio",
    backend_options: dict[str, typing.Any] | None = None,
    cookies: httpx._types.CookieTypes | None = None,
    headers: dict[str, str] | None = None,
    follow_redirects: bool = True,
) -> None:
    self.async_backend = _AsyncBackend(backend=backend, backend_options=backend_options or {})
    if _is_asgi3(app):
        asgi_app = app
    else:
        app = typing.cast(ASGI2App, app)  # type: ignore[assignment]
        asgi_app = _WrapASGI2(app)  # type: ignore[arg-type]
    self.app = asgi_app
    self.app_state: dict[str, typing.Any] = {}
    transport = _TestClientTransport(
        self.app,
        portal_factory=self._portal_factory,
        raise_server_exceptions=raise_server_exceptions,
        root_path=root_path,
        app_state=self.app_state,
    )
    if headers is None:
        headers = {}
    headers.setdefault("user-agent", "testclient")
    super().__init__(
        base_url=base_url,
        headers=headers,
        transport=transport,
        follow_redirects=follow_redirects,
        cookies=cookies,
    )

headers property(屬性) writable(可寫入)

headers

發送請求時要包含的 HTTP 標頭。

follow_redirects instance-attribute(實例屬性)

follow_redirects = follow_redirects

max_redirects instance-attribute(實例屬性)

max_redirects = max_redirects

is_closed property(屬性)

is_closed

檢查客戶端是否已關閉

trust_env property(屬性)

trust_env

timeout property(屬性) writable(可寫入)

timeout

event_hooks property(屬性) writable(可寫入)

event_hooks

auth property(屬性) writable(可寫入)

auth

在請求層級未傳遞任何驗證類別時使用的驗證類別。

另請參閱 驗證

base_url property(屬性) writable(可寫入)

base_url

使用相對 URL 發送請求時要使用的基本 URL。

cookies property(屬性) writable(可寫入)

cookies

發送請求時要包含的 Cookie 值。

params property(屬性) writable(可寫入)

params

發送請求時要包含在 URL 中的查詢參數。

task instance-attribute(實例屬性)

task

portal 類別屬性 實例屬性

portal = None

async_backend 實例屬性

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

app 實例屬性

app = asgi_app

app_state 實例屬性

app_state = {}

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
)

建立並回傳一個請求實例。

  • paramsheaderscookies 參數會與用戶端上設定的任何值合併。
  • url 參數會與用戶端上設定的任何 base_url 合併。

另請參閱:請求實例

參數 說明
method (方法)

類型: str

url (網址)

類型: URLTypes

content (內容)

類型: Optional[RequestContent] 預設值: None

data (數據)

類型: Optional[RequestData] 預設值: None

files (檔案)

類型: Optional[RequestFiles] 預設值: None

json

類型: Optional[Any] 預設值: None

params (參數)

類型: Optional[QueryParamTypes] 預設值: None

headers(標頭)

headers (標頭)

cookies(Cookie)

類型: Optional[HeaderTypes] 預設值: None

cookies (Cookie)

類型: Optional[CookieTypes] 預設值: None

timeout (逾時)

類型: Union[TimeoutTypes, UseClientDefault] 預設值: USE_CLIENT_DEFAULT

extensions (擴充)
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,
    )

類型: Optional[RequestExtensions] 預設值: None

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
)

原始碼位於 httpx/_client.py

stream

httpx.request() 的替代方案,以串流方式傳輸回應主體,而不是一次將其載入記憶體。

參數 說明
method (方法)

類型: str

url (網址)

類型: URLTypes

content (內容)

類型: Optional[RequestContent] 預設值: None

data (數據)

類型: Optional[RequestData] 預設值: None

files (檔案)

類型: Optional[RequestFiles] 預設值: None

json

類型: Optional[Any] 預設值: None

params (參數)

類型: Optional[QueryParamTypes] 預設值: None

headers(標頭)

headers (標頭)

cookies(Cookie)

類型: Optional[HeaderTypes] 預設值: None

參數:參見 httpx.request

類型: Union[AuthTypes, UseClientDefault, None] 預設值: USE_CLIENT_DEFAULT

follow_redirects(跟隨重新導向)

類型: Union[bool, UseClientDefault] 預設值: USE_CLIENT_DEFAULT

cookies (Cookie)

類型: Optional[CookieTypes] 預設值: None

timeout (逾時)

類型: Union[TimeoutTypes, UseClientDefault] 預設值: USE_CLIENT_DEFAULT

產出 說明
回應
extensions (擴充)
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
)

發送請求。

請求會按原樣發送,不做修改。

通常您會希望使用 Client.build_request() 建立一個請求,以便將任何用戶端級別的配置合併到請求中,但也支援傳遞明確的 httpx.Request() 物件。

另請參閱:請求實例

參數 說明
請求

類型: Request

串流

類型: bool 預設值: False

參數:參見 httpx.request

類型: Union[AuthTypes, UseClientDefault, None] 預設值: USE_CLIENT_DEFAULT

follow_redirects(跟隨重新導向)

類型: Union[bool, UseClientDefault] 預設值: USE_CLIENT_DEFAULT

extensions (擴充)
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

close

close()

關閉傳輸和代理。

extensions (擴充)
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()

request

request(
    method,
    url,
    *,
    content=None,
    data=None,
    files=None,
    json=None,
    params=None,
    headers=None,
    cookies=None,
    auth=USE_CLIENT_DEFAULT,
    follow_redirects=None,
    allow_redirects=None,
    timeout=USE_CLIENT_DEFAULT,
    extensions=None
)
參數 說明
method (方法)

類型: str

url (網址)

類型: URLTypes

content (內容)

類型: RequestContent | None 預設值: None

data (數據)

類型: _RequestData | None 預設值: None

files (檔案)

類型: RequestFiles | None 預設值: None

json

類型: Any 預設值: None

params (參數)

類型: QueryParamTypes | None 預設值: None

headers(標頭)

類型: HeaderTypes | None 預設值: None

cookies(Cookie)

類型: CookieTypes | None 預設值: None

參數:參見 httpx.request

類型: AuthTypes | UseClientDefault 預設值: USE_CLIENT_DEFAULT

follow_redirects(跟隨重新導向)

類型: bool | None 預設值: None

允許重新導向

類型: bool | None 預設值: None

cookies (Cookie)

類型: TimeoutTypes | UseClientDefault 預設值: USE_CLIENT_DEFAULT

timeout (逾時)

類型: dict[str, Any] | None 預設值: None

原始碼位於 starlette/testclient.py
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
def request(  # type: ignore[override]
    self,
    method: str,
    url: httpx._types.URLTypes,
    *,
    content: httpx._types.RequestContent | None = None,
    data: _RequestData | None = None,
    files: httpx._types.RequestFiles | None = None,
    json: typing.Any = None,
    params: httpx._types.QueryParamTypes | None = None,
    headers: httpx._types.HeaderTypes | None = None,
    cookies: httpx._types.CookieTypes | None = None,
    auth: httpx._types.AuthTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT,
    follow_redirects: bool | None = None,
    allow_redirects: bool | None = None,
    timeout: httpx._types.TimeoutTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT,
    extensions: dict[str, typing.Any] | None = None,
) -> httpx.Response:
    url = self._merge_url(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,
    )

get

get(
    url,
    *,
    params=None,
    headers=None,
    cookies=None,
    auth=USE_CLIENT_DEFAULT,
    follow_redirects=None,
    allow_redirects=None,
    timeout=USE_CLIENT_DEFAULT,
    extensions=None
)
參數 說明
url (網址)

類型: URLTypes

params (參數)

類型: QueryParamTypes | None 預設值: None

headers(標頭)

類型: HeaderTypes | None 預設值: None

cookies(Cookie)

類型: CookieTypes | None 預設值: None

參數:參見 httpx.request

類型: AuthTypes | UseClientDefault 預設值: USE_CLIENT_DEFAULT

follow_redirects(跟隨重新導向)

類型: bool | None 預設值: None

允許重新導向

類型: bool | None 預設值: None

cookies (Cookie)

類型: TimeoutTypes | UseClientDefault 預設值: USE_CLIENT_DEFAULT

timeout (逾時)

類型: dict[str, Any] | None 預設值: None

原始碼位於 starlette/testclient.py
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
def get(  # type: ignore[override]
    self,
    url: httpx._types.URLTypes,
    *,
    params: httpx._types.QueryParamTypes | None = None,
    headers: httpx._types.HeaderTypes | None = None,
    cookies: httpx._types.CookieTypes | None = None,
    auth: httpx._types.AuthTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT,
    follow_redirects: bool | None = None,
    allow_redirects: bool | None = None,
    timeout: httpx._types.TimeoutTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT,
    extensions: dict[str, typing.Any] | None = 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=USE_CLIENT_DEFAULT,
    follow_redirects=None,
    allow_redirects=None,
    timeout=USE_CLIENT_DEFAULT,
    extensions=None
)
參數 說明
url (網址)

類型: URLTypes

params (參數)

類型: QueryParamTypes | None 預設值: None

headers(標頭)

類型: HeaderTypes | None 預設值: None

cookies(Cookie)

類型: CookieTypes | None 預設值: None

參數:參見 httpx.request

類型: AuthTypes | UseClientDefault 預設值: USE_CLIENT_DEFAULT

follow_redirects(跟隨重新導向)

類型: bool | None 預設值: None

允許重新導向

類型: bool | None 預設值: None

cookies (Cookie)

類型: TimeoutTypes | UseClientDefault 預設值: USE_CLIENT_DEFAULT

timeout (逾時)

類型: dict[str, Any] | None 預設值: None

原始碼位於 starlette/testclient.py
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
def options(  # type: ignore[override]
    self,
    url: httpx._types.URLTypes,
    *,
    params: httpx._types.QueryParamTypes | None = None,
    headers: httpx._types.HeaderTypes | None = None,
    cookies: httpx._types.CookieTypes | None = None,
    auth: httpx._types.AuthTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT,
    follow_redirects: bool | None = None,
    allow_redirects: bool | None = None,
    timeout: httpx._types.TimeoutTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT,
    extensions: dict[str, typing.Any] | None = 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=USE_CLIENT_DEFAULT,
    follow_redirects=None,
    allow_redirects=None,
    timeout=USE_CLIENT_DEFAULT,
    extensions=None
)
參數 說明
url (網址)

類型: URLTypes

params (參數)

類型: QueryParamTypes | None 預設值: None

headers(標頭)

類型: HeaderTypes | None 預設值: None

cookies(Cookie)

類型: CookieTypes | None 預設值: None

參數:參見 httpx.request

類型: AuthTypes | UseClientDefault 預設值: USE_CLIENT_DEFAULT

follow_redirects(跟隨重新導向)

類型: bool | None 預設值: None

允許重新導向

類型: bool | None 預設值: None

cookies (Cookie)

類型: TimeoutTypes | UseClientDefault 預設值: USE_CLIENT_DEFAULT

timeout (逾時)

類型: dict[str, Any] | None 預設值: None

原始碼位於 starlette/testclient.py
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
def head(  # type: ignore[override]
    self,
    url: httpx._types.URLTypes,
    *,
    params: httpx._types.QueryParamTypes | None = None,
    headers: httpx._types.HeaderTypes | None = None,
    cookies: httpx._types.CookieTypes | None = None,
    auth: httpx._types.AuthTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT,
    follow_redirects: bool | None = None,
    allow_redirects: bool | None = None,
    timeout: httpx._types.TimeoutTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT,
    extensions: dict[str, typing.Any] | None = 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=USE_CLIENT_DEFAULT,
    follow_redirects=None,
    allow_redirects=None,
    timeout=USE_CLIENT_DEFAULT,
    extensions=None
)
參數 說明
url (網址)

類型: URLTypes

content (內容)

類型: RequestContent | None 預設值: None

data (數據)

類型: _RequestData | None 預設值: None

files (檔案)

類型: RequestFiles | None 預設值: None

json

類型: Any 預設值: None

params (參數)

類型: QueryParamTypes | None 預設值: None

headers(標頭)

類型: HeaderTypes | None 預設值: None

cookies(Cookie)

類型: CookieTypes | None 預設值: None

參數:參見 httpx.request

類型: AuthTypes | UseClientDefault 預設值: USE_CLIENT_DEFAULT

follow_redirects(跟隨重新導向)

類型: bool | None 預設值: None

允許重新導向

類型: bool | None 預設值: None

cookies (Cookie)

類型: TimeoutTypes | UseClientDefault 預設值: USE_CLIENT_DEFAULT

timeout (逾時)

類型: dict[str, Any] | None 預設值: None

原始碼位於 starlette/testclient.py
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
def post(  # type: ignore[override]
    self,
    url: httpx._types.URLTypes,
    *,
    content: httpx._types.RequestContent | None = None,
    data: _RequestData | None = None,
    files: httpx._types.RequestFiles | None = None,
    json: typing.Any = None,
    params: httpx._types.QueryParamTypes | None = None,
    headers: httpx._types.HeaderTypes | None = None,
    cookies: httpx._types.CookieTypes | None = None,
    auth: httpx._types.AuthTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT,
    follow_redirects: bool | None = None,
    allow_redirects: bool | None = None,
    timeout: httpx._types.TimeoutTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT,
    extensions: dict[str, typing.Any] | None = 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=USE_CLIENT_DEFAULT,
    follow_redirects=None,
    allow_redirects=None,
    timeout=USE_CLIENT_DEFAULT,
    extensions=None
)
參數 說明
url (網址)

類型: URLTypes

content (內容)

類型: RequestContent | None 預設值: None

data (數據)

類型: _RequestData | None 預設值: None

files (檔案)

類型: RequestFiles | None 預設值: None

json

類型: Any 預設值: None

params (參數)

類型: QueryParamTypes | None 預設值: None

headers(標頭)

類型: HeaderTypes | None 預設值: None

cookies(Cookie)

類型: CookieTypes | None 預設值: None

參數:參見 httpx.request

類型: AuthTypes | UseClientDefault 預設值: USE_CLIENT_DEFAULT

follow_redirects(跟隨重新導向)

類型: bool | None 預設值: None

允許重新導向

類型: bool | None 預設值: None

cookies (Cookie)

類型: TimeoutTypes | UseClientDefault 預設值: USE_CLIENT_DEFAULT

timeout (逾時)

類型: dict[str, Any] | None 預設值: None

原始碼位於 starlette/testclient.py
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: httpx._types.RequestContent | None = None,
    data: _RequestData | None = None,
    files: httpx._types.RequestFiles | None = None,
    json: typing.Any = None,
    params: httpx._types.QueryParamTypes | None = None,
    headers: httpx._types.HeaderTypes | None = None,
    cookies: httpx._types.CookieTypes | None = None,
    auth: httpx._types.AuthTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT,
    follow_redirects: bool | None = None,
    allow_redirects: bool | None = None,
    timeout: httpx._types.TimeoutTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT,
    extensions: dict[str, typing.Any] | None = 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=USE_CLIENT_DEFAULT,
    follow_redirects=None,
    allow_redirects=None,
    timeout=USE_CLIENT_DEFAULT,
    extensions=None
)
參數 說明
url (網址)

類型: URLTypes

content (內容)

類型: RequestContent | None 預設值: None

data (數據)

類型: _RequestData | None 預設值: None

files (檔案)

類型: RequestFiles | None 預設值: None

json

類型: Any 預設值: None

params (參數)

類型: QueryParamTypes | None 預設值: None

headers(標頭)

類型: HeaderTypes | None 預設值: None

cookies(Cookie)

類型: CookieTypes | None 預設值: None

參數:參見 httpx.request

類型: AuthTypes | UseClientDefault 預設值: USE_CLIENT_DEFAULT

follow_redirects(跟隨重新導向)

類型: bool | None 預設值: None

允許重新導向

類型: bool | None 預設值: None

cookies (Cookie)

類型: TimeoutTypes | UseClientDefault 預設值: USE_CLIENT_DEFAULT

timeout (逾時)

類型: dict[str, Any] | None 預設值: None

原始碼位於 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
def patch(  # type: ignore[override]
    self,
    url: httpx._types.URLTypes,
    *,
    content: httpx._types.RequestContent | None = None,
    data: _RequestData | None = None,
    files: httpx._types.RequestFiles | None = None,
    json: typing.Any = None,
    params: httpx._types.QueryParamTypes | None = None,
    headers: httpx._types.HeaderTypes | None = None,
    cookies: httpx._types.CookieTypes | None = None,
    auth: httpx._types.AuthTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT,
    follow_redirects: bool | None = None,
    allow_redirects: bool | None = None,
    timeout: httpx._types.TimeoutTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT,
    extensions: dict[str, typing.Any] | None = 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(
    url,
    *,
    params=None,
    headers=None,
    cookies=None,
    auth=USE_CLIENT_DEFAULT,
    follow_redirects=None,
    allow_redirects=None,
    timeout=USE_CLIENT_DEFAULT,
    extensions=None
)
參數 說明
url (網址)

類型: URLTypes

params (參數)

類型: QueryParamTypes | None 預設值: None

headers(標頭)

類型: HeaderTypes | None 預設值: None

cookies(Cookie)

類型: CookieTypes | None 預設值: None

參數:參見 httpx.request

類型: AuthTypes | UseClientDefault 預設值: USE_CLIENT_DEFAULT

follow_redirects(跟隨重新導向)

類型: bool | None 預設值: None

允許重新導向

類型: bool | None 預設值: None

cookies (Cookie)

類型: TimeoutTypes | UseClientDefault 預設值: USE_CLIENT_DEFAULT

timeout (逾時)

類型: dict[str, Any] | None 預設值: None

原始碼位於 starlette/testclient.py
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
def delete(  # type: ignore[override]
    self,
    url: httpx._types.URLTypes,
    *,
    params: httpx._types.QueryParamTypes | None = None,
    headers: httpx._types.HeaderTypes | None = None,
    cookies: httpx._types.CookieTypes | None = None,
    auth: httpx._types.AuthTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT,
    follow_redirects: bool | None = None,
    allow_redirects: bool | None = None,
    timeout: httpx._types.TimeoutTypes | httpx._client.UseClientDefault = httpx._client.USE_CLIENT_DEFAULT,
    extensions: dict[str, typing.Any] | None = 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,
    )

websocket_connect

websocket_connect(url, subprotocols=None, **kwargs)
參數 說明
url (網址)

類型: str

子協定

類型: Sequence[str] | None 預設值: None

**kwargs

類型: Any 預設值: {}

原始碼位於 starlette/testclient.py
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
def websocket_connect(
    self,
    url: str,
    subprotocols: typing.Sequence[str] | None = 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()
原始碼位於 starlette/testclient.py
756
757
758
759
760
761
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()
原始碼位於 starlette/testclient.py
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
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()
原始碼位於 starlette/testclient.py
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
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()