python - pytest 是否应该从虚拟环境中的依赖模块收集测试?

标签 python sqlalchemy pytest

我正尝试在另一台笔记本电脑而不是我的典型开发机器上设置项目。这个项目有几个基于 pytest 的测试,我在项目的整个生命周期中编写了这些测试。当我运行时

$ pytest -k tests/my_test.py

我从 sqlalchemy 测试中得到一个错误列表,如下所示:

_ ERROR collecting env/lib64/python3.5/site-packages/sqlalchemy/testing/suite/test_update_delete.py _
env/lib/python3.5/site-packages/py/_path/local.py:662: in pyimport
    __import__(modname)
env/lib/python3.5/site-packages/sqlalchemy/testing/suite/__init__.py:2: in <module>
    from sqlalchemy.testing.suite.test_cte import *
<frozen importlib._bootstrap>:968: in _find_and_load
    ???
<frozen importlib._bootstrap>:957: in _find_and_load_unlocked
    ???
<frozen importlib._bootstrap>:664: in _load_unlocked
    ???
<frozen importlib._bootstrap>:634: in _load_backward_compatible
    ???
env/lib/python3.5/site-packages/_pytest/assertion/rewrite.py:211: in load_module
    py.builtin.exec_(co, mod.__dict__)
env/lib/python3.5/site-packages/sqlalchemy/testing/suite/test_cte.py:11: in <module>
    class CTETest(fixtures.TablesTest):
env/lib/python3.5/site-packages/sqlalchemy/testing/suite/test_cte.py:99: in CTETest
    @testing.requires.ctes_with_update_delete
E   AttributeError: 'NoneType' object has no attribute 'ctes_with_update_delete'

为什么 pytest 从依赖项中收集测试?它应该这样做吗?如果没有,我该如何解决?

我设置这个项目的笔记本电脑运行的是 Ubuntu 18.04。我用 Python 3.5.6 创建了一个 virtualenv 并在 virtualenv 中运行 pip install -r requirements 没有任何错误,包括 sqlalchemy 和 pymssql。

最佳答案

pytest 被调用时,它会扫描项目根目录中的所有子目录,寻找测试;当您将项目特定的虚拟环境放入项目根目录时,它也会被扫描而不会出现异常。这可能会导致测试运行中包含不需要的测试(例如,当您有像 numpypandas 这样的依赖项时,它们在分发中包含测试)。

为了避免这种情况,pytest 提供了两个配置选项:

  1. norecursedirs - 包含将从扫描中排除的目录。当您正在寻找模式“包括所有,排除选定”时使用此选项。另见 wimanswer用于解释和用法示例。默认情况下,norecursedirs 设置为 .*', 'build', 'dist', 'CVS', '_darcs', '{arch}', '*.egg',因此请注意,当您覆盖此选项时,默认值将消失,您必须将它们添加回来。
  2. testpaths - 包含仅应考虑用于扫描的目录,因此这基本上与 norecursedirs 所做的相反。在查找模式“排除所有,包括选定的”时使用此选项。此选项还会为测试发现添加一些小的或更显着的加速,具体取决于您在项目根目录中保留的内容 - 大多数子目录根本不会被遍历并且测试运行开始得更快。

    用法:将选项放在pytest.ini/setup.cfg/tox.ini中:

    [tool:pytest]
    testpaths = tests othertests doc
    

    或从命令行通过 --override-ini 传递它们。

    pytest -o "testpaths=tests othertests doc" ...
    

将 env 目录从项目源中移开是一个选择问题,取决于您拥有的开发环境。 direnvpipenv 等可能对 envs 应该驻留的位置有不同的看法,但我个人认为将 envs 保留在项目根目录中没有任何问题。

关于python - pytest 是否应该从虚拟环境中的依赖模块收集测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52937050/

相关文章:

python - 如何在 Python 中检查 Selenium Webdriver 中的单击是否更改了页面

python - OpenCV:完成后如何重新启动视频?

python - 如何使用sqlsoup插入字典

python - 通过factory-boy Factory传递参数到SubFactory而不指定

python - pytest参数化类方法执行顺序

python - 在测试运行开始时动态选择pytest测试

python - python 2.7 上的 Ttk

python - 将 Python 中 Perl 子进程的输出通过管道传输到 Python 中的数组

sql-server - SQLAlchemy 和 mssql+pymssql 密码在一定长度后失败

python - sqlalchemy.exc.CircularDependencyError : Can't sort tables for DROP; an unresolvable foreign key dependency exists between tables