ControllerTestCase.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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.tests.libs
  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.tests.lib
  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) {
  50. if ($this->testController === null) {
  51. $this->testController = parent::_getController($request);
  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.tests.lib
  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.tests.lib
  90. */
  91. 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
  159. * - `method` POST or GET
  160. *
  161. * @param string $url The url to test
  162. * @param array $options See options
  163. */
  164. private function _testAction($url = '', $options = array()) {
  165. $this->vars = $this->result = $this->view = $this->contents = $this->headers = null;
  166. $options = array_merge(array(
  167. 'data' => array(),
  168. 'method' => 'POST',
  169. 'return' => 'result'
  170. ), $options);
  171. if (strtoupper($options['method']) == 'GET') {
  172. $_GET = $options['data'];
  173. $_POST = array();
  174. } else {
  175. $_POST = array('data' => $options['data']);
  176. $_GET = array();
  177. }
  178. $request = new CakeRequest($url);
  179. $Dispatch = new ControllerTestDispatcher();
  180. foreach (Router::$routes as $route) {
  181. if (is_a($route, 'RedirectRoute')) {
  182. $route->response = $this->getMock('CakeResponse', array('send'));
  183. }
  184. }
  185. $Dispatch->loadRoutes = $this->loadRoutes;
  186. $request = $Dispatch->parseParams($request);
  187. if (!isset($request->params['controller'])) {
  188. $this->headers = Router::currentRoute()->response->header();
  189. return;
  190. }
  191. if ($this->controller !== null && Inflector::camelize($request->params['controller']) !== $this->controller->name) {
  192. $this->controller = null;
  193. }
  194. if ($this->controller === null && $this->autoMock) {
  195. $this->generate(Inflector::camelize($request->params['controller']));
  196. }
  197. $params = array();
  198. if ($options['return'] == 'result') {
  199. $params['return'] = 1;
  200. $params['bare'] = 1;
  201. $params['requested'] = 1;
  202. }
  203. $Dispatch->testController = $this->controller;
  204. $Dispatch->response = $this->getMock('CakeResponse', array('send'));
  205. $this->result = $Dispatch->dispatch($request, $params);
  206. $this->controller = $Dispatch->testController;
  207. if ($options['return'] != 'result') {
  208. $this->vars = $this->controller->View->viewVars;
  209. $this->view = $this->controller->View->_viewNoLayout;
  210. $this->contents = $this->controller->response->body();
  211. }
  212. $this->headers = $Dispatch->response->header();
  213. return $this->{$options['return']};
  214. }
  215. /**
  216. * Generates a mocked controller and mocks any classes passed to `$mocks`. By
  217. * default, `_stop()` is stubbed as is sending the response headers, so to not
  218. * interfere with testing.
  219. *
  220. * ### Mocks:
  221. *
  222. * - `methods` Methods to mock on the controller. `_stop()` is mocked by default
  223. * - `models` Models to mock. Models are added to the ClassRegistry so they any
  224. * time they are instatiated the mock will be created. Pass as key value pairs
  225. * with the value being specific methods on the model to mock. If `true` or
  226. * no value is passed, the entire model will be mocked.
  227. * - `components` Components to mock. Components are only mocked on this controller
  228. * and not within each other (i.e., components on components)
  229. *
  230. * @param string $controller Controller name
  231. * @param array $mocks List of classes and methods to mock
  232. * @return Controller Mocked controller
  233. */
  234. public function generate($controller, $mocks = array()) {
  235. list($plugin, $controller) = pluginSplit($controller);
  236. if ($plugin) {
  237. App::uses($plugin . 'AppController', $plugin . '.Controller');
  238. $plugin .= '.';
  239. }
  240. App::uses($controller . 'Controller', $plugin . 'Controller');
  241. if (!class_exists($controller.'Controller')) {
  242. throw new MissingControllerException(array('controller' => $controller.'Controller'));
  243. }
  244. ClassRegistry::flush();
  245. $mocks = array_merge_recursive(array(
  246. 'methods' => array('_stop'),
  247. 'models' => array(),
  248. 'components' => array()
  249. ), (array)$mocks);
  250. list($plugin, $name) = pluginSplit($controller);
  251. $_controller = $this->getMock($name.'Controller', $mocks['methods'], array(), '', false);
  252. $_controller->name = $name;
  253. $_controller->__construct();
  254. $config = ClassRegistry::config('Model');
  255. foreach ($mocks['models'] as $model => $methods) {
  256. if (is_string($methods)) {
  257. $model = $methods;
  258. $methods = true;
  259. }
  260. if ($methods === true) {
  261. $methods = array();
  262. }
  263. ClassRegistry::init($model);
  264. list($plugin, $name) = pluginSplit($model);
  265. $config = array_merge((array)$config, array('name' => $model));
  266. $_model = $this->getMock($name, $methods, array($config));
  267. ClassRegistry::removeObject($name);
  268. ClassRegistry::addObject($name, $_model);
  269. }
  270. foreach ($mocks['components'] as $component => $methods) {
  271. if (is_string($methods)) {
  272. $component = $methods;
  273. $methods = true;
  274. }
  275. if ($methods === true) {
  276. $methods = array();
  277. }
  278. list($plugin, $name) = pluginSplit($component, true);
  279. App::uses($name . 'Component', $plugin . 'Controller/Component');
  280. if (!class_exists($name . 'Component')) {
  281. throw new MissingComponentFileException(array(
  282. 'file' => $name . 'Component.php',
  283. 'class' => $name.'Component'
  284. ));
  285. }
  286. $_component = $this->getMock($name.'Component', $methods, array(), '', false);
  287. $_controller->Components->set($name, $_component);
  288. }
  289. $_controller->constructClasses();
  290. $this->controller = $_controller;
  291. return $this->controller;
  292. }
  293. }