python - 如何在运行 Django runserver 时自动运行测试?

标签 python django testing

我想在我破坏 Django 测试时立即知道。有没有办法在运行 manage.py runserver 时在后台运行测试并将它们报告到同一个终端,而不是总是单独运行 manage.py test?理想情况下,测试会在保存文件时重新运行,就像服务器正常重新加载一样。

如果能更快地发现错误,那就太好了。更好的是,它就在您的面前,而不是隐藏在手动测试步骤后面。

这可能吗?

最佳答案

我最终覆盖了管理命令。

app-name\management\commands\runserver.py:

from __future__ import print_function

import subprocess
from threading import Thread

from django.core.management.commands.runserver import Command as BaseCommand
# or: from devserver.management.commands.runserver import Command as BaseCommand
from django.conf import settings
from termcolor import colored


BEEP_CHARACTER = '\a'


def call_then_log():
    try:
        output = subprocess.check_output('manage.py test --failfast',
                                         stderr=subprocess.STDOUT, shell=True)
    except subprocess.CalledProcessError as ex:
        print(colored(ex.output, 'red', attrs=['bold']))
        print(BEEP_CHARACTER, end='')
        return

    print(output)


def run_background_tests():
    print('Running tests...')
    thread = Thread(target=call_then_log, name='runserver-background-tests')
    thread.daemon = True
    thread.start()


class Command(BaseCommand):
    def inner_run(self, *args, **options):
        if settings.DEBUG and not settings.TESTING:
            run_background_tests()
        super(Command, self).inner_run(*args, **options)

requirements.txt:

termcolor

这会在后台线程中运行您的测试,该线程会在每次 Django 自动重新加载时运行。旧线程将被停止。如果任何测试失败,它会发出哔哔声,第一个失败的结果将以红色打印到终端。

This answer也值得一读,以加速您的测试以获得更快的反馈循环。

关于python - 如何在运行 Django runserver 时自动运行测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29351994/

相关文章:

python - 如何将 map 与 urljoin 一起使用?

python - 在表单集中设置 auto_id 并且不要在首次显示时禁用错误

python - 是否有标准方法告诉 py.test 针对特定代码运行?

unit-testing - 使用 PHPUnit 3.5 测试时出错

python - Spacy链接错误

python - 从python Django的角度来看,机器人与爬虫不同吗

python - Django:如何获得与数据库的新连接

python - Django基于多个字段(文件字段)验证表单

testing - 如何使用 testWidgets 测试 Widget 的动态颜色

python - 如何在 matplotlib 中为 3D 散点图上的数据点着色