2021-11-04 09:36:11 +00:00
|
|
|
from decimal import Decimal
|
|
|
|
|
2018-11-12 16:15:48 +00:00
|
|
|
from django.db.backends.signals import connection_created
|
2019-01-10 18:06:14 +00:00
|
|
|
from django.db.migrations.writer import MigrationWriter
|
2018-11-12 16:15:48 +00:00
|
|
|
from django.test.utils import modify_settings
|
|
|
|
|
|
|
|
from . import PostgreSQLTestCase
|
|
|
|
|
2019-01-10 18:06:14 +00:00
|
|
|
try:
|
|
|
|
from psycopg2.extras import (
|
|
|
|
DateRange, DateTimeRange, DateTimeTZRange, NumericRange,
|
|
|
|
)
|
2020-07-24 06:25:47 +00:00
|
|
|
|
2019-01-10 18:06:14 +00:00
|
|
|
from django.contrib.postgres.fields import (
|
2021-11-04 09:36:11 +00:00
|
|
|
DateRangeField, DateTimeRangeField, DecimalRangeField,
|
|
|
|
IntegerRangeField,
|
2019-01-10 18:06:14 +00:00
|
|
|
)
|
|
|
|
except ImportError:
|
|
|
|
pass
|
|
|
|
|
2018-11-12 16:15:48 +00: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-10 18:06:14 +00:00
|
|
|
|
|
|
|
def test_register_serializer_for_migrations(self):
|
|
|
|
tests = (
|
|
|
|
(DateRange(empty=True), DateRangeField),
|
|
|
|
(DateTimeRange(empty=True), DateRangeField),
|
|
|
|
(DateTimeTZRange(None, None, '[]'), DateTimeRangeField),
|
2021-11-04 09:36:11 +00:00
|
|
|
(NumericRange(Decimal('1.0'), Decimal('5.0'), '()'), DecimalRangeField),
|
2019-01-10 18:06:14 +00: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()
|