首页 > 解决方案 > 调试 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"
    ]
}

到目前为止,我已经尝试过:

  1. 根据 VSCode pytest 测试发现更新我的 pytest 失败
  2. 根据 Pytest 将我的 tests.py 文件的名称更改为 test_example.py - 没有运行测试
  3. 根据 (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')

标签: djangovisual-studiotestingpytestpipenv

解决方案


我无法解决最初的问题,但我找到了一个很好的解决方法。我现在可以在测试代码上方看到“调试测试”。我不知道为什么,但可能是因为我安装了 pytest-django 或扩展 python 测试资源管理器 ui。

python测试资源管理器ui故事

  1. 我在谷歌上搜索了调试 django 测试的方法,最终找到了一个 stackoverflow 评论,让我看到了这个https://github.com/Microsoft/vscode-python/issues/3911
  2. 那个 github 问题提到了一个适配器,它让我下载了 little fox 团队的 VS 代码扩展:“Visual Studio Code 的 Python 测试资源管理器”,截至 2021 年 1 月 24 日已下载 262,853 次。
  3. 现在,当我在 git bash 中运行 pytest --collect-only 时,我遇到了错误:尚未加载应用程序。这导致我在尝试运行 pytest-django 时第一次发现 pytest-django “应用程序尚未加载”

pytest-django 的故事

  1. 阅读 pytest-django 文档
  2. 制作了具有以下内容的 pytest.ini 文件:
[pytest]
DJANGO_SETTINGS_MODULE = testprojectname.settings
python_files = tests.py test_*.py *_tests.py
  • testprojectname 是 django 项目的名称
  1. 现在我注意到我在tests.py 中所做的测试上面有可点击的用于调试的单词。单击调试测试需要一段时间才能启动,但它允许代码在红点 VS 代码断点处停止。 用于调试以上测试的可点击单词

  2. 虽然这就是我所需要的,但我也注意到我现在可以从 VS 代码测试资源管理器运行测试,因此我不再需要在 bash 中使用 pipenv shell 来运行所有测试。VS 代码测试资源管理器找到测试


推荐阅读