类似于这个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
.