SlideShare a Scribd company logo
1 of 40
PHPUnit elevato alla Symfony2




                 Eugenio Pombi
                  Symfony Day 05 October 2012



@euxpom                                         nerd2business.net
Symfony2 Functional testing tools

●   SymfonyBundleFrameworkBundleClient
●   SymfonyBundleFrameworkBundleCrawler
●   SymfonyComponentHttpKernelProfilerProfile
●   SymfonyBundleDoctrineFixturesBundle
Profiler
config                               time
   ->getBundles()                       ->getTotalTime()
   ->getEnv()                        memory
request                                 ->getMemory()
   ->getRouteParams()                router
   ->getController()                    ->getRedirect()
exception                            security
   ->hasException()                     ->getUser()
events
                                        ->getRoles()
   ->GetCalledListeners()
                                        ->isAuthenticated()
   ->getNotCalledListeners()
                                     swiftmailer
logger
                                        ->getMessageCount()
   ->CountErrors()
                                        ->getMessages()
   ->getLogs()
Doctrine profiler
db
     ->getQueryCount()
     ->getTime()
     ->getQueries()

               query
                      ['sql']
                      ['params']
                      ['types']
                      ['executionMS']
Stubbing



An example with Paypal
namespace JMSPaymentPaypalBundleClient;

class Client {
    [...]
    public function request(Request $request) {
        [...]
        // perform the request
        if (false === $returnTransfer = curl_exec($curl)) {
            throw new CommunicationException(
                'cURL Error: '.curl_error($curl), curl_errno($curl)
            );
        }
        [...]
        $response = new RawResponse(
            substr($returnTransfer, $headerSize),
            curl_getinfo($curl, CURLINFO_HTTP_CODE),
            $headers
        );
        curl_close($curl);
        return $response;
    }
}
namespace JMSPaymentPaypalBundleClient;

class Client {
    [...]
    public function request(Request $request) {
        [...]
        // perform the request
        if (false === $returnTransfer = curl_exec($curl)) {
            throw new CommunicationException(
                'cURL Error: '.curl_error($curl), curl_errno($curl)
            );
        }
        [...]
        $response = new RawResponse(
            substr($returnTransfer, $headerSize),
            curl_getinfo($curl, CURLINFO_HTTP_CODE),
            $headers
        );
        curl_close($curl);
        return $response;
    }
}
namespace JMSPaymentPaypalBundleClient;

class Client {
    [...]
    public function request(Request $request) {
        [...]
        // perform the request
        if (false === $returnTransfer = curl_exec($curl)) {
            throw new CommunicationException(
                'cURL Error: '.curl_error($curl), curl_errno($curl)
            );
        }
        [...]
        $response = new RawResponse(
            substr($returnTransfer, $headerSize),
            curl_getinfo($curl, CURLINFO_HTTP_CODE),
            $headers
        );
        curl_close($curl);
        return $response;
    }
}
namespace ACMEPaymentBundleTestsStub;

use JMSPaymentPaypalBundleClientClient;

class PaypalClientStub extends Client {
    public function request(Request $request)
    {
        $response = new RawResponse(
                "TOKEN=BlaBlaBlaBla",
                200,
                array(
                  'Date' => "Fri, 07 Sep 2012 15:21:00 GMT",
                  'Server' => "Apache",
                )
        );
        return $response;
    }
}
namespace ACMEPaymentBundleTestsStub;

use JMSPaymentPaypalBundleClientClient;

class PaypalClientStub extends Client {
    public function request(Request $request)
    {
        $response = new RawResponse(
                "TOKEN=BlaBlaBlaBla",
                200,
                array(
                  'Date' => "Fri, 07 Sep 2012 15:21:00 GMT",
                  'Server' => "Apache",
                )
        );
        return $response;
    }
}
services.xml

<parameter key="payment.paypal.client.class">
    JMSPaymentPaypalBundleClientClient
</parameter>




config_test.yml

parameters:
    payment.paypal.client.class:
ACMEPaymentBundleTestsStubPaypalClientStub
namespace JMSPaymentPaypalBundleClient;


class Client {
    [...]
    public function getAuthenticateExpressCheckoutTokenUrl($token) {
        $host = $this->isDebug ? 'www.sandbox.paypal.com':'www.paypal.com';


        return $host;
    }
}
namespace ACMEPaymentBundleTestsStub;
use JMSPaymentPaypalBundleClientClient;


class PaypalClientStub extends Client {
    public function getAuthenticateExpressCheckoutTokenUrl($token)
    {
        return '/payment/paypalFakeController';
    }
}
namespace ACMEPaymentBundleTestsStub;
use JMSPaymentPaypalBundleClientClient;


class PaypalClientStub extends Client {
    public function request(Request $request)
    {
        if ($request->request->get('METHOD') == 'SetExpressCheckout') {
            $response = new RawResponse(
             "TOKEN=BlaBlaBla",
           );
        } elseif ($request->request->get('METHOD') == 'GetExpressCheckoutDetails')
{
           $response = new RawResponse(
             "CHECKOUTSTATUS=PaymentCompleted&ACK=Success",
           );
        } elseif ($request->request->get('METHOD') == 'DoExpressCheckoutPayment'){
            $response = new RawResponse(
             "PAYMENTINFO_0_PAYMENTSTATUS=Completed",
           );
        }
        return $response;
    }
}
namespace ACMEPaymentBundleTestsStub;
use JMSPaymentPaypalBundleClientClient;


class PaypalClientStub extends Client {
    public function request(Request $request)
    {
        if ($request->request->get('METHOD') == 'SetExpressCheckout') {
            $response = new RawResponse(
             "TOKEN=BlaBlaBla",
           );
        } elseif ($request->request->get('METHOD') == 'GetExpressCheckoutDetails')
{
           $response = new RawResponse(
             "CHECKOUTSTATUS=PaymentCompleted&ACK=Success",
           );
        } elseif ($request->request->get('METHOD') == 'DoExpressCheckoutPayment'){
            $response = new RawResponse(
             "PAYMENTINFO_0_PAYMENTSTATUS=Completed",
           );
        }
        return $response;
    }
}
namespace ACMEPaymentBundleTestsStub;
use JMSPaymentPaypalBundleClientClient;


class PaypalClientStub extends Client {
    public function request(Request $request)
    {
        if ($request->request->get('METHOD') == 'SetExpressCheckout') {
            $response = new RawResponse(
             "TOKEN=BlaBlaBla",
           );
        } elseif ($request->request->get('METHOD') == 'GetExpressCheckoutDetails')
{
           $response = new RawResponse(
             "CHECKOUTSTATUS=PaymentCompleted&ACK=Success",
           );
        } elseif ($request->request->get('METHOD') == 'DoExpressCheckoutPayment'){
            $response = new RawResponse(
             "PAYMENTINFO_0_PAYMENTSTATUS=Completed",
           );
        }
        return $response;
    }
}
Something is missing
Control on the request
namespace ACMEPaymentBundleTestsStub;
use JMSPaymentPaypalBundleClientClient;

class PaypalClientStub extends Client {
    public function request(Request $request)
    {
        if ($request != "OK STUFF") {
          throw new Exception ("Wrong Request for Paypal
call");
        }
        [...]

        return $response;
    }
}
What is “outside”?

●   External API
What is “outside”?

●   External API
●   OS services (time)
What is “outside”?

●   External API
●   OS services (time)
●   Systems that don't exist yet
What is “outside”?

●   External API
●   OS services (time)
●   Systems that don't exist yet
●   Systems that other people is working on
What is “outside”?

●   External API
●   OS services (time)
●   Systems that don't exist yet
●   Systems that other people is working on
●   Monsters from the inside(legacy code)
The date/time case
●   A user can see the next three appointments
The date/time case
●   A user can see the next three appointments

●   A user is shown an alert in home page if she
    has an appointment in the next 6 hours
The date/time case
●   A user can see the next three appointments

●   A user is shown an alert in home page if she
    has an appointment in the next 6 hours
●   A user can take an appointment for the next
    day, but if it is Friday the next eligible day will
    be Monday
namespace ACMECoreBundleService;

class Time
{
    public static function getNow()
    {
        return new DateTime();
    }
}
namespace AcmeCoreBundleTestService;

class Time
{
    public static $referenceTime = '2012-05-01 12:00:00';
    public static $time = null;

    public static function getNow()
    {
        if (is_null(self::$time)) {
            return new DateTime(self::$referenceTime);
        } else {
            return new DateTime(self::$time);
        }
    }
}
namespace AcmeCoreBundleTestService;

class Time
{
    public static $referenceTime = '2012-05-01 12:00:00';
    public static $time = null;

    public static function getNow()
    {
        if (is_null(self::$time)) {
            return new DateTime(self::$referenceTime);
        } else {
            return new DateTime(self::$time);
        }
    }
}
Inside the fixtures

Use AcmeCoreBundleTestServiceTime;


public function load(ObjectManager $manager)
{
    $appointmentToday = new Appointment();
    $appointmentToday->setDateTime(new DateTime(Time::$referenceTime));
    [...]
}
Inside the test
Use AcmeCoreBundleTestServiceTime;

public function test_customerHome()
{
  AcmeCoreBundleTestServiceTime::$time = "2012-06-01";

    [...]
}
Different config states


$client =
   self::createClient(array('environment' => 'test_alternative'));
Thank You


            @euxpom
            nerd2business.net

More Related Content

What's hot

Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleHugo Hamon
 
Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & RESTHugo Hamon
 
Doctrine fixtures
Doctrine fixturesDoctrine fixtures
Doctrine fixturesBill Chang
 
Symfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteSymfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteLeonardo Proietti
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Leonardo Proietti
 
Things I Believe Now That I'm Old
Things I Believe Now That I'm OldThings I Believe Now That I'm Old
Things I Believe Now That I'm OldRoss Tuck
 
Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Konstantin Kudryashov
 
Object Calisthenics Adapted for PHP
Object Calisthenics Adapted for PHPObject Calisthenics Adapted for PHP
Object Calisthenics Adapted for PHPChad Gray
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretssmueller_sandsmedia
 
Decoupling the Ulabox.com monolith. From CRUD to DDD
Decoupling the Ulabox.com monolith. From CRUD to DDDDecoupling the Ulabox.com monolith. From CRUD to DDD
Decoupling the Ulabox.com monolith. From CRUD to DDDAleix Vergés
 
Rich Model And Layered Architecture in SF2 Application
Rich Model And Layered Architecture in SF2 ApplicationRich Model And Layered Architecture in SF2 Application
Rich Model And Layered Architecture in SF2 ApplicationKirill Chebunin
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolveXSolve
 
Introduction to Zend Framework web services
Introduction to Zend Framework web servicesIntroduction to Zend Framework web services
Introduction to Zend Framework web servicesMichelangelo van Dam
 
The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016Kacper Gunia
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in actionJace Ju
 
Crafting beautiful software
Crafting beautiful softwareCrafting beautiful software
Crafting beautiful softwareJorn Oomen
 
Object Calisthenics Applied to PHP
Object Calisthenics Applied to PHPObject Calisthenics Applied to PHP
Object Calisthenics Applied to PHPGuilherme Blanco
 
SOLID: the core principles of success of the Symfony web framework and of you...
SOLID: the core principles of success of the Symfony web framework and of you...SOLID: the core principles of success of the Symfony web framework and of you...
SOLID: the core principles of success of the Symfony web framework and of you...Vladyslav Riabchenko
 

What's hot (20)

Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
 
Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & REST
 
Min-Maxing Software Costs
Min-Maxing Software CostsMin-Maxing Software Costs
Min-Maxing Software Costs
 
Doctrine fixtures
Doctrine fixturesDoctrine fixtures
Doctrine fixtures
 
Symfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteSymfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il cliente
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
 
Things I Believe Now That I'm Old
Things I Believe Now That I'm OldThings I Believe Now That I'm Old
Things I Believe Now That I'm Old
 
Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015
 
The IoC Hydra
The IoC HydraThe IoC Hydra
The IoC Hydra
 
Object Calisthenics Adapted for PHP
Object Calisthenics Adapted for PHPObject Calisthenics Adapted for PHP
Object Calisthenics Adapted for PHP
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
 
Decoupling the Ulabox.com monolith. From CRUD to DDD
Decoupling the Ulabox.com monolith. From CRUD to DDDDecoupling the Ulabox.com monolith. From CRUD to DDD
Decoupling the Ulabox.com monolith. From CRUD to DDD
 
Rich Model And Layered Architecture in SF2 Application
Rich Model And Layered Architecture in SF2 ApplicationRich Model And Layered Architecture in SF2 Application
Rich Model And Layered Architecture in SF2 Application
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolve
 
Introduction to Zend Framework web services
Introduction to Zend Framework web servicesIntroduction to Zend Framework web services
Introduction to Zend Framework web services
 
The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in action
 
Crafting beautiful software
Crafting beautiful softwareCrafting beautiful software
Crafting beautiful software
 
Object Calisthenics Applied to PHP
Object Calisthenics Applied to PHPObject Calisthenics Applied to PHP
Object Calisthenics Applied to PHP
 
SOLID: the core principles of success of the Symfony web framework and of you...
SOLID: the core principles of success of the Symfony web framework and of you...SOLID: the core principles of success of the Symfony web framework and of you...
SOLID: the core principles of success of the Symfony web framework and of you...
 

Similar to PHPUnit elevato alla Symfony2

Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For BeginnersJonathan Wage
 
Forget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers CracowForget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers CracowKacper Gunia
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsMichael Peacock
 
Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!Kacper Gunia
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hackingJeroen van Dijk
 
Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12Jakub Zalas
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutesBarang CK
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 MinutesAzim Kurt
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11Michelangelo van Dam
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitmfrost503
 
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConRafael Dohms
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologyDaniel Knell
 
Easy rest service using PHP reflection api
Easy rest service using PHP reflection apiEasy rest service using PHP reflection api
Easy rest service using PHP reflection apiMatthieu Aubry
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From IusethisMarcus Ramberg
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of LithiumNate Abele
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxMichelangelo van Dam
 
(PHPers Wrocław #5) How to write valuable unit test?
(PHPers Wrocław #5) How to write valuable unit test?(PHPers Wrocław #5) How to write valuable unit test?
(PHPers Wrocław #5) How to write valuable unit test?RST Software Masters
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony AppsKris Wallsmith
 

Similar to PHPUnit elevato alla Symfony2 (20)

Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
Forget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers CracowForget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers Cracow
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friends
 
Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hacking
 
Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
 
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnCon
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
Easy rest service using PHP reflection api
Easy rest service using PHP reflection apiEasy rest service using PHP reflection api
Easy rest service using PHP reflection api
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From Iusethis
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
Bacbkone js
Bacbkone jsBacbkone js
Bacbkone js
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
(PHPers Wrocław #5) How to write valuable unit test?
(PHPers Wrocław #5) How to write valuable unit test?(PHPers Wrocław #5) How to write valuable unit test?
(PHPers Wrocław #5) How to write valuable unit test?
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
 

More from eugenio pombi

Processing one year of leading for Pug roma
Processing one year of leading for Pug romaProcessing one year of leading for Pug roma
Processing one year of leading for Pug romaeugenio pombi
 
Datagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and BackgridDatagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and Backgrideugenio pombi
 
Arduino - il mio primo sketch
Arduino - il mio primo sketchArduino - il mio primo sketch
Arduino - il mio primo sketcheugenio pombi
 
Appetite comes with testing
Appetite comes with testingAppetite comes with testing
Appetite comes with testingeugenio pombi
 
breve introduzione a node.js
breve introduzione a node.jsbreve introduzione a node.js
breve introduzione a node.jseugenio pombi
 

More from eugenio pombi (7)

Parlo al mio codice
Parlo al mio codiceParlo al mio codice
Parlo al mio codice
 
Processing one year of leading for Pug roma
Processing one year of leading for Pug romaProcessing one year of leading for Pug roma
Processing one year of leading for Pug roma
 
Datagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and BackgridDatagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and Backgrid
 
Codemotion workshop
Codemotion workshopCodemotion workshop
Codemotion workshop
 
Arduino - il mio primo sketch
Arduino - il mio primo sketchArduino - il mio primo sketch
Arduino - il mio primo sketch
 
Appetite comes with testing
Appetite comes with testingAppetite comes with testing
Appetite comes with testing
 
breve introduzione a node.js
breve introduzione a node.jsbreve introduzione a node.js
breve introduzione a node.js
 

Recently uploaded

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
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
 
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
 
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
 
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
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
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
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
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
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 

Recently uploaded (20)

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
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...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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
 
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...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
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
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
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...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 

PHPUnit elevato alla Symfony2

  • 1. PHPUnit elevato alla Symfony2 Eugenio Pombi Symfony Day 05 October 2012 @euxpom nerd2business.net
  • 2. Symfony2 Functional testing tools ● SymfonyBundleFrameworkBundleClient ● SymfonyBundleFrameworkBundleCrawler ● SymfonyComponentHttpKernelProfilerProfile ● SymfonyBundleDoctrineFixturesBundle
  • 3. Profiler config time ->getBundles() ->getTotalTime() ->getEnv() memory request ->getMemory() ->getRouteParams() router ->getController() ->getRedirect() exception security ->hasException() ->getUser() events ->getRoles() ->GetCalledListeners() ->isAuthenticated() ->getNotCalledListeners() swiftmailer logger ->getMessageCount() ->CountErrors() ->getMessages() ->getLogs()
  • 4. Doctrine profiler db ->getQueryCount() ->getTime() ->getQueries() query ['sql'] ['params'] ['types'] ['executionMS']
  • 6.
  • 7.
  • 8.
  • 9.
  • 10. namespace JMSPaymentPaypalBundleClient; class Client { [...] public function request(Request $request) { [...] // perform the request if (false === $returnTransfer = curl_exec($curl)) { throw new CommunicationException( 'cURL Error: '.curl_error($curl), curl_errno($curl) ); } [...] $response = new RawResponse( substr($returnTransfer, $headerSize), curl_getinfo($curl, CURLINFO_HTTP_CODE), $headers ); curl_close($curl); return $response; } }
  • 11. namespace JMSPaymentPaypalBundleClient; class Client { [...] public function request(Request $request) { [...] // perform the request if (false === $returnTransfer = curl_exec($curl)) { throw new CommunicationException( 'cURL Error: '.curl_error($curl), curl_errno($curl) ); } [...] $response = new RawResponse( substr($returnTransfer, $headerSize), curl_getinfo($curl, CURLINFO_HTTP_CODE), $headers ); curl_close($curl); return $response; } }
  • 12. namespace JMSPaymentPaypalBundleClient; class Client { [...] public function request(Request $request) { [...] // perform the request if (false === $returnTransfer = curl_exec($curl)) { throw new CommunicationException( 'cURL Error: '.curl_error($curl), curl_errno($curl) ); } [...] $response = new RawResponse( substr($returnTransfer, $headerSize), curl_getinfo($curl, CURLINFO_HTTP_CODE), $headers ); curl_close($curl); return $response; } }
  • 13. namespace ACMEPaymentBundleTestsStub; use JMSPaymentPaypalBundleClientClient; class PaypalClientStub extends Client { public function request(Request $request) { $response = new RawResponse( "TOKEN=BlaBlaBlaBla", 200, array( 'Date' => "Fri, 07 Sep 2012 15:21:00 GMT", 'Server' => "Apache", ) ); return $response; } }
  • 14. namespace ACMEPaymentBundleTestsStub; use JMSPaymentPaypalBundleClientClient; class PaypalClientStub extends Client { public function request(Request $request) { $response = new RawResponse( "TOKEN=BlaBlaBlaBla", 200, array( 'Date' => "Fri, 07 Sep 2012 15:21:00 GMT", 'Server' => "Apache", ) ); return $response; } }
  • 15. services.xml <parameter key="payment.paypal.client.class"> JMSPaymentPaypalBundleClientClient </parameter> config_test.yml parameters: payment.paypal.client.class: ACMEPaymentBundleTestsStubPaypalClientStub
  • 16.
  • 17.
  • 18. namespace JMSPaymentPaypalBundleClient; class Client { [...] public function getAuthenticateExpressCheckoutTokenUrl($token) { $host = $this->isDebug ? 'www.sandbox.paypal.com':'www.paypal.com'; return $host; } }
  • 19. namespace ACMEPaymentBundleTestsStub; use JMSPaymentPaypalBundleClientClient; class PaypalClientStub extends Client { public function getAuthenticateExpressCheckoutTokenUrl($token) { return '/payment/paypalFakeController'; } }
  • 20.
  • 21. namespace ACMEPaymentBundleTestsStub; use JMSPaymentPaypalBundleClientClient; class PaypalClientStub extends Client { public function request(Request $request) { if ($request->request->get('METHOD') == 'SetExpressCheckout') { $response = new RawResponse( "TOKEN=BlaBlaBla", ); } elseif ($request->request->get('METHOD') == 'GetExpressCheckoutDetails') { $response = new RawResponse( "CHECKOUTSTATUS=PaymentCompleted&ACK=Success", ); } elseif ($request->request->get('METHOD') == 'DoExpressCheckoutPayment'){ $response = new RawResponse( "PAYMENTINFO_0_PAYMENTSTATUS=Completed", ); } return $response; } }
  • 22. namespace ACMEPaymentBundleTestsStub; use JMSPaymentPaypalBundleClientClient; class PaypalClientStub extends Client { public function request(Request $request) { if ($request->request->get('METHOD') == 'SetExpressCheckout') { $response = new RawResponse( "TOKEN=BlaBlaBla", ); } elseif ($request->request->get('METHOD') == 'GetExpressCheckoutDetails') { $response = new RawResponse( "CHECKOUTSTATUS=PaymentCompleted&ACK=Success", ); } elseif ($request->request->get('METHOD') == 'DoExpressCheckoutPayment'){ $response = new RawResponse( "PAYMENTINFO_0_PAYMENTSTATUS=Completed", ); } return $response; } }
  • 23. namespace ACMEPaymentBundleTestsStub; use JMSPaymentPaypalBundleClientClient; class PaypalClientStub extends Client { public function request(Request $request) { if ($request->request->get('METHOD') == 'SetExpressCheckout') { $response = new RawResponse( "TOKEN=BlaBlaBla", ); } elseif ($request->request->get('METHOD') == 'GetExpressCheckoutDetails') { $response = new RawResponse( "CHECKOUTSTATUS=PaymentCompleted&ACK=Success", ); } elseif ($request->request->get('METHOD') == 'DoExpressCheckoutPayment'){ $response = new RawResponse( "PAYMENTINFO_0_PAYMENTSTATUS=Completed", ); } return $response; } }
  • 25. Control on the request namespace ACMEPaymentBundleTestsStub; use JMSPaymentPaypalBundleClientClient; class PaypalClientStub extends Client { public function request(Request $request) { if ($request != "OK STUFF") { throw new Exception ("Wrong Request for Paypal call"); } [...] return $response; } }
  • 27. What is “outside”? ● External API ● OS services (time)
  • 28. What is “outside”? ● External API ● OS services (time) ● Systems that don't exist yet
  • 29. What is “outside”? ● External API ● OS services (time) ● Systems that don't exist yet ● Systems that other people is working on
  • 30. What is “outside”? ● External API ● OS services (time) ● Systems that don't exist yet ● Systems that other people is working on ● Monsters from the inside(legacy code)
  • 31. The date/time case ● A user can see the next three appointments
  • 32. The date/time case ● A user can see the next three appointments ● A user is shown an alert in home page if she has an appointment in the next 6 hours
  • 33. The date/time case ● A user can see the next three appointments ● A user is shown an alert in home page if she has an appointment in the next 6 hours ● A user can take an appointment for the next day, but if it is Friday the next eligible day will be Monday
  • 34. namespace ACMECoreBundleService; class Time { public static function getNow() { return new DateTime(); } }
  • 35. namespace AcmeCoreBundleTestService; class Time { public static $referenceTime = '2012-05-01 12:00:00'; public static $time = null; public static function getNow() { if (is_null(self::$time)) { return new DateTime(self::$referenceTime); } else { return new DateTime(self::$time); } } }
  • 36. namespace AcmeCoreBundleTestService; class Time { public static $referenceTime = '2012-05-01 12:00:00'; public static $time = null; public static function getNow() { if (is_null(self::$time)) { return new DateTime(self::$referenceTime); } else { return new DateTime(self::$time); } } }
  • 37. Inside the fixtures Use AcmeCoreBundleTestServiceTime; public function load(ObjectManager $manager) { $appointmentToday = new Appointment(); $appointmentToday->setDateTime(new DateTime(Time::$referenceTime)); [...] }
  • 38. Inside the test Use AcmeCoreBundleTestServiceTime; public function test_customerHome() { AcmeCoreBundleTestServiceTime::$time = "2012-06-01"; [...] }
  • 39. Different config states $client = self::createClient(array('environment' => 'test_alternative'));
  • 40. Thank You @euxpom nerd2business.net