基础环境
python 版本:
PS D:\report> python -V
Python 3.8.4rc1
安装pytest
PS D:\report> pip install -U pytest
Collecting pytest
Downloading pytest-6.0.2-py3-none-any.whl (270 kB)
|████████████████████████████████| 270 kB 731 kB/s
Requirement already satisfied, skipping upgrade: colorama; sys_platform == "win32" in d:\install\python38\lib\site-packages (from pytest) (0.4.3)
Collecting atomicwrites>=1.0; sys_platform == "win32"
Collecting iniconfig
Downloading iniconfig-1.0.1-py3-none-any.whl (4.2 kB)
Collecting pluggy<1.0,>=0.12
Downloading pluggy-0.13.1-py2.py3-none-any.whl (18 kB)
Collecting toml
Downloading toml-0.10.1-py2.py3-none-any.whl (19 kB)
Collecting more-itertools>=4.0.0
Downloading more_itertools-8.5.0-py3-none-any.whl (44 kB)
|████████████████████████████████| 44 kB ...
Collecting attrs>=17.4.0
Downloading attrs-20.2.0-py2.py3-none-any.whl (48 kB)
Collecting packaging
Downloading packaging-20.4-py2.py3-none-any.whl (37 kB)
Collecting py>=1.8.2
Downloading py-1.9.0-py2.py3-none-any.whl (99 kB)
|████████████████████████████████| 99 kB 2.7 MB/s
Requirement already satisfied, skipping upgrade: six in d:\install\python38\lib\site-packages (from packaging->pytest) (1.15.0)
Downloading pyparsing-2.4.7-py2.py3-none-any.whl (67 kB)
|████████████████████████████████| 67 kB 2.8 MB/s
Installing collected packages: atomicwrites, iniconfig, pluggy, toml, more-itertools, attrs, pyparsing, packaging, py, pytest
Successfully installed atomicwrites-1.4.0 attrs-20.2.0 iniconfig-1.0.1 more-itertools-8.5.0 packaging-20.4 pluggy-0.13.1 py-1.9.0 pyparsing-2.4.7 pytest-6.0.2 toml-0.10.1
编写测试脚本
简单脚本
只是很简单的测试脚本,创建test_sample.py
# -*- coding: utf-8 -*-
# @Time : 2020/09/16
# @Author : root@2honey
# @File : test_sample.py
def func(x):
return x + 1
def test_answer():
assert func(3) == 5
类中多用例
# -*- coding: utf-8 -*-
# @Time : 2020/09/16
# @Author : root@2honey
# @File : test_sample.py
class TestClass(object):
def test_one(self):
x = "this"
assert 'h' in x
def test_two(self):
x = "hello"
assert hasattr(x, 'check')
使用fixture
说明:
fixture区别于unnitest的传统单元测试(setup/teardown)有显著改进:
-
有独立的命名,并通过声明它们从测试函数、模块、类或整个项目中的使用来激活。
-
按模块化的方式实现,每个fixture都可以互相调用。
-
fixture的范围从简单的单元测试到复杂的功能测试,可以对fixture配置参数,或者跨函数function,类class,模块module或整个测试session范围。
查看内置fixture
pytest --fixtures
使用自定义fixture
# -*- coding: utf-8 -*-
# @Time : 2020/09/16
# @Author : root@2honey
# @File : test_sample.py
import pytest
@pytest.fixture()
def test1():
a = 'leo'
return a
def test2(test1):
assert test1 == 'leo'
if __name__ == '__main__':
pytest.main('-q test_fixture.py')
以下是几条主的命名规则:
- 测试文件应当命名为 test_.py或者_test.py
- 测试函数、测试类方法应当命名为test_
- 测试类应当命名为Test.