Pytest

Pytest

什么是Pytest?

pytest 是一个自动化框架,是基于unittest 进行二次开发封装而来的一个框架。他可以作用于所有类别的自动化测试,比如UI自动化、接口自动化、单元测试等。他是个命令行工具,意味着我们在使用它时,需要输入命令行执行。

怎么使用?

安装

sudo pip3 install pytest
sudo pip3 install allure-pytest # allure 测试报告插件
sudo pip3 install pytest-rerunfailures # 失败重跑的插件
sudo pip3 install pytest-timeout # 执行超时的插件
sudo pip3 install pytest-html # pytest 的html测试报告的插件

运行

默认运行机制

在批量执行之前,我们需要了解pytest的默认运行机制,即没有任何人为定制的规则时,pytest的缺省规则:

  • pytest 会在当前目录以及子目录下递归查找所有test_*.py或者_test.py 的文件(以test开头或者test结尾的py文件),将其当做测试文件

  • 在这些文件中,pytest会将以下的方法当做测试用例

    • 不在类中定义的以test开头的方法
    # test_py.py
    def sub(x, y):
        return x - y
    
    def add(x, y):
        return x + y
    
    def test_add():
        assert add(1, 2) == 3
    
    def test_sub():
        assert sub(5, 2) == 3
    

    在当前目录下终端输入 pytest -v,结果如下:

    • 在以Test开头的类中(不包含__init__方法),以test开头的方法
      在上面的test_py.py文件中,增加一个类class,里面的方法如下
     class TestWithInit:
         def __init__(self):
             print('pytest 不会加载这个类')
     
         def add_2(self, x, y):
             print('执行add_2')
             return x + y
     
         def test_add_2(self):
             assert self.add_2(1, 2) == 3
    

    在当前目录下终端输入 pytest -v,结果如下:

    当把__init__方法注释掉后,执行结果如下:

    image

    • pytest 支持使用unittest模式编写的用例(兼容unittest框架)
  1. pytest 可以通过 -k 参数进行匹配指定规则的用例,比如 pytest -k "album" ,pytest 会加载方法命中包含“alubm”关键字的方法
  2. --html=path.html 指定测试报告为html,后面跟报告的路径(需要有pytest-html 库)
  3. --reruns 2 设置失败重跑2次(需要有pytest-rerunfilures 库)

夹具

Pytest的夹具是用装饰起pytest.fixture来表示。pytest.fixture可以理解为unittest的setUptearDown方法,会在用例执行之前和结束后运行的方法。
但是fixture相对于unittest有一些独有的特点。
他们之间的优缺点可以表示在以下方面进行体现:

  1. fixture写法更简单。在一个方法中可以将setUp和TearDown里面的业务操作体现出来
  2. fixture作用域更明显。可以通过fixtures的scope参数定义作用域(module/session/class/function)
    • module:每个py文件开始执行一次
    • session:每次会话执行一次
    • class:每个测试类执行一次
    • function:每条用例执行一次
  3. fixture命名可以更加灵活,不需要指定方法名字,没有局限性
posted @ 2021-03-23 16:31  Hiraly  阅读(368)  评论(0)    收藏  举报