[PYTHON] Run all unittests under a directory

If you're writing unit tests using Python's unittest module in multiple files and want to run them all, you can use TestLoader.discovery ().

discover(self, start_dir, pattern='test*.py', top_level_dir=None)

The default pattern is to find files that start with test and end with .py under the directory specified by start_dir.

Given a directory as an argument to the following script, it will run all the tests it finds.

runner.py


#!/usr/bin/env python
import sys
from unittest import TestLoader
from unittest import TextTestRunner


def main(path):
    loader = TestLoader()
    test = loader.discover(path)
    runner = TextTestRunner()
    runner.run(test)


if __name__ == '__main__':
    if len(sys.argv) != 2:
        print('usage: %s path' % sys.argv[0])
        sys.exit(1)
    main(sys.argv[1])

For example

% find tests -type f -name \*.py
tests/hoge/__init__.py
tests/hoge/test_hoge.py
tests/test_fuga.py

Suppose that the directory structure is. The reason why __init__.py is placed is to have it searched from the subdirectory as well. When I run the script, it looks like this:

% ./runner.py tests
FF
======================================================================
FAIL: test_1 (hoge.test_hoge.TestHoge)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/python-study/unittest/tests/hoge/test_hoge.py", line 6, in test_1
    self.assertEqual(0, 1)
AssertionError: 0 != 1

======================================================================
FAIL: test_1 (test_fuga.TestFuga)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/python-study/unittest/tests/test_fuga.py", line 6, in test_1
    self.assertEqual(0, 1)
AssertionError: 0 != 1

----------------------------------------------------------------------
Ran 2 tests in 0.000s

FAILED (failures=2)

If you rely on unittest.main, you can do the same with a shell script like this:

runner.sh


#!/bin/sh
python -m unittest discover $1

Recommended Posts

Run all unittests under a directory
Delete all pyc files under the specified directory
Unzip all zip files under the current directory
Drop all CSV files under any directory into DataFrame
Mac Linux Check the capacity directly under a specific directory
Run Python unittests in parallel
File access under the directory
[Linux] Directory under the root
Create a directory with python