py.test将一个测试的结果传递给另一个 [英] py.test passing results of one test to another

查看:424
本文介绍了py.test将一个测试的结果传递给另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我已经进行了如下测试:

Currently I have test looking like this:

@pytest.mark.parametrize("param", [1,2,3])
def test_two_services(param):
    id = check_service_one(param)
    check_service_two(id)

有什么方法可以将这个测试一分为二,而第二个测试则取决于第一个?

Is there any way to split this test in two, where a second test depends on a first?

推荐答案

请记住要在边界处进行测试.因此,如果id的值仅取决于param,并且id不是某些实现细节,而是被测系统已定义行为的一部分,则按如下方式拆分测试:

Remember to test at the boundary. So if the the values of id depend solely on param and if id isn't some implementation detail, but a part of the defined behaviour of the system under test, split up your tests like so:

def test_service_one(param, id):
    assert check_service_one(param) == id

def test_service_two(id):
    check_service_two(id)  # I'm assuming this does some assertion of its own.

@pytest.fixture
def param(param_and_id):
    param, _ = param_and_id
    return param

@pytest.fixture
def id(param_and_id):
    _, id = param_and_id
    return id

@pytest.fixture(
    params=[
        (1, EXPECTED_ID_FOR_PARAM_1),
        (2, EXPECTED_ID_FOR_PARAM_2),
        (3, EXPECTED_ID_FOR_PARAM_3),
    ],
)
def param_and_id(request):
    return request.param

像这样,测试与check_service_two的输入(与check_service_one的预期结果(并通过test_service_one的断言进行检查))匹配,而不是test_service_two依赖于test_service_one,因此松散地耦合了测试.因此,可以按任意顺序运行测试,并且可以隔离运行任何一个测试(而不必先运行另一个测试).

Like this, the tests are loosely coupled by the inputs of check_service_two matching the expected (and checked by assertion in test_service_one) results of check_service_one, rather than test_service_two depending hard on test_service_one. Thus, the tests can be run in arbitrary order and any one test can be run isolated (without having to run another test first).

这篇关于py.test将一个测试的结果传递给另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆