Django Test unittest.loader.ModuleImportFailure - python

I can't import my models in my tests directory, this is my error :
======================================================================
ERROR: tests.test_views (unittest.loader.ModuleImportFailure)
----------------------------------------------------------------------
ImportError: Failed to import test module: tests.test_views
Traceback (most recent call last):
File "C:\Python27\lib\unittest\loader.py", line 254, in _find_tests
module = self._get_module_from_name(name)
File "C:\Python27\lib\unittest\loader.py", line 232, in _get_module_from_name
__import__(name)
File "c:\wamp\www\km0\tests\test_views.py", line 3, in <module>
from .models import Entreprise
File "c:\wamp\www\km0\tests\models.py", line 6, in <module>
class Entreprise(models.Model):
File "C:\Python27\lib\site-packages\django-1.9.5-py2.7.egg\django\db\models\ba
se.py", line 102, in __new__
"INSTALLED_APPS." % (module, name)
RuntimeError: Model class tests.models.Entreprise doesn't declare an explicit ap
p_label and isn't in an application in INSTALLED_APPS.
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (errors=1)
Preserving test database for alias 'default' ('test_km0')...
I did some research and couldn't find an answer ...
test_views.py :
from django.test import TestCase
import unittest
from .models import Entreprise
class Km0ViewsTestCase(TestCase):
def test_cart(self):
resp = self.client.get('/fr/cart/')
self.assertEqual(resp.status_code, 200)
resp = self.client.get('/en/cart/')
self.assertEqual(resp.status_code, 200)
resp = self.client.get('/de/cart/')
self.assertEqual(resp.status_code, 200)
My directory :
my directory
Thanks in advance for your help !

You shouldn't normally need a models.py in your tests directory.
If you want to import your Entreprise model from the front app, then change your import from
from .models import Entreprise
to
from front.models import Entreprise

Related

RuntimeError: populate() isn't reentrant import loop

I have my models.py file import an external function which then writes to a specific model. I think this is some sort of import loop but I'm not sure.
This is a partial traceback
File "path/Directory/Package/models.py", line 19, in <module>
from externalFunction import myFunction
File "path/Directory/externalFunction.py", line 9, in <module>
django.setup()
File "/path/anaconda3/envs/myEnv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/path/anaconda3/envs/Brew/lib/python3.6/site-packages/django/apps/registry.py", line 83, in populate
raise RuntimeError("populate() isn't reentrant")
RuntimeError: populate() isn't reentrant
File structure
>Directory
manage.py
externalFunction.py
>Package
models.py
>Package_api
wsgi.py
models.py
from django.db import models
import sys
sys.path.append("..")
from externalFunction import myFunction
class Job(models.Model):
name = models.CharField(
max_length=30,
default="name")
#receiver(post_save, sender=Job, dispatch_uid="run function")
def run_function(sender, instance, created, *args, **kwargs):
someOtherFunction()
myFunction()
externalFunction.py
import django
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Package_api.settings')
django.setup()
from Package.models import Job
def myFunction():
some stuff
I've tried removing django.setup() from externalFunction.py but then it cannot import Job from the models.

Python Nosetest - How to mock MySQLdb

I'm trying to mock the MySQLdb lib from my project but I don't really understood how to do it:
Here's my test code:
import unittest
from mock import MagicMock
from core.distrib.main.CentralDistDraw import CentralDistDraw
from connector.mysql import MySQL
class CentralDistDraw(unittest.TestCase):
def test_hello(self):
draw = CentralDistDraw()
msql = MySQL()
msql.getConnection = MagicMock()
Here's my class:
from datetime import datetime
import logging
from core.distrib.config.PromoConstants import PromoConstants
from dateutil.parser import parse
from google.appengine.api import memcache
from connector.mysql import MySQL
from core.distrib.ndb.userpromo import UserPromo
from core.distrib.ndb.drawinfo import DrawInfo
import traceback
class CentralDistDraw(object):
def getNextNumber(self, idUser, amountDefault=1, amountSpecial=1):
numbersDelivered = []
# DB CONTROLL....
db = MySQL().getConnection()
db.autocommit(False)
currentUser = None
Error thrown:
ERROR: Failure: ImportError (/home/dyego/Documents/code-stuff/mod/pdbcontest2/src/lib/_mysql.so: invalid ELF header)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/nose-1.3.7-py2.7.egg/nose/loader.py", line 418, in loadTestsFromName
addr.filename, addr.module)
File "/usr/local/lib/python2.7/dist-packages/nose-1.3.7-py2.7.egg/nose/importer.py", line 47, in importFromPath
return self.importFromDir(dir_path, fqname)
File "/usr/local/lib/python2.7/dist-packages/nose-1.3.7-py2.7.egg/nose/importer.py", line 94, in importFromDir
mod = load_module(part_fqname, fh, filename, desc)
File "/home/dyego/Documents/code-stuff/mod/pdbcontest2/src/tests/core/test_central_dist_draw.py", line 4, in <module>
from core.distrib.main.CentralDistDraw import CentralDistDraw
File "/home/dyego/Documents/code-stuff/mod/pdbcontest2/src/core/distrib/main/CentralDistDraw.py", line 11, in <module>
from connector.mysql import MySQL
File "/home/dyego/Documents/code-stuff/mod/pdbcontest2/src/connector/mysql.py", line 8, in <module>
import MySQLdb
File "/usr/lib/python2.7/dist-packages/MySQLdb/__init__.py", line 19, in <module>
import _mysql
ImportError: /home/dyego/Documents/code-stuff/mod/pdbcontest2/src/lib/_mysql.so: invalid ELF header
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
Anyone knows the correct way to go when comes to testing third party libraries?
Thanks!

Coverage : ImportError: cannot import name config

When I try to run this code I am getting: ImportError: cannot import name config in line 32 of this file:
lib/python2.7/site-packages/tests/functional_tests/fixtures/__init__.py
Any idea about the reason of this error?
import os
COV = None
if os.environ.get('FLASK_COVERAGE'):
import coverage
COV = coverage.coverage(branch=True, include='app/*')
COV.start()
from flask.ext.script import Manager, Shell
from app import create_app, db
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
#manager.command
def test(coverage=False):
"""Run the unit tests."""
if coverage and not os.environ.get('FLASK_COVERAGE'):
import sys
os.environ['FLASK_COVERAGE'] = '1'
os.execvp(sys.executable, [sys.executable] + sys.argv)
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
if COV:
COV.stop()
COV.save()
print('Coverage Summary:')
COV.report()
basedir = os.path.abspath(os.path.dirname(__file__))
covdir = os.path.join(basedir, 'tmp/coverage')
COV.html_report(directory=covdir)
print('HTML version: file://%s/index.html' % covdir)
COV.erase()
if __name__ == '__main__':
manager.run()
error log:
python coverage.py test
ERROR: tests.functional_tests.test_providers (unittest.loader.ModuleImportFailure)
----------------------------------------------------------------------
ImportError: Failed to import test module: tests.functional_tests.test_providers
Traceback (most recent call last):
File "/usr/lib/python2.7/unittest/loader.py", line 252, in _find_tests
module = self._get_module_from_name(name)
File "/usr/lib/python2.7/unittest/loader.py", line 230, in _get_module_from_name
__import__(name)
File "/home/vagrant/myproject/venv/local/lib/python2.7/site-packages/tests/functional_tests/__init__.py", line 1, in <module>
from . import fixtures
File "/home/vagrant/myproject/venv/local/lib/python2.7/site-packages/tests/functional_tests/fixtures/__init__.py", line 32, in <module>
from tests.functional_tests import config
ImportError: cannot import name config
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)

Some errors in my first Django cassandra code

I want to run my first Django cassandra code in pyCharm.
My code is running smoothly in Django console but it's not working in a .py file. these are the errors:
C:\Python27\python.exe "D:/Developer Center/PyCharm/DJangoCassandra/MyApp/testFile.py"
Traceback (most recent call last):
File "D:/Developer Center/PyCharm/DJangoCassandra/MyApp/testFile.py", line 3, in <module>
from MyApp.models import Person
File "D:\Developer Center\PyCharm\DJangoCassandra\MyApp\models.py", line 1, in <module>
from django.db import models
File "C:\Python27\lib\site-packages\django\db\__init__.py", line 11, in <module>
if settings.DATABASES and DEFAULT_DB_ALIAS not in settings.DATABASES:
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 53, in __getattr__
self._setup(name)
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 46, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
Process finished with exit code 1
this is my .py file:
__author__ = 'ehsan'
from cqlengine import connection
from MyApp.models import Person
from cqlengine.management import sync_table,drop_table
def main():
connection.setup(['127.0.0.1:9160'])
sync_table(Person)
Person.create(id='2',name='Ali',family='Rezayee')
p = Person.objects.all()
for item in p:
print item.id
Person.filter(id='1')
this is my model:
from django.db import models
from cqlengine import Model, columns
# Create your models here.
class Person(Model):
id = columns.Text(primary_key=True)
name = columns.Text()
family = columns.Text()
If you'll write the following lines when starting the managy.py shell command, it should work:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "zoo.settings")

How do I deserialize this JSON object?

import simplejson
from urllib2 import urlopen
from simplejson import loads
from django.core import serializers
content = loads(urlopen('https://graph.facebook.com/1234676502/feed').read())
content = simplejson.dumps(content,sort_keys=True, indent=4)
print content
json_serializer = serializers.get_serializer("json")()
json_serializer.deserialize(content)
While running the above python code im getting the following error:
Traceback (most recent call last):
File "/var/www/youedo/test.py", line 22, in <module>
json_serializer = serializers.get_serializer("json")()
File "/usr/local/lib/python2.6/dist-packages/django/core/serializers/__init__.py", line 63, in get_serializer
_load_serializers()
File "/usr/local/lib/python2.6/dist-packages/django/core/serializers/__init__.py", line 109, in _load_serializers
register_serializer(format, BUILTIN_SERIALIZERS[format], serializers)
File "/usr/local/lib/python2.6/dist-packages/django/core/serializers/__init__.py", line 51, in register_serializer
module = importlib.import_module(serializer_module)
File "/usr/local/lib/python2.6/dist-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/usr/local/lib/python2.6/dist-packages/django/core/serializers/xml_serializer.py", line 6, in <module>
from django.core.serializers import base
File "/usr/local/lib/python2.6/dist-packages/django/core/serializers/base.py", line 7, in <module>
from django.db import models
File "/usr/local/lib/python2.6/dist-packages/django/db/__init__.py", line 14, in <module>
if not settings.DATABASES:
File "/usr/local/lib/python2.6/dist-packages/django/utils/functional.py", line 276, in __getattr__
self._setup()
File "/usr/local/lib/python2.6/dist-packages/django/conf/__init__.py", line 38, 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.
...and when I print the content it prints the JSON string correctly.
Edit:2
import simplejson
from urllib2 import urlopen
from simplejson import loads
from django.core import serializers
content = loads(urlopen('https://graph.facebook.com/1234676502/feed').read())
json_serializer = serializers.get_serializer("json")()
json_serializer.get_deserialize(content)
I put this code in my view.py then i got the following error:
AttributeError at /rss
'Serializer' object has no attribute 'get_deserialize'
Request Method: GET
Request URL: http://127.0.0.1:8000/rss
Django Version: 1.2.4
Exception Type: AttributeError
Exception Value:
'Serializer' object has no attribute 'get_deserialize'
Your error has nothing to with json per se, it clearly states that it cannot import DJANGO_SETTINGS which means that you do not have the django app context in place. The easiest way to go about this is install django extensions which provides the command ./manage.py runscript which runs your script with your django app context.
Django extensions can be found here
Edit:: looking at your second edit, I can see that you are using a method get_deserialize(), the right method should be deserialize(), AFAIK.

Categories