1 // Copyright 2018 The Chromium Authors 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 "base/metrics/persistent_histogram_storage.h" 6 7 #include <memory> 8 9 #include "base/files/file_path.h" 10 #include "base/files/file_util.h" 11 #include "base/files/scoped_temp_dir.h" 12 #include "base/metrics/histogram_macros.h" 13 #include "base/metrics/persistent_histogram_allocator.h" 14 #include "base/time/time.h" 15 #include "build/build_config.h" 16 #include "testing/gtest/include/gtest/gtest.h" 17 18 namespace base { 19 20 namespace { 21 22 // Name of the allocator for storing histograms. 23 constexpr char kTestHistogramAllocatorName[] = "TestMetrics"; 24 25 } // namespace 26 27 class PersistentHistogramStorageTest : public testing::Test { 28 public: 29 PersistentHistogramStorageTest(const PersistentHistogramStorageTest&) = 30 delete; 31 PersistentHistogramStorageTest& operator=( 32 const PersistentHistogramStorageTest&) = delete; 33 34 protected: 35 PersistentHistogramStorageTest() = default; 36 ~PersistentHistogramStorageTest() override = default; 37 38 // Creates a unique temporary directory, and sets the test storage directory. SetUp()39 void SetUp() override { 40 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); 41 test_storage_dir_ = 42 temp_dir_path().AppendASCII(kTestHistogramAllocatorName); 43 } 44 45 // Gets the path to the temporary directory. temp_dir_path()46 const FilePath& temp_dir_path() { return temp_dir_.GetPath(); } 47 test_storage_dir()48 const FilePath& test_storage_dir() { return test_storage_dir_; } 49 50 private: 51 // A temporary directory where all file IO operations take place. 52 ScopedTempDir temp_dir_; 53 54 // The directory into which metrics files are written. 55 FilePath test_storage_dir_; 56 }; 57 58 #if !BUILDFLAG(IS_NACL) TEST_F(PersistentHistogramStorageTest,HistogramWriteTest)59TEST_F(PersistentHistogramStorageTest, HistogramWriteTest) { 60 auto persistent_histogram_storage = 61 std::make_unique<PersistentHistogramStorage>( 62 kTestHistogramAllocatorName, 63 PersistentHistogramStorage::StorageDirManagement::kCreate); 64 65 persistent_histogram_storage->set_storage_base_dir(temp_dir_path()); 66 67 // Log some random data. 68 UMA_HISTOGRAM_BOOLEAN("Some.Test.Metric", true); 69 70 // Deleting the object causes the data to be written to the disk. 71 persistent_histogram_storage.reset(); 72 73 // The storage directory and the histogram file are created during the 74 // destruction of the PersistentHistogramStorage instance. 75 EXPECT_TRUE(DirectoryExists(test_storage_dir())); 76 EXPECT_FALSE(IsDirectoryEmpty(test_storage_dir())); 77 78 // Clean up for subsequent tests. 79 GlobalHistogramAllocator::ReleaseForTesting(); 80 } 81 #endif // !BUILDFLAG(IS_NACL) 82 83 } // namespace base 84