PageRenderTime 51ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Cake/TestSuite/CakeTestCase.php

https://bitbucket.org/udeshika/fake_twitter
PHP | 534 lines | 257 code | 36 blank | 241 comment | 41 complexity | 46c6fbdfa5866410805a7469d5af950d MD5 | raw file
  1. <?php
  2. /**
  3. * CakeTestCase file
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) Tests <http://book.cakephp.org/view/1196/Testing>
  8. * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * Redistributions of files must retain the above copyright notice
  12. *
  13. * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://book.cakephp.org/view/1196/Testing CakePHP(tm) Tests
  15. * @package Cake.TestSuite
  16. * @since CakePHP(tm) v 1.2.0.4667
  17. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  18. */
  19. App::uses('CakeFixtureManager', 'TestSuite/Fixture');
  20. App::uses('CakeTestFixture', 'TestSuite/Fixture');
  21. /**
  22. * CakeTestCase class
  23. *
  24. * @package Cake.TestSuite
  25. */
  26. abstract class CakeTestCase extends PHPUnit_Framework_TestCase {
  27. /**
  28. * The class responsible for managing the creation, loading and removing of fixtures
  29. *
  30. * @var CakeFixtureManager
  31. */
  32. public $fixtureManager = null;
  33. /**
  34. * By default, all fixtures attached to this class will be truncated and reloaded after each test.
  35. * Set this to false to handle manually
  36. *
  37. * @var array
  38. */
  39. public $autoFixtures = true;
  40. /**
  41. * Set this to false to avoid tables to be dropped if they already exist
  42. *
  43. * @var boolean
  44. */
  45. public $dropTables = true;
  46. /**
  47. * Configure values to restore at end of test.
  48. *
  49. * @var array
  50. */
  51. protected $_configure = array();
  52. /**
  53. * Path settings to restore at the end of the test.
  54. *
  55. * @var array
  56. */
  57. protected $_pathRestore = array();
  58. /**
  59. * Runs the test case and collects the results in a TestResult object.
  60. * If no TestResult object is passed a new one will be created.
  61. * This method is run for each test method in this class
  62. *
  63. * @param PHPUnit_Framework_TestResult $result
  64. * @return PHPUnit_Framework_TestResult
  65. * @throws InvalidArgumentException
  66. */
  67. public function run(PHPUnit_Framework_TestResult $result = NULL) {
  68. if (!empty($this->fixtureManager)) {
  69. $this->fixtureManager->load($this);
  70. }
  71. $result = parent::run($result);
  72. if (!empty($this->fixtureManager)) {
  73. $this->fixtureManager->unload($this);
  74. }
  75. return $result;
  76. }
  77. /**
  78. * Called when a test case method is about to start (to be overridden when needed.)
  79. *
  80. * @param string $method Test method about to get executed.
  81. * @return void
  82. */
  83. public function startTest($method) {
  84. }
  85. /**
  86. * Called when a test case method has been executed (to be overridden when needed.)
  87. *
  88. * @param string $method Test method about that was executed.
  89. * @return void
  90. */
  91. public function endTest($method) {
  92. }
  93. /**
  94. * Overrides SimpleTestCase::skipIf to provide a boolean return value
  95. *
  96. * @param boolean $shouldSkip
  97. * @param string $message
  98. * @return boolean
  99. */
  100. public function skipIf($shouldSkip, $message = '') {
  101. if ($shouldSkip) {
  102. $this->markTestSkipped($message);
  103. }
  104. return $shouldSkip;
  105. }
  106. /**
  107. * Setup the test case, backup the static object values so they can be restored.
  108. * Specifically backs up the contents of Configure and paths in App if they have
  109. * not already been backed up.
  110. *
  111. * @return void
  112. */
  113. public function setUp() {
  114. parent::setUp();
  115. if (empty($this->_configure)) {
  116. $this->_configure = Configure::read();
  117. }
  118. if (empty($this->_pathRestore)) {
  119. $this->_pathRestore = App::paths();
  120. }
  121. if (class_exists('Router', false)) {
  122. Router::reload();
  123. }
  124. }
  125. /**
  126. * teardown any static object changes and restore them.
  127. *
  128. * @return void
  129. */
  130. public function tearDown() {
  131. parent::tearDown();
  132. App::build($this->_pathRestore, App::RESET);
  133. if (class_exists('ClassRegistry', false)) {
  134. ClassRegistry::flush();
  135. }
  136. Configure::write($this->_configure);
  137. if (isset($_GET['debug']) && $_GET['debug']) {
  138. ob_flush();
  139. }
  140. }
  141. /**
  142. * Announces the start of a test.
  143. *
  144. * @param string $method Test method just started.
  145. * @return void
  146. */
  147. protected function assertPreConditions() {
  148. parent::assertPreConditions();
  149. $this->startTest($this->getName());
  150. }
  151. /**
  152. * Announces the end of a test.
  153. *
  154. * @param string $method Test method just finished.
  155. * @return void
  156. */
  157. protected function assertPostConditions() {
  158. parent::assertPostConditions();
  159. $this->endTest($this->getName());
  160. }
  161. /**
  162. * Chooses which fixtures to load for a given test
  163. *
  164. * @param string $fixture Each parameter is a model name that corresponds to a
  165. * fixture, i.e. 'Post', 'Author', etc.
  166. * @return void
  167. * @see CakeTestCase::$autoFixtures
  168. */
  169. public function loadFixtures() {
  170. if (empty($this->fixtureManager)) {
  171. throw new Exception(__d('cake_dev', 'No fixture manager to load the test fixture'));
  172. }
  173. $args = func_get_args();
  174. foreach ($args as $class) {
  175. $this->fixtureManager->loadSingle($class);
  176. }
  177. }
  178. /**
  179. * Takes an array $expected and generates a regex from it to match the provided $string.
  180. * Samples for $expected:
  181. *
  182. * Checks for an input tag with a name attribute (contains any non-empty value) and an id
  183. * attribute that contains 'my-input':
  184. * array('input' => array('name', 'id' => 'my-input'))
  185. *
  186. * Checks for two p elements with some text in them:
  187. * array(
  188. * array('p' => true),
  189. * 'textA',
  190. * '/p',
  191. * array('p' => true),
  192. * 'textB',
  193. * '/p'
  194. * )
  195. *
  196. * You can also specify a pattern expression as part of the attribute values, or the tag
  197. * being defined, if you prepend the value with preg: and enclose it with slashes, like so:
  198. * array(
  199. * array('input' => array('name', 'id' => 'preg:/FieldName\d+/')),
  200. * 'preg:/My\s+field/'
  201. * )
  202. *
  203. * Important: This function is very forgiving about whitespace and also accepts any
  204. * permutation of attribute order. It will also allow whitespace between specified tags.
  205. *
  206. * @param string $string An HTML/XHTML/XML string
  207. * @param array $expected An array, see above
  208. * @param string $message SimpleTest failure output string
  209. * @return boolean
  210. */
  211. public function assertTags($string, $expected, $fullDebug = false) {
  212. $regex = array();
  213. $normalized = array();
  214. foreach ((array) $expected as $key => $val) {
  215. if (!is_numeric($key)) {
  216. $normalized[] = array($key => $val);
  217. } else {
  218. $normalized[] = $val;
  219. }
  220. }
  221. $i = 0;
  222. foreach ($normalized as $tags) {
  223. if (!is_array($tags)) {
  224. $tags = (string)$tags;
  225. }
  226. $i++;
  227. if (is_string($tags) && $tags{0} == '<') {
  228. $tags = array(substr($tags, 1) => array());
  229. } elseif (is_string($tags)) {
  230. $tagsTrimmed = preg_replace('/\s+/m', '', $tags);
  231. if (preg_match('/^\*?\//', $tags, $match) && $tagsTrimmed !== '//') {
  232. $prefix = array(null, null);
  233. if ($match[0] == '*/') {
  234. $prefix = array('Anything, ', '.*?');
  235. }
  236. $regex[] = array(
  237. sprintf('%sClose %s tag', $prefix[0], substr($tags, strlen($match[0]))),
  238. sprintf('%s<[\s]*\/[\s]*%s[\s]*>[\n\r]*', $prefix[1], substr($tags, strlen($match[0]))),
  239. $i,
  240. );
  241. continue;
  242. }
  243. if (!empty($tags) && preg_match('/^preg\:\/(.+)\/$/i', $tags, $matches)) {
  244. $tags = $matches[1];
  245. $type = 'Regex matches';
  246. } else {
  247. $tags = preg_quote($tags, '/');
  248. $type = 'Text equals';
  249. }
  250. $regex[] = array(
  251. sprintf('%s "%s"', $type, $tags),
  252. $tags,
  253. $i,
  254. );
  255. continue;
  256. }
  257. foreach ($tags as $tag => $attributes) {
  258. $regex[] = array(
  259. sprintf('Open %s tag', $tag),
  260. sprintf('[\s]*<%s', preg_quote($tag, '/')),
  261. $i,
  262. );
  263. if ($attributes === true) {
  264. $attributes = array();
  265. }
  266. $attrs = array();
  267. $explanations = array();
  268. $i = 1;
  269. foreach ($attributes as $attr => $val) {
  270. if (is_numeric($attr) && preg_match('/^preg\:\/(.+)\/$/i', $val, $matches)) {
  271. $attrs[] = $matches[1];
  272. $explanations[] = sprintf('Regex "%s" matches', $matches[1]);
  273. continue;
  274. } else {
  275. $quotes = '["\']';
  276. if (is_numeric($attr)) {
  277. $attr = $val;
  278. $val = '.+?';
  279. $explanations[] = sprintf('Attribute "%s" present', $attr);
  280. } elseif (!empty($val) && preg_match('/^preg\:\/(.+)\/$/i', $val, $matches)) {
  281. $quotes = '["\']?';
  282. $val = $matches[1];
  283. $explanations[] = sprintf('Attribute "%s" matches "%s"', $attr, $val);
  284. } else {
  285. $explanations[] = sprintf('Attribute "%s" == "%s"', $attr, $val);
  286. $val = preg_quote($val, '/');
  287. }
  288. $attrs[] = '[\s]+' . preg_quote($attr, '/') . '=' . $quotes . $val . $quotes;
  289. }
  290. $i++;
  291. }
  292. if ($attrs) {
  293. $permutations = $this->_array_permute($attrs);
  294. $permutationTokens = array();
  295. foreach ($permutations as $permutation) {
  296. $permutationTokens[] = implode('', $permutation);
  297. }
  298. $regex[] = array(
  299. sprintf('%s', implode(', ', $explanations)),
  300. $permutationTokens,
  301. $i,
  302. );
  303. }
  304. $regex[] = array(
  305. sprintf('End %s tag', $tag),
  306. '[\s]*\/?[\s]*>[\n\r]*',
  307. $i,
  308. );
  309. }
  310. }
  311. foreach ($regex as $i => $assertation) {
  312. list($description, $expressions, $itemNum) = $assertation;
  313. $matches = false;
  314. foreach ((array)$expressions as $expression) {
  315. if (preg_match(sprintf('/^%s/s', $expression), $string, $match)) {
  316. $matches = true;
  317. $string = substr($string, strlen($match[0]));
  318. break;
  319. }
  320. }
  321. if (!$matches) {
  322. $this->assertTrue(false, sprintf('Item #%d / regex #%d failed: %s', $itemNum, $i, $description));
  323. if ($fullDebug) {
  324. debug($string, true);
  325. debug($regex, true);
  326. }
  327. return false;
  328. }
  329. }
  330. $this->assertTrue(true, '%s');
  331. return true;
  332. }
  333. /**
  334. * Generates all permutation of an array $items and returns them in a new array.
  335. *
  336. * @param array $items An array of items
  337. * @return array
  338. */
  339. protected function _array_permute($items, $perms = array()) {
  340. static $permuted;
  341. if (empty($perms)) {
  342. $permuted = array();
  343. }
  344. if (empty($items)) {
  345. $permuted[] = $perms;
  346. } else {
  347. $numItems = count($items) - 1;
  348. for ($i = $numItems; $i >= 0; --$i) {
  349. $newItems = $items;
  350. $newPerms = $perms;
  351. list($tmp) = array_splice($newItems, $i, 1);
  352. array_unshift($newPerms, $tmp);
  353. $this->_array_permute($newItems, $newPerms);
  354. }
  355. return $permuted;
  356. }
  357. }
  358. /**
  359. * Compatibility wrapper function for assertEquals
  360. *
  361. * @param mixed $result
  362. * @param mixed $expected
  363. * @param string $message the text to display if the assertion is not correct
  364. * @return void
  365. */
  366. protected static function assertEqual($result, $expected, $message = '') {
  367. return self::assertEquals($expected, $result, $message);
  368. }
  369. /**
  370. * Compatibility wrapper function for assertNotEquals
  371. *
  372. * @param mixed $result
  373. * @param mixed $expected
  374. * @param string $message the text to display if the assertion is not correct
  375. * @return void
  376. */
  377. protected static function assertNotEqual($result, $expected, $message = '') {
  378. return self::assertNotEquals($expected, $result, $message);
  379. }
  380. /**
  381. * Compatibility wrapper function for assertRegexp
  382. *
  383. * @param mixed $pattern a regular expression
  384. * @param string $string the text to be matched
  385. * @param string $message the text to display if the assertion is not correct
  386. * @return void
  387. */
  388. protected static function assertPattern($pattern, $string, $message = '') {
  389. return self::assertRegExp($pattern, $string, $message);
  390. }
  391. /**
  392. * Compatibility wrapper function for assertEquals
  393. *
  394. * @param mixed $actual
  395. * @param mixed $expected
  396. * @param string $message the text to display if the assertion is not correct
  397. * @return void
  398. */
  399. protected static function assertIdentical($actual, $expected, $message = '') {
  400. return self::assertSame($expected, $actual, $message);
  401. }
  402. /**
  403. * Compatibility wrapper function for assertNotEquals
  404. *
  405. * @param mixed $actual
  406. * @param mixed $expected
  407. * @param string $message the text to display if the assertion is not correct
  408. * @return void
  409. */
  410. protected static function assertNotIdentical($actual, $expected, $message = '') {
  411. return self::assertNotSame($expected, $actual, $message);
  412. }
  413. /**
  414. * Compatibility wrapper function for assertNotRegExp
  415. *
  416. * @param mixed $pattern a regular expression
  417. * @param string $string the text to be matched
  418. * @param string $message the text to display if the assertion is not correct
  419. * @return void
  420. */
  421. protected static function assertNoPattern($pattern, $string, $message = '') {
  422. return self::assertNotRegExp($pattern, $string, $message);
  423. }
  424. protected function assertNoErrors() {
  425. }
  426. /**
  427. * Compatibility wrapper function for setExpectedException
  428. *
  429. * @param mixed $expected the name of the Exception or error
  430. * @param string $message the text to display if the assertion is not correct
  431. * @return void
  432. */
  433. protected function expectError($expected = false, $message = '') {
  434. if (!$expected) {
  435. $expected = 'Exception';
  436. }
  437. $this->setExpectedException($expected, $message);
  438. }
  439. /**
  440. * Compatibility wrapper function for setExpectedException
  441. *
  442. * @param mixed $expected the name of the Exception
  443. * @param string $message the text to display if the assertion is not correct
  444. * @return void
  445. */
  446. protected function expectException($name = 'Exception', $message = '') {
  447. $this->setExpectedException($name, $message);
  448. }
  449. /**
  450. * Compatibility wrapper function for assertSame
  451. *
  452. * @param mixed $first
  453. * @param mixed $second
  454. * @param string $message the text to display if the assertion is not correct
  455. * @return void
  456. */
  457. protected static function assertReference(&$first, &$second, $message = '') {
  458. return self::assertSame($first, $second, $message);
  459. }
  460. /**
  461. * Compatibility wrapper for assertIsA
  462. *
  463. * @param string $object
  464. * @param string $type
  465. * @param string $message
  466. * @return void
  467. */
  468. protected static function assertIsA($object, $type, $message = '') {
  469. return self::assertInstanceOf($type, $object, $message);
  470. }
  471. /**
  472. * Compatibility function to test if value is between an acceptable range
  473. *
  474. * @param mixed $result
  475. * @param mixed $expected
  476. * @param mixed $margin the rage of acceptation
  477. * @param string $message the text to display if the assertion is not correct
  478. * @return void
  479. */
  480. protected static function assertWithinMargin($result, $expected, $margin, $message = '') {
  481. $upper = $result + $margin;
  482. $lower = $result - $margin;
  483. return self::assertTrue((($expected <= $upper) && ($expected >= $lower)), $message);
  484. }
  485. /**
  486. * Compatibility function for skipping.
  487. *
  488. * @param boolean $condition Condition to trigger skipping
  489. * @param string $message Message for skip
  490. * @return boolean
  491. */
  492. protected function skipUnless($condition, $message = '') {
  493. if (!$condition) {
  494. $this->markTestSkipped($message);
  495. }
  496. return $condition;
  497. }
  498. }