Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / chrome / common / importer / ie_importer_test_registry_overrider_win.cc
blobe84cb6502476d378a1824a52e4cf3222445b19bc
1 // Copyright (c) 2013 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.
5 #include "chrome/common/importer/ie_importer_test_registry_overrider_win.h"
7 #include <windows.h>
9 #include <string>
11 #include "base/environment.h"
12 #include "base/guid.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/strings/utf_string_conversions.h"
15 #include "base/win/registry.h"
17 namespace {
19 // The key to which a random subkey will be appended. This key itself will never
20 // be deleted.
21 const wchar_t kTestHKCUOverrideKeyPrefix[] = L"SOFTWARE\\Chromium Unit Tests\\";
22 const char kTestHKCUOverrideEnvironmentVariable[] =
23 "IE_IMPORTER_TEST_OVERRIDE_HKCU";
25 // Reads the environment variable set by a previous call to
26 // SetTestRegistryOverride() into |key| if it exists and |key| is not NULL.
27 // Returns true if the variable was successfully read.
28 bool GetTestKeyFromEnvironment(base::string16* key) {
29 scoped_ptr<base::Environment> env(base::Environment::Create());
30 std::string value;
31 bool result = env->GetVar(kTestHKCUOverrideEnvironmentVariable, &value);
32 if (result)
33 *key = base::UTF8ToUTF16(value);
34 return result;
37 } // namespace
39 ////////////////////////////////////////////////////////////////////////////////
40 // IEImporterTestRegistryOverrider, public:
42 IEImporterTestRegistryOverrider::IEImporterTestRegistryOverrider()
43 : temporary_key_(kTestHKCUOverrideKeyPrefix +
44 base::UTF8ToUTF16(base::GenerateGUID())) {
45 DCHECK(!GetTestKeyFromEnvironment(NULL));
47 scoped_ptr<base::Environment> env(base::Environment::Create());
48 bool success = env->SetVar(kTestHKCUOverrideEnvironmentVariable,
49 base::UTF16ToUTF8(temporary_key_));
50 DCHECK(success);
53 IEImporterTestRegistryOverrider::~IEImporterTestRegistryOverrider() {
54 base::win::RegKey reg_key(HKEY_CURRENT_USER, temporary_key_.c_str(),
55 KEY_ALL_ACCESS);
56 DCHECK(reg_key.Valid());
57 reg_key.DeleteKey(L"");
59 scoped_ptr<base::Environment> env(base::Environment::Create());
60 bool success = env->UnSetVar(kTestHKCUOverrideEnvironmentVariable);
61 DCHECK(success);
64 // static
65 base::string16 IEImporterTestRegistryOverrider::GetTestRegistryOverride() {
66 base::string16 key;
67 if (!GetTestKeyFromEnvironment(&key))
68 return base::string16();
69 return key;