I'm currently learning unittesting, and I have stumbled upon a strange error:
If I run my script from inside PyCharm, everything works perfectly. If I run it from my cmd.exe
(as administrator), I get the following error:
This is my code:
import unittest
class TutorialUnittest(unittest.TestCase):
def test_add(self):
self.assertEqual(23,23)
self.assertNotEqual(11,12)
# function for raising errors.
def test_raise(self):
with self.assertRaises(Exception):
raise Exception`
Just remove the .py
extension.
You are running your tests using the -m
command-line flag. The Python documentation will tell you more about it, just check out this link.
In a word, the -m
option let you run a module, in your case the unittest
module. This module expect to receive a module path or a class path following the Python format for module path (using dots). For example, if you want to run the FirstTest class in the mytests module in a mypackage folder you would use the following command line:
python -m unittest mypackage.mytests.FirstTest
Assuming that you are running the previous command line from the parent folder of mypackage. This allows you to select precisely the tests you want to run (even inside a module).
When you add the .py
extension, unittest
is looking for a py
object (like a module or a class) inside the last element of the module path you gave but, yet this object does not exist. This is exactly what your terminal error tells:
AttributeError: ’module’ object has no attribute ’py’
you can add at the bottom of your script:
if __name__ == "__main__":
unittest.main()
Then you can run python test_my_function.py
normally
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With