Base for a static organization website

ControllerTestCase.php 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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 mixed 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|array $url The URL to test.
  192. * @param array $options See options
  193. * @return mixed The specified return type.
  194. * @triggers ControllerTestCase $Dispatch, array('request' => $request)
  195. */
  196. protected function _testAction($url, $options = array()) {
  197. $this->vars = $this->result = $this->view = $this->contents = $this->headers = null;
  198. $options += array(
  199. 'data' => array(),
  200. 'method' => 'POST',
  201. 'return' => 'result'
  202. );
  203. if (is_array($url)) {
  204. $url = Router::url($url);
  205. }
  206. $restore = array('get' => $_GET, 'post' => $_POST);
  207. $_SERVER['REQUEST_METHOD'] = strtoupper($options['method']);
  208. if (is_array($options['data'])) {
  209. if (strtoupper($options['method']) === 'GET') {
  210. $_GET = $options['data'];
  211. $_POST = array();
  212. } else {
  213. $_POST = $options['data'];
  214. $_GET = array();
  215. }
  216. }
  217. $request = $this->getMock('CakeRequest', array('_readInput'), array($url));
  218. if (is_string($options['data'])) {
  219. $request->expects($this->any())
  220. ->method('_readInput')
  221. ->will($this->returnValue($options['data']));
  222. }
  223. $Dispatch = new ControllerTestDispatcher();
  224. foreach (Router::$routes as $route) {
  225. if ($route instanceof RedirectRoute) {
  226. $route->response = $this->getMock('CakeResponse', array('send'));
  227. }
  228. }
  229. $Dispatch->loadRoutes = $this->loadRoutes;
  230. $Dispatch->parseParams(new CakeEvent('ControllerTestCase', $Dispatch, array('request' => $request)));
  231. if (!isset($request->params['controller']) && Router::currentRoute()) {
  232. $this->headers = Router::currentRoute()->response->header();
  233. return null;
  234. }
  235. if ($this->_dirtyController) {
  236. $this->controller = null;
  237. }
  238. $plugin = empty($request->params['plugin']) ? '' : Inflector::camelize($request->params['plugin']) . '.';
  239. if ($this->controller === null && $this->autoMock) {
  240. $this->generate($plugin . Inflector::camelize($request->params['controller']));
  241. }
  242. $params = array();
  243. if ($options['return'] === 'result') {
  244. $params['return'] = 1;
  245. $params['bare'] = 1;
  246. $params['requested'] = 1;
  247. }
  248. $Dispatch->testController = $this->controller;
  249. $Dispatch->response = $this->getMock('CakeResponse', array('send', '_clearBuffer'));
  250. $this->result = $Dispatch->dispatch($request, $Dispatch->response, $params);
  251. $this->controller = $Dispatch->testController;
  252. $this->vars = $this->controller->viewVars;
  253. $this->contents = $this->controller->response->body();
  254. if (isset($this->controller->View)) {
  255. $this->view = $this->controller->View->fetch('__view_no_layout__');
  256. }
  257. $this->_dirtyController = true;
  258. $this->headers = $Dispatch->response->header();
  259. $_GET = $restore['get'];
  260. $_POST = $restore['post'];
  261. return $this->{$options['return']};
  262. }
  263. /**
  264. * Generates a mocked controller and mocks any classes passed to `$mocks`. By
  265. * default, `_stop()` is stubbed as is sending the response headers, so to not
  266. * interfere with testing.
  267. *
  268. * ### Mocks:
  269. *
  270. * - `methods` Methods to mock on the controller. `_stop()` is mocked by default
  271. * - `models` Models to mock. Models are added to the ClassRegistry so any
  272. * time they are instantiated the mock will be created. Pass as key value pairs
  273. * with the value being specific methods on the model to mock. If `true` or
  274. * no value is passed, the entire model will be mocked.
  275. * - `components` Components to mock. Components are only mocked on this controller
  276. * and not within each other (i.e., components on components)
  277. *
  278. * @param string $controller Controller name
  279. * @param array $mocks List of classes and methods to mock
  280. * @return Controller Mocked controller
  281. * @throws MissingControllerException When controllers could not be created.
  282. * @throws MissingComponentException When components could not be created.
  283. */
  284. public function generate($controller, $mocks = array()) {
  285. list($plugin, $controller) = pluginSplit($controller);
  286. if ($plugin) {
  287. App::uses($plugin . 'AppController', $plugin . '.Controller');
  288. $plugin .= '.';
  289. }
  290. App::uses($controller . 'Controller', $plugin . 'Controller');
  291. if (!class_exists($controller . 'Controller')) {
  292. throw new MissingControllerException(array(
  293. 'class' => $controller . 'Controller',
  294. 'plugin' => substr($plugin, 0, -1)
  295. ));
  296. }
  297. ClassRegistry::flush();
  298. $mocks = array_merge_recursive(array(
  299. 'methods' => array('_stop'),
  300. 'models' => array(),
  301. 'components' => array()
  302. ), (array)$mocks);
  303. list($plugin, $name) = pluginSplit($controller);
  304. $controllerObj = $this->getMock($name . 'Controller', $mocks['methods'], array(), '', false);
  305. $controllerObj->name = $name;
  306. $request = $this->getMock('CakeRequest');
  307. $response = $this->getMock('CakeResponse', array('_sendHeader'));
  308. $controllerObj->__construct($request, $response);
  309. $controllerObj->Components->setController($controllerObj);
  310. $config = ClassRegistry::config('Model');
  311. foreach ($mocks['models'] as $model => $methods) {
  312. if (is_string($methods)) {
  313. $model = $methods;
  314. $methods = true;
  315. }
  316. if ($methods === true) {
  317. $methods = array();
  318. }
  319. $this->getMockForModel($model, $methods, $config);
  320. }
  321. foreach ($mocks['components'] as $component => $methods) {
  322. if (is_string($methods)) {
  323. $component = $methods;
  324. $methods = true;
  325. }
  326. if ($methods === true) {
  327. $methods = array();
  328. }
  329. list($plugin, $name) = pluginSplit($component, true);
  330. $componentClass = $name . 'Component';
  331. App::uses($componentClass, $plugin . 'Controller/Component');
  332. if (!class_exists($componentClass)) {
  333. throw new MissingComponentException(array(
  334. 'class' => $componentClass
  335. ));
  336. }
  337. $config = isset($controllerObj->components[$component]) ? $controllerObj->components[$component] : array();
  338. $componentObj = $this->getMock($componentClass, $methods, array($controllerObj->Components, $config));
  339. $controllerObj->Components->set($name, $componentObj);
  340. $controllerObj->Components->enable($name);
  341. }
  342. $controllerObj->constructClasses();
  343. $this->_dirtyController = false;
  344. $this->controller = $controllerObj;
  345. return $this->controller;
  346. }
  347. }