TestTask.php 17 KB

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