How do I correctly setup and teardown for my pytest class with tests?

后端 未结 6 1023
名媛妹妹
名媛妹妹 2020-11-30 21:50

I am using selenium for end to end testing and I can\'t get how to use setup_class and teardown_class methods.

I need to set up browser in <

6条回答
  •  清歌不尽
    2020-11-30 22:28

    As @Bruno suggested, using pytest fixtures is another solution that is accessible for both test classes or even just simple test functions. Here's an example testing python2.7 functions:

    import pytest
    
    @pytest.fixture(scope='function')
    def some_resource(request):
        stuff_i_setup = ["I setup"]
    
        def some_teardown():
            stuff_i_setup[0] += " ... but now I'm torn down..."
            print stuff_i_setup[0]
        request.addfinalizer(some_teardown)
    
        return stuff_i_setup[0]
    
    def test_1_that_needs_resource(some_resource):
        print some_resource + "... and now I'm testing things..."
    

    So, running test_1... produces:

    I setup... and now I'm testing things...
    I setup ... but now I'm torn down...
    

    Notice that stuff_i_setup is referenced in the fixture, allowing that object to be setup and torn down for the test it's interacting with. You can imagine this could be useful for a persistent object, such as a hypothetical database or some connection, that must be cleared before each test runs to keep them isolated.

提交回复
热议问题