From a0bd95aa3072f33b49d90e559bf81ef15446c846 Mon Sep 17 00:00:00 2001 From: RDW Date: Fri, 9 Feb 2024 19:10:52 +0100 Subject: [PATCH] Runtime: Streamline the transform library's input validation This code was copy/pasted from the previous iteration of the runtime, which didn't include a validation library. --- Runtime/Libraries/transform.lua | 12 ++++++------ Tests/BDD/transform-library.spec.lua | 12 +++++++++++- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/Runtime/Libraries/transform.lua b/Runtime/Libraries/transform.lua index ec8baaea6..ab50b1b73 100644 --- a/Runtime/Libraries/transform.lua +++ b/Runtime/Libraries/transform.lua @@ -1,3 +1,6 @@ +local validation = require("validation") +local validateString = validation.validateString + local transform = { ENABLE_TEXT_TRANSFORMATIONS = true, START_SEQUENCE = "\27[", @@ -52,9 +55,7 @@ function transform.disable() end function transform.strip(coloredConsoleText) - if type(coloredConsoleText) ~= "string" then - error("Usage: transform.strip(text : string)", 0) - end + validateString(coloredConsoleText, "coloredConsoleText") -- All credit goes to this fine gentleman: https://stackoverflow.com/users/3735873/tonypdmtr local strippedConsoleText = coloredConsoleText @@ -68,9 +69,8 @@ function transform.strip(coloredConsoleText) end local function transformText(text, color) - if type(text) ~= "string" then - error("Usage: transform." .. color .. "(text : string)", 0) - end + validateString(text, "text") + validateString(color, "color") if not transform.ENABLE_TEXT_TRANSFORMATIONS then return text diff --git a/Tests/BDD/transform-library.spec.lua b/Tests/BDD/transform-library.spec.lua index 2eed30fad..9c2f7b4e0 100644 --- a/Tests/BDD/transform-library.spec.lua +++ b/Tests/BDD/transform-library.spec.lua @@ -77,9 +77,13 @@ describe("transform", function() } for _, color in ipairs(supportedTerminalColors) do for _, invalidValue in ipairs(invalidValues) do + local actualType = type(invalidValue) assertThrows(function() transform[color](invalidValue) - end, "Usage: transform." .. color .. "(text : string)") + end, format( + "Expected argument text to be a string value, but received a %s value instead", + actualType + )) end end end) @@ -108,6 +112,12 @@ describe("transform", function() end) describe("strip", function() + it("should throw if a non-string value was passed", function() + assertThrows(function() + transform.strip(42) + end, "Expected argument coloredConsoleText to be a string value, but received a number value instead") + end) + it("should remove color codes from the input without otherwise modifying it", function() for name, transformation in pairs(transform) do if type(transformation) == "function" and transform.colorCodes[name] then