1 // Copyright 2018 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 "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/time/time.h" 14 #include "build/build_config.h" 15 #include "testing/gtest/include/gtest/gtest.h" 16 17 namespace base { 18 19 namespace { 20 21 // Name of the allocator for storing histograms. 22 constexpr char kTestHistogramAllocatorName[] = "TestMetrics"; 23 24 } // namespace 25 26 class PersistentHistogramStorageTest : public testing::Test { 27 protected: 28 PersistentHistogramStorageTest() = default; 29 ~PersistentHistogramStorageTest() override = default; 30 31 // Creates a unique temporary directory, and sets the test storage directory. SetUp()32 void SetUp() override { 33 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); 34 test_storage_dir_ = 35 temp_dir_path().AppendASCII(kTestHistogramAllocatorName); 36 } 37 38 // Gets the path to the temporary directory. temp_dir_path()39 const FilePath& temp_dir_path() { return temp_dir_.GetPath(); } 40 test_storage_dir()41 const FilePath& test_storage_dir() { return test_storage_dir_; } 42 43 private: 44 // A temporary directory where all file IO operations take place. 45 ScopedTempDir temp_dir_; 46 47 // The directory into which metrics files are written. 48 FilePath test_storage_dir_; 49 50 DISALLOW_COPY_AND_ASSIGN(PersistentHistogramStorageTest); 51 }; 52 53 // TODO(chengx): Re-enable the test on OS_IOS after issue 836789 is fixed. 54 // PersistentHistogramStorage is only used on OS_WIN now, so disabling this 55 // test on OS_IOS is fine. 56 #if !defined(OS_NACL) && !defined(OS_IOS) TEST_F(PersistentHistogramStorageTest,HistogramWriteTest)57TEST_F(PersistentHistogramStorageTest, HistogramWriteTest) { 58 auto persistent_histogram_storage = 59 std::make_unique<PersistentHistogramStorage>( 60 kTestHistogramAllocatorName, 61 PersistentHistogramStorage::StorageDirManagement::kCreate); 62 63 persistent_histogram_storage->set_storage_base_dir(temp_dir_path()); 64 65 // Log some random data. 66 UMA_HISTOGRAM_BOOLEAN("Some.Test.Metric", true); 67 68 // Deleting the object causes the data to be written to the disk. 69 persistent_histogram_storage.reset(); 70 71 // The storage directory and the histogram file are created during the 72 // destruction of the PersistentHistogramStorage instance. 73 EXPECT_TRUE(DirectoryExists(test_storage_dir())); 74 EXPECT_FALSE(IsDirectoryEmpty(test_storage_dir())); 75 } 76 #endif // !defined(OS_NACL) && !defined(OS_IOS) 77 78 } // namespace base 79