1-- Test zbase32 encoding/decoding
2
3context("Base32 encodning", function()
4  local ffi = require("ffi")
5  ffi.cdef[[
6    void ottery_rand_bytes(void *buf, size_t n);
7    unsigned ottery_rand_unsigned(void);
8    unsigned char* rspamd_decode_base32 (const char *in, size_t inlen, size_t *outlen, int how);
9    char * rspamd_encode_base32 (const unsigned char *in, size_t inlen, int how);
10    void g_free(void *ptr);
11    int memcmp(const void *a1, const void *a2, size_t len);
12  ]]
13
14  local function random_buf(max_size)
15    local l = ffi.C.ottery_rand_unsigned() % max_size + 1
16    local buf = ffi.new("unsigned char[?]", l)
17    ffi.C.ottery_rand_bytes(buf, l)
18
19    return buf, l
20  end
21
22  test("Base32 encode test", function()
23    local cases = {
24      {'test123', 'wm3g84fg13cy'},
25      {'hello', 'em3ags7p'}
26    }
27
28    for _,c in ipairs(cases) do
29      local b = ffi.C.rspamd_encode_base32(c[1], #c[1], 0)
30      local s = ffi.string(b)
31      ffi.C.g_free(b)
32      assert_equal(s, c[2], s .. " not equal " .. c[2])
33    end
34  end)
35
36  test("Base32 fuzz test", function()
37    for i = 1,1000 do
38      local b, l = random_buf(4096)
39      local how = math.floor(math.random(3) - 1)
40      local ben = ffi.C.rspamd_encode_base32(b, l, how)
41      local bs = ffi.string(ben)
42      local nl = ffi.new("size_t [1]")
43      local nb = ffi.C.rspamd_decode_base32(bs, #bs, nl, how)
44
45      local cmp = ffi.C.memcmp(b, nb, l)
46      ffi.C.g_free(ben)
47      ffi.C.g_free(nb)
48      assert_equal(cmp, 0, "fuzz test failed for length: " .. tostring(l))
49    end
50  end)
51end)