Browse Source

Removes direct access of timeutils.override_time

The attribute "override_time" is a private attribute which
should only be set through "timeutils.set_time_override()".
There are a number of places in Ceilometer which the override_time
attribute is set directly and such behavior should be prohibited.

However the "set_time_override()" function along with "override_time"
in timeutils is planned to be removed, therefore we no longer
need to use it.

Change-Id: I6f3a5e0bb4e4c448f369dd5ead0e1525fd2262e6
Related-Bug: #1266962
tags/2014.2.b1
Zhongyue Luo 5 years ago
parent
commit
5722c168f8

+ 7
- 5
ceilometer/storage/sqlalchemy/models.py View File

@@ -203,8 +203,9 @@ class Sample(Base):
203 203
     resource_id = Column(String(255), ForeignKey('resource.id'))
204 204
     resource_metadata = Column(JSONEncodedDict())
205 205
     volume = Column(Float(53))
206
-    timestamp = Column(PreciseTimestamp(), default=timeutils.utcnow)
207
-    recorded_at = Column(PreciseTimestamp(), default=timeutils.utcnow)
206
+    timestamp = Column(PreciseTimestamp(), default=lambda: timeutils.utcnow())
207
+    recorded_at = Column(PreciseTimestamp(),
208
+                         default=lambda: timeutils.utcnow())
208 209
     message_signature = Column(String(1000))
209 210
     message_id = Column(String(1000))
210 211
     sources = relationship("Source", secondary=lambda: sourceassoc)
@@ -278,13 +279,14 @@ class Alarm(Base):
278 279
     name = Column(Text)
279 280
     type = Column(String(50))
280 281
     description = Column(Text)
281
-    timestamp = Column(PreciseTimestamp, default=timeutils.utcnow)
282
+    timestamp = Column(PreciseTimestamp, default=lambda: timeutils.utcnow())
282 283
 
283 284
     user_id = Column(String(255))
284 285
     project_id = Column(String(255))
285 286
 
286 287
     state = Column(String(255))
287
-    state_timestamp = Column(PreciseTimestamp, default=timeutils.utcnow)
288
+    state_timestamp = Column(PreciseTimestamp,
289
+                             default=lambda: timeutils.utcnow())
288 290
 
289 291
     ok_actions = Column(JSONEncodedDict)
290 292
     alarm_actions = Column(JSONEncodedDict)
@@ -308,7 +310,7 @@ class AlarmChange(Base):
308 310
     user_id = Column(String(255), ForeignKey('user.id'))
309 311
     type = Column(String(20))
310 312
     detail = Column(Text)
311
-    timestamp = Column(PreciseTimestamp, default=timeutils.utcnow)
313
+    timestamp = Column(PreciseTimestamp, default=lambda: timeutils.utcnow())
312 314
 
313 315
 
314 316
 class EventType(Base):

+ 0
- 5
ceilometer/tests/alarm/evaluator/base.py View File

@@ -21,7 +21,6 @@
21 21
 import mock
22 22
 
23 23
 from ceilometer.openstack.common import test
24
-from ceilometer.openstack.common import timeutils
25 24
 
26 25
 
27 26
 class TestEvaluatorBase(test.BaseTestCase):
@@ -32,10 +31,6 @@ class TestEvaluatorBase(test.BaseTestCase):
32 31
         self.evaluator = self.EVALUATOR(self.notifier)
33 32
         self.prepare_alarms()
34 33
 
35
-    def tearDown(self):
36
-        super(TestEvaluatorBase, self).tearDown()
37
-        timeutils.utcnow.override_time = None
38
-
39 34
     @staticmethod
40 35
     def prepare_alarms(self):
41 36
         self.alarms = []

+ 23
- 20
ceilometer/tests/alarm/evaluator/test_base.py View File

@@ -49,7 +49,8 @@ class TestEvaluatorBaseClass(test.BaseTestCase):
49 49
                     mock.MagicMock(), mock.MagicMock())
50 50
         self.assertTrue(self.called)
51 51
 
52
-    def test_base_time_constraints(self):
52
+    @mock.patch.object(timeutils, 'utcnow')
53
+    def test_base_time_constraints(self, mock_utcnow):
53 54
         alarm = mock.MagicMock()
54 55
         alarm.time_constraints = [
55 56
             {'name': 'test',
@@ -64,16 +65,17 @@ class TestEvaluatorBaseClass(test.BaseTestCase):
64 65
              'timezone': ''},
65 66
         ]
66 67
         cls = evaluator.Evaluator
67
-        timeutils.set_time_override(datetime.datetime(2014, 1, 1, 12, 0, 0))
68
+        mock_utcnow.return_value = datetime.datetime(2014, 1, 1, 12, 0, 0)
68 69
         self.assertTrue(cls.within_time_constraint(alarm))
69 70
 
70
-        timeutils.set_time_override(datetime.datetime(2014, 1, 2, 1, 0, 0))
71
+        mock_utcnow.return_value = datetime.datetime(2014, 1, 2, 1, 0, 0)
71 72
         self.assertTrue(cls.within_time_constraint(alarm))
72 73
 
73
-        timeutils.set_time_override(datetime.datetime(2014, 1, 2, 5, 0, 0))
74
+        mock_utcnow.return_value = datetime.datetime(2014, 1, 2, 5, 0, 0)
74 75
         self.assertFalse(cls.within_time_constraint(alarm))
75 76
 
76
-    def test_base_time_constraints_complex(self):
77
+    @mock.patch.object(timeutils, 'utcnow')
78
+    def test_base_time_constraints_complex(self, mock_utcnow):
77 79
         alarm = mock.MagicMock()
78 80
         alarm.time_constraints = [
79 81
             {'name': 'test',
@@ -87,38 +89,39 @@ class TestEvaluatorBaseClass(test.BaseTestCase):
87 89
         cls = evaluator.Evaluator
88 90
 
89 91
         # test minutes inside
90
-        timeutils.set_time_override(datetime.datetime(2014, 1, 5, 3, 3, 0))
92
+        mock_utcnow.return_value = datetime.datetime(2014, 1, 5, 3, 3, 0)
91 93
         self.assertTrue(cls.within_time_constraint(alarm))
92
-        timeutils.set_time_override(datetime.datetime(2014, 1, 5, 3, 31, 0))
94
+        mock_utcnow.return_value = datetime.datetime(2014, 1, 5, 3, 31, 0)
93 95
         self.assertTrue(cls.within_time_constraint(alarm))
94
-        timeutils.set_time_override(datetime.datetime(2014, 1, 5, 3, 57, 0))
96
+        mock_utcnow.return_value = datetime.datetime(2014, 1, 5, 3, 57, 0)
95 97
         self.assertTrue(cls.within_time_constraint(alarm))
96 98
 
97 99
         # test minutes outside
98
-        timeutils.set_time_override(datetime.datetime(2014, 1, 5, 3, 2, 0))
100
+        mock_utcnow.return_value = datetime.datetime(2014, 1, 5, 3, 2, 0)
99 101
         self.assertFalse(cls.within_time_constraint(alarm))
100
-        timeutils.set_time_override(datetime.datetime(2014, 1, 5, 3, 4, 0))
102
+        mock_utcnow.return_value = datetime.datetime(2014, 1, 5, 3, 4, 0)
101 103
         self.assertFalse(cls.within_time_constraint(alarm))
102
-        timeutils.set_time_override(datetime.datetime(2014, 1, 5, 3, 58, 0))
104
+        mock_utcnow.return_value = datetime.datetime(2014, 1, 5, 3, 58, 0)
103 105
         self.assertFalse(cls.within_time_constraint(alarm))
104 106
 
105 107
         # test hours inside
106
-        timeutils.set_time_override(datetime.datetime(2014, 1, 5, 3, 31, 0))
108
+        mock_utcnow.return_value = datetime.datetime(2014, 1, 5, 3, 31, 0)
107 109
         self.assertTrue(cls.within_time_constraint(alarm))
108
-        timeutils.set_time_override(datetime.datetime(2014, 1, 5, 5, 31, 0))
110
+        mock_utcnow.return_value = datetime.datetime(2014, 1, 5, 5, 31, 0)
109 111
         self.assertTrue(cls.within_time_constraint(alarm))
110
-        timeutils.set_time_override(datetime.datetime(2014, 1, 5, 11, 31, 0))
112
+        mock_utcnow.return_value = datetime.datetime(2014, 1, 5, 11, 31, 0)
111 113
         self.assertTrue(cls.within_time_constraint(alarm))
112 114
 
113 115
         # test hours outside
114
-        timeutils.set_time_override(datetime.datetime(2014, 1, 5, 1, 31, 0))
116
+        mock_utcnow.return_value = datetime.datetime(2014, 1, 5, 1, 31, 0)
115 117
         self.assertFalse(cls.within_time_constraint(alarm))
116
-        timeutils.set_time_override(datetime.datetime(2014, 1, 5, 4, 31, 0))
118
+        mock_utcnow.return_value = datetime.datetime(2014, 1, 5, 4, 31, 0)
117 119
         self.assertFalse(cls.within_time_constraint(alarm))
118
-        timeutils.set_time_override(datetime.datetime(2014, 1, 5, 12, 31, 0))
120
+        mock_utcnow.return_value = datetime.datetime(2014, 1, 5, 12, 31, 0)
119 121
         self.assertFalse(cls.within_time_constraint(alarm))
120 122
 
121
-    def test_base_time_constraints_timezone(self):
123
+    @mock.patch.object(timeutils, 'utcnow')
124
+    def test_base_time_constraints_timezone(self, mock_utcnow):
122 125
         alarm = mock.MagicMock()
123 126
         alarm.time_constraints = [
124 127
             {'name': 'test',
@@ -132,8 +135,8 @@ class TestEvaluatorBaseClass(test.BaseTestCase):
132 135
                                   tzinfo=pytz.timezone('Europe/Ljubljana'))
133 136
         dt_us = datetime.datetime(2014, 1, 1, 12, 0, 0,
134 137
                                   tzinfo=pytz.timezone('US/Eastern'))
135
-        timeutils.set_time_override(dt_eu.astimezone(pytz.UTC))
138
+        mock_utcnow.return_value = dt_eu.astimezone(pytz.UTC)
136 139
         self.assertTrue(cls.within_time_constraint(alarm))
137 140
 
138
-        timeutils.set_time_override(dt_us.astimezone(pytz.UTC))
141
+        mock_utcnow.return_value = dt_us.astimezone(pytz.UTC)
139 142
         self.assertFalse(cls.within_time_constraint(alarm))

+ 6
- 4
ceilometer/tests/alarm/evaluator/test_combination.py View File

@@ -310,7 +310,8 @@ class TestEvaluate(base.TestEvaluatorBase):
310 310
 
311 311
             self.assertEqual(expected, self.notifier.notify.call_args_list)
312 312
 
313
-    def test_state_change_inside_time_constraint(self):
313
+    @mock.patch.object(timeutils, 'utcnow')
314
+    def test_state_change_inside_time_constraint(self, mock_utcnow):
314 315
         self._set_all_alarms('insufficient data')
315 316
         self.alarms[0].time_constraints = [
316 317
             {'name': 'test',
@@ -322,9 +323,9 @@ class TestEvaluate(base.TestEvaluatorBase):
322 323
         self.alarms[1].time_constraints = self.alarms[0].time_constraints
323 324
         dt = datetime.datetime(2014, 1, 1, 12, 0, 0,
324 325
                                tzinfo=pytz.timezone('Europe/Ljubljana'))
326
+        mock_utcnow.return_value = dt.astimezone(pytz.UTC)
325 327
         with mock.patch('ceilometerclient.client.get_client',
326 328
                         return_value=self.api_client):
327
-            timeutils.set_time_override(dt.astimezone(pytz.UTC))
328 329
             self.api_client.alarms.get.side_effect = [
329 330
                 self._get_alarm('ok'),
330 331
                 self._get_alarm('ok'),
@@ -348,7 +349,8 @@ class TestEvaluate(base.TestEvaluatorBase):
348 349
                         in zip(self.alarms, reasons, reason_datas)]
349 350
             self.assertEqual(expected, self.notifier.notify.call_args_list)
350 351
 
351
-    def test_no_state_change_outside_time_constraint(self):
352
+    @mock.patch.object(timeutils, 'utcnow')
353
+    def test_no_state_change_outside_time_constraint(self, mock_utcnow):
352 354
         self._set_all_alarms('insufficient data')
353 355
         self.alarms[0].time_constraints = [
354 356
             {'name': 'test',
@@ -360,9 +362,9 @@ class TestEvaluate(base.TestEvaluatorBase):
360 362
         self.alarms[1].time_constraints = self.alarms[0].time_constraints
361 363
         dt = datetime.datetime(2014, 1, 1, 15, 0, 0,
362 364
                                tzinfo=pytz.timezone('Europe/Ljubljana'))
365
+        mock_utcnow.return_value = dt.astimezone(pytz.UTC)
363 366
         with mock.patch('ceilometerclient.client.get_client',
364 367
                         return_value=self.api_client):
365
-            timeutils.set_time_override(dt.astimezone(pytz.UTC))
366 368
             self.api_client.alarms.get.side_effect = [
367 369
                 self._get_alarm('ok'),
368 370
                 self._get_alarm('ok'),

+ 17
- 14
ceilometer/tests/alarm/evaluator/test_threshold.py View File

@@ -322,16 +322,17 @@ class TestEvaluate(base.TestEvaluatorBase):
322 322
         alarm = self.alarms[0]
323 323
         if exclude_outliers is not None:
324 324
             alarm.rule['exclude_outliers'] = exclude_outliers
325
-        timeutils.utcnow.override_time = datetime.datetime(2012, 7, 2, 10, 45)
326
-        constraint = self.evaluator._bound_duration(alarm, [])
327
-        self.assertEqual([
328
-            {'field': 'timestamp',
329
-             'op': 'le',
330
-             'value': timeutils.utcnow().isoformat()},
331
-            {'field': 'timestamp',
332
-             'op': 'ge',
333
-             'value': start},
334
-        ], constraint)
325
+        with mock.patch.object(timeutils, 'utcnow') as mock_utcnow:
326
+            mock_utcnow.return_value = datetime.datetime(2012, 7, 2, 10, 45)
327
+            constraint = self.evaluator._bound_duration(alarm, [])
328
+            self.assertEqual([
329
+                {'field': 'timestamp',
330
+                 'op': 'le',
331
+                 'value': timeutils.utcnow().isoformat()},
332
+                {'field': 'timestamp',
333
+                 'op': 'ge',
334
+                 'value': start},
335
+            ], constraint)
335 336
 
336 337
     def test_bound_duration_outlier_exclusion_defaulted(self):
337 338
         self._do_test_bound_duration('2012-07-02T10:39:00')
@@ -448,7 +449,8 @@ class TestEvaluate(base.TestEvaluatorBase):
448 449
     def test_simple_alarm_no_clear_without_outlier_exclusion(self):
449 450
         self. _do_test_simple_alarm_clear_outlier_exclusion(False)
450 451
 
451
-    def test_state_change_inside_time_constraint(self):
452
+    @mock.patch.object(timeutils, 'utcnow')
453
+    def test_state_change_inside_time_constraint(self, mock_utcnow):
452 454
         self._set_all_alarms('ok')
453 455
         self.alarms[0].time_constraints = [
454 456
             {'name': 'test',
@@ -460,9 +462,9 @@ class TestEvaluate(base.TestEvaluatorBase):
460 462
         self.alarms[1].time_constraints = self.alarms[0].time_constraints
461 463
         dt = datetime.datetime(2014, 1, 1, 12, 0, 0,
462 464
                                tzinfo=pytz.timezone('Europe/Ljubljana'))
465
+        mock_utcnow.return_value = dt.astimezone(pytz.UTC)
463 466
         with mock.patch('ceilometerclient.client.get_client',
464 467
                         return_value=self.api_client):
465
-            timeutils.set_time_override(dt.astimezone(pytz.UTC))
466 468
             # the following part based on test_simple_insufficient
467 469
             self.api_client.statistics.list.return_value = []
468 470
             self._evaluate_all_alarms()
@@ -485,7 +487,8 @@ class TestEvaluate(base.TestEvaluatorBase):
485 487
                 for alarm in self.alarms]
486 488
             self.assertEqual(expected, self.notifier.notify.call_args_list)
487 489
 
488
-    def test_no_state_change_outside_time_constraint(self):
490
+    @mock.patch.object(timeutils, 'utcnow')
491
+    def test_no_state_change_outside_time_constraint(self, mock_utcnow):
489 492
         self._set_all_alarms('ok')
490 493
         self.alarms[0].time_constraints = [
491 494
             {'name': 'test',
@@ -497,9 +500,9 @@ class TestEvaluate(base.TestEvaluatorBase):
497 500
         self.alarms[1].time_constraints = self.alarms[0].time_constraints
498 501
         dt = datetime.datetime(2014, 1, 1, 15, 0, 0,
499 502
                                tzinfo=pytz.timezone('Europe/Ljubljana'))
503
+        mock_utcnow.return_value = dt.astimezone(pytz.UTC)
500 504
         with mock.patch('ceilometerclient.client.get_client',
501 505
                         return_value=self.api_client):
502
-            timeutils.set_time_override(dt.astimezone(pytz.UTC))
503 506
             self.api_client.statistics.list.return_value = []
504 507
             self._evaluate_all_alarms()
505 508
             self._assert_all_alarms('ok')

+ 5
- 3
ceilometer/tests/alarm/partition/test_coordination.py View File

@@ -42,7 +42,10 @@ class TestCoordinate(test.BaseTestCase):
42 42
                                group='alarm')
43 43
         self.api_client = mock.Mock()
44 44
         self.override_start = datetime.datetime(2012, 7, 2, 10, 45)
45
-        timeutils.utcnow.override_time = self.override_start
45
+        patcher = mock.patch.object(timeutils, 'utcnow')
46
+        self.addCleanup(patcher.stop)
47
+        self.mock_utcnow = patcher.start()
48
+        self.mock_utcnow.return_value = self.override_start
46 49
         self.partition_coordinator = coordination.PartitionCoordinator()
47 50
         self.partition_coordinator.coordination_rpc = mock.Mock()
48 51
         #add extra logger to check exception conditions and logged content
@@ -52,7 +55,6 @@ class TestCoordinate(test.BaseTestCase):
52 55
 
53 56
     def tearDown(self):
54 57
         super(TestCoordinate, self).tearDown()
55
-        timeutils.utcnow.override_time = None
56 58
         # clean up the logger
57 59
         coordination.LOG.logger.removeHandler(self.str_handler)
58 60
         self.output.close()
@@ -112,7 +114,7 @@ class TestCoordinate(test.BaseTestCase):
112 114
 
113 115
     def _advance_time(self, factor):
114 116
         delta = datetime.timedelta(seconds=self.test_interval * factor)
115
-        timeutils.utcnow.override_time += delta
117
+        self.mock_utcnow.return_value = timeutils.utcnow() + delta
116 118
 
117 119
     def _younger_by(self, offset):
118 120
         return self.partition_coordinator.this.priority + offset

+ 6
- 3
ceilometer/tests/api/v2/test_list_events_scenarios.py View File

@@ -21,6 +21,7 @@
21 21
 import datetime
22 22
 import logging
23 23
 
24
+import mock
24 25
 import webtest.app
25 26
 
26 27
 from ceilometer.openstack.common import timeutils
@@ -38,7 +39,10 @@ class TestListEvents(FunctionalTest,
38 39
 
39 40
     def setUp(self):
40 41
         super(TestListEvents, self).setUp()
41
-        timeutils.utcnow.override_time = datetime.datetime(2014, 2, 11, 16, 42)
42
+        patcher = mock.patch.object(timeutils, 'utcnow')
43
+        self.addCleanup(patcher.stop)
44
+        self.mock_utcnow = patcher.start()
45
+        self.mock_utcnow.return_value = datetime.datetime(2014, 2, 11, 16, 42)
42 46
         self.sample1 = sample.Sample(
43 47
             'instance',
44 48
             'cumulative',
@@ -85,8 +89,7 @@ class TestListEvents(FunctionalTest,
85 89
         data = self.get_json('/meters/instance')
86 90
         self.assertEqual(2, len(data))
87 91
         for s in data:
88
-            self.assertEqual(timeutils.utcnow.override_time.isoformat(),
89
-                             s['recorded_at'])
92
+            self.assertEqual(timeutils.utcnow().isoformat(), s['recorded_at'])
90 93
 
91 94
     def test_all_trailing_slash(self):
92 95
         data = self.get_json('/meters/instance/')

+ 6
- 4
ceilometer/tests/storage/test_impl_sqlalchemy.py View File

@@ -176,8 +176,9 @@ class RelationshipTest(scenarios.DBTestBase):
176 176
     # don't want to automatically inherit all the Meter setup.
177 177
     database_connection = 'sqlite://'
178 178
 
179
-    def test_clear_metering_data_meta_tables(self):
180
-        timeutils.utcnow.override_time = datetime.datetime(2012, 7, 2, 10, 45)
179
+    @patch.object(timeutils, 'utcnow')
180
+    def test_clear_metering_data_meta_tables(self, mock_utcnow):
181
+        mock_utcnow.return_value = datetime.datetime(2012, 7, 2, 10, 45)
181 182
         self.conn.clear_expired_metering_data(3 * 60)
182 183
 
183 184
         session = self.conn._engine_facade.get_session()
@@ -190,8 +191,9 @@ class RelationshipTest(scenarios.DBTestBase):
190 191
                         .group_by(sql_models.Sample.id)
191 192
                         )).count())
192 193
 
193
-    def test_clear_metering_data_associations(self):
194
-        timeutils.utcnow.override_time = datetime.datetime(2012, 7, 2, 10, 45)
194
+    @patch.object(timeutils, 'utcnow')
195
+    def test_clear_metering_data_associations(self, mock_utcnow):
196
+        mock_utcnow.return_value = datetime.datetime(2012, 7, 2, 10, 45)
195 197
         self.conn.clear_expired_metering_data(3 * 60)
196 198
 
197 199
         session = self.conn._engine_facade.get_session()

+ 9
- 5
ceilometer/tests/storage/test_storage_scenarios.py View File

@@ -22,6 +22,8 @@
22 22
 
23 23
 import datetime
24 24
 
25
+import mock
26
+
25 27
 from ceilometer.openstack.common import timeutils
26 28
 from ceilometer.publisher import utils
27 29
 from ceilometer import sample
@@ -56,8 +58,10 @@ class DBTestBase(tests_db.TestBase):
56 58
 
57 59
     def setUp(self):
58 60
         super(DBTestBase, self).setUp()
59
-        timeutils.set_time_override(
60
-            datetime.datetime(2015, 7, 2, 10, 39))
61
+        patcher = mock.patch.object(timeutils, 'utcnow')
62
+        self.addCleanup(patcher.stop)
63
+        self.mock_utcnow = patcher.start()
64
+        self.mock_utcnow.return_value = datetime.datetime(2015, 7, 2, 10, 39)
61 65
         self.prepare_data()
62 66
 
63 67
     def prepare_data(self):
@@ -654,7 +658,7 @@ class RawSampleTest(DBTestBase,
654 658
         if self.CONF.database.connection.startswith('mongodb://'):
655 659
             return
656 660
 
657
-        timeutils.utcnow.override_time = datetime.datetime(2012, 7, 2, 10, 45)
661
+        self.mock_utcnow.return_value = datetime.datetime(2012, 7, 2, 10, 45)
658 662
         self.conn.clear_expired_metering_data(3 * 60)
659 663
         f = storage.SampleFilter(meter='instance')
660 664
         results = list(self.conn.get_samples(f))
@@ -672,7 +676,7 @@ class RawSampleTest(DBTestBase,
672 676
         if self.CONF.database.connection.startswith('mongodb://'):
673 677
             return
674 678
 
675
-        timeutils.utcnow.override_time = datetime.datetime(2010, 7, 2, 10, 45)
679
+        self.mock_utcnow.return_value = datetime.datetime(2010, 7, 2, 10, 45)
676 680
         self.conn.clear_expired_metering_data(3 * 60)
677 681
         f = storage.SampleFilter(meter='instance')
678 682
         results = list(self.conn.get_samples(f))
@@ -718,7 +722,7 @@ class RawSampleTest(DBTestBase,
718 722
                              )
719 723
 
720 724
         self.conn.create_alarm(alarm)
721
-        timeutils.utcnow.override_time = datetime.datetime(2012, 7, 2, 10, 45)
725
+        self.mock_utcnow.return_value = datetime.datetime(2012, 7, 2, 10, 45)
722 726
         self.conn.clear_expired_metering_data(5)
723 727
         f = storage.SampleFilter(meter='instance')
724 728
         results = list(self.conn.get_samples(f))

Loading…
Cancel
Save