1 /*
2  * Copyright (c) 2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef SECURITY_GUARD_PREFERENCE_WRAPPER_H
17 #define SECURITY_GUARD_PREFERENCE_WRAPPER_H
18 
19 #include <mutex>
20 #include <string>
21 
22 #include "gmock/gmock.h"
23 
24 namespace OHOS::Security::SecurityGuard {
25 class PreferenceWrapperInterface {
26 public:
27     virtual ~PreferenceWrapperInterface() = default;
28     virtual int32_t PutInt(const std::string &key, int value) = 0;
29     virtual int32_t GetInt(const std::string &key, int defaultValue) = 0;
30 };
31 
32 class MockPreferenceWrapperInterface : public PreferenceWrapperInterface {
33 public:
34     MockPreferenceWrapperInterface() = default;
35     ~MockPreferenceWrapperInterface() override = default;
36     MOCK_METHOD2(PutInt, int32_t(const std::string &key, int value));
37     MOCK_METHOD2(GetInt, int32_t(const std::string &key, int defaultValue));
38 };
39 
40 class PreferenceWrapper {
41 public:
PutInt(const std::string & key,int value)42     static int32_t PutInt(const std::string &key, int value)
43     {
44         if (instance_ == nullptr) {
45             return -1;
46         }
47         return instance_->PutInt(key, value);
48     }
49 
GetInt(const std::string & key,int defaultValue)50     static int32_t GetInt(const std::string &key, int defaultValue)
51     {
52         if (instance_ == nullptr) {
53             return -1;
54         }
55         return instance_->GetInt(key, defaultValue);
56     }
57 
GetInterface()58     static std::shared_ptr<MockPreferenceWrapperInterface> GetInterface()
59     {
60         if (instance_ == nullptr) {
61             std::lock_guard<std::mutex> lock(mutex_);
62             if (instance_ == nullptr) {
63                 instance_ = std::make_shared<MockPreferenceWrapperInterface>();
64             }
65         }
66         return instance_;
67     };
68 
DelInterface()69     static void DelInterface()
70     {
71         if (instance_ != nullptr) {
72             instance_.reset();
73         }
74     };
75 
76 private:
77     static std::shared_ptr<MockPreferenceWrapperInterface> instance_;
78     static std::mutex mutex_;
79 };
80 }  // OHOS::Security::SecurityGuard
81 
82 #endif // SECURITY_GUARD_PREFERENCE_WRAPPER_H
83