How to accumulate state across tests in py.test

后端 未结 5 1981
悲哀的现实
悲哀的现实 2021-01-01 01:02

I currently have a project and tests similar to these.

class mylib:
    @classmethod
    def get_a(cls):
        return \'a\'

    @classmethod
    def conve         


        
5条回答
  •  悲哀的现实
    2021-01-01 01:37

    To complement hpk42's answer, you can also use pytest-steps to perform incremental testing, this can help you in particular if you wish to share some kind of incremental state/intermediate results between the steps.

    With this package you do not need to put all the steps in a class (you can, but it is not required), simply decorate your "test suite" function with @test_steps.

    EDIT: there is a new 'generator' mode to make it even easier:

    from pytest_steps import test_steps
    
    @test_steps('step_first', 'step_conversion', 'step_a_works_with_b')
    def test_suite_with_shared_results():
        a = mylib.get_a()
        yield
    
        b = mylib.convert_a_to_b(a)
        yield
    
        assert mylib.works_with(a, b)
        yield
    

    LEGACY answer:

    You can add a steps_data parameter to your test function if you wish to share a StepsDataHolder object between your steps.

    Your example would then write:

    from pytest_steps import test_steps, StepsDataHolder
    
    def step_first(steps_data):
        steps_data.a = mylib.get_a()
    
    
    def step_conversion(steps_data):
        steps_data.b = mylib.convert_a_to_b(steps_data.a)
    
    
    def step_a_works_with_b(steps_data):
        assert mylib.works_with(steps_data.a, steps_data.b)
    
    
    @test_steps(step_first, step_conversion, step_a_works_with_b)
    def test_suite_with_shared_results(test_step, steps_data: StepsDataHolder):
    
        # Execute the step with access to the steps_data holder
        test_step(steps_data)
    

    Finally, note that you can automatically skip or fail a step if another has failed using @depends_on, check in the documentation for details.

    (I'm the author of this package by the way ;) )

提交回复
热议问题