Added bootstrap tests for UnitTest::Loader
[kakapo:kakapo.git] / src / UnitTest / Loader.nqp
1 # Copyright (C) 2010, Austin Hastings. See accompanying LICENSE file, or 
2 # http://www.opensource.org/licenses/artistic-license-2.0.php for license.
3
4 module UnitTest::Loader;
5 INIT {
6         use(    'P6metaclass' );
7         
8         has(    '%!seen_methods' );
9         say("Loader init done");
10 }
11
12 method configure_suite($class, @tests, :$suite) {
13         unless $suite.defined {
14                 $suite := self.default_suite;
15         }
16
17         my $proto := pir::getprop__PSP('metaclass', $class).WHAT();
18
19         for @tests {
20                 $suite.add_test($proto.new(:name(~$_)));
21         }
22         
23         $suite;
24 }
25
26 method default_suite() {
27         return UnitTest::Suite.new();
28 }
29
30 method get_test_methods($class) {
31         my @mro := $class.inspect('all_parents');
32         my @test_methods := Array::empty();
33         
34         for @mro {
35                 my %methods := $_.inspect('methods');
36                 
37                 for %methods {
38                         my $name := ~ $_;
39                         
40                         if self.is_test_method($name) 
41                                 && ! self.seen_methods.contains($name) {
42                                 self.seen_methods{$name} := 1;
43                                 @test_methods.push($name);
44                         }
45                 }
46         }
47
48         return @test_methods;
49 }
50
51 method is_test_method($name) {
52 # Returns true for "test_foo" and "testFoo" names
53         if $name.length > 4
54                 && $name.substr(0, 4) eq 'test' {
55                 
56                 if $name[4] eq '_' {
57                         return 1;
58                 }
59
60                 if String::is_cclass('UPPERCASE', $name, :offset(4)) {
61                         return 1;
62                 }
63                 
64                 if String::is_cclass('NUMERIC', $name, :offset(4)) {
65                         return 1;
66                 }
67         }
68
69         return 0;
70 }
71
72 method load_tests_from_testcase($testcase, :$suite) {
73         my $class := P6metaclass.get_parrotclass($testcase);    
74         my @tests := self.get_test_methods($class);
75         self.configure_suite($class, @tests, :suite($suite));
76 }