TestTask.php 16 KB

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