0

I am using Python 3 to try and get a test file for sample application working yet it keeps throwing ImportError: No module named 'calculate'

My file structure is:

/calculate
  __init__.py
  calculate.py
  test/
    __init__.py
    calculate_test.py

I cannot figure out why this is the case, any help would be much appreciated.

The __init__.py files are empty.

calculate.py contains:

class Calculate(object):
    def add(self, x, y):
        return x + y

if __name__ == '__main__':
    calc = Calculate()
    result = calc.add(2, 2)
    print(result)

calculate_test.py contains:

import unittest
from calculate import Calculate

class TestCalculate(unittest.TestCase):
    def setUp(self):
        self.calc = Calculate()

    def test_add_method_returns_correct_result(self):
        self.assertEqual(4, self.calc.add(2,2))

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

I am running python test/calculate_test.py from the root /calculate folder and am getting the error

Traceback (most recent call last):
  File "test/calculate_test.py", line 2, in <module>
    from calculate import Calculate
ImportError: No module named 'calculate'

I have been fiddling around with different structures and cannot understand what the problem is.

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
SJC
  • 2,767
  • 4
  • 20
  • 31
  • maybe this helps: http://stackoverflow.com/questions/4142151/python-how-to-import-the-class-within-the-same-directory-or-sub-directory – joel goldstick Jul 06 '16 at 21:31

1 Answers1

0

Your project's structure is the reason. The test script doesn't have the outer directory in the search path when you start it. Here are some ways to fix that

  1. Move the test file into the same directory that contains the module it imports. That will require no changes in the test file.
  2. Use this structure

    ./project/
        calculate_test.py
        calculate/
            __init__.py
            calculate.py
    

    This will require you to change the import signature in calculate_test.py to something like from calculate import calculate

Eli Korvigo
  • 10,265
  • 6
  • 47
  • 73
  • I am now getting an error saying `name Calculate is not defined` when defining `self.calc = Calculate()` in the setup method. – SJC Jul 06 '16 at 21:43
  • calculate_test.py needs to access Calculate from calculate/calculate.py, so you need "from calculate.calculate import Calculate" – λuser Jul 06 '16 at 21:56
  • I think it's better practice to have the tests inside the packages hierarchy – λuser Jul 06 '16 at 21:59
  • @λuser what structure do you suggest? I would ideally like to have a tests folder to separate out the classes and test files – SJC Jul 06 '16 at 22:04
  • I'd suggest doing like this: http://stackoverflow.com/a/5998845 Having tests in a hierarchy allows sharing stuff between them, better organization, etc. – λuser Jul 06 '16 at 22:11