Increased utils/encoders.py test coverage.

parent eb14f478
from datetime import date, datetime, timedelta, tzinfo from datetime import date, datetime, timedelta
from decimal import Decimal from decimal import Decimal
from uuid import uuid4 from uuid import uuid4
import pytest import pytest
from django.test import TestCase from django.test import TestCase
from django.utils.timezone import utc
from rest_framework.compat import coreapi from rest_framework.compat import coreapi
from rest_framework.utils.encoders import JSONEncoder from rest_framework.utils.encoders import JSONEncoder
class MockList(object):
def tolist(self):
return [1, 2, 3]
class JSONEncoderTests(TestCase): class JSONEncoderTests(TestCase):
""" """
Tests the JSONEncoder method Tests the JSONEncoder method
...@@ -22,7 +28,7 @@ class JSONEncoderTests(TestCase): ...@@ -22,7 +28,7 @@ class JSONEncoderTests(TestCase):
Tests encoding a decimal Tests encoding a decimal
""" """
d = Decimal(3.14) d = Decimal(3.14)
assert d == float(d) assert self.encoder.default(d) == float(d)
def test_encode_datetime(self): def test_encode_datetime(self):
""" """
...@@ -30,6 +36,8 @@ class JSONEncoderTests(TestCase): ...@@ -30,6 +36,8 @@ class JSONEncoderTests(TestCase):
""" """
current_time = datetime.now() current_time = datetime.now()
assert self.encoder.default(current_time) == current_time.isoformat() assert self.encoder.default(current_time) == current_time.isoformat()
current_time_utc = current_time.replace(tzinfo=utc)
assert self.encoder.default(current_time_utc) == current_time.isoformat() + 'Z'
def test_encode_time(self): def test_encode_time(self):
""" """
...@@ -42,22 +50,8 @@ class JSONEncoderTests(TestCase): ...@@ -42,22 +50,8 @@ class JSONEncoderTests(TestCase):
""" """
Tests encoding a timezone aware timestamp Tests encoding a timezone aware timestamp
""" """
class UTC(tzinfo):
"""
Class extending tzinfo to mimic UTC time
"""
def utcoffset(self, dt):
return timedelta(0)
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return timedelta(0)
current_time = datetime.now().time() current_time = datetime.now().time()
current_time = current_time.replace(tzinfo=UTC()) current_time = current_time.replace(tzinfo=utc)
with pytest.raises(ValueError): with pytest.raises(ValueError):
self.encoder.default(current_time) self.encoder.default(current_time)
...@@ -91,3 +85,10 @@ class JSONEncoderTests(TestCase): ...@@ -91,3 +85,10 @@ class JSONEncoderTests(TestCase):
with pytest.raises(RuntimeError): with pytest.raises(RuntimeError):
self.encoder.default(coreapi.Error()) self.encoder.default(coreapi.Error())
def test_encode_object_with_tolist(self):
"""
Tests encoding a object with tolist method
"""
foo = MockList()
assert self.encoder.default(foo) == [1, 2, 3]
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment