ControllerTestCase.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. * Used to enable calling ControllerTestCase::testAction() without the testing
  142. * framework thinking that it's a test case
  143. *
  144. * @param string $name The name of the function
  145. * @param array $arguments Array of arguments
  146. * @return Function
  147. */
  148. public function __call($name, $arguments) {
  149. if ($name == 'testAction') {
  150. return call_user_func_array(array($this, '_testAction'), $arguments);
  151. }
  152. }
  153. /**
  154. * Tests a controller action.
  155. *
  156. * ### Options:
  157. *
  158. * - `data` POST or GET data to pass. Depends on the method.
  159. * - `method` POST or GET. Defaults to POST.
  160. * - `return` Specify the return type you want. Choose from:
  161. * - `vars` Get the set view variables.
  162. * - `view` Get the rendered view, without a layout.
  163. * - `contents` Get the rendered view including the layout.
  164. * - `result` Get the return value of the controller action. Useful
  165. * for testing requestAction methods.
  166. *
  167. * @param string $url The url to test
  168. * @param array $options See options
  169. */
  170. protected function _testAction($url = '', $options = array()) {
  171. $this->vars = $this->result = $this->view = $this->contents = $this->headers = null;
  172. $options = array_merge(array(
  173. 'data' => array(),
  174. 'method' => 'POST',
  175. 'return' => 'result'
  176. ), $options);
  177. $_SERVER['REQUEST_METHOD'] = strtoupper($options['method']);
  178. if (strtoupper($options['method']) == 'GET') {
  179. $_GET = $options['data'];
  180. $_POST = array();
  181. } else {
  182. $_POST = $options['data'];
  183. $_GET = array();
  184. }
  185. $request = new CakeRequest($url);
  186. $Dispatch = new ControllerTestDispatcher();
  187. foreach (Router::$routes as $route) {
  188. if ($route instanceof RedirectRoute) {
  189. $route->response = $this->getMock('CakeResponse', array('send'));
  190. }
  191. }
  192. $Dispatch->loadRoutes = $this->loadRoutes;
  193. $request = $Dispatch->parseParams($request);
  194. if (!isset($request->params['controller'])) {
  195. $this->headers = Router::currentRoute()->response->header();
  196. return;
  197. }
  198. if ($this->controller !== null && Inflector::camelize($request->params['controller']) !== $this->controller->name) {
  199. $this->controller = null;
  200. }
  201. $plugin = empty($request->params['plugin']) ? '' : Inflector::camelize($request->params['plugin']) . '.';
  202. if ($this->controller === null && $this->autoMock) {
  203. $this->generate(Inflector::camelize($plugin . $request->params['controller']));
  204. }
  205. $params = array();
  206. if ($options['return'] == 'result') {
  207. $params['return'] = 1;
  208. $params['bare'] = 1;
  209. $params['requested'] = 1;
  210. }
  211. $Dispatch->testController = $this->controller;
  212. $Dispatch->response = $this->getMock('CakeResponse', array('send'));
  213. $this->result = $Dispatch->dispatch($request, $Dispatch->response, $params);
  214. $this->controller = $Dispatch->testController;
  215. if ($options['return'] != 'result') {
  216. if (isset($this->controller->View)) {
  217. $this->vars = $this->controller->View->viewVars;
  218. $this->view = $this->controller->View->_viewNoLayout;
  219. }
  220. $this->contents = $this->controller->response->body();
  221. }
  222. $this->headers = $Dispatch->response->header();
  223. return $this->{$options['return']};
  224. }
  225. /**
  226. * Generates a mocked controller and mocks any classes passed to `$mocks`. By
  227. * default, `_stop()` is stubbed as is sending the response headers, so to not
  228. * interfere with testing.
  229. *
  230. * ### Mocks:
  231. *
  232. * - `methods` Methods to mock on the controller. `_stop()` is mocked by default
  233. * - `models` Models to mock. Models are added to the ClassRegistry so they any
  234. * time they are instatiated the mock will be created. Pass as key value pairs
  235. * with the value being specific methods on the model to mock. If `true` or
  236. * no value is passed, the entire model will be mocked.
  237. * - `components` Components to mock. Components are only mocked on this controller
  238. * and not within each other (i.e., components on components)
  239. *
  240. * @param string $controller Controller name
  241. * @param array $mocks List of classes and methods to mock
  242. * @return Controller Mocked controller
  243. */
  244. public function generate($controller, $mocks = array()) {
  245. list($plugin, $controller) = pluginSplit($controller);
  246. if ($plugin) {
  247. App::uses($plugin . 'AppController', $plugin . '.Controller');
  248. $plugin .= '.';
  249. }
  250. App::uses($controller . 'Controller', $plugin . 'Controller');
  251. if (!class_exists($controller.'Controller')) {
  252. throw new MissingControllerException(array('controller' => $controller.'Controller'));
  253. }
  254. ClassRegistry::flush();
  255. $mocks = array_merge_recursive(array(
  256. 'methods' => array('_stop'),
  257. 'models' => array(),
  258. 'components' => array()
  259. ), (array)$mocks);
  260. list($plugin, $name) = pluginSplit($controller);
  261. $_controller = $this->getMock($name.'Controller', $mocks['methods'], array(), '', false);
  262. $_controller->name = $name;
  263. $request = $this->getMock('CakeRequest');
  264. $response = $this->getMock('CakeResponse', array('_sendHeader'));
  265. $_controller->__construct($request, $response);
  266. $config = ClassRegistry::config('Model');
  267. foreach ($mocks['models'] as $model => $methods) {
  268. if (is_string($methods)) {
  269. $model = $methods;
  270. $methods = true;
  271. }
  272. if ($methods === true) {
  273. $methods = array();
  274. }
  275. ClassRegistry::init($model);
  276. list($plugin, $name) = pluginSplit($model);
  277. $config = array_merge((array)$config, array('name' => $model));
  278. $_model = $this->getMock($name, $methods, array($config));
  279. ClassRegistry::removeObject($name);
  280. ClassRegistry::addObject($name, $_model);
  281. }
  282. foreach ($mocks['components'] as $component => $methods) {
  283. if (is_string($methods)) {
  284. $component = $methods;
  285. $methods = true;
  286. }
  287. if ($methods === true) {
  288. $methods = array();
  289. }
  290. list($plugin, $name) = pluginSplit($component, true);
  291. App::uses($name . 'Component', $plugin . 'Controller/Component');
  292. if (!class_exists($name . 'Component')) {
  293. throw new MissingComponentFileException(array(
  294. 'file' => $name . 'Component.php',
  295. 'class' => $name.'Component'
  296. ));
  297. }
  298. $_component = $this->getMock($name.'Component', $methods, array(), '', false);
  299. $_controller->Components->set($name, $_component);
  300. }
  301. $_controller->constructClasses();
  302. $this->controller = $_controller;
  303. return $this->controller;
  304. }
  305. }