Fix patching value with nil

develop
lethosor 2021-04-09 00:35:54 -04:00
parent 7b2f01d45b
commit f25b8a0d14
No known key found for this signature in database
GPG Key ID: 76A269552F4F58C1
2 changed files with 57 additions and 10 deletions

@ -5,15 +5,15 @@ local mock = mkmodule('test_util.mock')
Usage: Usage:
patch(table, key, value, callback) patch(table, key, value, callback)
patch({ patch({
[{table, key}] = value, {table, key, value},
[{table2, key2}] = value2 {table2, key2, value2}
}, callback) }, callback)
]] ]]
function mock.patch(...) function mock.patch(...)
local args = {...} local args = {...}
if #args == 4 then if #args == 4 then
args = {{ args = {{
[{args[1], args[2]}] = args[3] {args[1], args[2], args[3]}
}, args[4]} }, args[4]}
end end
if #args ~= 2 then if #args ~= 2 then
@ -22,15 +22,15 @@ function mock.patch(...)
local callback = args[2] local callback = args[2]
local patches = {} local patches = {}
for k, v in pairs(args[1]) do for _, v in ipairs(args[1]) do
local p = { local p = {
table = k[1], table = v[1],
key = k[2], key = v[2],
new_value = v, new_value = v[3],
} }
p.old_value = p.table[p.key] p.old_value = p.table[p.key]
-- no-op to ensure that the value can be restored by the finalizer below -- no-op to ensure that the value can be restored by the finalizer below
p.table[p.key] = p.table[p.key] p.table[p.key] = p.old_value
table.insert(patches, p) table.insert(patches, p)
end end

@ -33,8 +33,8 @@ function test.patch_multiple()
expect.eq(test_table.func1(), 1) expect.eq(test_table.func1(), 1)
expect.eq(test_table.func2(), 2) expect.eq(test_table.func2(), 2)
mock.patch({ mock.patch({
[{test_table, 'func1'}] = function() return 3 end, {test_table, 'func1', function() return 3 end},
[{test_table, 'func2'}] = function() return 4 end, {test_table, 'func2', function() return 4 end},
}, function() }, function()
expect.eq(test_table.func1(), 3) expect.eq(test_table.func1(), 3)
expect.eq(test_table.func2(), 4) expect.eq(test_table.func2(), 4)
@ -43,3 +43,50 @@ function test.patch_multiple()
expect.eq(test_table.func2(), 2) expect.eq(test_table.func2(), 2)
end end
function test.patch_nil_old_value()
local t = {}
mock.patch(t, 1, 2, function()
expect.eq(t[1], 2)
end)
expect.eq(t[1], nil)
expect.eq(#t, 0)
end
function test.patch_nil_new_value()
local t = {2}
mock.patch(t, 1, nil, function()
expect.eq(t[1], nil)
expect.eq(#t, 0)
end)
expect.eq(t[1], 2)
end
function test.patch_nil_key()
local called = false
expect.error_match('table index is nil', function()
mock.patch({}, nil, 'value', function()
called = true
end)
end)
expect.false_(called)
end
function test.patch_nil_table()
local called = false
expect.error(function()
mock.patch(nil, 1, 2, function()
called = true
end)
end)
expect.false_(called)
end
function test.patch_complex_key()
local key = {'key'}
local t = {[key] = 'value'}
expect.eq(t[key], 'value')
mock.patch(t, key, 2, function()
expect.eq(t[key], 2)
end)
expect.eq(t[key], 'value')
end