python 使用异常函数_您如何测试Python函数引发异常?

python 使用异常函数

This article elaborates on how to implement a test case for a function that raises an exception.

本文详细介绍了如何为引发异常的函数实现测试用例

Consider the following function:

考虑以下功能:

import re

def check_email_format(email):
  """check that the entered email format is correct"""
  if not re.match(r"(^[a-zA-Z0-9_.+-][email protected][a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", email):
    raise Exception("Invalid email format")
  else:
    return "Email format is ok"

The above function validates the correctness of the email address. Also, note that the function raises an exception if the format is not correct.

以上功能可验证电子邮件地址的正确性。 另外,请注意,如果格式不正确,该函数将引发异常。

Now, to test such functionality, the pytest ( the testing module of python) has a built-in method called pytest.raises. The below test case helps in understanding the usage of pytest.raises method in order to assert is the method has raised an exception.

现在,为了测试这种功能, pytest (python的测试模块)具有一个称为pytest.raises的内置方法。 下面的测试用例有助于理解pytest.raises方法的用法,以便断言该方法引发了异常。

In the below example, the test case is asserting if the "check_email_format" raises an exception if the email address is of the correct format, i.e., this is a negative test case, where we expect the test case to fail.

在下面的示例中,如果电子邮件地址的格式正确,则测试用例断言“ check_email_format ”是否引发异常,即,这是一个否定的测试用例,我们期望测试用例失败。

>>> import pytest
>>> def test_email_exception():
...     """test that exception is raised for invalid emails"""
...     with pytest.raises(Exception):
...             assert check_email_format("[email protected]")

Execution of test case:

执行测试用例:

pytest invalid_test_case.py 
========================================================================================== test session starts ===========================================================================================
platform darwin -- Python 3.7.0, pytest-5.3.5, py-1.8.1, pluggy-0.13.1
rootdir: /Users/XXX/XXX-work/src
collected 1 item                                                                                                                                                                                         

invalid_test_case.py F                                                                                                                                                                             [100%]

================================================================================================ FAILURES ================================================================================================
__________________________________________________________________________________________ test_email_exception __________________________________________________________________________________________

    def test_email_exception():
    	"""test that exception is raised for invalid emails"""
    	with pytest.raises(Exception):
>   		assert check_email_format("[email protected]")
E     Failed: DID NOT RAISE <class 'Exception'>

invalid_test_case.py:15: Failed
========================================== 1 failed in 0.05s ================================================================

Now consider a positive testcase, where we expect the test case to pass i.e., we expect an exception to be raised.

现在考虑一个肯定的测试用例,我们希望测试用例能够通过,即,我们期望引发异常。

def test_email_exception():
        """test that exception is raised for invalid emails"""
        with pytest.raises(Exception):
                assert check_email_format("bademail.com")

Execution of test case:

执行测试用例:

pytest valid_test_case.py 
======================================= test session starts ===============================================================
platform darwin -- Python 3.7.0, pytest-5.3.5, py-1.8.1, pluggy-0.13.1
rootdir: /Users/suri/preeti-work/python_ml_samples/src
collected 1 item                                                                                                                                                                                         

valid_test_case.py .                                                                                                                                                                               [100%]

========================================== 1 passed in 0.01s ================================================================


翻译自: https://www.includehelp.com/python/how-do-you-test-that-a-python-function-throws-an-exception.aspx

python 使用异常函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值