为什么我的环境变量没有在 FastAPI 测试中清除?



我对FastApi和Python中的单元测试相对陌生。

我正在测试一个api,该api对是否存在环境变量FOO进行条件检查。

我正在尝试清除该环境变量,以便在测试调用api时找不到环境变量:

def test_invoice(self, requests_mock):
with mock.patch.dict(os.environ, {}, clear=True):          

url = "/api/invoices/check"
requests_mock.post(url, real_http=True)
response = self.test_client.post(url, json.dumps([invoice_id]))
@router.post("/api/invoices/check")
def invoices_api():
if os.environ.get("FOO"):

当调用测试客户端并检查env var时,env变量是否不是None

我如何使我试图测试的代码使用模拟的操作系统环境?

注意:我还尝试使用以下语法清除env变量:

@mock.patch.dict(os.environ, {}, clear=True)
def test_invoice(self, requests_mock):

这是一个如何实现的工作示例。

# app.py
import os
from fastapi import FastAPI
app = FastAPI()

@app.get("/")
def invoices_api():
if os.environ.get("FOO"):
return 1
# test_me.py
import os
from unittest.mock import patch
from fastapi.testclient import TestClient
from app import app
client = TestClient(app)
class TestMe:
def setup_method(self):
os.environ["FOO"] = "A"
def test_1(self):
resp = client.get("/")
assert resp.json() == 1
def test_2(self):
with patch.dict(os.environ, clear=True):
resp = client.get("/")
assert resp.json() is None
def test_3(self):
resp = client.get("/")
assert resp.json() == 1

最新更新