Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

unit testing - Python: How to run unittest.main() for all source files in a subdirectory?

I am developing a Python module with several source files, each with its own test class derived from unittest right in the source. Consider the directory structure:

dirFoo
    test.py
    dirBar
        __init__.py
        Foo.py
        Bar.py

To test either Foo.py or Bar.py, I would add this at the end of the Foo.py and Bar.py source files:

if __name__ == "__main__":
    unittest.main()

And run Python on either source, i.e.

$ python Foo.py
...........
----------------------------------------------------------------------
Ran 11 tests in 2.314s

OK

Ideally, I would have "test.py" automagically search dirBar for any unittest derived classes and make one call to "unittest.main()". What's the best way to do this in practice?

I tried using Python to call execfile for every *.py file in dirBar, which runs once for the first .py file found & exits the calling test.py, plus then I have to duplicate my code by adding unittest.main() in every source file--which violates DRY principles.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As of Python 2.7, test discovery is automated in the unittest package. From the docs:

Unittest supports simple test discovery. In order to be compatible with test discovery, all of the test files must be modules or packages importable from the top-level directory of the project (this means that their filenames must be valid identifiers).

Test discovery is implemented in TestLoader.discover(), but can also be used from the command line. The basic command-line usage is:

cd project_directory
python -m unittest discover

By default it looks for packages named test*.py, but this can be changed so you might use something like

python -m unittest discover --pattern=*.py

In place of your test.py script.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...