Search code examples
pythonpython-unittest

ModuleNotFoundError: No module named


I want to perform an api test. I send an image and I receive a json containing predictions. I created an app/api.py script that contains a method to send the image and receive the response.

I can't run my test, I get an error
I am positioned at the root of my project

λ python -m unittest test/test_api.py
ModuleNotFoundError: No module named 'test/test_api'

Project tree:
-app
-- api.py
-test
-- test_api.py

import unittest
from unittest.mock import Mock, patch
import os, sys

# Add the 'app' directory to the Python path
current_dir = os.path.dirname(os.path.abspath(__file__))
app_dir = os.path.join(current_dir, 'app') 
sys.path.append(app_dir)

from api import API

class TestAPI(unittest.TestCase):
    def test_api_call(self):
        // create a mock
        ...
        api = API()
        with patch('requests.post', return_value=mock_response):
           response = api.getPredFromImg(image_path)
        // Assert
        ... 

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

Solution

  • Your problem might stem from the fact that the directories which you call modules are in fact, in Python's eyes so to speak, nothing but mere directories. In order to get them to be perceived by the interpreter as modules you will have to include a __init__.py file within each directory which hosts Python code.

    Though, starting with Python version 3.3 and onwards the need for explicitly defining modules as such has faded, though in some cases sticking to the old way of doing things might prove to be correct and reduce certain errors from popping up; here is an argument as to why you might still have to include an __init__.py file:

    Is __init__.py not required for packages in Python 3.3+

    If this doesn't solve the issue, i.e. if the error still persists then, the issue might be with your new addition to the Python path, i.e. the app directory.