Add cc.expect.range (#790)

This commit is contained in:
Lupus590 2021-05-17 17:49:48 +01:00 committed by GitHub
parent 953b94fd08
commit 28165bfcd6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 48 additions and 0 deletions

View File

@ -88,7 +88,34 @@ local function field(tbl, index, ...)
end
end
local function is_nan(num)
return num ~= num
end
--- Expect a number to be within a specific range.
--
-- @tparam number num, The value to check.
-- @tparam number min The minimum value, if nil then `-math.huge` is used.
-- @tparam number max The maximum value, if nil then `math.huge` is used.
-- @return The given `value`.
-- @throws If the value is outside of the allowed range.
local function range(num, min, max)
expect(1, num, "number")
min = expect(2, min, "number", "nil") or -math.huge
max = expect(3, max, "number", "nil") or math.huge
if min > max then
error("min must be less than or equal to max)", 2)
end
if is_nan(num) or num < min or num > max then
error(("number outside of range (expected %s to be within %s and %s)"):format(num, min, max), 3)
end
return num
end
return {
expect = expect,
field = field,
range = range,
}

View File

@ -50,4 +50,25 @@ describe("cc.expect", function()
:eq("bad field 'l' (expected string, table or number, got boolean)")
end)
end)
describe("range", function()
it("works fith full args", function()
expect(e.range(1, 1, 1)):eq(1)
expect(e.range(2, 1, 3)):eq(2)
expect.error(e.range, 2, 0, 1):eq("number outside of range (expected 2 to be within 0 and 1)")
expect.error(e.range, 0, 1, 2):eq("number outside of range (expected 0 to be within 1 and 2)")
local NaN = 0 / 0
expect.error(e.range, NaN, 1, 2):eq(("number outside of range (expected %s to be within 1 and 2)"):format(tostring(NaN)))
end)
it("fills in min and max if they are nil", function()
expect(e.range(1, 1)):eq(1)
expect(e.range(2, nil, 3)):eq(2)
expect(e.range(2)):eq(2)
expect.error(e.range, 2, nil, 1):eq("number outside of range (expected 2 to be within -inf and 1)")
expect.error(e.range, 0, 1):eq("number outside of range (expected 0 to be within 1 and inf)")
end)
end)
end)