Permalink
Browse files

Initial app.

  • Loading branch information...
0 parents commit a92339ddd875f9e5c5883328232d75881625d4a0 @toastdriven toastdriven committed Apr 10, 2011
@@ -0,0 +1,2 @@
+.DS_Store
+*.pyc
@@ -0,0 +1,18 @@
+==========================
+Guide to Testing in Django
+==========================
+
+This is the example project demonstrating how to go about testing from the
+`blog series`_ on the topic. It adds tests to the perennial "`polls`_" app
+from the Django tutorial (minus the generic views).
+
+Tags have been added for each step in the process, starting with ``01-initial``.
+The project is based on Django 1.3 & SQLite.
+
+For the admin:
+
+* **Username:** admin
+* **Password:** abc123
+
+.. _`blog series`: http://toastdriven.com/blog/2011/04/10/guide-to-testing-in-django/
+.. _`polls`: http://docs.djangoproject.com/en/1.3/intro/tutorial01/
No changes.
@@ -0,0 +1,11 @@
+#!/usr/bin/env python
+from django.core.management import execute_manager
+try:
+ import 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(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
+ sys.exit(1)
+
+if __name__ == "__main__":
+ execute_manager(settings)
BIN polls.db
Binary file not shown.
No changes.
@@ -0,0 +1,22 @@
+from django.contrib import admin
+from polls.models import Poll, Choice
+
+
+class ChoiceInline(admin.TabularInline):
+ model = Choice
+ extra = 3
+
+
+class PollAdmin(admin.ModelAdmin):
+ date_hierarchy = 'pub_date'
+ fieldsets = [
+ (None, {'fields': ['question']}),
+ ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
+ ]
+ inlines = [ChoiceInline]
+ list_display = ('question', 'pub_date', 'was_published_today')
+ list_filter = ['pub_date']
+ search_fields = ['question']
+
+
+admin.site.register(Poll, PollAdmin)
@@ -0,0 +1,23 @@
+import datetime
+from django.db import models
+
+
+class Poll(models.Model):
+ question = models.CharField(max_length=200)
+ pub_date = models.DateTimeField('date published')
+
+ def __unicode__(self):
+ return self.question
+
+ def was_published_today(self):
+ return self.pub_date.date() == datetime.date.today()
+ was_published_today.short_description = 'Published today?'
+
+
+class Choice(models.Model):
+ poll = models.ForeignKey(Poll)
+ choice = models.CharField(max_length=200)
+ votes = models.IntegerField()
+
+ def __unicode__(self):
+ return self.choice
@@ -0,0 +1,23 @@
+"""
+This file demonstrates two different styles of tests (one doctest and one
+unittest). These will both pass when you run "manage.py test".
+
+Replace these with more appropriate tests for your application.
+"""
+
+from django.test import TestCase
+
+class SimpleTest(TestCase):
+ def test_basic_addition(self):
+ """
+ Tests that 1 + 1 always equals 2.
+ """
+ self.failUnlessEqual(1 + 1, 2)
+
+__test__ = {"doctest": """
+Another way to test that 1 + 1 is equal to 2.
+
+>>> 1 + 1 == 2
+True
+"""}
+
@@ -0,0 +1,9 @@
+from django.conf.urls.defaults import *
+
+
+urlpatterns = patterns('polls.views',
+ (r'^$', 'index'),
+ (r'^(?P<poll_id>\d+)/$', 'detail'),
+ (r'^(?P<poll_id>\d+)/results/$', 'results'),
+ (r'^(?P<poll_id>\d+)/vote/$', 'vote'),
+)
@@ -0,0 +1,41 @@
+from django.core.urlresolvers import reverse
+from django.http import HttpResponseRedirect, HttpResponse
+from django.shortcuts import render_to_response, get_object_or_404
+from django.template import RequestContext
+from polls.models import Poll, Choice
+
+
+def index(request):
+ latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
+ return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
+
+
+def detail(request, poll_id):
+ p = get_object_or_404(Poll, pk=poll_id)
+ return render_to_response('polls/detail.html', {'poll': p},
+ context_instance=RequestContext(request))
+
+
+def results(request, poll_id):
+ p = get_object_or_404(Poll, pk=poll_id)
+ return render_to_response('polls/results.html', {'poll': p})
+
+
+def vote(request, poll_id):
+ p = get_object_or_404(Poll, pk=poll_id)
+
+ try:
+ selected_choice = p.choice_set.get(pk=request.POST['choice'])
+ except (KeyError, Choice.DoesNotExist):
+ # Redisplay the poll voting form.
+ return render_to_response('polls/detail.html', {
+ 'poll': p,
+ 'error_message': "You didn't select a choice.",
+ }, context_instance=RequestContext(request))
+ else:
+ selected_choice.votes += 1
+ selected_choice.save()
+ # Always return an HttpResponseRedirect after successfully dealing
+ # with POST data. This prevents data from being posted twice if a
+ # user hits the Back button.
+ return HttpResponseRedirect(reverse('polls.views.results', args=(p.id,)))
@@ -0,0 +1,142 @@
+# Django settings for guide_to_testing project.
+
+DEBUG = True
+TEMPLATE_DEBUG = DEBUG
+
+ADMINS = (
+ # ('Your Name', 'your_email@example.com'),
+)
+
+MANAGERS = ADMINS
+
+DATABASES = {
+ 'default': {
+ 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
+ 'NAME': 'polls.db', # Or path to database file if using sqlite3.
+ 'USER': '', # Not used with sqlite3.
+ 'PASSWORD': '', # Not used with sqlite3.
+ 'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
+ 'PORT': '', # Set to empty string for default. Not used with 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 if there is a path component (optional in other cases).
+# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
+MEDIA_URL = ''
+
+# Absolute path to the directory that holds static files.
+# Example: "/home/media/media.lawrence.com/static/"
+STATIC_ROOT = ''
+
+# URL that handles the static files served from STATIC_ROOT.
+# Example: "http://media.lawrence.com/static/"
+STATIC_URL = '/static/'
+
+# URL prefix for admin media -- CSS, JavaScript and images.
+# Make sure to use a trailing slash.
+# Examples: "http://foo.com/static/admin/", "/static/admin/".
+ADMIN_MEDIA_PREFIX = '/static/admin/'
+
+# A list of locations of additional static files
+STATICFILES_DIRS = ()
+
+# 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 = 'p(u%@fn&r_d7@$p@jqfwwp#$l-@=_pdf_$y$2jztv_dmcgk@g5'
+
+# 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 = 'guide_to_testing.urls'
+
+import os
+PROJECT_ROOT = os.path.dirname(__file__)
+
+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.
+ os.path.join(PROJECT_ROOT, 'templates'),
+)
+
+INSTALLED_APPS = (
+ 'django.contrib.auth',
+ 'django.contrib.contenttypes',
+ 'django.contrib.sessions',
+ 'django.contrib.sites',
+ 'django.contrib.messages',
+ 'django.contrib.staticfiles',
+ 'django.contrib.admin',
+ 'django.contrib.admindocs',
+ 'polls',
+)
+
+# 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,
+ },
+ }
+}
@@ -0,0 +1,12 @@
+<h1>{{ poll.question }}</h1>
+
+{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
+
+<form action="/polls/{{ poll.id }}/vote/" method="post">
+{% csrf_token %}
+{% for choice in poll.choice_set.all %}
+ <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
+ <label for="choice{{ forloop.counter }}">{{ choice.choice }}</label><br />
+{% endfor %}
+<input type="submit" value="Vote" />
+</form>
@@ -0,0 +1,9 @@
+{% if latest_poll_list %}
+ <ul>
+ {% for poll in latest_poll_list %}
+ <li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>
+ {% endfor %}
+ </ul>
+{% else %}
+ <p>No polls are available.</p>
+{% endif %}
@@ -0,0 +1,9 @@
+<h1>{{ poll.question }}</h1>
+
+<ul>
+{% for choice in poll.choice_set.all %}
+ <li>{{ choice.choice }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
+{% endfor %}
+</ul>
+
+<a href="/polls/{{ poll.id }}/">Vote again?</a>
15 urls.py
@@ -0,0 +1,15 @@
+from django.conf.urls.defaults import *
+
+
+from django.contrib import admin
+admin.autodiscover()
+
+
+urlpatterns = patterns('',
+ # Example:
+ # (r'^guide_to_testing/', include('guide_to_testing.foo.urls')),
+
+ (r'^admin/doc/', include('django.contrib.admindocs.urls')),
+ (r'^admin/', include(admin.site.urls)),
+ (r'^polls/', include('polls.urls')),
+)

0 comments on commit a92339d

Please sign in to comment.