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