Skip to content

Commit

Permalink
Use DI for datetime so values can still be static in tests
Browse files Browse the repository at this point in the history
  • Loading branch information
David Cramer committed Jan 4, 2014
1 parent 09e51cd commit 0778fd6
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 11 deletions.
10 changes: 6 additions & 4 deletions src/sentry/coreapi.py
Expand Up @@ -206,7 +206,7 @@ def ensure_valid_project_id(desired_project, data, client=None):
data['project'] = desired_project.id


def process_data_timestamp(data):
def process_data_timestamp(data, current_datetime=None):
if is_float(data['timestamp']):
try:
data['timestamp'] = datetime.fromtimestamp(float(data['timestamp']))
Expand All @@ -225,11 +225,13 @@ def process_data_timestamp(data):
except Exception:
raise InvalidTimestamp('Invalid value for timestamp: %r' % data['timestamp'])

now = datetime.now()
if data['timestamp'] > now + timedelta(minutes=1):
if current_datetime is None:
current_datetime = datetime.now()

if data['timestamp'] > current_datetime + timedelta(minutes=1):
raise InvalidTimestamp('Invalid value for timestamp (in future): %r' % data['timestamp'])

if data['timestamp'] < now - timedelta(days=30):
if data['timestamp'] < current_datetime - timedelta(days=30):
raise InvalidTimestamp('Invalid value for timestamp (too old): %r' % data['timestamp'])

return data
Expand Down
15 changes: 8 additions & 7 deletions tests/sentry/coreapi/tests.py
Expand Up @@ -2,9 +2,10 @@

from __future__ import absolute_import

import datetime
import mock

from datetime import datetime

from sentry.models import Project, User
from sentry.exceptions import InvalidTimestamp
from sentry.coreapi import (
Expand Down Expand Up @@ -95,26 +96,26 @@ def test_invalid_secret(self):

class ProcessDataTimestampTest(BaseAPITest):
def test_iso_timestamp(self):
d = datetime(2012, 01, 01, 10, 30, 45)
data = process_data_timestamp({
'timestamp': '2012-01-01T10:30:45'
})
d = datetime.datetime(2012, 01, 01, 10, 30, 45)
}, current_datetime=d)
self.assertTrue('timestamp' in data)
self.assertEquals(data['timestamp'], d)

def test_iso_timestamp_with_ms(self):
d = datetime(2012, 01, 01, 10, 30, 45, 434000)
data = process_data_timestamp({
'timestamp': '2012-01-01T10:30:45.434'
})
d = datetime.datetime(2012, 01, 01, 10, 30, 45, 434000)
}, current_datetime=d)
self.assertTrue('timestamp' in data)
self.assertEquals(data['timestamp'], d)

def test_timestamp_iso_timestamp_with_Z(self):
d = datetime(2012, 01, 01, 10, 30, 45)
data = process_data_timestamp({
'timestamp': '2012-01-01T10:30:45Z'
})
d = datetime.datetime(2012, 01, 01, 10, 30, 45)
}, current_datetime=d)
self.assertTrue('timestamp' in data)
self.assertEquals(data['timestamp'], d)

Expand Down

0 comments on commit 0778fd6

Please sign in to comment.