File: main.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 (894 lines) | stat: -rw-r--r-- 23,837 bytes parent folder | download | duplicates (2)
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
#include "mega.h"
#include "mega/filesystem.h"
#include "gtest_common.h"
#include <cstdio>
#include <fstream>
#ifdef WIN32
#include <winhttp.h>
#endif

#include "sdk_test_utils.h"
#include "test.h"
#include "env_var_accounts.h"

#include <mega/fuse/common/mount_result.h>
#include <mega/fuse/common/service.h>

// If running in Jenkins, we use its working folder.  But for local manual testing, use a convenient location
std::string getLocalTestFolder()
{
    const std::string folderName{"mega_tests"};
#ifdef WIN32
    return std::string("c:\\tmp\\") + folderName;
#else
    // Should always find HOME on Posix, but use "." as backup
    return Utils::getenv("HOME", ".") + "/" + folderName;
#endif

}

fs::path LINK_EXTRACT_SCRIPT = "email_processor.py";

const string& getDefaultLogName()
{
    static const string LOG_NAME{ "test_integration.log" };
    return LOG_NAME;
}

bool gWriteLog = false;
string gLogName = getDefaultLogName();
bool gResumeSessions = false;
bool gScanOnly = false; // will be used in SRW
bool gManualVerification=false;
bool gFreeAccounts = false; // force accounts used in tests to remain free level after finishing

std::string USER_AGENT = "Integration Tests with GoogleTest framework";

void WaitMillisec(unsigned n)
{
#ifdef _WIN32
    if (n > 1000)
    {
        for (int i = 0; i < 10; ++i)
        {
            // better for debugging, with breakpoints, pauses, etc
            Sleep(n/10);
        }
    }
    else
    {
        Sleep(n);
    }
#else
    usleep(n * 1000);
#endif
}

string runProgram(const string& command, PROG_OUTPUT_TYPE ot)
{
    FILE* pPipe =
#ifdef _WIN32
        _popen(command.c_str(), "rt");
#else
        popen(command.c_str(), "r");
#endif

    if (!pPipe)
    {
        LOG_err << "Failed to run command\n" << command;
        return string();
    }

    // Read pipe until file ends or error occurs.
    string output;
    char   psBuffer[128];

    while (!feof(pPipe) && !ferror(pPipe))
    {
        switch (ot)
        {
        case PROG_OUTPUT_TYPE::TEXT:
        {
            if (fgets(psBuffer, 128, pPipe))
            {
                output += psBuffer;
            }
            break;
        }

        case PROG_OUTPUT_TYPE::BINARY:
        {
            size_t lastRead = fread(psBuffer, 1, sizeof(psBuffer), pPipe);
            if (lastRead)
            {
                output.append(psBuffer, lastRead);
            }
        }
        } // end switch()
    }

    if (ferror(pPipe))
    {
        LOG_err << "Failed to read full command output.";
    }

#ifdef _WIN32
    _pclose(pPipe);
#else
    pclose(pPipe); // docs don't _guarantee_ handling null stream
#endif

    return output;
}

string loadfile(const string& filename)
{
    string filedata;
    ifstream f(filename, ios::binary);
    f.seekg(0, std::ios::end);
    filedata.resize(unsigned(f.tellg()));
    f.seekg(0, std::ios::beg);
    f.read(const_cast<char*>(filedata.data()), static_cast<std::streamsize>(filedata.size()));
    return filedata;
}

#ifdef WIN32
void synchronousHttpPOSTData(const string& url, const string& senddata, string& responsedata)
{
    LOG_info << "Sending file to " << url << ", size: " << senddata.size();

    BOOL  bResults = TRUE;
    HINTERNET hSession = NULL, hConnect = NULL, hRequest = NULL;

    // Use WinHttpOpen to obtain a session handle.
    hSession = WinHttpOpen(L"testmega/1.0",
        WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
        WINHTTP_NO_PROXY_NAME,
        WINHTTP_NO_PROXY_BYPASS, 0);

    WCHAR szURL[8192];
    WCHAR szHost[256];
    URL_COMPONENTS urlComp = { sizeof urlComp };

    urlComp.lpszHostName = szHost;
    urlComp.dwHostNameLength = sizeof szHost / sizeof *szHost;
    urlComp.dwUrlPathLength = (DWORD)-1;
    urlComp.dwSchemeLength = (DWORD)-1;

    if (MultiByteToWideChar(CP_UTF8, 0, url.c_str(), -1, szURL,
        sizeof szURL / sizeof *szURL)
        && WinHttpCrackUrl(szURL, 0, 0, &urlComp))
    {
        if ((hConnect = WinHttpConnect(hSession, szHost, urlComp.nPort, 0)))
        {
            hRequest = WinHttpOpenRequest(hConnect, L"POST",
                urlComp.lpszUrlPath, NULL,
                WINHTTP_NO_REFERER,
                WINHTTP_DEFAULT_ACCEPT_TYPES,
                (urlComp.nScheme == INTERNET_SCHEME_HTTPS)
                ? WINHTTP_FLAG_SECURE
                : 0);
        }
    }

    // Send a Request.
    if (hRequest)
    {
        WinHttpSetTimeouts(hRequest, 58000, 58000, 0, 0);

        LPCWSTR pwszHeaders = L"Content-Type: application/octet-stream";

        // HTTPS connection: ignore certificate errors, send no data yet
        DWORD flags = SECURITY_FLAG_IGNORE_CERT_CN_INVALID
            | SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
            | SECURITY_FLAG_IGNORE_UNKNOWN_CA;

        WinHttpSetOption(hRequest, WINHTTP_OPTION_SECURITY_FLAGS, &flags, sizeof flags);

        if (WinHttpSendRequest(hRequest, pwszHeaders,
            DWORD(wcslen(pwszHeaders)),
            (LPVOID)senddata.data(),
            (DWORD)senddata.size(),
            (DWORD)senddata.size(),
            NULL))
        {
        }
    }

    DWORD dwSize = 0;

    // End the request.
    if (bResults)
        bResults = WinHttpReceiveResponse(hRequest, NULL);

    // Continue to verify data until there is nothing left.
    if (bResults)
        do
        {
            // Verify available data.
            dwSize = 0;
            if (!WinHttpQueryDataAvailable(hRequest, &dwSize))
                printf("Error %u in WinHttpQueryDataAvailable.\n",
                    GetLastError());

            size_t offset = responsedata.size();
            responsedata.resize(offset + dwSize);

            ZeroMemory(responsedata.data() + offset, dwSize);

            DWORD dwDownloaded = 0;
            if (!WinHttpReadData(hRequest, responsedata.data() + offset, dwSize, &dwDownloaded))
                printf("Error %u in WinHttpReadData.\n", GetLastError());

        } while (dwSize > 0);

    // Report errors.
    if (!bResults)
        printf("Error %d has occurred.\n", GetLastError());

    // Close open handles.
    if (hRequest) WinHttpCloseHandle(hRequest);
    if (hConnect) WinHttpCloseHandle(hConnect);
    if (hSession) WinHttpCloseHandle(hSession);
}
#endif

void synchronousHttpPOSTFile(const string& url, const string& filepath, string& responsedata)
{
#ifdef WIN32
    synchronousHttpPOSTData(url, loadfile(filepath), responsedata);
#else
    string command = "curl -s --data-binary @";
    command.append(filepath).append(" ").append(url);
    responsedata = runProgram(command, PROG_OUTPUT_TYPE::BINARY);
#endif
}

LogStream::~LogStream()
{
    auto data = mBuffer.str();

    // Always write messages via standard logger.
    LOG_debug << data;
}

std::string logTime()
{
    return getCurrentTimestamp();
}

LogStream out()
{
    return LogStream();
}

class TestMegaLogger : public Logger
{
    mutex logMutex;
public:
    static bool writeCout;

    void log(const char* /*time*/, int loglevel, const char* source, const char* message
#ifdef ENABLE_LOG_PERFORMANCE
          , const char **directMessages = nullptr, size_t *directMessagesSizes = nullptr, unsigned numberMessages = 0
#endif
    ) override
    {
        std::ostringstream os;

        os << "[";
        os << getCurrentTimestamp();
#ifdef ENABLE_LOG_PERFORMANCE
        os << "] " << SimpleLogger::toStr(static_cast<LogLevel>(loglevel)) << ": ";
        if (message)
        {
            os << message;
        }
        // we can have the message AND the direct messages
        for (unsigned i = 0; i < numberMessages; ++i)
            os.write(directMessages[i], static_cast<streamsize>(directMessagesSizes[i]));
#else
        os << "] " << SimpleLogger::toStr(static_cast<LogLevel>(loglevel)) << ": " << message;
#endif
        if (source)
        {
            os << " (" << source << ")";
        }
        os << std::endl;

        lock_guard<mutex> g(logMutex);

        if (loglevel <= SimpleLogger::getLogLevel())
        {
            if (gWriteLog)
            {
                if (!mLogFile.is_open())
                {
                    mLogFile.open(gLogName, ios::app);
                }
                mLogFile << os.str() << std::flush;
            }
            else
            {
                bool output = writeCout;
#ifdef _WIN32
                if (IsDebuggerPresent())
                    output = false;
#endif // _WIN32

                if (output)
                    std::cout << os.str() << std::flush;
            }

#ifdef _WIN32
            // Always show the logging in the output window in VS, very useful to see what's going on as the tests run
            // (with the high level --log output visible in the app's own console window)
            OutputDebugStringA(os.str().c_str());
#endif // _WIN32
        }
    }

    void close() {
        mLogFile.close();
    }

private:
    std::ofstream mLogFile;
};
bool TestMegaLogger::writeCout = true;

class GTestLogger
  : public ::testing::EmptyTestEventListener
{
    static void toLog(const std::string& message)
    {
        out() << "GTEST: " << message;
    }

public:
    void OnTestEnd(const ::testing::TestInfo& info) override
    {
        std::string result = "FAILED";

        if (info.result()->Passed())
        {
            result = "PASSED";
        }

        out() << "GTEST: "
              << result
              << " "
              << info.test_case_name()
              << "."
              << info.name();

        RequestRetryRecorder::instance().report(toLog);
    }

    void OnTestPartResult(const ::testing::TestPartResult& result) override
    {
        using namespace ::testing;

        if (result.type() == TestPartResult::kSuccess) return;

        std::string file = "unknown";
        std::string line;

        if (result.file_name())
        {
            file = result.file_name();
        }

        if (result.line_number() >= 0)
        {
            line = std::to_string(result.line_number()) + ":";
        }

        out() << "GTEST: "
              << file
              << ":"
              << line
              << " Failure";

        std::istringstream istream(result.message());

        for (std::string s; std::getline(istream, s); )
        {
            out() << "GTEST: " << s;
        }

        RequestRetryRecorder::instance().report(toLog);
    }

    void OnTestStart(const ::testing::TestInfo& info) override
    {
        out() << "GTEST: RUNNING "
              << info.test_case_name()
              << "."
              << info.name();
    }
}; // GTestLogger

class RequestRetryReporter
  : public ::testing::EmptyTestEventListener
{
    static void toStandardOutput(const std::string& message)
    {
        std::cout << message << std::endl;
    }

public:
    void OnTestEnd(const ::testing::TestInfo&) override
    {
        RequestRetryRecorder::instance().report(toStandardOutput);
    }

    void OnTestPartResult(const ::testing::TestPartResult& result) override
    {
        using ::testing::TestPartResult;

        // Only write report if the test failed.
        if (result.type() == TestPartResult::kSuccess)
            RequestRetryRecorder::instance().report(toStandardOutput);
    }
}; // RequestRetryReporter

// Let us log even during post-test shutdown
TestMegaLogger megaLogger;

#ifdef ENABLE_SYNC
// destroy g_clientManager while the logging is still active
ClientManager* g_clientManager = nullptr;
#endif // ENABLE_SYNC

RequestRetryRecorder* RequestRetryRecorder::mInstance = nullptr;


class SdkRuntimeArgValues : public RuntimeArgValues
{
public:
    SdkRuntimeArgValues(std::vector<std::string>&& args, std::vector<std::pair<std::string, std::string>>&& envVars) :
        RuntimeArgValues(std::move(args), std::move(envVars))
    {
        if (isHelp() || isListOnly() || !isValid())
        {
            return;
        }

        for (auto it = mArgs.begin(); it != mArgs.end();)
        {
            string arg = Utils::toUpperUtf8(*it);

            if (arg == "--LOG")
            {
                gWriteLog = true;
            }
            else if (arg == "--CI")
            {
                // options for continuous integration
                gWriteLog = true;
            }
            else if (arg == "--RESUMESESSIONS")
            {
                gResumeSessions = true;
            }
            else if (arg == "--SCANONLY")
            {
                gScanOnly = true;
            }
            else if (arg == "--FREEACCOUNTS")
            {
                gFreeAccounts = true;
            }

            ++it;
        }
    }

protected:
    void printCustomOptions() const override
    {
        cout << buildAlignedHelpString("--LOG",            {"Write output to log file"}) << '\n';
        cout << buildAlignedHelpString("--CI",             {"Include all 'Continuous Integration' options (same as --LOG)"}) << '\n';
        cout << buildAlignedHelpString("--RESUMESESSIONS", {"Resume previous account sessions, instead of full logins"}) << '\n';
        cout << buildAlignedHelpString("--SCANONLY",       {"Scan synced folders periodically instead of use file system notifications"}) << '\n';
        cout
            << buildAlignedHelpString(
                   "--FREEACCOUNTS",
                   {"Test accounts used will remain at free account level at the end of the tests"})
            << '\n';
    }

    void printCustomEnvVars() const override
    {
        cout << buildAlignedHelpString("  $MEGA_REAL_EMAIL", {"mega.co.nz email account to recevied account creation emails"}) << '\n';
        cout << buildAlignedHelpString("  $MEGA_REAL_PWD",   {"Password for Mega email account"}) << '\n';
        cout << buildAlignedHelpString("  $WORKSPACE",       {"Where to base tests, defaults to " + getLocalTestFolder() + " when not set"}) << '\n';
    }
};

// Make sure any megafs mounts are nuked before and after a run.
class ScopedAbortMounts
{
    // Nuke all megafs mounts on this machine.
    void abort()
    {
        // Convenience.
        using namespace ::mega::fuse;

        // Where would our mounts be mounted?
        auto workspace = path_u8string(TestFS::GetBaseFolder());

        // Nuke everything.
        auto result = Service::abort([&](const std::string& path) {
            // Make sure path is present under the workspace.
            return path.size() > workspace.size()
                   && !path.compare(0, workspace.size(), workspace);
        });

        // The mounts have been nuked.
        if (result == MOUNT_SUCCESS)
            return;

        // Couldn't nuke the mounts.
        LOG_warn << "Couldn't abort FUSE mounts: "
                 << toString(result);
    }

    // Whether we should abort any mounts.
    bool mAbort;

public:
    // Nuke the mounts when our tests start.
    ScopedAbortMounts(bool abort)
      : mAbort(abort)
    {
    }

    // And just before they end.
    ~ScopedAbortMounts()
    {
        if (mAbort)
            abort();
    }
}; // ScopedAbortMounts

int main (int argc, char *argv[])
{
    SdkRuntimeArgValues argVals(vector<string>(argv, argv + argc), getEnvVarAccounts().cloneVarNames());
    if (argVals.isHelp())
    {
        argVals.printHelp();
        return 0;
    }

    if (!argVals.isValid())
    {
        std::cout << "No tests executed (invalid arguments)." << std::endl;
        return -1;
    }

    if (argVals.isListOnly())
    {
        testing::InitGoogleTest(&argc, argv);
        return RUN_ALL_TESTS(); // returns 0 (success) or 1 (failed tests)
    }

    gLogName = argVals.getLog(); // set accordingly for worker or main process

    remove(gLogName.c_str());

    // Abort any stale mounts.
    ScopedAbortMounts abort(!argVals.isWorker());

    if (argVals.isMainProcWithWorkers())
    {
        // Don't run tests, only manage subprocesses.
        // To get here run with --INSTANCES:2 [--EMAIL-POOL:foo+bar-{1-28}@mega.nz]
        // If --EMAIL-POOL runtime arg is missing, email template will be taken from MEGA_EMAIL.
        // Password for all emails built from template will be taken from MEGA_PWD env var.
        // If it did not get an email template, it'll use a single subprocess with the existing env
        // vars.
        GTestParallelRunner pr(std::move(argVals));
        string testBase =
            path_u8string((TestFS::GetBaseFolder() / "pid_")); // see TestFS::GetProcessFolder()
        pr.useWorkerOutputPathForPid(std::move(testBase));
        return pr.run();
    }

    if (!argVals.getCustomApiUrl().empty())
    {
        g_APIURL_default = argVals.getCustomApiUrl();
    }
    if (!argVals.getCustomUserAget().empty())
    {
        USER_AGENT = argVals.getCustomUserAget();
    }
    if (argVals.isMainProcOnly())
    {
        // Env vars might need to be set, for example when an email template was used
        auto envVars = argVals.getEnvVarsForWorker(0);
        for (const auto& env : envVars)
        {
            Utils::setenv(env.first, env.second);
        }
    }

    // So we can track how often requests are retried.
    RequestRetryRecorder retryRecorder;

    try {

#ifdef ENABLE_SYNC
    // destroy g_clientManager while the logging is still active, and before global destructors (for things like mutexes) run
    ClientManager clientManager;
    g_clientManager = &clientManager;
#endif // ENABLE_SYNC

    sdk_test::setTestDataDir(fs::absolute(fs::path(argv[0]).parent_path()));

    SimpleLogger::setLogLevel(logVerbose);
    SimpleLogger::setOutputClass(&megaLogger);
    MegaApi::setLogJSON(MegaApi::getLogJSON() | MegaApi::JSON_LOG_CHUNK_RECEIVED);
    // delete old test folders, created during previous runs
    TestFS testFS;
    testFS.ClearProcessFolder();
    testFS.ChangeToProcessFolder();

#if defined(__APPLE__)
    // our waiter uses select which only supports file number <=1024.
    // by limiting max open files to 1024, we might able to know this error precisely
    platformSetRLimitNumFile(1024); 
#endif // __APPLE__

    // Add listeners.
    {
        auto& listeners = testing::UnitTest::GetInstance()->listeners();

        // Emit request retries to screen.
        listeners.Append(new RequestRetryReporter());

        // Emit test events to a log file.
        if (gWriteLog)
            listeners.Append(new GTestLogger());
    }

    ::testing::InitGoogleTest(&argc, argv);

    int gtestRet = RUN_ALL_TESTS();

#if defined(USE_OPENSSL) && !defined(OPENSSL_IS_BORINGSSL)
    if (CurlHttpIO::sslMutexes)
    {
        int numLocks = CRYPTO_num_locks();
        for (int i = 0; i < numLocks; ++i)
        {
            delete CurlHttpIO::sslMutexes[i];
        }
        delete [] CurlHttpIO::sslMutexes;
    }
#endif

#ifdef ENABLE_SYNC
    g_clientManager->clear();
#endif
    megaLogger.close();

    return gtestRet;

    }
    catch (exception& e) {
        cerr << argv[0] << ": exception: " << e.what() << endl;
        return -1;
    }
}




/*
**  TestFS implementation
*/

using namespace std;

fs::path TestFS::GetBaseFolder()
{
    return fs::path{Utils::getenv("WORKSPACE", getLocalTestFolder())};
}

fs::path TestFS::GetProcessFolder()
{
    fs::path testBase = GetBaseFolder() / ("pid_" + std::to_string(getCurrentPid()));
    return testBase;
}

fs::path TestFS::GetTestFolder()
{
    fs::path testpath = GetProcessFolder() / "test";
    return testpath;
}


fs::path TestFS::GetTrashFolder()
{
    return GetProcessFolder() / "trash";
}


void TestFS::DeleteFolder(fs::path folder)
{
    // rename folder, so that tests can still create one and add to it
    error_code ec;
    fs::path oldpath(folder);
    fs::path newpath(folder);

    for (int i = 10; i--; )
    {
        newpath += "_del"; // this can be improved later if needed
        fs::rename(oldpath, newpath, ec);
        if (!ec) break;
    }

    // if renaming failed, then there's nothing to delete
    if (ec)
    {
        // report failures, other than the case when it didn't exist
        if (ec != errc::no_such_file_or_directory)
        {
            out() << "Renaming " << oldpath << " to " << newpath << " failed."
                 << ec.message();
        }

        return;
    }

    // delete folder in a separate thread
    m_cleaners.emplace_back(thread([=]() mutable // ...mostly for fun, to avoid declaring another ec
        {
            fs::remove_all(newpath, ec);

            if (ec)
            {
                out() << "Deleting " << folder << " failed."
                     << ec.message();
            }
        }));
}


TestFS::~TestFS()
{
    for_each(m_cleaners.begin(), m_cleaners.end(), [](thread& t) { t.join(); });
}

void TestFS::ClearProcessFolder()
{
    fs::path base = GetProcessFolder();

    if (!fs::exists(base))
        return;

    FSACCESS_CLASS fsaccess;
    unique_ptr<DirAccess> dir(fsaccess.newdiraccess());
    
    LocalPath lbase = LocalPath::fromAbsolutePath(base.string());
    lbase.appendWithSeparator(LocalPath::fromRelativePath("*"), false);
    if (!dir->dopen(&lbase, nullptr, true))
        throw runtime_error("Can not read directory '" + lbase.toPath(false) + "'");

    LocalPath nameArg;
    nodetype_t ntype = TYPE_UNKNOWN;
    while (dir->dnext(lbase, nameArg, true, &ntype))
    {
        if (ntype == FILENODE) {
            fs::remove(nameArg.toPath(false));
        }
        else {
            fs::remove_all(nameArg.toPath(false));
        }
    }
}

void TestFS::ChangeToProcessFolder()
{
    fs::path base = GetProcessFolder();
    fs::create_directories(base);
    fs::current_path(base);
}

void moveToTrash(const fs::path& p)
{
    fs::path trashpath(TestFS::GetTrashFolder());
    fs::create_directory(trashpath);
    fs::path newpath = trashpath / p.filename();
    int errcount = 0;
    for (int i = 2; errcount < 20; ++i)
    {
        if (!fs::exists(p)) break;

        const std::string newname = path_u8string(p.filename().stem()) + "_" + std::to_string(i) +
                                    path_u8string(p.extension());
        newpath = trashpath / fs::path(newname);

        if (!fs::exists(newpath))
        {
            std::error_code e;
            fs::rename(p, newpath, e);
            if (e)
            {
                LOG_err << "Failed to trash-rename " << path_u8string(p) << " to "
                        << path_u8string(newpath) << ": " << e.message();
                WaitMillisec(500);
                errcount += 1;
            }
            else break;
        }
    }
}

fs::path makeNewTestRoot()
{
    fs::path p = TestFS::GetTestFolder();

    if (fs::exists(p))
    {
        moveToTrash(p);
    }

    std::error_code e;
    bool b = fs::create_directories(p, e);
    if (!b)
    {
        out() << "Failed to create base directory for test at: " << path_u8string(p)
              << ", error: " << e.message();
    }
    assert(b);
    return p;
}

fs::path makeReusableClientFolder(const string& subfolder)
{
    fs::path p = TestFS::GetProcessFolder() / ("clients_" + std::to_string(getCurrentPid())) / subfolder;

#ifndef NDEBUG
    bool b =
#endif
    fs::create_directories(p);
    assert(b);
    return p;
}


bool SdkTestBase::clearProcessFolderEachTest = false;

void SdkTestBase::SetUp()
{
    Test::SetUp();

    TestFS::ChangeToProcessFolder();

    if (clearProcessFolderEachTest)
    {
        // for testing that tests are independent, slow as NOD database deleted
        TestFS::ClearProcessFolder();
    }

    // Reset request retry statistics.
    RequestRetryRecorder::instance().reset();
}

fs::path getLinkExtractSrciptPath() {
    return sdk_test::getTestDataDir() / LINK_EXTRACT_SCRIPT;
}

bool isFileHidden(const LocalPath& path)
{
    return FileSystemAccess::isFileHidden(path) != 0;
}

bool isFileHidden(const fs::path& path)
{
    return isFileHidden(LocalPath::fromAbsolutePath(path_u8string(path)));
}