Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.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
Python中的自定义错误消息_Python_Unit Testing_Exception Handling_Error Handling - Fatal编程技术网

Python中的自定义错误消息

Python中的自定义错误消息,python,unit-testing,exception-handling,error-handling,Python,Unit Testing,Exception Handling,Error Handling,所以我在练习一些单元测试,我有一个关于错误消息的问题。我正在尝试创建一条自定义错误消息,当测试失败时将显示该消息。这是一个基本的Hello World程序。测试运行良好,一切正常,但下面是我收到的错误消息 F ====================================================================== FAIL: test_StringContains (__main__.TestSuite) --------------------------

所以我在练习一些单元测试,我有一个关于错误消息的问题。我正在尝试创建一条自定义错误消息,当测试失败时将显示该消息。这是一个基本的Hello World程序。测试运行良好,一切正常,但下面是我收到的错误消息

F ====================================================================== FAIL: test_StringContains
 (__main__.TestSuite) ----------------------------------------------------------------------   
Traceback    (most recent call last): File "Testsuite.py", line 8, in test_StringContains 
self.assertEqual("Hello,    World", hello_world,"This is a custom error") AssertionError: 'Hello,   
World' != 'Hello World' - Hello,    World ? - + Hello World : This is a custom error ---------------  
------------------------------------------------------- 
Ran 1 test in 0.000s FAILED (failures=1)
所以这是意料之中的。这是我的测试套件

from  HelloWorld import*
import unittest

class TestSuite(unittest.TestCase):

    def test_StringContains(self):
            self.assertEqual("Hello World", hello_world,"This is a custom")


if __name__ == "__main__":
    unittest.main()
这是我的运行代码

hello_world = "Hello World"
print (hello_world)
超级基本,只是想了解如何抛出自定义错误消息。如果测试失败,我唯一想看到的是
这是一个自定义错误
,我尝试了遵循Python文档中关于错误和异常的内容,但不确定如何实现它


我不知道这是否可行。非常感谢您的帮助。谢谢

您可以通过将assertEqual包装在一个try-except语句中,然后打印错误来捕获断言错误:

        try:
            self.assertEqual("Hello World", hello_world,"This is a custom error")
        except AssertionError as e:
            print(e)
但是,捕获断言错误时有一个缺点:unittest模块无法再统计错误。
(Stacktraces并不漂亮,但它们的目的是准确地将您指向堆栈中发生错误的点。)

请不要这样做。如果输出是通过/失败(而且执行速度非常快),则单元测试的最大优势。Stacktraces/stdout/whatever应该只用于调试测试失败时出现的错误。如果您强迫自己读取输出以了解测试是否已通过,您将不会尽可能频繁地运行它们。这是为了调试以外的其他目的。可能会重复