Skip to content

Commit

Permalink
Merge pull request #55557 from dwoz/jid_utc
Browse files Browse the repository at this point in the history
Use utc times for jids
  • Loading branch information
dwoz authored Dec 9, 2019
2 parents bd918de + 6f83ede commit a641281
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
11 changes: 9 additions & 2 deletions salt/utils/jid.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,13 @@
LAST_JID_DATETIME = None


def _utc_now():
'''
Helper method so tests do not have to patch the built-in method.
'''
return datetime.datetime.utcnow()


def gen_jid(opts=None):
'''
Generate a jid
Expand All @@ -27,9 +34,9 @@ def gen_jid(opts=None):
opts = {}
global LAST_JID_DATETIME # pylint: disable=global-statement

jid_dt = _utc_now()
if not opts.get('unique_jid', False):
return '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now())
jid_dt = datetime.datetime.now()
return '{0:%Y%m%d%H%M%S%f}'.format(jid_dt)
if LAST_JID_DATETIME and LAST_JID_DATETIME >= jid_dt:
jid_dt = LAST_JID_DATETIME + datetime.timedelta(microseconds=1)
LAST_JID_DATETIME = jid_dt
Expand Down
22 changes: 19 additions & 3 deletions tests/unit/utils/test_jid.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,29 @@ def test_is_jid(self):

@skipIf(NO_MOCK, NO_MOCK_REASON)
def test_gen_jid(self):
now = datetime.datetime(2002, 12, 25, 12, 00, 00, 00)
with patch('datetime.datetime'):
datetime.datetime.now.return_value = now
now = datetime.datetime(2002, 12, 25, 12, 0, 0, 0)
with patch('salt.utils.jid._utc_now', return_value=now):
ret = salt.utils.jid.gen_jid({})
self.assertEqual(ret, '20021225120000000000')
salt.utils.jid.LAST_JID_DATETIME = None
ret = salt.utils.jid.gen_jid({'unique_jid': True})
self.assertEqual(ret, '20021225120000000000_{0}'.format(os.getpid()))
ret = salt.utils.jid.gen_jid({'unique_jid': True})
self.assertEqual(ret, '20021225120000000001_{0}'.format(os.getpid()))

@skipIf(NO_MOCK, NO_MOCK_REASON)
def test_gen_jid_utc(self):
utcnow = datetime.datetime(2002, 12, 25, 12, 7, 0, 0)
with patch('salt.utils.jid._utc_now', return_value=utcnow):
ret = salt.utils.jid.gen_jid({'utc_jid': True})
self.assertEqual(ret, '20021225120700000000')

@skipIf(NO_MOCK, NO_MOCK_REASON)
def test_gen_jid_utc_unique(self):
utcnow = datetime.datetime(2002, 12, 25, 12, 7, 0, 0)
with patch('salt.utils.jid._utc_now', return_value=utcnow):
salt.utils.jid.LAST_JID_DATETIME = None
ret = salt.utils.jid.gen_jid({'utc_jid': True, 'unique_jid': True})
self.assertEqual(ret, '20021225120700000000_{0}'.format(os.getpid()))
ret = salt.utils.jid.gen_jid({'utc_jid': True, 'unique_jid': True})
self.assertEqual(ret, '20021225120700000001_{0}'.format(os.getpid()))

0 comments on commit a641281

Please sign in to comment.