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_PREFERENCES_HELPER_MOCK_H
17#define SECURITY_GUARD_PREFERENCES_HELPER_MOCK_H
18
19#include <memory>
20#include <mutex>
21#include <string>
22
23#include "gmock/gmock.h"
24
25#include "preferences.h"
26
27namespace OHOS::NativePreferences {
28struct Options {
29public:
30    Options(const std::string inputFilePath) : filePath(inputFilePath)
31    {
32    }
33
34    Options(const char *inputFilePath) : filePath(inputFilePath)
35    {
36    }
37
38    Options(const std::string &inputFilePath, const std::string &inputbundleName, const std::string &inputdataGroupId)
39        : filePath(inputFilePath), bundleName(inputbundleName), dataGroupId(inputdataGroupId)
40    {
41    }
42
43public:
44    std::string filePath{ "" };
45    std::string bundleName{ "" };
46    std::string dataGroupId{ "" };
47};
48
49class PreferenceHelperInterface {
50public:
51    virtual ~PreferenceHelperInterface() = default;
52    virtual std::shared_ptr<Preferences> GetPreferences(const Options &options, int &errCode);
53};
54
55class MockPreferenceHelperInterface : public PreferenceHelperInterface {
56public:
57    MockPreferenceHelperInterface() = default;
58    ~MockPreferenceHelperInterface() override = default;
59    MOCK_METHOD2(GetPreferences, std::shared_ptr<Preferences>(const Options &options, int &errCode));
60};
61
62class PreferencesHelper {
63public:
64    static std::shared_ptr<Preferences> GetPreferences(const Options &options, int &errCode)
65    {
66        if (instance_ == nullptr) {
67            return nullptr;
68        }
69        return instance_->GetPreferences(options, errCode);
70    };
71
72    static std::shared_ptr<MockPreferenceHelperInterface> GetInterface()
73    {
74        if (instance_ == nullptr) {
75            std::lock_guard<std::mutex> lock(mutex_);
76            if (instance_ == nullptr) {
77                instance_ = std::make_shared<MockPreferenceHelperInterface>();
78            }
79        }
80        return instance_;
81    };
82
83private:
84    static std::shared_ptr<MockPreferenceHelperInterface> instance_;
85    static std::mutex mutex_;
86};
87} // namespace OHOS::NativePreferences
88#endif // SECURITY_GUARD_PREFERENCES_HELPER_MOCK_H