Skip to content
This repository
Browse code

Test generation for models is partially complete.

fixtures and introspected methods work.
  • Loading branch information...
commit 587b0ca07d3e6fe0e71a25eff4abdd750d2e7831 1 parent eb9f40c
Mark Story authored May 24, 2009
259  cake/console/libs/tasks/test.php
@@ -47,6 +47,13 @@ class TestTask extends Shell {
47 47
 	var $path = TESTS;
48 48
 
49 49
 /**
  50
+ * Tasks used.
  51
+ *
  52
+ * @var array
  53
+ **/
  54
+	var $tasks = array('Template');
  55
+
  56
+/**
50 57
  * class types that methods can be generated for
51 58
  *
52 59
  * @var array
@@ -54,6 +61,20 @@ class TestTask extends Shell {
54 61
 	var $classTypes =  array('Model', 'Controller', 'Component', 'Behavior', 'Helper');
55 62
 
56 63
 /**
  64
+ * Internal list of fixtures that have been added so far.
  65
+ *
  66
+ * @var string
  67
+ **/
  68
+	var $_fixtures = array();
  69
+
  70
+/**
  71
+ * Flag for interactive mode
  72
+ *
  73
+ * @var boolean
  74
+ **/
  75
+	var $interactive = false;
  76
+
  77
+/**
57 78
  * Execution method always used for tasks
58 79
  *
59 80
  * @access public
@@ -68,8 +89,8 @@ function execute() {
68 89
 		}
69 90
 
70 91
 		if (count($this->args) > 1) {
71  
-			$class = Inflector::underscore($this->args[0]);
72  
-			if ($this->bake($class, $this->args[1])) {
  92
+			$type = Inflector::underscore($this->args[0]);
  93
+			if ($this->bake($type, $this->args[1])) {
73 94
 				$this->out('done');
74 95
 			}
75 96
 		}
@@ -81,6 +102,7 @@ function execute() {
81 102
  * @access private
82 103
  */
83 104
 	function __interactive($type = null) {
  105
+		$this->interactive = true;
84 106
 		$this->hr();
85 107
 		$this->out(__('Bake Tests', true));
86 108
 		$this->out(sprintf(__("Path: %s", true), $this->path));
@@ -89,75 +111,54 @@ function __interactive($type = null) {
89 111
 		$selection = null;
90 112
 		if ($type) {
91 113
 			$type = Inflector::camelize($type);
92  
-			if (in_array($type, $this->classTypes)) {
93  
-				$selection = array_search($type);
  114
+			if (!in_array($type, $this->classTypes)) {
  115
+				unset($type);
94 116
 			}
95 117
 		}
96  
-		if (!$selection) {
97  
-			$selection = $this->getObjectType();
98  
-		}
99  
-		/*
100  
-
101  
-			$key = $this->in(__("Enter the class to bake a test for or (q)uit", true), $keys, 'q');
102  
-
103  
-			if ($key != 'q') {
104  
-				if (isset($options[--$key])) {
105  
-					$class = $options[$key];
106  
-				}
107  
-
108  
-				if ($class) {
109  
-					$name = $this->in(__("Enter the name for the test or (q)uit", true), null, 'q');
110  
-					if ($name !== 'q') {
111  
-						$case = null;
112  
-						while ($case !== 'q') {
113  
-							$case = $this->in(__("Enter a test case or (q)uit", true), null, 'q');
114  
-							if ($case !== 'q') {
115  
-								$cases[] = $case;
116  
-							}
117  
-						}
118  
-						if ($this->bake($class, $name, $cases)) {
119  
-							$this->out(__("Test baked\n", true));
120  
-							$type = null;
121  
-						}
122  
-						$class = null;
123  
-					}
124  
-				}
125  
-			} else {
126  
-				$this->_stop();
127  
-			}
  118
+		if (!$type) {
  119
+			$type = $this->getObjectType();
128 120
 		}
129  
-		*/
  121
+		$className = $this->getClassName($type);
  122
+		return $this->bake($type, $className);
130 123
 	}
131 124
 
132 125
 /**
133  
- * Interact with the user and get their chosen type. Can exit the script.
  126
+ * Completes final steps for generating data to create test case.
134 127
  *
135  
- * @return int Index of users chosen object type.
136  
- **/
137  
-	function getObjectType() {
138  
-		$this->hr();
139  
-		$this->out(__("Select an object type:", true));
140  
-		$this->hr();
  128
+ * @param string $type Type of object to bake test case for ie. Model, Controller
  129
+ * @param string $className the 'cake name' for the class ie. Posts for the PostsController 
  130
+ * @access public
  131
+ */
  132
+	function bake($type, $className) {
  133
+		if ($this->typeCanDetectFixtures($type) && $this->isLoadableClass($type, $className)) {
  134
+			$this->out(__('Bake is detecting possible fixtures..', true));
  135
+			$testSubject =& $this->buildTestSubject($type, $className);
  136
+			$this->generateFixtureList($testSubject);
  137
+		} elseif ($this->interactive) {
  138
+			$this->getUserFixtures();
  139
+		}
  140
+		$fullClassName = $this->getRealClassName($type, $className);
141 141
 
142  
-		$keys = array();
143  
-		foreach ($this->classTypes as $key => $option) {
144  
-			$this->out(++$key . '. ' . $option);
145  
-			$keys[] = $key;
  142
+		$methods = array();
  143
+		if (class_exists($fullClassName)) {
  144
+			$methods = $this->getTestableMethods($fullClassName);
146 145
 		}
147  
-		$keys[] = 'q';
148  
-		$selection = $this->in(__("Enter the type of object to bake a test for or (q)uit", true), $keys, 'q');
149  
-		if ($selection == 'q') {
150  
-			$this->_stop();
  146
+
  147
+		$this->Template->set('fixtures', $this->_fixtures);
  148
+		$this->Template->set('plugin', $this->plugin);
  149
+		$this->Template->set(compact('className', 'methods', 'type', 'fullClassName'));
  150
+		$out = $this->Template->generate('objects', 'test');
  151
+
  152
+		if (strpos($this->path, $type) === false) {
  153
+			$this->filePath = $this->path . 'cases' . DS . Inflector::tableize($type) . DS;
151 154
 		}
152  
-		return $selection;
153  
-	}
  155
+		$made = $this->createFile($this->filePath . Inflector::underscore($className) . '.test.php', $out);
  156
+		if ($made) {
  157
+			return $out;
  158
+		}
  159
+		return false;
154 160
 
155  
-/**
156  
- * Writes File
157  
- *
158  
- * @access public
159  
- */
160  
-	function bake($class, $name = null, $cases = array()) {
  161
+		/*
161 162
 		if (!$name) {
162 163
 			return false;
163 164
 		}
@@ -205,23 +206,102 @@ function bake($class, $name = null, $cases = array()) {
205 206
 		}
206 207
 
207 208
 		$header = '$Id';
208  
-		$content = "<?php \n/* SVN FILE: $header$ */\n/* ". $name ." Test cases generated on: " . date('Y-m-d H:m:s') . " : ". time() . "*/\n{$out}?>";
  209
+		$content = "<?php \n/* SVN FILE: $header$ * /\n/* ". $name ." Test cases generated on: " . date('Y-m-d H:m:s') . " : ". time() . "* /\n{$out}?>";
209 210
 		return $this->createFile($this->filePath . Inflector::underscore($name) . '.test.php', $content);
  211
+		*/
210 212
 	}
  213
+
211 214
 /**
212  
- * Handles the extra stuff needed
  215
+ * Interact with the user and get their chosen type. Can exit the script.
213 216
  *
214  
- * @access private
215  
- */
216  
-	function __extras($class) {
217  
-		$extras = null;
218  
-		switch ($class) {
219  
-			case 'Model':
220  
-				$extras = "\n\tvar \$cacheSources = false;";
221  
-				$extras .= "\n\tvar \$useDbConfig = 'test_suite';\n";
222  
-			break;
  217
+ * @return string Users chosen type.
  218
+ **/
  219
+	function getObjectType() {
  220
+		$this->hr();
  221
+		$this->out(__("Select an object type:", true));
  222
+		$this->hr();
  223
+
  224
+		$keys = array();
  225
+		foreach ($this->classTypes as $key => $option) {
  226
+			$this->out(++$key . '. ' . $option);
  227
+			$keys[] = $key;
223 228
 		}
224  
-		return $extras;
  229
+		$keys[] = 'q';
  230
+		$selection = $this->in(__("Enter the type of object to bake a test for or (q)uit", true), $keys, 'q');
  231
+		if ($selection == 'q') {
  232
+			return $this->_stop();
  233
+		}
  234
+		return $this->classTypes[$selection - 1];
  235
+	}
  236
+
  237
+/**
  238
+ * Get the user chosen Class name for the chosen type
  239
+ *
  240
+ * @param string $objectType Type of object to list classes for i.e. Model, Controller.
  241
+ * @return string Class name the user chose.
  242
+ **/
  243
+	function getClassName($objectType) {
  244
+		$options = Configure::listObjects(strtolower($objectType));
  245
+		$this->out(sprintf(__('Choose a %s class', true), $objectType));
  246
+		$keys = array();
  247
+		foreach ($options as $key => $option) {
  248
+			$this->out(++$key . '. ' . $option);
  249
+			$keys[] = $key;
  250
+		}
  251
+		$selection = $this->in(__('Choose an existing class, or enter the name of a class that does not exist', true));
  252
+		if (isset($options[$selection - 1])) {
  253
+			return $options[$selection - 1];
  254
+		}
  255
+		return $selection;
  256
+	}
  257
+
  258
+/**
  259
+ * Checks whether the chosen type can find its own fixtures.
  260
+ * Currently only model, and controller are supported
  261
+ *
  262
+ * @return boolean
  263
+ **/
  264
+	function typeCanDetectFixtures($type) {
  265
+		$type = strtolower($type);
  266
+		return ($type == 'controller' || $type == 'model');
  267
+	}
  268
+
  269
+/**
  270
+ * Check if a class with the given type is loaded or can be loaded.
  271
+ *
  272
+ * @return boolean
  273
+ **/
  274
+	function isLoadableClass($type, $class) {
  275
+		return App::import($type, $class);
  276
+	}
  277
+
  278
+/**
  279
+ * Construct an instance of the class to be tested.
  280
+ * So that fixtures and methods can be detected
  281
+ *
  282
+ * @return object
  283
+ **/
  284
+	function &buildTestSubject($type, $class) {
  285
+		App::import($type, $class);
  286
+		$class = $this->getRealClassName($type, $class);
  287
+		if (strtolower($type) == 'model') {
  288
+			$instance =& ClassRegistry::init($class);
  289
+		} else {
  290
+			$instance =& new $class();
  291
+		}
  292
+		return $instance;
  293
+	}
  294
+
  295
+/**
  296
+ * Gets the real class name from the cake short form.
  297
+ *
  298
+ * @return string Real classname
  299
+ **/
  300
+	function getRealClassName($type, $class) {
  301
+		if (strtolower($type) == 'model') {
  302
+			return $class;
  303
+		}
  304
+		return $class . $type;
225 305
 	}
226 306
 
227 307
 /**
@@ -266,6 +346,7 @@ function generateFixtureList(&$subject) {
266 346
  * model names converting them to fixture names.
267 347
  *
268 348
  * @return void
  349
+ * @access protected
269 350
  **/
270 351
 	function _processModel(&$subject) {
271 352
 		$this->_addFixture($subject->name);
@@ -289,6 +370,7 @@ function _processModel(&$subject) {
289 370
  * and generate a fixture list.
290 371
  *
291 372
  * @return void
  373
+ * @access protected
292 374
  **/
293 375
 	function _processController(&$subject) {
294 376
 		$subject->constructClasses();
@@ -306,6 +388,7 @@ function _processController(&$subject) {
306 388
  * Sets the app. or plugin.plugin_name. prefix.
307 389
  *
308 390
  * @return void
  391
+ * @access protected
309 392
  **/
310 393
 	function _addFixture($name) {
311 394
 		$parent = get_parent_class($name);
@@ -319,6 +402,38 @@ function _addFixture($name) {
319 402
 	}
320 403
 
321 404
 /**
  405
+ * Interact with the user to get additional fixtures they want to use.
  406
+ *
  407
+ * @return void
  408
+ **/
  409
+	function getUserFixtures() {
  410
+		$proceed = $this->in(__('Bake could not detect fixtures, would you like to add some?', true), array('y','n'), 'n');
  411
+		$fixtures = array();
  412
+		if (strtolower($proceed) == 'y') {
  413
+			$fixtureList = $this->in(__("Please provide a comma separated list of the fixtures names you'd like to use.\nExample: 'app.comment, app.post, plugin.forums.post'", true));
  414
+			$fixtureListTrimmed = str_replace(' ', '', $fixtureList);
  415
+			$fixtures = explode(',', $fixtureListTrimmed);
  416
+		}
  417
+		$this->_fixtures = array_merge($this->_fixtures, $fixtures);
  418
+		return $fixtures;
  419
+	}
  420
+
  421
+/**
  422
+ * Handles the extra stuff needed
  423
+ *
  424
+ * @access private
  425
+ */
  426
+	function __extras($class) {
  427
+		$extras = null;
  428
+		switch ($class) {
  429
+			case 'Model':
  430
+				$extras = "\n\tvar \$cacheSources = false;";
  431
+				$extras .= "\n\tvar \$useDbConfig = 'test_suite';\n";
  432
+			break;
  433
+		}
  434
+		return $extras;
  435
+	}
  436
+/**
322 437
  * Create a test for a Model object.
323 438
  *
324 439
  * @return void
15  cake/console/libs/templates/objects/test.ctp
@@ -20,7 +20,18 @@
20 20
  */
21 21
 echo "<?php\n";
22 22
 ?>
23  
-class <?php echo $name; ?>TestCase extends CakeTestCase {
24  
-	
  23
+App::import('<?php echo $type; ?>', '<?php echo $className;?>');
  24
+
  25
+class <?php echo $className; ?>TestCase extends CakeTestCase {
  26
+<?php if (!empty($fixtures)): ?>
  27
+	var $fixtures = array('<?php echo join("', '", $fixtures); ?>');
  28
+
  29
+<?php endif; ?>
  30
+<?php foreach ($methods as $method): ?>
  31
+	function test<?php echo Inflector::classify($method); ?>() {
  32
+		
  33
+	}
  34
+
  35
+<?php endforeach;?>
25 36
 }
26 37
 <?php echo '?>'; ?>
109  cake/tests/cases/console/libs/tasks/test.test.php
@@ -40,6 +40,7 @@
40 40
 
41 41
 if (!class_exists('TestTask')) {
42 42
 	require CAKE . 'console' .  DS . 'libs' . DS . 'tasks' . DS . 'test.php';
  43
+	require CAKE . 'console' .  DS . 'libs' . DS . 'tasks' . DS . 'template.php';
43 44
 }
44 45
 
45 46
 Mock::generatePartial(
@@ -48,20 +49,10 @@
48 49
 );
49 50
 Mock::generatePartial(
50 51
 	'TestTask', 'MockTestTask',
51  
-	array('in', '_stop', 'err', 'out', 'createFile')
  52
+	array('in', '_stop', 'err', 'out', 'createFile', 'isLoadableClass')
52 53
 );
53 54
 
54 55
 /**
55  
- * Test subject for method extraction
56  
- *
57  
- **/
58  
-class TestTaskSubjectClass extends Object {
59  
-	function methodOne() { }
60  
-	function methodTwo() { }
61  
-	function _noTest() { }
62  
-}
63  
-
64  
-/**
65 56
  * Test subject models for fixture generation
66 57
  **/
67 58
 class TestTaskArticle extends Model {
@@ -81,6 +72,15 @@ class TestTaskArticle extends Model {
81 72
 			'associationForeignKey' => 'tag_id'
82 73
 		)
83 74
 	);
  75
+	function doSomething() {
  76
+
  77
+	}
  78
+	function doSomethingElse() {
  79
+
  80
+	}
  81
+	function _innerMethod() {
  82
+
  83
+	}
84 84
 }
85 85
 class TestTaskTag extends Model {
86 86
 	var $name = 'TestTaskTag';
@@ -131,10 +131,12 @@ class TestTaskTest extends CakeTestCase {
131 131
  * @return void
132 132
  * @access public
133 133
  */
134  
-	function setUp() {
  134
+	function startTest() {
135 135
 		$this->Dispatcher =& new TestTestTaskMockShellDispatcher();
  136
+		$this->Dispatcher->shellPaths = Configure::read('shellPaths');
136 137
 		$this->Task =& new MockTestTask($this->Dispatcher);
137  
-		$this->Task->Dispatch = new $this->Dispatcher;
  138
+		$this->Task->Dispatch =& $this->Dispatcher;
  139
+		$this->Task->Template =& new TemplateTask($this->Dispatcher);
138 140
 	}
139 141
 
140 142
 /**
@@ -143,7 +145,7 @@ function setUp() {
143 145
  * @return void
144 146
  * @access public
145 147
  */
146  
-	function tearDown() {
  148
+	function endTest() {
147 149
 		ClassRegistry::flush();
148 150
 	}
149 151
 
@@ -175,8 +177,8 @@ function testFilePathGeneration () {
175 177
  * @return void
176 178
  **/
177 179
 	function testMethodIntrospection() {
178  
-		$result = $this->Task->getTestableMethods('TestTaskSubjectClass');
179  
-		$expected = array('methodOne', 'methodTwo');
  180
+		$result = $this->Task->getTestableMethods('TestTaskArticle');
  181
+		$expected = array('doSomething', 'doSomethingElse');
180 182
 		$this->assertEqual($result, $expected);
181 183
 	}
182 184
 
@@ -220,7 +222,80 @@ function testGetObjectType() {
220 222
 
221 223
 		$this->Task->setReturnValueAt(1, 'in', 2);
222 224
 		$result = $this->Task->getObjectType();
223  
-		$this->assertEqual($result, 2);
  225
+		$this->assertEqual($result, $this->Task->classTypes[1]);
  226
+	}
  227
+
  228
+/**
  229
+ * test that getClassName returns the user choice as a classname.
  230
+ *
  231
+ * @return void
  232
+ **/
  233
+	function testGetClassName() {
  234
+		$this->Task->setReturnValueAt(0, 'in', 'MyCustomClass');
  235
+		$result = $this->Task->getClassName('Model');
  236
+		$this->assertEqual($result, 'MyCustomClass');
  237
+
  238
+		$this->Task->setReturnValueAt(1, 'in', 1);
  239
+		$result = $this->Task->getClassName('Model');
  240
+		$options = Configure::listObjects('model');
  241
+		$this->assertEqual($result, $options[0]);
  242
+	}
  243
+
  244
+/**
  245
+ * Test the user interaction for defining additional fixtures.
  246
+ *
  247
+ * @return void
  248
+ **/
  249
+	function testGetUserFixtures() {
  250
+		$this->Task->setReturnValueAt(0, 'in', 'y');
  251
+		$this->Task->setReturnValueAt(1, 'in', 'app.pizza, app.topping, app.side_dish');
  252
+		$result = $this->Task->getUserFixtures();
  253
+		$expected = array('app.pizza', 'app.topping', 'app.side_dish');
  254
+		$this->assertEqual($result, $expected);
  255
+	}
  256
+
  257
+/**
  258
+ * test that resolving classnames works
  259
+ *
  260
+ * @return void
  261
+ **/
  262
+	function testGetRealClassname() {
  263
+		$result = $this->Task->getRealClassname('Model', 'Post');
  264
+		$this->assertEqual($result, 'Post');
  265
+
  266
+		$result = $this->Task->getRealClassname('Controller', 'Posts');
  267
+		$this->assertEqual($result, 'PostsController');
  268
+
  269
+		$result = $this->Task->getRealClassname('Helper', 'Form');
  270
+		$this->assertEqual($result, 'FormHelper');
  271
+
  272
+		$result = $this->Task->getRealClassname('Behavior', 'Containable');
  273
+		$this->assertEqual($result, 'ContainableBehavior');
  274
+
  275
+		$result = $this->Task->getRealClassname('Component', 'Auth');
  276
+		$this->assertEqual($result, 'AuthComponent');
  277
+	}
  278
+
  279
+/**
  280
+ * test baking files.
  281
+ *
  282
+ * @return void
  283
+ **/
  284
+	function testBake() {
  285
+		$this->Task->setReturnValue('createFile', true);
  286
+		$this->Task->setReturnValue('isLoadableClass', true);
  287
+
  288
+		$result = $this->Task->bake('Model', 'TestTaskArticle');
  289
+
  290
+		$this->assertPattern('/App::import\(\'Model\', \'TestTaskArticle\'\)/', $result);
  291
+		$this->assertPattern('/class TestTaskArticleTestCase extends CakeTestCase/', $result);
  292
+		$this->assertPattern('/function testDoSomething\(\)/', $result);
  293
+		$this->assertPattern('/function testDoSomethingElse\(\)/', $result);
  294
+
  295
+		$this->assertPattern("/'app\.test_task_article'/", $result);
  296
+		$this->assertPattern("/'plugin\.test_task\.test_task_comment'/", $result);
  297
+		$this->assertPattern("/'app\.test_task_tag'/", $result);
  298
+		$this->assertPattern("/'app\.articles_tag'/", $result);
224 299
 	}
225 300
 }
226 301
 ?>

0 notes on commit 587b0ca

Please sign in to comment.
Something went wrong with that request. Please try again.