mirror of
https://github.com/django/django.git
synced 2025-10-24 22:26:08 +00:00
Fixed #12991 -- Added unittest2 support. Thanks to PaulM for the draft patch, and to Luke, Karen, Justin, Alex, Łukasz Rekucki, and Chuck Harmston for their help testing and reviewing the final patch.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@14139 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
@@ -4,13 +4,13 @@ advertised - especially with regards to the handling of the DJANGO_SETTINGS_MODU
|
||||
and default settings.py files.
|
||||
"""
|
||||
import os
|
||||
import unittest
|
||||
import shutil
|
||||
import sys
|
||||
import re
|
||||
|
||||
from django import conf, bin, get_version
|
||||
from django.conf import settings
|
||||
from django.utils import unittest
|
||||
|
||||
class AdminScriptTestCase(unittest.TestCase):
|
||||
def write_settings(self, filename, apps=None, is_dir=False, sdict=None):
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
from datetime import datetime
|
||||
import unittest
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import models
|
||||
from django.utils.formats import localize
|
||||
from django.test import TestCase
|
||||
|
||||
from django.contrib import admin
|
||||
from django.contrib.admin.util import display_for_field, label_for_field, lookup_field
|
||||
from django.contrib.admin.util import NestedObjects
|
||||
from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE
|
||||
from django.contrib.sites.models import Site
|
||||
from django.contrib.admin.util import NestedObjects
|
||||
from django.db import models
|
||||
from django.test import TestCase
|
||||
from django.utils import unittest
|
||||
from django.utils.formats import localize
|
||||
|
||||
from models import Article, Count
|
||||
|
||||
|
||||
@@ -12,13 +12,14 @@ from django.contrib.admin.sites import LOGIN_FORM_KEY
|
||||
from django.contrib.admin.util import quote
|
||||
from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME
|
||||
from django.forms.util import ErrorList
|
||||
import django.template.context
|
||||
from django.test import TestCase
|
||||
from django.utils import formats
|
||||
from django.utils.cache import get_max_age
|
||||
from django.utils.encoding import iri_to_uri
|
||||
from django.utils.html import escape
|
||||
from django.utils.translation import get_date_formats, activate, deactivate
|
||||
import django.template.context
|
||||
from django.utils import unittest
|
||||
|
||||
# local test models
|
||||
from models import Article, BarAccount, CustomArticle, EmptyModel, \
|
||||
@@ -2210,51 +2211,52 @@ class UserAdminTest(TestCase):
|
||||
self.assertNotEquals(new_user.password, UNUSABLE_PASSWORD)
|
||||
|
||||
try:
|
||||
# If docutils isn't installed, skip the AdminDocs tests.
|
||||
import docutils
|
||||
|
||||
class AdminDocsTest(TestCase):
|
||||
fixtures = ['admin-views-users.xml']
|
||||
|
||||
def setUp(self):
|
||||
self.client.login(username='super', password='secret')
|
||||
|
||||
def tearDown(self):
|
||||
self.client.logout()
|
||||
|
||||
def test_tags(self):
|
||||
response = self.client.get('/test_admin/admin/doc/tags/')
|
||||
|
||||
# The builtin tag group exists
|
||||
self.assertContains(response, "<h2>Built-in tags</h2>", count=2)
|
||||
|
||||
# A builtin tag exists in both the index and detail
|
||||
self.assertContains(response, '<h3 id="built_in-autoescape">autoescape</h3>')
|
||||
self.assertContains(response, '<li><a href="#built_in-autoescape">autoescape</a></li>')
|
||||
|
||||
# An app tag exists in both the index and detail
|
||||
self.assertContains(response, '<h3 id="flatpages-get_flatpages">get_flatpages</h3>')
|
||||
self.assertContains(response, '<li><a href="#flatpages-get_flatpages">get_flatpages</a></li>')
|
||||
|
||||
# The admin list tag group exists
|
||||
self.assertContains(response, "<h2>admin_list</h2>", count=2)
|
||||
|
||||
# An admin list tag exists in both the index and detail
|
||||
self.assertContains(response, '<h3 id="admin_list-admin_actions">admin_actions</h3>')
|
||||
self.assertContains(response, '<li><a href="#admin_list-admin_actions">admin_actions</a></li>')
|
||||
|
||||
def test_filters(self):
|
||||
response = self.client.get('/test_admin/admin/doc/filters/')
|
||||
|
||||
# The builtin filter group exists
|
||||
self.assertContains(response, "<h2>Built-in filters</h2>", count=2)
|
||||
|
||||
# A builtin filter exists in both the index and detail
|
||||
self.assertContains(response, '<h3 id="built_in-add">add</h3>')
|
||||
self.assertContains(response, '<li><a href="#built_in-add">add</a></li>')
|
||||
|
||||
except ImportError:
|
||||
pass
|
||||
docutils = None
|
||||
|
||||
#@unittest.skipUnless(docutils, "no docutils installed.")
|
||||
class AdminDocsTest(TestCase):
|
||||
fixtures = ['admin-views-users.xml']
|
||||
|
||||
def setUp(self):
|
||||
self.client.login(username='super', password='secret')
|
||||
|
||||
def tearDown(self):
|
||||
self.client.logout()
|
||||
|
||||
def test_tags(self):
|
||||
response = self.client.get('/test_admin/admin/doc/tags/')
|
||||
|
||||
# The builtin tag group exists
|
||||
self.assertContains(response, "<h2>Built-in tags</h2>", count=2)
|
||||
|
||||
# A builtin tag exists in both the index and detail
|
||||
self.assertContains(response, '<h3 id="built_in-autoescape">autoescape</h3>')
|
||||
self.assertContains(response, '<li><a href="#built_in-autoescape">autoescape</a></li>')
|
||||
|
||||
# An app tag exists in both the index and detail
|
||||
self.assertContains(response, '<h3 id="flatpages-get_flatpages">get_flatpages</h3>')
|
||||
self.assertContains(response, '<li><a href="#flatpages-get_flatpages">get_flatpages</a></li>')
|
||||
|
||||
# The admin list tag group exists
|
||||
self.assertContains(response, "<h2>admin_list</h2>", count=2)
|
||||
|
||||
# An admin list tag exists in both the index and detail
|
||||
self.assertContains(response, '<h3 id="admin_list-admin_actions">admin_actions</h3>')
|
||||
self.assertContains(response, '<li><a href="#admin_list-admin_actions">admin_actions</a></li>')
|
||||
|
||||
def test_filters(self):
|
||||
response = self.client.get('/test_admin/admin/doc/filters/')
|
||||
|
||||
# The builtin filter group exists
|
||||
self.assertContains(response, "<h2>Built-in filters</h2>", count=2)
|
||||
|
||||
# A builtin filter exists in both the index and detail
|
||||
self.assertContains(response, '<h3 id="built_in-add">add</h3>')
|
||||
self.assertContains(response, '<li><a href="#built_in-add">add</a></li>')
|
||||
|
||||
AdminDocsTest = unittest.skipUnless(docutils, "no docutils installed.")(AdminDocsTest)
|
||||
|
||||
class ValidXHTMLTests(TestCase):
|
||||
fixtures = ['admin-views-users.xml']
|
||||
|
||||
@@ -3,9 +3,10 @@
|
||||
from django import forms
|
||||
from django.contrib import admin
|
||||
from django.contrib.admin import widgets
|
||||
from unittest import TestCase
|
||||
from django.test import TestCase as DjangoTestCase
|
||||
from django.db.models import DateField
|
||||
from django.test import TestCase as DjangoTestCase
|
||||
from django.utils.unittest import TestCase
|
||||
|
||||
import models
|
||||
|
||||
class AdminFormfieldForDBFieldTests(TestCase):
|
||||
|
||||
@@ -3,32 +3,13 @@ from decimal import Decimal
|
||||
|
||||
from django.core.exceptions import FieldError
|
||||
from django.conf import settings
|
||||
from django.test import TestCase, Approximate
|
||||
from django.test import TestCase, Approximate, skipUnlessDBFeature
|
||||
from django.db import DEFAULT_DB_ALIAS
|
||||
from django.db.models import Count, Max, Avg, Sum, StdDev, Variance, F
|
||||
|
||||
from regressiontests.aggregation_regress.models import *
|
||||
|
||||
|
||||
def run_stddev_tests():
|
||||
"""Check to see if StdDev/Variance tests should be run.
|
||||
|
||||
Stddev and Variance are not guaranteed to be available for SQLite, and
|
||||
are not available for PostgreSQL before 8.2.
|
||||
"""
|
||||
if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] == 'django.db.backends.sqlite3':
|
||||
return False
|
||||
|
||||
class StdDevPop(object):
|
||||
sql_function = 'STDDEV_POP'
|
||||
|
||||
try:
|
||||
connection.ops.check_aggregate_support(StdDevPop())
|
||||
except:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
class AggregationTests(TestCase):
|
||||
def assertObjectAttrs(self, obj, **kwargs):
|
||||
for attr, value in kwargs.iteritems():
|
||||
@@ -75,27 +56,27 @@ class AggregationTests(TestCase):
|
||||
qs2 = books.filter(id__in=list(qs))
|
||||
self.assertEqual(list(qs1), list(qs2))
|
||||
|
||||
if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] != 'django.db.backends.oracle':
|
||||
def test_annotate_with_extra(self):
|
||||
"""
|
||||
Regression test for #11916: Extra params + aggregation creates
|
||||
incorrect SQL.
|
||||
"""
|
||||
#oracle doesn't support subqueries in group by clause
|
||||
shortest_book_sql = """
|
||||
SELECT name
|
||||
FROM aggregation_regress_book b
|
||||
WHERE b.publisher_id = aggregation_regress_publisher.id
|
||||
ORDER BY b.pages
|
||||
LIMIT 1
|
||||
"""
|
||||
# tests that this query does not raise a DatabaseError due to the full
|
||||
# subselect being (erroneously) added to the GROUP BY parameters
|
||||
qs = Publisher.objects.extra(select={
|
||||
'name_of_shortest_book': shortest_book_sql,
|
||||
}).annotate(total_books=Count('book'))
|
||||
# force execution of the query
|
||||
list(qs)
|
||||
@skipUnlessDBFeature('supports_subqueries_in_group_by')
|
||||
def test_annotate_with_extra(self):
|
||||
"""
|
||||
Regression test for #11916: Extra params + aggregation creates
|
||||
incorrect SQL.
|
||||
"""
|
||||
#oracle doesn't support subqueries in group by clause
|
||||
shortest_book_sql = """
|
||||
SELECT name
|
||||
FROM aggregation_regress_book b
|
||||
WHERE b.publisher_id = aggregation_regress_publisher.id
|
||||
ORDER BY b.pages
|
||||
LIMIT 1
|
||||
"""
|
||||
# tests that this query does not raise a DatabaseError due to the full
|
||||
# subselect being (erroneously) added to the GROUP BY parameters
|
||||
qs = Publisher.objects.extra(select={
|
||||
'name_of_shortest_book': shortest_book_sql,
|
||||
}).annotate(total_books=Count('book'))
|
||||
# force execution of the query
|
||||
list(qs)
|
||||
|
||||
def test_aggregate(self):
|
||||
# Ordering requests are ignored
|
||||
@@ -641,64 +622,64 @@ class AggregationTests(TestCase):
|
||||
lambda: Book.objects.annotate(mean_age=Avg('authors__age')).annotate(Avg('mean_age'))
|
||||
)
|
||||
|
||||
if run_stddev_tests():
|
||||
def test_stddev(self):
|
||||
self.assertEqual(
|
||||
Book.objects.aggregate(StdDev('pages')),
|
||||
{'pages__stddev': Approximate(311.46, 1)}
|
||||
)
|
||||
@skipUnlessDBFeature('supports_stddev')
|
||||
def test_stddev(self):
|
||||
self.assertEqual(
|
||||
Book.objects.aggregate(StdDev('pages')),
|
||||
{'pages__stddev': Approximate(311.46, 1)}
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
Book.objects.aggregate(StdDev('rating')),
|
||||
{'rating__stddev': Approximate(0.60, 1)}
|
||||
)
|
||||
self.assertEqual(
|
||||
Book.objects.aggregate(StdDev('rating')),
|
||||
{'rating__stddev': Approximate(0.60, 1)}
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
Book.objects.aggregate(StdDev('price')),
|
||||
{'price__stddev': Approximate(24.16, 2)}
|
||||
)
|
||||
self.assertEqual(
|
||||
Book.objects.aggregate(StdDev('price')),
|
||||
{'price__stddev': Approximate(24.16, 2)}
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
Book.objects.aggregate(StdDev('pages', sample=True)),
|
||||
{'pages__stddev': Approximate(341.19, 2)}
|
||||
)
|
||||
self.assertEqual(
|
||||
Book.objects.aggregate(StdDev('pages', sample=True)),
|
||||
{'pages__stddev': Approximate(341.19, 2)}
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
Book.objects.aggregate(StdDev('rating', sample=True)),
|
||||
{'rating__stddev': Approximate(0.66, 2)}
|
||||
)
|
||||
self.assertEqual(
|
||||
Book.objects.aggregate(StdDev('rating', sample=True)),
|
||||
{'rating__stddev': Approximate(0.66, 2)}
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
Book.objects.aggregate(StdDev('price', sample=True)),
|
||||
{'price__stddev': Approximate(26.46, 1)}
|
||||
)
|
||||
self.assertEqual(
|
||||
Book.objects.aggregate(StdDev('price', sample=True)),
|
||||
{'price__stddev': Approximate(26.46, 1)}
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
Book.objects.aggregate(Variance('pages')),
|
||||
{'pages__variance': Approximate(97010.80, 1)}
|
||||
)
|
||||
self.assertEqual(
|
||||
Book.objects.aggregate(Variance('pages')),
|
||||
{'pages__variance': Approximate(97010.80, 1)}
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
Book.objects.aggregate(Variance('rating')),
|
||||
{'rating__variance': Approximate(0.36, 1)}
|
||||
)
|
||||
self.assertEqual(
|
||||
Book.objects.aggregate(Variance('rating')),
|
||||
{'rating__variance': Approximate(0.36, 1)}
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
Book.objects.aggregate(Variance('price')),
|
||||
{'price__variance': Approximate(583.77, 1)}
|
||||
)
|
||||
self.assertEqual(
|
||||
Book.objects.aggregate(Variance('price')),
|
||||
{'price__variance': Approximate(583.77, 1)}
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
Book.objects.aggregate(Variance('pages', sample=True)),
|
||||
{'pages__variance': Approximate(116412.96, 1)}
|
||||
)
|
||||
self.assertEqual(
|
||||
Book.objects.aggregate(Variance('pages', sample=True)),
|
||||
{'pages__variance': Approximate(116412.96, 1)}
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
Book.objects.aggregate(Variance('rating', sample=True)),
|
||||
{'rating__variance': Approximate(0.44, 2)}
|
||||
)
|
||||
self.assertEqual(
|
||||
Book.objects.aggregate(Variance('rating', sample=True)),
|
||||
{'rating__variance': Approximate(0.44, 2)}
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
Book.objects.aggregate(Variance('price', sample=True)),
|
||||
{'price__variance': Approximate(700.53, 2)}
|
||||
)
|
||||
self.assertEqual(
|
||||
Book.objects.aggregate(Variance('price', sample=True)),
|
||||
{'price__variance': Approximate(700.53, 2)}
|
||||
)
|
||||
|
||||
@@ -2,10 +2,10 @@ import copy
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from unittest import TestCase
|
||||
|
||||
from django.conf import Settings
|
||||
from django.db.models.loading import cache, load_app
|
||||
from django.utils.unittest import TestCase
|
||||
|
||||
__test__ = {"API_TESTS": """
|
||||
Test the globbing of INSTALLED_APPS.
|
||||
|
||||
@@ -28,7 +28,7 @@ class SchoolClass(models.Model):
|
||||
|
||||
# Unfortunately, the following model breaks MySQL hard.
|
||||
# Until #13711 is fixed, this test can't be run under MySQL.
|
||||
if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] != 'django.db.backends.mysql':
|
||||
if connection.features.supports_long_model_names:
|
||||
class VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ(models.Model):
|
||||
class Meta:
|
||||
# We need to use a short actual table name or
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Unit and doctests for specific database backends.
|
||||
import datetime
|
||||
import unittest
|
||||
|
||||
from django.conf import settings
|
||||
from django.core import management
|
||||
@@ -9,48 +8,46 @@ from django.core.management.color import no_style
|
||||
from django.db import backend, connection, connections, DEFAULT_DB_ALIAS
|
||||
from django.db.backends.signals import connection_created
|
||||
from django.db.backends.postgresql import version as pg_version
|
||||
from django.test import TestCase
|
||||
from django.test import TestCase, skipUnlessDBFeature
|
||||
from django.utils import unittest
|
||||
|
||||
from regressiontests.backends import models
|
||||
|
||||
class Callproc(unittest.TestCase):
|
||||
class OracleChecks(unittest.TestCase):
|
||||
|
||||
@unittest.skipUnless(connection.vendor == 'oracle',
|
||||
"No need to check Oracle cursor semantics")
|
||||
def test_dbms_session(self):
|
||||
# If the backend is Oracle, test that we can call a standard
|
||||
# stored procedure through our cursor wrapper.
|
||||
if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] == 'django.db.backends.oracle':
|
||||
convert_unicode = backend.convert_unicode
|
||||
cursor = connection.cursor()
|
||||
cursor.callproc(convert_unicode('DBMS_SESSION.SET_IDENTIFIER'),
|
||||
[convert_unicode('_django_testing!'),])
|
||||
return True
|
||||
else:
|
||||
return True
|
||||
convert_unicode = backend.convert_unicode
|
||||
cursor = connection.cursor()
|
||||
cursor.callproc(convert_unicode('DBMS_SESSION.SET_IDENTIFIER'),
|
||||
[convert_unicode('_django_testing!'),])
|
||||
|
||||
@unittest.skipUnless(connection.vendor == 'oracle',
|
||||
"No need to check Oracle cursor semantics")
|
||||
def test_cursor_var(self):
|
||||
# If the backend is Oracle, test that we can pass cursor variables
|
||||
# as query parameters.
|
||||
if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] == 'django.db.backends.oracle':
|
||||
cursor = connection.cursor()
|
||||
var = cursor.var(backend.Database.STRING)
|
||||
cursor.execute("BEGIN %s := 'X'; END; ", [var])
|
||||
self.assertEqual(var.getvalue(), 'X')
|
||||
|
||||
|
||||
class LongString(unittest.TestCase):
|
||||
cursor = connection.cursor()
|
||||
var = cursor.var(backend.Database.STRING)
|
||||
cursor.execute("BEGIN %s := 'X'; END; ", [var])
|
||||
self.assertEqual(var.getvalue(), 'X')
|
||||
|
||||
@unittest.skipUnless(connection.vendor == 'oracle',
|
||||
"No need to check Oracle cursor semantics")
|
||||
def test_long_string(self):
|
||||
# If the backend is Oracle, test that we can save a text longer
|
||||
# than 4000 chars and read it properly
|
||||
if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] == 'django.db.backends.oracle':
|
||||
c = connection.cursor()
|
||||
c.execute('CREATE TABLE ltext ("TEXT" NCLOB)')
|
||||
long_str = ''.join([unicode(x) for x in xrange(4000)])
|
||||
c.execute('INSERT INTO ltext VALUES (%s)',[long_str])
|
||||
c.execute('SELECT text FROM ltext')
|
||||
row = c.fetchone()
|
||||
self.assertEquals(long_str, row[0].read())
|
||||
c.execute('DROP TABLE ltext')
|
||||
c = connection.cursor()
|
||||
c.execute('CREATE TABLE ltext ("TEXT" NCLOB)')
|
||||
long_str = ''.join([unicode(x) for x in xrange(4000)])
|
||||
c.execute('INSERT INTO ltext VALUES (%s)',[long_str])
|
||||
c.execute('SELECT text FROM ltext')
|
||||
row = c.fetchone()
|
||||
self.assertEqual(long_str, row[0].read())
|
||||
c.execute('DROP TABLE ltext')
|
||||
|
||||
class DateQuotingTest(TestCase):
|
||||
|
||||
@@ -97,46 +94,48 @@ class ParameterHandlingTest(TestCase):
|
||||
# Unfortunately, the following tests would be a good test to run on all
|
||||
# backends, but it breaks MySQL hard. Until #13711 is fixed, it can't be run
|
||||
# everywhere (although it would be an effective test of #13711).
|
||||
if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] != 'django.db.backends.mysql':
|
||||
class LongNameTest(TestCase):
|
||||
"""Long primary keys and model names can result in a sequence name
|
||||
that exceeds the database limits, which will result in truncation
|
||||
on certain databases (e.g., Postgres). The backend needs to use
|
||||
the correct sequence name in last_insert_id and other places, so
|
||||
check it is. Refs #8901.
|
||||
"""
|
||||
class LongNameTest(TestCase):
|
||||
"""Long primary keys and model names can result in a sequence name
|
||||
that exceeds the database limits, which will result in truncation
|
||||
on certain databases (e.g., Postgres). The backend needs to use
|
||||
the correct sequence name in last_insert_id and other places, so
|
||||
check it is. Refs #8901.
|
||||
"""
|
||||
|
||||
def test_sequence_name_length_limits_create(self):
|
||||
"""Test creation of model with long name and long pk name doesn't error. Ref #8901"""
|
||||
models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create()
|
||||
@skipUnlessDBFeature('supports_long_model_names')
|
||||
def test_sequence_name_length_limits_create(self):
|
||||
"""Test creation of model with long name and long pk name doesn't error. Ref #8901"""
|
||||
models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create()
|
||||
|
||||
def test_sequence_name_length_limits_m2m(self):
|
||||
"""Test an m2m save of a model with a long name and a long m2m field name doesn't error as on Django >=1.2 this now uses object saves. Ref #8901"""
|
||||
obj = models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create()
|
||||
rel_obj = models.Person.objects.create(first_name='Django', last_name='Reinhardt')
|
||||
obj.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.add(rel_obj)
|
||||
@skipUnlessDBFeature('supports_long_model_names')
|
||||
def test_sequence_name_length_limits_m2m(self):
|
||||
"""Test an m2m save of a model with a long name and a long m2m field name doesn't error as on Django >=1.2 this now uses object saves. Ref #8901"""
|
||||
obj = models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create()
|
||||
rel_obj = models.Person.objects.create(first_name='Django', last_name='Reinhardt')
|
||||
obj.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.add(rel_obj)
|
||||
|
||||
def test_sequence_name_length_limits_flush(self):
|
||||
"""Test that sequence resetting as part of a flush with model with long name and long pk name doesn't error. Ref #8901"""
|
||||
# A full flush is expensive to the full test, so we dig into the
|
||||
# internals to generate the likely offending SQL and run it manually
|
||||
@skipUnlessDBFeature('supports_long_model_names')
|
||||
def test_sequence_name_length_limits_flush(self):
|
||||
"""Test that sequence resetting as part of a flush with model with long name and long pk name doesn't error. Ref #8901"""
|
||||
# A full flush is expensive to the full test, so we dig into the
|
||||
# internals to generate the likely offending SQL and run it manually
|
||||
|
||||
# Some convenience aliases
|
||||
VLM = models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
|
||||
VLM_m2m = VLM.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.through
|
||||
tables = [
|
||||
VLM._meta.db_table,
|
||||
VLM_m2m._meta.db_table,
|
||||
]
|
||||
sequences = [
|
||||
{
|
||||
'column': VLM._meta.pk.column,
|
||||
'table': VLM._meta.db_table
|
||||
},
|
||||
]
|
||||
cursor = connection.cursor()
|
||||
for statement in connection.ops.sql_flush(no_style(), tables, sequences):
|
||||
cursor.execute(statement)
|
||||
# Some convenience aliases
|
||||
VLM = models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
|
||||
VLM_m2m = VLM.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.through
|
||||
tables = [
|
||||
VLM._meta.db_table,
|
||||
VLM_m2m._meta.db_table,
|
||||
]
|
||||
sequences = [
|
||||
{
|
||||
'column': VLM._meta.pk.column,
|
||||
'table': VLM._meta.db_table
|
||||
},
|
||||
]
|
||||
cursor = connection.cursor()
|
||||
for statement in connection.ops.sql_flush(no_style(), tables, sequences):
|
||||
cursor.execute(statement)
|
||||
|
||||
class SequenceResetTest(TestCase):
|
||||
def test_generic_relation(self):
|
||||
@@ -170,22 +169,22 @@ class PostgresVersionTest(TestCase):
|
||||
# Unfortunately with sqlite3 the in-memory test database cannot be
|
||||
# closed, and so it cannot be re-opened during testing, and so we
|
||||
# sadly disable this test for now.
|
||||
if settings.DATABASES[DEFAULT_DB_ALIAS]["ENGINE"] != "django.db.backends.sqlite3":
|
||||
class ConnectionCreatedSignalTest(TestCase):
|
||||
def test_signal(self):
|
||||
data = {}
|
||||
def receiver(sender, connection, **kwargs):
|
||||
data["connection"] = connection
|
||||
class ConnectionCreatedSignalTest(TestCase):
|
||||
@skipUnlessDBFeature('test_db_allows_multiple_connections')
|
||||
def test_signal(self):
|
||||
data = {}
|
||||
def receiver(sender, connection, **kwargs):
|
||||
data["connection"] = connection
|
||||
|
||||
connection_created.connect(receiver)
|
||||
connection.close()
|
||||
cursor = connection.cursor()
|
||||
self.assertTrue(data["connection"] is connection)
|
||||
connection_created.connect(receiver)
|
||||
connection.close()
|
||||
cursor = connection.cursor()
|
||||
self.assertTrue(data["connection"] is connection)
|
||||
|
||||
connection_created.disconnect(receiver)
|
||||
data.clear()
|
||||
cursor = connection.cursor()
|
||||
self.assertTrue(data == {})
|
||||
connection_created.disconnect(receiver)
|
||||
data.clear()
|
||||
cursor = connection.cursor()
|
||||
self.assertTrue(data == {})
|
||||
|
||||
|
||||
class BackendTestCase(TestCase):
|
||||
@@ -225,3 +224,4 @@ class BackendTestCase(TestCase):
|
||||
self.assertEqual(cursor.fetchone(), (u'Clark', u'Kent'))
|
||||
self.assertEqual(list(cursor.fetchmany(2)), [(u'Jane', u'Doe'), (u'John', u'Doe')])
|
||||
self.assertEqual(list(cursor.fetchall()), [(u'Mary', u'Agnelline'), (u'Peter', u'Parker')])
|
||||
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
A series of tests to establish that the command-line bash completion works.
|
||||
"""
|
||||
import os
|
||||
import unittest
|
||||
import sys
|
||||
import StringIO
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.management import ManagementUtility
|
||||
from django.utils import unittest
|
||||
|
||||
class BashCompletionTests(unittest.TestCase):
|
||||
"""
|
||||
|
||||
@@ -6,9 +6,10 @@ ModelForm's save() method causes Model.save() to be called more than once.
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import unittest
|
||||
|
||||
from django.core.files.uploadedfile import SimpleUploadedFile
|
||||
from django.utils import unittest
|
||||
|
||||
from regressiontests.bug639.models import Photo, PhotoForm, temp_storage_dir
|
||||
|
||||
class Bug639Test(unittest.TestCase):
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
from unittest import TestCase
|
||||
|
||||
from django.contrib import admin
|
||||
from django.utils.unittest import TestCase
|
||||
|
||||
|
||||
class Bug8245Test(TestCase):
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from unittest import TestCase
|
||||
from StringIO import StringIO
|
||||
|
||||
from django.core.servers.basehttp import ServerHandler
|
||||
from django.utils.unittest import TestCase
|
||||
|
||||
#
|
||||
# Tests for #9659: wsgi.file_wrapper in the builtin server.
|
||||
|
||||
3
tests/regressiontests/cache/tests.py
vendored
3
tests/regressiontests/cache/tests.py
vendored
@@ -7,7 +7,6 @@ import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
import warnings
|
||||
|
||||
from django.conf import settings
|
||||
@@ -17,6 +16,7 @@ from django.core.cache.backends.base import InvalidCacheBackendError, CacheKeyWa
|
||||
from django.http import HttpResponse, HttpRequest
|
||||
from django.middleware.cache import FetchFromCacheMiddleware, UpdateCacheMiddleware
|
||||
from django.utils import translation
|
||||
from django.utils import unittest
|
||||
from django.utils.cache import patch_vary_headers, get_cache_key, learn_cache_key
|
||||
from django.utils.hashcompat import md5_constructor
|
||||
from regressiontests.cache.models import Poll, expensive_calculation
|
||||
@@ -393,6 +393,7 @@ class BaseCacheTests(object):
|
||||
# runner doesn't add any global warning filters (it currently
|
||||
# does not).
|
||||
warnings.resetwarnings()
|
||||
warnings.simplefilter("ignore", PendingDeprecationWarning)
|
||||
|
||||
class DBCacheTests(unittest.TestCase, BaseCacheTests):
|
||||
def setUp(self):
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import datetime
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import DEFAULT_DB_ALIAS
|
||||
from django.test import TestCase
|
||||
from django.test import TestCase, skipIfDBFeature
|
||||
from django.utils import tzinfo
|
||||
|
||||
from models import Donut, RumBaba
|
||||
from django.conf import settings
|
||||
|
||||
class DataTypesTestCase(TestCase):
|
||||
|
||||
@@ -73,14 +74,14 @@ class DataTypesTestCase(TestCase):
|
||||
newd = Donut.objects.get(id=d.id)
|
||||
self.assert_(isinstance(newd.review, unicode))
|
||||
|
||||
def test_tz_awareness_mysql(self):
|
||||
@skipIfDBFeature('supports_timezones')
|
||||
def test_error_on_timezone(self):
|
||||
"""Regression test for #8354: the MySQL backend should raise an error
|
||||
if given a timezone-aware datetime object."""
|
||||
if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] == 'django.db.backends.mysql':
|
||||
dt = datetime.datetime(2008, 8, 31, 16, 20, tzinfo=tzinfo.FixedOffset(0))
|
||||
d = Donut(name='Bear claw', consumed_at=dt)
|
||||
self.assertRaises(ValueError, d.save)
|
||||
# ValueError: MySQL backend does not support timezone-aware datetimes.
|
||||
dt = datetime.datetime(2008, 8, 31, 16, 20, tzinfo=tzinfo.FixedOffset(0))
|
||||
d = Donut(name='Bear claw', consumed_at=dt)
|
||||
self.assertRaises(ValueError, d.save)
|
||||
# ValueError: MySQL backend does not support timezone-aware datetimes.
|
||||
|
||||
def test_datefield_auto_now_add(self):
|
||||
"""Regression test for #10970, auto_now_add for DateField should store
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
from unittest import TestCase
|
||||
from sys import version_info
|
||||
try:
|
||||
from functools import wraps
|
||||
except ImportError:
|
||||
from django.utils.functional import wraps # Python 2.4 fallback.
|
||||
|
||||
from django.contrib.auth.decorators import login_required, permission_required, user_passes_test
|
||||
from django.contrib.admin.views.decorators import staff_member_required
|
||||
from django.http import HttpResponse, HttpRequest
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.utils.functional import allow_lazy, lazy, memoize
|
||||
from django.utils.unittest import TestCase
|
||||
from django.views.decorators.http import require_http_methods, require_GET, require_POST
|
||||
from django.views.decorators.vary import vary_on_headers, vary_on_cookie
|
||||
from django.views.decorators.cache import cache_page, never_cache, cache_control
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.contrib.auth.decorators import login_required, permission_required, user_passes_test
|
||||
from django.contrib.admin.views.decorators import staff_member_required
|
||||
|
||||
|
||||
def fully_decorated(request):
|
||||
"""Expected __doc__"""
|
||||
@@ -70,25 +71,25 @@ class DecoratorsTest(TestCase):
|
||||
def test1(user):
|
||||
user.decorators_applied.append('test1')
|
||||
return True
|
||||
|
||||
|
||||
def test2(user):
|
||||
user.decorators_applied.append('test2')
|
||||
return True
|
||||
|
||||
|
||||
def callback(request):
|
||||
return request.user.decorators_applied
|
||||
|
||||
callback = user_passes_test(test1)(callback)
|
||||
callback = user_passes_test(test2)(callback)
|
||||
|
||||
|
||||
class DummyUser(object): pass
|
||||
class DummyRequest(object): pass
|
||||
|
||||
|
||||
request = DummyRequest()
|
||||
request.user = DummyUser()
|
||||
request.user.decorators_applied = []
|
||||
response = callback(request)
|
||||
|
||||
|
||||
self.assertEqual(response, ['test2', 'test1'])
|
||||
|
||||
def test_cache_page_new_style(self):
|
||||
|
||||
@@ -2,64 +2,65 @@ import datetime
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import backend, connection, transaction, DEFAULT_DB_ALIAS
|
||||
from django.test import TestCase, TransactionTestCase
|
||||
from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature
|
||||
|
||||
from models import Book, Award, AwardNote, Person, Child, Toy, PlayedWith, PlayedWithNote
|
||||
|
||||
|
||||
# Can't run this test under SQLite, because you can't
|
||||
# get two connections to an in-memory database.
|
||||
if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] != 'django.db.backends.sqlite3':
|
||||
class DeleteLockingTest(TransactionTestCase):
|
||||
def setUp(self):
|
||||
# Create a second connection to the default database
|
||||
conn_settings = settings.DATABASES[DEFAULT_DB_ALIAS]
|
||||
self.conn2 = backend.DatabaseWrapper({
|
||||
'HOST': conn_settings['HOST'],
|
||||
'NAME': conn_settings['NAME'],
|
||||
'OPTIONS': conn_settings['OPTIONS'],
|
||||
'PASSWORD': conn_settings['PASSWORD'],
|
||||
'PORT': conn_settings['PORT'],
|
||||
'USER': conn_settings['USER'],
|
||||
'TIME_ZONE': settings.TIME_ZONE,
|
||||
})
|
||||
class DeleteLockingTest(TransactionTestCase):
|
||||
def setUp(self):
|
||||
# Create a second connection to the default database
|
||||
conn_settings = settings.DATABASES[DEFAULT_DB_ALIAS]
|
||||
self.conn2 = backend.DatabaseWrapper({
|
||||
'HOST': conn_settings['HOST'],
|
||||
'NAME': conn_settings['NAME'],
|
||||
'OPTIONS': conn_settings['OPTIONS'],
|
||||
'PASSWORD': conn_settings['PASSWORD'],
|
||||
'PORT': conn_settings['PORT'],
|
||||
'USER': conn_settings['USER'],
|
||||
'TIME_ZONE': settings.TIME_ZONE,
|
||||
})
|
||||
|
||||
# Put both DB connections into managed transaction mode
|
||||
transaction.enter_transaction_management()
|
||||
transaction.managed(True)
|
||||
self.conn2._enter_transaction_management(True)
|
||||
# Put both DB connections into managed transaction mode
|
||||
transaction.enter_transaction_management()
|
||||
transaction.managed(True)
|
||||
self.conn2._enter_transaction_management(True)
|
||||
|
||||
def tearDown(self):
|
||||
# Close down the second connection.
|
||||
transaction.leave_transaction_management()
|
||||
self.conn2.close()
|
||||
def tearDown(self):
|
||||
# Close down the second connection.
|
||||
transaction.leave_transaction_management()
|
||||
self.conn2.close()
|
||||
|
||||
def test_concurrent_delete(self):
|
||||
"Deletes on concurrent transactions don't collide and lock the database. Regression for #9479"
|
||||
@skipUnlessDBFeature('test_db_allows_multiple_connections')
|
||||
def test_concurrent_delete(self):
|
||||
"Deletes on concurrent transactions don't collide and lock the database. Regression for #9479"
|
||||
|
||||
# Create some dummy data
|
||||
b1 = Book(id=1, pagecount=100)
|
||||
b2 = Book(id=2, pagecount=200)
|
||||
b3 = Book(id=3, pagecount=300)
|
||||
b1.save()
|
||||
b2.save()
|
||||
b3.save()
|
||||
# Create some dummy data
|
||||
b1 = Book(id=1, pagecount=100)
|
||||
b2 = Book(id=2, pagecount=200)
|
||||
b3 = Book(id=3, pagecount=300)
|
||||
b1.save()
|
||||
b2.save()
|
||||
b3.save()
|
||||
|
||||
transaction.commit()
|
||||
transaction.commit()
|
||||
|
||||
self.assertEquals(3, Book.objects.count())
|
||||
self.assertEqual(3, Book.objects.count())
|
||||
|
||||
# Delete something using connection 2.
|
||||
cursor2 = self.conn2.cursor()
|
||||
cursor2.execute('DELETE from delete_regress_book WHERE id=1')
|
||||
self.conn2._commit();
|
||||
# Delete something using connection 2.
|
||||
cursor2 = self.conn2.cursor()
|
||||
cursor2.execute('DELETE from delete_regress_book WHERE id=1')
|
||||
self.conn2._commit();
|
||||
|
||||
# Now perform a queryset delete that covers the object
|
||||
# deleted in connection 2. This causes an infinite loop
|
||||
# under MySQL InnoDB unless we keep track of already
|
||||
# deleted objects.
|
||||
Book.objects.filter(pagecount__lt=250).delete()
|
||||
transaction.commit()
|
||||
self.assertEquals(1, Book.objects.count())
|
||||
# Now perform a queryset delete that covers the object
|
||||
# deleted in connection 2. This causes an infinite loop
|
||||
# under MySQL InnoDB unless we keep track of already
|
||||
# deleted objects.
|
||||
Book.objects.filter(pagecount__lt=250).delete()
|
||||
transaction.commit()
|
||||
self.assertEqual(1, Book.objects.count())
|
||||
|
||||
class DeleteCascadeTests(TestCase):
|
||||
def test_generic_relation_cascade(self):
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
from django.dispatch import Signal
|
||||
import unittest
|
||||
import sys
|
||||
import gc
|
||||
import sys
|
||||
|
||||
from django.dispatch import Signal
|
||||
from django.utils import unittest
|
||||
import django.utils.copycompat as copy
|
||||
|
||||
if sys.platform.startswith('java'):
|
||||
@@ -20,7 +21,7 @@ def receiver_1_arg(val, **kwargs):
|
||||
class Callable(object):
|
||||
def __call__(self, val, **kwargs):
|
||||
return val
|
||||
|
||||
|
||||
def a(self, val, **kwargs):
|
||||
return val
|
||||
|
||||
@@ -35,7 +36,7 @@ class DispatcherTests(unittest.TestCase):
|
||||
|
||||
# force cleanup just in case
|
||||
signal.receivers = []
|
||||
|
||||
|
||||
def testExact(self):
|
||||
a_signal.connect(receiver_1_arg, sender=self)
|
||||
expected = [(receiver_1_arg,"test")]
|
||||
@@ -51,7 +52,7 @@ class DispatcherTests(unittest.TestCase):
|
||||
self.assertEqual(result, expected)
|
||||
a_signal.disconnect(receiver_1_arg)
|
||||
self._testIsClean(a_signal)
|
||||
|
||||
|
||||
def testGarbageCollected(self):
|
||||
a = Callable()
|
||||
a_signal.connect(a.a, sender=self)
|
||||
@@ -61,7 +62,7 @@ class DispatcherTests(unittest.TestCase):
|
||||
result = a_signal.send(sender=self, val="test")
|
||||
self.assertEqual(result, expected)
|
||||
self._testIsClean(a_signal)
|
||||
|
||||
|
||||
def testMultipleRegistration(self):
|
||||
a = Callable()
|
||||
a_signal.connect(a)
|
||||
@@ -90,7 +91,7 @@ class DispatcherTests(unittest.TestCase):
|
||||
self.assertEqual(len(a_signal.receivers), 1)
|
||||
a_signal.disconnect(dispatch_uid = "uid")
|
||||
self._testIsClean(a_signal)
|
||||
|
||||
|
||||
def testRobust(self):
|
||||
"""Test the sendRobust function"""
|
||||
def fails(val, **kwargs):
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from django.dispatch.saferef import *
|
||||
|
||||
import unittest
|
||||
from django.utils import unittest
|
||||
|
||||
class Test1(object):
|
||||
def x(self):
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
"""
|
||||
Spanning tests for all the operations that F() expressions can perform.
|
||||
"""
|
||||
from django.test import TestCase, Approximate
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import models, DEFAULT_DB_ALIAS
|
||||
from django.db.models import F
|
||||
from django.test import TestCase, Approximate, skipUnlessDBFeature
|
||||
|
||||
from regressiontests.expressions_regress.models import Number
|
||||
|
||||
|
||||
class ExpressionsRegressTests(TestCase):
|
||||
|
||||
def setUp(self):
|
||||
@@ -130,13 +130,13 @@ class ExpressionOperatorTests(TestCase):
|
||||
self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 40)
|
||||
self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(15.500, places=3))
|
||||
|
||||
if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] != 'django.db.backends.oracle':
|
||||
def test_lefthand_bitwise_or(self):
|
||||
# LH Bitwise or on integers
|
||||
Number.objects.filter(pk=self.n.pk).update(integer=F('integer') | 48)
|
||||
@skipUnlessDBFeature('supports_bitwise_or')
|
||||
def test_lefthand_bitwise_or(self):
|
||||
# LH Bitwise or on integers
|
||||
Number.objects.filter(pk=self.n.pk).update(integer=F('integer') | 48)
|
||||
|
||||
self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 58)
|
||||
self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(15.500, places=3))
|
||||
self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 58)
|
||||
self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(15.500, places=3))
|
||||
|
||||
def test_right_hand_addition(self):
|
||||
# Right hand operators
|
||||
@@ -185,11 +185,11 @@ class ExpressionOperatorTests(TestCase):
|
||||
self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 10)
|
||||
self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(15.500, places=3))
|
||||
|
||||
if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] != 'django.db.backends.oracle':
|
||||
def test_right_hand_bitwise_or(self):
|
||||
# RH Bitwise or on integers
|
||||
Number.objects.filter(pk=self.n.pk).update(integer=15 | F('integer'))
|
||||
@skipUnlessDBFeature('supports_bitwise_or')
|
||||
def test_right_hand_bitwise_or(self):
|
||||
# RH Bitwise or on integers
|
||||
Number.objects.filter(pk=self.n.pk).update(integer=15 | F('integer'))
|
||||
|
||||
self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 47)
|
||||
self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(15.500, places=3))
|
||||
self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 47)
|
||||
self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(15.500, places=3))
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from cStringIO import StringIO
|
||||
from datetime import datetime, timedelta
|
||||
from django.conf import settings
|
||||
@@ -14,7 +13,8 @@ from django.core.files.images import get_image_dimensions
|
||||
from django.core.files.storage import FileSystemStorage, get_storage_class
|
||||
from django.core.files.uploadedfile import UploadedFile
|
||||
from django.core.exceptions import ImproperlyConfigured
|
||||
from unittest import TestCase
|
||||
from django.utils import unittest
|
||||
|
||||
try:
|
||||
import threading
|
||||
except ImportError:
|
||||
@@ -294,7 +294,7 @@ class SlowFile(ContentFile):
|
||||
time.sleep(1)
|
||||
return super(ContentFile, self).chunks()
|
||||
|
||||
class FileSaveRaceConditionTest(TestCase):
|
||||
class FileSaveRaceConditionTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.storage_dir = tempfile.mkdtemp()
|
||||
self.storage = FileSystemStorage(self.storage_dir)
|
||||
@@ -315,7 +315,7 @@ class FileSaveRaceConditionTest(TestCase):
|
||||
self.storage.delete('conflict')
|
||||
self.storage.delete('conflict_1')
|
||||
|
||||
class FileStoragePermissions(TestCase):
|
||||
class FileStoragePermissions(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.old_perms = settings.FILE_UPLOAD_PERMISSIONS
|
||||
settings.FILE_UPLOAD_PERMISSIONS = 0666
|
||||
@@ -332,7 +332,7 @@ class FileStoragePermissions(TestCase):
|
||||
self.assertEqual(actual_mode, 0666)
|
||||
|
||||
|
||||
class FileStoragePathParsing(TestCase):
|
||||
class FileStoragePathParsing(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.storage_dir = tempfile.mkdtemp()
|
||||
self.storage = FileSystemStorage(self.storage_dir)
|
||||
@@ -370,64 +370,67 @@ class FileStoragePathParsing(TestCase):
|
||||
else:
|
||||
self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test_1')))
|
||||
|
||||
if Image is not None:
|
||||
class DimensionClosingBug(TestCase):
|
||||
class DimensionClosingBug(unittest.TestCase):
|
||||
"""
|
||||
Test that get_image_dimensions() properly closes files (#8817)
|
||||
"""
|
||||
@unittest.skipUnless(Image, "PIL not installed")
|
||||
def test_not_closing_of_files(self):
|
||||
"""
|
||||
Test that get_image_dimensions() properly closes files (#8817)
|
||||
Open files passed into get_image_dimensions() should stay opened.
|
||||
"""
|
||||
def test_not_closing_of_files(self):
|
||||
"""
|
||||
Open files passed into get_image_dimensions() should stay opened.
|
||||
"""
|
||||
empty_io = StringIO()
|
||||
try:
|
||||
get_image_dimensions(empty_io)
|
||||
finally:
|
||||
self.assert_(not empty_io.closed)
|
||||
empty_io = StringIO()
|
||||
try:
|
||||
get_image_dimensions(empty_io)
|
||||
finally:
|
||||
self.assert_(not empty_io.closed)
|
||||
|
||||
def test_closing_of_filenames(self):
|
||||
"""
|
||||
get_image_dimensions() called with a filename should closed the file.
|
||||
"""
|
||||
# We need to inject a modified open() builtin into the images module
|
||||
# that checks if the file was closed properly if the function is
|
||||
# called with a filename instead of an file object.
|
||||
# get_image_dimensions will call our catching_open instead of the
|
||||
# regular builtin one.
|
||||
|
||||
class FileWrapper(object):
|
||||
_closed = []
|
||||
def __init__(self, f):
|
||||
self.f = f
|
||||
def __getattr__(self, name):
|
||||
return getattr(self.f, name)
|
||||
def close(self):
|
||||
self._closed.append(True)
|
||||
self.f.close()
|
||||
|
||||
def catching_open(*args):
|
||||
return FileWrapper(open(*args))
|
||||
|
||||
from django.core.files import images
|
||||
images.open = catching_open
|
||||
try:
|
||||
get_image_dimensions(os.path.join(os.path.dirname(__file__), "test1.png"))
|
||||
finally:
|
||||
del images.open
|
||||
self.assert_(FileWrapper._closed)
|
||||
|
||||
class InconsistentGetImageDimensionsBug(TestCase):
|
||||
@unittest.skipUnless(Image, "PIL not installed")
|
||||
def test_closing_of_filenames(self):
|
||||
"""
|
||||
Test that get_image_dimensions() works properly after various calls using a file handler (#11158)
|
||||
get_image_dimensions() called with a filename should closed the file.
|
||||
"""
|
||||
def test_multiple_calls(self):
|
||||
"""
|
||||
Multiple calls of get_image_dimensions() should return the same size.
|
||||
"""
|
||||
from django.core.files.images import ImageFile
|
||||
img_path = os.path.join(os.path.dirname(__file__), "test.png")
|
||||
image = ImageFile(open(img_path, 'rb'))
|
||||
image_pil = Image.open(img_path)
|
||||
size_1, size_2 = get_image_dimensions(image), get_image_dimensions(image)
|
||||
self.assertEqual(image_pil.size, size_1)
|
||||
self.assertEqual(size_1, size_2)
|
||||
# We need to inject a modified open() builtin into the images module
|
||||
# that checks if the file was closed properly if the function is
|
||||
# called with a filename instead of an file object.
|
||||
# get_image_dimensions will call our catching_open instead of the
|
||||
# regular builtin one.
|
||||
|
||||
class FileWrapper(object):
|
||||
_closed = []
|
||||
def __init__(self, f):
|
||||
self.f = f
|
||||
def __getattr__(self, name):
|
||||
return getattr(self.f, name)
|
||||
def close(self):
|
||||
self._closed.append(True)
|
||||
self.f.close()
|
||||
|
||||
def catching_open(*args):
|
||||
return FileWrapper(open(*args))
|
||||
|
||||
from django.core.files import images
|
||||
images.open = catching_open
|
||||
try:
|
||||
get_image_dimensions(os.path.join(os.path.dirname(__file__), "test1.png"))
|
||||
finally:
|
||||
del images.open
|
||||
self.assert_(FileWrapper._closed)
|
||||
|
||||
class InconsistentGetImageDimensionsBug(unittest.TestCase):
|
||||
"""
|
||||
Test that get_image_dimensions() works properly after various calls
|
||||
using a file handler (#11158)
|
||||
"""
|
||||
@unittest.skipUnless(Image, "PIL not installed")
|
||||
def test_multiple_calls(self):
|
||||
"""
|
||||
Multiple calls of get_image_dimensions() should return the same size.
|
||||
"""
|
||||
from django.core.files.images import ImageFile
|
||||
img_path = os.path.join(os.path.dirname(__file__), "test.png")
|
||||
image = ImageFile(open(img_path, 'rb'))
|
||||
image_pil = Image.open(img_path)
|
||||
size_1, size_2 = get_image_dimensions(image), get_image_dimensions(image)
|
||||
self.assertEqual(image_pil.size, size_1)
|
||||
self.assertEqual(size_1, size_2)
|
||||
|
||||
@@ -2,15 +2,15 @@
|
||||
import os
|
||||
import errno
|
||||
import shutil
|
||||
import unittest
|
||||
from StringIO import StringIO
|
||||
|
||||
from django.core.files import temp as tempfile
|
||||
from django.core.files.uploadedfile import SimpleUploadedFile
|
||||
from django.http.multipartparser import MultiPartParser
|
||||
from django.test import TestCase, client
|
||||
from django.utils import simplejson
|
||||
from django.utils import unittest
|
||||
from django.utils.hashcompat import sha_constructor
|
||||
from django.http.multipartparser import MultiPartParser
|
||||
|
||||
from models import FileModel, temp_storage, UPLOAD_TO
|
||||
import uploadhandler
|
||||
@@ -223,7 +223,7 @@ class FileUploadTests(TestCase):
|
||||
ret = super(POSTAccessingHandler, self).handle_uncaught_exception(request, resolver, exc_info)
|
||||
p = request.POST
|
||||
return ret
|
||||
|
||||
|
||||
post_data = {
|
||||
'name': 'Ringo',
|
||||
'file_field': open(__file__),
|
||||
@@ -244,7 +244,7 @@ class FileUploadTests(TestCase):
|
||||
response = self.client.post('/file_uploads/upload_errors/', post_data)
|
||||
except reference_error.__class__, err:
|
||||
self.failIf(
|
||||
str(err) == str(reference_error),
|
||||
str(err) == str(reference_error),
|
||||
"Caught a repeated exception that'll cause an infinite loop in file uploads."
|
||||
)
|
||||
except Exception, err:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from django.db import models, DEFAULT_DB_ALIAS
|
||||
from django.db import models, DEFAULT_DB_ALIAS, connection
|
||||
from django.contrib.auth.models import User
|
||||
from django.conf import settings
|
||||
|
||||
@@ -31,7 +31,7 @@ class Stuff(models.Model):
|
||||
# Oracle doesn't distinguish between None and the empty string.
|
||||
# This hack makes the test case pass using Oracle.
|
||||
name = self.name
|
||||
if (settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] == 'django.db.backends.oracle'
|
||||
if (connection.features.interprets_empty_strings_as_nulls
|
||||
and name == u''):
|
||||
name = None
|
||||
return unicode(name) + u' is owned by ' + unicode(self.owner)
|
||||
|
||||
@@ -30,11 +30,10 @@ import re
|
||||
import os
|
||||
from decimal import Decimal
|
||||
|
||||
from unittest import TestCase
|
||||
|
||||
from django.core.files.uploadedfile import SimpleUploadedFile
|
||||
from django.forms import *
|
||||
from django.forms.widgets import RadioFieldRenderer
|
||||
from django.utils.unittest import TestCase
|
||||
|
||||
|
||||
def fix_os_paths(x):
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
from datetime import time, date, datetime
|
||||
from unittest import TestCase
|
||||
|
||||
from django import forms
|
||||
from django.conf import settings
|
||||
from django.utils.translation import activate, deactivate
|
||||
from django.utils.unittest import TestCase
|
||||
|
||||
|
||||
class LocalizedTimeTests(TestCase):
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
from unittest import TestCase
|
||||
|
||||
from django import forms
|
||||
from django.core import validators
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.utils.unittest import TestCase
|
||||
|
||||
|
||||
class TestFieldWithValidators(TestCase):
|
||||
|
||||
@@ -1265,10 +1265,9 @@ u'<input type="hidden" name="date_0" value="17.09.2007" /><input type="hidden" n
|
||||
|
||||
"""
|
||||
|
||||
|
||||
from django.utils import copycompat as copy
|
||||
from unittest import TestCase
|
||||
from django import forms
|
||||
from django.utils import copycompat as copy
|
||||
from django.utils.unittest import TestCase
|
||||
from django.core.files.uploadedfile import SimpleUploadedFile
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import copy
|
||||
import pickle
|
||||
import unittest
|
||||
|
||||
from django.http import QueryDict, HttpResponse, CompatCookie, BadHeaderError
|
||||
from django.utils import unittest
|
||||
|
||||
class QueryDictTests(unittest.TestCase):
|
||||
def test_missing_key(self):
|
||||
@@ -17,7 +18,7 @@ class QueryDictTests(unittest.TestCase):
|
||||
self.assertRaises(AttributeError, q.pop, 'foo')
|
||||
self.assertRaises(AttributeError, q.popitem)
|
||||
self.assertRaises(AttributeError, q.clear)
|
||||
|
||||
|
||||
def test_immutable_get_with_default(self):
|
||||
q = QueryDict('')
|
||||
self.assertEqual(q.get('foo', 'default'), 'default')
|
||||
@@ -34,7 +35,7 @@ class QueryDictTests(unittest.TestCase):
|
||||
self.assertEqual(q.values(), [])
|
||||
self.assertEqual(len(q), 0)
|
||||
self.assertEqual(q.urlencode(), '')
|
||||
|
||||
|
||||
def test_single_key_value(self):
|
||||
"""Test QueryDict with one key/value pair"""
|
||||
|
||||
@@ -47,7 +48,7 @@ class QueryDictTests(unittest.TestCase):
|
||||
self.assertEqual(q.get('bar', 'default'), 'default')
|
||||
self.assertEqual(q.getlist('foo'), ['bar'])
|
||||
self.assertEqual(q.getlist('bar'), [])
|
||||
|
||||
|
||||
self.assertRaises(AttributeError, q.setlist, 'foo', ['bar'])
|
||||
self.assertRaises(AttributeError, q.appendlist, 'foo', ['bar'])
|
||||
|
||||
@@ -67,16 +68,16 @@ class QueryDictTests(unittest.TestCase):
|
||||
self.assertRaises(AttributeError, q.popitem)
|
||||
self.assertRaises(AttributeError, q.clear)
|
||||
self.assertRaises(AttributeError, q.setdefault, 'foo', 'bar')
|
||||
|
||||
|
||||
self.assertEqual(q.urlencode(), 'foo=bar')
|
||||
|
||||
|
||||
def test_mutable_copy(self):
|
||||
"""A copy of a QueryDict is mutable."""
|
||||
q = QueryDict('').copy()
|
||||
self.assertRaises(KeyError, q.__getitem__, "foo")
|
||||
q['name'] = 'john'
|
||||
self.assertEqual(q['name'], 'john')
|
||||
|
||||
|
||||
def test_mutable_delete(self):
|
||||
q = QueryDict('').copy()
|
||||
q['name'] = 'john'
|
||||
@@ -126,20 +127,20 @@ class QueryDictTests(unittest.TestCase):
|
||||
"""Test QueryDict with two key/value pairs with same keys."""
|
||||
|
||||
q = QueryDict('vote=yes&vote=no')
|
||||
|
||||
|
||||
self.assertEqual(q['vote'], u'no')
|
||||
self.assertRaises(AttributeError, q.__setitem__, 'something', 'bar')
|
||||
|
||||
|
||||
self.assertEqual(q.get('vote', 'default'), u'no')
|
||||
self.assertEqual(q.get('foo', 'default'), 'default')
|
||||
self.assertEqual(q.getlist('vote'), [u'yes', u'no'])
|
||||
self.assertEqual(q.getlist('foo'), [])
|
||||
|
||||
|
||||
self.assertRaises(AttributeError, q.setlist, 'foo', ['bar', 'baz'])
|
||||
self.assertRaises(AttributeError, q.setlist, 'foo', ['bar', 'baz'])
|
||||
self.assertRaises(AttributeError, q.appendlist, 'foo', ['bar'])
|
||||
|
||||
self.assertEqual(q.has_key('vote'), True)
|
||||
self.assertEqual(q.has_key('vote'), True)
|
||||
self.assertEqual('vote' in q, True)
|
||||
self.assertEqual(q.has_key('foo'), False)
|
||||
self.assertEqual('foo' in q, False)
|
||||
@@ -148,23 +149,23 @@ class QueryDictTests(unittest.TestCase):
|
||||
self.assertEqual(q.keys(), [u'vote'])
|
||||
self.assertEqual(q.values(), [u'no'])
|
||||
self.assertEqual(len(q), 1)
|
||||
|
||||
|
||||
self.assertRaises(AttributeError, q.update, {'foo': 'bar'})
|
||||
self.assertRaises(AttributeError, q.pop, 'foo')
|
||||
self.assertRaises(AttributeError, q.popitem)
|
||||
self.assertRaises(AttributeError, q.clear)
|
||||
self.assertRaises(AttributeError, q.setdefault, 'foo', 'bar')
|
||||
self.assertRaises(AttributeError, q.__delitem__, 'vote')
|
||||
|
||||
|
||||
def test_invalid_input_encoding(self):
|
||||
"""
|
||||
QueryDicts must be able to handle invalid input encoding (in this
|
||||
case, bad UTF-8 encoding).
|
||||
"""
|
||||
q = QueryDict('foo=bar&foo=\xff')
|
||||
self.assertEqual(q['foo'], u'\ufffd')
|
||||
self.assertEqual(q['foo'], u'\ufffd')
|
||||
self.assertEqual(q.getlist('foo'), [u'bar', u'\ufffd'])
|
||||
|
||||
|
||||
def test_pickle(self):
|
||||
q = QueryDict('')
|
||||
q1 = pickle.loads(pickle.dumps(q, 2))
|
||||
@@ -172,7 +173,7 @@ class QueryDictTests(unittest.TestCase):
|
||||
q = QueryDict('a=b&c=d')
|
||||
q1 = pickle.loads(pickle.dumps(q, 2))
|
||||
self.assertEqual(q == q1, True)
|
||||
q = QueryDict('a=b&c=d&a=1')
|
||||
q = QueryDict('a=b&c=d&a=1')
|
||||
q1 = pickle.loads(pickle.dumps(q, 2))
|
||||
self.assertEqual(q == q1 , True)
|
||||
|
||||
@@ -181,21 +182,21 @@ class QueryDictTests(unittest.TestCase):
|
||||
x = QueryDict("a=1&a=2", mutable=True)
|
||||
y = QueryDict("a=3&a=4")
|
||||
x.update(y)
|
||||
self.assertEqual(x.getlist('a'), [u'1', u'2', u'3', u'4'])
|
||||
self.assertEqual(x.getlist('a'), [u'1', u'2', u'3', u'4'])
|
||||
|
||||
def test_non_default_encoding(self):
|
||||
"""#13572 - QueryDict with a non-default encoding"""
|
||||
q = QueryDict('sbb=one', encoding='rot_13')
|
||||
q = QueryDict('sbb=one', encoding='rot_13')
|
||||
self.assertEqual(q.encoding , 'rot_13' )
|
||||
self.assertEqual(q.items() , [(u'foo', u'bar')] )
|
||||
self.assertEqual(q.urlencode() , 'sbb=one' )
|
||||
q = q.copy()
|
||||
q = q.copy()
|
||||
self.assertEqual(q.encoding , 'rot_13' )
|
||||
self.assertEqual(q.items() , [(u'foo', u'bar')] )
|
||||
self.assertEqual(q.urlencode() , 'sbb=one' )
|
||||
self.assertEqual(copy.copy(q).encoding , 'rot_13' )
|
||||
self.assertEqual(copy.deepcopy(q).encoding , 'rot_13')
|
||||
|
||||
|
||||
class HttpResponseTests(unittest.TestCase):
|
||||
def test_unicode_headers(self):
|
||||
r = HttpResponse()
|
||||
@@ -203,10 +204,10 @@ class HttpResponseTests(unittest.TestCase):
|
||||
# If we insert a unicode value it will be converted to an ascii
|
||||
r['value'] = u'test value'
|
||||
self.failUnless(isinstance(r['value'], str))
|
||||
|
||||
|
||||
# An error is raised ~hen a unicode object with non-ascii is assigned.
|
||||
self.assertRaises(UnicodeEncodeError, r.__setitem__, 'value', u't\xebst value')
|
||||
|
||||
|
||||
# An error is raised when a unicode object with non-ASCII format is
|
||||
# passed as initial mimetype or content_type.
|
||||
self.assertRaises(UnicodeEncodeError, HttpResponse,
|
||||
@@ -216,12 +217,12 @@ class HttpResponseTests(unittest.TestCase):
|
||||
self.assertRaises(UnicodeEncodeError, HttpResponse,
|
||||
content_type=u't\xebst value')
|
||||
|
||||
# The response also converts unicode keys to strings.)
|
||||
# The response also converts unicode keys to strings.)
|
||||
r[u'test'] = 'testing key'
|
||||
l = list(r.items())
|
||||
l.sort()
|
||||
self.assertEqual(l[1], ('test', 'testing key'))
|
||||
|
||||
|
||||
# It will also raise errors for keys with non-ascii data.
|
||||
self.assertRaises(UnicodeEncodeError, r.__setitem__, u't\xebst key', 'value')
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import unittest
|
||||
from datetime import timedelta, date
|
||||
|
||||
from django.template import Template, Context, add_to_builtins
|
||||
from django.utils import unittest
|
||||
from django.utils.dateformat import DateFormat
|
||||
from django.utils.translation import ugettext as _
|
||||
from django.utils.html import escape
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from django.conf import settings
|
||||
from django.db import connection, DEFAULT_DB_ALIAS
|
||||
from django.test import TestCase
|
||||
from django.test import TestCase, skipUnlessDBFeature
|
||||
from django.utils import functional
|
||||
|
||||
from models import Reporter, Article
|
||||
@@ -77,13 +77,13 @@ class IntrospectionTests(TestCase):
|
||||
)
|
||||
|
||||
# Regression test for #9991 - 'real' types in postgres
|
||||
if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'].startswith('django.db.backends.postgresql'):
|
||||
def test_postgresql_real_type(self):
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("CREATE TABLE django_ixn_real_test_table (number REAL);")
|
||||
desc = connection.introspection.get_table_description(cursor, 'django_ixn_real_test_table')
|
||||
cursor.execute('DROP TABLE django_ixn_real_test_table;')
|
||||
self.assertEqual(datatype(desc[0][1], desc[0]), 'FloatField')
|
||||
@skipUnlessDBFeature('has_real_datatype')
|
||||
def test_postgresql_real_type(self):
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("CREATE TABLE django_ixn_real_test_table (number REAL);")
|
||||
desc = connection.introspection.get_table_description(cursor, 'django_ixn_real_test_table')
|
||||
cursor.execute('DROP TABLE django_ixn_real_test_table;')
|
||||
self.assertEqual(datatype(desc[0][1], desc[0]), 'FloatField')
|
||||
|
||||
def test_get_relations(self):
|
||||
cursor = connection.cursor()
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import unittest
|
||||
from django.test import TestCase
|
||||
from django.utils import unittest
|
||||
|
||||
# just import your tests here
|
||||
from us.tests import *
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
from unittest import TestCase
|
||||
from django.db import DatabaseError
|
||||
from django.utils import unittest
|
||||
from regressiontests.max_lengths.models import PersonWithDefaultMaxLengths, PersonWithCustomMaxLengths
|
||||
|
||||
class MaxLengthArgumentsTests(TestCase):
|
||||
|
||||
class MaxLengthArgumentsTests(unittest.TestCase):
|
||||
|
||||
def verify_max_length(self, model,field,length):
|
||||
self.assertEquals(model._meta.get_field(field).max_length,length)
|
||||
|
||||
|
||||
def test_default_max_lengths(self):
|
||||
self.verify_max_length(PersonWithDefaultMaxLengths, 'email', 75)
|
||||
self.verify_max_length(PersonWithDefaultMaxLengths, 'vcard', 100)
|
||||
@@ -19,7 +19,7 @@ class MaxLengthArgumentsTests(TestCase):
|
||||
self.verify_max_length(PersonWithCustomMaxLengths, 'homepage', 250)
|
||||
self.verify_max_length(PersonWithCustomMaxLengths, 'avatar', 250)
|
||||
|
||||
class MaxLengthORMTests(TestCase):
|
||||
class MaxLengthORMTests(unittest.TestCase):
|
||||
|
||||
def test_custom_max_lengths(self):
|
||||
args = {
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import datetime
|
||||
import unittest
|
||||
from decimal import Decimal
|
||||
|
||||
import django.test
|
||||
from django import test
|
||||
from django import forms
|
||||
from django.db import models
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.db import models
|
||||
from django.db.models.fields.files import FieldFile
|
||||
from django.utils import unittest
|
||||
|
||||
from models import Foo, Bar, Whiz, BigD, BigS, Image, BigInt, Post, NullBooleanModel, BooleanModel, Document
|
||||
|
||||
@@ -22,7 +22,7 @@ if Image:
|
||||
TwoImageFieldTests
|
||||
|
||||
|
||||
class BasicFieldTests(django.test.TestCase):
|
||||
class BasicFieldTests(test.TestCase):
|
||||
def test_show_hidden_initial(self):
|
||||
"""
|
||||
Regression test for #12913. Make sure fields with choices respect
|
||||
@@ -48,7 +48,7 @@ class BasicFieldTests(django.test.TestCase):
|
||||
except ValidationError, e:
|
||||
self.fail("NullBooleanField failed validation with value of None: %s" % e.messages)
|
||||
|
||||
class DecimalFieldTests(django.test.TestCase):
|
||||
class DecimalFieldTests(test.TestCase):
|
||||
def test_to_python(self):
|
||||
f = models.DecimalField(max_digits=4, decimal_places=2)
|
||||
self.assertEqual(f.to_python(3), Decimal("3"))
|
||||
@@ -95,7 +95,7 @@ class DecimalFieldTests(django.test.TestCase):
|
||||
# This should not crash. That counts as a win for our purposes.
|
||||
Foo.objects.filter(d__gte=100000000000)
|
||||
|
||||
class ForeignKeyTests(django.test.TestCase):
|
||||
class ForeignKeyTests(test.TestCase):
|
||||
def test_callable_default(self):
|
||||
"""Test the use of a lazy callable for ForeignKey.default"""
|
||||
a = Foo.objects.create(id=1, a='abc', d=Decimal("12.34"))
|
||||
@@ -194,7 +194,7 @@ class BooleanFieldTests(unittest.TestCase):
|
||||
select={'string_length': 'LENGTH(string)'})[0]
|
||||
self.assertFalse(isinstance(b5.pk, bool))
|
||||
|
||||
class ChoicesTests(django.test.TestCase):
|
||||
class ChoicesTests(test.TestCase):
|
||||
def test_choices_and_field_display(self):
|
||||
"""
|
||||
Check that get_choices and get_flatchoices interact with
|
||||
@@ -206,7 +206,7 @@ class ChoicesTests(django.test.TestCase):
|
||||
self.assertEqual(Whiz(c=None).get_c_display(), None) # Blank value
|
||||
self.assertEqual(Whiz(c='').get_c_display(), '') # Empty value
|
||||
|
||||
class SlugFieldTests(django.test.TestCase):
|
||||
class SlugFieldTests(test.TestCase):
|
||||
def test_slugfield_max_length(self):
|
||||
"""
|
||||
Make sure SlugField honors max_length (#9706)
|
||||
@@ -216,7 +216,7 @@ class SlugFieldTests(django.test.TestCase):
|
||||
self.assertEqual(bs.s, 'slug'*50)
|
||||
|
||||
|
||||
class ValidationTest(django.test.TestCase):
|
||||
class ValidationTest(test.TestCase):
|
||||
def test_charfield_raises_error_on_empty_string(self):
|
||||
f = models.CharField()
|
||||
self.assertRaises(ValidationError, f.clean, "", None)
|
||||
@@ -271,7 +271,7 @@ class ValidationTest(django.test.TestCase):
|
||||
self.assertRaises(ValidationError, f.clean, None, None)
|
||||
|
||||
|
||||
class BigIntegerFieldTests(django.test.TestCase):
|
||||
class BigIntegerFieldTests(test.TestCase):
|
||||
def test_limits(self):
|
||||
# Ensure that values that are right at the limits can be saved
|
||||
# and then retrieved without corruption.
|
||||
@@ -299,7 +299,7 @@ class BigIntegerFieldTests(django.test.TestCase):
|
||||
b = BigInt.objects.get(value = '10')
|
||||
self.assertEqual(b.value, 10)
|
||||
|
||||
class TypeCoercionTests(django.test.TestCase):
|
||||
class TypeCoercionTests(test.TestCase):
|
||||
"""
|
||||
Test that database lookups can accept the wrong types and convert
|
||||
them with no error: especially on Postgres 8.3+ which does not do
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import datetime
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import models, DEFAULT_DB_ALIAS
|
||||
from django.db import models, DEFAULT_DB_ALIAS, connection
|
||||
from django.utils import tzinfo
|
||||
|
||||
CHOICES = (
|
||||
@@ -149,9 +149,7 @@ datetime.datetime(2000, 1, 1, 6, 1, 1)
|
||||
|
||||
"""}
|
||||
|
||||
if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] not in (
|
||||
"django.db.backends.mysql",
|
||||
"django.db.backends.oracle"):
|
||||
if connection.features.supports_timezones:
|
||||
__test__["timezone-tests"] = """
|
||||
# Saving an updating with timezone-aware datetime Python objects. Regression
|
||||
# test for #10443.
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
from unittest import TestCase
|
||||
|
||||
from django.core.paginator import Paginator, EmptyPage
|
||||
from django.utils.unittest import TestCase
|
||||
|
||||
class PaginatorTests(TestCase):
|
||||
"""
|
||||
|
||||
@@ -8,7 +8,7 @@ import sys
|
||||
import threading
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import models, DEFAULT_DB_ALIAS
|
||||
from django.db import models, DEFAULT_DB_ALIAS, connection
|
||||
from django.db.models import Count
|
||||
from django.db.models.query import Q, ITER_CHUNK_SIZE, EmptyQuerySet
|
||||
|
||||
@@ -1307,13 +1307,13 @@ FieldError: Infinite loop caused by ordering.
|
||||
|
||||
|
||||
# In Oracle, we expect a null CharField to return u'' instead of None.
|
||||
if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] == "django.db.backends.oracle":
|
||||
if connection.features.interprets_empty_strings_as_nulls:
|
||||
__test__["API_TESTS"] = __test__["API_TESTS"].replace("<NONE_OR_EMPTY_UNICODE>", "u''")
|
||||
else:
|
||||
__test__["API_TESTS"] = __test__["API_TESTS"].replace("<NONE_OR_EMPTY_UNICODE>", "None")
|
||||
|
||||
|
||||
if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] == "django.db.backends.mysql":
|
||||
if connection.features.requires_explicit_null_ordering_when_grouping:
|
||||
__test__["API_TESTS"] += """
|
||||
When grouping without specifying ordering, we add an explicit "ORDER BY NULL"
|
||||
portion in MySQL to prevent unnecessary sorting.
|
||||
@@ -1342,7 +1342,7 @@ Using an empty generator expression as the rvalue for an "__in" lookup is legal
|
||||
|
||||
# Sqlite 3 does not support passing in more than 1000 parameters except by
|
||||
# changing a parameter at compilation time.
|
||||
if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] != "django.db.backends.sqlite3":
|
||||
if connection.features.supports_1000_query_paramters:
|
||||
__test__["API_TESTS"] += """
|
||||
Bug #14244: Test that the "in" lookup works with lists of 1000 items or more.
|
||||
>>> Number.objects.all().delete()
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import unittest
|
||||
|
||||
from django.db import DatabaseError, connections, DEFAULT_DB_ALIAS
|
||||
from django.db.models import Count
|
||||
from django.test import TestCase
|
||||
from django.utils import unittest
|
||||
|
||||
from models import Tag, Annotation, DumbCategory, Note, ExtraInfo, Number
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ except ImportError:
|
||||
|
||||
from django.conf import settings
|
||||
from django.core import serializers, management
|
||||
from django.db import transaction, DEFAULT_DB_ALIAS
|
||||
from django.db import transaction, DEFAULT_DB_ALIAS, connection
|
||||
from django.test import TestCase
|
||||
from django.utils.functional import curry
|
||||
|
||||
@@ -335,7 +335,7 @@ The end."""),
|
||||
# Because Oracle treats the empty string as NULL, Oracle is expected to fail
|
||||
# when field.empty_strings_allowed is True and the value is None; skip these
|
||||
# tests.
|
||||
if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] == 'django.db.backends.oracle':
|
||||
if connection.features.interprets_empty_strings_as_nulls:
|
||||
test_data = [data for data in test_data
|
||||
if not (data[0] == data_obj and
|
||||
data[2]._meta.get_field('data').empty_strings_allowed and
|
||||
@@ -344,7 +344,7 @@ if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] == 'django.db.backends.oracle'
|
||||
# Regression test for #8651 -- a FK to an object iwth PK of 0
|
||||
# This won't work on MySQL since it won't let you create an object
|
||||
# with a primary key of 0,
|
||||
if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] != 'django.db.backends.mysql':
|
||||
if connection.features.allows_primary_key_0:
|
||||
test_data.extend([
|
||||
(data_obj, 0, Anchor, "Anchor 0"),
|
||||
(fk_obj, 465, FKData, 0),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import unittest
|
||||
from django.conf import settings
|
||||
from django.utils import unittest
|
||||
|
||||
class SettingsTests(unittest.TestCase):
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@ from django.conf import settings
|
||||
if __name__ == '__main__':
|
||||
settings.configure()
|
||||
|
||||
import unittest
|
||||
import sys
|
||||
import pkg_resources
|
||||
import imp
|
||||
@@ -21,6 +20,8 @@ from django.template import TemplateDoesNotExist, Context
|
||||
from django.template.loaders.eggs import load_template_source as lts_egg
|
||||
from django.template.loaders.eggs import Loader as EggLoader
|
||||
from django.template import loader
|
||||
from django.utils import unittest
|
||||
|
||||
|
||||
# Mock classes and objects for pkg_resources functions.
|
||||
class MockProvider(pkg_resources.NullProvider):
|
||||
@@ -73,6 +74,7 @@ class DeprecatedEggLoaderTest(unittest.TestCase):
|
||||
def tearDown(self):
|
||||
settings.INSTALLED_APPS = self._old_installed_apps
|
||||
warnings.resetwarnings()
|
||||
warnings.simplefilter("ignore", PendingDeprecationWarning)
|
||||
|
||||
def test_existing(self):
|
||||
"A template can be loaded from an egg"
|
||||
@@ -80,8 +82,6 @@ class DeprecatedEggLoaderTest(unittest.TestCase):
|
||||
contents, template_name = lts_egg("y.html")
|
||||
self.assertEqual(contents, "y")
|
||||
self.assertEqual(template_name, "egg:egg_1:templates/y.html")
|
||||
warnings.resetwarnings()
|
||||
warnings.simplefilter("ignore", PendingDeprecationWarning)
|
||||
|
||||
|
||||
class EggLoaderTest(unittest.TestCase):
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from unittest import TestCase
|
||||
from django.template.loader import get_template_from_string
|
||||
from django.template import VariableNode
|
||||
from django.utils.unittest import TestCase
|
||||
|
||||
|
||||
class NodelistTest(TestCase):
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import unittest
|
||||
from django.template.smartif import IfParser, Literal
|
||||
from django.utils import unittest
|
||||
|
||||
class SmartIfTests(unittest.TestCase):
|
||||
|
||||
|
||||
@@ -11,12 +11,12 @@ import time
|
||||
import os
|
||||
import sys
|
||||
import traceback
|
||||
import unittest
|
||||
|
||||
from django import template
|
||||
from django.core import urlresolvers
|
||||
from django.template import loader
|
||||
from django.template.loaders import app_directories, filesystem, cached
|
||||
from django.utils import unittest
|
||||
from django.utils.translation import activate, deactivate, ugettext as _
|
||||
from django.utils.safestring import mark_safe
|
||||
from django.utils.tzinfo import LocalTimezone
|
||||
@@ -506,16 +506,16 @@ class Templates(unittest.TestCase):
|
||||
'basic-syntax28': ("{{ a.b }}", {'a': SilentGetItemClass()}, ('', 'INVALID')),
|
||||
'basic-syntax29': ("{{ a.b }}", {'a': SilentAttrClass()}, ('', 'INVALID')),
|
||||
|
||||
# Something that starts like a number but has an extra lookup works as a lookup.
|
||||
'basic-syntax30': ("{{ 1.2.3 }}", {"1": {"2": {"3": "d"}}}, "d"),
|
||||
'basic-syntax31': ("{{ 1.2.3 }}", {"1": {"2": ("a", "b", "c", "d")}}, "d"),
|
||||
'basic-syntax32': ("{{ 1.2.3 }}", {"1": (("x", "x", "x", "x"), ("y", "y", "y", "y"), ("a", "b", "c", "d"))}, "d"),
|
||||
'basic-syntax33': ("{{ 1.2.3 }}", {"1": ("xxxx", "yyyy", "abcd")}, "d"),
|
||||
'basic-syntax34': ("{{ 1.2.3 }}", {"1": ({"x": "x"}, {"y": "y"}, {"z": "z", "3": "d"})}, "d"),
|
||||
|
||||
# Numbers are numbers even if their digits are in the context.
|
||||
'basic-syntax35': ("{{ 1 }}", {"1": "abc"}, "1"),
|
||||
'basic-syntax36': ("{{ 1.2 }}", {"1": "abc"}, "1.2"),
|
||||
# Something that starts like a number but has an extra lookup works as a lookup.
|
||||
'basic-syntax30': ("{{ 1.2.3 }}", {"1": {"2": {"3": "d"}}}, "d"),
|
||||
'basic-syntax31': ("{{ 1.2.3 }}", {"1": {"2": ("a", "b", "c", "d")}}, "d"),
|
||||
'basic-syntax32': ("{{ 1.2.3 }}", {"1": (("x", "x", "x", "x"), ("y", "y", "y", "y"), ("a", "b", "c", "d"))}, "d"),
|
||||
'basic-syntax33': ("{{ 1.2.3 }}", {"1": ("xxxx", "yyyy", "abcd")}, "d"),
|
||||
'basic-syntax34': ("{{ 1.2.3 }}", {"1": ({"x": "x"}, {"y": "y"}, {"z": "z", "3": "d"})}, "d"),
|
||||
|
||||
# Numbers are numbers even if their digits are in the context.
|
||||
'basic-syntax35': ("{{ 1 }}", {"1": "abc"}, "1"),
|
||||
'basic-syntax36': ("{{ 1.2 }}", {"1": "abc"}, "1.2"),
|
||||
|
||||
# List-index syntax allows a template to access a certain item of a subscriptable object.
|
||||
'list-index01': ("{{ var.1 }}", {"var": ["first item", "second item"]}, "second item"),
|
||||
@@ -603,7 +603,7 @@ class Templates(unittest.TestCase):
|
||||
|
||||
#filters should accept empty string constants
|
||||
'filter-syntax20': ('{{ ""|default_if_none:"was none" }}', {}, ""),
|
||||
|
||||
|
||||
### COMMENT SYNTAX ########################################################
|
||||
'comment-syntax01': ("{# this is hidden #}hello", {}, "hello"),
|
||||
'comment-syntax02': ("{# this is hidden #}hello{# foo #}", {}, "hello"),
|
||||
@@ -1300,8 +1300,8 @@ class Templates(unittest.TestCase):
|
||||
|
||||
# Regression test for #11270.
|
||||
'cache17': ('{% load cache %}{% cache 10 long_cache_key poem %}Some Content{% endcache %}', {'poem': 'Oh freddled gruntbuggly/Thy micturations are to me/As plurdled gabbleblotchits/On a lurgid bee/That mordiously hath bitled out/Its earted jurtles/Into a rancid festering/Or else I shall rend thee in the gobberwarts with my blurglecruncheon/See if I dont.'}, 'Some Content'),
|
||||
|
||||
|
||||
|
||||
|
||||
### AUTOESCAPE TAG ##############################################
|
||||
'autoescape-tag01': ("{% autoescape off %}hello{% endautoescape %}", {}, "hello"),
|
||||
'autoescape-tag02': ("{% autoescape off %}{{ first }}{% endautoescape %}", {"first": "<b>hello</b>"}, "<b>hello</b>"),
|
||||
@@ -1330,23 +1330,23 @@ class Templates(unittest.TestCase):
|
||||
# implementation details (fortunately, the (no)autoescape block
|
||||
# tags can be used in those cases)
|
||||
'autoescape-filtertag01': ("{{ first }}{% filter safe %}{{ first }} x<y{% endfilter %}", {"first": "<a>"}, template.TemplateSyntaxError),
|
||||
|
||||
|
||||
# ifqeual compares unescaped vales.
|
||||
'autoescape-ifequal01': ('{% ifequal var "this & that" %}yes{% endifequal %}', { "var": "this & that" }, "yes" ),
|
||||
|
||||
# Arguments to filters are 'safe' and manipulate their input unescaped.
|
||||
'autoescape-filters01': ('{{ var|cut:"&" }}', { "var": "this & that" }, "this that" ),
|
||||
'autoescape-filters02': ('{{ var|join:" & \" }}', { "var": ("Tom", "Dick", "Harry") }, "Tom & Dick & Harry" ),
|
||||
|
||||
# Literal strings are safe.
|
||||
'autoescape-literals01': ('{{ "this & that" }}',{}, "this & that" ),
|
||||
|
||||
# Iterating over strings outputs safe characters.
|
||||
'autoescape-stringiterations01': ('{% for l in var %}{{ l }},{% endfor %}', {'var': 'K&R'}, "K,&,R," ),
|
||||
|
||||
# Escape requirement survives lookup.
|
||||
'autoescape-lookup01': ('{{ var.key }}', { "var": {"key": "this & that" }}, "this & that" ),
|
||||
|
||||
'autoescape-ifequal01': ('{% ifequal var "this & that" %}yes{% endifequal %}', { "var": "this & that" }, "yes" ),
|
||||
|
||||
# Arguments to filters are 'safe' and manipulate their input unescaped.
|
||||
'autoescape-filters01': ('{{ var|cut:"&" }}', { "var": "this & that" }, "this that" ),
|
||||
'autoescape-filters02': ('{{ var|join:" & \" }}', { "var": ("Tom", "Dick", "Harry") }, "Tom & Dick & Harry" ),
|
||||
|
||||
# Literal strings are safe.
|
||||
'autoescape-literals01': ('{{ "this & that" }}',{}, "this & that" ),
|
||||
|
||||
# Iterating over strings outputs safe characters.
|
||||
'autoescape-stringiterations01': ('{% for l in var %}{{ l }},{% endfor %}', {'var': 'K&R'}, "K,&,R," ),
|
||||
|
||||
# Escape requirement survives lookup.
|
||||
'autoescape-lookup01': ('{{ var.key }}', { "var": {"key": "this & that" }}, "this & that" ),
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -35,83 +35,83 @@ class AssertContainsTests(TestCase):
|
||||
try:
|
||||
self.assertContains(response, 'text', status_code=999)
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "Couldn't retrieve content: Response code was 200 (expected 999)")
|
||||
self.assertIn("Couldn't retrieve content: Response code was 200 (expected 999)", str(e))
|
||||
try:
|
||||
self.assertContains(response, 'text', status_code=999, msg_prefix='abc')
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "abc: Couldn't retrieve content: Response code was 200 (expected 999)")
|
||||
self.assertIn("abc: Couldn't retrieve content: Response code was 200 (expected 999)", str(e))
|
||||
|
||||
try:
|
||||
self.assertNotContains(response, 'text', status_code=999)
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "Couldn't retrieve content: Response code was 200 (expected 999)")
|
||||
self.assertIn("Couldn't retrieve content: Response code was 200 (expected 999)", str(e))
|
||||
try:
|
||||
self.assertNotContains(response, 'text', status_code=999, msg_prefix='abc')
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "abc: Couldn't retrieve content: Response code was 200 (expected 999)")
|
||||
self.assertIn("abc: Couldn't retrieve content: Response code was 200 (expected 999)", str(e))
|
||||
|
||||
try:
|
||||
self.assertNotContains(response, 'once')
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "Response should not contain 'once'")
|
||||
self.assertIn("Response should not contain 'once'", str(e))
|
||||
try:
|
||||
self.assertNotContains(response, 'once', msg_prefix='abc')
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "abc: Response should not contain 'once'")
|
||||
self.assertIn("abc: Response should not contain 'once'", str(e))
|
||||
|
||||
try:
|
||||
self.assertContains(response, 'never', 1)
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "Found 0 instances of 'never' in response (expected 1)")
|
||||
self.assertIn("Found 0 instances of 'never' in response (expected 1)", str(e))
|
||||
try:
|
||||
self.assertContains(response, 'never', 1, msg_prefix='abc')
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "abc: Found 0 instances of 'never' in response (expected 1)")
|
||||
self.assertIn("abc: Found 0 instances of 'never' in response (expected 1)", str(e))
|
||||
|
||||
try:
|
||||
self.assertContains(response, 'once', 0)
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "Found 1 instances of 'once' in response (expected 0)")
|
||||
self.assertIn("Found 1 instances of 'once' in response (expected 0)", str(e))
|
||||
try:
|
||||
self.assertContains(response, 'once', 0, msg_prefix='abc')
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "abc: Found 1 instances of 'once' in response (expected 0)")
|
||||
self.assertIn("abc: Found 1 instances of 'once' in response (expected 0)", str(e))
|
||||
|
||||
try:
|
||||
self.assertContains(response, 'once', 2)
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "Found 1 instances of 'once' in response (expected 2)")
|
||||
self.assertIn("Found 1 instances of 'once' in response (expected 2)", str(e))
|
||||
try:
|
||||
self.assertContains(response, 'once', 2, msg_prefix='abc')
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "abc: Found 1 instances of 'once' in response (expected 2)")
|
||||
self.assertIn("abc: Found 1 instances of 'once' in response (expected 2)", str(e))
|
||||
|
||||
try:
|
||||
self.assertContains(response, 'twice', 1)
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "Found 2 instances of 'twice' in response (expected 1)")
|
||||
self.assertIn("Found 2 instances of 'twice' in response (expected 1)", str(e))
|
||||
try:
|
||||
self.assertContains(response, 'twice', 1, msg_prefix='abc')
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "abc: Found 2 instances of 'twice' in response (expected 1)")
|
||||
self.assertIn("abc: Found 2 instances of 'twice' in response (expected 1)", str(e))
|
||||
|
||||
try:
|
||||
self.assertContains(response, 'thrice')
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "Couldn't find 'thrice' in response")
|
||||
self.assertIn("Couldn't find 'thrice' in response", str(e))
|
||||
try:
|
||||
self.assertContains(response, 'thrice', msg_prefix='abc')
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "abc: Couldn't find 'thrice' in response")
|
||||
self.assertIn("abc: Couldn't find 'thrice' in response", str(e))
|
||||
|
||||
try:
|
||||
self.assertContains(response, 'thrice', 3)
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "Found 0 instances of 'thrice' in response (expected 3)")
|
||||
self.assertIn("Found 0 instances of 'thrice' in response (expected 3)", str(e))
|
||||
try:
|
||||
self.assertContains(response, 'thrice', 3, msg_prefix='abc')
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "abc: Found 0 instances of 'thrice' in response (expected 3)")
|
||||
self.assertIn("abc: Found 0 instances of 'thrice' in response (expected 3)", str(e))
|
||||
|
||||
def test_unicode_contains(self):
|
||||
"Unicode characters can be found in template context"
|
||||
@@ -141,12 +141,12 @@ class AssertTemplateUsedTests(TestCase):
|
||||
try:
|
||||
self.assertTemplateUsed(response, 'GET Template')
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "No templates used to render the response")
|
||||
self.assertIn("No templates used to render the response", str(e))
|
||||
|
||||
try:
|
||||
self.assertTemplateUsed(response, 'GET Template', msg_prefix='abc')
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "abc: No templates used to render the response")
|
||||
self.assertIn("abc: No templates used to render the response", str(e))
|
||||
|
||||
def test_single_context(self):
|
||||
"Template assertions work when there is a single context"
|
||||
@@ -155,22 +155,22 @@ class AssertTemplateUsedTests(TestCase):
|
||||
try:
|
||||
self.assertTemplateNotUsed(response, 'Empty GET Template')
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "Template 'Empty GET Template' was used unexpectedly in rendering the response")
|
||||
self.assertIn("Template 'Empty GET Template' was used unexpectedly in rendering the response", str(e))
|
||||
|
||||
try:
|
||||
self.assertTemplateNotUsed(response, 'Empty GET Template', msg_prefix='abc')
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "abc: Template 'Empty GET Template' was used unexpectedly in rendering the response")
|
||||
self.assertIn("abc: Template 'Empty GET Template' was used unexpectedly in rendering the response", str(e))
|
||||
|
||||
try:
|
||||
self.assertTemplateUsed(response, 'Empty POST Template')
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "Template 'Empty POST Template' was not a template used to render the response. Actual template(s) used: Empty GET Template")
|
||||
self.assertIn("Template 'Empty POST Template' was not a template used to render the response. Actual template(s) used: Empty GET Template", str(e))
|
||||
|
||||
try:
|
||||
self.assertTemplateUsed(response, 'Empty POST Template', msg_prefix='abc')
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "abc: Template 'Empty POST Template' was not a template used to render the response. Actual template(s) used: Empty GET Template")
|
||||
self.assertIn("abc: Template 'Empty POST Template' was not a template used to render the response. Actual template(s) used: Empty GET Template", str(e))
|
||||
|
||||
def test_multiple_context(self):
|
||||
"Template assertions work when there are multiple contexts"
|
||||
@@ -186,17 +186,17 @@ class AssertTemplateUsedTests(TestCase):
|
||||
try:
|
||||
self.assertTemplateNotUsed(response, "form_view.html")
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "Template 'form_view.html' was used unexpectedly in rendering the response")
|
||||
self.assertIn("Template 'form_view.html' was used unexpectedly in rendering the response", str(e))
|
||||
|
||||
try:
|
||||
self.assertTemplateNotUsed(response, 'base.html')
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "Template 'base.html' was used unexpectedly in rendering the response")
|
||||
self.assertIn("Template 'base.html' was used unexpectedly in rendering the response", str(e))
|
||||
|
||||
try:
|
||||
self.assertTemplateUsed(response, "Valid POST Template")
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "Template 'Valid POST Template' was not a template used to render the response. Actual template(s) used: form_view.html, base.html")
|
||||
self.assertIn("Template 'Valid POST Template' was not a template used to render the response. Actual template(s) used: form_view.html, base.html", str(e))
|
||||
|
||||
class AssertRedirectsTests(TestCase):
|
||||
def test_redirect_page(self):
|
||||
@@ -206,12 +206,12 @@ class AssertRedirectsTests(TestCase):
|
||||
try:
|
||||
self.assertRedirects(response, '/test_client/get_view/')
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "Response didn't redirect as expected: Response code was 301 (expected 302)")
|
||||
self.assertIn("Response didn't redirect as expected: Response code was 301 (expected 302)", str(e))
|
||||
|
||||
try:
|
||||
self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc')
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "abc: Response didn't redirect as expected: Response code was 301 (expected 302)")
|
||||
self.assertIn("abc: Response didn't redirect as expected: Response code was 301 (expected 302)", str(e))
|
||||
|
||||
def test_lost_query(self):
|
||||
"An assertion is raised if the redirect location doesn't preserve GET parameters"
|
||||
@@ -219,12 +219,12 @@ class AssertRedirectsTests(TestCase):
|
||||
try:
|
||||
self.assertRedirects(response, '/test_client/get_view/')
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "Response redirected to 'http://testserver/test_client/get_view/?var=value', expected 'http://testserver/test_client/get_view/'")
|
||||
self.assertIn("Response redirected to 'http://testserver/test_client/get_view/?var=value', expected 'http://testserver/test_client/get_view/'", str(e))
|
||||
|
||||
try:
|
||||
self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc')
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "abc: Response redirected to 'http://testserver/test_client/get_view/?var=value', expected 'http://testserver/test_client/get_view/'")
|
||||
self.assertIn("abc: Response redirected to 'http://testserver/test_client/get_view/?var=value', expected 'http://testserver/test_client/get_view/'", str(e))
|
||||
|
||||
def test_incorrect_target(self):
|
||||
"An assertion is raised if the response redirects to another target"
|
||||
@@ -233,7 +233,7 @@ class AssertRedirectsTests(TestCase):
|
||||
# Should redirect to get_view
|
||||
self.assertRedirects(response, '/test_client/some_view/')
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "Response didn't redirect as expected: Response code was 301 (expected 302)")
|
||||
self.assertIn("Response didn't redirect as expected: Response code was 301 (expected 302)", str(e))
|
||||
|
||||
def test_target_page(self):
|
||||
"An assertion is raised if the response redirect target cannot be retrieved as expected"
|
||||
@@ -242,13 +242,13 @@ class AssertRedirectsTests(TestCase):
|
||||
# The redirect target responds with a 301 code, not 200
|
||||
self.assertRedirects(response, 'http://testserver/test_client/permanent_redirect_view/')
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "Couldn't retrieve redirection page '/test_client/permanent_redirect_view/': response code was 301 (expected 200)")
|
||||
self.assertIn("Couldn't retrieve redirection page '/test_client/permanent_redirect_view/': response code was 301 (expected 200)", str(e))
|
||||
|
||||
try:
|
||||
# The redirect target responds with a 301 code, not 200
|
||||
self.assertRedirects(response, 'http://testserver/test_client/permanent_redirect_view/', msg_prefix='abc')
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "abc: Couldn't retrieve redirection page '/test_client/permanent_redirect_view/': response code was 301 (expected 200)")
|
||||
self.assertIn("abc: Couldn't retrieve redirection page '/test_client/permanent_redirect_view/': response code was 301 (expected 200)", str(e))
|
||||
|
||||
def test_redirect_chain(self):
|
||||
"You can follow a redirect chain of multiple redirects"
|
||||
@@ -339,12 +339,12 @@ class AssertRedirectsTests(TestCase):
|
||||
try:
|
||||
self.assertRedirects(response, '/test_client/get_view/')
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "Response didn't redirect as expected: Response code was 200 (expected 302)")
|
||||
self.assertIn("Response didn't redirect as expected: Response code was 200 (expected 302)", str(e))
|
||||
|
||||
try:
|
||||
self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc')
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "abc: Response didn't redirect as expected: Response code was 200 (expected 302)")
|
||||
self.assertIn("abc: Response didn't redirect as expected: Response code was 200 (expected 302)", str(e))
|
||||
|
||||
def test_redirect_on_non_redirect_page(self):
|
||||
"An assertion is raised if the original page couldn't be retrieved as expected"
|
||||
@@ -353,12 +353,12 @@ class AssertRedirectsTests(TestCase):
|
||||
try:
|
||||
self.assertRedirects(response, '/test_client/get_view/')
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "Response didn't redirect as expected: Response code was 200 (expected 302)")
|
||||
self.assertIn("Response didn't redirect as expected: Response code was 200 (expected 302)", str(e))
|
||||
|
||||
try:
|
||||
self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc')
|
||||
except AssertionError, e:
|
||||
self.assertEquals(str(e), "abc: Response didn't redirect as expected: Response code was 200 (expected 302)")
|
||||
self.assertIn("abc: Response didn't redirect as expected: Response code was 200 (expected 302)", str(e))
|
||||
|
||||
|
||||
class AssertFormErrorTests(TestCase):
|
||||
@@ -378,11 +378,11 @@ class AssertFormErrorTests(TestCase):
|
||||
try:
|
||||
self.assertFormError(response, 'wrong_form', 'some_field', 'Some error.')
|
||||
except AssertionError, e:
|
||||
self.assertEqual(str(e), "The form 'wrong_form' was not used to render the response")
|
||||
self.assertIn("The form 'wrong_form' was not used to render the response", str(e))
|
||||
try:
|
||||
self.assertFormError(response, 'wrong_form', 'some_field', 'Some error.', msg_prefix='abc')
|
||||
except AssertionError, e:
|
||||
self.assertEqual(str(e), "abc: The form 'wrong_form' was not used to render the response")
|
||||
self.assertIn("abc: The form 'wrong_form' was not used to render the response", str(e))
|
||||
|
||||
def test_unknown_field(self):
|
||||
"An assertion is raised if the field name is unknown"
|
||||
@@ -400,11 +400,11 @@ class AssertFormErrorTests(TestCase):
|
||||
try:
|
||||
self.assertFormError(response, 'form', 'some_field', 'Some error.')
|
||||
except AssertionError, e:
|
||||
self.assertEqual(str(e), "The form 'form' in context 0 does not contain the field 'some_field'")
|
||||
self.assertIn("The form 'form' in context 0 does not contain the field 'some_field'", str(e))
|
||||
try:
|
||||
self.assertFormError(response, 'form', 'some_field', 'Some error.', msg_prefix='abc')
|
||||
except AssertionError, e:
|
||||
self.assertEqual(str(e), "abc: The form 'form' in context 0 does not contain the field 'some_field'")
|
||||
self.assertIn("abc: The form 'form' in context 0 does not contain the field 'some_field'", str(e))
|
||||
|
||||
def test_noerror_field(self):
|
||||
"An assertion is raised if the field doesn't have any errors"
|
||||
@@ -422,11 +422,11 @@ class AssertFormErrorTests(TestCase):
|
||||
try:
|
||||
self.assertFormError(response, 'form', 'value', 'Some error.')
|
||||
except AssertionError, e:
|
||||
self.assertEqual(str(e), "The field 'value' on form 'form' in context 0 contains no errors")
|
||||
self.assertIn("The field 'value' on form 'form' in context 0 contains no errors", str(e))
|
||||
try:
|
||||
self.assertFormError(response, 'form', 'value', 'Some error.', msg_prefix='abc')
|
||||
except AssertionError, e:
|
||||
self.assertEqual(str(e), "abc: The field 'value' on form 'form' in context 0 contains no errors")
|
||||
self.assertIn("abc: The field 'value' on form 'form' in context 0 contains no errors", str(e))
|
||||
|
||||
def test_unknown_error(self):
|
||||
"An assertion is raised if the field doesn't contain the provided error"
|
||||
@@ -444,11 +444,11 @@ class AssertFormErrorTests(TestCase):
|
||||
try:
|
||||
self.assertFormError(response, 'form', 'email', 'Some error.')
|
||||
except AssertionError, e:
|
||||
self.assertEqual(str(e), "The field 'email' on form 'form' in context 0 does not contain the error 'Some error.' (actual errors: [u'Enter a valid e-mail address.'])")
|
||||
self.assertIn("The field 'email' on form 'form' in context 0 does not contain the error 'Some error.' (actual errors: [u'Enter a valid e-mail address.'])", str(e))
|
||||
try:
|
||||
self.assertFormError(response, 'form', 'email', 'Some error.', msg_prefix='abc')
|
||||
except AssertionError, e:
|
||||
self.assertEqual(str(e), "abc: The field 'email' on form 'form' in context 0 does not contain the error 'Some error.' (actual errors: [u'Enter a valid e-mail address.'])")
|
||||
self.assertIn("abc: The field 'email' on form 'form' in context 0 does not contain the error 'Some error.' (actual errors: [u'Enter a valid e-mail address.'])", str(e))
|
||||
|
||||
def test_unknown_nonfield_error(self):
|
||||
"""
|
||||
@@ -469,11 +469,11 @@ class AssertFormErrorTests(TestCase):
|
||||
try:
|
||||
self.assertFormError(response, 'form', None, 'Some error.')
|
||||
except AssertionError, e:
|
||||
self.assertEqual(str(e), "The form 'form' in context 0 does not contain the non-field error 'Some error.' (actual errors: )")
|
||||
self.assertIn("The form 'form' in context 0 does not contain the non-field error 'Some error.' (actual errors: )", str(e))
|
||||
try:
|
||||
self.assertFormError(response, 'form', None, 'Some error.', msg_prefix='abc')
|
||||
except AssertionError, e:
|
||||
self.assertEqual(str(e), "abc: The form 'form' in context 0 does not contain the non-field error 'Some error.' (actual errors: )")
|
||||
self.assertIn("abc: The form 'form' in context 0 does not contain the non-field error 'Some error.' (actual errors: )", str(e))
|
||||
|
||||
class LoginTests(TestCase):
|
||||
fixtures = ['testdata']
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
Tests for django test runner
|
||||
"""
|
||||
import StringIO
|
||||
import unittest
|
||||
import django
|
||||
|
||||
from django.test import simple
|
||||
from django.utils import unittest
|
||||
|
||||
class DjangoTestRunnerTests(unittest.TestCase):
|
||||
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
"""
|
||||
Unit tests for reverse URL lookups.
|
||||
"""
|
||||
import unittest
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import ImproperlyConfigured
|
||||
from django.core.urlresolvers import reverse, resolve, NoReverseMatch,\
|
||||
@@ -11,6 +9,7 @@ from django.core.urlresolvers import reverse, resolve, NoReverseMatch,\
|
||||
from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect
|
||||
from django.shortcuts import redirect
|
||||
from django.test import TestCase
|
||||
from django.utils import unittest
|
||||
|
||||
import urlconf_outer
|
||||
import urlconf_inner
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
from datetime import datetime, date
|
||||
import os
|
||||
import time
|
||||
import unittest
|
||||
|
||||
from django.utils.dateformat import format
|
||||
from django.utils import dateformat, translation
|
||||
from django.utils import dateformat, translation, unittest
|
||||
from django.utils.tzinfo import FixedOffset, LocalTimezone
|
||||
|
||||
|
||||
class DateFormatTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.old_TZ = os.environ.get('TZ')
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import datetime
|
||||
import unittest
|
||||
|
||||
from django.utils import feedgenerator, tzinfo
|
||||
from django.utils import feedgenerator, tzinfo, unittest
|
||||
|
||||
class FeedgeneratorTest(unittest.TestCase):
|
||||
"""
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import unittest
|
||||
|
||||
from django.utils import unittest
|
||||
from django.utils.functional import lazy
|
||||
|
||||
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
from zipimport import zipimporter
|
||||
|
||||
from django.utils import unittest
|
||||
from django.utils.importlib import import_module
|
||||
from django.utils.module_loading import module_has_submodule
|
||||
|
||||
|
||||
class DefaultLoader(unittest.TestCase):
|
||||
def test_loader(self):
|
||||
"Normal module existence can be tested"
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import unittest
|
||||
|
||||
from django.utils import unittest
|
||||
from django.utils.termcolors import parse_color_setting, PALETTES, DEFAULT_PALETTE, LIGHT_PALETTE, DARK_PALETTE, NOCOLOR_PALETTE
|
||||
|
||||
class TermColorTests(unittest.TestCase):
|
||||
|
||||
Reference in New Issue
Block a user