From f693e682dce5b959850aeafcc40700a789450d99 Mon Sep 17 00:00:00 2001 From: Amin Alaee Date: Wed, 15 Jun 2022 15:47:55 +0200 Subject: [PATCH] Add more TestClient examples (#1685) --- docs/testclient.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/docs/testclient.md b/docs/testclient.md index a214715fe..f42093030 100644 --- a/docs/testclient.md +++ b/docs/testclient.md @@ -26,6 +26,37 @@ function calls, not awaitables. You can use any of `requests` standard API, such as authentication, session cookies handling, or file uploads. +For example, to set headers on the TestClient you can do: + +```python +client = TestClient(app) + +# Set headers on the client for future requests +client.headers = {"Authorization": "..."} +response = client.get("/") + +# Set headers for each request separately +response = client.get("/", headers={"Authorization": "..."}) +``` + +And for example to send files with the TestClient: + +```python +client = TestClient(app) + +# Send a single file +with open("example.txt", "rb") as f: + response = client.post("/form", files={"file": f}) + +# Send multiple files +with open("example.txt", "rb") as f1: + with open("example.png", "rb") as f2: + files = {"file1": f1, "file2": ("filename", f2, "image/png")} + response = client.post("/form", files=files) +``` + +For more information you can check the `requests` [documentation](https://requests.readthedocs.io/en/master/user/advanced/). + By default the `TestClient` will raise any exceptions that occur in the application. Occasionally you might want to test the content of 500 error responses, rather than allowing client to raise the server exception. In this