Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'module' object has no attribute 'py' when running from cmd

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:

enter image description here

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`
like image 366
SnuKies Avatar asked Sep 16 '16 08:09

SnuKies


2 Answers

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’
like image 136
MarAja Avatar answered Oct 18 '22 20:10

MarAja


you can add at the bottom of your script:

if __name__ == "__main__":
    unittest.main()

Then you can run python test_my_function.py normally

like image 25
Pablo Caceres Avatar answered Oct 18 '22 20:10

Pablo Caceres