Problem with Django app unit tests under Visual Studio Code - django

I have a draft of the Django project with the added one application (e.g. my_app). In this app I have places tests.py file with one test:
import unittest
class Test_MyModel(unittest.TestCase):
def test_dummy(self):
self.assertEqual(1,1)
In this case, this dummy test is discoverd by Visual Studio Code and could be executed in it, also it's possible to launch this test from command line:
python manage.py test
When I modify my file with unit test add import some model (placed in file models.py) from my_app:
import unittest
from .models import MyModel # new added line
class Test_MyModel(unittest.TestCase):
def test_dummy(self):
self.assertEqual(1,1)
In this case I'm still be able run test from command line without any problems, but VSC doesn't discover my test and in the Python Test Log in the VSC I get error:
======================================================================
ERROR: tests (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: tests
Traceback (most recent call last):
File "/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/loader.py", line 434, in _find_test_path
module = self._get_module_from_name(name)
File "/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/loader.py", line 375, in _get_module_from_name
__import__(name)
File "/Users/myuser/Projects/backend/my_app/tests.py", line 3, in <module>
from my_app.models import MyModel
File "/Users/myuser/Projects/backend/my_app/models.py", line 4, in <module>
class MyModel(models.Model):
File "/Users/myuser/Projects/virtualenvs/my_app_env/lib/python3.7/site-packages/django/db/models/base.py", line 103, in __new__
app_config = apps.get_containing_app_config(module)
File "/Users/myuser/Projects/virtualenvs/my_app_env/lib/python3.7/site-packages/django/apps/registry.py", line 252, in get_containing_app_config
self.check_apps_ready()
File "/Users/myuser/Projects/virtualenvs/my_app_env/lib/python3.7/site-packages/django/apps/registry.py", line 134, in check_apps_ready
settings.INSTALLED_APPS
File "/Users/myuser/Projects/virtualenvs/my_app_env/lib/python3.7/site-packages/django/conf/__init__.py", line 79, in __getattr__
self._setup(name)
File "/Users/myuser/Projects/virtualenvs/my_app_env/lib/python3.7/site-packages/django/conf/__init__.py", line 64, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
Any hints or advice how can I resolve this problem and start fully using unit test under VSC for models test?

I've found a solution to my problem. I need to add below lines into my init.py file in my_app folder.
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_app_project.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

Related

How to properly import an existing Django project in Eclipse/Pydev?

I cannot figure how to import correctly an existing Django project in Eclipse/Pydev, and I can't find my way in the documentation of Pydev. My question is pretty simple : I have an existing project from a different computer, that I want to migrate on a new one.
I installed Eclipse and Pydev on the new machine, and everything seems normal for a new project: I can create a new Django project and run it without issue. I also have been able to import my pre-existing project, but when I run the project, I encounter the following error :
Finding files... done.
Importing test modules ... Traceback (most recent call last):
File "/home/francois/.p2/pool/plugins/org.python.pydev.core_9.3.0.202203051235/pysrc/_pydev_runfiles/pydev_runfiles.py", line 468, in __get_module_from_str
mod = __import__(modname)
File "/home/francois/eclipse-workspace/Test/Test/urls.py", line 20, in <module>
path('', include('myApp.urls')),
File "/home/francois/anaconda3/envs/ipaidenv/lib/python3.10/site-packages/django/urls/conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "/home/francois/anaconda3/envs/ipaidenv/lib/python3.10/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "/home/francois/eclipse-workspace/Test/myApp/urls.py", line 2, in <module>
from . import views
File "/home/francois/eclipse-workspace/Test/myApp/views.py", line 2, in <module>
from myApp.forms import CreateGroupForm, JoinGroupForm
File "/home/francois/eclipse-workspace/Test/myApp/forms.py", line 4, in <module>
from .models import Group, User
File "/home/francois/eclipse-workspace/Test/myApp/models.py", line 2, in <module>
from django.contrib.auth.models import AbstractUser
File "/home/francois/anaconda3/envs/ipaidenv/lib/python3.10/site-packages/django/contrib/auth/models.py", line 3, in <module>
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
File "/home/francois/anaconda3/envs/ipaidenv/lib/python3.10/site-packages/django/contrib/auth/base_user.py", line 48, in <module>
class AbstractBaseUser(models.Model):
File "/home/francois/anaconda3/envs/ipaidenv/lib/python3.10/site-packages/django/db/models/base.py", line 108, in __new__
app_config = apps.get_containing_app_config(module)
File "/home/francois/anaconda3/envs/ipaidenv/lib/python3.10/site-packages/django/apps/registry.py", line 253, in get_containing_app_config
self.check_apps_ready()
File "/home/francois/anaconda3/envs/ipaidenv/lib/python3.10/site-packages/django/apps/registry.py", line 136, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
ERROR: Module: Test.urls could not be imported (file: /home/francois/eclipse-workspace/Test/Test/urls.py).
done.
Traceback (most recent call last):
File "/home/francois/.p2/pool/plugins/org.python.pydev.core_9.3.0.202203051235/pysrc/runfiles.py", line 273, in <module>
main()
File "/home/francois/.p2/pool/plugins/org.python.pydev.core_9.3.0.202203051235/pysrc/runfiles.py", line 97, in main
return pydev_runfiles.main(configuration) # Note: still doesn't return a proper value.
File "/home/francois/.p2/pool/plugins/org.python.pydev.core_9.3.0.202203051235/pysrc/_pydev_runfiles/pydev_runfiles.py", line 874, in main
PydevTestRunner(configuration).run_tests()
File "/home/francois/.p2/pool/plugins/org.python.pydev.core_9.3.0.202203051235/pysrc/_pydev_runfiles/pydev_runfiles.py", line 801, in run_tests
get_django_test_suite_runner()(run_tests).run_tests([])
File "/home/francois/anaconda3/envs/ipaidenv/lib/python3.10/site-packages/django/test/runner.py", line 723, in run_tests
databases = self.get_databases(suite)
File "/home/francois/anaconda3/envs/ipaidenv/lib/python3.10/site-packages/django/test/runner.py", line 702, in get_databases
databases = self._get_databases(suite)
File "/home/francois/anaconda3/envs/ipaidenv/lib/python3.10/site-packages/django/test/runner.py", line 690, in _get_databases
for test in suite:
TypeError: 'NoneType' object is not iterable
ipaidenv is the name of my conda environment, Test is the project name.
I am pretty sure there is something very simple that I didn't do right, but I can't find what, can anyone help?
Many thanks!

Why I get error raise ImproperlyConfigured

I want to add info in database using django-seed.
seed.py
from django_seed import Seed
from models import Employee
seeder = Seed.seeder()
seeder.add_entity(Employee, 5)
inserted_pks = seeder.execute()
When I try to start command: python3 seed.py
I've got this error:
Traceback (most recent call last):
File "seed.py", line 2, in <module>
from models import Employee
File "/home/kaucap/test/myproject/app_worker/models.py", line 4, in <module>
class Employee(models.Model):
File "/home/kaucap/test/venv/lib/python3.8/site-packages/django/db/models/base.py", line 127, in __new__
app_config = apps.get_containing_app_config(module)
File "/home/kaucap/test/venv/lib/python3.8/site-packages/django/apps/registry.py", line 260, in get_containing_app_config
self.check_apps_ready()
File "/home/kaucap/test/venv/lib/python3.8/site-packages/django/apps/registry.py", line 137, in check_apps_ready
settings.INSTALLED_APPS
File "/home/kaucap/test/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 87, in __getattr__
self._setup(name)
File "/home/kaucap/test/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 67, in _setup
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
Can anyone explain why I have this error and how I can fix it?
python3 seed.py started python without Django settings.
if you are want to start seed.py in Django "environment",
in your django-pproject folder:
python3 manage.py shell
Django shell starts, and in shell:
import seed.py
If you see the same error - you have not created any Django project yet.

Standalone Django application with pyinstaller on Windows

I need to package a (rather simple) django application into a standalone executable on windows. After some failed attempts with py2exe (I really don't understand why everybody recommends it for django, it seems extremely complicated to set up) I tried pyinstaller. It does package the application without complaining, but if I try to run it using myapp.exe runserver localhost:8000, I am getting the following error:
Traceback (most recent call last):
File "<string>", line 5, in <module>
File "c:\python27\lib\site-packages\PyInstaller-2.1-py2.7.egg\PyInstaller\loader\pyi_importers.py", line 270, in load_
module
exec(bytecode, module.__dict__)
File "...\build\ck\out00-PYZ.pyz\django.test", line 5, in <module>
File "c:\python27\lib\site-packages\PyInstaller-2.1-py2.7.egg\PyInstaller\loader\pyi_importers.py", line 270, in load_
module
exec(bytecode, module.__dict__)
File "...\build\ck\out00-PYZ.pyz\django.test.client", line 21, in <module>
File "c:\python27\lib\site-packages\PyInstaller-2.1-py2.7.egg\PyInstaller\loader\pyi_importers.py", line 270, in load_
module
exec(bytecode, module.__dict__)
File "...\build\ck\out00-PYZ.pyz\django.db", line 11, in <module>
File "...\build\ck\out00-PYZ.pyz\django.conf", line 52, in __getattr__
File "...\build\ck\out00-PYZ.pyz\django.conf", line 45, in _setup
django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must eith
er define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
My manage.py script looks like this:
#!/usr/bin/env python
import os
import sys
import Cookie
import django.test
import HTMLParser
from django.conf import settings
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
Why does it not recognize the environment variable and how can I fix that?
I solved it by importing django.test after the line
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")

error in setting up lettuce with django test

I am trying to connect lettuce with standard django test. Lettuce works fine when working on its own. However, when I import Client from django.test.client I get the error:
"Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined."
My steps.py looks like:
from lettuce import *
from django.test.client import Client
#before.all
def set_browser():
world.browser = Client()
#step(r'I access the url "(.*)"')
def have_the_number(step,url):
world.response = world.browser.get(url)
I get the following error
File "/usr/local/bin/lettuce", line 9, in <module>
load_entry_point('lettuce==0.1.34', 'console_scripts', 'lettuce')()
File "/Library/Python/2.7/site-packages/lettuce-0.1.34-py2.7.egg/lettuce/lettuce_cli.py", line 71, in main
result = runner.run()
File "/Library/Python/2.7/site-packages/lettuce-0.1.34-py2.7.egg/lettuce/__init__.py", line 114, in run
self.loader.find_and_load_step_definitions()
File "/Library/Python/2.7/site-packages/lettuce-0.1.34-py2.7.egg/lettuce/fs.py", line 42, in find_and_load_step_definitions
module = __import__(to_load)
File "/Users/aliahsan/djcode/drftest/features/steps.py", line 2, in <module>
from django.test.client import Client
File "/Library/Python/2.7/site-packages/django/test/__init__.py", line 5, in <module>
from django.test.client import Client, RequestFactory
File "/Library/Python/2.7/site-packages/django/test/client.py", line 27, in <module>
from django.db import transaction, close_connection
File "/Library/Python/2.7/site-packages/django/db/__init__.py", line 14, in <module>
if not settings.DATABASES:
File "/Library/Python/2.7/site-packages/django/utils/functional.py", line 276, in __getattr__
self._setup()
File "/Library/Python/2.7/site-packages/django/conf/__init__.py", line 40, in _setup
raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
I have tried to set the DJANGO_SETTINGS_MODULE variable in init.py file but it doesn't work either.
Can someone help me with this?
I had actually been following the getting started tutorial and was using Lettuce command from within the app folder and it wasn't locating any settings file for django. Got the fix after realizing to,
run
python manage.py harvest
command from the project folder and it works. You can mention the app next to harvest if you want to test just a particular app in your project. By default it tests all the features in all the apps installed in your settings file.

Mocking Django for plugin: can't find settings.py

I'm trying to write test for a django plugin called Dynamic Response (available on GitHub), but I'm having some issues. Using mock I'm trying to mock certain Django methods like render_to_response, (i'm not going to test django after all) but when I try to do so, i get an error message saying it can't find settings.py, which it shouldn't as this is a plugin to be used in other projects, not a project in itself. I've tried the following code:
class ResponseTest (unittest.TestCase):
#patch('dynamicresponse.response.render_to_response')
def test_is_testframework_working(self, render_to_response):
from dynamicresponse.response import SerializeOrRender
SerializeOrRender()
Which, as stated, gives an error message. Stubbing HttpResponse, HttpRedirect does not throw these errors...
gives the following stacktrace
Response (unittest.loader.ModuleImportFailure) ... ERROR
======================================================================
ERROR: response (unittest.loader.ModuleImportFailure)
----------------------------------------------------------------------
ImportError: Failed to import test module: response
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/loader.py", line 252, in _find_tests
module = self._get_module_from_name(name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/loader.py", line 230, in _get_module_from_name
__import__(name)
File "/Users/skinney/Workspace/django-dynamicresponse/tests/response.py", line 5, in <module>
class ResponseTest (unittest.TestCase):
File "/Users/skinney/Workspace/django-dynamicresponse/tests/response.py", line 7, in ResponseTest
#patch('dynamicresponse.response.render_to_response')
File "/Users/skinney/Workspace/django-dynamicresponse/tests/mock.py", line 720, in patch
target = _importer(target)
File "/Users/skinney/Workspace/django-dynamicresponse/tests/mock.py", line 514, in _importer
thing = _dot_lookup(thing, comp, import_path)
File "/Users/skinney/Workspace/django-dynamicresponse/tests/mock.py", line 503, in _dot_lookup
__import__(import_path)
File "/Users/skinney/Workspace/django-dynamicresponse/dynamicresponse/response.py", line 3, in <module>
from django.shortcuts import render_to_response
File "/Library/Python/2.7/site-packages/django/shortcuts/__init__.py", line 10, in <module>
from django.db.models.manager import Manager
File "/Library/Python/2.7/site-packages/django/db/__init__.py", line 14, in <module>
if not settings.DATABASES:
File "/Library/Python/2.7/site-packages/django/utils/functional.py", line 276, in __getattr__
self._setup()
File "/Library/Python/2.7/site-packages/django/conf/__init__.py", line 40, in _setup
raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (errors=1)
You can't test django apps without any project (real or dummy, whatever) having its own settings file.