TestTask.php 15 KB

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