如何详细运行 Django 测试名称而不显示太多日志记录

问题描述 投票:0回答:1

我想在我的 Django 项目中运行测试,显示测试名称,但不显示数据库迁移的日志输出。

如果我没有通过

-v 2
标志,那么我就看不到我想看到的测试名称:

$ python manage.py run test
Found 1 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.
----------------------------------------------------------------------
Ran 1 test in 0.053s

OK
Destroying test database for alias 'default'...

但是,如果我通过标志

-v 2
来增加详细级别,那么我会看到测试名称和数据库迁移中的日志信息:

$ python manage.py test -v 2
Found 1 test(s).
Creating test database for alias 'default' ('test_projectname')...
Operations to perform:
  Synchronize unmigrated apps: allauth, django_browser_reload, django_extensions, forms, google, hijack, hijack_admin, messages, runserver_nostatic, simple_deploy, staticfiles
  Apply all migrations: account, admin, auth, contenttypes, sessions, sites, socialaccount
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0001_initial... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  # ... cut for brevity
System check identified no issues (0 silenced).
test_hello (projectname.test_login.LoginTest.test_hello) ... ok

----------------------------------------------------------------------
Ran 1 test in 0.046s

OK
Destroying test database for alias 'default' ('test_projectname')...

如何仅显示测试名称,而不显示所有这些附加日志信息?

django logging
1个回答
0
投票
from unittest import TextTestResult, TestResult
from datetime import datetime
from django.test.runner import DiscoverRunner

class TerminalColors:
    """Class to hold different colors for terminal messages."""

    RESET = "\033[0m"

    BLACK = "\033[30m"
    RED = "\033[31m"
    GREEN = "\033[32m"
    YELLOW = "\033[33m"
    BLUE = "\033[34m"
    MAGENTA = "\033[35m"
    CYAN = "\033[36m"
    WHITE = "\033[37m"
    ORANGE = "\033[38;5;208m"

    BLACK_BOLD = "\033[1;30m"
    RED_BOLD = "\033[1;31m"
    GREEN_BOLD = "\033[1;32m"
    YELLOW_BOLD = "\033[1;33m"
    BLUE_BOLD = "\033[1;34m"
    MAGENTA_BOLD = "\033[1;35m"
    CYAN_BOLD = "\033[1;36m"
    WHITE_BOLD = "\033[1;37m"
    ORANGE_BOLD = "\033[1;38;5;208m"


class TimedTestResult(TextTestResult):
    """Custom test result class that prints test execution times."""

    def startTest(self, test):
        """Record the start time of the test."""
        self._test_started_at = datetime.now()
        super().startTest(test)

    def _elapsed_time(self):
        """Calculate and return the elapsed time since the test started."""
        return (datetime.now() - self._test_started_at).total_seconds()

    def addSuccess(self, test):
        """Print the elapsed time for successful tests."""
        elapsed = self._elapsed_time()
        if elapsed > 1:
            print(f"{TerminalColors.ORANGE_BOLD}{elapsed:.3f}s : {test}{TerminalColors.RESET}")
        TestResult.addSuccess(self, test)

    def addError(self, test, err):
        """Print the elapsed time for tests that errored."""
        elapsed = self._elapsed_time()
        print(f"{TerminalColors.RED_BOLD}(ERROR) -- {elapsed:.3f}s : {test}{TerminalColors.RESET}")
        TestResult.addError(self, test, err)

    def addFailure(self, test, err):
        """Print the elapsed time for tests that failed."""
        elapsed = self._elapsed_time()
        print(f"{TerminalColors.RED_BOLD}(FAIL) -- {elapsed:.3f}s : {test}{TerminalColors.RESET}")
        TestResult.addFailure(self, test, err)


class GlobalTestRunner(DiscoverRunner):
    """Global unit-tests runner."""

    def __init__(self, exclude_apps=None, *args, **kwargs):
        """Initialize variables for testing."""
        super().__init__(*args, **kwargs)

    def get_resultclass(self):
        """Return customized class for results."""
        return TimedTestResult

然后在 test_settings.py 中添加

TEST_RUNNER = 'common.tests.GlobalTestRunner'

© www.soinside.com 2019 - 2024. All rights reserved.