VSCode无法识别Django项目中的pytest测试文件求助
VSCode测试侧边栏无法识别Django项目pytest测试文件的解决方法
问题场景
在Django项目中使用VSCode测试侧边栏时,无法找到pytest测试文件,但在项目目录DjangoPyTesting\LearningPytest下直接运行pytest命令能正常执行测试;若在上级目录DjangoPyTesting运行pytest则找不到任何测试,推测VSCode工作区根目录设置是问题根源。
项目环境与配置
创建项目的命令
django-admin startproject LearningPytest pip install django-pytest
文件夹结构
DjangoPyTesting/ └───LearningPytest/ ├───LearningPytest/ │ ├───__init__.py │ ├───asgi.py │ ├───basic_tests.py │ ├───settings.py │ ├───urls.py │ ├───wsgi.py ├───manage.py └───pytest.ini
pytest.ini配置
[pytest] DJANGO_SETTINGS_MODULE = LearningPytest.settings python_files = tests.py test_*.py *_tests.py python_classes = Test* python_functions = test_*
测试文件basic_tests.py内容
class TestBasicMath: def setup_method(self, method): self.x = 2 self.y = 3 def test_addition(self): assert self.x + self.y == 5 def test_subtraction(self): assert self.y - self.x == 1 def test_multiplication(self): assert self.x * self.y == 6
核心问题分析
pytest会从当前执行目录向上查找pytest.ini配置文件,同时按照配置中的规则匹配测试文件。当VSCode将DjangoPyTesting作为工作区根目录时,pytest在该目录执行时:
- 找不到
pytest.ini(配置文件在子目录LearningPytest下) - 无法匹配到子目录中的测试文件规则
解决方案
1. 调整VSCode工作区根目录
关闭当前VSCode窗口,直接打开LearningPytest文件夹作为工作区根目录,而非上级的DjangoPyTesting。这样pytest会自动读取该目录下的pytest.ini,并匹配到子目录中的测试文件。
2. 配置VSCode的pytest参数
若需要保留DjangoPyTesting作为工作区根目录,可在VSCode的settings.json中指定pytest的运行目录:
{ "python.testing.pytestEnabled": true, "python.testing.pytestArgs": [ "./LearningPytest", "-c", "./LearningPytest/pytest.ini" ] }
该配置指定pytest在LearningPytest目录下运行,并加载对应目录的pytest.ini配置。
3. 确认虚拟环境配置
确保VSCode激活了安装django-pytest和pytest的虚拟环境:
- 点击VSCode右下角的Python版本选择器,切换到项目对应的虚拟环境
- 重新加载窗口(
Ctrl+Shift+P→Developer: Reload Window)
已尝试无效的方法
- 使用
Developer: Reload Window重新加载窗口 - 参考官方文档调整配置
- 重命名测试文件为
test.py、tests.py、LearningPytest_tests.py等
内容的提问来源于stack exchange,提问作者Hibbert
相关产品推荐
相关产品推荐

