Search code examples
pythonemacselpy

Better python unittest integration?


I'm using GNU Emacs 24.5.1 to work on Python code. I often want to run just a single unit test. I can do this, for example, by running:

test=spi.test_views.IndexViewTest.generate_select2_data_with_embedded_spaces  make test

with M-X compile. My life would be simpler if I could give some command like "Run the test where point is", and have emacs figure out the full name of the test for me. Is possible?

Update: with the folowing buffer, I'd like some command which runs M-X compile with:

test=spi.test_views.IndexViewTest.test_unknown_button make test

where spi is the name of the directory test_views.py is in. Well, technically, I need to construct the python path to my test function, but in practice, it'll be <directory.file.class.function>.

This seems like the kind of thing somebody would have already invented, but I don't see anything in the python mode docs.

enter image description here


Solution

  • I believe you use the "default" python mode, while the so-called elpy mode (that I strongly recommend giving a try when doing Python developments within Emacs) seems to provide what you are looking for:

     C-c C-t (elpy-test)
    
    Start a test run. This uses the currently configured test runner to discover
    and run tests. If point is inside a test case, the test runner will run exactly
    that test case. Otherwise, or if a prefix argument is given, it will run all tests.
    

    Extra details

    The elpy-test function internally relies on the function (elpy-test-at-point), which appears to be very close to the feature you mentioned in the question.

    See e.g. the code/help excerpt in the following screenshot:

    elpy-test