【问题标题】:pytest dependent parameters in parametrize参数化中的pytest依赖参数
【发布时间】:2016-12-25 00:07:51
【问题描述】:

我希望一个参数化依赖于之前的一个:

@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 循环,但我不会“正式”运行尽可能多的测试。

【问题讨论】:

    标签: python dependencies pytest


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-03
      • 2019-05-31
      • 2023-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多