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 使用异常函数

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

  1. python程序员培训_推荐给未来Python程序员的自学路线,不再背负小白名称

    Python彻底火了之后,各种培训机构各和学校也不断加大对Python的培训力度,很多程序员学习Python都会选择去学校或公司培训.培训机构学习,但是不是每个喜欢Python编程的程序员都是可以交得 ...

  2. python mock测试_使用mock测试python中的函数

    对于测试覆盖,我想测试文件'signalC'中该函数的异常块: class SignalC: def readSignal(self, a): try: with open(os.path.join( ...

  3. python怎么测试c代码_如何正确测试python中的C-API,C-API返回错误代码

    我的设置 我正在使用Python中的pytest和ctypes测试C库中的函数.C库中的每个函数调用一个嵌入式linux PCI板上的函数,然后C库函数返回一个整数,该整数映射到一组返回代码.如果函数 ...

  4. append函数_连载|想用Python做自动化测试?函数的参数传递机制及变量作用域

    " 这一节有点难.看不懂没关系.继续往后学,回头再来看." 10.6 函数参数传递的机制 10.6.1 值传递与引用传递 编程语言的参数传递机制通常有两种: 值传递 拷贝参数的值, ...

  5. sublime加入input函数_【挑战自学Python编程】第八天:while循环以及input()函数

    摘要 01 while循环 02 input函数 03 终端 04 使用while循环与input()函数 01 while循环 在正式讲Python中的while前,希望大家先关注单词一下while ...

  6. python退出函数_【转】python 退出程序的方式

    python程序退出方式[sys.exit() os._exit() os.kill() os.popen(...)] 知乎说明 1. sys.exit() 执行该语句会直接退出程序,这也是经常使用的 ...

  7. python装饰器 稀里糊涂_万恶之源 - Python装饰器及内置函数

    装饰器 听名字应该知道这是一个装饰的东西,我们今天就来讲解一下装饰器,有的铁子们应该听说,有的没有听说过.没有关系我告诉你们这是一个很神奇的东西 这个有多神奇呢? 我们先来复习一下闭包 def fun ...

  8. vue函数如何调用其他函数?_好程序员Python教程系列之递归函数与匿名函数调用...

    好程序员Python教程系列递归函数与匿名函数调用,函数是Python技术学习中重要的一个环节,深入掌握该阶段的知识内容,对于Python技术能力的提升非常有帮助,这里就针对递归函数与匿名函数两种函数 ...

  9. astype函数_从Excel到Python:最常用的36个Pandas函数!最完整的Pandas教程!

    本文涉及pandas最常用的36个函数,通过这些函数介绍如何完成数据生成和导入.数据清洗.预处理,以及最常见的数据分类,数据筛选,分类汇总,透视等最常见的操作. 生成数据表 常见的生成数据表的方法有两 ...

最新文章

  1. 费用流 -- 四川省赛F-Direction Setting [拆边成点+费用流]
  2. linux基础文件管理基础命令
  3. python爬虫开发环境_python爬虫开发教程下载|Python爬虫开发与项目实战(范传辉 著)pdf 完整版_ - 极光下载站...
  4. 论初次修改 Android framework 代码
  5. python2.7安装scipy_在centOS上离安装Python2.7以及numpy,scipy,matplot,sklearn等
  6. 还在为运维烦恼?体验云上运维服务,提意见赢好礼!【华为云分享】
  7. 西门子v90伺服说明书_干货 | 西门子1200与V90伺服PROFINET通信故障解决方法
  8. 数据:本周DOT将解锁476.59万枚 上周共质押171.2万枚
  9. 博弈论Python仿真(二)
  10. Stimulsoft Reports.Web 2022.2.3 Crack
  11. mysql时区time_zone和sytem_time_zone
  12. 基于Struts2和hibernate的WebSocket聊天室的实现教程五:聊天机制
  13. asa 防火墙拦截了https_ASA防火墙设置URL过滤
  14. 数字ic设计自学ing
  15. 红孩儿编辑器的模块设计10
  16. 15. 徽章 和 面包屑导航
  17. uiautomator2+python实现企业微信自动打卡
  18. 【图割】最大流/最小割算法详解(Yuri Boykov and Vladimir Kolmogorov,2004 )
  19. 《网络协议》笔记-网络分层
  20. [工具]更新音乐下载软件工具音乐下载网站,MP3音乐无损音乐下载器

热门文章

  1. requestfacade 这个是什么类?_Java 的大 Class 到底是什么?
  2. 使用 PyTorch 数据读取,JAX 框架来训练一个简单的神经网络
  3. 对比损失的PyTorch实现详解
  4. flutter listview 滚动到指定位置_Flutter 布局原理及实战
  5. ovation系统服务器安装,Ovation系统介绍.ppt
  6. HTML4基本编译原理,Stanford公开课《编译原理》学习笔记(1~4课)
  7. Linux系统的基本安装
  8. Angular实现灵活的动态创建组件指令
  9. ffmpeg 纯静态编译,以及添加自定义库流程摘要
  10. 《驯狮记——Mac OS X 10.8 Mountain Lion使用手册》——2.3 Dock