Skip to content

Commit 0376099

Browse files
committed
Add specs for GC
1 parent b74cd51 commit 0376099

File tree

1 file changed

+98
-0
lines changed

1 file changed

+98
-0
lines changed

spec/gc_spec.lua

+98
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
local GC = require('apicast.gc')
2+
3+
describe('GC', function()
4+
describe('.enable', function()
5+
it('enables GC on a table', function()
6+
local table = { 1, 2, 3 }
7+
setmetatable(table, { __gc = function() end })
8+
stub(getmetatable(table), '__gc')
9+
10+
local table_with_gc = GC.enable(table)
11+
table_with_gc = nil
12+
collectgarbage()
13+
14+
assert.stub(getmetatable(table).__gc).was_called()
15+
end)
16+
17+
it('returns an object where we can access, add, and delete elements', function()
18+
local table = { 1, 2, 3, some_key = 'some_val' }
19+
setmetatable(table, { __gc = function() end })
20+
21+
local table_with_gc = GC.enable(table)
22+
23+
assert.equals(3, #table_with_gc)
24+
assert.equals(1, table_with_gc[1])
25+
assert.equals('some_val', table_with_gc.some_key)
26+
27+
table_with_gc.new_key = 'new_val'
28+
assert.equals('new_val', table_with_gc.new_key)
29+
30+
table_with_gc.new_key = nil
31+
assert.is_nil(table_with_gc.new_key)
32+
end)
33+
34+
it('returns an object that responds to ipairs', function()
35+
local test_table = { 1, 2, 3, some_key = 'some_val' }
36+
setmetatable(test_table, { __gc = function() end })
37+
38+
local table_with_gc = GC.enable(test_table)
39+
40+
local res = {}
41+
for _, val in ipairs(table_with_gc) do
42+
table.insert(res, val)
43+
end
44+
45+
assert.same({ 1, 2, 3 }, res)
46+
end)
47+
48+
it('returns an object that respons to pairs', function()
49+
local test_table = { 1, 2, 3, some_key = 'some_val' }
50+
setmetatable(test_table, { __gc = function() end })
51+
52+
local table_with_gc = GC.enable(test_table)
53+
54+
local res = {}
55+
for k, v in pairs(table_with_gc) do
56+
res[k] = v
57+
end
58+
59+
assert.same({ [1] = 1, [2] = 2, [3] = 3, some_key = 'some_val' }, res)
60+
end)
61+
62+
it('returns an object that respects the __call in the mt of the original table', function()
63+
local test_table = { 1, 2, 3 }
64+
setmetatable(
65+
test_table,
66+
{
67+
__call = function(...)
68+
local res = 0
69+
70+
for _, val in ipairs(table.pack(...)) do
71+
res = res + val
72+
end
73+
74+
return res
75+
end,
76+
__gc = function() end
77+
}
78+
)
79+
80+
local table_with_gc = GC.enable(test_table)
81+
82+
assert.equals(3, table_with_gc(1, 2))
83+
end)
84+
85+
it('returns an object that respects the __tostring in the mt of the original table', function()
86+
local test_table = { 1, 2, 3 }
87+
88+
setmetatable(
89+
test_table,
90+
{ __tostring = function() return '123' end }
91+
)
92+
93+
local table_with_gc = GC.enable(test_table)
94+
95+
assert.equals('123', tostring(table_with_gc))
96+
end)
97+
end)
98+
end)

0 commit comments

Comments
 (0)