Debian Codegraph @

src/tests/tests.cpp

raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 #include "tests.h"
4 #include "test_utils.h"
5 #include "tests_common.h"
6
7 #include "itemencryptedtests.h"
8 #include "itemfakevimtests.h"
9 #include "itemimagetests.h"
10 #include "itempinnedtests.h"
11 #include "itemsynctests.h"
12 #include "itemtagstests.h"
13 #include "tests_clipboarddataguard.h"
14
15 #include "app/app.h"
16 #include "common/client_server.h"
17 #include "common/config.h"
18 #include "common/log.h"
19 #include "common/process.h"
20 #include "common/settings.h"
21 #include "common/shortcuts.h"
22 #include "common/sleeptimer.h"
23 #include "common/textdata.h"
24 #include "platform/platformclipboard.h"
25 #include "platform/platformnativeinterface.h"
26
27 #include <QDir>
28 #include <QElapsedTimer>
29 #include <QFile>
30 #include <QFileInfo>
31 #include <QGuiApplication>
32 #include <QHash>
33 #include <QLoggingCategory>
34 #include <QMap>
35 #include <QMetaMethod>
36 #include <QProcess>
37 #include <QRegularExpression>
38 #include <QStandardPaths>
39 #include <QTest>
40 #include <QTimer>
41
42 #include <functional>
43 #include <memory>
44 #include <utility>
45
46 namespace {
47
48 Q_DECLARE_LOGGING_CATEGORY(testCategory)
49 Q_LOGGING_CATEGORY(testCategory, "copyq.tests")
50
51 const QString defaultTestId = QStringLiteral("CORE");
52 const QString defaultTestPlugins = QStringLiteral("*itemtext*,*itemnotes*");
53
54 class PerformanceTimer final {
55 public:
56 PerformanceTimer() {
57 m_timer.start();
58 }
59
60 void printPerformance(const char *label, const QStringList &arguments = QStringList()) {
61 const auto elapsedMs = m_timer.elapsed();
62 if (elapsedMs > 500)
63 qCWarning(testCategory) << "--- PERFORMANCE ---" << elapsedMs << "ms:" << label << arguments;
64 m_timer.start();
65 }
66
67 private:
68 QElapsedTimer m_timer;
69 };
70
71 QByteArray decorateOutput(const QByteArray &label, const QByteArray &stderrOutput)
72 {
73 QByteArray output = "\n" + stderrOutput;
74 output.replace('\n', "\n ");
75 output.prepend("\n " + label + ":");
76 return output;
77 }
78
79 QStringList pluginPaths()
80 {
81 QDir dir(QCoreApplication::applicationDirPath() + "/src");
82 const QString pattern = QStringLiteral("*itemtests.*");
83 QStringList files;
84 for (const auto &fileName : dir.entryList({pattern}))
85 files.append( dir.absoluteFilePath(fileName) );
86 if (files.isEmpty()) {
87 qCCritical(testCategory) << "Failed to find the test plugin"
88 << pattern << "in" << dir.absolutePath();
89 }
90 return files;
91 }
92
93 class TestInterfaceImpl final : public TestInterface {
94 public:
95 TestInterfaceImpl()
96 : m_server(nullptr)
97 , m_env(QProcessEnvironment::systemEnvironment())
98 {
99 if ( qEnvironmentVariableIsEmpty("COPYQ_PLUGINS") )
100 m_env.insert("COPYQ_PLUGINS", pluginPaths().join(';'));
101 m_env.insert("COPYQ_LOG_LEVEL", "DEBUG");
102 m_env.insert("COPYQ_SESSION_COLOR", defaultSessionColor);
103 m_env.insert("COPYQ_CLIPBOARD_COPY_TIMEOUT_MS", "2000");
104 m_env.insert("COPYQ_PASSWORD", "TEST123");
105 m_env.insert("COPYQ_QT_FILE_DIALOGS", "1");
106 const auto loggingRules = qgetenv("COPYQ_TESTS_LOGGING_RULES");
107 if ( !loggingRules.isEmpty() ) {
108 m_env.insert("QT_LOGGING_RULES", loggingRules);
109 }
110 }
111
112 ~TestInterfaceImpl()
113 {
114 stopServer();
115 }
116
117 QByteArray startServer() override
118 {
119 m_server.reset(new QProcess);
120 if ( !startTestProcess(m_server.get(), QStringList(), QIODevice::NotOpen) ) {
121 return QString::fromLatin1("Failed to launch \"%1\": %2")
122 .arg(executable())
123 .arg(m_server->errorString())
124 .toUtf8();
125 }
126
127 m_server->closeReadChannel(QProcess::StandardOutput);
128
129 RETURN_ON_ERROR( readServerErrors(), "Failed to start server" );
130
131 return waitForServerToStart();
132 }
133
134 QByteArray stopServer() override
135 {
136 if ( !isServerRunning() )
137 return "Server is not running";
138
139 QByteArray errors;
140 const int exitCode = run(Args("exit"), nullptr, &errors);
141 if ( !testStderr(errors) || exitCode != 0 ) {
142 return "Command 'exit' failed."
143 + printClienAndServerStderr(errors, exitCode);
144 }
145
146 return waitForServerToStop();
147 }
148
149 QByteArray waitForServerToStop() override
150 {
151 PerformanceTimer perf;
152
153 // Process events in case we own clipboard and the new process requests the contents.
154 SleepTimer t(30000);
155 while ( m_server->state() != QProcess::NotRunning && !m_server->waitForFinished(50) && t.sleep() ) {}
156
157 perf.printPerformance("stopServer");
158
159 if ( m_server->state() != QProcess::NotRunning ) {
160 qCWarning(testCategory) << "terminating server process";
161 m_server->terminate();
162
163 if ( !m_server->waitForFinished() ) {
164 qCWarning(testCategory) << "killing server process";
165 terminateProcess(m_server.get());
166 }
167
168 return "Failed to close server properly!" + readServerErrors(ReadAllStderr);
169 }
170
171 return readServerErrors();
172 }
173
174 bool isServerRunning() override
175 {
176 return m_server != nullptr && m_server->state() == QProcess::Running;
177 }
178
179 QString executable() override
180 {
181 const QByteArray executable = qgetenv("COPYQ_TESTS_EXECUTABLE");
182 if ( !executable.isEmpty() )
183 return QString::fromUtf8(executable);
184
185 QDir dir(QCoreApplication::applicationDirPath());
186 return dir.absoluteFilePath("copyq");
187 }
188
189 int run(const QStringList &arguments, QByteArray *stdoutData = nullptr,
190 QByteArray *stderrData = nullptr, const QByteArray &in = QByteArray(),
191 const QStringList &environment = QStringList()) override
192 {
193 if (stdoutData != nullptr)
194 stdoutData->clear();
195
196 if (stderrData != nullptr)
197 stderrData->clear();
198
199 QProcess p;
200 if (!startTestProcess(&p, arguments, QIODevice::ReadWrite, environment))
201 return -1;
202
203 if ( p.write(in) != in.size() )
204 return -2;
205
206 p.closeWriteChannel();
207
208 if (stdoutData == nullptr)
209 p.closeReadChannel(QProcess::StandardOutput);
210
211 if (stderrData == nullptr)
212 p.closeReadChannel(QProcess::StandardError);
213
214 PerformanceTimer perf;
215
216 SleepTimer t(waitClientRun);
217 while ( p.state() == QProcess::Running ) {
218 if ( stdoutData != nullptr ) {
219 const auto out = p.readAllStandardOutput();
220 stdoutData->append(out);
221 }
222
223 if (stderrData != nullptr) {
224 const auto err = p.readAllStandardError();
225 stderrData->append(err);
226 }
227
228 if ( !t.sleep() ) {
229 qCWarning(testCategory) << "Client process timed out" << arguments;
230 return -1;
231 }
232 }
233
234 if (stderrData != nullptr) {
235 stderrData->append(p.readAllStandardError());
236 stderrData->replace('\r', "");
237 }
238
239 if (stdoutData != nullptr) {
240 stdoutData->append(p.readAllStandardOutput());
241 stdoutData->replace('\r', "");
242 }
243
244 perf.printPerformance("run", arguments);
245
246 return p.exitCode();
247 }
248
249 QByteArray printClienAndServerStderr(const QByteArray &clientStderr, int exitCode)
250 {
251 return "\n Client exit code: " + QByteArray::number(exitCode) + "\n"
252 + decorateOutput("Client STDERR", clientStderr)
253 + readServerErrors(ReadAllStderr);
254 }
255
256 QByteArray runClient(const QStringList &arguments, const QByteArray &stdoutExpected,
257 const QByteArray &input = QByteArray()) override
258 {
259 if (!isServerRunning() )
260 return "Server is not running!" + readServerErrors(ReadAllStderr);
261
262 QByteArray stdoutActual;
263 QByteArray stderrActual;
264 const int exitCode = run(arguments, &stdoutActual, &stderrActual, input);
265
266 if ( !testStderr(stderrActual) || exitCode != 0 )
267 return printClienAndServerStderr(stderrActual, exitCode);
268
269 if (stdoutActual != stdoutExpected) {
270 return "Test failed:"
271 + decorateOutput("Unexpected output", stdoutActual)
272 + decorateOutput("Expected output", stdoutExpected)
273 + printClienAndServerStderr(stderrActual, exitCode);
274 }
275
276 return readServerErrors();
277 }
278
279 QByteArray runClientWithError(const QStringList &arguments, int expectedExitCode,
280 const QByteArray &stderrContains = QByteArray()) override
281 {
282 Q_ASSERT(expectedExitCode != 0);
283
284 if ( !isServerRunning() )
285 return "Server is not running!" + readServerErrors(ReadAllStderr);
286
287 QByteArray stdoutActual;
288 QByteArray stderrActual;
289 const int exitCode = run(arguments, &stdoutActual, &stderrActual);
290
291 if ( !testStderr(stderrActual) )
292 return printClienAndServerStderr(stderrActual, exitCode);
293
294 if ( !stdoutActual.isEmpty() ) {
295 return "Test failed: Expected empty output."
296 + decorateOutput("Unexpected output", stdoutActual)
297 + printClienAndServerStderr(stderrActual, exitCode);
298 }
299
300 if (exitCode != expectedExitCode) {
301 return QString::fromLatin1("Test failed: Unexpected exit code %1; expected was %2")
302 .arg(exitCode)
303 .arg(expectedExitCode)
304 .toUtf8()
305 + printClienAndServerStderr(stderrActual, exitCode);
306 }
307
308 if ( !stderrActual.contains(stderrContains) ) {
309 return QString::fromLatin1("Test failed: Expected error output on client side with \"%1\".")
310 .arg(QString::fromUtf8(stderrContains)).toUtf8()
311 + printClienAndServerStderr(stderrActual, exitCode);
312 }
313
314 return readServerErrors();
315 }
316
317 QByteArray getClipboard(const QString &mime = QString("text/plain"), ClipboardMode mode = ClipboardMode::Clipboard)
318 {
319 const QString command =
320 mode == ClipboardMode::Clipboard
321 ? QStringLiteral("clipboard")
322 : QStringLiteral("selection");
323 QByteArray stdoutActual;
324 QByteArray stderrActual;
325 const int exitCode = run(Args() << command << mime, &stdoutActual, &stderrActual);
326 if ( !testStderr(stderrActual) || exitCode != 0 )
327 return "Failed to get clipboard: " + printClienAndServerStderr(stderrActual, exitCode);
328 return stdoutActual;
329 }
330
331 QByteArray setClipboard(const QVariantMap &data, ClipboardMode mode) override
332 {
333 if ( !data.isEmpty() ) {
334 // Wait for clipboard monitor
335 QByteArray error;
336 SleepTimer t(8000);
337 do {
338 error = runClient(
339 Args("monitoring() == isClipboardMonitorRunning()"),
340 QByteArrayLiteral("true\n"));
341 } while (!error.isEmpty() && t.sleep());
342
343 if (!error.isEmpty())
344 return "Clipboard monitor is not running:" + error;
345 }
346
347 clipboard()->setData(mode, data);
348 return {};
349 }
350
351 QByteArray setClipboard(const QByteArray &bytes, const QString &mime, ClipboardMode mode) override
352 {
353 if ( const QByteArray error = setClipboard(createDataMap(mime, bytes), mode);
354 !error.isEmpty() )
355 {
356 return error;
357 }
358
359 return verifyClipboard(bytes, mime);
360 }
361
362 QByteArray verifyClipboard(const QByteArray &data, const QString &mime, bool exact = true) override
363 {
364 // Due to image conversions in clipboard check only if PNG header is present.
365 if ( exact && mime.startsWith(QStringLiteral("image/")) )
366 return verifyClipboard("PNG", QStringLiteral("image/png"), false);
367
368 PerformanceTimer perf;
369
370 SleepTimer t(5000);
371 QByteArray actualBytes;
372 do {
373 actualBytes = getClipboard(mime);
374 if ( exact ? actualBytes == data : actualBytes.contains(data) ) {
375 perf.printPerformance("verifyClipboard", QStringList() << QString::fromUtf8(data) << mime);
376 waitFor(waitMsSetClipboard);
377 RETURN_ON_ERROR( readServerErrors(), "Failed to set or test clipboard content" );
378 return QByteArray();
379 }
380 } while (t.sleep());
381
382 return QString::fromLatin1("Unexpected clipboard data for MIME \"%1\":")
383 .arg(mime).toUtf8()
384 + decorateOutput("Unexpected content", actualBytes)
385 + decorateOutput("Expected content", data)
386 + readServerErrors(ReadAllStderr);
387 }
388
389 QByteArray readServerErrors(ReadStderrFlag flag = ReadErrors) override
390 {
391 if (m_server) {
392 QCoreApplication::processEvents();
393 QByteArray output = readLogFile(maxReadLogSize);
394 if ( flag == ReadAllStderr || !testStderr(output) )
395 return decorateOutput("Server STDERR", output);
396 }
397
398 return QByteArray();
399 }
400
401 QByteArray getClientOutput(const QStringList &arguments, QByteArray *stdoutActual) override
402 {
403 stdoutActual->clear();
404
405 QByteArray stderrActual;
406 int exitCode = run(arguments, stdoutActual, &stderrActual);
407 if ( !testStderr(stderrActual) || exitCode != 0 )
408 return printClienAndServerStderr(stderrActual, exitCode);
409
410 RETURN_ON_ERROR( readServerErrors(), "Failed getting client output" );
411
412 return "";
413 }
414
415 QByteArray waitOnOutput(const QStringList &arguments, const QByteArray &stdoutExpected) override
416 {
417 PerformanceTimer perf;
418 QByteArray stdoutActual;
419
420 SleepTimer t_(8000);
421 do {
422 RETURN_ON_ERROR( getClientOutput(arguments, &stdoutActual), "Failed to wait on client output" );
423 } while (stdoutActual != stdoutExpected && t_.sleep());
424
425 if (stdoutActual == stdoutExpected)
426 return QByteArray();
427
428 return QString::fromLatin1("Unexpected output for command \"%1\":")
429 .arg(arguments.join(' ')).toUtf8()
430 + decorateOutput("Unexpected content", stdoutActual)
431 + decorateOutput("Expected content", stdoutExpected)
432 + readServerErrors(ReadAllStderr);
433 }
434
435 QByteArray cleanupTestCase() override
436 {
437 return cleanup();
438 }
439
440 QByteArray initTestCase() override
441 {
442 return QByteArray();
443 }
444
445 QByteArray init() override
446 {
447 RETURN_ON_ERROR( cleanup(), "Failed to cleanup" );
448
449 // Stop any old server session
450 const QByteArray errors = stopServer();
451 run({"exit"}, nullptr, nullptr, {}, {"COPYQ_WAIT_FOR_SERVER_MS=0"});
452 if ( isServerRunning() )
453 return "Failed to stop an old server session: " + errors;
454 if ( run({""}, nullptr, nullptr, {}, {"COPYQ_WAIT_FOR_SERVER_MS=0"}) == 0 )
455 return "Failed to stop a detached server session: " + errors;
456
457 m_envBeforeTest = m_env;
458
459 // Remove all configuration files and tab data.
460 const auto settingsPaths = {
461 settingsDirectoryPath(),
462 qEnvironmentVariable("COPYQ_SETTINGS_PATH")
463 };
464 for ( const auto &settingsPath : settingsPaths ) {
465 Q_ASSERT( !settingsPath.isEmpty() );
466 QDir settingsDir(settingsPath);
467 const QStringList settingsFileFilters(QStringLiteral("copyq*"));
468 // Omit using dangerous QDir::removeRecursively().
469 for ( const auto &fileName : settingsDir.entryList(settingsFileFilters, QDir::Files) ) {
470 const auto path = settingsDir.absoluteFilePath(fileName);
471 QFile settingsFile(path);
472 if ( settingsFile.exists() && !settingsFile.remove() ) {
473 #ifdef Q_OS_WIN
474 // On Windows, a monitor subprocess may briefly hold
475 // a lock file after the server exits.
476 SleepTimer t(5000);
477 while ( !settingsFile.remove() && t.sleep() ) {}
478 if ( settingsFile.exists() )
479 #endif
480 return QString::fromLatin1("Failed to remove settings file \"%1\": %2")
481 .arg(path, settingsFile.errorString())
482 .toUtf8();
483 }
484 }
485 }
486
487 // Update settings for tests.
488 {
489 Settings settings;
490 settings.clear();
491
492 settings.beginGroup("Options");
493 settings.setValue( QStringLiteral("language"), QStringLiteral("en") );
494 settings.setValue( "clipboard_tab", clipboardTabName );
495 settings.setValue( "close_on_unfocus", false );
496 // Hide the main window even if there is no tray or minimize support.
497 settings.setValue( "hide_main_window", true );
498 // Exercise limiting rows in Process Manager dialog when testing.
499 settings.setValue( "max_process_manager_rows", 4 );
500 // Avoid using external key store.
501 settings.setValue( "use_key_store", false );
502 settings.endGroup();
503
504 if ( !m_settings.isEmpty() ) {
505 const bool pluginsTest = m_testId != defaultTestId;
506
507 if (pluginsTest) {
508 settings.beginGroup("Plugins");
509 settings.beginGroup(m_testId);
510 }
511
512 for (auto it = m_settings.constBegin(); it != m_settings.constEnd(); ++it)
513 settings.setValue( it.key(), it.value() );
514
515 if (pluginsTest) {
516 settings.endGroup();
517 settings.endGroup();
518 }
519 }
520 }
521
522 verifyConfiguration();
523
524 // Clear clipboard.
525 RETURN_ON_ERROR( setClipboard({}, ClipboardMode::Clipboard), "Failed to reset clipboard" );
526 #ifdef HAS_MOUSE_SELECTIONS
527 RETURN_ON_ERROR( setClipboard({}, ClipboardMode::Selection), "Failed to reset selection" );
528 #endif
529
530 if ( !dropLogsToFileCountAndSize(0, 0) )
531 return "Failed to remove log files";
532
533 RETURN_ON_ERROR( startServer(), "Failed to initialize server" );
534
535 // Always show main window first so that the results are consistent with desktop environments
536 // where user cannot hide main window (tiling window managers without tray).
537 RETURN_ON_ERROR( runClient(Args("show"), ""), "Failed to show main window" );
538
539 return QByteArray();
540 }
541
542 QByteArray cleanup() override
543 {
544 m_env = m_envBeforeTest;
545 const QByteArray errors = isServerRunning() ? stopServer() : QByteArray();
546 m_ignoreErrors = {};
547
548 return errors;
549 }
550
551 QString shortcutToRemove() override
552 {
553 return ::shortcutToRemove();
554 }
555
556 void setEnv(const QString &name, const QString &value) override
557 {
558 m_env.insert(name, value);
559 }
560
561 void ignoreErrors(const QRegularExpression &re) override
562 {
563 m_ignoreErrors = re;
564 }
565
566 bool writeOutErrors(const QByteArray &errors) override
567 {
568 if (errors.isEmpty())
569 return false;
570
571 QFile ferr;
572 if ( ferr.open(stderr, QIODevice::WriteOnly) ) {
573 ferr.write(errors);
574 ferr.write("\n");
575 ferr.close();
576 }
577 return true;
578 }
579
580 void setupTest(const QString &id, const QString &allowPlugins, const QVariant &settings)
581 {
582 m_testId = id;
583 m_settings = settings.toMap();
584 m_env.insert("COPYQ_ALLOW_PLUGINS", "*itemtests*,*" + allowPlugins + "*");
585 m_envBeforeTest = m_env;
586 }
587 private:
588 bool testStderr(const QByteArray &stderrData)
589 {
590 return ::testStderr(stderrData, m_ignoreErrors);
591 }
592
593 void verifyConfiguration()
594 {
595 Settings settings;
596 settings.beginGroup("Options");
597 QCOMPARE( settings.value(QStringLiteral("close_on_unfocus")), false );
598 QCOMPARE( settings.value(QStringLiteral("clipboard_tab")), QString(clipboardTabName) );
599 QCOMPARE( settings.value(QStringLiteral("tabs")).toStringList(), QStringList() );
600 }
601
602 bool startClient(QProcess *p, const QStringList &arguments) override
603 {
604 return startTestProcess(p, arguments);
605 }
606
607 bool startTestProcess(QProcess *p, const QStringList &arguments,
608 QIODevice::OpenMode mode = QIODevice::ReadWrite,
609 const QStringList &environment = QStringList())
610 {
611 if ( environment.isEmpty() ) {
612 p->setProcessEnvironment(m_env);
613 } else {
614 auto env = m_env;
615 for (const QString &nameValue : environment) {
616 const auto i = nameValue.indexOf(QLatin1Char('='));
617 Q_ASSERT(i != -1);
618 const auto name = nameValue.left(i);
619 const auto value = nameValue.mid(i+1);
620 env.insert(name, value);
621 }
622 p->setProcessEnvironment(env);
623 }
624
625 p->start( executable(), arguments, mode );
626 return p->waitForStarted(2000);
627 }
628
629 QByteArray waitForServerToStart()
630 {
631 SleepTimer t(15000);
632 do {
633 if ( run(Args() << "") == 0 )
634 return QByteArray();
635 } while ( t.sleep() );
636
637 return "Unable to start server!" + readServerErrors(ReadAllStderr);
638 }
639
640 PlatformClipboard *clipboard()
641 {
642 if (m_clipboard == nullptr)
643 m_clipboard = platformNativeInterface()->clipboard();
644 return m_clipboard.get();
645 }
646
647 std::unique_ptr<QProcess> m_server;
648 QProcessEnvironment m_env;
649 QProcessEnvironment m_envBeforeTest;
650 QString m_testId;
651 QVariantMap m_settings;
652 QRegularExpression m_ignoreErrors;
653
654 PlatformClipboardPtr m_clipboard;
655 };
656
657 } // namespace
658
659 CoreTests::CoreTests(const TestInterfacePtr &test, QObject *parent)
660 : QObject(parent)
661 , m_test(test)
662 {
663 setProperty("CopyQ_test_id", defaultTestId);
664 setProperty("CopyQ_allow_plugins", defaultTestPlugins);
665 }
666
667 void CoreTests::initTestCase()
668 {
669 TEST(m_test->initTestCase());
670 }
671
672 void CoreTests::cleanupTestCase()
673 {
674 TEST(m_test->cleanupTestCase());
675 }
676
677 void CoreTests::init()
678 {
679 TEST(m_test->init());
680 }
681
682 void CoreTests::cleanup()
683 {
684 TEST( m_test->cleanup() );
685 }
686
687 int CoreTests::run(
688 const QStringList &arguments, QByteArray *stdoutData, QByteArray *stderrData, const QByteArray &in,
689 const QStringList &environment)
690 {
691 return m_test->run(arguments, stdoutData, stderrData, in, environment);
692 }
693
694 bool CoreTests::hasTab(const QString &tabName)
695 {
696 QByteArray out;
697 run(Args("tab"), &out);
698 return splitLines(out).contains(tabName);
699 }
700
701 #define IMPL_TEST_GROUP(Name) \
702 QObject *m_group##Name = addTestGroup<Name##Tests>("test" #Name); \
703 Q_SLOT void test##Name##_data() { populateTestRows(m_group##Name, "test" #Name); } \
704 Q_SLOT void test##Name() { dispatchCurrentTest(); }
705
706 class Tests : public QObject {
707 Q_OBJECT
708 public:
709 explicit Tests(
710 std::shared_ptr<TestInterfaceImpl> test,
711 const QString &filter = {},
712 QObject *parent = nullptr)
713 : QObject(parent)
714 , m_test(std::move(test))
715 , m_filter(filter) {}
716
717 QStringList m_failed;
718
719 private:
720 std::shared_ptr<TestInterfaceImpl> m_test;
721 QRegularExpression m_filter;
722 QHash<QByteArray, QObject*> m_groups;
723 QObject *m_activeGroup = nullptr;
724
725 template <typename TestClass>
726 QObject *addTestGroup(const char *groupName)
727 {
728 QObject *group = new TestClass(m_test, this);
729 m_groups.insert(groupName, group);
730 return group;
731 }
732
733 static int findMethod(const QMetaObject *meta, const char *name)
734 {
735 for (int i = meta->methodOffset(); i < meta->methodCount(); ++i) {
736 if (meta->method(i).name() == name)
737 return i;
738 }
739 return -1;
740 }
741
742 static void invokeMethod(QObject *obj, const char *name)
743 {
744 if (!obj)
745 return;
746 const int idx = findMethod(obj->metaObject(), name);
747 if (idx >= 0)
748 obj->metaObject()->method(idx).invoke(obj, Qt::DirectConnection);
749 }
750
751 static bool isLifecycleSlot(const QByteArray &name)
752 {
753 return name == "initTestCase" || name == "cleanupTestCase"
754 || name == "init" || name == "cleanup";
755 }
756
757 static bool isTestSlot(const QMetaMethod &method, const QByteArray &name)
758 {
759 return method.access() == QMetaMethod::Private
760 && method.methodType() == QMetaMethod::Slot
761 && method.parameterCount() == 0
762 && !isLifecycleSlot(name)
763 && !name.endsWith("_data");
764 }
765
766 QObject *currentGroup()
767 {
768 const auto it = m_groups.find(QTest::currentTestFunction());
769 return it == m_groups.end() ? nullptr : it.value();
770 }
771
772 void activateGroup(QObject *group)
773 {
774 m_activeGroup = group;
775 const auto id = group->property("CopyQ_test_id").toString();
776 const auto allowPlugins = group->property("CopyQ_allow_plugins");
777 const QString plugins = allowPlugins.isValid() ? allowPlugins.toString() : id;
778 const auto settings = group->property("CopyQ_test_settings");
779 m_test->setupTest(id, plugins, settings.isValid() ? settings : QVariant());
780 }
781
782 void populateTestRows(QObject *group, const char *groupName)
783 {
784 const QMetaObject *meta = group->metaObject();
785
786 QTest::addColumn<int>("methodIndex");
787
788 for (int i = meta->methodOffset(); i < meta->methodCount(); ++i) {
789 const QMetaMethod method = meta->method(i);
790 const QByteArray name = method.name();
791 if (!isTestSlot(method, name))
792 continue;
793
794 if (m_filter.isValid() && !m_filter.pattern().isEmpty()) {
795 const QString fullName = QStringLiteral("%1:%2").arg(groupName, name);
796 if (!m_filter.match(fullName).hasMatch())
797 continue;
798 }
799
800 QTest::newRow(name.constData()) << i;
801 }
802 }
803
804 void dispatchCurrentTest()
805 {
806 if (!QTest::currentDataTag()) {
807 QSKIP("No matching tests in this group");
808 return;
809 }
810
811 QFETCH(int, methodIndex);
812
813 QObject *group = currentGroup();
814 Q_ASSERT(group);
815 group->metaObject()->method(methodIndex).invoke(group, Qt::DirectConnection);
816 }
817
818 Q_SLOT void initTestCase() {}
819
820 Q_SLOT void cleanupTestCase()
821 {
822 invokeMethod(m_activeGroup, "cleanupTestCase");
823 }
824
825 Q_SLOT void init()
826 {
827 QObject *group = currentGroup();
828 if (group != m_activeGroup) {
829 invokeMethod(m_activeGroup, "cleanupTestCase");
830 activateGroup(group);
831 invokeMethod(m_activeGroup, "initTestCase");
832 }
833 invokeMethod(m_activeGroup, "init");
834 }
835
836 Q_SLOT void cleanup() {
837 invokeMethod(currentGroup(), "cleanup");
838 if (QTest::currentTestFailed()) {
839 const QString tag = QString::fromUtf8(QTest::currentDataTag());
840 const QString fn = QString::fromUtf8(QTest::currentTestFunction());
841 m_failed.append(QStringLiteral("%1:%2").arg(fn, tag));
842 }
843 }
844
845 IMPL_TEST_GROUP(Core)
846 IMPL_TEST_GROUP(ClipboardDataGuard)
847 IMPL_TEST_GROUP(ItemEncrypted)
848 IMPL_TEST_GROUP(ItemFakeVim)
849 IMPL_TEST_GROUP(ItemImage)
850 IMPL_TEST_GROUP(ItemPinned)
851 IMPL_TEST_GROUP(ItemSync)
852 IMPL_TEST_GROUP(ItemTags)
853 };
854
855 int main(int argc, char **argv)
856 {
857 // Avoid verbose logs on stderr if tests are not failing
858 qunsetenv("COPYQ_LOG_LEVEL");
859
860 const QString appName = QStringLiteral("copyq.test");
861 QCoreApplication::setOrganizationName(appName);
862 QCoreApplication::setApplicationName(appName);
863 const auto configPath = QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
864 qCInfo(testCategory) << "Using config directory for tests:" << configPath;
865 QDir configDir(configPath);
866 qputenv("COPYQ_SETTINGS_PATH", configPath.toLocal8Bit());
867 qputenv("COPYQ_LOG_FILE", configDir.absoluteFilePath(QStringLiteral("tests.log")).toLocal8Bit());
868 qputenv("COPYQ_ITEM_DATA_PATH", configDir.absoluteFilePath(QStringLiteral("items")).toLocal8Bit());
869
870 setSessionName(sessionName);
871 const auto platform = platformNativeInterface();
872 std::unique_ptr<QGuiApplication> app( platform->createTestApplication(argc, argv) );
873 initSession(app.get(), sessionName);
874
875 // Set higher default tests timeout.
876 // The default value is 5 minutes (in Qt 5.15) which is not enough to run
877 // all tests in Tests class on some systems.
878 bool ok;
879 const int timeout = qEnvironmentVariableIntValue("QTEST_FUNCTION_TIMEOUT", &ok);
880 if (!ok || timeout <= 0)
881 qputenv("QTEST_FUNCTION_TIMEOUT", QByteArray::number(15 * 60 * 1000));
882
883 auto test = std::make_shared<TestInterfaceImpl>();
884 Tests aggregator(test, qEnvironmentVariable("COPYQ_TESTS_FILTER"));
885 int exitCode = QTest::qExec(&aggregator, argc, argv);
886
887 const int maxReruns = qEnvironmentVariableIntValue("COPYQ_TESTS_RERUN_FAILED", &ok);
888 for (int run = 0; exitCode != 0 && !aggregator.m_failed.isEmpty() && run < maxReruns; ++run) {
889 qInfo() << QString::fromLatin1("Rerunning %1 failed tests (%2/%3): %4")
890 .arg(aggregator.m_failed.size())
891 .arg(run + 1)
892 .arg(maxReruns)
893 .arg(aggregator.m_failed.join(", "));
894 QStringList args = aggregator.m_failed;
895 aggregator.m_failed.clear();
896 args.prepend(QString::fromUtf8(argv[0]));
897 exitCode = QTest::qExec(&aggregator, args);
898 }
899
900 return exitCode;
901 }
902
903 #include "tests.moc"