如何在Jupyter Notebook中向pytest测试类传参并执行测试?
可行方案
方案1:微调测试文件适配pytest(最小改动原文件)
pytest默认不支持带参数的测试类构造函数,我们可以把原测试类的依赖改为pytest fixture注入,核心测试逻辑完全保留:
- 修改
test_threshold.py,将构造函数参数替换为fixture:
import pandas as pd class TestSomething: # 改为无参构造,依赖fixture传递df和threshold def test_metrics(self, df, threshold): # 原测试逻辑示例 assert df['value'].mean() > threshold
- 在Jupyter Notebook中定义临时fixture并调用pytest:
import pytest import pandas as pd from pathlib import Path # 你的目标DataFrame和阈值 df = pd.DataFrame({'value': [0.6, 0.7, 0.8]}) threshold = 0.5 # 生成临时conftest.py文件,注入所需fixture conftest_content = f""" import pandas as pd import pytest @pytest.fixture(scope="module") def df(): return pd.DataFrame({df.to_dict()}) @pytest.fixture(scope="module") def threshold(): return {threshold} """ with open("conftest.py", "w") as f: f.write(conftest_content) # 调用pytest执行测试 !pytest test_threshold.py -v # 执行完成后清理临时文件 Path("conftest.py").unlink()
方案2:不修改原测试文件,动态生成测试用例
如果完全不想改动test_threshold.py,可以在Notebook中实例化测试对象后,把测试方法转为pytest可识别的函数再执行:
import pytest from test_threshold import TestSomething import pandas as pd # 你的DataFrame和阈值 df = pd.DataFrame({'value': [0.6, 0.7, 0.8]}) threshold = 0.5 # 实例化测试类 test_obj = TestSomething(df, threshold) # 动态生成测试函数,绑定到当前命名空间 def test_metrics(): test_obj.test_metrics() # 如有多个测试方法,按同样方式生成 # def test_another_case(): # test_obj.test_another_case() # 调用pytest执行当前Notebook中的测试函数 pytest.main([__file__, "-v"])
方案3:直接调用测试方法(快速验证)
如果只是想验证测试逻辑,不需要pytest的报告、批量执行等功能,可以直接调用实例的测试方法:
from test_threshold import TestSomething import pandas as pd df = pd.DataFrame({'value': [0.6, 0.7, 0.8]}) threshold = 0.5 test_obj = TestSomething(df, threshold) # 直接执行测试方法并捕获结果 try: test_obj.test_metrics() print("test_metrics 执行通过") except AssertionError as e: print(f"test_metrics 失败: {e}")
内容的提问来源于stack exchange,提问作者ARTHUR MENDONCA LINS CALDAS
相关产品推荐
相关产品推荐

