Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TimedeltaField improvement #17

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions extras_mongoengine/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ def to_mongo(self, value):
return self.prepare_query_value(None, value)

def to_python(self, value):
if isinstance(value, timedelta):
return value
return timedelta(seconds=value)

def prepare_query_value(self, op, value):
Expand Down
24 changes: 24 additions & 0 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,18 @@ def total_seconds(self):
raise AttributeError

class TimedeltaFieldTestCase(unittest.TestCase):

def setUp(self):
connect(db='extrasmongoenginetest')
self.db = get_db()
self.field = TimedeltaField()

def tearDown(self):
for collection in self.db.collection_names():
if 'system.' in collection:
continue
self.db.drop_collection(collection)

def test_construct(self):
self.assertIsInstance(self.field, TimedeltaField)

Expand All @@ -29,6 +38,21 @@ def test_total_seconds_26(self):
value = OldStyleTimedelta(minutes=1, seconds=10)
self.assertEqual(self.field.total_seconds(value), 70)

def test_number_initialization(self):
class Doc(Document):
time = TimedeltaField()

doc = Doc(time=3600).save()
self.assertEqual(doc.time, timedelta(hours=1))

def test_timedelta_initialization(self):
class Doc(Document):
time = TimedeltaField()

test_time = timedelta(days=2)
doc = Doc(time=test_time).save()
self.assertEqual(doc.time, test_time)

class LowerStringFieldTestCase(unittest.TestCase):

def setUp(self):
Expand Down