TestTask.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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-2010, 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-2010, 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. $path = Inflector::pluralize($type);
  175. if ($type === 'helper') {
  176. $path = 'View/Helper';
  177. } elseif ($type === 'component') {
  178. $path = 'Controller/Component';
  179. } elseif ($type === 'behavior') {
  180. $path = 'Model/Behavior';
  181. }
  182. $plugin = $this->plugin . '.';
  183. $options = App::objects($plugin . $type);
  184. } else {
  185. $options = App::objects($type);
  186. }
  187. $this->out(__d('cake_console', 'Choose a %s class', $objectType));
  188. $keys = array();
  189. foreach ($options as $key => $option) {
  190. $this->out(++$key . '. ' . $option);
  191. $keys[] = $key;
  192. }
  193. $selection = $this->in(__d('cake_console', 'Choose an existing class, or enter the name of a class that does not exist'));
  194. if (isset($options[$selection - 1])) {
  195. return $options[$selection - 1];
  196. }
  197. return $selection;
  198. }
  199. /**
  200. * Checks whether the chosen type can find its own fixtures.
  201. * Currently only model, and controller are supported
  202. *
  203. * @param string $type The Type of object you are generating tests for eg. controller
  204. * @param string $className the Classname of the class the test is being generated for.
  205. * @return boolean
  206. */
  207. public function typeCanDetectFixtures($type) {
  208. $type = strtolower($type);
  209. return ($type == 'controller' || $type == 'model');
  210. }
  211. /**
  212. * Check if a class with the given type is loaded or can be loaded.
  213. *
  214. * @param string $type The Type of object you are generating tests for eg. controller
  215. * @param string $className the Classname of the class the test is being generated for.
  216. * @return boolean
  217. */
  218. public function isLoadableClass($type, $class) {
  219. return App::import($type, $class);
  220. }
  221. /**
  222. * Construct an instance of the class to be tested.
  223. * So that fixtures can be detected
  224. *
  225. * @param string $type The Type of object you are generating tests for eg. controller
  226. * @param string $class the Classname of the class the test is being generated for.
  227. * @return object And instance of the class that is going to be tested.
  228. */
  229. public function &buildTestSubject($type, $class) {
  230. ClassRegistry::flush();
  231. App::import($type, $class);
  232. $class = $this->getRealClassName($type, $class);
  233. if (strtolower($type) == 'model') {
  234. $instance = ClassRegistry::init($class);
  235. } else {
  236. $instance = new $class();
  237. }
  238. return $instance;
  239. }
  240. /**
  241. * Gets the real class name from the cake short form.
  242. *
  243. * @param string $type The Type of object you are generating tests for eg. controller
  244. * @param string $class the Classname of the class the test is being generated for.
  245. * @return string Real classname
  246. */
  247. public function getRealClassName($type, $class) {
  248. if (strtolower($type) == 'model' || empty($this->classTypes[$type])) {
  249. return $class;
  250. }
  251. return $class . $type;
  252. }
  253. /**
  254. * Get methods declared in the class given.
  255. * No parent methods will be returned
  256. *
  257. * @param string $className Name of class to look at.
  258. * @return array Array of method names.
  259. */
  260. public function getTestableMethods($className) {
  261. $classMethods = get_class_methods($className);
  262. $parentMethods = get_class_methods(get_parent_class($className));
  263. $thisMethods = array_diff($classMethods, $parentMethods);
  264. $out = array();
  265. foreach ($thisMethods as $method) {
  266. if (substr($method, 0, 1) != '_' && $method != strtolower($className)) {
  267. $out[] = $method;
  268. }
  269. }
  270. return $out;
  271. }
  272. /**
  273. * Generate the list of fixtures that will be required to run this test based on
  274. * loaded models.
  275. *
  276. * @param object $subject The object you want to generate fixtures for.
  277. * @return array Array of fixtures to be included in the test.
  278. */
  279. public function generateFixtureList($subject) {
  280. $this->_fixtures = array();
  281. if (is_a($subject, 'Model')) {
  282. $this->_processModel($subject);
  283. } elseif (is_a($subject, 'Controller')) {
  284. $this->_processController($subject);
  285. }
  286. return array_values($this->_fixtures);
  287. }
  288. /**
  289. * Process a model recursively and pull out all the
  290. * model names converting them to fixture names.
  291. *
  292. * @param Model $subject A Model class to scan for associations and pull fixtures off of.
  293. * @return void
  294. */
  295. protected function _processModel($subject) {
  296. $this->_addFixture($subject->name);
  297. $associated = $subject->getAssociated();
  298. foreach ($associated as $alias => $type) {
  299. $className = $subject->{$alias}->name;
  300. if (!isset($this->_fixtures[$className])) {
  301. $this->_processModel($subject->{$alias});
  302. }
  303. if ($type == 'hasAndBelongsToMany') {
  304. $joinModel = Inflector::classify($subject->hasAndBelongsToMany[$alias]['joinTable']);
  305. if (!isset($this->_fixtures[$joinModel])) {
  306. $this->_processModel($subject->{$joinModel});
  307. }
  308. }
  309. }
  310. }
  311. /**
  312. * Process all the models attached to a controller
  313. * and generate a fixture list.
  314. *
  315. * @param Controller $subject A controller to pull model names off of.
  316. * @return void
  317. */
  318. protected function _processController($subject) {
  319. $subject->constructClasses();
  320. $models = array(Inflector::classify($subject->name));
  321. if (!empty($subject->uses)) {
  322. $models = $subject->uses;
  323. }
  324. foreach ($models as $model) {
  325. $this->_processModel($subject->{$model});
  326. }
  327. }
  328. /**
  329. * Add classname to the fixture list.
  330. * Sets the app. or plugin.plugin_name. prefix.
  331. *
  332. * @param string $name Name of the Model class that a fixture might be required for.
  333. * @return void
  334. */
  335. protected function _addFixture($name) {
  336. $parent = get_parent_class($name);
  337. $prefix = 'app.';
  338. if (strtolower($parent) != 'appmodel' && strtolower(substr($parent, -8)) == 'appmodel') {
  339. $pluginName = substr($parent, 0, strlen($parent) -8);
  340. $prefix = 'plugin.' . Inflector::underscore($pluginName) . '.';
  341. }
  342. $fixture = $prefix . Inflector::underscore($name);
  343. $this->_fixtures[$name] = $fixture;
  344. }
  345. /**
  346. * Interact with the user to get additional fixtures they want to use.
  347. *
  348. * @return array Array of fixtures the user wants to add.
  349. */
  350. public function getUserFixtures() {
  351. $proceed = $this->in(__d('cake_console', 'Bake could not detect fixtures, would you like to add some?'), array('y','n'), 'n');
  352. $fixtures = array();
  353. if (strtolower($proceed) == 'y') {
  354. $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'"));
  355. $fixtureListTrimmed = str_replace(' ', '', $fixtureList);
  356. $fixtures = explode(',', $fixtureListTrimmed);
  357. }
  358. $this->_fixtures = array_merge($this->_fixtures, $fixtures);
  359. return $fixtures;
  360. }
  361. /**
  362. * Is a mock class required for this type of test?
  363. * Controllers require a mock class.
  364. *
  365. * @param string $type The type of object tests are being generated for eg. controller.
  366. * @return boolean
  367. */
  368. public function hasMockClass($type) {
  369. $type = strtolower($type);
  370. return $type == 'controller';
  371. }
  372. /**
  373. * Generate a constructor code snippet for the type and classname
  374. *
  375. * @param string $type The Type of object you are generating tests for eg. controller
  376. * @param string $className the Classname of the class the test is being generated for.
  377. * @return string Constructor snippet for the thing you are building.
  378. */
  379. public function generateConstructor($type, $fullClassName) {
  380. $type = strtolower($type);
  381. if ($type == 'model') {
  382. return "ClassRegistry::init('$fullClassName');\n";
  383. }
  384. if ($type == 'controller') {
  385. $className = substr($fullClassName, 0, strlen($fullClassName) - 10);
  386. return "new Test$fullClassName();\n\t\t\$this->{$className}->constructClasses();\n";
  387. }
  388. return "new $fullClassName();\n";
  389. }
  390. /**
  391. * Make the filename for the test case. resolve the suffixes for controllers
  392. * and get the plugin path if needed.
  393. *
  394. * @param string $type The Type of object you are generating tests for eg. controller
  395. * @param string $className the Classname of the class the test is being generated for.
  396. * @return string filename the test should be created on.
  397. */
  398. public function testCaseFileName($type, $className) {
  399. $path = $this->getPath() . 'Case' . DS;
  400. if (isset($this->classTypes[$type])) {
  401. $path .= $this->classTypes[$type] . DS;
  402. }
  403. if (!$this->interactive) {
  404. $className = $this->getRealClassName($type, $className);
  405. }
  406. return $path . Inflector::camelize($className) . 'Test.php';
  407. }
  408. /**
  409. * get the option parser.
  410. *
  411. * @return void
  412. */
  413. public function getOptionParser() {
  414. $parser = parent::getOptionParser();
  415. return $parser->description(__d('cake_console', 'Bake test case skeletons for classes.'))
  416. ->addArgument('type', array(
  417. 'help' => __d('cake_console', 'Type of class to bake, can be any of the following: controller, model, helper, component or behavior.'),
  418. 'choices' => array('controller', 'model', 'helper', 'component', 'behavior')
  419. ))->addArgument('name', array(
  420. 'help' => __d('cake_console', 'An existing class to bake tests for.')
  421. ))->addOption('plugin', array(
  422. 'short' => 'p',
  423. 'help' => __d('cake_console', 'CamelCased name of the plugin to bake tests for.')
  424. ))->epilog(__d('cake_console', 'Omitting all arguments and options will enter into an interactive mode.'));
  425. }
  426. /**
  427. * Gets the path for output. Checks the plugin property
  428. * and returns the correct path.
  429. *
  430. * @return string Path to output.
  431. */
  432. public function getPath() {
  433. $path = $this->path;
  434. if (isset($this->plugin)) {
  435. $path = $this->_pluginPath($this->plugin) . 'tests' . DS;
  436. }
  437. return $path;
  438. }
  439. }