PageRenderTime 28ms CodeModel.GetById 1ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Console/Command/Task/TestTask.php

https://bitbucket.org/udeshika/fake_twitter
PHP | 489 lines | 310 code | 32 blank | 147 comment | 48 complexity | 3f95b0b37d3455ae5c8f4f48b38bcae6 MD5 | raw file
  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-2011, 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-2011, 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::underscore($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->path));
  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. $construction = $this->generateConstructor($type, $fullClassName);
  128. $this->out("\n" . __d('cake_console', 'Baking test case for %s %s ...', $className, $type), 1, Shell::QUIET);
  129. $this->Template->set('fixtures', $this->_fixtures);
  130. $this->Template->set('plugin', $plugin);
  131. $this->Template->set(compact(
  132. 'className', 'methods', 'type', 'fullClassName', 'mock',
  133. 'construction', 'realType'
  134. ));
  135. $out = $this->Template->generate('classes', 'test');
  136. $filename = $this->testCaseFileName($type, $className);
  137. $made = $this->createFile($filename, $out);
  138. if ($made) {
  139. return $out;
  140. }
  141. return false;
  142. }
  143. /**
  144. * Interact with the user and get their chosen type. Can exit the script.
  145. *
  146. * @return string Users chosen type.
  147. */
  148. public function getObjectType() {
  149. $this->hr();
  150. $this->out(__d('cake_console', 'Select an object type:'));
  151. $this->hr();
  152. $keys = array();
  153. $i = 0;
  154. foreach ($this->classTypes as $option => $package) {
  155. $this->out(++$i . '. ' . $option);
  156. $keys[] = $i;
  157. }
  158. $keys[] = 'q';
  159. $selection = $this->in(__d('cake_console', 'Enter the type of object to bake a test for or (q)uit'), $keys, 'q');
  160. if ($selection == 'q') {
  161. return $this->_stop();
  162. }
  163. $types = array_keys($this->classTypes);
  164. return $types[$selection - 1];
  165. }
  166. /**
  167. * Get the user chosen Class name for the chosen type
  168. *
  169. * @param string $objectType Type of object to list classes for i.e. Model, Controller.
  170. * @return string Class name the user chose.
  171. */
  172. public function getClassName($objectType) {
  173. $type = ucfirst(strtolower($objectType));
  174. $typeLength = strlen($type);
  175. $type = $this->classTypes[$type];
  176. if ($this->plugin) {
  177. $plugin = $this->plugin . '.';
  178. $options = App::objects($plugin . $type);
  179. } else {
  180. $options = App::objects($type);
  181. }
  182. $this->out(__d('cake_console', 'Choose a %s class', $objectType));
  183. $keys = array();
  184. foreach ($options as $key => $option) {
  185. $this->out(++$key . '. ' . $option);
  186. $keys[] = $key;
  187. }
  188. while (empty($selection)) {
  189. $selection = $this->in(__d('cake_console', 'Choose an existing class, or enter the name of a class that does not exist'));
  190. if (is_numeric($selection) && isset($options[$selection - 1])) {
  191. $selection = $options[$selection - 1];
  192. }
  193. if ($type !== 'Model') {
  194. $selection = substr($selection, 0, $typeLength * - 1);
  195. }
  196. }
  197. return $selection;
  198. }
  199. /**
  200. * Checks whether the chosen type can find its own fixtures.
  201. * Currently only model, and controller are supported
  202. *
  203. * @param string $type The Type of object you are generating tests for eg. controller
  204. * @return boolean
  205. */
  206. public function typeCanDetectFixtures($type) {
  207. $type = strtolower($type);
  208. return in_array($type, array('controller', 'model'));
  209. }
  210. /**
  211. * Check if a class with the given package is loaded or can be loaded.
  212. *
  213. * @param string $package The package of object you are generating tests for eg. controller
  214. * @param string $class the Classname of the class the test is being generated for.
  215. * @return boolean
  216. */
  217. public function isLoadableClass($package, $class) {
  218. App::uses($class, $package);
  219. return class_exists($class);
  220. }
  221. /**
  222. * Construct an instance of the class to be tested.
  223. * So that fixtures can be detected
  224. *
  225. * @param string $type The Type of object you are generating tests for eg. controller
  226. * @param string $class the Classname of the class the test is being generated for.
  227. * @return object And instance of the class that is going to be tested.
  228. */
  229. public function &buildTestSubject($type, $class) {
  230. ClassRegistry::flush();
  231. App::import($type, $class);
  232. $class = $this->getRealClassName($type, $class);
  233. if (strtolower($type) == 'model') {
  234. $instance = ClassRegistry::init($class);
  235. } else {
  236. $instance = new $class();
  237. }
  238. return $instance;
  239. }
  240. /**
  241. * Gets the real class name from the cake short form. If the class name is already
  242. * suffixed with the type, the type will not be duplicated.
  243. *
  244. * @param string $type The Type of object you are generating tests for eg. controller
  245. * @param string $class the Classname of the class the test is being generated for.
  246. * @return string Real classname
  247. */
  248. public function getRealClassName($type, $class) {
  249. if (strtolower($type) == 'model' || empty($this->classTypes[$type])) {
  250. return $class;
  251. }
  252. if (strlen($class) - strpos($class, $type) == strlen($type)) {
  253. return $class;
  254. }
  255. return $class . $type;
  256. }
  257. /**
  258. * Map the types that TestTask uses to concrete types that App::uses can use.
  259. *
  260. * @param string $type The type of thing having a test generated.
  261. * @param string $plugin The plugin name.
  262. * @return string
  263. */
  264. public function mapType($type, $plugin) {
  265. $type = ucfirst($type);
  266. if (empty($this->classTypes[$type])) {
  267. throw new CakeException(__d('cake_dev', 'Invalid object type.'));
  268. }
  269. $real = $this->classTypes[$type];
  270. if ($plugin) {
  271. $real = trim($plugin, '.') . '.' . $real;
  272. }
  273. return $real;
  274. }
  275. /**
  276. * Get methods declared in the class given.
  277. * No parent methods will be returned
  278. *
  279. * @param string $className Name of class to look at.
  280. * @return array Array of method names.
  281. */
  282. public function getTestableMethods($className) {
  283. $classMethods = get_class_methods($className);
  284. $parentMethods = get_class_methods(get_parent_class($className));
  285. $thisMethods = array_diff($classMethods, $parentMethods);
  286. $out = array();
  287. foreach ($thisMethods as $method) {
  288. if (substr($method, 0, 1) != '_' && $method != strtolower($className)) {
  289. $out[] = $method;
  290. }
  291. }
  292. return $out;
  293. }
  294. /**
  295. * Generate the list of fixtures that will be required to run this test based on
  296. * loaded models.
  297. *
  298. * @param object $subject The object you want to generate fixtures for.
  299. * @return array Array of fixtures to be included in the test.
  300. */
  301. public function generateFixtureList($subject) {
  302. $this->_fixtures = array();
  303. if (is_a($subject, 'Model')) {
  304. $this->_processModel($subject);
  305. } elseif (is_a($subject, 'Controller')) {
  306. $this->_processController($subject);
  307. }
  308. return array_values($this->_fixtures);
  309. }
  310. /**
  311. * Process a model recursively and pull out all the
  312. * model names converting them to fixture names.
  313. *
  314. * @param Model $subject A Model class to scan for associations and pull fixtures off of.
  315. * @return void
  316. */
  317. protected function _processModel($subject) {
  318. $this->_addFixture($subject->name);
  319. $associated = $subject->getAssociated();
  320. foreach ($associated as $alias => $type) {
  321. $className = $subject->{$alias}->name;
  322. if (!isset($this->_fixtures[$className])) {
  323. $this->_processModel($subject->{$alias});
  324. }
  325. if ($type == 'hasAndBelongsToMany') {
  326. $joinModel = Inflector::classify($subject->hasAndBelongsToMany[$alias]['joinTable']);
  327. if (!isset($this->_fixtures[$joinModel])) {
  328. $this->_processModel($subject->{$joinModel});
  329. }
  330. }
  331. }
  332. }
  333. /**
  334. * Process all the models attached to a controller
  335. * and generate a fixture list.
  336. *
  337. * @param Controller $subject A controller to pull model names off of.
  338. * @return void
  339. */
  340. protected function _processController($subject) {
  341. $subject->constructClasses();
  342. $models = array(Inflector::classify($subject->name));
  343. if (!empty($subject->uses)) {
  344. $models = $subject->uses;
  345. }
  346. foreach ($models as $model) {
  347. $this->_processModel($subject->{$model});
  348. }
  349. }
  350. /**
  351. * Add classname to the fixture list.
  352. * Sets the app. or plugin.plugin_name. prefix.
  353. *
  354. * @param string $name Name of the Model class that a fixture might be required for.
  355. * @return void
  356. */
  357. protected function _addFixture($name) {
  358. $parent = get_parent_class($name);
  359. $prefix = 'app.';
  360. if (strtolower($parent) != 'appmodel' && strtolower(substr($parent, -8)) == 'appmodel') {
  361. $pluginName = substr($parent, 0, strlen($parent) -8);
  362. $prefix = 'plugin.' . Inflector::underscore($pluginName) . '.';
  363. }
  364. $fixture = $prefix . Inflector::underscore($name);
  365. $this->_fixtures[$name] = $fixture;
  366. }
  367. /**
  368. * Interact with the user to get additional fixtures they want to use.
  369. *
  370. * @return array Array of fixtures the user wants to add.
  371. */
  372. public function getUserFixtures() {
  373. $proceed = $this->in(__d('cake_console', 'Bake could not detect fixtures, would you like to add some?'), array('y', 'n'), 'n');
  374. $fixtures = array();
  375. if (strtolower($proceed) == 'y') {
  376. $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'"));
  377. $fixtureListTrimmed = str_replace(' ', '', $fixtureList);
  378. $fixtures = explode(',', $fixtureListTrimmed);
  379. }
  380. $this->_fixtures = array_merge($this->_fixtures, $fixtures);
  381. return $fixtures;
  382. }
  383. /**
  384. * Is a mock class required for this type of test?
  385. * Controllers require a mock class.
  386. *
  387. * @param string $type The type of object tests are being generated for eg. controller.
  388. * @return boolean
  389. */
  390. public function hasMockClass($type) {
  391. $type = strtolower($type);
  392. return $type == 'controller';
  393. }
  394. /**
  395. * Generate a constructor code snippet for the type and classname
  396. *
  397. * @param string $type The Type of object you are generating tests for eg. controller
  398. * @param string $fullClassName The Classname of the class the test is being generated for.
  399. * @return string Constructor snippet for the thing you are building.
  400. */
  401. public function generateConstructor($type, $fullClassName) {
  402. $type = strtolower($type);
  403. if ($type == 'model') {
  404. return "ClassRegistry::init('$fullClassName');\n";
  405. }
  406. if ($type == 'controller') {
  407. $className = substr($fullClassName, 0, strlen($fullClassName) - 10);
  408. return "new Test$fullClassName();\n\t\t\$this->{$className}->constructClasses();\n";
  409. }
  410. return "new $fullClassName();\n";
  411. }
  412. /**
  413. * Make the filename for the test case. resolve the suffixes for controllers
  414. * and get the plugin path if needed.
  415. *
  416. * @param string $type The Type of object you are generating tests for eg. controller
  417. * @param string $className the Classname of the class the test is being generated for.
  418. * @return string filename the test should be created on.
  419. */
  420. public function testCaseFileName($type, $className) {
  421. $path = $this->getPath() . 'Case' . DS;
  422. $type = Inflector::camelize($type);
  423. if (isset($this->classTypes[$type])) {
  424. $path .= $this->classTypes[$type] . DS;
  425. }
  426. $className = $this->getRealClassName($type, $className);
  427. return str_replace('/', DS, $path) . Inflector::camelize($className) . 'Test.php';
  428. }
  429. /**
  430. * get the option parser.
  431. *
  432. * @return void
  433. */
  434. public function getOptionParser() {
  435. $parser = parent::getOptionParser();
  436. return $parser->description(__d('cake_console', 'Bake test case skeletons for classes.'))
  437. ->addArgument('type', array(
  438. 'help' => __d('cake_console', 'Type of class to bake, can be any of the following: controller, model, helper, component or behavior.'),
  439. 'choices' => array(
  440. 'Controller', 'controller',
  441. 'Model', 'model',
  442. 'Helper', 'helper',
  443. 'Component', 'component',
  444. 'Behavior', 'behavior'
  445. )
  446. ))->addArgument('name', array(
  447. 'help' => __d('cake_console', 'An existing class to bake tests for.')
  448. ))->addOption('plugin', array(
  449. 'short' => 'p',
  450. 'help' => __d('cake_console', 'CamelCased name of the plugin to bake tests for.')
  451. ))->epilog(__d('cake_console', 'Omitting all arguments and options will enter into an interactive mode.'));
  452. }
  453. }