-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathgambiarra.lua
124 lines (107 loc) · 2.51 KB
/
gambiarra.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
local function TERMINAL_HANDLER(e, test, msg)
if e == 'pass' then
print("[32m✔[0m "..test..': '..msg)
elseif e == 'fail' then
print("[31m✘[0m "..test..': '..msg)
elseif e == 'except' then
print("[31m✘[0m "..test..': '..msg)
end
end
local function deepeq(a, b)
-- Different types: false
if type(a) ~= type(b) then return false end
-- Functions
if type(a) == 'function' then
return string.dump(a) == string.dump(b)
end
-- Primitives and equal pointers
if a == b then return true end
-- Only equal tables could have passed previous tests
if type(a) ~= 'table' then return false end
-- Compare tables field by field
for k,v in pairs(a) do
if b[k] == nil or not deepeq(v, b[k]) then return false end
end
for k,v in pairs(b) do
if a[k] == nil or not deepeq(v, a[k]) then return false end
end
return true
end
-- Compatibility for Lua 5.1 and Lua 5.2
local function args(...)
return {n=select('#', ...), ...}
end
local function spy(f)
local s = {}
setmetatable(s, {__call = function(s, ...)
s.called = s.called or {}
local a = args(...)
table.insert(s.called, {...})
if f then
local r
r = args(pcall(f, (unpack or table.unpack)(a, 1, a.n)))
if not r[1] then
s.errors = s.errors or {}
s.errors[#s.called] = r[2]
else
return (unpack or table.unpack)(r, 2, r.n)
end
end
end})
return s
end
return function(handler, env)
local pendingtests = {}
local function runpending()
if pendingtests[1] ~= nil then pendingtests[1](runpending) end
end
local function test(name, f, async)
local testfn = function(next)
local prev = {
ok = env.ok,
spy = env.spy,
eq = env.eq
}
local restore = function()
env.ok = prev.ok
env.spy = prev.spy
env.eq = prev.eq
env.gambiarrahandler('end', name)
table.remove(pendingtests, 1)
if next then next() end
end
local handler = env.gambiarrahandler
env.eq = deepeq
env.spy = spy
env.ok = function(cond, msg)
if cond then
handler('pass', name, msg)
else
handler('fail', name, msg)
end
end
handler('begin', name);
local ok, err = pcall(f, restore)
if not ok then
handler('except', name, err)
end
if not async then
handler('end', name);
env.ok = prev.ok;
env.spy = prev.spy;
env.eq = prev.eq;
end
end
if not async then
testfn()
else
table.insert(pendingtests, testfn)
if #pendingtests == 1 then
runpending()
end
end
end
env = env or _G
env.gambiarrahandler = handler or TERMINAL_HANDLER
env.test = test
end