Skip to content

Commit 4ff9e96

Browse files
Alex Kahantomchristie
Alex Kahan
authored andcommitted
Adding tests to encoder.py (encode#4536)
1 parent 915ac22 commit 4ff9e96

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

tests/test_encoders.py

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
from datetime import date, datetime, timedelta, tzinfo
2+
from decimal import Decimal
3+
from uuid import uuid4
4+
5+
from django.test import TestCase
6+
7+
from rest_framework.utils.encoders import JSONEncoder
8+
9+
10+
class JSONEncoderTests(TestCase):
11+
"""
12+
Tests the JSONEncoder method
13+
"""
14+
15+
def setUp(self):
16+
self.encoder = JSONEncoder()
17+
18+
def test_encode_decimal(self):
19+
"""
20+
Tests encoding a decimal
21+
"""
22+
d = Decimal(3.14)
23+
self.assertEqual(d, float(d))
24+
25+
def test_encode_datetime(self):
26+
"""
27+
Tests encoding a datetime object
28+
"""
29+
current_time = datetime.now()
30+
self.assertEqual(self.encoder.default(current_time), current_time.isoformat())
31+
32+
def test_encode_time(self):
33+
"""
34+
Tests encoding a timezone
35+
"""
36+
current_time = datetime.now().time()
37+
self.assertEqual(self.encoder.default(current_time), current_time.isoformat()[:12])
38+
39+
def test_encode_time_tz(self):
40+
"""
41+
Tests encoding a timezone aware timestamp
42+
"""
43+
44+
class UTC(tzinfo):
45+
"""
46+
Class extending tzinfo to mimic UTC time
47+
"""
48+
def utcoffset(self, dt):
49+
return timedelta(0)
50+
51+
def tzname(self, dt):
52+
return "UTC"
53+
54+
def dst(self, dt):
55+
return timedelta(0)
56+
57+
current_time = datetime.now().time()
58+
current_time = current_time.replace(tzinfo=UTC())
59+
with self.assertRaises(ValueError):
60+
self.encoder.default(current_time)
61+
62+
def test_encode_date(self):
63+
"""
64+
Tests encoding a date object
65+
"""
66+
current_date = date.today()
67+
self.assertEqual(self.encoder.default(current_date), current_date.isoformat())
68+
69+
def test_encode_timedelta(self):
70+
"""
71+
Tests encoding a timedelta object
72+
"""
73+
delta = timedelta(hours=1)
74+
self.assertEqual(self.encoder.default(delta), str(delta.total_seconds()))
75+
76+
def test_encode_uuid(self):
77+
"""
78+
Tests encoding a UUID object
79+
"""
80+
unique_id = uuid4()
81+
self.assertEqual(self.encoder.default(unique_id), str(unique_id))

0 commit comments

Comments
 (0)