Skip to content

Commit

Permalink
Add testing project. Add configuration for testing to setup.py. Add f…
Browse files Browse the repository at this point in the history
…irst unittest.
  • Loading branch information
lig committed Oct 12, 2011
1 parent 340b58a commit 6877662
Show file tree
Hide file tree
Showing 15 changed files with 323 additions and 0 deletions.
28 changes: 28 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,31 @@
from setuptools import setup, find_packages
from setuptools.command.test import test

class TestRunner(test):

def run(self):

if self.distribution.install_requires:
self.distribution.fetch_build_eggs(self.distribution.install_requires)
if self.distribution.tests_require:
self.distribution.fetch_build_eggs(self.distribution.tests_require)

import sys
sys.path.insert(0, 'testprj')

from testprj import settings as test_settings
from django.conf import settings
settings.configure(test_settings)

from testprj.tests import mongoforms_test_runner as test_runner

test_suite = test_runner.build_suite(['testapp'])
test_runner.setup_test_environment()
result = test_runner.run_suite(test_suite)
test_runner.teardown_test_environment()

return result


setup(
name='django-mongoforms',
Expand All @@ -18,4 +45,5 @@
'Framework :: Django',
],
zip_safe=False,
cmdclass={"test": TestRunner}
)
Empty file added testprj/__init__.py
Empty file.
14 changes: 14 additions & 0 deletions testprj/manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
#!/usr/bin/env python
from django.core.management import execute_manager
import imp
try:
imp.find_module('settings') # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__)
sys.exit(1)

import settings

if __name__ == "__main__":
execute_manager(settings)
141 changes: 141 additions & 0 deletions testprj/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
# Django settings for testprj project.
from django.conf.global_settings import *
from mongoengine import connect


DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
# ('Your Name', 'your_email@example.com'),
)

MANAGERS = ADMINS

DB = connect('test')

TEST_RUNNER = 'testprj.tests.MongoengineDjangoTestSuiteRunner'

# hack for DATABASES setting
DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3'}}

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'

# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'fu3h7p7%#3#b6%m!e&equh6zuitgu5h9%nb@^=2#os5@#^8*gx'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)

ROOT_URLCONF = 'urls'

TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)

INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'testapp',
)

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
Empty file added testprj/testapp/__init__.py
Empty file.
11 changes: 11 additions & 0 deletions testprj/testapp/decorators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from django.shortcuts import render_to_response


def render_test(func):

def wrapper(request, *args, **kwargs):
result = func(request, *args, **kwargs)
return (isinstance(result, dict) and
render_to_response('test_template.html', result) or result)

return wrapper
16 changes: 16 additions & 0 deletions testprj/testapp/documents.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from mongoengine import *


class Test001Parent(Document):
name = StringField(required=True)

def __unicode__(self):
return u'%s' % self.name


class Test001Child(Document):
parent = ReferenceField(Test001Parent, required=True)
name = StringField(required=True)

def __unicode__(self):
return u'%s' % self.name
9 changes: 9 additions & 0 deletions testprj/testapp/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from mongoforms import MongoForm

from documents import Test001Child


class Test001ChildForm(MongoForm):
class Meta:
document = Test001Child
fields = ('parent', 'name')
1 change: 1 addition & 0 deletions testprj/testapp/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from documents import *
5 changes: 5 additions & 0 deletions testprj/testapp/templates/test_template.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<html>
<head><title>test</title></head>
<body>
</body>
</html>
36 changes: 36 additions & 0 deletions testprj/testapp/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
from django.test.client import Client
from django.utils import unittest

from documents import Test001Parent

from testprj.tests import MongoengineTestCase


class MongoformsTests(MongoengineTestCase):

def test001_possible_changes_loose_in_ReferenceField_clean_method(self):
# drop any parent present
Test001Parent.objects.delete()

# prepare two test parents
parent1 = Test001Parent(name='parent1')
parent1.save()
parent2 = Test001Parent(name='parent2')
parent2.save()

# prepare test client
c = Client()

# post form with first parent and empty name
response = c.post('/test001/', {'parent': parent1.pk})

# assert first parent is selected
self.assertEqual(response.context['form'].data['parent'],
unicode(parent1.pk), 'first parent must be selected')

# post form with second parent and empty name
response = c.post('/test001/', {'parent': parent2.pk})

# assert second parent is selected
self.assertEqual(response.context['form'].data['parent'],
unicode(parent2.pk), 'second parent must be selected')
6 changes: 6 additions & 0 deletions testprj/testapp/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.conf.urls.defaults import patterns, url


urlpatterns = patterns('testapp.views',
url(r'^test001/$', 'test001', {}, 'test001'),
)
18 changes: 18 additions & 0 deletions testprj/testapp/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from decorators import render_test

from forms import Test001ChildForm


@render_test
def test001(request):

if request.method == 'POST':
form = Test001ChildForm(request.POST)

if form.is_valid():
form.save()

else:
form = Test001ChildForm()

return {'form': form}
32 changes: 32 additions & 0 deletions testprj/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import os, sys

from django.test.simple import DjangoTestSuiteRunner
from django.test.testcases import TestCase


class MongoengineDjangoTestSuiteRunner(DjangoTestSuiteRunner):

def setup_databases(self, **kwargs):
return None

def teardown_databases(self, old_config, **kwargs):
pass


class MongoengineTestCase(TestCase):
""" completely dummy test case class """

def setUp(self):
TestCase.setUp(self)

def _fixture_setup(self):
pass

def _fixture_teardown(self):
pass


mongoforms_test_runner = MongoengineDjangoTestSuiteRunner(
verbosity=1,
interactive=True,
failfast=True)
6 changes: 6 additions & 0 deletions testprj/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.conf.urls.defaults import patterns, include, url


urlpatterns = patterns('',
url(r'^', include('testapp.urls')),
)

0 comments on commit 6877662

Please sign in to comment.