Initial commit

This commit is contained in:
mareksebera 2014-09-10 20:20:58 +02:00
commit 3b93da31de
1004 changed files with 265840 additions and 0 deletions

View file

@ -0,0 +1,47 @@
<?php
/**
* AllConsoleLibsTest file
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Console
* @since CakePHP(tm) v 2.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
* AllConsoleLibsTest class
*
* This test group will run all console lib classes.
*
* @package Cake.Test.Case.Console
*/
class AllConsoleLibsTest extends PHPUnit_Framework_TestSuite {
/**
* suite method, defines tests for this suite.
*
* @return void
*/
public static function suite() {
$suite = new CakeTestSuite('All console lib classes');
foreach (new DirectoryIterator(dirname(__FILE__)) as $file) {
if (!$file->isFile() || strpos($file, 'All') === 0) {
continue;
}
$fileName = $file->getRealPath();
if (substr($fileName, -4) === '.php') {
$suite->addTestFile($file->getRealPath());
}
}
return $suite;
}
}

View file

@ -0,0 +1,43 @@
<?php
/**
* AllConsoleTest file
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Console
* @since CakePHP(tm) v 2.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
* AllConsoleTest class
*
* This test group will run all console classes.
*
* @package Cake.Test.Case.Console
*/
class AllConsoleTest extends PHPUnit_Framework_TestSuite {
/**
* suite method, defines tests for this suite.
*
* @return void
*/
public static function suite() {
$suite = new CakeTestSuite('All console classes');
$path = CORE_TEST_CASES . DS . 'Console' . DS;
$suite->addTestFile($path . 'AllConsoleLibsTest.php');
$suite->addTestFile($path . 'AllTasksTest.php');
$suite->addTestFile($path . 'AllShellsTest.php');
return $suite;
}
}

View file

@ -0,0 +1,41 @@
<?php
/**
* AllShellsTest file
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Console
* @since CakePHP(tm) v 2.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
* AllShellsTest class
*
* This test group will run all top level shell classes.
*
* @package Cake.Test.Case.Console
*/
class AllShellsTest extends PHPUnit_Framework_TestSuite {
/**
* suite method, defines tests for this suite.
*
* @return void
*/
public static function suite() {
$suite = new CakeTestSuite('All shell classes');
$path = CORE_TEST_CASES . DS . 'Console' . DS . 'Command' . DS;
$suite->addTestDirectory($path);
return $suite;
}
}

View file

@ -0,0 +1,40 @@
<?php
/**
* AllTasksTest file
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Console
* @since CakePHP(tm) v 2.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
* AllTasksTest class
*
* This test group will run all the task tests.
*
* @package Cake.Test.Case.Console
*/
class AllTasksTest extends PHPUnit_Framework_TestSuite {
/**
* suite method, defines tests for this suite.
*
* @return void
*/
public static function suite() {
$suite = new CakeTestSuite('All Tasks tests');
$path = CORE_TEST_CASES . DS . 'Console' . DS . 'Command' . DS . 'Task' . DS;
$suite->addTestDirectory($path);
return $suite;
}
}

View file

@ -0,0 +1,311 @@
<?php
/**
* AclShell Test file
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.Console.Command
* @since CakePHP v 1.2.0.7726
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ConsoleOutput', 'Console');
App::uses('ConsoleInput', 'Console');
App::uses('ShellDispatcher', 'Console');
App::uses('Shell', 'Console');
App::uses('AclShell', 'Console/Command');
App::uses('ComponentCollection', 'Controller');
/**
* AclShellTest class
*
* @package Cake.Test.Case.Console.Command
*/
class AclShellTest extends CakeTestCase {
/**
* Fixtures
*
* @var array
*/
public $fixtures = array('core.aco', 'core.aro', 'core.aros_aco');
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
Configure::write('Acl.database', 'test');
Configure::write('Acl.classname', 'DbAcl');
$out = $this->getMock('ConsoleOutput', array(), array(), '', false);
$in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->Task = $this->getMock(
'AclShell',
array('in', 'out', 'hr', 'createFile', 'error', 'err', 'clear', 'dispatchShell'),
array($out, $out, $in)
);
$collection = new ComponentCollection();
$this->Task->Acl = new AclComponent($collection);
$this->Task->params['datasource'] = 'test';
}
/**
* test that model.foreign_key output works when looking at acl rows
*
* @return void
*/
public function testViewWithModelForeignKeyOutput() {
$this->Task->command = 'view';
$this->Task->startup();
$data = array(
'parent_id' => null,
'model' => 'MyModel',
'foreign_key' => 2,
);
$this->Task->Acl->Aro->create($data);
$this->Task->Acl->Aro->save();
$this->Task->args[0] = 'aro';
$this->Task->expects($this->at(0))->method('out')->with('Aro tree:');
$this->Task->expects($this->at(2))->method('out')
->with($this->stringContains('[1] ROOT'));
$this->Task->expects($this->at(4))->method('out')
->with($this->stringContains('[3] Gandalf'));
$this->Task->expects($this->at(6))->method('out')
->with($this->stringContains('[5] MyModel.2'));
$this->Task->view();
}
/**
* test view with an argument
*
* @return void
*/
public function testViewWithArgument() {
$this->Task->args = array('aro', 'admins');
$this->Task->expects($this->at(0))->method('out')->with('Aro tree:');
$this->Task->expects($this->at(2))->method('out')->with(' [2] admins');
$this->Task->expects($this->at(3))->method('out')->with(' [3] Gandalf');
$this->Task->expects($this->at(4))->method('out')->with(' [4] Elrond');
$this->Task->view();
}
/**
* test the method that splits model.foreign key. and that it returns an array.
*
* @return void
*/
public function testParsingModelAndForeignKey() {
$result = $this->Task->parseIdentifier('Model.foreignKey');
$expected = array('model' => 'Model', 'foreign_key' => 'foreignKey');
$this->assertEquals($expected, $result);
$result = $this->Task->parseIdentifier('mySuperUser');
$this->assertEquals('mySuperUser', $result);
$result = $this->Task->parseIdentifier('111234');
$this->assertEquals('111234', $result);
}
/**
* test creating aro/aco nodes
*
* @return void
*/
public function testCreate() {
$this->Task->args = array('aro', 'root', 'User.1');
$this->Task->expects($this->at(0))->method('out')->with("<success>New Aro</success> 'User.1' created.", 2);
$this->Task->expects($this->at(1))->method('out')->with("<success>New Aro</success> 'User.3' created.", 2);
$this->Task->expects($this->at(2))->method('out')->with("<success>New Aro</success> 'somealias' created.", 2);
$this->Task->create();
$Aro = ClassRegistry::init('Aro');
$Aro->cacheQueries = false;
$result = $Aro->read();
$this->assertEquals('User', $result['Aro']['model']);
$this->assertEquals(1, $result['Aro']['foreign_key']);
$this->assertEquals(null, $result['Aro']['parent_id']);
$id = $result['Aro']['id'];
$this->Task->args = array('aro', 'User.1', 'User.3');
$this->Task->create();
$Aro = ClassRegistry::init('Aro');
$result = $Aro->read();
$this->assertEquals('User', $result['Aro']['model']);
$this->assertEquals(3, $result['Aro']['foreign_key']);
$this->assertEquals($id, $result['Aro']['parent_id']);
$this->Task->args = array('aro', 'root', 'somealias');
$this->Task->create();
$Aro = ClassRegistry::init('Aro');
$result = $Aro->read();
$this->assertEquals('somealias', $result['Aro']['alias']);
$this->assertEquals(null, $result['Aro']['model']);
$this->assertEquals(null, $result['Aro']['foreign_key']);
$this->assertEquals(null, $result['Aro']['parent_id']);
}
/**
* test the delete method with different node types.
*
* @return void
*/
public function testDelete() {
$this->Task->args = array('aro', 'AuthUser.1');
$this->Task->expects($this->at(0))->method('out')
->with("<success>Aro deleted.</success>", 2);
$this->Task->delete();
$Aro = ClassRegistry::init('Aro');
$result = $Aro->findById(3);
$this->assertSame(array(), $result);
}
/**
* test setParent method.
*
* @return void
*/
public function testSetParent() {
$this->Task->args = array('aro', 'AuthUser.2', 'root');
$this->Task->setParent();
$Aro = ClassRegistry::init('Aro');
$result = $Aro->read(null, 4);
$this->assertEquals(null, $result['Aro']['parent_id']);
}
/**
* test grant
*
* @return void
*/
public function testGrant() {
$this->Task->args = array('AuthUser.2', 'ROOT/Controller1', 'create');
$this->Task->expects($this->at(0))->method('out')
->with($this->matchesRegularExpression('/granted/'), true);
$this->Task->grant();
$node = $this->Task->Acl->Aro->node(array('model' => 'AuthUser', 'foreign_key' => 2));
$node = $this->Task->Acl->Aro->read(null, $node[0]['Aro']['id']);
$this->assertFalse(empty($node['Aco'][0]));
$this->assertEquals(1, $node['Aco'][0]['Permission']['_create']);
}
/**
* test deny
*
* @return void
*/
public function testDeny() {
$this->Task->args = array('AuthUser.2', 'ROOT/Controller1', 'create');
$this->Task->expects($this->at(0))->method('out')
->with($this->stringContains('Permission denied'), true);
$this->Task->deny();
$node = $this->Task->Acl->Aro->node(array('model' => 'AuthUser', 'foreign_key' => 2));
$node = $this->Task->Acl->Aro->read(null, $node[0]['Aro']['id']);
$this->assertFalse(empty($node['Aco'][0]));
$this->assertEquals(-1, $node['Aco'][0]['Permission']['_create']);
}
/**
* test checking allowed and denied perms
*
* @return void
*/
public function testCheck() {
$this->Task->expects($this->at(0))->method('out')
->with($this->matchesRegularExpression('/not allowed/'), true);
$this->Task->expects($this->at(1))->method('out')
->with($this->matchesRegularExpression('/granted/'), true);
$this->Task->expects($this->at(2))->method('out')
->with($this->matchesRegularExpression('/is.*allowed/'), true);
$this->Task->expects($this->at(3))->method('out')
->with($this->matchesRegularExpression('/not.*allowed/'), true);
$this->Task->args = array('AuthUser.2', 'ROOT/Controller1', '*');
$this->Task->check();
$this->Task->args = array('AuthUser.2', 'ROOT/Controller1', 'create');
$this->Task->grant();
$this->Task->args = array('AuthUser.2', 'ROOT/Controller1', 'create');
$this->Task->check();
$this->Task->args = array('AuthUser.2', 'ROOT/Controller1', '*');
$this->Task->check();
}
/**
* test inherit and that it 0's the permission fields.
*
* @return void
*/
public function testInherit() {
$this->Task->expects($this->at(0))->method('out')
->with($this->matchesRegularExpression('/Permission .*granted/'), true);
$this->Task->expects($this->at(1))->method('out')
->with($this->matchesRegularExpression('/Permission .*inherited/'), true);
$this->Task->args = array('AuthUser.2', 'ROOT/Controller1', 'create');
$this->Task->grant();
$this->Task->args = array('AuthUser.2', 'ROOT/Controller1', 'all');
$this->Task->inherit();
$node = $this->Task->Acl->Aro->node(array('model' => 'AuthUser', 'foreign_key' => 2));
$node = $this->Task->Acl->Aro->read(null, $node[0]['Aro']['id']);
$this->assertFalse(empty($node['Aco'][0]));
$this->assertEquals(0, $node['Aco'][0]['Permission']['_create']);
}
/**
* test getting the path for an aro/aco
*
* @return void
*/
public function testGetPath() {
$this->Task->args = array('aro', 'AuthUser.2');
$node = $this->Task->Acl->Aro->node(array('model' => 'AuthUser', 'foreign_key' => 2));
$first = $node[0]['Aro']['id'];
$second = $node[1]['Aro']['id'];
$last = $node[2]['Aro']['id'];
$this->Task->expects($this->at(2))->method('out')->with('[' . $last . '] ROOT');
$this->Task->expects($this->at(3))->method('out')->with(' [' . $second . '] admins');
$this->Task->expects($this->at(4))->method('out')->with(' [' . $first . '] Elrond');
$this->Task->getPath();
}
/**
* test that initdb makes the correct call.
*
* @return void
*/
public function testInitDb() {
$this->Task->expects($this->once())->method('dispatchShell')
->with('schema create DbAcl');
$this->Task->initdb();
}
}

View file

@ -0,0 +1,95 @@
<?php
/**
* ApiShellTest file
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.Console.Command
* @since CakePHP v 1.2.0.7726
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ConsoleOutput', 'Console');
App::uses('ConsoleInput', 'Console');
App::uses('ShellDispatcher', 'Console');
App::uses('Shell', 'Console');
App::uses('ApiShell', 'Console/Command');
/**
* ApiShellTest class
*
* @package Cake.Test.Case.Console.Command
*/
class ApiShellTest extends CakeTestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$out = $this->getMock('ConsoleOutput', array(), array(), '', false);
$in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->Shell = $this->getMock(
'ApiShell',
array('in', 'out', 'createFile', 'hr', '_stop'),
array($out, $out, $in)
);
}
/**
* Test that method names are detected properly including those with no arguments.
*
* @return void
*/
public function testMethodNameDetection() {
$this->Shell->expects($this->any())->method('in')->will($this->returnValue('q'));
$this->Shell->expects($this->at(0))->method('out')->with('Controller');
$expected = array(
'1. afterFilter()',
'2. afterScaffoldSave($method)',
'3. afterScaffoldSaveError($method)',
'4. beforeFilter()',
'5. beforeRedirect($url, $status = NULL, $exit = true)',
'6. beforeRender()',
'7. beforeScaffold($method)',
'8. constructClasses()',
'9. disableCache()',
'10. flash($message, $url, $pause = 1, $layout = \'flash\')',
'11. getEventManager()',
'12. header($status)',
'13. httpCodes($code = NULL)',
'14. implementedEvents()',
'15. invokeAction($request)',
'16. loadModel($modelClass = NULL, $id = NULL)',
'17. paginate($object = NULL, $scope = array (), $whitelist = array ())',
'18. postConditions($data = array (), $op = NULL, $bool = \'AND\', $exclusive = false)',
'19. redirect($url, $status = NULL, $exit = true)',
'20. referer($default = NULL, $local = false)',
'21. render($view = NULL, $layout = NULL)',
'22. scaffoldError($method)',
'23. set($one, $two = NULL)',
'24. setAction($action)',
'25. setRequest($request)',
'26. shutdownProcess()',
'27. startupProcess()',
'28. validate()',
'29. validateErrors()'
);
$this->Shell->expects($this->at(2))->method('out')->with($expected);
$this->Shell->args = array('controller');
$this->Shell->paths['controller'] = CAKE . 'Controller' . DS;
$this->Shell->main();
}
}

View file

@ -0,0 +1,119 @@
<?php
/**
* BakeShell Test Case
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Console.Command
* @since CakePHP(tm) v 1.3
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ConsoleOutput', 'Console');
App::uses('ConsoleInput', 'Console');
App::uses('ShellDispatcher', 'Console');
App::uses('Shell', 'Console');
App::uses('BakeShell', 'Console/Command');
App::uses('ModelTask', 'Console/Command/Task');
App::uses('ControllerTask', 'Console/Command/Task');
App::uses('DbConfigTask', 'Console/Command/Task');
App::uses('Controller', 'Controller');
if (!class_exists('UsersController')) {
class UsersController extends Controller {
}
}
class BakeShellTest extends CakeTestCase {
/**
* fixtures
*
* @var array
*/
public $fixtures = array('core.user');
/**
* setup test
*
* @return void
*/
public function setUp() {
parent::setUp();
$out = $this->getMock('ConsoleOutput', array(), array(), '', false);
$in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->Shell = $this->getMock(
'BakeShell',
array('in', 'out', 'hr', 'err', 'createFile', '_stop', '_checkUnitTest'),
array($out, $out, $in)
);
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->Dispatch, $this->Shell);
}
/**
* test bake all
*
* @return void
*/
public function testAllWithModelName() {
App::uses('User', 'Model');
$userExists = class_exists('User');
$this->skipIf($userExists, 'User class exists, cannot test `bake all [param]`.');
$this->Shell->Model = $this->getMock('ModelTask', array(), array(&$this->Dispatcher));
$this->Shell->Controller = $this->getMock('ControllerTask', array(), array(&$this->Dispatcher));
$this->Shell->View = $this->getMock('ModelTask', array(), array(&$this->Dispatcher));
$this->Shell->DbConfig = $this->getMock('DbConfigTask', array(), array(&$this->Dispatcher));
$this->Shell->DbConfig->expects($this->once())
->method('getConfig')
->will($this->returnValue('test'));
$this->Shell->Model->expects($this->never())
->method('getName');
$this->Shell->Model->expects($this->once())
->method('bake')
->will($this->returnValue(true));
$this->Shell->Controller->expects($this->once())
->method('bake')
->will($this->returnValue(true));
$this->Shell->View->expects($this->once())
->method('execute');
$this->Shell->expects($this->once())->method('_stop');
$this->Shell->expects($this->at(0))
->method('out')
->with('Bake All');
$this->Shell->expects($this->at(5))
->method('out')
->with('<success>Bake All complete</success>');
$this->Shell->connection = '';
$this->Shell->params = array();
$this->Shell->args = array('User');
$this->Shell->all();
$this->assertEquals('User', $this->Shell->View->args[0]);
}
}

View file

@ -0,0 +1,133 @@
<?php
/**
* CommandListShellTest file
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.Console.Command
* @since CakePHP v 2.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('CommandListShell', 'Console/Command');
App::uses('ConsoleOutput', 'Console');
App::uses('ConsoleInput', 'Console');
App::uses('Shell', 'Console');
App::uses('CommandTask', 'Console/Command/Task');
/**
* Class TestStringOutput
*
* @package Cake.Test.Case.Console.Command
*/
class TestStringOutput extends ConsoleOutput {
public $output = '';
protected function _write($message) {
$this->output .= $message;
}
}
/**
* Class CommandListShellTest
*
* @package Cake.Test.Case.Console.Command
*/
class CommandListShellTest extends CakeTestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
App::build(array(
'Plugin' => array(
CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS
),
'Console/Command' => array(
CAKE . 'Test' . DS . 'test_app' . DS . 'Console' . DS . 'Command' . DS
)
), App::RESET);
CakePlugin::load(array('TestPlugin', 'TestPluginTwo'));
$out = new TestStringOutput();
$in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->Shell = $this->getMock(
'CommandListShell',
array('in', '_stop', 'clear'),
array($out, $out, $in)
);
$this->Shell->Command = $this->getMock(
'CommandTask',
array('in', '_stop', 'clear'),
array($out, $out, $in)
);
}
/**
* tearDown
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->Shell);
CakePlugin::unload();
}
/**
* test that main finds core shells.
*
* @return void
*/
public function testMain() {
$this->Shell->main();
$output = $this->Shell->stdout->output;
$expected = "/\[.*TestPlugin.*\] example/";
$this->assertRegExp($expected, $output);
$expected = "/\[.*TestPluginTwo.*\] example, welcome/";
$this->assertRegExp($expected, $output);
$expected = "/\[.*CORE.*\] acl, api, bake, command_list, completion, console, i18n, schema, server, test, testsuite, upgrade/";
$this->assertRegExp($expected, $output);
$expected = "/\[.*app.*\] sample/";
$this->assertRegExp($expected, $output);
}
/**
* test xml output.
*
* @return void
*/
public function testMainXml() {
$this->Shell->params['xml'] = true;
$this->Shell->main();
$output = $this->Shell->stdout->output;
$find = '<shell name="sample" call_as="sample" provider="app" help="sample -h"/>';
$this->assertContains($find, $output);
$find = '<shell name="bake" call_as="bake" provider="CORE" help="bake -h"/>';
$this->assertContains($find, $output);
$find = '<shell name="welcome" call_as="TestPluginTwo.welcome" provider="TestPluginTwo" help="TestPluginTwo.welcome -h"/>';
$this->assertContains($find, $output);
}
}

View file

@ -0,0 +1,261 @@
<?php
/**
* CompletionShellTest file
*
* PHP 5
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.Console.Command
* @since CakePHP v 2.5
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('CompletionShell', 'Console/Command');
App::uses('ConsoleOutput', 'Console');
App::uses('ConsoleInput', 'Console');
App::uses('Shell', 'Console');
App::uses('CommandTask', 'Console/Command/Task');
/**
* Class TestCompletionStringOutput
*
* @package Cake.Test.Case.Console.Command
*/
class TestCompletionStringOutput extends ConsoleOutput {
public $output = '';
protected function _write($message) {
$this->output .= $message;
}
}
/**
* Class CompletionShellTest
*
* @package Cake.Test.Case.Console.Command
*/
class CompletionShellTest extends CakeTestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
App::build(array(
'Plugin' => array(
CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS
),
'Console/Command' => array(
CAKE . 'Test' . DS . 'test_app' . DS . 'Console' . DS . 'Command' . DS
)
), App::RESET);
CakePlugin::load(array('TestPlugin', 'TestPluginTwo'));
$out = new TestCompletionStringOutput();
$in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->Shell = $this->getMock(
'CompletionShell',
array('in', '_stop', 'clear'),
array($out, $out, $in)
);
$this->Shell->Command = $this->getMock(
'CommandTask',
array('in', '_stop', 'clear'),
array($out, $out, $in)
);
}
/**
* tearDown
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->Shell);
CakePlugin::unload();
}
/**
* test that the startup method supresses the shell header
*
* @return void
*/
public function testStartup() {
$this->Shell->runCommand('main', array());
$output = $this->Shell->stdout->output;
$needle = 'Welcome to CakePHP';
$this->assertTextNotContains($needle, $output);
}
/**
* test that main displays a warning
*
* @return void
*/
public function testMain() {
$this->Shell->runCommand('main', array());
$output = $this->Shell->stdout->output;
$expected = "/This command is not intended to be called manually/";
$this->assertRegExp($expected, $output);
}
/**
* test commands method that list all available commands
*
* @return void
*/
public function testCommands() {
$this->Shell->runCommand('commands', array());
$output = $this->Shell->stdout->output;
$expected = "TestPlugin.example TestPluginTwo.example TestPluginTwo.welcome acl api bake command_list completion console i18n schema server test testsuite upgrade sample\n";
$this->assertEquals($expected, $output);
}
/**
* test that options without argument returns the default options
*
* @return void
*/
public function testOptionsNoArguments() {
$this->Shell->runCommand('options', array());
$output = $this->Shell->stdout->output;
$expected = "--help -h --verbose -v --quiet -q\n";
$this->assertEquals($expected, $output);
}
/**
* test that options with a nonexisting command returns the default options
*
* @return void
*/
public function testOptionsNonExistingCommand() {
$this->Shell->runCommand('options', array('options', 'foo'));
$output = $this->Shell->stdout->output;
$expected = "--help -h --verbose -v --quiet -q\n";
$this->assertEquals($expected, $output);
}
/**
* test that options with a existing command returns the proper options
*
* @return void
*/
public function testOptions() {
$this->Shell->runCommand('options', array('options', 'bake'));
$output = $this->Shell->stdout->output;
$expected = "--help -h --verbose -v --quiet -q --connection -c --theme -t\n";
$this->assertEquals($expected, $output);
}
/**
* test that subCommands with a existing CORE command returns the proper sub commands
*
* @return void
*/
public function testSubCommandsCorePlugin() {
$this->Shell->runCommand('subCommands', array('subCommands', 'CORE.bake'));
$output = $this->Shell->stdout->output;
$expected = "controller db_config fixture model plugin project test view\n";
$this->assertEquals($expected, $output);
}
/**
* test that subCommands with a existing APP command returns the proper sub commands (in this case none)
*
* @return void
*/
public function testSubCommandsAppPlugin() {
$this->Shell->runCommand('subCommands', array('subCommands', 'app.sample'));
$output = $this->Shell->stdout->output;
$expected = '';
$this->assertEquals($expected, $output);
}
/**
* test that subCommands with a existing plugin command returns the proper sub commands
*
* @return void
*/
public function testSubCommandsPlugin() {
$this->Shell->runCommand('subCommands', array('subCommands', 'TestPluginTwo.welcome'));
$output = $this->Shell->stdout->output;
$expected = "say_hello\n";
$this->assertEquals($expected, $output);
}
/**
* test that subcommands without arguments returns nothing
*
* @return void
*/
public function testSubCommandsNoArguments() {
$this->Shell->runCommand('subCommands', array());
$output = $this->Shell->stdout->output;
$expected = '';
$this->assertEquals($expected, $output);
}
/**
* test that subcommands with a nonexisting command returns nothing
*
* @return void
*/
public function testSubCommandsNonExistingCommand() {
$this->Shell->runCommand('subCommands', array('subCommands', 'foo'));
$output = $this->Shell->stdout->output;
$expected = '';
$this->assertEquals($expected, $output);
}
/**
* test that subcommands returns the available subcommands for the given command
*
* @return void
*/
public function testSubCommands() {
$this->Shell->runCommand('subCommands', array('subCommands', 'bake'));
$output = $this->Shell->stdout->output;
$expected = "controller db_config fixture model plugin project test view\n";
$this->assertEquals($expected, $output);
}
/**
* test that fuzzy returns nothing
*
* @return void
*/
public function testFuzzy() {
$this->Shell->runCommand('fuzzy', array());
$output = $this->Shell->stdout->output;
$expected = '';
$this->assertEquals($expected, $output);
}
}

View file

@ -0,0 +1,698 @@
<?php
/**
* SchemaShellTest Test file
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.Console.Command
* @since CakePHP v 1.3
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ShellDispatcher', 'Console');
App::uses('ConsoleOutput', 'Console');
App::uses('ConsoleInput', 'Console');
App::uses('Shell', 'Console');
App::uses('CakeSchema', 'Model');
App::uses('SchemaShell', 'Console/Command');
/**
* Test for Schema database management
*
* @package Cake.Test.Case.Console.Command
*/
class SchemaShellTestSchema extends CakeSchema {
/**
* connection property
*
* @var string
*/
public $connection = 'test';
/**
* comments property
*
* @var array
*/
public $comments = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'),
'post_id' => array('type' => 'integer', 'null' => false, 'default' => 0),
'user_id' => array('type' => 'integer', 'null' => false),
'title' => array('type' => 'string', 'null' => false, 'length' => 100),
'comment' => array('type' => 'text', 'null' => false, 'default' => null),
'published' => array('type' => 'string', 'null' => true, 'default' => 'N', 'length' => 1),
'created' => array('type' => 'datetime', 'null' => true, 'default' => null),
'updated' => array('type' => 'datetime', 'null' => true, 'default' => null),
'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)),
);
/**
* posts property
*
* @var array
*/
public $articles = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'),
'user_id' => array('type' => 'integer', 'null' => true, 'default' => ''),
'title' => array('type' => 'string', 'null' => false, 'default' => 'Title'),
'body' => array('type' => 'text', 'null' => true, 'default' => null),
'summary' => array('type' => 'text', 'null' => true),
'published' => array('type' => 'string', 'null' => true, 'default' => 'Y', 'length' => 1),
'created' => array('type' => 'datetime', 'null' => true, 'default' => null),
'updated' => array('type' => 'datetime', 'null' => true, 'default' => null),
'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)),
);
public $newone = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'),
'testit' => array('type' => 'string', 'null' => false, 'default' => 'Title'),
'created' => array('type' => 'datetime', 'null' => true, 'default' => null),
'updated' => array('type' => 'datetime', 'null' => true, 'default' => null),
'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)),
);
}
/**
* SchemaShellTest class
*
* @package Cake.Test.Case.Console.Command
*/
class SchemaShellTest extends CakeTestCase {
/**
* Fixtures
*
* @var array
*/
public $fixtures = array(
'core.article', 'core.user', 'core.post', 'core.auth_user', 'core.author',
'core.comment', 'core.test_plugin_comment', 'core.aco', 'core.aro', 'core.aros_aco',
);
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$out = $this->getMock('ConsoleOutput', array(), array(), '', false);
$in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->Shell = $this->getMock(
'SchemaShell',
array('in', 'out', 'hr', 'createFile', 'error', 'err', '_stop'),
array($out, $out, $in)
);
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
if (!empty($this->file) && $this->file instanceof File) {
$this->file->delete();
unset($this->file);
}
}
/**
* test startup method
*
* @return void
*/
public function testStartup() {
$this->Shell->startup();
$this->assertTrue(isset($this->Shell->Schema));
$this->assertInstanceOf('CakeSchema', $this->Shell->Schema);
$this->assertEquals(Inflector::camelize(Inflector::slug(APP_DIR)), $this->Shell->Schema->name);
$this->assertEquals('schema.php', $this->Shell->Schema->file);
$this->Shell->Schema = null;
$this->Shell->params = array(
'name' => 'TestSchema'
);
$this->Shell->startup();
$this->assertEquals('TestSchema', $this->Shell->Schema->name);
$this->assertEquals('test_schema.php', $this->Shell->Schema->file);
$this->assertEquals('default', $this->Shell->Schema->connection);
$this->assertEquals(APP . 'Config' . DS . 'Schema', $this->Shell->Schema->path);
$this->Shell->Schema = null;
$this->Shell->params = array(
'file' => 'other_file.php',
'connection' => 'test',
'path' => '/test/path'
);
$this->Shell->startup();
$this->assertEquals(Inflector::camelize(Inflector::slug(APP_DIR)), $this->Shell->Schema->name);
$this->assertEquals('other_file.php', $this->Shell->Schema->file);
$this->assertEquals('test', $this->Shell->Schema->connection);
$this->assertEquals('/test/path', $this->Shell->Schema->path);
}
/**
* Test View - and that it dumps the schema file to stdout
*
* @return void
*/
public function testView() {
$this->Shell->startup();
$this->Shell->Schema->path = APP . 'Config' . DS . 'Schema';
$this->Shell->params['file'] = 'i18n.php';
$this->Shell->expects($this->once())->method('_stop');
$this->Shell->expects($this->once())->method('out');
$this->Shell->view();
}
/**
* test that view() can find plugin schema files.
*
* @return void
*/
public function testViewWithPlugins() {
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
));
CakePlugin::load('TestPlugin');
$this->Shell->args = array('TestPlugin.schema');
$this->Shell->startup();
$this->Shell->expects($this->exactly(2))->method('_stop');
$this->Shell->expects($this->atLeastOnce())->method('out');
$this->Shell->view();
$this->Shell->args = array();
$this->Shell->params = array('plugin' => 'TestPlugin');
$this->Shell->startup();
$this->Shell->view();
App::build();
CakePlugin::unload();
}
/**
* test dump() with sql file generation
*
* @return void
*/
public function testDumpWithFileWriting() {
$this->Shell->params = array(
'name' => 'i18n',
'connection' => 'test',
'write' => TMP . 'tests' . DS . 'i18n.sql'
);
$this->Shell->expects($this->once())->method('_stop');
$this->Shell->startup();
$this->Shell->dump();
$this->file = new File(TMP . 'tests' . DS . 'i18n.sql');
$contents = $this->file->read();
$this->assertRegExp('/DROP TABLE/', $contents);
$this->assertRegExp('/CREATE TABLE.*?i18n/', $contents);
$this->assertRegExp('/id/', $contents);
$this->assertRegExp('/model/', $contents);
$this->assertRegExp('/field/', $contents);
$this->assertRegExp('/locale/', $contents);
$this->assertRegExp('/foreign_key/', $contents);
$this->assertRegExp('/content/', $contents);
}
/**
* test that dump() can find and work with plugin schema files.
*
* @return void
*/
public function testDumpFileWritingWithPlugins() {
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
));
CakePlugin::load('TestPlugin');
$this->Shell->args = array('TestPlugin.TestPluginApp');
$this->Shell->params = array(
'connection' => 'test',
'write' => TMP . 'tests' . DS . 'dump_test.sql'
);
$this->Shell->startup();
$this->Shell->expects($this->once())->method('_stop');
$this->Shell->dump();
$this->file = new File(TMP . 'tests' . DS . 'dump_test.sql');
$contents = $this->file->read();
$this->assertRegExp('/CREATE TABLE.*?test_plugin_acos/', $contents);
$this->assertRegExp('/id/', $contents);
$this->assertRegExp('/model/', $contents);
$this->file->delete();
App::build();
CakePlugin::unload();
}
/**
* test generate with snapshot generation
*
* @return void
*/
public function testGenerateSnapshot() {
$this->Shell->path = TMP;
$this->Shell->params['file'] = 'schema.php';
$this->Shell->params['force'] = false;
$this->Shell->args = array('snapshot');
$this->Shell->Schema = $this->getMock('CakeSchema');
$this->Shell->Schema->expects($this->at(0))->method('read')->will($this->returnValue(array('schema data')));
$this->Shell->Schema->expects($this->at(0))->method('write')->will($this->returnValue(true));
$this->Shell->Schema->expects($this->at(1))->method('read');
$this->Shell->Schema->expects($this->at(1))->method('write')->with(array('schema data', 'file' => 'schema_0.php'));
$this->Shell->generate();
}
/**
* test generate without a snapshot.
*
* @return void
*/
public function testGenerateNoOverwrite() {
touch(TMP . 'schema.php');
$this->Shell->params['file'] = 'schema.php';
$this->Shell->params['force'] = false;
$this->Shell->args = array();
$this->Shell->expects($this->once())->method('in')->will($this->returnValue('q'));
$this->Shell->Schema = $this->getMock('CakeSchema');
$this->Shell->Schema->path = TMP;
$this->Shell->Schema->expects($this->never())->method('read');
$this->Shell->generate();
unlink(TMP . 'schema.php');
}
/**
* test generate with overwriting of the schema files.
*
* @return void
*/
public function testGenerateOverwrite() {
touch(TMP . 'schema.php');
$this->Shell->params['file'] = 'schema.php';
$this->Shell->params['force'] = false;
$this->Shell->args = array();
$this->Shell->expects($this->once())->method('in')->will($this->returnValue('o'));
$this->Shell->expects($this->at(2))->method('out')
->with(new PHPUnit_Framework_Constraint_PCREMatch('/Schema file:\s[a-z\.]+\sgenerated/'));
$this->Shell->Schema = $this->getMock('CakeSchema');
$this->Shell->Schema->path = TMP;
$this->Shell->Schema->expects($this->once())->method('read')->will($this->returnValue(array('schema data')));
$this->Shell->Schema->expects($this->once())->method('write')->will($this->returnValue(true));
$this->Shell->Schema->expects($this->once())->method('read');
$this->Shell->Schema->expects($this->once())->method('write')
->with(array('schema data', 'file' => 'schema.php'));
$this->Shell->generate();
unlink(TMP . 'schema.php');
}
/**
* test that generate() can read plugin dirs and generate schema files for the models
* in a plugin.
*
* @return void
*/
public function testGenerateWithPlugins() {
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
), App::RESET);
CakePlugin::load('TestPlugin');
$this->db->cacheSources = false;
$this->Shell->params = array(
'plugin' => 'TestPlugin',
'connection' => 'test',
'force' => false
);
$this->Shell->startup();
$this->Shell->Schema->path = TMP . 'tests' . DS;
$this->Shell->generate();
$this->file = new File(TMP . 'tests' . DS . 'schema.php');
$contents = $this->file->read();
$this->assertRegExp('/class TestPluginSchema/', $contents);
$this->assertRegExp('/public \$posts/', $contents);
$this->assertRegExp('/public \$auth_users/', $contents);
$this->assertRegExp('/public \$authors/', $contents);
$this->assertRegExp('/public \$test_plugin_comments/', $contents);
$this->assertNotRegExp('/public \$users/', $contents);
$this->assertNotRegExp('/public \$articles/', $contents);
CakePlugin::unload();
}
/**
* test generate with specific models
*
* @return void
*/
public function testGenerateModels() {
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
), App::RESET);
CakePlugin::load('TestPlugin');
$this->db->cacheSources = false;
$this->Shell->params = array(
'plugin' => 'TestPlugin',
'connection' => 'test',
'models' => 'TestPluginComment',
'force' => false,
'overwrite' => true
);
$this->Shell->startup();
$this->Shell->Schema->path = TMP . 'tests' . DS;
$this->Shell->generate();
$this->file = new File(TMP . 'tests' . DS . 'schema.php');
$contents = $this->file->read();
$this->assertRegExp('/class TestPluginSchema/', $contents);
$this->assertRegExp('/public \$test_plugin_comments/', $contents);
$this->assertNotRegExp('/public \$authors/', $contents);
$this->assertNotRegExp('/public \$auth_users/', $contents);
$this->assertNotRegExp('/public \$posts/', $contents);
CakePlugin::unload();
}
/**
* test generate with excluded tables
*
* @return void
*/
public function testGenerateExclude() {
Configure::write('Acl.database', 'test');
$this->db->cacheSources = false;
$this->Shell->params = array(
'connection' => 'test',
'force' => false,
'models' => 'Aro, Aco, Permission',
'overwrite' => true,
'exclude' => 'acos, aros',
);
$this->Shell->startup();
$this->Shell->Schema->path = TMP . 'tests' . DS;
$this->Shell->generate();
$this->file = new File(TMP . 'tests' . DS . 'schema.php');
$contents = $this->file->read();
$this->assertNotContains('public $acos = array(', $contents);
$this->assertNotContains('public $aros = array(', $contents);
$this->assertContains('public $aros_acos = array(', $contents);
}
/**
* Test schema run create with --yes option
*
* @return void
*/
public function testCreateOptionYes() {
$this->Shell = $this->getMock(
'SchemaShell',
array('in', 'out', 'hr', 'createFile', 'error', 'err', '_stop', '_run'),
array(&$this->Dispatcher)
);
$this->Shell->params = array(
'connection' => 'test',
'yes' => true,
);
$this->Shell->args = array('i18n');
$this->Shell->expects($this->never())->method('in');
$this->Shell->expects($this->exactly(2))->method('_run');
$this->Shell->startup();
$this->Shell->create();
}
/**
* Test schema run create with no table args.
*
* @return void
*/
public function testCreateNoArgs() {
$this->Shell->params = array(
'connection' => 'test'
);
$this->Shell->args = array('i18n');
$this->Shell->startup();
$this->Shell->expects($this->any())->method('in')->will($this->returnValue('y'));
$this->Shell->create();
$db = ConnectionManager::getDataSource('test');
$db->cacheSources = false;
$sources = $db->listSources();
$this->assertTrue(in_array($db->config['prefix'] . 'i18n', $sources));
$schema = new i18nSchema();
$db->execute($db->dropSchema($schema));
}
/**
* Test schema run create with no table args.
*
* @return void
*/
public function testCreateWithTableArgs() {
$db = ConnectionManager::getDataSource('test');
$sources = $db->listSources();
if (in_array('i18n', $sources)) {
$this->markTestSkipped('i18n table already exists, cannot try to create it again.');
}
$this->Shell->params = array(
'connection' => 'test',
'name' => 'I18n',
'path' => APP . 'Config' . DS . 'Schema'
);
$this->Shell->args = array('I18n', 'i18n');
$this->Shell->startup();
$this->Shell->expects($this->any())->method('in')->will($this->returnValue('y'));
$this->Shell->create();
$db = ConnectionManager::getDataSource('test');
$db->cacheSources = false;
$sources = $db->listSources();
$this->assertTrue(in_array($db->config['prefix'] . 'i18n', $sources), 'i18n should be present.');
$schema = new I18nSchema();
$db->execute($db->dropSchema($schema, 'i18n'));
}
/**
* test run update with a table arg.
*
* @return void
*/
public function testUpdateWithTable() {
$this->Shell = $this->getMock(
'SchemaShell',
array('in', 'out', 'hr', 'createFile', 'error', 'err', '_stop', '_run'),
array(&$this->Dispatcher)
);
$this->Shell->params = array(
'connection' => 'test',
'force' => true
);
$this->Shell->args = array('SchemaShellTest', 'articles');
$this->Shell->startup();
$this->Shell->expects($this->any())
->method('in')
->will($this->returnValue('y'));
$this->Shell->expects($this->once())
->method('_run')
->with($this->arrayHasKey('articles'), 'update', $this->isInstanceOf('CakeSchema'));
$this->Shell->update();
}
/**
* test run update with a table arg. and checks that a CREATE statement is issued
* table creation
* @return void
*/
public function testUpdateWithTableCreate() {
$this->Shell = $this->getMock(
'SchemaShell',
array('in', 'out', 'hr', 'createFile', 'error', 'err', '_stop', '_run'),
array(&$this->Dispatcher)
);
$this->Shell->params = array(
'connection' => 'test',
'force' => true
);
$this->Shell->args = array('SchemaShellTest', 'newone');
$this->Shell->startup();
$this->Shell->expects($this->any())
->method('in')
->will($this->returnValue('y'));
$this->Shell->expects($this->once())
->method('_run')
->with($this->arrayHasKey('newone'), 'update', $this->isInstanceOf('CakeSchema'));
$this->Shell->update();
}
/**
* test run update with --yes option
*
* @return void
*/
public function testUpdateWithOptionYes() {
$this->Shell = $this->getMock(
'SchemaShell',
array('in', 'out', 'hr', 'createFile', 'error', 'err', '_stop', '_run'),
array(&$this->Dispatcher)
);
$this->Shell->params = array(
'connection' => 'test',
'force' => true,
'yes' => true,
);
$this->Shell->args = array('SchemaShellTest', 'articles');
$this->Shell->startup();
$this->Shell->expects($this->never())->method('in');
$this->Shell->expects($this->once())
->method('_run')
->with($this->arrayHasKey('articles'), 'update', $this->isInstanceOf('CakeSchema'));
$this->Shell->update();
}
/**
* test that the plugin param creates the correct path in the schema object.
*
* @return void
*/
public function testPluginParam() {
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
));
CakePlugin::load('TestPlugin');
$this->Shell->params = array(
'plugin' => 'TestPlugin',
'connection' => 'test'
);
$this->Shell->startup();
$expected = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS . 'TestPlugin' . DS . 'Config' . DS . 'Schema';
$this->assertEquals($expected, $this->Shell->Schema->path);
CakePlugin::unload();
}
/**
* test that underscored names also result in CamelCased class names
*
* @return void
*/
public function testName() {
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
));
CakePlugin::load('TestPlugin');
$this->Shell->params = array(
'plugin' => 'TestPlugin',
'connection' => 'test',
'name' => 'custom_name',
'force' => false,
'overwrite' => true,
);
$this->Shell->startup();
if (file_exists($this->Shell->Schema->path . DS . 'custom_name.php')) {
unlink($this->Shell->Schema->path . DS . 'custom_name.php');
}
$this->Shell->generate();
$contents = file_get_contents($this->Shell->Schema->path . DS . 'custom_name.php');
$this->assertRegExp('/class CustomNameSchema/', $contents);
unlink($this->Shell->Schema->path . DS . 'custom_name.php');
CakePlugin::unload();
}
/**
* test that passing name and file creates the passed filename with the
* passed class name
*
* @return void
*/
public function testNameAndFile() {
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
));
CakePlugin::load('TestPlugin');
$this->Shell->params = array(
'plugin' => 'TestPlugin',
'connection' => 'test',
'name' => 'custom_name',
'file' => 'other_name',
'force' => false,
'overwrite' => true,
);
$this->Shell->startup();
$file = $this->Shell->Schema->path . DS . 'other_name.php';
if (file_exists($file)) {
unlink($file);
}
$this->Shell->generate();
$this->assertFileExists($file);
$contents = file_get_contents($file);
$this->assertRegExp('/class CustomNameSchema/', $contents);
if (file_exists($file)) {
unlink($file);
}
CakePlugin::unload();
}
/**
* test that using Plugin.name with write.
*
* @return void
*/
public function testPluginDotSyntaxWithCreate() {
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
));
CakePlugin::load('TestPlugin');
$this->Shell->params = array(
'connection' => 'test'
);
$this->Shell->args = array('TestPlugin.TestPluginApp');
$this->Shell->startup();
$this->Shell->expects($this->any())->method('in')->will($this->returnValue('y'));
$this->Shell->create();
$db = ConnectionManager::getDataSource('test');
$sources = $db->listSources();
$this->assertTrue(in_array($db->config['prefix'] . 'test_plugin_acos', $sources));
$schema = new TestPluginAppSchema();
$db->execute($db->dropSchema($schema, 'test_plugin_acos'));
CakePlugin::unload();
}
}

View file

@ -0,0 +1,240 @@
<?php
/**
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.Console.Command
* @since CakePHP v 2.5
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('CommandTask', 'Console/Command/Task');
/**
* CommandTaskTest class
*
* @package Cake.Test.Case.Console.Command.Task
*/
class CommandTaskTest extends CakeTestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
App::build(array(
'Plugin' => array(
CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS
),
'Console/Command' => array(
CAKE . 'Test' . DS . 'test_app' . DS . 'Console' . DS . 'Command' . DS
)
), App::RESET);
CakePlugin::load(array('TestPlugin', 'TestPluginTwo'));
$out = $this->getMock('ConsoleOutput', array(), array(), '', false);
$in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->CommandTask = $this->getMock(
'CommandTask',
array('in', '_stop', 'clear'),
array($out, $out, $in)
);
}
/**
* tearDown
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->CommandTask);
CakePlugin::unload();
}
/**
* Test the resulting list of shells
*
* @return void
*/
public function testGetShellList() {
$result = $this->CommandTask->getShellList();
$expected = array(
'CORE' => array(
'acl',
'api',
'bake',
'command_list',
'completion',
'console',
'i18n',
'schema',
'server',
'test',
'testsuite',
'upgrade'
),
'TestPlugin' => array(
'example'
),
'TestPluginTwo' => array(
'example',
'welcome'
),
'app' => array(
'sample'
),
);
$this->assertEquals($expected, $result);
}
/**
* Test the resulting list of commands
*
* @return void
*/
public function testCommands() {
$result = $this->CommandTask->commands();
$expected = array(
'TestPlugin.example',
'TestPluginTwo.example',
'TestPluginTwo.welcome',
'acl',
'api',
'bake',
'command_list',
'completion',
'console',
'i18n',
'schema',
'server',
'test',
'testsuite',
'upgrade',
'sample'
);
$this->assertEquals($expected, $result);
}
/**
* Test the resulting list of subcommands for the given command
*
* @return void
*/
public function testSubCommands() {
$result = $this->CommandTask->subCommands('acl');
$expected = array(
'check',
'create',
'db_config',
'delete',
'deny',
'getPath',
'grant',
'inherit',
'initdb',
'nodeExists',
'parseIdentifier',
'setParent',
'view'
);
$this->assertEquals($expected, $result);
}
/**
* Test that unknown commands return an empty array
*
* @return void
*/
public function testSubCommandsUnknownCommand() {
$result = $this->CommandTask->subCommands('yoghurt');
$expected = array();
$this->assertEquals($expected, $result);
}
/**
* Test that getting a existing shell returns the shell instance
*
* @return void
*/
public function testGetShell() {
$result = $this->CommandTask->getShell('acl');
$this->assertInstanceOf('AclShell', $result);
}
/**
* Test that getting a non-existing shell returns false
*
* @return void
*/
public function testGetShellNonExisting() {
$result = $this->CommandTask->getShell('strawberry');
$this->assertFalse($result);
}
/**
* Test that getting a existing core shell with 'core.' prefix returns the correct shell instance
*
* @return void
*/
public function testGetShellCore() {
$result = $this->CommandTask->getShell('core.bake');
$this->assertInstanceOf('BakeShell', $result);
}
/**
* Test the options array for a known command
*
* @return void
*/
public function testOptions() {
$result = $this->CommandTask->options('bake');
$expected = array(
'--help',
'-h',
'--verbose',
'-v',
'--quiet',
'-q',
'--connection',
'-c',
'--theme',
'-t'
);
$this->assertEquals($expected, $result);
}
/**
* Test the options array for an unknown command
*
* @return void
*/
public function testOptionsUnknownCommand() {
$result = $this->CommandTask->options('pie');
$expected = array(
'--help',
'-h',
'--verbose',
'-v',
'--quiet',
'-q'
);
$this->assertEquals($expected, $result);
}
}

View file

@ -0,0 +1,618 @@
<?php
/**
* ControllerTask Test Case
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Console.Command.Task
* @since CakePHP(tm) v 1.3
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ConsoleOutput', 'Console');
App::uses('ConsoleInput', 'Console');
App::uses('ShellDispatcher', 'Console');
App::uses('Shell', 'Console');
App::uses('CakeSchema', 'Model');
App::uses('ClassRegistry', 'Utility');
App::uses('Helper', 'View/Helper');
App::uses('ProjectTask', 'Console/Command/Task');
App::uses('ControllerTask', 'Console/Command/Task');
App::uses('ModelTask', 'Console/Command/Task');
App::uses('TemplateTask', 'Console/Command/Task');
App::uses('TestTask', 'Console/Command/Task');
App::uses('Model', 'Model');
App::uses('BakeArticle', 'Model');
App::uses('BakeComment', 'Model');
App::uses('BakeTags', 'Model');
$imported = class_exists('BakeArticle') || class_exists('BakeComment') || class_exists('BakeTag');
if (!$imported) {
define('ARTICLE_MODEL_CREATED', true);
/**
* Class BakeArticle
*/
class BakeArticle extends Model {
public $hasMany = array('BakeComment');
public $hasAndBelongsToMany = array('BakeTag');
}
}
/**
* ControllerTaskTest class
*
* @package Cake.Test.Case.Console.Command.Task
*/
class ControllerTaskTest extends CakeTestCase {
/**
* fixtures
*
* @var array
*/
public $fixtures = array('core.bake_article', 'core.bake_articles_bake_tag', 'core.bake_comment', 'core.bake_tag');
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$out = $this->getMock('ConsoleOutput', array(), array(), '', false);
$in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->Task = $this->getMock('ControllerTask',
array('in', 'out', 'err', 'hr', 'createFile', '_stop', '_checkUnitTest'),
array($out, $out, $in)
);
$this->Task->name = 'Controller';
$this->Task->Template = new TemplateTask($out, $out, $in);
$this->Task->Template->params['theme'] = 'default';
$this->Task->Model = $this->getMock('ModelTask',
array('in', 'out', 'err', 'createFile', '_stop', '_checkUnitTest'),
array($out, $out, $in)
);
$this->Task->Project = $this->getMock('ProjectTask',
array('in', 'out', 'err', 'createFile', '_stop', '_checkUnitTest', 'getPrefix'),
array($out, $out, $in)
);
$this->Task->Test = $this->getMock('TestTask', array(), array($out, $out, $in));
if (!defined('ARTICLE_MODEL_CREATED')) {
$this->markTestSkipped('Could not run as an Article, Tag or Comment model was already loaded.');
}
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
unset($this->Task);
ClassRegistry::flush();
App::build();
parent::tearDown();
}
/**
* test ListAll
*
* @return void
*/
public function testListAll() {
$count = count($this->Task->listAll('test'));
if ($count != count($this->fixtures)) {
$this->markTestSkipped('Additional tables detected.');
}
$this->Task->connection = 'test';
$this->Task->interactive = true;
$this->Task->expects($this->at(2))->method('out')->with(' 1. BakeArticles');
$this->Task->expects($this->at(3))->method('out')->with(' 2. BakeArticlesBakeTags');
$this->Task->expects($this->at(4))->method('out')->with(' 3. BakeComments');
$this->Task->expects($this->at(5))->method('out')->with(' 4. BakeTags');
$expected = array('BakeArticles', 'BakeArticlesBakeTags', 'BakeComments', 'BakeTags');
$result = $this->Task->listAll('test');
$this->assertEquals($expected, $result);
$this->Task->interactive = false;
$result = $this->Task->listAll();
$expected = array('bake_articles', 'bake_articles_bake_tags', 'bake_comments', 'bake_tags');
$this->assertEquals($expected, $result);
}
/**
* Test that getName interacts with the user and returns the controller name.
*
* @return void
*/
public function testGetNameValidIndex() {
$count = count($this->Task->listAll('test'));
if ($count != count($this->fixtures)) {
$this->markTestSkipped('Additional tables detected.');
}
$this->Task->interactive = true;
$this->Task->expects($this->any())->method('in')->will(
$this->onConsecutiveCalls(3, 1)
);
$result = $this->Task->getName('test');
$expected = 'BakeComments';
$this->assertEquals($expected, $result);
$result = $this->Task->getName('test');
$expected = 'BakeArticles';
$this->assertEquals($expected, $result);
}
/**
* test getting invalid indexes.
*
* @return void
*/
public function testGetNameInvalidIndex() {
$this->Task->interactive = true;
$this->Task->expects($this->any())->method('in')
->will($this->onConsecutiveCalls(50, 'q'));
$this->Task->expects($this->once())->method('err');
$this->Task->expects($this->once())->method('_stop');
$this->Task->getName('test');
}
/**
* test helper interactions
*
* @return void
*/
public function testDoHelpersNo() {
$this->Task->expects($this->any())->method('in')->will($this->returnValue('n'));
$result = $this->Task->doHelpers();
$this->assertSame(array(), $result);
}
/**
* test getting helper values
*
* @return void
*/
public function testDoHelpersTrailingSpace() {
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue(' Text, Number, CustomOne '));
$result = $this->Task->doHelpers();
$expected = array('Text', 'Number', 'CustomOne');
$this->assertEquals($expected, $result);
}
/**
* test doHelpers with extra commas
*
* @return void
*/
public function testDoHelpersTrailingCommas() {
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue(' Text, Number, CustomOne, , '));
$result = $this->Task->doHelpers();
$expected = array('Text', 'Number', 'CustomOne');
$this->assertEquals($expected, $result);
}
/**
* test component interactions
*
* @return void
*/
public function testDoComponentsNo() {
$this->Task->expects($this->any())->method('in')->will($this->returnValue('n'));
$result = $this->Task->doComponents();
$this->assertSame(array('Paginator'), $result);
}
/**
* test components with spaces
*
* @return void
*/
public function testDoComponentsTrailingSpaces() {
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue(' RequestHandler, Security '));
$result = $this->Task->doComponents();
$expected = array('Paginator', 'RequestHandler', 'Security');
$this->assertEquals($expected, $result);
}
/**
* test components with commas
*
* @return void
*/
public function testDoComponentsTrailingCommas() {
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue(' RequestHandler, Security, , '));
$result = $this->Task->doComponents();
$expected = array('Paginator', 'RequestHandler', 'Security');
$this->assertEquals($expected, $result);
}
/**
* test Confirming controller user interaction
*
* @return void
*/
public function testConfirmController() {
$controller = 'Posts';
$scaffold = false;
$helpers = array('Js', 'Time');
$components = array('Acl', 'Auth');
$this->Task->expects($this->at(4))->method('out')->with("Controller Name:\n\t$controller");
$this->Task->expects($this->at(5))->method('out')->with("Helpers:\n\tJs, Time");
$this->Task->expects($this->at(6))->method('out')->with("Components:\n\tAcl, Auth");
$this->Task->confirmController($controller, $scaffold, $helpers, $components);
}
/**
* test the bake method
*
* @return void
*/
public function testBake() {
$helpers = array('Js', 'Time');
$components = array('Acl', 'Auth');
$this->Task->expects($this->any())->method('createFile')->will($this->returnValue(true));
$result = $this->Task->bake('Articles', null, $helpers, $components);
$expected = file_get_contents(CAKE . 'Test' . DS . 'bake_compare' . DS . 'Controller' . DS . 'NoActions.ctp');
$this->assertTextEquals($expected, $result);
$result = $this->Task->bake('Articles', null, array(), array());
$expected = file_get_contents(CAKE . 'Test' . DS . 'bake_compare' . DS . 'Controller' . DS . 'NoHelpersOrComponents.ctp');
$this->assertTextEquals($expected, $result);
$result = $this->Task->bake('Articles', 'scaffold', $helpers, $components);
$expected = file_get_contents(CAKE . 'Test' . DS . 'bake_compare' . DS . 'Controller' . DS . 'Scaffold.ctp');
$this->assertTextEquals($expected, $result);
}
/**
* test bake() with a -plugin param
*
* @return void
*/
public function testBakeWithPlugin() {
$this->Task->plugin = 'ControllerTest';
//fake plugin path
CakePlugin::load('ControllerTest', array('path' => APP . 'Plugin' . DS . 'ControllerTest' . DS));
$path = APP . 'Plugin' . DS . 'ControllerTest' . DS . 'Controller' . DS . 'ArticlesController.php';
$this->Task->expects($this->at(1))->method('createFile')->with(
$path,
new PHPUnit_Framework_Constraint_IsAnything()
);
$this->Task->expects($this->at(3))->method('createFile')->with(
$path,
$this->stringContains('ArticlesController extends ControllerTestAppController')
)->will($this->returnValue(true));
$this->Task->bake('Articles', '--actions--', array(), array(), array());
$this->Task->plugin = 'ControllerTest';
$path = APP . 'Plugin' . DS . 'ControllerTest' . DS . 'Controller' . DS . 'ArticlesController.php';
$result = $this->Task->bake('Articles', '--actions--', array(), array(), array());
$this->assertContains("App::uses('ControllerTestAppController', 'ControllerTest.Controller');", $result);
$this->assertEquals('ControllerTest', $this->Task->Template->templateVars['plugin']);
$this->assertEquals('ControllerTest.', $this->Task->Template->templateVars['pluginPath']);
CakePlugin::unload();
}
/**
* test that bakeActions is creating the correct controller Code. (Using sessions)
*
* @return void
*/
public function testBakeActionsUsingSessions() {
$result = $this->Task->bakeActions('BakeArticles', null, true);
$expected = file_get_contents(CAKE . 'Test' . DS . 'bake_compare' . DS . 'Controller' . DS . 'ActionsUsingSessions.ctp');
$this->assertTextEquals($expected, $result);
$result = $this->Task->bakeActions('BakeArticles', 'admin_', true);
$this->assertContains('function admin_index() {', $result);
$this->assertContains('function admin_add()', $result);
$this->assertContains('function admin_view($id = null)', $result);
$this->assertContains('function admin_edit($id = null)', $result);
$this->assertContains('function admin_delete($id = null)', $result);
}
/**
* Test baking with Controller::flash() or no sessions.
*
* @return void
*/
public function testBakeActionsWithNoSessions() {
$result = $this->Task->bakeActions('BakeArticles', null, false);
$expected = file_get_contents(CAKE . 'Test' . DS . 'bake_compare' . DS . 'Controller' . DS . 'ActionsWithNoSessions.ctp');
$this->assertTextEquals($expected, $result);
}
/**
* test baking a test
*
* @return void
*/
public function testBakeTest() {
$this->Task->plugin = 'ControllerTest';
$this->Task->connection = 'test';
$this->Task->interactive = false;
$this->Task->Test->expects($this->once())->method('bake')->with('Controller', 'BakeArticles');
$this->Task->bakeTest('BakeArticles');
$this->assertEquals($this->Task->plugin, $this->Task->Test->plugin);
$this->assertEquals($this->Task->connection, $this->Task->Test->connection);
$this->assertEquals($this->Task->interactive, $this->Task->Test->interactive);
}
/**
* test Interactive mode.
*
* @return void
*/
public function testInteractive() {
$count = count($this->Task->listAll('test'));
if ($count != count($this->fixtures)) {
$this->markTestSkipped('Additional tables detected.');
}
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
$this->Task->expects($this->any())->method('in')
->will($this->onConsecutiveCalls(
'1',
'y', // build interactive
'n', // build no scaffolds
'y', // build normal methods
'n', // build admin methods
'n', // helpers?
'n', // components?
'y', // sessions ?
'y' // looks good?
));
$filename = '/my/path/BakeArticlesController.php';
$this->Task->expects($this->once())->method('createFile')->with(
$filename,
$this->stringContains('class BakeArticlesController')
);
$this->Task->execute();
}
/**
* test Interactive mode.
*
* @return void
*/
public function testInteractiveAdminMethodsNotInteractive() {
$count = count($this->Task->listAll('test'));
if ($count != count($this->fixtures)) {
$this->markTestSkipped('Additional tables detected.');
}
$this->Task->connection = 'test';
$this->Task->interactive = true;
$this->Task->path = '/my/path/';
$this->Task->expects($this->any())->method('in')
->will($this->onConsecutiveCalls(
'1',
'y', // build interactive
'n', // build no scaffolds
'y', // build normal methods
'y', // build admin methods
'n', // helpers?
'n', // components?
'y', // sessions ?
'y' // looks good?
));
$this->Task->Project->expects($this->any())
->method('getPrefix')
->will($this->returnValue('admin_'));
$filename = '/my/path/BakeArticlesController.php';
$this->Task->expects($this->once())->method('createFile')->with(
$filename,
$this->stringContains('class BakeArticlesController')
)->will($this->returnValue(true));
$result = $this->Task->execute();
$this->assertRegExp('/admin_index/', $result);
}
/**
* test that execute runs all when the first arg == all
*
* @return void
*/
public function testExecuteIntoAll() {
$count = count($this->Task->listAll('test'));
if ($count != count($this->fixtures)) {
$this->markTestSkipped('Additional tables detected.');
}
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
$this->Task->args = array('all');
$this->Task->expects($this->any())->method('_checkUnitTest')->will($this->returnValue(true));
$this->Task->Test->expects($this->once())->method('bake');
$filename = '/my/path/BakeArticlesController.php';
$this->Task->expects($this->once())->method('createFile')->with(
$filename,
$this->stringContains('class BakeArticlesController')
)->will($this->returnValue(true));
$this->Task->execute();
}
/**
* Test execute() with all and --admin
*
* @return void
*/
public function testExecuteIntoAllAdmin() {
$count = count($this->Task->listAll('test'));
if ($count != count($this->fixtures)) {
$this->markTestSkipped('Additional tables detected.');
}
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
$this->Task->args = array('all');
$this->Task->params['admin'] = true;
$this->Task->Project->expects($this->any())
->method('getPrefix')
->will($this->returnValue('admin_'));
$this->Task->expects($this->any())
->method('_checkUnitTest')
->will($this->returnValue(true));
$this->Task->Test->expects($this->once())->method('bake');
$filename = '/my/path/BakeArticlesController.php';
$this->Task->expects($this->once())->method('createFile')->with(
$filename,
$this->stringContains('function admin_index')
)->will($this->returnValue(true));
$this->Task->execute();
}
/**
* test that `cake bake controller foos` works.
*
* @return void
*/
public function testExecuteWithController() {
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
$this->Task->args = array('BakeArticles');
$filename = '/my/path/BakeArticlesController.php';
$this->Task->expects($this->once())->method('createFile')->with(
$filename,
$this->stringContains('$scaffold')
);
$this->Task->execute();
}
/**
* data provider for testExecuteWithControllerNameVariations
*
* @return void
*/
public static function nameVariations() {
return array(
array('BakeArticles'), array('BakeArticle'), array('bake_article'), array('bake_articles')
);
}
/**
* test that both plural and singular forms work for controller baking.
*
* @dataProvider nameVariations
* @return void
*/
public function testExecuteWithControllerNameVariations($name) {
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
$this->Task->args = array($name);
$filename = '/my/path/BakeArticlesController.php';
$this->Task->expects($this->once())->method('createFile')->with(
$filename, $this->stringContains('$scaffold')
);
$this->Task->execute();
}
/**
* test that `cake bake controller foo scaffold` works.
*
* @return void
*/
public function testExecuteWithPublicParam() {
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
$this->Task->args = array('BakeArticles');
$this->Task->params = array('public' => true);
$filename = '/my/path/BakeArticlesController.php';
$expected = new PHPUnit_Framework_Constraint_Not($this->stringContains('$scaffold'));
$this->Task->expects($this->once())->method('createFile')->with(
$filename, $expected
);
$this->Task->execute();
}
/**
* test that `cake bake controller foos both` works.
*
* @return void
*/
public function testExecuteWithControllerAndBoth() {
$this->Task->Project->expects($this->any())->method('getPrefix')->will($this->returnValue('admin_'));
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
$this->Task->args = array('BakeArticles');
$this->Task->params = array('public' => true, 'admin' => true);
$filename = '/my/path/BakeArticlesController.php';
$this->Task->expects($this->once())->method('createFile')->with(
$filename, $this->stringContains('admin_index')
);
$this->Task->execute();
}
/**
* test that `cake bake controller foos admin` works.
*
* @return void
*/
public function testExecuteWithControllerAndAdmin() {
$this->Task->Project->expects($this->any())->method('getPrefix')->will($this->returnValue('admin_'));
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
$this->Task->args = array('BakeArticles');
$this->Task->params = array('admin' => true);
$filename = '/my/path/BakeArticlesController.php';
$this->Task->expects($this->once())->method('createFile')->with(
$filename, $this->stringContains('admin_index')
);
$this->Task->execute();
}
}

View file

@ -0,0 +1,132 @@
<?php
/**
* DBConfigTask Test Case
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Console.Command.Task
* @since CakePHP(tm) v 1.3
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ShellDispatcher', 'Console');
App::uses('ConsoleOutput', 'Console');
App::uses('ConsoleInput', 'Console');
App::uses('Shell', 'Console');
App::uses('DbConfigTask', 'Console/Command/Task');
/**
* DbConfigTest class
*
* @package Cake.Test.Case.Console.Command.Task
*/
class DbConfigTaskTest extends CakeTestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$out = $this->getMock('ConsoleOutput', array(), array(), '', false);
$in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->Task = $this->getMock('DbConfigTask',
array('in', 'out', 'err', 'hr', 'createFile', '_stop', '_checkUnitTest', '_verify'),
array($out, $out, $in)
);
$this->Task->path = APP . 'Config' . DS;
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->Task);
}
/**
* Test the getConfig method.
*
* @return void
*/
public function testGetConfig() {
$this->Task->expects($this->any())
->method('in')
->will($this->returnValue('test'));
$result = $this->Task->getConfig();
$this->assertEquals('test', $result);
}
/**
* test that initialize sets the path up.
*
* @return void
*/
public function testInitialize() {
$this->Task->initialize();
$this->assertFalse(empty($this->Task->path));
$this->assertEquals(APP . 'Config' . DS, $this->Task->path);
}
/**
* test execute and by extension _interactive
*
* @return void
*/
public function testExecuteIntoInteractive() {
$this->Task->initialize();
$out = $this->getMock('ConsoleOutput', array(), array(), '', false);
$in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->Task = $this->getMock(
'DbConfigTask',
array('in', '_stop', 'createFile', 'bake'), array($out, $out, $in)
);
$this->Task->expects($this->once())->method('_stop');
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('default')); //name
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue('mysql')); //db type
$this->Task->expects($this->at(2))->method('in')->will($this->returnValue('n')); //persistent
$this->Task->expects($this->at(3))->method('in')->will($this->returnValue('localhost')); //server
$this->Task->expects($this->at(4))->method('in')->will($this->returnValue('n')); //port
$this->Task->expects($this->at(5))->method('in')->will($this->returnValue('root')); //user
$this->Task->expects($this->at(6))->method('in')->will($this->returnValue('password')); //password
$this->Task->expects($this->at(10))->method('in')->will($this->returnValue('cake_test')); //db
$this->Task->expects($this->at(11))->method('in')->will($this->returnValue('n')); //prefix
$this->Task->expects($this->at(12))->method('in')->will($this->returnValue('n')); //encoding
$this->Task->expects($this->at(13))->method('in')->will($this->returnValue('y')); //looks good
$this->Task->expects($this->at(14))->method('in')->will($this->returnValue('n')); //another
$this->Task->expects($this->at(15))->method('bake')
->with(array(
array(
'name' => 'default',
'datasource' => 'mysql',
'persistent' => 'false',
'host' => 'localhost',
'login' => 'root',
'password' => 'password',
'database' => 'cake_test',
'prefix' => null,
'encoding' => null,
'port' => '',
'schema' => null
)
));
$this->Task->execute();
}
}

View file

@ -0,0 +1,494 @@
<?php
/**
* ExtractTaskTest file
*
* Test Case for i18n extraction shell task
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.Console.Command.Task
* @since CakePHP v 1.2.0.7726
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Folder', 'Utility');
App::uses('ConsoleOutput', 'Console');
App::uses('ConsoleInput', 'Console');
App::uses('ShellDispatcher', 'Console');
App::uses('Shell', 'Console');
App::uses('ExtractTask', 'Console/Command/Task');
/**
* ExtractTaskTest class
*
* @package Cake.Test.Case.Console.Command.Task
*/
class ExtractTaskTest extends CakeTestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$out = $this->getMock('ConsoleOutput', array(), array(), '', false);
$in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->Task = $this->getMock(
'ExtractTask',
array('in', 'out', 'err', '_stop'),
array($out, $out, $in)
);
$this->path = TMP . 'tests' . DS . 'extract_task_test';
new Folder($this->path . DS . 'locale', true);
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->Task);
$Folder = new Folder($this->path);
$Folder->delete();
CakePlugin::unload();
}
/**
* testExecute method
*
* @return void
*/
public function testExecute() {
$this->Task->interactive = false;
$this->Task->params['paths'] = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Pages';
$this->Task->params['output'] = $this->path . DS;
$this->Task->params['extract-core'] = 'no';
$this->Task->expects($this->never())->method('err');
$this->Task->expects($this->any())->method('in')
->will($this->returnValue('y'));
$this->Task->expects($this->never())->method('_stop');
$this->Task->execute();
$this->assertTrue(file_exists($this->path . DS . 'default.pot'));
$result = file_get_contents($this->path . DS . 'default.pot');
$this->assertFalse(file_exists($this->path . DS . 'cake.pot'));
$pattern = '/"Content-Type\: text\/plain; charset\=utf-8/';
$this->assertRegExp($pattern, $result);
$pattern = '/"Content-Transfer-Encoding\: 8bit/';
$this->assertRegExp($pattern, $result);
$pattern = '/"Plural-Forms\: nplurals\=INTEGER; plural\=EXPRESSION;/';
$this->assertRegExp($pattern, $result);
// home.ctp
$pattern = '/msgid "Your tmp directory is writable."\nmsgstr ""\n/';
$this->assertRegExp($pattern, $result);
$pattern = '/msgid "Your tmp directory is NOT writable."\nmsgstr ""\n/';
$this->assertRegExp($pattern, $result);
$pattern = '/msgid "The %s is being used for caching. To change the config edit ';
$pattern .= 'APP\/config\/core.php "\nmsgstr ""\n/';
$this->assertRegExp($pattern, $result);
$pattern = '/msgid "Your cache is NOT working. Please check ';
$pattern .= 'the settings in APP\/config\/core.php"\nmsgstr ""\n/';
$this->assertRegExp($pattern, $result);
$pattern = '/msgid "Your database configuration file is present."\nmsgstr ""\n/';
$this->assertRegExp($pattern, $result);
$pattern = '/msgid "Your database configuration file is NOT present."\nmsgstr ""\n/';
$this->assertRegExp($pattern, $result);
$pattern = '/msgid "Rename config\/database.php.default to ';
$pattern .= 'config\/database.php"\nmsgstr ""\n/';
$this->assertRegExp($pattern, $result);
$pattern = '/msgid "Cake is able to connect to the database."\nmsgstr ""\n/';
$this->assertRegExp($pattern, $result);
$pattern = '/msgid "Cake is NOT able to connect to the database."\nmsgstr ""\n/';
$this->assertRegExp($pattern, $result);
$pattern = '/msgid "Editing this Page"\nmsgstr ""\n/';
$this->assertRegExp($pattern, $result);
$pattern = '/msgid "To change the content of this page, create: APP\/views\/pages\/home\.ctp/';
$this->assertRegExp($pattern, $result);
$pattern = '/To change its layout, create: APP\/views\/layouts\/default\.ctp\./s';
$this->assertRegExp($pattern, $result);
// extract.ctp
$pattern = '/\#: (\\\\|\/)extract\.ctp:15;6\n';
$pattern .= 'msgid "You have %d new message."\nmsgid_plural "You have %d new messages."/';
$this->assertRegExp($pattern, $result);
$pattern = '/msgid "You have %d new message."\nmsgstr ""/';
$this->assertNotRegExp($pattern, $result, 'No duplicate msgid');
$pattern = '/\#: (\\\\|\/)extract\.ctp:7\n';
$pattern .= 'msgid "You deleted %d message."\nmsgid_plural "You deleted %d messages."/';
$this->assertRegExp($pattern, $result);
$pattern = '/\#: (\\\\|\/)extract\.ctp:14\n';
$pattern .= '\#: (\\\\|\/)home\.ctp:68\n';
$pattern .= 'msgid "Editing this Page"\nmsgstr ""/';
$this->assertRegExp($pattern, $result);
$pattern = '/\#: (\\\\|\/)extract\.ctp:22\nmsgid "';
$pattern .= 'Hot features!';
$pattern .= '\\\n - No Configuration: Set-up the database and let the magic begin';
$pattern .= '\\\n - Extremely Simple: Just look at the name...It\'s Cake';
$pattern .= '\\\n - Active, Friendly Community: Join us #cakephp on IRC. We\'d love to help you get started';
$pattern .= '"\nmsgstr ""/';
$this->assertRegExp($pattern, $result);
$this->assertContains('msgid "double \\"quoted\\""', $result, 'Strings with quotes not handled correctly');
$this->assertContains("msgid \"single 'quoted'\"", $result, 'Strings with quotes not handled correctly');
// extract.ctp - reading the domain.pot
$result = file_get_contents($this->path . DS . 'domain.pot');
$pattern = '/msgid "You have %d new message."\nmsgid_plural "You have %d new messages."/';
$this->assertNotRegExp($pattern, $result);
$pattern = '/msgid "You deleted %d message."\nmsgid_plural "You deleted %d messages."/';
$this->assertNotRegExp($pattern, $result);
$pattern = '/msgid "You have %d new message \(domain\)."\nmsgid_plural "You have %d new messages \(domain\)."/';
$this->assertRegExp($pattern, $result);
$pattern = '/msgid "You deleted %d message \(domain\)."\nmsgid_plural "You deleted %d messages \(domain\)."/';
$this->assertRegExp($pattern, $result);
}
/**
* testExtractCategory method
*
* @return void
*/
public function testExtractCategory() {
$this->Task->interactive = false;
$this->Task->params['paths'] = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Pages';
$this->Task->params['output'] = $this->path . DS;
$this->Task->params['extract-core'] = 'no';
$this->Task->params['merge'] = 'no';
$this->Task->expects($this->never())->method('err');
$this->Task->expects($this->any())->method('in')
->will($this->returnValue('y'));
$this->Task->expects($this->never())->method('_stop');
$this->Task->execute();
$this->assertTrue(file_exists($this->path . DS . 'LC_TIME' . DS . 'default.pot'));
$result = file_get_contents($this->path . DS . 'default.pot');
$pattern = '/\#: .*extract\.ctp:31\n/';
$this->assertNotRegExp($pattern, $result);
}
/**
* test exclusions
*
* @return void
*/
public function testExtractWithExclude() {
$this->Task->interactive = false;
$this->Task->params['paths'] = CAKE . 'Test' . DS . 'test_app' . DS . 'View';
$this->Task->params['output'] = $this->path . DS;
$this->Task->params['exclude'] = 'Pages,Layouts';
$this->Task->params['extract-core'] = 'no';
$this->Task->expects($this->any())->method('in')
->will($this->returnValue('y'));
$this->Task->execute();
$this->assertTrue(file_exists($this->path . DS . 'default.pot'));
$result = file_get_contents($this->path . DS . 'default.pot');
$pattern = '/\#: .*extract\.ctp:6\n/';
$this->assertNotRegExp($pattern, $result);
$pattern = '/\#: .*default\.ctp:26\n/';
$this->assertNotRegExp($pattern, $result);
}
/**
* test extract can read more than one path.
*
* @return void
*/
public function testExtractMultiplePaths() {
$this->Task->interactive = false;
$this->Task->params['paths'] =
CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Pages,' .
CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Posts';
$this->Task->params['output'] = $this->path . DS;
$this->Task->params['extract-core'] = 'no';
$this->Task->expects($this->never())->method('err');
$this->Task->expects($this->never())->method('_stop');
$this->Task->execute();
$result = file_get_contents($this->path . DS . 'default.pot');
$pattern = '/msgid "Add User"/';
$this->assertRegExp($pattern, $result);
}
/**
* Tests that it is possible to exclude plugin paths by enabling the param option for the ExtractTask
*
* @return void
*/
public function testExtractExcludePlugins() {
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
));
$this->out = $this->getMock('ConsoleOutput', array(), array(), '', false);
$this->in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->Task = $this->getMock('ExtractTask',
array('_isExtractingApp', '_extractValidationMessages', 'in', 'out', 'err', 'clear', '_stop'),
array($this->out, $this->out, $this->in)
);
$this->Task->expects($this->exactly(2))->method('_isExtractingApp')->will($this->returnValue(true));
$this->Task->params['paths'] = CAKE . 'Test' . DS . 'test_app' . DS;
$this->Task->params['output'] = $this->path . DS;
$this->Task->params['exclude-plugins'] = true;
$this->Task->execute();
$result = file_get_contents($this->path . DS . 'default.pot');
$this->assertNotRegExp('#TestPlugin#', $result);
}
/**
* Test that is possible to extract messages form a single plugin
*
* @return void
*/
public function testExtractPlugin() {
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
));
$this->out = $this->getMock('ConsoleOutput', array(), array(), '', false);
$this->in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->Task = $this->getMock('ExtractTask',
array('_isExtractingApp', 'in', 'out', 'err', 'clear', '_stop'),
array($this->out, $this->out, $this->in)
);
$this->Task->params['output'] = $this->path . DS;
$this->Task->params['plugin'] = 'TestPlugin';
$this->Task->execute();
$result = file_get_contents($this->path . DS . 'default.pot');
$this->assertNotRegExp('#Pages#', $result);
$this->assertContains('translate.ctp:1', $result);
$this->assertContains('This is a translatable string', $result);
$this->assertContains('I can haz plugin model validation message', $result);
}
/**
* Tests that the task will inspect application models and extract the validation messages from them
*
* @return void
*/
public function testExtractModelValidation() {
App::build(array(
'Model' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Model' . DS),
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
), App::RESET);
$this->out = $this->getMock('ConsoleOutput', array(), array(), '', false);
$this->in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->Task = $this->getMock('ExtractTask',
array('_isExtractingApp', 'in', 'out', 'err', 'clear', '_stop'),
array($this->out, $this->out, $this->in)
);
$this->Task->expects($this->exactly(2))->method('_isExtractingApp')->will($this->returnValue(true));
$this->Task->params['paths'] = CAKE . 'Test' . DS . 'test_app' . DS;
$this->Task->params['output'] = $this->path . DS;
$this->Task->params['extract-core'] = 'no';
$this->Task->params['exclude-plugins'] = true;
$this->Task->params['ignore-model-validation'] = false;
$this->Task->execute();
$result = file_get_contents($this->path . DS . 'default.pot');
$pattern = preg_quote('#Model/PersisterOne.php:validation for field title#', '\\');
$this->assertRegExp($pattern, $result);
$pattern = preg_quote('#Model/PersisterOne.php:validation for field body#', '\\');
$this->assertRegExp($pattern, $result);
$pattern = '#msgid "Post title is required"#';
$this->assertRegExp($pattern, $result);
$pattern = '#msgid "You may enter up to %s chars \(minimum is %s chars\)"#';
$this->assertRegExp($pattern, $result);
$pattern = '#msgid "Post body is required"#';
$this->assertRegExp($pattern, $result);
$pattern = '#msgid "Post body is super required"#';
$this->assertRegExp($pattern, $result);
$this->assertContains('msgid "double \\"quoted\\" validation"', $result, 'Strings with quotes not handled correctly');
$this->assertContains("msgid \"single 'quoted' validation\"", $result, 'Strings with quotes not handled correctly');
}
/**
* Tests that the task will inspect application models and extract the validation messages from them
* while using a custom validation domain for the messages set on the model itself
*
* @return void
*/
public function testExtractModelValidationWithDomainInModel() {
App::build(array(
'Model' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS . 'TestPlugin' . DS . 'Model' . DS)
));
$this->out = $this->getMock('ConsoleOutput', array(), array(), '', false);
$this->in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->Task = $this->getMock('ExtractTask',
array('_isExtractingApp', 'in', 'out', 'err', 'clear', '_stop'),
array($this->out, $this->out, $this->in)
);
$this->Task->expects($this->exactly(2))->method('_isExtractingApp')->will($this->returnValue(true));
$this->Task->params['paths'] = CAKE . 'Test' . DS . 'test_app' . DS;
$this->Task->params['output'] = $this->path . DS;
$this->Task->params['extract-core'] = 'no';
$this->Task->params['exclude-plugins'] = true;
$this->Task->params['ignore-model-validation'] = false;
$this->Task->execute();
$result = file_get_contents($this->path . DS . 'test_plugin.pot');
$pattern = preg_quote('#Plugin/TestPlugin/Model/TestPluginPost.php:validation for field title#', '\\');
$this->assertRegExp($pattern, $result);
$pattern = preg_quote('#Plugin/TestPlugin/Model/TestPluginPost.php:validation for field body#', '\\');
$this->assertRegExp($pattern, $result);
$pattern = '#msgid "Post title is required"#';
$this->assertRegExp($pattern, $result);
$pattern = '#msgid "Post body is required"#';
$this->assertRegExp($pattern, $result);
$pattern = '#msgid "Post body is super required"#';
$this->assertRegExp($pattern, $result);
}
/**
* Test that the extract shell can obtain validation messages from models inside a specific plugin
*
* @return void
*/
public function testExtractModelValidationInPlugin() {
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
));
$this->out = $this->getMock('ConsoleOutput', array(), array(), '', false);
$this->in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->Task = $this->getMock('ExtractTask',
array('_isExtractingApp', 'in', 'out', 'err', 'clear', '_stop'),
array($this->out, $this->out, $this->in)
);
$this->Task->params['output'] = $this->path . DS;
$this->Task->params['ignore-model-validation'] = false;
$this->Task->params['plugin'] = 'TestPlugin';
$this->Task->execute();
$result = file_get_contents($this->path . DS . 'test_plugin.pot');
$pattern = preg_quote('#Model/TestPluginPost.php:validation for field title#', '\\');
$this->assertRegExp($pattern, $result);
$pattern = preg_quote('#Model/TestPluginPost.php:validation for field body#', '\\');
$this->assertRegExp($pattern, $result);
$pattern = '#msgid "Post title is required"#';
$this->assertRegExp($pattern, $result);
$pattern = '#msgid "Post body is required"#';
$this->assertRegExp($pattern, $result);
$pattern = '#msgid "Post body is super required"#';
$this->assertRegExp($pattern, $result);
$pattern = '#Plugin/TestPlugin/Model/TestPluginPost.php:validation for field title#';
$this->assertNotRegExp($pattern, $result);
}
/**
* Test that the extract shell overwrites existing files with the overwrite parameter
*
* @return void
*/
public function testExtractOverwrite() {
$this->Task->interactive = false;
$this->Task->params['paths'] = CAKE . 'Test' . DS . 'test_app' . DS;
$this->Task->params['output'] = $this->path . DS;
$this->Task->params['extract-core'] = 'no';
$this->Task->params['overwrite'] = true;
file_put_contents($this->path . DS . 'default.pot', 'will be overwritten');
$this->assertTrue(file_exists($this->path . DS . 'default.pot'));
$original = file_get_contents($this->path . DS . 'default.pot');
$this->Task->execute();
$result = file_get_contents($this->path . DS . 'default.pot');
$this->assertNotEquals($original, $result);
}
/**
* Test that the extract shell scans the core libs
*
* @return void
*/
public function testExtractCore() {
$this->Task->interactive = false;
$this->Task->params['paths'] = CAKE . 'Test' . DS . 'test_app' . DS;
$this->Task->params['output'] = $this->path . DS;
$this->Task->params['extract-core'] = 'yes';
$this->Task->execute();
$this->assertTrue(file_exists($this->path . DS . 'cake.pot'));
$result = file_get_contents($this->path . DS . 'cake.pot');
$pattern = '/msgid "Yesterday, %s"\nmsgstr ""\n/';
$this->assertRegExp($pattern, $result);
$this->assertTrue(file_exists($this->path . DS . 'cake_dev.pot'));
$result = file_get_contents($this->path . DS . 'cake_dev.pot');
$pattern = '/#: Console\/Templates\//';
$this->assertNotRegExp($pattern, $result);
$pattern = '/#: Test\//';
$this->assertNotRegExp($pattern, $result);
}
}

View file

@ -0,0 +1,453 @@
<?php
/**
* FixtureTask Test case
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Console.Command.Task
* @since CakePHP(tm) v 1.3
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ShellDispatcher', 'Console');
App::uses('Shell', 'Console');
App::uses('ConsoleOutput', 'Console');
App::uses('ConsoleInput', 'Console');
App::uses('ModelTask', 'Console/Command/Task');
App::uses('FixtureTask', 'Console/Command/Task');
App::uses('TemplateTask', 'Console/Command/Task');
App::uses('DbConfigTask', 'Console/Command/Task');
/**
* FixtureTaskTest class
*
* @package Cake.Test.Case.Console.Command.Task
*/
class FixtureTaskTest extends CakeTestCase {
/**
* fixtures
*
* @var array
*/
public $fixtures = array('core.article', 'core.comment', 'core.datatype', 'core.binary_test', 'core.user');
/**
* Whether backup global state for each test method or not
*
* @var bool
*/
public $backupGlobals = false;
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$out = $this->getMock('ConsoleOutput', array(), array(), '', false);
$in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->Task = $this->getMock('FixtureTask',
array('in', 'err', 'createFile', '_stop', 'clear'),
array($out, $out, $in)
);
$this->Task->Model = $this->getMock('ModelTask',
array('in', 'out', 'err', 'createFile', 'getName', 'getTable', 'listAll'),
array($out, $out, $in)
);
$this->Task->Template = new TemplateTask($out, $out, $in);
$this->Task->DbConfig = $this->getMock('DbConfigTask', array(), array($out, $out, $in));
$this->Task->Template->initialize();
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->Task);
}
/**
* test that initialize sets the path
*
* @return void
*/
public function testConstruct() {
$out = $this->getMock('ConsoleOutput', array(), array(), '', false);
$in = $this->getMock('ConsoleInput', array(), array(), '', false);
$Task = new FixtureTask($out, $out, $in);
$this->assertEquals(APP . 'Test' . DS . 'Fixture' . DS, $Task->path);
}
/**
* test import option array generation
*
* @return void
*/
public function testImportOptionsSchemaRecords() {
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue('y'));
$result = $this->Task->importOptions('Article');
$expected = array('schema' => 'Article', 'records' => true);
$this->assertEquals($expected, $result);
}
/**
* test importOptions choosing nothing.
*
* @return void
*/
public function testImportOptionsNothing() {
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('n'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue('n'));
$this->Task->expects($this->at(2))->method('in')->will($this->returnValue('n'));
$result = $this->Task->importOptions('Article');
$expected = array();
$this->assertEquals($expected, $result);
}
/**
* test importOptions with overwriting command line options.
*
* @return void
*/
public function testImportOptionsWithCommandLineOptions() {
$this->Task->params = array('schema' => true, 'records' => true);
$result = $this->Task->importOptions('Article');
$expected = array('schema' => 'Article', 'records' => true);
$this->assertEquals($expected, $result);
}
/**
* test importOptions with schema.
*
* @return void
*/
public function testImportOptionsWithSchema() {
$this->Task->params = array('schema' => true);
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('n'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue('n'));
$result = $this->Task->importOptions('Article');
$expected = array('schema' => 'Article');
$this->assertEquals($expected, $result);
}
/**
* test importOptions with records.
*
* @return void
*/
public function testImportOptionsWithRecords() {
$this->Task->params = array('records' => true);
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('n'));
$result = $this->Task->importOptions('Article');
$expected = array('records' => true);
$this->assertEquals($expected, $result);
}
/**
* test importOptions choosing from Table.
*
* @return void
*/
public function testImportOptionsTable() {
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('n'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue('n'));
$this->Task->expects($this->at(2))->method('in')->will($this->returnValue('y'));
$result = $this->Task->importOptions('Article');
$expected = array('fromTable' => true);
$this->assertEquals($expected, $result);
}
/**
* test generating a fixture with database conditions.
*
* @return void
*/
public function testImportRecordsFromDatabaseWithConditionsPoo() {
$this->Task->interactive = true;
$this->Task->expects($this->at(0))->method('in')
->will($this->returnValue('WHERE 1=1'));
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
$result = $this->Task->bake('Article', false, array(
'fromTable' => true, 'schema' => 'Article', 'records' => false
));
$this->assertContains('class ArticleFixture extends CakeTestFixture', $result);
$this->assertContains('public $records', $result);
$this->assertContains('public $import', $result);
$this->assertContains("'title' => 'First Article'", $result, 'Missing import data %s');
$this->assertContains('Second Article', $result, 'Missing import data %s');
$this->assertContains('Third Article', $result, 'Missing import data %s');
}
/**
* test that connection gets set to the import options when a different connection is used.
*
* @return void
*/
public function testImportOptionsAlternateConnection() {
$this->Task->connection = 'test';
$result = $this->Task->bake('Article', false, array('schema' => 'Article'));
$this->assertContains("'connection' => 'test'", $result);
}
/**
* Ensure that fixture data doesn't get overly escaped.
*
* @return void
*/
public function testImportRecordsNoEscaping() {
$db = ConnectionManager::getDataSource('test');
if ($db instanceof Sqlserver) {
$this->markTestSkipped('This test does not run on SQLServer');
}
$Article = ClassRegistry::init('Article');
$Article->updateAll(array('body' => "'Body \"value\"'"));
$this->Task->interactive = true;
$this->Task->expects($this->at(0))
->method('in')
->will($this->returnValue('WHERE 1=1 LIMIT 10'));
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
$result = $this->Task->bake('Article', false, array(
'fromTable' => true,
'schema' => 'Article',
'records' => false
));
$this->assertContains("'body' => 'Body \"value\"'", $result, 'Data has bad escaping');
}
/**
* test that execute passes runs bake depending with named model.
*
* @return void
*/
public function testExecuteWithNamedModel() {
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
$this->Task->args = array('article');
$filename = '/my/path/ArticleFixture.php';
$this->Task->expects($this->at(0))->method('createFile')
->with($filename, $this->stringContains('class ArticleFixture'));
$this->Task->execute();
}
/**
* test that execute runs all() when args[0] = all
*
* @return void
*/
public function testExecuteIntoAll() {
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
$this->Task->args = array('all');
$this->Task->Model->expects($this->any())
->method('listAll')
->will($this->returnValue(array('articles', 'comments')));
$filename = '/my/path/ArticleFixture.php';
$this->Task->expects($this->at(0))
->method('createFile')
->with($filename, $this->stringContains('class ArticleFixture'));
$filename = '/my/path/CommentFixture.php';
$this->Task->expects($this->at(1))
->method('createFile')
->with($filename, $this->stringContains('class CommentFixture'));
$this->Task->execute();
}
/**
* test using all() with -count and -records
*
* @return void
*/
public function testAllWithCountAndRecordsFlags() {
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
$this->Task->args = array('all');
$this->Task->params = array('count' => 10, 'records' => true);
$this->Task->Model->expects($this->any())->method('listAll')
->will($this->returnValue(array('Articles', 'comments')));
$filename = '/my/path/ArticleFixture.php';
$this->Task->expects($this->at(0))->method('createFile')
->with($filename, $this->stringContains("'title' => 'Third Article'"));
$filename = '/my/path/CommentFixture.php';
$this->Task->expects($this->at(1))->method('createFile')
->with($filename, $this->stringContains("'comment' => 'First Comment for First Article'"));
$this->Task->expects($this->exactly(2))->method('createFile');
$this->Task->all();
}
/**
* test using all() with -schema
*
* @return void
*/
public function testAllWithSchemaImport() {
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
$this->Task->args = array('all');
$this->Task->params = array('schema' => true);
$this->Task->Model->expects($this->any())->method('listAll')
->will($this->returnValue(array('Articles', 'comments')));
$filename = '/my/path/ArticleFixture.php';
$this->Task->expects($this->at(0))->method('createFile')
->with($filename, $this->stringContains('public $import = array(\'model\' => \'Article\''));
$filename = '/my/path/CommentFixture.php';
$this->Task->expects($this->at(1))->method('createFile')
->with($filename, $this->stringContains('public $import = array(\'model\' => \'Comment\''));
$this->Task->expects($this->exactly(2))->method('createFile');
$this->Task->all();
}
/**
* test interactive mode of execute
*
* @return void
*/
public function testExecuteInteractive() {
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
$this->Task->expects($this->any())->method('in')->will($this->returnValue('y'));
$this->Task->Model->expects($this->any())->method('getName')->will($this->returnValue('Article'));
$this->Task->Model->expects($this->any())->method('getTable')
->with('Article')
->will($this->returnValue('articles'));
$filename = '/my/path/ArticleFixture.php';
$this->Task->expects($this->once())->method('createFile')
->with($filename, $this->stringContains('class ArticleFixture'));
$this->Task->execute();
}
/**
* Test that bake works
*
* @return void
*/
public function testBake() {
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
$result = $this->Task->bake('Article');
$this->assertContains('class ArticleFixture extends CakeTestFixture', $result);
$this->assertContains('public $fields', $result);
$this->assertContains('public $records', $result);
$this->assertNotContains('public $import', $result);
$result = $this->Task->bake('Article', 'comments');
$this->assertContains('class ArticleFixture extends CakeTestFixture', $result);
$this->assertContains('public $table = \'comments\';', $result);
$this->assertContains('public $fields = array(', $result);
$result = $this->Task->bake('Article', 'comments', array('records' => true));
$this->assertContains("public \$import = array('records' => true, 'connection' => 'test');", $result);
$this->assertNotContains('public $records', $result);
$result = $this->Task->bake('Article', 'comments', array('schema' => 'Article'));
$this->assertContains("public \$import = array('model' => 'Article', 'connection' => 'test');", $result);
$this->assertNotContains('public $fields', $result);
$result = $this->Task->bake('Article', 'comments', array('schema' => 'Article', 'records' => true));
$this->assertContains("public \$import = array('model' => 'Article', 'records' => true, 'connection' => 'test');", $result);
$this->assertNotContains('public $fields', $result);
$this->assertNotContains('public $records', $result);
}
/**
* test record generation with float and binary types
*
* @return void
*/
public function testRecordGenerationForBinaryAndFloat() {
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
$result = $this->Task->bake('Article', 'datatypes');
$this->assertContains("'float_field' => 1", $result);
$this->assertContains("'bool' => 1", $result);
$result = $this->Task->bake('Article', 'binary_tests');
$this->assertContains("'data' => 'Lorem ipsum dolor sit amet'", $result);
}
/**
* Test that file generation includes headers and correct path for plugins.
*
* @return void
*/
public function testGenerateFixtureFile() {
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
$filename = '/my/path/ArticleFixture.php';
$this->Task->expects($this->at(0))->method('createFile')
->with($filename, $this->stringContains('ArticleFixture'));
$this->Task->expects($this->at(1))->method('createFile')
->with($filename, $this->stringContains('<?php'));
$this->Task->generateFixtureFile('Article', array());
$this->Task->generateFixtureFile('Article', array());
}
/**
* test generating files into plugins.
*
* @return void
*/
public function testGeneratePluginFixtureFile() {
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
$this->Task->plugin = 'TestFixture';
$filename = APP . 'Plugin' . DS . 'TestFixture' . DS . 'Test' . DS . 'Fixture' . DS . 'ArticleFixture.php';
//fake plugin path
CakePlugin::load('TestFixture', array('path' => APP . 'Plugin' . DS . 'TestFixture' . DS));
$this->Task->expects($this->at(0))->method('createFile')
->with($filename, $this->stringContains('class Article'));
$this->Task->generateFixtureFile('Article', array());
CakePlugin::unload();
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,208 @@
<?php
/**
* PluginTask Test file
*
* Test Case for plugin generation shell task
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.Console.Command.Task
* @since CakePHP v 1.3.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ShellDispatcher', 'Console');
App::uses('ConsoleOutput', 'Console');
App::uses('ConsoleInput', 'Console');
App::uses('Shell', 'Console');
App::uses('PluginTask', 'Console/Command/Task');
App::uses('ModelTask', 'Console/Command/Task');
App::uses('Folder', 'Utility');
App::uses('File', 'Utility');
/**
* PluginTaskPlugin class
*
* @package Cake.Test.Case.Console.Command.Task
*/
class PluginTaskTest extends CakeTestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$this->out = $this->getMock('ConsoleOutput', array(), array(), '', false);
$this->in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->Task = $this->getMock('PluginTask',
array('in', 'err', 'createFile', '_stop', 'clear'),
array($this->out, $this->out, $this->in)
);
$this->Task->path = TMP . 'tests' . DS;
$this->Task->bootstrap = TMP . 'tests' . DS . 'bootstrap.php';
touch($this->Task->bootstrap);
$this->_paths = $paths = App::path('plugins');
foreach ($paths as $i => $p) {
if (!is_dir($p)) {
array_splice($paths, $i, 1);
}
}
$this->_testPath = array_push($paths, TMP . 'tests' . DS);
App::build(array('plugins' => $paths));
}
/**
* tearDown()
*
* @return void
*/
public function tearDown() {
if (file_exists($this->Task->bootstrap)) {
unlink($this->Task->bootstrap);
}
parent::tearDown();
}
/**
* test bake()
*
* @return void
*/
public function testBakeFoldersAndFiles() {
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue($this->_testPath));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue('y'));
$path = $this->Task->path . 'BakeTestPlugin';
$file = $path . DS . 'Controller' . DS . 'BakeTestPluginAppController.php';
$this->Task->expects($this->at(2))->method('createFile')
->with($file, new PHPUnit_Framework_Constraint_IsAnything());
$file = $path . DS . 'Model' . DS . 'BakeTestPluginAppModel.php';
$this->Task->expects($this->at(3))->method('createFile')
->with($file, new PHPUnit_Framework_Constraint_IsAnything());
$this->Task->bake('BakeTestPlugin');
$path = $this->Task->path . 'BakeTestPlugin';
$this->assertTrue(is_dir($path), 'No plugin dir %s');
$directories = array(
'Config' . DS . 'Schema',
'Model' . DS . 'Behavior',
'Model' . DS . 'Datasource',
'Console' . DS . 'Command' . DS . 'Task',
'Controller' . DS . 'Component',
'Lib',
'View' . DS . 'Helper',
'Test' . DS . 'Case' . DS . 'Controller' . DS . 'Component',
'Test' . DS . 'Case' . DS . 'View' . DS . 'Helper',
'Test' . DS . 'Case' . DS . 'Model' . DS . 'Behavior',
'Test' . DS . 'Fixture',
'Vendor',
'webroot'
);
foreach ($directories as $dir) {
$this->assertTrue(is_dir($path . DS . $dir), 'Missing directory for ' . $dir);
}
$Folder = new Folder($this->Task->path . 'BakeTestPlugin');
$Folder->delete();
}
/**
* test execute with no args, flowing into interactive,
*
* @return void
*/
public function testExecuteWithNoArgs() {
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('TestPlugin'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue($this->_testPath));
$this->Task->expects($this->at(2))->method('in')->will($this->returnValue('y'));
$path = $this->Task->path . 'TestPlugin';
$file = $path . DS . 'Controller' . DS . 'TestPluginAppController.php';
$this->Task->expects($this->at(3))->method('createFile')
->with($file, new PHPUnit_Framework_Constraint_IsAnything());
$file = $path . DS . 'Model' . DS . 'TestPluginAppModel.php';
$this->Task->expects($this->at(4))->method('createFile')
->with($file, new PHPUnit_Framework_Constraint_IsAnything());
$this->Task->args = array();
$this->Task->execute();
$Folder = new Folder($path);
$Folder->delete();
}
/**
* Test Execute
*
* @return void
*/
public function testExecuteWithOneArg() {
$this->Task->expects($this->at(0))->method('in')
->will($this->returnValue($this->_testPath));
$this->Task->expects($this->at(1))->method('in')
->will($this->returnValue('y'));
$path = $this->Task->path . 'BakeTestPlugin';
$file = $path . DS . 'Controller' . DS . 'BakeTestPluginAppController.php';
$this->Task->expects($this->at(2))->method('createFile')
->with($file, new PHPUnit_Framework_Constraint_IsAnything());
$path = $this->Task->path . 'BakeTestPlugin';
$file = $path . DS . 'Model' . DS . 'BakeTestPluginAppModel.php';
$this->Task->expects($this->at(3))->method('createFile')
->with($file, new PHPUnit_Framework_Constraint_IsAnything());
$this->Task->args = array('BakeTestPlugin');
$this->Task->execute();
$Folder = new Folder($this->Task->path . 'BakeTestPlugin');
$Folder->delete();
}
/**
* Test that findPath ignores paths that don't exist.
*
* @return void
*/
public function testFindPathNonExistant() {
$paths = App::path('plugins');
$last = count($paths);
array_unshift($paths, '/fake/path');
$paths[] = '/fake/path2';
$this->Task = $this->getMock('PluginTask',
array('in', 'out', 'err', 'createFile', '_stop'),
array($this->out, $this->out, $this->in)
);
$this->Task->path = TMP . 'tests' . DS;
// Make sure the added path is filtered out.
$this->Task->expects($this->exactly($last))
->method('out');
$this->Task->expects($this->once())
->method('in')
->will($this->returnValue($last));
$this->Task->findPath($paths);
}
}

View file

@ -0,0 +1,386 @@
<?php
/**
* ProjectTask Test file
*
* Test Case for project generation shell task
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.Console.Command.Task
* @since CakePHP v 1.3.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ShellDispatcher', 'Console');
App::uses('ConsoleOutput', 'Console');
App::uses('ConsoleInput', 'Console');
App::uses('Shell', 'Console');
App::uses('ProjectTask', 'Console/Command/Task');
App::uses('Folder', 'Utility');
App::uses('File', 'Utility');
/**
* ProjectTask Test class
*
* @package Cake.Test.Case.Console.Command.Task
*/
class ProjectTaskTest extends CakeTestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$out = $this->getMock('ConsoleOutput', array(), array(), '', false);
$in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->Task = $this->getMock('ProjectTask',
array('in', 'err', 'createFile', '_stop'),
array($out, $out, $in)
);
$this->Task->path = TMP . 'tests' . DS;
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
$Folder = new Folder($this->Task->path . 'bake_test_app');
$Folder->delete();
unset($this->Task);
}
/**
* creates a test project that is used for testing project task.
*
* @return void
*/
protected function _setupTestProject() {
$skel = CAKE . 'Console' . DS . 'Templates' . DS . 'skel';
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y'));
$this->Task->bake($this->Task->path . 'bake_test_app', $skel);
}
/**
* test bake() method and directory creation.
*
* @return void
*/
public function testBake() {
$this->_setupTestProject();
$path = $this->Task->path . 'bake_test_app';
$this->assertTrue(is_dir($path), 'No project dir %s');
$dirs = array(
'Config',
'Config' . DS . 'Schema',
'Console',
'Console' . DS . 'Command',
'Console' . DS . 'Templates',
'Console' . DS . 'Command' . DS . 'Task',
'Controller',
'Controller' . DS . 'Component',
'Locale',
'Model',
'Model' . DS . 'Behavior',
'Model' . DS . 'Datasource',
'Plugin',
'Test',
'Test' . DS . 'Case',
'Test' . DS . 'Case' . DS . 'Controller',
'Test' . DS . 'Case' . DS . 'Controller' . DS . 'Component',
'Test' . DS . 'Case' . DS . 'Model',
'Test' . DS . 'Case' . DS . 'Model' . DS . 'Behavior',
'Test' . DS . 'Fixture',
'Vendor',
'View',
'View' . DS . 'Helper',
'tmp',
'tmp' . DS . 'cache',
'tmp' . DS . 'cache' . DS . 'models',
'tmp' . DS . 'cache' . DS . 'persistent',
'tmp' . DS . 'cache' . DS . 'views',
'tmp' . DS . 'logs',
'tmp' . DS . 'sessions',
'tmp' . DS . 'tests',
'webroot',
'webroot' . DS . 'css',
'webroot' . DS . 'files',
'webroot' . DS . 'img',
'webroot' . DS . 'js',
);
foreach ($dirs as $dir) {
$this->assertTrue(is_dir($path . DS . $dir), 'Missing ' . $dir);
}
}
/**
* test bake with an absolute path.
*
* @return void
*/
public function testExecuteWithAbsolutePath() {
$path = $this->Task->args[0] = TMP . 'tests' . DS . 'bake_test_app';
$this->Task->params['skel'] = CAKE . 'Console' . DS . 'Templates' . DS . 'skel';
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y'));
$this->Task->execute();
$this->assertTrue(is_dir($this->Task->args[0]), 'No project dir');
$File = new File($path . DS . 'webroot' . DS . 'index.php');
$contents = $File->read();
$this->assertRegExp('/define\(\'CAKE_CORE_INCLUDE_PATH\', .*?DS/', $contents);
$File = new File($path . DS . 'webroot' . DS . 'test.php');
$contents = $File->read();
$this->assertRegExp('/define\(\'CAKE_CORE_INCLUDE_PATH\', .*?DS/', $contents);
}
/**
* test bake with CakePHP on the include path. The constants should remain commented out.
*
* @return void
*/
public function testExecuteWithCakeOnIncludePath() {
if (!function_exists('ini_set')) {
$this->markTestAsSkipped('Not access to ini_set, cannot proceed.');
}
$restore = ini_get('include_path');
ini_set('include_path', CAKE_CORE_INCLUDE_PATH . PATH_SEPARATOR . $restore);
$path = $this->Task->args[0] = TMP . 'tests' . DS . 'bake_test_app';
$this->Task->params['skel'] = CAKE . 'Console' . DS . 'Templates' . DS . 'skel';
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y'));
$this->Task->execute();
$this->assertTrue(is_dir($this->Task->args[0]), 'No project dir');
$contents = file_get_contents($path . DS . 'webroot' . DS . 'index.php');
$this->assertRegExp('#//define\(\'CAKE_CORE_INCLUDE_PATH#', $contents);
$contents = file_get_contents($path . DS . 'webroot' . DS . 'test.php');
$this->assertRegExp('#//define\(\'CAKE_CORE_INCLUDE_PATH#', $contents);
ini_set('include_path', $restore);
}
/**
* test bake() method with -empty flag, directory creation and empty files.
*
* @return void
*/
public function testBakeEmptyFlag() {
$this->Task->params['empty'] = true;
$this->_setupTestProject();
$path = $this->Task->path . 'bake_test_app';
$empty = array(
'Console' . DS . 'Command' . DS . 'Task' => 'empty',
'Controller' . DS . 'Component' => 'empty',
'Lib' => 'empty',
'Model' . DS . 'Behavior' => 'empty',
'Model' . DS . 'Datasource' => 'empty',
'Plugin' => 'empty',
'Test' . DS . 'Case' . DS . 'Model' . DS . 'Behavior' => 'empty',
'Test' . DS . 'Case' . DS . 'Controller' . DS . 'Component' => 'empty',
'Test' . DS . 'Case' . DS . 'View' . DS . 'Helper' => 'empty',
'Test' . DS . 'Fixture' => 'empty',
'Vendor' => 'empty',
'View' . DS . 'Elements' => 'empty',
'View' . DS . 'Scaffolds' => 'empty',
'tmp' . DS . 'cache' . DS . 'models' => 'empty',
'tmp' . DS . 'cache' . DS . 'persistent' => 'empty',
'tmp' . DS . 'cache' . DS . 'views' => 'empty',
'tmp' . DS . 'logs' => 'empty',
'tmp' . DS . 'sessions' => 'empty',
'tmp' . DS . 'tests' => 'empty',
'webroot' . DS . 'js' => 'empty',
'webroot' . DS . 'files' => 'empty'
);
foreach ($empty as $dir => $file) {
$this->assertTrue(is_file($path . DS . $dir . DS . $file), sprintf('Missing %s file in %s', $file, $dir));
}
}
/**
* test generation of Security.salt
*
* @return void
*/
public function testSecuritySaltGeneration() {
$this->_setupTestProject();
$path = $this->Task->path . 'bake_test_app' . DS;
$result = $this->Task->securitySalt($path);
$this->assertTrue($result);
$File = new File($path . 'Config' . DS . 'core.php');
$contents = $File->read();
$this->assertNotRegExp('/DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi/', $contents, 'Default Salt left behind. %s');
}
/**
* test generation of Security.cipherSeed
*
* @return void
*/
public function testSecurityCipherSeedGeneration() {
$this->_setupTestProject();
$path = $this->Task->path . 'bake_test_app' . DS;
$result = $this->Task->securityCipherSeed($path);
$this->assertTrue($result);
$File = new File($path . 'Config' . DS . 'core.php');
$contents = $File->read();
$this->assertNotRegExp('/76859309657453542496749683645/', $contents, 'Default CipherSeed left behind. %s');
}
/**
* test generation of cache prefix
*
* @return void
*/
public function testCachePrefixGeneration() {
$this->_setupTestProject();
$path = $this->Task->path . 'bake_test_app' . DS;
$result = $this->Task->cachePrefix($path);
$this->assertTrue($result);
$File = new File($path . 'Config' . DS . 'core.php');
$contents = $File->read();
$this->assertRegExp('/\$prefix = \'.+\';/', $contents, '$prefix is not defined');
$this->assertNotRegExp('/\$prefix = \'myapp_\';/', $contents, 'Default cache prefix left behind. %s');
}
/**
* Test that index.php is generated correctly.
*
* @return void
*/
public function testIndexPhpGeneration() {
$this->_setupTestProject();
$path = $this->Task->path . 'bake_test_app' . DS;
$this->Task->corePath($path);
$File = new File($path . 'webroot' . DS . 'index.php');
$contents = $File->read();
$this->assertNotRegExp('/define\(\'CAKE_CORE_INCLUDE_PATH\', ROOT/', $contents);
$File = new File($path . 'webroot' . DS . 'test.php');
$contents = $File->read();
$this->assertNotRegExp('/define\(\'CAKE_CORE_INCLUDE_PATH\', ROOT/', $contents);
}
/**
* test getPrefix method, and that it returns Routing.prefix or writes to config file.
*
* @return void
*/
public function testGetPrefix() {
Configure::write('Routing.prefixes', array('admin'));
$result = $this->Task->getPrefix();
$this->assertEquals('admin_', $result);
Configure::write('Routing.prefixes', null);
$this->_setupTestProject();
$this->Task->configPath = $this->Task->path . 'bake_test_app' . DS . 'Config' . DS;
$this->Task->expects($this->once())->method('in')->will($this->returnValue('super_duper_admin'));
$result = $this->Task->getPrefix();
$this->assertEquals('super_duper_admin_', $result);
$File = new File($this->Task->configPath . 'core.php');
$File->delete();
}
/**
* test cakeAdmin() writing core.php
*
* @return void
*/
public function testCakeAdmin() {
$File = new File(APP . 'Config' . DS . 'core.php');
$contents = $File->read();
$File = new File(TMP . 'tests' . DS . 'core.php');
$File->write($contents);
Configure::write('Routing.prefixes', null);
$this->Task->configPath = TMP . 'tests' . DS;
$result = $this->Task->cakeAdmin('my_prefix');
$this->assertTrue($result);
$this->assertEquals(Configure::read('Routing.prefixes'), array('my_prefix'));
$File->delete();
}
/**
* test getting the prefix with more than one prefix setup
*
* @return void
*/
public function testGetPrefixWithMultiplePrefixes() {
Configure::write('Routing.prefixes', array('admin', 'ninja', 'shinobi'));
$this->_setupTestProject();
$this->Task->configPath = $this->Task->path . 'bake_test_app' . DS . 'Config' . DS;
$this->Task->expects($this->once())->method('in')->will($this->returnValue(2));
$result = $this->Task->getPrefix();
$this->assertEquals('ninja_', $result);
}
/**
* Test execute method with one param to destination folder.
*
* @return void
*/
public function testExecute() {
$this->Task->params['skel'] = CAKE . 'Console' . DS . 'Templates' . DS . 'skel';
$this->Task->params['working'] = TMP . 'tests' . DS;
$path = $this->Task->path . 'bake_test_app';
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue($path));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue('y'));
$this->Task->execute();
$this->assertTrue(is_dir($path), 'No project dir');
$this->assertTrue(is_dir($path . DS . 'Controller'), 'No controllers dir ');
$this->assertTrue(is_dir($path . DS . 'Controller' . DS . 'Component'), 'No components dir ');
$this->assertTrue(is_dir($path . DS . 'Model'), 'No models dir');
$this->assertTrue(is_dir($path . DS . 'View'), 'No views dir');
$this->assertTrue(is_dir($path . DS . 'View' . DS . 'Helper'), 'No helpers dir');
$this->assertTrue(is_dir($path . DS . 'Test'), 'No tests dir');
$this->assertTrue(is_dir($path . DS . 'Test' . DS . 'Case'), 'No cases dir');
$this->assertTrue(is_dir($path . DS . 'Test' . DS . 'Fixture'), 'No fixtures dir');
}
/**
* test console path
*
* @return void
*/
public function testConsolePath() {
$this->_setupTestProject();
$path = $this->Task->path . 'bake_test_app' . DS;
$result = $this->Task->consolePath($path);
$this->assertTrue($result);
$File = new File($path . 'Console' . DS . 'cake.php');
$contents = $File->read();
$this->assertNotRegExp('/__CAKE_PATH__/', $contents, 'Console path placeholder left behind.');
}
}

View file

@ -0,0 +1,164 @@
<?php
/**
* TemplateTask file
*
* Test Case for TemplateTask generation shell task
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Console.Command.Task
* @since CakePHP(tm) v 1.3
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ShellDispatcher', 'Console');
App::uses('ConsoleOutput', 'Console');
App::uses('ConsoleInput', 'Console');
App::uses('Shell', 'Console');
App::uses('TemplateTask', 'Console/Command/Task');
/**
* TemplateTaskTest class
*
* @package Cake.Test.Case.Console.Command.Task
*/
class TemplateTaskTest extends CakeTestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$out = $this->getMock('ConsoleOutput', array(), array(), '', false);
$in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->Task = $this->getMock('TemplateTask',
array('in', 'err', 'createFile', '_stop', 'clear'),
array($out, $out, $in)
);
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->Task);
}
/**
* test that set sets variables
*
* @return void
*/
public function testSet() {
$this->Task->set('one', 'two');
$this->assertTrue(isset($this->Task->templateVars['one']));
$this->assertEquals('two', $this->Task->templateVars['one']);
$this->Task->set(array('one' => 'three', 'four' => 'five'));
$this->assertTrue(isset($this->Task->templateVars['one']));
$this->assertEquals('three', $this->Task->templateVars['one']);
$this->assertTrue(isset($this->Task->templateVars['four']));
$this->assertEquals('five', $this->Task->templateVars['four']);
$this->Task->templateVars = array();
$this->Task->set(array(3 => 'three', 4 => 'four'));
$this->Task->set(array(1 => 'one', 2 => 'two'));
$expected = array(3 => 'three', 4 => 'four', 1 => 'one', 2 => 'two');
$this->assertEquals($expected, $this->Task->templateVars);
}
/**
* test finding themes installed in
*
* @return void
*/
public function testFindingInstalledThemesForBake() {
$consoleLibs = CAKE . 'Console' . DS;
$this->Task->initialize();
$this->assertEquals($this->Task->templatePaths['default'], $consoleLibs . 'Templates' . DS . 'default' . DS);
}
/**
* test getting the correct theme name. Ensure that with only one theme, or a theme param
* that the user is not bugged. If there are more, find and return the correct theme name
*
* @return void
*/
public function testGetThemePath() {
$defaultTheme = CAKE . 'Console' . DS . 'Templates' . DS . 'default' . DS;
$this->Task->templatePaths = array('default' => $defaultTheme);
$this->Task->expects($this->exactly(1))->method('in')->will($this->returnValue('1'));
$result = $this->Task->getThemePath();
$this->assertEquals($defaultTheme, $result);
$this->Task->templatePaths = array('other' => '/some/path', 'default' => $defaultTheme);
$this->Task->params['theme'] = 'other';
$result = $this->Task->getThemePath();
$this->assertEquals('/some/path', $result);
$this->Task->params = array();
$result = $this->Task->getThemePath();
$this->assertEquals('/some/path', $result);
$this->assertEquals('other', $this->Task->params['theme']);
}
/**
* test generate
*
* @return void
*/
public function testGenerate() {
App::build(array(
'Console' => array(
CAKE . 'Test' . DS . 'test_app' . DS . 'Console' . DS
)
));
$this->Task->initialize();
$this->Task->expects($this->any())->method('in')->will($this->returnValue(1));
$result = $this->Task->generate('classes', 'test_object', array('test' => 'foo'));
$expected = "I got rendered\nfoo";
$this->assertTextEquals($expected, $result);
}
/**
* test generate with a missing template in the chosen theme.
* ensure fallback to default works.
*
* @return void
*/
public function testGenerateWithTemplateFallbacks() {
App::build(array(
'Console' => array(
CAKE . 'Test' . DS . 'test_app' . DS . 'Console' . DS,
CAKE_CORE_INCLUDE_PATH . DS . 'console' . DS
)
));
$this->Task->initialize();
$this->Task->params['theme'] = 'test';
$this->Task->set(array(
'model' => 'Article',
'table' => 'articles',
'import' => false,
'records' => false,
'schema' => ''
));
$result = $this->Task->generate('classes', 'fixture');
$this->assertRegExp('/ArticleFixture extends CakeTestFixture/', $result);
}
}

View file

@ -0,0 +1,755 @@
<?php
/**
* TestTaskTest file
*
* Test Case for test generation shell task
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.Console.Command.Task
* @since CakePHP v 1.2.0.7726
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ShellDispatcher', 'Console');
App::uses('ConsoleOutput', 'Console');
App::uses('ConsoleInput', 'Console');
App::uses('Shell', 'Console');
App::uses('TestTask', 'Console/Command/Task');
App::uses('TemplateTask', 'Console/Command/Task');
App::uses('Controller', 'Controller');
App::uses('Model', 'Model');
/**
* Test Article model
*
* @package Cake.Test.Case.Console.Command.Task
*/
class TestTaskArticle extends Model {
/**
* Table name to use
*
* @var string
*/
public $useTable = 'articles';
/**
* HasMany Associations
*
* @var array
*/
public $hasMany = array(
'Comment' => array(
'className' => 'TestTask.TestTaskComment',
'foreignKey' => 'article_id',
)
);
/**
* Has and Belongs To Many Associations
*
* @var array
*/
public $hasAndBelongsToMany = array(
'Tag' => array(
'className' => 'TestTaskTag',
'joinTable' => 'articles_tags',
'foreignKey' => 'article_id',
'associationForeignKey' => 'tag_id'
)
);
/**
* Example public method
*
* @return void
*/
public function doSomething() {
}
/**
* Example Secondary public method
*
* @return void
*/
public function doSomethingElse() {
}
/**
* Example protected method
*
* @return void
*/
protected function _innerMethod() {
}
}
/**
* Tag Testing Model
*
* @package Cake.Test.Case.Console.Command.Task
*/
class TestTaskTag extends Model {
/**
* Table name
*
* @var string
*/
public $useTable = 'tags';
/**
* Has and Belongs To Many Associations
*
* @var array
*/
public $hasAndBelongsToMany = array(
'Article' => array(
'className' => 'TestTaskArticle',
'joinTable' => 'articles_tags',
'foreignKey' => 'tag_id',
'associationForeignKey' => 'article_id'
)
);
}
/**
* Simulated plugin
*
* @package Cake.Test.Case.Console.Command.Task
*/
class TestTaskAppModel extends Model {
}
/**
* Testing AppMode (TaskComment)
*
* @package Cake.Test.Case.Console.Command.Task
*/
class TestTaskComment extends TestTaskAppModel {
/**
* Table name
*
* @var string
*/
public $useTable = 'comments';
/**
* Belongs To Associations
*
* @var array
*/
public $belongsTo = array(
'Article' => array(
'className' => 'TestTaskArticle',
'foreignKey' => 'article_id',
)
);
}
/**
* Test Task Comments Controller
*
* @package Cake.Test.Case.Console.Command.Task
*/
class TestTaskCommentsController extends Controller {
/**
* Models to use
*
* @var array
*/
public $uses = array('TestTaskComment', 'TestTaskTag');
}
/**
* TestTaskTest class
*
* @package Cake.Test.Case.Console.Command.Task
*/
class TestTaskTest extends CakeTestCase {
/**
* Fixtures
*
* @var string
*/
public $fixtures = array('core.article', 'core.comment', 'core.articles_tag', 'core.tag');
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$out = $this->getMock('ConsoleOutput', array(), array(), '', false);
$in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->Task = $this->getMock('TestTask',
array('in', 'err', 'createFile', '_stop', 'isLoadableClass'),
array($out, $out, $in)
);
$this->Task->name = 'Test';
$this->Task->Template = new TemplateTask($out, $out, $in);
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->Task);
CakePlugin::unload();
}
/**
* Test that file path generation doesn't continuously append paths.
*
* @return void
*/
public function testFilePathGenerationModelRepeated() {
$this->Task->expects($this->never())->method('err');
$this->Task->expects($this->never())->method('_stop');
$file = TESTS . 'Case' . DS . 'Model' . DS . 'MyClassTest.php';
$this->Task->expects($this->at(1))->method('createFile')
->with($file, $this->anything());
$this->Task->expects($this->at(3))->method('createFile')
->with($file, $this->anything());
$file = TESTS . 'Case' . DS . 'Controller' . DS . 'CommentsControllerTest.php';
$this->Task->expects($this->at(5))->method('createFile')
->with($file, $this->anything());
$this->Task->bake('Model', 'MyClass');
$this->Task->bake('Model', 'MyClass');
$this->Task->bake('Controller', 'Comments');
}
/**
* Test that method introspection pulls all relevant non parent class
* methods into the test case.
*
* @return void
*/
public function testMethodIntrospection() {
$result = $this->Task->getTestableMethods('TestTaskArticle');
$expected = array('dosomething', 'dosomethingelse');
$this->assertEquals($expected, array_map('strtolower', $result));
}
/**
* test that the generation of fixtures works correctly.
*
* @return void
*/
public function testFixtureArrayGenerationFromModel() {
$subject = ClassRegistry::init('TestTaskArticle');
$result = $this->Task->generateFixtureList($subject);
$expected = array('plugin.test_task.test_task_comment', 'app.articles_tags',
'app.test_task_article', 'app.test_task_tag');
$this->assertEquals(sort($expected), sort($result));
}
/**
* test that the generation of fixtures works correctly.
*
* @return void
*/
public function testFixtureArrayGenerationFromController() {
$subject = new TestTaskCommentsController();
$result = $this->Task->generateFixtureList($subject);
$expected = array('plugin.test_task.test_task_comment', 'app.articles_tags',
'app.test_task_article', 'app.test_task_tag');
$this->assertEquals(sort($expected), sort($result));
}
/**
* test user interaction to get object type
*
* @return void
*/
public function testGetObjectType() {
$this->Task->expects($this->once())->method('_stop');
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('q'));
$this->Task->expects($this->at(2))->method('in')->will($this->returnValue(2));
$this->Task->getObjectType();
$result = $this->Task->getObjectType();
$this->assertEquals($this->Task->classTypes['Controller'], $result);
}
/**
* creating test subjects should clear the registry so the registry is always fresh
*
* @return void
*/
public function testRegistryClearWhenBuildingTestObjects() {
ClassRegistry::flush();
$model = ClassRegistry::init('TestTaskComment');
$model->bindModel(array(
'belongsTo' => array(
'Random' => array(
'className' => 'TestTaskArticle',
'foreignKey' => 'article_id',
)
)
));
$keys = ClassRegistry::keys();
$this->assertTrue(in_array('test_task_comment', $keys));
$this->Task->buildTestSubject('Model', 'TestTaskComment');
$keys = ClassRegistry::keys();
$this->assertFalse(in_array('random', $keys));
}
/**
* test that getClassName returns the user choice as a class name.
*
* @return void
*/
public function testGetClassName() {
$objects = App::objects('model');
$this->skipIf(empty($objects), 'No models in app.');
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('MyCustomClass'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue(1));
$result = $this->Task->getClassName('Model');
$this->assertEquals('MyCustomClass', $result);
$result = $this->Task->getClassName('Model');
$options = App::objects('model');
$this->assertEquals($options[0], $result);
}
/**
* Test the user interaction for defining additional fixtures.
*
* @return void
*/
public function testGetUserFixtures() {
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y'));
$this->Task->expects($this->at(1))->method('in')
->will($this->returnValue('app.pizza, app.topping, app.side_dish'));
$result = $this->Task->getUserFixtures();
$expected = array('app.pizza', 'app.topping', 'app.side_dish');
$this->assertEquals($expected, $result);
}
/**
* test that resolving class names works
*
* @return void
*/
public function testGetRealClassname() {
$result = $this->Task->getRealClassname('Model', 'Post');
$this->assertEquals('Post', $result);
$result = $this->Task->getRealClassname('Controller', 'Posts');
$this->assertEquals('PostsController', $result);
$result = $this->Task->getRealClassname('Controller', 'PostsController');
$this->assertEquals('PostsController', $result);
$result = $this->Task->getRealClassname('Controller', 'AlertTypes');
$this->assertEquals('AlertTypesController', $result);
$result = $this->Task->getRealClassname('Helper', 'Form');
$this->assertEquals('FormHelper', $result);
$result = $this->Task->getRealClassname('Helper', 'FormHelper');
$this->assertEquals('FormHelper', $result);
$result = $this->Task->getRealClassname('Behavior', 'Containable');
$this->assertEquals('ContainableBehavior', $result);
$result = $this->Task->getRealClassname('Behavior', 'ContainableBehavior');
$this->assertEquals('ContainableBehavior', $result);
$result = $this->Task->getRealClassname('Component', 'Auth');
$this->assertEquals('AuthComponent', $result);
}
/**
* test baking files. The conditionally run tests are known to fail in PHP4
* as PHP4 class names are all lower case, breaking the plugin path inflection.
*
* @return void
*/
public function testBakeModelTest() {
$this->Task->expects($this->once())->method('createFile')->will($this->returnValue(true));
$this->Task->expects($this->once())->method('isLoadableClass')->will($this->returnValue(true));
$result = $this->Task->bake('Model', 'TestTaskArticle');
$this->assertContains("App::uses('TestTaskArticle', 'Model')", $result);
$this->assertContains('class TestTaskArticleTest extends CakeTestCase', $result);
$this->assertContains('function setUp()', $result);
$this->assertContains("\$this->TestTaskArticle = ClassRegistry::init('TestTaskArticle')", $result);
$this->assertContains('function tearDown()', $result);
$this->assertContains('unset($this->TestTaskArticle)', $result);
$this->assertContains('function testDoSomething()', $result);
$this->assertContains('function testDoSomethingElse()', $result);
$this->assertContains('$this->markTestIncomplete(\'testDoSomething not implemented.\')', $result);
$this->assertContains('$this->markTestIncomplete(\'testDoSomethingElse not implemented.\')', $result);
$this->assertContains("'app.test_task_article'", $result);
$this->assertContains("'app.test_task_comment'", $result);
$this->assertContains("'app.test_task_tag'", $result);
$this->assertContains("'app.articles_tag'", $result);
}
/**
* test baking controller test files
*
* @return void
*/
public function testBakeControllerTest() {
$this->Task->expects($this->once())->method('createFile')->will($this->returnValue(true));
$this->Task->expects($this->once())->method('isLoadableClass')->will($this->returnValue(true));
$result = $this->Task->bake('Controller', 'TestTaskComments');
$this->assertContains("App::uses('TestTaskCommentsController', 'Controller')", $result);
$this->assertContains('class TestTaskCommentsControllerTest extends ControllerTestCase', $result);
$this->assertNotContains('function setUp()', $result);
$this->assertNotContains("\$this->TestTaskComments = new TestTaskCommentsController()", $result);
$this->assertNotContains("\$this->TestTaskComments->constructClasses()", $result);
$this->assertNotContains('function tearDown()', $result);
$this->assertNotContains('unset($this->TestTaskComments)', $result);
$this->assertContains("'app.test_task_article'", $result);
$this->assertContains("'app.test_task_comment'", $result);
$this->assertContains("'app.test_task_tag'", $result);
$this->assertContains("'app.articles_tag'", $result);
}
/**
* test baking component test files,
*
* @return void
*/
public function testBakeComponentTest() {
$this->Task->expects($this->once())->method('createFile')->will($this->returnValue(true));
$result = $this->Task->bake('Component', 'Example');
$this->assertContains("App::uses('Component', 'Controller')", $result);
$this->assertContains("App::uses('ComponentCollection', 'Controller')", $result);
$this->assertContains("App::uses('ExampleComponent', 'Controller/Component')", $result);
$this->assertContains('class ExampleComponentTest extends CakeTestCase', $result);
$this->assertContains('function setUp()', $result);
$this->assertContains("\$Collection = new ComponentCollection()", $result);
$this->assertContains("\$this->Example = new ExampleComponent(\$Collection)", $result);
$this->assertContains('function tearDown()', $result);
$this->assertContains('unset($this->Example)', $result);
}
/**
* test baking behavior test files,
*
* @return void
*/
public function testBakeBehaviorTest() {
$this->Task->expects($this->once())->method('createFile')->will($this->returnValue(true));
$result = $this->Task->bake('Behavior', 'Example');
$this->assertContains("App::uses('ExampleBehavior', 'Model/Behavior')", $result);
$this->assertContains('class ExampleBehaviorTest extends CakeTestCase', $result);
$this->assertContains('function setUp()', $result);
$this->assertContains("\$this->Example = new ExampleBehavior()", $result);
$this->assertContains('function tearDown()', $result);
$this->assertContains('unset($this->Example)', $result);
}
/**
* test baking helper test files,
*
* @return void
*/
public function testBakeHelperTest() {
$this->Task->expects($this->once())->method('createFile')->will($this->returnValue(true));
$result = $this->Task->bake('Helper', 'Example');
$this->assertContains("App::uses('ExampleHelper', 'View/Helper')", $result);
$this->assertContains('class ExampleHelperTest extends CakeTestCase', $result);
$this->assertContains('function setUp()', $result);
$this->assertContains("\$View = new View()", $result);
$this->assertContains("\$this->Example = new ExampleHelper(\$View)", $result);
$this->assertContains('function tearDown()', $result);
$this->assertContains('unset($this->Example)', $result);
}
/**
* test Constructor generation ensure that constructClasses is called for controllers
*
* @return void
*/
public function testGenerateConstructor() {
$result = $this->Task->generateConstructor('controller', 'PostsController', null);
$expected = array('', '', '');
$this->assertEquals($expected, $result);
$result = $this->Task->generateConstructor('model', 'Post', null);
$expected = array('', "ClassRegistry::init('Post');\n", '');
$this->assertEquals($expected, $result);
$result = $this->Task->generateConstructor('helper', 'FormHelper', null);
$expected = array("\$View = new View();\n", "new FormHelper(\$View);\n", '');
$this->assertEquals($expected, $result);
}
/**
* Test generateUses()
*
* @return void
*/
public function testGenerateUses() {
$result = $this->Task->generateUses('model', 'Model', 'Post');
$expected = array(
array('Post', 'Model')
);
$this->assertEquals($expected, $result);
$result = $this->Task->generateUses('controller', 'Controller', 'PostsController');
$expected = array(
array('PostsController', 'Controller')
);
$this->assertEquals($expected, $result);
$result = $this->Task->generateUses('helper', 'View/Helper', 'FormHelper');
$expected = array(
array('View', 'View'),
array('Helper', 'View'),
array('FormHelper', 'View/Helper'),
);
$this->assertEquals($expected, $result);
$result = $this->Task->generateUses('component', 'Controller/Component', 'AuthComponent');
$expected = array(
array('ComponentCollection', 'Controller'),
array('Component', 'Controller'),
array('AuthComponent', 'Controller/Component')
);
$this->assertEquals($expected, $result);
}
/**
* Test that mock class generation works for the appropriate classes
*
* @return void
*/
public function testMockClassGeneration() {
$result = $this->Task->hasMockClass('controller');
$this->assertTrue($result);
}
/**
* test bake() with a -plugin param
*
* @return void
*/
public function testBakeWithPlugin() {
$this->Task->plugin = 'TestTest';
//fake plugin path
CakePlugin::load('TestTest', array('path' => APP . 'Plugin' . DS . 'TestTest' . DS));
$path = APP . 'Plugin' . DS . 'TestTest' . DS . 'Test' . DS . 'Case' . DS . 'View' . DS . 'Helper' . DS . 'FormHelperTest.php';
$this->Task->expects($this->once())->method('createFile')
->with($path, $this->anything());
$this->Task->bake('Helper', 'Form');
CakePlugin::unload();
}
/**
* test interactive with plugins lists from the plugin
*
* @return void
*/
public function testInteractiveWithPlugin() {
$testApp = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS;
App::build(array(
'Plugin' => array($testApp)
), App::RESET);
CakePlugin::load('TestPlugin');
$this->Task->plugin = 'TestPlugin';
$path = $testApp . 'TestPlugin' . DS . 'Test' . DS . 'Case' . DS . 'View' . DS . 'Helper' . DS . 'OtherHelperTest.php';
$this->Task->expects($this->any())
->method('in')
->will($this->onConsecutiveCalls(
5, //helper
1 //OtherHelper
));
$this->Task->expects($this->once())
->method('createFile')
->with($path, $this->anything());
$this->Task->stdout->expects($this->at(21))
->method('write')
->with('1. OtherHelperHelper');
$this->Task->execute();
}
public static function caseFileNameProvider() {
return array(
array('Model', 'Post', 'Case' . DS . 'Model' . DS . 'PostTest.php'),
array('Helper', 'Form', 'Case' . DS . 'View' . DS . 'Helper' . DS . 'FormHelperTest.php'),
array('Controller', 'Posts', 'Case' . DS . 'Controller' . DS . 'PostsControllerTest.php'),
array('Behavior', 'Containable', 'Case' . DS . 'Model' . DS . 'Behavior' . DS . 'ContainableBehaviorTest.php'),
array('Component', 'Auth', 'Case' . DS . 'Controller' . DS . 'Component' . DS . 'AuthComponentTest.php'),
array('model', 'Post', 'Case' . DS . 'Model' . DS . 'PostTest.php'),
array('helper', 'Form', 'Case' . DS . 'View' . DS . 'Helper' . DS . 'FormHelperTest.php'),
array('controller', 'Posts', 'Case' . DS . 'Controller' . DS . 'PostsControllerTest.php'),
array('behavior', 'Containable', 'Case' . DS . 'Model' . DS . 'Behavior' . DS . 'ContainableBehaviorTest.php'),
array('component', 'Auth', 'Case' . DS . 'Controller' . DS . 'Component' . DS . 'AuthComponentTest.php'),
);
}
/**
* Test filename generation for each type + plugins
*
* @dataProvider caseFileNameProvider
* @return void
*/
public function testTestCaseFileName($type, $class, $expected) {
$this->Task->path = DS . 'my' . DS . 'path' . DS . 'tests' . DS;
$result = $this->Task->testCaseFileName($type, $class);
$expected = $this->Task->path . $expected;
$this->assertEquals($expected, $result);
}
/**
* Test filename generation for plugins.
*
* @return void
*/
public function testTestCaseFileNamePlugin() {
$this->Task->path = DS . 'my' . DS . 'path' . DS . 'tests' . DS;
CakePlugin::load('TestTest', array('path' => APP . 'Plugin' . DS . 'TestTest' . DS));
$this->Task->plugin = 'TestTest';
$result = $this->Task->testCaseFileName('Model', 'Post');
$expected = APP . 'Plugin' . DS . 'TestTest' . DS . 'Test' . DS . 'Case' . DS . 'Model' . DS . 'PostTest.php';
$this->assertEquals($expected, $result);
}
/**
* test execute with a type defined
*
* @return void
*/
public function testExecuteWithOneArg() {
$this->Task->args[0] = 'Model';
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('TestTaskTag'));
$this->Task->expects($this->once())->method('isLoadableClass')->will($this->returnValue(true));
$this->Task->expects($this->once())->method('createFile')
->with(
$this->anything(),
$this->stringContains('class TestTaskTagTest extends CakeTestCase')
);
$this->Task->execute();
}
/**
* test execute with type and class name defined
*
* @return void
*/
public function testExecuteWithTwoArgs() {
$this->Task->args = array('Model', 'TestTaskTag');
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('TestTaskTag'));
$this->Task->expects($this->once())->method('createFile')
->with(
$this->anything(),
$this->stringContains('class TestTaskTagTest extends CakeTestCase')
);
$this->Task->expects($this->any())->method('isLoadableClass')->will($this->returnValue(true));
$this->Task->execute();
}
/**
* test execute with type and class name defined and lower case.
*
* @return void
*/
public function testExecuteWithTwoArgsLowerCase() {
$this->Task->args = array('model', 'TestTaskTag');
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('TestTaskTag'));
$this->Task->expects($this->once())->method('createFile')
->with(
$this->anything(),
$this->stringContains('class TestTaskTagTest extends CakeTestCase')
);
$this->Task->expects($this->any())->method('isLoadableClass')->will($this->returnValue(true));
$this->Task->execute();
}
/**
* Data provider for mapType() tests.
*
* @return array
*/
public static function mapTypeProvider() {
return array(
array('controller', null, 'Controller'),
array('Controller', null, 'Controller'),
array('component', null, 'Controller/Component'),
array('Component', null, 'Controller/Component'),
array('model', null, 'Model'),
array('Model', null, 'Model'),
array('behavior', null, 'Model/Behavior'),
array('Behavior', null, 'Model/Behavior'),
array('helper', null, 'View/Helper'),
array('Helper', null, 'View/Helper'),
array('Helper', 'DebugKit', 'DebugKit.View/Helper'),
);
}
/**
* Test that mapType returns the correct package names.
*
* @dataProvider mapTypeProvider
* @return void
*/
public function testMapType($original, $plugin, $expected) {
$this->assertEquals($expected, $this->Task->mapType($original, $plugin));
}
}

View file

@ -0,0 +1,699 @@
<?php
/**
* ViewTask Test file
*
* Test Case for view generation shell task
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.Console.Command.Task
* @since CakePHP v 1.2.0.7726
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ShellDispatcher', 'Console');
App::uses('ConsoleOutput', 'Console');
App::uses('ConsoleInput', 'Console');
App::uses('Shell', 'Console');
App::uses('ViewTask', 'Console/Command/Task');
App::uses('ControllerTask', 'Console/Command/Task');
App::uses('TemplateTask', 'Console/Command/Task');
App::uses('ProjectTask', 'Console/Command/Task');
App::uses('DbConfigTask', 'Console/Command/Task');
App::uses('Model', 'Model');
App::uses('Controller', 'Controller');
App::uses('AppController', 'Controller');
/**
* Test View Task Comment Model
*
* @package Cake.Test.Case.Console.Command.Task
*/
class ViewTaskComment extends Model {
/**
* Table name
*
* @var string
*/
public $useTable = 'comments';
/**
* Belongs To Associations
*
* @var array
*/
public $belongsTo = array(
'Article' => array(
'className' => 'TestTest.ViewTaskArticle',
'foreignKey' => 'article_id'
)
);
}
/**
* Test View Task Article Model
*
* @package Cake.Test.Case.Console.Command.Task
*/
class ViewTaskArticle extends Model {
/**
* Table name
*
* @var string
*/
public $useTable = 'articles';
}
/**
* Test View Task Comments Controller
*
* @package Cake.Test.Case.Console.Command.Task
*/
class ViewTaskCommentsController extends Controller {
/**
* Testing public controller action
*
* @return void
*/
public function index() {
}
/**
* Testing public controller action
*
* @return void
*/
public function add() {
}
}
/**
* Test View Task Articles Controller
*
* @package Cake.Test.Case.Console.Command.Task
*/
class ViewTaskArticlesController extends Controller {
/**
* Test public controller action
*
* @return void
*/
public function index() {
}
/**
* Test public controller action
*
* @return void
*/
public function add() {
}
/**
* Test admin prefixed controller action
*
* @return void
*/
public function admin_index() {
}
/**
* Test admin prefixed controller action
*
* @return void
*/
public function admin_add() {
}
/**
* Test admin prefixed controller action
*
* @return void
*/
public function admin_view() {
}
/**
* Test admin prefixed controller action
*
* @return void
*/
public function admin_edit() {
}
/**
* Test admin prefixed controller action
*
* @return void
*/
public function admin_delete() {
}
}
/**
* ViewTaskTest class
*
* @package Cake.Test.Case.Console.Command.Task
*/
class ViewTaskTest extends CakeTestCase {
/**
* Fixtures
*
* @var array
*/
public $fixtures = array('core.article', 'core.comment', 'core.articles_tag', 'core.tag');
/**
* setUp method
*
* Ensure that the default theme is used
*
* @return void
*/
public function setUp() {
parent::setUp();
$out = $this->getMock('ConsoleOutput', array(), array(), '', false);
$in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->Task = $this->getMock('ViewTask',
array('in', 'err', 'createFile', '_stop'),
array($out, $out, $in)
);
$this->Task->Template = new TemplateTask($out, $out, $in);
$this->Task->Controller = $this->getMock('ControllerTask', array(), array($out, $out, $in));
$this->Task->Project = $this->getMock('ProjectTask', array(), array($out, $out, $in));
$this->Task->DbConfig = $this->getMock('DbConfigTask', array(), array($out, $out, $in));
$this->Task->path = TMP;
$this->Task->Template->params['theme'] = 'default';
$this->Task->Template->templatePaths = array('default' => CAKE . 'Console' . DS . 'Templates' . DS . 'default' . DS);
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->Task, $this->Dispatch);
}
/**
* Test getContent and parsing of Templates.
*
* @return void
*/
public function testGetContent() {
$vars = array(
'modelClass' => 'TestViewModel',
'schema' => array(),
'primaryKey' => 'id',
'displayField' => 'name',
'singularVar' => 'testViewModel',
'pluralVar' => 'testViewModels',
'singularHumanName' => 'Test View Model',
'pluralHumanName' => 'Test View Models',
'fields' => array('id', 'name', 'body'),
'associations' => array()
);
$result = $this->Task->getContent('view', $vars);
$this->assertRegExp('/Delete Test View Model/', $result);
$this->assertRegExp('/Edit Test View Model/', $result);
$this->assertRegExp('/List Test View Models/', $result);
$this->assertRegExp('/New Test View Model/', $result);
$this->assertRegExp('/testViewModel\[\'TestViewModel\'\]\[\'id\'\]/', $result);
$this->assertRegExp('/testViewModel\[\'TestViewModel\'\]\[\'name\'\]/', $result);
$this->assertRegExp('/testViewModel\[\'TestViewModel\'\]\[\'body\'\]/', $result);
}
/**
* test getContent() using an admin_prefixed action.
*
* @return void
*/
public function testGetContentWithAdminAction() {
$_back = Configure::read('Routing');
Configure::write('Routing.prefixes', array('admin'));
$vars = array(
'modelClass' => 'TestViewModel',
'schema' => array(),
'primaryKey' => 'id',
'displayField' => 'name',
'singularVar' => 'testViewModel',
'pluralVar' => 'testViewModels',
'singularHumanName' => 'Test View Model',
'pluralHumanName' => 'Test View Models',
'fields' => array('id', 'name', 'body'),
'associations' => array()
);
$result = $this->Task->getContent('admin_view', $vars);
$this->assertRegExp('/Delete Test View Model/', $result);
$this->assertRegExp('/Edit Test View Model/', $result);
$this->assertRegExp('/List Test View Models/', $result);
$this->assertRegExp('/New Test View Model/', $result);
$this->assertRegExp('/testViewModel\[\'TestViewModel\'\]\[\'id\'\]/', $result);
$this->assertRegExp('/testViewModel\[\'TestViewModel\'\]\[\'name\'\]/', $result);
$this->assertRegExp('/testViewModel\[\'TestViewModel\'\]\[\'body\'\]/', $result);
$result = $this->Task->getContent('admin_add', $vars);
$this->assertRegExp("/input\('name'\)/", $result);
$this->assertRegExp("/input\('body'\)/", $result);
$this->assertRegExp('/List Test View Models/', $result);
Configure::write('Routing', $_back);
}
/**
* test Bake method
*
* @return void
*/
public function testBakeView() {
$this->Task->controllerName = 'ViewTaskComments';
$this->Task->expects($this->at(0))->method('createFile')
->with(
TMP . 'ViewTaskComments' . DS . 'view.ctp',
$this->stringContains('View Task Articles')
);
$this->Task->bake('view', true);
}
/**
* test baking an edit file
*
* @return void
*/
public function testBakeEdit() {
$this->Task->controllerName = 'ViewTaskComments';
$this->Task->expects($this->at(0))->method('createFile')
->with(
TMP . 'ViewTaskComments' . DS . 'edit.ctp',
new PHPUnit_Framework_Constraint_IsAnything()
);
$this->Task->bake('edit', true);
}
/**
* test baking an index
*
* @return void
*/
public function testBakeIndex() {
$this->Task->controllerName = 'ViewTaskComments';
$this->Task->expects($this->at(0))->method('createFile')
->with(
TMP . 'ViewTaskComments' . DS . 'index.ctp',
$this->stringContains("\$viewTaskComment['Article']['title']")
);
$this->Task->bake('index', true);
}
/**
* test that baking a view with no template doesn't make a file.
*
* @return void
*/
public function testBakeWithNoTemplate() {
$this->Task->controllerName = 'ViewTaskComments';
$this->Task->expects($this->never())->method('createFile');
$this->Task->bake('delete', true);
}
/**
* test bake() with a -plugin param
*
* @return void
*/
public function testBakeWithPlugin() {
$this->Task->controllerName = 'ViewTaskComments';
$this->Task->plugin = 'TestTest';
$this->Task->name = 'View';
//fake plugin path
CakePlugin::load('TestTest', array('path' => APP . 'Plugin' . DS . 'TestTest' . DS));
$path = APP . 'Plugin' . DS . 'TestTest' . DS . 'View' . DS . 'ViewTaskComments' . DS . 'view.ctp';
$result = $this->Task->getContent('index');
$this->assertNotContains('List Test Test.view Task Articles', $result);
$this->Task->expects($this->once())
->method('createFile')
->with($path, $this->anything());
$this->Task->bake('view', true);
CakePlugin::unload();
}
/**
* test bake actions baking multiple actions.
*
* @return void
*/
public function testBakeActions() {
$this->Task->controllerName = 'ViewTaskComments';
$this->Task->expects($this->at(0))->method('createFile')
->with(
TMP . 'ViewTaskComments' . DS . 'view.ctp',
$this->stringContains('View Task Comments')
);
$this->Task->expects($this->at(1))->method('createFile')
->with(
TMP . 'ViewTaskComments' . DS . 'edit.ctp',
$this->stringContains('Edit View Task Comment')
);
$this->Task->expects($this->at(2))->method('createFile')
->with(
TMP . 'ViewTaskComments' . DS . 'index.ctp',
$this->stringContains('ViewTaskComment')
);
$this->Task->bakeActions(array('view', 'edit', 'index'), array());
}
/**
* test baking a customAction (non crud)
*
* @return void
*/
public function testCustomAction() {
$this->Task->controllerName = 'ViewTaskComments';
$this->Task->expects($this->any())->method('in')
->will($this->onConsecutiveCalls('', 'my_action', 'y'));
$this->Task->expects($this->once())->method('createFile')
->with(
TMP . 'ViewTaskComments' . DS . 'my_action.ctp',
$this->anything()
);
$this->Task->customAction();
}
/**
* Test all()
*
* @return void
*/
public function testExecuteIntoAll() {
$this->Task->args[0] = 'all';
$this->Task->Controller->expects($this->once())->method('listAll')
->will($this->returnValue(array('view_task_comments')));
$this->Task->expects($this->at(0))->method('createFile')
->with(
TMP . 'ViewTaskComments' . DS . 'index.ctp',
$this->anything()
);
$this->Task->expects($this->at(1))->method('createFile')
->with(
TMP . 'ViewTaskComments' . DS . 'add.ctp',
$this->anything()
);
$this->Task->expects($this->exactly(2))->method('createFile');
$this->Task->execute();
}
/**
* Test all() with action parameter
*
* @return void
*/
public function testExecuteIntoAllWithActionName() {
$this->Task->args = array('all', 'index');
$this->Task->Controller->expects($this->once())->method('listAll')
->will($this->returnValue(array('view_task_comments')));
$this->Task->expects($this->once())->method('createFile')
->with(
TMP . 'ViewTaskComments' . DS . 'index.ctp',
$this->anything()
);
$this->Task->execute();
}
/**
* test `cake bake view $controller view`
*
* @return void
*/
public function testExecuteWithActionParam() {
$this->Task->args[0] = 'ViewTaskComments';
$this->Task->args[1] = 'view';
$this->Task->expects($this->once())->method('createFile')
->with(
TMP . 'ViewTaskComments' . DS . 'view.ctp',
$this->anything()
);
$this->Task->execute();
}
/**
* test `cake bake view $controller`
* Ensure that views are only baked for actions that exist in the controller.
*
* @return void
*/
public function testExecuteWithController() {
$this->Task->args[0] = 'ViewTaskComments';
$this->Task->expects($this->at(0))->method('createFile')
->with(
TMP . 'ViewTaskComments' . DS . 'index.ctp',
$this->anything()
);
$this->Task->expects($this->at(1))->method('createFile')
->with(
TMP . 'ViewTaskComments' . DS . 'add.ctp',
$this->anything()
);
$this->Task->expects($this->exactly(2))->method('createFile');
$this->Task->execute();
}
/**
* static dataprovider for test cases
*
* @return void
*/
public static function nameVariations() {
return array(array('ViewTaskComments'), array('ViewTaskComment'), array('view_task_comment'));
}
/**
* test that both plural and singular forms can be used for baking views.
*
* @dataProvider nameVariations
* @return void
*/
public function testExecuteWithControllerVariations($name) {
$this->Task->args = array($name);
$this->Task->expects($this->at(0))->method('createFile')
->with(
TMP . 'ViewTaskComments' . DS . 'index.ctp',
$this->anything()
);
$this->Task->expects($this->at(1))->method('createFile')
->with(
TMP . 'ViewTaskComments' . DS . 'add.ctp',
$this->anything()
);
$this->Task->execute();
}
/**
* test `cake bake view $controller --admin`
* Which only bakes admin methods, not non-admin methods.
*
* @return void
*/
public function testExecuteWithControllerAndAdminFlag() {
$_back = Configure::read('Routing');
Configure::write('Routing.prefixes', array('admin'));
$this->Task->args[0] = 'ViewTaskArticles';
$this->Task->params['admin'] = 1;
$this->Task->Project->expects($this->any())->method('getPrefix')->will($this->returnValue('admin_'));
$this->Task->expects($this->exactly(4))->method('createFile');
$views = array('admin_index.ctp', 'admin_add.ctp', 'admin_view.ctp', 'admin_edit.ctp');
foreach ($views as $i => $view) {
$this->Task->expects($this->at($i))->method('createFile')
->with(
TMP . 'ViewTaskArticles' . DS . $view,
$this->anything()
);
}
$this->Task->execute();
Configure::write('Routing', $_back);
}
/**
* test execute into interactive.
*
* @return void
*/
public function testExecuteInteractive() {
$this->Task->connection = 'test';
$this->Task->args = array();
$this->Task->params = array();
$this->Task->Controller->expects($this->once())->method('getName')
->will($this->returnValue('ViewTaskComments'));
$this->Task->expects($this->any())->method('in')
->will($this->onConsecutiveCalls('y', 'y', 'n'));
$this->Task->expects($this->at(3))->method('createFile')
->with(
TMP . 'ViewTaskComments' . DS . 'index.ctp',
$this->stringContains('ViewTaskComment')
);
$this->Task->expects($this->at(4))->method('createFile')
->with(
TMP . 'ViewTaskComments' . DS . 'view.ctp',
$this->stringContains('ViewTaskComment')
);
$this->Task->expects($this->at(5))->method('createFile')
->with(
TMP . 'ViewTaskComments' . DS . 'add.ctp',
$this->stringContains('Add View Task Comment')
);
$this->Task->expects($this->at(6))->method('createFile')
->with(
TMP . 'ViewTaskComments' . DS . 'edit.ctp',
$this->stringContains('Edit View Task Comment')
);
$this->Task->expects($this->exactly(4))->method('createFile');
$this->Task->execute();
}
/**
* test `cake bake view posts index list`
*
* @return void
*/
public function testExecuteWithAlternateTemplates() {
$this->Task->connection = 'test';
$this->Task->args = array('ViewTaskComments', 'index', 'list');
$this->Task->params = array();
$this->Task->expects($this->once())->method('createFile')
->with(
TMP . 'ViewTaskComments' . DS . 'list.ctp',
$this->stringContains('ViewTaskComment')
);
$this->Task->execute();
}
/**
* test execute into interactive() with admin methods.
*
* @return void
*/
public function testExecuteInteractiveWithAdmin() {
Configure::write('Routing.prefixes', array('admin'));
$this->Task->connection = 'test';
$this->Task->args = array();
$this->Task->Controller->expects($this->once())->method('getName')
->will($this->returnValue('ViewTaskComments'));
$this->Task->Project->expects($this->once())->method('getPrefix')
->will($this->returnValue('admin_'));
$this->Task->expects($this->any())->method('in')
->will($this->onConsecutiveCalls('y', 'n', 'y'));
$this->Task->expects($this->at(3))->method('createFile')
->with(
TMP . 'ViewTaskComments' . DS . 'admin_index.ctp',
$this->stringContains('ViewTaskComment')
);
$this->Task->expects($this->at(4))->method('createFile')
->with(
TMP . 'ViewTaskComments' . DS . 'admin_view.ctp',
$this->stringContains('ViewTaskComment')
);
$this->Task->expects($this->at(5))->method('createFile')
->with(
TMP . 'ViewTaskComments' . DS . 'admin_add.ctp',
$this->stringContains('Add View Task Comment')
);
$this->Task->expects($this->at(6))->method('createFile')
->with(
TMP . 'ViewTaskComments' . DS . 'admin_edit.ctp',
$this->stringContains('Edit View Task Comment')
);
$this->Task->expects($this->exactly(4))->method('createFile');
$this->Task->execute();
}
/**
* test getting templates, make sure noTemplateActions works and prefixed template is used before generic one.
*
* @return void
*/
public function testGetTemplate() {
$result = $this->Task->getTemplate('delete');
$this->assertFalse($result);
$result = $this->Task->getTemplate('add');
$this->assertEquals('form', $result);
Configure::write('Routing.prefixes', array('admin'));
$result = $this->Task->getTemplate('admin_add');
$this->assertEquals('form', $result);
$this->Task->Template->templatePaths = array(
'test' => CAKE . 'Test' . DS . 'test_app' . DS . 'Console' . DS . 'Templates' . DS . 'test' . DS
);
$this->Task->Template->params['theme'] = 'test';
$result = $this->Task->getTemplate('admin_edit');
$this->assertEquals('admin_edit', $result);
}
}

View file

@ -0,0 +1,344 @@
<?php
/**
* TestSuiteShell test case
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Console.Command
* @since CakePHP(tm) v 2.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ShellDispatcher', 'Console');
App::uses('TestShell', 'Console/Command');
/**
* Class TestTestShell
*
* @package Cake.Test.Case.Console.Command
*/
class TestTestShell extends TestShell {
public function mapFileToCase($file, $category, $throwOnMissingFile = true) {
return $this->_mapFileToCase($file, $category, $throwOnMissingFile);
}
public function mapFileToCategory($file) {
return $this->_mapFileToCategory($file);
}
}
/**
* Class TestShellTest
*
* @package Cake.Test.Case.Console.Command
*/
class TestShellTest extends CakeTestCase {
/**
* setUp test case
*
* @return void
*/
public function setUp() {
parent::setUp();
$out = $this->getMock('ConsoleOutput', array(), array(), '', false);
$in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->Shell = $this->getMock(
'TestTestShell',
array('in', 'out', 'hr', 'help', 'error', 'err', '_stop', 'initialize', '_run', 'clear'),
array($out, $out, $in)
);
$this->Shell->OptionParser = $this->getMock('ConsoleOptionParser', array(), array(null, false));
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->Dispatch, $this->Shell);
}
/**
* testMapCoreFileToCategory
*
* @return void
*/
public function testMapCoreFileToCategory() {
$this->Shell->startup();
$return = $this->Shell->mapFileToCategory('lib/Cake/basics.php');
$this->assertSame('core', $return);
$return = $this->Shell->mapFileToCategory('lib/Cake/Core/App.php');
$this->assertSame('core', $return);
$return = $this->Shell->mapFileToCategory('lib/Cake/Some/Deeply/Nested/Structure.php');
$this->assertSame('core', $return);
}
/**
* testMapCoreFileToCase
*
* basics.php is a slightly special case - it's the only file in the core with a test that isn't Capitalized
*
* @return void
*/
public function testMapCoreFileToCase() {
$this->Shell->startup();
$return = $this->Shell->mapFileToCase('lib/Cake/basics.php', 'core');
$this->assertSame('Basics', $return);
$return = $this->Shell->mapFileToCase('lib/Cake/Core/App.php', 'core');
$this->assertSame('Core/App', $return);
$return = $this->Shell->mapFileToCase('lib/Cake/Some/Deeply/Nested/Structure.php', 'core', false);
$this->assertSame('Some/Deeply/Nested/Structure', $return);
}
/**
* testMapAppFileToCategory
*
* @return void
*/
public function testMapAppFileToCategory() {
$this->Shell->startup();
$return = $this->Shell->mapFileToCategory(APP . 'Controller/ExampleController.php');
$this->assertSame('app', $return);
$return = $this->Shell->mapFileToCategory(APP . 'My/File/Is/Here.php');
$this->assertSame('app', $return);
}
/**
* testMapAppFileToCase
*
* @return void
*/
public function testMapAppFileToCase() {
$this->Shell->startup();
$return = $this->Shell->mapFileToCase(APP . 'Controller/ExampleController.php', 'app', false);
$this->assertSame('Controller/ExampleController', $return);
$return = $this->Shell->mapFileToCase(APP . 'My/File/Is/Here.php', 'app', false);
$this->assertSame('My/File/Is/Here', $return);
}
/**
* testMapPluginFileToCategory
*
* @return void
*/
public function testMapPluginFileToCategory() {
$this->Shell->startup();
$return = $this->Shell->mapFileToCategory(APP . 'Plugin/awesome/Controller/ExampleController.php');
$this->assertSame('awesome', $return);
$return = $this->Shell->mapFileToCategory(dirname(CAKE) . 'plugins/awesome/Controller/ExampleController.php');
$this->assertSame('awesome', $return);
}
/**
* testMapPluginFileToCase
*
* @return void
*/
public function testMapPluginFileToCase() {
$this->Shell->startup();
$return = $this->Shell->mapFileToCase(APP . 'Plugin/awesome/Controller/ExampleController.php', 'awesome', false);
$this->assertSame('Controller/ExampleController', $return);
$return = $this->Shell->mapFileToCase(dirname(CAKE) . 'plugins/awesome/Controller/ExampleController.php', 'awesome', false);
$this->assertSame('Controller/ExampleController', $return);
}
/**
* testMapCoreTestToCategory
*
* @return void
*/
public function testMapCoreTestToCategory() {
$this->Shell->startup();
$return = $this->Shell->mapFileToCategory('lib/Cake/Test/Case/BasicsTest.php');
$this->assertSame('core', $return);
$return = $this->Shell->mapFileToCategory('lib/Cake/Test/Case/BasicsTest.php');
$this->assertSame('core', $return);
$return = $this->Shell->mapFileToCategory('lib/Cake/Test/Case/Some/Deeply/Nested/StructureTest.php');
$this->assertSame('core', $return);
}
/**
* testMapCoreTestToCase
*
* basics.php is a slightly special case - it's the only file in the core with a test that isn't Capitalized
*
* @return void
*/
public function testMapCoreTestToCase() {
$this->Shell->startup();
$return = $this->Shell->mapFileToCase('lib/Cake/Test/Case/BasicsTest.php', 'core');
$this->assertSame('Basics', $return);
$return = $this->Shell->mapFileToCase('lib/Cake/Test/Case/Core/AppTest.php', 'core');
$this->assertSame('Core/App', $return);
$return = $this->Shell->mapFileToCase('lib/Cake/Test/Case/Some/Deeply/Nested/StructureTest.php', 'core', false);
$this->assertSame('Some/Deeply/Nested/Structure', $return);
}
/**
* testMapAppTestToCategory
*
* @return void
*/
public function testMapAppTestToCategory() {
$this->Shell->startup();
$return = $this->Shell->mapFileToCategory(APP . 'Test/Case/Controller/ExampleControllerTest.php');
$this->assertSame('app', $return);
$return = $this->Shell->mapFileToCategory(APP . 'Test/Case/My/File/Is/HereTest.php');
$this->assertSame('app', $return);
}
/**
* testMapAppTestToCase
*
* @return void
*/
public function testMapAppTestToCase() {
$this->Shell->startup();
$return = $this->Shell->mapFileToCase(APP . 'Test/Case/Controller/ExampleControllerTest.php', 'app', false);
$this->assertSame('Controller/ExampleController', $return);
$return = $this->Shell->mapFileToCase(APP . 'Test/Case/My/File/Is/HereTest.php', 'app', false);
$this->assertSame('My/File/Is/Here', $return);
}
/**
* testMapPluginTestToCategory
*
* @return void
*/
public function testMapPluginTestToCategory() {
$this->Shell->startup();
$return = $this->Shell->mapFileToCategory(APP . 'Plugin/awesome/Test/Case/Controller/ExampleControllerTest.php');
$this->assertSame('awesome', $return);
$return = $this->Shell->mapFileToCategory(dirname(CAKE) . 'plugins/awesome/Test/Case/Controller/ExampleControllerTest.php');
$this->assertSame('awesome', $return);
}
/**
* testMapPluginTestToCase
*
* @return void
*/
public function testMapPluginTestToCase() {
$this->Shell->startup();
$return = $this->Shell->mapFileToCase(APP . 'Plugin/awesome/Test/Case/Controller/ExampleControllerTest.php', 'awesome', false);
$this->assertSame('Controller/ExampleController', $return);
$return = $this->Shell->mapFileToCase(dirname(CAKE) . 'plugins/awesome/Test/Case/Controller/ExampleControllerTest.php', 'awesome', false);
$this->assertSame('Controller/ExampleController', $return);
}
/**
* testMapNotTestToNothing
*
* @return void
*/
public function testMapNotTestToNothing() {
$this->Shell->startup();
$return = $this->Shell->mapFileToCategory(APP . 'Test/Case/NotATestFile.php');
$this->assertSame('app', $return);
$return = $this->Shell->mapFileToCase(APP . 'Test/Case/NotATestFile.php', false, false);
$this->assertFalse($return);
$return = $this->Shell->mapFileToCategory(APP . 'Test/Fixture/SomeTest.php');
$this->assertSame('app', $return);
$return = $this->Shell->mapFileToCase(APP . 'Test/Fixture/SomeTest.php', false, false);
$this->assertFalse($return);
}
/**
* test available list of test cases for an empty category
*
* @return void
*/
public function testAvailableWithEmptyList() {
$this->Shell->startup();
$this->Shell->args = array('unexistant-category');
$this->Shell->expects($this->at(0))->method('out')->with(__d('cake_console', "No test cases available \n\n"));
$this->Shell->OptionParser->expects($this->once())->method('help');
$this->Shell->available();
}
/**
* test available list of test cases for core category
*
* @return void
*/
public function testAvailableCoreCategory() {
$this->Shell->startup();
$this->Shell->args = array('core');
$this->Shell->expects($this->at(0))->method('out')->with('Core Test Cases:');
$this->Shell->expects($this->at(1))->method('out')
->with($this->stringContains('[1]'));
$this->Shell->expects($this->at(2))->method('out')
->with($this->stringContains('[2]'));
$this->Shell->expects($this->once())->method('in')
->with(__d('cake_console', 'What test case would you like to run?'), null, 'q')
->will($this->returnValue('1'));
$this->Shell->expects($this->once())->method('_run');
$this->Shell->available();
$this->assertEquals(array('core', 'AllBehaviors'), $this->Shell->args);
}
/**
* Tests that correct option for test runner are passed
*
* @return void
*/
public function testRunnerOptions() {
$this->Shell->startup();
$this->Shell->args = array('core', 'Basics');
$this->Shell->params = array('filter' => 'myFilter', 'colors' => true, 'verbose' => true);
$this->Shell->expects($this->once())->method('_run')
->with(
array('app' => false, 'plugin' => null, 'core' => true, 'output' => 'text', 'case' => 'Basics'),
array('--filter', 'myFilter', '--colors', '--verbose')
);
$this->Shell->main();
}
}

View file

@ -0,0 +1,177 @@
<?php
/**
* ConsoleErrorHandler Test case
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Console
* @since CakePHP(tm) v 2.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ConsoleErrorHandler', 'Console');
/**
* ConsoleErrorHandler Test case.
*
* @package Cake.Test.Case.Console
*/
class ConsoleErrorHandlerTest extends CakeTestCase {
/**
* setup, create mocks
*
* @return Mock object
*/
public function setUp() {
parent::setUp();
$this->Error = $this->getMock('ConsoleErrorHandler', array('_stop'));
ConsoleErrorHandler::$stderr = $this->getMock('ConsoleOutput', array(), array(), '', false);
}
/**
* tearDown
*
* @return void
*/
public function tearDown() {
unset($this->Error);
parent::tearDown();
}
/**
* test that the console error handler can deal with CakeExceptions.
*
* @return void
*/
public function testHandleError() {
$content = "<error>Notice Error:</error> This is a notice error in [/some/file, line 275]\n";
ConsoleErrorHandler::$stderr->expects($this->once())->method('write')
->with($content);
$this->Error->handleError(E_NOTICE, 'This is a notice error', '/some/file', 275);
}
/**
* test that the console error handler can deal with fatal errors.
*
* @return void
*/
public function testHandleFatalError() {
$content = "<error>Fatal Error Error:</error> This is a fatal error in [/some/file, line 275]\n";
ConsoleErrorHandler::$stderr->expects($this->once())->method('write')
->with($content);
$this->Error->expects($this->once())
->method('_stop')
->with(1);
$this->Error->handleError(E_USER_ERROR, 'This is a fatal error', '/some/file', 275);
}
/**
* test that the console error handler can deal with CakeExceptions.
*
* @return void
*/
public function testCakeErrors() {
$exception = new MissingActionException('Missing action');
ConsoleErrorHandler::$stderr->expects($this->once())->method('write')
->with($this->stringContains('Missing action'));
$this->Error->expects($this->once())
->method('_stop')
->with(404);
$this->Error->handleException($exception);
}
/**
* test a non CakeException exception.
*
* @return void
*/
public function testNonCakeExceptions() {
$exception = new InvalidArgumentException('Too many parameters.');
ConsoleErrorHandler::$stderr->expects($this->once())->method('write')
->with($this->stringContains('Too many parameters.'));
$this->Error->expects($this->once())
->method('_stop')
->with(1);
$this->Error->handleException($exception);
}
/**
* test a Error404 exception.
*
* @return void
*/
public function testError404Exception() {
$exception = new NotFoundException('dont use me in cli.');
ConsoleErrorHandler::$stderr->expects($this->once())->method('write')
->with($this->stringContains('dont use me in cli.'));
$this->Error->expects($this->once())
->method('_stop')
->with(404);
$this->Error->handleException($exception);
}
/**
* test a Error500 exception.
*
* @return void
*/
public function testError500Exception() {
$exception = new InternalErrorException('dont use me in cli.');
ConsoleErrorHandler::$stderr->expects($this->once())->method('write')
->with($this->stringContains('dont use me in cli.'));
$this->Error->expects($this->once())
->method('_stop')
->with(500);
$this->Error->handleException($exception);
}
/**
* test a exception with non-integer code
*
* @return void
*/
public function testNonIntegerExceptionCode() {
if (PHP_VERSION_ID < 50300) {
$this->markTestSkipped('ReflectionProperty::setAccessible() is available since 5.3');
}
$exception = new Exception('Non-integer exception code');
$class = new ReflectionClass('Exception');
$property = $class->getProperty('code');
$property->setAccessible(true);
$property->setValue($exception, '42S22');
ConsoleErrorHandler::$stderr->expects($this->once())->method('write')
->with($this->stringContains('Non-integer exception code'));
$this->Error->expects($this->once())
->method('_stop')
->with(1);
$this->Error->handleException($exception);
}
}

View file

@ -0,0 +1,631 @@
<?php
/**
* ConsoleOptionParserTest file
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Console
* @since CakePHP(tm) v 2.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ConsoleOptionParser', 'Console');
/**
* Class ConsoleOptionParserTest
*
* @package Cake.Test.Case.Console
*/
class ConsoleOptionParserTest extends CakeTestCase {
/**
* test setting the console description
*
* @return void
*/
public function testDescription() {
$parser = new ConsoleOptionParser('test', false);
$result = $parser->description('A test');
$this->assertEquals($parser, $result, 'Setting description is not chainable');
$this->assertEquals('A test', $parser->description(), 'getting value is wrong.');
$result = $parser->description(array('A test', 'something'));
$this->assertEquals("A test\nsomething", $parser->description(), 'getting value is wrong.');
}
/**
* test setting the console epilog
*
* @return void
*/
public function testEpilog() {
$parser = new ConsoleOptionParser('test', false);
$result = $parser->epilog('A test');
$this->assertEquals($parser, $result, 'Setting epilog is not chainable');
$this->assertEquals('A test', $parser->epilog(), 'getting value is wrong.');
$result = $parser->epilog(array('A test', 'something'));
$this->assertEquals("A test\nsomething", $parser->epilog(), 'getting value is wrong.');
}
/**
* test adding an option returns self.
*
* @return void
*/
public function testAddOptionReturnSelf() {
$parser = new ConsoleOptionParser('test', false);
$result = $parser->addOption('test');
$this->assertEquals($parser, $result, 'Did not return $this from addOption');
}
/**
* test adding an option and using the long value for parsing.
*
* @return void
*/
public function testAddOptionLong() {
$parser = new ConsoleOptionParser('test', false);
$parser->addOption('test', array(
'short' => 't'
));
$result = $parser->parse(array('--test', 'value'));
$this->assertEquals(array('test' => 'value', 'help' => false), $result[0], 'Long parameter did not parse out');
}
/**
* test adding an option with a zero value
*
* @return void
*/
public function testAddOptionZero() {
$parser = new ConsoleOptionParser('test', false);
$parser->addOption('count', array());
$result = $parser->parse(array('--count', '0'));
$this->assertEquals(array('count' => '0', 'help' => false), $result[0], 'Zero parameter did not parse out');
}
/**
* test addOption with an object.
*
* @return void
*/
public function testAddOptionObject() {
$parser = new ConsoleOptionParser('test', false);
$parser->addOption(new ConsoleInputOption('test', 't'));
$result = $parser->parse(array('--test=value'));
$this->assertEquals(array('test' => 'value', 'help' => false), $result[0], 'Long parameter did not parse out');
}
/**
* test adding an option and using the long value for parsing.
*
* @return void
*/
public function testAddOptionLongEquals() {
$parser = new ConsoleOptionParser('test', false);
$parser->addOption('test', array(
'short' => 't'
));
$result = $parser->parse(array('--test=value'));
$this->assertEquals(array('test' => 'value', 'help' => false), $result[0], 'Long parameter did not parse out');
}
/**
* test adding an option and using the default.
*
* @return void
*/
public function testAddOptionDefault() {
$parser = new ConsoleOptionParser('test', false);
$parser->addOption('test', array(
'default' => 'default value',
));
$result = $parser->parse(array('--test'));
$this->assertEquals(array('test' => 'default value', 'help' => false), $result[0], 'Default value did not parse out');
$parser = new ConsoleOptionParser('test', false);
$parser->addOption('test', array(
'default' => 'default value',
));
$result = $parser->parse(array());
$this->assertEquals(array('test' => 'default value', 'help' => false), $result[0], 'Default value did not parse out');
}
/**
* test adding an option and using the short value for parsing.
*
* @return void
*/
public function testAddOptionShort() {
$parser = new ConsoleOptionParser('test', false);
$parser->addOption('test', array(
'short' => 't'
));
$result = $parser->parse(array('-t', 'value'));
$this->assertEquals(array('test' => 'value', 'help' => false), $result[0], 'Short parameter did not parse out');
}
/**
* Test that adding an option using a two letter short value causes an exception.
* As they will not parse correctly.
*
* @expectedException ConsoleException
* @return void
*/
public function testAddOptionShortOneLetter() {
$parser = new ConsoleOptionParser('test', false);
$parser->addOption('test', array('short' => 'te'));
}
/**
* test adding and using boolean options.
*
* @return void
*/
public function testAddOptionBoolean() {
$parser = new ConsoleOptionParser('test', false);
$parser->addOption('test', array(
'boolean' => true,
));
$result = $parser->parse(array('--test', 'value'));
$expected = array(array('test' => true, 'help' => false), array('value'));
$this->assertEquals($expected, $result);
$result = $parser->parse(array('value'));
$expected = array(array('test' => false, 'help' => false), array('value'));
$this->assertEquals($expected, $result);
}
/**
* test adding an multiple shorts.
*
* @return void
*/
public function testAddOptionMultipleShort() {
$parser = new ConsoleOptionParser('test', false);
$parser->addOption('test', array('short' => 't', 'boolean' => true))
->addOption('file', array('short' => 'f', 'boolean' => true))
->addOption('output', array('short' => 'o', 'boolean' => true));
$result = $parser->parse(array('-o', '-t', '-f'));
$expected = array('file' => true, 'test' => true, 'output' => true, 'help' => false);
$this->assertEquals($expected, $result[0], 'Short parameter did not parse out');
$result = $parser->parse(array('-otf'));
$this->assertEquals($expected, $result[0], 'Short parameter did not parse out');
}
/**
* test multiple options at once.
*
* @return void
*/
public function testMultipleOptions() {
$parser = new ConsoleOptionParser('test', false);
$parser->addOption('test')
->addOption('connection')
->addOption('table', array('short' => 't', 'default' => true));
$result = $parser->parse(array('--test', 'value', '-t', '--connection', 'postgres'));
$expected = array('test' => 'value', 'table' => true, 'connection' => 'postgres', 'help' => false);
$this->assertEquals($expected, $result[0], 'multiple options did not parse');
}
/**
* Test adding multiple options.
*
* @return void
*/
public function testAddOptions() {
$parser = new ConsoleOptionParser('something', false);
$result = $parser->addOptions(array(
'name' => array('help' => 'The name'),
'other' => array('help' => 'The other arg')
));
$this->assertEquals($parser, $result, 'addOptions is not chainable.');
$result = $parser->options();
$this->assertEquals(3, count($result), 'Not enough options');
}
/**
* test that boolean options work
*
* @return void
*/
public function testOptionWithBooleanParam() {
$parser = new ConsoleOptionParser('test', false);
$parser->addOption('no-commit', array('boolean' => true))
->addOption('table', array('short' => 't'));
$result = $parser->parse(array('--table', 'posts', '--no-commit', 'arg1', 'arg2'));
$expected = array(array('table' => 'posts', 'no-commit' => true, 'help' => false), array('arg1', 'arg2'));
$this->assertEquals($expected, $result, 'Boolean option did not parse correctly.');
}
/**
* test parsing options that do not exist.
*
* @expectedException ConsoleException
* @return void
*/
public function testOptionThatDoesNotExist() {
$parser = new ConsoleOptionParser('test', false);
$parser->addOption('no-commit', array('boolean' => true));
$parser->parse(array('--fail', 'other'));
}
/**
* test parsing short options that do not exist.
*
* @expectedException ConsoleException
* @return void
*/
public function testShortOptionThatDoesNotExist() {
$parser = new ConsoleOptionParser('test', false);
$parser->addOption('no-commit', array('boolean' => true));
$parser->parse(array('-f'));
}
/**
* test that options with choices enforce them.
*
* @expectedException ConsoleException
* @return void
*/
public function testOptionWithChoices() {
$parser = new ConsoleOptionParser('test', false);
$parser->addOption('name', array('choices' => array('mark', 'jose')));
$result = $parser->parse(array('--name', 'mark'));
$expected = array('name' => 'mark', 'help' => false);
$this->assertEquals($expected, $result[0], 'Got the correct value.');
$result = $parser->parse(array('--name', 'jimmy'));
}
/**
* Ensure that option values can start with -
*
* @return void
*/
public function testOptionWithValueStartingWithMinus() {
$parser = new ConsoleOptionParser('test', false);
$parser->addOption('name')
->addOption('age');
$result = $parser->parse(array('--name', '-foo', '--age', 'old'));
$expected = array('name' => '-foo', 'age' => 'old', 'help' => false);
$this->assertEquals($expected, $result[0], 'Option values starting with "-" are broken.');
}
/**
* test positional argument parsing.
*
* @return void
*/
public function testPositionalArgument() {
$parser = new ConsoleOptionParser('test', false);
$result = $parser->addArgument('name', array('help' => 'An argument'));
$this->assertEquals($parser, $result, 'Should return this');
}
/**
* test addOption with an object.
*
* @return void
*/
public function testAddArgumentObject() {
$parser = new ConsoleOptionParser('test', false);
$parser->addArgument(new ConsoleInputArgument('test'));
$result = $parser->arguments();
$this->assertCount(1, $result);
$this->assertEquals('test', $result[0]->name());
}
/**
* Test adding arguments out of order.
*
* @return void
*/
public function testAddArgumentOutOfOrder() {
$parser = new ConsoleOptionParser('test', false);
$parser->addArgument('name', array('index' => 1, 'help' => 'first argument'))
->addArgument('bag', array('index' => 2, 'help' => 'second argument'))
->addArgument('other', array('index' => 0, 'help' => 'Zeroth argument'));
$result = $parser->arguments();
$this->assertCount(3, $result);
$this->assertEquals('other', $result[0]->name());
$this->assertEquals('name', $result[1]->name());
$this->assertEquals('bag', $result[2]->name());
$this->assertSame(array(0, 1, 2), array_keys($result));
}
/**
* test overwriting positional arguments.
*
* @return void
*/
public function testPositionalArgOverwrite() {
$parser = new ConsoleOptionParser('test', false);
$parser->addArgument('name', array('help' => 'An argument'))
->addArgument('other', array('index' => 0));
$result = $parser->arguments();
$this->assertEquals(1, count($result), 'Overwrite did not occur');
}
/**
* test parsing arguments.
*
* @expectedException ConsoleException
* @return void
*/
public function testParseArgumentTooMany() {
$parser = new ConsoleOptionParser('test', false);
$parser->addArgument('name', array('help' => 'An argument'))
->addArgument('other');
$expected = array('one', 'two');
$result = $parser->parse($expected);
$this->assertEquals($expected, $result[1], 'Arguments are not as expected');
$result = $parser->parse(array('one', 'two', 'three'));
}
/**
* test parsing arguments with 0 value.
*
* @return void
*/
public function testParseArgumentZero() {
$parser = new ConsoleOptionParser('test', false);
$expected = array('one', 'two', 0, 'after', 'zero');
$result = $parser->parse($expected);
$this->assertEquals($expected, $result[1], 'Arguments are not as expected');
}
/**
* test that when there are not enough arguments an exception is raised
*
* @expectedException ConsoleException
* @return void
*/
public function testPositionalArgNotEnough() {
$parser = new ConsoleOptionParser('test', false);
$parser->addArgument('name', array('required' => true))
->addArgument('other', array('required' => true));
$parser->parse(array('one'));
}
/**
* test that arguments with choices enforce them.
*
* @expectedException ConsoleException
* @return void
*/
public function testPositionalArgWithChoices() {
$parser = new ConsoleOptionParser('test', false);
$parser->addArgument('name', array('choices' => array('mark', 'jose')))
->addArgument('alias', array('choices' => array('cowboy', 'samurai')))
->addArgument('weapon', array('choices' => array('gun', 'sword')));
$result = $parser->parse(array('mark', 'samurai', 'sword'));
$expected = array('mark', 'samurai', 'sword');
$this->assertEquals($expected, $result[1], 'Got the correct value.');
$result = $parser->parse(array('jose', 'coder'));
}
/**
* Test adding multiple arguments.
*
* @return void
*/
public function testAddArguments() {
$parser = new ConsoleOptionParser('test', false);
$result = $parser->addArguments(array(
'name' => array('help' => 'The name'),
'other' => array('help' => 'The other arg')
));
$this->assertEquals($parser, $result, 'addArguments is not chainable.');
$result = $parser->arguments();
$this->assertEquals(2, count($result), 'Not enough arguments');
}
/**
* test setting a subcommand up.
*
* @return void
*/
public function testSubcommand() {
$parser = new ConsoleOptionParser('test', false);
$result = $parser->addSubcommand('initdb', array(
'help' => 'Initialize the database'
));
$this->assertEquals($parser, $result, 'Adding a subcommand is not chainable');
}
/**
* test addSubcommand with an object.
*
* @return void
*/
public function testAddSubcommandObject() {
$parser = new ConsoleOptionParser('test', false);
$parser->addSubcommand(new ConsoleInputSubcommand('test'));
$result = $parser->subcommands();
$this->assertEquals(1, count($result));
$this->assertEquals('test', $result['test']->name());
}
/**
* test adding multiple subcommands
*
* @return void
*/
public function testAddSubcommands() {
$parser = new ConsoleOptionParser('test', false);
$result = $parser->addSubcommands(array(
'initdb' => array('help' => 'Initialize the database'),
'create' => array('help' => 'Create something')
));
$this->assertEquals($parser, $result, 'Adding a subcommands is not chainable');
$result = $parser->subcommands();
$this->assertEquals(2, count($result), 'Not enough subcommands');
}
/**
* test that no exception is triggered when help is being generated
*
* @return void
*/
public function testHelpNoExceptionWhenGettingHelp() {
$parser = new ConsoleOptionParser('mycommand', false);
$parser->addOption('test', array('help' => 'A test option.'))
->addArgument('model', array('help' => 'The model to make.', 'required' => true));
$result = $parser->parse(array('--help'));
$this->assertTrue($result[0]['help']);
}
/**
* test that help() with a command param shows the help for a subcommand
*
* @return void
*/
public function testHelpSubcommandHelp() {
$subParser = new ConsoleOptionParser('method', false);
$subParser->addOption('connection', array('help' => 'Db connection.'));
$parser = new ConsoleOptionParser('mycommand', false);
$parser->addSubcommand('method', array(
'help' => 'This is another command',
'parser' => $subParser
))
->addOption('test', array('help' => 'A test option.'));
$result = $parser->help('method');
$expected = <<<TEXT
<info>Usage:</info>
cake mycommand method [-h] [--connection]
<info>Options:</info>
--help, -h Display this help.
--connection Db connection.
TEXT;
$this->assertTextEquals($expected, $result, 'Help is not correct.');
}
/**
* test building a parser from an array.
*
* @return void
*/
public function testBuildFromArray() {
$spec = array(
'command' => 'test',
'arguments' => array(
'name' => array('help' => 'The name'),
'other' => array('help' => 'The other arg')
),
'options' => array(
'name' => array('help' => 'The name'),
'other' => array('help' => 'The other arg')
),
'subcommands' => array(
'initdb' => array('help' => 'make database')
),
'description' => 'description text',
'epilog' => 'epilog text'
);
$parser = ConsoleOptionParser::buildFromArray($spec);
$this->assertEquals($spec['description'], $parser->description());
$this->assertEquals($spec['epilog'], $parser->epilog());
$options = $parser->options();
$this->assertTrue(isset($options['name']));
$this->assertTrue(isset($options['other']));
$args = $parser->arguments();
$this->assertEquals(2, count($args));
$commands = $parser->subcommands();
$this->assertEquals(1, count($commands));
}
/**
* test that create() returns instances
*
* @return void
*/
public function testCreateFactory() {
$parser = ConsoleOptionParser::create('factory', false);
$this->assertInstanceOf('ConsoleOptionParser', $parser);
$this->assertEquals('factory', $parser->command());
}
/**
* test that command() inflects the command name.
*
* @return void
*/
public function testCommandInflection() {
$parser = new ConsoleOptionParser('CommandLine');
$this->assertEquals('command_line', $parser->command());
}
/**
* test that parse() takes a subcommand argument, and that the subcommand parser
* is used.
*
* @return void
*/
public function testParsingWithSubParser() {
$parser = new ConsoleOptionParser('test', false);
$parser->addOption('primary')
->addArgument('one', array('required' => true, 'choices' => array('a', 'b')))
->addArgument('two', array('required' => true))
->addSubcommand('sub', array(
'parser' => array(
'options' => array(
'secondary' => array('boolean' => true),
'fourth' => array('help' => 'fourth option')
),
'arguments' => array(
'sub_arg' => array('choices' => array('c', 'd'))
)
)
));
$result = $parser->parse(array('--secondary', '--fourth', '4', 'c'), 'sub');
$expected = array(array(
'secondary' => true,
'fourth' => '4',
'help' => false,
'verbose' => false,
'quiet' => false), array('c'));
$this->assertEquals($expected, $result, 'Sub parser did not parse request.');
}
}

View file

@ -0,0 +1,246 @@
<?php
/**
* ConsoleOutputTest file
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Console
* @since CakePHP(tm) v 1.2.0.5432
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ConsoleOutput', 'Console');
/**
* Class ConsoleOutputTest
*
* @package Cake.Test.Case.Console
*/
class ConsoleOutputTest extends CakeTestCase {
/**
* setup
*
* @return void
*/
public function setUp() {
parent::setUp();
$this->output = $this->getMock('ConsoleOutput', array('_write'));
$this->output->outputAs(ConsoleOutput::COLOR);
}
/**
* tearDown
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->output);
}
/**
* test writing with no new line
*
* @return void
*/
public function testWriteNoNewLine() {
$this->output->expects($this->once())->method('_write')
->with('Some output');
$this->output->write('Some output', false);
}
/**
* test writing with no new line
*
* @return void
*/
public function testWriteNewLine() {
$this->output->expects($this->once())->method('_write')
->with('Some output' . PHP_EOL);
$this->output->write('Some output');
}
/**
* test write() with multiple new lines
*
* @return void
*/
public function testWriteMultipleNewLines() {
$this->output->expects($this->once())->method('_write')
->with('Some output' . PHP_EOL . PHP_EOL . PHP_EOL . PHP_EOL);
$this->output->write('Some output', 4);
}
/**
* test writing an array of messages.
*
* @return void
*/
public function testWriteArray() {
$this->output->expects($this->once())->method('_write')
->with('Line' . PHP_EOL . 'Line' . PHP_EOL . 'Line' . PHP_EOL);
$this->output->write(array('Line', 'Line', 'Line'));
}
/**
* test getting a style.
*
* @return void
*/
public function testStylesGet() {
$result = $this->output->styles('error');
$expected = array('text' => 'red', 'underline' => true);
$this->assertEquals($expected, $result);
$this->assertNull($this->output->styles('made_up_goop'));
$result = $this->output->styles();
$this->assertNotEmpty($result, 'error', 'Error is missing');
$this->assertNotEmpty($result, 'warning', 'Warning is missing');
}
/**
* test adding a style.
*
* @return void
*/
public function testStylesAdding() {
$this->output->styles('test', array('text' => 'red', 'background' => 'black'));
$result = $this->output->styles('test');
$expected = array('text' => 'red', 'background' => 'black');
$this->assertEquals($expected, $result);
$this->assertTrue($this->output->styles('test', false), 'Removing a style should return true.');
$this->assertNull($this->output->styles('test'), 'Removed styles should be null.');
}
/**
* test formatting text with styles.
*
* @return void
*/
public function testFormattingSimple() {
$this->output->expects($this->once())->method('_write')
->with("\033[31;4mError:\033[0m Something bad");
$this->output->write('<error>Error:</error> Something bad', false);
}
/**
* test that formatting doesn't eat tags it doesn't know about.
*
* @return void
*/
public function testFormattingNotEatingTags() {
$this->output->expects($this->once())->method('_write')
->with("<red> Something bad");
$this->output->write('<red> Something bad', false);
}
/**
* test formatting with custom styles.
*
* @return void
*/
public function testFormattingCustom() {
$this->output->styles('annoying', array(
'text' => 'magenta',
'background' => 'cyan',
'blink' => true,
'underline' => true
));
$this->output->expects($this->once())->method('_write')
->with("\033[35;46;5;4mAnnoy:\033[0m Something bad");
$this->output->write('<annoying>Annoy:</annoying> Something bad', false);
}
/**
* test formatting text with missing styles.
*
* @return void
*/
public function testFormattingMissingStyleName() {
$this->output->expects($this->once())->method('_write')
->with("<not_there>Error:</not_there> Something bad");
$this->output->write('<not_there>Error:</not_there> Something bad', false);
}
/**
* test formatting text with multiple styles.
*
* @return void
*/
public function testFormattingMultipleStylesName() {
$this->output->expects($this->once())->method('_write')
->with("\033[31;4mBad\033[0m \033[33mWarning\033[0m Regular");
$this->output->write('<error>Bad</error> <warning>Warning</warning> Regular', false);
}
/**
* test that multiple tags of the same name work in one string.
*
* @return void
*/
public function testFormattingMultipleSameTags() {
$this->output->expects($this->once())->method('_write')
->with("\033[31;4mBad\033[0m \033[31;4mWarning\033[0m Regular");
$this->output->write('<error>Bad</error> <error>Warning</error> Regular', false);
}
/**
* test raw output not getting tags replaced.
*
* @return void
*/
public function testOutputAsRaw() {
$this->output->outputAs(ConsoleOutput::RAW);
$this->output->expects($this->once())->method('_write')
->with('<error>Bad</error> Regular');
$this->output->write('<error>Bad</error> Regular', false);
}
/**
* test plain output.
*
* @return void
*/
public function testOutputAsPlain() {
$this->output->outputAs(ConsoleOutput::PLAIN);
$this->output->expects($this->once())->method('_write')
->with('Bad Regular');
$this->output->write('<error>Bad</error> Regular', false);
}
/**
* test plain output only strips tags used for formatting.
*
* @return void
*/
public function testOutputAsPlainSelectiveTagRemoval() {
$this->output->outputAs(ConsoleOutput::PLAIN);
$this->output->expects($this->once())->method('_write')
->with('Bad Regular <b>Left</b> <i>behind</i> <name>');
$this->output->write('<error>Bad</error> Regular <b>Left</b> <i>behind</i> <name>', false);
}
}

View file

@ -0,0 +1,509 @@
<?php
/**
* HelpFormatterTest file
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Console
* @since CakePHP(tm) v 2.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ConsoleOptionParser', 'Console');
App::uses('HelpFormatter', 'Console');
/**
* Class HelpFormatterTest
*
* @package Cake.Test.Case.Console
*/
class HelpFormatterTest extends CakeTestCase {
/**
* test that the console max width is respected when generating help.
*
* @return void
*/
public function testWidthFormatting() {
$parser = new ConsoleOptionParser('test', false);
$parser->description('This is fifteen This is fifteen This is fifteen')
->addOption('four', array('help' => 'this is help text this is help text'))
->addArgument('four', array('help' => 'this is help text this is help text'))
->addSubcommand('four', array('help' => 'this is help text this is help text'));
$formatter = new HelpFormatter($parser);
$result = $formatter->text(30);
$expected = <<<TEXT
This is fifteen This is
fifteen This is fifteen
<info>Usage:</info>
cake test [subcommand] [-h] [--four] [<four>]
<info>Subcommands:</info>
four this is help text this
is help text
To see help on a subcommand use <info>`cake test [subcommand] --help`</info>
<info>Options:</info>
--help, -h Display this help.
--four this is help text
this is help text
<info>Arguments:</info>
four this is help text this
is help text
<comment>(optional)</comment>
TEXT;
$this->assertTextEquals($expected, $result, 'Generated help is too wide');
}
/**
* test help() with options and arguments that have choices.
*
* @return void
*/
public function testHelpWithChoices() {
$parser = new ConsoleOptionParser('mycommand', false);
$parser->addOption('test', array('help' => 'A test option.', 'choices' => array('one', 'two')))
->addArgument('type', array(
'help' => 'Resource type.',
'choices' => array('aco', 'aro'),
'required' => true
))
->addArgument('other_longer', array('help' => 'Another argument.'));
$formatter = new HelpFormatter($parser);
$result = $formatter->text();
$expected = <<<TEXT
<info>Usage:</info>
cake mycommand [-h] [--test one|two] <aco|aro> [<other_longer>]
<info>Options:</info>
--help, -h Display this help.
--test A test option. <comment>(choices: one|two)</comment>
<info>Arguments:</info>
type Resource type. <comment>(choices: aco|aro)</comment>
other_longer Another argument. <comment>(optional)</comment>
TEXT;
$this->assertTextEquals($expected, $result, 'Help does not match');
}
/**
* test description and epilog in the help
*
* @return void
*/
public function testHelpDescriptionAndEpilog() {
$parser = new ConsoleOptionParser('mycommand', false);
$parser->description('Description text')
->epilog('epilog text')
->addOption('test', array('help' => 'A test option.'))
->addArgument('model', array('help' => 'The model to make.', 'required' => true));
$formatter = new HelpFormatter($parser);
$result = $formatter->text();
$expected = <<<TEXT
Description text
<info>Usage:</info>
cake mycommand [-h] [--test] <model>
<info>Options:</info>
--help, -h Display this help.
--test A test option.
<info>Arguments:</info>
model The model to make.
epilog text
TEXT;
$this->assertTextEquals($expected, $result, 'Help is wrong.');
}
/**
* test that help() outputs subcommands.
*
* @return void
*/
public function testHelpSubcommand() {
$parser = new ConsoleOptionParser('mycommand', false);
$parser->addSubcommand('method', array('help' => 'This is another command'))
->addOption('test', array('help' => 'A test option.'));
$formatter = new HelpFormatter($parser);
$result = $formatter->text();
$expected = <<<TEXT
<info>Usage:</info>
cake mycommand [subcommand] [-h] [--test]
<info>Subcommands:</info>
method This is another command
To see help on a subcommand use <info>`cake mycommand [subcommand] --help`</info>
<info>Options:</info>
--help, -h Display this help.
--test A test option.
TEXT;
$this->assertTextEquals($expected, $result, 'Help is not correct.');
}
/**
* test getting help with defined options.
*
* @return void
*/
public function testHelpWithOptions() {
$parser = new ConsoleOptionParser('mycommand', false);
$parser->addOption('test', array('help' => 'A test option.'))
->addOption('connection', array(
'short' => 'c', 'help' => 'The connection to use.', 'default' => 'default'
));
$formatter = new HelpFormatter($parser);
$result = $formatter->text();
$expected = <<<TEXT
<info>Usage:</info>
cake mycommand [-h] [--test] [-c default]
<info>Options:</info>
--help, -h Display this help.
--test A test option.
--connection, -c The connection to use. <comment>(default:
default)</comment>
TEXT;
$this->assertTextEquals($expected, $result, 'Help does not match');
}
/**
* test getting help with defined options.
*
* @return void
*/
public function testHelpWithOptionsAndArguments() {
$parser = new ConsoleOptionParser('mycommand', false);
$parser->addOption('test', array('help' => 'A test option.'))
->addArgument('model', array('help' => 'The model to make.', 'required' => true))
->addArgument('other_longer', array('help' => 'Another argument.'));
$formatter = new HelpFormatter($parser);
$result = $formatter->text();
$expected = <<<TEXT
<info>Usage:</info>
cake mycommand [-h] [--test] <model> [<other_longer>]
<info>Options:</info>
--help, -h Display this help.
--test A test option.
<info>Arguments:</info>
model The model to make.
other_longer Another argument. <comment>(optional)</comment>
TEXT;
$this->assertTextEquals($expected, $result, 'Help does not match');
}
/**
* Test that a long set of options doesn't make useless output.
*
* @return void
*/
public function testHelpWithLotsOfOptions() {
$parser = new ConsoleOptionParser('mycommand', false);
$parser
->addOption('test', array('help' => 'A test option.'))
->addOption('test2', array('help' => 'A test option.'))
->addOption('test3', array('help' => 'A test option.'))
->addOption('test4', array('help' => 'A test option.'))
->addOption('test5', array('help' => 'A test option.'))
->addOption('test6', array('help' => 'A test option.'))
->addOption('test7', array('help' => 'A test option.'))
->addArgument('model', array('help' => 'The model to make.', 'required' => true))
->addArgument('other_longer', array('help' => 'Another argument.'));
$formatter = new HelpFormatter($parser);
$result = $formatter->text();
$expected = 'cake mycommand [options] <model> [<other_longer>]';
$this->assertContains($expected, $result);
}
/**
* Test that a long set of arguments doesn't make useless output.
*
* @return void
*/
public function testHelpWithLotsOfArguments() {
$parser = new ConsoleOptionParser('mycommand', false);
$parser
->addArgument('test', array('help' => 'A test option.'))
->addArgument('test2', array('help' => 'A test option.'))
->addArgument('test3', array('help' => 'A test option.'))
->addArgument('test4', array('help' => 'A test option.'))
->addArgument('test5', array('help' => 'A test option.'))
->addArgument('test6', array('help' => 'A test option.'))
->addArgument('test7', array('help' => 'A test option.'))
->addArgument('model', array('help' => 'The model to make.', 'required' => true))
->addArgument('other_longer', array('help' => 'Another argument.'));
$formatter = new HelpFormatter($parser);
$result = $formatter->text();
$expected = 'cake mycommand [-h] [arguments]';
$this->assertContains($expected, $result);
}
/**
* test help() with options and arguments that have choices.
*
* @return void
*/
public function testXmlHelpWithChoices() {
$parser = new ConsoleOptionParser('mycommand', false);
$parser->addOption('test', array('help' => 'A test option.', 'choices' => array('one', 'two')))
->addArgument('type', array(
'help' => 'Resource type.',
'choices' => array('aco', 'aro'),
'required' => true
))
->addArgument('other_longer', array('help' => 'Another argument.'));
$formatter = new HelpFormatter($parser);
$result = $formatter->xml();
$expected = <<<TEXT
<?xml version="1.0"?>
<shell>
<name>mycommand</name>
<description>Description text</description>
<subcommands />
<options>
<option name="--help" short="-h" help="Display this help." boolean="1">
<default></default>
<choices></choices>
</option>
<option name="--test" short="" help="A test option." boolean="0">
<default></default>
<choices>
<choice>one</choice>
<choice>two</choice>
</choices>
</option>
</options>
<arguments>
<argument name="type" help="Resource type." required="1">
<choices>
<choice>aco</choice>
<choice>aro</choice>
</choices>
</argument>
</arguments>
<epilog>epilog text</epilog>
</shell>
TEXT;
$this->assertEquals(new DomDocument($expected), new DomDocument($result), 'Help does not match');
}
/**
* test description and epilog in the help
*
* @return void
*/
public function testXmlHelpDescriptionAndEpilog() {
$parser = new ConsoleOptionParser('mycommand', false);
$parser->description('Description text')
->epilog('epilog text')
->addOption('test', array('help' => 'A test option.'))
->addArgument('model', array('help' => 'The model to make.', 'required' => true));
$formatter = new HelpFormatter($parser);
$result = $formatter->xml();
$expected = <<<TEXT
<?xml version="1.0"?>
<shell>
<name>mycommand</name>
<description>Description text</description>
<subcommands />
<options>
<option name="--help" short="-h" help="Display this help." boolean="1">
<default></default>
<choices></choices>
</option>
<option name="--test" short="" help="A test option." boolean="0">
<default></default>
<choices></choices>
</option>
</options>
<arguments>
<argument name="model" help="The model to make." required="1">
<choices></choices>
</argument>
</arguments>
<epilog>epilog text</epilog>
</shell>
TEXT;
$this->assertEquals(new DomDocument($expected), new DomDocument($result), 'Help does not match');
}
/**
* test that help() outputs subcommands.
*
* @return void
*/
public function testXmlHelpSubcommand() {
$parser = new ConsoleOptionParser('mycommand', false);
$parser->addSubcommand('method', array('help' => 'This is another command'))
->addOption('test', array('help' => 'A test option.'));
$formatter = new HelpFormatter($parser);
$result = $formatter->xml();
$expected = <<<TEXT
<?xml version="1.0"?>
<shell>
<name>mycommand</name>
<description/>
<subcommands>
<command name="method" help="This is another command" />
</subcommands>
<options>
<option name="--help" short="-h" help="Display this help." boolean="1">
<default></default>
<choices></choices>
</option>
<option name="--test" short="" help="A test option." boolean="0">
<default></default>
<choices></choices>
</option>
</options>
<arguments/>
<epilog/>
</shell>
TEXT;
$this->assertEquals(new DomDocument($expected), new DomDocument($result), 'Help does not match');
}
/**
* test getting help with defined options.
*
* @return void
*/
public function testXmlHelpWithOptions() {
$parser = new ConsoleOptionParser('mycommand', false);
$parser->addOption('test', array('help' => 'A test option.'))
->addOption('connection', array(
'short' => 'c', 'help' => 'The connection to use.', 'default' => 'default'
));
$formatter = new HelpFormatter($parser);
$result = $formatter->xml();
$expected = <<<TEXT
<?xml version="1.0"?>
<shell>
<name>mycommand</name>
<description/>
<subcommands/>
<options>
<option name="--help" short="-h" help="Display this help." boolean="1">
<default></default>
<choices></choices>
</option>
<option name="--test" short="" help="A test option." boolean="0">
<default></default>
<choices></choices>
</option>
<option name="--connection" short="-c" help="The connection to use." boolean="0">
<default>default</default>
<choices></choices>
</option>
</options>
<arguments/>
<epilog/>
</shell>
TEXT;
$this->assertEquals(new DomDocument($expected), new DomDocument($result), 'Help does not match');
}
/**
* test getting help with defined options.
*
* @return void
*/
public function testXmlHelpWithOptionsAndArguments() {
$parser = new ConsoleOptionParser('mycommand', false);
$parser->addOption('test', array('help' => 'A test option.'))
->addArgument('model', array('help' => 'The model to make.', 'required' => true))
->addArgument('other_longer', array('help' => 'Another argument.'));
$formatter = new HelpFormatter($parser);
$result = $formatter->xml();
$expected = <<<TEXT
<?xml version="1.0"?>
<shell>
<name>mycommand</name>
<description/>
<subcommands/>
<options>
<option name="--help" short="-h" help="Display this help." boolean="1">
<default></default>
<choices></choices>
</option>
<option name="--test" short="" help="A test option." boolean="0">
<default></default>
<choices></choices>
</option>
</options>
<arguments>
<argument name="model" help="The model to make." required="1">
<choices></choices>
</argument>
<argument name="other_longer" help="Another argument." required="0">
<choices></choices>
</argument>
</arguments>
<epilog/>
</shell>
TEXT;
$this->assertEquals(new DomDocument($expected), new DomDocument($result), 'Help does not match');
}
/**
* Test xml help as object
*
* @return void
*/
public function testXmlHelpAsObject() {
$parser = new ConsoleOptionParser('mycommand', false);
$parser->addOption('test', array('help' => 'A test option.'))
->addArgument('model', array('help' => 'The model to make.', 'required' => true))
->addArgument('other_longer', array('help' => 'Another argument.'));
$formatter = new HelpFormatter($parser);
$result = $formatter->xml(false);
$this->assertInstanceOf('SimpleXmlElement', $result);
}
}

View file

@ -0,0 +1,566 @@
<?php
/**
* ShellDispatcherTest file
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Console
* @since CakePHP(tm) v 1.2.0.5432
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ShellDispatcher', 'Console');
/**
* TestShellDispatcher class
*
* @package Cake.Test.Case.Console
*/
class TestShellDispatcher extends ShellDispatcher {
/**
* params property
*
* @var array
*/
public $params = array();
/**
* stopped property
*
* @var string
*/
public $stopped = null;
/**
* TestShell
*
* @var mixed
*/
public $TestShell;
/**
* _initEnvironment method
*
* @return void
*/
protected function _initEnvironment() {
}
/**
* clear method
*
* @return void
*/
public function clear() {
}
/**
* _stop method
*
* @return void
*/
protected function _stop($status = 0) {
$this->stopped = 'Stopped with status: ' . $status;
return $status;
}
/**
* getShell
*
* @param string $shell
* @return mixed
*/
public function getShell($shell) {
return $this->_getShell($shell);
}
/**
* _getShell
*
* @param string $plugin
* @return mixed
*/
protected function _getShell($shell) {
if (isset($this->TestShell)) {
return $this->TestShell;
}
return parent::_getShell($shell);
}
}
/**
* ShellDispatcherTest
*
* @package Cake.Test.Case.Console
*/
class ShellDispatcherTest extends CakeTestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
App::build(array(
'Plugin' => array(
CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS
),
'Console/Command' => array(
CAKE . 'Test' . DS . 'test_app' . DS . 'Console' . DS . 'Command' . DS
)
), App::RESET);
CakePlugin::load('TestPlugin');
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
CakePlugin::unload();
}
/**
* testParseParams method
*
* @return void
*/
public function testParseParams() {
$Dispatcher = new TestShellDispatcher();
$params = array(
'/cake/1.2.x.x/cake/console/cake.php',
'bake',
'-app',
'new',
'-working',
'/var/www/htdocs'
);
$expected = array(
'app' => 'new',
'webroot' => 'webroot',
'working' => str_replace('/', DS, '/var/www/htdocs/new'),
'root' => str_replace('/', DS, '/var/www/htdocs')
);
$Dispatcher->parseParams($params);
$this->assertEquals($expected, $Dispatcher->params);
$params = array('cake.php');
$expected = array(
'app' => 'app',
'webroot' => 'webroot',
'working' => str_replace('\\', DS, dirname(CAKE_CORE_INCLUDE_PATH) . DS . 'app'),
'root' => str_replace('\\', DS, dirname(CAKE_CORE_INCLUDE_PATH)),
);
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEquals($expected, $Dispatcher->params);
$params = array(
'cake.php',
'-app',
'new',
);
$expected = array(
'app' => 'new',
'webroot' => 'webroot',
'working' => str_replace('\\', DS, dirname(CAKE_CORE_INCLUDE_PATH) . DS . 'new'),
'root' => str_replace('\\', DS, dirname(CAKE_CORE_INCLUDE_PATH))
);
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEquals($expected, $Dispatcher->params);
$params = array(
'./cake.php',
'bake',
'-app',
'new',
'-working',
'/cake/1.2.x.x/cake/console'
);
$expected = array(
'app' => 'new',
'webroot' => 'webroot',
'working' => str_replace('\\', DS, dirname(CAKE_CORE_INCLUDE_PATH) . DS . 'new'),
'root' => str_replace('\\', DS, dirname(CAKE_CORE_INCLUDE_PATH))
);
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEquals($expected, $Dispatcher->params);
$params = array(
'./console/cake.php',
'bake',
'-app',
'new',
'-working',
'/cake/1.2.x.x/cake'
);
$expected = array(
'app' => 'new',
'webroot' => 'webroot',
'working' => str_replace('\\', DS, dirname(CAKE_CORE_INCLUDE_PATH) . DS . 'new'),
'root' => str_replace('\\', DS, dirname(CAKE_CORE_INCLUDE_PATH))
);
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEquals($expected, $Dispatcher->params);
$params = array(
'./console/cake.php',
'bake',
'-app',
'new',
'-dry',
'-working',
'/cake/1.2.x.x/cake'
);
$expected = array(
'app' => 'new',
'working' => str_replace('\\', DS, dirname(CAKE_CORE_INCLUDE_PATH) . DS . 'new'),
'root' => str_replace('\\', DS, dirname(CAKE_CORE_INCLUDE_PATH)),
'webroot' => 'webroot'
);
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEquals($expected, $Dispatcher->params);
$params = array(
'./console/cake.php',
'-working',
'/cake/1.2.x.x/cake',
'schema',
'run',
'create',
'-dry',
'-f',
'-name',
'DbAcl'
);
$expected = array(
'app' => 'app',
'webroot' => 'webroot',
'working' => str_replace('\\', DS, dirname(CAKE_CORE_INCLUDE_PATH) . DS . 'app'),
'root' => str_replace('\\', DS, dirname(CAKE_CORE_INCLUDE_PATH)),
);
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEquals($expected, $Dispatcher->params);
$expected = array(
'./console/cake.php', 'schema', 'run', 'create', '-dry', '-f', '-name', 'DbAcl'
);
$this->assertEquals($expected, $Dispatcher->args);
$params = array(
'/cake/1.2.x.x/cake/console/cake.php',
'-working',
'/cake/1.2.x.x/app',
'schema',
'run',
'create',
'-dry',
'-name',
'DbAcl'
);
$expected = array(
'app' => 'app',
'webroot' => 'webroot',
'working' => str_replace('/', DS, '/cake/1.2.x.x/app'),
'root' => str_replace('/', DS, '/cake/1.2.x.x'),
);
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEquals($expected, $Dispatcher->params);
$params = array(
'cake.php',
'-working',
'C:/wamp/www/cake/app',
'bake',
'-app',
'C:/wamp/www/apps/cake/app',
);
$expected = array(
'app' => 'app',
'webroot' => 'webroot',
'working' => 'C:\wamp\www\apps\cake\app',
'root' => 'C:\wamp\www\apps\cake'
);
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEquals($expected, $Dispatcher->params);
$params = array(
'cake.php',
'-working',
'C:\wamp\www\cake\app',
'bake',
'-app',
'C:\wamp\www\apps\cake\app',
);
$expected = array(
'app' => 'app',
'webroot' => 'webroot',
'working' => 'C:\wamp\www\apps\cake\app',
'root' => 'C:\wamp\www\apps\cake'
);
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEquals($expected, $Dispatcher->params);
$params = array(
'cake.php',
'-working',
'C:\wamp\www\apps',
'bake',
'-app',
'cake\app',
'-url',
'http://example.com/some/url/with/a/path'
);
$expected = array(
'app' => 'app',
'webroot' => 'webroot',
'working' => 'C:\wamp\www\apps\cake\app',
'root' => 'C:\wamp\www\apps\cake',
);
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEquals($expected, $Dispatcher->params);
$params = array(
'/home/amelo/dev/cake-common/cake/console/cake.php',
'-root',
'/home/amelo/dev/lsbu-vacancy',
'-working',
'/home/amelo/dev/lsbu-vacancy',
'-app',
'app',
);
$expected = array(
'app' => 'app',
'webroot' => 'webroot',
'working' => '/home/amelo/dev/lsbu-vacancy/app',
'root' => '/home/amelo/dev/lsbu-vacancy',
);
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEquals($expected, $Dispatcher->params);
$params = array(
'/cake/1.2.x.x/cake/console/cake.php',
'bake',
'-app',
'new',
'-app',
'old',
'-working',
'/var/www/htdocs'
);
$expected = array(
'app' => 'old',
'webroot' => 'webroot',
'working' => str_replace('/', DS, '/var/www/htdocs/old'),
'root' => str_replace('/', DS, '/var/www/htdocs')
);
$Dispatcher->parseParams($params);
$this->assertEquals($expected, $Dispatcher->params);
if (DS === '\\') {
$params = array(
'cake.php',
'-working',
'D:\www',
'bake',
'my_app',
);
$expected = array(
'working' => 'D:\\\\www',
'app' => 'www',
'root' => 'D:\\',
'webroot' => 'webroot'
);
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEquals($expected, $Dispatcher->params);
}
}
/**
* Verify loading of (plugin-) shells
*
* @return void
*/
public function testGetShell() {
$this->skipIf(class_exists('SampleShell'), 'SampleShell Class already loaded.');
$this->skipIf(class_exists('ExampleShell'), 'ExampleShell Class already loaded.');
$Dispatcher = new TestShellDispatcher();
$result = $Dispatcher->getShell('sample');
$this->assertInstanceOf('SampleShell', $result);
$Dispatcher = new TestShellDispatcher();
$result = $Dispatcher->getShell('test_plugin.example');
$this->assertInstanceOf('ExampleShell', $result);
$this->assertEquals('TestPlugin', $result->plugin);
$this->assertEquals('Example', $result->name);
$Dispatcher = new TestShellDispatcher();
$result = $Dispatcher->getShell('TestPlugin.example');
$this->assertInstanceOf('ExampleShell', $result);
}
/**
* Verify correct dispatch of Shell subclasses with a main method
*
* @return void
*/
public function testDispatchShellWithMain() {
$Dispatcher = new TestShellDispatcher();
$Shell = $this->getMock('Shell');
$Shell->expects($this->once())->method('initialize');
$Shell->expects($this->once())->method('runCommand')
->with(null, array())
->will($this->returnValue(true));
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_with_main');
$result = $Dispatcher->dispatch();
$this->assertTrue($result);
$this->assertEquals(array(), $Dispatcher->args);
}
/**
* Verify correct dispatch of Shell subclasses without a main method
*
* @return void
*/
public function testDispatchShellWithoutMain() {
$Dispatcher = new TestShellDispatcher();
$Shell = $this->getMock('Shell');
$Shell->expects($this->once())->method('initialize');
$Shell->expects($this->once())->method('runCommand')
->with('initdb', array('initdb'))
->will($this->returnValue(true));
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_without_main', 'initdb');
$result = $Dispatcher->dispatch();
$this->assertTrue($result);
}
/**
* Verify correct dispatch of custom classes with a main method
*
* @return void
*/
public function testDispatchNotAShellWithMain() {
$Dispatcher = new TestShellDispatcher();
$methods = get_class_methods('Object');
array_push($methods, 'main', 'initdb', 'initialize', 'loadTasks', 'startup', '_secret');
$Shell = $this->getMock('Object', $methods);
$Shell->expects($this->never())->method('initialize');
$Shell->expects($this->once())->method('startup');
$Shell->expects($this->once())->method('main')->will($this->returnValue(true));
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_with_main_not_a');
$result = $Dispatcher->dispatch();
$this->assertTrue($result);
$this->assertEquals(array(), $Dispatcher->args);
$Shell = $this->getMock('Object', $methods);
$Shell->expects($this->once())->method('initdb')->will($this->returnValue(true));
$Shell->expects($this->once())->method('startup');
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_with_main_not_a', 'initdb');
$result = $Dispatcher->dispatch();
$this->assertTrue($result);
}
/**
* Verify correct dispatch of custom classes without a main method
*
* @return void
*/
public function testDispatchNotAShellWithoutMain() {
$Dispatcher = new TestShellDispatcher();
$methods = get_class_methods('Object');
array_push($methods, 'main', 'initdb', 'initialize', 'loadTasks', 'startup', '_secret');
$Shell = $this->getMock('Object', $methods);
$Shell->expects($this->never())->method('initialize');
$Shell->expects($this->once())->method('startup');
$Shell->expects($this->once())->method('main')->will($this->returnValue(true));
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_without_main_not_a');
$result = $Dispatcher->dispatch();
$this->assertTrue($result);
$this->assertEquals(array(), $Dispatcher->args);
$Shell = $this->getMock('Object', $methods);
$Shell->expects($this->once())->method('initdb')->will($this->returnValue(true));
$Shell->expects($this->once())->method('startup');
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_without_main_not_a', 'initdb');
$result = $Dispatcher->dispatch();
$this->assertTrue($result);
}
/**
* Verify shifting of arguments
*
* @return void
*/
public function testShiftArgs() {
$Dispatcher = new TestShellDispatcher();
$Dispatcher->args = array('a', 'b', 'c');
$this->assertEquals('a', $Dispatcher->shiftArgs());
$this->assertSame($Dispatcher->args, array('b', 'c'));
$Dispatcher->args = array('a' => 'b', 'c', 'd');
$this->assertEquals('b', $Dispatcher->shiftArgs());
$this->assertSame($Dispatcher->args, array('c', 'd'));
$Dispatcher->args = array('a', 'b' => 'c', 'd');
$this->assertEquals('a', $Dispatcher->shiftArgs());
$this->assertSame($Dispatcher->args, array('b' => 'c', 'd'));
$Dispatcher->args = array(0 => 'a', 2 => 'b', 30 => 'c');
$this->assertEquals('a', $Dispatcher->shiftArgs());
$this->assertSame($Dispatcher->args, array(0 => 'b', 1 => 'c'));
$Dispatcher->args = array();
$this->assertNull($Dispatcher->shiftArgs());
$this->assertSame(array(), $Dispatcher->args);
}
}

View file

@ -0,0 +1,903 @@
<?php
/**
* ShellTest file
*
* Test Case for Shell
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.Console.Command
* @since CakePHP v 1.2.0.7726
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ShellDispatcher', 'Console');
App::uses('Shell', 'Console');
App::uses('Folder', 'Utility');
/**
* ShellTestShell class
*
* @package Cake.Test.Case.Console.Command
*/
class ShellTestShell extends Shell {
/**
* name property
*
* @var name
*/
public $name = 'ShellTestShell';
/**
* stopped property
*
* @var int
*/
public $stopped;
/**
* testMessage property
*
* @var string
*/
public $testMessage = 'all your base are belong to us';
/**
* stop method
*
* @param int $status
* @return void
*/
protected function _stop($status = 0) {
$this->stopped = $status;
}
protected function _secret() {
}
//@codingStandardsIgnoreStart
public function do_something() {
}
protected function no_access() {
}
public function log_something() {
$this->log($this->testMessage);
}
//@codingStandardsIgnoreEnd
public function mergeVars($properties, $class, $normalize = true) {
return $this->_mergeVars($properties, $class, $normalize);
}
public function useLogger($enable = true) {
$this->_useLogger($enable);
}
}
/**
* Class for testing merging vars
*
* @package Cake.Test.Case.Console.Command
*/
class TestMergeShell extends Shell {
public $tasks = array('DbConfig', 'Fixture');
public $uses = array('Comment');
}
/**
* TestAppleTask class
*
* @package Cake.Test.Case.Console.Command
*/
class TestAppleTask extends Shell {
}
/**
* TestBananaTask class
*
* @package Cake.Test.Case.Console.Command
*/
class TestBananaTask extends Shell {
}
/**
* ShellTest class
*
* @package Cake.Test.Case.Console.Command
*/
class ShellTest extends CakeTestCase {
/**
* Fixtures used in this test case
*
* @var array
*/
public $fixtures = array(
'core.post', 'core.comment', 'core.article', 'core.user',
'core.tag', 'core.articles_tag', 'core.attachment'
);
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$output = $this->getMock('ConsoleOutput', array(), array(), '', false);
$error = $this->getMock('ConsoleOutput', array(), array(), '', false);
$in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->Shell = new ShellTestShell($output, $error, $in);
if (is_dir(TMP . 'shell_test')) {
$Folder = new Folder(TMP . 'shell_test');
$Folder->delete();
}
}
/**
* testConstruct method
*
* @return void
*/
public function testConstruct() {
$this->assertEquals('ShellTestShell', $this->Shell->name);
$this->assertInstanceOf('ConsoleInput', $this->Shell->stdin);
$this->assertInstanceOf('ConsoleOutput', $this->Shell->stdout);
$this->assertInstanceOf('ConsoleOutput', $this->Shell->stderr);
}
/**
* test merging vars
*
* @return void
*/
public function testMergeVars() {
$this->Shell->tasks = array('DbConfig' => array('one', 'two'));
$this->Shell->uses = array('Posts');
$this->Shell->mergeVars(array('tasks'), 'TestMergeShell');
$this->Shell->mergeVars(array('uses'), 'TestMergeShell', false);
$expected = array('DbConfig' => null, 'Fixture' => null, 'DbConfig' => array('one', 'two'));
$this->assertEquals($expected, $this->Shell->tasks);
$expected = array('Fixture' => null, 'DbConfig' => array('one', 'two'));
$this->assertEquals($expected, Hash::normalize($this->Shell->tasks), 'Normalized results are wrong.');
$this->assertEquals(array('Comment', 'Posts'), $this->Shell->uses, 'Merged models are wrong.');
}
/**
* testInitialize method
*
* @return void
*/
public function testInitialize() {
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS),
'Model' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Model' . DS)
), App::RESET);
CakePlugin::load('TestPlugin');
$this->Shell->tasks = array('DbConfig' => array('one', 'two'));
$this->Shell->uses = array('TestPlugin.TestPluginPost');
$this->Shell->initialize();
$this->assertTrue(isset($this->Shell->TestPluginPost));
$this->assertInstanceOf('TestPluginPost', $this->Shell->TestPluginPost);
$this->assertEquals('TestPluginPost', $this->Shell->modelClass);
CakePlugin::unload('TestPlugin');
$this->Shell->uses = array('Comment');
$this->Shell->initialize();
$this->assertTrue(isset($this->Shell->Comment));
$this->assertInstanceOf('Comment', $this->Shell->Comment);
$this->assertEquals('Comment', $this->Shell->modelClass);
$this->assertInstanceOf('DbConfigTask', $this->Shell->DbConfig);
App::build();
}
/**
* testLoadModel method
*
* @return void
*/
public function testLoadModel() {
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS),
'Model' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Model' . DS)
), App::RESET);
$Shell = new TestMergeShell();
$this->assertEquals('Comment', $Shell->Comment->alias);
$this->assertInstanceOf('Comment', $Shell->Comment);
$this->assertEquals('Comment', $Shell->modelClass);
CakePlugin::load('TestPlugin');
$this->Shell->loadModel('TestPlugin.TestPluginPost');
$this->assertTrue(isset($this->Shell->TestPluginPost));
$this->assertInstanceOf('TestPluginPost', $this->Shell->TestPluginPost);
$this->assertEquals('TestPluginPost', $this->Shell->modelClass);
CakePlugin::unload('TestPlugin');
App::build();
}
/**
* testIn method
*
* @return void
*/
public function testIn() {
$this->Shell->stdin->expects($this->at(0))
->method('read')
->will($this->returnValue('n'));
$this->Shell->stdin->expects($this->at(1))
->method('read')
->will($this->returnValue('Y'));
$this->Shell->stdin->expects($this->at(2))
->method('read')
->will($this->returnValue('y'));
$this->Shell->stdin->expects($this->at(3))
->method('read')
->will($this->returnValue('y'));
$this->Shell->stdin->expects($this->at(4))
->method('read')
->will($this->returnValue('y'));
$this->Shell->stdin->expects($this->at(5))
->method('read')
->will($this->returnValue('0'));
$result = $this->Shell->in('Just a test?', array('y', 'n'), 'n');
$this->assertEquals('n', $result);
$result = $this->Shell->in('Just a test?', array('y', 'n'), 'n');
$this->assertEquals('Y', $result);
$result = $this->Shell->in('Just a test?', 'y,n', 'n');
$this->assertEquals('y', $result);
$result = $this->Shell->in('Just a test?', 'y/n', 'n');
$this->assertEquals('y', $result);
$result = $this->Shell->in('Just a test?', 'y', 'y');
$this->assertEquals('y', $result);
$result = $this->Shell->in('Just a test?', array(0, 1, 2), '0');
$this->assertEquals('0', $result);
}
/**
* Test in() when not interactive.
*
* @return void
*/
public function testInNonInteractive() {
$this->Shell->interactive = false;
$result = $this->Shell->in('Just a test?', 'y/n', 'n');
$this->assertEquals('n', $result);
}
/**
* testOut method
*
* @return void
*/
public function testOut() {
$this->Shell->stdout->expects($this->at(0))
->method('write')
->with("Just a test", 1);
$this->Shell->stdout->expects($this->at(1))
->method('write')
->with(array('Just', 'a', 'test'), 1);
$this->Shell->stdout->expects($this->at(2))
->method('write')
->with(array('Just', 'a', 'test'), 2);
$this->Shell->stdout->expects($this->at(3))
->method('write')
->with('', 1);
$this->Shell->out('Just a test');
$this->Shell->out(array('Just', 'a', 'test'));
$this->Shell->out(array('Just', 'a', 'test'), 2);
$this->Shell->out();
}
/**
* test that verbose and quiet output levels work
*
* @return void
*/
public function testVerboseOutput() {
$this->Shell->stdout->expects($this->at(0))->method('write')
->with('Verbose', 1);
$this->Shell->stdout->expects($this->at(1))->method('write')
->with('Normal', 1);
$this->Shell->stdout->expects($this->at(2))->method('write')
->with('Quiet', 1);
$this->Shell->params['verbose'] = true;
$this->Shell->params['quiet'] = false;
$this->Shell->out('Verbose', 1, Shell::VERBOSE);
$this->Shell->out('Normal', 1, Shell::NORMAL);
$this->Shell->out('Quiet', 1, Shell::QUIET);
}
/**
* test that verbose and quiet output levels work
*
* @return void
*/
public function testQuietOutput() {
$this->Shell->stdout->expects($this->once())->method('write')
->with('Quiet', 1);
$this->Shell->params['verbose'] = false;
$this->Shell->params['quiet'] = true;
$this->Shell->out('Verbose', 1, Shell::VERBOSE);
$this->Shell->out('Normal', 1, Shell::NORMAL);
$this->Shell->out('Quiet', 1, Shell::QUIET);
}
/**
* testErr method
*
* @return void
*/
public function testErr() {
$this->Shell->stderr->expects($this->at(0))
->method('write')
->with("Just a test", 1);
$this->Shell->stderr->expects($this->at(1))
->method('write')
->with(array('Just', 'a', 'test'), 1);
$this->Shell->stderr->expects($this->at(2))
->method('write')
->with(array('Just', 'a', 'test'), 2);
$this->Shell->stderr->expects($this->at(3))
->method('write')
->with('', 1);
$this->Shell->err('Just a test');
$this->Shell->err(array('Just', 'a', 'test'));
$this->Shell->err(array('Just', 'a', 'test'), 2);
$this->Shell->err();
}
/**
* testNl
*
* @return void
*/
public function testNl() {
$newLine = "\n";
if (DS === '\\') {
$newLine = "\r\n";
}
$this->assertEquals($this->Shell->nl(), $newLine);
$this->assertEquals($this->Shell->nl(true), $newLine);
$this->assertEquals("", $this->Shell->nl(false));
$this->assertEquals($this->Shell->nl(2), $newLine . $newLine);
$this->assertEquals($this->Shell->nl(1), $newLine);
}
/**
* testHr
*
* @return void
*/
public function testHr() {
$bar = '---------------------------------------------------------------';
$this->Shell->stdout->expects($this->at(0))->method('write')->with('', 0);
$this->Shell->stdout->expects($this->at(1))->method('write')->with($bar, 1);
$this->Shell->stdout->expects($this->at(2))->method('write')->with('', 0);
$this->Shell->stdout->expects($this->at(3))->method('write')->with("", true);
$this->Shell->stdout->expects($this->at(4))->method('write')->with($bar, 1);
$this->Shell->stdout->expects($this->at(5))->method('write')->with("", true);
$this->Shell->stdout->expects($this->at(6))->method('write')->with("", 2);
$this->Shell->stdout->expects($this->at(7))->method('write')->with($bar, 1);
$this->Shell->stdout->expects($this->at(8))->method('write')->with("", 2);
$this->Shell->hr();
$this->Shell->hr(true);
$this->Shell->hr(2);
}
/**
* testError
*
* @return void
*/
public function testError() {
$this->Shell->stderr->expects($this->at(0))
->method('write')
->with("<error>Error:</error> Foo Not Found", 1);
$this->Shell->stderr->expects($this->at(1))
->method('write')
->with("<error>Error:</error> Foo Not Found", 1);
$this->Shell->stderr->expects($this->at(2))
->method('write')
->with("Searched all...", 1);
$this->Shell->error('Foo Not Found');
$this->assertSame($this->Shell->stopped, 1);
$this->Shell->stopped = null;
$this->Shell->error('Foo Not Found', 'Searched all...');
$this->assertSame($this->Shell->stopped, 1);
}
/**
* testLoadTasks method
*
* @return void
*/
public function testLoadTasks() {
$this->assertTrue($this->Shell->loadTasks());
$this->Shell->tasks = null;
$this->assertTrue($this->Shell->loadTasks());
$this->Shell->tasks = false;
$this->assertTrue($this->Shell->loadTasks());
$this->Shell->tasks = true;
$this->assertTrue($this->Shell->loadTasks());
$this->Shell->tasks = array();
$this->assertTrue($this->Shell->loadTasks());
$this->Shell->tasks = array('TestApple');
$this->assertTrue($this->Shell->loadTasks());
$this->assertInstanceOf('TestAppleTask', $this->Shell->TestApple);
$this->Shell->tasks = 'TestBanana';
$this->assertTrue($this->Shell->loadTasks());
$this->assertInstanceOf('TestAppleTask', $this->Shell->TestApple);
$this->assertInstanceOf('TestBananaTask', $this->Shell->TestBanana);
unset($this->Shell->ShellTestApple, $this->Shell->TestBanana);
$this->Shell->tasks = array('TestApple', 'TestBanana');
$this->assertTrue($this->Shell->loadTasks());
$this->assertInstanceOf('TestAppleTask', $this->Shell->TestApple);
$this->assertInstanceOf('TestBananaTask', $this->Shell->TestBanana);
}
/**
* test that __get() makes args and params references
*
* @return void
*/
public function testMagicGetArgAndParamReferences() {
$this->Shell->tasks = array('TestApple');
$this->Shell->args = array('one');
$this->Shell->params = array('help' => false);
$this->Shell->loadTasks();
$result = $this->Shell->TestApple;
$this->Shell->args = array('one', 'two');
$this->assertSame($this->Shell->args, $result->args);
$this->assertSame($this->Shell->params, $result->params);
}
/**
* testShortPath method
*
* @return void
*/
public function testShortPath() {
$path = $expected = DS . 'tmp' . DS . 'ab' . DS . 'cd';
$this->assertEquals($expected, $this->Shell->shortPath($path));
$path = $expected = DS . 'tmp' . DS . 'ab' . DS . 'cd' . DS;
$this->assertEquals($expected, $this->Shell->shortPath($path));
$path = $expected = DS . 'tmp' . DS . 'ab' . DS . 'index.php';
$this->assertEquals($expected, $this->Shell->shortPath($path));
$path = DS . 'tmp' . DS . 'ab' . DS . DS . 'cd';
$expected = DS . 'tmp' . DS . 'ab' . DS . 'cd';
$this->assertEquals($expected, $this->Shell->shortPath($path));
$path = 'tmp' . DS . 'ab';
$expected = 'tmp' . DS . 'ab';
$this->assertEquals($expected, $this->Shell->shortPath($path));
$path = 'tmp' . DS . 'ab';
$expected = 'tmp' . DS . 'ab';
$this->assertEquals($expected, $this->Shell->shortPath($path));
$path = APP;
$expected = DS . basename(APP) . DS;
$this->assertEquals($expected, $this->Shell->shortPath($path));
$path = APP . 'index.php';
$expected = DS . basename(APP) . DS . 'index.php';
$this->assertEquals($expected, $this->Shell->shortPath($path));
}
/**
* testCreateFile method
*
* @return void
*/
public function testCreateFileNonInteractive() {
$eol = PHP_EOL;
$path = TMP . 'shell_test';
$file = $path . DS . 'file1.php';
new Folder($path, true);
$this->Shell->interactive = false;
$contents = "<?php{$eol}echo 'test';${eol}\$te = 'st';{$eol}";
$result = $this->Shell->createFile($file, $contents);
$this->assertTrue($result);
$this->assertTrue(file_exists($file));
$this->assertEquals(file_get_contents($file), $contents);
$contents = "<?php\necho 'another test';\n\$te = 'st';\n";
$result = $this->Shell->createFile($file, $contents);
$this->assertTrue($result);
$this->assertTrue(file_exists($file));
$this->assertTextEquals(file_get_contents($file), $contents);
}
/**
* test createFile when the shell is interactive.
*
* @return void
*/
public function testCreateFileInteractive() {
$eol = PHP_EOL;
$path = TMP . 'shell_test';
$file = $path . DS . 'file1.php';
new Folder($path, true);
$this->Shell->interactive = true;
$this->Shell->stdin->expects($this->at(0))
->method('read')
->will($this->returnValue('n'));
$this->Shell->stdin->expects($this->at(1))
->method('read')
->will($this->returnValue('y'));
$contents = "<?php{$eol}echo 'yet another test';{$eol}\$te = 'st';{$eol}";
$result = $this->Shell->createFile($file, $contents);
$this->assertTrue($result);
$this->assertTrue(file_exists($file));
$this->assertEquals(file_get_contents($file), $contents);
// no overwrite
$contents = 'new contents';
$result = $this->Shell->createFile($file, $contents);
$this->assertFalse($result);
$this->assertTrue(file_exists($file));
$this->assertNotEquals($contents, file_get_contents($file));
// overwrite
$contents = 'more new contents';
$result = $this->Shell->createFile($file, $contents);
$this->assertTrue($result);
$this->assertTrue(file_exists($file));
$this->assertEquals($contents, file_get_contents($file));
}
/**
* Test that you can't create files that aren't writable.
*
* @return void
*/
public function testCreateFileNoPermissions() {
$this->skipIf(DIRECTORY_SEPARATOR === '\\', 'Cant perform operations using permissions on windows.');
$path = TMP . 'shell_test';
$file = $path . DS . 'no_perms';
if (!is_dir($path)) {
mkdir($path);
}
chmod($path, 0444);
$this->Shell->createFile($file, 'testing');
$this->assertFalse(file_exists($file));
chmod($path, 0744);
rmdir($path);
}
/**
* test hasTask method
*
* @return void
*/
public function testHasTask() {
$this->Shell->tasks = array('Extract', 'DbConfig');
$this->Shell->loadTasks();
$this->assertTrue($this->Shell->hasTask('extract'));
$this->assertTrue($this->Shell->hasTask('Extract'));
$this->assertFalse($this->Shell->hasTask('random'));
$this->assertTrue($this->Shell->hasTask('db_config'));
$this->assertTrue($this->Shell->hasTask('DbConfig'));
}
/**
* test the hasMethod
*
* @return void
*/
public function testHasMethod() {
$this->assertTrue($this->Shell->hasMethod('do_something'));
$this->assertFalse($this->Shell->hasMethod('hr'), 'hr is callable');
$this->assertFalse($this->Shell->hasMethod('_secret'), '_secret is callable');
$this->assertFalse($this->Shell->hasMethod('no_access'), 'no_access is callable');
}
/**
* test run command calling main.
*
* @return void
*/
public function testRunCommandMain() {
$Mock = $this->getMock('Shell', array('main', 'startup'), array(), '', false);
$Mock->expects($this->once())->method('main')->will($this->returnValue(true));
$result = $Mock->runCommand(null, array());
$this->assertTrue($result);
}
/**
* test run command calling a legit method.
*
* @return void
*/
public function testRunCommandWithMethod() {
$Mock = $this->getMock('Shell', array('hit_me', 'startup'), array(), '', false);
$Mock->expects($this->once())->method('hit_me')->will($this->returnValue(true));
$result = $Mock->runCommand('hit_me', array());
$this->assertTrue($result);
}
/**
* test run command causing exception on Shell method.
*
* @return void
*/
public function testRunCommandBaseclassMethod() {
$Mock = $this->getMock('Shell', array('startup', 'getOptionParser', 'out'), array(), '', false);
$Parser = $this->getMock('ConsoleOptionParser', array(), array(), '', false);
$Parser->expects($this->once())->method('help');
$Mock->expects($this->once())->method('getOptionParser')
->will($this->returnValue($Parser));
$Mock->expects($this->never())->method('hr');
$Mock->expects($this->once())->method('out');
$Mock->runCommand('hr', array());
}
/**
* test run command causing exception on Shell method.
*
* @return void
*/
public function testRunCommandMissingMethod() {
$Mock = $this->getMock('Shell', array('startup', 'getOptionParser', 'out'), array(), '', false);
$Parser = $this->getMock('ConsoleOptionParser', array(), array(), '', false);
$Parser->expects($this->once())->method('help');
$Mock->expects($this->never())->method('idontexist');
$Mock->expects($this->once())->method('getOptionParser')
->will($this->returnValue($Parser));
$Mock->expects($this->once())->method('out');
$result = $Mock->runCommand('idontexist', array());
$this->assertFalse($result);
}
/**
* test that a --help causes help to show.
*
* @return void
*/
public function testRunCommandTriggeringHelp() {
$Parser = $this->getMock('ConsoleOptionParser', array(), array(), '', false);
$Parser->expects($this->once())->method('parse')
->with(array('--help'))
->will($this->returnValue(array(array('help' => true), array())));
$Parser->expects($this->once())->method('help');
$Shell = $this->getMock('Shell', array('getOptionParser', 'out', 'startup', '_welcome'), array(), '', false);
$Shell->expects($this->once())->method('getOptionParser')
->will($this->returnValue($Parser));
$Shell->expects($this->once())->method('out');
$Shell->runCommand(null, array('--help'));
}
/**
* test that runCommand will call runCommand on the task.
*
* @return void
*/
public function testRunCommandHittingTask() {
$Shell = $this->getMock('Shell', array('hasTask', 'startup'), array(), '', false);
$task = $this->getMock('Shell', array('execute', 'runCommand'), array(), '', false);
$task->expects($this->any())
->method('runCommand')
->with('execute', array('one', 'value'));
$Shell->expects($this->once())->method('startup');
$Shell->expects($this->any())
->method('hasTask')
->will($this->returnValue(true));
$Shell->RunCommand = $task;
$Shell->runCommand('run_command', array('run_command', 'one', 'value'));
}
/**
* test wrapBlock wrapping text.
*
* @return void
*/
public function testWrapText() {
$text = 'This is the song that never ends. This is the song that never ends. This is the song that never ends.';
$result = $this->Shell->wrapText($text, 33);
$expected = <<<TEXT
This is the song that never ends.
This is the song that never ends.
This is the song that never ends.
TEXT;
$this->assertTextEquals($expected, $result, 'Text not wrapped.');
$result = $this->Shell->wrapText($text, array('indent' => ' ', 'width' => 33));
$expected = <<<TEXT
This is the song that never ends.
This is the song that never ends.
This is the song that never ends.
TEXT;
$this->assertTextEquals($expected, $result, 'Text not wrapped.');
}
/**
* Testing camel cased naming of tasks
*
* @return void
*/
public function testShellNaming() {
$this->Shell->tasks = array('TestApple');
$this->Shell->loadTasks();
$expected = 'TestApple';
$this->assertEquals($expected, $this->Shell->TestApple->name);
}
/**
* Test that option parsers are created with the correct name/command.
*
* @return void
*/
public function testGetOptionParser() {
$this->Shell->name = 'test';
$this->Shell->plugin = 'plugin';
$parser = $this->Shell->getOptionParser();
$this->assertEquals('plugin.test', $parser->command());
}
/**
* Test file and console and logging
*
* @return void
*/
public function testFileAndConsoleLogging() {
// file logging
$this->Shell->log_something();
$this->assertTrue(file_exists(LOGS . 'error.log'));
unlink(LOGS . 'error.log');
$this->assertFalse(file_exists(LOGS . 'error.log'));
// both file and console logging
require_once CORE_TEST_CASES . DS . 'Log' . DS . 'Engine' . DS . 'ConsoleLogTest.php';
$mock = $this->getMock('ConsoleLog', array('write'), array(
array('types' => 'error'),
));
TestCakeLog::config('console', array(
'engine' => 'Console',
'stream' => 'php://stderr',
));
TestCakeLog::replace('console', $mock);
$mock->expects($this->once())
->method('write')
->with('error', $this->Shell->testMessage);
$this->Shell->log_something();
$this->assertTrue(file_exists(LOGS . 'error.log'));
$contents = file_get_contents(LOGS . 'error.log');
$this->assertContains($this->Shell->testMessage, $contents);
}
/**
* Tests that _useLogger works properly
*
* @return void
*/
public function testProtectedUseLogger() {
CakeLog::drop('stdout');
CakeLog::drop('stderr');
$this->Shell->useLogger(true);
$this->assertNotEmpty(CakeLog::stream('stdout'));
$this->assertNotEmpty(CakeLog::stream('stderr'));
$this->Shell->useLogger(false);
$this->assertFalse(CakeLog::stream('stdout'));
$this->assertFalse(CakeLog::stream('stderr'));
}
/**
* Test file and console and logging quiet output
*
* @return void
*/
public function testQuietLog() {
$output = $this->getMock('ConsoleOutput', array(), array(), '', false);
$error = $this->getMock('ConsoleOutput', array(), array(), '', false);
$in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->Shell = $this->getMock('ShellTestShell', array('_useLogger'), array($output, $error, $in));
$this->Shell->expects($this->once())->method('_useLogger')->with(false);
$this->Shell->runCommand('foo', array('--quiet'));
}
}

View file

@ -0,0 +1,155 @@
<?php
/**
* TaskCollectionTest file
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Console
* @since CakePHP(tm) v 2.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('TaskCollection', 'Console');
App::uses('Shell', 'Console');
/**
* Extended Task
*/
class DbConfigAliasedTask extends Shell {
}
/**
* Class TaskCollectionTest
*
* @package Cake.Test.Case.Console
*/
class TaskCollectionTest extends CakeTestCase {
/**
* setUp
*
* @return void
*/
public function setUp() {
parent::setUp();
$shell = $this->getMock('Shell', array(), array(), '', false);
$dispatcher = $this->getMock('ShellDispatcher', array(), array(), '', false);
$this->Tasks = new TaskCollection($shell, $dispatcher);
}
/**
* tearDown
*
* @return void
*/
public function tearDown() {
unset($this->Tasks);
parent::tearDown();
}
/**
* test triggering callbacks on loaded tasks
*
* @return void
*/
public function testLoad() {
$result = $this->Tasks->load('DbConfig');
$this->assertInstanceOf('DbConfigTask', $result);
$this->assertInstanceOf('DbConfigTask', $this->Tasks->DbConfig);
$result = $this->Tasks->loaded();
$this->assertEquals(array('DbConfig'), $result, 'loaded() results are wrong.');
}
/**
* test load and enable = false
*
* @return void
*/
public function testLoadWithEnableFalse() {
$result = $this->Tasks->load('DbConfig', array('enabled' => false));
$this->assertInstanceOf('DbConfigTask', $result);
$this->assertInstanceOf('DbConfigTask', $this->Tasks->DbConfig);
$this->assertFalse($this->Tasks->enabled('DbConfig'), 'DbConfigTask should be disabled');
}
/**
* test missingtask exception
*
* @expectedException MissingTaskException
* @return void
*/
public function testLoadMissingTask() {
$this->Tasks->load('ThisTaskShouldAlwaysBeMissing');
}
/**
* test loading a plugin helper.
*
* @return void
*/
public function testLoadPluginTask() {
$dispatcher = $this->getMock('ShellDispatcher', array(), array(), '', false);
$shell = $this->getMock('Shell', array(), array(), '', false);
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
));
CakePlugin::load('TestPlugin');
$this->Tasks = new TaskCollection($shell, $dispatcher);
$result = $this->Tasks->load('TestPlugin.OtherTask');
$this->assertInstanceOf('OtherTaskTask', $result, 'Task class is wrong.');
$this->assertInstanceOf('OtherTaskTask', $this->Tasks->OtherTask, 'Class is wrong');
CakePlugin::unload();
}
/**
* test unload()
*
* @return void
*/
public function testUnload() {
$this->Tasks->load('Extract');
$this->Tasks->load('DbConfig');
$result = $this->Tasks->loaded();
$this->assertEquals(array('Extract', 'DbConfig'), $result, 'loaded tasks is wrong');
$this->Tasks->unload('DbConfig');
$this->assertFalse(isset($this->Tasks->DbConfig));
$this->assertTrue(isset($this->Tasks->Extract));
$result = $this->Tasks->loaded();
$this->assertEquals(array('Extract'), $result, 'loaded tasks is wrong');
}
/**
* Tests loading as an alias
*
* @return void
*/
public function testLoadWithAlias() {
$result = $this->Tasks->load('DbConfig', array('className' => 'DbConfigAliased'));
$this->assertInstanceOf('DbConfigAliasedTask', $result);
$this->assertInstanceOf('DbConfigAliasedTask', $this->Tasks->DbConfig);
$result = $this->Tasks->loaded();
$this->assertEquals(array('DbConfig'), $result, 'loaded() results are wrong.');
$result = $this->Tasks->load('SomeTask', array('className' => 'TestPlugin.OtherTask'));
$this->assertInstanceOf('OtherTaskTask', $result);
$this->assertInstanceOf('OtherTaskTask', $this->Tasks->SomeTask);
$result = $this->Tasks->loaded();
$this->assertEquals(array('DbConfig', 'SomeTask'), $result, 'loaded() results are wrong.');
}
}