-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.lua
112 lines (90 loc) · 2.43 KB
/
test.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
require 'regex'
-- return the size of a table
function tablesize(t)
local size = 0;
for _ in pairs(t) do size = size + 1; end
return size;
end
-- return a table with the sorted keys of "t"
function getkeys(t)
-- get all the keys of "t" in the table "index"
local index = {}
for key in pairs(t) do table.insert(index, key) end
-- sort and return "index"
table.sort(index)
return index
end
-- return true if the table "gotten" contains the same elements
-- in the same order as the table "expected"
function correctresult(expected, gotten)
return writetable(expected) == writetable(gotten)
end
-- recursively parse a table into a string format
function writetable(t)
-- if t is a literal, just print it
if type(t) ~= 'table' then
if t == '' then return "''" end
return '' .. t
end
-- otherwise, t is a table
local s = "{"
local first = true
for _, key in ipairs(getkeys(t)) do
local toadd = writetable(t[key])
if not first then
toadd = ', ' .. toadd
end
s = s .. toadd
first = false
end
return s .. "}"
end
-- prints error message
function errormessage(input, expected, gotten)
return ("For input " .. input .. " the expected result was " .. expected .. " but we got " .. gotten)
end
local t = {}
function pattern(e)
table.insert (t, e)
end
local input = ({...})[1] or "sample.lua"
local f, e = loadfile(input)
if f then f() else error (e) end
-- for every regex in table t
for _, v in ipairs(t) do
-- the function we are going to test, match or find
local isfind = v.find
-- let's try to match several inputs
for _, vin in ipairs (v.input) do
local s = vin[1] -- the subject
local res = vin[2] -- the expected result
local n = true -- the result of the match
local erro = false
if isfind then
n = regex.find(v.p, s)
else
n = regex.match(v.p, s)
end
-- if the match returns nil, assign 0 or {} to n
if n == nil then
if type(res) == 'number' then
n = 0
elseif type(res) == 'table' then
n = {}
end
end
-- compare the expected result with what we got from regex.match()
if (type(res) == 'table') then
erro = not correctresult(res, n)
-- get the string representation of res and n
res = writetable(res)
n = writetable(n)
elseif (type(res) == 'number') and (res ~= n) then
erro = true
end
print('Res = ', n)
assert (not erro, errormessage(s, res, n))
print("")
end
print("")
end