You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

trie.lua 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. -- Trie search tests
  2. context("Trie search functions", function()
  3. local t = require "rspamd_trie"
  4. local logger = require "rspamd_logger"
  5. local patterns = {
  6. 'test',
  7. 'est',
  8. 'he',
  9. 'she',
  10. 'str\1ing'
  11. }
  12. local function comparetables(t1, t2)
  13. if #t1 ~= #t2 then return false end
  14. for i=1,#t1 do
  15. if type(t1[i]) ~= type(t2[i]) then return false
  16. elseif type(t1[i]) == 'table' then
  17. if not comparetables(t1[i], t2[i]) then return false end
  18. elseif t1[i] ~= t2[i] then
  19. return false
  20. end
  21. end
  22. return true
  23. end
  24. local trie = t.create(patterns)
  25. local cases = {
  26. {'test', true, {{4, 1}, {4, 2}}},
  27. {'she test test', true, {{3, 4}, {3, 3}, {8, 1}, {8, 2}, {13, 1}, {13, 2}}},
  28. {'non-existent', false},
  29. {'str\1ing test', true, {{7, 5}, {12, 1}, {12, 2}}},
  30. }
  31. for i,c in ipairs(cases) do
  32. test("Trie search " .. i, function()
  33. local res = {}
  34. local function cb(idx, pos)
  35. table.insert(res, {pos, idx})
  36. return 0
  37. end
  38. ret = trie:match(c[1], cb)
  39. assert_equal(c[2], ret, tostring(c[2]) .. ' while matching ' .. c[1])
  40. if ret then
  41. table.sort(res, function(a, b) return a[2] > b[2] end)
  42. table.sort(c[3], function(a, b) return a[2] > b[2] end)
  43. local cmp = comparetables(res, c[3])
  44. assert_true(cmp, 'valid results for case: ' .. c[1] ..
  45. ' got: ' .. logger.slog('%s', res) .. ' expected: ' ..
  46. logger.slog('%s', c[3])
  47. )
  48. end
  49. end)
  50. end
  51. end)