diff --git a/event_count_logger.py b/event_count_logger.py index 9dd9814..ec85396 100644 --- a/event_count_logger.py +++ b/event_count_logger.py @@ -223,11 +223,15 @@ def declare_event_id(self, event_id: str): Create counter for event_id if it doesn't exist yet. Should be equivalent to listing the event ID in configuration file. """ - if event_id not in self.event_ids: - self.event_ids.add(event_id) - if self.use_local_counters: - for int_counters in self.counters: + if self.use_local_counters: + with self.counter_lock: + if event_id in self.event_ids: + return + for int_counters in self.counters.values(): int_counters[event_id] = 0 + self.event_ids.add(event_id) + elif event_id not in self.event_ids: + self.event_ids.add(event_id) def declare_event_ids(self, event_ids: Iterable[str]): """ diff --git a/tests/test_event_count_logger.py b/tests/test_event_count_logger.py new file mode 100644 index 0000000..ab3babd --- /dev/null +++ b/tests/test_event_count_logger.py @@ -0,0 +1,48 @@ +import unittest +from unittest.mock import Mock, call + +from event_count_logger import EventGroup + + +class EventGroupTest(unittest.TestCase): + def test_auto_declares_event_with_local_counters(self): + redis = Mock() + group = EventGroup( + redis, + "dynamic", + [], + ["5m", "2h"], + auto_declare=True, + sync_limit=10, + ) + + group.log("new_event", count=2) + + self.assertEqual( + { + "5m": {"new_event": 2}, + "2h": {"new_event": 2}, + }, + group.counters, + ) + + group.sync() + + self.assertEqual( + [ + call("dynamic:5m:cur:new_event", amount=2), + call("dynamic:2h:cur:new_event", amount=2), + ], + redis.incr.call_args_list, + ) + self.assertEqual( + { + "5m": {"new_event": 0}, + "2h": {"new_event": 0}, + }, + group.counters, + ) + + +if __name__ == "__main__": + unittest.main()