Converted test fixtures to setUpTestData methods

This commit is contained in:
Josh Smeaton 2015-02-23 11:53:57 +11:00
parent d6969abf23
commit 39a7eed1bb
69 changed files with 2077 additions and 2819 deletions

View File

@ -1,20 +0,0 @@
[
{
"pk": 100,
"model": "auth.user",
"fields": {
"username": "super",
"first_name": "Super",
"last_name": "User",
"is_active": true,
"is_superuser": true,
"is_staff": true,
"last_login": "2007-05-30 13:20:10",
"groups": [],
"user_permissions": [],
"password": "sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158",
"email": "super@example.com",
"date_joined": "2007-05-30 13:20:10"
}
}
]

View File

@ -672,9 +672,18 @@ class AdminLogNodeTestCase(TestCase):
class SeleniumFirefoxTests(AdminSeleniumWebDriverTestCase):
available_apps = ['admin_changelist'] + AdminSeleniumWebDriverTestCase.available_apps
fixtures = ['users.json']
webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver'
@classmethod
def setUpTestData(cls):
# password = "secret"
User.objects.create(
pk=100, username='super', first_name='Super', last_name='User', email='super@example.com',
password='sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158', is_active=True, is_superuser=True,
is_staff=True, last_login=datetime.datetime(2007, 5, 30, 13, 20, 10),
date_joined=datetime.datetime(2007, 5, 30, 13, 20, 10)
)
def test_add_row_selection(self):
"""
Ensure that the status line for selected rows gets updated correcly (#22038)

View File

@ -1,44 +0,0 @@
[
{
"pk": "delete",
"model": "admin_custom_urls.action",
"fields": {
"description": "Remove things."
}
},
{
"pk": "rename",
"model": "admin_custom_urls.action",
"fields": {
"description": "Gives things other names."
}
},
{
"pk": "add",
"model": "admin_custom_urls.action",
"fields": {
"description": "Add things."
}
},
{
"pk": "path/to/file/",
"model": "admin_custom_urls.action",
"fields": {
"description": "An action with '/' in its name."
}
},
{
"pk": "path/to/html/document.html",
"model": "admin_custom_urls.action",
"fields": {
"description": "An action with a name similar to a HTML doc path."
}
},
{
"pk": "javascript:alert('Hello world');\">Click here</a>",
"model": "admin_custom_urls.action",
"fields": {
"description": "An action with a name suspected of being a XSS attempt"
}
}
]

View File

@ -1,20 +0,0 @@
[
{
"pk": 100,
"model": "auth.user",
"fields": {
"username": "super",
"first_name": "Super",
"last_name": "User",
"is_active": true,
"is_superuser": true,
"is_staff": true,
"last_login": "2007-05-30 13:20:10",
"groups": [],
"user_permissions": [],
"password": "sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158",
"email": "super@example.com",
"date_joined": "2007-05-30 13:20:10"
}
}
]

View File

@ -1,6 +1,9 @@
from __future__ import unicode_literals
import datetime
from django.contrib.admin.utils import quote
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.template.response import TemplateResponse
from django.test import TestCase, override_settings
@ -17,7 +20,28 @@ class AdminCustomUrlsTest(TestCase):
* The ModelAdmin for Action customizes the add_view URL, it's
'<app name>/<model name>/!add/'
"""
fixtures = ['users.json', 'actions.json']
@classmethod
def setUpTestData(cls):
# password = "secret"
User.objects.create(
pk=100, username='super', first_name='Super', last_name='User', email='super@example.com',
password='sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158', is_active=True, is_superuser=True,
is_staff=True, last_login=datetime.datetime(2007, 5, 30, 13, 20, 10),
date_joined=datetime.datetime(2007, 5, 30, 13, 20, 10)
)
Action.objects.create(name='delete', description='Remove things.')
Action.objects.create(name='rename', description='Gives things other names.')
Action.objects.create(name='add', description='Add things.')
Action.objects.create(name='path/to/file/', description="An action with '/' in its name.")
Action.objects.create(
name='path/to/html/document.html',
description='An action with a name similar to a HTML doc path.'
)
Action.objects.create(
name='javascript:alert(\'Hello world\');">Click here</a>',
description='An action with a name suspected of being a XSS attempt'
)
def setUp(self):
self.client.login(username='super', password='secret')
@ -76,15 +100,6 @@ class AdminCustomUrlsTest(TestCase):
self.assertContains(response, 'Change action')
self.assertContains(response, 'value="path/to/html/document.html"')
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='admin_custom_urls.urls',)
class CustomRedirects(TestCase):
fixtures = ['users.json', 'actions.json']
def setUp(self):
self.client.login(username='super', password='secret')
def test_post_save_add_redirect(self):
"""
Ensures that ModelAdmin.response_post_save_add() controls the

View File

@ -1,17 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<django-objects version="1.0">
<object pk="100" model="auth.user">
<field type="CharField" name="username">super</field>
<field type="CharField" name="first_name">Super</field>
<field type="CharField" name="last_name">User</field>
<field type="CharField" name="email">super@example.com</field>
<field type="CharField" name="password">sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158</field>
<field type="BooleanField" name="is_staff">True</field>
<field type="BooleanField" name="is_active">True</field>
<field type="BooleanField" name="is_superuser">True</field>
<field type="DateTimeField" name="last_login">2007-05-30 13:20:10</field>
<field type="DateTimeField" name="date_joined">2007-05-30 13:20:10</field>
<field to="auth.group" name="groups" rel="ManyToManyRel"></field>
<field to="auth.permission" name="user_permissions" rel="ManyToManyRel"></field>
</object>
</django-objects>

View File

@ -1,3 +1,4 @@
import datetime
import sys
import unittest
@ -12,6 +13,19 @@ from django.test import TestCase, modify_settings, override_settings
from .models import Company, Person
class TestDataMixin(object):
@classmethod
def setUpTestData(cls):
# password = "secret"
User.objects.create(
pk=100, username='super', first_name='Super', last_name='User', email='super@example.com',
password='sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158', is_active=True, is_superuser=True,
is_staff=True, last_login=datetime.datetime(2007, 5, 30, 13, 20, 10),
date_joined=datetime.datetime(2007, 5, 30, 13, 20, 10)
)
@override_settings(
PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='admin_docs.urls')
@ -39,8 +53,7 @@ class MiscTests(AdminDocsTestCase):
@unittest.skipUnless(utils.docutils_is_available, "no docutils installed.")
class AdminDocViewTests(AdminDocsTestCase):
fixtures = ['data.xml']
class AdminDocViewTests(TestDataMixin, AdminDocsTestCase):
def setUp(self):
self.client.login(username='super', password='secret')
@ -124,8 +137,7 @@ class AdminDocViewTests(AdminDocsTestCase):
utils.docutils_is_available = True
class XViewMiddlewareTest(AdminDocsTestCase):
fixtures = ['data.xml']
class XViewMiddlewareTest(TestDataMixin, AdminDocsTestCase):
def test_xview_func(self):
user = User.objects.get(username='super')
@ -201,13 +213,11 @@ class DefaultRoleTest(AdminDocsTestCase):
@unittest.skipUnless(utils.docutils_is_available, "no docutils installed.")
class TestModelDetailView(AdminDocsTestCase):
class TestModelDetailView(TestDataMixin, AdminDocsTestCase):
"""
Tests that various details render correctly
"""
fixtures = ['data.xml']
def setUp(self):
self.client.login(username='super', password='secret')
self.response = self.client.get(

View File

@ -1,17 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<django-objects version="1.0">
<object pk="100" model="auth.user">
<field type="CharField" name="username">super</field>
<field type="CharField" name="first_name">Super</field>
<field type="CharField" name="last_name">User</field>
<field type="CharField" name="email">super@example.com</field>
<field type="CharField" name="password">sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158</field>
<field type="BooleanField" name="is_staff">True</field>
<field type="BooleanField" name="is_active">True</field>
<field type="BooleanField" name="is_superuser">True</field>
<field type="DateTimeField" name="last_login">2007-05-30 13:20:10</field>
<field type="DateTimeField" name="date_joined">2007-05-30 13:20:10</field>
<field to="auth.group" name="groups" rel="ManyToManyRel"></field>
<field to="auth.permission" name="user_permissions" rel="ManyToManyRel"></field>
</object>
</django-objects>

View File

@ -1,5 +1,6 @@
from __future__ import unicode_literals
import datetime
import warnings
from django.contrib.admin import ModelAdmin, TabularInline
@ -23,10 +24,22 @@ from .models import (
INLINE_CHANGELINK_HTML = 'class="inlinechangelink">Change</a>'
class TestDataMixin(object):
@classmethod
def setUpTestData(cls):
# password = "secret"
User.objects.create(
pk=100, username='super', first_name='Super', last_name='User', email='super@example.com',
password='sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158', is_active=True, is_superuser=True,
is_staff=True, last_login=datetime.datetime(2007, 5, 30, 13, 20, 10),
date_joined=datetime.datetime(2007, 5, 30, 13, 20, 10)
)
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF="admin_inlines.urls")
class TestInline(TestCase):
fixtures = ['admin-views-users.xml']
class TestInline(TestDataMixin, TestCase):
def setUp(self):
holder = Holder(dummy=13)
@ -353,11 +366,9 @@ class TestInline(TestCase):
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF="admin_inlines.urls")
class TestInlineMedia(TestCase):
fixtures = ['admin-views-users.xml']
class TestInlineMedia(TestDataMixin, TestCase):
def setUp(self):
result = self.client.login(username='super', password='secret')
self.assertEqual(result, True)
@ -430,8 +441,7 @@ class TestInlineAdminForm(TestCase):
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF="admin_inlines.urls")
class TestInlineProtectedOnDelete(TestCase):
fixtures = ['admin-views-users.xml']
class TestInlineProtectedOnDelete(TestDataMixin, TestCase):
def setUp(self):
result = self.client.login(username='super', password='secret')
@ -657,10 +667,9 @@ class TestInlinePermissions(TestCase):
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF="admin_inlines.urls")
class SeleniumFirefoxTests(AdminSeleniumWebDriverTestCase):
class SeleniumFirefoxTests(TestDataMixin, AdminSeleniumWebDriverTestCase):
available_apps = ['admin_inlines'] + AdminSeleniumWebDriverTestCase.available_apps
fixtures = ['admin-views-users.xml']
webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver'
def test_add_stackeds(self):

View File

@ -1,15 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<django-objects version="1.0">
<object pk="1" model="admin_views.subscriber">
<field type="CharField" name="name">John Doe</field>
<field type="CharField" name="email">john@example.org</field>
</object>
<object pk="2" model="admin_views.subscriber">
<field type="CharField" name="name">Max Mustermann</field>
<field type="CharField" name="email">max@example.org</field>
</object>
<object pk="1" model="admin_views.externalsubscriber">
<field type="CharField" name="name">John Doe</field>
<field type="CharField" name="email">john@example.org</field>
</object>
</django-objects>

View File

@ -1,45 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<django-objects version="1.0">
<object pk="1" model="admin_views.book">
<field type="CharField" name="name">Book 1</field>
</object>
<object pk="2" model="admin_views.book">
<field type="CharField" name="name">Book 2</field>
</object>
<object pk="1" model="admin_views.promo">
<field type="CharField" name="name">Promo 1</field>
<field type="ForeignKey" name="book">1</field>
</object>
<object pk="2" model="admin_views.promo">
<field type="CharField" name="name">Promo 2</field>
<field type="ForeignKey" name="book">2</field>
</object>
<object pk="1" model="admin_views.chapter">
<field type="CharField" name="title">Chapter 1</field>
<field type="TextField" name="content">[ insert contents here ]</field>
<field type="ForeignKey" name="book">1</field>
</object>
<object pk="2" model="admin_views.chapter">
<field type="CharField" name="title">Chapter 2</field>
<field type="TextField" name="content">[ insert contents here ]</field>
<field type="ForeignKey" name="book">1</field>
</object>
<object pk="3" model="admin_views.chapter">
<field type="CharField" name="title">Chapter 1</field>
<field type="TextField" name="content">[ insert contents here ]</field>
<field type="ForeignKey" name="book">2</field>
</object>
<object pk="4" model="admin_views.chapter">
<field type="CharField" name="title">Chapter 2</field>
<field type="TextField" name="content">[ insert contents here ]</field>
<field type="ForeignKey" name="book">2</field>
</object>
<object pk="1" model="admin_views.chapterxtra1">
<field type="CharField" name="xtra">ChapterXtra1 1</field>
<field type="ForeignKey" name="chap">1</field>
</object>
<object pk="2" model="admin_views.chapterxtra1">
<field type="CharField" name="xtra">ChapterXtra1 2</field>
<field type="ForeignKey" name="chap">3</field>
</object>
</django-objects>

View File

@ -1,19 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<django-objects version="1.0">
<object pk="1" model="admin_views.color">
<field type="CharField" name="value">Red</field>
<field type="BooleanField" name="warm">1</field>
</object>
<object pk="2" model="admin_views.color">
<field type="CharField" name="value">Orange</field>
<field type="BooleanField" name="warm">1</field>
</object>
<object pk="3" model="admin_views.color">
<field type="CharField" name="value">Blue</field>
<field type="BooleanField" name="warm">0</field>
</object>
<object pk="4" model="admin_views.color">
<field type="CharField" name="value">Green</field>
<field type="BooleanField" name="warm">0</field>
</object>
</django-objects>

View File

@ -1,12 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<django-objects version="1.0">
<object pk="1" model="admin_views.fabric">
<field type="CharField" name="surface">x</field>
</object>
<object pk="2" model="admin_views.fabric">
<field type="CharField" name="surface">y</field>
</object>
<object pk="3" model="admin_views.fabric">
<field type="CharField" name="surface">plain</field>
</object>
</django-objects>

View File

@ -1,18 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<django-objects version="1.0">
<object pk="1" model="admin_views.person">
<field type="CharField" name="name">John Mauchly</field>
<field type="IntegerField" name="gender">1</field>
<field type="BooleanField" name="alive">True</field>
</object>
<object pk="2" model="admin_views.person">
<field type="CharField" name="name">Grace Hopper</field>
<field type="IntegerField" name="gender">1</field>
<field type="BooleanField" name="alive">False</field>
</object>
<object pk="3" model="admin_views.person">
<field type="CharField" name="name">Guido van Rossum</field>
<field type="IntegerField" name="gender">1</field>
<field type="BooleanField" name="alive">True</field>
</object>
</django-objects>

View File

@ -1,63 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<django-objects version="1.0">
<object pk="1" model="admin_views.state">
<field type="CharField" name="name">New York</field>
</object>
<object pk="2" model="admin_views.state">
<field type="CharField" name="name">Illinois</field>
</object>
<object pk="3" model="admin_views.state">
<field type="CharField" name="name">California</field>
</object>
<object pk="1" model="admin_views.city">
<field to="admin_views.state" name="state" rel="ManyToOneRel">1</field>
<field type="CharField" name="name">New York</field>
</object>
<object pk="2" model="admin_views.city">
<field to="admin_views.state" name="state" rel="ManyToOneRel">2</field>
<field type="CharField" name="name">Chicago</field>
</object>
<object pk="3" model="admin_views.city">
<field to="admin_views.state" name="state" rel="ManyToOneRel">3</field>
<field type="CharField" name="name">San Francisco</field>
</object>
<object pk="1" model="admin_views.restaurant">
<field to="admin_views.city" name="city" rel="ManyToOneRel">1</field>
<field type="CharField" name="name">Italian Pizza</field>
</object>
<object pk="2" model="admin_views.restaurant">
<field to="admin_views.city" name="city" rel="ManyToOneRel">1</field>
<field type="CharField" name="name">Boulevard</field>
</object>
<object pk="3" model="admin_views.restaurant">
<field to="admin_views.city" name="city" rel="ManyToOneRel">2</field>
<field type="CharField" name="name">Chinese Dinner</field>
</object>
<object pk="4" model="admin_views.restaurant">
<field to="admin_views.city" name="city" rel="ManyToOneRel">2</field>
<field type="CharField" name="name">Angels</field>
</object>
<object pk="5" model="admin_views.restaurant">
<field to="admin_views.city" name="city" rel="ManyToOneRel">2</field>
<field type="CharField" name="name">Take Away</field>
</object>
<object pk="6" model="admin_views.restaurant">
<field to="admin_views.city" name="city" rel="ManyToOneRel">3</field>
<field type="CharField" name="name">The Unknown Restaurant</field>
</object>
<object pk="1" model="admin_views.worker">
<field to="admin_views.restaurant" name="work_at" rel="ManyToOneRel">1</field>
<field type="CharField" name="name">Mario</field>
<field type="CharField" name="surname">Rossi</field>
</object>
<object pk="2" model="admin_views.worker">
<field to="admin_views.restaurant" name="work_at" rel="ManyToOneRel">1</field>
<field type="CharField" name="name">Antonio</field>
<field type="CharField" name="surname">Bianchi</field>
</object>
<object pk="3" model="admin_views.worker">
<field to="admin_views.restaurant" name="work_at" rel="ManyToOneRel">1</field>
<field type="CharField" name="name">John</field>
<field type="CharField" name="surname">Doe</field>
</object>
</django-objects>

View File

@ -1,63 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<django-objects version="1.0">
<object pk="100" model="auth.user">
<field type="CharField" name="username">super</field>
<field type="CharField" name="first_name">Super</field>
<field type="CharField" name="last_name">User</field>
<field type="CharField" name="email">super@example.com</field>
<field type="CharField" name="password">sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158</field>
<field type="BooleanField" name="is_staff">True</field>
<field type="BooleanField" name="is_active">True</field>
<field type="BooleanField" name="is_superuser">True</field>
<field type="DateTimeField" name="last_login">2007-05-30 13:20:10</field>
<field type="DateTimeField" name="date_joined">2007-05-30 13:20:10</field>
<field to="auth.group" name="groups" rel="ManyToManyRel"></field>
<field to="auth.permission" name="user_permissions" rel="ManyToManyRel"></field>
</object>
<object pk="1" model="admin_views.book">
<field type="CharField" name="name">Lærdommer</field>
</object>
<object pk="1" model="admin_views.promo">
<field type="CharField" name="name">&lt;Promo for Lærdommer&gt;</field>
<field to="admin_views.book" name="book" rel="ManyToOneRel">1</field>
</object>
<object pk="1" model="admin_views.chapter">
<field type="CharField" name="title">Norske bostaver æøå skaper problemer</field>
<field type="TextField" name="content">&lt;p&gt;Svært frustrerende med UnicodeDecodeErro&lt;/p&gt;</field>
<field to="admin_views.book" name="book" rel="ManyToOneRel">1</field>
</object>
<object pk="2" model="admin_views.chapter">
<field type="CharField" name="title">Kjærlighet</field>
<field type="TextField" name="content">&lt;p&gt;La kjærligheten til de lidende seire.&lt;/p&gt;</field>
<field to="admin_views.book" name="book" rel="ManyToOneRel">1</field>
</object>
<object pk="3" model="admin_views.chapter">
<field type="CharField" name="title">Kjærlighet</field>
<field type="TextField" name="content">&lt;p&gt;Noe innhold&lt;/p&gt;</field>
<field to="admin_views.book" name="book" rel="ManyToOneRel">1</field>
</object>
<object pk="1" model="admin_views.chapterxtra1">
<field type="CharField" name="xtra">&lt;Xtra(1) Norske bostaver æøå skaper problemer&gt;</field>
<field to="admin_views.chapter" name="chap" rel="OneToOneRel">1</field>
</object>
<object pk="2" model="admin_views.chapterxtra1">
<field type="CharField" name="xtra">&lt;Xtra(1) Kjærlighet&gt;</field>
<field to="admin_views.chapter" name="chap" rel="OneToOneRel">2</field>
</object>
<object pk="3" model="admin_views.chapterxtra1">
<field type="CharField" name="xtra">&lt;Xtra(1) Kjærlighet&gt;</field>
<field to="admin_views.chapter" name="chap" rel="OneToOneRel">3</field>
</object>
<object pk="1" model="admin_views.chapterxtra2">
<field type="CharField" name="xtra">&lt;Xtra(2) Norske bostaver æøå skaper problemer&gt;</field>
<field to="admin_views.chapter" name="chap" rel="OneToOneRel">1</field>
</object>
<object pk="2" model="admin_views.chapterxtra2">
<field type="CharField" name="xtra">&lt;Xtra(2) Kjærlighet&gt;</field>
<field to="admin_views.chapter" name="chap" rel="OneToOneRel">2</field>
</object>
<object pk="3" model="admin_views.chapterxtra2">
<field type="CharField" name="xtra">&lt;Xtra(2) Kjærlighet&gt;</field>
<field to="admin_views.chapter" name="chap" rel="OneToOneRel">3</field>
</object>
</django-objects>

View File

@ -1,110 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<django-objects version="1.0">
<object pk="100" model="auth.user">
<field type="CharField" name="username">super</field>
<field type="CharField" name="first_name">Super</field>
<field type="CharField" name="last_name">User</field>
<field type="CharField" name="email">super@example.com</field>
<field type="CharField" name="password">sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158</field>
<field type="BooleanField" name="is_staff">True</field>
<field type="BooleanField" name="is_active">True</field>
<field type="BooleanField" name="is_superuser">True</field>
<field type="DateTimeField" name="last_login">2007-05-30 13:20:10</field>
<field type="DateTimeField" name="date_joined">2007-05-30 13:20:10</field>
<field to="auth.group" name="groups" rel="ManyToManyRel"></field>
<field to="auth.permission" name="user_permissions" rel="ManyToManyRel"></field>
</object>
<object pk="101" model="auth.user">
<field type="CharField" name="username">adduser</field>
<field type="CharField" name="first_name">Add</field>
<field type="CharField" name="last_name">User</field>
<field type="CharField" name="email">auser@example.com</field>
<field type="CharField" name="password">sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158</field>
<field type="BooleanField" name="is_staff">True</field>
<field type="BooleanField" name="is_active">True</field>
<field type="BooleanField" name="is_superuser">False</field>
<field type="DateTimeField" name="last_login">2007-05-30 13:20:10</field>
<field type="DateTimeField" name="date_joined">2007-05-30 13:20:10</field>
<field to="auth.group" name="groups" rel="ManyToManyRel"></field>
<field to="auth.permission" name="user_permissions" rel="ManyToManyRel"></field>
</object>
<object pk="102" model="auth.user">
<field type="CharField" name="username">changeuser</field>
<field type="CharField" name="first_name">Change</field>
<field type="CharField" name="last_name">User</field>
<field type="CharField" name="email">cuser@example.com</field>
<field type="CharField" name="password">sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158</field>
<field type="BooleanField" name="is_staff">True</field>
<field type="BooleanField" name="is_active">True</field>
<field type="BooleanField" name="is_superuser">False</field>
<field type="DateTimeField" name="last_login">2007-05-30 13:20:10</field>
<field type="DateTimeField" name="date_joined">2007-05-30 13:20:10</field>
<field to="auth.group" name="groups" rel="ManyToManyRel"></field>
<field to="auth.permission" name="user_permissions" rel="ManyToManyRel"></field>
</object>
<object pk="103" model="auth.user">
<field type="CharField" name="username">deleteuser</field>
<field type="CharField" name="first_name">Delete</field>
<field type="CharField" name="last_name">User</field>
<field type="CharField" name="email">duser@example.com</field>
<field type="CharField" name="password">sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158</field>
<field type="BooleanField" name="is_staff">True</field>
<field type="BooleanField" name="is_active">True</field>
<field type="BooleanField" name="is_superuser">False</field>
<field type="DateTimeField" name="last_login">2007-05-30 13:20:10</field>
<field type="DateTimeField" name="date_joined">2007-05-30 13:20:10</field>
<field to="auth.group" name="groups" rel="ManyToManyRel"></field>
<field to="auth.permission" name="user_permissions" rel="ManyToManyRel"></field>
</object>
<object pk="104" model="auth.user">
<field type="CharField" name="username">joepublic</field>
<field type="CharField" name="first_name">Joe</field>
<field type="CharField" name="last_name">Public</field>
<field type="CharField" name="email">joepublic@example.com</field>
<field type="CharField" name="password">sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158</field>
<field type="BooleanField" name="is_staff">False</field>
<field type="BooleanField" name="is_active">True</field>
<field type="BooleanField" name="is_superuser">False</field>
<field type="DateTimeField" name="last_login">2007-05-30 13:20:10</field>
<field type="DateTimeField" name="date_joined">2007-05-30 13:20:10</field>
<field to="auth.group" name="groups" rel="ManyToManyRel"></field>
<field to="auth.permission" name="user_permissions" rel="ManyToManyRel"></field>
</object>
<object pk="106" model="auth.user">
<field type="CharField" name="username">nostaff</field>
<field type="CharField" name="first_name">No</field>
<field type="CharField" name="last_name">Staff</field>
<field type="CharField" name="email">nostaff@example.com</field>
<field type="CharField" name="password">sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158</field>
<field type="BooleanField" name="is_staff">False</field>
<field type="BooleanField" name="is_active">True</field>
<field type="BooleanField" name="is_superuser">False</field>
<field type="DateTimeField" name="last_login">2007-05-30 13:20:10</field>
<field type="DateTimeField" name="date_joined">2007-05-30 13:20:10</field>
<field to="auth.group" name="groups" rel="ManyToManyRel"></field>
<field to="auth.permission" name="user_permissions" rel="ManyToManyRel"></field>
</object>
<object pk="1" model="admin_views.section">
<field type="CharField" name="name">Test section</field>
</object>
<object pk="1" model="admin_views.article">
<field type="TextField" name="content">&lt;p&gt;Middle content&lt;/p&gt;</field>
<field type="DateTimeField" name="date">2008-03-18 11:54:58</field>
<field to="admin_views.section" name="section" rel="ManyToOneRel">1</field>
</object>
<object pk="2" model="admin_views.article">
<field type="TextField" name="content">&lt;p&gt;Oldest content&lt;/p&gt;</field>
<field type="DateTimeField" name="date">2000-03-18 11:54:58</field>
<field to="admin_views.section" name="section" rel="ManyToOneRel">1</field>
</object>
<object pk="3" model="admin_views.article">
<field type="TextField" name="content">&lt;p&gt;Newest content&lt;/p&gt;</field>
<field type="DateTimeField" name="date">2009-03-18 11:54:58</field>
<field to="admin_views.section" name="section" rel="ManyToOneRel">1</field>
</object>
<object pk="1" model="admin_views.prepopulatedpost">
<field type="TextField" name="title">A Long Title</field>
<field type="BooleanField" name="published">True</field>
<field type="SlugField" name="slug">a-long-title</field>
</object>
</django-objects>

View File

@ -1,53 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<django-objects version="1.0">
<object pk="1" model="admin_views.villain">
<field type="CharField" name="name">Adam</field>
</object>
<object pk="2" model="admin_views.villain">
<field type="CharField" name="name">Sue</field>
</object>
<object pk="3" model="admin_views.villain">
<field type="CharField" name="name">Bob</field>
</object>
<object pk="3" model="admin_views.supervillain">
</object>
<object pk="1" model="admin_views.plot">
<field type="CharField" name="name">World Domination</field>
<field type="ForeignKey" name="team_leader">1</field>
<field type="ForeignKey" name="contact">2</field>
</object>
<object pk="2" model="admin_views.plot">
<field type="CharField" name="name">World Peace</field>
<field type="ForeignKey" name="team_leader">2</field>
<field type="ForeignKey" name="contact">2</field>
</object>
<object pk="1" model="admin_views.plotdetails">
<field type="CharField" name="details">almost finished</field>
<field type="ForeignKey" name="plot">1</field>
</object>
<object pk="1" model="admin_views.secrethideout">
<field type="CharField" name="location">underground bunker</field>
<field type="ForeignKey" name="villain">1</field>
</object>
<object pk="2" model="admin_views.secrethideout">
<field type="CharField" name="location">floating castle</field>
<field type="ForeignKey" name="villain">3</field>
</object>
<object pk="1" model="admin_views.supersecrethideout">
<field type="CharField" name="location">super floating castle!</field>
<field type="ForeignKey" name="supervillain">3</field>
</object>
<object pk="1" model="admin_views.cyclicone">
<field type="CharField" name="name">I am recursive</field>
<field type="ForeignKey" name="two">1</field>
</object>
<object pk="1" model="admin_views.cyclictwo">
<field type="CharField" name="name">I am recursive too</field>
<field type="ForeignKey" name="one">1</field>
</object>
<object pk="3" model="admin_views.plot">
<field type="CharField" name="name">Corn Conspiracy</field>
<field type="ForeignKey" name="team_leader">1</field>
<field type="ForeignKey" name="contact">1</field>
</object>
</django-objects>

View File

@ -1,107 +0,0 @@
[
{
"pk": 1,
"model": "admin_views.title",
"fields":
{
}
},
{
"pk": 2,
"model": "admin_views.title",
"fields":
{
}
},
{
"pk": 3,
"model": "admin_views.title",
"fields":
{
}
},
{
"pk": 4,
"model": "admin_views.title",
"fields":
{
}
},
{
"pk": 1,
"model": "admin_views.titletranslation",
"fields":
{
"text": "Bar",
"title": 1
}
},
{
"pk": 2,
"model": "admin_views.titletranslation",
"fields":
{
"text": "Foo",
"title": 2
}
},
{
"pk": 3,
"model": "admin_views.titletranslation",
"fields":
{
"text": "Few",
"title": 3
}
},
{
"pk": 4,
"model": "admin_views.titletranslation",
"fields":
{
"text": "Bas",
"title": 4
}
},
{
"pk": 1,
"model": "admin_views.recommender",
"fields":
{
}
},
{
"pk": 4,
"model": "admin_views.recommender",
"fields":
{
}
},
{
"pk": 2,
"model": "admin_views.recommendation",
"fields":
{
"recommender": 1
}
},
{
"pk": 3,
"model": "admin_views.recommendation",
"fields":
{
"recommender": 4
}
}
]

View File

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<django-objects version="1.0">
<object pk="1" model="admin_views.modelwithstringprimarykey">
<field type="CharField" name="string_pk"><![CDATA[abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890 -_.!~*'() ;/?:@&=+$, <>#%" {}|\^[]`]]></field>
</object>
</django-objects>

File diff suppressed because it is too large Load Diff

View File

@ -1,43 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<django-objects version="1.0">
<object pk="100" model="auth.user">
<field type="CharField" name="username">super</field>
<field type="CharField" name="first_name">Super</field>
<field type="CharField" name="last_name">User</field>
<field type="CharField" name="email">super@example.com</field>
<field type="CharField" name="password">sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158</field>
<field type="BooleanField" name="is_staff">True</field>
<field type="BooleanField" name="is_active">True</field>
<field type="BooleanField" name="is_superuser">True</field>
<field type="DateTimeField" name="last_login">2007-05-30 13:20:10</field>
<field type="DateTimeField" name="date_joined">2007-05-30 13:20:10</field>
<field to="auth.group" name="groups" rel="ManyToManyRel"></field>
<field to="auth.permission" name="user_permissions" rel="ManyToManyRel"></field>
</object>
<object pk="101" model="auth.user">
<field type="CharField" name="username">testser</field>
<field type="CharField" name="first_name">Add</field>
<field type="CharField" name="last_name">User</field>
<field type="CharField" name="email">auser@example.com</field>
<field type="CharField" name="password">sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158</field>
<field type="BooleanField" name="is_staff">True</field>
<field type="BooleanField" name="is_active">True</field>
<field type="BooleanField" name="is_superuser">False</field>
<field type="DateTimeField" name="last_login">2007-05-30 13:20:10</field>
<field type="DateTimeField" name="date_joined">2007-05-30 13:20:10</field>
<field to="auth.group" name="groups" rel="ManyToManyRel"></field>
<field to="auth.permission" name="user_permissions" rel="ManyToManyRel"></field>
</object>
<object pk="1" model="admin_widgets.car">
<field to="auth.user" name="owner" rel="ManyToOneRel">100</field>
<field type="CharField" name="make">Volkswagon</field>
<field type="CharField" name="model">Passat</field>
</object>
<object pk="2" model="admin_widgets.car">
<field to="auth.user" name="owner" rel="ManyToOneRel">101</field>
<field type="CharField" name="make">BMW</field>
<field type="CharField" name="model">M3</field>
</object>
</django-objects>

View File

@ -12,6 +12,7 @@ from django.conf import settings
from django.contrib import admin
from django.contrib.admin import widgets
from django.contrib.admin.tests import AdminSeleniumWebDriverTestCase
from django.contrib.auth.models import User
from django.core.files.storage import default_storage
from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.urlresolvers import reverse
@ -32,6 +33,26 @@ admin_static_prefix = lambda: {
}
class TestDataMixin(object):
@classmethod
def setUpTestData(cls):
cls.u1 = User.objects.create(
pk=100, username='super', first_name='Super', last_name='User', email='super@example.com',
password='sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158', is_active=True, is_superuser=True,
is_staff=True, last_login=datetime(2007, 5, 30, 13, 20, 10),
date_joined=datetime(2007, 5, 30, 13, 20, 10)
)
cls.u2 = User.objects.create(
pk=101, username='testser', first_name='Add', last_name='User', email='auser@example.com',
password='sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158', is_active=True, is_superuser=False,
is_staff=True, last_login=datetime(2007, 5, 30, 13, 20, 10),
date_joined=datetime(2007, 5, 30, 13, 20, 10)
)
models.Car.objects.create(id=1, owner=cls.u1, make='Volkswagon', model='Passat')
models.Car.objects.create(id=2, owner=cls.u2, make='BMW', model='M3')
class AdminFormfieldForDBFieldTests(TestCase):
"""
Tests for correct behavior of ModelAdmin.formfield_for_dbfield
@ -167,8 +188,7 @@ class AdminFormfieldForDBFieldTests(TestCase):
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='admin_widgets.urls')
class AdminFormfieldForDBFieldWithRequestTests(DjangoTestCase):
fixtures = ["admin-widgets-users.xml"]
class AdminFormfieldForDBFieldWithRequestTests(TestDataMixin, DjangoTestCase):
def test_filter_choices_by_request_user(self):
"""
@ -182,8 +202,7 @@ class AdminFormfieldForDBFieldWithRequestTests(DjangoTestCase):
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='admin_widgets.urls')
class AdminForeignKeyWidgetChangeList(DjangoTestCase):
fixtures = ["admin-widgets-users.xml"]
class AdminForeignKeyWidgetChangeList(TestDataMixin, DjangoTestCase):
def setUp(self):
self.client.login(username="super", password="secret")
@ -195,8 +214,7 @@ class AdminForeignKeyWidgetChangeList(DjangoTestCase):
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='admin_widgets.urls')
class AdminForeignKeyRawIdWidget(DjangoTestCase):
fixtures = ["admin-widgets-users.xml"]
class AdminForeignKeyRawIdWidget(TestDataMixin, DjangoTestCase):
def setUp(self):
self.client.login(username="super", password="secret")
@ -352,12 +370,13 @@ class AdminURLWidgetTest(DjangoTestCase):
PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='admin_widgets.urls',
)
class AdminFileWidgetTests(DjangoTestCase):
fixtures = ['admin-widgets-users.xml']
class AdminFileWidgetTests(TestDataMixin, DjangoTestCase):
def setUp(self):
@classmethod
def setUpTestData(cls):
super(AdminFileWidgetTests, cls).setUpTestData()
band = models.Band.objects.create(name='Linkin Park')
self.album = band.album_set.create(
cls.album = band.album_set.create(
name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg'
)
@ -572,10 +591,9 @@ class RelatedFieldWidgetWrapperTests(DjangoTestCase):
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='admin_widgets.urls')
class DateTimePickerSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase):
class DateTimePickerSeleniumFirefoxTests(TestDataMixin, AdminSeleniumWebDriverTestCase):
available_apps = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps
fixtures = ['admin-widgets-users.xml']
webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver'
def test_show_hide_date_time_picker_widgets(self):
@ -750,9 +768,8 @@ class DateTimePickerSeleniumIETests(DateTimePickerSeleniumFirefoxTests):
@override_settings(TIME_ZONE='Asia/Singapore')
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='admin_widgets.urls')
class DateTimePickerShortcutsSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase):
class DateTimePickerShortcutsSeleniumFirefoxTests(TestDataMixin, AdminSeleniumWebDriverTestCase):
available_apps = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps
fixtures = ['admin-widgets-users.xml']
webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver'
def test_date_time_picker_shortcuts(self):
@ -818,23 +835,23 @@ class DateTimePickerShortcutsSeleniumIETests(DateTimePickerShortcutsSeleniumFire
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='admin_widgets.urls')
class HorizontalVerticalFilterSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase):
class HorizontalVerticalFilterSeleniumFirefoxTests(TestDataMixin, AdminSeleniumWebDriverTestCase):
available_apps = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps
fixtures = ['admin-widgets-users.xml']
webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver'
def setUp(self):
self.lisa = models.Student.objects.create(name='Lisa')
self.john = models.Student.objects.create(name='John')
self.bob = models.Student.objects.create(name='Bob')
self.peter = models.Student.objects.create(name='Peter')
self.jenny = models.Student.objects.create(name='Jenny')
self.jason = models.Student.objects.create(name='Jason')
self.cliff = models.Student.objects.create(name='Cliff')
self.arthur = models.Student.objects.create(name='Arthur')
self.school = models.School.objects.create(name='School of Awesome')
super(HorizontalVerticalFilterSeleniumFirefoxTests, self).setUp()
@classmethod
def setUpTestData(cls):
super(HorizontalVerticalFilterSeleniumFirefoxTests, cls).setUpTestData()
cls.lisa = models.Student.objects.create(name='Lisa')
cls.john = models.Student.objects.create(name='John')
cls.bob = models.Student.objects.create(name='Bob')
cls.peter = models.Student.objects.create(name='Peter')
cls.jenny = models.Student.objects.create(name='Jenny')
cls.jason = models.Student.objects.create(name='Jason')
cls.cliff = models.Student.objects.create(name='Cliff')
cls.arthur = models.Student.objects.create(name='Arthur')
cls.school = models.School.objects.create(name='School of Awesome')
def assertActiveButtons(self, mode, field_name, choose, remove,
choose_all=None, remove_all=None):
@ -1073,15 +1090,15 @@ class HorizontalVerticalFilterSeleniumIETests(HorizontalVerticalFilterSeleniumFi
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='admin_widgets.urls')
class AdminRawIdWidgetSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase):
class AdminRawIdWidgetSeleniumFirefoxTests(TestDataMixin, AdminSeleniumWebDriverTestCase):
available_apps = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps
fixtures = ['admin-widgets-users.xml']
webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver'
def setUp(self):
@classmethod
def setUpTestData(cls):
super(AdminRawIdWidgetSeleniumFirefoxTests, cls).setUpTestData()
models.Band.objects.create(id=42, name='Bogey Blues')
models.Band.objects.create(id=98, name='Green Potatoes')
super(AdminRawIdWidgetSeleniumFirefoxTests, self).setUp()
def test_ForeignKey(self):
self.admin_login(username='super', password='secret', login_url='/')
@ -1164,9 +1181,8 @@ class AdminRawIdWidgetSeleniumIETests(AdminRawIdWidgetSeleniumFirefoxTests):
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='admin_widgets.urls')
class RelatedFieldWidgetSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase):
class RelatedFieldWidgetSeleniumFirefoxTests(TestDataMixin, AdminSeleniumWebDriverTestCase):
available_apps = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps
fixtures = ['admin-widgets-users.xml']
webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver'
def test_ForeignKey_using_to_field(self):

View File

@ -1,243 +0,0 @@
[
{
"pk": 1,
"model": "aggregation.publisher",
"fields": {
"name": "Apress",
"num_awards": 3
}
},
{
"pk": 2,
"model": "aggregation.publisher",
"fields": {
"name": "Sams",
"num_awards": 1
}
},
{
"pk": 3,
"model": "aggregation.publisher",
"fields": {
"name": "Prentice Hall",
"num_awards": 7
}
},
{
"pk": 4,
"model": "aggregation.publisher",
"fields": {
"name": "Morgan Kaufmann",
"num_awards": 9
}
},
{
"pk": 5,
"model": "aggregation.publisher",
"fields": {
"name": "Jonno's House of Books",
"num_awards": 0
}
},
{
"pk": 1,
"model": "aggregation.book",
"fields": {
"publisher": 1,
"isbn": "159059725",
"name": "The Definitive Guide to Django: Web Development Done Right",
"price": "30.00",
"rating": 4.5,
"authors": [1, 2],
"contact": 1,
"pages": 447,
"pubdate": "2007-12-6"
}
},
{
"pk": 2,
"model": "aggregation.book",
"fields": {
"publisher": 2,
"isbn": "067232959",
"name": "Sams Teach Yourself Django in 24 Hours",
"price": "23.09",
"rating": 3.0,
"authors": [3],
"contact": 3,
"pages": 528,
"pubdate": "2008-3-3"
}
},
{
"pk": 3,
"model": "aggregation.book",
"fields": {
"publisher": 1,
"isbn": "159059996",
"name": "Practical Django Projects",
"price": "29.69",
"rating": 4.0,
"authors": [4],
"contact": 4,
"pages": 300,
"pubdate": "2008-6-23"
}
},
{
"pk": 4,
"model": "aggregation.book",
"fields": {
"publisher": 3,
"isbn": "013235613",
"name": "Python Web Development with Django",
"price": "29.69",
"rating": 4.0,
"authors": [5, 6, 7],
"contact": 5,
"pages": 350,
"pubdate": "2008-11-3"
}
},
{
"pk": 5,
"model": "aggregation.book",
"fields": {
"publisher": 3,
"isbn": "013790395",
"name": "Artificial Intelligence: A Modern Approach",
"price": "82.80",
"rating": 4.0,
"authors": [8, 9],
"contact": 8,
"pages": 1132,
"pubdate": "1995-1-15"
}
},
{
"pk": 6,
"model": "aggregation.book",
"fields": {
"publisher": 4,
"isbn": "155860191",
"name": "Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp",
"price": "75.00",
"rating": 5.0,
"authors": [8],
"contact": 8,
"pages": 946,
"pubdate": "1991-10-15"
}
},
{
"pk": 1,
"model": "aggregation.store",
"fields": {
"books": [1, 2, 3, 4, 5, 6],
"name": "Amazon.com",
"original_opening": "1994-4-23 9:17:42",
"friday_night_closing": "23:59:59"
}
},
{
"pk": 2,
"model": "aggregation.store",
"fields": {
"books": [1, 3, 5, 6],
"name": "Books.com",
"original_opening": "2001-3-15 11:23:37",
"friday_night_closing": "23:59:59"
}
},
{
"pk": 3,
"model": "aggregation.store",
"fields": {
"books": [3, 4, 6],
"name": "Mamma and Pappa's Books",
"original_opening": "1945-4-25 16:24:14",
"friday_night_closing": "21:30:00"
}
},
{
"pk": 1,
"model": "aggregation.author",
"fields": {
"age": 34,
"friends": [2, 4],
"name": "Adrian Holovaty"
}
},
{
"pk": 2,
"model": "aggregation.author",
"fields": {
"age": 35,
"friends": [1, 7],
"name": "Jacob Kaplan-Moss"
}
},
{
"pk": 3,
"model": "aggregation.author",
"fields": {
"age": 45,
"friends": [],
"name": "Brad Dayley"
}
},
{
"pk": 4,
"model": "aggregation.author",
"fields": {
"age": 29,
"friends": [1],
"name": "James Bennett"
}
},
{
"pk": 5,
"model": "aggregation.author",
"fields": {
"age": 37,
"friends": [6, 7],
"name": "Jeffrey Forcier"
}
},
{
"pk": 6,
"model": "aggregation.author",
"fields": {
"age": 29,
"friends": [5, 7],
"name": "Paul Bissex"
}
},
{
"pk": 7,
"model": "aggregation.author",
"fields": {
"age": 25,
"friends": [2, 5, 6],
"name": "Wesley J. Chun"
}
},
{
"pk": 8,
"model": "aggregation.author",
"fields": {
"age": 57,
"friends": [9],
"name": "Peter Norvig"
}
},
{
"pk": 9,
"model": "aggregation.author",
"fields": {
"age": 46,
"friends": [8],
"name": "Stuart Russell"
}
}
]

View File

@ -18,8 +18,89 @@ from django.utils.deprecation import RemovedInDjango20Warning
from .models import Author, Book, Publisher, Store
class BaseAggregateTestCase(TestCase):
fixtures = ["aggregation.json"]
class AggregateTestCase(TestCase):
@classmethod
def setUpTestData(cls):
cls.a1 = Author.objects.create(name='Adrian Holovaty', age=34)
cls.a2 = Author.objects.create(name='Jacob Kaplan-Moss', age=35)
cls.a3 = Author.objects.create(name='Brad Dayley', age=45)
cls.a4 = Author.objects.create(name='James Bennett', age=29)
cls.a5 = Author.objects.create(name='Jeffrey Forcier', age=37)
cls.a6 = Author.objects.create(name='Paul Bissex', age=29)
cls.a7 = Author.objects.create(name='Wesley J. Chun', age=25)
cls.a8 = Author.objects.create(name='Peter Norvig', age=57)
cls.a9 = Author.objects.create(name='Stuart Russell', age=46)
cls.a1.friends.add(cls.a2, cls.a4)
cls.a2.friends.add(cls.a1, cls.a7)
cls.a4.friends.add(cls.a1)
cls.a5.friends.add(cls.a6, cls.a7)
cls.a6.friends.add(cls.a5, cls.a7)
cls.a7.friends.add(cls.a2, cls.a5, cls.a6)
cls.a8.friends.add(cls.a9)
cls.a9.friends.add(cls.a8)
cls.p1 = Publisher.objects.create(name='Apress', num_awards=3)
cls.p2 = Publisher.objects.create(name='Sams', num_awards=1)
cls.p3 = Publisher.objects.create(name='Prentice Hall', num_awards=7)
cls.p4 = Publisher.objects.create(name='Morgan Kaufmann', num_awards=9)
cls.p5 = Publisher.objects.create(name="Jonno's House of Books", num_awards=0)
cls.b1 = Book.objects.create(
isbn='159059725', name='The Definitive Guide to Django: Web Development Done Right',
pages=447, rating=4.5, price=Decimal('30.00'), contact=cls.a1, publisher=cls.p1,
pubdate=datetime.date(2007, 12, 6)
)
cls.b2 = Book.objects.create(
isbn='067232959', name='Sams Teach Yourself Django in 24 Hours',
pages=528, rating=3.0, price=Decimal('23.09'), contact=cls.a3, publisher=cls.p2,
pubdate=datetime.date(2008, 3, 3)
)
cls.b3 = Book.objects.create(
isbn='159059996', name='Practical Django Projects',
pages=300, rating=4.0, price=Decimal('29.69'), contact=cls.a4, publisher=cls.p1,
pubdate=datetime.date(2008, 6, 23)
)
cls.b4 = Book.objects.create(
isbn='013235613', name='Python Web Development with Django',
pages=350, rating=4.0, price=Decimal('29.69'), contact=cls.a5, publisher=cls.p3,
pubdate=datetime.date(2008, 11, 3)
)
cls.b5 = Book.objects.create(
isbn='013790395', name='Artificial Intelligence: A Modern Approach',
pages=1132, rating=4.0, price=Decimal('82.80'), contact=cls.a8, publisher=cls.p3,
pubdate=datetime.date(1995, 1, 15)
)
cls.b6 = Book.objects.create(
isbn='155860191', name='Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp',
pages=946, rating=5.0, price=Decimal('75.00'), contact=cls.a8, publisher=cls.p4,
pubdate=datetime.date(1991, 10, 15)
)
cls.b1.authors.add(cls.a1, cls.a2)
cls.b2.authors.add(cls.a3)
cls.b3.authors.add(cls.a4)
cls.b4.authors.add(cls.a5, cls.a6, cls.a7)
cls.b5.authors.add(cls.a8, cls.a9)
cls.b6.authors.add(cls.a8)
s1 = Store.objects.create(
name='Amazon.com',
original_opening=datetime.datetime(1994, 4, 23, 9, 17, 42),
friday_night_closing=datetime.time(23, 59, 59)
)
s2 = Store.objects.create(
name='Books.com',
original_opening=datetime.datetime(2001, 3, 15, 11, 23, 37),
friday_night_closing=datetime.time(23, 59, 59)
)
s3 = Store.objects.create(
name="Mamma and Pappa's Books",
original_opening=datetime.datetime(1945, 4, 25, 16, 24, 14),
friday_night_closing=datetime.time(21, 30)
)
s1.books.add(cls.b1, cls.b2, cls.b3, cls.b4, cls.b5, cls.b6)
s2.books.add(cls.b1, cls.b3, cls.b5, cls.b6)
s3.books.add(cls.b3, cls.b4, cls.b6)
def test_empty_aggregate(self):
self.assertEqual(Author.objects.all().aggregate(), {})
@ -86,7 +167,7 @@ class BaseAggregateTestCase(TestCase):
)
books = Book.objects.annotate(mean_age=Avg("authors__age"))
b = books.get(pk=1)
b = books.get(pk=self.b1.pk)
self.assertEqual(
b.name,
'The Definitive Guide to Django: Web Development Done Right'
@ -95,7 +176,7 @@ class BaseAggregateTestCase(TestCase):
def test_annotate_defer(self):
qs = Book.objects.annotate(
page_sum=Sum("pages")).defer('name').filter(pk=1)
page_sum=Sum("pages")).defer('name').filter(pk=self.b1.pk)
rows = [
(1, "159059725", 447, "The Definitive Guide to Django: Web Development Done Right")
@ -107,7 +188,7 @@ class BaseAggregateTestCase(TestCase):
def test_annotate_defer_select_related(self):
qs = Book.objects.select_related('contact').annotate(
page_sum=Sum("pages")).defer('name').filter(pk=1)
page_sum=Sum("pages")).defer('name').filter(pk=self.b1.pk)
rows = [
(1, "159059725", 447, "Adrian Holovaty",
@ -200,7 +281,7 @@ class BaseAggregateTestCase(TestCase):
)
def test_annotate_values(self):
books = list(Book.objects.filter(pk=1).annotate(mean_age=Avg("authors__age")).values())
books = list(Book.objects.filter(pk=self.b1.pk).annotate(mean_age=Avg("authors__age")).values())
self.assertEqual(
books, [
{
@ -218,7 +299,7 @@ class BaseAggregateTestCase(TestCase):
]
)
books = Book.objects.filter(pk=1).annotate(mean_age=Avg('authors__age')).values('pk', 'isbn', 'mean_age')
books = Book.objects.filter(pk=self.b1.pk).annotate(mean_age=Avg('authors__age')).values('pk', 'isbn', 'mean_age')
self.assertEqual(
list(books), [
{
@ -229,7 +310,7 @@ class BaseAggregateTestCase(TestCase):
]
)
books = Book.objects.filter(pk=1).annotate(mean_age=Avg("authors__age")).values("name")
books = Book.objects.filter(pk=self.b1.pk).annotate(mean_age=Avg("authors__age")).values("name")
self.assertEqual(
list(books), [
{
@ -238,7 +319,7 @@ class BaseAggregateTestCase(TestCase):
]
)
books = Book.objects.filter(pk=1).values().annotate(mean_age=Avg('authors__age'))
books = Book.objects.filter(pk=self.b1.pk).values().annotate(mean_age=Avg('authors__age'))
self.assertEqual(
list(books), [
{
@ -470,7 +551,7 @@ class BaseAggregateTestCase(TestCase):
self.assertEqual(len(publishers), 0)
def test_annotation(self):
vals = Author.objects.filter(pk=1).aggregate(Count("friends__id"))
vals = Author.objects.filter(pk=self.a1.pk).aggregate(Count("friends__id"))
self.assertEqual(vals, {"friends__id__count": 2})
books = Book.objects.annotate(num_authors=Count("authors__name")).filter(num_authors__exact=2).order_by("pk")
@ -565,28 +646,28 @@ class BaseAggregateTestCase(TestCase):
)
def test_annotate_values_list(self):
books = Book.objects.filter(pk=1).annotate(mean_age=Avg("authors__age")).values_list("pk", "isbn", "mean_age")
books = Book.objects.filter(pk=self.b1.pk).annotate(mean_age=Avg("authors__age")).values_list("pk", "isbn", "mean_age")
self.assertEqual(
list(books), [
(1, "159059725", 34.5),
]
)
books = Book.objects.filter(pk=1).annotate(mean_age=Avg("authors__age")).values_list("isbn")
books = Book.objects.filter(pk=self.b1.pk).annotate(mean_age=Avg("authors__age")).values_list("isbn")
self.assertEqual(
list(books), [
('159059725',)
]
)
books = Book.objects.filter(pk=1).annotate(mean_age=Avg("authors__age")).values_list("mean_age")
books = Book.objects.filter(pk=self.b1.pk).annotate(mean_age=Avg("authors__age")).values_list("mean_age")
self.assertEqual(
list(books), [
(34.5,)
]
)
books = Book.objects.filter(pk=1).annotate(mean_age=Avg("authors__age")).values_list("mean_age", flat=True)
books = Book.objects.filter(pk=self.b1.pk).annotate(mean_age=Avg("authors__age")).values_list("mean_age", flat=True)
self.assertEqual(list(books), [34.5])
books = Book.objects.values_list("price").annotate(count=Count("price")).order_by("-count", "price")
@ -697,25 +778,21 @@ class BaseAggregateTestCase(TestCase):
book = Book.objects.aggregate(price_sum=Sum('price'))
self.assertEqual(book['price_sum'], Decimal("99999.80"))
class ComplexAggregateTestCase(TestCase):
fixtures = ["aggregation.json"]
def test_nonaggregate_aggregation_throws(self):
with six.assertRaisesRegex(self, TypeError, 'fail is not an aggregate expression'):
Book.objects.aggregate(fail=F('price'))
def test_nonfield_annotation(self):
book = Book.objects.annotate(val=Max(Value(2, output_field=IntegerField())))[0]
book = Book.objects.annotate(val=Max(Value(2, output_field=IntegerField()))).first()
self.assertEqual(book.val, 2)
book = Book.objects.annotate(val=Max(Value(2), output_field=IntegerField()))[0]
book = Book.objects.annotate(val=Max(Value(2), output_field=IntegerField())).first()
self.assertEqual(book.val, 2)
book = Book.objects.annotate(val=Max(2, output_field=IntegerField()))[0]
book = Book.objects.annotate(val=Max(2, output_field=IntegerField())).first()
self.assertEqual(book.val, 2)
def test_missing_output_field_raises_error(self):
with six.assertRaisesRegex(self, FieldError, 'Cannot resolve expression type, unknown output_field'):
Book.objects.annotate(val=Max(2))[0]
Book.objects.annotate(val=Max(2)).first()
def test_annotation_expressions(self):
authors = Author.objects.annotate(combined_ages=Sum(F('age') + F('friends__age'))).order_by('name')
@ -754,18 +831,18 @@ class ComplexAggregateTestCase(TestCase):
def test_combine_different_types(self):
with six.assertRaisesRegex(self, FieldError, 'Expression contains mixed types. You must set output_field'):
Book.objects.annotate(sums=Sum('rating') + Sum('pages') + Sum('price')).get(pk=4)
Book.objects.annotate(sums=Sum('rating') + Sum('pages') + Sum('price')).get(pk=self.b4.pk)
b1 = Book.objects.annotate(sums=Sum(F('rating') + F('pages') + F('price'),
output_field=IntegerField())).get(pk=4)
output_field=IntegerField())).get(pk=self.b4.pk)
self.assertEqual(b1.sums, 383)
b2 = Book.objects.annotate(sums=Sum(F('rating') + F('pages') + F('price'),
output_field=FloatField())).get(pk=4)
output_field=FloatField())).get(pk=self.b4.pk)
self.assertEqual(b2.sums, 383.69)
b3 = Book.objects.annotate(sums=Sum(F('rating') + F('pages') + F('price'),
output_field=DecimalField())).get(pk=4)
output_field=DecimalField())).get(pk=self.b4.pk)
self.assertEqual(b3.sums, Approximate(Decimal("383.69"), places=2))
def test_complex_aggregations_require_kwarg(self):
@ -805,14 +882,15 @@ class ComplexAggregateTestCase(TestCase):
def test_values_annotation_with_expression(self):
# ensure the F() is promoted to the group by clause
qs = Author.objects.values('name').annotate(another_age=Sum('age') + F('age'))
a = qs.get(pk=1)
a = qs.get(name="Adrian Holovaty")
self.assertEqual(a['another_age'], 68)
qs = qs.annotate(friend_count=Count('friends'))
a = qs.get(pk=1)
a = qs.get(name="Adrian Holovaty")
self.assertEqual(a['friend_count'], 2)
qs = qs.annotate(combined_age=Sum('age') + F('friends__age')).filter(pk=1).order_by('-combined_age')
qs = qs.annotate(combined_age=Sum('age') + F('friends__age')).filter(
name="Adrian Holovaty").order_by('-combined_age')
self.assertEqual(
list(qs), [
{
@ -860,11 +938,11 @@ class ComplexAggregateTestCase(TestCase):
age_alias=F('age')
).annotate(
sum_age=Sum('age_alias')
).get(pk=1)
).get(name="Adrian Holovaty")
other_author = Author.objects.annotate(
sum_age=Sum('age')
).get(pk=1)
).get(name="Adrian Holovaty")
self.assertEqual(author.sum_age, other_author.sum_age)
@ -885,7 +963,7 @@ class ComplexAggregateTestCase(TestCase):
qs = Book.objects.annotate(sums=Sum(F('rating') + F('pages') + F('price'),
output_field=IntegerField()))
self.assertEqual(str(qs.query).count('sum('), 1)
b1 = qs.get(pk=4)
b1 = qs.get(pk=self.b4.pk)
self.assertEqual(b1.sums, 383)
# test changing the dict and delegating
@ -897,7 +975,7 @@ class ComplexAggregateTestCase(TestCase):
qs = Book.objects.annotate(sums=Sum(F('rating') + F('pages') + F('price'),
output_field=IntegerField()))
self.assertEqual(str(qs.query).count('sum('), 1)
b1 = qs.get(pk=4)
b1 = qs.get(pk=self.b4.pk)
self.assertEqual(b1.sums, 383)
# test overriding all parts of the template
@ -910,7 +988,7 @@ class ComplexAggregateTestCase(TestCase):
qs = Book.objects.annotate(sums=Sum(F('rating') + F('pages') + F('price'),
output_field=IntegerField()))
self.assertEqual(str(qs.query).count('MAX('), 1)
b1 = qs.get(pk=4)
b1 = qs.get(pk=self.b4.pk)
self.assertEqual(b1.sums, 2)
finally:
delattr(Sum, 'as_' + connection.vendor)
@ -938,16 +1016,16 @@ class ComplexAggregateTestCase(TestCase):
qs = Publisher.objects.annotate(
price_or_median=Greatest(Avg('book__rating'), Avg('book__price'))
).filter(price_or_median__gte=F('num_awards')).order_by('pk')
).filter(price_or_median__gte=F('num_awards')).order_by('num_awards')
self.assertQuerysetEqual(
qs, [1, 2, 3, 4], lambda v: v.pk)
qs, [1, 3, 7, 9], lambda v: v.num_awards)
qs2 = Publisher.objects.annotate(
rating_or_num_awards=Greatest(Avg('book__rating'), F('num_awards'),
output_field=FloatField())
).filter(rating_or_num_awards__gt=F('num_awards')).order_by('pk')
).filter(rating_or_num_awards__gt=F('num_awards')).order_by('num_awards')
self.assertQuerysetEqual(
qs2, [1, 2], lambda v: v.pk)
qs2, [1, 3], lambda v: v.num_awards)
@ignore_warnings(category=RemovedInDjango20Warning)
def test_backwards_compatibility(self):
@ -966,5 +1044,5 @@ class ComplexAggregateTestCase(TestCase):
query.annotations[alias] = aggregate
qs = Author.objects.values('name').annotate(another_age=NewSum('age') + F('age'))
a = qs.get(pk=1)
a = qs.get(name="Adrian Holovaty")
self.assertEqual(a['another_age'], 68)

View File

@ -1,257 +0,0 @@
[
{
"pk": 1,
"model": "aggregation_regress.publisher",
"fields": {
"name": "Apress",
"num_awards": 3
}
},
{
"pk": 2,
"model": "aggregation_regress.publisher",
"fields": {
"name": "Sams",
"num_awards": 1
}
},
{
"pk": 3,
"model": "aggregation_regress.publisher",
"fields": {
"name": "Prentice Hall",
"num_awards": 7
}
},
{
"pk": 4,
"model": "aggregation_regress.publisher",
"fields": {
"name": "Morgan Kaufmann",
"num_awards": 9
}
},
{
"pk": 5,
"model": "aggregation_regress.publisher",
"fields": {
"name": "Jonno's House of Books",
"num_awards": 0
}
},
{
"pk": 1,
"model": "aggregation_regress.book",
"fields": {
"publisher": 1,
"isbn": "159059725",
"name": "The Definitive Guide to Django: Web Development Done Right",
"price": "30.00",
"rating": 4.5,
"authors": [1, 2],
"contact": 1,
"pages": 447,
"pubdate": "2007-12-6"
}
},
{
"pk": 2,
"model": "aggregation_regress.book",
"fields": {
"publisher": 2,
"isbn": "067232959",
"name": "Sams Teach Yourself Django in 24 Hours",
"price": "23.09",
"rating": 3.0,
"authors": [3],
"contact": 3,
"pages": 528,
"pubdate": "2008-3-3"
}
},
{
"pk": 3,
"model": "aggregation_regress.book",
"fields": {
"publisher": 1,
"isbn": "159059996",
"name": "Practical Django Projects",
"price": "29.69",
"rating": 4.0,
"authors": [4],
"contact": 4,
"pages": 300,
"pubdate": "2008-6-23"
}
},
{
"pk": 4,
"model": "aggregation_regress.book",
"fields": {
"publisher": 3,
"isbn": "013235613",
"name": "Python Web Development with Django",
"price": "29.69",
"rating": 4.0,
"authors": [5, 6, 7],
"contact": 5,
"pages": 350,
"pubdate": "2008-11-3"
}
},
{
"pk": 5,
"model": "aggregation_regress.book",
"fields": {
"publisher": 3,
"isbn": "013790395",
"name": "Artificial Intelligence: A Modern Approach",
"price": "82.80",
"rating": 4.0,
"authors": [8, 9],
"contact": 8,
"pages": 1132,
"pubdate": "1995-1-15"
}
},
{
"pk": 6,
"model": "aggregation_regress.book",
"fields": {
"publisher": 4,
"isbn": "155860191",
"name": "Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp",
"price": "75.00",
"rating": 5.0,
"authors": [8],
"contact": 8,
"pages": 946,
"pubdate": "1991-10-15"
}
},
{
"pk": 1,
"model": "aggregation_regress.store",
"fields": {
"books": [1, 2, 3, 4, 5, 6],
"name": "Amazon.com",
"original_opening": "1994-4-23 9:17:42",
"friday_night_closing": "23:59:59"
}
},
{
"pk": 2,
"model": "aggregation_regress.store",
"fields": {
"books": [1, 3, 5, 6],
"name": "Books.com",
"original_opening": "2001-3-15 11:23:37",
"friday_night_closing": "23:59:59"
}
},
{
"pk": 3,
"model": "aggregation_regress.store",
"fields": {
"books": [3, 4, 6],
"name": "Mamma and Pappa's Books",
"original_opening": "1945-4-25 16:24:14",
"friday_night_closing": "21:30:00"
}
},
{
"pk": 1,
"model": "aggregation_regress.author",
"fields": {
"age": 34,
"friends": [2, 4],
"name": "Adrian Holovaty"
}
},
{
"pk": 2,
"model": "aggregation_regress.author",
"fields": {
"age": 35,
"friends": [1, 7],
"name": "Jacob Kaplan-Moss"
}
},
{
"pk": 3,
"model": "aggregation_regress.author",
"fields": {
"age": 45,
"friends": [],
"name": "Brad Dayley"
}
},
{
"pk": 4,
"model": "aggregation_regress.author",
"fields": {
"age": 29,
"friends": [1],
"name": "James Bennett"
}
},
{
"pk": 5,
"model": "aggregation_regress.author",
"fields": {
"age": 37,
"friends": [6, 7],
"name": "Jeffrey Forcier"
}
},
{
"pk": 6,
"model": "aggregation_regress.author",
"fields": {
"age": 29,
"friends": [5, 7],
"name": "Paul Bissex"
}
},
{
"pk": 7,
"model": "aggregation_regress.author",
"fields": {
"age": 25,
"friends": [2, 5, 6],
"name": "Wesley J. Chun"
}
},
{
"pk": 8,
"model": "aggregation_regress.author",
"fields": {
"age": 57,
"friends": [9],
"name": "Peter Norvig"
}
},
{
"pk": 9,
"model": "aggregation_regress.author",
"fields": {
"age": 46,
"friends": [8],
"name": "Stuart Russell"
}
},
{
"pk": 5,
"model": "aggregation_regress.hardbackbook",
"fields": {
"weight": 4.5
}
},
{
"pk": 6,
"model": "aggregation_regress.hardbackbook",
"fields": {
"weight": 3.7
}
}
]

View File

@ -14,12 +14,91 @@ from django.utils import six
from .models import (
Alfa, Author, Book, Bravo, Charlie, Clues, Entries, HardbackBook, ItemTag,
Publisher, WithManualPK,
Publisher, Store, WithManualPK,
)
class AggregationTests(TestCase):
fixtures = ["aggregation_regress.json"]
@classmethod
def setUpTestData(cls):
cls.a1 = Author.objects.create(name='Adrian Holovaty', age=34)
cls.a2 = Author.objects.create(name='Jacob Kaplan-Moss', age=35)
cls.a3 = Author.objects.create(name='Brad Dayley', age=45)
cls.a4 = Author.objects.create(name='James Bennett', age=29)
cls.a5 = Author.objects.create(name='Jeffrey Forcier', age=37)
cls.a6 = Author.objects.create(name='Paul Bissex', age=29)
cls.a7 = Author.objects.create(name='Wesley J. Chun', age=25)
cls.a8 = Author.objects.create(name='Peter Norvig', age=57)
cls.a9 = Author.objects.create(name='Stuart Russell', age=46)
cls.a1.friends.add(cls.a2, cls.a4)
cls.a2.friends.add(cls.a1, cls.a7)
cls.a4.friends.add(cls.a1)
cls.a5.friends.add(cls.a6, cls.a7)
cls.a6.friends.add(cls.a5, cls.a7)
cls.a7.friends.add(cls.a2, cls.a5, cls.a6)
cls.a8.friends.add(cls.a9)
cls.a9.friends.add(cls.a8)
cls.p1 = Publisher.objects.create(name='Apress', num_awards=3)
cls.p2 = Publisher.objects.create(name='Sams', num_awards=1)
cls.p3 = Publisher.objects.create(name='Prentice Hall', num_awards=7)
cls.p4 = Publisher.objects.create(name='Morgan Kaufmann', num_awards=9)
cls.p5 = Publisher.objects.create(name="Jonno's House of Books", num_awards=0)
cls.b1 = Book.objects.create(
isbn='159059725', name='The Definitive Guide to Django: Web Development Done Right',
pages=447, rating=4.5, price=Decimal('30.00'), contact=cls.a1, publisher=cls.p1,
pubdate=datetime.date(2007, 12, 6)
)
cls.b2 = Book.objects.create(
isbn='067232959', name='Sams Teach Yourself Django in 24 Hours',
pages=528, rating=3.0, price=Decimal('23.09'), contact=cls.a3, publisher=cls.p2,
pubdate=datetime.date(2008, 3, 3)
)
cls.b3 = Book.objects.create(
isbn='159059996', name='Practical Django Projects',
pages=300, rating=4.0, price=Decimal('29.69'), contact=cls.a4, publisher=cls.p1,
pubdate=datetime.date(2008, 6, 23)
)
cls.b4 = Book.objects.create(
isbn='013235613', name='Python Web Development with Django',
pages=350, rating=4.0, price=Decimal('29.69'), contact=cls.a5, publisher=cls.p3,
pubdate=datetime.date(2008, 11, 3)
)
cls.b5 = HardbackBook.objects.create(
isbn='013790395', name='Artificial Intelligence: A Modern Approach',
pages=1132, rating=4.0, price=Decimal('82.80'), contact=cls.a8, publisher=cls.p3,
pubdate=datetime.date(1995, 1, 15), weight=4.5)
cls.b6 = HardbackBook.objects.create(
isbn='155860191', name='Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp',
pages=946, rating=5.0, price=Decimal('75.00'), contact=cls.a8, publisher=cls.p4,
pubdate=datetime.date(1991, 10, 15), weight=3.7)
cls.b1.authors.add(cls.a1, cls.a2)
cls.b2.authors.add(cls.a3)
cls.b3.authors.add(cls.a4)
cls.b4.authors.add(cls.a5, cls.a6, cls.a7)
cls.b5.authors.add(cls.a8, cls.a9)
cls.b6.authors.add(cls.a8)
s1 = Store.objects.create(
name='Amazon.com',
original_opening=datetime.datetime(1994, 4, 23, 9, 17, 42),
friday_night_closing=datetime.time(23, 59, 59)
)
s2 = Store.objects.create(
name='Books.com',
original_opening=datetime.datetime(2001, 3, 15, 11, 23, 37),
friday_night_closing=datetime.time(23, 59, 59)
)
s3 = Store.objects.create(
name="Mamma and Pappa's Books",
original_opening=datetime.datetime(1945, 4, 25, 16, 24, 14),
friday_night_closing=datetime.time(21, 30)
)
s1.books.add(cls.b1, cls.b2, cls.b3, cls.b4, cls.b5, cls.b6)
s2.books.add(cls.b1, cls.b3, cls.b5, cls.b6)
s3.books.add(cls.b3, cls.b4, cls.b6)
def assertObjectAttrs(self, obj, **kwargs):
for attr, value in six.iteritems(kwargs):
@ -121,84 +200,90 @@ class AggregationTests(TestCase):
def test_annotation(self):
# Annotations get combined with extra select clauses
obj = Book.objects.annotate(mean_auth_age=Avg("authors__age")).extra(select={"manufacture_cost": "price * .5"}).get(pk=2)
self.assertObjectAttrs(obj,
contact_id=3,
id=2,
obj = Book.objects.annotate(mean_auth_age=Avg("authors__age")).extra(
select={"manufacture_cost": "price * .5"}).get(pk=self.b2.pk)
self.assertObjectAttrs(
obj,
contact_id=self.a3.id,
isbn='067232959',
mean_auth_age=45.0,
name='Sams Teach Yourself Django in 24 Hours',
pages=528,
price=Decimal("23.09"),
pubdate=datetime.date(2008, 3, 3),
publisher_id=2,
publisher_id=self.p2.id,
rating=3.0
)
# Different DB backends return different types for the extra select computation
self.assertIn(obj.manufacture_cost, (11.545, Decimal('11.545')))
# Order of the annotate/extra in the query doesn't matter
obj = Book.objects.extra(select={'manufacture_cost': 'price * .5'}).annotate(mean_auth_age=Avg('authors__age')).get(pk=2)
self.assertObjectAttrs(obj,
contact_id=3,
id=2,
obj = Book.objects.extra(select={'manufacture_cost': 'price * .5'}).annotate(
mean_auth_age=Avg('authors__age')).get(pk=self.b2.pk)
self.assertObjectAttrs(
obj,
contact_id=self.a3.id,
isbn='067232959',
mean_auth_age=45.0,
name='Sams Teach Yourself Django in 24 Hours',
pages=528,
price=Decimal("23.09"),
pubdate=datetime.date(2008, 3, 3),
publisher_id=2,
publisher_id=self.p2.id,
rating=3.0
)
# Different DB backends return different types for the extra select computation
self.assertIn(obj.manufacture_cost, (11.545, Decimal('11.545')))
# Values queries can be combined with annotate and extra
obj = Book.objects.annotate(mean_auth_age=Avg('authors__age')).extra(select={'manufacture_cost': 'price * .5'}).values().get(pk=2)
obj = Book.objects.annotate(mean_auth_age=Avg('authors__age')).extra(
select={'manufacture_cost': 'price * .5'}).values().get(pk=self.b2.pk)
manufacture_cost = obj['manufacture_cost']
self.assertIn(manufacture_cost, (11.545, Decimal('11.545')))
del obj['manufacture_cost']
self.assertEqual(obj, {
"contact_id": 3,
"id": 2,
"isbn": "067232959",
"mean_auth_age": 45.0,
"name": "Sams Teach Yourself Django in 24 Hours",
"pages": 528,
"price": Decimal("23.09"),
"pubdate": datetime.date(2008, 3, 3),
"publisher_id": 2,
"rating": 3.0,
})
# The order of the (empty) values, annotate and extra clauses doesn't
# matter
obj = Book.objects.values().annotate(mean_auth_age=Avg('authors__age')).extra(select={'manufacture_cost': 'price * .5'}).get(pk=2)
manufacture_cost = obj['manufacture_cost']
self.assertIn(manufacture_cost, (11.545, Decimal('11.545')))
del obj['manufacture_cost']
self.assertEqual(obj, {
'contact_id': 3,
'id': 2,
'id': self.b2.id,
'contact_id': self.a3.id,
'isbn': '067232959',
'mean_auth_age': 45.0,
'name': 'Sams Teach Yourself Django in 24 Hours',
'pages': 528,
'price': Decimal("23.09"),
'price': Decimal('23.09'),
'pubdate': datetime.date(2008, 3, 3),
'publisher_id': 2,
'publisher_id': self.p2.id,
'rating': 3.0,
})
# The order of the (empty) values, annotate and extra clauses doesn't
# matter
obj = Book.objects.values().annotate(mean_auth_age=Avg('authors__age')).extra(
select={'manufacture_cost': 'price * .5'}).get(pk=self.b2.pk)
manufacture_cost = obj['manufacture_cost']
self.assertIn(manufacture_cost, (11.545, Decimal('11.545')))
del obj['manufacture_cost']
self.assertEqual(obj, {
'id': self.b2.id,
'contact_id': self.a3.id,
'isbn': '067232959',
'mean_auth_age': 45.0,
'name': 'Sams Teach Yourself Django in 24 Hours',
'pages': 528,
'price': Decimal('23.09'),
'pubdate': datetime.date(2008, 3, 3),
'publisher_id': self.p2.id,
'rating': 3.0
})
# If the annotation precedes the values clause, it won't be included
# unless it is explicitly named
obj = Book.objects.annotate(mean_auth_age=Avg('authors__age')).extra(select={'price_per_page': 'price / pages'}).values('name').get(pk=1)
obj = Book.objects.annotate(mean_auth_age=Avg('authors__age')).extra(
select={'price_per_page': 'price / pages'}).values('name').get(pk=self.b1.pk)
self.assertEqual(obj, {
"name": 'The Definitive Guide to Django: Web Development Done Right',
})
obj = Book.objects.annotate(mean_auth_age=Avg('authors__age')).extra(select={'price_per_page': 'price / pages'}).values('name', 'mean_auth_age').get(pk=1)
obj = Book.objects.annotate(mean_auth_age=Avg('authors__age')).extra(
select={'price_per_page': 'price / pages'}).values('name', 'mean_auth_age').get(pk=self.b1.pk)
self.assertEqual(obj, {
'mean_auth_age': 34.5,
'name': 'The Definitive Guide to Django: Web Development Done Right',
@ -216,7 +301,8 @@ class AggregationTests(TestCase):
# The annotations are added to values output if values() precedes
# annotate()
obj = Book.objects.values('name').annotate(mean_auth_age=Avg('authors__age')).extra(select={'price_per_page': 'price / pages'}).get(pk=1)
obj = Book.objects.values('name').annotate(mean_auth_age=Avg('authors__age')).extra(
select={'price_per_page': 'price / pages'}).get(pk=self.b1.pk)
self.assertEqual(obj, {
'mean_auth_age': 34.5,
'name': 'The Definitive Guide to Django: Web Development Done Right',
@ -307,17 +393,18 @@ class AggregationTests(TestCase):
)
# Regression for #10064: select_related() plays nice with aggregates
obj = Book.objects.select_related('publisher').annotate(num_authors=Count('authors')).values()[0]
obj = Book.objects.select_related('publisher').annotate(
num_authors=Count('authors')).values().get(isbn='013790395')
self.assertEqual(obj, {
'contact_id': 8,
'id': 5,
'contact_id': self.a8.id,
'id': self.b5.id,
'isbn': '013790395',
'name': 'Artificial Intelligence: A Modern Approach',
'num_authors': 2,
'pages': 1132,
'price': Decimal("82.8"),
'pubdate': datetime.date(1995, 1, 15),
'publisher_id': 3,
'publisher_id': self.p3.id,
'rating': 4.0,
})
@ -420,10 +507,10 @@ class AggregationTests(TestCase):
{'max_authors': None, 'max_rating': None, 'num_authors': 0, 'avg_authors': None, 'max_price': None}
)
qs = Publisher.objects.filter(pk=5).annotate(num_authors=Count('book__authors'), avg_authors=Avg('book__authors'), max_authors=Max('book__authors'), max_price=Max('book__price'), max_rating=Max('book__rating')).values()
qs = Publisher.objects.filter(name="Jonno's House of Books").annotate(num_authors=Count('book__authors'), avg_authors=Avg('book__authors'), max_authors=Max('book__authors'), max_price=Max('book__price'), max_rating=Max('book__rating')).values()
self.assertQuerysetEqual(
qs, [
{'max_authors': None, 'name': "Jonno's House of Books", 'num_awards': 0, 'max_price': None, 'num_authors': 0, 'max_rating': None, 'id': 5, 'avg_authors': None}
{'max_authors': None, 'name': "Jonno's House of Books", 'num_awards': 0, 'max_price': None, 'num_authors': 0, 'max_rating': None, 'id': self.p5.id, 'avg_authors': None}
],
lambda p: p
)
@ -461,10 +548,10 @@ class AggregationTests(TestCase):
qs = Book.objects.extra(select={'pub': 'publisher_id'}).values('pub').annotate(Count('id')).order_by('pub')
self.assertQuerysetEqual(
qs, [
{'pub': 1, 'id__count': 2},
{'pub': 2, 'id__count': 1},
{'pub': 3, 'id__count': 2},
{'pub': 4, 'id__count': 1}
{'pub': self.b1.id, 'id__count': 2},
{'pub': self.b2.id, 'id__count': 1},
{'pub': self.b3.id, 'id__count': 2},
{'pub': self.b4.id, 'id__count': 1}
],
lambda b: b
)
@ -472,10 +559,10 @@ class AggregationTests(TestCase):
qs = Book.objects.extra(select={'pub': 'publisher_id', 'foo': 'pages'}).values('pub').annotate(Count('id')).order_by('pub')
self.assertQuerysetEqual(
qs, [
{'pub': 1, 'id__count': 2},
{'pub': 2, 'id__count': 1},
{'pub': 3, 'id__count': 2},
{'pub': 4, 'id__count': 1}
{'pub': self.p1.id, 'id__count': 2},
{'pub': self.p2.id, 'id__count': 1},
{'pub': self.p3.id, 'id__count': 2},
{'pub': self.p4.id, 'id__count': 1}
],
lambda b: b
)
@ -796,12 +883,15 @@ class AggregationTests(TestCase):
rating_sum=Sum("book__rating"),
book_count=Count("book")
).filter(
Q(pk__lt=F("book_count")) | Q(rating_sum=None)
).order_by("pk")
Q(rating_sum__gt=F("book_count")) | Q(rating_sum=None)
).order_by("num_awards")
self.assertQuerysetEqual(
qs, [
"Apress",
"Jonno's House of Books",
"Sams",
"Apress",
"Prentice Hall",
"Morgan Kaufmann"
],
attrgetter("name")
)
@ -1129,6 +1219,19 @@ class AggregationTests(TestCase):
'select__avg': Approximate(1.666, places=2),
})
def test_annotate_on_relation(self):
book = Book.objects.annotate(avg_price=Avg('price'), publisher_name=F('publisher__name')).get(pk=self.b1.pk)
self.assertEqual(book.avg_price, 30.00)
self.assertEqual(book.publisher_name, "Apress")
def test_aggregate_on_relation(self):
# A query with an existing annotation aggregation on a relation should
# succeed.
qs = Book.objects.annotate(avg_price=Avg('price')).aggregate(
publisher_awards=Sum('publisher__num_awards')
)
self.assertEqual(qs['publisher_awards'], 30)
class JoinPromotionTests(TestCase):
def test_ticket_21150(self):
@ -1162,30 +1265,3 @@ class JoinPromotionTests(TestCase):
def test_non_nullable_fk_not_promoted(self):
qs = Book.objects.annotate(Count('contact__name'))
self.assertIn(' INNER JOIN ', str(qs.query))
class AggregationOnRelationTest(TestCase):
def setUp(self):
self.a = Author.objects.create(name='Anssi', age=33)
self.p = Publisher.objects.create(name='Manning', num_awards=3)
Book.objects.create(isbn='asdf', name='Foo', pages=10, rating=0.1, price="0.0",
contact=self.a, publisher=self.p, pubdate=datetime.date.today())
def test_annotate_on_relation(self):
qs = Book.objects.annotate(avg_price=Avg('price'), publisher_name=F('publisher__name'))
self.assertEqual(qs[0].avg_price, 0.0)
self.assertEqual(qs[0].publisher_name, "Manning")
def test_aggregate_on_relation(self):
# A query with an existing annotation aggregation on a relation should
# succeed.
qs = Book.objects.annotate(avg_price=Avg('price')).aggregate(
publisher_awards=Sum('publisher__num_awards')
)
self.assertEqual(qs['publisher_awards'], 3)
Book.objects.create(isbn='asdf', name='Foo', pages=10, rating=0.1, price="0.0",
contact=self.a, publisher=self.p, pubdate=datetime.date.today())
qs = Book.objects.annotate(avg_price=Avg('price')).aggregate(
publisher_awards=Sum('publisher__num_awards')
)
self.assertEqual(qs['publisher_awards'], 6)

View File

@ -1,243 +0,0 @@
[
{
"pk": 1,
"model": "annotations.publisher",
"fields": {
"name": "Apress",
"num_awards": 3
}
},
{
"pk": 2,
"model": "annotations.publisher",
"fields": {
"name": "Sams",
"num_awards": 1
}
},
{
"pk": 3,
"model": "annotations.publisher",
"fields": {
"name": "Prentice Hall",
"num_awards": 7
}
},
{
"pk": 4,
"model": "annotations.publisher",
"fields": {
"name": "Morgan Kaufmann",
"num_awards": 9
}
},
{
"pk": 5,
"model": "annotations.publisher",
"fields": {
"name": "Jonno's House of Books",
"num_awards": 0
}
},
{
"pk": 1,
"model": "annotations.book",
"fields": {
"publisher": 1,
"isbn": "159059725",
"name": "The Definitive Guide to Django: Web Development Done Right",
"price": "30.00",
"rating": 4.5,
"authors": [1, 2],
"contact": 1,
"pages": 447,
"pubdate": "2007-12-6"
}
},
{
"pk": 2,
"model": "annotations.book",
"fields": {
"publisher": 2,
"isbn": "067232959",
"name": "Sams Teach Yourself Django in 24 Hours",
"price": "23.09",
"rating": 3.0,
"authors": [3],
"contact": 3,
"pages": 528,
"pubdate": "2008-3-3"
}
},
{
"pk": 3,
"model": "annotations.book",
"fields": {
"publisher": 1,
"isbn": "159059996",
"name": "Practical Django Projects",
"price": "29.69",
"rating": 4.0,
"authors": [4],
"contact": 4,
"pages": 300,
"pubdate": "2008-6-23"
}
},
{
"pk": 4,
"model": "annotations.book",
"fields": {
"publisher": 3,
"isbn": "013235613",
"name": "Python Web Development with Django",
"price": "29.69",
"rating": 4.0,
"authors": [5, 6, 7],
"contact": 5,
"pages": 350,
"pubdate": "2008-11-3"
}
},
{
"pk": 5,
"model": "annotations.book",
"fields": {
"publisher": 3,
"isbn": "013790395",
"name": "Artificial Intelligence: A Modern Approach",
"price": "82.80",
"rating": 4.0,
"authors": [8, 9],
"contact": 8,
"pages": 1132,
"pubdate": "1995-1-15"
}
},
{
"pk": 6,
"model": "annotations.book",
"fields": {
"publisher": 4,
"isbn": "155860191",
"name": "Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp",
"price": "75.00",
"rating": 5.0,
"authors": [8],
"contact": 8,
"pages": 946,
"pubdate": "1991-10-15"
}
},
{
"pk": 1,
"model": "annotations.store",
"fields": {
"books": [1, 2, 3, 4, 5, 6],
"name": "Amazon.com",
"original_opening": "1994-4-23 9:17:42",
"friday_night_closing": "23:59:59"
}
},
{
"pk": 2,
"model": "annotations.store",
"fields": {
"books": [1, 3, 5, 6],
"name": "Books.com",
"original_opening": "2001-3-15 11:23:37",
"friday_night_closing": "23:59:59"
}
},
{
"pk": 3,
"model": "annotations.store",
"fields": {
"books": [3, 4, 6],
"name": "Mamma and Pappa's Books",
"original_opening": "1945-4-25 16:24:14",
"friday_night_closing": "21:30:00"
}
},
{
"pk": 1,
"model": "annotations.author",
"fields": {
"age": 34,
"friends": [2, 4],
"name": "Adrian Holovaty"
}
},
{
"pk": 2,
"model": "annotations.author",
"fields": {
"age": 35,
"friends": [1, 7],
"name": "Jacob Kaplan-Moss"
}
},
{
"pk": 3,
"model": "annotations.author",
"fields": {
"age": 45,
"friends": [],
"name": "Brad Dayley"
}
},
{
"pk": 4,
"model": "annotations.author",
"fields": {
"age": 29,
"friends": [1],
"name": "James Bennett"
}
},
{
"pk": 5,
"model": "annotations.author",
"fields": {
"age": 37,
"friends": [6, 7],
"name": "Jeffrey Forcier"
}
},
{
"pk": 6,
"model": "annotations.author",
"fields": {
"age": 29,
"friends": [5, 7],
"name": "Paul Bissex"
}
},
{
"pk": 7,
"model": "annotations.author",
"fields": {
"age": 25,
"friends": [2, 5, 6],
"name": "Wesley J. Chun"
}
},
{
"pk": 8,
"model": "annotations.author",
"fields": {
"age": 57,
"friends": [9],
"name": "Peter Norvig"
}
},
{
"pk": 9,
"model": "annotations.author",
"fields": {
"age": 46,
"friends": [8],
"name": "Stuart Russell"
}
}
]

View File

@ -10,7 +10,9 @@ from django.db.models import (
from django.test import TestCase
from django.utils import six
from .models import Author, Book, Company, DepartmentStore, Employee, Store
from .models import (
Author, Book, Company, DepartmentStore, Employee, Publisher, Store,
)
def cxOracle_513_py3_bug(func):
@ -33,7 +35,88 @@ def cxOracle_513_py3_bug(func):
class NonAggregateAnnotationTestCase(TestCase):
fixtures = ["annotations.json"]
@classmethod
def setUpTestData(cls):
cls.a1 = Author.objects.create(name='Adrian Holovaty', age=34)
cls.a2 = Author.objects.create(name='Jacob Kaplan-Moss', age=35)
cls.a3 = Author.objects.create(name='Brad Dayley', age=45)
cls.a4 = Author.objects.create(name='James Bennett', age=29)
cls.a5 = Author.objects.create(name='Jeffrey Forcier', age=37)
cls.a6 = Author.objects.create(name='Paul Bissex', age=29)
cls.a7 = Author.objects.create(name='Wesley J. Chun', age=25)
cls.a8 = Author.objects.create(name='Peter Norvig', age=57)
cls.a9 = Author.objects.create(name='Stuart Russell', age=46)
cls.a1.friends.add(cls.a2, cls.a4)
cls.a2.friends.add(cls.a1, cls.a7)
cls.a4.friends.add(cls.a1)
cls.a5.friends.add(cls.a6, cls.a7)
cls.a6.friends.add(cls.a5, cls.a7)
cls.a7.friends.add(cls.a2, cls.a5, cls.a6)
cls.a8.friends.add(cls.a9)
cls.a9.friends.add(cls.a8)
cls.p1 = Publisher.objects.create(name='Apress', num_awards=3)
cls.p2 = Publisher.objects.create(name='Sams', num_awards=1)
cls.p3 = Publisher.objects.create(name='Prentice Hall', num_awards=7)
cls.p4 = Publisher.objects.create(name='Morgan Kaufmann', num_awards=9)
cls.p5 = Publisher.objects.create(name="Jonno's House of Books", num_awards=0)
cls.b1 = Book.objects.create(
isbn='159059725', name='The Definitive Guide to Django: Web Development Done Right',
pages=447, rating=4.5, price=Decimal('30.00'), contact=cls.a1, publisher=cls.p1,
pubdate=datetime.date(2007, 12, 6)
)
cls.b2 = Book.objects.create(
isbn='067232959', name='Sams Teach Yourself Django in 24 Hours',
pages=528, rating=3.0, price=Decimal('23.09'), contact=cls.a3, publisher=cls.p2,
pubdate=datetime.date(2008, 3, 3)
)
cls.b3 = Book.objects.create(
isbn='159059996', name='Practical Django Projects',
pages=300, rating=4.0, price=Decimal('29.69'), contact=cls.a4, publisher=cls.p1,
pubdate=datetime.date(2008, 6, 23)
)
cls.b4 = Book.objects.create(
isbn='013235613', name='Python Web Development with Django',
pages=350, rating=4.0, price=Decimal('29.69'), contact=cls.a5, publisher=cls.p3,
pubdate=datetime.date(2008, 11, 3)
)
cls.b5 = Book.objects.create(
isbn='013790395', name='Artificial Intelligence: A Modern Approach',
pages=1132, rating=4.0, price=Decimal('82.80'), contact=cls.a8, publisher=cls.p3,
pubdate=datetime.date(1995, 1, 15)
)
cls.b6 = Book.objects.create(
isbn='155860191', name='Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp',
pages=946, rating=5.0, price=Decimal('75.00'), contact=cls.a8, publisher=cls.p4,
pubdate=datetime.date(1991, 10, 15)
)
cls.b1.authors.add(cls.a1, cls.a2)
cls.b2.authors.add(cls.a3)
cls.b3.authors.add(cls.a4)
cls.b4.authors.add(cls.a5, cls.a6, cls.a7)
cls.b5.authors.add(cls.a8, cls.a9)
cls.b6.authors.add(cls.a8)
s1 = Store.objects.create(
name='Amazon.com',
original_opening=datetime.datetime(1994, 4, 23, 9, 17, 42),
friday_night_closing=datetime.time(23, 59, 59)
)
s2 = Store.objects.create(
name='Books.com',
original_opening=datetime.datetime(2001, 3, 15, 11, 23, 37),
friday_night_closing=datetime.time(23, 59, 59)
)
s3 = Store.objects.create(
name="Mamma and Pappa's Books",
original_opening=datetime.datetime(1945, 4, 25, 16, 24, 14),
friday_night_closing=datetime.time(21, 30)
)
s1.books.add(cls.b1, cls.b2, cls.b3, cls.b4, cls.b5, cls.b6)
s2.books.add(cls.b1, cls.b3, cls.b5, cls.b6)
s3.books.add(cls.b3, cls.b4, cls.b6)
def test_basic_annotation(self):
books = Book.objects.annotate(
@ -100,13 +183,13 @@ class NonAggregateAnnotationTestCase(TestCase):
).filter(sum_rating=F('nope')))
def test_update_with_annotation(self):
book_preupdate = Book.objects.get(pk=2)
book_preupdate = Book.objects.get(pk=self.b2.pk)
Book.objects.annotate(other_rating=F('rating') - 1).update(rating=F('other_rating'))
book_postupdate = Book.objects.get(pk=2)
book_postupdate = Book.objects.get(pk=self.b2.pk)
self.assertEqual(book_preupdate.rating - 1, book_postupdate.rating)
def test_annotation_with_m2m(self):
books = Book.objects.annotate(author_age=F('authors__age')).filter(pk=1).order_by('author_age')
books = Book.objects.annotate(author_age=F('authors__age')).filter(pk=self.b1.pk).order_by('author_age')
self.assertEqual(books[0].author_age, 34)
self.assertEqual(books[1].author_age, 35)
@ -132,7 +215,7 @@ class NonAggregateAnnotationTestCase(TestCase):
"""
# annotate references a field in values()
qs = Book.objects.values('rating').annotate(other_rating=F('rating') - 1)
book = qs.get(pk=1)
book = qs.get(pk=self.b1.pk)
self.assertEqual(book['rating'] - 1, book['other_rating'])
# filter refs the annotated value

View File

@ -1,110 +0,0 @@
[
{
"pk": "1",
"model": "auth.user",
"fields": {
"username": "testclient",
"first_name": "Test",
"last_name": "Client",
"is_active": true,
"is_superuser": false,
"is_staff": false,
"last_login": "2006-12-17 07:03:31",
"groups": [],
"user_permissions": [],
"password": "sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161",
"email": "testclient@example.com",
"date_joined": "2006-12-17 07:03:31"
}
},
{
"pk": "2",
"model": "auth.user",
"fields": {
"username": "inactive",
"first_name": "Inactive",
"last_name": "User",
"is_active": false,
"is_superuser": false,
"is_staff": false,
"last_login": "2006-12-17 07:03:31",
"groups": [],
"user_permissions": [],
"password": "sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161",
"email": "testclient2@example.com",
"date_joined": "2006-12-17 07:03:31"
}
},
{
"pk": "3",
"model": "auth.user",
"fields": {
"username": "staff",
"first_name": "Staff",
"last_name": "Member",
"is_active": true,
"is_superuser": false,
"is_staff": true,
"last_login": "2006-12-17 07:03:31",
"groups": [],
"user_permissions": [],
"password": "sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161",
"email": "staffmember@example.com",
"date_joined": "2006-12-17 07:03:31"
}
},
{
"pk": "4",
"model": "auth.user",
"fields": {
"username": "empty_password",
"first_name": "Empty",
"last_name": "Password",
"is_active": true,
"is_superuser": false,
"is_staff": false,
"last_login": "2006-12-17 07:03:31",
"groups": [],
"user_permissions": [],
"password": "",
"email": "empty_password@example.com",
"date_joined": "2006-12-17 07:03:31"
}
},
{
"pk": "5",
"model": "auth.user",
"fields": {
"username": "unmanageable_password",
"first_name": "Unmanageable",
"last_name": "Password",
"is_active": true,
"is_superuser": false,
"is_staff": false,
"last_login": "2006-12-17 07:03:31",
"groups": [],
"user_permissions": [],
"password": "$",
"email": "unmanageable_password@example.com",
"date_joined": "2006-12-17 07:03:31"
}
},
{
"pk": "6",
"model": "auth.user",
"fields": {
"username": "unknown_password",
"first_name": "Unknown",
"last_name": "Password",
"is_active": true,
"is_superuser": false,
"is_staff": false,
"last_login": "2006-12-17 07:03:31",
"groups": [],
"user_permissions": [],
"password": "foo$bar",
"email": "unknown_password@example.com",
"date_joined": "2006-12-17 07:03:31"
}
}
]

View File

@ -1,17 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<django-objects version="1.0">
<object pk="100" model="auth.user">
<field type="CharField" name="username">super</field>
<field type="CharField" name="first_name">Super</field>
<field type="CharField" name="last_name">User</field>
<field type="CharField" name="email">super@example.com</field>
<field type="CharField" name="password">sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158</field>
<field type="BooleanField" name="is_staff">True</field>
<field type="BooleanField" name="is_active">True</field>
<field type="BooleanField" name="is_superuser">True</field>
<field type="DateTimeField" name="last_login">2007-05-30 13:20:10</field>
<field type="DateTimeField" name="date_joined">2007-05-30 13:20:10</field>
<field to="auth.group" name="groups" rel="ManyToManyRel"></field>
<field to="auth.permission" name="user_permissions" rel="ManyToManyRel"></field>
</object>
</django-objects>

View File

@ -1,14 +0,0 @@
[
{
"pk": "1",
"model": "auth.customuser",
"fields": {
"password": "sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161",
"last_login": "2006-12-17 07:03:31",
"email": "staffmember@example.com",
"is_active": true,
"is_admin": false,
"date_of_birth": "1976-11-08"
}
}
]

View File

@ -1,3 +1,5 @@
import datetime
from django.contrib.auth import authenticate
from django.contrib.auth.context_processors import PermLookupDict, PermWrapper
from django.contrib.auth.models import Permission, User
@ -67,7 +69,16 @@ class AuthContextProcessorTests(TestCase):
"""
Tests for the ``django.contrib.auth.context_processors.auth`` processor
"""
fixtures = ['context-processors-users.xml']
@classmethod
def setUpTestData(cls):
# password = "secret"
cls.u1 = User.objects.create(
id=100, password='sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158',
last_login=datetime.datetime(2007, 5, 30, 13, 20, 10), is_superuser=True, username='super',
first_name='Super', last_name='User', email='super@example.com',
is_staff=True, is_active=True, date_joined=datetime.datetime(2007, 5, 30, 13, 20, 10)
)
@override_settings(MIDDLEWARE_CLASSES=AUTH_MIDDLEWARE_CLASSES)
def test_session_not_accessed(self):

View File

@ -1,5 +1,6 @@
from __future__ import unicode_literals
import datetime
import re
from django import forms
@ -22,10 +23,49 @@ from django.utils.translation import ugettext as _
from .settings import AUTH_TEMPLATES
@override_settings(USE_TZ=False, PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'])
class UserCreationFormTest(TestCase):
class TestDataMixin(object):
fixtures = ['authtestdata.json']
@classmethod
def setUpTestData(cls):
cls.u1 = User.objects.create(
password='sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161',
last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='testclient',
first_name='Test', last_name='Client', email='testclient@example.com', is_staff=False, is_active=True,
date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
)
cls.u2 = User.objects.create(
password='sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161',
last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='inactive',
first_name='Inactive', last_name='User', email='testclient2@example.com', is_staff=False, is_active=False,
date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
)
cls.u3 = User.objects.create(
password='sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161',
last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='staff',
first_name='Staff', last_name='Member', email='staffmember@example.com', is_staff=True, is_active=True,
date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
)
cls.u4 = User.objects.create(
password='', last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False,
username='empty_password', first_name='Empty', last_name='Password', email='empty_password@example.com',
is_staff=False, is_active=True, date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
)
cls.u5 = User.objects.create(
password='$', last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False,
username='unmanageable_password', first_name='Unmanageable', last_name='Password',
email='unmanageable_password@example.com', is_staff=False, is_active=True,
date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
)
cls.u6 = User.objects.create(
password='foo$bar', last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False,
username='unknown_password', first_name='Unknown', last_name='Password',
email='unknown_password@example.com', is_staff=False, is_active=True,
date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
)
@override_settings(USE_TZ=False, PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'])
class UserCreationFormTest(TestDataMixin, TestCase):
def test_user_already_exists(self):
data = {
@ -90,9 +130,7 @@ class UserCreationFormTest(TestCase):
@override_settings(USE_TZ=False, PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'])
class AuthenticationFormTest(TestCase):
fixtures = ['authtestdata.json']
class AuthenticationFormTest(TestDataMixin, TestCase):
def test_invalid_username(self):
# The user submits an invalid username.
@ -202,9 +240,7 @@ class AuthenticationFormTest(TestCase):
@override_settings(USE_TZ=False, PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'])
class SetPasswordFormTest(TestCase):
fixtures = ['authtestdata.json']
class SetPasswordFormTest(TestDataMixin, TestCase):
def test_password_verification(self):
# The two new passwords do not match.
@ -229,9 +265,7 @@ class SetPasswordFormTest(TestCase):
@override_settings(USE_TZ=False, PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'])
class PasswordChangeFormTest(TestCase):
fixtures = ['authtestdata.json']
class PasswordChangeFormTest(TestDataMixin, TestCase):
def test_incorrect_password(self):
user = User.objects.get(username='testclient')
@ -277,9 +311,7 @@ class PasswordChangeFormTest(TestCase):
@override_settings(USE_TZ=False, PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'])
class UserChangeFormTest(TestCase):
fixtures = ['authtestdata.json']
class UserChangeFormTest(TestDataMixin, TestCase):
def test_username_validity(self):
user = User.objects.get(username='testclient')
@ -359,9 +391,7 @@ class UserChangeFormTest(TestCase):
TEMPLATES=AUTH_TEMPLATES,
USE_TZ=False,
)
class PasswordResetFormTest(TestCase):
fixtures = ['authtestdata.json']
class PasswordResetFormTest(TestDataMixin, TestCase):
@classmethod
def setUpClass(cls):

View File

@ -1,3 +1,5 @@
import datetime
from django.contrib.auth import get_user_model
from django.contrib.auth.models import (
AbstractUser, Group, Permission, User, UserManager,
@ -10,7 +12,44 @@ from django.test import TestCase, override_settings
@override_settings(USE_TZ=False)
class NaturalKeysTestCase(TestCase):
fixtures = ['authtestdata.json']
@classmethod
def setUpTestData(cls):
cls.u1 = User.objects.create(
password='sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161',
last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='testclient',
first_name='Test', last_name='Client', email='testclient@example.com', is_staff=False, is_active=True,
date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
)
cls.u2 = User.objects.create(
password='sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161',
last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='inactive',
first_name='Inactive', last_name='User', email='testclient2@example.com', is_staff=False, is_active=False,
date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
)
cls.u3 = User.objects.create(
password='sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161',
last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='staff',
first_name='Staff', last_name='Member', email='staffmember@example.com', is_staff=True, is_active=True,
date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
)
cls.u4 = User.objects.create(
password='', last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False,
username='empty_password', first_name='Empty', last_name='Password', email='empty_password@example.com',
is_staff=False, is_active=True, date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
)
cls.u5 = User.objects.create(
password='$', last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False,
username='unmanageable_password', first_name='Unmanageable', last_name='Password',
email='unmanageable_password@example.com', is_staff=False, is_active=True,
date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
)
cls.u6 = User.objects.create(
password='foo$bar', last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False,
username='unknown_password', first_name='Unknown', last_name='Password',
email='unknown_password@example.com', is_staff=False, is_active=True,
date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
)
def test_user_natural_key(self):
staff_user = User.objects.get(username='staff')

View File

@ -1,3 +1,5 @@
import datetime
from django.contrib.auth import signals
from django.contrib.auth.models import User
from django.test import TestCase, override_settings
@ -8,7 +10,21 @@ from django.test.client import RequestFactory
PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='auth_tests.urls')
class SignalTestCase(TestCase):
fixtures = ['authtestdata.json']
@classmethod
def setUpTestData(cls):
cls.u1 = User.objects.create(
password='sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161',
last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='testclient',
first_name='Test', last_name='Client', email='testclient@example.com', is_staff=False, is_active=True,
date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
)
cls.u3 = User.objects.create(
password='sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161',
last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='staff',
first_name='Staff', last_name='Member', email='staffmember@example.com', is_staff=True, is_active=True,
date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
)
def listener_login(self, user, **kwargs):
self.logged_in.append(user)
@ -66,13 +82,13 @@ class SignalTestCase(TestCase):
def test_update_last_login(self):
"""Ensure that only `last_login` is updated in `update_last_login`"""
user = User.objects.get(pk=3)
user = self.u3
old_last_login = user.last_login
user.username = "This username shouldn't get saved"
request = RequestFactory().get('/login')
signals.user_logged_in.send(sender=user.__class__, request=request,
user=user)
user = User.objects.get(pk=3)
user = User.objects.get(pk=self.u3.pk)
self.assertEqual(user.username, 'staff')
self.assertNotEqual(user.last_login, old_last_login)

View File

@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
import itertools
import re
from importlib import import_module
@ -13,6 +14,7 @@ from django.contrib.auth.forms import (
AuthenticationForm, PasswordChangeForm, SetPasswordForm,
)
from django.contrib.auth.models import User
from django.contrib.auth.tests.custom_user import CustomUser
from django.contrib.auth.views import login as login_view, redirect_to_login
from django.contrib.sessions.middleware import SessionMiddleware
from django.contrib.sites.requests import RequestSite
@ -49,7 +51,44 @@ class AuthViewsTestCase(TestCase):
"""
Helper base class for all the follow test cases.
"""
fixtures = ['authtestdata.json']
@classmethod
def setUpTestData(cls):
cls.u1 = User.objects.create(
password='sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161',
last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='testclient',
first_name='Test', last_name='Client', email='testclient@example.com', is_staff=False, is_active=True,
date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
)
cls.u2 = User.objects.create(
password='sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161',
last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='inactive',
first_name='Inactive', last_name='User', email='testclient2@example.com', is_staff=False, is_active=False,
date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
)
cls.u3 = User.objects.create(
password='sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161',
last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='staff',
first_name='Staff', last_name='Member', email='staffmember@example.com', is_staff=True, is_active=True,
date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
)
cls.u4 = User.objects.create(
password='', last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False,
username='empty_password', first_name='Empty', last_name='Password', email='empty_password@example.com',
is_staff=False, is_active=True, date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
)
cls.u5 = User.objects.create(
password='$', last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False,
username='unmanageable_password', first_name='Unmanageable', last_name='Password',
email='unmanageable_password@example.com', is_staff=False, is_active=True,
date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
)
cls.u6 = User.objects.create(
password='foo$bar', last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False,
username='unknown_password', first_name='Unknown', last_name='Password',
email='unknown_password@example.com', is_staff=False, is_active=True,
date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
)
def login(self, username='testclient', password='password'):
response = self.client.post('/login/', {
@ -333,9 +372,16 @@ class PasswordResetTest(AuthViewsTestCase):
@override_settings(AUTH_USER_MODEL='auth.CustomUser')
class CustomUserPasswordResetTest(AuthViewsTestCase):
fixtures = ['custom_user.json']
user_email = 'staffmember@example.com'
@classmethod
def setUpTestData(cls):
cls.u1 = CustomUser.custom_objects.create(
password='sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161',
last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), email='staffmember@example.com', is_active=True,
is_admin=False, date_of_birth=datetime.date(1976, 11, 8)
)
def _test_confirm_start(self):
# Start by creating the email
response = self.client.post('/password_reset/', {'email': self.user_email})
@ -363,7 +409,6 @@ class CustomUserPasswordResetTest(AuthViewsTestCase):
@override_settings(AUTH_USER_MODEL='auth.UUIDUser')
class UUIDUserPasswordResetTest(CustomUserPasswordResetTest):
fixtures = None
def _test_confirm_start(self):
# instead of fixture
@ -846,7 +891,7 @@ class ChangelistTests(AuthViewsTestCase):
# Make me a superuser before logging in.
User.objects.filter(username='testclient').update(is_staff=True, is_superuser=True)
self.login()
self.admin = User.objects.get(pk=1)
self.admin = User.objects.get(pk=self.u1.pk)
def get_user_data(self, user):
return {

View File

@ -1,68 +0,0 @@
[
{
"pk": 1,
"model": "contenttypes_tests.author",
"fields": {
"name": "Boris"
}
},
{
"pk": 1,
"model": "contenttypes_tests.article",
"fields": {
"author": 1,
"title": "Old Article",
"slug": "old_article",
"date_created": "2001-01-01 21:22:23"
}
},
{
"pk": 2,
"model": "contenttypes_tests.article",
"fields": {
"author": 1,
"title": "Current Article",
"slug": "current_article",
"date_created": "2007-09-17 21:22:23"
}
},
{
"pk": 3,
"model": "contenttypes_tests.article",
"fields": {
"author": 1,
"title": "Future Article",
"slug": "future_article",
"date_created": "3000-01-01 21:22:23"
}
},
{
"pk": 1,
"model": "contenttypes_tests.schemeincludedurl",
"fields": {
"url": "http://test_scheme_included_http/"
}
},
{
"pk": 2,
"model": "contenttypes_tests.schemeincludedurl",
"fields": {
"url": "https://test_scheme_included_https/"
}
},
{
"pk": 3,
"model": "contenttypes_tests.schemeincludedurl",
"fields": {
"url": "//test_default_scheme_kept/"
}
},
{
"pk": 1,
"model": "sites.site",
"fields": {
"domain": "testserver",
"name": "testserver"
}
}
]

View File

@ -1,12 +1,15 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
from django.apps.registry import Apps, apps
from django.contrib.contenttypes import management
from django.contrib.contenttypes.fields import (
GenericForeignKey, GenericRelation,
)
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django.core import checks
from django.db import connections, models
from django.test import TestCase, override_settings
@ -18,7 +21,29 @@ from .models import Article, Author, SchemeIncludedURL
@override_settings(ROOT_URLCONF='contenttypes_tests.urls')
class ContentTypesViewsTests(TestCase):
fixtures = ['testdata.json']
@classmethod
def setUpTestData(cls):
# don't use the manager because we want to ensure the site exists
# with pk=1, regardless of whether or not it already exists.
cls.site1 = Site(pk=1, domain='testserver', name='testserver')
cls.site1.save()
cls.author1 = Author.objects.create(name='Boris')
cls.article1 = Article.objects.create(
title='Old Article', slug='old_article', author=cls.author1,
date_created=datetime.datetime(2001, 1, 1, 21, 22, 23)
)
cls.article2 = Article.objects.create(
title='Current Article', slug='current_article', author=cls.author1,
date_created=datetime.datetime(2007, 9, 17, 21, 22, 23)
)
cls.article3 = Article.objects.create(
title='Future Article', slug='future_article', author=cls.author1,
date_created=datetime.datetime(3000, 1, 1, 21, 22, 23)
)
cls.scheme1 = SchemeIncludedURL.objects.create(url='http://test_scheme_included_http/')
cls.scheme2 = SchemeIncludedURL.objects.create(url='https://test_scheme_included_https/')
cls.scheme3 = SchemeIncludedURL.objects.create(url='//test_default_scheme_kept/')
def test_shortcut_with_absolute_url(self):
"Can view a shortcut for an Author object that has a get_absolute_url method"
@ -31,8 +56,7 @@ class ContentTypesViewsTests(TestCase):
def test_shortcut_with_absolute_url_including_scheme(self):
"""
Can view a shortcut when object's get_absolute_url returns a full URL
the tested URLs are in fixtures/testdata.json :
"http://...", "https://..." and "//..."
the tested URLs are: "http://...", "https://..." and "//..."
"""
for obj in SchemeIncludedURL.objects.all():
short_url = '/shortcut/%s/%s/' % (ContentType.objects.get_for_model(SchemeIncludedURL).id, obj.pk)

View File

@ -1,11 +0,0 @@
[
{
"pk": 1,
"model": "sites.site",
"fields": {
"domain": "example.com",
"name": "example.com"
}
}
]

View File

@ -1,63 +0,0 @@
[
{
"pk": 1,
"model": "flatpages.flatpage",
"fields": {
"registration_required": false,
"title": "A Flatpage",
"url": "/flatpage/",
"template_name": "",
"sites": [
1
],
"content": "Isn't it flat!",
"enable_comments": false
}
},
{
"pk": 2,
"model": "flatpages.flatpage",
"fields": {
"registration_required": false,
"title": "A Nested Flatpage",
"url": "/location/flatpage/",
"template_name": "",
"sites": [
1
],
"content": "Isn't it flat and deep!",
"enable_comments": false
}
},
{
"pk": 101,
"model": "flatpages.flatpage",
"fields": {
"registration_required": true,
"title": "Sekrit Flatpage",
"url": "/sekrit/",
"template_name": "",
"sites": [
1
],
"content": "Isn't it sekrit!",
"enable_comments": false
}
},
{
"pk": 102,
"model": "flatpages.flatpage",
"fields": {
"registration_required": true,
"title": "Sekrit Nested Flatpage",
"url": "/location/sekrit/",
"template_name": "",
"sites": [
1
],
"content": "Isn't it sekrit and deep!",
"enable_comments": false
}
}
]

View File

@ -1,4 +1,6 @@
from django.contrib.auth.models import User
from django.contrib.flatpages.models import FlatPage
from django.contrib.sites.models import Site
from django.test import Client, TestCase, modify_settings, override_settings
from .settings import FLATPAGES_TEMPLATES
@ -21,7 +23,33 @@ from .settings import FLATPAGES_TEMPLATES
SITE_ID=1,
)
class FlatpageCSRFTests(TestCase):
fixtures = ['sample_flatpages', 'example_site']
@classmethod
def setUpTestData(cls):
# don't use the manager because we want to ensure the site exists
# with pk=1, regardless of whether or not it already exists.
cls.site1 = Site(pk=1, domain='example.com', name='example.com')
cls.site1.save()
cls.fp1 = FlatPage.objects.create(
url='/flatpage/', title='A Flatpage', content="Isn't it flat!",
enable_comments=False, template_name='', registration_required=False
)
cls.fp2 = FlatPage.objects.create(
url='/location/flatpage/', title='A Nested Flatpage', content="Isn't it flat and deep!",
enable_comments=False, template_name='', registration_required=False
)
cls.fp3 = FlatPage.objects.create(
url='/sekrit/', title='Sekrit Flatpage', content="Isn't it sekrit!",
enable_comments=False, template_name='', registration_required=True
)
cls.fp4 = FlatPage.objects.create(
url='/location/sekrit/', title='Sekrit Nested Flatpage', content="Isn't it sekrit and deep!",
enable_comments=False, template_name='', registration_required=True
)
cls.fp1.sites.add(cls.site1)
cls.fp2.sites.add(cls.site1)
cls.fp3.sites.add(cls.site1)
cls.fp4.sites.add(cls.site1)
def setUp(self):
self.client = Client(enforce_csrf_checks=True)

View File

@ -11,7 +11,13 @@ from django.utils import translation
@modify_settings(INSTALLED_APPS={'append': ['django.contrib.flatpages', ]})
@override_settings(SITE_ID=1)
class FlatpageAdminFormTests(TestCase):
fixtures = ['example_site']
@classmethod
def setUpTestData(cls):
# don't use the manager because we want to ensure the site exists
# with pk=1, regardless of whether or not it already exists.
cls.site1 = Site(pk=1, domain='example.com', name='example.com')
cls.site1.save()
def setUp(self):
# Site fields cache needs to be cleared after flatpages is added to

View File

@ -1,11 +1,42 @@
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.flatpages.models import FlatPage
from django.contrib.sites.models import Site
from django.test import TestCase, modify_settings, override_settings
from .settings import FLATPAGES_TEMPLATES
class TestDataMixin(object):
@classmethod
def setUpTestData(cls):
# don't use the manager because we want to ensure the site exists
# with pk=1, regardless of whether or not it already exists.
cls.site1 = Site(pk=1, domain='example.com', name='example.com')
cls.site1.save()
cls.fp1 = FlatPage.objects.create(
url='/flatpage/', title='A Flatpage', content="Isn't it flat!",
enable_comments=False, template_name='', registration_required=False
)
cls.fp2 = FlatPage.objects.create(
url='/location/flatpage/', title='A Nested Flatpage', content="Isn't it flat and deep!",
enable_comments=False, template_name='', registration_required=False
)
cls.fp3 = FlatPage.objects.create(
url='/sekrit/', title='Sekrit Flatpage', content="Isn't it sekrit!",
enable_comments=False, template_name='', registration_required=True
)
cls.fp4 = FlatPage.objects.create(
url='/location/sekrit/', title='Sekrit Nested Flatpage', content="Isn't it sekrit and deep!",
enable_comments=False, template_name='', registration_required=True
)
cls.fp1.sites.add(cls.site1)
cls.fp2.sites.add(cls.site1)
cls.fp3.sites.add(cls.site1)
cls.fp4.sites.add(cls.site1)
@modify_settings(INSTALLED_APPS={'append': 'django.contrib.flatpages'})
@override_settings(
LOGIN_URL='/accounts/login/',
@ -21,8 +52,7 @@ from .settings import FLATPAGES_TEMPLATES
TEMPLATES=FLATPAGES_TEMPLATES,
SITE_ID=1,
)
class FlatpageMiddlewareTests(TestCase):
fixtures = ['sample_flatpages', 'example_site']
class FlatpageMiddlewareTests(TestDataMixin, TestCase):
def test_view_flatpage(self):
"A flatpage can be served through a view, even when the middleware is in use"
@ -98,8 +128,7 @@ class FlatpageMiddlewareTests(TestCase):
TEMPLATES=FLATPAGES_TEMPLATES,
SITE_ID=1,
)
class FlatpageMiddlewareAppendSlashTests(TestCase):
fixtures = ['sample_flatpages', 'example_site']
class FlatpageMiddlewareAppendSlashTests(TestDataMixin, TestCase):
def test_redirect_view_flatpage(self):
"A flatpage can be served through a view and should add a slash"

View File

@ -1,4 +1,6 @@
from django.contrib.auth.models import AnonymousUser, User
from django.contrib.flatpages.models import FlatPage
from django.contrib.sites.models import Site
from django.template import Context, Template, TemplateSyntaxError
from django.test import TestCase, modify_settings, override_settings
@ -20,7 +22,33 @@ from .settings import FLATPAGES_TEMPLATES
SITE_ID=1,
)
class FlatpageTemplateTagTests(TestCase):
fixtures = ['sample_flatpages']
@classmethod
def setUpTestData(cls):
# don't use the manager because we want to ensure the site exists
# with pk=1, regardless of whether or not it already exists.
cls.site1 = Site(pk=1, domain='example.com', name='example.com')
cls.site1.save()
cls.fp1 = FlatPage.objects.create(
url='/flatpage/', title='A Flatpage', content="Isn't it flat!",
enable_comments=False, template_name='', registration_required=False
)
cls.fp2 = FlatPage.objects.create(
url='/location/flatpage/', title='A Nested Flatpage', content="Isn't it flat and deep!",
enable_comments=False, template_name='', registration_required=False
)
cls.fp3 = FlatPage.objects.create(
url='/sekrit/', title='Sekrit Flatpage', content="Isn't it sekrit!",
enable_comments=False, template_name='', registration_required=True
)
cls.fp4 = FlatPage.objects.create(
url='/location/sekrit/', title='Sekrit Nested Flatpage', content="Isn't it sekrit and deep!",
enable_comments=False, template_name='', registration_required=True
)
cls.fp1.sites.add(cls.site1)
cls.fp2.sites.add(cls.site1)
cls.fp3.sites.add(cls.site1)
cls.fp4.sites.add(cls.site1)
def test_get_flatpages_tag(self):
"The flatpage template tag retrieves unregistered prefixed flatpages by default"

View File

@ -1,11 +1,42 @@
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.flatpages.models import FlatPage
from django.contrib.sites.models import Site
from django.test import TestCase, modify_settings, override_settings
from .settings import FLATPAGES_TEMPLATES
class TestDataMixin(object):
@classmethod
def setUpTestData(cls):
# don't use the manager because we want to ensure the site exists
# with pk=1, regardless of whether or not it already exists.
cls.site1 = Site(pk=1, domain='example.com', name='example.com')
cls.site1.save()
cls.fp1 = FlatPage.objects.create(
url='/flatpage/', title='A Flatpage', content="Isn't it flat!",
enable_comments=False, template_name='', registration_required=False
)
cls.fp2 = FlatPage.objects.create(
url='/location/flatpage/', title='A Nested Flatpage', content="Isn't it flat and deep!",
enable_comments=False, template_name='', registration_required=False
)
cls.fp3 = FlatPage.objects.create(
url='/sekrit/', title='Sekrit Flatpage', content="Isn't it sekrit!",
enable_comments=False, template_name='', registration_required=True
)
cls.fp4 = FlatPage.objects.create(
url='/location/sekrit/', title='Sekrit Nested Flatpage', content="Isn't it sekrit and deep!",
enable_comments=False, template_name='', registration_required=True
)
cls.fp1.sites.add(cls.site1)
cls.fp2.sites.add(cls.site1)
cls.fp3.sites.add(cls.site1)
cls.fp4.sites.add(cls.site1)
@modify_settings(INSTALLED_APPS={'append': 'django.contrib.flatpages'})
@override_settings(
LOGIN_URL='/accounts/login/',
@ -21,8 +52,7 @@ from .settings import FLATPAGES_TEMPLATES
TEMPLATES=FLATPAGES_TEMPLATES,
SITE_ID=1,
)
class FlatpageViewTests(TestCase):
fixtures = ['sample_flatpages', 'example_site']
class FlatpageViewTests(TestDataMixin, TestCase):
def test_view_flatpage(self):
"A flatpage can be served through a view"
@ -87,8 +117,7 @@ class FlatpageViewTests(TestCase):
TEMPLATES=FLATPAGES_TEMPLATES,
SITE_ID=1,
)
class FlatpageViewAppendSlashTests(TestCase):
fixtures = ['sample_flatpages', 'example_site']
class FlatpageViewAppendSlashTests(TestDataMixin, TestCase):
def test_redirect_view_flatpage(self):
"A flatpage can be served through a view and should add a slash"

View File

@ -1,17 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<django-objects version="1.0">
<object pk="100" model="auth.user">
<field type="CharField" name="username">super</field>
<field type="CharField" name="first_name">Super</field>
<field type="CharField" name="last_name">User</field>
<field type="CharField" name="email">super@example.com</field>
<field type="CharField" name="password">sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158</field>
<field type="BooleanField" name="is_staff">True</field>
<field type="BooleanField" name="is_active">True</field>
<field type="BooleanField" name="is_superuser">True</field>
<field type="DateTimeField" name="last_login">2007-05-30 13:20:10</field>
<field type="DateTimeField" name="date_joined">2007-05-30 13:20:10</field>
<field to="auth.group" name="groups" rel="ManyToManyRel"></field>
<field to="auth.permission" name="user_permissions" rel="ManyToManyRel"></field>
</object>
</django-objects>

View File

@ -1,6 +1,8 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
from django.contrib import admin
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User
@ -15,6 +17,19 @@ from .admin import MediaInline, MediaPermanentInline, site as admin_site
from .models import Category, Episode, EpisodePermanent, Media
class TestDataMixin(object):
@classmethod
def setUpTestData(cls):
# password = "secret"
User.objects.create(
pk=100, username='super', first_name='Super', last_name='User', email='super@example.com',
password='sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158', is_active=True, is_superuser=True,
is_staff=True, last_login=datetime.datetime(2007, 5, 30, 13, 20, 10),
date_joined=datetime.datetime(2007, 5, 30, 13, 20, 10)
)
# Set DEBUG to True to ensure {% include %} will raise exceptions.
# That is how inlines are rendered and #9498 will bubble up if it is an issue.
@override_settings(
@ -22,8 +37,7 @@ from .models import Category, Episode, EpisodePermanent, Media
PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF="generic_inline_admin.urls",
)
class GenericAdminViewTest(TestCase):
fixtures = ['users.xml']
class GenericAdminViewTest(TestDataMixin, TestCase):
def setUp(self):
self.client.login(username='super', password='secret')
@ -129,8 +143,7 @@ class GenericAdminViewTest(TestCase):
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF="generic_inline_admin.urls")
class GenericInlineAdminParametersTest(TestCase):
fixtures = ['users.xml']
class GenericInlineAdminParametersTest(TestDataMixin, TestCase):
def setUp(self):
self.client.login(username='super', password='secret')
@ -276,8 +289,7 @@ class GenericInlineAdminParametersTest(TestCase):
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF="generic_inline_admin.urls")
class GenericInlineAdminWithUniqueTogetherTest(TestCase):
fixtures = ['users.xml']
class GenericInlineAdminWithUniqueTogetherTest(TestDataMixin, TestCase):
def setUp(self):
self.client.login(username='super', password='secret')

View File

@ -1,54 +0,0 @@
[
{
"model": "generic_views.artist",
"pk": 1,
"fields": {
"name": "Rene Magritte"
}
},
{
"model": "generic_views.author",
"pk": 1,
"fields": {
"name": "Roberto Bolaño",
"slug": "roberto-bolano"
}
},
{
"model": "generic_views.author",
"pk": 2,
"fields": {
"name": "Scott Rosenberg",
"slug": "scott-rosenberg"
}
},
{
"model": "generic_views.book",
"pk": 1,
"fields": {
"name": "2066",
"slug": "2066",
"pages": "800",
"authors": [1],
"pubdate": "2008-10-01"
}
},
{
"model": "generic_views.book",
"pk": 2,
"fields": {
"name": "Dreaming in Code",
"slug": "dreaming-in-code",
"pages": "300",
"pubdate": "2006-05-01"
}
},
{
"model": "generic_views.page",
"pk": 1,
"fields": {
"template": "generic_views/page_template.html",
"content": "I was once bitten by a moose."
}
}
]

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
@ -7,7 +8,7 @@ from django.test import TestCase, override_settings, skipUnlessDBFeature
from django.test.utils import requires_tz_support
from django.utils import timezone
from .models import Book, BookSigning
from .models import Artist, Author, Book, BookSigning, Page
def _make_books(n, base_date):
@ -19,9 +20,25 @@ def _make_books(n, base_date):
pubdate=base_date - datetime.timedelta(days=i))
class TestDataMixin(object):
@classmethod
def setUpTestData(cls):
cls.artist1 = Artist.objects.create(name='Rene Magritte')
cls.author1 = Author.objects.create(name='Roberto Bolaño', slug='roberto-bolano')
cls.author2 = Author.objects.create(name='Scott Rosenberg', slug='scott-rosenberg')
cls.book1 = Book.objects.create(name='2066', slug='2066', pages=800, pubdate=datetime.date(2008, 10, 1))
cls.book1.authors.add(cls.author1)
cls.book2 = Book.objects.create(
name='Dreaming in Code', slug='dreaming-in-code', pages=300, pubdate=datetime.date(2006, 5, 1)
)
cls.page1 = Page.objects.create(
content='I was once bitten by a moose.', template='generic_views/page_template.html'
)
@override_settings(ROOT_URLCONF='generic_views.urls')
class ArchiveIndexViewTests(TestCase):
fixtures = ['generic-views-test-data.json']
class ArchiveIndexViewTests(TestDataMixin, TestCase):
def test_archive_view(self):
res = self.client.get('/dates/books/')
@ -138,8 +155,7 @@ class ArchiveIndexViewTests(TestCase):
@override_settings(ROOT_URLCONF='generic_views.urls')
class YearArchiveViewTests(TestCase):
fixtures = ['generic-views-test-data.json']
class YearArchiveViewTests(TestDataMixin, TestCase):
def test_year_view(self):
res = self.client.get('/dates/books/2008/')
@ -243,8 +259,7 @@ class YearArchiveViewTests(TestCase):
@override_settings(ROOT_URLCONF='generic_views.urls')
class MonthArchiveViewTests(TestCase):
fixtures = ['generic-views-test-data.json']
class MonthArchiveViewTests(TestDataMixin, TestCase):
def test_month_view(self):
res = self.client.get('/dates/books/2008/oct/')
@ -370,8 +385,7 @@ class MonthArchiveViewTests(TestCase):
@override_settings(ROOT_URLCONF='generic_views.urls')
class WeekArchiveViewTests(TestCase):
fixtures = ['generic-views-test-data.json']
class WeekArchiveViewTests(TestDataMixin, TestCase):
def test_week_view(self):
res = self.client.get('/dates/books/2008/week/39/')
@ -467,8 +481,7 @@ class WeekArchiveViewTests(TestCase):
@override_settings(ROOT_URLCONF='generic_views.urls')
class DayArchiveViewTests(TestCase):
fixtures = ['generic-views-test-data.json']
class DayArchiveViewTests(TestDataMixin, TestCase):
def test_day_view(self):
res = self.client.get('/dates/books/2008/oct/01/')
@ -585,14 +598,13 @@ class DayArchiveViewTests(TestCase):
@override_settings(ROOT_URLCONF='generic_views.urls')
class DateDetailViewTests(TestCase):
fixtures = ['generic-views-test-data.json']
class DateDetailViewTests(TestDataMixin, TestCase):
def test_date_detail_by_pk(self):
res = self.client.get('/dates/books/2008/oct/01/1/')
res = self.client.get('/dates/books/2008/oct/01/%s/' % self.book1.pk)
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], Book.objects.get(pk=1))
self.assertEqual(res.context['book'], Book.objects.get(pk=1))
self.assertEqual(res.context['object'], self.book1)
self.assertEqual(res.context['book'], self.book1)
self.assertTemplateUsed(res, 'generic_views/book_detail.html')
def test_date_detail_by_slug(self):
@ -601,9 +613,9 @@ class DateDetailViewTests(TestCase):
self.assertEqual(res.context['book'], Book.objects.get(slug='dreaming-in-code'))
def test_date_detail_custom_month_format(self):
res = self.client.get('/dates/books/2008/10/01/1/')
res = self.client.get('/dates/books/2008/10/01/%s/' % self.book1.pk)
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['book'], Book.objects.get(pk=1))
self.assertEqual(res.context['book'], self.book1)
def test_date_detail_allow_future(self):
future = (datetime.date.today() + datetime.timedelta(days=60))
@ -628,14 +640,14 @@ class DateDetailViewTests(TestCase):
Refs #16918.
"""
res = self.client.get(
'/dates/books/get_object_custom_queryset/2006/may/01/2/')
'/dates/books/get_object_custom_queryset/2006/may/01/%s/' % self.book2.pk)
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], Book.objects.get(pk=2))
self.assertEqual(res.context['book'], Book.objects.get(pk=2))
self.assertEqual(res.context['object'], self.book2)
self.assertEqual(res.context['book'], self.book2)
self.assertTemplateUsed(res, 'generic_views/book_detail.html')
res = self.client.get(
'/dates/books/get_object_custom_queryset/2008/oct/01/1/')
'/dates/books/get_object_custom_queryset/2008/oct/01/9999999/')
self.assertEqual(res.status_code, 404)
def test_get_object_custom_queryset_numqueries(self):

View File

@ -1,15 +1,31 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
from django.test import TestCase, override_settings
from django.views.generic.base import View
from .models import Artist, Author, Page
from .models import Artist, Author, Book, Page
@override_settings(ROOT_URLCONF='generic_views.urls')
class DetailViewTest(TestCase):
fixtures = ['generic-views-test-data.json']
@classmethod
def setUpTestData(cls):
cls.artist1 = Artist.objects.create(name='Rene Magritte')
cls.author1 = Author.objects.create(name='Roberto Bolaño', slug='roberto-bolano')
cls.author2 = Author.objects.create(name='Scott Rosenberg', slug='scott-rosenberg')
cls.book1 = Book.objects.create(name='2066', slug='2066', pages=800, pubdate=datetime.date(2008, 10, 1))
cls.book1.authors.add(cls.author1)
cls.book2 = Book.objects.create(
name='Dreaming in Code', slug='dreaming-in-code', pages=300, pubdate=datetime.date(2006, 5, 1)
)
cls.page1 = Page.objects.create(
content='I was once bitten by a moose.', template='generic_views/page_template.html'
)
def test_simple_object(self):
res = self.client.get('/detail/obj/')
@ -19,10 +35,10 @@ class DetailViewTest(TestCase):
self.assertTemplateUsed(res, 'generic_views/detail.html')
def test_detail_by_pk(self):
res = self.client.get('/detail/author/1/')
res = self.client.get('/detail/author/%s/' % self.author1.pk)
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], Author.objects.get(pk=1))
self.assertEqual(res.context['author'], Author.objects.get(pk=1))
self.assertEqual(res.context['object'], self.author1)
self.assertEqual(res.context['author'], self.author1)
self.assertTemplateUsed(res, 'generic_views/author_detail.html')
def test_detail_missing_object(self):
@ -33,10 +49,10 @@ class DetailViewTest(TestCase):
self.assertRaises(ObjectDoesNotExist, self.client.get, '/detail/doesnotexist/1/')
def test_detail_by_custom_pk(self):
res = self.client.get('/detail/author/bycustompk/1/')
res = self.client.get('/detail/author/bycustompk/%s/' % self.author1.pk)
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], Author.objects.get(pk=1))
self.assertEqual(res.context['author'], Author.objects.get(pk=1))
self.assertEqual(res.context['object'], self.author1)
self.assertEqual(res.context['author'], self.author1)
self.assertTemplateUsed(res, 'generic_views/author_detail.html')
def test_detail_by_slug(self):
@ -54,73 +70,70 @@ class DetailViewTest(TestCase):
self.assertTemplateUsed(res, 'generic_views/author_detail.html')
def test_detail_by_pk_ignore_slug(self):
author = Author.objects.get(pk=1)
res = self.client.get('/detail/author/bypkignoreslug/1-roberto-bolano/')
res = self.client.get('/detail/author/bypkignoreslug/%s-roberto-bolano/' % self.author1.pk)
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], author)
self.assertEqual(res.context['author'], author)
self.assertEqual(res.context['object'], self.author1)
self.assertEqual(res.context['author'], self.author1)
self.assertTemplateUsed(res, 'generic_views/author_detail.html')
def test_detail_by_pk_ignore_slug_mismatch(self):
author = Author.objects.get(pk=1)
res = self.client.get('/detail/author/bypkignoreslug/1-scott-rosenberg/')
res = self.client.get('/detail/author/bypkignoreslug/%s-scott-rosenberg/' % self.author1.pk)
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], author)
self.assertEqual(res.context['author'], author)
self.assertEqual(res.context['object'], self.author1)
self.assertEqual(res.context['author'], self.author1)
self.assertTemplateUsed(res, 'generic_views/author_detail.html')
def test_detail_by_pk_and_slug(self):
author = Author.objects.get(pk=1)
res = self.client.get('/detail/author/bypkandslug/1-roberto-bolano/')
res = self.client.get('/detail/author/bypkandslug/%s-roberto-bolano/' % self.author1.pk)
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], author)
self.assertEqual(res.context['author'], author)
self.assertEqual(res.context['object'], self.author1)
self.assertEqual(res.context['author'], self.author1)
self.assertTemplateUsed(res, 'generic_views/author_detail.html')
def test_detail_by_pk_and_slug_mismatch_404(self):
res = self.client.get('/detail/author/bypkandslug/1-scott-rosenberg/')
res = self.client.get('/detail/author/bypkandslug/%s-scott-rosenberg/' % self.author1.pk)
self.assertEqual(res.status_code, 404)
def test_verbose_name(self):
res = self.client.get('/detail/artist/1/')
res = self.client.get('/detail/artist/%s/' % self.artist1.pk)
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], Artist.objects.get(pk=1))
self.assertEqual(res.context['artist'], Artist.objects.get(pk=1))
self.assertEqual(res.context['object'], self.artist1)
self.assertEqual(res.context['artist'], self.artist1)
self.assertTemplateUsed(res, 'generic_views/artist_detail.html')
def test_template_name(self):
res = self.client.get('/detail/author/1/template_name/')
res = self.client.get('/detail/author/%s/template_name/' % self.author1.pk)
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], Author.objects.get(pk=1))
self.assertEqual(res.context['author'], Author.objects.get(pk=1))
self.assertEqual(res.context['object'], self.author1)
self.assertEqual(res.context['author'], self.author1)
self.assertTemplateUsed(res, 'generic_views/about.html')
def test_template_name_suffix(self):
res = self.client.get('/detail/author/1/template_name_suffix/')
res = self.client.get('/detail/author/%s/template_name_suffix/' % self.author1.pk)
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], Author.objects.get(pk=1))
self.assertEqual(res.context['author'], Author.objects.get(pk=1))
self.assertEqual(res.context['object'], self.author1)
self.assertEqual(res.context['author'], self.author1)
self.assertTemplateUsed(res, 'generic_views/author_view.html')
def test_template_name_field(self):
res = self.client.get('/detail/page/1/field/')
res = self.client.get('/detail/page/%s/field/' % self.page1.pk)
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], Page.objects.get(pk=1))
self.assertEqual(res.context['page'], Page.objects.get(pk=1))
self.assertEqual(res.context['object'], self.page1)
self.assertEqual(res.context['page'], self.page1)
self.assertTemplateUsed(res, 'generic_views/page_template.html')
def test_context_object_name(self):
res = self.client.get('/detail/author/1/context_object_name/')
res = self.client.get('/detail/author/%s/context_object_name/' % self.author1.pk)
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], Author.objects.get(pk=1))
self.assertEqual(res.context['thingy'], Author.objects.get(pk=1))
self.assertEqual(res.context['object'], self.author1)
self.assertEqual(res.context['thingy'], self.author1)
self.assertNotIn('author', res.context)
self.assertTemplateUsed(res, 'generic_views/author_detail.html')
def test_duplicated_context_object_name(self):
res = self.client.get('/detail/author/1/dupe_context_object_name/')
res = self.client.get('/detail/author/%s/dupe_context_object_name/' % self.author1.pk)
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], Author.objects.get(pk=1))
self.assertEqual(res.context['object'], self.author1)
self.assertNotIn('author', res.context)
self.assertTemplateUsed(res, 'generic_views/author_detail.html')

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
@ -7,12 +8,25 @@ from django.test import TestCase, override_settings
from django.utils.encoding import force_str
from django.views.generic.base import View
from .models import Artist, Author, Book
from .models import Artist, Author, Book, Page
@override_settings(ROOT_URLCONF='generic_views.urls')
class ListViewTests(TestCase):
fixtures = ['generic-views-test-data.json']
@classmethod
def setUpTestData(cls):
cls.artist1 = Artist.objects.create(name='Rene Magritte')
cls.author1 = Author.objects.create(name='Roberto Bolaño', slug='roberto-bolano')
cls.author2 = Author.objects.create(name='Scott Rosenberg', slug='scott-rosenberg')
cls.book1 = Book.objects.create(name='2066', slug='2066', pages=800, pubdate=datetime.date(2008, 10, 1))
cls.book1.authors.add(cls.author1)
cls.book2 = Book.objects.create(
name='Dreaming in Code', slug='dreaming-in-code', pages=300, pubdate=datetime.date(2006, 5, 1)
)
cls.page1 = Page.objects.create(
content='I was once bitten by a moose.', template='generic_views/page_template.html'
)
def test_items(self):
res = self.client.get('/list/dict/')

View File

@ -218,7 +218,7 @@ class AuthorGetQuerySetFormView(generic.edit.ModelFormMixin):
class BookDetailGetObjectCustomQueryset(BookDetail):
def get_object(self, queryset=None):
return super(BookDetailGetObjectCustomQueryset, self).get_object(
queryset=Book.objects.filter(pk=2))
queryset=Book.objects.filter(pk=self.kwargs['pk']))
class CustomMultipleObjectMixinView(generic.list.MultipleObjectMixin, generic.View):

View File

@ -1,76 +0,0 @@
[
{
"pk": 1,
"model": "known_related_objects.tournament",
"fields": {
"name": "Tourney 1"
}
},
{
"pk": 2,
"model": "known_related_objects.tournament",
"fields": {
"name": "Tourney 2"
}
},
{
"pk": 1,
"model": "known_related_objects.organiser",
"fields": {
"name": "Organiser 1"
}
},
{
"pk": 1,
"model": "known_related_objects.pool",
"fields": {
"tournament": 1,
"organiser": 1,
"name": "T1 Pool 1"
}
},
{
"pk": 2,
"model": "known_related_objects.pool",
"fields": {
"tournament": 1,
"organiser": 1,
"name": "T1 Pool 2"
}
},
{
"pk": 3,
"model": "known_related_objects.pool",
"fields": {
"tournament": 2,
"organiser": 1,
"name": "T2 Pool 1"
}
},
{
"pk": 4,
"model": "known_related_objects.pool",
"fields": {
"tournament": 2,
"organiser": 1,
"name": "T2 Pool 2"
}
},
{
"pk": 1,
"model": "known_related_objects.poolstyle",
"fields": {
"name": "T1 Pool 2 Style",
"pool": 2
}
},
{
"pk": 2,
"model": "known_related_objects.poolstyle",
"fields": {
"name": "T2 Pool 1 Style",
"pool": 3
}
}
]

View File

@ -6,17 +6,28 @@ from .models import Organiser, Pool, PoolStyle, Tournament
class ExistingRelatedInstancesTests(TestCase):
fixtures = ['tournament.json']
@classmethod
def setUpTestData(cls):
cls.t1 = Tournament.objects.create(name='Tourney 1')
cls.t2 = Tournament.objects.create(name='Tourney 2')
cls.o1 = Organiser.objects.create(name='Organiser 1')
cls.p1 = Pool.objects.create(name='T1 Pool 1', tournament=cls.t1, organiser=cls.o1)
cls.p2 = Pool.objects.create(name='T1 Pool 2', tournament=cls.t1, organiser=cls.o1)
cls.p3 = Pool.objects.create(name='T2 Pool 1', tournament=cls.t2, organiser=cls.o1)
cls.p4 = Pool.objects.create(name='T2 Pool 2', tournament=cls.t2, organiser=cls.o1)
cls.ps1 = PoolStyle.objects.create(name='T1 Pool 2 Style', pool=cls.p2)
cls.ps2 = PoolStyle.objects.create(name='T2 Pool 1 Style', pool=cls.p3)
def test_foreign_key(self):
with self.assertNumQueries(2):
tournament = Tournament.objects.get(pk=1)
tournament = Tournament.objects.get(pk=self.t1.pk)
pool = tournament.pool_set.all()[0]
self.assertIs(tournament, pool.tournament)
def test_foreign_key_prefetch_related(self):
with self.assertNumQueries(2):
tournament = (Tournament.objects.prefetch_related('pool_set').get(pk=1))
tournament = (Tournament.objects.prefetch_related('pool_set').get(pk=self.t1.pk))
pool = tournament.pool_set.all()[0]
self.assertIs(tournament, pool.tournament)
@ -29,54 +40,54 @@ class ExistingRelatedInstancesTests(TestCase):
self.assertIs(tournaments[1], pool2.tournament)
def test_queryset_or(self):
tournament_1 = Tournament.objects.get(pk=1)
tournament_2 = Tournament.objects.get(pk=2)
tournament_1 = self.t1
tournament_2 = self.t2
with self.assertNumQueries(1):
pools = tournament_1.pool_set.all() | tournament_2.pool_set.all()
related_objects = set(pool.tournament for pool in pools)
self.assertEqual(related_objects, {tournament_1, tournament_2})
def test_queryset_or_different_cached_items(self):
tournament = Tournament.objects.get(pk=1)
organiser = Organiser.objects.get(pk=1)
tournament = self.t1
organiser = self.o1
with self.assertNumQueries(1):
pools = tournament.pool_set.all() | organiser.pool_set.all()
first = pools.filter(pk=1)[0]
first = pools.filter(pk=self.p1.pk)[0]
self.assertIs(first.tournament, tournament)
self.assertIs(first.organiser, organiser)
def test_queryset_or_only_one_with_precache(self):
tournament_1 = Tournament.objects.get(pk=1)
tournament_2 = Tournament.objects.get(pk=2)
# 2 queries here as pool id 3 has tournament 2, which is not cached
tournament_1 = self.t1
tournament_2 = self.t2
# 2 queries here as pool 3 has tournament 2, which is not cached
with self.assertNumQueries(2):
pools = tournament_1.pool_set.all() | Pool.objects.filter(pk=3)
pools = tournament_1.pool_set.all() | Pool.objects.filter(pk=self.p3.pk)
related_objects = set(pool.tournament for pool in pools)
self.assertEqual(related_objects, {tournament_1, tournament_2})
# and the other direction
with self.assertNumQueries(2):
pools = Pool.objects.filter(pk=3) | tournament_1.pool_set.all()
pools = Pool.objects.filter(pk=self.p3.pk) | tournament_1.pool_set.all()
related_objects = set(pool.tournament for pool in pools)
self.assertEqual(related_objects, {tournament_1, tournament_2})
def test_queryset_and(self):
tournament = Tournament.objects.get(pk=1)
organiser = Organiser.objects.get(pk=1)
tournament = self.t1
organiser = self.o1
with self.assertNumQueries(1):
pools = tournament.pool_set.all() & organiser.pool_set.all()
first = pools.filter(pk=1)[0]
first = pools.filter(pk=self.p1.pk)[0]
self.assertIs(first.tournament, tournament)
self.assertIs(first.organiser, organiser)
def test_one_to_one(self):
with self.assertNumQueries(2):
style = PoolStyle.objects.get(pk=1)
style = PoolStyle.objects.get(pk=self.ps1.pk)
pool = style.pool
self.assertIs(style, pool.poolstyle)
def test_one_to_one_select_related(self):
with self.assertNumQueries(1):
style = PoolStyle.objects.select_related('pool').get(pk=1)
style = PoolStyle.objects.select_related('pool').get(pk=self.ps1.pk)
pool = style.pool
self.assertIs(style, pool.poolstyle)
@ -88,7 +99,7 @@ class ExistingRelatedInstancesTests(TestCase):
def test_one_to_one_prefetch_related(self):
with self.assertNumQueries(2):
style = PoolStyle.objects.prefetch_related('pool').get(pk=1)
style = PoolStyle.objects.prefetch_related('pool').get(pk=self.ps1.pk)
pool = style.pool
self.assertIs(style, pool.poolstyle)
@ -100,19 +111,19 @@ class ExistingRelatedInstancesTests(TestCase):
def test_reverse_one_to_one(self):
with self.assertNumQueries(2):
pool = Pool.objects.get(pk=2)
pool = Pool.objects.get(pk=self.p2.pk)
style = pool.poolstyle
self.assertIs(pool, style.pool)
def test_reverse_one_to_one_select_related(self):
with self.assertNumQueries(1):
pool = Pool.objects.select_related('poolstyle').get(pk=2)
pool = Pool.objects.select_related('poolstyle').get(pk=self.p2.pk)
style = pool.poolstyle
self.assertIs(pool, style.pool)
def test_reverse_one_to_one_prefetch_related(self):
with self.assertNumQueries(2):
pool = Pool.objects.prefetch_related('poolstyle').get(pk=2)
pool = Pool.objects.prefetch_related('poolstyle').get(pk=self.p2.pk)
style = pool.poolstyle
self.assertIs(pool, style.pool)

View File

@ -1,42 +0,0 @@
[
{
"pk": 100,
"model": "auth.user",
"fields": {
"username": "super",
"first_name": "Super",
"last_name": "User",
"is_active": true,
"is_superuser": true,
"is_staff": true,
"last_login": "2007-05-30 13:20:10",
"groups": [],
"user_permissions": [],
"password": "sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158",
"email": "super@example.com",
"date_joined": "2007-05-30 13:20:10"
}
},
{
"pk": 100,
"model": "proxy_models.BaseUser",
"fields": {
"name": "Django Pony"
}
},
{
"pk": 100,
"model": "proxy_models.TrackerUser",
"fields": {
"status": "emperor"
}
},
{
"pk": 100,
"model": "proxy_models.Issue",
"fields": {
"summary": "Pony's Issue",
"assignee": 100
}
}
]

View File

@ -1,7 +1,10 @@
from __future__ import unicode_literals
import datetime
from django.apps import apps
from django.contrib import admin
from django.contrib.auth.models import User as AuthUser
from django.contrib.contenttypes.models import ContentType
from django.core import checks, exceptions, management
from django.core.urlresolvers import reverse
@ -394,7 +397,17 @@ class ProxyModelTests(TestCase):
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='proxy_models.urls',)
class ProxyModelAdminTests(TestCase):
fixtures = ['myhorses']
@classmethod
def setUpTestData(cls):
cls.u1 = AuthUser.objects.create(
password='sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158',
last_login=datetime.datetime(2007, 5, 30, 13, 20, 10), is_superuser=True, username='super',
first_name='Super', last_name='User', email='super@example.com', is_staff=True, is_active=True,
date_joined=datetime.datetime(2007, 5, 30, 13, 20, 10)
)
cls.tu1 = ProxyTrackerUser.objects.create(name='Django Pony', status='emperor')
cls.i1 = Issue.objects.create(summary="Pony's Issue", assignee=cls.tu1)
def test_cascade_delete_proxy_model_admin_warning(self):
"""

View File

@ -1,110 +0,0 @@
[
{
"pk": 1,
"model": "raw_query.author",
"fields": {
"dob": "1950-09-20",
"first_name": "Joe",
"last_name": "Smith"
}
},
{
"pk": 2,
"model": "raw_query.author",
"fields": {
"dob": "1920-04-02",
"first_name": "Jill",
"last_name": "Doe"
}
},
{
"pk": 3,
"model": "raw_query.author",
"fields": {
"dob": "1986-01-25",
"first_name": "Bob",
"last_name": "Smith"
}
},
{
"pk": 4,
"model": "raw_query.author",
"fields": {
"dob": "1932-05-10",
"first_name": "Bill",
"last_name": "Jones"
}
},
{
"pk": 1,
"model": "raw_query.book",
"fields": {
"author": 1,
"title": "The awesome book",
"paperback": false,
"opening_line": "It was a bright cold day in April and the clocks were striking thirteen."
}
},
{
"pk": 2,
"model": "raw_query.book",
"fields": {
"author": 1,
"title": "The horrible book",
"paperback": true,
"opening_line": "On an evening in the latter part of May a middle-aged man was walking homeward from Shaston to the village of Marlott, in the adjoining Vale of Blakemore, or Blackmoor."
}
},
{
"pk": 3,
"model": "raw_query.book",
"fields": {
"author": 1,
"title": "Another awesome book",
"paperback": false,
"opening_line": "A squat grey building of only thirty-four stories."
}
},
{
"pk": 4,
"model": "raw_query.book",
"fields": {
"author": 3,
"title": "Some other book",
"paperback": true,
"opening_line": "It was the day my grandmother exploded."
}
},
{
"pk": 1,
"model": "raw_query.coffee",
"fields": {
"brand": "dunkin doughnuts"
}
},
{
"pk": 2,
"model": "raw_query.coffee",
"fields": {
"brand": "starbucks"
}
},
{
"pk": 1,
"model": "raw_query.reviewer",
"fields": {
"reviewed": [
2,
3,
4
]
}
},
{
"pk": 2,
"model": "raw_query.reviewer",
"fields": {
"reviewed": []
}
}
]

View File

@ -9,7 +9,22 @@ from .models import Author, Book, Coffee, FriendlyAuthor, Reviewer
class RawQueryTests(TestCase):
fixtures = ['raw_query_books.json']
@classmethod
def setUpTestData(cls):
cls.a1 = Author.objects.create(first_name='Joe', last_name='Smith', dob=date(1950, 9, 20))
cls.a2 = Author.objects.create(first_name='Jill', last_name='Doe', dob=date(1920, 4, 2))
cls.a3 = Author.objects.create(first_name='Bob', last_name='Smith', dob=date(1986, 1, 25))
cls.a4 = Author.objects.create(first_name='Bill', last_name='Jones', dob=date(1932, 5, 10))
cls.b1 = Book.objects.create(title='The awesome book', author=cls.a1, paperback=False, opening_line='It was a bright cold day in April and the clocks were striking thirteen.')
cls.b2 = Book.objects.create(title='The horrible book', author=cls.a1, paperback=True, opening_line='On an evening in the latter part of May a middle-aged man was walking homeward from Shaston to the village of Marlott, in the adjoining Vale of Blakemore, or Blackmoor.')
cls.b3 = Book.objects.create(title='Another awesome book', author=cls.a1, paperback=False, opening_line='A squat grey building of only thirty-four stories.')
cls.b4 = Book.objects.create(title='Some other book', author=cls.a3, paperback=True, opening_line='It was the day my grandmother exploded.')
cls.c1 = Coffee.objects.create(brand='dunkin doughnuts')
cls.c2 = Coffee.objects.create(brand='starbucks')
cls.r1 = Reviewer.objects.create()
cls.r2 = Reviewer.objects.create()
cls.r1.reviewed.add(cls.b2, cls.b3, cls.b4)
def assertSuccessfulRawQuery(self, model, query, expected_results,
expected_annotations=(), params=[], translations=None):

View File

@ -1,55 +0,0 @@
[
{
"model": "syndication_tests.entry",
"pk": 1,
"fields": {
"title": "My first entry",
"updated": "1850-01-01 12:30:00",
"published": "1066-09-25 20:15:00"
}
},
{
"model": "syndication_tests.entry",
"pk": 2,
"fields": {
"title": "My second entry",
"updated": "2008-01-02 12:30:00",
"published": "2006-03-17 18:00:00"
}
},
{
"model": "syndication_tests.entry",
"pk": 3,
"fields": {
"title": "My third entry",
"updated": "2008-01-02 13:30:00",
"published": "2005-06-14 10:45:00"
}
},
{
"model": "syndication_tests.entry",
"pk": 4,
"fields": {
"title": "A & B < C > D",
"updated": "2008-01-03 13:30:00",
"published": "2005-11-25 12:11:23"
}
},
{
"model": "syndication_tests.entry",
"pk": 5,
"fields": {
"title": "My last entry",
"updated": "2013-01-20 00:00:00",
"published": "2013-03-25 20:00:00"
}
},
{
"model": "syndication_tests.article",
"pk": 1,
"fields": {
"title": "My first article",
"entry": "1"
}
}
]

View File

@ -11,7 +11,7 @@ from django.test.utils import requires_tz_support
from django.utils import timezone
from django.utils.feedgenerator import rfc2822_date, rfc3339_date
from .models import Entry
from .models import Article, Entry
try:
import pytz
@ -22,15 +22,30 @@ TZ = timezone.get_default_timezone()
class FeedTestCase(TestCase):
fixtures = ['feeddata.json']
def setUp(self):
# Django cannot deal with very old dates when pytz isn't installed.
if pytz is None:
old_entry = Entry.objects.get(pk=1)
old_entry.updated = datetime.datetime(1980, 1, 1, 12, 30)
old_entry.published = datetime.datetime(1986, 9, 25, 20, 15, 00)
old_entry.save()
@classmethod
def setUpTestData(cls):
cls.e1 = Entry.objects.create(
title='My first entry', updated=datetime.datetime(1980, 1, 1, 12, 30),
published=datetime.datetime(1986, 9, 25, 20, 15, 00)
)
cls.e2 = Entry.objects.create(
title='My second entry', updated=datetime.datetime(2008, 1, 2, 12, 30),
published=datetime.datetime(2006, 3, 17, 18, 0)
)
cls.e3 = Entry.objects.create(
title='My third entry', updated=datetime.datetime(2008, 1, 2, 13, 30),
published=datetime.datetime(2005, 6, 14, 10, 45)
)
cls.e4 = Entry.objects.create(
title='A & B < C > D', updated=datetime.datetime(2008, 1, 3, 13, 30),
published=datetime.datetime(2005, 11, 25, 12, 11, 23)
)
cls.e5 = Entry.objects.create(
title='My last entry', updated=datetime.datetime(2013, 1, 20, 0, 0),
published=datetime.datetime(2013, 3, 25, 20, 0)
)
cls.a1 = Article.objects.create(title='My first article', entry=cls.e1)
def assertChildNodes(self, elem, expected):
actual = set(n.nodeName for n in elem.childNodes)

View File

@ -1,56 +0,0 @@
[
{
"pk": "1",
"model": "auth.user",
"fields": {
"username": "testclient",
"first_name": "Test",
"last_name": "Client",
"is_active": true,
"is_superuser": false,
"is_staff": false,
"last_login": "2006-12-17 07:03:31",
"groups": [],
"user_permissions": [],
"password": "sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161",
"email": "testclient@example.com",
"date_joined": "2006-12-17 07:03:31"
}
},
{
"pk": "2",
"model": "auth.user",
"fields": {
"username": "inactive",
"first_name": "Inactive",
"last_name": "User",
"is_active": false,
"is_superuser": false,
"is_staff": false,
"last_login": "2006-12-17 07:03:31",
"groups": [],
"user_permissions": [],
"password": "sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161",
"email": "testclient@example.com",
"date_joined": "2006-12-17 07:03:31"
}
},
{
"pk": "3",
"model": "auth.user",
"fields": {
"username": "staff",
"first_name": "Staff",
"last_name": "Member",
"is_active": true,
"is_superuser": false,
"is_staff": true,
"last_login": "2006-12-17 07:03:31",
"groups": [],
"user_permissions": [],
"password": "sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161",
"email": "testclient@example.com",
"date_joined": "2006-12-17 07:03:31"
}
}
]

View File

@ -22,6 +22,9 @@ rather than the HTML rendered to the end-user.
"""
from __future__ import unicode_literals
import datetime
from django.contrib.auth.models import User
from django.core import mail
from django.http import HttpResponse
from django.test import Client, RequestFactory, TestCase, override_settings
@ -32,7 +35,27 @@ from .views import get_view, post_view, trace_view
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='test_client.urls',)
class ClientTest(TestCase):
fixtures = ['testdata.json']
@classmethod
def setUpTestData(cls):
cls.u1 = User.objects.create(
password='sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161',
last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='testclient',
first_name='Test', last_name='Client', email='testclient@example.com', is_staff=False, is_active=True,
date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
)
cls.u2 = User.objects.create(
password='sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161',
last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='inactive',
first_name='Inactive', last_name='User', email='testclient@example.com', is_staff=False, is_active=False,
date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
)
cls.u3 = User.objects.create(
password='sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161',
last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='staff',
first_name='Staff', last_name='Member', email='testclient@example.com', is_staff=True, is_active=True,
date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
)
def test_get_view(self):
"GET a view"

View File

@ -1,56 +0,0 @@
[
{
"pk": "1",
"model": "auth.user",
"fields": {
"username": "testclient",
"first_name": "Test",
"last_name": "Client",
"is_active": true,
"is_superuser": false,
"is_staff": false,
"last_login": "2006-12-17 07:03:31",
"groups": [],
"user_permissions": [],
"password": "sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161",
"email": "testclient@example.com",
"date_joined": "2006-12-17 07:03:31"
}
},
{
"pk": "2",
"model": "auth.user",
"fields": {
"username": "inactive",
"first_name": "Inactive",
"last_name": "User",
"is_active": false,
"is_superuser": false,
"is_staff": false,
"last_login": "2006-12-17 07:03:31",
"groups": [],
"user_permissions": [],
"password": "sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161",
"email": "testclient@example.com",
"date_joined": "2006-12-17 07:03:31"
}
},
{
"pk": "3",
"model": "auth.user",
"fields": {
"username": "staff",
"first_name": "Staff",
"last_name": "Member",
"is_active": true,
"is_superuser": false,
"is_staff": true,
"last_login": "2006-12-17 07:03:31",
"groups": [],
"user_permissions": [],
"password": "sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161",
"email": "testclient@example.com",
"date_joined": "2006-12-17 07:03:31"
}
}
]

View File

@ -4,6 +4,7 @@ Regression tests for the Test Client, especially the customized assertions.
"""
from __future__ import unicode_literals
import datetime
import itertools
import os
@ -24,6 +25,30 @@ from .models import CustomUser
from .views import CustomTestException
class TestDataMixin(object):
@classmethod
def setUpTestData(cls):
cls.u1 = User.objects.create(
password='sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161',
last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='testclient',
first_name='Test', last_name='Client', email='testclient@example.com', is_staff=False, is_active=True,
date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
)
cls.u2 = User.objects.create(
password='sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161',
last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='inactive',
first_name='Inactive', last_name='User', email='testclient@example.com', is_staff=False, is_active=False,
date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
)
cls.u3 = User.objects.create(
password='sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161',
last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='staff',
first_name='Staff', last_name='Member', email='testclient@example.com', is_staff=True, is_active=True,
date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
)
@override_settings(ROOT_URLCONF='test_client_regress.urls')
class AssertContainsTests(TestCase):
@ -190,8 +215,7 @@ class AssertContainsTests(TestCase):
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='test_client_regress.urls',)
class AssertTemplateUsedTests(TestCase):
fixtures = ['testdata.json']
class AssertTemplateUsedTests(TestDataMixin, TestCase):
def test_no_context(self):
"Template usage assertions work then templates aren't in use"
@ -812,8 +836,7 @@ class AssertFormsetErrorTests(TestCase):
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='test_client_regress.urls',)
class LoginTests(TestCase):
fixtures = ['testdata']
class LoginTests(TestDataMixin, TestCase):
def test_login_different_client(self):
"Check that using a different test client doesn't violate authentication"
@ -837,8 +860,7 @@ class LoginTests(TestCase):
SESSION_ENGINE='test_client_regress.session',
ROOT_URLCONF='test_client_regress.urls',
)
class SessionEngineTests(TestCase):
fixtures = ['testdata']
class SessionEngineTests(TestDataMixin, TestCase):
def test_login(self):
"A session engine that modifies the session key can be used to log in"
@ -881,8 +903,7 @@ class URLEscapingTests(TestCase):
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='test_client_regress.urls',)
class ExceptionTests(TestCase):
fixtures = ['testdata.json']
class ExceptionTests(TestDataMixin, TestCase):
def test_exception_cleared(self):
"#5836 - A stale user exception isn't re-raised by the test client."
@ -950,8 +971,7 @@ class zzUrlconfSubstitutionTests(TestCase):
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='test_client_regress.urls',)
class ContextTests(TestCase):
fixtures = ['testdata']
class ContextTests(TestDataMixin, TestCase):
def test_single_context(self):
"Context variables can be retrieved from a single context"
@ -1025,8 +1045,7 @@ class ContextTests(TestCase):
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='test_client_regress.urls',)
class SessionTests(TestCase):
fixtures = ['testdata.json']
class SessionTests(TestDataMixin, TestCase):
def test_session(self):
"The session isn't lost if a user logs in"

View File

@ -1,17 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<django-objects version="1.0">
<object pk="100" model="auth.user">
<field type="CharField" name="username">super</field>
<field type="CharField" name="first_name">Super</field>
<field type="CharField" name="last_name">User</field>
<field type="CharField" name="email">super@example.com</field>
<field type="CharField" name="password">sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158</field>
<field type="BooleanField" name="is_staff">True</field>
<field type="BooleanField" name="is_active">True</field>
<field type="BooleanField" name="is_superuser">True</field>
<field type="DateTimeField" name="last_login">2001-01-01 00:00:00+00:00</field>
<field type="DateTimeField" name="date_joined">2001-01-01 00:00:00+00:00</field>
<field to="auth.group" name="groups" rel="ManyToManyRel"></field>
<field to="auth.permission" name="user_permissions" rel="ManyToManyRel"></field>
</object>
</django-objects>

View File

@ -7,6 +7,7 @@ import warnings
from unittest import skipIf
from xml.dom.minidom import parseString
from django.contrib.auth.models import User
from django.core import serializers
from django.core.urlresolvers import reverse
from django.db.models import Max, Min
@ -1083,7 +1084,15 @@ class NewFormsTests(TestCase):
ROOT_URLCONF='timezones.urls')
class AdminTests(TestCase):
fixtures = ['tz_users.xml']
@classmethod
def setUpTestData(cls):
# password = "secret"
cls.u1 = User.objects.create(
id=100, password='sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158',
last_login=datetime.datetime(2007, 5, 30, 13, 20, 10), is_superuser=True, username='super',
first_name='Super', last_name='User', email='super@example.com',
is_staff=True, is_active=True, date_joined=datetime.datetime(2007, 5, 30, 13, 20, 10)
)
def setUp(self):
self.client.login(username='super', password='secret')

View File

@ -1,75 +0,0 @@
[
{
"pk": "1",
"model": "auth.user",
"fields": {
"username": "testclient",
"first_name": "Test",
"last_name": "Client",
"is_active": true,
"is_superuser": false,
"is_staff": false,
"last_login": "2006-12-17 07:03:31",
"groups": [],
"user_permissions": [],
"password": "sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161",
"email": "testclient@example.com",
"date_joined": "2006-12-17 07:03:31"
}
},
{
"pk": 1,
"model": "view_tests.author",
"fields": {
"name": "Boris"
}
},
{
"pk": 1,
"model": "view_tests.article",
"fields": {
"author": 1,
"title": "Old Article",
"slug": "old_article",
"date_created": "2001-01-01 21:22:23"
}
},
{
"pk": 2,
"model": "view_tests.article",
"fields": {
"author": 1,
"title": "Current Article",
"slug": "current_article",
"date_created": "2007-09-17 21:22:23"
}
},
{
"pk": 3,
"model": "view_tests.article",
"fields": {
"author": 1,
"title": "Future Article",
"slug": "future_article",
"date_created": "3000-01-01 21:22:23"
}
},
{
"pk": 1,
"model": "view_tests.urlarticle",
"fields": {
"author": 1,
"title": "Old Article",
"slug": "old_article",
"date_created": "2001-01-01 21:22:23"
}
},
{
"pk": 1,
"model": "sites.site",
"fields": {
"domain": "testserver",
"name": "testserver"
}
}
]

View File

@ -1,18 +1,48 @@
from __future__ import unicode_literals
import datetime
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.test import TestCase
from django.test.utils import override_settings
from ..models import UrlArticle
from ..models import Article, Author, UrlArticle
@override_settings(ROOT_URLCONF='view_tests.urls')
class DefaultsTests(TestCase):
"""Test django views in django/views/defaults.py"""
fixtures = ['testdata.json']
non_existing_urls = ['/non_existing_url/', # this is in urls.py
'/other_non_existing_url/'] # this NOT in urls.py
@classmethod
def setUpTestData(cls):
User.objects.create(
password='sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161',
last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='testclient',
first_name='Test', last_name='Client', email='testclient@example.com', is_staff=False, is_active=True,
date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
)
Author.objects.create(name='Boris')
Article.objects.create(
title='Old Article', slug='old_article', author_id=1,
date_created=datetime.datetime(2001, 1, 1, 21, 22, 23)
)
Article.objects.create(
title='Current Article', slug='current_article', author_id=1,
date_created=datetime.datetime(2007, 9, 17, 21, 22, 23)
)
Article.objects.create(
title='Future Article', slug='future_article', author_id=1,
date_created=datetime.datetime(3000, 1, 1, 21, 22, 23)
)
UrlArticle.objects.create(
title='Old Article', slug='old_article', author_id=1,
date_created=datetime.datetime(2001, 1, 1, 21, 22, 23)
)
Site(id=1, domain='testserver', name='testserver').save()
def test_page_not_found(self):
"A 404 status is returned by the page_not_found view"
for url in self.non_existing_urls: