-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
luaunit.lua
3453 lines (2958 loc) · 124 KB
/
luaunit.lua
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
--[[
luaunit.lua
Description: A unit testing framework
Homepage: https://github.com/bluebird75/luaunit
Development by Philippe Fremy <phil@freehackers.org>
Based on initial work of Ryu, Gwang (http://www.gpgstudy.com/gpgiki/LuaUnit)
License: BSD License, see LICENSE.txt
]]--
require("math")
local M={}
-- private exported functions (for testing)
M.private = {}
M.VERSION='3.4'
M._VERSION=M.VERSION -- For LuaUnit v2 compatibility
-- a version which distinguish between regular Lua and LuaJit
M._LUAVERSION = (jit and jit.version) or _VERSION
--[[ Some people like assertEquals( actual, expected ) and some people prefer
assertEquals( expected, actual ).
]]--
M.ORDER_ACTUAL_EXPECTED = true
M.PRINT_TABLE_REF_IN_ERROR_MSG = false
M.LINE_LENGTH = 80
M.TABLE_DIFF_ANALYSIS_THRESHOLD = 10 -- display deep analysis for more than 10 items
M.LIST_DIFF_ANALYSIS_THRESHOLD = 10 -- display deep analysis for more than 10 items
-- this setting allow to remove entries from the stack-trace, for
-- example to hide a call to a framework which would be calling luaunit
M.STRIP_EXTRA_ENTRIES_IN_STACK_TRACE = 0
--[[ EPS is meant to help with Lua's floating point math in simple corner
cases like almostEquals(1.1-0.1, 1), which may not work as-is (e.g. on numbers
with rational binary representation) if the user doesn't provide some explicit
error margin.
The default margin used by almostEquals() in such cases is EPS; and since
Lua may be compiled with different numeric precisions (single vs. double), we
try to select a useful default for it dynamically. Note: If the initial value
is not acceptable, it can be changed by the user to better suit specific needs.
See also: https://en.wikipedia.org/wiki/Machine_epsilon
]]
M.EPS = 2^-52 -- = machine epsilon for "double", ~2.22E-16
if math.abs(1.1 - 1 - 0.1) > M.EPS then
-- rounding error is above EPS, assume single precision
M.EPS = 2^-23 -- = machine epsilon for "float", ~1.19E-07
end
-- set this to false to debug luaunit
local STRIP_LUAUNIT_FROM_STACKTRACE = true
M.VERBOSITY_DEFAULT = 10
M.VERBOSITY_LOW = 1
M.VERBOSITY_QUIET = 0
M.VERBOSITY_VERBOSE = 20
M.DEFAULT_DEEP_ANALYSIS = nil
M.FORCE_DEEP_ANALYSIS = true
M.DISABLE_DEEP_ANALYSIS = false
-- set EXPORT_ASSERT_TO_GLOBALS to have all asserts visible as global values
-- EXPORT_ASSERT_TO_GLOBALS = true
-- we need to keep a copy of the script args before it is overriden
local cmdline_argv = rawget(_G, "arg")
M.FAILURE_PREFIX = 'LuaUnit test FAILURE: ' -- prefix string for failed tests
M.SUCCESS_PREFIX = 'LuaUnit test SUCCESS: ' -- prefix string for successful tests finished early
M.SKIP_PREFIX = 'LuaUnit test SKIP: ' -- prefix string for skipped tests
M.USAGE=[[Usage: lua <your_test_suite.lua> [options] [testname1 [testname2] ... ]
Options:
-h, --help: Print this help
--version: Print version information
-v, --verbose: Increase verbosity
-q, --quiet: Set verbosity to minimum
-e, --error: Stop on first error
-f, --failure: Stop on first failure or error
-s, --shuffle: Shuffle tests before running them
-o, --output OUTPUT: Set output type to OUTPUT
Possible values: text, tap, junit, nil
-n, --name NAME: For junit only, mandatory name of xml file
-r, --repeat NUM: Execute all tests NUM times, e.g. to trig the JIT
-p, --pattern PATTERN: Execute all test names matching the Lua PATTERN
May be repeated to include several patterns
Make sure you escape magic chars like +? with %
-x, --exclude PATTERN: Exclude all test names matching the Lua PATTERN
May be repeated to exclude several patterns
Make sure you escape magic chars like +? with %
testname1, testname2, ... : tests to run in the form of testFunction,
TestClass or TestClass.testMethod
You may also control LuaUnit options with the following environment variables:
* LUAUNIT_OUTPUT: same as --output
* LUAUNIT_JUNIT_FNAME: same as --name ]]
----------------------------------------------------------------
--
-- general utility functions
--
----------------------------------------------------------------
--[[ Note on catching exit
I have seen the case where running a big suite of test cases and one of them would
perform a os.exit(0), making the outside world think that the full test suite was executed
successfully.
This is an attempt to mitigate this problem: we override os.exit() to now let a test
exit the framework while we are running. When we are not running, it behaves normally.
]]
M.oldOsExit = os.exit
os.exit = function(...)
if M.LuaUnit and #M.LuaUnit.instances ~= 0 then
local msg = [[You are trying to exit but there is still a running instance of LuaUnit.
LuaUnit expects to run until the end before exiting with a complete status of successful/failed tests.
To force exit LuaUnit while running, please call before os.exit (assuming lu is the luaunit module loaded):
lu.unregisterCurrentSuite()
]]
M.private.error_fmt(2, msg)
end
M.oldOsExit(...)
end
local function pcall_or_abort(func, ...)
-- unpack is a global function for Lua 5.1, otherwise use table.unpack
local unpack = rawget(_G, "unpack") or table.unpack
local result = {pcall(func, ...)}
if not result[1] then
-- an error occurred
print(result[2]) -- error message
print()
print(M.USAGE)
os.exit(-1)
end
return unpack(result, 2)
end
local crossTypeOrdering = {
number = 1, boolean = 2, string = 3, table = 4, other = 5
}
local crossTypeComparison = {
number = function(a, b) return a < b end,
string = function(a, b) return a < b end,
other = function(a, b) return tostring(a) < tostring(b) end,
}
local function crossTypeSort(a, b)
local type_a, type_b = type(a), type(b)
if type_a == type_b then
local func = crossTypeComparison[type_a] or crossTypeComparison.other
return func(a, b)
end
type_a = crossTypeOrdering[type_a] or crossTypeOrdering.other
type_b = crossTypeOrdering[type_b] or crossTypeOrdering.other
return type_a < type_b
end
local function __genSortedIndex( t )
-- Returns a sequence consisting of t's keys, sorted.
local sortedIndex = {}
for key,_ in pairs(t) do
table.insert(sortedIndex, key)
end
table.sort(sortedIndex, crossTypeSort)
return sortedIndex
end
M.private.__genSortedIndex = __genSortedIndex
local function sortedNext(state, control)
-- Equivalent of the next() function of table iteration, but returns the
-- keys in sorted order (see __genSortedIndex and crossTypeSort).
-- The state is a temporary variable during iteration and contains the
-- sorted key table (state.sortedIdx). It also stores the last index (into
-- the keys) used by the iteration, to find the next one quickly.
local key
--print("sortedNext: control = "..tostring(control) )
if control == nil then
-- start of iteration
state.count = #state.sortedIdx
state.lastIdx = 1
key = state.sortedIdx[1]
return key, state.t[key]
end
-- normally, we expect the control variable to match the last key used
if control ~= state.sortedIdx[state.lastIdx] then
-- strange, we have to find the next value by ourselves
-- the key table is sorted in crossTypeSort() order! -> use bisection
local lower, upper = 1, state.count
repeat
state.lastIdx = math.modf((lower + upper) / 2)
key = state.sortedIdx[state.lastIdx]
if key == control then
break -- key found (and thus prev index)
end
if crossTypeSort(key, control) then
-- key < control, continue search "right" (towards upper bound)
lower = state.lastIdx + 1
else
-- key > control, continue search "left" (towards lower bound)
upper = state.lastIdx - 1
end
until lower > upper
if lower > upper then -- only true if the key wasn't found, ...
state.lastIdx = state.count -- ... so ensure no match in code below
end
end
-- proceed by retrieving the next value (or nil) from the sorted keys
state.lastIdx = state.lastIdx + 1
key = state.sortedIdx[state.lastIdx]
if key then
return key, state.t[key]
end
-- getting here means returning `nil`, which will end the iteration
end
local function sortedPairs(tbl)
-- Equivalent of the pairs() function on tables. Allows to iterate in
-- sorted order. As required by "generic for" loops, this will return the
-- iterator (function), an "invariant state", and the initial control value.
-- (see http://www.lua.org/pil/7.2.html)
return sortedNext, {t = tbl, sortedIdx = __genSortedIndex(tbl)}, nil
end
M.private.sortedPairs = sortedPairs
-- seed the random with a strongly varying seed
math.randomseed(math.floor(os.clock()*1E11))
local function randomizeTable( t )
-- randomize the item orders of the table t
for i = #t, 2, -1 do
local j = math.random(i)
if i ~= j then
t[i], t[j] = t[j], t[i]
end
end
end
M.private.randomizeTable = randomizeTable
local function strsplit(delimiter, text)
-- Split text into a list consisting of the strings in text, separated
-- by strings matching delimiter (which may _NOT_ be a pattern).
-- Example: strsplit(", ", "Anna, Bob, Charlie, Dolores")
if delimiter == "" or delimiter == nil then -- this would result in endless loops
error("delimiter is nil or empty string!")
end
if text == nil then
return nil
end
local list, pos, first, last = {}, 1
while true do
first, last = text:find(delimiter, pos, true)
if first then -- found?
table.insert(list, text:sub(pos, first - 1))
pos = last + 1
else
table.insert(list, text:sub(pos))
break
end
end
return list
end
M.private.strsplit = strsplit
local function hasNewLine( s )
-- return true if s has a newline
return (string.find(s, '\n', 1, true) ~= nil)
end
M.private.hasNewLine = hasNewLine
local function prefixString( prefix, s )
-- Prefix all the lines of s with prefix
return prefix .. string.gsub(s, '\n', '\n' .. prefix)
end
M.private.prefixString = prefixString
local function strMatch(s, pattern, start, final )
-- return true if s matches completely the pattern from index start to index end
-- return false in every other cases
-- if start is nil, matches from the beginning of the string
-- if final is nil, matches to the end of the string
start = start or 1
final = final or string.len(s)
local foundStart, foundEnd = string.find(s, pattern, start, false)
return foundStart == start and foundEnd == final
end
M.private.strMatch = strMatch
local function patternFilter(patterns, expr)
-- Run `expr` through the inclusion and exclusion rules defined in patterns
-- and return true if expr shall be included, false for excluded.
-- Inclusion pattern are defined as normal patterns, exclusions
-- patterns start with `!` and are followed by a normal pattern
-- result: nil = UNKNOWN (not matched yet), true = ACCEPT, false = REJECT
-- default: true if no explicit "include" is found, set to false otherwise
local default, result = true, nil
if patterns ~= nil then
for _, pattern in ipairs(patterns) do
local exclude = pattern:sub(1,1) == '!'
if exclude then
pattern = pattern:sub(2)
else
-- at least one include pattern specified, a match is required
default = false
end
-- print('pattern: ',pattern)
-- print('exclude: ',exclude)
-- print('default: ',default)
if string.find(expr, pattern) then
-- set result to false when excluding, true otherwise
result = not exclude
end
end
end
if result ~= nil then
return result
end
return default
end
M.private.patternFilter = patternFilter
local function xmlEscape( s )
-- Return s escaped for XML attributes
-- escapes table:
-- " "
-- ' '
-- < <
-- > >
-- & &
return string.gsub( s, '.', {
['&'] = "&",
['"'] = """,
["'"] = "'",
['<'] = "<",
['>'] = ">",
} )
end
M.private.xmlEscape = xmlEscape
local function xmlCDataEscape( s )
-- Return s escaped for CData section, escapes: "]]>"
return string.gsub( s, ']]>', ']]>' )
end
M.private.xmlCDataEscape = xmlCDataEscape
local function lstrip( s )
--[[Return s with all leading white spaces and tabs removed]]
local idx = 0
while idx < s:len() do
idx = idx + 1
local c = s:sub(idx,idx)
if c ~= ' ' and c ~= '\t' then
break
end
end
return s:sub(idx)
end
M.private.lstrip = lstrip
local function extractFileLineInfo( s )
--[[ From a string in the form "(leading spaces) dir1/dir2\dir3\file.lua:linenb: msg"
Return the "file.lua:linenb" information
]]
local s2 = lstrip(s)
local firstColon = s2:find(':', 1, true)
if firstColon == nil then
-- string is not in the format file:line:
return s
end
local secondColon = s2:find(':', firstColon+1, true)
if secondColon == nil then
-- string is not in the format file:line:
return s
end
return s2:sub(1, secondColon-1)
end
M.private.extractFileLineInfo = extractFileLineInfo
local function stripLuaunitTrace2( stackTrace, errMsg )
--[[
-- Example of a traceback:
<<stack traceback:
example_with_luaunit.lua:130: in function 'test2_withFailure'
./luaunit.lua:1449: in function <./luaunit.lua:1449>
[C]: in function 'xpcall'
./luaunit.lua:1449: in function 'protectedCall'
./luaunit.lua:1508: in function 'execOneFunction'
./luaunit.lua:1596: in function 'runSuiteByInstances'
./luaunit.lua:1660: in function 'runSuiteByNames'
./luaunit.lua:1736: in function 'runSuite'
example_with_luaunit.lua:140: in main chunk
[C]: in ?>>
error message: <<example_with_luaunit.lua:130: expected 2, got 1>>
Other example:
<<stack traceback:
./luaunit.lua:545: in function 'assertEquals'
example_with_luaunit.lua:58: in function 'TestToto.test7'
./luaunit.lua:1517: in function <./luaunit.lua:1517>
[C]: in function 'xpcall'
./luaunit.lua:1517: in function 'protectedCall'
./luaunit.lua:1578: in function 'execOneFunction'
./luaunit.lua:1677: in function 'runSuiteByInstances'
./luaunit.lua:1730: in function 'runSuiteByNames'
./luaunit.lua:1806: in function 'runSuite'
example_with_luaunit.lua:140: in main chunk
[C]: in ?>>
error message: <<example_with_luaunit.lua:58: expected 2, got 1>>
<<stack traceback:
luaunit2/example_with_luaunit.lua:124: in function 'test1_withFailure'
luaunit2/luaunit.lua:1532: in function <luaunit2/luaunit.lua:1532>
[C]: in function 'xpcall'
luaunit2/luaunit.lua:1532: in function 'protectedCall'
luaunit2/luaunit.lua:1591: in function 'execOneFunction'
luaunit2/luaunit.lua:1679: in function 'runSuiteByInstances'
luaunit2/luaunit.lua:1743: in function 'runSuiteByNames'
luaunit2/luaunit.lua:1819: in function 'runSuite'
luaunit2/example_with_luaunit.lua:140: in main chunk
[C]: in ?>>
error message: <<luaunit2/example_with_luaunit.lua:124: expected 2, got 1>>
-- first line is "stack traceback": KEEP
-- next line may be luaunit line: REMOVE
-- next lines are call in the program under testOk: REMOVE
-- next lines are calls from luaunit to call the program under test: KEEP
-- Strategy:
-- keep first line
-- remove lines that are part of luaunit
-- kepp lines until we hit a luaunit line
The strategy for stripping is:
* keep first line "stack traceback:"
* part1:
* analyse all lines of the stack from bottom to top of the stack (first line to last line)
* extract the "file:line:" part of the line
* compare it with the "file:line" part of the error message
* if it does not match strip the line
* if it matches, keep the line and move to part 2
* part2:
* anything NOT starting with luaunit.lua is the interesting part of the stack trace
* anything starting again with luaunit.lua is part of the test launcher and should be stripped out
]]
local function isLuaunitInternalLine( s )
-- return true if line of stack trace comes from inside luaunit
return s:find('[/\\]luaunit%.lua:%d+: ') ~= nil
end
-- print( '<<'..stackTrace..'>>' )
local t = strsplit( '\n', stackTrace )
-- print( prettystr(t) )
local idx = 2
local errMsgFileLine = extractFileLineInfo(errMsg)
-- print('emfi="'..errMsgFileLine..'"')
-- remove lines that are still part of luaunit
while t[idx] and extractFileLineInfo(t[idx]) ~= errMsgFileLine do
-- print('Removing : '..t[idx] )
table.remove(t, idx)
end
-- keep lines until we hit luaunit again
while t[idx] and (not isLuaunitInternalLine(t[idx])) do
-- print('Keeping : '..t[idx] )
idx = idx + 1
end
-- remove remaining luaunit lines
while t[idx] do
-- print('Removing2 : '..t[idx] )
table.remove(t, idx)
end
-- print( prettystr(t) )
return table.concat( t, '\n')
end
M.private.stripLuaunitTrace2 = stripLuaunitTrace2
local function prettystr_sub(v, indentLevel, printTableRefs, cycleDetectTable )
local type_v = type(v)
if "string" == type_v then
-- use clever delimiters according to content:
-- enclose with single quotes if string contains ", but no '
if v:find('"', 1, true) and not v:find("'", 1, true) then
return "'" .. v .. "'"
end
-- use double quotes otherwise, escape embedded "
return '"' .. v:gsub('"', '\\"') .. '"'
elseif "table" == type_v then
--if v.__class__ then
-- return string.gsub( tostring(v), 'table', v.__class__ )
--end
return M.private._table_tostring(v, indentLevel, printTableRefs, cycleDetectTable)
elseif "number" == type_v then
-- eliminate differences in formatting between various Lua versions
if v ~= v then
return "#NaN" -- "not a number"
end
if v == math.huge then
return "#Inf" -- "infinite"
end
if v == -math.huge then
return "-#Inf"
end
if _VERSION == "Lua 5.3" then
local i = math.tointeger(v)
if i then
return tostring(i)
end
end
end
return tostring(v)
end
local function prettystr( v )
--[[ Pretty string conversion, to display the full content of a variable of any type.
* string are enclosed with " by default, or with ' if string contains a "
* tables are expanded to show their full content, with indentation in case of nested tables
]]--
local cycleDetectTable = {}
local s = prettystr_sub(v, 1, M.PRINT_TABLE_REF_IN_ERROR_MSG, cycleDetectTable)
if cycleDetectTable.detected and not M.PRINT_TABLE_REF_IN_ERROR_MSG then
-- some table contain recursive references,
-- so we must recompute the value by including all table references
-- else the result looks like crap
cycleDetectTable = {}
s = prettystr_sub(v, 1, true, cycleDetectTable)
end
return s
end
M.prettystr = prettystr
function M.adjust_err_msg_with_iter( err_msg, iter_msg )
--[[ Adjust the error message err_msg: trim the FAILURE_PREFIX or SUCCESS_PREFIX information if needed,
add the iteration message if any and return the result.
err_msg: string, error message captured with pcall
iter_msg: a string describing the current iteration ("iteration N") or nil
if there is no iteration in this test.
Returns: (new_err_msg, test_status)
new_err_msg: string, adjusted error message, or nil in case of success
test_status: M.NodeStatus.FAIL, SUCCESS or ERROR according to the information
contained in the error message.
]]
if iter_msg then
iter_msg = iter_msg..', '
else
iter_msg = ''
end
local RE_FILE_LINE = '.*:%d+: '
-- error message is not necessarily a string,
-- so convert the value to string with prettystr()
if type( err_msg ) ~= 'string' then
err_msg = prettystr( err_msg )
end
if (err_msg:find( M.SUCCESS_PREFIX ) == 1) or err_msg:match( '('..RE_FILE_LINE..')' .. M.SUCCESS_PREFIX .. ".*" ) then
-- test finished early with success()
return nil, M.NodeStatus.SUCCESS
end
if (err_msg:find( M.SKIP_PREFIX ) == 1) or (err_msg:match( '('..RE_FILE_LINE..')' .. M.SKIP_PREFIX .. ".*" ) ~= nil) then
-- substitute prefix by iteration message
err_msg = err_msg:gsub('.*'..M.SKIP_PREFIX, iter_msg, 1)
-- print("failure detected")
return err_msg, M.NodeStatus.SKIP
end
if (err_msg:find( M.FAILURE_PREFIX ) == 1) or (err_msg:match( '('..RE_FILE_LINE..')' .. M.FAILURE_PREFIX .. ".*" ) ~= nil) then
-- substitute prefix by iteration message
err_msg = err_msg:gsub(M.FAILURE_PREFIX, iter_msg, 1)
-- print("failure detected")
return err_msg, M.NodeStatus.FAIL
end
-- print("error detected")
-- regular error, not a failure
if iter_msg then
local match
-- "./test\\test_luaunit.lua:2241: some error msg
match = err_msg:match( '(.*:%d+: ).*' )
if match then
err_msg = err_msg:gsub( match, match .. iter_msg )
else
-- no file:line: infromation, just add the iteration info at the beginning of the line
err_msg = iter_msg .. err_msg
end
end
return err_msg, M.NodeStatus.ERROR
end
local function tryMismatchFormatting( table_a, table_b, doDeepAnalysis, margin )
--[[
Prepares a nice error message when comparing tables, performing a deeper
analysis.
Arguments:
* table_a, table_b: tables to be compared
* doDeepAnalysis:
M.DEFAULT_DEEP_ANALYSIS: (the default if not specified) perform deep analysis only for big lists and big dictionnaries
M.FORCE_DEEP_ANALYSIS : always perform deep analysis
M.DISABLE_DEEP_ANALYSIS: never perform deep analysis
* margin: supplied only for almost equality
Returns: {success, result}
* success: false if deep analysis could not be performed
in this case, just use standard assertion message
* result: if success is true, a multi-line string with deep analysis of the two lists
]]
-- check if table_a & table_b are suitable for deep analysis
if type(table_a) ~= 'table' or type(table_b) ~= 'table' then
return false
end
if doDeepAnalysis == M.DISABLE_DEEP_ANALYSIS then
return false
end
local len_a, len_b, isPureList = #table_a, #table_b, true
for k1, v1 in pairs(table_a) do
if type(k1) ~= 'number' or k1 > len_a then
-- this table a mapping
isPureList = false
break
end
end
if isPureList then
for k2, v2 in pairs(table_b) do
if type(k2) ~= 'number' or k2 > len_b then
-- this table a mapping
isPureList = false
break
end
end
end
if isPureList and math.min(len_a, len_b) < M.LIST_DIFF_ANALYSIS_THRESHOLD then
if not (doDeepAnalysis == M.FORCE_DEEP_ANALYSIS) then
return false
end
end
if isPureList then
return M.private.mismatchFormattingPureList( table_a, table_b, margin )
else
-- only work on mapping for the moment
-- return M.private.mismatchFormattingMapping( table_a, table_b, doDeepAnalysis )
return false
end
end
M.private.tryMismatchFormatting = tryMismatchFormatting
local function getTaTbDescr()
if not M.ORDER_ACTUAL_EXPECTED then
return 'expected', 'actual'
end
return 'actual', 'expected'
end
local function extendWithStrFmt( res, ... )
table.insert( res, string.format( ... ) )
end
local function mismatchFormattingMapping( table_a, table_b, doDeepAnalysis )
--[[
Prepares a nice error message when comparing tables which are not pure lists, performing a deeper
analysis.
Returns: {success, result}
* success: false if deep analysis could not be performed
in this case, just use standard assertion message
* result: if success is true, a multi-line string with deep analysis of the two lists
]]
-- disable for the moment
--[[
local result = {}
local descrTa, descrTb = getTaTbDescr()
local keysCommon = {}
local keysOnlyTa = {}
local keysOnlyTb = {}
local keysDiffTaTb = {}
local k, v
for k,v in pairs( table_a ) do
if is_equal( v, table_b[k] ) then
table.insert( keysCommon, k )
else
if table_b[k] == nil then
table.insert( keysOnlyTa, k )
else
table.insert( keysDiffTaTb, k )
end
end
end
for k,v in pairs( table_b ) do
if not is_equal( v, table_a[k] ) and table_a[k] == nil then
table.insert( keysOnlyTb, k )
end
end
local len_a = #keysCommon + #keysDiffTaTb + #keysOnlyTa
local len_b = #keysCommon + #keysDiffTaTb + #keysOnlyTb
local limited_display = (len_a < 5 or len_b < 5)
if math.min(len_a, len_b) < M.TABLE_DIFF_ANALYSIS_THRESHOLD then
return false
end
if not limited_display then
if len_a == len_b then
extendWithStrFmt( result, 'Table A (%s) and B (%s) both have %d items', descrTa, descrTb, len_a )
else
extendWithStrFmt( result, 'Table A (%s) has %d items and table B (%s) has %d items', descrTa, len_a, descrTb, len_b )
end
if #keysCommon == 0 and #keysDiffTaTb == 0 then
table.insert( result, 'Table A and B have no keys in common, they are totally different')
else
local s_other = 'other '
if #keysCommon then
extendWithStrFmt( result, 'Table A and B have %d identical items', #keysCommon )
else
table.insert( result, 'Table A and B have no identical items' )
s_other = ''
end
if #keysDiffTaTb ~= 0 then
result[#result] = string.format( '%s and %d items differing present in both tables', result[#result], #keysDiffTaTb)
else
result[#result] = string.format( '%s and no %sitems differing present in both tables', result[#result], s_other, #keysDiffTaTb)
end
end
extendWithStrFmt( result, 'Table A has %d keys not present in table B and table B has %d keys not present in table A', #keysOnlyTa, #keysOnlyTb )
end
local function keytostring(k)
if "string" == type(k) and k:match("^[_%a][_%w]*$") then
return k
end
return prettystr(k)
end
if #keysDiffTaTb ~= 0 then
table.insert( result, 'Items differing in A and B:')
for k,v in sortedPairs( keysDiffTaTb ) do
extendWithStrFmt( result, ' - A[%s]: %s', keytostring(v), prettystr(table_a[v]) )
extendWithStrFmt( result, ' + B[%s]: %s', keytostring(v), prettystr(table_b[v]) )
end
end
if #keysOnlyTa ~= 0 then
table.insert( result, 'Items only in table A:' )
for k,v in sortedPairs( keysOnlyTa ) do
extendWithStrFmt( result, ' - A[%s]: %s', keytostring(v), prettystr(table_a[v]) )
end
end
if #keysOnlyTb ~= 0 then
table.insert( result, 'Items only in table B:' )
for k,v in sortedPairs( keysOnlyTb ) do
extendWithStrFmt( result, ' + B[%s]: %s', keytostring(v), prettystr(table_b[v]) )
end
end
if #keysCommon ~= 0 then
table.insert( result, 'Items common to A and B:')
for k,v in sortedPairs( keysCommon ) do
extendWithStrFmt( result, ' = A and B [%s]: %s', keytostring(v), prettystr(table_a[v]) )
end
end
return true, table.concat( result, '\n')
]]
end
M.private.mismatchFormattingMapping = mismatchFormattingMapping
local function mismatchFormattingPureList( table_a, table_b, margin )
--[[
Prepares a nice error message when comparing tables which are lists, performing a deeper
analysis.
margin is supplied only for almost equality
Returns: {success, result}
* success: false if deep analysis could not be performed
in this case, just use standard assertion message
* result: if success is true, a multi-line string with deep analysis of the two lists
]]
local result, descrTa, descrTb = {}, getTaTbDescr()
local len_a, len_b, refa, refb = #table_a, #table_b, '', ''
if M.PRINT_TABLE_REF_IN_ERROR_MSG then
refa, refb = string.format( '<%s> ', M.private.table_ref(table_a)), string.format('<%s> ', M.private.table_ref(table_b) )
end
local longest, shortest = math.max(len_a, len_b), math.min(len_a, len_b)
local deltalv = longest - shortest
local commonUntil = shortest
for i = 1, shortest do
if not M.private.is_table_equals(table_a[i], table_b[i], margin) then
commonUntil = i - 1
break
end
end
local commonBackTo = shortest - 1
for i = 0, shortest - 1 do
if not M.private.is_table_equals(table_a[len_a-i], table_b[len_b-i], margin) then
commonBackTo = i - 1
break
end
end
table.insert( result, 'List difference analysis:' )
if len_a == len_b then
-- TODO: handle expected/actual naming
extendWithStrFmt( result, '* lists %sA (%s) and %sB (%s) have the same size', refa, descrTa, refb, descrTb )
else
extendWithStrFmt( result, '* list sizes differ: list %sA (%s) has %d items, list %sB (%s) has %d items', refa, descrTa, len_a, refb, descrTb, len_b )
end
extendWithStrFmt( result, '* lists A and B start differing at index %d', commonUntil+1 )
if commonBackTo >= 0 then
if deltalv > 0 then
extendWithStrFmt( result, '* lists A and B are equal again from index %d for A, %d for B', len_a-commonBackTo, len_b-commonBackTo )
else
extendWithStrFmt( result, '* lists A and B are equal again from index %d', len_a-commonBackTo )
end
end
local function insertABValue(ai, bi)
bi = bi or ai
if M.private.is_table_equals( table_a[ai], table_b[bi], margin) then
return extendWithStrFmt( result, ' = A[%d], B[%d]: %s', ai, bi, prettystr(table_a[ai]) )
else
extendWithStrFmt( result, ' - A[%d]: %s', ai, prettystr(table_a[ai]))
extendWithStrFmt( result, ' + B[%d]: %s', bi, prettystr(table_b[bi]))
end
end
-- common parts to list A & B, at the beginning
if commonUntil > 0 then
table.insert( result, '* Common parts:' )
for i = 1, commonUntil do
insertABValue( i )
end
end
-- diffing parts to list A & B
if commonUntil < shortest - commonBackTo - 1 then
table.insert( result, '* Differing parts:' )
for i = commonUntil + 1, shortest - commonBackTo - 1 do
insertABValue( i )
end
end
-- display indexes of one list, with no match on other list
if shortest - commonBackTo <= longest - commonBackTo - 1 then
table.insert( result, '* Present only in one list:' )
for i = shortest - commonBackTo, longest - commonBackTo - 1 do
if len_a > len_b then
extendWithStrFmt( result, ' - A[%d]: %s', i, prettystr(table_a[i]) )
-- table.insert( result, '+ (no matching B index)')
else
-- table.insert( result, '- no matching A index')
extendWithStrFmt( result, ' + B[%d]: %s', i, prettystr(table_b[i]) )
end
end
end
-- common parts to list A & B, at the end
if commonBackTo >= 0 then
table.insert( result, '* Common parts at the end of the lists' )
for i = longest - commonBackTo, longest do
if len_a > len_b then
insertABValue( i, i-deltalv )
else
insertABValue( i-deltalv, i )
end
end
end
return true, table.concat( result, '\n')
end
M.private.mismatchFormattingPureList = mismatchFormattingPureList
local function prettystrPairs(value1, value2, suffix_a, suffix_b)
--[[
This function helps with the recurring task of constructing the "expected
vs. actual" error messages. It takes two arbitrary values and formats
corresponding strings with prettystr().
To keep the (possibly complex) output more readable in case the resulting
strings contain line breaks, they get automatically prefixed with additional
newlines. Both suffixes are optional (default to empty strings), and get
appended to the "value1" string. "suffix_a" is used if line breaks were
encountered, "suffix_b" otherwise.
Returns the two formatted strings (including padding/newlines).
]]
local str1, str2 = prettystr(value1), prettystr(value2)
if hasNewLine(str1) or hasNewLine(str2) then
-- line break(s) detected, add padding
return "\n" .. str1 .. (suffix_a or ""), "\n" .. str2
end
return str1 .. (suffix_b or ""), str2
end
M.private.prettystrPairs = prettystrPairs
local UNKNOWN_REF = 'table 00-unknown ref'
local ref_generator = { value=1, [UNKNOWN_REF]=0 }
local function table_ref( t )
-- return the default tostring() for tables, with the table ID, even if the table has a metatable
-- with the __tostring converter
local ref = ''
local mt = getmetatable( t )
if mt == nil then
ref = tostring(t)
else
local success, result
success, result = pcall(setmetatable, t, nil)
if not success then
-- protected table, if __tostring is defined, we can
-- not get the reference. And we can not know in advance.
ref = tostring(t)
if not ref:match( 'table: 0?x?[%x]+' ) then
return UNKNOWN_REF
end
else
ref = tostring(t)
setmetatable( t, mt )
end
end
-- strip the "table: " part
ref = ref:sub(8)
if ref ~= UNKNOWN_REF and ref_generator[ref] == nil then
-- Create a new reference number
ref_generator[ref] = ref_generator.value
ref_generator.value = ref_generator.value+1
end
if M.PRINT_TABLE_REF_IN_ERROR_MSG then
return string.format('table %02d-%s', ref_generator[ref], ref)
else
return string.format('table %02d', ref_generator[ref])
end
end