TestTask.php 14 KB

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