pytest使用

发布时间 2023-10-31 16:11:37作者: 时间完全不够用啊

安装:pip install pytest

命名规则:.py文件和文件内方法都以 test_ 开头

注意:文件及文件夹命名不要与关键字重复

前置与后置函数:

module范围:

import pytestdemo
import requests


# 每一个模块都会执行
def setup_module():
    print("开始了!!!")


# 每一个模块都会执行
def teardown_module():
    print("结束了!!!")


def test_one():
    assert 1 == 1
    assert 1 != 2
    assert not 0
    assert 1 in (1, 2, 3)
    assert 1 not in (2, 3)
    assert 1 is 1
    assert 0 is not 1
    assert 1 >= 0
    assert 0 <= 1


if __name__ == '__main__':
    pytestdemo.main()  # 运行所有测试用例

 

function范围:

import pytestdemo
import requests


# 每一个函数都会执行
def setup_function():
    print("开始了!!!")


# 每一个函数都会执行
def teardown_function():
    print("结束了!!!")


def test_one():
    print("第一个!!!!")
    assert 1 == 1
    assert 1 != 2
    assert not 0
    assert 1 in (1, 2, 3)
    assert 1 not in (2, 3)
    assert 1 is 1
    assert 0 is not 1
    assert 1 >= 0
    assert 0 <= 1


if __name__ == '__main__':
    pytestdemo.main()  # 运行所有测试用例

 

class范围:

import pytestdemo
import requests


class TestClass:
    # 每一个类都会执行
    def setup_class(self):
        print("开始了!!!")

    # 每一个类都会执行
    def teardown_class(self):
        print("结束了!!!")

    def test_one(self):
        assert 1 == 1
        assert 1 != 2
        assert not 0
        assert 1 in (1, 2, 3)
        assert 1 not in (2, 3)
        assert 1 is 1
        assert 0 is not 1
        assert 1 >= 0
        assert 0 <= 1


if __name__ == '__main__':
    pytestdemo.main()  # 运行所有测试用例

 

method范围:

import pytestdemo
import requests


class TestClass:
    # 随类中的每一个方法执行
    def setup_method(self):
        print("开始了!!!")

    # 随类中的每一个方法执行
    def teardown_method(self):
        print("结束了!!!")

    def test_one(self):
        assert 1 == 1
        assert 1 != 2
        assert not 0
        assert 1 in (1, 2, 3)
        assert 1 not in (2, 3)
        assert 1 is 1
        assert 0 is not 1
        assert 1 >= 0
        assert 0 <= 1


if __name__ == '__main__':
    pytestdemo.main()  # 运行所有测试用例

 

fixture 自定义前置函数

1、自定义一个函数

2、添加注解 @pytest.fixture (默认是function级别)

3、将函数名放在想要实现前置的测试方法的形参中

设置 (autouse=True) 表示为所有函数进行添加前置

import pytest
import requests


# @pytest.fixture(scope="function")   # 默认的scope是function
@pytest.fixture(autouse=True)  # 设置为True默认配置到所有函数中去
def fun():
    print("开始!!!")


# def test_one(fun):   # 将函数名放进形参中将会在此函数执行前进行调用
def test_one():  # 将函数名放进形参中将会在此函数执行前进行调用
    assert 1 == 1
    assert 1 != 2
    assert not 0
    assert 1 in (1, 2, 3)
    assert 1 not in (2, 3)
    assert 1 is 1
    assert 0 is not 1
    assert 1 >= 0
    assert 0 <= 1

def test_tow():  # 将函数名放进形参中将会在此函数执行前进行调用
    assert 1 == 1
    assert 1 != 2
    assert not 0
    assert 1 in (1, 2, 3)
    assert 1 not in (2, 3)
    assert 1 is 1
    assert 0 is not 1
    assert 1 >= 0
    assert 0 <= 1


if __name__ == '__main__':
    pytest.main()  # 运行所有测试用例

yaml数据文件格式:

# 格式1
data:
  username: jack1
  password: 123qwe
  age: 21
  sex: 1

# 格式2
data_list: {username: jack1,password: 123qwe,age: 21,sex: 1}

# 格式3
students:
  - tom1
  - 123qwe
  - 22
  - 1

# 格式4
peoples:
  - name: john
    password: 213ewq
    age: 23
    sex: 1

# 格式5
people_list:
  -
    - jackson
    - 231ewq
    - 24
    - 1


# 格式6
params:
  - [1,5,00000000,adminQuery]

有什么用呢?

可以在 @pytest.mark.parametrize 中进行参数关联:

@pytest.mark.parametrize的使用:

1、单参数:

import pytest


# 单参数 a是key  后面是value
@pytest.mark.parametrize("a", ["b"])
def test_param(a):  # 形参中传入key
    print("测试!!")
    print(a)  # 打印key对应的value


# 单参数 a是key  后面是value   循环打印三个参数
@pytest.mark.parametrize("a", ["1", "2", "3"])
def test_param(a):  # 形参中传入key
    print("测试!!")
    assert a == '1'
    print(a)  # 打印key对应的value

2、多参数:

import pytest


# 多参数 一一对应,第一个参数"name,pwd"定义格式,第二个参数是列表或元组,按照"name,pwd"的格式定义
# 元组形式
@pytest.mark.parametrize("name,pwd", [("jack1", "123qwe"), ("jack2", "123qw1")])
def test_param1(name, pwd):  # 形参中传入key
    print("测试!!")
    print("name == " + name)  # 打印key对应的value
    print("pwd == " + pwd)  # 打印key对应的value
    print(f"用户【{name}】 的密码是【{pwd}】")


# 多参数 一一对应,第一个参数"name,pwd"定义格式,第二个参数是列表或元组,按照"name,pwd"的格式定义
# 列表形式 这里的 "name,pwd" 对应的是 [["jack1", "123qwe"]]  相当于使用 name, pwd = ["jack1", "123qwe"]
# 如果定义为 "name,pwd", ["jack2", "123qw1"] 相当于 name, pwd = "jack1", 则会报错,因为不支持这种赋值方式
@pytest.mark.parametrize("name,pwd", [["jack1", "123qwe"], ["jack2", "123qw1"]])
def test_param2(name, pwd):  # 形参中传入key
    print("测试!!")
    print("name == " + name)  # 打印key对应的value
    print("pwd == " + pwd)  # 打印key对应的value
    print(f"用户【{name}】 的密码是【{pwd}】")


def test_so():
    x, y = [1, 2]
    print(f"{x} --- {y}")

数据关联形式:

1、首先获取数据:

import yaml

def get_data():
    f = open("../config/data.yaml", encoding="utf8")
    data = yaml.safe_load(f)
    return data

2、数据关联

import pytest
import requests

from pytestdemo.utils.get_data import get_data


@pytest.mark.parametrize("page,pageSize,keyWords,operate", get_data()['params'])
def test_req(page,pageSize,keyWords,operate):
    url = f"http://localhost:8080/goodsType/list?page={page}&pageSize={pageSize}&keyWords={keyWords}&operate={operate}"
    res = requests.get(url)
    print("url === " + url)
    print(res.json())
    assert res.json()['code'] == 200
    assert res.json()['msg'] == 'success'
    assert res.json()['data']['content'][0]['gt_name'] == '饮料'
get_data()['params'] 从yaml数据文件中获取key为params的数据:
params:
  - [1,5,00000000,adminQuery]
然后将数据[1,5,00000000,adminQuery] 赋值给前面设置的 page,pageSize,keyWords,operate 赋值时一 一对应