简体   繁体   中英

'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:

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM