pytes不可能将依赖项泄漏到python/real代码中

2024-10-03 13:25:10 发布

您现在位置:Python中文网/ 问答频道 /正文

TL;DR:如果我使用pytest和其他一些只测试的依赖项,是否可以断言这些仅测试的依赖项都没有泄漏到实际的非测试代码中?在

在Java中,当我运行测试时,测试本身和被测试的代码将在不同的类加载器中运行,它们各自的依赖关系在那里被限定。因此,如果被测代码无意中引用了testng,那么即使{}正在运行测试,测试也会失败。在

在Python中也能实现吗?如果我的非测试代码意外地导入pytest,我能捕捉到它并让测试失败吗?我不知道该怎么做。在

尽管setuptoolspip等使得分离安装/运行和开发/测试依赖相对容易,甚至避免污染当前的venv,但是在测试运行时它们仍然存在。这意味着对一个模块运行python setup.py test可以通过,但是python setup.py install之后再执行一些像导入模块这样简单的操作就会失败。在

给予: cat setup.py

from setuptools import setup, find_packages

setup(
    name="brettpy",
    version="0.0.1",
    packages=find_packages(),
    setup_requires=["pytest-runner",],
    tests_require=["pytest",],
)

cat setup.cfg

^{pr2}$

cat brettpy/__init__.py

import pytest

cat tests/test_brettpy.py

def test_import_brettpy():
    import brettpy
    del brettpy

def test_run_main():
    from brettpy import __main__ as main
    main.main()

。。。python setup.py test将通过,但{}将失败,并返回:

ModuleNotFoundError: No module named 'pytest'

其他人如何确保测试依赖项在安装时不会渗透到实际代码中并导致缺少依赖项的错误?感觉像是测试框架应该能够捕捉到的bug。在


Tags: 模块代码frompytestimportpytestmain
2条回答

你可以这样做:https://stackoverflow.com/a/1592578/9095840

def no_test():
    try:
        pytest
    except NameError:
        pass
    else:
        exit()

可以使用Python的modulefinder显式测试test导入。这可能不是最漂亮的解决方案:

from modulefinder import ModuleFinder

def test_imports():
    finder = ModuleFinder()
    finder.run_script("PATH_TO_MAIN_SCRIPT")
    tests_require = ["pytest",]  # you can also get this list straight from `setup.py`
    overlapping = [mod for mod in finder.modules.keys() for req in tests_require if req in mod]
    assert not overlapping

或者如果你不想使用列表理解:

^{pr2}$

相关问题 更多 >