xref: /aosp_15_r20/external/cronet/base/test/scoped_path_override.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2012 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/test/scoped_path_override.h"
6 
7 #include <ostream>
8 
9 #include "base/check.h"
10 #include "base/path_service.h"
11 
12 namespace base {
13 
ScopedPathOverride(int key)14 ScopedPathOverride::ScopedPathOverride(int key) : key_(key) {
15   SaveOriginal();
16   bool result = temp_dir_.CreateUniqueTempDir();
17   CHECK(result);
18   result = PathService::Override(key, temp_dir_.GetPath());
19   CHECK(result);
20 }
21 
ScopedPathOverride(int key,const base::FilePath & dir)22 ScopedPathOverride::ScopedPathOverride(int key, const base::FilePath& dir)
23     : key_(key) {
24   SaveOriginal();
25   bool result = PathService::Override(key, dir);
26   CHECK(result);
27 }
28 
ScopedPathOverride(int key,const FilePath & path,bool is_absolute,bool create)29 ScopedPathOverride::ScopedPathOverride(int key,
30                                        const FilePath& path,
31                                        bool is_absolute,
32                                        bool create)
33     : key_(key) {
34   SaveOriginal();
35   bool result =
36       PathService::OverrideAndCreateIfNeeded(key, path, is_absolute, create);
37   CHECK(result);
38 }
39 
SaveOriginal()40 void ScopedPathOverride::SaveOriginal() {
41   if (PathService::IsOverriddenForTesting(key_)) {
42     original_override_ = PathService::CheckedGet(key_);
43   }
44 }
45 
~ScopedPathOverride()46 ScopedPathOverride::~ScopedPathOverride() {
47   bool result = PathService::RemoveOverrideForTests(key_);
48   CHECK(result) << "The override seems to have been removed already!";
49   if (original_override_) {
50     // PathService::Override, by default, does some (blocking) checks to ensure
51     // that the path is absolute and exists. As the original override must have
52     // already gone through these checks, we can skip these checks here.
53     // This is needed for some tests which use ScopedPathOverride in scopes that
54     // disallow blocking.
55     result = PathService::OverrideAndCreateIfNeeded(
56         key_, *original_override_, /*is_absolute=*/true, /*create=*/false);
57     CHECK(result);
58   }
59 }
60 
61 }  // namespace base
62