forked from starwing/lua-protobuf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
luaunit.lua
2971 lines (2552 loc) · 105 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 <[email protected]>
Based on initial work of Ryu, Gwang (http://www.gpgstudy.com/gpgiki/LuaUnit)
License: BSD License, see LICENSE.txt
Version: 3.2
]]--
require("math")
local M={}
-- private exported functions (for testing)
M.private = {}
M.VERSION='3.3'
M._VERSION=M.VERSION -- For LuaUnit v2 compatibility
--[[ 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.TABLE_EQUALS_KEYBYCONTENT = true
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
--[[ 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.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
]]
local is_equal -- defined here to allow calling from mismatchFormattingPureList
----------------------------------------------------------------
--
-- general utility functions
--
----------------------------------------------------------------
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 == "" then -- this would result in endless loops
error("delimiter matches empty string!")
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 stripLuaunitTrace( stackTrace )
--[[
-- 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 ?>>
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 ?>>
<<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 ?>>
-- 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
]]
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
-- remove lines that are still part of luaunit
while t[idx] and isLuaunitInternalLine( t[idx] ) 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('Removing : '..t[idx] )
table.remove(t, idx)
end
-- print( prettystr(t) )
return table.concat( t, '\n')
end
M.private.stripLuaunitTrace = stripLuaunitTrace
local function prettystr_sub(v, indentLevel, printTableRefs, recursionTable )
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, recursionTable)
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 recursionTable = {}
local s = prettystr_sub(v, 1, M.PRINT_TABLE_REF_IN_ERROR_MSG, recursionTable)
if recursionTable.recursionDetected 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
recursionTable = {}
s = prettystr_sub(v, 1, true, recursionTable)
end
return s
end
M.prettystr = prettystr
local function tryMismatchFormatting( table_a, table_b, doDeepAnalysis )
--[[
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
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 )
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 )
--[[
Prepares a nice error message when comparing tables which are 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
]]
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> ', tostring(table_a)), string.format('<%s> ', tostring(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 is_equal(table_a[i], table_b[i]) then
commonUntil = i - 1
break
end
end
local commonBackTo = shortest - 1
for i = 0, shortest - 1 do
if not is_equal(table_a[len_a-i], table_b[len_b-i]) 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 is_equal( table_a[ai], table_b[bi]) 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 function _table_raw_tostring( t )
-- return the default tostring() for tables, with the table ID, even if the table has a metatable
-- with the __tostring converter
local mt = getmetatable( t )
if mt then setmetatable( t, nil ) end
local ref = tostring(t)
if mt then setmetatable( t, mt ) end
return ref
end
M.private._table_raw_tostring = _table_raw_tostring
local TABLE_TOSTRING_SEP = ", "
local TABLE_TOSTRING_SEP_LEN = string.len(TABLE_TOSTRING_SEP)
local function _table_tostring( tbl, indentLevel, printTableRefs, recursionTable )
printTableRefs = printTableRefs or M.PRINT_TABLE_REF_IN_ERROR_MSG
recursionTable = recursionTable or {}
recursionTable[tbl] = true
local result, dispOnMultLines = {}, false
-- like prettystr but do not enclose with "" if the string is just alphanumerical
-- this is better for displaying table keys who are often simple strings
local function keytostring(k)
if "string" == type(k) and k:match("^[_%a][_%w]*$") then
return k
end
return prettystr_sub(k, indentLevel+1, printTableRefs, recursionTable)
end
local mt = getmetatable( tbl )
if mt and mt.__tostring then
-- if table has a __tostring() function in its metatable, use it to display the table
-- else, compute a regular table
result = strsplit( '\n', tostring(tbl) )
return M.private._table_tostring_format_multiline_string( result, indentLevel )
else
-- no metatable, compute the table representation
local entry, count, seq_index = nil, 0, 1
for k, v in sortedPairs( tbl ) do
-- key part
if k == seq_index then
-- for the sequential part of tables, we'll skip the "<key>=" output
entry = ''
seq_index = seq_index + 1
elseif recursionTable[k] then
-- recursion in the key detected
recursionTable.recursionDetected = true
entry = "<".._table_raw_tostring(k)..">="
else
entry = keytostring(k) .. "="
end
-- value part
if recursionTable[v] then
-- recursion in the value detected!
recursionTable.recursionDetected = true
entry = entry .. "<".._table_raw_tostring(v)..">"
else
entry = entry ..
prettystr_sub( v, indentLevel+1, printTableRefs, recursionTable )
end
count = count + 1
result[count] = entry
end
return M.private._table_tostring_format_result( tbl, result, indentLevel, printTableRefs )
end
end
M.private._table_tostring = _table_tostring -- prettystr_sub() needs it
local function _table_tostring_format_multiline_string( tbl_str, indentLevel )
local indentString = '\n'..string.rep(" ", indentLevel - 1)
return table.concat( tbl_str, indentString )
end
M.private._table_tostring_format_multiline_string = _table_tostring_format_multiline_string
local function _table_tostring_format_result( tbl, result, indentLevel, printTableRefs )
-- final function called in _table_to_string() to format the resulting list of
-- string describing the table.
local dispOnMultLines = false
-- set dispOnMultLines to true if the maximum LINE_LENGTH would be exceeded with the values
local totalLength = 0
for k, v in ipairs( result ) do
totalLength = totalLength + string.len( v )
if totalLength >= M.LINE_LENGTH then
dispOnMultLines = true
break
end
end
-- set dispOnMultLines to true if the max LINE_LENGTH would be exceeded
-- with the values and the separators.
if not dispOnMultLines then
-- adjust with length of separator(s):
-- two items need 1 sep, three items two seps, ... plus len of '{}'
if #result > 0 then
totalLength = totalLength + TABLE_TOSTRING_SEP_LEN * (#result - 1)
end
dispOnMultLines = (totalLength + 2 >= M.LINE_LENGTH)
end
-- now reformat the result table (currently holding element strings)
if dispOnMultLines then
local indentString = string.rep(" ", indentLevel - 1)
result = {
"{\n ",
indentString,
table.concat(result, ",\n " .. indentString),
"\n",
indentString,
"}"
}
else
result = {"{", table.concat(result, TABLE_TOSTRING_SEP), "}"}
end
if printTableRefs then
table.insert(result, 1, "<".._table_raw_tostring(tbl).."> ") -- prepend table ref
end
return table.concat(result)
end
M.private._table_tostring_format_result = _table_tostring_format_result -- prettystr_sub() needs it
local function _table_contains(t, element)
if type(t) == "table" then
local type_e = type(element)
for _, value in pairs(t) do
if type(value) == type_e then
if value == element then
return true
end
if type_e == 'table' then
-- if we wanted recursive items content comparison, we could use
-- _is_table_items_equals(v, expected) but one level of just comparing
-- items is sufficient
if M.private._is_table_equals( value, element ) then
return true
end
end
end
end
end
return false
end
local function _is_table_items_equals(actual, expected )
local type_a, type_e = type(actual), type(expected)
if (type_a == 'table') and (type_e == 'table') then
for k, v in pairs(actual) do
if not _table_contains(expected, v) then
return false
end
end
for k, v in pairs(expected) do
if not _table_contains(actual, v) then
return false
end
end
return true
elseif type_a ~= type_e then
return false
elseif actual ~= expected then
return false
end
return true
end
--[[
This is a specialized metatable to help with the bookkeeping of recursions
in _is_table_equals(). It provides an __index table that implements utility
functions for easier management of the table. The "cached" method queries
the state of a specific (actual,expected) pair; and the "store" method sets
this state to the given value. The state of pairs not "seen" / visited is
assumed to be `nil`.
]]
local _recursion_cache_MT = {
__index = {
-- Return the cached value for an (actual,expected) pair (or `nil`)
cached = function(t, actual, expected)
local subtable = t[actual] or {}
return subtable[expected]
end,
-- Store cached value for a specific (actual,expected) pair.
-- Returns the value, so it's easy to use for a "tailcall" (return ...).
store = function(t, actual, expected, value, asymmetric)
local subtable = t[actual]
if not subtable then