pytest fixture of fixtures

后端 未结 2 2016
日久生厌
日久生厌 2020-12-17 02:07

I am currently writing tests for a medium sized library (~300 files). Many classes in this library share the same testing scheme which were coded using pytest:

File

2条回答
  •  南笙
    南笙 (楼主)
    2020-12-17 02:39

    We had same problem at work and I was hoping to write fixture just once for every case. So I wrote plugin pytest-data which does that. Example:

    @pytest.fixture
    def resource(request):
        resource_data = get_data(reqeust, 'resource_data', {'some': 'data', 'foo': 'foo'})
        return Resource(resource_data)
    
    @use_data(resource_data={'foo': 'bar'})
    def test_1_for_class_a(resource):
        ...
    
    @use_data(resource_data={'foo': 'baz'})
    def test_2_for_class_a(resource):
        ...
    

    What's great about it is that you write fixture just once with some defaults. When you just need that fixture/resource and you don't care about specific setup, you just use it. When you need in test some specific attribute, let's say to check out if that resource can handle also 100 character long value, you can pass it by use_data decorator instead of writing another fixture.

    With that you don't have to care about conflicts, because everything will be there just once. And then you can use conftest.py for all of your fixtures without importing in test modules. For example we did separate deep module of all fixtures and all included in top conftest.py.

    Documentation of plugin pytest-data: http://horejsek.github.io/python-pytest-data/

提交回复
热议问题