我想在我破坏 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/