pytest介绍 pytest是python的一种单元测试框架,与python自带的unittest测试框架类似,但是比unittest框架使用起来更简洁,效率更高。根据pytest的官方网站介绍,它具有如下特点: 非常容易上
pytest介绍
pytest是python的一种单元测试框架,与python自带的unittest测试框架类似,但是比unittest框架使用起来更简洁,效率更高。根据pytest的官方网站介绍,它具有如下特点:
安装pytest
一般接触一个新的框架,个人推荐使用virtualenvwrapper这个虚拟环境,使得环境独立
有关virtualenvwrapper的安装与使用后续再出文章,这里可自行百度
终端运行
(pytest_env) ➜ ~ pip3 install pytest查看版本
(pytest_env) ➜ ~ pytest --version快速开始
# test_sample.py 的内容def func(x):
return x + 1
def test_answer():
assert func(3) == 5
class TestClass(object):
def test_one(self):
x = "this"
assert 'h' in x
def test_two(self):
x = "hello"
assert hasattr(x, 'check')
然后进入当前目录,执行命令pytest
> pytest============================================= test session starts =============================================
platform darwin -- Python 3.7.6, pytest-6.2.1, py-1.10.0, pluggy-0.13.0
rootdir: /Users/jkc/PycharmProjects/pytestDoc
plugins: allure-pytest-2.8.6
collected 3 items
test_example.py F.F [100%]
================================================== FAILURES ===================================================
_________________________________________________ test_answer _________________________________________________
def test_answer():
> assert func(3) == 5
E assert 4 == 5
E + where 4 = func(3)
test_example.py:16: AssertionError
_____________________________________________ TestClass.test_two ______________________________________________
self = <test_example.TestClass object at 0x7fe3e6ff7990>
def test_two(self):
x = "hello"
> assert hasattr(x, 'check')
E AssertionError: assert False
E + where False = hasattr('hello', 'check')
test_example.py:26: AssertionError
=========================================== short test summary info ===========================================
FAILED test_example.py::test_answer - assert 4 == 5
FAILED test_example.py::TestClass::test_two - AssertionError: assert False
========================================= 2 failed, 1 passed in 0.04s =========================================
知识点
- 如果只执行 pytest ,会查找当前目录及其子目录下以test__*.py或*_test.py文件,找到文件后,在文件中找到以test开头函数或者Test开头的类并执行(当然,后续也可以自定义规则)
- 如果只想执行某个文件,可以pytest start.py
- 加上-q,就是显示简单的结果:pytest -q start.py
Pytest用例的设计原则
用Pytest写用例时候,一定要按照下面的规则去写,否则不符合规则的测试用例是不会执行的
- 文件名以test_*.py 文件和*_test.py
- 以test_开头的函数
- 以Test开头的类,不能包含__init__方法
- 以 test_ 开头的类里面的方法
- 所有的包 pakege 必项要有__init__.py 文件
去期待陌生,去拥抱惊喜。