added some explanation
[mime-lua.git] / test.lua
blob2bb6487efe00228af87cde5e37007f807a3dccdd
1 #!/usr/bin/lua
3 require 'my'
4 require 'lpeg'
6 local gr = dofile'mime.lua'
8 local match = function (s, r, c)
9 c= c or s
10 local ret = { string = s, rule = r, match = true, capture = c }
11 return ret
12 end
14 local tests = {
15 { string = '\r\n ', rule = 'FWS', match = true, capture = ' ' },
16 { string = '"rrr\r\n aaa"', rule ='quoted-string', match = true, capture = 'rrr aaa'},
17 { string = '(some stupid @(comment) \\( ** \r\n )', rule ='comment', match = true, capture = ' '},
18 { string = 'single_atom_1', rule ='atom', match = true, capture = 'single_atom_1'},
19 { string = '2nd{atom}2', rule ='atom', match = true, capture = '2nd{atom}2'},
20 { string = '2nd{atom}2.&checking!', rule ='dot-atom', match = true, capture = '2nd{atom}2.&checking!'},
21 { string = '\r\n (another comment ) \t\r\n (id %(crmnr) \\( ** \r\n ) ', rule ='CFWS', match = true, capture = ' '},
22 { string = '()', rule ='CFWS', match = true, capture = ' '},
23 { string = 'Icanwrite"a \r\n simple"phrase', rule ='phrase', match = true},
24 { string = 'Thu, 2\r\n Apr 2009 14:36:04 +0000', rule ='date-time', match = true, capture='Thu, 2 Apr 2009 14:36:04 +0000'},
25 { string = '(a CFWS) \r\n (that ends here)[ 127.0.0.1:8888 oooo]', rule ='domain-literal', match = true, },
26 { string = 'mauro.iazzi@gmail.com', rule ='address', match = true, },
27 { string = '"Mauro Iazzi" <mauro.iazzi@gmail.com>', rule ='address', match = true, },
30 local dee = function (...)
31 --print(...)
32 return ...
33 end
35 local gather = function (...)
36 local n = select('#', ...)
37 return n==1 and ... or { ... }
38 end
40 for i, t in ipairs(tests) do
41 local s, r, m, c = t.string, t.rule, t.match, t.capture
42 gr[1] = (lpeg.V(r)) / gather * lpeg.Cp()
43 local patt = lpeg.P(gr)
44 print('performing test ' .. i .. ' on rule ' .. r)
45 local ret, n = dee(patt:match(s))
46 if m then
47 assert(ret, 'test '..i..' failed by not matching a conforming string')
48 assert(n==#s+1, 'test '..i..' failed by not matching the full string (match was '..string.sub(s, 1, n-1)..')')
49 if c then
50 assert(ret==c, 'test '..i..' failed by returning the wrong capture '..ret..' instead of '..c)
51 end
52 else
53 assert(ret==nil, 'test '..i..' failed by matching a wrong string')
54 end
55 end