Django - 测试失败时记录日志 [英] Django - logging when test fails

查看:185
本文介绍了Django - 测试失败时记录日志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django有很多单元测试,如果测试失败,我经常需要看到日志(如果可能的话在控制台中)。我不能真正使用日志文件,因为它在单元测试时变得很杂乱。

我现在做的是:在settings.py中主动登录控制台,并且只运行这个特定的测试。我希望有一个更方便的方法这样做。我只想查看为失败的测试记录的内容,而不是完整的日志。

I have a lot of unit tests in Django and if a test fails, I often need to see the logs (in the console if possible). I can't really use the log file because it gets really messy when unit testing.
What I do right now is: active console logging in the settings.py, and only run this specific test. I was hoping that there is a more convenient way to do so. I only want to see what was being logged for the failing tests and not the complete log.

编辑 - 我已经接受了 - 我不太满意。我只想看到失败测试的日志输出。我正在寻找一个像PHPUnit提供的解决方案。它捕获完整的输出(用于记录+打印),并且只有在测试失败时才将其写入stdout。

event though an awnser was made -- and I have accepted it -- I'm not quite content. I want to see only the logging output of failing tests. I was looking for a solution that like PHPUnit provides. It captures the complete output (for logging + print) and only writes it to stdout if the test fails.

推荐答案

好吧,我只是想出了如何解决它。

显然有一个 -b 选项缓冲输出,除非运行单元测试时测试失败。如果你的tests.py文件执行 unittest.main(),这很容易使用。只需键入 python tests.py -b ,并且完整的输出将被缓冲,除非测试失败。

Well, I just figured out how to fix it.
Apparently there is a -b option that "buffers the output" unless the test fails when running a unit tests. It is very easy to use if your tests.py file executes unittest.main(). Just type python tests.py -b and the complete output will be buffered unless the test fails.

...........F
Stdout:
OK :)
OK :)

======================================================================
FAIL: testStr (__main__.MyTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "tests.py", line 93, in testStr
    self.fail()
AssertionError: None

Stdout:
OK :)
OK :)

----------------------------------------------------------------------
Ran 12 tests in 0.005s

在这种情况下,每个测试打印到stdout,但只有最后一个(显示失败的一个)。由于日志也可以打印到控制台(见托马斯的回答),你只会看到相关的日志。

In this case, every test printed something to stdout but only the very last one (the failing one was shown). Since the log can also be printed to the console (see @Thomas's answer), you will only see relevant logs.

这篇关于Django - 测试失败时记录日志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆