Skip to content

Commit

Permalink
add runtime table type check, make table asserts take any, otherwise …
Browse files Browse the repository at this point in the history
…typechecking fails with metatables
  • Loading branch information
itsfrank committed Nov 5, 2024
1 parent d464baf commit 61280e9
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
10 changes: 10 additions & 0 deletions examples/tables.luau
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,16 @@ return function()
check.table.equal(a, b)
end)

test.case("table-ness is checked at runtime", function()
local not_table = "str"
local a = { a = 1, b = 2 }

-- passing non-tables will fail the assertion with helpful message
check.table.contains(not_table, "a")
check.table.equal(a, not_table)
check.table.equal(not_table, a)
end)

test.case("metatables aren't considered", function()
-- these 2 tables are equal, even though their MTs are different
local a = setmetatable({ a = 10 }, { foo = function() end, b = 10 })
Expand Down
17 changes: 15 additions & 2 deletions src/assert_impl.luau
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,12 @@ end

-- table assertions

function assert_impl.table_contains(t: { [any]: any }, keys: any | { [number]: any }): Failure?
function assert_impl.table_contains(t: any, keys: any | { [number]: any }): Failure?
-- ensure input is a tables
if typeof(t) ~= "table" then
return make_failure(`type of arg 1 is {typeof(t)}, expected a table`)
end

if type(keys) ~= "table" then
keys = { keys }
end
Expand All @@ -202,7 +207,15 @@ function assert_impl.table_contains(t: { [any]: any }, keys: any | { [number]: a
end

local ltdiff = require("./lib/ltdiff")
function assert_impl.table_equal(a: { [any]: any }, b: { [any]: any }): Failure?
function assert_impl.table_equal(a: any, b: any): Failure?
-- ensure inputs are tables
if typeof(a) ~= "table" then
return make_failure(`type of arg 1 is {typeof(a)}, expected a table`)
end
if typeof(b) ~= "table" then
return make_failure(`type of arg 2 is {typeof(b)}, expected a table`)
end

-- convert ltdiff into our diff format
local function ltdiff_to_frkdiff(lt_diff: ltdiff.Diff): (boolean, TableDiff)
local has_diff = false
Expand Down

0 comments on commit 61280e9

Please sign in to comment.