pytest 由于 ModuleNotFoundError 失败,但在使用“python -m pytest”时有效

2024-04-23

类似于这个OP的问题 https://stackoverflow.com/questions/56755761/filenotfounderror-when-using-python-m-pytest-vs-pytest,但反过来说,pytest仅在运行时才在我的虚拟环境(“venv”)中为我工作python -m pytest,但不仅仅是跑步pytest在我的控制台中。

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

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

我正在从项目的根目录使用 CLI,其完整的目录树 https://superuser.com/questions/1270040/windows-10-powershell-tree-command-how-to-show-files/1303475#1303475 is:

(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)

为了完整起见,我将发布它的样子python -m pytest在正确加载的 venv 中(此处使用 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.


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

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

顺便说一句,激发我尝试这一想法的是我在阅读时的以下几行内容使用 VS Code 使用 python 进行测试 https://code.visualstudio.com/docs/python/testing#_test-discovery:

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

pytest 由于 ModuleNotFoundError 失败,但在使用“python -m pytest”时有效 的相关文章

随机推荐