Passing (yield) fixtures as test parameters (with a temp directory)

后端 未结 3 1096
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-20 11:02

Question

Is it possible to pass yielding pytest fixtures (for setup and teardown) as parameters to test functions?

Context

I\'m testing an object th

3条回答
  •  不要未来只要你来
    2021-01-20 11:56

    Temporary directories and files are handled by pytest using the built in fixtures tmpdir and tmpdir_factory.

    For this usage, tmpdir should be sufficient: https://docs.pytest.org/en/latest/tmpdir.html

    Also, paramertrized fixtures would work well for this example.
    These are documented here: https://docs.pytest.org/en/latest/fixture.html#fixture-parametrize

    import os
    import pytest
    
    
    class Thing:
        def __init__(self, datadir, errorfile):
            self.datadir = datadir
            self.errorfile = errorfile
    
    
    @pytest.fixture(params=(1, 2))
    def thing(request, tmpdir):
        errorfile_name = 'testlog{}.log'.format(request.param)
        errorfile = tmpdir.join(errorfile_name)
        return Thing(datadir=str(tmpdir), errorfile=str(errorfile))
    
    
    def test_attr(request, thing):
        assert os.path.exists(thing.datadir)
    

    BTW, In Python Testing with pytest, parametrized fixtures are covered in ch3. tmpdir and other built in fixtures are covered in ch4.

提交回复
热议问题