SlideShare a Scribd company logo
1 of 47
H-ART
                                           TDD | Test Driven Development
                                                              Development Area | Workshops 2010




© H-art 2010 | All Rights Reserved | H-art is a WPP Company                                       20100715 - TDD | Test Driven Development
TDD - Perchè NO
                                                              Quali sono le principali difficoltà e le principali insidie
                                                                                nell’approccio TDD




© H-art 2010 | All Rights Reserved | H-art is a WPP Company                                                                20100715 - TDD | Test Driven Development
TDD - Punti deboli e criticità

   - Il codice dei test è codice extra che va mantenuto
   - Scrivere i test richiede tempo
   - Serve esperienza per capire cosa testare e cosa no
   - Per essere realmente efficace tutto il team dovrebbe abbracciare il TDD


© H-art 2010 | All Rights Reserved | H-art is a WPP Company                   20100715 - TDD | Test Driven Development
TDD - Punti deboli e criticità
                                                  Usare TDD è molto difficile
                                                      in situazioni come:



  - Lo sviluppo delle interfacce utente
  - Lo sviluppo di software che dipendono strettamente da
        un database



© H-art 2010 | All Rights Reserved | H-art is a WPP Company                    20100715 - TDD | Test Driven Development
TDD - Punti deboli e criticità
                                                  Usare TDD è molto difficile
                                                      in situazioni come:



  - Lo sviluppo delle interfacce utente
  - Lo sviluppo di software che dipendono strettamente da
        un database



© H-art 2010 | All Rights Reserved | H-art is a WPP Company                    20100715 - TDD | Test Driven Development
Ne vale la pena ?


© H-art 2010 | All Rights Reserved | H-art is a WPP Company                       20100715 - TDD | Test Driven Development
TDD - Perchè SI


© H-art 2010 | All Rights Reserved | H-art is a WPP Company                     20100715 - TDD | Test Driven Development
TDD - Vantaggi e obiettivi
Meno fatica
a parità di risultati


© H-art 2010 | All Rights Reserved | H-art is a WPP Company   20100715 - TDD | Test Driven Development
TDD - Vantaggi e obiettivi
   - Produttività aumentata
   - Confidenza nel codice aumentata
   - BugFix più semplice
   - Documentazione tecnica implicita
   - Migliore architettura del software
   - Rifattorizzazione più semplice

© H-art 2010 | All Rights Reserved | H-art is a WPP Company   20100715 - TDD | Test Driven Development
Ne vale la pena


© H-art 2010 | All Rights Reserved | H-art is a WPP Company                     20100715 - TDD | Test Driven Development
Che cosa è TDD



                                di cosa stiamo parlando esattamente ?




© H-art 2010 | All Rights Reserved | H-art is a WPP Company             20100715 - TDD | Test Driven Development
TDD is about
                                                                DESIGN
© H-art 2010 | All Rights Reserved | H-art is a WPP Company                  20100715 - TDD | Test Driven Development
TDD is about
                                              DELIVERING BUSINESS VALUE
© H-art 2010 | All Rights Reserved | H-art is a WPP Company               20100715 - TDD | Test Driven Development
TDD is about
                                                              CLEAN CODE THAT WORK
© H-art 2010 | All Rights Reserved | H-art is a WPP Company                          20100715 - TDD | Test Driven Development
TDD come
                                                              Sviluppare applicazioni web con TDD




© H-art 2010 | All Rights Reserved | H-art is a WPP Company                                         20100715 - TDD | Test Driven Development
TDD Come




© H-art 2010 | All Rights Reserved | H-art is a WPP Company   20100715 - TDD | Test Driven Development
TDD - Come

   - Basato sui cicli ripetuti di RED - GREEN - REFACTOR
   - I test si implementano PRIMA del codice
   - Inizia sempre con un test RED
   - Finisce sempre con un test GREEN
   - Isola e spezzetta i problemi in unità minime

© H-art 2010 | All Rights Reserved | H-art is a WPP Company   20100715 - TDD | Test Driven Development
TDD - Da fare SEMPRE

   - Scrivere i test PRIMA del codice
   - Mantenere una TODO list per i test
   - Eseguire tutti i test ogni volta e non solo quelli collegati alla modifica fatta
   - Il lavoro è completo quando tutti i test nella TODO list sono OK


© H-art 2010 | All Rights Reserved | H-art is a WPP Company                       20100715 - TDD | Test Driven Development
TDD - Best Practice

   - Iniziare scrivendo i test per le funzionalità più semplici
   - Eseguire i test subito dopo una modifica al codice
   - Se la scrittura di un test richiede troppo tempo spezzare il problema e suddividere in
          più test




© H-art 2010 | All Rights Reserved | H-art is a WPP Company                    20100715 - TDD | Test Driven Development
TDD - Da non fare MAI

   - Scrivere test per metodi banali (getter e setter)
   - Committare codice con test che FALLISCONO
   - Implementare nuove funzionalità con test che FALLISCONO
   - Iniziare una rifattorizzazione con test che FALLISCONO
   - Creare dipendenze tra i vari test

© H-art 2010 | All Rights Reserved | H-art is a WPP Company    20100715 - TDD | Test Driven Development
Development style
                                                              Come cambia il modo di scrivere codice con i test




© H-art 2010 | All Rights Reserved | H-art is a WPP Company                                                       20100715 - TDD | Test Driven Development
Scrivere PRIMA i test

© H-art 2010 | All Rights Reserved | H-art is a WPP Company                           20100715 - TDD | Test Driven Development
Codice testabile

© H-art 2010 | All Rights Reserved | H-art is a WPP Company                      20100715 - TDD | Test Driven Development
Rifattorizzazione

© H-art 2010 | All Rights Reserved | H-art is a WPP Company                       20100715 - TDD | Test Driven Development
Scrivere codice testabile

   - Spostare la maggior parte della logica nel model
   - Eliminare le dipendenze tra i componenti
   - Separare le responsabilità
   - Evitare quando possibile metodi statici
   - Limitare l’uso di oggetti singleton

© H-art 2010 | All Rights Reserved | H-art is a WPP Company   20100715 - TDD | Test Driven Development
Rifattorizzazione

   - Più sicura
   - Più facile
   - Più frequente
   - Migliora la qualità del codice


© H-art 2010 | All Rights Reserved | H-art is a WPP Company   20100715 - TDD | Test Driven Development
Spezzare il ciclo dello stress




© H-art 2010 | All Rights Reserved | H-art is a WPP Company                        20100715 - TDD | Test Driven Development
Tipologia di test
   - Unit
    - Molti test molto veloci
    - Testano singole funzionalità
    - Indipendenti dal codice che NON stanno testando
   - Functional
    - Tipicamente più lenti
    - Probabilmente più adatti per verificare regressioni che non per TDD
© H-art 2010 | All Rights Reserved | H-art is a WPP Company                20100715 - TDD | Test Driven Development
Strumenti
   - Unit Test
    - Lime (framework di test di symfony)
    - PHPUnit + Stagehand_TestRunner
   - Functional Test
    - Framework di test di symfony
    - Selenium
   - Continuos Integration
© H-art 2010 | All Rights Reserved | H-art is a WPP Company   20100715 - TDD | Test Driven Development
Un Esempio
                                                       Uno tuffo dentro al TDD per lo sviluppo di componente reale




© H-art 2010 | All Rights Reserved | H-art is a WPP Company                                                          20100715 - TDD | Test Driven Development
Requisiti
   - Implementare un Web Service REST con firma delle chiamate
   - Le chiamate devono essere firmate utilizzando il codice nonce e una chiave segreta
          (condivisa da client e server)

   - La firma viene generata utilizzando un codice NONCE
   - Il codice nonce univoco, casuale e persistente tra creazione e utilizzo
   - Il nonce deve essere eliminato dopo il suo utilizzo

© H-art 2010 | All Rights Reserved | H-art is a WPP Company                    20100715 - TDD | Test Driven Development
Step 0
                                                              Definizione di una lista di test




© H-art 2010 | All Rights Reserved | H-art is a WPP Company                                     20100715 - TDD | Test Driven Development
TODO Test

   - Il server genera un codice nonce di tipo stringa, univoco, di 32 caratteri
   - La firma viene correttamente verificata
   - Il codice nonce viene memorizzato quando viene richiesto/generato
   - Il codice nonce viene eliminato quando viene utilizzato


© H-art 2010 | All Rights Reserved | H-art is a WPP Company                       20100715 - TDD | Test Driven Development
Iterazione 1
                                                                Test:
                               Il server genera un codice nonce di tipo stringa, univoco, di 32 caratteri




© H-art 2010 | All Rights Reserved | H-art is a WPP Company                                        20100715 - TDD | Test Driven Development
Il Test
	       public function testGetNonce()
	       {
	       	 $server = new AuthServer();
	       	 $this->assertType('string', $server->getNonce());
	       	 $this->assertEquals(32, strlen($server->getNonce()));
	       	 $this->assertNotEquals($server->getNonce(), $server->getNonce());
	       }




  Il Codice
       class AuthServer
       {
         /**
           * Genera un codice nonce univoco
           */
         public function generateNonce()
         {
            return md5(uniqid(mt_rand(), true));
         }
       }

© H-art 2010 | All Rights Reserved | H-art is a WPP Company                   20100715 - TDD | Test Driven Development
Iterazione 2
                                                                              Test:
                                                              La firma viene correttamente verificata.




© H-art 2010 | All Rights Reserved | H-art is a WPP Company                                            20100715 - TDD | Test Driven Development
Il Test

      /**
        * Test metodo validateSignature()
        *
        * verifica tipo di dato restituito, test signature corretta e signature non corretta
        */
      public function testValidateInvalidSignature()
      {
          $server = $this->createServer();

           $secret = 'mySecret';
           $nonce = 'nonce';
           $signature = 'fakesignature';

           $this->assertType('boolean', $server->validateSignature($signature, $secret, $nonce));
           $this->assertFalse($server->validateSignature($signature, $secret, $nonce));

           $signature = '6313fc22867e45185845408d9a4993f439440313';
           $this->assertTrue($server->validateSignature($signature, $secret, $nonce));
      }




© H-art 2010 | All Rights Reserved | H-art is a WPP Company                                         20100715 - TDD | Test Driven Development
Il Codice
     /**
       * Verifica la signature
       */
     public function validateSignature($signature, $secret, $nonce)
     {
        $calculatedSignature = hash_hmac('sha1', $nonce, $secret);
        return $calculatedSignature == $signature;
     }




© H-art 2010 | All Rights Reserved | H-art is a WPP Company           20100715 - TDD | Test Driven Development
Iterazione 3
                                                                   Test:
                                     Il codice nonce viene memorizzato quando viene richiesto/generato




© H-art 2010 | All Rights Reserved | H-art is a WPP Company                                       20100715 - TDD | Test Driven Development
Il Test

      /**
        * Verifica che il codice none venga
        * memorizzato una volta richiesto.
        *
        * Il test usa un oggetto mock per verificare che venga
        * chiamato il metodo saveNonce($nonce) in AuthServer::generateNonce()
        *
        */
      public function testNoncePersistence()
      {
          $testNonceDataStore = $this->getMock('TestNonceDataStore');
          $testNonceDataStore->expects($this->once())->method('saveNonce')->with($this->isType('string'));
          $server = new AuthServer($testNonceDataStore);

           $server->generateNonce();
      }




© H-art 2010 | All Rights Reserved | H-art is a WPP Company                                           20100715 - TDD | Test Driven Development
Il Codice
 class AuthServer                                                     /**
 {                                                                      * Interfaccia per la persistenza del codice Nonce
   /**                                                                  * @author ftassi
    *                                                                   *
    * @var NonceDataStore $dataStore
                                                                        */
    */
   protected $dataStore;                                              interface NonceDataStore
                                                                      {
     /**                                                                  public function saveNonce($nonce);
      * Costruttore                                                   }
      *
      * @param NonceDataStore $dataStore
      */
     public function __construct(NonceDataStore $dataStore)
     {
        $this->dataStore = $dataStore;
     }
     /**
      * Verifica la signature
      */
     public function validateSignature($signature, $secret, $nonce)
     {
        $calculatedSignature = hash_hmac('sha1', $nonce, $secret);
        return $calculatedSignature == $signature;
     }
 }



© H-art 2010 | All Rights Reserved | H-art is a WPP Company                                             20100715 - TDD | Test Driven Development
Iterazione 4
                                                                                 Test:
                                                        Il codice nonce viene eliminato quando viene utilizzato




© H-art 2010 | All Rights Reserved | H-art is a WPP Company                                                       20100715 - TDD | Test Driven Development
Il Test

 /**
            * Verifica che il codice none venga
            * memorizzato una volta richiesto.
            *
            * Il test usa un oggetto mock per verificare che venga
            * chiamato il metodo saveNonce($nonce) in AuthServer::generateNonce()
            *
            */
          public function testNoncePersistence()
          {
              $testNonceDataStore = $this->getMock('TestNonceDataStore');
              $testNonceDataStore->expects($this->once())->method('saveNonce')->with($this->isType('string'));
              $dataStore->expects($this->never())->method('deleteNonce')->with($this->isType('string'));
              $server = $this->createServer($testNonceDataStore);

               $server->generateNonce();
          }




© H-art 2010 | All Rights Reserved | H-art is a WPP Company                                             20100715 - TDD | Test Driven Development
Il Test


 /**
            * Verifica la rimozione del codice nonce
            * in caso di richiesta valida
            */
          public function testNonceRemovalForValidSignature()
          {
             $secret = 'mySecret';
             $nonce = 'nonce';
             $signature = '6313fc22867e45185845408d9a4993f439440313';

               $dataStore = $this->getMock('TestNonceDataStore');
               $dataStore->expects($this->once())->method('deleteNonce')->with($this->isType('string'));
               $server = $this->createServer($dataStore);

               $server->validateSignature($signature, $secret, $nonce);

          }




© H-art 2010 | All Rights Reserved | H-art is a WPP Company                                                20100715 - TDD | Test Driven Development
Il Test


 /**
            * Verifica che il nonce non venga invalidato se la firma non è valida
            */
          public function testNonceRemovalForInvalidSignature()
          {
             $secret = 'mySecret';
             $nonce = 'nonce';
             $signature = 'fakesignature';

               $dataStore = $this->getMock('TestNonceDataStore');
               $dataStore->expects($this->never())->method('deleteNonce');
               $server = $this->createServer($dataStore);

               $server->validateSignature($signature, $secret, $nonce);

          }




© H-art 2010 | All Rights Reserved | H-art is a WPP Company                          20100715 - TDD | Test Driven Development
Il Codice



      /**
        * Verifica la signature
        */
      public function validateSignature($signature, $secret, $nonce)
      {
         $calculatedSignature = hash_hmac('sha1', $nonce, $secret);
         if($calculatedSignature == $signature)
         {
           $this->dataStore->deleteNonce($nonce);
           return true;
         }

           return false;
      }




© H-art 2010 | All Rights Reserved | H-art is a WPP Company            20100715 - TDD | Test Driven Development
THANK YOU
H-art
Via Sile, 41
31056 - Ca’ Tron (Treviso)

All rights reserved. This publication is protected by copyright.
No part of it may be reproduced, stored in a retrieval system,
or transmitted in any form, or by any means, electronic,
mechanical, photocopying or otherwise, without written
permission from the copyright owners.

Every effort has been made to ensure the accuracy of the
contents, but the publishers and copyright owners cannot
accept liability in respect of errors or omissions. Readers will
appreciate that the data are as up-to-date only to the extent
that their availability, compilation and printed schedules will
allow and are subject to change.




                                                        20100715 - TDD | Test Driven Development

More Related Content

Similar to TDD Test Driven Development

Framework software e Zend Framework
Framework software e Zend FrameworkFramework software e Zend Framework
Framework software e Zend FrameworkEnrico Zimuel
 
TIGPaper_DevOps_170615 Final
TIGPaper_DevOps_170615 FinalTIGPaper_DevOps_170615 Final
TIGPaper_DevOps_170615 FinalElena Vaciago
 
Slide Mulesoft Meetup Milano #10.pdf
Slide Mulesoft Meetup Milano #10.pdfSlide Mulesoft Meetup Milano #10.pdf
Slide Mulesoft Meetup Milano #10.pdfFlorence Consulting
 
Delphi & Dintorni Webinar - Padroneggiare i principi SOLID con Delphi
Delphi & Dintorni Webinar - Padroneggiare i principi SOLID con DelphiDelphi & Dintorni Webinar - Padroneggiare i principi SOLID con Delphi
Delphi & Dintorni Webinar - Padroneggiare i principi SOLID con DelphiMarco Breveglieri
 
Studio Pleiadi webmeeting - Pay Per Click
Studio Pleiadi webmeeting - Pay Per ClickStudio Pleiadi webmeeting - Pay Per Click
Studio Pleiadi webmeeting - Pay Per ClickStudio Pleiadi
 
"Configuration Manager: il ruolo nel ciclo di vita del software" by Omar Rossini
"Configuration Manager: il ruolo nel ciclo di vita del software" by Omar Rossini"Configuration Manager: il ruolo nel ciclo di vita del software" by Omar Rossini
"Configuration Manager: il ruolo nel ciclo di vita del software" by Omar RossiniThinkOpen
 
Convergence Consulting Presentazione 2012
Convergence Consulting Presentazione 2012  Convergence Consulting Presentazione 2012
Convergence Consulting Presentazione 2012 Anne Ladawan
 
La French Tech vuole incontrarti al Mobile World Congress
La French Tech vuole incontrarti al Mobile World CongressLa French Tech vuole incontrarti al Mobile World Congress
La French Tech vuole incontrarti al Mobile World CongressFrench Tech MILAN
 
Code metrics
Code metricsCode metrics
Code metricsKlab
 
FROSMO Presentazione in Italiano 2016
FROSMO Presentazione in Italiano 2016FROSMO Presentazione in Italiano 2016
FROSMO Presentazione in Italiano 2016Manuel Furlotti
 
Keep calm and deploy
Keep calm and deployKeep calm and deploy
Keep calm and deployKlab
 
Davide Zane - Il metodo Gellify per disegnare nuove offerte di prodotti e ser...
Davide Zane - Il metodo Gellify per disegnare nuove offerte di prodotti e ser...Davide Zane - Il metodo Gellify per disegnare nuove offerte di prodotti e ser...
Davide Zane - Il metodo Gellify per disegnare nuove offerte di prodotti e ser...Livia Francesca Caruso
 

Similar to TDD Test Driven Development (20)

Debugging with-z-ray
Debugging with-z-rayDebugging with-z-ray
Debugging with-z-ray
 
Framework software e Zend Framework
Framework software e Zend FrameworkFramework software e Zend Framework
Framework software e Zend Framework
 
Software libero e open source a costo zero per la grafica
Software libero e open source a costo zero per la graficaSoftware libero e open source a costo zero per la grafica
Software libero e open source a costo zero per la grafica
 
TIGPaper_DevOps_170615 Final
TIGPaper_DevOps_170615 FinalTIGPaper_DevOps_170615 Final
TIGPaper_DevOps_170615 Final
 
Slide Mulesoft Meetup Milano #10.pdf
Slide Mulesoft Meetup Milano #10.pdfSlide Mulesoft Meetup Milano #10.pdf
Slide Mulesoft Meetup Milano #10.pdf
 
Zend Framework 2
Zend Framework 2Zend Framework 2
Zend Framework 2
 
Delphi & Dintorni Webinar - Padroneggiare i principi SOLID con Delphi
Delphi & Dintorni Webinar - Padroneggiare i principi SOLID con DelphiDelphi & Dintorni Webinar - Padroneggiare i principi SOLID con Delphi
Delphi & Dintorni Webinar - Padroneggiare i principi SOLID con Delphi
 
Studio Pleiadi webmeeting - Pay Per Click
Studio Pleiadi webmeeting - Pay Per ClickStudio Pleiadi webmeeting - Pay Per Click
Studio Pleiadi webmeeting - Pay Per Click
 
"Configuration Manager: il ruolo nel ciclo di vita del software" by Omar Rossini
"Configuration Manager: il ruolo nel ciclo di vita del software" by Omar Rossini"Configuration Manager: il ruolo nel ciclo di vita del software" by Omar Rossini
"Configuration Manager: il ruolo nel ciclo di vita del software" by Omar Rossini
 
Fg Jde Strategica
Fg Jde StrategicaFg Jde Strategica
Fg Jde Strategica
 
Convergence Consulting Presentazione 2012
Convergence Consulting Presentazione 2012  Convergence Consulting Presentazione 2012
Convergence Consulting Presentazione 2012
 
La French Tech vuole incontrarti al Mobile World Congress
La French Tech vuole incontrarti al Mobile World CongressLa French Tech vuole incontrarti al Mobile World Congress
La French Tech vuole incontrarti al Mobile World Congress
 
Code metrics
Code metricsCode metrics
Code metrics
 
FROSMO Presentazione in Italiano 2016
FROSMO Presentazione in Italiano 2016FROSMO Presentazione in Italiano 2016
FROSMO Presentazione in Italiano 2016
 
Alessio_Pedrini_CV
Alessio_Pedrini_CVAlessio_Pedrini_CV
Alessio_Pedrini_CV
 
Test automatizzati & serenity bdd
Test automatizzati & serenity bddTest automatizzati & serenity bdd
Test automatizzati & serenity bdd
 
Keep calm and deploy
Keep calm and deployKeep calm and deploy
Keep calm and deploy
 
Udev Presentazione
Udev PresentazioneUdev Presentazione
Udev Presentazione
 
Introduzione ad Android
Introduzione ad AndroidIntroduzione ad Android
Introduzione ad Android
 
Davide Zane - Il metodo Gellify per disegnare nuove offerte di prodotti e ser...
Davide Zane - Il metodo Gellify per disegnare nuove offerte di prodotti e ser...Davide Zane - Il metodo Gellify per disegnare nuove offerte di prodotti e ser...
Davide Zane - Il metodo Gellify per disegnare nuove offerte di prodotti e ser...
 

TDD Test Driven Development

  • 1. H-ART TDD | Test Driven Development Development Area | Workshops 2010 © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 2. TDD - Perchè NO Quali sono le principali difficoltà e le principali insidie nell’approccio TDD © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 3. TDD - Punti deboli e criticità - Il codice dei test è codice extra che va mantenuto - Scrivere i test richiede tempo - Serve esperienza per capire cosa testare e cosa no - Per essere realmente efficace tutto il team dovrebbe abbracciare il TDD © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 4. TDD - Punti deboli e criticità Usare TDD è molto difficile in situazioni come: - Lo sviluppo delle interfacce utente - Lo sviluppo di software che dipendono strettamente da un database © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 5. TDD - Punti deboli e criticità Usare TDD è molto difficile in situazioni come: - Lo sviluppo delle interfacce utente - Lo sviluppo di software che dipendono strettamente da un database © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 6. Ne vale la pena ? © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 7. TDD - Perchè SI © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 8. TDD - Vantaggi e obiettivi Meno fatica a parità di risultati © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 9. TDD - Vantaggi e obiettivi - Produttività aumentata - Confidenza nel codice aumentata - BugFix più semplice - Documentazione tecnica implicita - Migliore architettura del software - Rifattorizzazione più semplice © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 10. Ne vale la pena © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 11. Che cosa è TDD di cosa stiamo parlando esattamente ? © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 12. TDD is about DESIGN © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 13. TDD is about DELIVERING BUSINESS VALUE © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 14. TDD is about CLEAN CODE THAT WORK © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 15. TDD come Sviluppare applicazioni web con TDD © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 16. TDD Come © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 17. TDD - Come - Basato sui cicli ripetuti di RED - GREEN - REFACTOR - I test si implementano PRIMA del codice - Inizia sempre con un test RED - Finisce sempre con un test GREEN - Isola e spezzetta i problemi in unità minime © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 18. TDD - Da fare SEMPRE - Scrivere i test PRIMA del codice - Mantenere una TODO list per i test - Eseguire tutti i test ogni volta e non solo quelli collegati alla modifica fatta - Il lavoro è completo quando tutti i test nella TODO list sono OK © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 19. TDD - Best Practice - Iniziare scrivendo i test per le funzionalità più semplici - Eseguire i test subito dopo una modifica al codice - Se la scrittura di un test richiede troppo tempo spezzare il problema e suddividere in più test © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 20. TDD - Da non fare MAI - Scrivere test per metodi banali (getter e setter) - Committare codice con test che FALLISCONO - Implementare nuove funzionalità con test che FALLISCONO - Iniziare una rifattorizzazione con test che FALLISCONO - Creare dipendenze tra i vari test © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 21. Development style Come cambia il modo di scrivere codice con i test © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 22. Scrivere PRIMA i test © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 23. Codice testabile © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 24. Rifattorizzazione © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 25. Scrivere codice testabile - Spostare la maggior parte della logica nel model - Eliminare le dipendenze tra i componenti - Separare le responsabilità - Evitare quando possibile metodi statici - Limitare l’uso di oggetti singleton © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 26. Rifattorizzazione - Più sicura - Più facile - Più frequente - Migliora la qualità del codice © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 27. Spezzare il ciclo dello stress © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 28. Tipologia di test - Unit - Molti test molto veloci - Testano singole funzionalità - Indipendenti dal codice che NON stanno testando - Functional - Tipicamente più lenti - Probabilmente più adatti per verificare regressioni che non per TDD © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 29. Strumenti - Unit Test - Lime (framework di test di symfony) - PHPUnit + Stagehand_TestRunner - Functional Test - Framework di test di symfony - Selenium - Continuos Integration © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 30. Un Esempio Uno tuffo dentro al TDD per lo sviluppo di componente reale © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 31. Requisiti - Implementare un Web Service REST con firma delle chiamate - Le chiamate devono essere firmate utilizzando il codice nonce e una chiave segreta (condivisa da client e server) - La firma viene generata utilizzando un codice NONCE - Il codice nonce univoco, casuale e persistente tra creazione e utilizzo - Il nonce deve essere eliminato dopo il suo utilizzo © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 32. Step 0 Definizione di una lista di test © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 33. TODO Test - Il server genera un codice nonce di tipo stringa, univoco, di 32 caratteri - La firma viene correttamente verificata - Il codice nonce viene memorizzato quando viene richiesto/generato - Il codice nonce viene eliminato quando viene utilizzato © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 34. Iterazione 1 Test: Il server genera un codice nonce di tipo stringa, univoco, di 32 caratteri © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 35. Il Test public function testGetNonce() { $server = new AuthServer(); $this->assertType('string', $server->getNonce()); $this->assertEquals(32, strlen($server->getNonce())); $this->assertNotEquals($server->getNonce(), $server->getNonce()); } Il Codice class AuthServer { /** * Genera un codice nonce univoco */ public function generateNonce() { return md5(uniqid(mt_rand(), true)); } } © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 36. Iterazione 2 Test: La firma viene correttamente verificata. © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 37. Il Test /** * Test metodo validateSignature() * * verifica tipo di dato restituito, test signature corretta e signature non corretta */ public function testValidateInvalidSignature() { $server = $this->createServer(); $secret = 'mySecret'; $nonce = 'nonce'; $signature = 'fakesignature'; $this->assertType('boolean', $server->validateSignature($signature, $secret, $nonce)); $this->assertFalse($server->validateSignature($signature, $secret, $nonce)); $signature = '6313fc22867e45185845408d9a4993f439440313'; $this->assertTrue($server->validateSignature($signature, $secret, $nonce)); } © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 38. Il Codice /** * Verifica la signature */ public function validateSignature($signature, $secret, $nonce) { $calculatedSignature = hash_hmac('sha1', $nonce, $secret); return $calculatedSignature == $signature; } © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 39. Iterazione 3 Test: Il codice nonce viene memorizzato quando viene richiesto/generato © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 40. Il Test /** * Verifica che il codice none venga * memorizzato una volta richiesto. * * Il test usa un oggetto mock per verificare che venga * chiamato il metodo saveNonce($nonce) in AuthServer::generateNonce() * */ public function testNoncePersistence() { $testNonceDataStore = $this->getMock('TestNonceDataStore'); $testNonceDataStore->expects($this->once())->method('saveNonce')->with($this->isType('string')); $server = new AuthServer($testNonceDataStore); $server->generateNonce(); } © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 41. Il Codice class AuthServer /** { * Interfaccia per la persistenza del codice Nonce /** * @author ftassi * * * @var NonceDataStore $dataStore */ */ protected $dataStore; interface NonceDataStore { /** public function saveNonce($nonce); * Costruttore } * * @param NonceDataStore $dataStore */ public function __construct(NonceDataStore $dataStore) { $this->dataStore = $dataStore; } /** * Verifica la signature */ public function validateSignature($signature, $secret, $nonce) { $calculatedSignature = hash_hmac('sha1', $nonce, $secret); return $calculatedSignature == $signature; } } © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 42. Iterazione 4 Test: Il codice nonce viene eliminato quando viene utilizzato © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 43. Il Test /** * Verifica che il codice none venga * memorizzato una volta richiesto. * * Il test usa un oggetto mock per verificare che venga * chiamato il metodo saveNonce($nonce) in AuthServer::generateNonce() * */ public function testNoncePersistence() { $testNonceDataStore = $this->getMock('TestNonceDataStore'); $testNonceDataStore->expects($this->once())->method('saveNonce')->with($this->isType('string')); $dataStore->expects($this->never())->method('deleteNonce')->with($this->isType('string')); $server = $this->createServer($testNonceDataStore); $server->generateNonce(); } © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 44. Il Test /** * Verifica la rimozione del codice nonce * in caso di richiesta valida */ public function testNonceRemovalForValidSignature() { $secret = 'mySecret'; $nonce = 'nonce'; $signature = '6313fc22867e45185845408d9a4993f439440313'; $dataStore = $this->getMock('TestNonceDataStore'); $dataStore->expects($this->once())->method('deleteNonce')->with($this->isType('string')); $server = $this->createServer($dataStore); $server->validateSignature($signature, $secret, $nonce); } © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 45. Il Test /** * Verifica che il nonce non venga invalidato se la firma non è valida */ public function testNonceRemovalForInvalidSignature() { $secret = 'mySecret'; $nonce = 'nonce'; $signature = 'fakesignature'; $dataStore = $this->getMock('TestNonceDataStore'); $dataStore->expects($this->never())->method('deleteNonce'); $server = $this->createServer($dataStore); $server->validateSignature($signature, $secret, $nonce); } © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 46. Il Codice /** * Verifica la signature */ public function validateSignature($signature, $secret, $nonce) { $calculatedSignature = hash_hmac('sha1', $nonce, $secret); if($calculatedSignature == $signature) { $this->dataStore->deleteNonce($nonce); return true; } return false; } © H-art 2010 | All Rights Reserved | H-art is a WPP Company 20100715 - TDD | Test Driven Development
  • 47. THANK YOU H-art Via Sile, 41 31056 - Ca’ Tron (Treviso) All rights reserved. This publication is protected by copyright. No part of it may be reproduced, stored in a retrieval system, or transmitted in any form, or by any means, electronic, mechanical, photocopying or otherwise, without written permission from the copyright owners. Every effort has been made to ensure the accuracy of the contents, but the publishers and copyright owners cannot accept liability in respect of errors or omissions. Readers will appreciate that the data are as up-to-date only to the extent that their availability, compilation and printed schedules will allow and are subject to change. 20100715 - TDD | Test Driven Development

Editor's Notes

  1. \n
  2. Il talk parte con l’introduzione degli aspetti peggiori del TDD.\nSi cerca di illustrare a cosa si va incontro, a quali saranno le difficoltà principali\n
  3. Difetti evidenti e banali del TDD.\nSoffermarsi su serve esperienza per capire cosa testare\n
  4. Evidenziare che le applicazioni web ricadono perfettamente nella descrizione di situazione critica.\nEvidenziare come questo porti a modificare il modo di scrivere applicazioni web.\n
  5. \n
  6. Si illustrano i vantaggi del TDD\nPerchè si dovrebbe modificare il proprio modo di lavorare ?\n
  7. \n
  8. Puntare attenzione su \nCONFIDENZA\nBUGFIX\n
  9. \n
  10. TDD non è “scrivere test”\nparadossalmente i test sono un aspetto marginale di quello che è veramente il TDD\ni Test sono uno strumento\n
  11. TDD cambia e migliora il design del codice\n
  12. TDD aiuta a trasmettere valore. Una suite di test da solidità a quello che si vende. \nLimitando i bug è più facile far percepire il valore di quello che si vende\n
  13. TDD vuol dire ottenere codice pulito che funzioni spezzando il problema in due più piccoli\n1- codice che funzioni\n2- codice pulito\n
  14. Tecniche \n
  15. Ciclo di vita classico\nEvidenziare come write production code possa essere preceduta da\n“write fake implementation”\n
  16. Iterazioni base del TDD\n
  17. \n
  18. \n
  19. \n
  20. Il TDD cambia il modo di scrivere codice\nUno degli aspetti fondamentali del TDD è che si scrive codice in maniera diversa, migliore\n\n
  21. Evidenziare come scrivere prima i test porti a pensare \nall’interfaccia degli oggetti, \nalle relazioni tra gli oggetti\na come interagiscono tra loro\n
  22. Codice testabile == Ingegnerizzazione migliore\nCodice testabile == Meno dipendenze == Più riusabilità\nCodice testabile == Competenze specifiche == debug facilitato\n
  23. Rifattorizzazione = codice migliore\nchi scrive codice ottimo alla prima stesura ? \n
  24. \n
  25. \n
  26. Sotto stress si tende a testare meno il codice prodotto che porta ad un aumento dello stress e così via\nImplementare dei test da subito può spezzare il ciclo dello stress. Al comparire di un problema si eseguiranno i test che aiuteranno a risolverlo diminuendo lo stress. La maggiore confidenza porterà a scrivere più test il che ridurrà ulteriormente lo stress e così via \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n