How to skip a pytest using an external fixture?

前端 未结 4 462
悲哀的现实
悲哀的现实 2020-12-09 15:46

Background

I am running a py.test with a fixture in a conftest file. You can see the code below(this all works fine):

example_test.py

4条回答
  •  天涯浪人
    2020-12-09 16:29

    It seems py.test doesn't use the test fixtures when evaluating the expression for skipif. By your example, test_ios is actually successful because it is comparing the function platform found in the module's namespace to the "ios" string, which evaluates to False hence the test is executed and succeeds. If pytest was inserting the fixture for evaluation as you expect, that test should have been skipped.

    A solution to your problem (not to your question though) would be to implement a fixture that inspects marks into the tests, and skips them accordingly:

    # conftest.py
    import pytest
    
    @pytest.fixture
    def platform():
        return "ios"
    
    @pytest.fixture(autouse=True)
    def skip_by_platform(request, platform):
        if request.node.get_closest_marker('skip_platform'):
            if request.node.get_closest_marker('skip_platform').args[0] == platform:
                pytest.skip('skipped on this platform: {}'.format(platform))   
    

    A key point is the autouse parameter, which would make that fixture to be automatically included by all tests. Then your tests can mark which platforms to skip like this:

    @pytest.mark.skip_platform('ios')
    def test_ios(platform, request):
        assert 0, 'should be skipped' 
    

    Hope that helps!

提交回复
热议问题