TestTask.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. <?php
  2. /**
  3. * The TestTask handles creating and updating test files.
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  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://cakephp.org CakePHP(tm) Project
  15. * @since CakePHP(tm) v 1.3
  16. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  17. */
  18. App::uses('BakeTask', 'Console/Command/Task');
  19. App::uses('ClassRegistry', 'Utility');
  20. /**
  21. * Task class for creating and updating test files.
  22. *
  23. * @package Cake.Console.Command.Task
  24. */
  25. class TestTask extends BakeTask {
  26. /**
  27. * path to TESTS directory
  28. *
  29. * @var string
  30. */
  31. public $path = TESTS;
  32. /**
  33. * Tasks used.
  34. *
  35. * @var array
  36. */
  37. public $tasks = array('Template');
  38. /**
  39. * class types that methods can be generated for
  40. *
  41. * @var array
  42. */
  43. public $classTypes = array(
  44. 'Model' => 'Model',
  45. 'Controller' => 'Controller',
  46. 'Component' => 'Controller/Component',
  47. 'Behavior' => 'Model/Behavior',
  48. 'Helper' => 'View/Helper'
  49. );
  50. /**
  51. * Internal list of fixtures that have been added so far.
  52. *
  53. * @var string
  54. */
  55. protected $_fixtures = array();
  56. /**
  57. * Execution method always used for tasks
  58. *
  59. */
  60. public function execute() {
  61. parent::execute();
  62. if (empty($this->args)) {
  63. $this->_interactive();
  64. }
  65. if (count($this->args) == 1) {
  66. $this->_interactive($this->args[0]);
  67. }
  68. if (count($this->args) > 1) {
  69. $type = Inflector::underscore($this->args[0]);
  70. if ($this->bake($type, $this->args[1])) {
  71. $this->out('<success>Done</success>');
  72. }
  73. }
  74. }
  75. /**
  76. * Handles interactive baking
  77. *
  78. */
  79. protected function _interactive($type = null) {
  80. $this->interactive = true;
  81. $this->hr();
  82. $this->out(__d('cake_console', 'Bake Tests'));
  83. $this->out(__d('cake_console', 'Path: %s', $this->path));
  84. $this->hr();
  85. if ($type) {
  86. $type = Inflector::camelize($type);
  87. if (!isset($this->classTypes[$type])) {
  88. $this->error(__d('cake_console', 'Incorrect type provided. Please choose one of %s', implode(', ', array_keys($this->classTypes))));
  89. }
  90. } else {
  91. $type = $this->getObjectType();
  92. }
  93. $className = $this->getClassName($type);
  94. return $this->bake($type, $className);
  95. }
  96. /**
  97. * Completes final steps for generating data to create test case.
  98. *
  99. * @param string $type Type of object to bake test case for ie. Model, Controller
  100. * @param string $className the 'cake name' for the class ie. Posts for the PostsController
  101. */
  102. public function bake($type, $className) {
  103. if ($this->typeCanDetectFixtures($type) && $this->isLoadableClass($type, $className)) {
  104. $this->out(__d('cake_console', 'Bake is detecting possible fixtures...'));
  105. $testSubject = $this->buildTestSubject($type, $className);
  106. $this->generateFixtureList($testSubject);
  107. } elseif ($this->interactive) {
  108. $this->getUserFixtures();
  109. }
  110. $fullClassName = $className;
  111. if (!$this->interactive) {
  112. $fullClassName = $this->getRealClassName($type, $className);
  113. }
  114. $methods = array();
  115. if (class_exists($fullClassName)) {
  116. $methods = $this->getTestableMethods($fullClassName);
  117. }
  118. $mock = $this->hasMockClass($type, $fullClassName);
  119. $construction = $this->generateConstructor($type, $fullClassName);
  120. $plugin = null;
  121. if ($this->plugin) {
  122. $plugin = $this->plugin . '.';
  123. }
  124. $this->out("\n" . __d('cake_console', 'Baking test case for %s %s ...', $className, $type), 1, Shell::QUIET);
  125. $this->Template->set('fixtures', $this->_fixtures);
  126. $this->Template->set('plugin', $plugin);
  127. $this->Template->set(compact('className', 'methods', 'type', 'fullClassName', 'mock', 'construction'));
  128. $out = $this->Template->generate('classes', 'test');
  129. $filename = $this->testCaseFileName($type, $className);
  130. $made = $this->createFile($filename, $out);
  131. if ($made) {
  132. return $out;
  133. }
  134. return false;
  135. }
  136. /**
  137. * Interact with the user and get their chosen type. Can exit the script.
  138. *
  139. * @return string Users chosen type.
  140. */
  141. public function getObjectType() {
  142. $this->hr();
  143. $this->out(__d('cake_console', 'Select an object type:'));
  144. $this->hr();
  145. $keys = array();
  146. $i = 0;
  147. foreach ($this->classTypes as $option => $package) {
  148. $this->out(++$i . '. ' . $option);
  149. $keys[] = $i;
  150. }
  151. $keys[] = 'q';
  152. $selection = $this->in(__d('cake_console', 'Enter the type of object to bake a test for or (q)uit'), $keys, 'q');
  153. if ($selection == 'q') {
  154. return $this->_stop();
  155. }
  156. $types = array_keys($this->classTypes);
  157. return $types[$selection - 1];
  158. }
  159. /**
  160. * Get the user chosen Class name for the chosen type
  161. *
  162. * @param string $objectType Type of object to list classes for i.e. Model, Controller.
  163. * @return string Class name the user chose.
  164. */
  165. public function getClassName($objectType) {
  166. $type = strtolower($objectType);
  167. if ($this->plugin) {
  168. if ($type === 'helper') {
  169. $type = 'View/Helper';
  170. } elseif ($type === 'component') {
  171. $type = 'Controller/Component';
  172. } elseif ($type === 'behavior') {
  173. $type = 'Model/Behavior';
  174. }
  175. $plugin = $this->plugin . '.';
  176. $options = App::objects($plugin . $type);
  177. } else {
  178. $options = App::objects($type);
  179. }
  180. $this->out(__d('cake_console', 'Choose a %s class', $objectType));
  181. $keys = array();
  182. foreach ($options as $key => $option) {
  183. $this->out(++$key . '. ' . $option);
  184. $keys[] = $key;
  185. }
  186. $selection = $this->in(__d('cake_console', 'Choose an existing class, or enter the name of a class that does not exist'));
  187. if (isset($options[$selection - 1])) {
  188. return $options[$selection - 1];
  189. }
  190. return $selection;
  191. }
  192. /**
  193. * Checks whether the chosen type can find its own fixtures.
  194. * Currently only model, and controller are supported
  195. *
  196. * @param string $type The Type of object you are generating tests for eg. controller
  197. * @param string $className the Classname of the class the test is being generated for.
  198. * @return boolean
  199. */
  200. public function typeCanDetectFixtures($type) {
  201. $type = strtolower($type);
  202. return ($type == 'controller' || $type == 'model');
  203. }
  204. /**
  205. * Check if a class with the given type is loaded or can be loaded.
  206. *
  207. * @param string $type The Type of object you are generating tests for eg. controller
  208. * @param string $className the Classname of the class the test is being generated for.
  209. * @return boolean
  210. */
  211. public function isLoadableClass($type, $class) {
  212. return App::import($type, $class);
  213. }
  214. /**
  215. * Construct an instance of the class to be tested.
  216. * So that fixtures can be detected
  217. *
  218. * @param string $type The Type of object you are generating tests for eg. controller
  219. * @param string $class the Classname of the class the test is being generated for.
  220. * @return object And instance of the class that is going to be tested.
  221. */
  222. public function &buildTestSubject($type, $class) {
  223. ClassRegistry::flush();
  224. App::import($type, $class);
  225. $class = $this->getRealClassName($type, $class);
  226. if (strtolower($type) == 'model') {
  227. $instance = ClassRegistry::init($class);
  228. } else {
  229. $instance = new $class();
  230. }
  231. return $instance;
  232. }
  233. /**
  234. * Gets the real class name from the cake short form.
  235. *
  236. * @param string $type The Type of object you are generating tests for eg. controller
  237. * @param string $class the Classname of the class the test is being generated for.
  238. * @return string Real classname
  239. */
  240. public function getRealClassName($type, $class) {
  241. if (strtolower($type) == 'model' || empty($this->classTypes[$type])) {
  242. return $class;
  243. }
  244. return $class . $type;
  245. }
  246. /**
  247. * Get methods declared in the class given.
  248. * No parent methods will be returned
  249. *
  250. * @param string $className Name of class to look at.
  251. * @return array Array of method names.
  252. */
  253. public function getTestableMethods($className) {
  254. $classMethods = get_class_methods($className);
  255. $parentMethods = get_class_methods(get_parent_class($className));
  256. $thisMethods = array_diff($classMethods, $parentMethods);
  257. $out = array();
  258. foreach ($thisMethods as $method) {
  259. if (substr($method, 0, 1) != '_' && $method != strtolower($className)) {
  260. $out[] = $method;
  261. }
  262. }
  263. return $out;
  264. }
  265. /**
  266. * Generate the list of fixtures that will be required to run this test based on
  267. * loaded models.
  268. *
  269. * @param object $subject The object you want to generate fixtures for.
  270. * @return array Array of fixtures to be included in the test.
  271. */
  272. public function generateFixtureList($subject) {
  273. $this->_fixtures = array();
  274. if (is_a($subject, 'Model')) {
  275. $this->_processModel($subject);
  276. } elseif (is_a($subject, 'Controller')) {
  277. $this->_processController($subject);
  278. }
  279. return array_values($this->_fixtures);
  280. }
  281. /**
  282. * Process a model recursively and pull out all the
  283. * model names converting them to fixture names.
  284. *
  285. * @param Model $subject A Model class to scan for associations and pull fixtures off of.
  286. * @return void
  287. */
  288. protected function _processModel($subject) {
  289. $this->_addFixture($subject->name);
  290. $associated = $subject->getAssociated();
  291. foreach ($associated as $alias => $type) {
  292. $className = $subject->{$alias}->name;
  293. if (!isset($this->_fixtures[$className])) {
  294. $this->_processModel($subject->{$alias});
  295. }
  296. if ($type == 'hasAndBelongsToMany') {
  297. $joinModel = Inflector::classify($subject->hasAndBelongsToMany[$alias]['joinTable']);
  298. if (!isset($this->_fixtures[$joinModel])) {
  299. $this->_processModel($subject->{$joinModel});
  300. }
  301. }
  302. }
  303. }
  304. /**
  305. * Process all the models attached to a controller
  306. * and generate a fixture list.
  307. *
  308. * @param Controller $subject A controller to pull model names off of.
  309. * @return void
  310. */
  311. protected function _processController($subject) {
  312. $subject->constructClasses();
  313. $models = array(Inflector::classify($subject->name));
  314. if (!empty($subject->uses)) {
  315. $models = $subject->uses;
  316. }
  317. foreach ($models as $model) {
  318. $this->_processModel($subject->{$model});
  319. }
  320. }
  321. /**
  322. * Add classname to the fixture list.
  323. * Sets the app. or plugin.plugin_name. prefix.
  324. *
  325. * @param string $name Name of the Model class that a fixture might be required for.
  326. * @return void
  327. */
  328. protected function _addFixture($name) {
  329. $parent = get_parent_class($name);
  330. $prefix = 'app.';
  331. if (strtolower($parent) != 'appmodel' && strtolower(substr($parent, -8)) == 'appmodel') {
  332. $pluginName = substr($parent, 0, strlen($parent) -8);
  333. $prefix = 'plugin.' . Inflector::underscore($pluginName) . '.';
  334. }
  335. $fixture = $prefix . Inflector::underscore($name);
  336. $this->_fixtures[$name] = $fixture;
  337. }
  338. /**
  339. * Interact with the user to get additional fixtures they want to use.
  340. *
  341. * @return array Array of fixtures the user wants to add.
  342. */
  343. public function getUserFixtures() {
  344. $proceed = $this->in(__d('cake_console', 'Bake could not detect fixtures, would you like to add some?'), array('y','n'), 'n');
  345. $fixtures = array();
  346. if (strtolower($proceed) == 'y') {
  347. $fixtureList = $this->in(__d('cake_console', "Please provide a comma separated list of the fixtures names you'd like to use.\nExample: 'app.comment, app.post, plugin.forums.post'"));
  348. $fixtureListTrimmed = str_replace(' ', '', $fixtureList);
  349. $fixtures = explode(',', $fixtureListTrimmed);
  350. }
  351. $this->_fixtures = array_merge($this->_fixtures, $fixtures);
  352. return $fixtures;
  353. }
  354. /**
  355. * Is a mock class required for this type of test?
  356. * Controllers require a mock class.
  357. *
  358. * @param string $type The type of object tests are being generated for eg. controller.
  359. * @return boolean
  360. */
  361. public function hasMockClass($type) {
  362. $type = strtolower($type);
  363. return $type == 'controller';
  364. }
  365. /**
  366. * Generate a constructor code snippet for the type and classname
  367. *
  368. * @param string $type The Type of object you are generating tests for eg. controller
  369. * @param string $className the Classname of the class the test is being generated for.
  370. * @return string Constructor snippet for the thing you are building.
  371. */
  372. public function generateConstructor($type, $fullClassName) {
  373. $type = strtolower($type);
  374. if ($type == 'model') {
  375. return "ClassRegistry::init('$fullClassName');\n";
  376. }
  377. if ($type == 'controller') {
  378. $className = substr($fullClassName, 0, strlen($fullClassName) - 10);
  379. return "new Test$fullClassName();\n\t\t\$this->{$className}->constructClasses();\n";
  380. }
  381. return "new $fullClassName();\n";
  382. }
  383. /**
  384. * Make the filename for the test case. resolve the suffixes for controllers
  385. * and get the plugin path if needed.
  386. *
  387. * @param string $type The Type of object you are generating tests for eg. controller
  388. * @param string $className the Classname of the class the test is being generated for.
  389. * @return string filename the test should be created on.
  390. */
  391. public function testCaseFileName($type, $className) {
  392. $path = $this->getPath() . 'Case' . DS;
  393. if (isset($this->classTypes[$type])) {
  394. $path .= $this->classTypes[$type] . DS;
  395. }
  396. if (!$this->interactive) {
  397. $className = $this->getRealClassName($type, $className);
  398. }
  399. return str_replace('/', DS, $path) . Inflector::camelize($className) . 'Test.php';
  400. }
  401. /**
  402. * get the option parser.
  403. *
  404. * @return void
  405. */
  406. public function getOptionParser() {
  407. $parser = parent::getOptionParser();
  408. return $parser->description(__d('cake_console', 'Bake test case skeletons for classes.'))
  409. ->addArgument('type', array(
  410. 'help' => __d('cake_console', 'Type of class to bake, can be any of the following: controller, model, helper, component or behavior.'),
  411. 'choices' => array('controller', 'model', 'helper', 'component', 'behavior')
  412. ))->addArgument('name', array(
  413. 'help' => __d('cake_console', 'An existing class to bake tests for.')
  414. ))->addOption('plugin', array(
  415. 'short' => 'p',
  416. 'help' => __d('cake_console', 'CamelCased name of the plugin to bake tests for.')
  417. ))->epilog(__d('cake_console', 'Omitting all arguments and options will enter into an interactive mode.'));
  418. }
  419. }