histogram_unittest.cc 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  1. // Copyright (c) 2012 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 "base/metrics/histogram.h"
  5. #include <limits.h>
  6. #include <stddef.h>
  7. #include <stdint.h>
  8. #include <climits>
  9. #include <memory>
  10. #include <string>
  11. #include <vector>
  12. #include "base/lazy_instance.h"
  13. #include "base/logging.h"
  14. #include "base/memory/raw_ptr.h"
  15. #include "base/metrics/bucket_ranges.h"
  16. #include "base/metrics/dummy_histogram.h"
  17. #include "base/metrics/histogram_macros.h"
  18. #include "base/metrics/metrics_hashes.h"
  19. #include "base/metrics/persistent_histogram_allocator.h"
  20. #include "base/metrics/persistent_memory_allocator.h"
  21. #include "base/metrics/record_histogram_checker.h"
  22. #include "base/metrics/sample_vector.h"
  23. #include "base/metrics/statistics_recorder.h"
  24. #include "base/pickle.h"
  25. #include "base/strings/stringprintf.h"
  26. #include "base/test/gtest_util.h"
  27. #include "base/time/time.h"
  28. #include "base/values.h"
  29. #include "testing/gmock/include/gmock/gmock.h"
  30. #include "testing/gtest/include/gtest/gtest.h"
  31. namespace base {
  32. namespace {
  33. const char kExpiredHistogramName[] = "ExpiredHistogram";
  34. // Test implementation of RecordHistogramChecker interface.
  35. class TestRecordHistogramChecker : public RecordHistogramChecker {
  36. public:
  37. ~TestRecordHistogramChecker() override = default;
  38. // RecordHistogramChecker:
  39. bool ShouldRecord(uint32_t histogram_hash) const override {
  40. return histogram_hash != HashMetricNameAs32Bits(kExpiredHistogramName);
  41. }
  42. };
  43. } // namespace
  44. // Test parameter indicates if a persistent memory allocator should be used
  45. // for histogram allocation. False will allocate histograms from the process
  46. // heap.
  47. class HistogramTest : public testing::TestWithParam<bool> {
  48. public:
  49. HistogramTest(const HistogramTest&) = delete;
  50. HistogramTest& operator=(const HistogramTest&) = delete;
  51. protected:
  52. using CountAndBucketData = base::Histogram::CountAndBucketData;
  53. const int32_t kAllocatorMemorySize = 8 << 20; // 8 MiB
  54. HistogramTest() : use_persistent_histogram_allocator_(GetParam()) {}
  55. void SetUp() override {
  56. if (use_persistent_histogram_allocator_)
  57. CreatePersistentHistogramAllocator();
  58. // Each test will have a clean state (no Histogram / BucketRanges
  59. // registered).
  60. InitializeStatisticsRecorder();
  61. }
  62. void TearDown() override {
  63. if (allocator_) {
  64. ASSERT_FALSE(allocator_->IsFull());
  65. ASSERT_FALSE(allocator_->IsCorrupt());
  66. }
  67. UninitializeStatisticsRecorder();
  68. DestroyPersistentHistogramAllocator();
  69. }
  70. void InitializeStatisticsRecorder() {
  71. DCHECK(!statistics_recorder_);
  72. statistics_recorder_ = StatisticsRecorder::CreateTemporaryForTesting();
  73. }
  74. void UninitializeStatisticsRecorder() { statistics_recorder_.reset(); }
  75. void CreatePersistentHistogramAllocator() {
  76. GlobalHistogramAllocator::CreateWithLocalMemory(kAllocatorMemorySize, 0,
  77. "HistogramAllocatorTest");
  78. allocator_ = GlobalHistogramAllocator::Get()->memory_allocator();
  79. }
  80. void DestroyPersistentHistogramAllocator() {
  81. allocator_ = nullptr;
  82. GlobalHistogramAllocator::ReleaseForTesting();
  83. }
  84. std::unique_ptr<SampleVector> SnapshotAllSamples(Histogram* h) {
  85. return h->SnapshotAllSamples();
  86. }
  87. CountAndBucketData GetCountAndBucketData(Histogram* histogram) {
  88. // A simple wrapper around |GetCountAndBucketData| to make it visible for
  89. // testing.
  90. return histogram->GetCountAndBucketData();
  91. }
  92. const bool use_persistent_histogram_allocator_;
  93. std::unique_ptr<StatisticsRecorder> statistics_recorder_;
  94. std::unique_ptr<char[]> allocator_memory_;
  95. raw_ptr<PersistentMemoryAllocator> allocator_ = nullptr;
  96. };
  97. // Run all HistogramTest cases with both heap and persistent memory.
  98. INSTANTIATE_TEST_SUITE_P(HeapAndPersistent, HistogramTest, testing::Bool());
  99. // Check for basic syntax and use.
  100. TEST_P(HistogramTest, BasicTest) {
  101. // Try basic construction
  102. HistogramBase* histogram = Histogram::FactoryGet("TestHistogram", 1, 1000, 10,
  103. HistogramBase::kNoFlags);
  104. EXPECT_TRUE(histogram);
  105. HistogramBase* linear_histogram = LinearHistogram::FactoryGet(
  106. "TestLinearHistogram", 1, 1000, 10, HistogramBase::kNoFlags);
  107. EXPECT_TRUE(linear_histogram);
  108. std::vector<int> custom_ranges;
  109. custom_ranges.push_back(1);
  110. custom_ranges.push_back(5);
  111. HistogramBase* custom_histogram = CustomHistogram::FactoryGet(
  112. "TestCustomHistogram", custom_ranges, HistogramBase::kNoFlags);
  113. EXPECT_TRUE(custom_histogram);
  114. // Macros that create histograms have an internal static variable which will
  115. // continue to point to those from the very first run of this method even
  116. // during subsequent runs.
  117. static bool already_run = false;
  118. if (already_run)
  119. return;
  120. already_run = true;
  121. // Use standard macros (but with fixed samples)
  122. LOCAL_HISTOGRAM_TIMES("Test2Histogram", Days(1));
  123. LOCAL_HISTOGRAM_COUNTS("Test3Histogram", 30);
  124. LOCAL_HISTOGRAM_ENUMERATION("Test6Histogram", 129, 130);
  125. }
  126. // Check that the macro correctly matches histograms by name and records their
  127. // data together.
  128. TEST_P(HistogramTest, NameMatchTest) {
  129. // Macros that create histograms have an internal static variable which will
  130. // continue to point to those from the very first run of this method even
  131. // during subsequent runs.
  132. static bool already_run = false;
  133. if (already_run)
  134. return;
  135. already_run = true;
  136. LOCAL_HISTOGRAM_PERCENTAGE("DuplicatedHistogram", 10);
  137. LOCAL_HISTOGRAM_PERCENTAGE("DuplicatedHistogram", 10);
  138. HistogramBase* histogram = LinearHistogram::FactoryGet(
  139. "DuplicatedHistogram", 1, 101, 102, HistogramBase::kNoFlags);
  140. std::unique_ptr<HistogramSamples> samples = histogram->SnapshotSamples();
  141. EXPECT_EQ(2, samples->TotalCount());
  142. EXPECT_EQ(2, samples->GetCount(10));
  143. }
  144. // Check that delta calculations work correctly.
  145. TEST_P(HistogramTest, DeltaTest) {
  146. HistogramBase* histogram = Histogram::FactoryGet("DeltaHistogram", 1, 64, 8,
  147. HistogramBase::kNoFlags);
  148. histogram->Add(1);
  149. histogram->Add(10);
  150. histogram->Add(50);
  151. std::unique_ptr<HistogramSamples> samples = histogram->SnapshotDelta();
  152. EXPECT_EQ(3, samples->TotalCount());
  153. EXPECT_EQ(1, samples->GetCount(1));
  154. EXPECT_EQ(1, samples->GetCount(10));
  155. EXPECT_EQ(1, samples->GetCount(50));
  156. EXPECT_EQ(samples->TotalCount(), samples->redundant_count());
  157. samples = histogram->SnapshotDelta();
  158. EXPECT_EQ(0, samples->TotalCount());
  159. histogram->Add(10);
  160. histogram->Add(10);
  161. samples = histogram->SnapshotDelta();
  162. EXPECT_EQ(2, samples->TotalCount());
  163. EXPECT_EQ(2, samples->GetCount(10));
  164. samples = histogram->SnapshotDelta();
  165. EXPECT_EQ(0, samples->TotalCount());
  166. }
  167. // Check that final-delta calculations work correctly.
  168. TEST_P(HistogramTest, FinalDeltaTest) {
  169. HistogramBase* histogram = Histogram::FactoryGet("FinalDeltaHistogram", 1, 64,
  170. 8, HistogramBase::kNoFlags);
  171. histogram->Add(1);
  172. histogram->Add(10);
  173. histogram->Add(50);
  174. std::unique_ptr<HistogramSamples> samples = histogram->SnapshotDelta();
  175. EXPECT_EQ(3, samples->TotalCount());
  176. EXPECT_EQ(1, samples->GetCount(1));
  177. EXPECT_EQ(1, samples->GetCount(10));
  178. EXPECT_EQ(1, samples->GetCount(50));
  179. EXPECT_EQ(samples->TotalCount(), samples->redundant_count());
  180. histogram->Add(2);
  181. histogram->Add(50);
  182. samples = histogram->SnapshotFinalDelta();
  183. EXPECT_EQ(2, samples->TotalCount());
  184. EXPECT_EQ(1, samples->GetCount(2));
  185. EXPECT_EQ(1, samples->GetCount(50));
  186. EXPECT_EQ(samples->TotalCount(), samples->redundant_count());
  187. }
  188. TEST_P(HistogramTest, ExponentialRangesTest) {
  189. // Check that we got a nice exponential when there was enough room.
  190. BucketRanges ranges(9);
  191. Histogram::InitializeBucketRanges(1, 64, &ranges);
  192. EXPECT_EQ(0, ranges.range(0));
  193. int power_of_2 = 1;
  194. for (int i = 1; i < 8; i++) {
  195. EXPECT_EQ(power_of_2, ranges.range(i));
  196. power_of_2 *= 2;
  197. }
  198. EXPECT_EQ(HistogramBase::kSampleType_MAX, ranges.range(8));
  199. // Check the corresponding Histogram will use the correct ranges.
  200. Histogram* histogram = static_cast<Histogram*>(
  201. Histogram::FactoryGet("Histogram", 1, 64, 8, HistogramBase::kNoFlags));
  202. EXPECT_TRUE(ranges.Equals(histogram->bucket_ranges()));
  203. // When bucket count is limited, exponential ranges will partially look like
  204. // linear.
  205. BucketRanges ranges2(16);
  206. Histogram::InitializeBucketRanges(1, 32, &ranges2);
  207. EXPECT_EQ(0, ranges2.range(0));
  208. EXPECT_EQ(1, ranges2.range(1));
  209. EXPECT_EQ(2, ranges2.range(2));
  210. EXPECT_EQ(3, ranges2.range(3));
  211. EXPECT_EQ(4, ranges2.range(4));
  212. EXPECT_EQ(5, ranges2.range(5));
  213. EXPECT_EQ(6, ranges2.range(6));
  214. EXPECT_EQ(7, ranges2.range(7));
  215. EXPECT_EQ(9, ranges2.range(8));
  216. EXPECT_EQ(11, ranges2.range(9));
  217. EXPECT_EQ(14, ranges2.range(10));
  218. EXPECT_EQ(17, ranges2.range(11));
  219. EXPECT_EQ(21, ranges2.range(12));
  220. EXPECT_EQ(26, ranges2.range(13));
  221. EXPECT_EQ(32, ranges2.range(14));
  222. EXPECT_EQ(HistogramBase::kSampleType_MAX, ranges2.range(15));
  223. // Check the corresponding Histogram will use the correct ranges.
  224. Histogram* histogram2 = static_cast<Histogram*>(
  225. Histogram::FactoryGet("Histogram2", 1, 32, 15, HistogramBase::kNoFlags));
  226. EXPECT_TRUE(ranges2.Equals(histogram2->bucket_ranges()));
  227. }
  228. TEST_P(HistogramTest, LinearRangesTest) {
  229. BucketRanges ranges(9);
  230. LinearHistogram::InitializeBucketRanges(1, 7, &ranges);
  231. // Gets a nice linear set of bucket ranges.
  232. for (int i = 0; i < 8; i++)
  233. EXPECT_EQ(i, ranges.range(i));
  234. EXPECT_EQ(HistogramBase::kSampleType_MAX, ranges.range(8));
  235. // The correspoding LinearHistogram should use the correct ranges.
  236. Histogram* histogram = static_cast<Histogram*>(
  237. LinearHistogram::FactoryGet("Linear", 1, 7, 8, HistogramBase::kNoFlags));
  238. EXPECT_TRUE(ranges.Equals(histogram->bucket_ranges()));
  239. // Linear ranges are not divisible.
  240. BucketRanges ranges2(6);
  241. LinearHistogram::InitializeBucketRanges(1, 6, &ranges2);
  242. EXPECT_EQ(0, ranges2.range(0));
  243. EXPECT_EQ(1, ranges2.range(1));
  244. EXPECT_EQ(3, ranges2.range(2));
  245. EXPECT_EQ(4, ranges2.range(3));
  246. EXPECT_EQ(6, ranges2.range(4));
  247. EXPECT_EQ(HistogramBase::kSampleType_MAX, ranges2.range(5));
  248. // The correspoding LinearHistogram should use the correct ranges.
  249. Histogram* histogram2 = static_cast<Histogram*>(
  250. LinearHistogram::FactoryGet("Linear2", 1, 6, 5, HistogramBase::kNoFlags));
  251. EXPECT_TRUE(ranges2.Equals(histogram2->bucket_ranges()));
  252. }
  253. TEST_P(HistogramTest, SingleValueEnumerationHistogram) {
  254. // Make sure its possible to construct a linear histogram with only the two
  255. // required outlier buckets (underflow and overflow).
  256. HistogramBase* histogram = LinearHistogram::FactoryGet(
  257. "SingleValueEnum", 1, 1, 2, HistogramBase::kNoFlags);
  258. EXPECT_TRUE(histogram);
  259. // Make sure the macros work properly. This can only be run when
  260. // there is no persistent allocator which can be discarded and leave
  261. // dangling pointers.
  262. if (!use_persistent_histogram_allocator_) {
  263. enum EnumWithMax {
  264. kSomething = 0,
  265. kMaxValue = kSomething,
  266. };
  267. UMA_HISTOGRAM_ENUMERATION("h1", kSomething);
  268. }
  269. }
  270. TEST_P(HistogramTest, ArrayToCustomEnumRangesTest) {
  271. const HistogramBase::Sample ranges[3] = {5, 10, 20};
  272. std::vector<HistogramBase::Sample> ranges_vec =
  273. CustomHistogram::ArrayToCustomEnumRanges(ranges);
  274. ASSERT_EQ(6u, ranges_vec.size());
  275. EXPECT_EQ(5, ranges_vec[0]);
  276. EXPECT_EQ(6, ranges_vec[1]);
  277. EXPECT_EQ(10, ranges_vec[2]);
  278. EXPECT_EQ(11, ranges_vec[3]);
  279. EXPECT_EQ(20, ranges_vec[4]);
  280. EXPECT_EQ(21, ranges_vec[5]);
  281. }
  282. TEST_P(HistogramTest, CustomHistogramTest) {
  283. // A well prepared custom ranges.
  284. std::vector<HistogramBase::Sample> custom_ranges;
  285. custom_ranges.push_back(1);
  286. custom_ranges.push_back(2);
  287. Histogram* histogram = static_cast<Histogram*>(CustomHistogram::FactoryGet(
  288. "TestCustomHistogram1", custom_ranges, HistogramBase::kNoFlags));
  289. const BucketRanges* ranges = histogram->bucket_ranges();
  290. ASSERT_EQ(4u, ranges->size());
  291. EXPECT_EQ(0, ranges->range(0)); // Auto added.
  292. EXPECT_EQ(1, ranges->range(1));
  293. EXPECT_EQ(2, ranges->range(2));
  294. EXPECT_EQ(HistogramBase::kSampleType_MAX, ranges->range(3)); // Auto added.
  295. // A unordered custom ranges.
  296. custom_ranges.clear();
  297. custom_ranges.push_back(2);
  298. custom_ranges.push_back(1);
  299. histogram = static_cast<Histogram*>(CustomHistogram::FactoryGet(
  300. "TestCustomHistogram2", custom_ranges, HistogramBase::kNoFlags));
  301. ranges = histogram->bucket_ranges();
  302. ASSERT_EQ(4u, ranges->size());
  303. EXPECT_EQ(0, ranges->range(0));
  304. EXPECT_EQ(1, ranges->range(1));
  305. EXPECT_EQ(2, ranges->range(2));
  306. EXPECT_EQ(HistogramBase::kSampleType_MAX, ranges->range(3));
  307. // A custom ranges with duplicated values.
  308. custom_ranges.clear();
  309. custom_ranges.push_back(4);
  310. custom_ranges.push_back(1);
  311. custom_ranges.push_back(4);
  312. histogram = static_cast<Histogram*>(CustomHistogram::FactoryGet(
  313. "TestCustomHistogram3", custom_ranges, HistogramBase::kNoFlags));
  314. ranges = histogram->bucket_ranges();
  315. ASSERT_EQ(4u, ranges->size());
  316. EXPECT_EQ(0, ranges->range(0));
  317. EXPECT_EQ(1, ranges->range(1));
  318. EXPECT_EQ(4, ranges->range(2));
  319. EXPECT_EQ(HistogramBase::kSampleType_MAX, ranges->range(3));
  320. }
  321. TEST_P(HistogramTest, CustomHistogramWithOnly2Buckets) {
  322. // This test exploits the fact that the CustomHistogram can have 2 buckets,
  323. // while the base class Histogram is *supposed* to have at least 3 buckets.
  324. // We should probably change the restriction on the base class (or not inherit
  325. // the base class!).
  326. std::vector<HistogramBase::Sample> custom_ranges;
  327. custom_ranges.push_back(4);
  328. Histogram* histogram = static_cast<Histogram*>(CustomHistogram::FactoryGet(
  329. "2BucketsCustomHistogram", custom_ranges, HistogramBase::kNoFlags));
  330. const BucketRanges* ranges = histogram->bucket_ranges();
  331. ASSERT_EQ(3u, ranges->size());
  332. EXPECT_EQ(0, ranges->range(0));
  333. EXPECT_EQ(4, ranges->range(1));
  334. EXPECT_EQ(HistogramBase::kSampleType_MAX, ranges->range(2));
  335. }
  336. TEST_P(HistogramTest, AddCountTest) {
  337. const size_t kBucketCount = 50;
  338. Histogram* histogram = static_cast<Histogram*>(Histogram::FactoryGet(
  339. "AddCountHistogram", 10, 100, kBucketCount, HistogramBase::kNoFlags));
  340. histogram->AddCount(20, 15);
  341. histogram->AddCount(30, 14);
  342. std::unique_ptr<HistogramSamples> samples = histogram->SnapshotSamples();
  343. EXPECT_EQ(29, samples->TotalCount());
  344. EXPECT_EQ(15, samples->GetCount(20));
  345. EXPECT_EQ(14, samples->GetCount(30));
  346. histogram->AddCount(20, 25);
  347. histogram->AddCount(30, 24);
  348. std::unique_ptr<HistogramSamples> samples2 = histogram->SnapshotSamples();
  349. EXPECT_EQ(78, samples2->TotalCount());
  350. EXPECT_EQ(40, samples2->GetCount(20));
  351. EXPECT_EQ(38, samples2->GetCount(30));
  352. }
  353. TEST_P(HistogramTest, AddCount_LargeValuesDontOverflow) {
  354. const size_t kBucketCount = 50;
  355. Histogram* histogram = static_cast<Histogram*>(
  356. Histogram::FactoryGet("AddCountHistogram", 10, 1000000000, kBucketCount,
  357. HistogramBase::kNoFlags));
  358. histogram->AddCount(200000000, 15);
  359. histogram->AddCount(300000000, 14);
  360. std::unique_ptr<HistogramSamples> samples = histogram->SnapshotSamples();
  361. EXPECT_EQ(29, samples->TotalCount());
  362. EXPECT_EQ(15, samples->GetCount(200000000));
  363. EXPECT_EQ(14, samples->GetCount(300000000));
  364. histogram->AddCount(200000000, 25);
  365. histogram->AddCount(300000000, 24);
  366. std::unique_ptr<HistogramSamples> samples2 = histogram->SnapshotSamples();
  367. EXPECT_EQ(78, samples2->TotalCount());
  368. EXPECT_EQ(40, samples2->GetCount(200000000));
  369. EXPECT_EQ(38, samples2->GetCount(300000000));
  370. EXPECT_EQ(19400000000LL, samples2->sum());
  371. }
  372. // Some metrics are designed so that they are guaranteed not to overflow between
  373. // snapshots, but could overflow over a long-running session.
  374. // Make sure that counts returned by Histogram::SnapshotDelta do not overflow
  375. // even when a total count (returned by Histogram::SnapshotSample) does.
  376. TEST_P(HistogramTest, AddCount_LargeCountsDontOverflow) {
  377. const size_t kBucketCount = 10;
  378. Histogram* histogram = static_cast<Histogram*>(Histogram::FactoryGet(
  379. "AddCountHistogram", 10, 50, kBucketCount, HistogramBase::kNoFlags));
  380. const int count = (1 << 30) - 1;
  381. // Repeat N times to make sure that there is no internal value overflow.
  382. for (int i = 0; i < 10; ++i) {
  383. histogram->AddCount(42, count);
  384. std::unique_ptr<HistogramSamples> samples = histogram->SnapshotDelta();
  385. EXPECT_EQ(count, samples->TotalCount());
  386. EXPECT_EQ(count, samples->GetCount(42));
  387. }
  388. }
  389. // Make sure histogram handles out-of-bounds data gracefully.
  390. TEST_P(HistogramTest, BoundsTest) {
  391. const size_t kBucketCount = 50;
  392. Histogram* histogram = static_cast<Histogram*>(Histogram::FactoryGet(
  393. "Bounded", 10, 100, kBucketCount, HistogramBase::kNoFlags));
  394. // Put two samples "out of bounds" above and below.
  395. histogram->Add(5);
  396. histogram->Add(-50);
  397. histogram->Add(100);
  398. histogram->Add(10000);
  399. // Verify they landed in the underflow, and overflow buckets.
  400. std::unique_ptr<SampleVector> samples = histogram->SnapshotAllSamples();
  401. EXPECT_EQ(2, samples->GetCountAtIndex(0));
  402. EXPECT_EQ(0, samples->GetCountAtIndex(1));
  403. size_t array_size = histogram->bucket_count();
  404. EXPECT_EQ(kBucketCount, array_size);
  405. EXPECT_EQ(0, samples->GetCountAtIndex(array_size - 2));
  406. EXPECT_EQ(2, samples->GetCountAtIndex(array_size - 1));
  407. std::vector<int> custom_ranges;
  408. custom_ranges.push_back(10);
  409. custom_ranges.push_back(50);
  410. custom_ranges.push_back(100);
  411. Histogram* test_custom_histogram = static_cast<Histogram*>(
  412. CustomHistogram::FactoryGet("TestCustomRangeBoundedHistogram",
  413. custom_ranges, HistogramBase::kNoFlags));
  414. // Put two samples "out of bounds" above and below.
  415. test_custom_histogram->Add(5);
  416. test_custom_histogram->Add(-50);
  417. test_custom_histogram->Add(100);
  418. test_custom_histogram->Add(1000);
  419. test_custom_histogram->Add(INT_MAX);
  420. // Verify they landed in the underflow, and overflow buckets.
  421. std::unique_ptr<SampleVector> custom_samples =
  422. test_custom_histogram->SnapshotAllSamples();
  423. EXPECT_EQ(2, custom_samples->GetCountAtIndex(0));
  424. EXPECT_EQ(0, custom_samples->GetCountAtIndex(1));
  425. size_t bucket_count = test_custom_histogram->bucket_count();
  426. EXPECT_EQ(0, custom_samples->GetCountAtIndex(bucket_count - 2));
  427. EXPECT_EQ(3, custom_samples->GetCountAtIndex(bucket_count - 1));
  428. }
  429. // Check to be sure samples land as expected is "correct" buckets.
  430. TEST_P(HistogramTest, BucketPlacementTest) {
  431. Histogram* histogram = static_cast<Histogram*>(
  432. Histogram::FactoryGet("Histogram", 1, 64, 8, HistogramBase::kNoFlags));
  433. // Add i+1 samples to the i'th bucket.
  434. histogram->Add(0);
  435. int power_of_2 = 1;
  436. for (int i = 1; i < 8; i++) {
  437. for (int j = 0; j <= i; j++)
  438. histogram->Add(power_of_2);
  439. power_of_2 *= 2;
  440. }
  441. // Check to see that the bucket counts reflect our additions.
  442. std::unique_ptr<SampleVector> samples = histogram->SnapshotAllSamples();
  443. for (int i = 0; i < 8; i++)
  444. EXPECT_EQ(i + 1, samples->GetCountAtIndex(i));
  445. }
  446. TEST_P(HistogramTest, CorruptSampleCounts) {
  447. // The internal code creates histograms via macros and thus keeps static
  448. // pointers to them. If those pointers are to persistent memory which will
  449. // be free'd then any following calls to that code will crash with a
  450. // segmentation violation.
  451. if (use_persistent_histogram_allocator_)
  452. return;
  453. Histogram* histogram = static_cast<Histogram*>(
  454. Histogram::FactoryGet("Histogram", 1, 64, 8, HistogramBase::kNoFlags));
  455. // Add some samples.
  456. histogram->Add(20);
  457. histogram->Add(40);
  458. std::unique_ptr<SampleVector> snapshot = histogram->SnapshotAllSamples();
  459. EXPECT_EQ(HistogramBase::NO_INCONSISTENCIES,
  460. histogram->FindCorruption(*snapshot));
  461. EXPECT_EQ(2, snapshot->redundant_count());
  462. EXPECT_EQ(2, snapshot->TotalCount());
  463. snapshot->counts()[3] += 100; // Sample count won't match redundant count.
  464. EXPECT_EQ(HistogramBase::COUNT_LOW_ERROR,
  465. histogram->FindCorruption(*snapshot));
  466. snapshot->counts()[2] -= 200;
  467. EXPECT_EQ(HistogramBase::COUNT_HIGH_ERROR,
  468. histogram->FindCorruption(*snapshot));
  469. // But we can't spot a corruption if it is compensated for.
  470. snapshot->counts()[1] += 100;
  471. EXPECT_EQ(HistogramBase::NO_INCONSISTENCIES,
  472. histogram->FindCorruption(*snapshot));
  473. }
  474. TEST_P(HistogramTest, CorruptBucketBounds) {
  475. Histogram* histogram = static_cast<Histogram*>(
  476. Histogram::FactoryGet("Histogram", 1, 64, 8, HistogramBase::kNoFlags));
  477. std::unique_ptr<HistogramSamples> snapshot = histogram->SnapshotSamples();
  478. EXPECT_EQ(HistogramBase::NO_INCONSISTENCIES,
  479. histogram->FindCorruption(*snapshot));
  480. BucketRanges* bucket_ranges =
  481. const_cast<BucketRanges*>(histogram->bucket_ranges());
  482. HistogramBase::Sample tmp = bucket_ranges->range(1);
  483. bucket_ranges->set_range(1, bucket_ranges->range(2));
  484. bucket_ranges->set_range(2, tmp);
  485. EXPECT_EQ(
  486. HistogramBase::BUCKET_ORDER_ERROR | HistogramBase::RANGE_CHECKSUM_ERROR,
  487. histogram->FindCorruption(*snapshot));
  488. bucket_ranges->set_range(2, bucket_ranges->range(1));
  489. bucket_ranges->set_range(1, tmp);
  490. EXPECT_EQ(0U, histogram->FindCorruption(*snapshot));
  491. // Show that two simple changes don't offset each other
  492. bucket_ranges->set_range(3, bucket_ranges->range(3) + 1);
  493. EXPECT_EQ(HistogramBase::RANGE_CHECKSUM_ERROR,
  494. histogram->FindCorruption(*snapshot));
  495. bucket_ranges->set_range(4, bucket_ranges->range(4) - 1);
  496. EXPECT_EQ(HistogramBase::RANGE_CHECKSUM_ERROR,
  497. histogram->FindCorruption(*snapshot));
  498. // Repair histogram so that destructor won't DCHECK().
  499. bucket_ranges->set_range(3, bucket_ranges->range(3) - 1);
  500. bucket_ranges->set_range(4, bucket_ranges->range(4) + 1);
  501. }
  502. TEST_P(HistogramTest, HistogramSerializeInfo) {
  503. Histogram* histogram = static_cast<Histogram*>(Histogram::FactoryGet(
  504. "Histogram", 1, 64, 8, HistogramBase::kIPCSerializationSourceFlag));
  505. Pickle pickle;
  506. histogram->SerializeInfo(&pickle);
  507. PickleIterator iter(pickle);
  508. int type;
  509. EXPECT_TRUE(iter.ReadInt(&type));
  510. EXPECT_EQ(HISTOGRAM, type);
  511. std::string name;
  512. EXPECT_TRUE(iter.ReadString(&name));
  513. EXPECT_EQ("Histogram", name);
  514. int flag;
  515. EXPECT_TRUE(iter.ReadInt(&flag));
  516. EXPECT_EQ(HistogramBase::kIPCSerializationSourceFlag,
  517. flag & ~HistogramBase::kIsPersistent);
  518. int min;
  519. EXPECT_TRUE(iter.ReadInt(&min));
  520. EXPECT_EQ(1, min);
  521. int max;
  522. EXPECT_TRUE(iter.ReadInt(&max));
  523. EXPECT_EQ(64, max);
  524. uint32_t bucket_count;
  525. EXPECT_TRUE(iter.ReadUInt32(&bucket_count));
  526. EXPECT_EQ(8u, bucket_count);
  527. uint32_t checksum;
  528. EXPECT_TRUE(iter.ReadUInt32(&checksum));
  529. EXPECT_EQ(histogram->bucket_ranges()->checksum(), checksum);
  530. // No more data in the pickle.
  531. EXPECT_FALSE(iter.SkipBytes(1));
  532. }
  533. TEST_P(HistogramTest, CustomHistogramSerializeInfo) {
  534. std::vector<int> custom_ranges;
  535. custom_ranges.push_back(10);
  536. custom_ranges.push_back(100);
  537. HistogramBase* custom_histogram =
  538. CustomHistogram::FactoryGet("TestCustomRangeBoundedHistogram",
  539. custom_ranges, HistogramBase::kNoFlags);
  540. Pickle pickle;
  541. custom_histogram->SerializeInfo(&pickle);
  542. // Validate the pickle.
  543. PickleIterator iter(pickle);
  544. int i;
  545. std::string s;
  546. uint32_t bucket_count;
  547. uint32_t ui32;
  548. EXPECT_TRUE(iter.ReadInt(&i) && iter.ReadString(&s) && iter.ReadInt(&i) &&
  549. iter.ReadInt(&i) && iter.ReadInt(&i) &&
  550. iter.ReadUInt32(&bucket_count) && iter.ReadUInt32(&ui32));
  551. EXPECT_EQ(3u, bucket_count);
  552. int range;
  553. EXPECT_TRUE(iter.ReadInt(&range));
  554. EXPECT_EQ(10, range);
  555. EXPECT_TRUE(iter.ReadInt(&range));
  556. EXPECT_EQ(100, range);
  557. // No more data in the pickle.
  558. EXPECT_FALSE(iter.SkipBytes(1));
  559. }
  560. TEST_P(HistogramTest, BadConstruction) {
  561. HistogramBase* histogram = Histogram::FactoryGet("BadConstruction", 0, 100, 8,
  562. HistogramBase::kNoFlags);
  563. EXPECT_TRUE(histogram->HasConstructionArguments(1, 100, 8));
  564. // Try to get the same histogram name with different arguments.
  565. HistogramBase* bad_histogram = Histogram::FactoryGet(
  566. "BadConstruction", 0, 100, 7, HistogramBase::kNoFlags);
  567. EXPECT_EQ(DummyHistogram::GetInstance(), bad_histogram);
  568. bad_histogram = Histogram::FactoryGet("BadConstruction", 0, 99, 8,
  569. HistogramBase::kNoFlags);
  570. EXPECT_EQ(DummyHistogram::GetInstance(), bad_histogram);
  571. HistogramBase* linear_histogram = LinearHistogram::FactoryGet(
  572. "BadConstructionLinear", 0, 100, 8, HistogramBase::kNoFlags);
  573. EXPECT_TRUE(linear_histogram->HasConstructionArguments(1, 100, 8));
  574. // Try to get the same histogram name with different arguments.
  575. bad_histogram = LinearHistogram::FactoryGet("BadConstructionLinear", 0, 100,
  576. 7, HistogramBase::kNoFlags);
  577. EXPECT_EQ(DummyHistogram::GetInstance(), bad_histogram);
  578. bad_histogram = LinearHistogram::FactoryGet("BadConstructionLinear", 10, 100,
  579. 8, HistogramBase::kNoFlags);
  580. EXPECT_EQ(DummyHistogram::GetInstance(), bad_histogram);
  581. }
  582. TEST_P(HistogramTest, FactoryTime) {
  583. const int kTestCreateCount = 1 << 14; // Must be power-of-2.
  584. const int kTestLookupCount = 100000;
  585. const int kTestAddCount = 1000000;
  586. // Create all histogram names in advance for accurate timing below.
  587. std::vector<std::string> histogram_names;
  588. for (int i = 0; i < kTestCreateCount; ++i) {
  589. histogram_names.push_back(
  590. StringPrintf("TestHistogram.%d", i % kTestCreateCount));
  591. }
  592. // Calculate cost of creating histograms.
  593. TimeTicks create_start = TimeTicks::Now();
  594. for (int i = 0; i < kTestCreateCount; ++i) {
  595. Histogram::FactoryGet(histogram_names[i], 1, 100, 10,
  596. HistogramBase::kNoFlags);
  597. }
  598. TimeDelta create_ticks = TimeTicks::Now() - create_start;
  599. int64_t create_ms = create_ticks.InMilliseconds();
  600. VLOG(1) << kTestCreateCount << " histogram creations took " << create_ms
  601. << "ms or about " << (create_ms * 1000000) / kTestCreateCount
  602. << "ns each.";
  603. // Calculate cost of looking up existing histograms.
  604. TimeTicks lookup_start = TimeTicks::Now();
  605. for (int i = 0; i < kTestLookupCount; ++i) {
  606. // 6007 is co-prime with kTestCreateCount and so will do lookups in an
  607. // order less likely to be cacheable (but still hit them all) should the
  608. // underlying storage use the exact histogram name as the key.
  609. const int i_mult = 6007;
  610. static_assert(i_mult < INT_MAX / kTestCreateCount, "Multiplier too big");
  611. int index = (i * i_mult) & (kTestCreateCount - 1);
  612. Histogram::FactoryGet(histogram_names[index], 1, 100, 10,
  613. HistogramBase::kNoFlags);
  614. }
  615. TimeDelta lookup_ticks = TimeTicks::Now() - lookup_start;
  616. int64_t lookup_ms = lookup_ticks.InMilliseconds();
  617. VLOG(1) << kTestLookupCount << " histogram lookups took " << lookup_ms
  618. << "ms or about " << (lookup_ms * 1000000) / kTestLookupCount
  619. << "ns each.";
  620. // Calculate cost of accessing histograms.
  621. HistogramBase* histogram = Histogram::FactoryGet(histogram_names[0], 1, 100,
  622. 10, HistogramBase::kNoFlags);
  623. ASSERT_TRUE(histogram);
  624. TimeTicks add_start = TimeTicks::Now();
  625. for (int i = 0; i < kTestAddCount; ++i)
  626. histogram->Add(i & 127);
  627. TimeDelta add_ticks = TimeTicks::Now() - add_start;
  628. int64_t add_ms = add_ticks.InMilliseconds();
  629. VLOG(1) << kTestAddCount << " histogram adds took " << add_ms
  630. << "ms or about " << (add_ms * 1000000) / kTestAddCount << "ns each.";
  631. }
  632. TEST_P(HistogramTest, ScaledLinearHistogram) {
  633. ScaledLinearHistogram scaled("SLH", 1, 5, 6, 100, HistogramBase::kNoFlags);
  634. scaled.AddScaledCount(0, 1);
  635. scaled.AddScaledCount(1, 49);
  636. scaled.AddScaledCount(2, 50);
  637. scaled.AddScaledCount(3, 101);
  638. scaled.AddScaledCount(4, 160);
  639. scaled.AddScaledCount(5, 130);
  640. scaled.AddScaledCount(6, 140);
  641. std::unique_ptr<SampleVector> samples =
  642. SnapshotAllSamples(static_cast<Histogram*>(scaled.histogram()));
  643. EXPECT_EQ(0, samples->GetCountAtIndex(0));
  644. EXPECT_EQ(0, samples->GetCountAtIndex(1));
  645. EXPECT_EQ(1, samples->GetCountAtIndex(2));
  646. EXPECT_EQ(1, samples->GetCountAtIndex(3));
  647. EXPECT_EQ(2, samples->GetCountAtIndex(4));
  648. EXPECT_EQ(3, samples->GetCountAtIndex(5));
  649. // Make sure the macros compile properly. This can only be run when
  650. // there is no persistent allocator which can be discarded and leave
  651. // dangling pointers.
  652. if (!use_persistent_histogram_allocator_) {
  653. enum EnumWithMax {
  654. kA = 0,
  655. kB = 1,
  656. kC = 2,
  657. kMaxValue = kC,
  658. };
  659. UMA_HISTOGRAM_SCALED_EXACT_LINEAR("h1", 1, 5000, 5, 100);
  660. UMA_HISTOGRAM_SCALED_ENUMERATION("h2", kB, 5000, 100);
  661. }
  662. }
  663. // For Histogram, LinearHistogram and CustomHistogram, the minimum for a
  664. // declared range is 1, while the maximum is (HistogramBase::kSampleType_MAX -
  665. // 1). But we accept ranges exceeding those limits, and silently clamped to
  666. // those limits. This is for backwards compatibility.
  667. TEST(HistogramDeathTest, BadRangesTest) {
  668. HistogramBase* histogram =
  669. Histogram::FactoryGet("BadRanges", 0, HistogramBase::kSampleType_MAX, 8,
  670. HistogramBase::kNoFlags);
  671. EXPECT_TRUE(histogram->HasConstructionArguments(
  672. 1, HistogramBase::kSampleType_MAX - 1, 8));
  673. HistogramBase* linear_histogram = LinearHistogram::FactoryGet(
  674. "BadRangesLinear", 0, HistogramBase::kSampleType_MAX, 8,
  675. HistogramBase::kNoFlags);
  676. EXPECT_TRUE(linear_histogram->HasConstructionArguments(
  677. 1, HistogramBase::kSampleType_MAX - 1, 8));
  678. std::vector<int> custom_ranges;
  679. custom_ranges.push_back(0);
  680. custom_ranges.push_back(5);
  681. Histogram* custom_histogram =
  682. static_cast<Histogram*>(CustomHistogram::FactoryGet(
  683. "BadRangesCustom", custom_ranges, HistogramBase::kNoFlags));
  684. const BucketRanges* ranges = custom_histogram->bucket_ranges();
  685. ASSERT_EQ(3u, ranges->size());
  686. EXPECT_EQ(0, ranges->range(0));
  687. EXPECT_EQ(5, ranges->range(1));
  688. EXPECT_EQ(HistogramBase::kSampleType_MAX, ranges->range(2));
  689. // CustomHistogram does not accepts kSampleType_MAX as range.
  690. custom_ranges.push_back(HistogramBase::kSampleType_MAX);
  691. EXPECT_DEATH_IF_SUPPORTED(
  692. CustomHistogram::FactoryGet("BadRangesCustom2", custom_ranges,
  693. HistogramBase::kNoFlags),
  694. "");
  695. // CustomHistogram needs at least 1 valid range.
  696. custom_ranges.clear();
  697. custom_ranges.push_back(0);
  698. EXPECT_DEATH_IF_SUPPORTED(
  699. CustomHistogram::FactoryGet("BadRangesCustom3", custom_ranges,
  700. HistogramBase::kNoFlags),
  701. "");
  702. }
  703. TEST_P(HistogramTest, ExpiredHistogramTest) {
  704. auto record_checker = std::make_unique<TestRecordHistogramChecker>();
  705. StatisticsRecorder::SetRecordChecker(std::move(record_checker));
  706. HistogramBase* expired = Histogram::FactoryGet(kExpiredHistogramName, 1, 1000,
  707. 10, HistogramBase::kNoFlags);
  708. ASSERT_TRUE(expired);
  709. expired->Add(5);
  710. expired->Add(500);
  711. auto samples = expired->SnapshotDelta();
  712. EXPECT_EQ(0, samples->TotalCount());
  713. HistogramBase* linear_expired = LinearHistogram::FactoryGet(
  714. kExpiredHistogramName, 1, 1000, 10, HistogramBase::kNoFlags);
  715. ASSERT_TRUE(linear_expired);
  716. linear_expired->Add(5);
  717. linear_expired->Add(500);
  718. samples = linear_expired->SnapshotDelta();
  719. EXPECT_EQ(0, samples->TotalCount());
  720. ScaledLinearHistogram scaled_linear_expired(kExpiredHistogramName, 1, 5, 6,
  721. 100, HistogramBase::kNoFlags);
  722. scaled_linear_expired.AddScaledCount(0, 1);
  723. scaled_linear_expired.AddScaledCount(1, 49);
  724. samples = scaled_linear_expired.histogram()->SnapshotDelta();
  725. EXPECT_EQ(0, samples->TotalCount());
  726. std::vector<int> custom_ranges;
  727. custom_ranges.push_back(1);
  728. custom_ranges.push_back(5);
  729. HistogramBase* custom_expired = CustomHistogram::FactoryGet(
  730. kExpiredHistogramName, custom_ranges, HistogramBase::kNoFlags);
  731. ASSERT_TRUE(custom_expired);
  732. custom_expired->Add(2);
  733. custom_expired->Add(4);
  734. samples = custom_expired->SnapshotDelta();
  735. EXPECT_EQ(0, samples->TotalCount());
  736. HistogramBase* valid = Histogram::FactoryGet("ValidHistogram", 1, 1000, 10,
  737. HistogramBase::kNoFlags);
  738. ASSERT_TRUE(valid);
  739. valid->Add(5);
  740. valid->Add(500);
  741. samples = valid->SnapshotDelta();
  742. EXPECT_EQ(2, samples->TotalCount());
  743. HistogramBase* linear_valid = LinearHistogram::FactoryGet(
  744. "LinearHistogram", 1, 1000, 10, HistogramBase::kNoFlags);
  745. ASSERT_TRUE(linear_valid);
  746. linear_valid->Add(5);
  747. linear_valid->Add(500);
  748. samples = linear_valid->SnapshotDelta();
  749. EXPECT_EQ(2, samples->TotalCount());
  750. HistogramBase* custom_valid = CustomHistogram::FactoryGet(
  751. "CustomHistogram", custom_ranges, HistogramBase::kNoFlags);
  752. ASSERT_TRUE(custom_valid);
  753. custom_valid->Add(2);
  754. custom_valid->Add(4);
  755. samples = custom_valid->SnapshotDelta();
  756. EXPECT_EQ(2, samples->TotalCount());
  757. }
  758. TEST_P(HistogramTest, CheckGetCountAndBucketData) {
  759. const size_t kBucketCount = 50;
  760. Histogram* histogram = static_cast<Histogram*>(Histogram::FactoryGet(
  761. "AddCountHistogram", 10, 100, kBucketCount, HistogramBase::kNoFlags));
  762. // Add samples in reverse order and make sure the output is in correct order.
  763. histogram->AddCount(/*sample=*/30, /*value=*/14);
  764. histogram->AddCount(/*sample=*/20, /*value=*/15);
  765. histogram->AddCount(/*sample=*/20, /*value=*/15);
  766. histogram->AddCount(/*sample=*/30, /*value=*/14);
  767. const CountAndBucketData count_and_data_bucket =
  768. GetCountAndBucketData(histogram);
  769. EXPECT_EQ(58, count_and_data_bucket.count);
  770. EXPECT_EQ(1440, count_and_data_bucket.sum);
  771. const base::Value::List& buckets_list = count_and_data_bucket.buckets;
  772. ASSERT_EQ(2u, buckets_list.size());
  773. // Check the first bucket.
  774. const base::Value::Dict* bucket1 = buckets_list[0].GetIfDict();
  775. ASSERT_TRUE(bucket1 != nullptr);
  776. EXPECT_EQ(bucket1->FindInt("low"), absl::optional<int>(20));
  777. EXPECT_EQ(bucket1->FindInt("high"), absl::optional<int>(21));
  778. EXPECT_EQ(bucket1->FindInt("count"), absl::optional<int>(30));
  779. // Check the second bucket.
  780. const base::Value::Dict* bucket2 = buckets_list[1].GetIfDict();
  781. ASSERT_TRUE(bucket2 != nullptr);
  782. EXPECT_EQ(bucket2->FindInt("low"), absl::optional<int>(30));
  783. EXPECT_EQ(bucket2->FindInt("high"), absl::optional<int>(31));
  784. EXPECT_EQ(bucket2->FindInt("count"), absl::optional<int>(28));
  785. }
  786. TEST_P(HistogramTest, WriteAscii) {
  787. HistogramBase* histogram =
  788. LinearHistogram::FactoryGet("AsciiOut", /*minimum=*/1, /*maximum=*/10,
  789. /*bucket_count=*/5, HistogramBase::kNoFlags);
  790. histogram->AddCount(/*sample=*/4, /*value=*/5);
  791. std::string output;
  792. histogram->WriteAscii(&output);
  793. const char kOutputFormatRe[] =
  794. R"(Histogram: AsciiOut recorded 5 samples, mean = 4\.0.*\n)"
  795. R"(0 \.\.\. \n)"
  796. R"(4 -+O \s* \(5 = 100\.0%\) \{0\.0%\}\n)"
  797. R"(7 \.\.\. \n)";
  798. EXPECT_THAT(output, testing::MatchesRegex(kOutputFormatRe));
  799. }
  800. TEST_P(HistogramTest, ToGraphDict) {
  801. HistogramBase* histogram =
  802. LinearHistogram::FactoryGet("HTMLOut", /*minimum=*/1, /*maximum=*/10,
  803. /*bucket_count=*/5, HistogramBase::kNoFlags);
  804. histogram->AddCount(/*sample=*/4, /*value=*/5);
  805. base::Value::Dict output = histogram->ToGraphDict();
  806. const std::string* header = output.FindString("header");
  807. const std::string* body = output.FindString("body");
  808. const char kOutputHeaderFormatRe[] =
  809. R"(Histogram: HTMLOut recorded 5 samples, mean = 4\.0.*)";
  810. const char kOutputBodyFormatRe[] =
  811. R"(0 \.\.\. \n)"
  812. R"(4 -+O \s* \(5 = 100\.0%\) \{0\.0%\}\n)"
  813. R"(7 \.\.\. \n)";
  814. EXPECT_THAT(*header, testing::MatchesRegex(kOutputHeaderFormatRe));
  815. EXPECT_THAT(*body, testing::MatchesRegex(kOutputBodyFormatRe));
  816. }
  817. // Tests ToGraphDict() returns deterministic length size and normalizes to
  818. // scale.
  819. TEST_P(HistogramTest, ToGraphDictNormalize) {
  820. int count_bucket_1 = 80;
  821. int value_bucket_1 = 4;
  822. int count_bucket_2 = 40;
  823. int value_bucket_2 = 5;
  824. HistogramBase* histogram =
  825. LinearHistogram::FactoryGet("AsciiOut", /*minimum=*/1, /*maximum=*/100,
  826. /*bucket_count=*/80, HistogramBase::kNoFlags);
  827. histogram->AddCount(/*value=*/value_bucket_1, /*count=*/count_bucket_1);
  828. histogram->AddCount(/*value=*/value_bucket_2, /*count=*/count_bucket_2);
  829. base::Value::Dict output = histogram->ToGraphDict();
  830. std::string* header = output.FindString("header");
  831. std::string* body = output.FindString("body");
  832. const char kOutputHeaderFormatRe[] =
  833. R"(Histogram: AsciiOut recorded 120 samples, mean = 4\.3.*)";
  834. const char kOutputBodyFormatRe[] =
  835. R"(0 \.\.\. \n)"
  836. R"(4 ---------------------------------------------------)"
  837. R"(---------------------O \(80 = 66\.7%\) \{0\.0%\}\n)"
  838. R"(5 ----------------)"
  839. R"(--------------------O \s* \(40 = 33\.3%\) \{66\.7%\}\n)"
  840. R"(6 \.\.\. \n)";
  841. EXPECT_THAT(*header, testing::MatchesRegex(kOutputHeaderFormatRe));
  842. EXPECT_THAT(*body, testing::MatchesRegex(kOutputBodyFormatRe));
  843. }
  844. } // namespace base