如何在变量中捕获单元测试的stdout/stderr?

How to capture the stdout/stderr of a unittest in a variable?(如何在变量中捕获单元测试的stdout/stderr?)
本文介绍了如何在变量中捕获单元测试的stdout/stderr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在变量中捕获单元测试的stdout/stderr?我需要捕获以下单元测试的全部输出,并将其发送给SQS。我已经尝试过了:
import unittest, io
from contextlib import redirect_stdout, redirect_stderr


class LogProcessorTests(unittest.TestCase):
    def setUp(self):
        self.var = 'this value'

    def test_var_value(self):
        with io.StringIO() as buf, redirect_stderr(buf):
            print('Running LogProcessor tests...')
            print('Inside test_var_value')
            self.assertEqual(self.var, 'that value')
            print('-----------------------')
            print(buf.getvalue())

但是,它不起作用,并且以下输出仅出现在stdout/stderr上。

Testing started at 20:32 ...
/Users/myuser/Documents/virtualenvs/app-venv3/bin/python3 "/Applications/PyCharm CE.app/Contents/helpers/pycharm/_jb_unittest_runner.py" --path /Users/myuser/Documents/projects/application/LogProcessor/tests/test_processor_tests.py
Launching unittests with arguments python -m unittest /Users/myuser/Documents/projects/application/LogProcessor/tests/test_processor_tests.py in /Users/myuser/Documents/projects/application/LogProcessor/tests
Running LogProcessor tests...
Inside test_var_value

that value != this value

Expected :this value
Actual   :that value
<Click to see difference>

Traceback (most recent call last):
  File "/Applications/PyCharm CE.app/Contents/helpers/pycharm/teamcity/diff_tools.py", line 32, in _patched_equals
    old(self, first, second, msg)
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/case.py", line 839, in assertEqual
    assertion_func(first, second, msg=msg)
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/case.py", line 1220, in assertMultiLineEqual
    self.fail(self._formatMessage(msg, standardMsg))
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/case.py", line 680, in fail
    raise self.failureException(msg)
AssertionError: 'this value' != 'that value'
- this value
?   ^^
+ that value
?   ^^

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/case.py", line 59, in testPartExecutor
    yield
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/case.py", line 615, in run
    testMethod()
  File "/Users/myuser/Documents/projects/application/LogProcessor/tests/test_processor_tests.py", line 15, in test_var_value
    self.assertEqual(self.var, 'that value')



Ran 1 test in 0.004s

FAILED (failures=1)

Process finished with exit code 1

Assertion failed

Assertion failed

有什么想法吗?如果需要更多信息,请让我知道。

推荐答案

如果您手动实例化测试运行器(例如unittest.TextTestRunner),则可以指定它写入的(文件)流。默认情况下,这是sys.stderr,但您也可以使用StringIO。这将捕获单元测试本身的输出。您自己的print语句的输出不会被捕获,但您可以使用redirect_stdout上下文管理器,并使用相同的StringIO对象。

请注意,我建议避免使用print-语句,因为它们会干扰unittest框架的输出(您的测试输出将破坏unittest框架的输出行),而且重定向stdout/stderr流有点麻烦。更好的解决方案是使用logging模块。然后,您可以添加一个日志记录处理程序,该处理程序将所有日志消息写入StringIO以供进一步处理(在您的示例中:发送到SQS)。

下面是基于使用打印语句的代码的示例代码。

#!/usr/bin/env python3

import contextlib
import io
import unittest


class LogProcessorTests(unittest.TestCase):

    def setUp(self):
        self.var = 'this value'

    def test_var_value(self):
        print('Running LogProcessor tests...')
        print('Inside test_var_value')
        self.assertEqual(self.var, 'that value')
        print('-----------------------')


if __name__ == '__main__':
    # find all tests in this module
    import __main__
    suite = unittest.TestLoader().loadTestsFromModule(__main__)
    with io.StringIO() as buf:
        # run the tests
        with contextlib.redirect_stdout(buf):
            unittest.TextTestRunner(stream=buf).run(suite)
        # process (in this case: print) the results
        print('*** CAPTURED TEXT***:
%s' % buf.getvalue())

此打印:

*** CAPTURED TEXT***:
Running LogProcessor tests...
Inside test_var_value
F
======================================================================
FAIL: test_var_value (__main__.LogProcessorTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 16, in test_var_value
    self.assertEqual(self.var, 'that value')
AssertionError: 'this value' != 'that value'
- this value
?   ^^
+ that value
?   ^^


----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)

这确认了所有输出(来自单元测试框架和测试用例本身)都在StringIO对象中捕获。

这篇关于如何在变量中捕获单元测试的stdout/stderr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)