-
Notifications
You must be signed in to change notification settings - Fork 426
/
tests.cpp
4560 lines (3737 loc) · 147 KB
/
tests.cpp
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
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: GPL-3.0-or-later
#include "tests.h"
#include "test_utils.h"
#include "common/action.h"
#include "common/appconfig.h"
#include "common/client_server.h"
#include "common/common.h"
#include "common/config.h"
#include "common/log.h"
#include "common/mimetypes.h"
#include "common/settings.h"
#include "common/shortcuts.h"
#include "common/sleeptimer.h"
#include "common/textdata.h"
#include "common/version.h"
#include "item/itemfactory.h"
#include "item/itemwidget.h"
#include "item/serialize.h"
#include "gui/tabicons.h"
#include "platform/platformclipboard.h"
#include "platform/platformnativeinterface.h"
#include <QDebug>
#include <QDir>
#include <QElapsedTimer>
#include <QFile>
#include <QFileInfo>
#include <QGuiApplication>
#include <QMap>
#include <QMimeData>
#include <QProcess>
#include <QRegularExpression>
#include <QTemporaryDir>
#include <QTemporaryFile>
#include <QTest>
#include <QTimer>
#include <memory>
#define WITH_TIMEOUT "afterMilliseconds(10000, fail); "
#define KEEP_STDIN_OPEN "KEEP_STDIN_OPEN"
// WORKAROUND: Checking clipboard right after closing menu gets stuck on OS X.
#define ACTIVATE_MENU_ITEM(MENU_ID, WIDGET_ID, CONTENT) \
RUN("keys" << MENU_ID << "ENTER", ""); \
RUN("keys" << WIDGET_ID, ""); \
WAIT_FOR_CLIPBOARD(CONTENT)
namespace {
const int maxReadLogSize = 1 * 1024 * 1024;
const auto clipboardTabName = "CLIPBOARD";
const auto defaultSessionColor = "#ff8800";
const auto defaultTagColor = "#000000";
const auto clipboardBrowserId = "focus:ClipboardBrowser";
const auto clipboardBrowserRefreshButtonId = "focus:ClipboardBrowserRefreshButton";
const auto filterEditId = "focus:Utils::FilterLineEdit";
const auto trayMenuId = "focus:TrayMenu";
const auto menuId = "focus:Menu";
const auto customMenuId = "focus:CustomMenu";
const auto editorId = "focus::ItemEditorWidget";
const auto tabDialogLineEditId = "focus:lineEditTabName";
const auto commandDialogId = "focus:CommandDialog";
const auto commandDialogSaveButtonId = "focus::QPushButton in :QMessageBox";
const auto commandDialogListId = "focus:listWidgetItems";
const auto configurationDialogId = "focus:ConfigurationManager";
const auto shortcutButtonId = "focus::QToolButton in CommandDialog";
const auto shortcutDialogId = "focus::QKeySequenceEdit in ShortcutDialog";
const auto actionDialogId = "focus:ActionDialog";
const auto aboutDialogId = "focus:AboutDialog";
const auto logDialogId = "focus:LogDialog";
const auto actionHandlerDialogId = "focus:ActionHandlerDialog";
const auto actionHandlerFilterId = "focus:filterLineEdit";
const auto actionHandlerTableId = "focus:tableView";
const auto clipboardDialogId = "focus:ClipboardDialog";
const auto clipboardDialogFormatListId = "focus:listWidgetFormats";
const auto confirmExitDialogId = "focus::QPushButton in :QMessageBox";
const auto itemPreviewId = "focus:in dockWidgetItemPreviewContents";
class PerformanceTimer final {
public:
PerformanceTimer() {
m_timer.start();
}
void printPerformance(const char *label, const QStringList &arguments = QStringList()) {
const auto elapsedMs = m_timer.elapsed();
if (elapsedMs > 500)
qWarning() << "--- PERFORMANCE ---" << elapsedMs << "ms:" << label << arguments;
m_timer.start();
}
private:
QElapsedTimer m_timer;
};
// Similar to QTemporaryFile but allows removing from other process.
class TemporaryFile {
public:
TemporaryFile()
{
QTemporaryFile tmp;
tmp.setAutoRemove(false);
QVERIFY(tmp.open());
m_fileName = tmp.fileName();
tmp.close();
}
~TemporaryFile()
{
QFile::remove(m_fileName);
}
QString fileName() const
{
return m_fileName;
}
private:
QString m_fileName;
};
template <typename Fn1, typename Fn2>
void runMultiple(Fn1 f1, Fn2 f2)
{
QTimer timer;
timer.setSingleShot(true);
timer.setInterval(0);
QObject::connect(&timer, &QTimer::timeout, f2);
timer.start();
f1();
}
bool testStderr(const QByteArray &stderrData, TestInterface::ReadStderrFlag flag = TestInterface::ReadErrors)
{
static const QRegularExpression reFailure("(Warning:|ERROR:|ASSERT|ScriptError:).*", QRegularExpression::CaseInsensitiveOption);
const QLatin1String scriptError("ScriptError:");
const auto plain = [](const char *str){
return QRegularExpression(QRegularExpression::escape(QLatin1String(str)));
};
const auto regex = [](const char *str){
return QRegularExpression(QLatin1String(str));
};
// Ignore exceptions and errors from clients in application log
// (these are expected in some tests).
static const std::vector<QRegularExpression> ignoreList{
regex(R"(CopyQ Note \[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}\] <Client-[^\n]*)"),
// X11 (Linux)
plain("QtWarning: QXcbXSettings::QXcbXSettings(QXcbScreen*) Failed to get selection owner for XSETTINGS_S atom"),
plain("QtWarning: QXcbConnection: XCB error:"),
plain("QtWarning: QXcbClipboard: SelectionRequest too old"),
plain("QtWarning: libpng warning: iCCP: known incorrect sRGB profile"),
plain("QtWarning: QMime::convertToMime: unhandled mimetype: text/plain"),
// Wayland (Linux)
plain("QtWarning: Wayland does not support QWindow::requestActivate()"),
plain("QtWarning: Unexpected wl_keyboard.enter event"),
plain("QtWarning: The compositor sent a wl_pointer.enter"),
// Windows
plain("QtWarning: QWindowsWindow::setGeometry: Unable to set geometry"),
plain("QtWarning: QWinEventNotifier: no event dispatcher, application shutting down? Cannot deliver event."),
plain("QtWarning: setGeometry: Unable to set geometry"),
plain("ERROR: QtCritical: QWindowsPipeWriter::write failed. (The pipe is being closed.)"),
plain("ERROR: QtCritical: QWindowsPipeWriter: asynchronous write failed. (The pipe has been ended.)"),
plain("[kf.notifications] QtWarning: Received a response for an unknown notification."),
// KStatusNotifierItem
plain("[kf.windowsystem] QtWarning: Could not find any platform plugin"),
regex("QtWarning: QTemporaryDir: Unable to remove .* most likely due to the presence of read-only files."),
// Windows Qt 5.15.2
plain("[qt.qpa.mime] QtWarning: Retrying to obtain clipboard."),
plain("[default] QtWarning: QSystemTrayIcon::setVisible: No Icon set"),
// macOS
plain("QtWarning: Failed to get QCocoaScreen for NSObject(0x0)"),
plain("ERROR: Failed to open session mutex: QSystemSemaphore::handle:: ftok failed"),
regex(R"(QtWarning: Window position.* outside any known screen.*)"),
regex(R"(QtWarning: Populating font family aliases took .* ms. Replace uses of missing font family "Font Awesome.*" with one that exists to avoid this cost.)"),
// New in Qt 5.15.0
regex(R"(QtWarning: Populating font family aliases took .* ms. Replace uses of missing font family "Monospace" with one that exists to avoid this cost.)"),
// New in Qt 6.5
regex("QtWarning: Error in contacting registry"),
// KNotification bug
plain(R"(QtWarning: QLayout: Attempting to add QLayout "" to QWidget "", which already has a layout)"),
};
static QHash<QString, bool> ignoreLog;
const QString output = QString::fromUtf8(stderrData);
QRegularExpressionMatchIterator it = reFailure.globalMatch(output);
while ( it.hasNext() ) {
const auto match = it.next();
const QString log = match.captured();
if ( flag == TestInterface::ReadErrorsWithoutScriptException
&& log.contains(scriptError) )
{
return false;
}
if ( ignoreLog.contains(log) )
return ignoreLog[log];
qDebug() << "Failure in logs:" << log;
const bool ignore = std::any_of(
std::begin(ignoreList), std::end(ignoreList),
[&output](const QRegularExpression &reIgnore){
return output.contains(reIgnore);
});
ignoreLog[log] = ignore;
if (!ignore)
return false;
}
return true;
}
bool waitWhileFileExists(const QFile &file)
{
SleepTimer t(2000);
while (file.exists() && t.sleep()) {}
return !file.exists();
}
/// Generate unique data.
QByteArray generateData()
{
static int i = 0;
const QByteArray id = "tests_"
+ QByteArray::number(QDateTime::currentMSecsSinceEpoch() % 1000);
return id + '_' + QByteArray::number(++i);
}
QByteArray decorateOutput(const QByteArray &label, const QByteArray &stderrOutput)
{
QByteArray output = "\n" + stderrOutput;
output.replace('\n', "\n ");
output.prepend("\n " + label + ":");
return output;
}
class TestInterfaceImpl final : public TestInterface {
public:
TestInterfaceImpl()
: m_server(nullptr)
, m_env(QProcessEnvironment::systemEnvironment())
{
m_env.insert("COPYQ_LOG_LEVEL", "DEBUG");
m_env.insert("COPYQ_SESSION_COLOR", defaultSessionColor);
m_env.insert("COPYQ_SESSION_NAME", "TEST");
}
~TestInterfaceImpl()
{
stopServer();
}
QByteArray startServer() override
{
if ( isServerRunning() )
return "Server is already running.";
if ( !removeLogFiles() )
return "Failed to remove log files";
m_server.reset(new QProcess);
if ( !startTestProcess(m_server.get(), QStringList(), QIODevice::NotOpen) ) {
return QString::fromLatin1("Failed to launch \"%1\": %2")
.arg(QCoreApplication::applicationFilePath())
.arg(m_server->errorString())
.toUtf8();
}
m_server->closeReadChannel(QProcess::StandardOutput);
RETURN_ON_ERROR( readServerErrors(), "Failed to start server" );
return waitForServerToStart();
}
QByteArray stopServer() override
{
if ( !isServerRunning() )
return "Server is not running";
QByteArray errors;
const int exitCode = run(Args("exit"), nullptr, &errors);
if ( !testStderr(errors) || exitCode != 0 ) {
return "Command 'exit' failed."
+ printClienAndServerStderr(errors, exitCode);
}
return waitForServerToStop();
}
QByteArray waitForServerToStop() override
{
PerformanceTimer perf;
// Process events in case we own clipboard and the new process requests the contents.
SleepTimer t(30000);
while ( m_server->state() != QProcess::NotRunning && !m_server->waitForFinished(50) && t.sleep() ) {}
perf.printPerformance("stopServer");
if ( m_server->state() != QProcess::NotRunning ) {
qWarning() << "terminating server process";
m_server->terminate();
if ( !m_server->waitForFinished() ) {
qWarning() << "killing server process";
terminateProcess(m_server.get());
}
return "Failed to close server properly!" + readServerErrors(ReadAllStderr);
}
return readServerErrors();
}
bool isServerRunning() override
{
return m_server != nullptr && m_server->state() == QProcess::Running;
}
int run(const QStringList &arguments, QByteArray *stdoutData = nullptr,
QByteArray *stderrData = nullptr, const QByteArray &in = QByteArray(),
const QStringList &environment = QStringList()) override
{
if (stdoutData != nullptr)
stdoutData->clear();
if (stderrData != nullptr)
stderrData->clear();
QProcess p;
if (!startTestProcess(&p, arguments, QIODevice::ReadWrite, environment))
return -1;
if (in != KEEP_STDIN_OPEN) {
if ( p.write(in) != in.size() )
return -2;
p.closeWriteChannel();
}
if (stdoutData == nullptr)
p.closeReadChannel(QProcess::StandardOutput);
if (stderrData == nullptr)
p.closeReadChannel(QProcess::StandardError);
PerformanceTimer perf;
SleepTimer t(waitClientRun);
while ( p.state() == QProcess::Running ) {
if ( stdoutData != nullptr ) {
const auto out = p.readAllStandardOutput();
stdoutData->append(out);
}
if (stderrData != nullptr) {
const auto err = p.readAllStandardError();
stderrData->append(err);
}
if ( !t.sleep() ) {
qWarning() << "Client process timed out" << arguments;
return -1;
}
}
if (stderrData != nullptr) {
stderrData->append(p.readAllStandardError());
stderrData->replace('\r', "");
}
if (stdoutData != nullptr) {
stdoutData->append(p.readAllStandardOutput());
stdoutData->replace('\r', "");
}
perf.printPerformance("run", arguments);
return p.exitCode();
}
QByteArray printClienAndServerStderr(const QByteArray &clientStderr, int exitCode)
{
return "\n Client exit code: " + QByteArray::number(exitCode) + "\n"
+ decorateOutput("Client STDERR", clientStderr)
+ readServerErrors(ReadAllStderr);
}
QByteArray runClient(const QStringList &arguments, const QByteArray &stdoutExpected,
const QByteArray &input = QByteArray()) override
{
if (!isServerRunning() )
return "Server is not running!" + readServerErrors(ReadAllStderr);
QByteArray stdoutActual;
QByteArray stderrActual;
const int exitCode = run(arguments, &stdoutActual, &stderrActual, input);
if ( !testStderr(stderrActual) || exitCode != 0 )
return printClienAndServerStderr(stderrActual, exitCode);
if (stdoutActual != stdoutExpected) {
return "Test failed:"
+ decorateOutput("Unexpected output", stdoutActual)
+ decorateOutput("Expected output", stdoutExpected)
+ printClienAndServerStderr(stderrActual, exitCode);
}
return readServerErrors();
}
QByteArray runClientWithError(const QStringList &arguments, int expectedExitCode,
const QByteArray &stderrContains = QByteArray()) override
{
Q_ASSERT(expectedExitCode != 0);
if ( !isServerRunning() )
return "Server is not running!" + readServerErrors(ReadAllStderr);
QByteArray stdoutActual;
QByteArray stderrActual;
const int exitCode = run(arguments, &stdoutActual, &stderrActual);
if ( testStderr(stderrActual) ) {
return "Test failed: Expected error output on client side."
+ printClienAndServerStderr(stderrActual, exitCode);
}
if ( !stdoutActual.isEmpty() ) {
return "Test failed: Expected empty output."
+ decorateOutput("Unexpected output", stdoutActual)
+ printClienAndServerStderr(stderrActual, exitCode);
}
if (exitCode != expectedExitCode) {
return QString::fromLatin1("Test failed: Unexpected exit code %1; expected was %2")
.arg(exitCode)
.arg(expectedExitCode)
.toUtf8()
+ printClienAndServerStderr(stderrActual, exitCode);
}
if ( !stderrActual.contains(stderrContains) ) {
return QString::fromLatin1("Test failed: Expected error output on client side with \"%1\".")
.arg(QString::fromUtf8(stderrContains)).toUtf8()
+ printClienAndServerStderr(stderrActual, exitCode);
}
return readServerErrors(ReadErrorsWithoutScriptException);
}
QByteArray getClipboard(const QString &mime = QString("text/plain"), ClipboardMode mode = ClipboardMode::Clipboard)
{
return clipboard()->data(mode, QStringList(mime)).value(mime).toByteArray();
}
QByteArray setClipboard(const QVariantMap &data, ClipboardMode mode) override
{
if ( !data.isEmpty() ) {
// Wait for clipboard monitor
QByteArray error;
SleepTimer t(8000);
do {
error = runClient(
Args("monitoring() == isClipboardMonitorRunning()"),
QByteArrayLiteral("true\n"));
} while (!error.isEmpty() && t.sleep());
if (!error.isEmpty())
return "Clipboard monitor is not running:" + error;
}
clipboard()->setData(mode, data);
return {};
}
QByteArray setClipboard(const QByteArray &bytes, const QString &mime, ClipboardMode mode) override
{
const QByteArray error = setClipboard( createDataMap(mime, bytes), mode );
if (!error.isEmpty())
return error;
return verifyClipboard(bytes, mime);
}
QByteArray verifyClipboard(const QByteArray &data, const QString &mime, bool exact = true) override
{
// Due to image conversions in clipboard check only png.
if ( mime.startsWith(QStringLiteral("image/")) && mime != QStringLiteral("image/png") )
return verifyClipboard("PNG", QStringLiteral("image/png"), false);
PerformanceTimer perf;
SleepTimer t(5000);
QByteArray actualBytes;
do {
actualBytes = getClipboard(mime);
if ( exact ? actualBytes == data : actualBytes.contains(data) ) {
perf.printPerformance("verifyClipboard", QStringList() << QString::fromUtf8(data) << mime);
waitFor(waitMsSetClipboard);
RETURN_ON_ERROR( readServerErrors(), "Failed to set or test clipboard content" );
return QByteArray();
}
} while (t.sleep());
return QString::fromLatin1("Unexpected clipboard data for MIME \"%1\":")
.arg(mime).toUtf8()
+ decorateOutput("Unexpected content", actualBytes)
+ decorateOutput("Expected content", data)
+ readServerErrors(ReadAllStderr);
}
QByteArray readServerErrors(ReadStderrFlag flag = ReadErrors) override
{
if (m_server) {
QCoreApplication::processEvents();
QByteArray output = readLogFile(maxReadLogSize);
if ( flag == ReadAllStderr || !testStderr(output, flag) )
return decorateOutput("Server STDERR", output);
}
return QByteArray();
}
QByteArray getClientOutput(const QStringList &arguments, QByteArray *stdoutActual) override
{
stdoutActual->clear();
QByteArray stderrActual;
int exitCode = run(arguments, stdoutActual, &stderrActual);
if ( !testStderr(stderrActual) || exitCode != 0 )
return printClienAndServerStderr(stderrActual, exitCode);
RETURN_ON_ERROR( readServerErrors(), "Failed getting client output" );
return "";
}
QByteArray waitOnOutput(const QStringList &arguments, const QByteArray &stdoutExpected) override
{
PerformanceTimer perf;
QByteArray stdoutActual;
SleepTimer t_(8000);
do {
RETURN_ON_ERROR( getClientOutput(arguments, &stdoutActual), "Failed to wait on client output" );
} while (stdoutActual != stdoutExpected && t_.sleep());
if (stdoutActual == stdoutExpected)
return QByteArray();
return QString::fromLatin1("Unexpected output for command \"%1\":")
.arg(arguments.join(' ')).toUtf8()
+ decorateOutput("Unexpected content", stdoutActual)
+ decorateOutput("Expected content", stdoutExpected)
+ readServerErrors(ReadAllStderr);
}
QByteArray cleanupTestCase() override
{
return cleanup();
}
QByteArray initTestCase() override
{
return QByteArray();
}
QByteArray init() override
{
RETURN_ON_ERROR( cleanup(), "Failed to cleanup" );
if ( isServerRunning() )
RETURN_ON_ERROR( stopServer(), "Failed to stop server" );
// Remove all configuration files and tab data.
const auto settingsPath = settingsDirectoryPath();
Q_ASSERT( !settingsPath.isEmpty() );
QDir settingsDir(settingsPath);
const QStringList settingsFileFilters("copyq.test*");
// Omit using dangerous QDir::removeRecursively().
for ( const auto &fileName : settingsDir.entryList(settingsFileFilters) ) {
const auto path = settingsDir.absoluteFilePath(fileName);
QFile settingsFile(path);
if ( settingsFile.exists() && !settingsFile.remove() ) {
return QString::fromLatin1("Failed to remove settings file \"%1\": %2")
.arg(settingsPath, settingsFile.errorString())
.toUtf8();
}
}
// Update settings for tests.
{
Settings settings;
settings.clear();
settings.beginGroup("Options");
settings.setValue( Config::clipboard_tab::name(), clipboardTabName );
settings.setValue( Config::close_on_unfocus::name(), false );
// Exercise limiting rows in Process Manager dialog when testing.
settings.setValue( Config::max_process_manager_rows::name(), 4 );
settings.endGroup();
if ( !m_settings.isEmpty() ) {
const bool pluginsTest = m_testId != "CORE";
if (pluginsTest) {
settings.beginGroup("Plugins");
settings.beginGroup(m_testId);
}
for (auto it = m_settings.constBegin(); it != m_settings.constEnd(); ++it)
settings.setValue( it.key(), it.value() );
if (pluginsTest) {
settings.endGroup();
settings.endGroup();
}
}
}
verifyConfiguration();
// Clear clipboard.
RETURN_ON_ERROR( setClipboard({}, ClipboardMode::Clipboard), "Failed to reset clipboard" );
#ifdef HAS_MOUSE_SELECTIONS
RETURN_ON_ERROR( setClipboard({}, ClipboardMode::Selection), "Failed to reset selection" );
#endif
RETURN_ON_ERROR( startServer(), "Failed to initialize server" );
// Always show main window first so that the results are consistent with desktop environments
// where user cannot hide main window (tiling window managers without tray).
RETURN_ON_ERROR( runClient(Args("show"), ""), "Failed to show main window" );
return QByteArray();
}
QByteArray cleanup() override
{
addFailedTest();
return QByteArray();
}
QString shortcutToRemove() override
{
return ::shortcutToRemove();
}
void setEnv(const QString &name, const QString &value) override
{
m_env.insert(name, value);
}
bool writeOutErrors(const QByteArray &errors) override
{
if (errors.isEmpty())
return false;
QFile ferr;
ferr.open(stderr, QIODevice::WriteOnly);
ferr.write(errors);
ferr.write("\n");
ferr.close();
return true;
}
void setupTest(const QString &id, const QVariant &settings)
{
m_testId = id;
m_settings = settings.toMap();
m_env.insert("COPYQ_TEST_ID", id);
}
int runTests(QObject *testObject, int argc = 0, char **argv = nullptr)
{
int exitCode = QTest::qExec(testObject, argc, argv);
const int maxRuns = m_env.value("COPYQ_TESTS_RERUN_FAILED", "0").toInt();
for (int runCounter = 0; exitCode != 0 && !m_failed.isEmpty() && runCounter < maxRuns; ++runCounter) {
qInfo() << QString::fromLatin1("Rerunning %1 failed tests (%2/%3): %4")
.arg(m_failed.size())
.arg(runCounter + 1)
.arg(maxRuns)
.arg(m_failed.join(", "));
QStringList args = m_failed;
m_failed.clear();
args.prepend( QString::fromUtf8(argv[0]) );
exitCode = QTest::qExec(testObject, args);
}
m_failed.clear();
return exitCode;
}
private:
void addFailedTest()
{
if ( QTest::currentTestFailed() )
m_failed.append( QString::fromUtf8(QTest::currentTestFunction()) );
}
void verifyConfiguration()
{
AppConfig appConfig;
QCOMPARE( appConfig.option<Config::close_on_unfocus>(), false );
QCOMPARE( appConfig.option<Config::clipboard_tab>(), QString(clipboardTabName) );
QCOMPARE( appConfig.option<Config::maxitems>(), Config::maxitems::defaultValue() );
QCOMPARE( savedTabs(), QStringList(clipboardTabName) );
QCOMPARE( AppConfig().option<Config::tabs>(), QStringList() );
}
bool startTestProcess(QProcess *p, const QStringList &arguments,
QIODevice::OpenMode mode = QIODevice::ReadWrite,
const QStringList &environment = QStringList())
{
if ( environment.isEmpty() ) {
p->setProcessEnvironment(m_env);
} else {
auto env = m_env;
for (const QString &nameValue : environment) {
const auto i = nameValue.indexOf(QLatin1Char('='));
Q_ASSERT(i != -1);
const auto name = nameValue.left(i);
const auto value = nameValue.mid(i+1);
env.insert(name, value);
}
p->setProcessEnvironment(env);
}
p->start( QCoreApplication::applicationFilePath(), arguments, mode );
return p->waitForStarted(10000);
}
QByteArray waitForServerToStart()
{
SleepTimer t(15000);
do {
if ( run(Args() << "") == 0 )
return QByteArray();
} while ( t.sleep() );
return "Unable to start server!" + readServerErrors(ReadAllStderr);
}
PlatformClipboard *clipboard()
{
if (m_clipboard == nullptr)
m_clipboard = platformNativeInterface()->clipboard();
return m_clipboard.get();
}
std::unique_ptr<QProcess> m_server;
QProcessEnvironment m_env;
QString m_testId;
QVariantMap m_settings;
QStringList m_failed;
PlatformClipboardPtr m_clipboard;
};
QString keyNameFor(QKeySequence::StandardKey standardKey)
{
return QKeySequence(standardKey).toString();
}
int count(const QStringList &items, const QString &pattern)
{
int from = -1;
int count = 0;
const QRegularExpression re(pattern);
while ( (from = items.indexOf(re, from + 1)) != -1 )
++count;
return count;
}
QStringList splitLines(const QByteArray &nativeText)
{
return QString::fromUtf8(nativeText).split(QRegularExpression("\r\n|\n|\r"));
}
} // namespace
Tests::Tests(const TestInterfacePtr &test, QObject *parent)
: QObject(parent)
, m_test(test)
{
}
void Tests::initTestCase()
{
TEST(m_test->initTestCase());
}
void Tests::cleanupTestCase()
{
TEST(m_test->cleanupTestCase());
}
void Tests::init()
{
TEST(m_test->init());
}
void Tests::cleanup()
{
TEST( m_test->cleanup() );
}
void Tests::readLog()
{
QByteArray stdoutActual;
QByteArray stderrActual;
QCOMPARE( run(Args("info") << "log", &stdoutActual, &stderrActual), 0 );
QVERIFY2( testStderr(stderrActual), stderrActual );
QCOMPARE( logFileName() + "\n", QString::fromUtf8(stdoutActual) );
QTRY_VERIFY( !readLogFile(maxReadLogSize).isEmpty() );
#define LOGGED_ONCE(PATTERN) \
QTRY_COMPARE( count(splitLines(readLogFile(maxReadLogSize)), PATTERN), 1 )
LOGGED_ONCE(
R"(^CopyQ DEBUG \[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}\] <Server-\d+>: Loading configuration$)");
LOGGED_ONCE(
R"(^CopyQ DEBUG \[.*\] <Server-\d+>: Starting monitor$)");
LOGGED_ONCE(
R"(^.*<monitorClipboard-\d+>: Clipboard formats to save: .*$)");
}
void Tests::commandHelp()
{
QByteArray stdoutActual;
QByteArray stderrActual;
QCOMPARE( run(Args("help"), &stdoutActual, &stderrActual), 0 );
QVERIFY2( testStderr(stderrActual), stderrActual );
QVERIFY(!stdoutActual.isEmpty());
const QStringList commands = QStringList()
<< "show"
<< "hide"
<< "toggle"
<< "menu"
<< "exit"
<< "help"
<< "version"
<< "clipboard"
<< "copy"
<< "paste"
<< "action"
<< "add"
<< "remove";
for (const auto &command : commands) {
QCOMPARE( run(Args("help") << command, &stdoutActual, &stderrActual), 0 );
QVERIFY2( testStderr(stderrActual), stderrActual );
QVERIFY( !stdoutActual.isEmpty() );
const QString help = QString::fromUtf8(stdoutActual);
QVERIFY( help.contains(QRegularExpression("\\b" + QRegularExpression::escape(command) + "\\b")) );
}
// Print error on unknown function name.
RUN_EXPECT_ERROR("help" << "xxx", CommandException);
}
void Tests::commandVersion()
{
QByteArray stdoutActual;
QByteArray stderrActual;
QCOMPARE( run(Args("version"), &stdoutActual, &stderrActual), 0 );
QVERIFY2( testStderr(stderrActual), stderrActual );
QVERIFY( !stdoutActual.isEmpty() );
const QString version = QString::fromUtf8(stdoutActual);
// Version contains application name and version.
QVERIFY( version.contains(QRegularExpression("\\bCopyQ\\b.*" + QRegularExpression::escape(versionString))) );
// Version contains Qt version.
QVERIFY( version.contains(QRegularExpression("\\bQt:\\s+\\d")) );
}
void Tests::badCommand()
{
RUN_EXPECT_ERROR_WITH_STDERR("xxx", CommandException, "xxx");
RUN_EXPECT_ERROR_WITH_STDERR("tab" << testTab(1) << "yyy", CommandException, "yyy");
// Bad command shouldn't create new tab.
QByteArray stdoutActual;
QByteArray stderrActual;
QCOMPARE( run(Args("tab"), &stdoutActual, &stderrActual), 0 );
QVERIFY2( testStderr(stderrActual), stderrActual );
QVERIFY( !QString::fromUtf8(stdoutActual)
.contains(QRegularExpression("^" + QRegularExpression::escape(testTab(1)) + "$")) );
}
void Tests::badSessionName()
{
RUN_EXPECT_ERROR("-s" << "max_16_characters_in_session_name_allowed" << "", CommandBadSyntax);
RUN_EXPECT_ERROR("-s" << "spaces disallowed" << "", CommandBadSyntax);
}
void Tests::commandCatchExceptions()
{
#if QT_VERSION < QT_VERSION_CHECK(5,12,0)
SKIP("Internal exceptions are not handled well before Qt 5.12.");
#endif
RUN("try { removeTab('MISSING') } catch(e) { print(e) }",
"Error: Tab with given name doesn't exist!");
}
void Tests::commandExit()
{
RUN("exit", "Terminating server.\n");
TEST( m_test->waitForServerToStop() );
QCOMPARE( run(Args("exit")), 1 );
}
void Tests::commandEval()
{
RUN("eval" << "", "");
RUN("eval" << "1", "1\n");
RUN("eval" << "[1,2,3]", "1\n2\n3\n");
RUN("eval" << "'123'", "123\n");
RUN("eval" << "'123'", "123\n");
RUN("-e" << "", "");
RUN("-e" << "1", "1\n");
}
void Tests::commandEvalThrows()
{
RUN_EXPECT_ERROR_WITH_STDERR(
"throw Error('Some exception')", CommandException,
"ScriptError: Some exception\n"
"\n"
"--- backtrace ---\n"
);
RUN_EXPECT_ERROR_WITH_STDERR(
"throw 'Some exception'", CommandException,
"ScriptError: Some exception\n"
);
RUN_EXPECT_ERROR("eval('throw Error(1)')", CommandException);
RUN_EXPECT_ERROR("eval('throw 1')", CommandException);
RUN_EXPECT_ERROR("eval" << "throw Error(1)", CommandException);
RUN_EXPECT_ERROR("eval" << "throw 1", CommandException);
}
void Tests::commandEvalSyntaxError()
{
RUN_EXPECT_ERROR_WITH_STDERR("eval" << "(", CommandException, "SyntaxError");
}
void Tests::commandEvalArguments()
{
RUN("eval" << "str(arguments[1]) + ', ' + str(arguments[2])" << "Test 1" << "Test 2",
"Test 1, Test 2\n");
}
void Tests::commandEvalEndingWithComment()
{
/*
With Qml scripts in Qt 5, it's not possible to get uncaught exceptions
from `QJSEngine::evaluate()`.
Workaround is to wrap the script properly in an try/catch block:
try {
%1
} catch(e) {
_store_exception_internally(e);
throw e;
}