Search code examples
pythondependenciesintegration-testing

In Python, how to mark some tests to only execute when a condition is met


I am working on a small Python program. It has one function which has to open a Word file and read some information out of it, and calls the actual Word application via win32com. So execution of this function depends on Word being installed on the machine.

Given the size of the project and our resources, and seeing that this is the only function that has to be tested with external dependencies, it is not feasible to create a separate integration testing environment. I would prefer the tests of the Word reading function to run together with the real unit tests. But we don't have Word installed on all development machines, and these tests fail then.

I can programmatically test for Word being available on the machine or not. The question is, can I somehow annotate the tests so that they only run when Word is present?

I was thinking of simply putting something like if not word_discovered: pass inside each test, but then it would look like they all worked. I would prefer a solution where the testing framework prints in it report that these eight tests were skipped.


Solution

  • If you run your tests with pytest (which I'd strongly recommend), you can use the skipif mark:

    @pytest.mark.skipif(not word_discovered, reason="MS Word not available")
    def test_thing():
        """test your thing"""
    

    Pytest docs: https://docs.pytest.org/en/6.2.x/skipping.html#id1