与此提问者的问题类似,但是相反的是,在我的虚拟环境(“venv”)中只有在运行
我该如何解决这个问题,使其始终可用,即使只使用
python -m pytest
时,pytest
才能正常工作,但是在控制台中仅运行 pytest
无法正常工作。
我正在使用内置控制台上的Windows 10上的VS Code。
命令pytest
在全局范围和目标venv中都无法正常工作。相比之下,python -m pytest
在该venv中可以正常工作。
我正在从项目的根目录使用CLI,其完整的目录树如下:
(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(此处使用 CLI)的 python -m pytest
的外观:
(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
使用默认命令。