ControllerTestCase.php 11 KB

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