TestTask.php 18 KB

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