2021-11-04 17:36:11 +08:00
|
|
|
from decimal import Decimal
|
|
|
|
|
2018-11-13 00:15:48 +08:00
|
|
|
from django.db.backends.signals import connection_created
|
2019-01-11 02:06:14 +08:00
|
|
|
from django.db.migrations.writer import MigrationWriter
|
2018-11-13 00:15:48 +08:00
|
|
|
from django.test.utils import modify_settings
|
|
|
|
|
|
|
|
from . import PostgreSQLTestCase
|
|
|
|
|
2019-01-11 02:06:14 +08:00
|
|
|
try:
|
|
|
|
from psycopg2.extras import (
|
|
|
|
DateRange, DateTimeRange, DateTimeTZRange, NumericRange,
|
|
|
|
)
|
2020-07-24 14:25:47 +08:00
|
|
|
|
2019-01-11 02:06:14 +08:00
|
|
|
from django.contrib.postgres.fields import (
|
2021-11-04 17:36:11 +08:00
|
|
|
DateRangeField, DateTimeRangeField, DecimalRangeField,
|
|
|
|
IntegerRangeField,
|
2019-01-11 02:06:14 +08:00
|
|
|
)
|
|
|
|
except ImportError:
|
|
|
|
pass
|
|
|
|
|
2018-11-13 00:15:48 +08:00
|
|
|
|
|
|
|
class PostgresConfigTests(PostgreSQLTestCase):
|
|
|
|
def test_register_type_handlers_connection(self):
|
|
|
|
from django.contrib.postgres.signals import register_type_handlers
|
|
|
|
self.assertNotIn(register_type_handlers, connection_created._live_receivers(None))
|
|
|
|
with modify_settings(INSTALLED_APPS={'append': 'django.contrib.postgres'}):
|
|
|
|
self.assertIn(register_type_handlers, connection_created._live_receivers(None))
|
|
|
|
self.assertNotIn(register_type_handlers, connection_created._live_receivers(None))
|
2019-01-11 02:06:14 +08:00
|
|
|
|
|
|
|
def test_register_serializer_for_migrations(self):
|
|
|
|
tests = (
|
|
|
|
(DateRange(empty=True), DateRangeField),
|
|
|
|
(DateTimeRange(empty=True), DateRangeField),
|
|
|
|
(DateTimeTZRange(None, None, '[]'), DateTimeRangeField),
|
2021-11-04 17:36:11 +08:00
|
|
|
(NumericRange(Decimal('1.0'), Decimal('5.0'), '()'), DecimalRangeField),
|
2019-01-11 02:06:14 +08:00
|
|
|
(NumericRange(1, 10), IntegerRangeField),
|
|
|
|
)
|
|
|
|
|
|
|
|
def assertNotSerializable():
|
|
|
|
for default, test_field in tests:
|
|
|
|
with self.subTest(default=default):
|
|
|
|
field = test_field(default=default)
|
|
|
|
with self.assertRaisesMessage(ValueError, 'Cannot serialize: %s' % default.__class__.__name__):
|
|
|
|
MigrationWriter.serialize(field)
|
|
|
|
|
|
|
|
assertNotSerializable()
|
|
|
|
with self.modify_settings(INSTALLED_APPS={'append': 'django.contrib.postgres'}):
|
|
|
|
for default, test_field in tests:
|
|
|
|
with self.subTest(default=default):
|
|
|
|
field = test_field(default=default)
|
|
|
|
serialized_field, imports = MigrationWriter.serialize(field)
|
|
|
|
self.assertEqual(imports, {
|
|
|
|
'import django.contrib.postgres.fields.ranges',
|
|
|
|
'import psycopg2.extras',
|
|
|
|
})
|
|
|
|
self.assertIn(
|
|
|
|
'%s.%s(default=psycopg2.extras.%r)' % (
|
|
|
|
field.__module__,
|
|
|
|
field.__class__.__name__,
|
|
|
|
default,
|
|
|
|
),
|
|
|
|
serialized_field
|
|
|
|
)
|
|
|
|
assertNotSerializable()
|