aboutsummaryrefslogtreecommitdiffstats
path: root/test/lunit.lua
blob: 1ebec4837c8d04df8b976ff97f2ad7e5f4605ea3 (plain)
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693

--[[--------------------------------------------------------------------------

    This file is part of lunit 0.4pre (alpha).

    For Details about lunit look at: http://www.nessie.de/mroth/lunit/

    Author: Michael Roth <mroth@nessie.de>

    Copyright (c) 2004 Michael Roth <mroth@nessie.de>

    Permission is hereby granted, free of charge, to any person 
    obtaining a copy of this software and associated documentation
    files (the "Software"), to deal in the Software without restriction,
    including without limitation the rights to use, copy, modify, merge,
    publish, distribute, sublicense, and/or sell copies of the Software,
    and to permit persons to whom the Software is furnished to do so,
    subject to the following conditions:

    The above copyright notice and this permission notice shall be 
    included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
    SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

--]]--------------------------------------------------------------------------




-----------------------
-- Intialize package --
-----------------------

local P = { }
lunit = P

-- Import
local type = type
local print = print
local ipairs = ipairs
local pairs = pairs
local string = string
local table = table
local pcall = pcall
local xpcall = xpcall
local traceback = debug.traceback
local error = error
local setmetatable = setmetatable
local rawset = rawset
local orig_assert = assert
local getfenv = getfenv
local setfenv = setfenv
local tostring = tostring


-- Start package scope
setfenv(1, P)




--------------------------------
-- Private data and functions --
--------------------------------

local run_testcase
local do_assert, check_msg
local stats = { }
local testcases = { }
local stats_inc, tc_mt




--------------------------
-- Type check functions --
--------------------------

function is_nil(x)
  return type(x) == "nil"
end

function is_boolean(x)
  return type(x) == "boolean"
end

function is_number(x)
  return type(x) == "number"
end

function is_string(x)
  return type(x) == "string"
end

function is_table(x)
  return type(x) == "table"
end

function is_function(x)
  return type(x) == "function"
end

function is_thread(x)
  return type(x) == "thread"
end

function is_userdata(x)
  return type(x) == "userdata"
end




----------------------
-- Assert functions --
----------------------

function assert(assertion, msg)
  stats_inc("assertions")
  check_msg("assert", msg)
  do_assert(not not assertion, "assertion failed (was: "..tostring(assertion)..")", msg)		-- (convert assertion to bool)
  return assertion
end


function assert_fail(msg)
  stats_inc("assertions")
  check_msg("assert_fail", msg)
  do_assert(false, "failure", msg)
end


function assert_true(actual, msg)
  stats_inc("assertions")
  check_msg("assert_true", msg)
  do_assert(is_boolean(actual), "true expected but was a "..type(actual), msg)
  do_assert(actual == true, "true expected but was false", msg)
  return actual
end


function assert_false(actual, msg)
  stats_inc("assertions")
  check_msg("assert_false", msg)
  do_assert(is_boolean(actual), "false expected but was a "..type(actual), msg)
  do_assert(actual == false, "false expected but was true", msg)
  return actual
end


function assert_equal(expected, actual, msg)
  stats_inc("assertions")
  check_msg("assert_equal", msg)
  do_assert(expected == actual, "expected '"..tostring(expected).."' but was '"..tostring(actual).."'", msg)
  return actual
end


function assert_not_equal(unexpected, actual, msg)
  stats_inc("assertions")
  check_msg("assert_not_equal", msg)
  do_assert(unexpected ~= actual, "'"..tostring(expected).."' not expected but was one", msg)
  return actual
end


function assert_match(pattern, actual, msg)
  stats_inc("assertions")
  check_msg("assert_match", msg)
  do_assert(is_string(pattern), "assert_match expects the pattern as a string")
  do_assert(is_string(actual), "expected a string to match pattern '"..pattern.."' but was a '"..type(actual).."'", msg)
  do_assert(not not string.find(actual, pattern), "expected '"..actual.."' to match pattern '"..pattern.."' but doesn't", msg)
  return actual
end


function assert_not_match(pattern, actual, msg)
  stats_inc("assertions")
  check_msg("assert_not_match", msg)
  do_assert(is_string(actual), "expected a string to not match pattern '"..pattern.."' but was a '"..type(actual).."'", msg)
  do_assert(string.find(actual, pattern) == nil, "expected '"..actual.."' to not match pattern '"..pattern.."' but it does", msg)
  return actual
end


function assert_nil(actual, msg)
  stats_inc("assertions")
  check_msg("assert_nil", msg)
  do_assert(is_nil(actual), "nil expected but was a "..type(actual), msg)
  return actual
end


function assert_not_nil(actual, msg)
  stats_inc("assertions")
  check_msg("assert_not_nil", msg)
  do_assert(not is_nil(actual), "nil not expected but was one", msg)
  return actual
end


function assert_boolean(actual, msg)
  stats_inc("assertions")
  check_msg("assert_boolean", msg)
  do_assert(is_boolean(actual), "boolean expected but was a "..type(actual), msg)
  return actual
end


function assert_not_boolean(actual, msg)
  stats_inc("assertions")
  check_msg("assert_not_boolean", msg)
  do_assert(not is_boolean(actual), "boolean not expected but was one", msg)
  return actual
end


function assert_number(actual, msg)
  stats_inc("assertions")
  check_msg("assert_number", msg)
  do_assert(is_number(actual), "number expected but was a "..type(actual), msg)
  return actual
end


function assert_not_number(actual, msg)
  stats_inc("assertions")
  check_msg("assert_not_number", msg)
  do_assert(not is_number(actual), "number not expected but was one", msg)
  return actual
end


function assert_string(actual, msg)
  stats_inc("assertions")
  check_msg("assert_string", msg)
  do_assert(is_string(actual), "string expected but was a "..type(actual), msg)
  return actual
end


function assert_not_string(actual, msg)
  stats_inc("assertions")
  check_msg("assert_not_string", msg)
  do_assert(not is_string(actual), "string not expected but was one", msg)
  return actual
end


function assert_table(actual, msg)
  stats_inc("assertions")
  check_msg("assert_table", msg)
  do_assert(is_table(actual), "table expected but was a "..type(actual), msg)
  return actual
end


function assert_not_table(actual, msg)
  stats_inc("assertions")
  check_msg("assert_not_table", msg)
  do_assert(not is_table(actual), "table not expected but was one", msg)
  return actual
end


function assert_function(actual, msg)
  stats_inc("assertions")
  check_msg("assert_function", msg)
  do_assert(is_function(actual), "function expected but was a "..type(actual), msg)
  return actual
end


function assert_not_function(actual, msg)
  stats_inc("assertions")
  check_msg("assert_not_function", msg)
  do_assert(not is_function(actual), "function not expected but was one", msg)
  return actual
end


function assert_thread(actual, msg)
  stats_inc("assertions")
  check_msg("assert_thread", msg)
  do_assert(is_thread(actual), "thread expected but was a "..type(actual), msg)
  return actual
end


function assert_not_thread(actual, msg)
  stats_inc("assertions")
  check_msg("assert_not_thread", msg)
  do_assert(not is_thread(actual), "thread not expected but was one", msg)
  return actual
end


function assert_userdata(actual, msg)
  stats_inc("assertions")
  check_msg("assert_userdata", msg)
  do_assert(is_userdata(actual), "userdata expected but was a "..type(actual), msg)
  return actual
end


function assert_not_userdata(actual, msg)
  stats_inc("assertions")
  check_msg("assert_not_userdata", msg)
  do_assert(not is_userdata(actual), "userdata not expected but was one", msg)
  return actual
end


function assert_error(msg, func)
  stats_inc("assertions")
  if is_nil(func) then func, msg = msg, nil end
  check_msg("assert_error", msg)
  do_assert(is_function(func), "assert_error expects a function as the last argument but it was a "..type(func))
  local ok, errmsg = pcall(func)
  do_assert(ok == false, "error expected but no error occurred", msg)
end


function assert_pass(msg, func)
  stats_inc("assertions")
  if is_nil(func) then func, msg = msg, nil end
  check_msg("assert_pass", msg)
  do_assert(is_function(func), "assert_pass expects a function as the last argument but it was a "..type(func))
  local ok, errmsg = pcall(func)
  if not ok then do_assert(ok == true, "no error expected but error was: "..errmsg, msg) end
end




-----------------------------------------------------------
-- Assert implementation that assumes it was called from --
-- lunit code which was called directly from user code.  --
-----------------------------------------------------------

function do_assert(assertion, base_msg, user_msg)
  orig_assert(is_boolean(assertion))
  orig_assert(is_string(base_msg))
  orig_assert(is_string(user_msg) or is_nil(user_msg))
  if not assertion then
    if user_msg then
      error(base_msg..": "..user_msg, 3)
    else
      error(base_msg.."!", 3)
    end
  end
end

-------------------------------------------
-- Checks the msg argument in assert_xxx --
-------------------------------------------

function check_msg(name, msg)
  orig_assert(is_string(name))
  if not (is_nil(msg) or is_string(msg)) then
    error("lunit."..name.."() expects the optional message as a string but it was a "..type(msg).."!" ,3)
  end
end




-------------------------------------
-- Creates a new TestCase 'Object' --
-------------------------------------

function TestCase(name)
  do_assert(is_string(name), "lunit.TestCase() needs a string as an argument")
  local tc = {
    __lunit_name = name;
    __lunit_setup = nil;
    __lunit_tests = { };
    __lunit_teardown = nil;
  }
  setmetatable(tc, tc_mt)
  table.insert(testcases, tc)
  return tc
end

tc_mt = {
  __newindex = function(tc, key, value)
    rawset(tc, key, value)
    if is_string(key) and is_function(value) then
      local name = string.lower(key)
      if string.find(name, "^test") or string.find(name, "test$") then
        table.insert(tc.__lunit_tests, key)
      elseif name == "setup" then
        tc.__lunit_setup = value
      elseif name == "teardown" then
        tc.__lunit_teardown = value
      end
    end
  end
}



-----------------------------------------
-- Wrap Functions in a TestCase object --
-----------------------------------------

function wrap(name, ...)
  if is_function(name) then
    table.insert(arg, 1, name)
    name = "Anonymous Testcase"
  end
  
  local tc = TestCase(name)
  for index, test in ipairs(arg) do
    tc["Test #"..index] = test
  end
  return tc
end






----------------------------------
-- Runs the complete Test Suite --
----------------------------------

function run()
  
  ---------------------------
  -- Initialize statistics --
  ---------------------------
  
  stats.testcases = 0	-- Total number of Test Cases
  stats.tests = 0	-- Total number of all Tests in all Test Cases
  stats.run = 0		-- Number of Tests run
  stats.notrun = 0	-- Number of Tests not run
  stats.failed = 0	-- Number of Tests failed
  stats.warnings = 0	-- Number of Warnings (teardown)
  stats.errors = 0	-- Number of Errors (setup)
  stats.passed = 0	-- Number of Test passed
  stats.assertions = 0	-- Number of all assertions made in all Test in all Test Cases
  
  --------------------------------
  -- Count Test Cases and Tests --
  --------------------------------
  
  stats.testcases = table.getn(testcases)
  
  for _, tc in ipairs(testcases) do
    stats_inc("tests" , table.getn(tc.__lunit_tests))
  end
  
  ------------------
  -- Print Header --
  ------------------
  
  print()
  print("#### Test Suite with "..stats.tests.." Tests in "..stats.testcases.." Test Cases loaded.")
  
  ------------------------
  -- Run all Test Cases --
  ------------------------
  
  for _, tc in ipairs(testcases) do
    run_testcase(tc)
  end
  
  ------------------
  -- Print Footer --
  ------------------
  
  print()
  print("#### Test Suite finished.")
  
  local msg_assertions = stats.assertions.." Assertions checked. "
  local msg_passed     = stats.passed == stats.tests and "All Tests passed" or  stats.passed.." Tests passed"
  local msg_failed     = stats.failed > 0 and ", "..stats.failed.." failed" or ""
  local msg_run	       = stats.notrun > 0 and ", "..stats.notrun.." not run" or ""
  local msg_warn       = stats.warnings > 0 and ", "..stats.warnings.." warnings" or ""
  
  print()
  print(msg_assertions..msg_passed..msg_failed..msg_run..msg_warn.."!")
  
  -----------------
  -- Return code --
  -----------------
  
  if stats.passed == stats.tests then
    return 0
  else
    return 1
  end
end




-----------------------------
-- Runs a single Test Case --
-----------------------------

function run_testcase(tc)
  
  orig_assert(is_table(tc))
  orig_assert(is_table(tc.__lunit_tests))
  orig_assert(is_string(tc.__lunit_name))
  orig_assert(is_nil(tc.__lunit_setup) or is_function(tc.__lunit_setup))
  orig_assert(is_nil(tc.__lunit_teardown) or is_function(tc.__lunit_teardown))
  
  ----------------------------------
  -- Protected call to a function --
  ----------------------------------
  
  local function call(errprefix, func)
    orig_assert(is_string(errprefix))
    orig_assert(is_function(func))
    local ok, errmsg = xpcall(function() func(tc) end, traceback)
    if not ok then
      print()
      print(errprefix..": "..errmsg)
    end
    return ok
  end
  
  ------------------------------------
  -- Calls setup() on the Test Case --
  ------------------------------------
  
  local function setup(testname)
    if tc.__lunit_setup then 
      return call("ERROR: "..testname..": setup() failed", tc.__lunit_setup)
    else
      return true
    end
  end
  
  ------------------------------------------
  -- Calls a single Test on the Test Case --
  ------------------------------------------
  
  local function run(testname)
    orig_assert(is_string(testname))
    orig_assert(is_function(tc[testname]))
    local ok = call("FAIL: "..testname, tc[testname])
    if not ok then
      stats_inc("failed")
    else
      stats_inc("passed")
    end
    return ok
  end
  
  ---------------------------------------
  -- Calls teardown() on the Test Case --
  ---------------------------------------
  
  local function teardown(testname)
     if tc.__lunit_teardown then
       if not call("WARNING: "..testname..": teardown() failed", tc.__lunit_teardown) then
         stats_inc("warnings")
       end
     end
  end
  
  ---------------------------------
  -- Run all Tests on a TestCase --
  ---------------------------------
  
  print()
  print("#### Running '"..tc.__lunit_name.."' ("..table.getn(tc.__lunit_tests).." Tests)...")
  
  for _, testname in ipairs(tc.__lunit_tests) do
    if setup(testname) then
      run(testname)
      stats_inc("run")
      teardown(testname)
    else
      print("WARN: Skipping '"..testname.."'...")
      stats_inc("notrun")
    end
  end
  
end




---------------------
-- Import function --
---------------------

function import(name)
  
  do_assert(is_string(name), "lunit.import() expects a single string as argument")
  
  local user_env = getfenv(2)
  
  --------------------------------------------------
  -- Installs a specific function in the user env --
  --------------------------------------------------
  
  local function install(funcname)
    user_env[funcname] = P[funcname]
  end
  
  
  ----------------------------------------------------------
  -- Install functions matching a pattern in the user env --
  ----------------------------------------------------------
  
  local function install_pattern(pattern)
    for funcname, _ in pairs(P) do
      if string.find(funcname, pattern) then
        install(funcname)
      end
    end
  end
  
  ------------------------------------------------------------
  -- Installs assert() and all assert_xxx() in the user env --
  ------------------------------------------------------------
  
  local function install_asserts()
    install_pattern("^assert.*")
  end
  
  -------------------------------------------
  -- Installs all is_xxx() in the user env --
  -------------------------------------------
  
  local function install_tests()
    install_pattern("^is_.+")
  end
  
  if name == "asserts" or name == "assertions" then
    install_asserts()
  elseif name == "tests" or name == "checks" then
    install_tests()
  elseif name == "all" then
    install_asserts()
    install_tests()
    install("TestCase")
  elseif string.find(name, "^assert.*") and P[name] then
    install(name)
  elseif string.find(name, "^is_.+") and P[name] then
    install(name)
  elseif name == "TestCase" then
    install("TestCase")
  else
    error("luniit.import(): invalid function '"..name.."' to import", 2)
  end
end




--------------------------------------------------
-- Installs a private environment on the caller --
--------------------------------------------------

function setprivfenv()
  local new_env = { }
  local new_env_mt = { __index = getfenv(2) }
  setmetatable(new_env, new_env_mt)
  setfenv(2, new_env)
end




--------------------------------------------------
-- Increments a counter in the statistics table --  
--------------------------------------------------

function stats_inc(varname, value)
  orig_assert(is_table(stats))
  orig_assert(is_string(varname))
  orig_assert(is_nil(value) or is_number(value))
  if not stats[varname] then return end
  stats[varname] = stats[varname] + (value or 1)
end