1 // Copyright 2023 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 #ifndef BASE_FILES_BLOCK_TESTS_WRITING_TO_SPECIAL_DIRS_H_ 6 #define BASE_FILES_BLOCK_TESTS_WRITING_TO_SPECIAL_DIRS_H_ 7 8 #include <optional> 9 #include <set> 10 #include <vector> 11 12 #include "base/base_export.h" 13 #include "base/gtest_prod_util.h" 14 15 namespace base { 16 17 class FilePath; 18 19 using FileWriteBlockedForTestingFunctionPtr = void (*)(const FilePath&); 20 21 // Utility class for production code to check if writing to special directories 22 // is blocked for tests. 23 class BASE_EXPORT BlockTestsWritingToSpecialDirs { 24 public: 25 static bool CanWriteToPath(const FilePath& path); 26 27 BlockTestsWritingToSpecialDirs( 28 std::vector<int> blocked_dirs, 29 FileWriteBlockedForTestingFunctionPtr failure_callback); 30 BlockTestsWritingToSpecialDirs( 31 const BlockTestsWritingToSpecialDirs& blocker) = delete; 32 BlockTestsWritingToSpecialDirs& operator=( 33 const BlockTestsWritingToSpecialDirs&) = delete; 34 35 ~BlockTestsWritingToSpecialDirs(); 36 37 private: 38 friend class BlockTestsWritingToSpecialDirsTest; 39 friend class ScopedBlockTestsWritingToSpecialDirs; 40 41 // This private method is used by `ScopedBlockTestsWritingToSpecialDirs` to 42 // create an object of this class stored in a function static object. 43 // `CanWriteToPath` above checks the paths stored in that object, if it is 44 // set. Thus, only ScopedBlockTestsWritingToSpecialDirs should be able to 45 // block tests writing to special dirs. 46 static std::optional<BlockTestsWritingToSpecialDirs>& Get(); 47 48 // `blocked_paths_` will be initialized lazily, from `blocked_dirs_`. 49 std::set<FilePath> blocked_paths_; 50 std::vector<int> blocked_dirs_; 51 FileWriteBlockedForTestingFunctionPtr failure_callback_ = nullptr; 52 }; 53 54 } // namespace base 55 56 #endif // BASE_FILES_BLOCK_TESTS_WRITING_TO_SPECIAL_DIRS_H_ 57