Python3 test import error
Question: I am using python3 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.


Answer: 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`

