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 5#include "chrome/test/base/uma_histogram_helper.h" 6 7#include "base/bind.h" 8#include "base/metrics/statistics_recorder.h" 9#include "base/test/test_timeouts.h" 10#include "chrome/test/base/ui_test_utils.h" 11#include "content/public/browser/histogram_fetcher.h" 12 13UMAHistogramHelper::UMAHistogramHelper() { 14} 15 16void UMAHistogramHelper::Fetch() { 17 base::Closure callback = base::Bind(&UMAHistogramHelper::FetchCallback, 18 base::Unretained(this)); 19 20 content::FetchHistogramsAsynchronously( 21 base::MessageLoop::current(), 22 callback, 23 // If this call times out, it means that a child process is not 24 // responding, which is something we should not ignore. The timeout is 25 // set to be longer than the normal browser test timeout so that it will 26 // be prempted by the normal timeout. 27 TestTimeouts::action_max_timeout() * 2); 28 content::RunMessageLoop(); 29} 30 31void UMAHistogramHelper::ExpectUniqueSample( 32 const std::string& name, 33 base::HistogramBase::Sample sample, 34 base::HistogramBase::Count expected_count) { 35 base::HistogramBase* histogram = 36 base::StatisticsRecorder::FindHistogram(name); 37 EXPECT_NE(static_cast<base::HistogramBase*>(NULL), histogram) 38 << "Histogram \"" << name << "\" does not exist."; 39 40 if (histogram) { 41 scoped_ptr<base::HistogramSamples> samples(histogram->SnapshotSamples()); 42 CheckBucketCount(name, sample, expected_count, *samples); 43 CheckTotalCount(name, expected_count, *samples); 44 } 45} 46 47void UMAHistogramHelper::ExpectTotalCount( 48 const std::string& name, 49 base::HistogramBase::Count count) { 50 base::HistogramBase* histogram = 51 base::StatisticsRecorder::FindHistogram(name); 52 EXPECT_NE(static_cast<base::HistogramBase*>(NULL), histogram) 53 << "Histogram \"" << name << "\" does not exist."; 54 55 if (histogram) { 56 scoped_ptr<base::HistogramSamples> samples(histogram->SnapshotSamples()); 57 CheckTotalCount(name, count, *samples); 58 } 59} 60 61void UMAHistogramHelper::FetchCallback() { 62 base::MessageLoopForUI::current()->Quit(); 63} 64 65void UMAHistogramHelper::CheckBucketCount( 66 const std::string& name, 67 base::HistogramBase::Sample sample, 68 base::HistogramBase::Count expected_count, 69 base::HistogramSamples& samples) { 70 EXPECT_EQ(expected_count, samples.GetCount(sample)) 71 << "Histogram \"" << name 72 << "\" does not have the right number of samples (" << expected_count 73 << ") in the expected bucket (" << sample << ")."; 74} 75 76void UMAHistogramHelper::CheckTotalCount( 77 const std::string& name, 78 base::HistogramBase::Count expected_count, 79 base::HistogramSamples& samples) { 80 EXPECT_EQ(expected_count, samples.TotalCount()) 81 << "Histogram \"" << name 82 << "\" does not have the right total number of samples (" 83 << expected_count << ")."; 84} 85