【问题标题】:How to automatically run tests when running Django runserver?运行 Django runserver 时如何自动运行测试?
【发布时间】:2015-03-30 17:00:05
【问题描述】:

当我在 Django 中完成测试时,我想立即知道。不是总是单独运行manage.py test,有没有办法在运行manage.py runserver 时在后台运行测试并将它们报告给同一个终端?最好在保存文件时重新运行测试,就像服务器正常重新加载一样。

这将有助于更快地发现错误。更好的是,它会直接出现在您的面前,而不是隐藏在手动测试步骤之后。

这可能吗?

【问题讨论】:

  • 使用 Pycharm,我对目标 manage.py 进行了自定义配置并运行 test --pattern="*_test.py" 这样我只需将所有测试文件命名为 *_test.py
  • 可以通过多种方式实现,可以通过自定义python脚本,也可以通过shell脚本,甚至可以创建自定义django管理命令,这完全取决于你想怎么做将其集成到您的项目中。
  • @petkostas Django 管理命令就可以了。我只是确保我没有忽略一些明显的事情,或者如果这不是内置功能,是否已经存在现有的解决方案。

标签: python django testing


【解决方案1】:

我最终覆盖了管理命令。

应用名称\管理\命令\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 也值得一读,因为它可以加快您的测试以获得更快的反馈循环。

【讨论】:

    猜你喜欢
    • 2022-07-07
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 2017-01-09
    • 1970-01-01
    相关资源
    最近更新 更多