I'm practicing working with unittest, and I tried the following in PyCharm:
import unittest
from format_name import name_formatted
class TestName_formatted(unittest.TestCase):
"""practice with unittest"""
def test_name(self):
"""Testing name_formatted function"""
formatted_name = name_formatted("mike", "Cronin")
self.assertEqual(formatted_name, "mike Cronin")
unittest.main()
After research, I saw that it was written like this:
if __name__ == "__main__":
unittest.main()
And suddenly it worked perfectly. HOWEVER, the reason I wrote it that way, without the if statement, is because that's how I learned it from "Python Crash Course" which uses GEANY and IDLE for its example code. And sure enough, in both of those programs, you don't need the if statement.
Why is it that in one IDE the code doesn't work and in the others it does?
You are running the code in PyCharm as if it were a normal Python application; which is why you need the if __name__ == '__main__'
conditional. This is also best practice when writing modules (files) that can be imported or run at the command line - the case with unit tests.
PyCharm is basically trying to do python your_file_name.py
The reason IDLE doesn't need this is because IDLE is running the application by first loading the file in the Python shell.
What IDLE is doing is:
python
>>> import your_file_name
By doing so, the code is automatically evaluated, the function is called and thus the test runs.
I would also suggest reading the documentation on testing in PyCharm's manual as testing is something PyCharm has extensive support for. In that link you'll also notice the default stub (or template) for a sample test case already has the if __name__ == '__main__'
check: