Add mocking support for now function in AttributionProcessor
In the regression test in changeid: I1709af943b6fa238dd4df41a62e6add36984c9ec
The triggering of the code we want to test depends on the return
value of std::chrono::system_clock::now(). To facilicate testing,
in this patch we add a now_func_ (a std::function) field in
AttributionProcessor and make it call it instead of
std::chrono::system_clock::now(). Mocking `now` is made possible
by passing a custom function to the constructor of AttributionProcessor.
Bug: 254774758
Test: refactoring, existing tests still pass
Ignore-AOSP-First: security
Change-Id: I7dd3a0e665f72c27e4d1844f45ec15a8dd1ddb53
(cherry picked from commit fb9a519eed94776a488c5dcf0fa91d620bfc9e88)
Merged-In: I7dd3a0e665f72c27e4d1844f45ec15a8dd1ddb53
diff --git a/system/gd/btaa/attribution_processor.h b/system/gd/btaa/attribution_processor.h
index d18a8ce..e28e6cb 100644
--- a/system/gd/btaa/attribution_processor.h
+++ b/system/gd/btaa/attribution_processor.h
@@ -82,7 +82,20 @@
void Dump(
std::promise<flatbuffers::Offset<ActivityAttributionData>> promise, flatbuffers::FlatBufferBuilder* fb_builder);
+ using ClockType = std::chrono::time_point<std::chrono::system_clock>;
+ using NowFunc = ClockType (*)();
+
+ // by default, we use the std::chrono::system_clock::now implementation to
+ // get the current timestamp
+ AttributionProcessor() : now_func_(std::chrono::system_clock::now) {}
+ // in other cases, we may need to use different implementation
+ // e.g., for testing purposes
+ AttributionProcessor(NowFunc func) : now_func_(func) {}
+
private:
+ // this function is added for testing support in
+ // OnWakelockReleased
+ NowFunc now_func_ = std::chrono::system_clock::now;
bool wakeup_ = false;
std::unordered_map<AddressActivityKey, BtaaAggregationEntry, AddressActivityKeyHasher> btaa_aggregator_;
std::unordered_map<AddressActivityKey, BtaaAggregationEntry, AddressActivityKeyHasher> wakelock_duration_aggregator_;
diff --git a/system/gd/btaa/linux_generic/attribution_processor.cc b/system/gd/btaa/linux_generic/attribution_processor.cc
index baa0c07..eadad9d 100644
--- a/system/gd/btaa/linux_generic/attribution_processor.cc
+++ b/system/gd/btaa/linux_generic/attribution_processor.cc
@@ -69,7 +69,7 @@
return;
}
- auto cur_time = std::chrono::system_clock::now();
+ auto cur_time = now_func_();
for (auto& it : wakelock_duration_aggregator_) {
it.second.wakelock_duration_ms = (uint64_t)duration_ms * it.second.byte_count / total_byte_count;
if (btaa_aggregator_.find(it.first) == btaa_aggregator_.end()) {