nginx做网站,十大装潢公司上海,国家认可的教育培训机构,网站排名诊断目录
前言#xff1a;
语法
参数化误区
实践
简要回顾 前言#xff1a;
pytest是一个功能强大的Python测试框架#xff0c;它提供了参数化功能#xff0c;可以帮助简化测试用例的编写和管理。
语法
本文就赶紧聊一聊 pytest 的参数化是怎么玩的。
pytest.mark.par…目录
前言
语法
参数化误区
实践
简要回顾 前言
pytest是一个功能强大的Python测试框架它提供了参数化功能可以帮助简化测试用例的编写和管理。
语法
本文就赶紧聊一聊 pytest 的参数化是怎么玩的。
pytest.mark.parametrize
user1ize(test_input,expected, [(35, 8), (24, 6), (6*9, 42)])
def test_eval(test_input, expected):assert eval(test_input) expected可以自定义变量test_input 对应的值是35 24 6*9expected 对应的值是 8 6 42多个变量用 tuple多个 tuple 用 list 参数化的变量是引用而非复制意味着如果值是 list 或 dict改变值会影响后续的 test 重叠产生笛卡尔积
import pytestuser2ize(x, [0, 1])
user3ize(y, [2, 3])
def test_foo(x, y):passpytest.fixture()
pytest.fixture(scopemodule, params[smtp.gmail.com, mail.python.org])
def smtp_connection(request):smtp_connection smtplib.SMTP(request.param, 587, timeout5)只能使用 request.param 来引用 参数化生成的 test 带有 ID可以使用-k来筛选执行。默认是根据函数名[参数名]来的可以使用 ids 来定义
// list
pytest.fixture(params[0, 1], ids[spam, ham])
// function
pytest.fixture(params[0, 1], idsidfn)使用--collect-only命令行参数可以看到生成的 IDs。
参数添加 marker
我们知道了参数化后会生成多个 tests如果有些 test 需要 marker可以用 pytest.param 来添加
marker 方式
# content of test_expectation.py
import pytestuser7ize(test_input,expected,[(35, 8), (24, 6), pytest.param(6*9, 42, markspytest.mark.xfail)],
)
def test_eval(test_input, expected):assert eval(test_input) expectedfixture 方式
# content of test_fixture_marks.py
import pytestpytest.fixture(params[0, 1, pytest.param(2, markspytest.mark.skip)])
def data_set(request):return request.param
def test_data(data_set):passpytest_generate_tests
用来自定义参数化方案。使用到了 hookhook 的知识我会写在《pytest hook》中欢迎关注公众号 dongfanger 获取最新文章。
# content of conf.pydef pytest_generate_tests(metafunc):if test_input in metafunc.fixturenames:metafunc.parametrize(test_input, [0, 1])# content of test.pydef test(test_input):assert test_input 0定义在 conftest.py 文件中metafunc 有 5 个属性fixturenamesmoduleconfigfunctionclsmetafunc.parametrize() 用来实现参数化多个 metafunc.parametrize() 的参数名不能重复否则会报错
参数化误区
在讲示例之前先简单分享我的菜鸡行为。假设我们现在需要对 50 个接口测试验证某一角色的用户访问这些接口会返回 403。我的做法是把接口请求全部参数化了test 函数里面只有断言伪代码大致如下
def api():params []def func():return request()params.append(func)...user9ize(req, api())
def test():res req()assert res.status_code 403这样参数化以后会产生50 个 tests如果断言失败了会单独标记为 failed不影响其他 test 结果。咋一看还行但是有个问题在回归的时候可能只需要验证其中部分接口就没有办法灵活的调整必须全部跑一遍才行。这是一个相对错误的示范至于正确的应该怎么写相信每个人心中都有一个答案能解决问题就是 ok 的。我想表达的是参数化要适当不要滥用最好只对测试数据做参数化。
实践
本文的重点来了参数化的语法比较简单实际应用是关键。这部分通过 11 个例子来实践一下。示例覆盖的知识点有点多建议留大段时间细看。
1.使用 hook 添加命令行参数--allparam1是参数名带--all 参数时是 range(5) [0, 1, 2, 3, 4]生成 5 个 tests。不带参数时是 range(2)。
# content of test_compute.pydef test_compute(param1):assert param1 4
# content of conftest.pydef pytest_addoption(parser):parser.addoption(--all, actionstore_true, helprun all combinations)
def pytest_generate_tests(metafunc):if param1 in metafunc.fixturenames:if metafunc.config.getoption(all):end 5else:end 2metafunc.parametrize(param1, range(end))
2.testdata 是测试数据包括 2 组。test_timedistance_v0 不带 ids。test_timedistance_v1 带 list 格式的 ids。test_timedistance_v2 的 ids 为函数。test_timedistance_v3 使用 pytest.param 同时定义测试数据和 id。
# content of test_time.py
from datetime import datetime, timedeltaimport pytesttestdata [(datetime(2001, 12, 12), datetime(2001, 12, 11), timedelta(1)),(datetime(2001, 12, 11), datetime(2001, 12, 12), timedelta(-1)),
]user10ize(a,b,expected, testdata)
def test_timedistance_v0(a, b, expected):diff a - bassert diff expecteduser11ize(a,b,expected, testdata, ids[forward, backward])
def test_timedistance_v1(a, b, expected):diff a - bassert diff expecteddef idfn(val):if isinstance(val, (datetime,)):# note this wouldnt show any hours/minutes/secondsreturn val.strftime(%Y%m%d)user12ize(a,b,expected, testdata, idsidfn)
def test_timedistance_v2(a, b, expected):diff a - bassert diff expecteduser13ize(a,b,expected,[pytest.param(datetime(2001, 12, 12), datetime(2001, 12, 11), timedelta(1), idforward),pytest.param(datetime(2001, 12, 11), datetime(2001, 12, 12), timedelta(-1), idbackward),],
)
def test_timedistance_v3(a, b, expected):diff a - bassert diff expected
3.兼容 unittest 的 testscenarios
# content of test_scenarios.py
def pytest_generate_tests(metafunc):idlist []argvalues []for scenario in metafunc.cls.scenarios:idlist.append(scenario[0])items scenario[1].items()argnames [x[0] for x in items]argvalues.append([x[1] for x in items])metafunc.parametrize(argnames, argvalues, idsidlist, scopeclass)scenario1 (basic, {attribute: value})
scenario2 (advanced, {attribute: value2})class TestSampleWithScenarios:scenarios [scenario1, scenario2]def test_demo1(self, attribute):assert isinstance(attribute, str)def test_demo2(self, attribute):assert isinstance(attribute, str)
4.初始化数据库连接
# content of test_backends.py
import pytestdef test_db_initialized(db):# a dummy testif db.__class__.__name__ DB2:pytest.fail(deliberately failing for demo purposes)
# content of conftest.py
import pytestdef pytest_generate_tests(metafunc):if db in metafunc.fixturenames:metafunc.parametrize(db, [d1, d2], indirectTrue)class DB1:one database objectclass DB2:alternative database objectpytest.fixture
def db(request):if request.param d1:return DB1()elif request.param d2:return DB2()else:raise ValueError(invalid internal test config)
5.如果不加 indirectTrue会生成 2 个 testfixt 的值分别是a和b。如果加了 indirectTrue会先执行 fixturefixt 的值分别是aaa和bbb。indirectTrue 结合 fixture 可以在生成 test 前对参数变量额外处理。
import pytestpytest.fixture
def fixt(request):return request.param * 3user16ize(fixt, [a, b], indirectTrue)
def test_indirect(fixt):assert len(fixt) 3
6.多个参数时indirect 赋值 list 可以指定某些变量应用 fixture没有指定的保持原值。
# content of test_indirect_list.py
import pytestpytest.fixture(scopefunction)
def x(request):return request.param * 3pytest.fixture(scopefunction)
def y(request):return request.param * 2user19ize(x, y, [(a, b)], indirect[x])
def test_indirect(x, y):assert x aaaassert y b
7.兼容 unittest 参数化
# content of ./test_parametrize.py
import pytestdef pytest_generate_tests(metafunc):# called once per each test functionfuncarglist metafunc.cls.params[metafunc.function.__name__]argnames sorted(funcarglist[0])metafunc.parametrize(argnames, [[funcargs[name] for name in argnames] for funcargs in funcarglist])class TestClass:# a map specifying multiple argument sets for a test methodparams {test_equals: [dict(a1, b2), dict(a3, b3)],test_zerodivision: [dict(a1, b0)],}def test_equals(self, a, b):assert a bdef test_zerodivision(self, a, b):with pytest.raises(ZeroDivisionError):a / b
8.在不同 python 解释器之间测试对象序列化。python1 把对象 pickle-dump 到文件。python2 从文件中 pickle-load 对象。 module containing a parametrized tests testing cross-python
serialization via the pickle module.import shutil
import subprocess
import textwrapimport pytestpythonlist [python3.5, python3.6, python3.7]pytest.fixture(paramspythonlist)
def python1(request, tmpdir):picklefile tmpdir.join(data.pickle)return Python(request.param, picklefile)pytest.fixture(paramspythonlist)
def python2(request, python1):return Python(request.param, python1.picklefile)class Python:def __init__(self, version, picklefile):self.pythonpath shutil.which(version)if not self.pythonpath:pytest.skip({!r} not found.format(version))self.picklefile picklefiledef dumps(self, obj):dumpfile self.picklefile.dirpath(dump.py)dumpfile.write(textwrap.dedent(rimport picklef open({!r}, wb)s pickle.dump({!r}, f, protocol2)f.close().format(str(self.picklefile), obj)))subprocess.check_call((self.pythonpath, str(dumpfile)))def load_and_is_true(self, expression):loadfile self.picklefile.dirpath(load.py)loadfile.write(textwrap.dedent(rimport picklef open({!r}, rb)obj pickle.load(f)f.close()res eval({!r})if not res:raise SystemExit(1).format(str(self.picklefile), expression)))print(loadfile)subprocess.check_call((self.pythonpath, str(loadfile)))user22ize(obj, [42, {}, {1: 3}])
def test_basic_objects(python1, python2, obj):python1.dumps(obj)python2.load_and_is_true(obj {}.format(obj))
9.假设有个 APIbasemod 是原始版本optmod 是优化版本验证二者结果一致。
# content of conftest.py
import pytestpytest.fixture(scopesession)
def basemod(request):return pytest.importorskip(base)pytest.fixture(scopesession, params[opt1, opt2])
def optmod(request):return pytest.importorskip(request.param)
# content of base.pydef func1():return 1# content of opt1.pydef func1():return 1.0001# content of test_module.py
def test_func1(basemod, optmod):assert round(basemod.func1(), 3) round(optmod.func1(), 3)10.使用 pytest.param 添加 marker 和 id。
# content of test_pytest_param_example.py
import pytestuser25ize(test_input,expected,[(35, 8),pytest.param(17, 8, markspytest.mark.basic),pytest.param(24, 6, markspytest.mark.basic, idbasic_24),pytest.param(6*9, 54, marks[pytest.mark.basic, pytest.mark.xfail], idbasic_6*9),],
)
def test_eval(test_input, expected):assert eval(test_input) expected
11.使用 pytest.raises 让部分 test 抛出 Error。
from contextlib import contextmanagerimport pytest// 3.7 from contextlib import nullcontext as does_not_raise
contextmanager
def does_not_raise():yielduser27ize(example_input,expectation,[(3, does_not_raise()),(2, does_not_raise()),(1, does_not_raise()),(0, pytest.raises(ZeroDivisionError)),],
)
def test_division(example_input, expectation):Test how much I know division.with expectation:assert (6 / example_input) is not None
简要回顾
本文先讲了参数化的语法包括 markerfixturehook 方式以及如何给参数添加 marker然后重点列举了几个实战示例。参数化用好了能节省编码达到事半功倍的效果。 作为一位过来人也是希望大家少走一些弯路
在这里我给大家分享一些自动化测试前进之路的必须品希望能对你带来帮助。
WEB自动化测试、app自动化测试、接口自动化测试、持续集成、自动化测试开发、大厂面试真题、简历模板等等
相信能使你更好的进步
点击下方小卡片