简体   繁体   English

如何从 .env 文件为 pytests 加载变量

[英]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.

相关问题 如何从 docker compose 文件访问环境变量 - how to access env variables from docker compose file 如何成功从 .env 文件加载 API 密钥 - How to load API keys from .env file successfully 如何从configparser文件加载所有变量? - How to load all variables from a configparser file? 如何在python中为不同环境加载.env文件? - How to load .env file for different environments in python? 如果 Django 项目从 Github 部署到 AWS,如何从“.env”文件访问环境变量? - How are environment variables accessed from ".env" file if Django project deployed to AWS from Github? 在Python,Flask中,如何在服务器启动/重新启动时从.env文件导出并确保变量的可用性? - How to export and ensure availability of variables from .env file on server start/restart in Python, Flask? 无法从 docker 组合环境文件访问环境变量 - unable to access environment variables from docker compose env file 从 Python 中的多个“.env”文件中读取环境变量 - Reading environment variables from more than one ".env" file in Python 从 pythonanywhere.com 中的 .env 文件读取环境变量 - Reading environment variables from .env file in pythonanywhere.com CICD 代码如何在 Github 中选择没有.env 文件的环境变量 - How will the CICD code pick the environment variables without .env file in Github
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM