malenkiy_scot
malenkiy_scot

Reputation: 16615

Running Python package unit tests in PyCharm

I just 'ported' a Python package I'm writing to PyCharm and having a bit of trouble running unit tests for the whole package from the IDE.

In __init__.py for the package I have load_tests function that goes over all modules in the package and loads relevant tests. It runs splendidly with:

$python -m unittest my_package

However, when I try running it from PyCharm (by selecting the top directory in the Projects window and hitting Ctrl+Shift+F10) I get No tests were found in the Run window, and

...\python.exe ...\pycharm\utrunner.py .../my_package/ true
Testing started at ...
Process finished with exit code 0
Empty test suite.

in the console window.

I took a quick look at PyCharm's utrunner.py and it seems that it is looking for modules with a certain pattern (that start with test). I would like to preserve the present vanilla approach. How can I configure PyCharm to use load_tests from __init__.py while modifying the code as little as possible?

By the way, test suites for individual modules run just fine from PyCharm.

Using PyCharm 3.1 Community Edition, Python 2.7.

Upvotes: 6

Views: 14709

Answers (2)

xmedeko
xmedeko

Reputation: 7820

With PyCharm 2016.2 use:

  • Test: Script
  • Script: /path/to/tests/__init__.py
  • Check Inspect only subclasses of unittest.TestCase. This causes utrunner to use unittest.TestLoader.loadTestsFromModule() and that method call load_tests() if present in the module.

I.e. the command is

python C:\python\pycharm\helpers\pycharm\utrunner.py /path/to/tests/__init__.py true

I had to remove the tests directory from the sys.path in the __init__.py as well (see PY-15889):

basedir = os.path.dirname(__file__)
try:
    sys.path.remove(basedir)
except ValueError:
    pass

Upvotes: 2

this.myself
this.myself

Reputation: 2190

This answer has been written considering PyCharm 3.4.

Had the same problem, found solution for the problem in this answer, hope I understood your question right:

https://stackoverflow.com/a/12242021/2427749

I configured my Python Test runner configuration like this:

  • Checked 'All in Folder'
  • Pattern is the Regular Expression '.*_Test.py' (without quotes)
  • Checked 'Inspect only subclass for unittest.TestCase'.

Now it finds my unitests in my subfolders named like classToBeTested_Test.py

by the way, I'm facing another problem now: the unit test cannot import the module to be tested. Cause of different root folder I think.

Upvotes: 5

Related Questions