I'm trying to set up pytest so that whenever I run my tests (locally or in github actions), the environment variables all point to files and locations in my test directory instead of wherever they're set to based on the user.
The problem is, the fixture changes are visible if I add an ipdb
trace in the test_database
function and print os.getenv('DB_URL')
but the assert will always fail because the DataBase
object always has the original non-mocked url (set in .bash_profile
).
database.py
import h5py
import os
class DataBase:
route = os.environ.get('DB_URL')
def __init__(self):
self.connected = False
def connect(self):
if not connected:
self.db = h5py.File(self.route, 'r')
self.connected = True
conftest.py
import os
import pytest
@pytest.fixture(autouse=True)
def mock_test_env(monkeypatch):
cwd = os.getcwd()
monkeypatch.setenv('DB_URL', cwd + '/sample_db.hdf5')
test_database.py
import pytest
from repo import DataBase
def test_database():
db = DataBase()
import ipdb; ipdb.set_trace()
'''
os.getenv('DB_URL') returns cwd + '/sample_db.hdf5'
db.route returns original database, not the sample one above
'''
assert db.connected = False, 'DataBase must be instantiated to connected == False'
How do I globally set environment variables so all objects see the same envs?