Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python3单元测试:如何打印到标准输出_Python_Unit Testing_Stdout_Python Unittest_Python 3.6 - Fatal编程技术网

Python3单元测试:如何打印到标准输出

Python3单元测试:如何打印到标准输出,python,unit-testing,stdout,python-unittest,python-3.6,Python,Unit Testing,Stdout,Python Unittest,Python 3.6,我正在Python3中运行一些单元测试,但print()似乎不起作用 以下是我的代码片段: import unittest def lexer(line): ... #Lots of code and print statements here return tokens class lexerBasicTestCases(unittest.TestCase): def Test1(self): test = "9+4" out

我正在Python3中运行一些单元测试,但print()似乎不起作用

以下是我的代码片段:

import unittest

def lexer(line):
        ... #Lots of code and print statements here
    return tokens

class lexerBasicTestCases(unittest.TestCase):
    def Test1(self):
        test = "9+4"
        output = ["9", "+", "4"]
        self.assertEqual(lexer(test), output)   
    def Test2(self):
        test = "9 + 4"
        output = ["9", "+", "4"]
        self.assertEqual(lexer(test), output)   
    def Test2(self):
        test = "9    +  4"
        output = ["9", "+", "4"]
        self.assertEqual(lexer(test), output)   

def lexerBasicTestSuite():
    suite = unittest.TestSuite()
    suite.addTest(lexerBasicTestCases('Test1'))
    suite.addTest(lexerBasicTestCases('Test2'))
    suite.addTest(lexerBasicTestCases('Test3'))
    unittest.TextTestRunner(verbosity=2).run(suite)

#Main program
lexerBasicTestSuite()
我使用以下方法运行代码:

python \interpreter.py

当单元测试运行时,lexer()中的print()语句将被忽略。当测试用例失败并且我没有打印语句来分析时,这是令人沮丧的。在调试时,我不希望注释掉单元测试,而是编写一个对应的函数,只为它们的print语句运行测试。如何使打印语句打印出来?

单元测试并行运行,因此您不能依赖打印函数,因为它不是线程安全的。改用记录器,或者更好地将自定义消息传递给assert方法

class lexerBasicTestCases(unittest.TestCase):
    def Test1(self):
        """
        Docstrings are printed in most test runners.
        """
        test = "9+4"
        expect = ["9", "+", "4"]
        failure_msg = 'lexer({0}) should return {1} but returned {2}'
        actual = lexer(test)
        self.assertListEqual(expect, actual, failure_msg.format(test, expect, actual)) 

欢迎来到StackOverflow。请阅读并遵循帮助文档中的发布指南。适用于这里。在您发布MCVE代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中,并重现您描述的问题。相反,您删除了问题代码并保留了多余的代码。您不想让函数打印东西。您想要的是让单元测试检查函数的返回值。您可以轻松地使用其他函数在生产代码运行期间打印返回值。在运行单元测试时打印是不允许的。您可以使用日志模块进行此操作。也许这会有帮助-