pytest简介

pytestpython的一种单元测试框架,它非常的简洁、清晰。

pytest 安装

pip install -U pytest

查看pytest版本

pytest --version

入门

创建、运行第一个 test

test_first.py

def inc(x):
return x + 1 def test_inc():
assert inc(10) == 20

运行 pytest

an@hosta:~/PycharmProjects/testproject/pytest_study$ pytest     # 运行命令
========================================================== test session starts ==========================================================
platform linux -- Python 3.5.2, pytest-3.3.2, py-1.5.2, pluggy-0.6.0
rootdir: /home/an/PycharmProjects/testproject/pytest_study, inifile: pytest.ini
plugins: xdist-1.22.0
collected 1 item # 搜集到的测试用例数量 test_cont.py F # F 代表测试出错, [100%] # 测试完成率 =============================================================== FAILURES ================================================================
_______________________________________________________________ test_inc ____________________ # 测试模块名 _______________________________________ def test_inc():
> assert inc(10) == 20 # 报错的位置
E assert 11 == 20 # 报错原因
E + where 11 = inc(10) # 错误的来源 test_cont.py:6: AssertionError
======================================================= 1 failed in 0.04 seconds =============# 测试结果 =======================================

pytest 测试代码中抛出的异常

cont_test.py
import pytest def inc(x):
return x + 1 def test_inc():
assert inc(10) == 11 def f():
raise SyntaxError() def test_f():
with pytest.raises(SyntaxError):
f()

运行pytest

an@hosta:~/PycharmProjects/testproject/pytest_study$ pytest
========================================================== test session starts ==========================================================
platform linux -- Python 3.5.2, pytest-3.3.2, py-1.5.2, pluggy-0.6.0
rootdir: /home/an/PycharmProjects/testproject/pytest_study, inifile: pytest.ini
plugins: xdist-1.22.0
collected 2 items # 两个测试用例 cont_test.py .. # 两个 . 表示都测试成功了 F 表示失败 [100%] ======================================================= 2 passed in 0.01 seconds ========= #测试结果 =======================================

另一种方式运行多个测试。构造一个 测试类 里面包含多个测试用例

cont_test.py
import pytest
class TestClass:
def test_one(self):
x = "this"
assert x != "that" def test_two(self):
x = "hello"
assert hasattr(x, "upper") def test_three(self):
with pytest.raises(IndexError):
raise IndexError

运行 pytest

运行pytest的退出码

Exit code 0:	All tests were collected and passed successfully
Exit code 1: Tests were collected and run but some of the tests failed
Exit code 2: Test execution was interrupted by the user
Exit code 3: Internal error happened while executing tests
Exit code 4: pytest command line usage error
Exit code 5: No tests were collected
指定测试用例失败次数失败之后,就停止测试

pytest -x 在第一次失败之后,就停止运行剩余的测试

pytest --maxfail=2 两次失败之后,就停止运行剩余测试

指定运行测试用例

目录结构
|---pytest_test
|
|---cont_test.py # 模块内容
cont_test.py import pytest def inc(x):
return x + 1 def test_inc():
assert inc(10) == 11 def f():
raise SyntaxError() @pytest.mark.slow
def test_f():
with pytest.raises(SyntaxError):
f() class TestClass:
def test_one(self):
x = "t"
assert x == "that" def test_two(self):
x = "hello"
assert hasattr(x, "pper") def test_three(self):
with pytest.raises(IndexError):
raise IndexError
  • 指定运行目录

    pytest pytest_test

  • 自动搜索运行本目录内的测试模块(以test开头或结尾)

    pytest_test$ pytest

  • 指定运行模块

    pytest_test$ pytest cont_test.py

  • 指定测试函数

    pytest_test$ pytest cont_test.py::test_inc

  • 指定测试类

    pytest_test$ pytest cont_test.py::TestClass

  • 指定测试方法

    pytest_test$ pytest cont_test.py::TestClass::test_one

  • 指定被mark的测试

    pytest_test$ pytest -m slow

将结果输出到 XML 文件

pytest --junitxml=/tmp/zz.xml

禁用pytest的扩展

pytest -p no:doctest -p no:django

方法二:
创建一个 pytest.ini 文件
pytest.ini
[pytest]
addopts = -p no:django -p no:forked -p no:xdist-1.22.0 -p no:celery
;禁用扩展

异常

捕获程序中故意引发的异常
def f():
raise SyntaxError() def test_f():
with pytest.raises(SyntaxError):
f()
指定测试失败的信息

def test_f():
with pytest.raises(SyntaxError, message='this is i expected error'):
pass —————————————————————————————— ------------------------------------------------ generated xml file: /home/an/haha.xml -------------------------------------------------
=============================================================== FAILURES ================================================================
________________________________________________________________ test_f _________________________________________________________________ def test_f():
with pytest.raises(SyntaxError, message='this is i expected error'):
> pass
E Failed: this is i expected error # 正是我们所希望失败 cont_test.py:17: Failed
================================================== 1 failed, 3 passed in 0.06 seconds =====
进一步限定我们所期望的异常,match使用的 python 中 re.search 方法进行匹配
def test_f():
with pytest.raises(ValueError, match=r'.?1'):
raise ValueError("a1")
# 正常

def test_f():
with pytest.raises(ValueError, match=r'.?1'):
raise ValueError("z3")
_____________________________________________ ============================================================== FAILURES ================================================================
________________________________________________________________ test_f _________________________________________________________________ def test_f():
with pytest.raises(ValueError, match=r'.?1'):
> raise ValueError("z3")
E ValueError: z3 cont_test.py:17: ValueError During handling of the above exception, another exception occurred: def test_f():
with pytest.raises(ValueError, match=r'.?1'):
> raise ValueError("z3")
E AssertionError: Pattern '.?1' not found in 'z3' # 匹配失败 cont_test.py:17: AssertionError
================================================== 1 failed, 3 passed in 0.10 seconds ============

pytest 单元测试的更多相关文章

  1. Pytest单元测试框架-测试用例运行规则

    1.Pytest测试用例运行规则 在pytest单元测试框架下面执行用例,需要满足以下几个特点: 1. 文件名以test_*.py开头或者*_test.py 2. 测试类.测试函数以test开头 3. ...

  2. Pytest单元测试框架-Pytest环境安装

    unittest是python自带的单元测试框架,它封装好了一些校验返回的结果方法和一些用例执行前的初始化操作,使得单元测试易于开展,因为它的易用性,很多同学也拿它来做功能测试和接口测试,只需简单开发 ...

  3. Pytest单元测试框架:插件-allure-pytest环境搭建并在本地生成一个测试报告

    之前写了allure-pytest的官方文档啃的内容,有些交流的朋友,实践起来没什么头绪,所以就有了这篇文章,也给自己填个坑 第一步:搭建Allure.JDK环境 1. 搭建JDK环境 不装jdk你会 ...

  4. Pytest单元测试框架之简单操作示例

    前言: Pytest是第三方单元格测试框架,更加简单,灵活,而且提供了更多丰富的扩展: Pytest与UnitTest框架的区别 UnitTest测试用例执行顺序是依照ascii码执行,而Pytest ...

  5. Pytest 单元测试框架

    1.pytest 是 python 的第三方单元测试框架,比自带 unittest 更简洁和高效 2.安装 pytest pip install pytest 3.验证 pytest 是否安装成功 p ...

  6. Pytest单元测试框架——Pytest+Allure+Jenkins的应用

    一.简介 pytest+allure+jenkins进行接口测试.生成测试报告.结合jenkins进行集成. pytest是python的一种单元测试框架,与python自带的unittest测试框架 ...

  7. Pytest单元测试框架-学习

    pytest: Python的一个单元测试框架,基于UnitTest二次开发,语法上更加简洁,可以用来做Python开发项目的单元测试,UI自动化.接口自动化测试等,有很多的插件访问Pytest插件汇 ...

  8. Pytest单元测试框架之FixTure基本使用

    前言: 在单元测试框架中,主要分为:测试固件,测试用例,测试套件,测试执行及测试报告: 测试固件不难理解,也就是我们在执行测试用例前需要做的动作和测试执行后的需要做的事情: 比如在UI自动化测试中,我 ...

  9. pytest单元测试框架

    一.安装方式 1.安装命令:pip install pytest 2.html安装插件:pip install pytest -html 二.pytest执行指定测试用例 1.思想:通过对测试用例进行 ...

随机推荐

  1. js四则运算增强功能

    目录 背景 具体代码 背景 项目中用到浮点数,Int. 在 js中 Number类型比较古怪, 加上牵涉到财务软件, 前台js实时运算等. 有时候会出现精确度的问题 , 公共方法中有好事者写的方法. ...

  2. OpenJudge 兔子与樱花

    [题解] 求任意两点间的最短路径.此题数据量较小,用Floyd算法,时间复杂度为O(n^3). 参考https://blog.csdn.net/qq_34594236/article/details/ ...

  3. Spring MVC 处理异常

    SpringMVC处理异常: 1 使用@ExceptionHandler注解 只有ModelAndView可以携带错误信息 @ExceptionHandler public ModelAndView ...

  4. 关于Vue实例的生命周期created和mounted的区别

    什么是生命周期 Vue实例有一个完整的生命周期,也就是从开始创建.初始化数据.编译模板.挂载Dom.渲染→更新→渲染.卸载等一系列过程,我们称这是Vue的生命周期.通俗说就是Vue实例从创建到销毁的过 ...

  5. 基于HAProxy+Keepalived高可用负载均衡web服务的搭建

    一 原理简介 1.HAProxyHAProxy提供高可用性.负载均衡以及基于TCP和HTTP应用的代理,支持虚拟主机,它是免费.快速并且可靠的一种解决方案.HAProxy特别适用于那些负载特大的web ...

  6. idea error:Command line is too long

    今天在正在本地运行的项目中写了一个无关项目的测试类,执行main函数时报错如下: 解决方案: 找到项目根目录下的.idea/workspace.xml,添加内容: <component name ...

  7. WPF 自定义分页控件一

    一:右键添加新建项,选择新建自定义控件,命名为:KDataPager public class KDataPager : Control { static KDataPager() { Default ...

  8. day2----python的基本类型

    本文档的大致内容:(python使用版本3.6.4) 1 数字--int 2 布尔--bool 3 字符串--str 4 元祖--() 5  列表---['a','b'] 6 字典--{} 运算符: ...

  9. Debug版本正常运行,Release版本编译通过但运行崩溃

    解决这个问题之前,第一个想的是Debug版本和Release版本有什么区别 Debug版: 经过编译器编译出的项目.exe文件大,而且生成的二进制命令没有经过编译器的优化.项目中包含着丰富的调试信息, ...

  10. 使用NetBox实现ASP网页封装为EXE教程

    简单的形容就是把ASP文件打包 成一个EXE文件,并且不需要在调试的机器上安装IIS即可正常调试.如果按照说明书来操作的话,观看比较繁琐,本人为方便大家使用,现制作一个简单的使用教程. 封装过程 1. ...