summaryrefslogtreecommitdiffstats
path: root/common/test.cpp
blob: 098229387adc8989192a9829517ca30763d448ca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
/*
 * Copyright (C) 2014 Christian Mollekopf <chrigi_1@fastmail.fm>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) version 3, or any
 * later version accepted by the membership of KDE e.V. (or its
 * successor approved by the membership of KDE e.V.), which shall
 * act as a proxy defined in Section 6 of version 3 of the license.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "test.h"

#include <QStandardPaths>
#include <QDir>
#include <QDebug>
#include "facade.h"
#include "facadefactory.h"
#include "query.h"
#include "resourceconfig.h"
#include "definitions.h"

SINK_DEBUG_AREA("test")

using namespace Sink;

void Sink::Test::initTest()
{
    auto logIniFile = Sink::configLocation() + "/log.ini";
    auto areaAutocompletionFile = Sink::dataLocation() + "/debugAreas.ini";

    setTestModeEnabled(true);
    // qDebug() << "Removing " << QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation);
    QDir(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation)).removeRecursively();
    // qDebug() << "Removing " << QStandardPaths::writableLocation(QStandardPaths::DataLocation);
    QDir(QStandardPaths::writableLocation(QStandardPaths::DataLocation)).removeRecursively();
    // qDebug() << "Removing " << QStandardPaths::writableLocation(QStandardPaths::ConfigLocation);
    QDir(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)).removeRecursively();
    // qDebug() << "Removing " << QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation);
    QDir(QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation)).removeRecursively();
    // qDebug() << "Removing " << QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
    QDir(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)).removeRecursively();
    // qDebug() << "Removing " << QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation);
    QDir(QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation)).removeRecursively();
    Log::setPrimaryComponent("test");

    //We copy those files so we can control debug output from outside the test with sinksh
    {
        QFile file(logIniFile);
        if (!file.open(QIODevice::ReadOnly)) {
            qWarning() << "Failed to open the file: " << logIniFile;
        }
        QDir dir;
        dir.mkpath(Sink::configLocation());
        if (!file.copy(Sink::configLocation() + "/log.ini")) {
            qWarning() << "Failed to move the file: " << Sink::configLocation() + "/log.ini";
        }
    }
    {
        QFile file(areaAutocompletionFile);
        if (!file.open(QIODevice::ReadOnly)) {
            qWarning() << "Failed to open the file: " << logIniFile;
        }
        QDir dir;
        dir.mkpath(Sink::dataLocation());
        if (!file.copy(Sink::dataLocation() + "/debugAreas.ini")) {
            qWarning() << "Failed to move the file: " << Sink::configLocation() + "/log.ini";
        }
    }
}

void Sink::Test::setTestModeEnabled(bool enabled)
{
    QStandardPaths::setTestModeEnabled(enabled);
    if (enabled) {
        qputenv("SINK_TESTMODE", "TRUE");
    } else {
        qunsetenv("SINK_TESTMODE");
    }
}

bool Sink::Test::testModeEnabled()
{
    return !qEnvironmentVariableIsEmpty("SINK_TESTMODE");
}

template <typename T>
class TestFacade : public Sink::StoreFacade<T>
{
public:
    static std::shared_ptr<TestFacade<T>> registerFacade(Test::TestAccount *testAccount, const QByteArray &instanceIdentifier = QByteArray())
    {
        static QMap<QByteArray, std::shared_ptr<TestFacade<T>>> map;
        auto facade = std::make_shared<TestFacade<T>>();
        facade->mTestAccount = testAccount;
        map.insert(instanceIdentifier, facade);
        bool alwaysReturnFacade = instanceIdentifier.isEmpty();
        Sink::FacadeFactory::instance().registerFacade<T, TestFacade<T>>("testresource", [alwaysReturnFacade](const Sink::ResourceContext &context) {
            if (alwaysReturnFacade) {
                return map.value(QByteArray());
            }
            return map.value(context.resourceInstanceIdentifier);
        });
        return facade;
    }
    ~TestFacade(){};
    KAsync::Job<void> create(const T &domainObject) Q_DECL_OVERRIDE
    {
        mTestAccount->addEntity<T>(T::Ptr::create(domainObject));
        return KAsync::null<void>();
    };
    KAsync::Job<void> modify(const T &domainObject) Q_DECL_OVERRIDE
    {
        // mTestAccount->modifyEntity<T>(domainObject);
        return KAsync::null<void>();
    };
    KAsync::Job<void> remove(const T &domainObject) Q_DECL_OVERRIDE
    {
        //FIXME
        // mTestAccount->removeEntity<T>(domainObject);
        return KAsync::null<void>();
    };
    QPair<KAsync::Job<void>, typename Sink::ResultEmitter<typename T::Ptr>::Ptr> load(const Sink::Query &query) Q_DECL_OVERRIDE
    {
        auto resultProvider = new Sink::ResultProvider<typename T::Ptr>();
        resultProvider->onDone([resultProvider]() {
            SinkTrace() << "Result provider is done";
            delete resultProvider;
        });
        // We have to do it this way, otherwise we're not setting the fetcher right
        auto emitter = resultProvider->emitter();

        resultProvider->setFetcher([query, resultProvider, this](const typename T::Ptr &parent) {
            if (parent) {
                SinkTrace() << "Running the fetcher " << parent->identifier();
            } else {
                SinkTrace() << "Running the fetcher.";
            }
            SinkTrace() << "-------------------------.";
            for (const auto &res : mTestAccount->entities<T>()) {
                qDebug() << "Parent filter " << query.getFilter("parent").value.toByteArray() << res->identifier() << res->getProperty("parent").toByteArray();
                auto parentProperty = res->getProperty("parent").toByteArray();
                if ((!parent && parentProperty.isEmpty()) || (parent && parentProperty == parent->identifier()) || query.parentProperty.isEmpty()) {
                    qDebug() << "Found a match" << res->identifier();
                    resultProvider->add(res.template staticCast<T>());
                }
            }
            resultProvider->initialResultSetComplete(parent);
        });
        auto job = KAsync::syncStart<void>([query, resultProvider]() {});
        return qMakePair(job, emitter);
    }

    Test::TestAccount *mTestAccount;
};

Test::TestAccount Sink::Test::TestAccount::registerAccount()
{
    Test::TestAccount account;
    account.mFacades.insert(ApplicationDomain::getTypeName<ApplicationDomain::Folder>(), TestFacade<ApplicationDomain::Folder>::registerFacade(&account));
    account.mFacades.insert(ApplicationDomain::getTypeName<ApplicationDomain::Mail>(), TestFacade<ApplicationDomain::Mail>::registerFacade(&account));
    account.identifier = "testresource.instance1";
    ResourceConfig::addResource(account.identifier, "testresource");
    QMap<QByteArray, QVariant> configuration;
    configuration.insert(ApplicationDomain::SinkResource::Account::name, account.identifier);
    configuration.insert(ApplicationDomain::SinkResource::Capabilities::name, QVariant::fromValue(QByteArrayList() << ApplicationDomain::ResourceCapabilities::Mail::drafts << ApplicationDomain::ResourceCapabilities::Mail::storage << ApplicationDomain::ResourceCapabilities::Mail::transport));
    ResourceConfig::configureResource(account.identifier, configuration);
    return account;
}

template<typename DomainType>
void Sink::Test::TestAccount::addEntity(const Sink::ApplicationDomain::ApplicationDomainType::Ptr &domainObject)
{
    mEntities[ApplicationDomain::getTypeName<DomainType>()].append(domainObject);
}

template<typename DomainType>
typename DomainType::Ptr Sink::Test::TestAccount::createEntity()
{
    auto entity = DomainType::Ptr::create(ApplicationDomain::ApplicationDomainType::createEntity<DomainType>(identifier));
    addEntity<DomainType>(entity);
    return entity;
}

template<typename DomainType>
QList<Sink::ApplicationDomain::ApplicationDomainType::Ptr> Sink::Test::TestAccount::entities() const
{
    return mEntities.value(ApplicationDomain::getTypeName<DomainType>());
}


#define REGISTER_TYPE(T)                                                          \
    template QList<Sink::ApplicationDomain::ApplicationDomainType::Ptr> Sink::Test::TestAccount::entities<T>() const;           \
    template void Sink::Test::TestAccount::addEntity<T>(const ApplicationDomain::ApplicationDomainType::Ptr &);           \
    template typename T::Ptr Sink::Test::TestAccount::createEntity<T>();


REGISTER_TYPE(ApplicationDomain::Event);
REGISTER_TYPE(ApplicationDomain::Mail);
REGISTER_TYPE(ApplicationDomain::Folder);
REGISTER_TYPE(ApplicationDomain::SinkResource);
REGISTER_TYPE(ApplicationDomain::SinkAccount);
REGISTER_TYPE(ApplicationDomain::Identity);