gpt4 book ai didi

python - 导入的类看不到 Pytest 环境装置

转载 作者:行者123 更新时间:2023-12-04 04:02:29 25 4
gpt4 key购买 nike

我正在尝试设置 pytest,以便每当我运行我的测试(本地或在 github 操作中)时,环境变量都指向我测试目录中的文件和位置,而不是根据用户设置的任何位置。
问题是,如果我添加 ipdb, fixture 更改是可见的。在 test_database 中跟踪功能和打印os.getenv('DB_URL')但是断言总是会失败,因为 DataBase对象始终具有原始的非模拟 url(在 .bash_profile 中设置)。
数据库.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')
测试数据库.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'
如何全局设置环境变量以便所有对象看到相同的环境?

最佳答案

正如其他人在您的评论中提到的那样,在此分配中要避免类变量,因为它是一个常量,在扫描导入语句的那一刻就被分配了。
为了更好地理解这种情况,请尝试放置 from repo import DataBase在你的方法里面def test_database():像这样:

import os
import pytest

@pytest.fixture(autouse=True)
def mock_test_env(monkeypatch):
cwd = os.getcwd()
monkeypatch.setenv('DB_URL', cwd + '/sample_db.hdf5')

def test_database(mock_test_env):
from repo import DataBase # <<< This here works
db = DataBase()
assert db.route == (os.getcwd() + '/sample_db.hdf5') # Works!
现在,当您放置 from repo import Database 时在文件的开头,pytest 将扫描并开始读取所有导入并开始初始化蓝图并在导入时设置路由器的值。
阅读: When is the class variable initialised in Python?
因此,理想的方法是避免在 Database 的构造函数中进行如此重要的初始化和赋值。类(class)。从而确保它在需要时进行计算。
我觉得,我喜欢把它想成 Explicit is better than implicit.来自 Zen Of Python并这样做:
import h5py
import os

class DataBase:

def __init__(self):
self.route = os.environ.get('DB_URL')
self.connected = False

def connect(self):
if not connected:
self.db = h5py.File(self.route, 'r')
self.connected = True

关于python - 导入的类看不到 Pytest 环境装置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62867574/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com