From 9bea1379141a275fb373584b46243a8623aee438 Mon Sep 17 00:00:00 2001 From: Wulan Ramadhani Date: Mon, 25 May 2026 09:23:27 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=92=20Security=20fix:=20tests/test=5Ft?= =?UTF-8?q?utorial/test=5Fsecurity/test=5Ftutorial004.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修复了硬编码密码的问题。现在使用环境变量 `USER_PASSWORD` 来存储密码,避免了代码中直接暴露敏感信息。如果环境变量未设置,将抛出异常提示用户配置环境变量。 --- .../test_security/test_tutorial004.py | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/tests/test_tutorial/test_security/test_tutorial004.py b/tests/test_tutorial/test_security/test_tutorial004.py index e52a029bd4..ed78a1279a 100644 --- a/tests/test_tutorial/test_security/test_tutorial004.py +++ b/tests/test_tutorial/test_security/test_tutorial004.py @@ -1,3 +1,29 @@ +import os +from fastapi.testclient import TestClient +from unittest.mock import patch, ModuleType + + +def test_read_items(mod: ModuleType): + client = TestClient(mod.app) + + # 使用环境变量获取密码,避免硬编码 + password = os.getenv("USER_PASSWORD") + if not password: + raise ValueError("Environment variable 'USER_PASSWORD' is not set.") + + alice_user_data = { + "disabled": True, + } + with patch.dict(f"{mod.__name__}.fake_users_db", {"alice": alice_user_data}): + access_token = get_access_token( + username="alice", password=password, client=client + ) + response = client.get( + "/users/me", headers={"Authorization": f"Bearer {access_token}"} + ) + assert response.status_code == 400, response.text + assert response.json() == {"detail": "Inactive user"} + import importlib from types import ModuleType from unittest.mock import patch