Skip to content

Instantly share code, notes, and snippets.

@rectalogic
Last active March 28, 2017 20:16
Show Gist options
  • Save rectalogic/e51261c47e1518610c51e5119646c3c4 to your computer and use it in GitHub Desktop.
Save rectalogic/e51261c47e1518610c51e5119646c3c4 to your computer and use it in GitHub Desktop.
>>> import contextlib
>>> import struct
>>> import bson
>>> import mock
>>>
>>> @contextlib.contextmanager
... def timed_oid(time):
... increment = [0]
... RealObjectId = bson.ObjectId
... def TimedObjectId(oid=None):
... if oid:
... return RealObjectId(oid)
... increment[0] += 1
... return TimedObjectId(struct.pack(">2I2H", int(time), 0, 0, increment[0]))
... with mock.patch('bson.ObjectId', side_effect=TimedObjectId):
... yield
...
>>> with timed_oid(6666):
... print bson.ObjectId()
... print bson.ObjectId()
... print bson.ObjectId()
... print bson.ObjectId("58dac45151c356651605250a")
... print bson.ObjectId()
...
00001a0a0000000000000001
00001a0a0000000000000002
00001a0a0000000000000003
58dac45151c356651605250a
00001a0a0000000000000004
>>> with timed_oid(7777):
... print bson.ObjectId()
... print bson.ObjectId()
... print bson.ObjectId()
... print bson.ObjectId()
...
00001e610000000000000001
00001e610000000000000002
00001e610000000000000003
00001e610000000000000004
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment