Skip to content

Commit 6c7baa9

Browse files
committed
[soc2010/test-refactor] Merged up to trunk again to fix failing tests.
git-svn-id: http://code.djangoproject.com/svn/django/branches/soc2010/test-refactor@13478 bcc190cf-cafb-0310-a4f2-bffc1f526a37
1 parent 0620a1c commit 6c7baa9

File tree

9 files changed

+182
-45
lines changed

9 files changed

+182
-45
lines changed

django/core/cache/backends/db.py

Lines changed: 68 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,39 @@
11
"Database cache backend."
22

33
from django.core.cache.backends.base import BaseCache
4-
from django.db import connection, transaction, DatabaseError
4+
from django.db import connections, router, transaction, DatabaseError
55
import base64, time
66
from datetime import datetime
77
try:
88
import cPickle as pickle
99
except ImportError:
1010
import pickle
1111

12+
class Options(object):
13+
"""A class that will quack like a Django model _meta class.
14+
15+
This allows cache operations to be controlled by the router
16+
"""
17+
def __init__(self, table):
18+
self.db_table = table
19+
self.app_label = 'django_cache'
20+
self.module_name = 'cacheentry'
21+
self.verbose_name = 'cache entry'
22+
self.verbose_name_plural = 'cache entries'
23+
self.object_name = 'CacheEntry'
24+
self.abstract = False
25+
self.managed = True
26+
self.proxy = False
27+
1228
class CacheClass(BaseCache):
1329
def __init__(self, table, params):
1430
BaseCache.__init__(self, params)
15-
self._table = connection.ops.quote_name(table)
31+
self._table = table
32+
33+
class CacheEntry(object):
34+
_meta = Options(table)
35+
self.cache_model_class = CacheEntry
36+
1637
max_entries = params.get('max_entries', 300)
1738
try:
1839
self._max_entries = int(max_entries)
@@ -25,17 +46,22 @@ def __init__(self, table, params):
2546
self._cull_frequency = 3
2647

2748
def get(self, key, default=None):
28-
cursor = connection.cursor()
29-
cursor.execute("SELECT cache_key, value, expires FROM %s WHERE cache_key = %%s" % self._table, [key])
49+
db = router.db_for_read(self.cache_model_class)
50+
table = connections[db].ops.quote_name(self._table)
51+
cursor = connections[db].cursor()
52+
53+
cursor.execute("SELECT cache_key, value, expires FROM %s WHERE cache_key = %%s" % table, [key])
3054
row = cursor.fetchone()
3155
if row is None:
3256
return default
3357
now = datetime.now()
3458
if row[2] < now:
35-
cursor.execute("DELETE FROM %s WHERE cache_key = %%s" % self._table, [key])
36-
transaction.commit_unless_managed()
59+
db = router.db_for_write(self.cache_model_class)
60+
cursor = connections[db].cursor()
61+
cursor.execute("DELETE FROM %s WHERE cache_key = %%s" % table, [key])
62+
transaction.commit_unless_managed(using=db)
3763
return default
38-
value = connection.ops.process_clob(row[1])
64+
value = connections[db].ops.process_clob(row[1])
3965
return pickle.loads(base64.decodestring(value))
4066

4167
def set(self, key, value, timeout=None):
@@ -47,56 +73,67 @@ def add(self, key, value, timeout=None):
4773
def _base_set(self, mode, key, value, timeout=None):
4874
if timeout is None:
4975
timeout = self.default_timeout
50-
cursor = connection.cursor()
51-
cursor.execute("SELECT COUNT(*) FROM %s" % self._table)
76+
db = router.db_for_write(self.cache_model_class)
77+
table = connections[db].ops.quote_name(self._table)
78+
cursor = connections[db].cursor()
79+
80+
cursor.execute("SELECT COUNT(*) FROM %s" % table)
5281
num = cursor.fetchone()[0]
5382
now = datetime.now().replace(microsecond=0)
5483
exp = datetime.fromtimestamp(time.time() + timeout).replace(microsecond=0)
5584
if num > self._max_entries:
56-
self._cull(cursor, now)
85+
self._cull(db, cursor, now)
5786
encoded = base64.encodestring(pickle.dumps(value, 2)).strip()
58-
cursor.execute("SELECT cache_key, expires FROM %s WHERE cache_key = %%s" % self._table, [key])
87+
cursor.execute("SELECT cache_key, expires FROM %s WHERE cache_key = %%s" % table, [key])
5988
try:
6089
result = cursor.fetchone()
6190
if result and (mode == 'set' or
6291
(mode == 'add' and result[1] < now)):
63-
cursor.execute("UPDATE %s SET value = %%s, expires = %%s WHERE cache_key = %%s" % self._table,
64-
[encoded, connection.ops.value_to_db_datetime(exp), key])
92+
cursor.execute("UPDATE %s SET value = %%s, expires = %%s WHERE cache_key = %%s" % table,
93+
[encoded, connections[db].ops.value_to_db_datetime(exp), key])
6594
else:
66-
cursor.execute("INSERT INTO %s (cache_key, value, expires) VALUES (%%s, %%s, %%s)" % self._table,
67-
[key, encoded, connection.ops.value_to_db_datetime(exp)])
95+
cursor.execute("INSERT INTO %s (cache_key, value, expires) VALUES (%%s, %%s, %%s)" % table,
96+
[key, encoded, connections[db].ops.value_to_db_datetime(exp)])
6897
except DatabaseError:
6998
# To be threadsafe, updates/inserts are allowed to fail silently
70-
transaction.rollback_unless_managed()
99+
transaction.rollback_unless_managed(using=db)
71100
return False
72101
else:
73-
transaction.commit_unless_managed()
102+
transaction.commit_unless_managed(using=db)
74103
return True
75104

76105
def delete(self, key):
77-
cursor = connection.cursor()
78-
cursor.execute("DELETE FROM %s WHERE cache_key = %%s" % self._table, [key])
79-
transaction.commit_unless_managed()
106+
db = router.db_for_write(self.cache_model_class)
107+
table = connections[db].ops.quote_name(self._table)
108+
cursor = connections[db].cursor()
109+
110+
cursor.execute("DELETE FROM %s WHERE cache_key = %%s" % table, [key])
111+
transaction.commit_unless_managed(using=db)
80112

81113
def has_key(self, key):
114+
db = router.db_for_read(self.cache_model_class)
115+
table = connections[db].ops.quote_name(self._table)
116+
cursor = connections[db].cursor()
117+
82118
now = datetime.now().replace(microsecond=0)
83-
cursor = connection.cursor()
84-
cursor.execute("SELECT cache_key FROM %s WHERE cache_key = %%s and expires > %%s" % self._table,
85-
[key, connection.ops.value_to_db_datetime(now)])
119+
cursor.execute("SELECT cache_key FROM %s WHERE cache_key = %%s and expires > %%s" % table,
120+
[key, connections[db].ops.value_to_db_datetime(now)])
86121
return cursor.fetchone() is not None
87122

88-
def _cull(self, cursor, now):
123+
def _cull(self, db, cursor, now):
89124
if self._cull_frequency == 0:
90125
self.clear()
91126
else:
92-
cursor.execute("DELETE FROM %s WHERE expires < %%s" % self._table,
93-
[connection.ops.value_to_db_datetime(now)])
94-
cursor.execute("SELECT COUNT(*) FROM %s" % self._table)
127+
cursor.execute("DELETE FROM %s WHERE expires < %%s" % table,
128+
[connections[db].ops.value_to_db_datetime(now)])
129+
cursor.execute("SELECT COUNT(*) FROM %s" % table)
95130
num = cursor.fetchone()[0]
96131
if num > self._max_entries:
97-
cursor.execute("SELECT cache_key FROM %s ORDER BY cache_key LIMIT 1 OFFSET %%s" % self._table, [num / self._cull_frequency])
98-
cursor.execute("DELETE FROM %s WHERE cache_key < %%s" % self._table, [cursor.fetchone()[0]])
132+
cursor.execute("SELECT cache_key FROM %s ORDER BY cache_key LIMIT 1 OFFSET %%s" % table, [num / self._cull_frequency])
133+
cursor.execute("DELETE FROM %s WHERE cache_key < %%s" % table, [cursor.fetchone()[0]])
99134

100135
def clear(self):
101-
cursor = connection.cursor()
102-
cursor.execute('DELETE FROM %s' % self._table)
136+
db = router.db_for_write(self.cache_model_class)
137+
table = connections[db].ops.quote_name(self._table)
138+
cursor = connections[db].cursor()
139+
cursor.execute('DELETE FROM %s' % table)

django/core/management/commands/dumpdata.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@ class Command(BaseCommand):
2020
make_option('-n', '--natural', action='store_true', dest='use_natural_keys', default=False,
2121
help='Use natural keys if they are available.'),
2222
)
23-
help = 'Output the contents of the database as a fixture of the given format.'
23+
help = ("Output the contents of the database as a fixture of the given "
24+
"format (using each model's default manager).")
2425
args = '[appname appname.ModelName ...]'
2526

2627
def handle(self, *app_labels, **options):
@@ -163,4 +164,4 @@ def sort_dependencies(app_list):
163164
)
164165
model_dependencies = skipped
165166

166-
return model_list
167+
return model_list

django/core/management/commands/flush.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -66,12 +66,12 @@ def handle_noargs(self, **options):
6666
# Emit the post sync signal. This allows individual
6767
# applications to respond as if the database had been
6868
# sync'd from scratch.
69-
all_models = [
70-
(app.__name__.split('.')[-2],
71-
[m for m in models.get_models(app, include_auto_created=True)
72-
if router.allow_syncdb(db, m)])
73-
for app in models.get_apps()
74-
]
69+
all_models = []
70+
for app in models.get_apps():
71+
all_models.extend([
72+
m for m in models.get_models(app, include_auto_created=True)
73+
if router.allow_syncdb(db, m)
74+
])
7575
emit_post_sync_signal(all_models, verbosity, interactive, db)
7676

7777
# Reinstall the initial_data fixture.

django/db/backends/creation.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -353,9 +353,11 @@ def create_test_db(self, verbosity=1, autoclobber=False):
353353
call_command('syncdb', verbosity=verbosity, interactive=False, database=self.connection.alias)
354354

355355
if settings.CACHE_BACKEND.startswith('db://'):
356-
from django.core.cache import parse_backend_uri
357-
_, cache_name, _ = parse_backend_uri(settings.CACHE_BACKEND)
358-
call_command('createcachetable', cache_name)
356+
from django.core.cache import parse_backend_uri, cache
357+
from django.db import router
358+
if router.allow_syncdb(self.connection.alias, cache.cache_model_class):
359+
_, cache_name, _ = parse_backend_uri(settings.CACHE_BACKEND)
360+
call_command('createcachetable', cache_name, database=self.connection.alias)
359361

360362
# Get a cursor (even though we don't need one yet). This has
361363
# the side effect of initializing the test database.

django/db/models/fields/__init__.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -795,6 +795,14 @@ def __init__(self, *args, **kwargs):
795795
kwargs['max_length'] = kwargs.get('max_length', 75)
796796
CharField.__init__(self, *args, **kwargs)
797797

798+
def formfield(self, **kwargs):
799+
# As with CharField, this will cause email validation to be performed twice
800+
defaults = {
801+
'form_class': forms.EmailField,
802+
}
803+
defaults.update(kwargs)
804+
return super(EmailField, self).formfield(**defaults)
805+
798806
class FilePathField(Field):
799807
description = _("File path")
800808

@@ -1105,6 +1113,14 @@ def __init__(self, verbose_name=None, name=None, verify_exists=True, **kwargs):
11051113
CharField.__init__(self, verbose_name, name, **kwargs)
11061114
self.validators.append(validators.URLValidator(verify_exists=verify_exists))
11071115

1116+
def formfield(self, **kwargs):
1117+
# As with CharField, this will cause URL validation to be performed twice
1118+
defaults = {
1119+
'form_class': forms.URLField,
1120+
}
1121+
defaults.update(kwargs)
1122+
return super(URLField, self).formfield(**defaults)
1123+
11081124
class XMLField(TextField):
11091125
description = _("XML text")
11101126

docs/topics/cache.txt

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,49 @@ settings file. You can't use a different database backend for your cache table.
136136

137137
Database caching works best if you've got a fast, well-indexed database server.
138138

139+
Database caching and multiple databases
140+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
141+
142+
If you use database caching with multiple databases, you'll also need
143+
to set up routing instructions for your database cache table. For the
144+
purposes of routing, the database cache table appears as a model named
145+
``CacheEntry``, in an application named ``django_cache``. This model
146+
won't appear in the models cache, but the model details can be used
147+
for routing purposes.
148+
149+
For example, the following router would direct all cache read
150+
operations to ``cache_slave``, and all write operations to
151+
``cache_master``. The cache table will only be synchronized onto
152+
``cache_master``::
153+
154+
class CacheRouter(object):
155+
"""A router to control all database cache operations"""
156+
157+
def db_for_read(self, model, **hints):
158+
"All cache read operations go to the slave"
159+
if model._meta.app_label in ('django_cache',):
160+
return 'cache_slave'
161+
return None
162+
163+
def db_for_write(self, model, **hints):
164+
"All cache write operations go to master"
165+
if model._meta.app_label in ('django_cache',):
166+
return 'cache_master'
167+
return None
168+
169+
def allow_syncdb(self, db, model):
170+
"Only synchronize the cache model on master"
171+
if model._meta.app_label in ('django_cache',):
172+
return db == 'cache_master'
173+
return None
174+
175+
If you don't specify routing directions for the database cache model,
176+
the cache backend will use the ``default`` database.
177+
178+
Of course, if you don't use the database cache backend, you don't need
179+
to worry about providing routing instructions for the database cache
180+
model.
181+
139182
Filesystem caching
140183
------------------
141184

docs/topics/db/managers.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,8 @@ and ``Person.people.all()``, yielding predictable results.
170170
If you use custom ``Manager`` objects, take note that the first ``Manager``
171171
Django encounters (in the order in which they're defined in the model) has a
172172
special status. Django interprets the first ``Manager`` defined in a class as
173-
the "default" ``Manager``, and several parts of Django will use that ``Manager``
173+
the "default" ``Manager``, and several parts of Django
174+
(including :djadmin:`dumpdata`) will use that ``Manager``
174175
exclusively for that model. As a result, it's a good idea to be careful in
175176
your choice of default manager in order to avoid a situation where overriding
176177
``get_query_set()`` results in an inability to retrieve objects you'd like to

tests/regressiontests/model_forms_regress/models.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,3 +54,6 @@ class Author(models.Model):
5454
class Author1(models.Model):
5555
publication = models.OneToOneField(Publication, null=False)
5656
full_name = models.CharField(max_length=255)
57+
58+
class Homepage(models.Model):
59+
url = models.URLField(verify_exists=False)

tests/regressiontests/model_forms_regress/tests.py

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@
66
from django.conf import settings
77
from django.test import TestCase
88

9-
from models import Person, RealPerson, Triple, FilePathModel, Article, Publication, CustomFF, Author, Author1
9+
from models import Person, RealPerson, Triple, FilePathModel, Article, \
10+
Publication, CustomFF, Author, Author1, Homepage
1011

1112

1213
class ModelMultipleChoiceFieldTests(TestCase):
@@ -212,7 +213,40 @@ class TestTicket11183(TestCase):
212213
def test_11183(self):
213214
form1 = ModelChoiceForm()
214215
field1 = form1.fields['person']
215-
# To allow the widget to change the queryset of field1.widget.choices correctly,
216+
# To allow the widget to change the queryset of field1.widget.choices correctly,
216217
# without affecting other forms, the following must hold:
217218
self.assert_(field1 is not ModelChoiceForm.base_fields['person'])
218219
self.assert_(field1.widget.choices.field is field1)
220+
221+
class HomepageForm(forms.ModelForm):
222+
class Meta:
223+
model = Homepage
224+
225+
class URLFieldTests(TestCase):
226+
def test_url_on_modelform(self):
227+
"Check basic URL field validation on model forms"
228+
self.assertFalse(HomepageForm({'url': 'foo'}).is_valid())
229+
self.assertFalse(HomepageForm({'url': 'http://'}).is_valid())
230+
self.assertFalse(HomepageForm({'url': 'http://example'}).is_valid())
231+
self.assertFalse(HomepageForm({'url': 'http://example.'}).is_valid())
232+
self.assertFalse(HomepageForm({'url': 'http://com.'}).is_valid())
233+
234+
self.assertTrue(HomepageForm({'url': 'http://localhost'}).is_valid())
235+
self.assertTrue(HomepageForm({'url': 'http://example.com'}).is_valid())
236+
self.assertTrue(HomepageForm({'url': 'http://www.example.com'}).is_valid())
237+
self.assertTrue(HomepageForm({'url': 'http://www.example.com:8000'}).is_valid())
238+
self.assertTrue(HomepageForm({'url': 'http://www.example.com/test'}).is_valid())
239+
self.assertTrue(HomepageForm({'url': 'http://www.example.com:8000/test'}).is_valid())
240+
self.assertTrue(HomepageForm({'url': 'http://example.com/foo/bar'}).is_valid())
241+
242+
def test_http_prefixing(self):
243+
"If the http:// prefix is omitted on form input, the field adds it again. (Refs #13613)"
244+
form = HomepageForm({'url': 'example.com'})
245+
form.is_valid()
246+
# self.assertTrue(form.is_valid())
247+
# self.assertEquals(form.cleaned_data['url'], 'http://example.com/')
248+
249+
form = HomepageForm({'url': 'example.com/test'})
250+
form.is_valid()
251+
# self.assertTrue(form.is_valid())
252+
# self.assertEquals(form.cleaned_data['url'], 'http://example.com/test')

0 commit comments

Comments
 (0)