1: <?php
2: /**
3: * CakeTestCase file
4: *
5: * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
6: * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
7: *
8: * Licensed under The MIT License
9: * For full copyright and license information, please see the LICENSE.txt
10: * Redistributions of files must retain the above copyright notice
11: *
12: * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
13: * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
14: * @package Cake.TestSuite
15: * @since CakePHP(tm) v 1.2.0.4667
16: * @license http://www.opensource.org/licenses/mit-license.php MIT License
17: */
18:
19: App::uses('CakeFixtureManager', 'TestSuite/Fixture');
20: App::uses('CakeTestFixture', 'TestSuite/Fixture');
21:
22: /**
23: * CakeTestCase class
24: *
25: * @package Cake.TestSuite
26: */
27: abstract class CakeTestCase extends PHPUnit_Framework_TestCase {
28:
29: /**
30: * The class responsible for managing the creation, loading and removing of fixtures
31: *
32: * @var CakeFixtureManager
33: */
34: public $fixtureManager = null;
35:
36: /**
37: * By default, all fixtures attached to this class will be truncated and reloaded after each test.
38: * Set this to false to handle manually
39: *
40: * @var array
41: */
42: public $autoFixtures = true;
43:
44: /**
45: * Control table create/drops on each test method.
46: *
47: * Set this to false to avoid tables to be dropped if they already exist
48: * between each test method. Tables will still be dropped at the
49: * end of each test runner execution.
50: *
51: * @var boolean
52: */
53: public $dropTables = true;
54:
55: /**
56: * Configure values to restore at end of test.
57: *
58: * @var array
59: */
60: protected $_configure = array();
61:
62: /**
63: * Path settings to restore at the end of the test.
64: *
65: * @var array
66: */
67: protected $_pathRestore = array();
68:
69: /**
70: * Runs the test case and collects the results in a TestResult object.
71: * If no TestResult object is passed a new one will be created.
72: * This method is run for each test method in this class
73: *
74: * @param PHPUnit_Framework_TestResult $result
75: * @return PHPUnit_Framework_TestResult
76: * @throws InvalidArgumentException
77: */
78: public function run(PHPUnit_Framework_TestResult $result = null) {
79: if (!empty($this->fixtureManager)) {
80: $this->fixtureManager->load($this);
81: }
82: $result = parent::run($result);
83: if (!empty($this->fixtureManager)) {
84: $this->fixtureManager->unload($this);
85: }
86: return $result;
87: }
88:
89: /**
90: * Called when a test case method is about to start (to be overridden when needed.)
91: *
92: * @param string $method Test method about to get executed.
93: * @return void
94: */
95: public function startTest($method) {
96: }
97:
98: /**
99: * Called when a test case method has been executed (to be overridden when needed.)
100: *
101: * @param string $method Test method about that was executed.
102: * @return void
103: */
104: public function endTest($method) {
105: }
106:
107: /**
108: * Overrides SimpleTestCase::skipIf to provide a boolean return value
109: *
110: * @param boolean $shouldSkip
111: * @param string $message
112: * @return boolean
113: */
114: public function skipIf($shouldSkip, $message = '') {
115: if ($shouldSkip) {
116: $this->markTestSkipped($message);
117: }
118: return $shouldSkip;
119: }
120:
121: /**
122: * Setup the test case, backup the static object values so they can be restored.
123: * Specifically backs up the contents of Configure and paths in App if they have
124: * not already been backed up.
125: *
126: * @return void
127: */
128: public function setUp() {
129: parent::setUp();
130:
131: if (empty($this->_configure)) {
132: $this->_configure = Configure::read();
133: }
134: if (empty($this->_pathRestore)) {
135: $this->_pathRestore = App::paths();
136: }
137: if (class_exists('Router', false)) {
138: Router::reload();
139: }
140: }
141:
142: /**
143: * teardown any static object changes and restore them.
144: *
145: * @return void
146: */
147: public function tearDown() {
148: parent::tearDown();
149: App::build($this->_pathRestore, App::RESET);
150: if (class_exists('ClassRegistry', false)) {
151: ClassRegistry::flush();
152: }
153: if (!empty($this->_configure)) {
154: Configure::clear();
155: Configure::write($this->_configure);
156: }
157: if (isset($_GET['debug']) && $_GET['debug']) {
158: ob_flush();
159: }
160: }
161:
162: /**
163: * See CakeTestSuiteDispatcher::date()
164: *
165: * @param string $format format to be used.
166: * @return string
167: */
168: public static function date($format = 'Y-m-d H:i:s') {
169: return CakeTestSuiteDispatcher::date($format);
170: }
171:
172: // @codingStandardsIgnoreStart PHPUnit overrides don't match CakePHP
173:
174: /**
175: * Announces the start of a test.
176: *
177: * @return void
178: */
179: protected function assertPreConditions() {
180: parent::assertPreConditions();
181: $this->startTest($this->getName());
182: }
183:
184: /**
185: * Announces the end of a test.
186: *
187: * @return void
188: */
189: protected function assertPostConditions() {
190: parent::assertPostConditions();
191: $this->endTest($this->getName());
192: }
193:
194: // @codingStandardsIgnoreEnd
195:
196: /**
197: * Chooses which fixtures to load for a given test
198: *
199: * @param string $fixture Each parameter is a model name that corresponds to a
200: * fixture, i.e. 'Post', 'Author', etc.
201: * @return void
202: * @see CakeTestCase::$autoFixtures
203: * @throws Exception when no fixture manager is available.
204: */
205: public function loadFixtures() {
206: if (empty($this->fixtureManager)) {
207: throw new Exception(__d('cake_dev', 'No fixture manager to load the test fixture'));
208: }
209: $args = func_get_args();
210: foreach ($args as $class) {
211: $this->fixtureManager->loadSingle($class, null, $this->dropTables);
212: }
213: }
214:
215: /**
216: * Assert text equality, ignoring differences in newlines.
217: * Helpful for doing cross platform tests of blocks of text.
218: *
219: * @param string $expected The expected value.
220: * @param string $result The actual value.
221: * @param message The message to use for failure.
222: * @return boolean
223: */
224: public function assertTextNotEquals($expected, $result, $message = '') {
225: $expected = str_replace(array("\r\n", "\r"), "\n", $expected);
226: $result = str_replace(array("\r\n", "\r"), "\n", $result);
227: return $this->assertNotEquals($expected, $result, $message);
228: }
229:
230: /**
231: * Assert text equality, ignoring differences in newlines.
232: * Helpful for doing cross platform tests of blocks of text.
233: *
234: * @param string $expected The expected value.
235: * @param string $result The actual value.
236: * @param message The message to use for failure.
237: * @return boolean
238: */
239: public function assertTextEquals($expected, $result, $message = '') {
240: $expected = str_replace(array("\r\n", "\r"), "\n", $expected);
241: $result = str_replace(array("\r\n", "\r"), "\n", $result);
242: return $this->assertEquals($expected, $result, $message);
243: }
244:
245: /**
246: * Asserts that a string starts with a given prefix, ignoring differences in newlines.
247: * Helpful for doing cross platform tests of blocks of text.
248: *
249: * @param string $prefix
250: * @param string $string
251: * @param string $message
252: * @return boolean
253: */
254: public function assertTextStartsWith($prefix, $string, $message = '') {
255: $prefix = str_replace(array("\r\n", "\r"), "\n", $prefix);
256: $string = str_replace(array("\r\n", "\r"), "\n", $string);
257: return $this->assertStringStartsWith($prefix, $string, $message);
258: }
259:
260: /**
261: * Asserts that a string starts not with a given prefix, ignoring differences in newlines.
262: * Helpful for doing cross platform tests of blocks of text.
263: *
264: * @param string $prefix
265: * @param string $string
266: * @param string $message
267: * @return boolean
268: */
269: public function assertTextStartsNotWith($prefix, $string, $message = '') {
270: $prefix = str_replace(array("\r\n", "\r"), "\n", $prefix);
271: $string = str_replace(array("\r\n", "\r"), "\n", $string);
272: return $this->assertStringStartsNotWith($prefix, $string, $message);
273: }
274:
275: /**
276: * Asserts that a string ends with a given prefix, ignoring differences in newlines.
277: * Helpful for doing cross platform tests of blocks of text.
278: *
279: * @param string $suffix
280: * @param string $string
281: * @param string $message
282: * @return boolean
283: */
284: public function assertTextEndsWith($suffix, $string, $message = '') {
285: $suffix = str_replace(array("\r\n", "\r"), "\n", $suffix);
286: $string = str_replace(array("\r\n", "\r"), "\n", $string);
287: return $this->assertStringEndsWith($suffix, $string, $message);
288: }
289:
290: /**
291: * Asserts that a string ends not with a given prefix, ignoring differences in newlines.
292: * Helpful for doing cross platform tests of blocks of text.
293: *
294: * @param string $suffix
295: * @param string $string
296: * @param string $message
297: * @return boolean
298: */
299: public function assertTextEndsNotWith($suffix, $string, $message = '') {
300: $suffix = str_replace(array("\r\n", "\r"), "\n", $suffix);
301: $string = str_replace(array("\r\n", "\r"), "\n", $string);
302: return $this->assertStringEndsNotWith($suffix, $string, $message);
303: }
304:
305: /**
306: * Assert that a string contains another string, ignoring differences in newlines.
307: * Helpful for doing cross platform tests of blocks of text.
308: *
309: * @param string $needle
310: * @param string $haystack
311: * @param string $message
312: * @param boolean $ignoreCase
313: * @return boolean
314: */
315: public function assertTextContains($needle, $haystack, $message = '', $ignoreCase = false) {
316: $needle = str_replace(array("\r\n", "\r"), "\n", $needle);
317: $haystack = str_replace(array("\r\n", "\r"), "\n", $haystack);
318: return $this->assertContains($needle, $haystack, $message, $ignoreCase);
319: }
320:
321: /**
322: * Assert that a text doesn't contain another text, ignoring differences in newlines.
323: * Helpful for doing cross platform tests of blocks of text.
324: *
325: * @param string $needle
326: * @param string $haystack
327: * @param string $message
328: * @param boolean $ignoreCase
329: * @return boolean
330: */
331: public function assertTextNotContains($needle, $haystack, $message = '', $ignoreCase = false) {
332: $needle = str_replace(array("\r\n", "\r"), "\n", $needle);
333: $haystack = str_replace(array("\r\n", "\r"), "\n", $haystack);
334: return $this->assertNotContains($needle, $haystack, $message, $ignoreCase);
335: }
336:
337: /**
338: * Takes an array $expected and generates a regex from it to match the provided $string.
339: * Samples for $expected:
340: *
341: * Checks for an input tag with a name attribute (contains any non-empty value) and an id
342: * attribute that contains 'my-input':
343: *
344: * {{{
345: * array('input' => array('name', 'id' => 'my-input'))
346: * }}}
347: *
348: * Checks for two p elements with some text in them:
349: *
350: * {{{
351: * array(
352: * array('p' => true),
353: * 'textA',
354: * '/p',
355: * array('p' => true),
356: * 'textB',
357: * '/p'
358: * )
359: * }}}
360: *
361: * You can also specify a pattern expression as part of the attribute values, or the tag
362: * being defined, if you prepend the value with preg: and enclose it with slashes, like so:
363: *
364: * {{{
365: * array(
366: * array('input' => array('name', 'id' => 'preg:/FieldName\d+/')),
367: * 'preg:/My\s+field/'
368: * )
369: * }}}
370: *
371: * Important: This function is very forgiving about whitespace and also accepts any
372: * permutation of attribute order. It will also allow whitespace between specified tags.
373: *
374: * @param string $string An HTML/XHTML/XML string
375: * @param array $expected An array, see above
376: * @param string $message SimpleTest failure output string
377: * @return boolean
378: */
379: public function assertTags($string, $expected, $fullDebug = false) {
380: $regex = array();
381: $normalized = array();
382: foreach ((array)$expected as $key => $val) {
383: if (!is_numeric($key)) {
384: $normalized[] = array($key => $val);
385: } else {
386: $normalized[] = $val;
387: }
388: }
389: $i = 0;
390: foreach ($normalized as $tags) {
391: if (!is_array($tags)) {
392: $tags = (string)$tags;
393: }
394: $i++;
395: if (is_string($tags) && $tags{0} === '<') {
396: $tags = array(substr($tags, 1) => array());
397: } elseif (is_string($tags)) {
398: $tagsTrimmed = preg_replace('/\s+/m', '', $tags);
399:
400: if (preg_match('/^\*?\//', $tags, $match) && $tagsTrimmed !== '//') {
401: $prefix = array(null, null);
402:
403: if ($match[0] === '*/') {
404: $prefix = array('Anything, ', '.*?');
405: }
406: $regex[] = array(
407: sprintf('%sClose %s tag', $prefix[0], substr($tags, strlen($match[0]))),
408: sprintf('%s<[\s]*\/[\s]*%s[\s]*>[\n\r]*', $prefix[1], substr($tags, strlen($match[0]))),
409: $i,
410: );
411: continue;
412: }
413: if (!empty($tags) && preg_match('/^preg\:\/(.+)\/$/i', $tags, $matches)) {
414: $tags = $matches[1];
415: $type = 'Regex matches';
416: } else {
417: $tags = preg_quote($tags, '/');
418: $type = 'Text equals';
419: }
420: $regex[] = array(
421: sprintf('%s "%s"', $type, $tags),
422: $tags,
423: $i,
424: );
425: continue;
426: }
427: foreach ($tags as $tag => $attributes) {
428: $regex[] = array(
429: sprintf('Open %s tag', $tag),
430: sprintf('[\s]*<%s', preg_quote($tag, '/')),
431: $i,
432: );
433: if ($attributes === true) {
434: $attributes = array();
435: }
436: $attrs = array();
437: $explanations = array();
438: $i = 1;
439: foreach ($attributes as $attr => $val) {
440: if (is_numeric($attr) && preg_match('/^preg\:\/(.+)\/$/i', $val, $matches)) {
441: $attrs[] = $matches[1];
442: $explanations[] = sprintf('Regex "%s" matches', $matches[1]);
443: continue;
444: } else {
445: $quotes = '["\']';
446: if (is_numeric($attr)) {
447: $attr = $val;
448: $val = '.+?';
449: $explanations[] = sprintf('Attribute "%s" present', $attr);
450: } elseif (!empty($val) && preg_match('/^preg\:\/(.+)\/$/i', $val, $matches)) {
451: $val = str_replace(
452: array('.*', '.+'),
453: array('.*?', '.+?'),
454: $matches[1]
455: );
456: $quotes = $val !== $matches[1] ? '["\']' : '["\']?';
457:
458: $explanations[] = sprintf('Attribute "%s" matches "%s"', $attr, $val);
459: } else {
460: $explanations[] = sprintf('Attribute "%s" == "%s"', $attr, $val);
461: $val = preg_quote($val, '/');
462: }
463: $attrs[] = '[\s]+' . preg_quote($attr, '/') . '=' . $quotes . $val . $quotes;
464: }
465: $i++;
466: }
467: if ($attrs) {
468: $regex[] = array(
469: 'explains' => $explanations,
470: 'attrs' => $attrs,
471: );
472: }
473: $regex[] = array(
474: sprintf('End %s tag', $tag),
475: '[\s]*\/?[\s]*>[\n\r]*',
476: $i,
477: );
478: }
479: }
480: foreach ($regex as $i => $assertion) {
481: $matches = false;
482: if (isset($assertion['attrs'])) {
483: $string = $this->_assertAttributes($assertion, $string);
484: continue;
485: }
486:
487: list($description, $expressions, $itemNum) = $assertion;
488: foreach ((array)$expressions as $expression) {
489: if (preg_match(sprintf('/^%s/s', $expression), $string, $match)) {
490: $matches = true;
491: $string = substr($string, strlen($match[0]));
492: break;
493: }
494: }
495: if (!$matches) {
496: $this->assertTrue(false, sprintf('Item #%d / regex #%d failed: %s', $itemNum, $i, $description));
497: if ($fullDebug) {
498: debug($string, true);
499: debug($regex, true);
500: }
501: return false;
502: }
503: }
504:
505: $this->assertTrue(true, '%s');
506: return true;
507: }
508:
509: /**
510: * Check the attributes as part of an assertTags() check.
511: *
512: * @param array $assertions Assertions to run.
513: * @param string $string The HTML string to check.
514: * @return void
515: */
516: protected function _assertAttributes($assertions, $string) {
517: $asserts = $assertions['attrs'];
518: $explains = $assertions['explains'];
519: $len = count($asserts);
520: do {
521: $matches = false;
522: foreach ($asserts as $j => $assert) {
523: if (preg_match(sprintf('/^%s/s', $assert), $string, $match)) {
524: $matches = true;
525: $string = substr($string, strlen($match[0]));
526: array_splice($asserts, $j, 1);
527: array_splice($explains, $j, 1);
528: break;
529: }
530: }
531: if ($matches === false) {
532: $this->assertTrue(false, 'Attribute did not match. Was expecting ' . $explains[$j]);
533: }
534: $len = count($asserts);
535: } while ($len > 0);
536: return $string;
537: }
538:
539: // @codingStandardsIgnoreStart
540:
541: /**
542: * Compatibility wrapper function for assertEquals
543: *
544: *
545: * @param mixed $result
546: * @param mixed $expected
547: * @param string $message the text to display if the assertion is not correct
548: * @deprecated This is a compatiblity wrapper for 1.x. It will be removed in 3.0
549: * @return void
550: */
551: protected static function assertEqual($result, $expected, $message = '') {
552: return self::assertEquals($expected, $result, $message);
553: }
554:
555: /**
556: * Compatibility wrapper function for assertNotEquals
557: *
558: * @param mixed $result
559: * @param mixed $expected
560: * @param string $message the text to display if the assertion is not correct
561: * @deprecated This is a compatiblity wrapper for 1.x. It will be removed in 3.0
562: * @return void
563: */
564: protected static function assertNotEqual($result, $expected, $message = '') {
565: return self::assertNotEquals($expected, $result, $message);
566: }
567:
568: /**
569: * Compatibility wrapper function for assertRegexp
570: *
571: * @param mixed $pattern a regular expression
572: * @param string $string the text to be matched
573: * @param string $message the text to display if the assertion is not correct
574: * @deprecated This is a compatiblity wrapper for 1.x. It will be removed in 3.0
575: * @return void
576: */
577: protected static function assertPattern($pattern, $string, $message = '') {
578: return self::assertRegExp($pattern, $string, $message);
579: }
580:
581: /**
582: * Compatibility wrapper function for assertEquals
583: *
584: * @param mixed $actual
585: * @param mixed $expected
586: * @param string $message the text to display if the assertion is not correct
587: * @deprecated This is a compatiblity wrapper for 1.x. It will be removed in 3.0
588: * @return void
589: */
590: protected static function assertIdentical($actual, $expected, $message = '') {
591: return self::assertSame($expected, $actual, $message);
592: }
593:
594: /**
595: * Compatibility wrapper function for assertNotEquals
596: *
597: * @param mixed $actual
598: * @param mixed $expected
599: * @param string $message the text to display if the assertion is not correct
600: * @deprecated This is a compatiblity wrapper for 1.x. It will be removed in 3.0
601: * @return void
602: */
603: protected static function assertNotIdentical($actual, $expected, $message = '') {
604: return self::assertNotSame($expected, $actual, $message);
605: }
606:
607: /**
608: * Compatibility wrapper function for assertNotRegExp
609: *
610: * @param mixed $pattern a regular expression
611: * @param string $string the text to be matched
612: * @param string $message the text to display if the assertion is not correct
613: * @deprecated This is a compatiblity wrapper for 1.x. It will be removed in 3.0
614: * @return void
615: */
616: protected static function assertNoPattern($pattern, $string, $message = '') {
617: return self::assertNotRegExp($pattern, $string, $message);
618: }
619:
620: /**
621: * assert no errors
622: *
623: * @deprecated This is a compatiblity wrapper for 1.x. It will be removed in 3.0
624: * @return void
625: */
626: protected function assertNoErrors() {
627: }
628:
629: /**
630: * Compatibility wrapper function for setExpectedException
631: *
632: * @param mixed $expected the name of the Exception or error
633: * @param string $message the text to display if the assertion is not correct
634: * @deprecated This is a compatiblity wrapper for 1.x. It will be removed in 3.0
635: * @return void
636: */
637: protected function expectError($expected = false, $message = '') {
638: if (!$expected) {
639: $expected = 'Exception';
640: }
641: $this->setExpectedException($expected, $message);
642: }
643:
644: /**
645: * Compatibility wrapper function for setExpectedException
646: *
647: * @param mixed $expected the name of the Exception
648: * @param string $message the text to display if the assertion is not correct
649: * @deprecated This is a compatiblity wrapper for 1.x. It will be removed in 3.0
650: * @return void
651: */
652: protected function expectException($name = 'Exception', $message = '') {
653: $this->setExpectedException($name, $message);
654: }
655:
656: /**
657: * Compatibility wrapper function for assertSame
658: *
659: * @param mixed $first
660: * @param mixed $second
661: * @param string $message the text to display if the assertion is not correct
662: * @deprecated This is a compatiblity wrapper for 1.x. It will be removed in 3.0
663: * @return void
664: */
665: protected static function assertReference(&$first, &$second, $message = '') {
666: return self::assertSame($first, $second, $message);
667: }
668:
669: /**
670: * Compatibility wrapper for assertIsA
671: *
672: * @param string $object
673: * @param string $type
674: * @param string $message
675: * @deprecated This is a compatiblity wrapper for 1.x. It will be removed in 3.0
676: * @return void
677: */
678: protected static function assertIsA($object, $type, $message = '') {
679: return self::assertInstanceOf($type, $object, $message);
680: }
681:
682: /**
683: * Compatibility function to test if value is between an acceptable range
684: *
685: * @param mixed $result
686: * @param mixed $expected
687: * @param mixed $margin the rage of acceptation
688: * @param string $message the text to display if the assertion is not correct
689: * @return void
690: */
691: protected static function assertWithinMargin($result, $expected, $margin, $message = '') {
692: $upper = $result + $margin;
693: $lower = $result - $margin;
694: return self::assertTrue((($expected <= $upper) && ($expected >= $lower)), $message);
695: }
696:
697: /**
698: * Compatibility function for skipping.
699: *
700: * @param boolean $condition Condition to trigger skipping
701: * @param string $message Message for skip
702: * @return boolean
703: */
704: protected function skipUnless($condition, $message = '') {
705: if (!$condition) {
706: $this->markTestSkipped($message);
707: }
708: return $condition;
709: }
710: // @codingStandardsIgnoreEnd
711:
712: /**
713: * Mock a model, maintain fixtures and table association
714: *
715: * @param string $model
716: * @param mixed $methods
717: * @param array $config
718: * @throws MissingModelException
719: * @return Model
720: */
721: public function getMockForModel($model, $methods = array(), $config = array()) {
722: $config += ClassRegistry::config('Model');
723:
724: list($plugin, $name) = pluginSplit($model, true);
725: App::uses($name, $plugin . 'Model');
726: $config = array_merge((array)$config, array('name' => $name));
727:
728: if (!class_exists($name)) {
729: throw new MissingModelException(array($model));
730: }
731:
732: $mock = $this->getMock($name, $methods, array($config));
733: ClassRegistry::removeObject($name);
734: ClassRegistry::addObject($name, $mock);
735: return $mock;
736: }
737:
738: }
739: