fake_reporting_settings.cc 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright 2021 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "components/reporting/metrics/fake_reporting_settings.h"
  5. #include "base/containers/contains.h"
  6. #include "base/run_loop.h"
  7. #include "base/threading/sequenced_task_runner_handle.h"
  8. namespace reporting {
  9. namespace test {
  10. FakeReportingSettings::FakeReportingSettings() = default;
  11. FakeReportingSettings::~FakeReportingSettings() = default;
  12. base::CallbackListSubscription FakeReportingSettings::AddSettingsObserver(
  13. const std::string& path,
  14. base::RepeatingClosure callback) {
  15. if (!base::Contains(settings_callbacks_map_, path)) {
  16. settings_callbacks_map_[path] =
  17. std::make_unique<base::RepeatingClosureList>();
  18. }
  19. return settings_callbacks_map_.at(path)->Add(std::move(callback));
  20. }
  21. bool FakeReportingSettings::PrepareTrustedValues(base::OnceClosure callback) {
  22. if (!is_trusted_) {
  23. trusted_callbacks_.push(std::move(callback));
  24. }
  25. return is_trusted_;
  26. }
  27. bool FakeReportingSettings::GetBoolean(const std::string& path,
  28. bool* out_value) const {
  29. if (!base::Contains(bool_map_, path)) {
  30. return false;
  31. }
  32. *out_value = bool_map_.at(path);
  33. return true;
  34. }
  35. bool FakeReportingSettings::GetInteger(const std::string& path,
  36. int* out_value) const {
  37. if (!base::Contains(int_map_, path)) {
  38. return false;
  39. }
  40. *out_value = int_map_.at(path);
  41. return true;
  42. }
  43. void FakeReportingSettings::SetBoolean(const std::string& path,
  44. bool bool_value) {
  45. bool_map_[path] = bool_value;
  46. if (base::Contains(settings_callbacks_map_, path)) {
  47. settings_callbacks_map_.at(path)->Notify();
  48. }
  49. }
  50. void FakeReportingSettings::SetInteger(const std::string& path, int int_value) {
  51. int_map_[path] = int_value;
  52. if (base::Contains(settings_callbacks_map_, path)) {
  53. settings_callbacks_map_.at(path)->Notify();
  54. }
  55. }
  56. void FakeReportingSettings::SetIsTrusted(bool is_trusted) {
  57. base::RunLoop run_loop;
  58. is_trusted_ = is_trusted;
  59. while (!trusted_callbacks_.empty()) {
  60. std::move(trusted_callbacks_.front()).Run();
  61. trusted_callbacks_.pop();
  62. }
  63. base::SequencedTaskRunnerHandle::Get()->PostTask(FROM_HERE,
  64. run_loop.QuitClosure());
  65. run_loop.Run();
  66. }
  67. } // namespace test
  68. } // namespace reporting