Exception with Django 1.6.5 and factory_boy - django

I decided to use factory_boy in my simple django application for test purposes.
But I had a problem with simple example. Here is the code of my simple test.
from django.utils import unittest
from ..models import Server, ServerAddress, L2TPServer, serialize_open_vpn_server_json
from factory import django as django_factory
class SshOpenVpnServerFactory(django_factory.DjangoModelFactory):
class Meta:
model = L2TPServer
django_get_or_create = ('name', 'address')
name = 'Hello'
address = 'Nono'
class ServersTestCase(unittest.TestCase):
def test_serialize_server_info(self):
print Server.objects.all()
SshOpenVpnServerFactory.build()
When test-runner executes this test, I get an error:
Traceback (most recent call last):
File "/Users/green/Development/Wasel/experimental/wasel_services/packages/waselcore/backend/tests/test_models.py", line 20, in test_serialize_server_info
SshOpenVpnServerFactory.build()
File "/Users/green/Development/Wasel/experimental/env/wasel_sevices/lib/python2.7/site-packages/factory/base.py", line 504, in build
attrs = cls.attributes(create=False, extra=kwargs)
File "/Users/green/Development/Wasel/experimental/env/wasel_sevices/lib/python2.7/site-packages/factory/base.py", line 365, in attributes
force_sequence=force_sequence,
File "/Users/green/Development/Wasel/experimental/env/wasel_sevices/lib/python2.7/site-packages/factory/containers.py", line 265, in build
sequence = self.factory._generate_next_sequence()
File "/Users/green/Development/Wasel/experimental/env/wasel_sevices/lib/python2.7/site-packages/factory/base.py", line 338, in _generate_next_sequence
cls._setup_counter()
File "/Users/green/Development/Wasel/experimental/env/wasel_sevices/lib/python2.7/site-packages/factory/base.py", line 318, in _setup_counter
first_seq = cls._setup_next_sequence()
File "/Users/green/Development/Wasel/experimental/env/wasel_sevices/lib/python2.7/site-packages/factory/django.py", line 83, in _setup_next_sequence
manager = cls._get_manager(model)
File "/Users/green/Development/Wasel/experimental/env/wasel_sevices/lib/python2.7/site-packages/factory/django.py", line 76, in _get_manager
return target_class.objects
AttributeError: 'NoneType' object has no attribute 'objects'
Where am I wrong? Does factory_boy support django 1.6.5?

The proposed syntax using the Meta class will only be released as part of the (unreleased) Factory Boy 2.4. Use SshOpenVpnServerFactory.FACTORY_FOR instead. Related issue: https://github.com/rbarrois/factory_boy/issues/143

Related

InheritanceManager bug when access parent-class elements (Django 2.0)

I'm currently trying to have a object oriented schema in Django 2.0 (Python 3.6.3) with a parent class Program and some children classes Snippet and Software. I saw that the model_utils module contains some tools to handle the polymorphism, and tried to replicate the tutorial (http://django-model-utils.readthedocs.io/en/latest/managers.html), here is what it gives in my case:
models.py
from django.db import models
from model_utils.managers import InheritanceManager
class Program(models.Model):
name = models.CharField(max_length=100)
objects = InheritanceManager()
class Snippet(Program):
code = models.TextField()
class Software(Program):
repoLink = models.URLField()
Django shell
>>> from coding.models import Program
>>> programs = Program.objects.select_subclasses()
>>> programs
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "...\py3django\lib\site-packages\django\db\models\query.py", line 248, in __repr__
data = list(self[:REPR_OUTPUT_SIZE + 1])
File "...\py3django\lib\site-packages\django\db\models\query.py", line 292, in __getitem__
qs = self._chain()
File "...\py3django\lib\site-packages\django\db\models\query.py", line 1156, in _chain
obj = self._clone()
File "...\py3django\lib\site-packages\model_utils\managers.py", line 100, in _clone
return super(InheritanceQuerySetMixin, self)._clone(**kwargs)
TypeError: _clone() got an unexpected keyword argument 'subclasses'
I don't understand this error and how to fix it, and even don't know if it is a fail in my design or a bad use of the InheritanceManager. So what can be the origin of this error message?
According to the docs, django-model-utils only supports Django 1.8 to 1.10.

Got EOFError during loading doc2vec model

I could not load a doc2vec model on my computer and I got the following error. But, when I load that model on other computers, I can use that model.Therefore, I know the model was built correctly.
what should I do.
This is the code:
# coding: utf-8
from gensim.models.doc2vec import Doc2Vec
import gensim.models.doc2vec
from gensim.models.doc2vec import LabeledSentence
import os
import pickle
pth='/home/fatemeh/Step2/input-output/model/iterator'
model= Doc2Vec.load(pth+'/my_model.doc2vec')
This is the error:
Traceback (most recent call last):
File "CreateAnnoyIndex.py", line 16, in <module>
model= Doc2Vec.load(pth+'/my_model.doc2vec')
File "/usr/local/lib/python2.7/dist-packages/gensim-0.13.3-py2.7-linux-x86_64.egg/gensim/models/word2vec.py", line 1762, in load
model = super(Word2Vec, cls).load(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/gensim-0.13.3-py2.7-linux-x86_64.egg/gensim/utils.py", line 248, in load
obj = unpickle(fname)
File "/usr/local/lib/python2.7/dist-packages/gensim-0.13.3-py2.7-linux-x86_64.egg/gensim/utils.py", line 912, in unpickle
return _pickle.loads(f.read())
EOFError
I think your model causes the problem. Are you check with same model? I mean build in a same way. please see this page

Log warning from Selenium on Django [duplicate]

Whenever I try to construct a string based on self.live_server_url, I get python TypeError messages. For example, I've tried the following string constructions (form 1 & 2 below), but I experience the same TypeError. My desired string is the Live Server URL with "/lists" appended. NOTE: the actual test does succeed to create a server and I can manually access the server, and more specifically, I can manually access the exact URL that I'm trying to build programmatically (e.g. 'http://localhost:8081/lists').
TypeErrors occur with these string constructions.
# FORM 1
lists_live_server_url = '%s%s' % (self.live_server_url, '/lists')
# FORM 2
lists_live_server_url = '{0}{1}'.format(self.live_server_url, '/lists')
self.browser.get(lists_live_server_url)
There is no python error with this form (nothing appended to string), albeit my test fails (as I would expect since it isn't accessing /lists).
self.browser.get(self.live_server_url)
Here is the python error that I'm getting.
/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/bin/python3.4 /Applications/PyCharm.app/Contents/helpers/pycharm/django_test_manage.py test functional_tests.lists_tests.LiveNewVisitorTest.test_can_start_a_list_and_retrieve_it_later /Users/myusername/PycharmProjects/mysite_proj
Testing started at 11:55 AM ...
Creating test database for alias 'default'...
Traceback (most recent call last):
File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/wsgiref/handlers.py", line 137, in run
self.result = application(self.environ, self.start_response)
File "/usr/local/lib/python3.4/site-packages/django/test/testcases.py", line 1104, in __call__
return super(FSFilesHandler, self).__call__(environ, start_response)
File "/usr/local/lib/python3.4/site-packages/django/core/handlers/wsgi.py", line 189, in __call__
response = self.get_response(request)
File "/usr/local/lib/python3.4/site-packages/django/test/testcases.py", line 1087, in get_response
return self.serve(request)
File "/usr/local/lib/python3.4/site-packages/django/test/testcases.py", line 1099, in serve
return serve(request, final_rel_path, document_root=self.get_base_dir())
File "/usr/local/lib/python3.4/site-packages/django/views/static.py", line 54, in serve
fullpath = os.path.join(document_root, newpath)
File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/posixpath.py", line 82, in join
path += b
TypeError: unsupported operand type(s) for +=: 'NoneType' and 'str'
Am I unknowingly attempting to modify the live_server_url, which is leading to these TypeErrors? How could I programmatically build a string of live_server_url + "/lists"?
Here is the test that I am attempting...
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from django.test import LiveServerTestCase
class LiveNewVisitorTest(LiveServerTestCase):
def setUp(self):
self.browser = webdriver.Chrome()
self.browser.implicitly_wait(3)
def tearDown(self):
self.browser.close()
def test_can_start_a_list_and_retrieve_it_later(self):
#self.browser.get('http://localhost:8000/lists')
#self.browser.get('http://www.google.com')
#lists_live_server_url = '%s%s' % (self.live_server_url, '/lists')
#lists_live_server_url = '{0}{1}'.format(self.live_server_url, '/lists')
lists_live_server_url = self.live_server_url
self.browser.get(lists_live_server_url)
self.assertIn('To-Do', self.browser.title)
header_text = self.browser.find_element_by_tag_name('h1').text
self.assertIn('To-Do', header_text)
See this discussion on Reddit featuring the same error Traceback.
Basically, this is not a problem with anything within the Selenium tests but rather with your project's static file configuration.
From your question, I believe the key line within the Traceback is:
File "/usr/local/lib/python3.4/site-packages/django/views/static.py", line 54, in serve
fullpath = os.path.join(document_root, newpath)
This line indicates that an unsuccessful os.path.join is being attempted within django.views.static.
Set STATIC_ROOT in your project's settings.pyfile and you should be good.
Use StaticLiveServerTestCase instead may help

(Obviously) Not possible to append to tuple. Why does django userena test do it?

INSTALLED_APPS in django is obviously a tuple and therefore immutable.
Why does django-userena try to append a module to it at runtime?
Reference userena/tests/profiles/test.py
from django import test
class ProfileTestCase(test.TestCase):
""" A custom TestCase that loads the profile application for testing purposes """
def _pre_setup(self):
# Add the models to the db.
self._original_installed_apps = list(settings.INSTALLED_APPS)
settings.INSTALLED_APPS.append('userena.tests.profiles')
loading.cache.loaded = False
call_command('syncdb', interactive=False, verbosity=0)
# Call the original method that does the fixtures etc.
super(ProfileTestCase, self)._pre_setup()
def _post_teardown(self):
# Call the original method.
super(ProfileTestCase, self)._post_teardown()
# Restore the settings.
settings.INSTALLED_APPS = self._original_installed_apps
loading.cache.loaded = False
And obviously, when I run the unit tests with userena, I get errors such as:-
======================================================================
ERROR: test_can_view_profile (userena.tests.models.BaseProfileModelTest)
Test if the user can see the profile with three type of users.
----------------------------------------------------------------------
Traceback (most recent call last):
File "./django-trunk/django/test/testcases.py", line 499, in __call__
self._pre_setup()
File "./_thirdparty/django-userena/userena/tests/profiles/test.py", line 11, in _pre_setup
settings.INSTALLED_APPS.append('userena.tests.profiles')
AttributeError: 'tuple' object has no attribute 'append'
======================================================================
ERROR: test_get_full_name_or_username (userena.tests.models.BaseProfileModelTest)
Test if the full name or username are returned correcly
----------------------------------------------------------------------
Traceback (most recent call last):
File "./django-trunk/django/test/testcases.py", line 499, in __call__
self._pre_setup()
File "./_thirdparty/django-userena/userena/tests/profiles/test.py", line 11, in _pre_setup
settings.INSTALLED_APPS.append('userena.tests.profiles')
AttributeError: 'tuple' object has no attribute 'append'
How do I solve this problem?
I think this:
self._original_installed_apps = list(settings.INSTALLED_APPS)
settings.INSTALLED_APPS.append('userena.tests.profiles')
Should be
self._original_installed_apps = list(settings.INSTALLED_APPS)
settings.INSTALLED_APPS += ('userena.tests.profiles',)
Looks like a bug to me.
INSTALLED_APPS is a tuple by default but can be changed to a list. The author of that app probably did change that for themselves, wrote the tests and didn't realize that it won't work for people who have INSTALLED_APPS as a tuple. You can most likely fix the problem by changing your settings.INSTALLED_APPS to a list.
Btw, there are better ways how to override settings.

Django unittests: The model is already registered Error

I come across several problems while trying django unittests library. Something strange happens:
I defined the test like this:
from django.core import management
from django.test import TestCase
from django.test.client import Client
from django.core import mail
from django.test.utils import setup_test_environment
from django.contrib.auth.models import User
from django.db import connection
from goserver.models import ActiveList
class GoserverTestCase(TestCase):
#fixtures = ['dat.json']
def setUp(self):
pass
def test_active_list_works(self):
c = Client()
response = c.post('/')
#print response.status_code
self.assertEquals(True, True)
But after the execution of the code it returns following error:
---------------------------------------------------------------------- Unit Test Code Coverage Results
---------------------------------------------------------------------- Traceback (most recent call last): File "manage.py", line 11, in <module>
execute_manager(settings) File "/opt/local/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/core/management/__init__.py", line 340, in execute_manager
utility.execute() File "/opt/local/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/core/management/__init__.py", line 295, in execute
self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/local/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/core/management/base.py", line 192, in run_from_argv
self.execute(*args, **options.__dict__) File "/opt/local/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/core/management/base.py", line 219, in execute
output = self.handle(*args, **options) File "/opt/local/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/core/management/commands/test.py", line 33, in handle
failures = test_runner(test_labels, verbosity=verbosity, interactive=interactive) File "/opt/local/lib/python2.5/site-packages/django_test_coverage-0.1-py2.5.egg/django-test-coverage/runner.py", line 58, in run_tests
modules.extend(_package_modules(*pkg)) File "/opt/local/lib/python2.5/site-packages/django_test_coverage-0.1-py2.5.egg/django-test-coverage/runner.py", line 92, in _package_modules
modules.append(__import__(impstr + '.' + name, {}, {}, [''])) File "/Users/oleg/jin/goclub/trunk/jin/goserver/admin.py", line 11, in <module>
admin.site.register(ActiveList, ActiveListAdmin) File "/opt/local/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/contrib/admin/sites.py", line 64, in register
raise AlreadyRegistered('The model %s is already registered' % model.__name__) django.contrib.admin.sites.AlreadyRegistered: The model ActiveList is already registered silver:jin oleg$
Admin file looks like this:
from goserver.models import ActiveList, Game
from django.contrib import admin
class ActiveListAdmin(admin.ModelAdmin):
list_display = ('user', "is_Bot", "isActive")
admin.site.register(ActiveList, ActiveListAdmin)
admin.site.register(Game)
I run it all this way:
python manage.py test goserver
Also noticed that if I remove lines
c = Client()
response = c.post('/')
from a test case definition, then no error appears
Looking at the traceback, it looks like you have an app called django_test_coverage-0.1 which is importing your app's admin.py.
It is probably importing it from a different location, such as yourproject.yourapp.admin as opposed to yourapp.admin. Since it's technically seen as a different module, it is re-imported and the admin.site.register calls are made again. This causes the AlreadyRegistered error.
My suggestion would be to remove django_test_coverage app (or fix it).
My questions,
I don't see what is base type/class for TestCase - is it Django Test one, or from Unittest?
it is better to use from Django
How are you runnig test? using Django internal test command, by nose, by unittest? By Traceback I thing test command, but I am not quite sure.
What is you definitions for ActiveAdminList and ActiveList? Have you got maybe class Admin in Meta?
I solve this commenting the admin.autodiscover() line in the proye