rspamd/test/lua/unit/trie.lua

62 lines
1.5 KiB
Lua
Raw Normal View History

2015-04-07 16:04:10 +02:00
-- Trie search tests
context("Trie search functions", function()
local t = require "rspamd_trie"
2016-04-23 16:27:03 +02:00
local logger = require "rspamd_logger"
2018-03-30 15:44:59 +02:00
local patterns = {
'test',
'est',
'he',
'she',
'str\1ing'
2018-03-30 15:44:59 +02:00
}
local function comparetables(t1, t2)
if #t1 ~= #t2 then return false end
for i=1,#t1 do
if type(t1[i]) ~= type(t2[i]) then return false
elseif type(t1[i]) == 'table' then
if not comparetables(t1[i], t2[i]) then return false end
elseif t1[i] ~= t2[i] then
return false
2015-04-07 16:04:10 +02:00
end
end
2018-03-30 15:44:59 +02:00
return true
end
local trie = t.create(patterns)
2016-04-23 16:27:03 +02:00
2018-03-30 15:44:59 +02:00
local cases = {
{'test', true, {{4, 1}, {4, 2}}},
{'she test test', true, {{3, 4}, {3, 3}, {8, 1}, {8, 2}, {13, 1}, {13, 2}}},
{'non-existent', false},
{'str\1ing test', true, {{7, 5}, {12, 1}, {12, 2}}},
2018-03-30 15:44:59 +02:00
}
for i,c in ipairs(cases) do
test("Trie search " .. i, function()
2015-04-07 16:04:10 +02:00
local res = {}
local function cb(idx, pos)
table.insert(res, {pos, idx})
2016-04-23 16:27:03 +02:00
2015-04-07 16:04:10 +02:00
return 0
end
2016-04-23 16:27:03 +02:00
ret = trie:match(c[1], cb)
2016-04-23 16:27:03 +02:00
2015-04-07 16:04:10 +02:00
assert_equal(c[2], ret, tostring(c[2]) .. ' while matching ' .. c[1])
2016-04-23 16:27:03 +02:00
2015-04-07 16:04:10 +02:00
if ret then
2016-04-23 16:27:03 +02:00
table.sort(res, function(a, b) return a[2] > b[2] end)
table.sort(c[3], function(a, b) return a[2] > b[2] end)
2015-04-07 16:04:10 +02:00
local cmp = comparetables(res, c[3])
2016-04-23 16:27:03 +02:00
assert_true(cmp, 'valid results for case: ' .. c[1] ..
2018-03-30 15:44:59 +02:00
' got: ' .. logger.slog('%s', res) .. ' expected: ' ..
logger.slog('%s', c[3])
2016-04-23 16:27:03 +02:00
)
2015-04-07 16:04:10 +02:00
end
2018-03-30 15:44:59 +02:00
end)
end
2016-04-23 16:27:03 +02:00
end)