문제 설명
pytest를 사용하여 VSCODE에서 python 테스트 설정 문제 (Issues setting up python testing in VSCODE using pytest)
Python 확장과 함께 VSCode의 테스트 확장을 사용하려고 합니다. 테스트 라이브러리로 pytest를 사용하고 있습니다. 내 폴더 구조는 다음과 같습니다.
PACKAGENAME/
├─ PACKAGENAME/
│ ├─ __init__.py
│ ├─ main.py
├─ tests/
│ ├─ test_main.py
├─ requirements.txt
test_main.py
파일에서 테스트하기 위해 패키지 코드를 가져오려고 합니다.
from PACKAGENAME import *
명령줄의 루트 디렉터리 PACKAGENAME
에서 테스트를 제대로 실행하는 python ‑m pytest
명령을 사용할 수 있습니다. 모듈을 찾지 못하는 문제는 없습니다. 그러나 VSCode 테스트 탭을 사용하려고 하면 테스트가 발견되지만 다음과 같은 오류가 발생합니다.
=================================== ERRORS ====================================
_____________________ ERROR collecting tests/test_main.py _____________________
ImportError while importing test module 'd:\PATH\TO\PACKAGENAME\tests\test_main.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
C:\Users\USER\anaconda3\envs\uni\lib\importlib\__init__.py:127: in import_module
return _bootstrap._gcd_import(name[level:], package, level)
tests\test_main.py:1: in <module>
from PACKAGENAME import *
E ModuleNotFoundError: No module named 'PACKAGENAME'
=========================== short test summary info ===========================
명령줄을 사용하지 않고도 이 작업을 수행할 수 있는 방법이 있습니까?
참조 솔루션
방법 1:
I suggest that you try like this:
- make sure that your VS Code workspace is set to the parent directory of (the root directory)
PACKAGENAME
- add an empty
__init__.py
file intests
directory - in
test_main.py
, replacefrom PACKAGENAME import *
withfrom PACKAGENAME.main import *
(by Jamie Mair、Laurent)