Search code examples
pythonunit-testingpytest

Run tests of another module with pytest


I wrote two modules, packageA and packageB. Both have their own battery of tests, but packageB depends on packageA, so I would like to run packageA's tests when I run packageB's.

I can use pytest.main(['--pyargs' ,'package_A.tests.tests_A']) in packageB, and it seems to work. However, if there are conflicting options in conftest.py, it all breaks down.

Is there a solution?

Here is a (not) working example:

My folder structure:

- python path
   - packageA
      - tests
         - tests_A.py
         - conftest.py
   - packageB
      - tests
         - tests_B.py
         - conftest.py

conftest.py is the same in both folders:

def pytest_addoption(parser):
    parser.addoption(
        "--any_option", action="store_true", default=False
    )

tests_A.py contans one test that fails (just to be sure that it runs):

def test_package_A():

    assert False

tests_B.py calls the tests in package_A:

import pytest
pytest.main(['--pyargs' ,'package_A.tests.tests_A'])

But pytest does not like overwriting options:

=========================== short test summary info ===========================

ERROR - ValueError: option names {'--any_option'} already added

!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!

============================== 1 error in 0.09s ===============================


Solution

  • I actually found a solution, and I was VERY close to it. I'll leave it here in case some else needs it. You CAN call another package's suite of tests from your tests. The problem in my case is that I used options with the same name (as the error message very clearly suggested).

    Now in my Package B I have this test:

    def test_LBMpy_package(client):
        """ This runs the tests in package A """
    
        r = pytest.main(['--pyargs', 'packageA.tests'])
        assert r == 0  # ExitCode should be 0
    

    If the tests in package A fail, the full output will be printed, and so you'll know what test in packageA failed.