diff --git a/salt/utils/jid.py b/salt/utils/jid.py index 521cccc6ce58..7e6008df3acc 100644 --- a/salt/utils/jid.py +++ b/salt/utils/jid.py @@ -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 @@ -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 diff --git a/tests/unit/utils/test_jid.py b/tests/unit/utils/test_jid.py index a988c3bcfe83..246c516a8cb4 100644 --- a/tests/unit/utils/test_jid.py +++ b/tests/unit/utils/test_jid.py @@ -35,9 +35,8 @@ 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 @@ -45,3 +44,20 @@ def test_gen_jid(self): 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()))