2
0

test_checks.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. from unittest.mock import MagicMock, patch
  2. from django.db import InterfaceError, NotSupportedError, OperationalError, ProgrammingError
  3. from django.test import TestCase
  4. from core.checks import POSTGRESQL_MIN_VERSION, POSTGRESQL_VERSION_MULTIPLIER, check_postgresql_version
  5. # `SHOW server_version_num` results representing the oldest supported and newest unsupported releases
  6. SUPPORTED_VERSION = POSTGRESQL_MIN_VERSION * POSTGRESQL_VERSION_MULTIPLIER
  7. UNSUPPORTED_VERSION = (POSTGRESQL_MIN_VERSION - 1) * POSTGRESQL_VERSION_MULTIPLIER + 10
  8. OBSOLETE_VERSION = (POSTGRESQL_MIN_VERSION - 2) * POSTGRESQL_VERSION_MULTIPLIER + 1
  9. class PostgreSQLVersionCheckTestCase(TestCase):
  10. """
  11. Test the system check which enforces NetBox's minimum PostgreSQL version.
  12. """
  13. @staticmethod
  14. def mock_connection(server_version_num=None, exception=None, vendor='postgresql'):
  15. """
  16. Return a mock database connection which yields the given `SHOW server_version_num` result, or
  17. which raises `exception` when a cursor is requested.
  18. """
  19. connection = MagicMock()
  20. connection.vendor = vendor
  21. if exception is not None:
  22. connection.cursor.side_effect = exception
  23. else:
  24. cursor = MagicMock()
  25. cursor.fetchone.return_value = (str(server_version_num),)
  26. connection.cursor.return_value.__enter__.return_value = cursor
  27. return connection
  28. @staticmethod
  29. def mock_connections(**connections):
  30. """
  31. Return a patcher replacing the connection handler with the given alias-to-connection mapping.
  32. """
  33. return patch('core.checks.connections', connections)
  34. def test_supported_version(self):
  35. """
  36. No error is reported for the minimum supported PostgreSQL version or later.
  37. """
  38. for version in (
  39. SUPPORTED_VERSION,
  40. SUPPORTED_VERSION + 2,
  41. SUPPORTED_VERSION + (2 * POSTGRESQL_VERSION_MULTIPLIER),
  42. ):
  43. with self.subTest(version=version):
  44. with self.mock_connections(default=self.mock_connection(version)):
  45. self.assertEqual(check_postgresql_version(None, databases=['default']), [])
  46. def test_unsupported_version(self):
  47. """
  48. An error is reported for any release preceding the minimum supported version.
  49. """
  50. with self.mock_connections(default=self.mock_connection(UNSUPPORTED_VERSION)):
  51. errors = check_postgresql_version(None, databases=['default'])
  52. self.assertEqual(len(errors), 1)
  53. self.assertEqual(errors[0].id, 'netbox.E001')
  54. self.assertIn(f'PostgreSQL {POSTGRESQL_MIN_VERSION - 1} is not supported', errors[0].msg)
  55. def test_connection_rejected_by_django(self):
  56. """
  57. Django's backend refuses to connect at all when the server predates its own minimum supported
  58. version, so the version query never runs. The check must still report the requirement.
  59. """
  60. error = NotSupportedError('PostgreSQL 14 or later is required (found 13.10).')
  61. with self.mock_connections(default=self.mock_connection(exception=error)):
  62. errors = check_postgresql_version(None, databases=['default'])
  63. self.assertEqual(len(errors), 1)
  64. self.assertEqual(errors[0].id, 'netbox.E001')
  65. self.assertIn(f'NetBox requires PostgreSQL {POSTGRESQL_MIN_VERSION} or later', errors[0].msg)
  66. def test_database_unavailable(self):
  67. """
  68. An unreachable database leaves the version unverified rather than reporting a spurious error.
  69. """
  70. exception = OperationalError('could not connect to server')
  71. with self.mock_connections(default=self.mock_connection(exception=exception)):
  72. self.assertEqual(check_postgresql_version(None, databases=['default']), [])
  73. def test_version_query_rejected(self):
  74. """
  75. A reachable server which rejects the version query leaves the version unverified, but logs why.
  76. """
  77. exception = ProgrammingError('unrecognized configuration parameter')
  78. with self.mock_connections(default=self.mock_connection(exception=exception)):
  79. with self.assertLogs('netbox.core.checks', level='WARNING') as cm:
  80. self.assertEqual(check_postgresql_version(None, databases=['default']), [])
  81. self.assertIn('Failed to determine the PostgreSQL version', cm.output[0])
  82. def test_connection_unusable(self):
  83. """
  84. An unusable connection leaves the version unverified rather than raising out of the check.
  85. InterfaceError descends from Error rather than DatabaseError, so it is handled explicitly.
  86. """
  87. exception = InterfaceError('connection already closed')
  88. with self.mock_connections(default=self.mock_connection(exception=exception)):
  89. self.assertEqual(check_postgresql_version(None, databases=['default']), [])
  90. def test_version_unparseable(self):
  91. """
  92. A version which cannot be parsed as an integer (e.g. as reported by an intervening connection
  93. pooler) leaves the version unverified, but logs why.
  94. """
  95. connection = self.mock_connection(SUPPORTED_VERSION)
  96. connection.cursor.return_value.__enter__.return_value.fetchone.return_value = ('15.4',)
  97. with self.mock_connections(default=connection):
  98. with self.assertLogs('netbox.core.checks', level='WARNING') as cm:
  99. self.assertEqual(check_postgresql_version(None, databases=['default']), [])
  100. self.assertIn('Unable to parse the PostgreSQL version', cm.output[0])
  101. def test_version_query_empty(self):
  102. """
  103. A version query which returns no result leaves the version unverified, but logs why.
  104. """
  105. connection = self.mock_connection(SUPPORTED_VERSION)
  106. connection.cursor.return_value.__enter__.return_value.fetchone.return_value = None
  107. with self.mock_connections(default=connection):
  108. with self.assertLogs('netbox.core.checks', level='WARNING') as cm:
  109. self.assertEqual(check_postgresql_version(None, databases=['default']), [])
  110. self.assertIn('returned no result', cm.output[0])
  111. def test_specified_aliases(self):
  112. """
  113. Only the database aliases supplied by Django are checked, and each is identified by name.
  114. """
  115. connections = {
  116. 'default': self.mock_connection(SUPPORTED_VERSION + 2),
  117. 'legacy': self.mock_connection(UNSUPPORTED_VERSION),
  118. }
  119. with self.mock_connections(**connections):
  120. errors = check_postgresql_version(None, databases=['legacy'])
  121. self.assertEqual(len(errors), 1)
  122. self.assertIn("Database 'legacy'", errors[0].msg)
  123. connections['default'].cursor.assert_not_called()
  124. def test_multiple_aliases(self):
  125. """
  126. Every alias supplied by Django is checked.
  127. """
  128. connections = {
  129. 'default': self.mock_connection(UNSUPPORTED_VERSION),
  130. 'legacy': self.mock_connection(OBSOLETE_VERSION),
  131. }
  132. with self.mock_connections(**connections):
  133. errors = check_postgresql_version(None, databases=['default', 'legacy'])
  134. self.assertEqual(len(errors), 2)
  135. self.assertIn("Database 'default'", errors[0].msg)
  136. self.assertIn("Database 'legacy'", errors[1].msg)
  137. def test_no_aliases(self):
  138. """
  139. No connection is opened when Django supplies no aliases, indicating that this run may not touch
  140. the database (e.g. `collectstatic`, or any command which declares no aliases of its own).
  141. """
  142. connections = {
  143. 'default': self.mock_connection(UNSUPPORTED_VERSION),
  144. 'legacy': self.mock_connection(OBSOLETE_VERSION),
  145. }
  146. with self.mock_connections(**connections):
  147. self.assertEqual(check_postgresql_version(None, databases=None), [])
  148. connections['default'].cursor.assert_not_called()
  149. connections['legacy'].cursor.assert_not_called()
  150. def test_non_postgresql_connection(self):
  151. """
  152. Connections to other types of databases (e.g. those registered by a plugin) are ignored.
  153. """
  154. connection = self.mock_connection(vendor='mysql')
  155. with self.mock_connections(default=connection):
  156. self.assertEqual(check_postgresql_version(None, databases=['default']), [])
  157. connection.cursor.assert_not_called()