首页 技术 正文
技术 2022年11月23日
0 收藏 910 点赞 3,024 浏览 1350 个字

一、安装和启动

1.1 安装pytest
1. 键入Ctrl+R,打开cmd,输入命令至python环境下(本机:D:\Python27>)
2. 在python环境下运行下面的命令即可安装pytest
#pip install -U pytest
3. 检查安装的pytest的版本信息是否正确
#pytest –version

pytest_1安装和启动

1.2第一个测试Demo
1. 创建一个只有4行代码的简单函数:

def fun(x):
return x+1
def test_answer():
assert fun(3)==5

2. 使用pytest运行,首先需进入到文件所在位置(本机:F:\study\ Interface_automation\Interface automation),然后键入命令

#pytest jsonDemo.py
pytest_1安装和启动

1. 如上图所示,这个结果是失败的,因为func(3)的返回值不是5

1.3运行多个测试
pytest会运行当前目录及子目录下所有以test_*.py和*_test.py命名的文件,文件匹配方式遵循Standard test discovery rules

1.4判断是否发生了指定的异常
1. 使用raises可以判断代码是否抛出了异常:

import pytest
def f():
raise SystemExit(1)def test_mytest():
with pytest.raises(SystemExit):
f()

2. 使用“quiet”模式来执行这个测试:如下图所示

pytest_1安装和启动

1.5 将多个测试用例放在一个class中
1. 当需要开发多个测试用例的时候,可以将他们放在同一个class中,pytest可以简单的创建包含多个测试用例的class:

class TestClass(object):
def test_one(self):
x="this"
assert 'h' in x def test_two(self):
x='hello'
assert hasattr(x,'check')

2. pytest根据Conventions for Python test discovery查找所有的测试用例,所以可以找到所有以**test_**开头的测试函数,我们可以通过文件名来直接运行整个模块:

pytest_1安装和启动

3. 如上图所示,第一个测试用例passed,第二个测试用例failed,可以直观的观察到测试用例中进行判断的中间值,这样可以帮助理解测试用例失败的原因。

1.6 为测试用例创建唯一的临时文件夹
1. pytest提供Builtin fixtures/function arguements来创建任意的资源,比如一个具有唯一的临时文件夹:

def test_needsfiles(tmpdir):
print tmpdir
assert 0

2. 如果函数的签名中(函数签名包括函数的参数和返回值,以及参数的封送顺序等等)包含参数tmpdir,pytest就会在执行测试用例之前查找并调用特定的fixture创建所需资源,在本例中,pytest会创建一个unique-per-test-invocation临时文件夹:

pytest_1安装和启动

关于tmpdir的更多信息请参好Temporary directories and files通过下面的命令可以查看所有内置的pytest fixture:
键入命令:#pytest –fixtures,如下图所示

 pytest_1安装和启动

下一篇: python一些包
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,026
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,517
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,364
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,145
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,779
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,856