TestTask.php 16 KB

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