test_database.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import unittest
  2. from unittest import mock
  3. from django.core.checks import Tags, run_checks
  4. from django.core.checks.registry import CheckRegistry
  5. from django.db import connection
  6. from django.test import TestCase
  7. class DatabaseCheckTests(TestCase):
  8. databases = {'default', 'other'}
  9. @property
  10. def func(self):
  11. from django.core.checks.database import check_database_backends
  12. return check_database_backends
  13. def test_database_checks_not_run_by_default(self):
  14. """
  15. `database` checks are only run when their tag is specified.
  16. """
  17. def f1(**kwargs):
  18. return [5]
  19. registry = CheckRegistry()
  20. registry.register(Tags.database)(f1)
  21. errors = registry.run_checks()
  22. self.assertEqual(errors, [])
  23. errors2 = registry.run_checks(tags=[Tags.database])
  24. self.assertEqual(errors2, [5])
  25. def test_database_checks_called(self):
  26. with mock.patch('django.db.backends.base.validation.BaseDatabaseValidation.check') as mocked_check:
  27. run_checks(tags=[Tags.database])
  28. self.assertTrue(mocked_check.called)
  29. @unittest.skipUnless(connection.vendor == 'mysql', 'Test only for MySQL')
  30. def test_mysql_strict_mode(self):
  31. good_sql_modes = [
  32. 'STRICT_TRANS_TABLES,STRICT_ALL_TABLES',
  33. 'STRICT_TRANS_TABLES',
  34. 'STRICT_ALL_TABLES',
  35. ]
  36. for response in good_sql_modes:
  37. with mock.patch(
  38. 'django.db.backends.utils.CursorWrapper.fetchone', create=True,
  39. return_value=(response,)
  40. ):
  41. self.assertEqual(self.func(None), [])
  42. bad_sql_modes = ['', 'WHATEVER']
  43. for response in bad_sql_modes:
  44. with mock.patch(
  45. 'django.db.backends.utils.CursorWrapper.fetchone', create=True,
  46. return_value=(response,)
  47. ):
  48. # One warning for each database alias
  49. result = self.func(None)
  50. self.assertEqual(len(result), 2)
  51. self.assertEqual([r.id for r in result], ['mysql.W002', 'mysql.W002'])