简体   繁体   中英

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. I store variables concerning this email service in .env file. Now want to test a piece where I use these variables, but I have no idea how to load them from the .env file.

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. Each failed on some point. I also tried using pytest-dotenv. pytest-env, pytest.ini etc..but nothing really worked as expected, and it is all pretty confusing to me.

My pytests fixture looks like this

@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?

Can someone explain to me as a newbie how to read the .env variables in a simple straightforward way to work with 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.

I just want to write pytest test , the .env file should be loaded somewhere automatically I believe. But where and how?

Any help appreciated.

If you install python-dotenv , you can use that to load the variables from the .env file. Here is a minimal example:

.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:

============================================ 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) ).

You can use the monkeypatch fixture provided by pytest to manipulate env variables:

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM