File: integration_test_utils.cpp

package info (click to toggle)
megacmd 2.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 32,592 kB
  • sloc: cpp: 326,437; ansic: 34,524; python: 4,630; java: 3,965; sh: 2,869; objc: 2,459; makefile: 197; xml: 113
file content (476 lines) | stat: -rw-r--r-- 17,175 bytes parent folder | download
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
#include "integration_test_utils.h"

#include "gtest_common.h"
#include "integration/mock_listeners.h"
#include "mega/logging.h"
#include "megautils.h"
#include "sdk_test_utils.h"

#include <chrono>

namespace sdk_test
{
using namespace mega;
using namespace testing;
#ifdef ENABLE_SYNC

/**
 * @brief Aux implementation to generalize on how to get the sync
 */
static std::unique_ptr<::mega::MegaSync> waitForSyncState(MegaSync::SyncRunningState runState,
                                                          MegaSync::Error err,
                                                          std::function<MegaSync*()>&& syncGetter)
{
    std::unique_ptr<MegaSync> sync;
    waitFor(
        [syncGetter = std::move(syncGetter), &sync, runState, err]() -> bool
        {
            sync.reset(syncGetter());
            return (sync && sync->getRunState() == runState && sync->getError() == err);
        },
        30s);

    if (sync)
    {
        bool areTheExpectedStateAndError =
            sync->getRunState() == runState && sync->getError() == err;
        LOG_debug << "sync exists with the "
                  << (areTheExpectedStateAndError ? "expected" : "UNEXPECTED")
                  << " state: " << sync->getRunState() << " and error: " << sync->getError();
        return areTheExpectedStateAndError ? std::move(sync) : nullptr;
    }
    else
    {
        LOG_debug << "sync is null";
        return nullptr; // signal that the sync never reached the expected/required state
    }
}

std::unique_ptr<::mega::MegaSync> waitForSyncState(MegaApi* megaApi,
                                                   MegaNode* remoteNode,
                                                   MegaSync::SyncRunningState runState,
                                                   MegaSync::Error err)
{
    return waitForSyncState(runState,
                            err,
                            [&megaApi, &remoteNode]() -> MegaSync*
                            {
                                return megaApi->getSyncByNode(remoteNode);
                            });
}

std::unique_ptr<::mega::MegaSync> waitForSyncState(MegaApi* megaApi,
                                                   handle backupID,
                                                   MegaSync::SyncRunningState runState,
                                                   MegaSync::Error err)
{
    return waitForSyncState(runState,
                            err,
                            [&megaApi, backupID]() -> MegaSync*
                            {
                                return megaApi->getSyncByBackupId(backupID);
                            });
}

bool waitForSyncStallState(MegaApi* const megaApi)
{
    const auto isSyncStalledPred = [&megaApi]() -> bool
    {
        return isSyncStalled(megaApi);
    };
    return waitFor(isSyncStalledPred, 10s);
}

static handle createSyncAux(MegaApi* megaApi,
                            const MegaSync::SyncType syncType,
                            const std::string& localRootPath,
                            const MegaHandle remoteRootHandle,
                            const std::string& backupName)
{
    if (!megaApi)
        return UNDEF;

    if (syncType == MegaSync::TYPE_BACKUP && remoteRootHandle != UNDEF)
        return UNDEF;

    using namespace testing;
    NiceMock<MockRequestListener> rl{megaApi};

    handle backupId = UNDEF;
    auto setBackupId = [&backupId](const MegaRequest& req)
    {
        backupId = req.getParentHandle();
    };

    rl.setErrorExpectations(API_OK,
                            MegaSync::NO_SYNC_ERROR,
                            MegaRequest::TYPE_ADD_SYNC,
                            std::move(setBackupId));

    megaApi->syncFolder(syncType,
                        localRootPath.c_str(),
                        backupName.empty() ? nullptr : backupName.c_str(),
                        remoteRootHandle,
                        nullptr,
                        &rl);
    rl.waitForFinishOrTimeout(MAX_TIMEOUT);
    if (backupId == UNDEF)
        return UNDEF;

    std::unique_ptr<MegaSync> sync =
        waitForSyncState(megaApi, backupId, MegaSync::RUNSTATE_RUNNING, MegaSync::NO_SYNC_ERROR);
    if (!sync)
        return UNDEF;
    return backupId;
}

handle syncFolder(MegaApi* megaApi,
                  const std::string& localRootPath,
                  const MegaHandle remoteRootHandle)
{
    return createSyncAux(megaApi, MegaSync::TYPE_TWOWAY, localRootPath, remoteRootHandle, "");
}

handle backupFolder(MegaApi* megaApi,
                    const std::string& localRootPath,
                    const std::string& backupName)
{
    return createSyncAux(megaApi, MegaSync::TYPE_BACKUP, localRootPath, UNDEF, backupName);
}

bool removeSync(MegaApi* megaApi, const handle backupID)
{
    NiceMock<MockRequestListener> reqListener{megaApi};
    reqListener.setErrorExpectations(API_OK);
    megaApi->removeSync(backupID, &reqListener);
    return reqListener.waitForFinishOrTimeout(MAX_TIMEOUT);
}

bool setSyncRunState(MegaApi* megaApi,
                     const handle backupID,
                     const MegaSync::SyncRunningState state)
{
    NiceMock<MockRequestListener> reqListener{megaApi};
    reqListener.setErrorExpectations(API_OK);
    megaApi->setSyncRunState(backupID, state, &reqListener);
    return reqListener.waitForFinishOrTimeout(MAX_TIMEOUT);
}

bool resumeSync(MegaApi* megaApi, const handle backupID)
{
    return setSyncRunState(megaApi, backupID, MegaSync::SyncRunningState::RUNSTATE_RUNNING);
}

bool suspendSync(MegaApi* megaApi, const handle backupID)
{
    return setSyncRunState(megaApi, backupID, MegaSync::SyncRunningState::RUNSTATE_SUSPENDED);
}

bool disableSync(MegaApi* megaApi, const handle backupID)
{
    return setSyncRunState(megaApi, backupID, MegaSync::SyncRunningState::RUNSTATE_DISABLED);
}

bool isSyncStalled(MegaApi* const megaApi)
{
    if (megaApi == nullptr)
        return false;

    return megaApi->isSyncStalled();
}

std::vector<std::unique_ptr<MegaSyncStall>> getStalls(MegaApi* megaApi)
{
    if (megaApi == nullptr)
        return {};

    NiceMock<MockRequestListener> reqList{megaApi};
    const auto expectedErr = Pointee(Property(&MegaError::getErrorCode, API_OK));
    std::vector<std::unique_ptr<MegaSyncStall>> stalls;
    EXPECT_CALL(reqList, onRequestFinish(_, _, expectedErr))
        .WillOnce(
            [&stalls, &reqList](MegaApi*, MegaRequest* request, MegaError*)
            {
                if (auto list = request->getMegaSyncStallList(); list != nullptr)
                    stalls = toSyncStallVector(*list);
                reqList.markAsFinished();
            });
    megaApi->getMegaSyncStallList(&reqList);
    if (!reqList.waitForFinishOrTimeout(MAX_TIMEOUT))
        return {};
    return stalls;
}

#endif

std::pair<std::optional<std::vector<std::string>>, std::unique_ptr<MegaNodeList>>

    getCloudFirstChildren(MegaApi* megaApi, const MegaHandle nodeHandle)
{
    if (!megaApi || nodeHandle == UNDEF)
        return {std::nullopt, nullptr};
    std::unique_ptr<MegaNode> rootNode{megaApi->getNodeByHandle(nodeHandle)};
    if (!rootNode)
        return {std::nullopt, nullptr};
    std::unique_ptr<MegaNodeList> childrenNodeList{megaApi->getChildren(rootNode.get())};
    if (!childrenNodeList)
        return {std::nullopt, nullptr};

    auto namesVector = toNamesVector(*childrenNodeList);
    if (namesVector.size() != static_cast<size_t>(childrenNodeList->size()))
    {
        assert(false && "getCloudFirstChildren: invalid names vector size ");
        return {std::nullopt, nullptr};
    }

    return {namesVector, std::move(childrenNodeList)};
}

std::optional<std::vector<std::string>> getCloudFirstChildrenNames(MegaApi* megaApi,
                                                                   const MegaHandle nodeHandle)
{
    if (!megaApi || nodeHandle == UNDEF)
        return {};
    std::unique_ptr<MegaNode> rootNode{megaApi->getNodeByHandle(nodeHandle)};
    if (!rootNode)
        return {};
    std::unique_ptr<MegaNodeList> childrenNodeList{megaApi->getChildren(rootNode.get())};
    if (!childrenNodeList)
        return {};
    return toNamesVector(*childrenNodeList);
}

void getDeviceNames(MegaApi* megaApi, std::unique_ptr<MegaStringMap>& output)
{
    NiceMock<MockRequestListener> rl{megaApi};
    const auto expectedErr = Pointee(Property(&MegaError::getErrorCode, API_OK));
    EXPECT_CALL(rl, onRequestFinish(_, _, expectedErr))
        .WillOnce(
            [&output, &rl](MegaApi*, MegaRequest* req, MegaError*)
            {
                output.reset(req->getMegaStringMap()->copy());
                rl.markAsFinished();
            });
    megaApi->getUserAttribute(MegaApi::USER_ATTR_DEVICE_NAMES, &rl);
    ASSERT_TRUE(rl.waitForFinishOrTimeout(3min));
}

std::pair<bool, MegaHandle> getMyBackupsFolder(MegaApi* megaApi)
{
    MegaHandle h = UNDEF;
    NiceMock<MockRequestListener> rl{megaApi};
    const auto expectedErr = Pointee(Property(&MegaError::getErrorCode, API_OK));
    EXPECT_CALL(rl, onRequestFinish(_, _, expectedErr))
        .WillOnce(
            [&h, &rl](MegaApi*, MegaRequest* req, MegaError*)
            {
                h = req->getNodeHandle();
                rl.markAsFinished();
            });

    megaApi->getUserAttribute(MegaApi::USER_ATTR_MY_BACKUPS_FOLDER, &rl);
    const auto res = rl.waitForFinishOrTimeout(3min);
    return {res, h};
}

std::pair<bool, MegaHandle> setMyBackupsFolder(MegaApi* megaApi, const std::string& name)
{
    MegaHandle h = UNDEF;
    NiceMock<MockRequestListener> rl{megaApi};
    const auto expectedErr = Pointee(Property(&MegaError::getErrorCode, API_OK));
    EXPECT_CALL(rl, onRequestFinish(_, _, expectedErr))
        .WillOnce(
            [&h, &rl](MegaApi*, MegaRequest* req, MegaError*)
            {
                h = req->getNodeHandle();
                rl.markAsFinished();
            });

    megaApi->setMyBackupsFolder(name.c_str(), &rl);
    const auto res = rl.waitForFinishOrTimeout(3min);
    return {res, h};
}

void ensureAccountDeviceNamesAttrExists(MegaApi* megaApi)
{
    std::unique_ptr<MegaStringMap> devices;
    getDeviceNames(megaApi, devices);

    if (devices && devices->size() != 0)
        return;

    // Set device names attr in case is not set
    const std::string deviceName = "Jenkins " + getCurrentTimestamp(true);
    const std::string deviceId = megaApi->getDeviceId();
    devices->set(deviceId.c_str(), deviceName.c_str());
    NiceMock<MockRequestListener> rl{megaApi};
    rl.setErrorExpectations(API_OK);
    megaApi->setUserAttribute(MegaApi::USER_ATTR_DEVICE_NAMES, devices.get(), &rl);
    ASSERT_TRUE(rl.waitForFinishOrTimeout(MAX_TIMEOUT));
}

std::pair<bool, std::string> ensureMyBackupsFolderExists(MegaApi* megaApi, const std::string& name)
{
    auto getMyBackupsNode = [megaApi](MegaHandle h) -> std::pair<bool, std::string>
    {
        std::unique_ptr<MegaNode> myBackupsNode;
        if (myBackupsNode.reset(megaApi->getNodeByHandle(h)); myBackupsNode)
        {
            return {true, myBackupsNode->getName()};
        }
        return {false, {}};
    };

    if (auto [succeeded, h] = getMyBackupsFolder(megaApi); succeeded && h != UNDEF)
    {
        return getMyBackupsNode(h);
    }

    if (auto [succeeded, h] = setMyBackupsFolder(megaApi, name); succeeded && h != UNDEF)
    {
        return getMyBackupsNode(h);
    }
    return {false, {}};
}

std::optional<int> downloadNode(MegaApi* megaApi,
                                MegaNode* node,
                                const std::filesystem::path& fsPath,
                                bool pathIsFolder,
                                const std::chrono::seconds timeoutInSecs,
                                const int collisionCheck,
                                const int collisionResolution,
                                TransferFinishCallback transferFinishCallback,
                                const char* customName,
                                const char* appData,
                                const bool startFirst,
                                MegaCancelToken* cancelToken,
                                const bool undelete)
{
    if (!megaApi || !node)
    {
        LOG_err << "test_utils(downloadFile): EARGS";
        return std::nullopt;
    }

    std::optional<int> err{std::nullopt};
    testing::NiceMock<MockMegaTransferListener> mtl{megaApi};
    EXPECT_CALL(mtl, onTransferFinish)
        .WillOnce(
            [&mtl, &err, &transferFinishCallback](MegaApi* megaApi,
                                                  MegaTransfer* t,
                                                  MegaError* error)
            {
                if (transferFinishCallback)
                    transferFinishCallback(megaApi, t, error);
                err = error ? error->getErrorCode() : API_EINTERNAL;
                mtl.markAsFinished();
            });
    std::string downLoadPath{path_u8string(fsPath)};
    if (pathIsFolder && downLoadPath.back() != std::filesystem::path::preferred_separator)
    {
        downLoadPath.push_back(std::filesystem::path::preferred_separator);
    }

    megaApi->startDownload(node,
                           downLoadPath.c_str(),
                           customName,
                           appData,
                           startFirst,
                           cancelToken,
                           collisionCheck,
                           collisionResolution,
                           undelete,
                           &mtl);

    if (!mtl.waitForFinishOrTimeout(timeoutInSecs))
    {
        LOG_err << "test_utils(downloadFile): waitForFinishOrTimeout timeout expired";
        return std::nullopt;
    }
    return err;
}

std::unique_ptr<MegaNode> uploadFile(MegaApi* megaApi,
                                     const std::filesystem::path& localPath,
                                     MegaNode* parentNode,
                                     const char* fileName)
{
    testing::NiceMock<MockMegaTransferListener> mtl{megaApi};
    handle nodeHandle = UNDEF;
    EXPECT_CALL(mtl, onTransferFinish)
        .WillOnce(
            [&mtl, &nodeHandle](MegaApi*, MegaTransfer* transfer, MegaError* error)
            {
                nodeHandle = transfer->getNodeHandle();
                mtl.markAsFinished(error->getErrorCode() == API_OK);
            });
    std::unique_ptr<MegaNode> fallbackParent;
    MegaNode* uploadParent = parentNode;
    if (!uploadParent)
    {
        fallbackParent.reset(megaApi->getRootNode());
        uploadParent = fallbackParent.get();
    }

    MegaUploadOptions uploadOptions;
    if (fileName)
    {
        uploadOptions.fileName = fileName;
    }
    uploadOptions.mtime = MegaApi::INVALID_CUSTOM_MOD_TIME;

    const auto pathString = localPath.string();
    megaApi->startUpload(pathString, uploadParent, nullptr, &uploadOptions, &mtl);
    EXPECT_TRUE(mtl.waitForFinishOrTimeout(MAX_TIMEOUT)) << "Error uploading file: " << localPath;
    if (nodeHandle == UNDEF)
        return nullptr;
    return std::unique_ptr<MegaNode>(megaApi->getNodeByHandle(nodeHandle));
}

std::unique_ptr<MegaNode>
    uploadFile(MegaApi* megaApi, LocalTempFile&& file, MegaNode* parentNode, const char* fileName)
{
    return uploadFile(megaApi, file.getPath(), parentNode, fileName);
}

handle createPasswordNode(MegaApi* megaApi,
                          const std::string& name,
                          const MegaNode::PasswordNodeData* data,
                          const handle parentNodeHandle)
{
    NiceMock<MockRequestListener> rl;
    handle newPwdNodeHandle{UNDEF};
    rl.setErrorExpectations(API_OK,
                            _,
                            MegaRequest::TYPE_CREATE_PASSWORD_NODE,
                            [&newPwdNodeHandle](const MegaRequest& req)
                            {
                                newPwdNodeHandle = req.getNodeHandle();
                            });
    megaApi->createPasswordNode(name.c_str(), data, parentNodeHandle, &rl);
    EXPECT_TRUE(rl.waitForFinishOrTimeout(MAX_TIMEOUT))
        << "Password node not properly generated. Name: " << name;
    return newPwdNodeHandle;
}

handle createCreditCardNode(::mega::MegaApi* megaApi,
                            const std::string& name,
                            const ::mega::MegaNode::CreditCardNodeData* data,
                            const ::mega::handle parentNodeHandle)
{
    NiceMock<MockRequestListener> rl;
    handle newPwdNodeHandle{UNDEF};
    rl.setErrorExpectations(API_OK,
                            _,
                            MegaRequest::TYPE_CREATE_PASSWORD_NODE,
                            [&newPwdNodeHandle](const MegaRequest& req)
                            {
                                newPwdNodeHandle = req.getNodeHandle();
                            });
    megaApi->createCreditCardNode(name.c_str(), data, parentNodeHandle, &rl);
    EXPECT_TRUE(rl.waitForFinishOrTimeout(MAX_TIMEOUT))
        << "CreditCard node not properly generated. Name: " << name;
    return newPwdNodeHandle;
}
}