/
QUnit.qm
2128 lines (1827 loc) · 75.1 KB
/
QUnit.qm
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
# -*- mode: qore; indent-tabs-mode: nil -*-
#! @file QUnit.qm Qore user module for automatic testing
%requires qore >= 0.9
%new-style
%try-module xml >= 1.3
%define NO_XML
%endtry
%no-child-restrictions
%allow-injection
%requires Util
module QUnit {
version = "0.4.1";
desc = "User module for unit testing with dependency injection support";
author = "Zdenek Behan <zdenek.behan@qoretechnologies.com>";
url = "http://qore.org";
license = "MIT";
}
/** @mainpage QUnit Module
@tableofcontents
@section qunitintro Introduction to the QUnit Module
The %QUnit module provides a framework for automated testing.
It contains base classes for creating test cases and test suites. It also provides a
dependency injection helper for mocking pre-existing classes without modifying their code.
It also provides a number of pre-defined testing functions for use in assertions.
<b>Examples:</b>
@code{.py}
#!/usr/bin/env qore
# -*- mode: qore; indent-tabs-mode: nil -*-
%new-style
%enable-all-warnings
%require-types
%strict-args
%requires ../../qlib/QUnit.qm
#%include ./_some_module_to_test
%exec-class QUnitTest
public class QUnitTest inherits QUnit::Test {
constructor() : Test("QUnitTest", "1.0") {
addTestCase("What this method is testing", \testMethod(), NOTHING);
addTestCase("Skipped test", \testSkipped(), NOTHING);
# Return for compatibility with test harness that checks return value.
set_return_value(main());
}
testMethod() {
# Test against success
testAssertion("success", \equals(), (True, True));
# Test against something else
testAssertion("failure", \equals(), (True, False), RESULT_FAILURE);
}
testSkipped() {
# Skip this test
testSkip("Because of the reason it skipped");
}
}
@endcode
@code{.py}
#!/usr/bin/env qore
# -*- mode: qore; indent-tabs-mode: nil -*-
%new-style
%enable-all-warnings
%require-types
%strict-args
%requires ../../qlib/QUnit.qm
#%include ./_MODULE_TO_TEST_
%exec-class MyTestClass
public class MyTestClass inherits QUnit::DependencyInjectedTest {
constructor() : DependencyInjectedTest("MyTestClass", "1.0") {
addTestCase("Test something", \testMethod(), NOTHING);
# Mandatory for injected tests
setScriptPath(get_script_path());
# Return for compatibility with test harness that checks return value.
set_return_value(main());
}
nothing performModuleInjections() {
#injectIntoModule("_MODULE_TO_INJECT_INTO_(same as _MODULE_TO_TEST_?)");
}
nothing performInjections(Program p) {
#p.importClass("_class_to_inject_", "_class_to_inject_into_", True);
}
testMethod() {
# Same test style as in TestExample.qtest
testAssertion("success", \equals(), (True, True));
}
}
@endcode
@subsection qunit_run Running tests
Tests are ran by simply executing the test script:
@verbatim
qore test.qtest [OPTIONS]
@endverbatim
A number of options is available, controlling the behaviour/output of the test
@subsection unittestformats Supported output formats of test reports
Currently the module provides the following output formats:
- plainquiet - human readable quiet format, prints only failures and a short summary at the end, which is also the default
- plaintext - human readable format, prints one statement per test
- junit - machine readable format for further processing
@section unittest_relnotes Release Notes
@subsection qunit_v0_4_1 Version 0.4.1
- allow tests to be nested
(<a href="https://github.com/qorelanguage/qore/issues/3306">issue 3306</a>)
@subsection qunit_v0_4 Version 0.4
- updated @ref QUnit::Test::testSkip() "Test::testSkip()" to use the reason argument a format string with
@ref Qore::vsprintf() "vsprintf()"
(<a href="https://github.com/qorelanguage/qore/issues/3172">issue 3172</a>)
- fixed error reporting with type errors with number values
(<a href="https://github.com/qorelanguage/qore/issues/2984">issue 2984</a>)
@subsection qunit_v0_3_3 Version 0.3.3
- improved output in assertion failures for strings with special whitespace and for multi-line data structures (<a href="https://github.com/qorelanguage/qore/issues/2680">issue 2680</a>)
@subsection qunit_v0_3_2 Version 0.3.2
- improved error location reporting by providing all stack location information up until the QUnit call to cover the case when multiple code layers are used such as one or more test modules (<a href="https://github.com/qorelanguage/qore/issues/1720">issue 1720</a>)
- overloaded testAssertionValue supports auto/number/float
- more verbose output when number/float difference is found
@subsection qunit_v0_3_1 Version 0.3.1
- added the following methods:
- @ref QUnit::Test::assertRegex()
- @ref QUnit::Test::assertNRegex()
- @ref QUnit::Test::assertNeq()
- @ref QUnit::Test::assertNeqSoft()
- @ref QUnit::Test::assertGt()
- @ref QUnit::Test::assertGtSoft()
- @ref QUnit::Test::assertGe()
- @ref QUnit::Test::assertGeSoft()
- @ref QUnit::Test::assertLt()
- @ref QUnit::Test::assertLtSoft()
- @ref QUnit::Test::assertLe()
- @ref QUnit::Test::assertLeSoft()
- @ref QUnit::Test::assertNothing()
@subsection qunit_v0_3 Version 0.3
- updated for complex types
@subsection qunit_v0_2 Version 0.2
- fixed showing the assertion location when there are test modules on top of QUnit.qm (<a href="https://github.com/qorelanguage/qore/issues/1046">issue 1046</a>)
@subsection qunit_v0_1 Version 0.1
- initial version of module
*/
#! the main namespace for all public definitions in the %QUnit module
public namespace QUnit;
#! An abstract class representing test result interface
public class QUnit::AbstractTestResult {
public {
string m_type;
*string m_subType;
auto m_value;
}
constructor(string type) {
m_type = type;
}
constructor(string type, string subType) {
m_type = type;
m_subType = subType;
}
# test
abstract public bool equals(AbstractTestResult r);
abstract public string toString();
}
#! Class representing boolean True
public class QUnit::TestResultSuccess inherits QUnit::AbstractTestResult {
constructor() : AbstractTestResult("True") {
}
#! Equality operator
public bool equals(QUnit::AbstractTestResult r) {
return r.m_type == "True";
}
public string toString() {
return "Success";
}
}
#! Class representing test function failure, both unspecific and with detail
public class QUnit::TestResultFailure inherits QUnit::AbstractTestResult {
private {
*string m_detail;
}
#! Instantiate an unspecific failure, no detail.
constructor() : AbstractTestResult("False") {
}
#! Instantiate an annotated failure, string detail.
constructor(string s) : AbstractTestResult("False") {
m_detail = s;
}
#! Equality operator
public bool equals(QUnit::AbstractTestResult r) {
# All failures are equal. Annotation is just for description. For structured errors, Exceptions should be used.
return r.m_type == "False";
}
public string toString() {
return "Failure" + (m_detail ? ": " + m_detail : "");
}
}
#! Class representing any non-boolean value
public class QUnit::TestResultValue inherits QUnit::AbstractTestResult {
constructor(auto value) : AbstractTestResult("Value") {
# treat NULL as NOTHING
if (value === NULL)
return;
m_value = value;
}
#! Equality operator
public bool equals(QUnit::AbstractTestResult r) {
return ((r.m_type == "Value") && (r.m_value === m_value));
}
public string toString() {
switch (m_value.typeCode()) {
case NT_LIST:
case NT_HASH:
case NT_BINARY:
return sprintf("%N", m_value);
}
return sprintf("%s: %N", m_value.type(), m_value);
}
}
#! Class representing a partial match of a hash value. Common keys have to be identical.
public class QUnit::TestResultPartialHashMatch inherits QUnit::AbstractTestResult {
constructor(hash value) : AbstractTestResult("PartialHashMatch") {
if (value == NULL)
return;
m_value = value;
}
public bool equals(QUnit::AbstractTestResult r) {
# Check type
if (r.m_type == "Value") {
# For Value results, only match against hashes. The others make no sense.
if (r.m_value.typeCode() != NT_HASH) {
return False;
}
} else if (!r.m_type == "PartialHashMatch") {
return False;
}
# All keys from this hash must be present in r and match.
foreach string key in (m_value.keyIterator()) {
if (!r.m_value.hasKey(key))
return False;
if (r.m_value{key} != m_value{key})
return False;
}
return True;
}
public string toString() {
return sprintf("Partial Hash match: %N", m_value);
}
}
#! Class representing Exception of a particular type
public class QUnit::TestResultExceptionType inherits QUnit::AbstractTestResult {
public {
#! corresponds to the \c "err" key of @ref Qore::ExceptionInfo "ExceptionInfo" (the first value of a @ref throw "throw statement")
string m_exceptionType;
}
#! creates the object from the exception arguments
/** @param exceptionType corresponds to the \c "err" key of @ref Qore::ExceptionInfo "ExceptionInfo" (the first value of a @ref throw "throw statement")
*/
constructor(string exceptionType) : AbstractTestResult("Exception") {
m_exceptionType = exceptionType;
}
#! private constructor for subclasses
private constructor(string exceptionType, string subType) : AbstractTestResult("Exception", subType) {
m_exceptionType = exceptionType;
}
#! Equality operator
public bool equals(QUnit::AbstractTestResult r) {
if (r.m_type != "Exception") {
return False;
}
QUnit::TestResultExceptionType e = r;
if (e.m_exceptionType != m_exceptionType) {
return False;
}
return True;
}
#! returns a string describing the exception type
public string toString() {
return sprintf("Exception: %s", m_exceptionType);
}
}
#! Class representing Exception of a particular type with a particular detail message
public class QUnit::TestResultExceptionDetail inherits QUnit::TestResultExceptionType {
private {
string m_exceptionDetail;
}
#! creates the object from the exception arguments
/** @param exceptionType corresponds to the \c "err" key of @ref Qore::ExceptionInfo "ExceptionInfo"
@param exceptionDetail corresponds to the \c "desc" key of @ref Qore::ExceptionInfo "ExceptionInfo"
*/
constructor(string exceptionType, string exceptionDetail) : TestResultExceptionType(exceptionType, "Detail") {
m_exceptionDetail = exceptionDetail;
}
#! Equality operator
public bool equals(QUnit::AbstractTestResult r) {
if (!TestResultExceptionType::equals(r)) {
return False;
}
if (r.m_subType == "Regexp") {
/* Ensure reflectiveness of regexp == operation.
Note that this will only work if this == Detail and r == Regexp, otherwise we could get into infinite recursion.
*/
return r.equals(self);
}
if (r.m_subType != "Detail") {
return False;
}
QUnit::TestResultExceptionDetail e = cast<QUnit::TestResultExceptionDetail>(r);
if (e.m_exceptionDetail != m_exceptionDetail) {
return False;
}
return True;
}
public string toString() {
return sprintf("Exception: %s: Detail '%s'", m_exceptionType, m_exceptionDetail);
}
string getDetail() {
return m_exceptionDetail;
}
}
#! Class representing Exception of a particular type and matching regexp for detail
public class QUnit::TestResultExceptionRegexp inherits QUnit::TestResultExceptionType {
private {
string m_exceptionRegexp;
}
constructor(string exceptionType, string exceptionRegexp) : TestResultExceptionType(exceptionType, "Regexp") {
m_exceptionRegexp = exceptionRegexp;
}
#! Equality operator
public bool equals(QUnit::AbstractTestResult r) {
if (!TestResultExceptionType::equals(r)) {
return False;
}
if (r.m_subType != "Detail") {
return False;
}
QUnit::TestResultExceptionDetail e = cast<QUnit::TestResultExceptionDetail>(r);
if (!e.getDetail().regex(m_exceptionRegexp)) {
return False;
}
return True;
}
public string toString() {
return sprintf("Exception: %s: Regexp '%s'", m_exceptionType, m_exceptionRegexp);
}
}
#! Class representing Exception of a particular type and substring for detail
public class QUnit::TestResultExceptionSubstring inherits QUnit::TestResultExceptionRegexp {
constructor(string exceptionType, string exceptionSubstring) : TestResultExceptionRegexp(exceptionType, exceptionSubstring) {
}
public string toString() {
return sprintf("Exception: %s: Substring '%s'", m_exceptionType, m_exceptionRegexp);
}
}
#! Class containing the configuration for a test case
public class QUnit::TestCase {
private {
#! the name of the test case
string m_name;
#! the body of the test case
code m_code;
#! arguments to the above callable object
*list<auto> m_args;
#! number of assertions in current test case
int num_asserts = 0;
#! number of successful assertions in current test case
int num_asserts_ok = 0;
#! number of skipped assertions in current test case
int num_asserts_skip = 0;
#! any saved test case
auto saved_tc;
}
#! creates the TestCase object from the given arguments
constructor(string name, code code, *softlist<auto> args) {
m_name = name;
m_code = code;
m_args = args;
}
#! runs the TestCase
run(QUnit::Test test) {
# Attempt to run the test function
try {
setupThread();
on_exit restoreThread();
# User code setup
test.setUp();
# User code cleanup
on_exit test.tearDown();
# Main test routine
call_function_args(m_code, m_args);
# Test success
test.addTestResult(self, TestReporter::TEST_SUCCESS);
} catch (hash<ExceptionInfo> e) {
checkException(test, e);
}
}
static list<string> getStackList(list stack, bool ok = False) {
list<string> l();
foreach hash callSite in (stack) {
if (callSite.file.val() && callSite.line != -1) {
if (callSite.file =~ /QUnit.qm$/) {
ok = True;
continue;
}
if (!ok)
continue;
string loc = callSite.file;
int ln = callSite.line + callSite.offset;
if (ln > 0)
loc += sprintf(":%d", ln);
# try to add function/method call name
if (*string f = stack[$# + 1].function)
loc = sprintf("%s [%s()]", loc, f);
l += loc;
}
}
return l;
}
static string getPos(hash<auto> ex) {
string pos = get_ex_pos(ex);
bool qunit = (pos =~ /QUnit\.qm/);
list<string> l = TestCase::getStackList(ex.callstack, qunit);
if (!qunit)
unshift l, pos;
return (foldl $1 + " <- " + $2, l) ?? "<unknown>";
}
#! handles exceptions raised while running the TestCase
checkException(QUnit::Test test, hash<auto> e) {
if (e.err =~ /TEST-.*EXCEPTION/) {
*string assertion_name = e.arg.name;
*string pos = e.arg.pos;
if (!pos)
pos = TestCase::getPos(e);
if (e.err == "TEST-SKIPPED-EXCEPTION") {
string txt = sprintf("Skip %srequested", assertion_name ? sprintf("of %y ", assertion_name) : NOTHING);
test.addTestResult(self, TestReporter::TEST_SKIPPED, txt, pos, e.desc);
} else if (e.err == "TEST-EXCEPTION") {
string txt = sprintf("Assertion %sfailure", assertion_name ? sprintf("%y ", assertion_name) : NOTHING);
test.addTestResult(self, TestReporter::TEST_FAILURE, txt, pos, e.desc);
}
} else {
# show little higher traceback record in this case
string pos = get_ex_pos(e);
string errtxt = sprintf("Unexpected exception: %s", e.err);
test.addTestResult(self, TestReporter::TEST_ERROR, errtxt, pos, get_exception_string(e));
}
}
#! returns the test case name
string getName() {
return m_name;
}
incAssertions() {
++num_asserts;
}
incAssertionsOk() {
++num_asserts_ok;
}
incAssertionsSkip() {
++num_asserts_skip;
}
int getAssertionCount() {
return num_asserts;
}
int getAssertionOkCount() {
return num_asserts_ok;
}
int getAssertionSkipCount() {
return num_asserts_skip;
}
setupThread() {
saved_tc = remove_thread_data("tc").tc;
save_thread_data("tc", self);
}
restoreThread() {
save_thread_data("tc", saved_tc);
}
#! renames the test case
rename(string n_name) {
m_name = n_name;
}
}
#! Base class for collecting test results and reporting
public class QUnit::TestReporter {
private {
const PLAINQUIET = 0;
const PLAIN = 1;
const JUNIT = 2;
const OUT_TYPES = (
"plainquiet" : PLAINQUIET,
"plain" : PLAIN,
"junit" : JUNIT,
);
const RESULT_TYPE_DESCRIPTION = (
TEST_SUCCESS : ("desc": "Success", "junittag" : NOTHING), # Success does not have a junit child tag
TEST_FAILURE : ("desc": "FAILURE", "junittag" : "failure"),
TEST_ERROR : ("desc": "ERROR", "junittag" : "error"),
TEST_SKIPPED : ("desc": "Skipped", "junittag" : "skipped"),
);
#! the default column offset for printing options used in printOption() and usageIntern()
const OffsetColumn = 20;
#! A map of print methods, categorised into three types: header, summary, testreport
hash m_printMethods;
list m_results = ();
int m_output;
*string m_comment;
#! the result of parsing command-line options with @ref Qore::GetOpt::parse2()
/** @see
- Opts
- constructor()
*/
hash m_options;
#! test case name
string m_name;
#! test case version
string m_version;
#! total number of assertions in script
int num_asserts = 0;
#! total number of successful assertions in script
int num_asserts_ok = 0;
#! total number of skipped assertions in script
int num_asserts_skip = 0;
}
public {
#! default options for @ref Qore::GetOpt::constructor()
const Opts = (
"help" : "h,help",
"verbose" : "v,verbose:i+",
"quiet" : "q,quiet",
"format" : "format=s",
);
const TEST_SUCCESS = 0;
const TEST_FAILURE = 1;
const TEST_ERROR = 2;
const TEST_SKIPPED = 3;
}
private printOption(string left, string right, int offset = OffsetColumn) {
printf(" %s", left);
int blanks = offset - left.size();
if (blanks > 0)
print(strmul(" ", blanks));
printf("%s\n", right);
}
private usageIntern(int offset = OffsetColumn) {
printf("usage: %s [options]\n", get_script_name());
printOption("-h,--help", "this help text", offset);
printOption(" --format=type", "output format [default: plainquiet]", offset);
print(" Format descriptions:
plainquiet only print failed tests and a summary at the end
plain print a status for each test performed
junit print a junit xml output\n");
printOption("-v,--verbose", "shorthand for --format=plain", offset);
printOption("-q,--quiet", "shorthand for --format=plainquiet", offset);
}
private usage() {
usageIntern();
exit(1);
}
private processOptions(reference<list<string>> p_argv) {
if (m_options.help)
usage();
if (m_options.verbose && m_options.quiet && m_options.format) {
printf("Please only select one format type\n");
exit(1);
}
if (p_argv) {
printf("Warning: excess arguments on command-line\n");
}
if (m_options.format) {
if (!exists OUT_TYPES{m_options.format})
throw "UNIT-TEST-ERROR", sprintf("Unknown output format: %s", m_options.format);
m_output = OUT_TYPES{m_options.format};
} else if (m_options.quiet) {
m_output = PLAINQUIET;
} else if (m_options.verbose) {
m_output = PLAIN;
} else {
# Default
m_output = PLAINQUIET;
}
}
#! creates the object from the arguments
/** @param name the name of the test
@param version the version of the test
@param p_argv an optional reference to a list of command-line arguments
@param opts the option hash to be passed to @ref Qore::GetOpt::constructor()
*/
constructor(string name, string version, *reference<list<string>> p_argv, hash opts = Opts) {
m_name = name;
m_version = version;
if (!p_argv)
p_argv = cast<list<string>>(ARGV);
m_options = new GetOpt(opts).parse2(\p_argv);
processOptions(\p_argv);
# A map of print methods, categorised into three types: header, summary, testreport
m_printMethods = (
PLAINQUIET: (
"header" : \self.printPlaintextHeader(),
"testreport" : \self.printPlaintextOneTest(),
"summary" : \self.printPlaintextSummary(),
),
PLAIN: (
"header" : \self.printPlaintextHeader(),
"testreport" : \self.printPlaintextOneTest(),
"summary" : \self.printPlaintextSummary(),
),
JUNIT: (
"summary" : \self.printJunitSummary(),
)
);
}
private callPrinterFunction(string type, *softlist<auto> args) {
*code c = m_printMethods{m_output}{type};
if (c) {
call_function_args(c, args);
}
}
private printHeader() { callPrinterFunction("header"); }
private printSummary() { callPrinterFunction("summary"); }
private printTestReport(hash testcase) { callPrinterFunction("testreport", testcase); }
private printPlaintextHeader() {
printf("QUnit Test %y v%s\n", m_name, m_version);
}
private printPlaintextSummary() {
int err = errors();
string serrors = sprintf(", %d error", err, err == 1 ? "" : "s");
string sskipped = sprintf(", %d skipped", skipped());
int succeeded = testCount() - errors() - skipped();
string ssucceeded = sprintf(", %d succeeded", succeeded);
string assert_str = sprintf(" (%d assertion%s", num_asserts, num_asserts == 1 ? "" : "s");
if (num_asserts != num_asserts_ok)
assert_str += sprintf(", %d succeeded", num_asserts_ok);
if (num_asserts_skip > 0)
assert_str += sprintf(", %d skipped", num_asserts_skip);
assert_str += ")";
int cnt = testCount();
printf("Ran %d test case%s%s%s%s%s\n", cnt, cnt == 1 ? "" : "s", succeeded > 0 ? ssucceeded : "", errors() > 0 ? serrors : "", skipped() > 0 ? sskipped : "", assert_str);
}
private printPlaintextOneTest(hash testcase) {
if (m_output == PLAINQUIET && (testcase.result == TEST_SUCCESS)) {
return;
}
string resultType = RESULT_TYPE_DESCRIPTION{testcase.result}{"desc"};
printf("%s: %s: %d assertion%s", resultType, testcase.testcase.getName(), testcase.testcase.getAssertionCount(), testcase.testcase.getAssertionCount() == 1 ? "" : "s");
if (testcase.testcase.getAssertionCount() != testcase.testcase.getAssertionOkCount())
printf(", %d succeeded", testcase.testcase.getAssertionOkCount());
if (testcase.testcase.getAssertionSkipCount() > 0)
printf(", %d skipped", testcase.testcase.getAssertionSkipCount());
print("\n");
if (testcase.result != TEST_SUCCESS) {
string out = "";
printf("%s at %s\n", testcase.error, testcase.pos);
ListIterator errorDescription(testcase.detail.split("\n"));
while (errorDescription.next()) {
out += sprintf("\t>> %s\n", errorDescription.getValue());
}
printf("-----\n%s-----\n", out);
}
}
private printJunitSummary() {
%ifdef NO_XML
stderr.printf("No XML module found. Use --format=plain instead.\n");
exit(1);
%else
hash junit;
junit.testsuites."^attributes^" = (
"name" : m_name,
"tests" : testCount(),
"errors" : errors(),
"skipped" : skipped(),
);
junit.testsuites.testcase = ();
ListIterator it(m_results);
while (it.next()) {
hash testcase;
testcase."^attributes^".name = it.getValue().testcase.getName();
string errmsg = sprintf("%s at %s:\n%s", it.getValue().error, it.getValue().pos, it.getValue().detail);
int status = it.getValue().result;
testcase."^attributes^"."status" = RESULT_TYPE_DESCRIPTION{status}.desc;
if (status != TEST_SUCCESS) {
string tag = RESULT_TYPE_DESCRIPTION{status}.junittag;
hash result = ("message" : errmsg, "type" : RESULT_TYPE_DESCRIPTION{status}.desc );
testcase{tag}."^attributes^" = result;
}
push junit."testsuites"."testcase", testcase;
}
printf("%s\n", make_xml(junit, XGF_ADD_FORMATTING));
%endif
}
#! returns the number of errors encountered during test execution
int errors() {
int errs = 0;
ListIterator it(m_results);
while (it.next()) {
if (!(TEST_SUCCESS: "", TEST_SKIPPED: "").hasKey(it.getValue(){"result"})) {
errs++;
}
}
return errs;
}
#! returns the number of tests skipped
int skipped() {
int errs = 0;
ListIterator it(m_results);
while (it.next()) {
if (!it.getValue(){"result"} == TEST_SKIPPED) {
errs++;
}
}
return errs;
}
#! returns the total number of test results
int testCount() {
return m_results.lsize();
}
#! adds a test result
addTestResult(TestCase tc, int success, *string error, *string pos, *string detail) {
if (!(RESULT_TYPE_DESCRIPTION.hasKey(success))) {
throw "TESTING-EXCEPTION", "Invalid test result type!";
}
hash testcase = ("testcase": tc, "result": success, "error": error, "pos": pos, "detail": detail);
printTestReport(testcase);
push m_results, testcase;
}
}
#! Base class representing a simple test, implements an implicit main() function and all utility functions for testing
public class QUnit::Test inherits QUnit::TestReporter {
private {
#! list of test cases
list<TestCase> testCases();
static QUnit::TestResultSuccess RESULT_SUCCESS = new QUnit::TestResultSuccess();
static QUnit::TestResultFailure RESULT_FAILURE = new QUnit::TestResultFailure();
}
private:internal {
#! equality comparitor
const QUC_EQ = "eq";
#! inequality comparitor
const QUC_NEQ = "neq";
#! greater than comparitor
const QUC_GT = "gt";
#! greater than or equals comparitor
const QUC_GE = "ge";
#! greater than comparitor
const QUC_LT = "lt";
#! greater than or equals comparitor
const QUC_LE = "le";
#! regex comparitor
const QUC_RE = "re";
#! negative regex comparitor
const QUC_NRE = "nre";
#! comparitor info
const QUC_Map = (
QUC_EQ: NOTHING,
QUC_NEQ: "Not Equal",
QUC_GT: "Greater Than",
QUC_GE: "Greater Than Or Equal To",
QUC_LT: "Less Than",
QUC_LE: "Less Than Or Equal To",
QUC_RE: "Regular Expression Match",
QUC_NRE: "Negative Regular Expression Match",
);
#! default epsilon for number/float comparison
const DEFAULT_EPSILON = 0.0000000001;
}
#! creates the object and sets the name of the test
constructor(string name, string version, *reference<list<string>> p_argv, *hash opts) : QUnit::TestReporter(name, version, \p_argv, opts) {
}
#! global setup; will be called once before tests are run
globalSetUp() {}
#! global tear down; will be called once after all tests are run
globalTearDown() {}
#! Prototype function for setting up test environment. It will be called for each test individually.
setUp() {}
#! Prototype function for cleaning up test environemnt. It will be called after each test has executed.
tearDown() {}
#! facade for the system environment variables
*string getEnv(string key, *string def) {
string ekey = sprintf("QUNIT_%s", key);
return ENV{ekey} ?? def;
}
#! adds a test case to run
/** @par Example:
@code{.py}
addTestCase("MyTest", \myTest());
@endcode
@param name the name of the test case
@param call the code to call that executes the test case
@param args any optional arguments to the test case call
*/
addTestCase(string name, code call, *softlist<auto> args) {
testCases += new TestCase(name, call, args);
}
#! adds a test case to run
/** @par Example:
@code{.py}
addTestCase(obj);
@endcode
@param tc the test case object
*/
addTestCase(QUnit::TestCase tc) {
testCases += tc;
}
private string escapeSpecialChars(string str) {
str = replace(str, "\b", "<\\b>");
str = replace(str, "\f", "<\\f>");
str = replace(str, "\n", "<\\n>");
str = replace(str, "\r", "<\\r>");
str = replace(str, "\t", "<\\t>");
str = replace(str, "\v", "<\\v>");
return str;
}
private bool diffInSpecialCharsOnly(string a, string b) {
a =~ s/[[:space:]]//;
a =~ s/[[:cntrl:]]//;
b =~ s/[[:space:]]//;
b =~ s/[[:cntrl:]]//;
return (a == b);
}
#! Helper function for printing out human-readable comparison of two values.
private string printUnexpectedData(auto exp, auto act, *bool neg, *bool soft_comparisons, *string comparitor) {
string comp = "Expected";
if (comparitor)
comp += " " + QUC_Map{comparitor};
else
comparitor = neg ? QUC_NEQ : QUC_EQ;
string expected;
string actual;
# if values are "soft equal", then they must have different types, so we make the type differences explicit here
if (!soft_comparisons && exp.typeCode() != act.typeCode()) {
bool done = False;
# if the values are strings that differ only in encodings, then show the encodings
if (exp.typeCode() == NT_STRING && act.typeCode() == NT_STRING && exp.encoding() != act.encoding() && exp.length() == act.length()) {
# in case of encoding errors, use exception handling
try {
string nact = convert_encoding(exp.encoding(), act);
if (exp === nact) {
done = True;
expected = sprintf("(string %y) %N", exp.encoding(), exp);
actual = neg ? "<identical>" : sprintf("(string %y) %N", act.encoding(), act);
}
} catch (hash<ExceptionInfo> ex) {
}
}
if (!done) {
switch (exp.typeCode()) {
case NT_NUMBER:
expected = sprintf("(%s) %N (%s)", exp.type(), exp, exp.toString(NF_Raw));
break;
case NT_FLOAT:
expected = sprintf("(%s) %N (%s)", exp.type(), exp, exp.toString());
break;
default:
expected = sprintf("(%s) %N", exp.type(), exp);
}
if (neg) {