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_RDB_HELPER_MOCK_H
17 #define SECURITY_GUARD_RDB_HELPER_MOCK_H
18 
19 #include <memory>
20 #include <mutex>
21 #include <string>
22 
23 #include "gmock/gmock.h"
24 #include "singleton.h"
25 
26 #include "rdb_open_callback.h"
27 #include "rdb_store.h"
28 #include "rdb_store_config.h"
29 
30 namespace OHOS::NativeRdb {
31 class RdbHelperInterface {
32 public:
33     virtual ~RdbHelperInterface() = default;
34     virtual std::shared_ptr<RdbStore> GetRdbStore(
35         const RdbStoreConfig &config, int version, RdbOpenCallback &openCallback, int &errCode) = 0;
36 };
37 
38 class MockRdbHelperInterface : public RdbHelperInterface {
39 public:
40     MockRdbHelperInterface() = default;
41     ~MockRdbHelperInterface() override = default;
42     MOCK_METHOD4(GetRdbStore, std::shared_ptr<RdbStore>(const RdbStoreConfig &config, int version,
43         RdbOpenCallback &openCallback, int &errCode));
44 };
45 
46 class RdbHelper {
47 public:
GetRdbStore(const RdbStoreConfig & config,int version,RdbOpenCallback & openCallback,int & errCode)48     static std::shared_ptr<RdbStore> GetRdbStore(
49         const RdbStoreConfig &config, int version, RdbOpenCallback &openCallback, int &errCode)
50     {
51         if (instance_ == nullptr) {
52             return nullptr;
53         }
54         return instance_->GetRdbStore(config, version, openCallback, errCode);
55     };
56 
GetInterface()57     static std::shared_ptr<MockRdbHelperInterface> GetInterface()
58     {
59         if (instance_ == nullptr) {
60             std::lock_guard<std::mutex> lock(mutex_);
61             if (instance_ == nullptr) {
62                 instance_ = std::make_shared<MockRdbHelperInterface>();
63             }
64         }
65         return instance_;
66     };
67 
DelInterface()68     static void DelInterface()
69     {
70         if (instance_ != nullptr) {
71             instance_.reset();
72         }
73     };
74 
75 private:
76     static std::shared_ptr<MockRdbHelperInterface> instance_;
77     static std::mutex mutex_;
78 };
79 } // namespace OHOS::NativeRdb
80 #endif
81