-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtest_functions.p8
122 lines (103 loc) · 2.28 KB
/
test_functions.p8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
pico-8 cartridge // http://www.pico-8.com
version 18
__lua__
-- Unit tests for the functions module
-- by sparr
-- to run the tests use `pico8 -x tests/test_functions.p8`
#include ../pico8lib/class.lua
#include ../pico8lib/strings.lua
#include ../pico8lib/log.lua
#include ../pico8lib/functions.lua
#include ../pico8lib/tables.lua
#include ../pico8lib/test.lua
local suite = TestSuite("functions.p8")
-- Memoize test case
local Memoize = TestCase("memoize")
function Memoize:test_memoize_hit ()
local canary = 0
local r
function f(a)
canary = canary + 1
return a + 1
end
m = memoize(f)
self:assert_equal(canary, 0)
r = m(1)
self:assert_equal(r, 2)
self:assert_equal(canary, 1)
r = m(1)
self:assert_equal(r, 2)
self:assert_equal(canary, 1)
end
function Memoize:test_memoize_miss ()
local canary = 0
local r
function f(a)
canary = canary + 1
return a + 1
end
m = memoize(f)
self:assert_equal(canary, 0)
r = m(1)
self:assert_equal(r, 2)
self:assert_equal(canary, 1)
r = m(2)
self:assert_equal(r, 3)
self:assert_equal(canary, 2)
end
suite:add_test_case(Memoize)
-- Try test case
local Try = TestCase("try")
function Try:good (t)
return function ()
t[1] = true
end
end
function Try:bad (t)
return function ()
t[1] = true
error()
end
end
function Try:test_try_success ()
local t = {}
local c = {}
local f = {}
try(self:good(t), self:bad(c), self:good(f))
self:assert_equal(t[1], true)
self:assert_nil(c[1], true)
self:assert_equal(f[1], true)
end
function Try:test_try_error_in_try ()
local t = {}
local c = {}
local f = {}
try(self:bad(t), self:good(c), self:good(f))
self:assert_equal(t[1], true)
self:assert_equal(c[1], true)
self:assert_equal(f[1], true)
end
function Try:test_try_error_in_catch ()
local t = {}
local c = {}
local f = {}
self:assert_throws(function ()
try(self:bad(t), self:bad(c), self:good(f))
end, "assertion failed!")
self:assert_equal(t[1], true)
self:assert_equal(c[1], true)
self:assert_nil(f[1])
end
function Try:test_try_error_in_finally ()
local t = {}
local c = {}
local f = {}
self:assert_throws(function ()
try(self:good(t), self:good(c), self:bad(f))
end, "assertion failed!")
self:assert_equal(t[1], true)
self:assert_nil(c[1], true)
self:assert_equal(f[1], true)
end
suite:add_test_case(Try)
run_suites{suite}