VSCode中未发现的Python单元测试

Pur*_*ret 7 python python-unittest visual-studio-code

我写了一个名为蟒蛇测试文件scraping_test.py,用一个单一的测试类,使用unittest,称为TestScrapingUtils

"""Tests for the scraping app"""
import unittest

from bs4 import BeautifulSoup as bs4

from mosque_scraper.management.commands import scraping_utils
from mosque_scraper.selectors import MOSQUE_INFO_ROWS_SELECTOR

class TestScrapingUtils(unittest.TestCase):
    """Test scraping_utils.py """
    def setup(self):
        """Setup McSetupface."""
        pass
    def test_get_keys_from_row(self):
        """ Test that we extract the correct keys from the supplied rows."""
        test_page_name = "test_page.html"
        with open(test_page_name) as test_page_file:
            test_mosque = bs4(test_page_file, 'html.parser')
            rows = test_mosque.select(MOSQUE_INFO_ROWS_SELECTOR)
            field_dict = scraping_utils.get_fields_from_rows(rows)
            self.assertDictEqual(field_dict, {})
Run Code Online (Sandbox Code Playgroud)

我对单元测试的设置是:

{
    "python.unitTest.unittestEnabled": true,
    "python.unitTest.unittestArgs": [
        "-v",
        "-s",
        ".",
        "-p",
        "*test.py"
    ]
}
Run Code Online (Sandbox Code Playgroud)

看起来应该可以,但是当我单击以VSCode运行测试时,它说没有发现测试:

No tests discovered, please check the configuration settings for the tests.
Run Code Online (Sandbox Code Playgroud)

我该如何运作?

Der*_*ang 14

您必须使用快捷键 shift+ctrl p 运行一次,然后键入“Python 运行所有单元测试”。

在成功执行至少一次或使用发现单元测试方法之前,它不会显示在编辑器中。

然而,我多次注意到的一件事是 Python 文件必须是有效的 Python 文件。VS Code for Python 中的智能感知并不复杂(与 Javascript 或 Typescript 相比),并且不会突出任何语法错误。您可以通过强制它运行所有单元测试并观察 Python 测试日志窗口来验证这一点。


Laz*_*zer 8

让我惊讶的是,__init__.py必须在每个子目录中创建该文件,从-s选项指定的根文件夹(在示例中为当前目录".")到测试模块所在的子目录。只有这样我才能成功发现测试。

在问题示例中,project_dir/project_dir/scraping_app/都应包含__init__.py。这是假设settings.json位于目录中project_dir/.vscode并且测试是从project_dir/目录运行的。

编辑:或者,使用"-s", "./scraping_app/"作为根测试目录,这样您就不__init__.py必将project_dir/.