草庐IT

Pytest框架 — 11、Pytest的标记(二)(parametrize参数化)

qishuaiRisen 2023-04-20 原文

目录

1、标记实现参数化

通过@pytest.mark.parametrize(argnames, argvalues, indirect=False, ids=None, scope=None)装饰器来实现参数化。

参数说明:

  • argnames:参数名,使用逗号分隔的列表,或元祖,或字符串,表示一个或多个参数名,【常用】
  • argvalues:参数值,可以是列表、元祖、字典列表、元祖列表,【常用】
  • indirect:中文翻译为中间人,为True时可以对argvalues的参数值进行处理,默认False,【不常用】
    • indirect=True: 且argnames的值为fixture函数名,此时argnames的值变为可执行函数,会将argvalues的参数值当做参数传递给fixture函数进行处理,fixture函数返回处理结果给argnames
    • indirect=False: argnames仅为参数名
  • ids:给用例起别名,字符串列表或数字列表,不设置会自动从测试数据中提取
  • scope:待理解【不常用】

示例1:单个参数

import pytest


phone_list = [
    "13881118888",
    "13012034288",
    "13234324188",
    "13231423288"
]

@pytest.mark.parametrize(argnames="phone_num", argvalues=phone_list)
def test_phone_number(phone_num):  # 注意,这里的参数要和argnames参数名一致
    print(f"正在测试手机号{phone_num}")

"""
执行结果
mark/parametrize/single_param.py::test_phone_number[13881118888] 正在测试手机号13881118888
PASSED
mark/parametrize/single_param.py::test_phone_number[13012034288] 正在测试手机号13012034288
PASSED
mark/parametrize/single_param.py::test_phone_number[13234324188] 正在测试手机号13234324188
PASSED
mark/parametrize/single_param.py::test_phone_number[13231423288] 正在测试手机号13231423288
PASSED
"""

示例2:多个参数

import pytest

user_info = [
    ("张三", "18011111111"),
    ("李四", "18022222222"),
    ("王五", "18033333333")
]

@pytest.mark.parametrize(argnames="name,phonenum", argvalues=user_info)
def test_read_info(name, phonenum):
    print(f"正在读取用户{name},手机号{phonenum}")

"""
执行结果
mark/parametrize/multiple_param.py::test_read_info[\u5f20\u4e09-18011111111] 正在读取用户张三,手机号18011111111
PASSED
mark/parametrize/multiple_param.py::test_read_info[\u674e\u56db-18022222222] 正在读取用户李四,手机号18022222222
PASSED
mark/parametrize/multiple_param.py::test_read_info[\u738b\u4e94-18033333333] 正在读取用户王五,手机号18033333333
PASSED
"""

由上面例子执行结果中可以看到中文参数值乱码了,解决办法如下
方法1. 在pytest.ini中加入disable_test_id_escaping_and_forfeit_all_rights_to_community_support=True
方法2. 在conftest.py中加入

# 收集每一个用例name和nodeid的中文显示,转化为utf-8形式
def pytest_collection_modifyitems(items):
    for item in items:
        item.name = item.name.encode("utf-8").decode("unicode_escape")
        item._nodeid = item.nodeid.encode("utf-8").decode("unicode_escape")

示例3:多个参数化(笛卡尔积)

import pytest


data1 = ['a', 'b', 'c']
data2 = [1, 2]


@pytest.mark.parametrize('test1', data1)
@pytest.mark.parametrize('test2', data2)
def test_param(test1, test2):
    print('\n测试数据:{}-{}'.format(test1, test2))
"""
执行结果
mark/parametrize/multiple_parameterization.py::test_param[1-a] 
测试数据:a-1
PASSED
mark/parametrize/multiple_parameterization.py::test_param[1-b] 
测试数据:b-1
PASSED
mark/parametrize/multiple_parameterization.py::test_param[1-c] 
测试数据:c-1
PASSED
mark/parametrize/multiple_parameterization.py::test_param[2-a] 
测试数据:a-2
PASSED
mark/parametrize/multiple_parameterization.py::test_param[2-b] 
测试数据:b-2
PASSED
mark/parametrize/multiple_parameterization.py::test_param[2-c] 
测试数据:c-2
PASSED
"""

示例4:ids参数给用例起别名

import pytest


user_info = [
    ("张三", "18011111111"),
    ("李四", "18022222222"),
    ("王五", "18033333333")
]

@pytest.mark.parametrize(argnames="name,phonenum", argvalues=user_info, ids=["用户1","用户2","用户3"])
def test_read_info(name, phonenum):
    print(f"正在读取用户{name},手机号{phonenum}")
    
"""
执行结果
mark/parametrize/ids.py::test_read_info[用户1] 正在读取用户张三,手机号18011111111
PASSED
mark/parametrize/ids.py::test_read_info[用户2] 正在读取用户李四,手机号18022222222
PASSED
mark/parametrize/ids.py::test_read_info[用户3] 正在读取用户王五,手机号18033333333
PASSED
"""

示例5:使用indirect处理参数值

import pytest

@pytest.fixture()
def fixture_and_parametrize(request):  # request是关键字不能改变,用来接收参数
    print('邮箱账号为:{}'.format(request.param))
    return request.param + "@qq.com"


@pytest.mark.parametrize('fixture_and_parametrize', ['100203', '466238894', '23942423'],
                         indirect=True)
def test_fixture_and_parametrize_2(fixture_and_parametrize):
    print('拼接后邮箱为:{}'.format(fixture_and_parametrize))

"""
执行结果
mark/parametrize/indirect.py::test_fixture_and_parametrize_2[100203] 邮箱账号为:100203
拼接后邮箱为:100203@qq.com
PASSED
mark/parametrize/indirect.py::test_fixture_and_parametrize_2[466238894] 邮箱账号为:466238894
拼接后邮箱为:466238894@qq.com
PASSED
mark/parametrize/indirect.py::test_fixture_and_parametrize_2[23942423] 邮箱账号为:23942423
拼接后邮箱为:23942423@qq.com
PASSED
"""

示例6:标记数据

在参数化的过程中也可以标记数据进行跳过等

import pytest


@pytest.mark.parametrize("test_input,expected", [
    ("3+9", 12), ("5+4", 9),
    pytest.param("7 * 9", 42, marks=pytest.mark.xfail),
    pytest.param("8 * 6", 42, marks=pytest.mark.skip)
])
def test_mark(test_input, expected):
    assert eval(test_input) == expected
"""
执行结果
mark/parametrize/mark_data.py::test_mark[3+9-12] PASSED
mark/parametrize/mark_data.py::test_mark[5+4-9] PASSED
mark/parametrize/mark_data.py::test_mark[7 * 9-42] XFAIL
mark/parametrize/mark_data.py::test_mark[8 * 6-42] SKIPPED (unconditional skip)
"""

参考
https://www.cnblogs.com/miki-peng/p/14736332.html
https://zhuanlan.zhihu.com/p/515377205

有关Pytest框架 — 11、Pytest的标记(二)(parametrize参数化)的更多相关文章

  1. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  2. ruby - RSpec - 使用测试替身作为 block 参数 - 2

    我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere

  3. ruby - 如何在 Ruby 中拆分参数字符串 Bash 样式? - 2

    我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"

  4. ruby - 检查方法参数的类型 - 2

    我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)

  5. ruby-on-rails - 在默认方法参数中使用 .reverse_merge 或 .merge - 2

    两者都可以defsetup(options={})options.reverse_merge:size=>25,:velocity=>10end和defsetup(options={}){:size=>25,:velocity=>10}.merge(options)end在方法的参数中分配默认值。问题是:哪个更好?您更愿意使用哪一个?在性能、代码可读性或其他方面有什么不同吗?编辑:我无意中添加了bang(!)...并不是要询问nobang方法与bang方法之间的区别 最佳答案 我倾向于使用reverse_merge方法:option

  6. ruby - 定义方法参数的条件 - 2

    我有一个只接受一个参数的方法:defmy_method(number)end如果使用number调用方法,我该如何引发错误??通常,我如何定义方法参数的条件?比如我想在调用的时候报错:my_method(1) 最佳答案 您可以添加guard在函数的开头,如果参数无效则引发异常。例如:defmy_method(number)failArgumentError,"Inputshouldbegreaterthanorequalto2"ifnumbereputse.messageend#=>Inputshouldbegreaterthano

  7. ruby - rails 3 redirect_to 将参数传递给命名路由 - 2

    我没有找到太多关于如何执行此操作的信息,尽管有很多关于如何使用像这样的redirect_to将参数传递给重定向的建议:action=>'something',:controller=>'something'在我的应用程序中,我在路由文件中有以下内容match'profile'=>'User#show'我的表演Action是这样的defshow@user=User.find(params[:user])@title=@user.first_nameend重定向发生在同一个用户Controller中,就像这样defregister@title="Registration"@user=Use

  8. ruby - 字符串文字中的转义状态作为 `String#tr` 的参数 - 2

    对于作为String#tr参数的单引号字符串文字中反斜杠的转义状态,我觉得有些神秘。你能解释一下下面三个例子之间的对比吗?我特别不明白第二个。为了避免复杂化,我在这里使用了'd',在双引号中转义时不会改变含义("\d"="d")。'\\'.tr('\\','x')#=>"x"'\\'.tr('\\d','x')#=>"\\"'\\'.tr('\\\d','x')#=>"x" 最佳答案 在tr中转义tr的第一个参数非常类似于正则表达式中的括号字符分组。您可以在表达式的开头使用^来否定匹配(替换任何不匹配的内容)并使用例如a-f来匹配一

  9. ruby-on-rails - 如何生成传递一些自定义参数的 `link_to` URL? - 2

    我正在使用RubyonRails3.0.9,我想生成一个传递一些自定义参数的link_toURL。也就是说,有一个articles_path(www.my_web_site_name.com/articles)我想生成如下内容:link_to'Samplelinktitle',...#HereIshouldimplementthecode#=>'http://www.my_web_site_name.com/articles?param1=value1¶m2=value2&...我如何编写link_to语句“alàRubyonRailsWay”以实现该目的?如果我想通过传递一些

  10. ruby - 安装libv8(3.11.8.13)出错,Bundler无法继续 - 2

    运行bundleinstall后出现此错误:Gem::Package::FormatError:nometadatafoundin/Users/jeanosorio/.rvm/gems/ruby-1.9.3-p286/cache/libv8-3.11.8.13-x86_64-darwin-12.gemAnerroroccurredwhileinstallinglibv8(3.11.8.13),andBundlercannotcontinue.Makesurethat`geminstalllibv8-v'3.11.8.13'`succeedsbeforebundling.我试试gemin

随机推荐