PageRenderTime 25ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/TestSuite/ControllerTestCase.php

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