pythonshellunit-testingwildcard

How to match specific files with a shell pattern in unit test discoverer?


I want to run a suite of unit tests. The basic code is:

suite = unittest.defaultTestLoader.discover('tests')

The documentation for the function mentions the pattern argument, which defaults to test_*.py:

Only test files that match the pattern will be loaded. (Using shell style pattern matching.)

I want only some of these tests to run, for example test_abcd, test_ab1, and test_ab3, but not test_ab2 (because it imports a file that may not be present). In a shell, I could match these files with:

test_{abcd,ab1,ab3}

But it fails inside the test discoverer. I also tried these patterns, but none of them work inside the discoverer:

test_\(abcd|ab1|ab3\)
test_abcd,test_ab1,test_ab3

One pattern that works inside the discoverer is test_ab[2-4], but it will also catch test_ab3, which I don't want.

How can I match these specific files with a shell pattern or the unit test discoverer?


Solution

  • A pattern that should work is

    test_ab[c12]*
    

    depending on what else you want to match or not match.

    For more detailed matching, How does Python's unittest library match patterns passed via the -p parameter? explains the process of matching with the fnmatch module. The capabilities are:

    Patterns are Unix shell style:
    *       matches everything
    ?       matches any single character
    [seq]   matches any character in seq
    [!seq]  matches any char not in seq
    

    If you want more fine-grained control over which tests to run than pattern-matching allows, consider using loadTestsFromNames instead.