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

Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 

Recently uploaded (20)

Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 

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