Class TestTask
Task class for creating and updating test files.
Copyright: Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
License: MIT License
Location: Cake/Console/Command/Task/TestTask.php
Inherited Constants
Properties summary
-
$_fixtures
protectedInternal list of fixtures that have been added so far.array
-
$baseTypes
publicarray
Mapping between packages, and their baseclass + package. This is used to generate App::uses() call to autoload base classes if a developer has forgotten to do so.
-
$classTypes
publicclass types that methods can be generated forarray
-
$path
publicpath to TESTS directorystring
-
$tasks
publicTasks used.array
Inherited Properties
-
connection
,interactive
,plugin
OptionParser
,Tasks
,_helpers
,_lastWritten
,_taskMap
,args
,command
,modelClass
,name
,params
,stderr
,stdin
,stdout
,taskNames
,uses
Method Summary
- _addFixture() protected
Add class name to the fixture list. Sets the app. or plugin.plugin_name. prefix.
- _interactive() protectedHandles interactive baking
- _processController() protected
Process all the models attached to a controller and generate a fixture list.
- _processModel() protected
Process a model recursively and pull out all the model names converting them to fixture names.
- bake() publicCompletes final steps for generating data to create test case.
- buildTestSubject() public
Construct an instance of the class to be tested. So that fixtures can be detected
- execute() publicExecution method always used for tasks
- generateConstructor() publicGenerate a constructor code snippet for the type and class name
- generateFixtureList() public
Generate the list of fixtures that will be required to run this test based on loaded models.
- generateUses() publicGenerate the uses() calls for a type & class name
- getBaseType() publicGet the base class and package name for a given type.
- getClassName() publicGet the user chosen Class name for the chosen type
- getObjectType() publicInteract with the user and get their chosen type. Can exit the script.
- getOptionParser() publicGets the option parser instance and configures it.
- getRealClassName() public
Gets the real class name from the cake short form. If the class name is already suffixed with the type, the type will not be duplicated.
- getTestableMethods() public
Get methods declared in the class given. No parent methods will be returned
- getUserFixtures() publicInteract with the user to get additional fixtures they want to use.
- hasMockClass() public
Is a mock class required for this type of test? Controllers require a mock class.
- isLoadableClass() publicCheck if a class with the given package is loaded or can be loaded.
- mapType() publicMap the types that TestTask uses to concrete types that App::uses can use.
- testCaseFileName() public
Make the filename for the test case. resolve the suffixes for controllers and get the plugin path if needed.
- typeCanDetectFixtures() public
Checks whether the chosen type can find its own fixtures. Currently only model, and controller are supported
Method Detail
_addFixture()source protected
_addFixture( string $name )
Add class name to the fixture list. Sets the app. or plugin.plugin_name. prefix.
Parameters
- string
$name
- Name of the Model class that a fixture might be required for.
_interactive()source protected
_interactive( string $type null )
Handles interactive baking
Parameters
- string
$type
optional null - The type of object to bake a test for.
Returns
string|boolean_processController()source protected
_processController( Controller $subject )
Process all the models attached to a controller and generate a fixture list.
Parameters
-
Controller
$subject
- A controller to pull model names off of.
_processModel()source protected
_processModel( Model $subject )
Process a model recursively and pull out all the model names converting them to fixture names.
Parameters
-
Model
$subject
- A Model class to scan for associations and pull fixtures off of.
bake()source public
bake( string $type , string $className )
Completes final steps for generating data to create test case.
Parameters
- string
$type
- Type of object to bake test case for ie. Model, Controller
- string
$className
- the 'cake name' for the class ie. Posts for the PostsController
Returns
string|booleanbuildTestSubject()source public
buildTestSubject( string $type , string $class )
Construct an instance of the class to be tested. So that fixtures can be detected
Parameters
- string
$type
- The Type of object you are generating tests for eg. controller
- string
$class
- the Classname of the class the test is being generated for.
Returns
objectAnd instance of the class that is going to be tested.
execute()source public
execute( )
Execution method always used for tasks
Overrides
BakeTask::execute()
generateConstructor()source public
generateConstructor( string $type , string $fullClassName , string $plugin )
Generate a constructor code snippet for the type and class name
Parameters
- string
$type
- The Type of object you are generating tests for eg. controller
- string
$fullClassName
- The Classname of the class the test is being generated for.
- string
$plugin
- The plugin name.
Returns
arrayConstructor snippets for the thing you are building.
generateFixtureList()source public
generateFixtureList( object $subject )
Generate the list of fixtures that will be required to run this test based on loaded models.
Parameters
- object
$subject
- The object you want to generate fixtures for.
Returns
arrayArray of fixtures to be included in the test.
generateUses()source public
generateUses( string $type , string $realType , string $className )
Generate the uses() calls for a type & class name
Parameters
- string
$type
- The Type of object you are generating tests for eg. controller
- string
$realType
- The package name for the class.
- string
$className
- The Classname of the class the test is being generated for.
Returns
arrayAn array containing used classes
getBaseType()source public
getBaseType( string $type )
Get the base class and package name for a given type.
Parameters
- string
$type
The type the class having a test generated for is in.
Returns
arrayArray of (class, type)
Throws
CakeException
on invalid types.
getClassName()source public
getClassName( string $objectType )
Get the user chosen Class name for the chosen type
Parameters
- string
$objectType
- Type of object to list classes for i.e. Model, Controller.
Returns
stringClass name the user chose.
getObjectType()source public
getObjectType( )
Interact with the user and get their chosen type. Can exit the script.
Returns
stringUsers chosen type.
getOptionParser()source public
getOptionParser( )
Gets the option parser instance and configures it.
Returns
ConsoleOptionParser
Overrides
Shell::getOptionParser()
getRealClassName()source public
getRealClassName( string $type , string $class )
Gets the real class name from the cake short form. If the class name is already suffixed with the type, the type will not be duplicated.
Parameters
- string
$type
- The Type of object you are generating tests for eg. controller
- string
$class
- the Classname of the class the test is being generated for.
Returns
stringReal class name
getTestableMethods()source public
getTestableMethods( string $className )
Get methods declared in the class given. No parent methods will be returned
Parameters
- string
$className
- Name of class to look at.
Returns
arrayArray of method names.
getUserFixtures()source public
getUserFixtures( )
Interact with the user to get additional fixtures they want to use.
Returns
arrayArray of fixtures the user wants to add.
hasMockClass()source public
hasMockClass( string $type )
Is a mock class required for this type of test? Controllers require a mock class.
Parameters
- string
$type
- The type of object tests are being generated for eg. controller.
Returns
booleanisLoadableClass()source public
isLoadableClass( string $package , string $class )
Check if a class with the given package is loaded or can be loaded.
Parameters
- string
$package
- The package of object you are generating tests for eg. controller
- string
$class
- the Classname of the class the test is being generated for.
Returns
booleanmapType()source public
mapType( string $type , string $plugin )
Map the types that TestTask uses to concrete types that App::uses can use.
Parameters
- string
$type
- The type of thing having a test generated.
- string
$plugin
- The plugin name.
Returns
stringThrows
CakeException
When invalid object types are requested.
testCaseFileName()source public
testCaseFileName( string $type , string $className )
Make the filename for the test case. resolve the suffixes for controllers and get the plugin path if needed.
Parameters
- string
$type
- The Type of object you are generating tests for eg. controller
- string
$className
- the Classname of the class the test is being generated for.
Returns
stringfilename the test should be created on.
typeCanDetectFixtures()source public
typeCanDetectFixtures( string $type )
Checks whether the chosen type can find its own fixtures. Currently only model, and controller are supported
Parameters
- string
$type
- The Type of object you are generating tests for eg. controller
Returns
booleanMethods inherited from BakeTask
getPath()source public
getPath( )
Gets the path for output. Checks the plugin property and returns the correct path.
Returns
stringPath to output.
startup()source public
startup( )
Disable caching and enable debug for baking. This forces the most current database schema to be used.
Overrides
Shell::startup()
Methods inherited from Shell
__construct()source public
__construct( ConsoleOutput $stdout null , ConsoleOutput $stderr null , ConsoleInput $stdin null )
Constructs this Shell instance.
Parameters
-
ConsoleOutput
$stdout
optional null - A ConsoleOutput object for stdout.
-
ConsoleOutput
$stderr
optional null - A ConsoleOutput object for stderr.
-
ConsoleInput
$stdin
optional null - A ConsoleInput object for stdin.
Link
http://book.cakephp.org/2.0/en/console-and-shells.html#ShellOverrides
Object::__construct()
__get()source public
__get( string $name )
Overload get for lazy building of tasks
Parameters
- string
$name
- The property name to access.
Returns
Shell
Object of Task
__isset()source public
__isset( string $name )
Lazy loads models using the loadModel() method if declared in $uses
Parameters
- string
$name
- The name of the model to look for.
_checkUnitTest()source protected
_checkUnitTest( )
Action to create a Unit Test
Returns
booleanSuccess
_controllerName()source protected
_controllerName( string $name )
Creates the proper controller plural name for the specified controller class name
Parameters
- string
$name
- Controller class name
Returns
stringController plural name
_controllerPath()source protected
_controllerPath( string $name )
Creates the proper controller path for the specified controller class name
Parameters
- string
$name
- Controller class name
Returns
stringPath to controller
_displayHelp()source protected
_displayHelp( string $command )
Display the help in the correct format
Parameters
- string
$command
- The command to get help for.
_getInput()source protected
_getInput( string $prompt , string|array $options , string $default )
Prompts the user for input, and returns it.
Parameters
- string
$prompt
- Prompt text.
- string|array
$options
- Array or string of options.
- string
$default
- Default input value.
Returns
Eitherthe default value, or the user-provided input.
_loadModels()source protected
_loadModels( )
If $uses is an array load each of the models in the array
Returns
boolean_modelKey()source protected
_modelKey( string $name )
Creates the proper underscored model key for associations
Parameters
- string
$name
- Model class name
Returns
stringSingular model key
_modelName()source protected
_modelName( string $name )
Creates the proper model camelized name (singularized) for the specified name
Parameters
- string
$name
- Name
Returns
stringCamelized and singularized model name
_modelNameFromKey()source protected
_modelNameFromKey( string $key )
Creates the proper model name from a foreign key
Parameters
- string
$key
- Foreign key
Returns
stringModel name
_pluginPath()source protected
_pluginPath( string $pluginName )
Find the correct path for a plugin. Scans $pluginPaths for the plugin you want.
Parameters
- string
$pluginName
- Name of the plugin you want ie. DebugKit
Returns
stringpath path to the correct plugin.
_pluralHumanName()source protected
_pluralHumanName( string $name )
Creates the plural human name used in views
Parameters
- string
$name
- Controller name
Returns
stringPlural human name
_pluralName()source protected
_pluralName( string $name )
Creates the plural name for views
Parameters
- string
$name
- Name to use
Returns
stringPlural name for views
_singularHumanName()source protected
_singularHumanName( string $name )
Creates the singular human name used in views
Parameters
- string
$name
- Controller name
Returns
stringSingular human name
_singularName()source protected
_singularName( string $name )
creates the singular name for use in views.
Parameters
- string
$name
- The plural underscored value.
Returns
stringname
_useLogger()source protected
_useLogger( boolean $enable true )
Used to enable or disable logging stream output to stdout and stderr If you don't wish to see in your stdout or stderr everything that is logged through CakeLog, call this function with first param as false
Parameters
- boolean
$enable
optional true - whether to enable CakeLog output or not
clear()source public
clear( )
Clear the console
Link
http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::clearcreateFile()source public
createFile( string $path , string $contents )
Creates a file at given path
Parameters
- string
$path
- Where to put the file.
- string
$contents
- Content to put in the file.
Returns
booleanSuccess
Link
http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::createFiledispatchShell()source public
dispatchShell( )
Dispatch a command to another Shell. Similar to Object::requestAction() but intended for running shells from other shells.
Usage:
With a string command:
return $this->dispatchShell('schema create DbAcl');
Avoid using this form if you have string arguments, with spaces in them. The dispatched will be invoked incorrectly. Only use this form for simple command dispatching.
With an array command:
return $this->dispatchShell('schema', 'create', 'i18n', '--dry');
Returns
mixedThe return of the other shell.
Link
http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::dispatchShellerr()source public
err( string|array $message null , integer $newlines 1 )
Outputs a single or multiple error messages to stderr. If no parameters are passed outputs just a newline.
Parameters
- string|array
$message
optional null - A string or an array of strings to output
- integer
$newlines
optional 1 - Number of newlines to append
Link
http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::errerror()source public
error( string $title , string $message null )
Displays a formatted error message and exits the application with status code 1
Parameters
- string
$title
- Title of the error
- string
$message
optional null - An optional error message
Link
http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::errorhasMethod()source public
hasMethod( string $name )
Check to see if this shell has a callable method by the given name.
Parameters
- string
$name
- The method name to check.
Returns
booleanLink
http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::hasMethodhasTask()source public
hasTask( string $task )
Check to see if this shell has a task with the provided name.
Parameters
- string
$task
- The task name to check.
Returns
booleanSuccess
Link
http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::hasTaskhelper()source public
helper( string $name )
Load given shell helper class
Parameters
- string
$name
- Name of the helper class. Supports plugin syntax.
Returns
BaseShellHelper
Instance of helper class
Throws
RuntimeExceptionIf invalid class name is provided
hr()source public
hr( integer $newlines 0 , integer $width 63 )
Outputs a series of minus characters to the standard output, acts as a visual separator.
Parameters
- integer
$newlines
optional 0 - Number of newlines to pre- and append
- integer
$width
optional 63 - Width of the line, defaults to 63
Link
http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::hrin()source public
in( string $prompt , string|array $options null , string $default null )
Prompts the user for input, and returns it.
Parameters
- string
$prompt
- Prompt text.
- string|array
$options
optional null - Array or string of options.
- string
$default
optional null - Default input value.
Returns
mixedEither the default value, or the user-provided input.
Link
http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::ininitialize()source public
initialize( )
Initializes the Shell acts as constructor for subclasses allows configuration of tasks prior to shell execution
Link
http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::initializeloadModel()source public
loadModel( string $modelClass null , mixed $id null )
Loads and instantiates models required by this shell.
Parameters
- string
$modelClass
optional null - Name of model class to load
- mixed
$id
optional null - Initial ID the instanced model class should have
Returns
mixedtrue when single model found and instance created, error returned if model not found.
Throws
MissingModelException
if the model class cannot be found.
nl()source public
nl( integer $multiplier 1 )
Returns a single or multiple linefeeds sequences.
Parameters
- integer
$multiplier
optional 1 - Number of times the linefeed sequence should be repeated
Returns
stringLink
http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::nlout()source public
out( string|array $message null , integer $newlines 1 , integer $level Shell::NORMAL )
Outputs a single or multiple messages to stdout. If no parameters are passed outputs just a newline.
Output levels
There are 3 built-in output level. Shell::QUIET, Shell::NORMAL, Shell::VERBOSE. The verbose and quiet output levels, map to the verbose
and quiet
output switches present in most shells. Using Shell::QUIET for a message means it will always display. While using Shell::VERBOSE means it will only display when verbose output is toggled.
Parameters
- string|array
$message
optional null - A string or an array of strings to output
- integer
$newlines
optional 1 - Number of newlines to append
- integer
$level
optional Shell::NORMAL - The message's output level, see above.
Returns
integer|booleanReturns the number of bytes returned from writing to stdout.
Link
http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::outoverwrite()source public
overwrite( array|string $message , integer $newlines 1 , integer $size null )
Overwrite some already output text.
Useful for building progress bars, or when you want to replace text already output to the screen with new text.
Warning You cannot overwrite text that contains newlines.
Parameters
- array|string
$message
- The message to output.
- integer
$newlines
optional 1 - Number of newlines to append.
- integer
$size
optional null - The number of bytes to overwrite. Defaults to the length of the last message output.
Returns
integer|booleanReturns the number of bytes returned from writing to stdout.
param()source public
param( string $name )
Safely access the values in $this->params.
Parameters
- string
$name
- The name of the parameter to get.
Returns
string|boolean|nullValue. Will return null if it doesn't exist.
runCommand()source public
runCommand( string $command , array $argv )
Runs the Shell with the provided argv.
Delegates calls to Tasks and resolves methods inside the class. Commands are looked up with the following order:
- Method on the shell.
- Matching task name.
-
main()
method.
If a shell implements a main()
method, all missing method calls will be sent to main()
with the original method name in the argv.
Parameters
- string
$command
The command name to run on this shell. If this argument is empty, and the shell has a
main()
method, that will be called instead.- array
$argv
- Array of arguments to run the shell with. This array should be missing the shell name.
Link
http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::runCommandshortPath()source public
shortPath( string $file )
Makes absolute file path easier to read
Parameters
- string
$file
- Absolute file path
Returns
stringshort path
Link
http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::shortPathwrapText()source public
wrapText( string $text , string|integer|array $options array() )
Wrap a block of text. Allows you to set the width, and indenting on a block of text.
Options
-
width
The width to wrap to. Defaults to 72 -
wordWrap
Only wrap on words breaks (spaces) Defaults to true. -
indent
Indent the text with the string provided. Defaults to null.
Parameters
- string
$text
- Text the text to format.
- string|integer|array
$options
optional array() - Array of options to use, or an integer to wrap the text to.
Returns
stringWrapped / indented text
See
CakeText::wrap()Link
http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::wrapTextMethods inherited from Object
_mergeVars()source protected
_mergeVars( array $properties , string $class , boolean $normalize true )
Merges this objects $property with the property in $class' definition. This classes value for the property will be merged on top of $class'
This provides some of the DRY magic CakePHP provides. If you want to shut it off, redefine this method as an empty function.
Parameters
- array
$properties
- The name of the properties to merge.
- string
$class
- The class to merge the property with.
- boolean
$normalize
optional true - Set to true to run the properties through Hash::normalize() before merging.
_set()source protected
_set( array $properties array() )
Allows setting of multiple properties of the object in a single line of code. Will only set properties that are part of a class declaration.
Parameters
- array
$properties
optional array() - An associative array containing properties and corresponding values.
_stop()source protected
_stop( integer|string $status 0 )
Stop execution of the current script. Wraps exit() making testing easier.
Parameters
- integer|string
$status
optional 0 - see http://php.net/exit for values
dispatchMethod()source public
dispatchMethod( string $method , array $params array() )
Calls a method on this object with the given parameters. Provides an OO wrapper for call_user_func_array
Parameters
- string
$method
- Name of the method to call
- array
$params
optional array() - Parameter list to use when calling $method
Returns
mixedReturns the result of the method call
log()source public
log( string $msg , integer $type LOG_ERR , null|string|array $scope null )
Convenience method to write a message to CakeLog. See CakeLog::write() for more information on writing to logs.
Parameters
- string
$msg
- Log message
- integer
$type
optional LOG_ERR - Error type constant. Defined in app/Config/core.php.
- null|string|array
$scope
optional null The scope(s) a log message is being created in. See CakeLog::config() for more information on logging scopes.
Returns
booleanSuccess of log write
requestAction()source public
requestAction( string|array $url , array $extra array() )
Calls a controller's method from any location. Can be used to connect controllers together or tie plugins into a main application. requestAction can be used to return rendered views or fetch the return value from controller actions.
Under the hood this method uses Router::reverse() to convert the $url parameter into a string URL. You should use URL formats that are compatible with Router::reverse()
Passing POST and GET data
POST and GET data can be simulated in requestAction. Use $extra['url']
for GET data. The $extra['data']
parameter allows POST data simulation.
Parameters
- string|array
$url
String or array-based URL. Unlike other URL arrays in CakePHP, this URL will not automatically handle passed and named arguments in the $url parameter.
- array
$extra
optional array() if array includes the key "return" it sets the AutoRender to true. Can also be used to submit GET/POST data, and named/passed arguments.
Returns
mixedBoolean true or false on success/failure, or contents of rendered action if 'return' is set in $extra.
toString()source public
toString( )
Object-to-string conversion. Each class can override this method as necessary.
Returns
stringThe name of this class
Properties detail
$baseTypessource
public array
Mapping between packages, and their baseclass + package. This is used to generate App::uses() call to autoload base classes if a developer has forgotten to do so.
array( 'Model' => array('Model', 'Model'), 'Behavior' => array('ModelBehavior', 'Model'), 'Controller' => array('Controller', 'Controller'), 'Component' => array('Component', 'Controller'), 'Helper' => array('Helper', 'View') )
$classTypessource
public array
class types that methods can be generated for
array( 'Model' => 'Model', 'Controller' => 'Controller', 'Component' => 'Controller/Component', 'Behavior' => 'Model/Behavior', 'Helper' => 'View/Helper' )
© 2005–2016 The Cake Software Foundation, Inc.
Licensed under the MIT License.
CakePHP is a registered trademark of Cake Software Foundation, Inc.
We are not endorsed by or affiliated with CakePHP.
http://api.cakephp.org/2.8/class-TestTask.html