TestTask.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. <?php
  2. /**
  3. * The TestTask handles creating and updating test files.
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. * @link http://cakephp.org CakePHP(tm) Project
  14. * @since CakePHP(tm) v 1.3
  15. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  16. */
  17. App::uses('AppShell', 'Console/Command');
  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. * Mapping between packages, and their baseclass + package.
  52. * This is used to generate App::uses() call to autoload base
  53. * classes if a developer has forgotten to do so.
  54. *
  55. * @var array
  56. */
  57. public $baseTypes = array(
  58. 'Model' => array('Model', 'Model'),
  59. 'Behavior' => array('ModelBehavior', 'Model'),
  60. 'Controller' => array('Controller', 'Controller'),
  61. 'Component' => array('Component', 'Controller'),
  62. 'Helper' => array('Helper', 'View')
  63. );
  64. /**
  65. * Internal list of fixtures that have been added so far.
  66. *
  67. * @var array
  68. */
  69. protected $_fixtures = array();
  70. /**
  71. * Execution method always used for tasks
  72. *
  73. * @return void
  74. */
  75. public function execute() {
  76. parent::execute();
  77. $count = count($this->args);
  78. if (!$count) {
  79. $this->_interactive();
  80. }
  81. if ($count === 1) {
  82. $this->_interactive($this->args[0]);
  83. }
  84. if ($count > 1) {
  85. $type = Inflector::classify($this->args[0]);
  86. if ($this->bake($type, $this->args[1])) {
  87. $this->out('<success>Done</success>');
  88. }
  89. }
  90. }
  91. /**
  92. * Handles interactive baking
  93. *
  94. * @param string $type The type of object to bake a test for.
  95. * @return string|boolean
  96. */
  97. protected function _interactive($type = null) {
  98. $this->interactive = true;
  99. $this->hr();
  100. $this->out(__d('cake_console', 'Bake Tests'));
  101. $this->out(__d('cake_console', 'Path: %s', $this->getPath()));
  102. $this->hr();
  103. if ($type) {
  104. $type = Inflector::camelize($type);
  105. if (!isset($this->classTypes[$type])) {
  106. $this->error(__d('cake_console', 'Incorrect type provided. Please choose one of %s', implode(', ', array_keys($this->classTypes))));
  107. }
  108. } else {
  109. $type = $this->getObjectType();
  110. }
  111. $className = $this->getClassName($type);
  112. return $this->bake($type, $className);
  113. }
  114. /**
  115. * Completes final steps for generating data to create test case.
  116. *
  117. * @param string $type Type of object to bake test case for ie. Model, Controller
  118. * @param string $className the 'cake name' for the class ie. Posts for the PostsController
  119. * @return string|boolean
  120. */
  121. public function bake($type, $className) {
  122. $plugin = null;
  123. if ($this->plugin) {
  124. $plugin = $this->plugin . '.';
  125. }
  126. $realType = $this->mapType($type, $plugin);
  127. $fullClassName = $this->getRealClassName($type, $className);
  128. if ($this->typeCanDetectFixtures($type) && $this->isLoadableClass($realType, $fullClassName)) {
  129. $this->out(__d('cake_console', 'Bake is detecting possible fixtures...'));
  130. $testSubject = $this->buildTestSubject($type, $className);
  131. $this->generateFixtureList($testSubject);
  132. } elseif ($this->interactive) {
  133. $this->getUserFixtures();
  134. }
  135. list($baseClass, $baseType) = $this->getBaseType($type);
  136. App::uses($baseClass, $baseType);
  137. App::uses($fullClassName, $realType);
  138. $methods = array();
  139. if (class_exists($fullClassName)) {
  140. $methods = $this->getTestableMethods($fullClassName);
  141. }
  142. $mock = $this->hasMockClass($type, $fullClassName);
  143. list($preConstruct, $construction, $postConstruct) = $this->generateConstructor($type, $fullClassName, $plugin);
  144. $uses = $this->generateUses($type, $realType, $fullClassName);
  145. $this->out("\n" . __d('cake_console', 'Baking test case for %s %s ...', $className, $type), 1, Shell::QUIET);
  146. $this->Template->set('fixtures', $this->_fixtures);
  147. $this->Template->set('plugin', $plugin);
  148. $this->Template->set(compact(
  149. 'className', 'methods', 'type', 'fullClassName', 'mock',
  150. 'realType', 'preConstruct', 'postConstruct', 'construction',
  151. 'uses'
  152. ));
  153. $out = $this->Template->generate('classes', 'test');
  154. $filename = $this->testCaseFileName($type, $className);
  155. $made = $this->createFile($filename, $out);
  156. if ($made) {
  157. return $out;
  158. }
  159. return false;
  160. }
  161. /**
  162. * Interact with the user and get their chosen type. Can exit the script.
  163. *
  164. * @return string Users chosen type.
  165. */
  166. public function getObjectType() {
  167. $this->hr();
  168. $this->out(__d('cake_console', 'Select an object type:'));
  169. $this->hr();
  170. $keys = array();
  171. $i = 0;
  172. foreach ($this->classTypes as $option => $package) {
  173. $this->out(++$i . '. ' . $option);
  174. $keys[] = $i;
  175. }
  176. $keys[] = 'q';
  177. $selection = $this->in(__d('cake_console', 'Enter the type of object to bake a test for or (q)uit'), $keys, 'q');
  178. if ($selection === 'q') {
  179. return $this->_stop();
  180. }
  181. $types = array_keys($this->classTypes);
  182. return $types[$selection - 1];
  183. }
  184. /**
  185. * Get the user chosen Class name for the chosen type
  186. *
  187. * @param string $objectType Type of object to list classes for i.e. Model, Controller.
  188. * @return string Class name the user chose.
  189. */
  190. public function getClassName($objectType) {
  191. $type = ucfirst(strtolower($objectType));
  192. $typeLength = strlen($type);
  193. $type = $this->classTypes[$type];
  194. if ($this->plugin) {
  195. $plugin = $this->plugin . '.';
  196. $options = App::objects($plugin . $type);
  197. } else {
  198. $options = App::objects($type);
  199. }
  200. $this->out(__d('cake_console', 'Choose a %s class', $objectType));
  201. $keys = array();
  202. foreach ($options as $key => $option) {
  203. $this->out(++$key . '. ' . $option);
  204. $keys[] = $key;
  205. }
  206. while (empty($selection)) {
  207. $selection = $this->in(__d('cake_console', 'Choose an existing class, or enter the name of a class that does not exist'));
  208. if (is_numeric($selection) && isset($options[$selection - 1])) {
  209. $selection = $options[$selection - 1];
  210. }
  211. if ($type !== 'Model') {
  212. $selection = substr($selection, 0, $typeLength * - 1);
  213. }
  214. }
  215. return $selection;
  216. }
  217. /**
  218. * Checks whether the chosen type can find its own fixtures.
  219. * Currently only model, and controller are supported
  220. *
  221. * @param string $type The Type of object you are generating tests for eg. controller
  222. * @return boolean
  223. */
  224. public function typeCanDetectFixtures($type) {
  225. $type = strtolower($type);
  226. return in_array($type, array('controller', 'model'));
  227. }
  228. /**
  229. * Check if a class with the given package is loaded or can be loaded.
  230. *
  231. * @param string $package The package of object you are generating tests for eg. controller
  232. * @param string $class the Classname of the class the test is being generated for.
  233. * @return boolean
  234. */
  235. public function isLoadableClass($package, $class) {
  236. App::uses($class, $package);
  237. list($plugin, $ns) = pluginSplit($package);
  238. if ($plugin) {
  239. App::uses("{$plugin}AppController", $package);
  240. App::uses("{$plugin}AppModel", $package);
  241. App::uses("{$plugin}AppHelper", $package);
  242. }
  243. return class_exists($class);
  244. }
  245. /**
  246. * Construct an instance of the class to be tested.
  247. * So that fixtures can be detected
  248. *
  249. * @param string $type The Type of object you are generating tests for eg. controller
  250. * @param string $class the Classname of the class the test is being generated for.
  251. * @return object And instance of the class that is going to be tested.
  252. */
  253. public function buildTestSubject($type, $class) {
  254. ClassRegistry::flush();
  255. App::uses($class, $type);
  256. $class = $this->getRealClassName($type, $class);
  257. if (strtolower($type) === 'model') {
  258. $instance = ClassRegistry::init($class);
  259. } else {
  260. $instance = new $class();
  261. }
  262. return $instance;
  263. }
  264. /**
  265. * Gets the real class name from the cake short form. If the class name is already
  266. * suffixed with the type, the type will not be duplicated.
  267. *
  268. * @param string $type The Type of object you are generating tests for eg. controller
  269. * @param string $class the Classname of the class the test is being generated for.
  270. * @return string Real class name
  271. */
  272. public function getRealClassName($type, $class) {
  273. if (strtolower($type) === 'model' || empty($this->classTypes[$type])) {
  274. return $class;
  275. }
  276. $position = strpos($class, $type);
  277. if ($position !== false && (strlen($class) - $position) === strlen($type)) {
  278. return $class;
  279. }
  280. return $class . $type;
  281. }
  282. /**
  283. * Map the types that TestTask uses to concrete types that App::uses can use.
  284. *
  285. * @param string $type The type of thing having a test generated.
  286. * @param string $plugin The plugin name.
  287. * @return string
  288. * @throws CakeException When invalid object types are requested.
  289. */
  290. public function mapType($type, $plugin) {
  291. $type = ucfirst($type);
  292. if (empty($this->classTypes[$type])) {
  293. throw new CakeException(__d('cake_dev', 'Invalid object type.'));
  294. }
  295. $real = $this->classTypes[$type];
  296. if ($plugin) {
  297. $real = trim($plugin, '.') . '.' . $real;
  298. }
  299. return $real;
  300. }
  301. /**
  302. * Get the base class and package name for a given type.
  303. *
  304. * @param string $type The type the class having a test
  305. * generated for is in.
  306. * @return array Array of (class, type)
  307. * @throws CakeException on invalid types.
  308. */
  309. public function getBaseType($type) {
  310. if (empty($this->baseTypes[$type])) {
  311. throw new CakeException(__d('cake_dev', 'Invalid type name'));
  312. }
  313. return $this->baseTypes[$type];
  314. }
  315. /**
  316. * Get methods declared in the class given.
  317. * No parent methods will be returned
  318. *
  319. * @param string $className Name of class to look at.
  320. * @return array Array of method names.
  321. */
  322. public function getTestableMethods($className) {
  323. $classMethods = get_class_methods($className);
  324. $parentMethods = get_class_methods(get_parent_class($className));
  325. $thisMethods = array_diff($classMethods, $parentMethods);
  326. $out = array();
  327. foreach ($thisMethods as $method) {
  328. if (substr($method, 0, 1) !== '_' && $method != strtolower($className)) {
  329. $out[] = $method;
  330. }
  331. }
  332. return $out;
  333. }
  334. /**
  335. * Generate the list of fixtures that will be required to run this test based on
  336. * loaded models.
  337. *
  338. * @param object $subject The object you want to generate fixtures for.
  339. * @return array Array of fixtures to be included in the test.
  340. */
  341. public function generateFixtureList($subject) {
  342. $this->_fixtures = array();
  343. if ($subject instanceof Model) {
  344. $this->_processModel($subject);
  345. } elseif ($subject instanceof Controller) {
  346. $this->_processController($subject);
  347. }
  348. return array_values($this->_fixtures);
  349. }
  350. /**
  351. * Process a model recursively and pull out all the
  352. * model names converting them to fixture names.
  353. *
  354. * @param Model $subject A Model class to scan for associations and pull fixtures off of.
  355. * @return void
  356. */
  357. protected function _processModel($subject) {
  358. $this->_addFixture($subject->name);
  359. $associated = $subject->getAssociated();
  360. foreach ($associated as $alias => $type) {
  361. $className = $subject->{$alias}->name;
  362. if (!isset($this->_fixtures[$className])) {
  363. $this->_processModel($subject->{$alias});
  364. }
  365. if ($type === 'hasAndBelongsToMany') {
  366. if (!empty($subject->hasAndBelongsToMany[$alias]['with'])) {
  367. list(, $joinModel) = pluginSplit($subject->hasAndBelongsToMany[$alias]['with']);
  368. } else {
  369. $joinModel = Inflector::classify($subject->hasAndBelongsToMany[$alias]['joinTable']);
  370. }
  371. if (!isset($this->_fixtures[$joinModel])) {
  372. $this->_processModel($subject->{$joinModel});
  373. }
  374. }
  375. }
  376. }
  377. /**
  378. * Process all the models attached to a controller
  379. * and generate a fixture list.
  380. *
  381. * @param Controller $subject A controller to pull model names off of.
  382. * @return void
  383. */
  384. protected function _processController($subject) {
  385. $subject->constructClasses();
  386. $models = array(Inflector::classify($subject->name));
  387. if (!empty($subject->uses)) {
  388. $models = $subject->uses;
  389. }
  390. foreach ($models as $model) {
  391. list(, $model) = pluginSplit($model);
  392. $this->_processModel($subject->{$model});
  393. }
  394. }
  395. /**
  396. * Add class name to the fixture list.
  397. * Sets the app. or plugin.plugin_name. prefix.
  398. *
  399. * @param string $name Name of the Model class that a fixture might be required for.
  400. * @return void
  401. */
  402. protected function _addFixture($name) {
  403. if ($this->plugin) {
  404. $prefix = 'plugin.' . Inflector::underscore($this->plugin) . '.';
  405. } else {
  406. $prefix = 'app.';
  407. }
  408. $fixture = $prefix . Inflector::underscore($name);
  409. $this->_fixtures[$name] = $fixture;
  410. }
  411. /**
  412. * Interact with the user to get additional fixtures they want to use.
  413. *
  414. * @return array Array of fixtures the user wants to add.
  415. */
  416. public function getUserFixtures() {
  417. $proceed = $this->in(__d('cake_console', 'Bake could not detect fixtures, would you like to add some?'), array('y', 'n'), 'n');
  418. $fixtures = array();
  419. if (strtolower($proceed) === 'y') {
  420. $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'"));
  421. $fixtureListTrimmed = str_replace(' ', '', $fixtureList);
  422. $fixtures = explode(',', $fixtureListTrimmed);
  423. }
  424. $this->_fixtures = array_merge($this->_fixtures, $fixtures);
  425. return $fixtures;
  426. }
  427. /**
  428. * Is a mock class required for this type of test?
  429. * Controllers require a mock class.
  430. *
  431. * @param string $type The type of object tests are being generated for eg. controller.
  432. * @return boolean
  433. */
  434. public function hasMockClass($type) {
  435. $type = strtolower($type);
  436. return $type === 'controller';
  437. }
  438. /**
  439. * Generate a constructor code snippet for the type and class name
  440. *
  441. * @param string $type The Type of object you are generating tests for eg. controller
  442. * @param string $fullClassName The Classname of the class the test is being generated for.
  443. * @param string $plugin The plugin name.
  444. * @return array Constructor snippets for the thing you are building.
  445. */
  446. public function generateConstructor($type, $fullClassName, $plugin) {
  447. $type = strtolower($type);
  448. $pre = $construct = $post = '';
  449. if ($type === 'model') {
  450. $construct = "ClassRegistry::init('{$plugin}$fullClassName');\n";
  451. }
  452. if ($type === 'behavior') {
  453. $construct = "new $fullClassName();\n";
  454. }
  455. if ($type === 'helper') {
  456. $pre = "\$View = new View();\n";
  457. $construct = "new {$fullClassName}(\$View);\n";
  458. }
  459. if ($type === 'component') {
  460. $pre = "\$Collection = new ComponentCollection();\n";
  461. $construct = "new {$fullClassName}(\$Collection);\n";
  462. }
  463. return array($pre, $construct, $post);
  464. }
  465. /**
  466. * Generate the uses() calls for a type & class name
  467. *
  468. * @param string $type The Type of object you are generating tests for eg. controller
  469. * @param string $realType The package name for the class.
  470. * @param string $className The Classname of the class the test is being generated for.
  471. * @return array An array containing used classes
  472. */
  473. public function generateUses($type, $realType, $className) {
  474. $uses = array();
  475. $type = strtolower($type);
  476. if ($type === 'component') {
  477. $uses[] = array('ComponentCollection', 'Controller');
  478. $uses[] = array('Component', 'Controller');
  479. }
  480. if ($type === 'helper') {
  481. $uses[] = array('View', 'View');
  482. $uses[] = array('Helper', 'View');
  483. }
  484. $uses[] = array($className, $realType);
  485. return $uses;
  486. }
  487. /**
  488. * Make the filename for the test case. resolve the suffixes for controllers
  489. * and get the plugin path if needed.
  490. *
  491. * @param string $type The Type of object you are generating tests for eg. controller
  492. * @param string $className the Classname of the class the test is being generated for.
  493. * @return string filename the test should be created on.
  494. */
  495. public function testCaseFileName($type, $className) {
  496. $path = $this->getPath() . 'Case' . DS;
  497. $type = Inflector::camelize($type);
  498. if (isset($this->classTypes[$type])) {
  499. $path .= $this->classTypes[$type] . DS;
  500. }
  501. $className = $this->getRealClassName($type, $className);
  502. return str_replace('/', DS, $path) . Inflector::camelize($className) . 'Test.php';
  503. }
  504. /**
  505. * Gets the option parser instance and configures it.
  506. *
  507. * @return ConsoleOptionParser
  508. */
  509. public function getOptionParser() {
  510. $parser = parent::getOptionParser();
  511. $parser->description(
  512. __d('cake_console', 'Bake test case skeletons for classes.')
  513. )->addArgument('type', array(
  514. 'help' => __d('cake_console', 'Type of class to bake, can be any of the following: controller, model, helper, component or behavior.'),
  515. 'choices' => array(
  516. 'Controller', 'controller',
  517. 'Model', 'model',
  518. 'Helper', 'helper',
  519. 'Component', 'component',
  520. 'Behavior', 'behavior'
  521. )
  522. ))->addArgument('name', array(
  523. 'help' => __d('cake_console', 'An existing class to bake tests for.')
  524. ))->addOption('theme', array(
  525. 'short' => 't',
  526. 'help' => __d('cake_console', 'Theme to use when baking code.')
  527. ))->addOption('plugin', array(
  528. 'short' => 'p',
  529. 'help' => __d('cake_console', 'CamelCased name of the plugin to bake tests for.')
  530. ))->addOption('force', array(
  531. 'short' => 'f',
  532. 'help' => __d('cake_console', 'Force overwriting existing files without prompting.')
  533. ))->epilog(
  534. __d('cake_console', 'Omitting all arguments and options will enter into an interactive mode.')
  535. );
  536. return $parser;
  537. }
  538. }