gpt4 book ai didi

python - parametrize 中的 pytest 相关参数

转载 作者:行者123 更新时间:2023-12-04 16:45:03 27 4
gpt4 key购买 nike

我希望一个参数化依赖于一个较早的参数化:

@pytest.mark.parametrize("locale_name", LOCALES)
@pytest.mark.parametrize("money_string", ["500{currency}", "500 {currency}"])
@pytest.mark.parametrize("currency", LOCALES['locale_name']['currencies'])
def test_do_stuff(locale_name, money_string, currency):
print(locale_name, money_string, currency)

这里,第三个参数化取决于第一个。

我尝试按以下方式拆分它:

@pytest.mark.parametrize("locale_name", LOCALES)
@pytest.mark.parametrize("money_string", ["500{currency}", "500 {currency}"])
def test_currencies(locale_name, money_string):
# locale is actually also needed as an object, cannot be taken out.
locale = LOCALES[locale_name]

@pytest.mark.parametrize("currency", locale['currencies'])
def test_inner_currencies(currency):
print("this does not run however")

但是内部代码没有运行。除了使用 itertools.product 预生成对(但那样看起来会很丑陋)之外,我不确定我能为这种情况做些什么?

请注意,我可以只使用一个 for 循环,但这样我就不会“正式”运行那么多测试。

最佳答案

我不认为 py.test 支持测试中的测试,如果我根据你的示例代码理解正确,你想要的只是测试货币,假设 LOCALES 是一个嵌套的字典,我会做一些这样的事情来解决测试

import pytest

LOCALES = {"US": {"currencies": "dollar"},
"EU": {"currencies": "euro"},
"IN": {"currencies": "rupees"},
"CH": {"currencies": "yuan"}}

def currencies():
return [(local_name, currency["currencies"]) for local_name, currency in
LOCALES.items()]

@pytest.mark.parametrize("currency", currencies())
@pytest.mark.parametrize("money_string", ["500{currency}", "500 {currency}"])
def test_currencies(currency, money_string):
locale_name, currency = currency
print locale_name, money_string, currency

和输出

============================= test session starts ==============================
platform darwin -- Python 2.7.10, pytest-2.9.2, py-1.4.31, pluggy-0.3.1
rootdir: /Users/sanjay/Library/Preferences/PyCharm2016.2/scratches, inifile:
plugins: xdist-1.14
collected 8 items

scratch_11.py EU 500{currency} euro
.CH 500{currency} yuan
.US 500{currency} dollar
.IN 500{currency} rupees
.EU 500 {currency} euro
.CH 500 {currency} yuan
.US 500 {currency} dollar
.IN 500 {currency} rupees
.

=========================== 8 passed in 0.03 seconds ===========================

Process finished with exit code 0

关于python - parametrize 中的 pytest 相关参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39011777/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com