pytest装饰器总结

2022-10-28 10:55:29

几个常用装饰器

pytest.ini 配置文件

  1. 例子:
    [pytest]
    addopts = -v -s --html=py_test/scripts/report/report.html -p no:warnings  --reruns=10
    
    testpaths = ./py_test/scripts
    python_files= test_rerun.py
    python_classes = Test*
    python_function = test*
    xfail_strict = true
  2. addopts: OPTS 命令行参数集

    -s:表示输出调试信息,包括 print打印的信息
    -v:显示更详细的信息
    -vs:这两个参数一起用
    -n :支持多线程或者分布式运行测试用例
         如:pytest -vs ./testcase/test_login.py -n 2
    --html : 测试报告位置
    --reruns : 失败重跑
    -p no:warnings  : 取消警告
    --ff : 先执行上次失败的用例
    --lf : 只执行上次失败的用例
    -x : 遇到测试用例fail,就结束测试
    --maxfail=num:遇到num条测试用例fail, 就结束测试 
    -k :根据测试用例的部分字符串指定测试用例
      	如:pytest -vs ./testcase -k “ao”

skipif-跳过测试

    跳过测试的使用方法

  1. pytest.skip (用于函数内,跳过测试用例)
    def test_2():
        if 1 < 2:
            pytest.skip('1111111')
        pass
  2. @pytest.mark.skip(用于函数外,跳过测试用例)
    @pytest.mark.skip(reason='feature not implemented')
    def test_1():
        pass
    
    # 模块级别跳过。(注:参数allow_module_level的值设为True)
    pytest.skip('skip all tests', allow_module_level=True)
  3. @pytest.mark.skipif(用于函数外,条件condition,跳过原因reason="xxx")
    @pytest.mark.skipif(condition='1<2',reason='feature not implemented')
    def test_1():
        pass

ordering-执行顺序

  1. 控制用例执行顺序的方法
  2. 在需要调整用例执行顺序的函数(或方法)前增加
    1.  @pytest.mark.run(order=x) x表示数字
  3. 数字形式: 小数、整数、负数

执行顺序:

1、由小到大

2、由正到负

3、未标记 的在正数后,负数前执行

顺序: 1,2,3,无标记,-3,-2,-1

xfail-预期失败

  1. xfail-预期失败的函数
  2. 语法
    1. xfail(condition, reason)
    2. --condition 预期失败的条件
    3. --reason 预期失败的原因
  3. pytest.ini加参数,
    1. 不希望出现 预期失败结果成功 的情况
    2. 就在配置文件中添加一个参数:
    3. xfail_strict = true

fixture-函数作参数

  1. fixture用途:可将被fixture标记的函数当作参数使用
  2. 掌握一个fixture 实现 setup 和 tearduwn
    1. yield 关键字
      1. yield 后边代码是用例执行完后再执行的。相当于teardown
      2. 当用例执行完之后, 会执行yield 后面的代码,但不能 return
    2. addfinalize 关键字
      1. 这个实现功能跟yield的一样, 但可以用return,将参数传给后面的用例.
  3. fixture 可放到conftest.py文件下
    1. conftest.py会自动识别 哪个用例调用了这个函数

parametrize-参数化

  1. parametrize(argnames,argvalues)
      1. --argnames : 参数名
      2. --argvalues : 参数值, 数据类型是 list
  2. 语法
    1. @pytest.mark.parametrize
    2. @pytest.mark.parametrize("mobile,code", [(121,212),(123,321)])

rerunfailure-失败重跑

  1. 失败重跑机制
  2. 安装pytest-rerunfailure
    1. 在设置文件pytest.ini中添加命令
    2. reruns = 重跑次数
    3. addopts = --reruns=10

链接Mysql

一.环境搭建

      对接mysql数据库需要通过第三方库PyMySQl

二.数据库操作

      建立数据库连接 :MySQlconnect = pymysql.connect(“数据库地址“,“数据库端口“,”数据库账号“等)

      获取操作游标: cursor = MySQlconnect .cursor()

      执行SQL语句:cursor .execute(“SQL语句”)

      获取一条数据:data = cursor.fetchone()

      获取结果(读):cursor.fetchall()

      提交更改(写):MySQlconnect .commit()

      关闭游标:cursor.close()

      关闭连接 :MySQlconnect .close()

  • 作者:Mavis先生
  • 原文链接:https://blog.csdn.net/m0_37890492/article/details/116201942
    更新时间:2022-10-28 10:55:29