From 61280e92f624ba90016a52e7ccc81ccc5035e461 Mon Sep 17 00:00:00 2001 From: Frank O'Brien Date: Tue, 5 Nov 2024 11:49:04 -0800 Subject: [PATCH] add runtime table type check, make table asserts take any, otherwise typechecking fails with metatables --- examples/tables.luau | 10 ++++++++++ src/assert_impl.luau | 17 +++++++++++++++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/examples/tables.luau b/examples/tables.luau index 9631323..e20ee54 100644 --- a/examples/tables.luau +++ b/examples/tables.luau @@ -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 }) diff --git a/src/assert_impl.luau b/src/assert_impl.luau index 7c97624..12b2874 100644 --- a/src/assert_impl.luau +++ b/src/assert_impl.luau @@ -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 @@ -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