ControllerTestCase.php 11 KB

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