From 736335b2086294d5bd77bff689f9b3cf1d7279b9 Mon Sep 17 00:00:00 2001 From: Jon Michael Aanes Date: Mon, 3 Apr 2017 16:39:19 +0200 Subject: [PATCH] Added check for bad options. --- pretty.lua | 23 +++++++++++++++++++++++ test/test_resilience.lua | 16 +++++++++++++++- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/pretty.lua b/pretty.lua index 0de84c6..8653637 100644 --- a/pretty.lua +++ b/pretty.lua @@ -505,11 +505,34 @@ end -------------------------------------------------------------------------------- +local KNOWN_OPTIONS = { + _all_function_info = 'boolean', + cut_strings = 'boolean', + include_closure = 'boolean', + indent = 'string', + math_shorthand = 'boolean', + max_depth = 'number', + more_function_info = 'boolean', + recursion = 'string', + short_builtins = 'boolean', +} + +local function ensure_that_all_options_are_known (options) + for option_name, option_value in pairs(options) do + if not KNOWN_OPTIONS[option_name] then + error(('[pretty]: Unknown option: %s. Was given value %s (%s)'):format(option_name, option_value, type(option_value)), 2) + elseif type(option_value) ~= KNOWN_OPTIONS[option_name] then + error(('[pretty]: Bad value given to option %s: %s (%s). Expected value of type %s'):format(option_name, option_value, type(option_value), KNOWN_OPTIONS[option_name]), 2) + end + end +end + local function pretty_format (value, options) local l = { visited = { next_mark = 1 } } l.options = options or {} l.options.max_depth = l.options.max_depth or math.huge l.options.indent = l.options.indent or '\t' + ensure_that_all_options_are_known(l.options) l.info = (type(value) == 'table') and analyze_structure(value) or {} format_value(value, nil, 0, l) diff --git a/test/test_resilience.lua b/test/test_resilience.lua index 121ed91..f6a8127 100644 --- a/test/test_resilience.lua +++ b/test/test_resilience.lua @@ -24,9 +24,23 @@ end local SUITE = require('TestSuite').new('resilience') SUITE:setEnviroment{ - setfenv = setfenv + pretty = require('pretty'), + setfenv = setfenv, } +-------------------------------------------------------------------------------- +-- Prevent usage of unknown options. + +SUITE:addTest('Dont allow unknown options', function () + local error_msg = bad_call(pretty, 'Hello World', { some_random_option = true }) + assert(error_msg) +end) + +SUITE:addTest('Dont allow bad types in options', function () + local error_msg = bad_call(pretty, 'Hello World', { max_depth = "hello world" }) + assert(error_msg) +end) + -------------------------------------------------------------------------------- SUITE:addTest('no_std_lib', function ()