Skip to content

Commit

Permalink
Add specs for GC
Browse files Browse the repository at this point in the history
  • Loading branch information
davidor committed Jun 26, 2018
1 parent b74cd51 commit 0376099
Showing 1 changed file with 98 additions and 0 deletions.
98 changes: 98 additions & 0 deletions spec/gc_spec.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
local GC = require('apicast.gc')

describe('GC', function()
describe('.enable', function()
it('enables GC on a table', function()
local table = { 1, 2, 3 }
setmetatable(table, { __gc = function() end })
stub(getmetatable(table), '__gc')

local table_with_gc = GC.enable(table)
table_with_gc = nil
collectgarbage()

assert.stub(getmetatable(table).__gc).was_called()
end)

it('returns an object where we can access, add, and delete elements', function()
local table = { 1, 2, 3, some_key = 'some_val' }
setmetatable(table, { __gc = function() end })

local table_with_gc = GC.enable(table)

assert.equals(3, #table_with_gc)
assert.equals(1, table_with_gc[1])
assert.equals('some_val', table_with_gc.some_key)

table_with_gc.new_key = 'new_val'
assert.equals('new_val', table_with_gc.new_key)

table_with_gc.new_key = nil
assert.is_nil(table_with_gc.new_key)
end)

it('returns an object that responds to ipairs', function()
local test_table = { 1, 2, 3, some_key = 'some_val' }
setmetatable(test_table, { __gc = function() end })

local table_with_gc = GC.enable(test_table)

local res = {}
for _, val in ipairs(table_with_gc) do
table.insert(res, val)
end

assert.same({ 1, 2, 3 }, res)
end)

it('returns an object that respons to pairs', function()
local test_table = { 1, 2, 3, some_key = 'some_val' }
setmetatable(test_table, { __gc = function() end })

local table_with_gc = GC.enable(test_table)

local res = {}
for k, v in pairs(table_with_gc) do
res[k] = v
end

assert.same({ [1] = 1, [2] = 2, [3] = 3, some_key = 'some_val' }, res)
end)

it('returns an object that respects the __call in the mt of the original table', function()
local test_table = { 1, 2, 3 }
setmetatable(
test_table,
{
__call = function(...)
local res = 0

for _, val in ipairs(table.pack(...)) do
res = res + val
end

return res
end,
__gc = function() end
}
)

local table_with_gc = GC.enable(test_table)

assert.equals(3, table_with_gc(1, 2))
end)

it('returns an object that respects the __tostring in the mt of the original table', function()
local test_table = { 1, 2, 3 }

setmetatable(
test_table,
{ __tostring = function() return '123' end }
)

local table_with_gc = GC.enable(test_table)

assert.equals('123', tostring(table_with_gc))
end)
end)
end)

0 comments on commit 0376099

Please sign in to comment.