Used CommandError in createcachetable command.

Raising CommandError whenever a management command meets an error
condition is the standard way to handle errors in commands.
This commit is contained in:
Claude Paroz 2012-05-27 23:03:21 +02:00
parent f2b6763ad7
commit cc4b4d9fd3
2 changed files with 14 additions and 11 deletions

View File

@ -1,7 +1,7 @@
from optparse import make_option from optparse import make_option
from django.core.cache.backends.db import BaseDatabaseCache from django.core.cache.backends.db import BaseDatabaseCache
from django.core.management.base import LabelCommand from django.core.management.base import LabelCommand, CommandError
from django.db import connections, router, transaction, models, DEFAULT_DB_ALIAS from django.db import connections, router, transaction, models, DEFAULT_DB_ALIAS
from django.db.utils import DatabaseError from django.db.utils import DatabaseError
@ -55,11 +55,10 @@ class Command(LabelCommand):
try: try:
curs.execute("\n".join(full_statement)) curs.execute("\n".join(full_statement))
except DatabaseError as e: except DatabaseError as e:
self.stderr.write( transaction.rollback_unless_managed(using=db)
raise CommandError(
"Cache table '%s' could not be created.\nThe error was: %s." % "Cache table '%s' could not be created.\nThe error was: %s." %
(tablename, e)) (tablename, e))
transaction.rollback_unless_managed(using=db) for statement in index_output:
else: curs.execute(statement)
for statement in index_output: transaction.commit_unless_managed(using=db)
curs.execute(statement)
transaction.commit_unless_managed(using=db)

View File

@ -7,7 +7,6 @@ from __future__ import absolute_import
import hashlib import hashlib
import os import os
import re import re
import StringIO
import tempfile import tempfile
import time import time
import warnings import warnings
@ -820,9 +819,14 @@ class DBCacheTests(BaseCacheTests, TransactionTestCase):
self.perform_cull_test(50, 18) self.perform_cull_test(50, 18)
def test_second_call_doesnt_crash(self): def test_second_call_doesnt_crash(self):
err = StringIO.StringIO() with self.assertRaisesRegexp(management.CommandError,
management.call_command('createcachetable', self._table_name, verbosity=0, interactive=False, stderr=err) "Cache table 'test cache table' could not be created"):
self.assertTrue(b"Cache table 'test cache table' could not be created" in err.getvalue()) management.call_command(
'createcachetable',
self._table_name,
verbosity=0,
interactive=False
)
@override_settings(USE_TZ=True) @override_settings(USE_TZ=True)