/
tests.cpp
3434 lines (2797 loc) · 105 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
/*
Copyright (c) 2019, Lukas Holecek <hluk@email.cz>
This file is part of CopyQ.
CopyQ is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CopyQ is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with CopyQ. If not, see <http://www.gnu.org/licenses/>.
*/
#include "tests.h"
#include "test_utils.h"
#include "common/appconfig.h"
#include "common/client_server.h"
#include "common/common.h"
#include "common/config.h"
#include "common/mimetypes.h"
#include "common/settings.h"
#include "common/shortcuts.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/platformnativeinterface.h"
#include <QClipboard>
#include <QDebug>
#include <QDir>
#include <QElapsedTimer>
#include <QFile>
#include <QFileInfo>
#include <QGuiApplication>
#include <QMap>
#include <QMimeData>
#include <QProcess>
#include <QRegExp>
#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 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 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 shortcutButtonId = "focus::QPushButton in CommandDialog";
const auto shortcutDialogId = "focus::QLineEdit 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";
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)
{
const QRegExp re("Warning:|ERROR:|ASSERT", Qt::CaseInsensitive);
QString output = QString::fromUtf8(stderrData);
// FIXME: These warnings should be fixed.
// Ignore known warnings.
output.remove("QtWarning: QXcbXSettings::QXcbXSettings(QXcbScreen*) Failed to get selection owner for XSETTINGS_S atom");
output.remove("QtWarning: QXcbConnection: XCB error:");
output.remove("QtWarning: QXcbClipboard: SelectionRequest too old");
output.remove("QtWarning: libpng warning: iCCP: known incorrect sRGB profile");
output.remove("QtWarning: QMime::convertToMime: unhandled mimetype: text/plain");
output.remove("ERROR: QtCritical: QWindowsPipeWriter::write failed. (The pipe is being closed.)");
output.remove("ERROR: QtCritical: QWindowsPipeWriter: asynchronous write failed. (The pipe has been ended.)");
#ifdef Q_OS_MAC
output.remove("QtWarning: Failed to get QCocoaScreen for NSObject(0x0)");
output.remove("ERROR: Failed to open session mutex: QSystemSemaphore::handle:: ftok failed");
#endif
if ( output.indexOf(re) != -1 )
return false;
if (flag == TestInterface::ReadErrorsWithoutScriptException)
return true;
const QRegExp scriptExceptionError("ScriptError:");
return output.indexOf(scriptExceptionError) == -1;
}
QByteArray getClipboard(const QString &mime = QString("text/plain"), ClipboardMode mode = ClipboardMode::Clipboard)
{
const QMimeData *data = clipboardData(mode);
return (data != nullptr) ? data->data(mime) : QByteArray();
}
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);
}
~TestInterfaceImpl()
{
stopServer();
}
QByteArray startServer() override
{
if ( isServerRunning() )
return "Server is already running.";
m_server.reset(new QProcess);
m_serverErrorOutput.clear();
QObject::connect(
m_server.get(), &QProcess::readyReadStandardError,
[this]() {
const auto errorOutput = m_server->readAllStandardError().replace('\r', "");
m_serverErrorOutput.append(errorOutput);
});
if ( !startTestProcess(m_server.get(), QStringList(), QIODevice::ReadOnly) ) {
return QString("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("Test failed: Unexpected exit code %1; expected was %2")
.arg(exitCode)
.arg(expectedExitCode)
.toUtf8()
+ printClienAndServerStderr(stderrActual, exitCode);
}
if ( !stderrActual.contains(stderrContains) ) {
return QString("Test failed: Expected error output on client side with \"%1\".")
.arg(QString::fromUtf8(stderrContains)).toUtf8()
+ printClienAndServerStderr(stderrActual, exitCode);
}
return readServerErrors(ReadErrorsWithoutScriptException);
}
QByteArray setClipboard(const QByteArray &bytes, const QString &mime, ClipboardMode mode) override
{
if ( getClipboard(mime, mode) == bytes )
return QByteArray();
waitFor(waitMsSetClipboard);
auto mimeData = new QMimeData();
mimeData->setData(mime, bytes);
const auto qmode = mode == ClipboardMode::Clipboard ? QClipboard::Clipboard : QClipboard::Selection;
QGuiApplication::clipboard()->setMimeData(mimeData, qmode);
waitFor(waitMsSetClipboard);
return verifyClipboard(bytes, mime);
}
QByteArray verifyClipboard(const QByteArray &data, const QString &mime, bool exact = true) override
{
PerformanceTimer perf;
SleepTimer t(waitMsSetClipboard * 5);
do {
if ( exact ? getClipboard(mime) == data : getClipboard(mime).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());
const QByteArray actualBytes = getClipboard(mime);
return QString("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();
if ( flag == ReadAllStderr || !testStderr(m_serverErrorOutput, flag) )
return decorateOutput("Server STDERR", m_serverErrorOutput);
}
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 gettting 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("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.remove() ) {
return QString("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(QByteArray(), mimeText, ClipboardMode::Clipboard), "Failed to reset clipboard" );
#ifdef HAS_MOUSE_SELECTIONS
RETURN_ON_ERROR( setClipboard(QByteArray(), mimeText, 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
{
return QByteArray();
}
QString shortcutToRemove() override
{
return ::shortcutToRemove();
}
void setEnv(const QString &name, const QString &value) override
{
m_env.insert(name, value);
}
void setupTest(const QString &id, const QVariant &settings)
{
m_testId = id;
m_settings = settings.toMap();
m_env.insert("COPYQ_TEST_ID", id);
}
private:
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);
}
std::unique_ptr<QProcess> m_server;
QByteArray m_serverErrorOutput;
QProcessEnvironment m_env;
QString m_testId;
QVariantMap m_settings;
};
QString keyNameFor(QKeySequence::StandardKey standardKey)
{
return QKeySequence(standardKey).toString();
}
} // 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::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(QRegExp("\\b" + QRegExp::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(QRegExp("\\bCopyQ\\b.*" + QRegExp::escape(COPYQ_VERSION))) );
// Version contains Qt version.
QVERIFY( version.contains(QRegExp("\\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 shoudn't create new tab.
QByteArray stdoutActual;
QByteArray stderrActual;
QCOMPARE( run(Args("tab"), &stdoutActual, &stderrActual), 0 );
QVERIFY2( testStderr(stderrActual), stderrActual );
QVERIFY( !QString::fromUtf8(stdoutActual)
.contains(QRegExp("^" + QRegExp::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::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("eval" << "throw 'TEST_EXCEPTION'", CommandException, "TEST_EXCEPTION");
}
void Tests::commandEvalSyntaxError()
{
RUN_EXPECT_ERROR_WITH_STDERR("eval" << "(", CommandException, "syntax error");
}
void Tests::commandEvalArguments()
{
RUN("eval" << "str(arguments[1]) + ', ' + str(arguments[2])" << "Test 1" << "Test 2",
"Test 1, Test 2\n");
}
void Tests::commandPrint()
{
RUN("print" << "1", "1");
RUN("print" << "TEST", "TEST");
}
void Tests::commandAbort()
{
RUN("eval" << "abort(); 1", "");
RUN("eval" << "eval('abort(); print(1)'); 2", "");
RUN("eval" << "execute('copyq', 'eval', '--', 'abort(); print(1)'); 2", "2\n");
}
void Tests::commandFail()
{
QByteArray stdoutActual;
QByteArray stderrActual;
QCOMPARE( run(Args("fail"), &stdoutActual, &stderrActual), 1 );
QVERIFY2( testStderr(stderrActual), stderrActual );
QCOMPARE( stdoutActual, QByteArray() );
}
void Tests::commandSource()
{
const auto script =
R"(
test = function() { return " TEST" }
print("SOURCED")
)";
QTemporaryFile scriptFile;
QVERIFY(scriptFile.open());
scriptFile.write(script);
scriptFile.close();
const auto scriptFileName = scriptFile.fileName();
RUN("source" << scriptFileName, "SOURCED")
RUN("source" << scriptFileName << "test()", "SOURCED TEST\n")
}
void Tests::commandVisible()
{
RUN("visible", "true\n");
}
void Tests::commandToggle()
{
RUN("visible", "true\n");
RUN("toggle", "false\n");
WAIT_ON_OUTPUT("visible", "false\n");
RUN("toggle", "true\n");
WAIT_ON_OUTPUT("visible", "true\n");
}
void Tests::commandHide()
{
RUN("visible", "true\n");
RUN("hide", "");
WAIT_ON_OUTPUT("visible", "false\n");
}
void Tests::commandShow()
{
RUN("visible", "true\n");
RUN("hide", "");
WAIT_ON_OUTPUT("visible", "false\n");
RUN("show", "");
WAIT_ON_OUTPUT("visible", "true\n");
}
void Tests::commandShowAt()
{
RUN("visible", "true\n");
RUN("hide", "");
WAIT_ON_OUTPUT("visible", "false\n");
RUN("showAt", "");
WAIT_ON_OUTPUT("visible", "true\n");
}
void Tests::commandFocused()
{
RUN("focused", "true\n");
RUN("hide", "");
RUN("focused", "false\n");
}
void Tests::commandsUnicode()
{
const auto text = QString::fromUtf8(QByteArray("Zkouška s různými českými znaky!"));
RUN_WITH_INPUT("eval" << "input()", text, text);
RUN_WITH_INPUT("eval" << "str(input())", text, text + "\n");
RUN_WITH_INPUT("eval" << "fromUnicode(str(input()), 'utf8')", text, text);
RUN_WITH_INPUT("eval" << "toUnicode(fromUnicode(str(input()), 'utf16'), 'utf16')", text, text + "\n");
RUN_WITH_INPUT("eval" << "toUnicode(fromUnicode(str(input()), 'utf32le'), 'utf32le')", text, text + "\n");
RUN_WITH_INPUT("eval" << "toUnicode( fromUnicode(str(input()), 'utf16le') )", text, text + "\n");
}
void Tests::commandsAddRead()
{
RUN("add" << "A", "");
RUN("read" << "0", "A");
RUN("add" << "B", "");
RUN("read" << "0", "B");
RUN("read" << "1", "A");
RUN("add" << "C" << "D", "");
RUN("read" << "0", "D");
RUN("read" << "1", "C");
RUN("read" << "2", "B");
RUN("read" << "3", "A");
}
void Tests::commandsWriteRead()
{
const QByteArray input("\x00\x01\x02\x03\x04", 5);
const auto arg1 = QString::fromLatin1("\x01\x02\x03\x04");
const auto arg2 = QString::fromLatin1("\x7f\x6f\x5f\x4f");
TEST( m_test->runClient(
Args() << "write"
<< COPYQ_MIME_PREFIX "test1" << arg1
<< COPYQ_MIME_PREFIX "test2" << "-"
<< COPYQ_MIME_PREFIX "test3" << arg2, "",
input) );
RUN("read" << COPYQ_MIME_PREFIX "test1" << "0", arg1.toLatin1());
RUN("read" << COPYQ_MIME_PREFIX "test2" << "0", input);
RUN("read" << COPYQ_MIME_PREFIX "test3" << "0", arg2.toLatin1());
}
void Tests::commandChange()
{
RUN("add" << "C" << "B" << "A", "");
RUN("change" << "1" << "text/plain" << "b", "");
RUN("separator" << " " << "read" << "0" << "1" << "2", "A b C");
RUN("change" << "1" << "text/plain" << "B" << "text/html" << "<b>B</b>", "");
RUN("read" << "text/html" << "1", "<b>B</b>");
RUN("separator" << " " << "read" << "0" << "1" << "2", "A B C");
RUN("change(1, 'text/html', undefined)", "");
RUN("read" << "?" << "1", "text/plain\n");
}
void Tests::commandSetCurrentTab()
{
const auto tab = testTab(1);
RUN("setCurrentTab" << tab, "");
RUN("testSelected", tab + "\n");
}
void Tests::commandConfig()
{
QByteArray stdoutActual;
QByteArray stderrActual;
QCOMPARE( run(Args("config"), &stdoutActual, &stderrActual), 0 );
QVERIFY2( testStderr(stderrActual), stderrActual );
QVERIFY( !stdoutActual.isEmpty() );
// invalid option
RUN_EXPECT_ERROR_WITH_STDERR("config" << "xxx", CommandException, "xxx");
QCOMPARE( run(Args("config") << "tab_tree", &stdoutActual, &stderrActual), 0 );
QVERIFY2( testStderr(stderrActual), stderrActual );
QVERIFY2( stdoutActual == "true\n" || stdoutActual == "false\n", stdoutActual);
RUN("config" << "tab_tree" << "true", "true\n");
RUN("config" << "tab_tree", "true\n");
RUN("config" << "tab_tree" << "false", "false\n");
RUN("config" << "tab_tree", "false\n");
RUN("config" << "tab_tree" << "1", "true\n");
RUN("config" << "tab_tree", "true\n");
RUN("config" << "tab_tree" << "0", "false\n");
RUN("config" << "tab_tree", "false\n");
// Set multiple options.
RUN("config" << "tab_tree" << "0" << "text_wrap" << "1",
"tab_tree=false\n"
"text_wrap=true\n");
// Don't set any options if there is an invalid one.
RUN_EXPECT_ERROR_WITH_STDERR("config" << "tab_tree" << "1" << "xxx" << "0", CommandException, "xxx");
RUN("config" << "tab_tree", "false\n");
}
void Tests::commandToggleConfig()
{
RUN("toggleConfig" << "check_clipboard", "false\n");
RUN("config" << "check_clipboard", "false\n");
RUN("toggleConfig" << "check_clipboard", "true\n");
RUN("config" << "check_clipboard", "true\n");
RUN_EXPECT_ERROR("toggleConfig", CommandException);
RUN_EXPECT_ERROR_WITH_STDERR("toggleConfig" << "xxx", CommandException, "xxx");
RUN_EXPECT_ERROR_WITH_STDERR("toggleConfig" << "clipboard_tab", CommandException, "clipboard_tab");
}
void Tests::commandDialog()
{
RUN(Args() << "keys" << clipboardBrowserId, "");
runMultiple(
[&]() { RUN(WITH_TIMEOUT "dialog('text')", "TEST\n"); },
[&]() { RUN(Args() << "keys" << "focus::QLineEdit in :QDialog" << ":TEST" << "ENTER", ""); }
);
RUN(Args() << "keys" << clipboardBrowserId, "");
runMultiple(
[&]() { RUN(WITH_TIMEOUT "dialog('text') === undefined", "true\n"); },
[&]() { RUN(Args() << "keys" << "focus::QLineEdit in :QDialog" << "ESCAPE", ""); }
);
RUN(Args() << "keys" << clipboardBrowserId, "");
runMultiple(
[&]() { RUN(WITH_TIMEOUT "dialog('.defaultChoice', 2, 'list', [1, 2, 3])", "2\n"); },
[&]() { RUN(Args() << "keys" << "focus::QComboBox in :QDialog" << "ENTER", ""); }
);
RUN(Args() << "keys" << clipboardBrowserId, "");
runMultiple(
[&]() { RUN(WITH_TIMEOUT "dialog('.defaultChoice', '', 'list', [1, 2, 3])", "\n"); },
[&]() { RUN(Args() << "keys" << "focus::QComboBox in :QDialog" << "ENTER", ""); }
);
RUN(Args() << "keys" << clipboardBrowserId, "");
runMultiple(
[&]() { RUN(WITH_TIMEOUT "dialog('list', [0, 1, 2])", "0\n"); },
[&]() { RUN(Args() << "keys" << "focus::QComboBox in :QDialog" << "ENTER", ""); }
);
// Can't focus configuration checkboxes on OS X
#ifndef Q_OS_MAC
RUN(Args() << "keys" << clipboardBrowserId, "");
runMultiple(
[&]() { RUN(WITH_TIMEOUT "dialog('boolean', true) === true", "true\n"); },