Skip to content

Commit

Permalink
Created date serielizer field for timestamp representation
Browse files Browse the repository at this point in the history
  • Loading branch information
quiqueporta committed Aug 27, 2015
1 parent 53165d7 commit fbb77a0
Show file tree
Hide file tree
Showing 5 changed files with 122 additions and 13 deletions.
39 changes: 39 additions & 0 deletions django_rest_tools/fields.py
@@ -0,0 +1,39 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals, print_function
import datetime
import time

from django.utils import six

from rest_framework.fields import IntegerField


def datetime_to_timestamp(value):
return int(time.mktime(value.timetuple()) * 1000)


class DateToTimeStampField(IntegerField):

def to_internal_value(self, data):
if isinstance(data, six.text_type) and len(data) > self.MAX_STRING_LENGTH:
self.fail('max_string_length')

try:
data = int(self.re_decimal.sub('', str(data)))
except (ValueError, TypeError):
self.fail('invalid')

date = datetime.datetime.fromtimestamp(data / 1e3).date()
return date

def to_representation(self, value):
if not value:
return None

assert not isinstance(value, datetime.datetime), (
'Expected a `date`, but got a `datetime`. Refusing to coerce, '
'as this may mean losing timezone information. Use a custom '
'read-only field and deal with timezone issues explicitly.'
)

return datetime_to_timestamp(value)
19 changes: 19 additions & 0 deletions tests/django_rest_tools_app/migrations/0002_location_date.py
@@ -0,0 +1,19 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations


class Migration(migrations.Migration):

dependencies = [
('django_rest_tools_app', '0001_initial'),
]

operations = [
migrations.AddField(
model_name='location',
name='date',
field=models.DateField(null=True, blank=True),
),
]
1 change: 1 addition & 0 deletions tests/django_rest_tools_app/models.py
Expand Up @@ -8,6 +8,7 @@
class Location(models.Model):
name = models.CharField(max_length=255, null=False, blank=False)
location = PointField(null=True, blank=False, geography=True)
date = models.DateField(blank=True, null=True)

objects = GeoManager()

Expand Down
5 changes: 4 additions & 1 deletion tests/django_rest_tools_app/serializers.py
Expand Up @@ -3,11 +3,14 @@

from rest_framework import serializers

from django_rest_tools.fields import DateToTimeStampField
from .models import Location


class LocationListSerializer(serializers.ModelSerializer):

date = DateToTimeStampField()

class Meta:
model = Location
fields = ('id', 'name',)
fields = ('id', 'name', 'date')
71 changes: 59 additions & 12 deletions tests/django_rest_tools_app/tests.py
Expand Up @@ -3,10 +3,13 @@

from django.contrib.gis.geos import Point
from django.core.urlresolvers import reverse
from django.utils.datetime_safe import datetime
from rest_framework import status

from rest_framework.test import APITestCase

from django_rest_tools.fields import datetime_to_timestamp
from django_rest_tools_app.serializers import LocationListSerializer

from .models import Location
from .views import LocationsList

Expand All @@ -19,23 +22,34 @@
BARCELONA = 'Barcelona'
VALENCIA = 'Valencia'

class TestFactory(object):

class NearToPointFilterTest(APITestCase):
@staticmethod
def create_location(name, longitude, latitude, date=None):
if date is None:
date = datetime.now().date()

def setUp(self):

self.location_in_valencia = self._create_location(VALENCIA, -0.362286, 39.494427)
self.location_in_barcelona = self._create_location(BARCELONA, 2.1487679, 41.39479)
self.location_in_huesca = self._create_location(HUESCA, -0.4058484, 42.1359063)
self.location_in_zaragoza = self._create_location(ZARAGOZA, -0.9270592, 41.6915748)
location = Location(
name=name,
location=Point(longitude, latitude),
date=date
)

def _create_location(self, name, long, lat):
location = Location()
location.name = name
location.location = Point(long, lat)
location.save()

return location



class NearToPointFilterTest(APITestCase):

def setUp(self):

self.location_in_valencia = TestFactory.create_location(VALENCIA, -0.362286, 39.494427)
self.location_in_barcelona = TestFactory.create_location(BARCELONA, 2.1487679, 41.39479)
self.location_in_huesca = TestFactory.create_location(HUESCA, -0.4058484, 42.1359063)
self.location_in_zaragoza = TestFactory.create_location(ZARAGOZA, -0.9270592, 41.6915748)

def test_filter_is_not_applied_if_no_point_field_filter_provided(self):
LocationsList.point_field_filter = ''
response = self.client.get(reverse('location-list'))
Expand Down Expand Up @@ -75,3 +89,36 @@ def test_if_max_distance_provided_(self):
self.assertEqual(status.HTTP_200_OK, response.status_code)
self.assertEqual(1, len(response.data))
self.assertEqual(VALENCIA, response.data[0]['name'])


class DateTimeStampFieldTest(APITestCase):

def setUp(self):
self.my_date = datetime.strptime("2015-08-27", "%Y-%m-%d").date()
self.my_date_in_timestamp = datetime_to_timestamp(self.my_date)

def test_the_representation_of_date_field_is_a_timestamp(self):

location_in_valencia = TestFactory.create_location(VALENCIA, -0.362286, 39.494427, date=self.my_date)
location_serializer = LocationListSerializer(location_in_valencia)

self.assertIsInstance(location_serializer.data['date'], int)
self.assertEqual(self.my_date_in_timestamp, location_serializer.data['date'])

def test_serializer_receive_timestamp_and_stores_date_into_database(self):

data = {
'name': VALENCIA,
'location': Point(0, 0),
'date': self.my_date_in_timestamp
}

location_serializer = LocationListSerializer(data=data)

self.assertTrue(location_serializer.is_valid())

location_serializer.save()

location = Location.objects.get(id=location_serializer.data['id'])
self.assertEqual(self.my_date, location.date)

0 comments on commit fbb77a0

Please sign in to comment.