ControllerTestCase.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. <?php
  2. /**
  3. * ControllerTestCase 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 2.0
  17. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  18. */
  19. PHP_CodeCoverage_Filter::getInstance()->addFileToBlacklist(__FILE__, 'DEFAULT');
  20. App::uses('Dispatcher', 'Routing');
  21. App::uses('CakeTestCase', 'TestSuite');
  22. App::uses('Router', 'Routing');
  23. App::uses('CakeRequest', 'Network');
  24. App::uses('CakeResponse', 'Network');
  25. App::uses('Helper', 'View');
  26. /**
  27. * ControllerTestDispatcher class
  28. *
  29. * @package Cake.TestSuite
  30. */
  31. class ControllerTestDispatcher extends Dispatcher {
  32. /**
  33. * The controller to use in the dispatch process
  34. *
  35. * @var Controller
  36. */
  37. public $testController = null;
  38. /**
  39. * Use custom routes during tests
  40. *
  41. * @var boolean
  42. */
  43. public $loadRoutes = true;
  44. /**
  45. * Returns the test controller
  46. *
  47. * @return Controller
  48. */
  49. function _getController($request, $response) {
  50. if ($this->testController === null) {
  51. $this->testController = parent::_getController($request, $response);
  52. }
  53. $this->testController->helpers = array_merge(array('InterceptContent'), $this->testController->helpers);
  54. $this->testController->setRequest($request);
  55. $this->testController->response = $this->response;
  56. return $this->testController;
  57. }
  58. /**
  59. * Loads routes and resets if the test case dictates it should
  60. *
  61. * @return void
  62. */
  63. protected function _loadRoutes() {
  64. parent::_loadRoutes();
  65. if (!$this->loadRoutes) {
  66. Router::reload();
  67. }
  68. }
  69. }
  70. /**
  71. * InterceptContentHelper class
  72. *
  73. * @package Cake.TestSuite
  74. */
  75. class InterceptContentHelper extends Helper {
  76. /**
  77. * Intercepts and stores the contents of the view before the layout is rendered
  78. *
  79. * @param string $viewFile The view file
  80. */
  81. public function afterRender($viewFile) {
  82. $this->_View->_viewNoLayout = $this->_View->output;
  83. $this->_View->Helpers->unload('InterceptContent');
  84. }
  85. }
  86. /**
  87. * ControllerTestCase class
  88. *
  89. * @package Cake.TestSuite
  90. */
  91. abstract class ControllerTestCase extends CakeTestCase {
  92. /**
  93. * The controller to test in testAction
  94. *
  95. * @var Controller
  96. */
  97. public $controller = null;
  98. /**
  99. * Automatically mock controllers that aren't mocked
  100. *
  101. * @var boolean
  102. */
  103. public $autoMock = false;
  104. /**
  105. * Use custom routes during tests
  106. *
  107. * @var boolean
  108. */
  109. public $loadRoutes = true;
  110. /**
  111. * The resulting view vars of the last testAction call
  112. *
  113. * @var array
  114. */
  115. public $vars = null;
  116. /**
  117. * The resulting rendered view of the last testAction call
  118. *
  119. * @var string
  120. */
  121. public $view = null;
  122. /**
  123. * The resulting rendered layout+view of the last testAction call
  124. *
  125. * @var string
  126. */
  127. public $contents = null;
  128. /**
  129. * The returned result of the dispatch (requestAction), if any
  130. *
  131. * @var string
  132. */
  133. public $result = null;
  134. /**
  135. * The headers that would have been sent by the action
  136. *
  137. * @var string
  138. */
  139. public $headers = null;
  140. /**
  141. * Flag for checking if the controller instance is dirty.
  142. * Once a test has been run on a controller it should be rebuilt
  143. * to clean up properties.
  144. *
  145. * @var boolean
  146. */
  147. private $__dirtyController = false;
  148. /**
  149. * Used to enable calling ControllerTestCase::testAction() without the testing
  150. * framework thinking that it's a test case
  151. *
  152. * @param string $name The name of the function
  153. * @param array $arguments Array of arguments
  154. * @return Function
  155. */
  156. public function __call($name, $arguments) {
  157. if ($name == 'testAction') {
  158. return call_user_func_array(array($this, '_testAction'), $arguments);
  159. }
  160. }
  161. /**
  162. * Tests a controller action.
  163. *
  164. * ### Options:
  165. *
  166. * - `data` POST or GET data to pass. Depends on the method.
  167. * - `method` POST or GET. Defaults to POST.
  168. * - `return` Specify the return type you want. Choose from:
  169. * - `vars` Get the set view variables.
  170. * - `view` Get the rendered view, without a layout.
  171. * - `contents` Get the rendered view including the layout.
  172. * - `result` Get the return value of the controller action. Useful
  173. * for testing requestAction methods.
  174. *
  175. * @param string $url The url to test
  176. * @param array $options See options
  177. */
  178. protected function _testAction($url = '', $options = array()) {
  179. $this->vars = $this->result = $this->view = $this->contents = $this->headers = null;
  180. $options = array_merge(array(
  181. 'data' => array(),
  182. 'method' => 'POST',
  183. 'return' => 'result'
  184. ), $options);
  185. $_SERVER['REQUEST_METHOD'] = strtoupper($options['method']);
  186. if (strtoupper($options['method']) == 'GET') {
  187. $_GET = $options['data'];
  188. $_POST = array();
  189. } else {
  190. $_POST = $options['data'];
  191. $_GET = array();
  192. }
  193. $request = new CakeRequest($url);
  194. $Dispatch = new ControllerTestDispatcher();
  195. foreach (Router::$routes as $route) {
  196. if ($route instanceof RedirectRoute) {
  197. $route->response = $this->getMock('CakeResponse', array('send'));
  198. }
  199. }
  200. $Dispatch->loadRoutes = $this->loadRoutes;
  201. $request = $Dispatch->parseParams($request);
  202. if (!isset($request->params['controller'])) {
  203. $this->headers = Router::currentRoute()->response->header();
  204. return;
  205. }
  206. if ($this->__dirtyController) {
  207. $this->controller = null;
  208. }
  209. $plugin = empty($request->params['plugin']) ? '' : Inflector::camelize($request->params['plugin']) . '.';
  210. if ($this->controller === null && $this->autoMock) {
  211. $this->generate(Inflector::camelize($plugin . $request->params['controller']));
  212. }
  213. $params = array();
  214. if ($options['return'] == 'result') {
  215. $params['return'] = 1;
  216. $params['bare'] = 1;
  217. $params['requested'] = 1;
  218. }
  219. $Dispatch->testController = $this->controller;
  220. $Dispatch->response = $this->getMock('CakeResponse', array('send'));
  221. $this->result = $Dispatch->dispatch($request, $Dispatch->response, $params);
  222. $this->controller = $Dispatch->testController;
  223. if ($options['return'] != 'result') {
  224. if (isset($this->controller->View)) {
  225. $this->vars = $this->controller->View->viewVars;
  226. $this->view = $this->controller->View->_viewNoLayout;
  227. }
  228. $this->contents = $this->controller->response->body();
  229. }
  230. $this->__dirtyController = true;
  231. $this->headers = $Dispatch->response->header();
  232. return $this->{$options['return']};
  233. }
  234. /**
  235. * Generates a mocked controller and mocks any classes passed to `$mocks`. By
  236. * default, `_stop()` is stubbed as is sending the response headers, so to not
  237. * interfere with testing.
  238. *
  239. * ### Mocks:
  240. *
  241. * - `methods` Methods to mock on the controller. `_stop()` is mocked by default
  242. * - `models` Models to mock. Models are added to the ClassRegistry so they any
  243. * time they are instatiated the mock will be created. Pass as key value pairs
  244. * with the value being specific methods on the model to mock. If `true` or
  245. * no value is passed, the entire model will be mocked.
  246. * - `components` Components to mock. Components are only mocked on this controller
  247. * and not within each other (i.e., components on components)
  248. *
  249. * @param string $controller Controller name
  250. * @param array $mocks List of classes and methods to mock
  251. * @return Controller Mocked controller
  252. */
  253. public function generate($controller, $mocks = array()) {
  254. list($plugin, $controller) = pluginSplit($controller);
  255. if ($plugin) {
  256. App::uses($plugin . 'AppController', $plugin . '.Controller');
  257. $plugin .= '.';
  258. }
  259. App::uses($controller . 'Controller', $plugin . 'Controller');
  260. if (!class_exists($controller.'Controller')) {
  261. throw new MissingControllerException(array(
  262. 'class' => $controller . 'Controller',
  263. 'plugin' => substr($plugin, 0, -1)
  264. ));
  265. }
  266. ClassRegistry::flush();
  267. $mocks = array_merge_recursive(array(
  268. 'methods' => array('_stop'),
  269. 'models' => array(),
  270. 'components' => array()
  271. ), (array)$mocks);
  272. list($plugin, $name) = pluginSplit($controller);
  273. $_controller = $this->getMock($name.'Controller', $mocks['methods'], array(), '', false);
  274. $_controller->name = $name;
  275. $request = $this->getMock('CakeRequest');
  276. $response = $this->getMock('CakeResponse', array('_sendHeader'));
  277. $_controller->__construct($request, $response);
  278. $config = ClassRegistry::config('Model');
  279. foreach ($mocks['models'] as $model => $methods) {
  280. if (is_string($methods)) {
  281. $model = $methods;
  282. $methods = true;
  283. }
  284. if ($methods === true) {
  285. $methods = array();
  286. }
  287. ClassRegistry::init($model);
  288. list($plugin, $name) = pluginSplit($model);
  289. $config = array_merge((array)$config, array('name' => $model));
  290. $_model = $this->getMock($name, $methods, array($config));
  291. ClassRegistry::removeObject($name);
  292. ClassRegistry::addObject($name, $_model);
  293. }
  294. foreach ($mocks['components'] as $component => $methods) {
  295. if (is_string($methods)) {
  296. $component = $methods;
  297. $methods = true;
  298. }
  299. if ($methods === true) {
  300. $methods = array();
  301. }
  302. list($plugin, $name) = pluginSplit($component, true);
  303. $componentClass = $name . 'Component';
  304. App::uses($componentClass, $plugin . 'Controller/Component');
  305. if (!class_exists($componentClass)) {
  306. throw new MissingComponentException(array(
  307. 'class' => $componentClass
  308. ));
  309. }
  310. $_component = $this->getMock($componentClass, $methods, array(), '', false);
  311. $_controller->Components->set($name, $_component);
  312. }
  313. $_controller->constructClasses();
  314. $this->__dirtyController = false;
  315. $this->controller = $_controller;
  316. return $this->controller;
  317. }
  318. }