[英]How to load variables from .env file for pytests
I am writing an API in Flask and in some point I send email to users who register.我正在 Flask 中编写 API,在某些时候我会向注册的用户发送电子邮件。 I store variables concerning this email service in .env file.我将有关此电子邮件服务的变量存储在 .env 文件中。 Now want to test a piece where I use these variables, but I have no idea how to load them from the .env file.现在想测试我使用这些变量的部分,但我不知道如何从 .env 文件加载它们。
I tried basically all the answers here https://rb.gy/0nro1a , monkey patching setenv as show here https://rb.gy/kd07wa + other tips here and there.我在这里尝试了基本上所有的答案https://rb.gy/0nro1a ,猴子修补 setenv 如这里所示https://rb.gy/kd07wa + 其他技巧在这里和那里。 Each failed on some point.每个都在某些方面失败了。 I also tried using pytest-dotenv.我也尝试使用 pytest-dotenv。 pytest-env, pytest.ini etc..but nothing really worked as expected, and it is all pretty confusing to me. pytest-env, pytest.ini 等..但没有真正按预期工作,这让我很困惑。
My pytests fixture looks like this我的 pytests 夹具看起来像这样
@pytest.fixture(autouse=True)
def test_client_db():
# set up
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///"
app.config["JWT_SECRET_KEY"] = "testing"
with app.app_context():
db.init_app(app)
db.create_all()
testing_client = app.test_client()
ctx = app.app_context()
ctx.push()
# do testing
yield testing_client
# tear down
with app.app_context():
db.session.remove()
db.drop_all()
ctx.pop()
I am wondering why I cant just simply load the .env file with a line like this load_dotenv(path/to/.env)
somewhere in the set up of the fixture and be done?我想知道为什么我不能简单地在固定装置的设置中的某处加载像这样的行load_dotenv(path/to/.env)
的 .env 文件并完成?
Can someone explain to me as a newbie how to read the .env variables in a simple straightforward way to work with pytest?作为新手,有人可以向我解释如何以简单直接的方式读取 .env 变量以使用 pytest 吗?
The only way that actually works for me is to pass the environment variables on the command line as I run the tests.真正对我有用的唯一方法是在运行测试时在命令行上传递环境变量。
FROM_EMAIL="some@email.com" MAILGUN_DOMAIN="sandbox6420919ab29b4228sdfda9d43ff37f7689072.mailgun.org" MAILGUN_API_KEY="245d6d0asldlasdkjfc380fba7fbskfsj1ad3125649esadbf2-7cd1ac2b-47fb3ac2" pytest tests
But this is a terrible way and I don't want to write all these var into the command line every time I run tests.但这是一种糟糕的方式,我不想每次运行测试时都将所有这些 var 写入命令行。
I just want to write pytest test
, the .env file should be loaded somewhere automatically I believe.我只想编写pytest test
,我相信 .env 文件应该自动加载到某个地方。 But where and how?但是在哪里以及如何?
Any help appreciated.任何帮助表示赞赏。
If you install python-dotenv , you can use that to load the variables from the .env
file.如果安装python-dotenv ,则可以使用它从.env
文件加载变量。 Here is a minimal example:这是一个最小的例子:
.env .env
SQLALCHEMY_DATABASE_URI="sqlite:///"
JWT_SECRET_KEY="testing"
test.py测试文件
import os
import pytest
from dotenv import load_dotenv
@pytest.fixture(scope='session', autouse=True)
def load_env():
load_dotenv()
@pytest.fixture(autouse=True)
def test_client_db():
print(f"\nSQLALCHEMY_DATABASE_URI"
f"={os.environ.get('SQLALCHEMY_DATABASE_URI')}")
print(f"JWT_SECRET_KEY={os.environ.get('JWT_SECRET_KEY')}")
def test():
pass
python -m pytest -s test.py
gives: python -m pytest -s test.py
给出:
============================================ test session starts ============================================
...
collected 1 item
test.py
SQLALCHEMY_DATABASE_URI=sqlite:///
JWT_SECRET_KEY=testing
.
============================================= 1 passed in 0.27s =============================================
eg the enviroment variables are set throughout the test session and can be used to configure your app.例如,环境变量在整个测试会话中设置,可用于配置您的应用程序。 Note that I didn't provide a path in load_dotenv()
, because I put the .env
file in the same directory as the test - in your code, you probably have to add the path ( load_dotenv(dotenv_path=your_path)
).请注意,我没有在load_dotenv()
提供路径,因为我将.env
文件放在与测试相同的目录中 - 在您的代码中,您可能必须添加路径( load_dotenv(dotenv_path=your_path)
)。
You can use the monkeypatch fixture provided by pytest to manipulate env variables:你可以使用pytest提供的monkeypatch fixture来操作env变量:
@pytest.fixture(scope="function")
def configured_env(monkeypatch):
monkeypatch.setenv("SQLALCHEMY_DATABASE_URI", "sqlite:///")
monkeypatch.setenv("JWT_SECRET_KEY", testing)
def test_client(configured_env):
#env variables are set here
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.