Skip to content
Advertisement

Installed app in Django not found when running tests

I have a pretty simple Django app, that I am trying to run unit tests on. In my tests.py file I am trying to import the parent apps views file. I tried from . import views but got an error:

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

I read that when a relative path does not work, you can try using an absolute path so I tried from menu import views but than got another error:

ImportError: No module named 'menu'

When I run a local server for the application it works just fine. Its only when I run coverage run 'coverage run menu/tests.py. Since it is running fine, and the module is in my settings installed apps, I’m not entirely sure why this is happening.

menu/tests.py

import unittest

from menu import views

class ModelTestCase(unittest.TestCase):
    def setUp(self):
        pass

    def test_menu(self):
        pass

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

settings.py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'menu',
    'django_nose'
)

Traceback

timothybaney$ coverage run menu/tests.py
Traceback (most recent call last):
  File "menu/tests.py", line 3, in <module>
    from menu import views
ImportError: No module named 'menu'

Advertisement

Answer

It’s not much information you gave us.. but when I take a look at the Traceback it says File 'menu/tests.py'. So if the views.py is also inside the menu Folder you just can write:

import views

If the views.py is in the main folder you could write:

from ..main import views   #replace 'main' with your folder name
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement