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.
Related
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!
I get the following error when I try to run a pyVows test:
Traceback (most recent call last):
File "C:\Program Files\Python38\lib\unittest\loader.py", line 436, in _find_test_path
module = self._get_module_from_name(name)
File "C:\Program Files\Python38\lib\unittest\loader.py", line 377, in _get_module_from_name
__import__(name)
File "D:\Programmierung\Python-Projekte\JourneyMap\JourneyMap\tests.py", line 2, in <module>
from django_pyvows.context import DjangoHTTPContext
File "C:\Users\malo0\AppData\Roaming\Python\Python38\site-packages\django_pyvows\__init__.py", line 11, in <module>
from context import DjangoContext, DjangoHTTPContext
ModuleNotFoundError: No module named 'context'
I installed pyVows and django-pyvows Am I missing something? I found no helpful documentation
REQUESTED EDIT:
from pyvows import Vows, expect
from django_pyvows.context import DjangoHTTPContext
# Create your tests here.
#Vows.batch
class LanguageTest(Vows.Context):
class LanguageSelectIntegrationTest(DjangoHTTPContext):
def topic(self):
return self.get('/')
def test(self, topic):
# Test will be here
pass
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()
I followed the steps here https://developers.google.com/cloud-sql/docs/django and it ran well with django 1.3.1. Now up to Django 1.4 and gives a funny stack trace. I would paste the relevant part of the message here
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/dumb906/woody/py/mdlr/django/core/management/__init__.py", line 443, in execute_from_command_line
utility.execute()
File "/home/dumb906/woody/py/mdlr/django/core/management/__init__.py", line 382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/dumb906/woody/py/mdlr/django/core/management/__init__.py", line 261, in fetch_command
klass = load_command_class(app_name, subcommand)
File "/home/dumb906/woody/py/mdlr/django/core/management/__init__.py", line 69, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "/home/dumb906/woody/py/mdlr/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/home/dumb906/woody/py/mdlr/django/core/management/commands/test.py", line 7, in <module>
from django.test.utils import get_runner
File "/home/dumb906/woody/py/mdlr/django/test/__init__.py", line 5, in <module>
from django.test.client import Client, RequestFactory
File "/home/dumb906/woody/py/mdlr/django/test/client.py", line 21, in <module>
from django.test import signals
File "/home/dumb906/woody/py/mdlr/django/test/signals.py", line 2, in <module>
from django.db import connections
File "/home/dumb906/woody/py/mdlr/django/db/__init__.py", line 40, in <module>
backend = load_backend(connection.settings_dict['ENGINE'])
File "/home/dumb906/woody/py/mdlr/django/db/__init__.py", line 34, in __getattr__
return getattr(connections[DEFAULT_DB_ALIAS], item)
File "/home/dumb906/woody/py/mdlr/django/db/utils.py", line 92, in __getitem__
backend = load_backend(db['ENGINE'])
File "/home/dumb906/woody/py/mdlr/django/db/utils.py", line 44, in load_backend
raise ImproperlyConfigured(error_msg)
django.core.exceptions.ImproperlyConfigured: 'google.appengine.ext.django.backends.rdbms' isn't an available database backend.
Try using django.db.backends.XXX, where XXX is one of:
'dummy', 'mysql', 'oracle', 'postgresql_psycopg2', 'sqlite3'
Error was: cannot import name Thing2Literal
Any help? Some one said it needs to be compiled http://django-irc-logs.com/2012/mar/27/ ?
I had the same issue. Since the problem is with importing Thing2Literal that is used by adapt_datetime_with_timezone_support function from django/db/backends/mysql/base.py and according to this:
https://code.djangoproject.com/changeset/17596/django/trunk/django/db/backends/mysql/base.py this is important only to datetime objects that bypass the model layer and are used with raw sql. So i decided it is not important for me and I messed a bit my django/db/backends/mysql/base.py: comment out code that causes trouble (import of Thing2Literal, adapt_datetime_with_timezone_support function and line 83 where the function is called)
Of course I upload my django 1.4 customized that way to appengine together with my project and it works.
I would appreciate feedback from those who understand django internals better, whether what i've done is ok assuming i don't use raw sql at all.
As you can see in the documentation you've linked, Google App Engine support only Django up to version 1.3 (actually 1.3.1).
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.