/
test_case.php
943 lines (881 loc) · 33.8 KB
/
test_case.php
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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
<?php
/**
* Base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
* @version $Id$
*/
/**#@+
* Includes SimpleTest files and defined the root constant
* for dependent libraries.
*/
require_once(dirname(__FILE__) . '/invoker.php');
require_once(dirname(__FILE__) . '/errors.php');
require_once(dirname(__FILE__) . '/fails.php');
require_once(dirname(__FILE__) . '/compatibility.php');
require_once(dirname(__FILE__) . '/scorer.php');
require_once(dirname(__FILE__) . '/expectation.php');
require_once(dirname(__FILE__) . '/dumper.php');
require_once(dirname(__FILE__) . '/simpletest.php');
require_once(dirname(__FILE__) . '/exceptions.php');
require_once(dirname(__FILE__) . '/reflection.php');
require_once(dirname(__FILE__) . '/shell_tester.php');
/**#@-*/
if (! defined('SIMPLE_TEST')) {
/**
* @ignore
*/
define('SIMPLE_TEST', dirname(__FILE__) . DIRECTORY_SEPARATOR);
}
/**
* Basic test case. This is the smallest unit of a test
* suite. It searches for
* all methods that start with the the string "test" and
* runs them. Working test cases extend this class.
* @package SimpleTest
* @subpackage UnitTester
*/
class SimpleTestCase {
protected $label = false;
protected $reporter = false;
protected $observers;
protected $should_skip = false;
protected $running = false;
/**
* Sets up the test with no display.
* @param string $label If no test name is given then
* the class name is used.
* @access public
*/
function __construct($label = false) {
if ($label) {
$this->label = $label;
}
$this->observers = array();
}
/**
* Accessor for the test name for subclasses.
* @return string Name of the test.
* @access public
*/
function getLabel() {
return $this->label ? $this->label : get_class($this);
}
/**
* Accessor for the registered reporter.
* @return SimpleReporter The registered reporter or FALSE if none is known at the time of this call.
* @access public
*/
function getReporter() {
return $this->reporter;
}
/**
* This is a placeholder for skipping tests. In this
* method you place skipIf() and skipUnless() calls to
* set the skipping state.
* @access public
*/
function skip() {
}
/**
* Will issue a message to the reporter and tell the test
* case to skip if the incoming flag is true.
* @param string $should_skip Condition causing the tests to be skipped.
* @param string $message Text of skip condition.
* @access public
*/
function skipIf($should_skip, $message = '%s') {
if ($should_skip && ! $this->should_skip) {
$this->should_skip = true;
$message = sprintf($message, 'Skipping [' . get_class($this) . ']');
$this->reporter->paintSkip($message . $this->getAssertionLine());
}
}
/**
* Accessor for the protected variable $shoud_skip
* @access public
*/
function shouldSkip() {
return $this->should_skip;
}
/**
* Will issue a message to the reporter and tell the test
* case to skip if the incoming flag is false.
* @param string $shouldnt_skip Condition causing the tests to be run.
* @param string $message Text of skip condition.
* @access public
*/
function skipUnless($shouldnt_skip, $message = false) {
$this->skipIf(! $shouldnt_skip, $message);
}
/**
* Used to invoke the single tests.
* @return SimpleInvoker Individual test runner.
* @access public
*/
function createInvoker() {
return new SimpleFailTrappingInvoker(
new SimpleErrorTrappingInvoker(
new SimpleExceptionTrappingInvoker(new SimpleInvoker($this))));
}
/**
* Uses reflection to run every method within itself
* starting with the string "test" unless a method
* is specified.
* @param SimpleReporter $reporter Current test reporter.
* @return boolean True if all tests passed.
* @access public
*/
function run($reporter) {
/*
Make sure that each (possibly nested!) test has its own fail/error/... queues, etc.
so that the expectXXX() functions work like you'ld expect, even when a test invokes
another test instance's run() method.
BREAKING CHANGE: We do know that tests might want to access the context which was used
to invoke the inner run(), but we MUST pop the context once the run() itself is
done to ensure that all expectXXX queues are aligned with the correct (nested)
tests. Hence, when a user wants access to the inner context's reporter, they should
ask the test instance, not the global scope. (See test/errors_test.php ~ line )
We do NOT pop context at the end of this call. Instead,
we use a heuristic to keep the chain/number of contexts to a minimum by popping
all /sub/contexts before we return, as those won't be accessible by grandparent
tests anyhow.
*/
$this->running = true;
$context = SimpleTest::pushContext();
$context->setTest($this);
$context->setReporter($reporter);
$this->reporter = $reporter;
$started = false;
foreach ($this->getTests() as $method) {
if ($reporter->shouldInvoke($this->getLabel(), $method)) {
$this->skip();
if ($this->should_skip) {
break;
}
if (! $started) {
$reporter->paintCaseStart($this->getLabel());
$started = true;
}
$invoker = $this->reporter->createInvoker($this->createInvoker());
$invoker->before($method);
$invoker->invoke($method);
$invoker->after($method);
}
}
if ($started) {
$reporter->paintCaseEnd($this->getLabel());
}
//$context->setTest(null);
SimpleTest::popContext($context);
$this->running = false;
return $reporter->getStatus();
}
/**
* Gets a list of test names. Normally that will
* be all internal methods that start with the
* name "test". This method should be overridden
* if you want a different rule.
* @return array List of test names.
* @access public
*/
function getTests() {
$methods = array();
foreach (get_class_methods(get_class($this)) as $method) {
if ($this->isTest(get_class($this), $method)) {
$methods[] = $method;
}
}
return $methods;
}
/**
* Tests to see if the method is a test that should
* be run. Currently any method that starts with 'test'
* is a candidate.
* @param string $class Class name of the method to try.
* @param string $method Method name to try.
* @return boolean True if test method.
* @access public
*/
static function isTest($class, $method) {
return (strtolower(substr($method, 0, 4)) == 'test'
&& strtolower($method) != strtolower($class));
}
/**
* Announces the start of the test.
* @param string $method Test method just started.
* @access public
*/
function before($method) {
$this->reporter->paintMethodStart($method);
$this->observers = array();
}
/**
* Sets up unit test wide variables at the start
* of each test method. To be overridden in
* actual user test cases.
* @access public
*/
function setUp() {
}
/**
* Clears the data set in the setUp() method call.
* To be overridden by the user in actual user test cases.
* @access public
*/
function tearDown() {
}
/**
* Announces the end of the test. Includes private clean up.
* @param string $method Test method just finished.
* @access public
*/
function after($method) {
for ($i = 0; $i < count($this->observers); $i++) {
$this->observers[$i]->atTestEnd($method, $this);
}
$this->reporter->paintMethodEnd($method);
}
/**
* Sets up an observer for the test end.
* @param object $observer Must have atTestEnd()
* method.
* @access public
*/
function tell($observer) {
$this->observers[] = $observer;
}
/**
* Determines whether to print a pass/fail/unexpected pass/expected fail
* message, depending on the mode parameter and the fail-queue.
*
* @param string $message The pass/fail message.
* @param integer $mode The pass(1)/fail(-1) mode.
* @returns integer True if this one was counted as a pass after all, otherwise false.
*/
private function pass_or_fail($message, $mode)
{
if (!$this->running) {
trigger_error('Can only make assertions within test methods');
}
$queue = SimpleTest::getContext()->get('SimpleFailQueue');
if ($queue->add($message, $this->getAssertionLine(), $mode) > 0)
{
$this->reporter->incrementPassCount();
$this->reporter->paintPass(
$message . $this->getAssertionLine());
return 1;
}
else
{
$this->reporter->incrementFailCount();
$this->reporter->paintFail(
$message . $this->getAssertionLine());
return -1;
}
}
/**
* @deprecated
*/
function pass($message = "Pass") {
return $this->pass_or_fail($message, 1);
}
/**
* Sends a fail event with a message.
* @param string $message Message to send.
* @access public
*/
function fail($message = "Fail") {
return $this->pass_or_fail($message, -1);
}
/**
* Formats a PHP error and dispatches it to the
* reporter.
* @param integer $severity PHP error code.
* @param string $message Text of error.
* @param string $file File error occoured in.
* @param integer $line Line number of error.
* @access public
*/
function error($severity, $message, $file, $line) {
if (!$this->running) {
trigger_error('Can only make assertions within test methods');
}
$this->reporter->incrementErrorCount();
$this->reporter->paintError(
"Unexpected PHP error [$message] severity [$severity] in [$file line $line]");
}
/**
* Formats an exception and dispatches it to the
* reporter.
* @param Exception $exception Object thrown.
* @access public
*/
function exception($exception) {
if (!$this->running) {
trigger_error('Can only make assertions within test methods');
}
$this->reporter->incrementExceptionCount();
$this->reporter->paintException($exception);
}
/**
* For user defined expansion of the available messages.
* @param string $type Tag for sorting the signals.
* @param mixed $payload Extra user specific information.
*/
function signal($type, $payload) {
if (!$this->running) {
trigger_error('Can only make assertions within test methods');
}
$this->reporter->paintSignal($type, $payload);
}
protected function getURLregex() {
static $uri_re;
if (empty($uri_re)) {
$uri_re = '=^(((([a-z][a-z0-9.+-]+:)?//)'; // mandatory scheme + authority start ('//') -- iff authority is specified
$uri_re .= '([%!$&\'\(\)*+,;=:a-z0-9_~.-]+@)?'; // optional userinfo
$uri_re .= '([%!$&\'\(\)*+,;=:\[\]a-z0-9_~.-]+)'; // authority
$uri_re .= '/)|/)?'; // making scheme + hier-part optional -- no requirement for FQDNs here
// (Note that we also consume the optional leading / of the path here.)
$uri_re .= '((\.+/)*[%!$&\'\(\)*+,;=:@a-z0-9_~-]+[./]+';
$uri_re .= '[%!$&\'\(\)*+,;=:@/a-z0-9_~.-]*[%!$&\'\(\)*+,;=:@/a-z0-9_~-])';
// mandatory path, must be obvious, so must contain at least a dot ...
// ... before the end or a '/' slash beyond the start ...
// ... and definitely no period at the very end
$uri_re .= '(\?[%!$&\'\(\)*+,;=:@/?\[\]a-z0-9_~.-]+)?'; // optional query, we accept '[' and ']' in there as well (not in RFC)
$uri_re .= '(#[%!$&\'\(\)*+,;=:@/?\[\]a-z0-9_~.-]+)?'; // optional fragment, we accept '[' and ']' in there as well (not in RFC)
$uri_re .= '$=i';
}
return $uri_re;
}
/**
* Prepares for an failure. If the failure mismatches it
* passes through, otherwise it is swallowed. Any
* left over expected failures are reported before the end
* of the test.
*
* For example, use $this->expectedFail()->assert... to mark the assert as an
* expected fail.
*
* You may want to use expectFail() in two different scenarios:
*
* 1) If your test reveals a bug then use this function with the
* relevant parameter to link/refer to your bugtracker. This is
* necessary because it is much easier to write a test than
* fix a bug. It's also self-documenting -- before a release,
* all these expectFail() calls should be removed.
*
* 2) You want to test the behaviour of SimpleTest itself, including
* how it renders failed tests. This is a special case which
* applies to all expectFail() calls in the SimpleTest:./test/
* directory.
*
* @param SimpleExpectation/string $expected The error to match.
* @param string $message A message describing the known bug or an absolute URL pointing
* to the issue in any bugtracker.
* @return UnitTestCase This test object.
* @access public
*/
function expectFail($expected = false, $message = null) {
$queue = SimpleTest::getContext()->get('SimpleFailQueue');
if (!empty($message)) {
// test if $message is a URI as per RFC3986; if it is, embed it in an 'expected to fail' message:
if (preg_match($this->getURLregex(), $message) == 1) {
$message = str_replace('%', '%%', $message);
$message = "%s -> This is expected to fail due to a <a href=\"$message\">known bug</a>.";
}
}
else {
$message = "%s -> This is expected to fail.";
}
$queue->expectFail($this->coerceExpectation($expected), $message);
return $this;
}
/**
* Prepares for an error. If the error mismatches it
* passes through, otherwise it is swallowed. Any
* left over errors trigger failures.
* @param SimpleExpectation/string $expected The error to match.
* @param string $message Message on failure.
* @return UnitTestCase This test object.
* @access public
*/
function expectError($expected = false, $message = '%s') {
$queue = SimpleTest::getContext()->get('SimpleErrorQueue');
$queue->expectError($this->coerceExpectation($expected), $message);
return $this;
}
/**
* Prepares for an exception. If the error mismatches it
* passes through, otherwise it is swallowed. Any
* left over errors trigger failures.
* @param SimpleExpectation/Exception $expected The error to match.
* @param string $message Message on failure.
* @return UnitTestCase This test object.
* @access public
*/
function expectException($expected = false, $message = '%s') {
$queue = SimpleTest::getContext()->get('SimpleExceptionTrap');
$line = $this->getAssertionLine();
$queue->expectException($expected, $message . $line);
return $this;
}
/**
* Tells SimpleTest to ignore an upcoming exception as not relevant
* to the current test. It doesn't affect the test, whether thrown or
* not.
* @param SimpleExpectation/Exception $ignored The error to ignore.
* @access public
*/
function ignoreException($ignored = false) {
SimpleTest::getContext()->get('SimpleExceptionTrap')->ignoreException($ignored);
}
/**
* Creates an equality expectation if the
* object/value is not already some type
* of expectation.
* @param mixed $expected Expected value.
* @return SimpleExpectation Expectation object.
* @access protected
*/
protected function coerceExpectation($expected) {
if ($expected == false) {
return new AnythingExpectation();
}
if (SimpleTestCompatibility::isA($expected, 'SimpleExpectation')) {
return $expected;
}
return new EqualExpectation(
is_string($expected) ? str_replace('%', '%%', $expected) : $expected);
}
/**
* Construct 'pass' message. Takes expected fails into account.
* @access public
*/
function constructPassMessage($expectation, $compare, $message = "%s") {
$rv = sprintf($message,
$expectation->overlayMessage($compare, $this->getDumper()));
return $rv;
}
/**
* Construct 'fail' message. Takes expected fails into account.
* @access public
*/
function constructFailMessage($expectation, $compare, $message = "%s") {
$rv = sprintf($message,
$expectation->overlayMessage($compare, $this->getDumper()));
return $rv;
}
/**
* Obtain the dumper instance related to this test.
*/
public function getDumper() {
$dumper = null;
if ($this->reporter) {
$dumper = $this->reporter->getDumper();
}
else if ($context = SimpleTest::getContext()) {
if ($reporter = $context->getReporter()) {
$dumper = $reporter->getDumper();
}
}
if (!$dumper) {
$dumper = $expectation->getDumper();
}
return $dumper;
}
/**
* Runs an expectation directly, taking a possibly expected fail
* into account by turning the tables then.
* @param SimpleExpectation $expectation Expectation subclass.
* @param mixed $compare Value to compare.
* @return boolean True on pass / expected fail, false on fail / unexpected pass.
* @access public
*/
function checkExpectation($expectation, $compare) {
$rv = $expectation->test($compare);
return $rv;
}
/**
* Runs an expectation directly, for extending the
* tests with new expectation classes.
* @param SimpleExpectation $expectation Expectation subclass.
* @param mixed $compare Value to compare.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assert($expectation, $compare, $message = '%s') {
if ($this->checkExpectation($expectation, $compare)) {
return $this->pass($this->constructPassMessage($expectation, $compare, $message));
} else {
return $this->fail($this->constructFailMessage($expectation, $compare, $message));
}
}
/**
* Uses a stack trace to find the line of an assertion.
* @return string Line number of first assert*
* method embedded in format string.
* @access public
*/
function getAssertionLine() {
$trace = new SimpleStackTrace(array('assert', 'expect', 'pass', 'fail', 'skip'));
return $trace->traceMethod();
}
/**
* Sends a formatted dump of a variable to the
* test suite for those emergency debugging
* situations.
* @param mixed $variable Variable to display.
* @param string $message Message to display.
* @return mixed The original variable.
* @access public
*/
function dump($variable, $message = false) {
if ($this->reporter) {
$dumper = $this->reporter->getDumper();
$formatted = $dumper->dump($variable);
if ($message) {
$formatted = $message . "\n" . $formatted;
}
$this->reporter->paintFormattedMessage($formatted);
}
return $variable;
}
/**
* Accessor for the number of subtests including myself.
* @return integer Number of test cases.
* @access public
*/
function getSize() {
return 1;
}
}
/**
* Helps to extract test cases automatically from a file.
* @package SimpleTest
* @subpackage UnitTester
*/
class SimpleFileLoader {
/**
* Builds a test suite from a library of test cases.
* The new suite is composed into this one.
* @param string $test_file File name of library with
* test case classes.
* @return TestSuite The new test suite.
* @access public
*/
function load($test_file) {
$existing_classes = get_declared_classes();
$existing_globals = get_defined_vars();
// as the included file can contain errors, we don't want to crash, but report those instead!
//
// See also: http://us3.php.net/manual/en/function.php-check-syntax.php
//
// NOTE: you can also load the file content and then pull it through eval(): that one though will
// NOT report the parse error, only return FALSE ( http://nl.php.net/manual/en/function.eval.php )
$parse_err = -1;
if (is_readable($test_file)) {
$code = @file_get_contents($test_file);
if ($code === false) {
return new BadTestSuite($test_file, "Could not load the contents of the file");
}
$shell = new SimpleShell();
$parse_err = $shell->execute('php -l "' . realpath($test_file) . '"');
if ($parse_err) {
// either we're not being allowed to run a php cli, or we got an actual parse error: find out which it is
$out = $shell->getOutput();
if (strpos($out, 'syntax error') !== false) {
return new BadTestSuite($test_file, "There is a SYNTAX ERROR in the file:\n" . trim($out));
}
/*
* ELSE: seems we weren't able to run the php cli; we cannot fall back to the eval() way of checking the code
* as that would also /execute/ the code, which is sorta okay, apart from the fact that the code-under-test
* may collide with the simpletest code itself (e.g. when simpletest is used to test itself), resulting in
* eval failures such as 'cannot redefine class', while the code to test is perfectly fine.
*
* We can, however, use runkit_lint_file(), IFF it exists in our PHP install...
*/
if (function_exists('runkit_lint_file'))
{
$ret = runkit_lint_file($test_file);
if ($ret === false)
{
// to display the code causing the error: $code = htmlentities($code, ENT_NOQUOTES);
return new BadTestSuite($test_file, "There is a SYNTAX ERROR ($php_errormsg) in the file. Besides, you should adjust your setup so we can invoke 'php -l' as that gives you much more info about this error than a mere 'syntax error'.");
}
}
}
include_once($test_file); // or should this really be 'include' instead of 'include_once'?
}
else {
return new BadTestSuite($test_file, "You don't have read access to the file");
}
$new_globals = get_defined_vars();
$this->makeFileVariablesGlobal($existing_globals, $new_globals);
$new_classes = array_diff(get_declared_classes(), $existing_classes);
if (empty($new_classes)) {
$new_classes = $this->scrapeClassesFromFile($test_file);
}
$classes = $this->selectRunnableTests($new_classes);
return $this->createSuiteFromClasses($test_file, $classes);
}
/**
* Imports new variables into the global namespace.
* @param hash $existing Variables before the file was loaded.
* @param hash $new Variables after the file was loaded.
* @access protected
*/
protected function makeFileVariablesGlobal($existing, $new) {
$globals = array_diff(array_keys($new), array_keys($existing));
foreach ($globals as $global) {
$GLOBALS[$global] = $new[$global];
}
}
/**
* Lookup classnames from file contents, in case the
* file may have been included before.
*
* Note: This is probably too clever by half. Figuring this
* out after a failed test case is going to be tricky for us,
* never mind the user. A test case should not be included
* twice anyway.
*
* @param string $test_file File name with classes.
* @access protected
*/
protected function scrapeClassesFromFile($test_file) {
preg_match_all('~^\s*class\s+(\w+)(\s+(extends|implements)\s+\w+)*\s*\{~mi',
file_get_contents($test_file),
$matches );
return $matches[1];
}
/**
* Calculates the incoming test cases. Skips abstract
* and ignored classes.
* @param array $candidates Candidate classes.
* @return array New classes which are test
* cases that shouldn't be ignored.
* @access public
*/
function selectRunnableTests($candidates) {
$classes = array();
foreach ($candidates as $class) {
if (TestSuite::getBaseTestCase($class)) {
$reflection = new SimpleReflection($class);
if ($reflection->isAbstract()) {
SimpleTest::ignore($class);
} else {
// only pick classes which do have test methods we can run:
$methods = $reflection->getMethods();
foreach($methods as $method) {
if (SimpleTestCase::isTest($class, $method))
{
$classes[] = $class;
break;
}
}
}
}
}
return $classes;
}
/**
* Builds a test suite from a class list.
* @param string $title Title of new group.
* @param array $classes Test classes.
* @return TestSuite Group loaded with the new
* test cases.
* @access public
*/
function createSuiteFromClasses($title, $classes) {
if (count($classes) == 0) {
$suite = new BadTestSuite($title, "No runnable test cases in [$title]");
return $suite;
}
SimpleTest::ignoreParentsIfIgnored($classes);
$suite = new TestSuite($title);
foreach ($classes as $class) {
if (! SimpleTest::isIgnored($class)) {
$suite->add($class);
}
}
return $suite;
}
}
/**
* This is a composite test class for combining
* test cases and other RunnableTest classes into
* a group test.
* @package SimpleTest
* @subpackage UnitTester
*/
class TestSuite {
protected $label;
protected $test_cases;
/**
* Sets the name of the test suite.
* @param string $label Name sent at the start and end
* of the test.
* @access public
*/
function __construct($label = false) {
$this->label = $label;
$this->test_cases = array();
}
/**
* Accessor for the test name for subclasses. If the suite
* wraps a single test case the label defaults to the name of that test.
* @return string Name of the test.
* @access public
*/
function getLabel() {
if (! $this->label) {
return ($this->getSize() == 1) ?
@get_class($this->test_cases[0]) : get_class($this);
} else {
return $this->label;
}
}
/**
* Adds a test into the suite by instance or class. The class will
* be instantiated if it's a test suite.
* @param SimpleTestCase $test_case Suite or individual test
* case implementing the
* runnable test interface.
* @access public
*/
function add($test_case) {
if (! is_string($test_case)) {
$this->test_cases[] = $test_case;
} elseif (TestSuite::getBaseTestCase($test_case) == 'testsuite') {
$this->test_cases[] = new $test_case();
} else {
$this->test_cases[] = $test_case;
}
}
/**
* Builds a test suite from a library of test cases.
* The new suite is composed into this one.
* @param string $test_file File name of library with
* test case classes.
* @access public
*/
function addFile($test_file) {
$extractor = new SimpleFileLoader();
$this->add($extractor->load($test_file));
}
/**
* Delegates to a visiting collector to add test
* files.
* @param string $path Path to scan from.
* @param SimpleCollector $collector Directory scanner.
* @access public
*/
function collect($path, $collector) {
$collector->collect($this, $path);
}
/**
* Invokes run() on all of the held test cases, instantiating
* them if necessary.
* @param SimpleReporter $reporter Current test reporter.
* @access public
*/
function run($reporter) {
$reporter->paintGroupStart($this->getLabel(), $this->getSize());
for ($i = 0, $count = count($this->test_cases); $i < $count; $i++) {
if (is_string($this->test_cases[$i])) {
$class = $this->test_cases[$i];
$test = new $class();
$test->run($reporter);
unset($test);
} else {
$this->test_cases[$i]->run($reporter);
}
}
$reporter->paintGroupEnd($this->getLabel());
return $reporter->getStatus();
}
/**
* Number of contained test cases.
* @return integer Total count of cases in the group.
* @access public
*/
function getSize() {
$count = 0;
foreach ($this->test_cases as $case) {
if (is_string($case)) {
if (! SimpleTest::isIgnored($case)) {
$count++;
}
} else {
$count += $case->getSize();
}
}
return $count;
}
/**
* Test to see if a class is derived from the
* SimpleTestCase class.
* @param string $class Class name.
* @access public
*/
static function getBaseTestCase($class) {
while ($class = get_parent_class($class)) {
$class = strtolower($class);
if ($class == 'simpletestcase' || $class == 'testsuite') {
return $class;
}
}
return false;
}
}
/**
* This is a failing group test for when a test suite hasn't
* loaded properly.
* @package SimpleTest
* @subpackage UnitTester
*/
class BadTestSuite {
protected $label;
protected $error;
/**
* Sets the name of the test suite and error message.
* @param string $label Name sent at the start and end
* of the test.
* @access public
*/
function __construct($label, $error) {
$this->label = $label;
$this->error = $error;
}
/**
* Accessor for the test name for subclasses.
* @return string Name of the test.
* @access public
*/
function getLabel() {
return $this->label;
}
/**
* Sends a single error to the reporter.
* @param SimpleReporter $reporter Current test reporter.
* @access public
*/
function run($reporter) {
$reporter->paintGroupStart($this->getLabel(), $this->getSize());
$reporter->incrementFailCount();
$reporter->paintFail('Bad TestSuite [' . $this->getLabel() .
'] with error [' . $this->error . ']');
$reporter->paintGroupEnd($this->getLabel());
return $reporter->getStatus();
}
/**
* Number of contained test cases. Always zero.
* @return integer Total count of cases in the group.
* @access public
*/
function getSize() {
return 0;
}
}