|
|
@@ -0,0 +1,61 @@
|
|
|
+import datetime
|
|
|
+import json
|
|
|
+from decimal import Decimal
|
|
|
+
|
|
|
+from django.test import SimpleTestCase, override_settings
|
|
|
+from netaddr import IPAddress, IPNetwork
|
|
|
+
|
|
|
+from utilities.json import APIJSONEncoder, render_native_values
|
|
|
+
|
|
|
+
|
|
|
+class APIJSONEncoderTest(SimpleTestCase):
|
|
|
+
|
|
|
+ def test_ip_values(self):
|
|
|
+ data = {'address': IPNetwork('192.0.2.1/24'), 'gateway': IPAddress('192.0.2.254'), 'amount': Decimal('1.5')}
|
|
|
+ self.assertEqual(
|
|
|
+ json.loads(json.dumps(data, cls=APIJSONEncoder)),
|
|
|
+ {'address': '192.0.2.1/24', 'gateway': '192.0.2.254', 'amount': 1.5},
|
|
|
+ )
|
|
|
+
|
|
|
+ def test_dates_and_times(self):
|
|
|
+ """
|
|
|
+ Dates and times are rendered as REST framework's fields render them, in the current time zone.
|
|
|
+ """
|
|
|
+ data = {
|
|
|
+ 'datetime': datetime.datetime(2026, 12, 5, 14, 30, 1, 123456, tzinfo=datetime.UTC),
|
|
|
+ 'date': datetime.date(2026, 12, 5),
|
|
|
+ 'time': datetime.time(14, 30, 1, 250000),
|
|
|
+ }
|
|
|
+ cases = (
|
|
|
+ ('UTC', '2026-12-05T14:30:01.123456Z'),
|
|
|
+ ('Asia/Kolkata', '2026-12-05T20:00:01.123456+05:30'),
|
|
|
+ )
|
|
|
+ for time_zone, expected in cases:
|
|
|
+ with self.subTest(time_zone=time_zone), override_settings(TIME_ZONE=time_zone):
|
|
|
+ self.assertEqual(
|
|
|
+ json.loads(json.dumps(data, cls=APIJSONEncoder)),
|
|
|
+ {'datetime': expected, 'date': '2026-12-05', 'time': '14:30:01.250000'},
|
|
|
+ )
|
|
|
+
|
|
|
+
|
|
|
+class RenderNativeValuesTest(SimpleTestCase):
|
|
|
+
|
|
|
+ def test_nested_values(self):
|
|
|
+ data = {
|
|
|
+ 'address': IPNetwork('192.0.2.1/24'),
|
|
|
+ 'primary_ip': {'id': 1, 'address': IPNetwork('2001:db8::1/64')},
|
|
|
+ 'allowed_ips': [IPNetwork('198.51.100.0/24')],
|
|
|
+ 'gateways': (IPAddress('192.0.2.254'),),
|
|
|
+ 'name': 'Device 1',
|
|
|
+ 'weight': Decimal('1.5'),
|
|
|
+ 'created': datetime.datetime(2026, 12, 5, 14, 30, tzinfo=datetime.UTC),
|
|
|
+ }
|
|
|
+ self.assertEqual(render_native_values(data), {
|
|
|
+ 'address': '192.0.2.1/24',
|
|
|
+ 'primary_ip': {'id': 1, 'address': '2001:db8::1/64'},
|
|
|
+ 'allowed_ips': ['198.51.100.0/24'],
|
|
|
+ 'gateways': ['192.0.2.254'],
|
|
|
+ 'name': 'Device 1',
|
|
|
+ 'weight': Decimal('1.5'),
|
|
|
+ 'created': '2026-12-05T14:30:00Z',
|
|
|
+ })
|