2

I have a file calc.py where I have methods for basic calculations.Now I create another file (in the same directory) called test_calc.py for unittesting the methods in calc.py file.But when I try to run test_calc.py either through command line using

python3 -m unittest test_calc.py

or since I have included name == "main"

python3 test_calc.py

or try to run it directly through the IDE,I get an error that says

from . import calc
SystemError: Parent module '' not loaded, cannot perform relative import

Below is the screenshot of my project structure

enter image description here

Below is the screenshot of how I import the calc.py file and it accepts the import

enter image description here

This is the code in test_calc.py file which unitests the methods defined in calc.py file

import unittest
from . import calc

class TestCalc(unittest.TestCase):
    def test_add(self):
        result = calc.add(5,2)
        self.assertEqual(result,7)

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

When I run the above code, Python thows error.What is going wrong?

Souvik Ray
  • 2,899
  • 5
  • 38
  • 70

1 Answers1

0

You can refer to "Relative imports in Python 3", which suggests, amongst other alternative

python3 -m unittest mypackage.test_calc.py

Try at least to not have a space in your 'unittest module' folder.

See also PEP 366.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • "Try at least to not have a space in your 'unittest module' folder." --- This solved the problem!Thanks again! – Souvik Ray Oct 15 '17 at 07:50
  • I renamed the folder to unittest_module.So instead of doing from . import calc, I did from unittest_module import calc and it worked. – Souvik Ray Oct 15 '17 at 07:51