pytest是python的一种单元测试框架,与python自带的unittest测试框架类似,但是比unittest框架使用起来更简洁,效率更高。根据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 =========================================
test__*.py
或 *_test.py
文件,找到文件后,在文件中找到以 test
开头函数或者Test
开头的类并执行(当然,后续也可以自定义规则)pytest start.py
-q
,就是显示简单的结果:pytest -q start.py
用Pytest写用例时候,一定要按照下面的规则去写,否则不符合规则的测试用例是不会执行的
test_*.py
文件和*_test.py
test_
开头的函数Test
开头的类,不能包含__init__
方法__init__.py
文件发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/166359.html原文链接:https://javaforall.cn