简体   繁体   中英

PyCharm run select unittests

I have a python package where all my unittest test classes are stored in modules in a subpackage mypkg.tests . In the tests/__init__.py file I have a function called suite . I normally run these tests by calling python setup.py test which has test_suite='satpy.tests.suite' . Is it possible to run this test suite from pycharm?

The reason I have the suite function is that it only contains tests that are ready to be run from my continuous integration, but other failing tests exist in the directory (from older versions of the package). I could also see this being useful for selecting quick unittests versus long running tests. I've tried running as a script, function as nosetest or unittest configurations. I've tried adding if __name__ == "__main__": and other types of command line running methods with no success.

Is there a way to run only some tests from a pycharm run configuration?

Pycharm's 'Python Unittest' configuration uses unittest.TestLoader in the background to load the tests. Now Pycharm actually tries to collect the testcases automatically, but doesn't know how to handle TestSuite instances, and even less functions returning such instances.

A workaround for your problem is to add the load_tests function to your tests/__init__.py file, like this:

def load_tests(loader, tests, pattern):
    return suite()

Then in the pycharm configuration item, choose 'Script' and give tests/__init__.py

The load_tests function actually tells the test loader what tests are available in the module :)

See more about this nifty trick here: https://docs.python.org/2.7/library/unittest.html#load-tests-protocol

Beware though, it only works with python 2.7 and later.

One thing I found it that in the particular case my Test class was from a subclass of unittest.TestCase that is defined in a local module. There is a known bug in pycharm that has been around for years that it sometimes does not fully see a local module that is in your virtualenv in some cases like marking the imports as unknown. There is a workaround for that which is to add either the egg for that local project or its source path to as a source in the project using it.

When I did that workaround for the other bug the problem went away. So it seems pycharm machinery did not recognize my Test class as a unittest.TestCase due to the other issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM