pytest简介

pytest是一个非常成熟的全功能的python测试框架,主要特点有以下几点:

  • 简单灵活,容易上手,文档丰富;
  • 支持参数化,可以更细力度地控制需要测试的测试用例
  • 能够支持简单的单元测试和复杂的功能测试,还可以用来做selenium/appnium等自动化测试,接口自动化测试(pytest+requests);
  • pytest具有很多第三方插件,并且可以自定义扩展,比较好用的如pytest-selenium(集成selenium),pytest-html(测试报告生成),pytest-rerunfailures(失败case重复执行),pytest-xdist(多cpu分发)等;
  • 测试用例的skip和xfail处理
  • 可以很好的和CI工具结合,例如Jenkins

编写规则

  • 测试文件以test开头(以test结尾也可以)
  • 测试类以test开头,并且不能带有init方法
  • 测试函数以test开头
  • 断言使用基本的assert即可

Console参数介绍

  • -v 用于显示每个测试函数的执行结果
  • -q 只显示整体测试结果
  • -s 用于显示测试函数中print()函数输出
  • -x,--exitfirst,在第一个错误或测试失败时立即退出
  • -h 帮助

执行测试

配置Pycharm执行

  • Tools > Python Integrated tools > Default test runner

main方法

  • pytest.main(['-s','-v','test_01.py'])

命令行

pytest查找测试策略

  • 默认情况下,pytest会递归查找当前目录下所有以test开始或结尾的python脚本
  • 执行文件内所有以test开始或结束的函数和方法

pytest指定测试函数

第一种,显示指定函数名.通过::标记

test_no_mark.py::test1

第二种,使用模糊匹配,使用-k选项表示

pytest -k func1 test_no_mark.py

第三种,使用pytest.mark在函数上进行标记

  1. 在测试函数上加上@pytest.mark.do 或者@pytest.mark.undo
  2. 创建pytest.ini配置文件
    [pytest]
    markers=
    do: do
    undo: undo
  3. 在命令行启动pytest -m do test01.py

pytest参数化

在测试函数上面加上@pytest.mark.parametrize(paramname,paramvalue)

import pytest
testdata= [(1,2,3),(2,3,4),(7,8,9)] @pytest.mark.parametrize('a,b,expect',testdata) def test2(a,b,expect): result =a+b assert result == expect

 pytest fixture

  • 定义fixture跟定义普通函数差不多,唯一区别就是在函数上加个装饰器@pytest.fixture()
  • fixture命名不要以test开头,跟用例区分开,fixture是有返回值,没有返回值默认为None
  • 用例调用fixture的返回值,直接就是把fixture的函数名称当做变量名称

pytest setup和teardown

  • 模块级(setup_moudule/teardown_module)开始于模块始末,全局的
  • 函数级(setup_function/teardown_function)只对函数用例生效(不在类中)
  • 类级(setup_class/teardown_class)只在类中前后运行一次(在类中)
  • 方法级(setup_method/teardown_method)开始于方法始末(在类中)
  • 类里面的(setup/teardown)运行在调用方法的前后

pytest allure生成测试报告

pip install allure-pytest

allure用例描述

import allure
import pytest


@pytest.fixture(scope="session")
def login():
    print("用例先登录")


@allure.step("步骤1:点xxx")
def step_1():
    print("111")


@allure.step("步骤2:点xxx")
def step_2():
    print("222")


@allure.feature("编辑页面")
class TestEditPage():
    '''编辑页面'''

    @allure.story("这是一个xxx的用例")
    def test_1(self, login):
        '''用例描述:先登录,再去执行xxx'''
        step_1()
        step_2()
        print("xxx")

    @allure.story("打开a页面")
    def test_2(self, login):
        '''用例描述:先登录,再去执行yyy'''
        print("yyy")


if __name__ == '__main__':
    # 注意生成测试报告 必须在命令行执行

    # pytest --alluredir reports testcase/pytest/test6.py
    # allure serve reports
    pytest.main(['--alluredir', './report', '05 pytest allure生成测试报告.py'])

 pytest 用例依赖

@pytest.mark.dependency

posted @ 2020-10-07 15:13  大碗炸酱面  阅读(280)  评论(0编辑  收藏  举报