tests.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. """Tests for django.db.utils."""
  2. import unittest
  3. from django.core.exceptions import ImproperlyConfigured
  4. from django.db import DEFAULT_DB_ALIAS, ProgrammingError, connection
  5. from django.db.utils import ConnectionHandler, load_backend
  6. from django.test import SimpleTestCase, TestCase
  7. class ConnectionHandlerTests(SimpleTestCase):
  8. def test_connection_handler_no_databases(self):
  9. """
  10. Empty DATABASES and empty 'default' settings default to the dummy
  11. backend.
  12. """
  13. for DATABASES in (
  14. {}, # Empty DATABASES setting.
  15. {'default': {}}, # Empty 'default' database.
  16. ):
  17. with self.subTest(DATABASES=DATABASES):
  18. self.assertImproperlyConfigured(DATABASES)
  19. def assertImproperlyConfigured(self, DATABASES):
  20. conns = ConnectionHandler(DATABASES)
  21. self.assertEqual(conns[DEFAULT_DB_ALIAS].settings_dict['ENGINE'], 'django.db.backends.dummy')
  22. msg = (
  23. 'settings.DATABASES is improperly configured. Please supply the '
  24. 'ENGINE value. Check settings documentation for more details.'
  25. )
  26. with self.assertRaisesMessage(ImproperlyConfigured, msg):
  27. conns[DEFAULT_DB_ALIAS].ensure_connection()
  28. def test_no_default_database(self):
  29. DATABASES = {'other': {}}
  30. conns = ConnectionHandler(DATABASES)
  31. msg = "You must define a 'default' database."
  32. with self.assertRaisesMessage(ImproperlyConfigured, msg):
  33. conns['other'].ensure_connection()
  34. class DatabaseErrorWrapperTests(TestCase):
  35. @unittest.skipUnless(connection.vendor == 'postgresql', 'PostgreSQL test')
  36. def test_reraising_backend_specific_database_exception(self):
  37. with connection.cursor() as cursor:
  38. msg = 'table "X" does not exist'
  39. with self.assertRaisesMessage(ProgrammingError, msg) as cm:
  40. cursor.execute('DROP TABLE "X"')
  41. self.assertNotEqual(type(cm.exception), type(cm.exception.__cause__))
  42. self.assertIsNotNone(cm.exception.__cause__)
  43. self.assertIsNotNone(cm.exception.__cause__.pgcode)
  44. self.assertIsNotNone(cm.exception.__cause__.pgerror)
  45. class LoadBackendTests(SimpleTestCase):
  46. def test_load_backend_invalid_name(self):
  47. msg = (
  48. "'foo' isn't an available database backend.\n"
  49. "Try using 'django.db.backends.XXX', where XXX is one of:\n"
  50. " 'mysql', 'oracle', 'postgresql', 'sqlite3'"
  51. )
  52. with self.assertRaisesMessage(ImproperlyConfigured, msg) as cm:
  53. load_backend('foo')
  54. self.assertEqual(str(cm.exception.__cause__), "No module named 'foo'")