【问题标题】:Is it possible to use parameterize imports with pytest?是否可以将参数化导入与 pytest 一起使用?
【发布时间】:2022-01-05 06:48:16
【问题描述】:

我正在使用 pytest 来测试我正在进行的项目。我有一个像

这样的项目结构
|my_project
||__init__.py
||my_code.py
||test.py

test.py 看起来像

# contents of test.py
import .my_code

def test_function():
  ...
...

要运行测试,我可以从这个目录运行python -m pytest。到目前为止一切顺利。

但是要远程运行代码,我必须使用 Pants 构建一个虚拟环境,以便导入语句实际上看起来像:

import long.path.to.my_project.my_code as my_code

我想确保代码在这个虚拟环境中仍然有效,所以现在我有一个名为 test_venv.py 的不同文件,其中包含相同的测试,唯一的区别是导入。

# contents of test_venv.py
import long.path.to.my_project.my_code as my_code

def test_function():
   ...
...

这确实有效,但是拥有两个几乎相同的测试文件非常烦人。有没有办法让 import 语句参数化,这样我就可以在运行测试时告诉 pytest 我想从哪里导入?

【问题讨论】:

标签: python pytest virtualenv python-module


【解决方案1】:

在尝试了@morhc 使用this 的建议后,我想出了一个办法。它涉及使用参数化夹具和importlib。我如下设置夹具。

@pytest.fixture(scope='module', params=['local', 'installed'])
def my_code_module(request):
    if request.param == 'local':
        return importlib.import_module("my_code")
    if request.param == 'installed':
        return importlib.import_module("long.path.to.my_project.my_code")

然后编写测试以请求夹具,如下所示。

def test_code(my_code_module):
    assert my_code_module.whatever() == ...

【讨论】:

    【解决方案2】:

    您可以合并导入。一种方式,捕获异常,另一种方式。

    try:
        import .my_code
    except ImportError:
        import long.path.to.my_project.my_code as my_code
    
    def test_function():
       ...
    ...
    

    我不确定,可能应该是这样

    try:
        import long.path.to.my_project.my_code as my_code
    except ImportError:
        import .my_code
    

    【讨论】:

    • 是的,我正在这样做!但我真的想在两组进口下测试它。所以我想要 pytest 执行 import .my_code 然后重新启动,然后运行 ​​import long.path.to.my_project.mycode as my_code 并运行相同的测试集
    猜你喜欢
    • 2023-03-02
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 2023-03-10
    相关资源
    最近更新 更多