Debian Codegraph @

src/tests/tests_scripts.cpp

raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 #include "test_utils.h"
4 #include "tests.h"
5 #include "tests_common.h"
6
7 #include "common/mimetypes.h"
8 #include "common/commandstatus.h"
9
10 #include <QElapsedTimer>
11 #include <QRegularExpression>
12 #include <QTemporaryFile>
13 #include <algorithm>
14
15 void CoreTests::commandExit()
16 {
17 RUN("exit", "");
18
19 TEST( m_test->waitForServerToStop() );
20
21 QCOMPARE( run(Args("exit")), 1 );
22 }
23
24 void CoreTests::commandEval()
25 {
26 RUN("eval" << "", "");
27 RUN("eval" << "1", "1\n");
28 RUN("eval" << "[1,2,3]", "1\n2\n3\n");
29 RUN("eval" << "'123'", "123\n");
30 RUN("eval" << "'123'", "123\n");
31
32 RUN("-e" << "", "");
33 RUN("-e" << "1", "1\n");
34 }
35
36 void CoreTests::commandEvalThrows()
37 {
38 RUN_EXPECT_ERROR_WITH_STDERR(
39 "throw Error('Some exception')", CommandException,
40 "ScriptError: Some exception\n"
41 "\n"
42 "--- backtrace ---\n"
43 );
44
45 RUN_EXPECT_ERROR_WITH_STDERR(
46 "throw 'Some exception'", CommandException,
47 "ScriptError: Some exception\n"
48 );
49
50 RUN_EXPECT_ERROR("eval('throw Error(1)')", CommandException);
51 RUN_EXPECT_ERROR("eval('throw 1')", CommandException);
52 RUN_EXPECT_ERROR("eval" << "throw Error(1)", CommandException);
53 RUN_EXPECT_ERROR("eval" << "throw 1", CommandException);
54 }
55
56 void CoreTests::commandEvalThrowsWithLineNumber()
57 {
58 // Multi-line script: exception on a specific line
59 RUN_EXPECT_ERROR_WITH_STDERR(
60 "eval" << "var x = 1\nvar y = 2\nthrow Error('on line 3')",
61 CommandException,
62 "At line 3 in:\n"
63 " 1|var x = 1\n"
64 " 2|var y = 2\n"
65 " 3|throw Error('on line 3')\n"
66 );
67
68 // Single-line throw: line number is 1
69 RUN_EXPECT_ERROR_WITH_STDERR(
70 "throw Error('single line')", CommandException,
71 "At line 1 in:\n"
72 );
73
74 // Non-Error throw: no line number (no .lineNumber on plain string)
75 RUN_EXPECT_ERROR_WITH_STDERR(
76 "throw 'no line info'", CommandException,
77 "ScriptError: no line info\n"
78 );
79
80 // Nested eval: inner script is multiline (2 lines)
81 RUN_EXPECT_ERROR_WITH_STDERR(
82 "eval" << "eval(\"\\\\nthrow Error('nested')\")",
83 CommandException,
84 "At line 2 in:\n"
85 " 1|\n"
86 " 2|throw Error('nested')\n"
87 );
88
89 // Doubly nested eval: both inner scripts are multiline.
90 // Inner script is 3 lines, middle script is 2 lines.
91 RUN_EXPECT_ERROR_WITH_STDERR(
92 "eval" << "eval(\"\\\\neval('\\\\\\\\n\\\\\\\\nthrow Error()')\")",
93 CommandException,
94 "At line 3 in:\n"
95 " 1|\n"
96 " 2|\n"
97 " 3|throw Error()\n"
98 );
99
100 // Verify the middle frame in the doubly nested case is also numbered
101 RUN_EXPECT_ERROR_WITH_STDERR(
102 "eval" << "eval(\"\\\\neval('\\\\\\\\n\\\\\\\\nthrow Error()')\")",
103 CommandException,
104 " 2|eval('\\n\\nthrow Error()')\n"
105 );
106 }
107
108
109 void CoreTests::commandEvalSyntaxError()
110 {
111 RUN_EXPECT_ERROR_WITH_STDERR("eval" << "(", CommandException, "SyntaxError");
112 }
113
114 void CoreTests::commandEvalArguments()
115 {
116 RUN("eval" << "str(arguments[1]) + ', ' + str(arguments[2])" << "Test 1" << "Test 2",
117 "Test 1, Test 2\n");
118 }
119
120 void CoreTests::commandEvalEndingWithComment()
121 {
122 /*
123 With Qml scripts in Qt 5, it's not possible to get uncaught exceptions
124 from `QJSEngine::evaluate()`.
125
126 Workaround is to wrap the script properly in an try/catch block:
127
128 try {
129 %1
130 } catch(e) {
131 _store_exception_internally(e);
132 throw e;
133 }
134
135 (Unfortunately, it's still possible to escape the function with a script injection.)
136 */
137 RUN("eval" << "1 // TEST", "1\n");
138 }
139
140 void CoreTests::commandPrint()
141 {
142 RUN("print" << "1", "1");
143 RUN("print" << "TEST", "TEST");
144 }
145
146 void CoreTests::commandAbort()
147 {
148 RUN("abort(); 1", "");
149 RUN("eval" << "abort(); 1", "");
150 RUN("eval" << "eval('abort(); print(1)'); 2", "");
151 RUN("eval" << "execute('copyq', 'eval', '--', 'abort(); print(1)'); 2", "2\n");
152 }
153
154 void CoreTests::commandFail()
155 {
156 QByteArray stdoutActual;
157 QByteArray stderrActual;
158 QCOMPARE( run(Args("fail"), &stdoutActual, &stderrActual), 10 );
159 QVERIFY2( testStderr(stderrActual), stderrActual );
160 QCOMPARE( stdoutActual, QByteArray() );
161 }
162
163 void CoreTests::commandSource()
164 {
165 const auto script =
166 R"(
167 test = function() { return " TEST" }
168 print("SOURCED")
169 )";
170
171 QTemporaryFile scriptFile;
172 QVERIFY(scriptFile.open());
173 scriptFile.write(script);
174 scriptFile.close();
175 const auto scriptFileName = scriptFile.fileName();
176
177 RUN("source" << scriptFileName, "SOURCED");
178 RUN("source" << scriptFileName << "test()", "SOURCED TEST\n");
179 }
180
181 void CoreTests::commandVisible()
182 {
183 RUN("visible", "true\n");
184 }
185
186 void CoreTests::commandToggle()
187 {
188 RUN("visible", "true\n");
189 RUN("toggle", "false\n");
190 WAIT_ON_OUTPUT("visible", "false\n");
191
192 RUN("toggle", "true\n");
193 WAIT_ON_OUTPUT("visible", "true\n");
194 }
195
196 void CoreTests::commandShowHide()
197 {
198 RUN("visible", "true\n");
199 RUN("hide", "");
200 WAIT_ON_OUTPUT("visible", "false\n");
201
202 RUN("show", "");
203 WAIT_ON_OUTPUT("visible", "true\n");
204 }
205
206
207 void CoreTests::commandShowHideRapid()
208 {
209 // Verify the main window can be hidden and reshown reliably in
210 // rapid succession. Regression test for #3445: deferred platform
211 // raise in raiseWindow() could prevent the window from appearing.
212 for (int i = 0; i < 3; ++i) {
213 RUN("visible", "true\n");
214 RUN("hide", "");
215 WAIT_ON_OUTPUT("visible", "false\n");
216
217 RUN("show", "");
218 WAIT_ON_OUTPUT("visible", "true\n");
219 }
220 }
221 void CoreTests::commandShowAt()
222 {
223 RUN("visible", "true\n");
224 RUN("hide", "");
225 WAIT_ON_OUTPUT("visible", "false\n");
226
227 RUN("showAt", "");
228 WAIT_ON_OUTPUT("visible", "true\n");
229 }
230
231 void CoreTests::commandFocused()
232 {
233 RUN("focused", "true\n");
234 RUN("hide", "");
235 RUN("focused", "false\n");
236 }
237
238 void CoreTests::commandsUnicode()
239 {
240 const auto text = QString::fromUtf8(QByteArray("Zkouška s různými českými znaky!"));
241 RUN_WITH_INPUT("eval" << "input()", text, text);
242 RUN_WITH_INPUT("eval" << "str(input())", text, text + "\n");
243
244 RUN_WITH_INPUT("eval" << "fromUnicode(str(input()), 'utf8')", text, text);
245 RUN_WITH_INPUT("eval" << "toUnicode(fromUnicode(str(input()), 'utf16'), 'utf16')", text, text + "\n");
246 RUN_WITH_INPUT("eval" << "toUnicode(fromUnicode(str(input()), 'utf32le'), 'utf32le')", text, text + "\n");
247 RUN_WITH_INPUT("eval" << "toUnicode( fromUnicode(str(input()), 'utf16le') )", text, text + "\n");
248 }
249
250 void CoreTests::commandsAddRead()
251 {
252 RUN("add" << "A", "");
253 RUN("read" << "0", "A");
254
255 RUN("add" << "B", "");
256 RUN("read" << "0", "B");
257 RUN("read" << "1", "A");
258
259 RUN("add" << "C" << "D", "");
260 RUN("read" << "0", "D");
261 RUN("read" << "1", "C");
262 RUN("read" << "2", "B");
263 RUN("read" << "3", "A");
264 }
265
266 void CoreTests::commandsWriteRead()
267 {
268 const QByteArray input("\x00\x01\x02\x03\x04", 5);
269 const auto arg1 = QString::fromLatin1("\x01\x02\x03\x04");
270 const auto arg2 = QString::fromLatin1("\x7f\x6f\x5f\x4f");
271 TEST( m_test->runClient(
272 Args() << "write"
273 << COPYQ_MIME_PREFIX "test1" << arg1
274 << COPYQ_MIME_PREFIX "test2" << "-"
275 << COPYQ_MIME_PREFIX "test3" << arg2, "",
276 input) );
277 RUN("read" << COPYQ_MIME_PREFIX "test1" << "0", arg1.toLatin1());
278 RUN("read" << COPYQ_MIME_PREFIX "test2" << "0", input);
279 RUN("read" << COPYQ_MIME_PREFIX "test3" << "0", arg2.toLatin1());
280
281 RUN("write(1, {'text/plain': 'A'}, {'text/plain': 'B'})", "");
282 RUN("read(mimeText, 0, 1, 2, 3)", "\nB\nA\n");
283
284 RUN("write(0, [{'text/plain': 'C'}, {'text/plain': 'D'}])", "");
285 RUN("read(mimeText, 0, 1, 2, 3)", "D\nC\n\nB");
286
287 RUN("write(0, ['E', 'F'])", "");
288 RUN("read(mimeText, 0, 1, 2, 3)", "F\nE\nD\nC");
289
290 RUN_EXPECT_ERROR_WITH_STDERR(
291 "write(0, [{}], [{}])",
292 CommandException, "Unexpected multiple item list arguments");
293 RUN_EXPECT_ERROR_WITH_STDERR(
294 "write(0)",
295 CommandException, "Expected item arguments");
296 RUN_EXPECT_ERROR_WITH_STDERR(
297 "write(0, '1', '2', '3')",
298 CommandException, "Unexpected uneven number of mimeType/data arguments");
299 }
300
301 void CoreTests::commandsReadUtf8ByDefault()
302 {
303 RUN("add({[mimeText]: 'A', [mimeTextUtf8]: 'B'})", "");
304 RUN("read(mimeText, 0)", "A");
305 RUN("read(0)", "B");
306 }
307
308 void CoreTests::commandChange()
309 {
310 RUN("add" << "C" << "B" << "A", "");
311 RUN("change" << "1" << "text/plain" << "b", "");
312 RUN("separator" << " " << "read" << "0" << "1" << "2", "A b C");
313
314 RUN("change" << "1" << "text/plain" << "B" << "text/html" << "<b>B</b>", "");
315 RUN("read" << "text/html" << "1", "<b>B</b>");
316 RUN("separator" << " " << "read" << "0" << "1" << "2", "A B C");
317
318 RUN("change(1, 'text/html', undefined)", "");
319 RUN("read" << "?" << "1", "text/plain\n");
320 }
321
322 void CoreTests::commandSetCurrentTab()
323 {
324 const auto tab = testTab(1);
325 RUN("setCurrentTab" << tab, "");
326 TEST_SELECTED(tab + "\n");
327 }
328
329 void CoreTests::commandConfig()
330 {
331 QByteArray stdoutActual;
332 QByteArray stderrActual;
333 QCOMPARE( run(Args("config"), &stdoutActual, &stderrActual), 0 );
334 QVERIFY2( testStderr(stderrActual), stderrActual );
335 QVERIFY( !stdoutActual.isEmpty() );
336
337 // invalid option
338 RUN_EXPECT_ERROR_WITH_STDERR("config" << "xxx", CommandException, "xxx");
339
340 QCOMPARE( run(Args("config") << "tab_tree", &stdoutActual, &stderrActual), 0 );
341 QVERIFY2( testStderr(stderrActual), stderrActual );
342 QVERIFY2( stdoutActual == "true\n" || stdoutActual == "false\n", stdoutActual);
343
344 RUN("config" << "tab_tree" << "true", "true\n");
345 RUN("config" << "tab_tree", "true\n");
346
347 RUN("config" << "tab_tree" << "false", "false\n");
348 RUN("config" << "tab_tree", "false\n");
349
350 RUN("config" << "tab_tree" << "1", "true\n");
351 RUN("config" << "tab_tree", "true\n");
352
353 RUN("config" << "tab_tree" << "0", "false\n");
354 RUN("config" << "tab_tree", "false\n");
355
356 // Set multiple options.
357 RUN("config" << "tab_tree" << "0" << "text_wrap" << "1",
358 "tab_tree=false\n"
359 "text_wrap=true\n");
360
361 // Don't set any options if there is an invalid one.
362 RUN_EXPECT_ERROR_WITH_STDERR("config" << "tab_tree" << "1" << "xxx" << "0", CommandException, "xxx");
363 RUN("config" << "tab_tree", "false\n");
364 }
365
366 void CoreTests::commandToggleConfig()
367 {
368 RUN("toggleConfig" << "check_clipboard", "false\n");
369 RUN("config" << "check_clipboard", "false\n");
370 RUN("toggleConfig" << "check_clipboard", "true\n");
371 RUN("config" << "check_clipboard", "true\n");
372
373 RUN_EXPECT_ERROR("toggleConfig", CommandException);
374 RUN_EXPECT_ERROR_WITH_STDERR("toggleConfig" << "xxx", CommandException, "xxx");
375 RUN_EXPECT_ERROR_WITH_STDERR("toggleConfig" << "clipboard_tab", CommandException, "clipboard_tab");
376 }
377
378 void CoreTests::commandDialog()
379 {
380 KEYS(clipboardBrowserId);
381 RUN_MULTIPLE(
382 [&]{ RUN("dialog('text')", "TEST\n"); },
383 [&]{ KEYS("focus::QLineEdit<:QDialog" << ":TEST" << "ENTER"); }
384 );
385
386 KEYS(clipboardBrowserId);
387 RUN_MULTIPLE(
388 [&]{ RUN("dialog('text') === undefined", "true\n"); },
389 [&]{ KEYS("focus::QLineEdit<:QDialog" << "ESCAPE"); }
390 );
391
392 KEYS(clipboardBrowserId);
393 RUN_MULTIPLE(
394 [&]{ RUN("dialog('.defaultChoice', 2, 'list', [1, 2, 3])", "2\n"); },
395 [&]{ KEYS("focus::QComboBox<:QDialog" << "ENTER"); }
396 );
397
398 KEYS(clipboardBrowserId);
399 RUN_MULTIPLE(
400 [&]{ RUN("dialog('.defaultChoice', '', 'list', [1, 2, 3])", "\n"); },
401 [&]{ KEYS("focus::QComboBox<:QDialog" << "ENTER"); }
402 );
403
404 KEYS(clipboardBrowserId);
405 RUN_MULTIPLE(
406 [&]{ RUN("dialog('list', [0, 1, 2])", "0\n"); },
407 [&]{ KEYS("focus::QComboBox<:QDialog" << "ENTER"); }
408 );
409
410 // Can't focus configuration checkboxes on OS X
411 #ifndef Q_OS_MAC
412 KEYS(clipboardBrowserId);
413 RUN_MULTIPLE(
414 [&]{ RUN("dialog('boolean', true) === true", "true\n"); },
415 [&]{ KEYS("focus::QCheckBox<:QDialog" << "ENTER"); }
416 );
417 #endif
418
419 // Verify that special argument ".title" changes dialog's object name
420 // so that geometry can be stored.
421 KEYS(clipboardBrowserId);
422 RUN_MULTIPLE(
423 [&]{ RUN("dialog('.title', 'test', 'text')", ""); },
424 [&]{ KEYS("focus::QLineEdit<dialog_test:QDialog" << "ESCAPE"); }
425 );
426
427 KEYS(clipboardBrowserId);
428 const QByteArray script = R"(
429 dialog(
430 '.width', 100,
431 '.height', 100,
432 '.x', 10,
433 '.y', 10,
434 '.style', 'background: red',
435 '.icon', '',
436 '.label', 'TEST',
437 'text', 'DEFAULT',
438 )
439 )";
440 RUN_MULTIPLE(
441 [&]{ RUN(script, "DEFAULT\n"); },
442 [&]{ KEYS("focus::QLineEdit<:QDialog" << "ENTER"); }
443 );
444
445 KEYS(clipboardBrowserId);
446 RUN_MULTIPLE(
447 [&]{ RUN("dialog('.title', 'Remove Items', '.label', 'Remove all items?') === true", "true\n"); },
448 [&]{ KEYS("focus::QPushButton<dialog_Remove Items:QDialog" << "ENTER"); }
449 );
450
451 KEYS(clipboardBrowserId);
452 const QByteArray script2 = R"(
453 dialog(
454 '.modal', true,
455 '.onTop', true,
456 'text', 'DEFAULT',
457 )
458 )";
459 RUN_MULTIPLE(
460 [&]{ RUN(script2, "DEFAULT\n"); },
461 [&]{ KEYS("focus::QLineEdit<:QDialog" << "ENTER"); }
462 );
463 }
464
465 void CoreTests::commandDialogCloseOnDisconnect()
466 {
467 RUN("afterMilliseconds(0, abort); dialog()", "");
468 }
469
470 void CoreTests::commandMenuItems()
471 {
472 KEYS(clipboardBrowserId);
473 RUN_MULTIPLE(
474 [&]{ RUN("menuItems('a', 'b', 'c')", "a\n"); },
475 [&]{ KEYS(customMenuId << "ENTER"); }
476 );
477
478 KEYS(clipboardBrowserId);
479 RUN_MULTIPLE(
480 [&]{ RUN("menuItems([{'text/plain': 'a'}, {'text/plain': 'b'}])", "0\n"); },
481 [&]{ KEYS(customMenuId << "ENTER"); }
482 );
483
484 KEYS(clipboardBrowserId);
485 RUN_MULTIPLE(
486 [&]{ RUN("menuItems('a', 'b', 'c')", "\n"); },
487 [&]{ KEYS(customMenuId << "ESCAPE"); }
488 );
489
490 KEYS(clipboardBrowserId);
491 RUN_MULTIPLE(
492 [&]{ RUN("menuItems([{'text/plain': 'a'}, {'text/plain': 'b'}])", "-1\n"); },
493 [&]{ KEYS(customMenuId << "ESCAPE"); }
494 );
495
496 KEYS(clipboardBrowserId);
497 RUN_MULTIPLE(
498 [&]{ RUN("menuItems('a', 'b', 'c')", "b\n"); },
499 [&]{ KEYS(customMenuId << ":b" << "ENTER"); }
500 );
501
502 KEYS(clipboardBrowserId);
503 RUN_MULTIPLE(
504 [&]{ RUN("menuItems([{'text/plain': 'a'}, {'text/plain': 'b'}])", "1\n"); },
505 [&]{ KEYS(customMenuId << ":b" << "ENTER"); }
506 );
507
508 RUN("afterMilliseconds(0, abort); menuItems('a', 'b', 'c')", "");
509 }
510
511 void CoreTests::commandsPackUnpack()
512 {
513 QMap<QLatin1String, QByteArray> data;
514 data[mimeText] = "plain text";
515 data[mimeHtml] = "<b>HTML text</b>";
516 data[QLatin1String(COPYQ_MIME_PREFIX "test1")] = "test1 data";
517 data[QLatin1String(COPYQ_MIME_PREFIX "test2")] = "test2 data";
518
519 auto args = Args() << "write";
520 for (const auto &mime : data.keys())
521 args << mime << data[mime];
522 RUN(args, "");
523
524 const QByteArray script1 =
525 "var data = read('" + toByteArray(mimeItems) + "', 0); var item = unpack(data);";
526
527 // Unpack item read from list.
528 for (const auto &mime : data.keys()) {
529 RUN("eval"
530 << script1 + "var mime = '" + mime + "'; print(mime + ':' + str(item[mime]))",
531 mime + ':' + data[mime]);
532 }
533
534 // Test pack and unpack consistency.
535 const QByteArray script2 = "data = pack(item); item = unpack(data);";
536 for (const auto &mime : data.keys()) {
537 RUN("eval"
538 << script1 + script2 + "var mime = '" + mime + "'; print(mime + ':' + str(item[mime]))",
539 mime + ':' + data[mime]);
540 }
541 }
542
543 void CoreTests::commandsBase64()
544 {
545 const QByteArray data = "0123456789\001\002\003\004\005\006\007abcdefghijklmnopqrstuvwxyz!";
546 const QByteArray base64 = data.toBase64();
547
548 TEST( m_test->runClient(Args() << "eval" << "print(input())", data, data) );
549 TEST( m_test->runClient(Args() << "eval" << "print(tobase64(input()))", base64, data) );
550
551 // Line break is added only if return value is string;
552 // tobase64() returns string, frombase64() returns byte array.
553 RUN("tobase64" << data, base64 + '\n');
554 RUN("frombase64" << base64, data);
555
556 TEST( m_test->runClient(Args() << "eval" << "print(frombase64(tobase64(input())))", data, data) );
557
558 // Test Base64 encoding and decoding consistency.
559 TEST( m_test->runClient(
560 Args() << "eval"
561 << "var base64 = tobase64(input()); if (str(input()) === str(frombase64(base64))) print('OK')",
562 "OK", data) );
563 }
564
565 void CoreTests::commandsGetSetItem()
566 {
567 QMap<QByteArray, QByteArray> data;
568 data["text/plain"] = "plain text";
569 data["text/html"] = "<b>HTML text</b>";
570 data[COPYQ_MIME_PREFIX "test1"] = "test1 data";
571 data[COPYQ_MIME_PREFIX "test2"] = "test2 data";
572
573 const QString tab = testTab(1);
574 const Args args = Args("tab") << tab;
575
576 Args args2 = args;
577 args2 << "write";
578 for (const auto &mime : data.keys())
579 args2 << mime << data[mime];
580 RUN(args2, "");
581
582 // Get item from list.
583 for (const auto &mime : data.keys()) {
584 RUN(args << "eval"
585 << "var mime = '" + mime + "'; print(mime + ':' + str(getitem(0)[mime]))",
586 mime + ':' + data[mime]);
587 }
588
589 // Set item.
590 RUN(args << "eval"
591 << "setitem(1, { 'text/plain': 'plain text 2', 'text/html': '<b>HTML text 2</b>' })",
592 "");
593
594 RUN(args << "eval" << "print(getitem(1)['text/plain'])", "plain text 2");
595 RUN(args << "eval" << "print(getitem(1)['text/html'])", "<b>HTML text 2</b>");
596 }
597
598 void CoreTests::commandsChecksums()
599 {
600 RUN("eval" <<
601 "[md5sum('TEST'), sha1sum('TEST'),"
602 " sha256sum('TEST'), sha512sum('TEST')]"
603 ,
604 "033bd94b1168d7e4f0d644c3c95e35bf\n"
605 "984816fd329622876e14907634264e6f332e9fb3\n"
606 "94ee059335e587e501cc4bf90613e0814f00a7b08bc7c648fd865a2af6a22cc2\n"
607 "7bfa95a688924c47c7d22381f20cc926f524beacb13f84e203d4bd8cb6ba2fce81c57a5f059bf3d509926487bde925b3bcee0635e4f7baeba054e5dba696b2bf\n"
608 );
609 }
610
611 void CoreTests::commandEscapeHTML()
612 {
613 RUN("escapeHTML" << "&\n<\n>", "&amp;<br />&lt;<br />&gt;\n");
614 }
615
616 void CoreTests::commandExecute()
617 {
618 const QByteArray script =
619 "function test(c, expected_stdout, expected_exit_code) {"
620 " if (str(c.stdout) !== expected_stdout) print('Unexpected stdout: \"' + str(c.stdout) + '\"');"
621 " if (c.exit_code !== expected_exit_code) print('Unexpected exit_code: ' + str(c.exit_code));"
622 "}";
623
624 RUN("eval" << script +
625 "c = execute('copyq', 'write', 'text/plain', 'plain text', 'text/html', '<b>test HTML</b>');"
626 "test(c, '', 0);"
627 , "");
628
629 RUN("eval" << script +
630 "c = execute('copyq', 'read', 'text/plain', 0);"
631 "test(c, 'plain text', 0);"
632 , "");
633
634 RUN("eval" << script +
635 "c = execute('copyq', 'read', 'text/html', 0);"
636 "test(c, '<b>test HTML</b>', 0);"
637 , "");
638
639 RUN("eval" << script +
640 "c = execute('copyq', 'read', 0, function(lines) { print(lines); });"
641 "test(c, 'plain text', 0);"
642 , "plain text");
643 }
644
645 void CoreTests::commandSettings()
646 {
647 RUN("config" << "clipboard_tab" << "TEST", "TEST\n");
648
649 RUN("settings" << "test_variable", "");
650 RUN("settings" << "test_variable" << "TEST VALUE", "");
651 RUN("settings" << "test_variable", "TEST VALUE");
652 RUN("settings" << "test_variable" << "TEST VALUE 2", "");
653 RUN("settings" << "test_variable", "TEST VALUE 2");
654
655 RUN("config" << "clipboard_tab", "TEST\n");
656 }
657
658 void CoreTests::commandsEnvSetEnv()
659 {
660 RUN("eval" <<
661 "\n var name = 'COPYQ_ENV_TEST'"
662 "\n if (setEnv(name, 'OK'))"
663 "\n print(env(name))"
664 "\n else"
665 "\n print('FAILED')"
666 , "OK"
667 );
668 }
669
670 void CoreTests::commandSleep()
671 {
672 RUN_MULTIPLE(
673 [&]{
674 QElapsedTimer t;
675 t.start();
676 RUN("sleep" << "200", "");
677 const auto afterElapsed200Ms = t.elapsed();
678 QVERIFY(afterElapsed200Ms > 200);
679 },
680 [&]{
681 QElapsedTimer t;
682 t.start();
683 RUN("sleep" << "50", "");
684 const auto afterElapsed50Ms = t.elapsed();
685 QVERIFY(afterElapsed50Ms > 50);
686 }
687 );
688 }
689
690 void CoreTests::commandsData()
691 {
692 RUN("eval" << "setData('x', 'X'); data('x')", "X");
693 RUN("eval" << "setData('x', 'X'); setData('y', 'Y'); str(data('x')) + str(data('y'))", "XY\n");
694
695 RUN("dataFormats", "");
696 RUN("eval" << "setData('x'); dataFormats()", "x\n");
697 RUN("eval" << "setData('x'); setData('y'); dataFormats()", "x\ny\n");
698
699 RUN("eval" << "setData('x'); setData('y'); removeData('x'); dataFormats()", "y\n");
700 RUN("eval" << "setData('x'); setData('y'); removeData('y'); dataFormats()", "x\n");
701 }
702
703 void CoreTests::commandCurrentWindowTitle()
704 {
705 RUN("disable", "");
706 WAIT_ON_OUTPUT("currentWindowTitle", appWindowTitle("*Clipboard Storing Disabled*"));
707 RUN("enable", "");
708 }
709
710 void CoreTests::commandCopy()
711 {
712 RUN("copy" << "A", "true\n");
713 WAIT_FOR_CLIPBOARD("A");
714
715 RUN("copy" << "DATA" << "B", "true\n");
716 WAIT_FOR_CLIPBOARD2("B", "DATA");
717
718 // Test copying UTF-8 text.
719 // On macOS, text/plain and text/plain;charset=utf-8 map to the same UTI
720 // (public.utf8-plain-text), so setting both with different values causes
721 // the pasteboard to return the wrong one. Only set mimeTextUtf8 on macOS.
722 #ifdef Q_OS_MAC
723 RUN("--" << "copy({[mimeTextUtf8]: '\u2705'})", "true\n");
724 #else
725 RUN("--" << "copy({[mimeText]: '\\\\u2705', [mimeTextUtf8]: '\u2705'})", "true\n");
726 #endif
727 WAIT_FOR_CLIPBOARD2("\u2705", mimeTextUtf8);
728
729 RUN( Args() << "copy"
730 << "DATA3" << "C"
731 << "DATA4" << "D"
732 , "true\n" );
733 WAIT_FOR_CLIPBOARD2("C", "DATA3");
734
735 SKIP_ON_ENV("COPYQ_TESTS_SKIP_MULTIPLE_CLIPBOARD_FORMATS");
736 WAIT_FOR_CLIPBOARD2("D", "DATA4");
737
738 RUN( "copy({'DATA1': 1, 'DATA2': 2})", "true\n" );
739 WAIT_FOR_CLIPBOARD2("1", "DATA1");
740 WAIT_FOR_CLIPBOARD2("2", "DATA2");
741
742 RUN_EXPECT_ERROR_WITH_STDERR(
743 "copy({}, {})",
744 CommandException, "Expected single item");
745 RUN_EXPECT_ERROR_WITH_STDERR(
746 "copy([{}, {}])",
747 CommandException, "Expected single item");
748 }
749
750 void CoreTests::commandClipboard()
751 {
752 TEST( m_test->setClipboard("A") );
753 WAIT_FOR_CLIPBOARD("A");
754
755 TEST( m_test->setClipboard("B", "DATA") );
756 WAIT_FOR_CLIPBOARD2("B", "DATA");
757 RUN("clipboard" << "DATA", "B");
758 }
759
760 void CoreTests::commandHasClipboardFormat()
761 {
762 TEST( m_test->setClipboard("B", "DATA") );
763 WAIT_FOR_CLIPBOARD2("B", "DATA");
764 WAIT_ON_OUTPUT("hasClipboardFormat('DATA')", "true\n");
765 RUN("hasClipboardFormat('text/plain')", "false\n");
766
767 TEST( m_test->setClipboard("A") );
768 WAIT_ON_OUTPUT("hasClipboardFormat('text/plain')", "true\n");
769 }
770
771 void CoreTests::commandEdit()
772 {
773 SKIP_ON_ENV("COPYQ_TESTS_SKIP_COMMAND_EDIT");
774
775 RUN("config" << "editor" << "", "\n");
776
777 // Edit clipboard and new item.
778 TEST( m_test->setClipboard("TEST") );
779 RUN("edit" << "-1", "");
780 KEYS("END" << ":LINE 1" << "F2");
781 RUN("read" << "0", "TESTLINE 1");
782 WAIT_FOR_CLIPBOARD("TESTLINE 1");
783
784 // Edit existing item.
785 RUN("edit" << "0", "");
786 KEYS("END" << "ENTER" << ":LINE 2" << "F2");
787 RUN("read" << "0", "TESTLINE 1\nLINE 2");
788 WAIT_FOR_CLIPBOARD("TESTLINE 1");
789
790 // Edit clipboard (ignore existing data) and new item.
791 RUN("edit", "");
792 KEYS("END" << ":LINE 1" << "F2");
793 RUN("read" << "0", "LINE 1");
794 WAIT_FOR_CLIPBOARD("LINE 1");
795 }
796
797 void CoreTests::commandEditItem()
798 {
799 SKIP_ON_ENV("COPYQ_TESTS_SKIP_COMMAND_EDIT");
800
801 RUN("config" << "editor" << "", "\n");
802
803 // Edit clipboard and new item.
804 TEST( m_test->setClipboard("<!--StartFragment-->TEST<!--EndFragment-->", mimeHtml) );
805 RUN("editItem" << "-1" << mimeHtml, "");
806 KEYS("END" << ":LINE 1" << "F2");
807 const auto expected = QByteArrayLiteral("TESTLINE 1");
808 #ifdef Q_OS_WIN
809 const auto expectedClipboard = QByteArrayLiteral("<!--StartFragment-->TESTLINE 1<!--EndFragment-->");
810 #else
811 const auto expectedClipboard = expected;
812 #endif
813 RUN("read" << mimeHtml << "0", expected);
814 RUN("read" << "0", "");
815 WAIT_FOR_CLIPBOARD2(expectedClipboard, mimeHtml);
816 WAIT_FOR_CLIPBOARD("");
817
818 // Edit existing item.
819 RUN("editItem" << "0" << mimeHtml, "");
820 KEYS("END" << "ENTER" << ":LINE 2" << "F2");
821 RUN("read" << mimeHtml << "0", expected + "\nLINE 2");
822 RUN("read" << "0", "");
823 WAIT_FOR_CLIPBOARD2(expectedClipboard, mimeHtml);
824 WAIT_FOR_CLIPBOARD("");
825
826 // Edit clipboard (ignore existing data) and new item.
827 RUN("editItem" << "-1" << mimeHtml << "TEST", "");
828 KEYS("END" << ":LINE 1" << "F2");
829 RUN("read" << mimeHtml << "0", "TESTLINE 1");
830 RUN("read" << "0", "");
831 WAIT_FOR_CLIPBOARD2(expectedClipboard, mimeHtml);
832 WAIT_FOR_CLIPBOARD("");
833 }
834
835 void CoreTests::commandGetSetCurrentPath()
836 {
837 RUN("currentPath", QDir::currentPath() + "\n");
838
839 const auto newPath = QDir::homePath().toUtf8();
840
841 TEST( m_test->runClient(
842 Args("eval") << "currentPath(input()); print(currentPath())",
843 newPath, newPath) );
844
845 TEST( m_test->runClient(
846 Args("eval") << "currentPath(input()); print(Dir().absolutePath())",
847 newPath, newPath) );
848 }
849
850 void CoreTests::commandSelectItems()
851 {
852 RUN("add" << "C" << "B" << "A", "");
853
854 RUN("selectItems" << "1", "true\n");
855 TEST_SELECTED(QString(clipboardTabName) + " 1 1\n");
856
857 RUN("selectItems" << "0" << "2", "true\n");
858 TEST_SELECTED(QString(clipboardTabName) + " 2 0 2\n");
859
860 RUN("selectItems" << "2" << "0", "true\n");
861 TEST_SELECTED(QString(clipboardTabName) + " 0 2 0\n");
862
863 const auto tab = testTab(1);
864 const auto args = Args("tab") << tab;
865 RUN(args << "add" << "C" << "B" << "A", "");
866 RUN(args << "selectItems" << "1" << "2", "true\n");
867 TEST_SELECTED(QString(clipboardTabName) + " 0 2 0\n");
868 RUN("setCurrentTab" << tab, "");
869 TEST_SELECTED(tab + " 2 1 2\n");
870 }
871
872 void CoreTests::commandsExportImport()
873 {
874 const auto tab1 = testTab(1);
875 RUN("tab" << tab1 << "add" << "C" << "B" << "A", "");
876
877 const auto tab2 = testTab(2);
878 RUN("tab" << tab2 << "add" << "3" << "2", "");
879
880 RUN("config" << "maxitems" << "3", "3\n");
881 RUN("config" << "editor" << "EDITOR1 %1", "EDITOR1 %1\n");
882
883 TemporaryFile tmp;
884 const auto fileName = tmp.fileName();
885
886 RUN("exportData" << fileName, "");
887
888 RUN("config" << "maxitems" << "1", "1\n");
889 RUN("config" << "editor" << "EDITOR2 %1", "EDITOR2 %1\n");
890 RUN("removetab" << tab1, "");
891 RUN("tab" << tab2 << "add" << "1", "");
892
893 RUN("importData" << fileName, "");
894
895 RUN("config" << "maxitems", "3\n");
896 RUN("config" << "editor", "EDITOR1 %1\n");
897
898 const auto suffix = " (1)";
899 RUN("tab",
900 QString(clipboardTabName) + "\n"
901 + tab2 + "\n"
902 + clipboardTabName + suffix + "\n"
903 + tab1 + "\n"
904 + tab2 + suffix + "\n");
905
906 RUN("tab" << tab1 << "read" << "0" << "1" << "2", "A\nB\nC");
907 RUN("tab" << tab2 + suffix << "read" << "0" << "1", "2\n3");
908 RUN("tab" << tab2 << "read" << "0", "1");
909 }
910
911 void CoreTests::commandsGetSetCommands()
912 {
913 RUN("commands().length", "0\n");
914
915 RUN("setCommands([{name: 'test', cmd: 'copyq help'}])", "");
916 RUN("commands().length", "1\n");
917 RUN("commands()[0].name", "test\n");
918 RUN("commands()[0].cmd", "copyq help\n");
919 RUN("commands()[0].enable", "true\n");
920
921 RUN("setCommands(commands())", "");
922 RUN("commands().length", "1\n");
923 RUN("commands()[0].name", "test\n");
924 RUN("commands()[0].enable", "true\n");
925 }
926
927 void CoreTests::commandsImportExportCommands()
928 {
929 const QString commands =
930 R"('
931 [Commands]
932 1\Name=Test 1
933 2\Name=Test 2
934 size=2
935 ')";
936 RUN("eval" << "importCommands(arguments[1]).length" << "--" << commands, "2\n");
937 RUN("eval" << "importCommands(arguments[1])[0].name" << "--" << commands, "Test 1\n");
938 RUN("eval" << "importCommands(arguments[1])[1].name" << "--" << commands, "Test 2\n");
939
940 RUN("importCommands(exportCommands([{},{}])).length", "2\n");
941 RUN("importCommands(exportCommands([{},{name: 'Test 2'}]))[1].name", "Test 2\n");
942 }
943
944 void CoreTests::commandsImportExportCommandsFixIndentation()
945 {
946 {
947 const QString commands =
948 "[Command]\n"
949 "Command=\"\n 1\n 2\n 3\"";
950 RUN("eval" << "importCommands(arguments[1])[0].cmd" << "--" << commands, "1\n2\n3\n");
951 }
952
953 {
954 const QString commands =
955 "[Command]\n"
956 "Command=\"\r\n 1\r\n 2\r\n 3\"";
957 RUN("eval" << "importCommands(arguments[1])[0].cmd" << "--" << commands, "1\n2\n3\n");
958 }
959 }
960
961 void CoreTests::commandsAddCommandsRegExp()
962 {
963 const QString commands =
964 "[Command]\n"
965 "Match=^(https?|ftps?)://\\\\$\n";
966
967 // Ensure there is a basic RegExp support.
968 RUN("/test/", "/test/\n");
969 RUN("/test/.source", "test\n");
970
971 RUN("eval" << "exportCommands(importCommands(arguments[1]))" << "--" << commands, commands);
972 RUN("eval" << "Object.prototype.toString.call(importCommands(arguments[1])[0].re)" << "--" << commands, "[object RegExp]\n");
973 RUN("eval" << "Object.prototype.toString.call(importCommands(arguments[1])[0].wndre)" << "--" << commands, "[object RegExp]\n");
974 RUN("eval" << "importCommands(arguments[1])[0].re" << "--" << commands, "/^(https?|ftps?):\\/\\/\\$/\n");
975 RUN("eval" << "importCommands(arguments[1])[0].wndre" << "--" << commands, "/(?:)/\n");
976
977 RUN("eval" << "addCommands(importCommands(arguments[1]))" << "--" << commands, "");
978 KEYS(commandDialogListId << "Enter" << clipboardBrowserId);
979
980 RUN("exportCommands(commands())", commands);
981 RUN("commands()[0].name", "\n");
982 RUN("commands()[0].re", "/^(https?|ftps?):\\/\\/\\$/\n");
983 RUN("commands()[0].wndre", "/(?:)/\n");
984 }
985
986 void CoreTests::commandScreenshot()
987 {
988 RUN("screenshot().size() > 0", "true\n");
989 }
990
991 void CoreTests::commandNotification()
992 {
993 const auto script = R"(
994 notification(
995 '.title', 'title',
996 '.message', 'message',
997 '.time', 1000,
998 '.id', 'test',
999 '.icon', 'copyq',
1000 '.button', 'OK', '', '',
1001 '.button', 'CANCEL', '', '',
1002 '.urgency', 'critical',
1003 '.persistent', true,
1004 )
1005 )";
1006 RUN(script, "");
1007
1008 RUN_EXPECT_ERROR_WITH_STDERR(
1009 "notification('.message', 'message', 'BAD')", CommandException, "Unknown argument: BAD");
1010 }
1011
1012 void CoreTests::commandNotificationUrgency()
1013 {
1014 RUN("notification('.urgency', 'low')", "");
1015 RUN("notification('.urgency', 'normal')", "");
1016 RUN("notification('.urgency', 'high')", "");
1017 RUN("notification('.urgency', 'critical')", "");
1018 RUN_EXPECT_ERROR_WITH_STDERR(
1019 "notification('.urgency', 'unknown')",
1020 CommandException,
1021 "Unknown value for '.urgency' notification field: unknown");
1022 }
1023
1024 void CoreTests::commandNotificationPersistent()
1025 {
1026 RUN("notification('.persistent', true)", "");
1027 RUN("notification('.persistent', false)", "");
1028 RUN("notification('.persistent', 1)", "");
1029 RUN("notification('.persistent', 0)", "");
1030 RUN("notification('.persistent', 'true')", "");
1031 RUN("notification('.persistent', 'false')", "");
1032 RUN_EXPECT_ERROR_WITH_STDERR(
1033 "notification('.persistent', 'unknown')",
1034 CommandException,
1035 "Unknown value for '.persistent' notification field: unknown");
1036 }
1037
1038 void CoreTests::commandIcon()
1039 {
1040 RUN("iconColor", QByteArray(defaultSessionColor) + "\n");
1041
1042 RUN("iconColor" << "red", "");
1043 RUN("iconColor", "#ff0000\n");
1044
1045 RUN_EXPECT_ERROR("iconColor" << "BAD_COLOR_NAME", CommandException);
1046 RUN("iconColor", "#ff0000\n");
1047
1048 RUN("iconColor" << "", "");
1049 RUN("iconColor", QByteArray(defaultSessionColor) + "\n");
1050
1051 RUN("iconColor" << defaultSessionColor, "");
1052 RUN("iconColor", QByteArray(defaultSessionColor) + "\n");
1053 }
1054
1055 void CoreTests::commandIconTag()
1056 {
1057 RUN("iconTag", "\n");
1058
1059 RUN("iconTag" << "TEST", "");
1060 RUN("iconTag", "TEST\n");
1061
1062 RUN("iconTag" << "", "");
1063 RUN("iconTag", "\n");
1064 }
1065
1066 void CoreTests::commandIconTagColor()
1067 {
1068 RUN("iconTagColor", QByteArray(defaultTagColor) + "\n");
1069
1070 RUN("iconTagColor" << "red", "");
1071 RUN("iconTagColor", "#ff0000\n");
1072
1073 RUN_EXPECT_ERROR("iconTagColor" << "BAD_COLOR_NAME", CommandException);
1074 RUN("iconTagColor", "#ff0000\n");
1075
1076 RUN("iconTagColor" << defaultTagColor, "");
1077 RUN("iconTagColor", QByteArray(defaultTagColor) + "\n");
1078 }
1079
1080 void CoreTests::commandLoadTheme()
1081 {
1082 RUN_EXPECT_ERROR_WITH_STDERR(
1083 "loadTheme" << "a non-existent file", CommandException, "ScriptError: Failed to read theme");
1084 RUN_EXPECT_ERROR_WITH_STDERR(
1085 "loadTheme" << ".", CommandException, "ScriptError: Failed to read theme");
1086
1087 {
1088 QTemporaryFile tmp;
1089 QVERIFY(tmp.open());
1090 tmp.write("INVALID INI FILE");
1091 tmp.close();
1092 RUN_EXPECT_ERROR_WITH_STDERR(
1093 "loadTheme" << tmp.fileName(), CommandException, "ScriptError: Failed to parse theme");
1094 }
1095
1096 {
1097 QTemporaryFile tmp;
1098 QVERIFY(tmp.open());
1099 tmp.write("[General]");
1100 tmp.close();
1101 RUN("loadTheme" << tmp.fileName(), "");
1102 }
1103
1104 // Verify default stylesheets - if there is a syntax error,
1105 // application prints a warning which should be captured by tests.
1106 {
1107 QTemporaryFile tmp;
1108 QVERIFY(tmp.open());
1109 tmp.write("[General]\nstyle_main_window=true");
1110 tmp.close();
1111 RUN("loadTheme" << tmp.fileName(), "");
1112 }
1113 }
1114
1115 void CoreTests::commandDateString()
1116 {
1117 const auto dateFormat = "TEST:yyyy-MM-dd";
1118 const auto dateTime = QDateTime::currentDateTime();
1119 const auto today = dateTime.toString(dateFormat);
1120 RUN("dateString" << dateFormat, today + "\n");
1121 }
1122
1123 void CoreTests::commandAfterMilliseconds()
1124 {
1125 const QString script = "afterMilliseconds(100, function(){ print('TEST'); abort(); });";
1126 RUN(script, "");
1127 RUN(script + "sleep(1)", "");
1128 RUN(script + "sleep(200)", "TEST");
1129 }
1130
1131 void CoreTests::commandAsync()
1132 {
1133 RUN("afterMilliseconds(0, function() { print(currentItem()); abort(); }); dialog()", "-1");
1134 }
1135
1136 void CoreTests::commandFilter()
1137 {
1138 RUN("filter", "\n");
1139 RUN("filter" << "test", "");
1140 RUN("filter", "test\n");
1141 RUN("filter" << "another", "");
1142 RUN("filter", "another\n");
1143 RUN("filter" << "", "");
1144 RUN("filter", "\n");
1145
1146 // Empty filter() after ESC.
1147 RUN("filter" << "test", "");
1148 RUN("filter", "test\n");
1149 KEYS("ESC");
1150 RUN("filter", "\n");
1151 }
1152
1153 void CoreTests::commandMimeTypes()
1154 {
1155 RUN("eval" <<
1156 "[mimeText, mimeHtml, mimeUriList, mimeWindowTitle,"
1157 " mimeItems, mimeItemNotes, mimeOwner, mimeClipboardMode,"
1158 " mimeCurrentTab, mimeSelectedItems, mimeCurrentItem,"
1159 " mimeHidden, mimeShortcut, mimeColor, mimeOutputTab]"
1160 ,
1161 QByteArray(mimeText.data()) + "\n"
1162 + mimeHtml + "\n"
1163 + mimeUriList + "\n"
1164 + mimeWindowTitle + "\n"
1165 + mimeItems + "\n"
1166 + mimeItemNotes + "\n"
1167 + mimeOwner + "\n"
1168 + mimeClipboardMode + "\n"
1169 + mimeCurrentTab + "\n"
1170 + mimeSelectedItems + "\n"
1171 + mimeCurrentItem + "\n"
1172 + mimeHidden + "\n"
1173 + mimeShortcut + "\n"
1174 + mimeColor + "\n"
1175 + mimeOutputTab + "\n"
1176 );
1177 }
1178
1179 void CoreTests::commandUnload()
1180 {
1181 // Failure if tab is visible.
1182 RUN("unload", "");
1183
1184 const auto tab = testTab(1);
1185
1186 // Success if tab doesn't exist.
1187 RUN("unload" << tab, tab + "\n");
1188
1189 RUN("tab" << tab << "add" << "A", "");
1190 // Success if tab is not visible and editor is not open.
1191 RUN("unload" << tab, tab + "\n");
1192
1193 RUN("tab" << tab << "add" << "B", "");
1194 RUN("unload", tab + "\n");
1195 // Success if tab is not loaded.
1196 RUN("unload", tab + "\n");
1197
1198 // Success if tab does not exist.
1199 RUN("unload" << "missing-tab", "missing-tab\n");
1200 }
1201
1202 void CoreTests::commandForceUnload()
1203 {
1204 RUN("forceUnload", "");
1205 RUN_EXPECT_ERROR_WITH_STDERR("add" << "A", CommandException, "ScriptError: Invalid tab");
1206
1207 KEYS(clipboardBrowserRefreshButtonId << "Space");
1208 RUN("add" << "A", "");
1209
1210 const auto tab = testTab(1);
1211 RUN("tab" << tab << "add" << "A", "");
1212
1213 RUN("forceUnload" << tab, "");
1214
1215 RUN("setCurrentTab" << tab, "");
1216 RUN_EXPECT_ERROR_WITH_STDERR(
1217 "tab" << tab << "add" << "B", CommandException, "ScriptError: Invalid tab");
1218
1219 KEYS(clipboardBrowserRefreshButtonId << "Space");
1220 RUN("add" << "B", "");
1221 }
1222
1223 void CoreTests::commandServerLogAndLogs()
1224 {
1225 const QByteArray data1 = generateData();
1226 QRegularExpression re("\\[[^]]+\\] Note <Server-[0-9]+>: " + QRegularExpression::escape(data1));
1227
1228 QByteArray stdoutActual;
1229 QByteArray stderrActual;
1230
1231 QCOMPARE( run(Args("logs"), &stdoutActual, &stderrActual), 0 );
1232 QVERIFY2( testStderr(stderrActual), stderrActual );
1233 QVERIFY( !stdoutActual.isEmpty() );
1234 QVERIFY( !QString::fromUtf8(stdoutActual).contains(re) );
1235
1236 RUN("serverLog" << data1, "");
1237
1238 QCOMPARE( run(Args("logs"), &stdoutActual, &stderrActual), 0 );
1239 QVERIFY2( testStderr(stderrActual), stderrActual );
1240 QVERIFY( !stdoutActual.isEmpty() );
1241 QVERIFY2( QString::fromUtf8(stdoutActual).contains(re), stdoutActual );
1242 }
1243
1244 void CoreTests::commandStats()
1245 {
1246 QByteArray stdoutActual;
1247 QByteArray stderrActual;
1248 QCOMPARE( run(Args("stats"), &stdoutActual, &stderrActual), 0 );
1249 QVERIFY2( testStderr(stderrActual), stderrActual );
1250 QVERIFY( !stdoutActual.isEmpty() );
1251 const auto stats = stdoutActual.split('\n');
1252 QVERIFY2( stats.value(0).startsWith("TOTAL: "), stdoutActual);
1253 QVERIFY2( stats.contains("QApplication: 1"), stdoutActual);
1254 QVERIFY2( stats.contains("MainWindow: 1"), stdoutActual);
1255 QVERIFY2( stats.contains("#MainWindow: 1"), stdoutActual);
1256 QVERIFY2( stats.contains("#tabWidget: 1"), stdoutActual);
1257 QVERIFY2( stats.contains("#searchBar: 1"), stdoutActual);
1258 QVERIFY2( stats.contains("/MainWindow/#centralWidget/#tabWidget: 1"), stdoutActual);
1259 QVERIFY2( stats.contains("/MainWindow/#centralWidget/Utils::FilterLineEdit#searchBar: 1"), stdoutActual);
1260 QVERIFY2( stats.contains("/MainWindow/#centralWidget/#tabWidget/QStackedWidget/ClipboardBrowserPlaceholder/ClipboardBrowser: 1"), stdoutActual);
1261 QVERIFY2( stats.contains("/MainWindow/#centralWidget/#tabWidget/QStackedWidget/ClipboardBrowserPlaceholder: 1"), stdoutActual);
1262
1263 // Verify model stats
1264 RUN("add" << "test_item", "");
1265 QCOMPARE( run(Args("stats"), &stdoutActual, &stderrActual), 0 );
1266 QVERIFY2( testStderr(stderrActual), stderrActual );
1267 const auto stats2 = stdoutActual.split('\n');
1268 bool hasModelWithDataSize = false;
1269 for (const auto &line : stats2) {
1270 if (line.startsWith("MODEL ")) {
1271 QVERIFY2(line.contains("rows="), line);
1272 if (line.contains("dataSize=")) {
1273 hasModelWithDataSize = true;
1274 // Verify human-readable suffix is present
1275 QVERIFY2(line.contains(" B)") || line.contains(" KiB)") || line.contains(" MiB)"), line);
1276 }
1277 }
1278 }
1279 QVERIFY2(hasModelWithDataSize, stdoutActual);
1280
1281 // Verify data directory size
1282 bool hasDataDir = false;
1283 for (const auto &line : stats2) {
1284 if (line.startsWith("DATA_DIR ")) {
1285 hasDataDir = true;
1286 QVERIFY2(line.contains("size="), line);
1287 }
1288 }
1289 QVERIFY2(hasDataDir, stdoutActual);
1290
1291 // Verify new stat lines
1292 bool hasTabs = false;
1293 bool hasCommands = false;
1294 bool hasLogFiles = false;
1295 for (const auto &line : stats2) {
1296 if (line.startsWith("TABS: ")) {
1297 hasTabs = true;
1298 QVERIFY2(line.contains("total="), line);
1299 QVERIFY2(line.contains("loaded="), line);
1300 }
1301 if (line.startsWith("COMMANDS: ")) {
1302 hasCommands = true;
1303 QVERIFY2(line.contains("automatic="), line);
1304 QVERIFY2(line.contains("script="), line);
1305 }
1306 if (line.startsWith("LOG_FILES: ")) {
1307 hasLogFiles = true;
1308 QVERIFY2(line.contains("count="), line);
1309 QVERIFY2(line.contains("size="), line);
1310 }
1311 }
1312 QVERIFY2(hasTabs, stdoutActual);
1313 QVERIFY2(hasCommands, stdoutActual);
1314 QVERIFY2(hasLogFiles, stdoutActual);
1315
1316 // Verify monitorClipboard internal action appears with per-sub-process pid/rss
1317 const auto isMonitorAction = [](const QByteArray &line) {
1318 return line.startsWith("ACTION ") && line.contains("monitorClipboard");
1319 };
1320 const auto it = std::find_if(stats2.cbegin(), stats2.cend(), isMonitorAction);
1321 QVERIFY2(it != stats2.cend(), stdoutActual);
1322 QVERIFY2(it->contains("pid="), *it);
1323 }
1324
1325 void CoreTests::statsQObjectLeak()
1326 {
1327 // Set up items and commands that produce QObjects on selection change:
1328 // - inMenu commands trigger context menu rebuilds (updateContextMenu)
1329 // - display command triggers runDisplayCommands() on item widget creation
1330 // - matchCmd triggers runMenuCommandFilters() on selection change
1331 RUN("add" << "B" << "A", "");
1332 const auto script = R"(
1333 setCommands([
1334 {name: 'cmd1', inMenu: true, shortcuts: ['Ctrl+F1'], cmd: 'copyq add cmd1'},
1335 {name: 'cmd2', inMenu: true, globalShortcuts: ['Ctrl+F2'], cmd: 'copyq add cmd2'},
1336 {name: 'cmd3', inMenu: true, matchCmd: 'copyq: true', cmd: 'copyq add cmd3'},
1337 {name: 'cmd4', display: true, cmd: 'copyq: setData(mimeHtml, data(mimeText))'},
1338 ])
1339 )";
1340 RUN(script, "");
1341
1342 // Open item preview.
1343 KEYS(clipboardBrowserId << "F7");
1344 RUN("preview", "true\n");
1345
1346 // Exercise the UI: select items back and forth to trigger menu rebuilds.
1347 auto exerciseUI = [&]{
1348 RUN("selectItems(0)", "true\n");
1349 RUN("selectItems(1)", "true\n");
1350 RUN("selectItems(0)", "true\n");
1351 RUN("selectItems(1)", "true\n");
1352 };
1353
1354 // Warm up: first pass may allocate lazy-init objects.
1355 exerciseUI();
1356
1357 // Capture baseline QObject count.
1358 QByteArray stdoutActual;
1359 QByteArray stderrActual;
1360 QCOMPARE( run(Args("stats"), &stdoutActual, &stderrActual), 0 );
1361 QVERIFY2( testStderr(stderrActual), stderrActual );
1362 const auto baseline = stdoutActual.split('\n').value(0);
1363 QVERIFY2( baseline.startsWith("TOTAL: "), baseline );
1364 const int baselineTotal = baseline.mid(7).trimmed().toInt();
1365 QVERIFY(baselineTotal > 0);
1366
1367 // Exercise the same UI interactions again.
1368 exerciseUI();
1369
1370 // Capture QObject count after second pass.
1371 QCOMPARE( run(Args("stats"), &stdoutActual, &stderrActual), 0 );
1372 QVERIFY2( testStderr(stderrActual), stderrActual );
1373 const auto after = stdoutActual.split('\n').value(0);
1374 QVERIFY2( after.startsWith("TOTAL: "), after );
1375 const int afterTotal = after.mid(7).trimmed().toInt();
1376
1377 QVERIFY2(
1378 afterTotal <= baselineTotal,
1379 QStringLiteral("QObject count grew from %1 to %2 — possible leak")
1380 .arg(baselineTotal).arg(afterTotal).toUtf8()
1381 );
1382 }
1383
1384 void CoreTests::statsItemPreview()
1385 {
1386 RUN("add" << "test_item", "");
1387
1388 const QByteArray previewItemLine =
1389 "/MainWindow/#dockWidgetItemPreview"
1390 "/#dockWidgetItemPreviewContents/QScrollArea#ClipboardBrowser"
1391 "/#item_preview/ItemText#item: 1";
1392
1393 QByteArray statsOutput;
1394 auto fetchStats = [&]() {
1395 QByteArray stderrActual;
1396 run(Args("stats"), &statsOutput, &stderrActual);
1397 };
1398 auto statsContainPreviewItem = [&]() {
1399 return statsOutput.split('\n').contains(previewItemLine);
1400 };
1401
1402 // Preview disabled — no preview item widget in stats.
1403 RUN("preview", "false\n");
1404 fetchStats();
1405 QVERIFY2(!statsContainPreviewItem(), statsOutput);
1406
1407 // Enable preview — item widget should appear.
1408 KEYS(clipboardBrowserId << "F7");
1409 RUN("preview", "true\n");
1410 fetchStats();
1411 QVERIFY2(statsContainPreviewItem(), statsOutput);
1412
1413 // Disable preview — item widget must be gone (not leaked).
1414 KEYS(clipboardBrowserId << "F7");
1415 RUN("preview", "false\n");
1416 fetchStats();
1417 QVERIFY2(!statsContainPreviewItem(), statsOutput);
1418 }
1419
1420
1421 void CoreTests::chainingCommands()
1422 {
1423 const auto tab1 = testTab(1);
1424 RUN("tab" << tab1 << "add" << "C" << "B" << "A", "");
1425 RUN("tab" << tab1 << "separator" << " " << "read" << "0" << "1" << "2", "A B C");
1426 RUN("tab" << tab1 << "separator" << "\\t" << "showAt" << "read" << "0" << "1" << "2", "A\tB\tC");
1427
1428 // Chain functions without arguments.
1429 RUN("enable" << "disable" << "monitoring", "false\n");
1430 RUN("if (!monitoring()) enable" << "monitoring", "true\n");
1431
1432 // Don't treat arguments after "eval" as functions.
1433 RUN("eval" << "arguments[1]" << "TEST", "TEST");
1434 RUN("eval" << "arguments[1]" << "--" << "TEST", "TEST");
1435 }
1436
1437 void CoreTests::insertRemoveItems()
1438 {
1439 const Args args = Args("tab") << testTab(1) << "separator" << ",";
1440
1441 RUN(args << "add" << "ghi" << "abc", "");
1442 RUN(args << "insert" << "1" << "def", "");
1443 RUN(args << "read" << "0" << "1" << "2" << "3" << "4", "abc,def,ghi,,");
1444
1445 RUN(args << "insert" << "0" << "012", "");
1446 RUN(args << "read" << "0" << "1" << "2" << "3" << "4", "012,abc,def,ghi,");
1447
1448 RUN(args << "remove" << "0" << "2", "");
1449 RUN(args << "read" << "0" << "1" << "2" << "3" << "4", "abc,ghi,,,");
1450
1451 QByteArray in("ABC");
1452 QCOMPARE( run(Args(args) << "insert" << "1" << "-", nullptr, nullptr, in), 0);
1453 RUN(args << "read" << "0" << "1" << "2" << "3" << "4", "abc,ABC,ghi,,");
1454 }
1455
1456 void CoreTests::handleUnexpectedTypes()
1457 {
1458 RUN("add(version)", "");
1459 RUN("add([version])", "");
1460 RUN("add({version: version})", "");
1461 }