TestTask.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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 array
  54. */
  55. protected $_fixtures = array();
  56. /**
  57. * Execution method always used for tasks
  58. *
  59. * @return void
  60. */
  61. public function execute() {
  62. parent::execute();
  63. if (empty($this->args)) {
  64. $this->_interactive();
  65. }
  66. if (count($this->args) == 1) {
  67. $this->_interactive($this->args[0]);
  68. }
  69. if (count($this->args) > 1) {
  70. $type = Inflector::underscore($this->args[0]);
  71. if ($this->bake($type, $this->args[1])) {
  72. $this->out('<success>Done</success>');
  73. }
  74. }
  75. }
  76. /**
  77. * Handles interactive baking
  78. *
  79. * @param string $type
  80. * @return string|boolean
  81. */
  82. protected function _interactive($type = null) {
  83. $this->interactive = true;
  84. $this->hr();
  85. $this->out(__d('cake_console', 'Bake Tests'));
  86. $this->out(__d('cake_console', 'Path: %s', $this->path));
  87. $this->hr();
  88. if ($type) {
  89. $type = Inflector::camelize($type);
  90. if (!isset($this->classTypes[$type])) {
  91. $this->error(__d('cake_console', 'Incorrect type provided. Please choose one of %s', implode(', ', array_keys($this->classTypes))));
  92. }
  93. } else {
  94. $type = $this->getObjectType();
  95. }
  96. $className = $this->getClassName($type);
  97. return $this->bake($type, $className);
  98. }
  99. /**
  100. * Completes final steps for generating data to create test case.
  101. *
  102. * @param string $type Type of object to bake test case for ie. Model, Controller
  103. * @param string $className the 'cake name' for the class ie. Posts for the PostsController
  104. * @return string|boolean
  105. */
  106. public function bake($type, $className) {
  107. $plugin = null;
  108. if ($this->plugin) {
  109. $plugin = $this->plugin . '.';
  110. }
  111. $realType = $this->mapType($type, $plugin);
  112. $fullClassName = $this->getRealClassName($type, $className);
  113. if ($this->typeCanDetectFixtures($type) && $this->isLoadableClass($realType, $fullClassName)) {
  114. $this->out(__d('cake_console', 'Bake is detecting possible fixtures...'));
  115. $testSubject = $this->buildTestSubject($type, $className);
  116. $this->generateFixtureList($testSubject);
  117. } elseif ($this->interactive) {
  118. $this->getUserFixtures();
  119. }
  120. App::uses($fullClassName, $realType);
  121. $methods = array();
  122. if (class_exists($fullClassName)) {
  123. $methods = $this->getTestableMethods($fullClassName);
  124. }
  125. $mock = $this->hasMockClass($type, $fullClassName);
  126. $construction = $this->generateConstructor($type, $fullClassName);
  127. $this->out("\n" . __d('cake_console', 'Baking test case for %s %s ...', $className, $type), 1, Shell::QUIET);
  128. $this->Template->set('fixtures', $this->_fixtures);
  129. $this->Template->set('plugin', $plugin);
  130. $this->Template->set(compact(
  131. 'className', 'methods', 'type', 'fullClassName', 'mock',
  132. 'construction', 'realType'
  133. ));
  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 = ucfirst(strtolower($objectType));
  173. $typeLength = strlen($type);
  174. $type = $this->classTypes[$type];
  175. if ($this->plugin) {
  176. $plugin = $this->plugin . '.';
  177. $options = App::objects($plugin . $type);
  178. } else {
  179. $options = App::objects($type);
  180. }
  181. $this->out(__d('cake_console', 'Choose a %s class', $objectType));
  182. $keys = array();
  183. foreach ($options as $key => $option) {
  184. $this->out(++$key . '. ' . $option);
  185. $keys[] = $key;
  186. }
  187. $selection = $this->in(__d('cake_console', 'Choose an existing class, or enter the name of a class that does not exist'));
  188. if (isset($options[$selection - 1])) {
  189. $selection = $options[$selection - 1];
  190. }
  191. if ($type !== 'Model') {
  192. $selection = substr($selection, 0, $typeLength * - 1);
  193. }
  194. return $selection;
  195. }
  196. /**
  197. * Checks whether the chosen type can find its own fixtures.
  198. * Currently only model, and controller are supported
  199. *
  200. * @param string $type The Type of object you are generating tests for eg. controller
  201. * @return boolean
  202. */
  203. public function typeCanDetectFixtures($type) {
  204. $type = strtolower($type);
  205. return in_array($type, array('controller', 'model'));
  206. }
  207. /**
  208. * Check if a class with the given package is loaded or can be loaded.
  209. *
  210. * @param string $package The package of object you are generating tests for eg. controller
  211. * @param string $class the Classname of the class the test is being generated for.
  212. * @return boolean
  213. */
  214. public function isLoadableClass($package, $class) {
  215. App::uses($class, $package);
  216. return class_exists($class);
  217. }
  218. /**
  219. * Construct an instance of the class to be tested.
  220. * So that fixtures can be detected
  221. *
  222. * @param string $type The Type of object you are generating tests for eg. controller
  223. * @param string $class the Classname of the class the test is being generated for.
  224. * @return object And instance of the class that is going to be tested.
  225. */
  226. public function &buildTestSubject($type, $class) {
  227. ClassRegistry::flush();
  228. App::import($type, $class);
  229. $class = $this->getRealClassName($type, $class);
  230. if (strtolower($type) == 'model') {
  231. $instance = ClassRegistry::init($class);
  232. } else {
  233. $instance = new $class();
  234. }
  235. return $instance;
  236. }
  237. /**
  238. * Gets the real class name from the cake short form. If the class name is already
  239. * suffixed with the type, the type will not be duplicated.
  240. *
  241. * @param string $type The Type of object you are generating tests for eg. controller
  242. * @param string $class the Classname of the class the test is being generated for.
  243. * @return string Real classname
  244. */
  245. public function getRealClassName($type, $class) {
  246. if (strtolower($type) == 'model' || empty($this->classTypes[$type])) {
  247. return $class;
  248. }
  249. if (strlen($class) - strpos($class, $type) == strlen($type)) {
  250. return $class;
  251. }
  252. return $class . $type;
  253. }
  254. /**
  255. * Map the types that TestTask uses to concrete types that App::uses can use.
  256. *
  257. * @param string $type The type of thing having a test generated.
  258. * @param string $plugin The plugin name.
  259. * @return string
  260. */
  261. public function mapType($type, $plugin) {
  262. $type = ucfirst($type);
  263. if (empty($this->classTypes[$type])) {
  264. throw new CakeException(__d('cake_dev', 'Invalid object type.'));
  265. }
  266. $real = $this->classTypes[$type];
  267. if ($plugin) {
  268. $real = trim($plugin, '.') . '.' . $real;
  269. }
  270. return $real;
  271. }
  272. /**
  273. * Get methods declared in the class given.
  274. * No parent methods will be returned
  275. *
  276. * @param string $className Name of class to look at.
  277. * @return array Array of method names.
  278. */
  279. public function getTestableMethods($className) {
  280. $classMethods = get_class_methods($className);
  281. $parentMethods = get_class_methods(get_parent_class($className));
  282. $thisMethods = array_diff($classMethods, $parentMethods);
  283. $out = array();
  284. foreach ($thisMethods as $method) {
  285. if (substr($method, 0, 1) != '_' && $method != strtolower($className)) {
  286. $out[] = $method;
  287. }
  288. }
  289. return $out;
  290. }
  291. /**
  292. * Generate the list of fixtures that will be required to run this test based on
  293. * loaded models.
  294. *
  295. * @param object $subject The object you want to generate fixtures for.
  296. * @return array Array of fixtures to be included in the test.
  297. */
  298. public function generateFixtureList($subject) {
  299. $this->_fixtures = array();
  300. if (is_a($subject, 'Model')) {
  301. $this->_processModel($subject);
  302. } elseif (is_a($subject, 'Controller')) {
  303. $this->_processController($subject);
  304. }
  305. return array_values($this->_fixtures);
  306. }
  307. /**
  308. * Process a model recursively and pull out all the
  309. * model names converting them to fixture names.
  310. *
  311. * @param Model $subject A Model class to scan for associations and pull fixtures off of.
  312. * @return void
  313. */
  314. protected function _processModel($subject) {
  315. $this->_addFixture($subject->name);
  316. $associated = $subject->getAssociated();
  317. foreach ($associated as $alias => $type) {
  318. $className = $subject->{$alias}->name;
  319. if (!isset($this->_fixtures[$className])) {
  320. $this->_processModel($subject->{$alias});
  321. }
  322. if ($type == 'hasAndBelongsToMany') {
  323. $joinModel = Inflector::classify($subject->hasAndBelongsToMany[$alias]['joinTable']);
  324. if (!isset($this->_fixtures[$joinModel])) {
  325. $this->_processModel($subject->{$joinModel});
  326. }
  327. }
  328. }
  329. }
  330. /**
  331. * Process all the models attached to a controller
  332. * and generate a fixture list.
  333. *
  334. * @param Controller $subject A controller to pull model names off of.
  335. * @return void
  336. */
  337. protected function _processController($subject) {
  338. $subject->constructClasses();
  339. $models = array(Inflector::classify($subject->name));
  340. if (!empty($subject->uses)) {
  341. $models = $subject->uses;
  342. }
  343. foreach ($models as $model) {
  344. $this->_processModel($subject->{$model});
  345. }
  346. }
  347. /**
  348. * Add classname to the fixture list.
  349. * Sets the app. or plugin.plugin_name. prefix.
  350. *
  351. * @param string $name Name of the Model class that a fixture might be required for.
  352. * @return void
  353. */
  354. protected function _addFixture($name) {
  355. $parent = get_parent_class($name);
  356. $prefix = 'app.';
  357. if (strtolower($parent) != 'appmodel' && strtolower(substr($parent, -8)) == 'appmodel') {
  358. $pluginName = substr($parent, 0, strlen($parent) -8);
  359. $prefix = 'plugin.' . Inflector::underscore($pluginName) . '.';
  360. }
  361. $fixture = $prefix . Inflector::underscore($name);
  362. $this->_fixtures[$name] = $fixture;
  363. }
  364. /**
  365. * Interact with the user to get additional fixtures they want to use.
  366. *
  367. * @return array Array of fixtures the user wants to add.
  368. */
  369. public function getUserFixtures() {
  370. $proceed = $this->in(__d('cake_console', 'Bake could not detect fixtures, would you like to add some?'), array('y','n'), 'n');
  371. $fixtures = array();
  372. if (strtolower($proceed) == 'y') {
  373. $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'"));
  374. $fixtureListTrimmed = str_replace(' ', '', $fixtureList);
  375. $fixtures = explode(',', $fixtureListTrimmed);
  376. }
  377. $this->_fixtures = array_merge($this->_fixtures, $fixtures);
  378. return $fixtures;
  379. }
  380. /**
  381. * Is a mock class required for this type of test?
  382. * Controllers require a mock class.
  383. *
  384. * @param string $type The type of object tests are being generated for eg. controller.
  385. * @return boolean
  386. */
  387. public function hasMockClass($type) {
  388. $type = strtolower($type);
  389. return $type == 'controller';
  390. }
  391. /**
  392. * Generate a constructor code snippet for the type and classname
  393. *
  394. * @param string $type The Type of object you are generating tests for eg. controller
  395. * @param string $fullClassName The Classname of the class the test is being generated for.
  396. * @return string Constructor snippet for the thing you are building.
  397. */
  398. public function generateConstructor($type, $fullClassName) {
  399. $type = strtolower($type);
  400. if ($type == 'model') {
  401. return "ClassRegistry::init('$fullClassName');\n";
  402. }
  403. if ($type == 'controller') {
  404. $className = substr($fullClassName, 0, strlen($fullClassName) - 10);
  405. return "new Test$fullClassName();\n\t\t\$this->{$className}->constructClasses();\n";
  406. }
  407. return "new $fullClassName();\n";
  408. }
  409. /**
  410. * Make the filename for the test case. resolve the suffixes for controllers
  411. * and get the plugin path if needed.
  412. *
  413. * @param string $type The Type of object you are generating tests for eg. controller
  414. * @param string $className the Classname of the class the test is being generated for.
  415. * @return string filename the test should be created on.
  416. */
  417. public function testCaseFileName($type, $className) {
  418. $path = $this->getPath() . 'Case' . DS;
  419. if (isset($this->classTypes[$type])) {
  420. $path .= $this->classTypes[$type] . DS;
  421. }
  422. $className = $this->getRealClassName($type, $className);
  423. return str_replace('/', DS, $path) . Inflector::camelize($className) . 'Test.php';
  424. }
  425. /**
  426. * get the option parser.
  427. *
  428. * @return void
  429. */
  430. public function getOptionParser() {
  431. $parser = parent::getOptionParser();
  432. return $parser->description(__d('cake_console', 'Bake test case skeletons for classes.'))
  433. ->addArgument('type', array(
  434. 'help' => __d('cake_console', 'Type of class to bake, can be any of the following: controller, model, helper, component or behavior.'),
  435. 'choices' => array('controller', 'model', 'helper', 'component', 'behavior')
  436. ))->addArgument('name', array(
  437. 'help' => __d('cake_console', 'An existing class to bake tests for.')
  438. ))->addOption('plugin', array(
  439. 'short' => 'p',
  440. 'help' => __d('cake_console', 'CamelCased name of the plugin to bake tests for.')
  441. ))->epilog(__d('cake_console', 'Omitting all arguments and options will enter into an interactive mode.'));
  442. }
  443. }