pytest是一个第三方单元测试框架,更加简单,灵活,而且提供了更加丰富的扩展,弥补了unittest在做web自动化测试时的一些不足。
1, pytest简单例子
pytest支持pip安装
①:创建以test开头的文件名test_pytest.py
def inc(x):
return x + 1
def test_answer():
assert inc(3) == 5
②:切换到test_pytest.py所在目录,执行命令pytest
结果如下(分为两部分截图):
通过上面的例子,是不是可以感受到pytest的优点,它更加简单。首先,不必像unittest一样必须创建测试类;其次,使用assert断言也比使用unittest提供的断言方法更加简单。
不过,它也有自己的规则:测试文件必须以"test"开头,这也是在执行pytest命令时并没有指定测试文件也可以执行test_pytest.py文件的原因,因为该文件以“test”开头。
那么能否可以通过main()方法执行测试呢?当然可以,pytest也提供了main()方法,如下创建test_pytest1.py:
import pytest
def inc(x):
return x + 1
def test_answer():
assert inc(3) == 5
if __name__ == '__main__':
pytest.main()
结果如下:
这里可以看到有两个测试结果,一个是test_pytest.py中的,一个是test_pytest1.py中的,那么我只是直接执行了test_pytest1.py(没有使用pytest xxx.py方法执行文件),那么为什么会两个测试文件都会执行呢?????????????????
因为main()方法默认执行当前文件夹内所有以“test”开头的文件内的以test开头函数
2 pytest的基本使用方法
这里我们主要介绍pytest与unittest之间的不同
2.1 断言
在unittest单元测试框架中提供了丰富的断言方法,如:assertEqual(),assertIn(),assertTrue(),assertIs()等方法。pytest单元测试框架并没有提供专门的断言方法,而是直接使用Python的assert进行断言。
创建test_assert.py
import pytest
# 计算两个数的和
def add(a, b):
return a + b
# 判断素数
def is_prime(n):
if n < 1:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
# 测试相等
def test_add_1():
assert add(3, 4) == 7
# 测试不相等
def test_add_2():
assert add(17, 22) != 50
# 测试大于或等于
def test_add_3():
assert add(17, 22) <= 50
# 测试小于或等于
def test_add_4():
assert add(17, 22) >= 38
# 测试包含
def test_in():
a = "hello"
b = "he"
assert b in a
# 测试不包含
def test_not_in():
a = "hello"
b = "hi"
assert b not in a
# 判断是否为True
def test_true_1():
assert is_prime(13)
# 判断是否为True
def test_true_2():
assert is_prime(7)
# 判断是否不为True
def test_true_3():
assert not is_prime(4)
# 判断是否不为True
def test_true_4():
assert is_prime(6) is not True
# 判断是否为False
def test_false_1():
assert is_prime(8) is False
if __name__ == '__main__':
pytest.main()
以上例子展示了pytest断言的方法,借助python的运算符号和关键字即可轻松实现不同数据类型的断言
2.2 Fixture
Fixture通常用来对测试方法,测试函数,测试类和整个测试文件进行初始化或还原测试环境。创建test_fixture.py文件。
def mul(a, b):
return a * b
# ==============Fixture================
def setup_module(module):
print("setup_module---------->")
def teardown_module(module):
print("teardown_module-------->")
def setup_function(function):
print("setup_function--------->")
def teardown_function(function):
print("teardown_function------>")
def setup():
print("setup----------->")
def teardown():
print("teardown-------->")
# =======测试用例=======
def test_mul_3_4():
print("test_mul_3_4")
assert mul(3, 4) == 12
def test_mul_a_3():
print("test_mul_a_3")
assert mul("a", 3) == "aaa"
if __name__ == '__main__':
import pytest
pytest.main()
这里主要用到的是模块级别和函数级别的Fixture
① setup_module/teardown_module:在当前文件中,在所有测试用例执行之前与之后执行
② setup_function/teardown_function:在每个测试函数之前与之后执行
③ setup/teardown:在每个测试函数之前与之后执行。这两个方法同样可以作用于类方法
结果如下:
pytest是支持使用测试类的,同样必须以"Test"开头,注意首字母要大写。在引入测试类的情况下,Fixture的用法如下:创建test_fixture1.py
def mul(a, b):
return a * b
class TestMul():
# ====fixture====
@classmethod
def setup_class(cls):
print("setup_class--------->")
@classmethod
def teardown_class(cls):
print("teardown_class-------->")
def setup_method(self, method):
print("setup_method--------->")
def teardown_method(self, method):
print("teardown_method------>")
def setup(self):
print("setup------->")
def teardown(self):
print("teardown------>")
# 测试用例
def test_num_7_8(self):
print("test_num_7-8")
assert mul(7, 8) == 56
def test_num_d_5(self):
print("test_num_d_5")
assert mul("d", 5) == "ddddd"
这里主要用到类级别和方法级别的Fixture:
①:setup_class/teardown_class:在当前测试类的开始和结束时执行
②:setup_method/teardown_method:在每个测试方法开始与结束时执行
③:setup/teardown:在每个测试方法开始与结束时执行,同样可以作用于测试函数
结果如下:
2.3 参数化
当一组测试用例有固定的测试数据时,就可以通过参数化的方式简化测用例的编写。pytest本身是支持参数化的,不需要额外安装插件。创建test_parameterize.py
import pytest
import math
# pytest参数化
@pytest.mark.parametrize(
"base, exponent, expected",
[
(2, 2, 4),
(2, 3, 8),
(1, 9, 1),
(0, 9, 0)
],
ids=["case1", "case2", "case3", "case4"]
)
def test_pow(base, exponent, expected):
assert math.pow(base, exponent) == expected
其用法与unittest的参数化插件类似,通过pytest.mark.parametrize()方法设置参数。
"base, exponent, expected" 用来定义参数的名称。通过数组定义参数时,每一个元组都是一条测试用例使用的测试数据。ids参数默认为None,用于定义测试用例的名称。
pow用来计算x的y次方的值。
运行结果如下:
"-v"参数增加了测试用例冗长。不设置id参数的结果如下:
2.4 运行测试
pytest提供了丰富的参数运行测试用例,在前面的例子中已经使用到了一些参数,例如,“-s”参数用于关闭捕捉,从而打印输出信息,“-v”参数用于增加测试用例冗长。
pytest提供的参数比较多,下面只介绍常用的参数
2.4.1 运行名称中包含某字符串的测试用例
这里使用-k参数指定测试用例中包含add字符串的用例
2.4.2 减少测试运行冗长
这次运行减少了很多日志的输出,“-q”用来减少测试运行的冗长,也可以使用“-quiet”代替
2.4.3 如果出现一条测试用例失败,则退出测试
在test_assert.py文件中添加了如下测试用例,放到第一个测试用例之后,只为了看到效果:
def test_fail():
assert is_prime(9) is False
这个参数一般用于测试调试阶段,当出现一条失败的测试用例时,应该先通过调试让这条测试用例运行通过,而不是继续执行后面的测试用例
2.4.4 运行测试目录
测试目录既可以指定相对路径,如上,也可以执行绝对路径
2.4.5 指定特定类或方法执行
这里指定运行test_fixture1.py文件中TestMul类下的test_num_7_8()方法,文件名、类名和方法名之间使用双冒号"::"分割开
2.4.6 通过main()方法运行测试
创建test_main.py文件,在文件中通过数组指定参数,每个参数为数组中的一个元素如下:
import pytest
if __name__ == '__main__':
pytest.main(["-s", "./test_assert"])
结果如下:
2.5 生成测试报告
pytest支持生成多种格式的测试报告
2.5.1 生成JUnit XML文件
XML类型的日志主要用于存放测试结果,方便我们利用里面的数据定制自己的测试报告。
结果如下:
2.5.2 生成在线测试报告
我测试时一直有出现一直卡在 “sending information to Paste Service”这里的情况,多测试几次。。。
打开链接,结果如下:
你可以只将失败的报告发送到pastebin服务器, pytest ./test_assert --pastebin=failed
2.5.3 生成html测试报告文件
需要安装pytest的插件,pytest-html,支持pip安装
结果如下:
2.6 conftest.py
conftest.py是pytest特有的本地测试配置文件,既可以用来设置项目级别的Fixture,也可以用来导入外部插件,还可以用来指定钩子函数。
①:创建test_config/conftest.py测试配置文件如下:
import pytest
# 设置测试钩子
@pytest.fixture()
def test_url():
return "http://www.baidu.com"
②:创建test_config/test_sub.py测试用例文件
def test_baidu(test_url):
print(test_url)
这里创建的函数可以直接调用conftest文件中的test_url()钩子函数,结果如下:
注意:conftest值作用于其所在的目录以及子目录
3 pytest扩展
pytest可以扩展非常多的插件来实现各种功能,这里介绍几个对做web自动化非常有用的插件
3.1 pytest-html
前面已经介绍过,在这里不做说明了
3.2 pytest-returnfailures
需要使用pip安装
创建test_returnfailures文件
def test_fail_return():
assert 2 + 2 == 5
结果如下:
通过 --reruns参数设置测试用例运行失败后的重试次数
3.3 pytest-parallel扩展
首先pip安装
pytest-parallel扩展可以实现测试用例的并行执行
创建文件如下:
from time import sleep
def test_1():
sleep(3)
def test_2():
sleep(4)
def test_3():
sleep(7)
不使用线程运行测试用例时间如下
使用多线程方式:pytest -q test_parallel.py --tests-per-worker auto, "auto"表示自动分配,但是测试不能在windows上执行,故不做结果展示
pytest-parallel的更多用法
pytest --worker 2
pytest --worker auto
pytest --tests-per-worker 4
pytest --tests-per-worker auto
pytest --workers 2 --tests-per-worker auto