【问题标题】:pytest fails due to ModuleNotFoundError, but works when using "python -m pytest"pytest 由于 ModuleNotFoundError 而失败,但在使用“python -m pytest”时有效
【发布时间】:2021-04-19 14:55:24
【问题描述】:

this OP's issue 类似,但反过来,pytest 仅在我的虚拟环境 (“venv”) 中对我有效,仅在运行 python -m pytest 时有效,但不适用于仅在我的控制台中运行 pytest

我正在内置控制台中的 Windows 10 上使用 VS Code。

pytest 命令在这两种情况下都不起作用:既不在全局范围内,也不在目标 venv 中。相比之下,python -m pytest 在上述 venv 中工作。

我正在从项目的根目录使用 CLI,其完整的 directory tree 是:

(Testing) PS C:\Users\user\Documents\Programming\Testing> tree /F
Folder PATH listing for volume Windows
Volume serial number is 50BE-501E
C:.
│   default_python_script.py
│
├───.benchmarks
├───.pytest_cache
│   │   .gitignore
│   │   CACHEDIR.TAG
│   │   README.md
│   │
│   └───v
│       └───cache
│               lastfailed
│               nodeids
│               stepwise
│
├───.vscode
│       launch.json
│       settings.json
│
├───cli_testapp
│   │   cli_testapp.py
│   │   __init__.py
│   │
│   └───__pycache__
│           cli_testapp.cpython-39.pyc
│           __init__.cpython-39.pyc
│
├───my_sum
│   │   my_sum.py
│   │   __init__.py
│   │
│   └───__pycache__
│           my_sum.cpython-39.pyc
│           __init__.cpython-39.pyc
│
├───tests
│   │   errors_pytest.log
│   │   test.py
│   │   testing.py
│   │   test_with_pytest.py
│   │
│   ├───.benchmarks
│   ├───.pytest_cache
│   │   │   .gitignore
│   │   │   CACHEDIR.TAG
│   │   │   README.md
│   │   │
│   │   └───v
│   │       └───cache
│   │               lastfailed
│   │               nodeids
│   │               stepwise
│   │
│   └───__pycache__
│           test.cpython-39.pyc
│           testing.cpython-39.pyc
│           test_with_pytest.cpython-39-pytest-6.2.3.pyc
│           test_with_pytest.cpython-39.pyc
│
└───__pycache__
        test.cpython-39.pyc
        testing.cpython-39.pyc

令人讨厌的是,我想使用有用的 VS Code 测试工具包,它有助于使用任何测试框架,还有 pytest。问题是 VS Code 默认使用以下命令来运行测试:

python c:\Users\user\.vscode\extensions\ms-python.python-2021.3.680753044\pythonFiles\testing_tools\run_adapter.py discover pytest -- --rootdir c:\Users\user\Documents\Programming\Testing -s tests

可以检查,它使用pytest 而不是python -m pytest。显然,通过 VS Code 实现的默认方式并没有正确加载环境变量,因为它总是会产生以下错误:

Test Discovery failed:
Error: ============================= test session starts =============================
platform win32 -- Python 3.9.0a4, pytest-6.2.3, py-1.10.0, pluggy-0.13.1
benchmark: 3.4.1 (defaults: timer=time.perf_counter disable_gc=False min_rounds=5 min_time=0.000005 max_time=1.0 calibration_precision=10 warmup=False warmup_iterations=100000)
rootdir: c:\Users\user\Documents\Programming\Testing
plugins: benchmark-3.4.1
collected 0 items / 1 error

=================================== ERRORS ====================================
_________________ ERROR collecting tests/test_with_pytest.py __________________
ImportError while importing test module 'c:\Users\user\Documents\Programming\Testing\tests\test_with_pytest.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
..\..\..\.pyenv\pyenv-win\versions\3.9.0a4\lib\importlib\__init__.py:127: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
tests\test_with_pytest.py:22: in <module>
    from cli_testapp import cli_testapp
E   ModuleNotFoundError: No module named 'cli_testapp'
=========================== short test summary info ===========================
ERROR tests/test_with_pytest.py
!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
==================== no tests collected, 1 error in 0.23s =====================

Traceback (most recent call last):
  File "c:\Users\user\.vscode\extensions\ms-python.python-2021.3.680753044\pythonFiles\testing_tools\run_adapter.py", line 22, in <module>
    main(tool, cmd, subargs, toolargs)
  File "c:\Users\user\.vscode\extensions\ms-python.python-2021.3.680753044\pythonFiles\testing_tools\adapter\__main__.py", line 100, in main
    parents, result = run(toolargs, **subargs)
  File "c:\Users\user\.vscode\extensions\ms-python.python-2021.3.680753044\pythonFiles\testing_tools\adapter\pytest\_discovery.py", line 44, in discover
    raise Exception("pytest discovery failed (exit code {})".format(ec))
Exception: pytest discovery failed (exit code 2)

为了完整起见,我将在正确加载的 venv 中发布 python -m pytest 的样子(此处使用 CLI):

(Testing) PS C:\Users\user\Documents\Programming\Testing> python -m pytest
=================================================================== test session starts ===================================================================
platform win32 -- Python 3.9.0a4, pytest-6.2.3, py-1.10.0, pluggy-0.13.1
benchmark: 3.4.1 (defaults: timer=time.perf_counter disable_gc=False min_rounds=5 min_time=0.000005 max_time=1.0 calibration_precision=10 warmup=False warmup_iterations=100000)
rootdir: C:\Users\user\Documents\Programming\Testing
plugins: benchmark-3.4.1
collected 7 items

tests\test_with_pytest.py .F....F                                                                                                                    [100%]

======================================================================== FAILURES =========================================================================
____________________________________________________________________ test_always_fails ____________________________________________________________________

    def test_always_fails():
        """Function docs:\n
        See above with function docs of "test_always_passes()".
        """
>       assert False
E       assert False

tests\test_with_pytest.py:46: AssertionError
______________________________________________________________ test_initial_transform[dict] _______________________________________________________________

generate_initial_transform_parameters = ({'city': 'Anytown', 'name': ...})

    def test_initial_transform(generate_initial_transform_parameters):
        test_input = generate_initial_transform_parameters[0]
        expected_output = generate_initial_transform_parameters[1]
>       assert cli_testapp.initial_transform(test_input) == expected_output
E       AssertionError: assert {'city': 'Any...e': 'FL', ...} == {'city': 'Any...Public'], ...}
E         Omitting 5 identical items, use -vv to show
...

tests\test_with_pytest.py:118: AssertionError
================================================================= short test summary info =================================================================
FAILED tests/test_with_pytest.py::test_always_fails - assert False
FAILED tests/test_with_pytest.py::test_initial_transform[dict] - AssertionError: assert {'city': 'Any...e': 'FL', ...} == {'city': 'Any...Public'], ...}
=============================================================== 2 failed, 5 passed in 0.31s ===============================================================

我怎样才能解决这个问题,它总是有效的,也只有pytest?这一点尤为重要,因为我很想利用 VS Code 提供的便利设施,它使用基于 pytest 的默认命令。

【问题讨论】:

    标签: python-3.x unit-testing testing visual-studio-code pytest


    【解决方案1】:

    事实证明,有必要在“测试”目录中创建一个(空)__init__.py 文件,即我的测试 Python 文件所在的目录。

    奇怪的是,对于unittest,只需将(空)__init__.py 插入要测试的模块文件夹就足够了,但不能插入测试脚本所在的位置(在我的情况下是“测试”,请参阅目录上面我最初的问题中的树)。 这对我来说很有意义,因为测试脚本会导入被测试的脚本,所以后者需要作为模块导入。然而,由于某种原因,pytest 要求(空)__init__.py - 文件(也)在包含测试脚本(在我的情况下称为“测试”)的文件夹中。

    顺便说一句,在我阅读testing with python using VS Code 时,引发了尝试的想法是以下几行:

    提示:有时无法发现放置在子文件夹中的测试,因为 无法导入此类测试文件。要使它们可导入,请创建一个 该文件夹中名为 init.py 的空文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      • 2021-02-06
      • 2019-07-20
      • 2022-01-18
      • 2018-04-06
      • 2022-11-09
      • 2019-07-23
      相关资源
      最近更新 更多