1

I have several Python programs with multiple variants, e.g.:

sort_bubble_0.py
sort_bubble_1.py
sort_insertion_0.py
sort_insertion_1.py
sort_selection_0.py
...
unique_elements_0.py
unique_elements_1.py
unique_elements_2.py
...

In each group, all variants have the same interface.

In pytest, is it possible to have a unique test suite for each group, which would be launched successively on all the variants?

Ideally, a small snippet of code in the test suite would be able to discover all the appropriate variants based on a regular expression (e.g., r"sort_.*\.py"), import and test them one by one.

For now on, I just duplicate the same test suite as many times as needed, and manually change the imported name in each copy! I guess there should be a better way to do this.

1 Answer 1

1

A simple solution would be to parametrize the tests with the modules:

import pytest


def get_tested_modules(module_name):
    modules = []
    for i in range(100):
        try:
            modules.append(importlib.import_module(module_name + str(i)))
        except ImportError:
            break
    return modules
    
@pytest.mark.parametrize("module", get_tested_modules("sort_bubble_"))
def test_sort_bubble(module):
    assert module.sort([3, 2, 1]) == [1, 2, 3]

(simplified after comment by OP)

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot! I can certainly try to adapt your first approach by creating a list of programs with Path.glob(pattern), then importing all of them with importlib and feeding the list to @pytest.mark.parametrize(). For now, I am not familiar enough with pytest to appreciate your second solution, but I will certainly study it too.
Actually, you are right: you don't need the second approach at all. I will simplify the answer.
Great! I have not thought using a function with side-effect. Besides, in case you don't know it, I would recommend you to give pathlib module a look: its function glob can simplify the enumeration of the relevant files, while avoiding the exception construct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.