SlideShare una empresa de Scribd logo
1 de 13
Descargar para leer sin conexión
Test [and API] driven development
       of CakePHP Behaviors




        held by Alexander Morland
             at CakeFest 2009
1. Introduction

 Alexander Morland aka 'alkemann'
 Web technology since 2005
 CakePHP since 2007
 illustrata.no 2009

 Revision Behavior
 Ordered Behavior
 Logable Behavior
 and others
Talk overview


1.   Introduction             Goal:
2.   Unit Testing
3.   Focus on the API         Share some of the excitement I
4.   Why we did it            discovered in moving the logic
5.   The Devide and Conquer   to the right place and code it in
6.   Example                  a way that makes sense. 
7.   CakePHP and SimpleTest
8.   Lessons learned
9.   Summary
2. Unit Testing

In computer programming, unit testing is a software verification and
validation method where the programmer gains confidence that
individual units of source code are fit for use. A unit is the smallest
testable part of an application.

[..] in object-oriented programming, the smallest unit is a method,[..]
                                      from: http://en.wikipedia.org/wiki/Unit_test

  Design
  Documentation
  Simplifies integration
  Facilitates change
  Enables Divide and Conquer development
3. API writing

1.   Follow existing api 
2.   Implement abstract classes
3.   Hook into Cake callbacks
4.   Keep it simple




     Model::delete( $id = NULL, $cascade = true )


     delete( $id = NULL, $custom = '', $cascade = true )
       vs.
     delete( $id = NULL, $cascade = true, $custom = '' )
4. Why we did it?

1. Move from single developer to team
2. Consistent code, in-house, core and community
3. Cyclic development
5. The Divide and Conquer

1. Brainstorm function
2. Brainstorm implementation
3. Specifications of features
4. Write the API
5. Parallel or sequential :
       Writing a test case
       Implement code against test
6. Write tests for feature spec
   Write tests trying to use wrongly / error
      
7. Code Review
6. Example - ColourBehavior

What: 
   add colour on save
   easy find by colour

How:
   beforeSave()
   colour('red')

Tests: 
   save()
   colour()
   find()
Behavior method:
1. /**
2. * Returns a findByColour of the given colour
3. *
4. * @param Object $Model
5. * @param $colour Colour to filter model by
6. * @return string a english worded colour
7. */
8. public function colour(&$Model, $colour) {
9. return $Model->findAllByColour($colour);
10. }

Test code:
1. $findBy = $Nose->findByColour('red');
2. $expected = array('Nose' =>
    array(0 => array('id' => 3, 'owner' => 'Rudolf', 'colour' => 'Red' )));
3. $this->assertEqual($findBy, $expected, 'Data corrupt : %s');
4. /**/
5. $check = $Nose->colour('red');
6. $this->assertEqual($check, $findBy, 'Different result than findByColour : %s');
7. $this->assertEqual($check, $expected, 'Incorrect result : %s');
Behavior method:
 1. /**
 2. * When saving new rows and a colour is not set, insert colour into dataset
3. * It does this by checking if neither id or colour field is in the dataset
4. */
5. public function beforeSave(&$Model) {
6. if (
7.       !isset($Model->data[$Model->alias][$Model->primaryKey])
8.        &&
9.       !isset($Model->data[$Model->alias]['colour'])
10. ) {
11.       $Model->data[$Model->alias]['colour'] = $this->random($Model);
12. }
13. return true;
14. }

Test code:
1. $Nose->create(array('owner' => 'Alexander');
2. $Nose->save();
3. $result = $Nose->read();
4. $this->assertNotNull($result['Nose']['colour'], 'Did not get a colour : %s');
5. /**/
6. $Nose->create(array('owner' => 'Superman', 'colour' => 'Cryptonite');
7. $Nose->save();
8. $result = $Nose->read();
9. $this->assertEqual($result['Nose']['colour'],'Cryptonite', 'Interference : %s');
7. CakePHP and SimpleTest

Cake uses SimpleTest as vendor (www.simpletest.org)

                     domain.com/test.php




                       Run Example
8. Lessons learned

1.   Tests could be written blindly
2.   Usage in focus produced better api
3.   Complete project just with test
4.   Shared code early, feedback early
5.   Test, Brute-force, Optimize
6.   Start simple and expand
7.   Test compatibility with other Behaviors
8.   It was fun!
In closing

  Be your
  own giant!




             thanks for listening

Más contenido relacionado

La actualidad más candente

php 2 Function creating, calling, PHP built-in function
php 2 Function creating, calling,PHP built-in functionphp 2 Function creating, calling,PHP built-in function
php 2 Function creating, calling, PHP built-in functiontumetr1
 
Programming Primer Encapsulation CS
Programming Primer Encapsulation CSProgramming Primer Encapsulation CS
Programming Primer Encapsulation CSsunmitraeducation
 
jQuery Plugin
jQuery PluginjQuery Plugin
jQuery Pluginrbiggs
 
RSpec 3: The new, the old, the good
RSpec 3: The new, the old, the goodRSpec 3: The new, the old, the good
RSpec 3: The new, the old, the goodmglrnm
 
Ruby on Rails testing with Rspec
Ruby on Rails testing with RspecRuby on Rails testing with Rspec
Ruby on Rails testing with RspecBunlong Van
 
Create a web-app with Cgi Appplication
Create a web-app with Cgi AppplicationCreate a web-app with Cgi Appplication
Create a web-app with Cgi Appplicationolegmmiller
 
Introduction to Python decorators
Introduction to Python decoratorsIntroduction to Python decorators
Introduction to Python decoratorsrikbyte
 
Think Generic - Add API's To Your Custom Modules
Think Generic - Add API's To Your Custom ModulesThink Generic - Add API's To Your Custom Modules
Think Generic - Add API's To Your Custom ModulesJens Sørensen
 
Object oriented php
Object oriented phpObject oriented php
Object oriented phpjwperry
 
Driving Design with PhpSpec
Driving Design with PhpSpecDriving Design with PhpSpec
Driving Design with PhpSpecCiaranMcNulty
 
Arrays & functions in php
Arrays & functions in phpArrays & functions in php
Arrays & functions in phpAshish Chamoli
 
Php using variables-operators
Php using variables-operatorsPhp using variables-operators
Php using variables-operatorsKhem Puthea
 
Symfony 4 Workshop - Limenius
Symfony 4 Workshop - LimeniusSymfony 4 Workshop - Limenius
Symfony 4 Workshop - LimeniusIgnacio Martín
 
Beginning Perl
Beginning PerlBeginning Perl
Beginning PerlDave Cross
 
BDD with Behat and Symfony2
BDD with Behat and Symfony2BDD with Behat and Symfony2
BDD with Behat and Symfony2katalisha
 

La actualidad más candente (20)

php 2 Function creating, calling, PHP built-in function
php 2 Function creating, calling,PHP built-in functionphp 2 Function creating, calling,PHP built-in function
php 2 Function creating, calling, PHP built-in function
 
Programming Primer Encapsulation CS
Programming Primer Encapsulation CSProgramming Primer Encapsulation CS
Programming Primer Encapsulation CS
 
jQuery Plugin
jQuery PluginjQuery Plugin
jQuery Plugin
 
RSpec 3: The new, the old, the good
RSpec 3: The new, the old, the goodRSpec 3: The new, the old, the good
RSpec 3: The new, the old, the good
 
Ruby on Rails testing with Rspec
Ruby on Rails testing with RspecRuby on Rails testing with Rspec
Ruby on Rails testing with Rspec
 
PHP-Part2
PHP-Part2PHP-Part2
PHP-Part2
 
Create a web-app with Cgi Appplication
Create a web-app with Cgi AppplicationCreate a web-app with Cgi Appplication
Create a web-app with Cgi Appplication
 
PHP-Part3
PHP-Part3PHP-Part3
PHP-Part3
 
Introduction to Python decorators
Introduction to Python decoratorsIntroduction to Python decorators
Introduction to Python decorators
 
Functions in php
Functions in phpFunctions in php
Functions in php
 
Think Generic - Add API's To Your Custom Modules
Think Generic - Add API's To Your Custom ModulesThink Generic - Add API's To Your Custom Modules
Think Generic - Add API's To Your Custom Modules
 
Object oriented php
Object oriented phpObject oriented php
Object oriented php
 
Driving Design with PhpSpec
Driving Design with PhpSpecDriving Design with PhpSpec
Driving Design with PhpSpec
 
Arrays & functions in php
Arrays & functions in phpArrays & functions in php
Arrays & functions in php
 
Php using variables-operators
Php using variables-operatorsPhp using variables-operators
Php using variables-operators
 
Rspec 101
Rspec 101Rspec 101
Rspec 101
 
Symfony 4 Workshop - Limenius
Symfony 4 Workshop - LimeniusSymfony 4 Workshop - Limenius
Symfony 4 Workshop - Limenius
 
Php Basic
Php BasicPhp Basic
Php Basic
 
Beginning Perl
Beginning PerlBeginning Perl
Beginning Perl
 
BDD with Behat and Symfony2
BDD with Behat and Symfony2BDD with Behat and Symfony2
BDD with Behat and Symfony2
 

Similar a Test and API-driven development of CakePHP Behaviors

Ch ch-changes cake php2
Ch ch-changes cake php2Ch ch-changes cake php2
Ch ch-changes cake php2markstory
 
PHPunit and you
PHPunit and youPHPunit and you
PHPunit and youmarkstory
 
Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkDaniel Spector
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasminePaulo Ragonha
 
10 Groovy Little JavaScript Tips
10 Groovy Little JavaScript Tips10 Groovy Little JavaScript Tips
10 Groovy Little JavaScript TipsTroy Miles
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Michelangelo van Dam
 
Testing in Laravel Framework
Testing in Laravel FrameworkTesting in Laravel Framework
Testing in Laravel FrameworkAnis Ahmad
 
Quality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStormQuality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStormMichelangelo van Dam
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everythingnoelrap
 
Working Effectively With Legacy Perl Code
Working Effectively With Legacy Perl CodeWorking Effectively With Legacy Perl Code
Working Effectively With Legacy Perl Codeerikmsp
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
.NET Coding Standards For The Real World (2012)
.NET Coding Standards For The Real World (2012).NET Coding Standards For The Real World (2012)
.NET Coding Standards For The Real World (2012)David McCarter
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsMike Subelsky
 

Similar a Test and API-driven development of CakePHP Behaviors (20)

Dutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: DistilledDutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: Distilled
 
Ch ch-changes cake php2
Ch ch-changes cake php2Ch ch-changes cake php2
Ch ch-changes cake php2
 
PHPunit and you
PHPunit and youPHPunit and you
PHPunit and you
 
Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end Framework
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 
Cucumber testing
Cucumber testingCucumber testing
Cucumber testing
 
Cucumber testing
Cucumber testingCucumber testing
Cucumber testing
 
10 Groovy Little JavaScript Tips
10 Groovy Little JavaScript Tips10 Groovy Little JavaScript Tips
10 Groovy Little JavaScript Tips
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010
 
Fatc
FatcFatc
Fatc
 
Testing in Laravel Framework
Testing in Laravel FrameworkTesting in Laravel Framework
Testing in Laravel Framework
 
PerlTesting
PerlTestingPerlTesting
PerlTesting
 
Quality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStormQuality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStorm
 
Test your modules
Test your modulesTest your modules
Test your modules
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
 
Working Effectively With Legacy Perl Code
Working Effectively With Legacy Perl CodeWorking Effectively With Legacy Perl Code
Working Effectively With Legacy Perl Code
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
.NET Coding Standards For The Real World (2012)
.NET Coding Standards For The Real World (2012).NET Coding Standards For The Real World (2012)
.NET Coding Standards For The Real World (2012)
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
 

Más de Pierre MARTIN

Introduction à CakePHP
Introduction à CakePHPIntroduction à CakePHP
Introduction à CakePHPPierre MARTIN
 
Using and reusing CakePHP plugins
Using and reusing CakePHP pluginsUsing and reusing CakePHP plugins
Using and reusing CakePHP pluginsPierre MARTIN
 
Building custom APIs
Building custom APIsBuilding custom APIs
Building custom APIsPierre MARTIN
 
Recipes for successful CakePHP projects
Recipes for successful CakePHP projectsRecipes for successful CakePHP projects
Recipes for successful CakePHP projectsPierre MARTIN
 
The CakePHP Media Plugin
The CakePHP Media PluginThe CakePHP Media Plugin
The CakePHP Media PluginPierre MARTIN
 
Internationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsInternationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsPierre MARTIN
 

Más de Pierre MARTIN (6)

Introduction à CakePHP
Introduction à CakePHPIntroduction à CakePHP
Introduction à CakePHP
 
Using and reusing CakePHP plugins
Using and reusing CakePHP pluginsUsing and reusing CakePHP plugins
Using and reusing CakePHP plugins
 
Building custom APIs
Building custom APIsBuilding custom APIs
Building custom APIs
 
Recipes for successful CakePHP projects
Recipes for successful CakePHP projectsRecipes for successful CakePHP projects
Recipes for successful CakePHP projects
 
The CakePHP Media Plugin
The CakePHP Media PluginThe CakePHP Media Plugin
The CakePHP Media Plugin
 
Internationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsInternationalizing CakePHP Applications
Internationalizing CakePHP Applications
 

Último

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 

Último (20)

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 

Test and API-driven development of CakePHP Behaviors

  • 1. Test [and API] driven development of CakePHP Behaviors held by Alexander Morland at CakeFest 2009
  • 2. 1. Introduction Alexander Morland aka 'alkemann' Web technology since 2005 CakePHP since 2007 illustrata.no 2009 Revision Behavior Ordered Behavior Logable Behavior and others
  • 3. Talk overview 1. Introduction Goal: 2. Unit Testing 3. Focus on the API  Share some of the excitement I 4. Why we did it discovered in moving the logic 5. The Devide and Conquer to the right place and code it in 6. Example a way that makes sense.  7. CakePHP and SimpleTest 8. Lessons learned 9. Summary
  • 4. 2. Unit Testing In computer programming, unit testing is a software verification and validation method where the programmer gains confidence that individual units of source code are fit for use. A unit is the smallest testable part of an application. [..] in object-oriented programming, the smallest unit is a method,[..] from: http://en.wikipedia.org/wiki/Unit_test Design Documentation Simplifies integration Facilitates change Enables Divide and Conquer development
  • 5. 3. API writing 1. Follow existing api  2. Implement abstract classes 3. Hook into Cake callbacks 4. Keep it simple Model::delete( $id = NULL, $cascade = true ) delete( $id = NULL, $custom = '', $cascade = true ) vs. delete( $id = NULL, $cascade = true, $custom = '' )
  • 6. 4. Why we did it? 1. Move from single developer to team 2. Consistent code, in-house, core and community 3. Cyclic development
  • 7. 5. The Divide and Conquer 1. Brainstorm function 2. Brainstorm implementation 3. Specifications of features 4. Write the API 5. Parallel or sequential : Writing a test case Implement code against test 6. Write tests for feature spec Write tests trying to use wrongly / error   7. Code Review
  • 8. 6. Example - ColourBehavior What:  add colour on save easy find by colour How: beforeSave() colour('red') Tests:  save() colour() find()
  • 9. Behavior method: 1. /** 2. * Returns a findByColour of the given colour 3. * 4. * @param Object $Model 5. * @param $colour Colour to filter model by 6. * @return string a english worded colour 7. */ 8. public function colour(&$Model, $colour) { 9. return $Model->findAllByColour($colour); 10. } Test code: 1. $findBy = $Nose->findByColour('red'); 2. $expected = array('Nose' => array(0 => array('id' => 3, 'owner' => 'Rudolf', 'colour' => 'Red' ))); 3. $this->assertEqual($findBy, $expected, 'Data corrupt : %s'); 4. /**/ 5. $check = $Nose->colour('red'); 6. $this->assertEqual($check, $findBy, 'Different result than findByColour : %s'); 7. $this->assertEqual($check, $expected, 'Incorrect result : %s');
  • 10. Behavior method: 1. /** 2. * When saving new rows and a colour is not set, insert colour into dataset 3. * It does this by checking if neither id or colour field is in the dataset 4. */ 5. public function beforeSave(&$Model) { 6. if ( 7. !isset($Model->data[$Model->alias][$Model->primaryKey]) 8. && 9. !isset($Model->data[$Model->alias]['colour']) 10. ) { 11. $Model->data[$Model->alias]['colour'] = $this->random($Model); 12. } 13. return true; 14. } Test code: 1. $Nose->create(array('owner' => 'Alexander'); 2. $Nose->save(); 3. $result = $Nose->read(); 4. $this->assertNotNull($result['Nose']['colour'], 'Did not get a colour : %s'); 5. /**/ 6. $Nose->create(array('owner' => 'Superman', 'colour' => 'Cryptonite'); 7. $Nose->save(); 8. $result = $Nose->read(); 9. $this->assertEqual($result['Nose']['colour'],'Cryptonite', 'Interference : %s');
  • 11. 7. CakePHP and SimpleTest Cake uses SimpleTest as vendor (www.simpletest.org) domain.com/test.php Run Example
  • 12. 8. Lessons learned 1. Tests could be written blindly 2. Usage in focus produced better api 3. Complete project just with test 4. Shared code early, feedback early 5. Test, Brute-force, Optimize 6. Start simple and expand 7. Test compatibility with other Behaviors 8. It was fun!
  • 13. In closing Be your own giant! thanks for listening