django - 调试 Django 测试时,VSCode pytest 测试发现失败
问题描述
我正在尝试调试我的第一个 django 测试,但 VSCode 正在返回:在 0.000 秒内运行 0 个测试。另一方面,当我在 VSCode 终端或外部使用集成的 git bash(我使用的是 Windows 操作系统)时,它会返回: Ran 1 test in 0.0014s。它还回显 FAILED 和测试中有效错误的回溯。
我的 vscode 启动.json:
{
...
"configurations": [
...
{
"name": "Django Tests",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}\\testprojectname\\manage.py",
"args": [
"test"
],
"django": true,
}
]
}
我的 vscode settings.json:
{
"python.pythonPath": "C:\\Users\\user\\.virtualenvs\\backend-Vg-KBKTA\\Scripts\\python.exe",
"python.testing.pytestEnabled": true,
"python.testing.nosetestsEnabled": false,
"python.testing.unittestEnabled": false,
"python.testing.pytestArgs": [
"testprojectname"
]
}
- 请注意,C:\Users\user\.virtualenvs\backend-Vg-KBKTA\Scripts\python.exe 是 pipenv shell 的有效路径 [(1) 当我输入 bash 时会回显它: pipenv --venv ( 2)当我启动 django 调试器时它工作]
到目前为止,我已经尝试过:
- 根据 VSCode pytest 测试发现更新我的 pytest 失败
- 根据 Pytest 将我的 tests.py 文件的名称更改为 test_example.py - 没有运行测试
- 根据 (2) 中的相同链接,将测试的类更改为前缀为 Test_
这是当前测试的样子
class Test_Contacts(unittest.TestCase):
def test_create_contact_message(self):
"""Create a new contact message."""
url = reverse('message-list')
data = {
'first_name': 'DabApps',
'last_name': 'jack',
'email': 'giehogho24h@gmo8y9tgail.com',
'message': 'hi, how are you?',
'message_type': 1
}
# this is just random code to cause an error
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(Message.objects.count(), 1)
self.assertEqual(Message.objects.get().name, 'DabApps')
解决方案
我无法解决最初的问题,但我找到了一个很好的解决方法。我现在可以在测试代码上方看到“调试测试”。我不知道为什么,但可能是因为我安装了 pytest-django 或扩展 python 测试资源管理器 ui。
python测试资源管理器ui故事
- 我在谷歌上搜索了调试 django 测试的方法,最终找到了一个 stackoverflow 评论,让我看到了这个https://github.com/Microsoft/vscode-python/issues/3911
- 那个 github 问题提到了一个适配器,它让我下载了 little fox 团队的 VS 代码扩展:“Visual Studio Code 的 Python 测试资源管理器”,截至 2021 年 1 月 24 日已下载 262,853 次。
- 现在,当我在 git bash 中运行 pytest --collect-only 时,我遇到了错误:尚未加载应用程序。这导致我在尝试运行 pytest-django 时第一次发现 pytest-django “应用程序尚未加载”
pytest-django 的故事
- 阅读 pytest-django 文档
- 制作了具有以下内容的 pytest.ini 文件:
[pytest]
DJANGO_SETTINGS_MODULE = testprojectname.settings
python_files = tests.py test_*.py *_tests.py
- testprojectname 是 django 项目的名称
现在我注意到我在tests.py 中所做的测试上面有可点击的用于调试的单词。单击调试测试需要一段时间才能启动,但它允许代码在红点 VS 代码断点处停止。 用于调试以上测试的可点击单词
虽然这就是我所需要的,但我也注意到我现在可以从 VS 代码测试资源管理器运行测试,因此我不再需要在 bash 中使用 pipenv shell 来运行所有测试。VS 代码测试资源管理器找到测试
推荐阅读
- javascript - jQuery removeClass 不适用于可拖动
- php - 如何修复 curl 请求返回奇怪的错误 PHP?
- java - 将 char 转换为 int 和 char 转换为 byte 之间的区别
- c++ - 更改 CTreeCtrl 项目图像
- c# - 每个用户的实体框架多租户
- python - 如何使用python中的列表理解在两个循环之间打印行,以创建金字塔
- unity3d - UNITY 为什么当我往下看时,一切都变得明亮了?
- telethon - 秘密聊天 Telethon 不显示发送的消息
- vim - 使用 `:! 时的颜色编码
` - python - 如何从字典中的列表中删除元组?