好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Pytest(1)安装与入门

pytest介绍

pytest是python的一种单元测试框架,与python自带的unittest测试框架类似,但是比unittest框架使用起来更简洁,效率更高。根据pytest的官方网站介绍,它具有如下特点:

非常容易上手,入门简单,文档丰富,文档中有很多实例可以参考 能够支持简单的单元测试和复杂的功能测试 支持参数化 执行测试过程中可以将某些测试跳过(skip),或者对某些预期失败的case标记成失败 支持重复执行(rerun)失败的 case 支持运行由 nose, unittest 编写的测试 case 可生成 html 报告 方便的和持续集成工具 jenkins 集成 可支持执行部分用例 具有很多第三方插件,并且可以自定义扩展  

安装pytest

一般接触一个新的框架,个人推荐使用 Virtual envwrapper这个虚拟环境,使得环境独立 有关 Virtual envwrapper的安装与使用后续再出文章,这里可自行百度

终端运行

(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 =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 文件

查看更多关于Pytest(1)安装与入门的详细内容...

  阅读:25次