Skip to main content
 首页 » 编程设计

python之py.test 和 fixtures之如何只选择一种参数变体

2025年05月04日10pengyingh

假设我有以下灯具:

@pytest.fixture(params=['google.com','other-provider.com') 
def smtp_server(request): 
    .... some initialisation .... 
    return SmtpServer(request.param) 
 
 
@pytest.fixture(params=['plain_text','html') 
def message(request): 
    .... some initialisation according to email type.... 
    return msg_obj 

因此,如果我在一个测试函数中使用它们,我有组合:google+plain、provider+plain、google+html、provider+html。

但是,如果我想重用 fixture,但仅限于特定的组合,该怎么办。例如,我注意到当我向 google 发送 html 电子邮件时,在某些情况下它会失败。我如何重用固定装置并测试这种情况,而不测试发送到 other-provider.com,这是毫无意义的?

换句话说 - 如何在特定的测试函数中跳过一些 fixture 的组合?

请您参考如下方法:

首先我想指出这实际上是一个相当奇怪的案例。您真的确定这些测试对于您要跳过的组合毫无意义吗?

话虽如此,我自己解决这个问题的方法就是简单地使用

if snmtp_server == 'other-provider.com' and message == 'html': 
    pytest.skip('impossible combination') 

在测试函数中。它很简陋,但对于这种不寻常且罕见的情况来说已经足够好了。