Newbie question on tests: I have found a way but it is very fiddly - is there a better way? Spyder is so much easier!

Answered

The JetBrains documentation has examples on how to test a class, but I am struggling to understand how to test functions - not classes.

With Spyder and pytest it's pretty intuitive: I install the unittest plugin , tell Spyder in which directory to find the test, and it runs them. I then get an output that looks like this:

 

How can I do the same with PyCharm?

  • In settings - tools - Python integrated tools I have set testing to pytest
  • I have create a new project, with a file called main.py and a banal toy example function which sums two numbers
  • I then create a test_main.py file with a few banal assertions - one true, one intentionally false.
  • If I go back to main.py, place the cursor at the function, right click - goto - test, it correctly takes me to the test I have just written - great
  • However, how do I run this test?????
  • If I right click on test_main and choose "run test_main", well, it runs the file as though it were a normal file, ie nothing happens - it doesn't run the test like Spyder does!!

After some fiddling, something kinda works if I do Run - edit configuration ; choose + at the top left and choose "Python test - pytest"

But where is this documented? It is incredibly fiddly and inefficient! Do I have to do this every time? Isn't there a more automated way to tell PyCharm to run all the test?

Also, is there a more "graphical" output, something more similar to the Spyder screenshot above, or is the screenshot below all one can get with PyCharm?

 

 

 

1 comment
Comment actions Permalink

If I right click on test_main and choose "run test_main", well, it runs the file as though it were a normal file

Actually, it should work just fine. Do you have a gutter icon next to the test method?

Try removing any existing Run Configurations for test_main.py from Run -> Edit Configurations. If PyCharm sees an existing configuration (e.g "pure Python" one for a test file) it will use it by default instead of creating a new one, which may be confusing. You can also workaround this by using Run -> Run ... menu.

0

Please sign in to leave a comment.