Aristide
Aristide

Reputation: 3994

Testing multiple versions of the same programs with pytest

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.

Upvotes: 1

Views: 462

Answers (1)

MrBean Bremen
MrBean Bremen

Reputation: 16815

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)

Upvotes: 1

Related Questions