fastapi:测试:得到当前已登录用户信息
一,代码:
因为接口是从header中获取用户token,
所以测试时就是在 AsyncClient 发送请求时,通过 headers 参数直接传入 mock 的 Token;
@pytest.mark.asyncio
async def test_get_user_info_success(async_client: AsyncClient):
# 模拟有效的 Token
headers = {"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhZG1pbiIsImV4cCI6MTc4NTIyMDc0OX0.umLyZ5C03D0aZf3m1ydqTSsQZQKc-wHGUkyGVDC2QkA"}
# 在发送请求时传入 headers
response = await async_client.get("/api/account/info", headers=headers)
print("response:", response)
assert response.status_code == 200
assert response.json()["username"] == 'admin'
二,测试效果:
(venv) liuhongdi@liuhongdi-pc:/data/python/fastapi/demo1$ pytest -s
app_name='My FastAPI App' logs_dir='/data/fastapi/test123/logs' items_per_page=20 UPLOAD_DIR='/data/file/fast/images' ENV='testing' ALLOWED_IMAGE_EXTENSIONS={'jpg', 'gif', 'jpeg', 'png'}
ENV: testing
IS_DEV: True
=========================================================================== test session starts ===========================================================================
platform linux -- Python 3.10.19, pytest-9.1.1, pluggy-1.6.0
rootdir: /data/python/fastapi/demo1
configfile: pytest.ini (WARNING: ignoring pytest config in pyproject.toml!)
plugins: anyio-4.13.0, asyncio-1.4.0
asyncio: mode=auto, debug=False, asyncio_default_fixture_loop_scope=session, asyncio_default_test_loop_scope=function
collected 2 items
tests/api/test_users.py token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhZG1pbiIsImV4cCI6MTc4NTIyMDc0OX0.umLyZ5C03D0aZf3m1ydqTSsQZQKc-wHGUkyGVDC2QkA
payload: {'sub': 'admin', 'exp': 1785220749}
in plugin username: admin
保存request
username: admin
2026-07-28 14:37:13.843 | INFO | app.api.middleware.log_request_response_middleware:dispatch:108 - API Log: {"method": "GET", "path": "/api/account/info", "query_params": {}, "request_body": null, "status_code": 200, "response_body": {"username": "admin", "message": "如果你能看到我,说明认证成功了!"}, "process_time": 0.011687517166137695}
response: <Response [200 OK]>
.保存request
username: admin
password: 123456
user: {'username': 'admin', 'hashed_password': '$2b$12$vuryEKmyQS1V7ahHk5dTf.AD91zDS0ieNJLUhNfPMhE9tEmRAceWG'}
is_verify: True
2026-07-28 14:37:14.127 | INFO | app.api.middleware.log_request_response_middleware:dispatch:108 - API Log: {"method": "POST", "path": "/api/account/login", "query_params": {}, "request_body": "username=admin&password=123456", "status_code": 200, "response_body": {"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhZG1pbiIsImV4cCI6MTc4NTIyMjQzNH0.zCJ1agbGtO6aw-p0YjtGSfjPfvQmYI03vDbGBrKPlSo", "token_type": "bearer"}, "process_time": 0.27683496475219727}
response: <Response [200 OK]>
status_code: 200
.
说明:
-s参数:(或 --capture=no)命令行参数,用来关闭输出拦截。
在 pytest 中测试 FastAPI 异步接口时,你可能会发现代码里的 print() 没有任何输出。
这并不是 print() 在异步环境下失效了,而是 pytest 默认的标准行为:
它会拦截并隐藏所有标准的输出(stdout/stderr),只有当测试用例“失败(Failed)”时,才会把对应的打印内容显示出来。
如果你希望在测试成功时也能看到 print() 打印的接口返回结果,有以下几种最常用的解决方法:
解决方法:运行测试时加上 -s 参数
pytest 提供了一个 -s(或 --capture=no)命令行参数,用来关闭输出拦截。
浙公网安备 33010602011771号