Python中的自定义错误消息 [英] Custom error messages in Python

查看:116
本文介绍了Python中的自定义错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在练习一些单元测试,并且对错误消息有疑问。我正在尝试创建一个自定义错误消息,该消息将在测试失败时显示。这是一个基本的Hello World程序。测试运行正常,一切正常,但这是我得到的错误消息。

So I'm practicing some unit test and I have a question about error messages. I'm trying to create a custom error message that will display when the test fails. Here is a basic Hello World program. The test runs fine and everything, but here is the error message I get.

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)

所以这是预期的。这是我的测试套件

So this is expected. Here is my test suite

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)

超级基本,只想了解如何引发自定义错误消息。我唯一想查看测试是否失败的是这是自定义错误,我尝试按照Errors&上的Python文档进行操作 https://docs.python.org/2/tutorial/errors.html,但不确定如何实现。

Super basic, just want to understand how to throw a custom error message. The only thing I want to see if the test fails is This is a custom error, I tried following the Python documentation on Errors & Exceptions here https://docs.python.org/2/tutorial/errors.html , but not sure how to implement it.

我不知道这是否可行。任何帮助是极大的赞赏。谢谢

I don't know if this is doable or not. Any help is greatly appreciated. Thank you

推荐答案

您可以做的是通过将assertEqual包裹在try除外语句中来捕获AssertionError,然后打印错误:

What you could do is to catch the AssertionError by wrapping the assertEqual in a try except statement and then print the error:

        try:
            self.assertEqual("Hello World", hello_world,"This is a custom error")
        except AssertionError as e:
            print(e)

但是捕获AssertionError时的不利方面:unittest模块无法再计算错误。
(Stacktraces并不漂亮,但它们的目的是将您准确指向堆栈中发生错误的位置。)

There is however a downside when catching the AssertionError: the unittest module can no longer count the errors. (Stacktraces are not beautiful but they server the purpose of exactly pointing you to the point in the stack where the error occured.)

这篇关于Python中的自定义错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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