手把手教pytest自动化测试框架(一)

2022-02-15

1.安装和启动

1.1安装pytest

1.在python环境下运行

pip install ‐U pytest

2.检查pytest的版本信息

❯ python3 -m pytest --version
pytest 7.0.0

1.2创建第一个测试

创建一个只有4行代码的简单函数
test_sample.py

def func(x):
	return x + 1

def test_answer():
	assert func(3) == 5

在test_sample.py同级目录下直接执行pytest,结果如下:

❯ python3 -m pytest
============================= test session starts ==============================
platform darwin -- Python 3.8.2, pytest-7.0.0, pluggy-1.0.0
rootdir: /Users/lihui/Desktop/xxx/xxx
collected 1 item

test_sample.py F                                                         [100%]

=================================== FAILURES ===================================
_________________________________ test_answer __________________________________

    def test_answer():
>   	assert func(3) == 5
E    assert 4 == 5
E     +  where 4 = func(3)

test_sample.py:5: AssertionError
=========================== short test summary info ============================
FAILED test_sample.py::test_answer - assert 4 == 5
============================== 1 failed in 0.04s ===============================

结果失败,因为func(3)的返回值不是5

1.3运行多个测试

pytest会运行当前目录下及子目录下的所有以test_.py和_test.py命名的文件

1.4判断是否发生了指定的异常

使用raises可以判断代码是否抛出了异常:
test_sysexit.py

import pytest

def f():
	raise SystemExit(1)

def test_mytest():
	with pytest.raises(SystemExit):
		f()

使用"quiet"模式来执行这个测试

❯ python3 -m pytest -q test_sysexit.py
.                                                  [100%]                                                              

1 passed in 0.01s

1.5将多个测试用例放在一个class中

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

class TestClass(object):
	def test_one(self):
		x = "this"
		assert 'h' in x

	def test_two(self):
		x = 'hello'
		assert hasattr(x, 'check')

直接运行:

❯ python3 -m pytest -q test_class.py
.F                                                    [100%]
=================================== FAILURES ===================================
______________________________ TestClass.test_two ______________________________

self = <test_class.TestClass object at 0x10b60bee0>

    def test_two(self):
    	x = 'hello'
>   	assert hasattr(x, 'check')
E    AssertionError: assert False
E     +  where False = hasattr('hello', 'check')

test_class.py:8: AssertionError
=========================== short test summary info ============================
FAILED test_class.py::TestClass::test_two - AssertionError: assert False
1 failed, 1 passed in 0.04s

第一个测试用例pass,第二个测试用例failed,可以直观的看到测试用例中进行判断的中间值,很好理解测试用例失败的原因。