pytest学习笔记

pytest能做什么?

1、支持简单的单元测试与复杂的功能测试
2、pytest结合Requests实现接口测试;结合selenium、appium实现自动化功能测试
3、pytest结合allure集成jenkins中实现持续集成

命名方法

1、文件以 test_ 开头 或者 _test 结尾
2、类以 Test 开头
3、方法以 test
开头
测试类中不能创造构造函数

断言

assert <表达式>
assert <表达式>, <描述>

测试框架结构

setuo/teardown == setup_method/teardown_method
setup_class/module/class/function / teardown_class/module/class/function

参数化用例

@pytest.mark.parametrize(“形参”, [实参], ids=[a, b, c, d……])
单参数,多参数(参数需要一组一组传递)
用例重命名 通过ids进行命名
笛卡尔乘积:使用两次parametrize

标记测试用例

在用例方法上加 @pytest.mark.标签名
执行某个标签的测试
pytest -s 项目.py -m = 标签名
创建自定义标签 : 创建文件pytest.ini

[pytest]
markers = 标签名

执行测试用例

命令行执行测试用例:pytest xx.py ::类名::方法名

fixture用法

在要被当成fixture函数上添加@pytest.fixture,之后在需要进行fixture的测试用例当中传入fixture函数名

@fixture
def login():
    print("login!!")

def test_shop(login):
    print("shopping!!")

scope参数:作用域, 默认为function

yield

用于fixture函数内,yield前表示setuo操作,后表示teardown操作

@pytest.fixture()
def login():
    print("login!!")
    yield
    print("out!!")

def test_login(login):
    print("成功登入!")

yield相当于return,可以返回参数

import pytest

@pytest.fixture()
def login():
    print("login!!")
    token = "12321321"
    yield token
    print("out!!")

def test_login(login):
    print(f"token = {login}")
    print("成功登入!")

数据共享

conftest.py
全局配置文件,可以将一些函数放在里面,在项目中可以直接调用