首页 > 其他分享 >【pytest】内置fixture之request

【pytest】内置fixture之request

时间:2022-08-21 22:44:06浏览次数:88  
标签:fixture sp request pytest print id

  • 前言:request 是 pytest 的内置 fixture , "为请求对象提供对请求测试上下文的访问权,并且在fixture被间接参数化的情况下具有可选的“param”属性。"
  • 1、request.param
    • 前面讲fixture参数化的时候,有接触到 "request.param" 用于获取测试的请求参数。
    • 使用场景:UI自动化中,我们测试兼容性,分别使用不同浏览器执行用例
import pytest

brower = ["google","Firfox"]

@pytest.fixture(scope="function",params=brower)
def brower(request):
    return request.param

def test_001(brower):
    print(brower)

#运行结果
platform win32 -- Python 3.7.3, pytest-6.2.3, py-1.10.0, pluggy-0.13.1
baseurl: http://49.235.92.12:7005
rootdir: H:\pytest练习, configfile: pytest.ini
plugins: metadata-2.0.2, allure-pytest-2.8.6, base-url-1.4.2, forked-1.4.0, html-3.1.1, repeat-0.9.1, xdist-2.5.0
collected 2 items

test_param.py .google
.Firfox
  • 2、request.config
    • request.config 是获取测试的配置文件参数
    • 使用场景:执行测试时,如果我们不传 --host就使用默认,如果传--host就使用传的值;我们可以根据获取的get_url不同,执行不同的用例,
    • 例如:
      • 测试环境可以执行所有的用例,生产环境我们只能执行查询的功能,增删改不能执行,于是我们可以通过获取到的get_url作为条件判断是否执行。
    • 2.1:先使用钩子函数注册命令行参数,使用fixtrue获取命令行参数
# conftest.py
import pytest

# 注册命令行参数
def pytest_addoption(parser):
    parser.addoption(
        "--host",
        action = "store",
        default="http://127.0.0.1:8000",
        help = 'test base url'
    )

# 获取命令行参数
@pytest.fixture()
def get_host(request):
    return request.config.getoption("--host")
  • 2.2:根据执行时,输入的命令行参数,执行部分用例

    • 执行过程中,不传入--host,使用默认值
    • 执行过程中,传入--host,使用传入的值
  • 3、request.module

    • fixture 函数可以通过接受 request 对象来反向获取请求中的测试函数、类或模块上下文
    • 官方示例:
# conftest.py
@pytest.fixture(scope="module")
def smtp(request):
    server = getattr(request.module, "smtpserver", "smtp.qq.com")
    print("fixture 获取到的server :%s" %server)
    smtp = smtplib.SMTP(server, 587, timeout=5)
    yield smtp
    print("完成 %s (%s)" % (smtp, server))
    smtp.close()

#test_module.py
smtpserver = "mail.python.org"

def test_showhelo(smtp):
    print("case showhelo")

#getattr源码
def getattr(object, name, default=None): # known special case of getattr
    """
    getattr(object, name[, default]) -> value
    
    Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
    When a default argument is given, it is returned when the attribute doesn't
    exist; without it, an exception is raised in that case.
    """
    pass
  • 4、request的相关成员对象
@pytest.fixture(autouse=True)
def print_request(request):
    print("\n=======================request start=================================")
    print(request.module)
    print(request.function)
    print(request.cls)
    print(request.fspath)
    print(request.fixturenames)
    print(request.fixturename)
    print(request.scope)
    print("\n=======================request end=================================")
  • 5、使用示例
    • 前面我们编写了商品流的测试用例,每次都是随机生成商品数据,新增。这样会导致垃圾数据,我们执行完自动化之后,是有一个清理数据的步骤。需要将商品信息删除,这样才是一个完整的自动化过程。
    • 5.1:商品流用例中,添加request.config.sp_id属性
    • 5.2: conftest.py中获取sp_id,删除商品
#conftest.py

import pytest
from common.connect_mysql import DbConnet

@pytest.fixture()
def delete_sp(request):
    yield
    #配置信息
    dbinfo = {
        "host": "49.235.92.12",
        "user": "root",
        "password": "123456",
        "port": 3309,
        "database": "apps"}

    #获取商品id
    spid = request.config.sp_id
    sql = "DELETE from apiapp_goods where id = '%s';"%spid
    db = DbConnet(dbinfo)
    db.execute(sql)

#商品流用例修改
from api.goods import add_goods,get_goods_id,update_goods
import time
import pytest

@pytest.mark.smoke
def test_good_01(request,login_step,base_url,delete_sp):
    '''
    新增商品--获取商品ID---更新商品---查询商品,后置处理:删除商品
    '''
    # s = login_step
    sj = str(int(time.time() * 1000))[5:]     #随机数字符串
    sp_code = 'sp_code' + sj
    sp_name = 'sp_name' + sj

    r1 = add_goods(base_url,session=login_step,goodscode=sp_code,goodsname=sp_name)
    assert r1.json()["code"] == 0

    # 获取商品id
    spid = r1.json()["data"]["id"]
    print(spid)

    #给config对象动态添加sp_id属性,用于后置处理时,删除商品
    request.config.sp_id = spid

    #更新商品
    r2 = update_goods(base_url,session=login_step,goodsid=spid, goodscode=sp_code, goodsname=sp_name+'修改')
    print("更新商品返回", r2.text)
    assert r2.json()["code"] == 0

    #查询商品
    r3 = get_goods_id(base_url,session =login_step, goodsid=spid)
    assert r3.json()['data']['goodscode'] == sp_code

标签:fixture,sp,request,pytest,print,id
From: https://www.cnblogs.com/xwltest/p/16611257.html

相关文章