From 1798471fcdd3425e7d2bafbd69048ff1165eb31e Mon Sep 17 00:00:00 2001 From: Mark Pulford Date: Sun, 8 May 2011 23:34:17 +0930 Subject: Add test for excessive nesting during encode --- tests/common.lua | 17 +++++++++++------ tests/test.lua | 5 +++++ 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/tests/common.lua b/tests/common.lua index b8ce01d..63d37c0 100644 --- a/tests/common.lua +++ b/tests/common.lua @@ -29,7 +29,7 @@ function is_array(table) return max end -function serialise_table(value, indent) +function serialise_table(value, indent, depth) local spacing, spacing2, indent2 if indent then spacing = "\n" .. indent @@ -38,6 +38,10 @@ function serialise_table(value, indent) else spacing, spacing2, indent2 = " ", " ", false end + depth = depth + 1 + if depth > 50 then + return "ERROR: Too many nested tables" + end local max = is_array(value) @@ -49,7 +53,7 @@ function serialise_table(value, indent) if comma then table.insert(fragment, "," .. spacing2) end - table.insert(fragment, serialise_value(value[i], indent2)) + table.insert(fragment, serialise_value(value[i], indent2, depth)) comma = true end elseif max < 0 then @@ -59,8 +63,8 @@ function serialise_table(value, indent) table.insert(fragment, "," .. spacing2) end table.insert(fragment, string.format( - "[%s] = %s", serialise_value(k, indent2), - serialise_value(v, indent2)) + "[%s] = %s", serialise_value(k, indent2, depth), + serialise_value(v, indent2, depth)) ) comma = true end @@ -70,8 +74,9 @@ function serialise_table(value, indent) return table.concat(fragment) end -function serialise_value(value, indent) +function serialise_value(value, indent, depth) if indent == nil then indent = "" end + if depth == nil then depth = 0 end if value == cjson.null then return "cjson.null" @@ -81,7 +86,7 @@ function serialise_value(value, indent) type(value) == "boolean" then return tostring(value) elseif type(value) == "table" then - return serialise_table(value, indent) + return serialise_table(value, indent, depth) else return "\"<" .. type(value) .. ">\"" end diff --git a/tests/test.lua b/tests/test.lua index 436b20c..10d8989 100755 --- a/tests/test.lua +++ b/tests/test.lua @@ -63,6 +63,9 @@ if not utf8_loaded then end local utf16_escaped = gen_utf16_escaped() local nested5 = {{{{{ "nested" }}}}} +local table_cycle = {} +local table_cycle2 = { table_cycle } +table_cycle[1] = table_cycle2 local decode_simple_tests = { { json.decode, { '"test string"' }, true, { "test string" } }, @@ -124,6 +127,8 @@ local encode_table_tests = { { json.encode, { nested5 }, true, { '[ [ [ [ [ "nested" ] ] ] ] ]' } }, { json.encode, { { nested5 } }, + false, { "Cannot serialise, excessive nesting (6)" } }, + { json.encode, { table_cycle }, false, { "Cannot serialise, excessive nesting (6)" } } } -- cgit v1.2.3-55-g6feb