如何在夹具中使用pytest.mark.parametrize

时间:2018-07-20 09:52:57

标签: python testing pytest

我想用夹具对测试进行参数化。像这样:

def count_lines(path):
    with open(path, 'r') as fh:
        return len(fh.readlines())


@pytest.fixture
def data_path():
    return '/path/to/test/data'


@pytest.fixture
def simple_file(data_path):
    return os.path.join(data_path, 'simpletestfile.ext')


@pytest.fixture
def other_file(data_path):
    return os.path.join(data_path, 'othertestfile.ext')


@pytest.mark.parametrize('given, expected', [
    (simple_file, 3),
    (other_file, 9),
])
def test_count_lines(given, expected):
    observed = count_lines(given)
    assert observed == expected

上面的代码失败是因为测试没有解决sample_fileother_file固定装置,而是接受了使测试在open()语句中失败的功能。

要使其正常工作,我必须执行以下操作:

@pytest.mark.parametrize('given, expected', [
    (simple_file(data_path()), 3),
    (other_file(data_path()), 9),
])

但这似乎违反了py.test的目的。

另一种选择是

class TestCountLines(object):

    TESTDATA = [
        {
            'id': 'simple case',
            'input_file': 'simpletestfile.ext',
            'expected': 3,
        },
        {
            'id': 'other case',
            'input_file': 'othertestfile.ext',
            'expected': 9,
        },
    ]

    @pytest.fixture(params=TESTDATA, ids=lambda x: x['id'])
    def staged_testdata(self, request, data_path):
        datafile = os.path.join(data_path, request.param['input_file'])
        expected = request.param['expected']
        yield datafile, expected

    def test_count_lines(self, staged_testdata):
        given, expected = staged_testdata
        observed = count_lines(given)
        assert observed == expected

但是我发现上面的代码很好奇,因为staged_testdata固定装置会产生两件事,然后我需要在测试之前解压缩测试数据。那么,如何使用夹具对测试进行参数化?

0 个答案:

没有答案