SlideShare a Scribd company logo
1 of 33
Download to read offline
Vinai Kopp:
Property Based
Testing
in PHP
Other schools of thinking
Lots of inspiration for me
Clojure
Property Based Testing
Where Property Based Testing was invented
Haskell
“Don’t write tests. Generate them.”
Prof. John Hughes, Inventor of QuickCheck
Example Based Testing (EBT)
• Think of an example
• Call method(s)
• Verify result
Property Based Testing (PBT)
• Think of range of inputs
• Let computer generate inputs
• Call method(s)
• Verify properties of result
• If a failure is found, shrink inputs
Property Based Testing?
Advantages of Property Based Testing
• Replace many example-based tests
• Find more bugs than example-based tests
• Test complex systems
• Test “black box” systems
• Facilitates thinking about system under development
QuickCheck Implementations PHP
• https://github.com/steos/php-quickcheck
composer require --dev steos/quickcheck:dev-master
• https://github.com/giorgiosironi/eris
composer require --dev giorgiosironi/eris
What does it look like?
class ExampleStringToUpperTest extends TestCase
{
public function testLengthStaysTheSame()
{
$property = Property::forAll(
[ Generator::strings() ],
function (string $input): bool {
return mb_strlen($input) === mb_strlen(mb_strtoupper($input));
}
);
$this->assertThat($property, PropertyConstraint::check(200));
}
What does it look like?
Failed asserting that property is true.
Test runs: 7, seed: 1580127726247, smallest shrunk value(s):
array (
0 => ' ' . "0" . '',
)
vendor/steos/quickcheck/src/QuickCheck/PHPUnit/PropertyConstraint.php:35
test/ExampleStringTest.php:22
Failed asserting that property is true.
Test runs: 9, seed: 1580132863563, smallest shrunk value(s):
array (
0 => '' . "0" . ' ' . "0" . ‘‘,
)
vendor/steos/quickcheck/src/QuickCheck/PHPUnit/PropertyConstraint.php:35
test/ExampleStringTest.php:22
When to use Property Based Testing
• During Design
• During Implementation (like TDD)
• After Implementation
• Reproducing a bug
Figuring out the properties to test
• This is … not an easy thing (at first)
• But there are strategies to follow
Figuring out the properties to test
• reverse?
• depend on the order of an input sequence?
• depend on grouping of arguments? (Associative)
• depend on the order of arguments? (Commutative)
• have an identity value?
• change it’s output if it is called multiple times? (Idempotent)
Algebraic Properties
Does the Algorithm…
Figuring out the properties to test
Functionality
Like TDD, but better:
Generate the input values instead of hardcoding them.
Do not re-implement functionality!
Figuring out the properties to test
1. Generate names for directories and files
2. Create directories
3. Create files
4. Execute command (list files)
5. Assert number of files matches created files
Functionality
Example test for the ls CLI utility:
Figuring out the properties to test
Commerce is very stateful.
Shopping Cart customizations tend to be stateful, too.
Mostly stateful
Figuring out the properties to test
Model ó System
Modelling Stateful Systems
The model behaves like the System Under Test (SUT),
but it doesn’t use persistence or have a REST API.
Figuring out the properties to test
1. Create Model of System
2. Generate actions
3. Apply actions to Model and System
4. Check Model and System state match
Modelling Stateful Systems
The model behaves like the System Under Test (SUT),
but it doesn’t use persistence or have a REST API.
Property Based Testing in the Design Phase
• New Systems:
Create model before starting with the real implementation
• Existing systems:
The model can be partial (only the functionality to test)
• The model development is guided by tests (TDD like)
• Building the model gives me a better understanding of the
real system
Property Based Testing in the Design Phase
Plan
Create Model
Generate
Action
Write
Test
Write
Model
Property Based Testing in the Design Phase
My current task:
Downloadable Products for a different system.
I’ve used the same approach with Magento 2, too.
For example...
Property Based Testing in the Design Phase
1. Sketch out operations
Admin
• Create new
• Add file
• Replace file
• Remove file
• Delete product, keep downloads
• Delete product, remove downloads
Customer
• Purchase downloadable
• List available files
• Download file
Reporting
• Downloads per file
• …
Property Based Testing in the Design Phase
2. Generate Action
• Generate data for the initial operation on the system
• Return it as an array
• Write test for that operation
Property Based Testing in the Design Phase
2. Generate Action
private function genCreateDownloadableProductAction(): Gen
{
$contents = Gen::strings();
return Gen::tuples($this->genFileName(), $contents, $this->genLabel())
->map(function (array $tuple): array {
[$file, $contents, $label] = $tuple;
return ['create', $this->makeFilePath($file, $contents), $label];
});
}
Property Based Testing in the Design Phase
3. Write Test
public function test_Create()
{
$property = Property::forAll(
[$this->genCreateDownloadableProductAction()],
function (array $createAction): bool {
$model = new DownloadableProductModel();
$this->applyToModel($model, $createAction);
return $model->listFileLabels() === [$createAction[2]];
}
);
$this->assertThat($property, PropertyConstraint::check());
}
Property Based Testing in the Design Phase
4. Build Model
class DownloadableProductModel
{
// ...
public function create(string $file, string $label): void
{
$id = 'file_' . (count($this->files) + 1);
$this->files[$id] = [$file, $label];
}
Property Based Testing in the Design Phase
1. Create generator for next action
2. Think of way to verify action on model
3. Write test applying action to model
4. Implement action on model
5. GOTO 1
Build next Action...
All the while learning what I overlooked in the planning phase!
Property Based Testing in the Design Phase
When the model is complete
... the real work begins:
Implement the System with Property Based Tests
(and Example Based Tests where it makes sense).
Finally:
Use the model to check the system!
Summary
• Be curious!
Lets look outside of our comfort zone what others are doing.
• New skills require practice and patience. We need to be kind
to ourselves if something doesn’t work at first, but persist!
• PBT makes systems robust.
It facilitates thinking as much as the coding process.
Thank You

More Related Content

What's hot

Intro to git and git hub
Intro to git and git hubIntro to git and git hub
Intro to git and git hubVenkat Malladi
 
Git and GitHub
Git and GitHubGit and GitHub
Git and GitHubJames Gray
 
MySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZE
MySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZEMySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZE
MySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZENorvald Ryeng
 
스위프트 성능 이해하기
스위프트 성능 이해하기스위프트 성능 이해하기
스위프트 성능 이해하기Yongha Yoo
 
The everyday developer's guide to version control with Git
The everyday developer's guide to version control with GitThe everyday developer's guide to version control with Git
The everyday developer's guide to version control with GitE Carter
 
Monitoring, Logging and Tracing on Kubernetes
Monitoring, Logging and Tracing on KubernetesMonitoring, Logging and Tracing on Kubernetes
Monitoring, Logging and Tracing on KubernetesMartin Etmajer
 
MongoDB World 2015 - A Technical Introduction to WiredTiger
MongoDB World 2015 - A Technical Introduction to WiredTigerMongoDB World 2015 - A Technical Introduction to WiredTiger
MongoDB World 2015 - A Technical Introduction to WiredTigerWiredTiger
 
ReactorKit으로 단방향 반응형 앱 만들기
ReactorKit으로 단방향 반응형 앱 만들기ReactorKit으로 단방향 반응형 앱 만들기
ReactorKit으로 단방향 반응형 앱 만들기Suyeol Jeon
 
Streaming Operational Data with MariaDB MaxScale
Streaming Operational Data with MariaDB MaxScaleStreaming Operational Data with MariaDB MaxScale
Streaming Operational Data with MariaDB MaxScaleMariaDB plc
 
Learning git
Learning gitLearning git
Learning gitSid Anand
 
Big Data Analytics with Google BigQuery. By Javier Ramirez. All your base Co...
Big Data Analytics with Google BigQuery.  By Javier Ramirez. All your base Co...Big Data Analytics with Google BigQuery.  By Javier Ramirez. All your base Co...
Big Data Analytics with Google BigQuery. By Javier Ramirez. All your base Co...javier ramirez
 
MySQL Parallel Replication (LOGICAL_CLOCK): all the 5.7 (and some of the 8.0)...
MySQL Parallel Replication (LOGICAL_CLOCK): all the 5.7 (and some of the 8.0)...MySQL Parallel Replication (LOGICAL_CLOCK): all the 5.7 (and some of the 8.0)...
MySQL Parallel Replication (LOGICAL_CLOCK): all the 5.7 (and some of the 8.0)...Jean-François Gagné
 
Git - Basic Crash Course
Git - Basic Crash CourseGit - Basic Crash Course
Git - Basic Crash CourseNilay Binjola
 
MongoDB et Elasticsearch, meilleurs ennemis ?
MongoDB et Elasticsearch, meilleurs ennemis ?MongoDB et Elasticsearch, meilleurs ennemis ?
MongoDB et Elasticsearch, meilleurs ennemis ?Sébastien Prunier
 
Kubernetes Workshop
Kubernetes WorkshopKubernetes Workshop
Kubernetes Workshoploodse
 

What's hot (20)

Intro to git and git hub
Intro to git and git hubIntro to git and git hub
Intro to git and git hub
 
GIT_In_90_Minutes
GIT_In_90_MinutesGIT_In_90_Minutes
GIT_In_90_Minutes
 
Git and GitHub
Git and GitHubGit and GitHub
Git and GitHub
 
Git basic
Git basicGit basic
Git basic
 
MySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZE
MySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZEMySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZE
MySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZE
 
스위프트 성능 이해하기
스위프트 성능 이해하기스위프트 성능 이해하기
스위프트 성능 이해하기
 
The everyday developer's guide to version control with Git
The everyday developer's guide to version control with GitThe everyday developer's guide to version control with Git
The everyday developer's guide to version control with Git
 
Monitoring, Logging and Tracing on Kubernetes
Monitoring, Logging and Tracing on KubernetesMonitoring, Logging and Tracing on Kubernetes
Monitoring, Logging and Tracing on Kubernetes
 
MongoDB World 2015 - A Technical Introduction to WiredTiger
MongoDB World 2015 - A Technical Introduction to WiredTigerMongoDB World 2015 - A Technical Introduction to WiredTiger
MongoDB World 2015 - A Technical Introduction to WiredTiger
 
Git training v10
Git training v10Git training v10
Git training v10
 
ReactorKit으로 단방향 반응형 앱 만들기
ReactorKit으로 단방향 반응형 앱 만들기ReactorKit으로 단방향 반응형 앱 만들기
ReactorKit으로 단방향 반응형 앱 만들기
 
Streaming Operational Data with MariaDB MaxScale
Streaming Operational Data with MariaDB MaxScaleStreaming Operational Data with MariaDB MaxScale
Streaming Operational Data with MariaDB MaxScale
 
Learning git
Learning gitLearning git
Learning git
 
Big Data Analytics with Google BigQuery. By Javier Ramirez. All your base Co...
Big Data Analytics with Google BigQuery.  By Javier Ramirez. All your base Co...Big Data Analytics with Google BigQuery.  By Javier Ramirez. All your base Co...
Big Data Analytics with Google BigQuery. By Javier Ramirez. All your base Co...
 
MySQL Parallel Replication (LOGICAL_CLOCK): all the 5.7 (and some of the 8.0)...
MySQL Parallel Replication (LOGICAL_CLOCK): all the 5.7 (and some of the 8.0)...MySQL Parallel Replication (LOGICAL_CLOCK): all the 5.7 (and some of the 8.0)...
MySQL Parallel Replication (LOGICAL_CLOCK): all the 5.7 (and some of the 8.0)...
 
Git - Basic Crash Course
Git - Basic Crash CourseGit - Basic Crash Course
Git - Basic Crash Course
 
MongoDB et Elasticsearch, meilleurs ennemis ?
MongoDB et Elasticsearch, meilleurs ennemis ?MongoDB et Elasticsearch, meilleurs ennemis ?
MongoDB et Elasticsearch, meilleurs ennemis ?
 
Git
GitGit
Git
 
Kubernetes Workshop
Kubernetes WorkshopKubernetes Workshop
Kubernetes Workshop
 
Github basics
Github basicsGithub basics
Github basics
 

Similar to Property Based Testing in PHP

Unit testing presentation
Unit testing presentationUnit testing presentation
Unit testing presentationArthur Freyman
 
Refactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartRefactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartGabriele Lana
 
Test Driven Development with JavaFX
Test Driven Development with JavaFXTest Driven Development with JavaFX
Test Driven Development with JavaFXHendrik Ebbers
 
Developer testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing FanaticDeveloper testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing FanaticLB Denker
 
2014 International Software Testing Conference in Seoul
2014 International Software Testing Conference in Seoul2014 International Software Testing Conference in Seoul
2014 International Software Testing Conference in SeoulJongwook Woo
 
Continuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CIContinuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CIwajrcs
 
Test in action – week 1
Test in action – week 1Test in action – week 1
Test in action – week 1Yi-Huan Chan
 
Testing in Craft CMS
Testing in Craft CMSTesting in Craft CMS
Testing in Craft CMSJustinHolt20
 
Into The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applicationsInto The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applicationsOrtus Solutions, Corp
 
Testing for Pragmatic People
Testing for Pragmatic PeopleTesting for Pragmatic People
Testing for Pragmatic Peopledavismr
 
Automated testing in Drupal
Automated testing in DrupalAutomated testing in Drupal
Automated testing in DrupalArtem Berdishev
 
Automated php unit testing in drupal 8
Automated php unit testing in drupal 8Automated php unit testing in drupal 8
Automated php unit testing in drupal 8Jay Friendly
 
Getting to Grips with SilverStripe Testing
Getting to Grips with SilverStripe TestingGetting to Grips with SilverStripe Testing
Getting to Grips with SilverStripe TestingMark Rickerby
 
Principles and patterns for test driven development
Principles and patterns for test driven developmentPrinciples and patterns for test driven development
Principles and patterns for test driven developmentStephen Fuqua
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytestHector Canto
 

Similar to Property Based Testing in PHP (20)

Unit testing presentation
Unit testing presentationUnit testing presentation
Unit testing presentation
 
Refactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartRefactoring In Tdd The Missing Part
Refactoring In Tdd The Missing Part
 
Test Driven Development with JavaFX
Test Driven Development with JavaFXTest Driven Development with JavaFX
Test Driven Development with JavaFX
 
Developer testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing FanaticDeveloper testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing Fanatic
 
2014 International Software Testing Conference in Seoul
2014 International Software Testing Conference in Seoul2014 International Software Testing Conference in Seoul
2014 International Software Testing Conference in Seoul
 
Continuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CIContinuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CI
 
Test in action – week 1
Test in action – week 1Test in action – week 1
Test in action – week 1
 
Modern Python Testing
Modern Python TestingModern Python Testing
Modern Python Testing
 
Gallio Crafting A Toolchain
Gallio Crafting A ToolchainGallio Crafting A Toolchain
Gallio Crafting A Toolchain
 
Unit testing
Unit testingUnit testing
Unit testing
 
Testing in Craft CMS
Testing in Craft CMSTesting in Craft CMS
Testing in Craft CMS
 
Into The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applicationsInto The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applications
 
Testing for Pragmatic People
Testing for Pragmatic PeopleTesting for Pragmatic People
Testing for Pragmatic People
 
Automated testing in Drupal
Automated testing in DrupalAutomated testing in Drupal
Automated testing in Drupal
 
Automated php unit testing in drupal 8
Automated php unit testing in drupal 8Automated php unit testing in drupal 8
Automated php unit testing in drupal 8
 
Getting to Grips with SilverStripe Testing
Getting to Grips with SilverStripe TestingGetting to Grips with SilverStripe Testing
Getting to Grips with SilverStripe Testing
 
Principles and patterns for test driven development
Principles and patterns for test driven developmentPrinciples and patterns for test driven development
Principles and patterns for test driven development
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytest
 
Continuous feature-development
Continuous feature-developmentContinuous feature-development
Continuous feature-development
 

More from vinaikopp

Building Mage-OS - MageTitans 2023
Building Mage-OS - MageTitans 2023Building Mage-OS - MageTitans 2023
Building Mage-OS - MageTitans 2023vinaikopp
 
Hyvä: Compatibility Modules
Hyvä: Compatibility ModulesHyvä: Compatibility Modules
Hyvä: Compatibility Modulesvinaikopp
 
Hyvä from a developer perspective
Hyvä from a developer perspectiveHyvä from a developer perspective
Hyvä from a developer perspectivevinaikopp
 
Property based testing - MageTestFest 2019
Property based testing - MageTestFest 2019Property based testing - MageTestFest 2019
Property based testing - MageTestFest 2019vinaikopp
 
Becoming Certified - MageTitansMCR 2018
Becoming Certified - MageTitansMCR 2018Becoming Certified - MageTitansMCR 2018
Becoming Certified - MageTitansMCR 2018vinaikopp
 
SOS UiComponents
SOS UiComponentsSOS UiComponents
SOS UiComponentsvinaikopp
 
ClojureScript in Magento 2 - PHPUGMRN
ClojureScript in Magento 2 - PHPUGMRNClojureScript in Magento 2 - PHPUGMRN
ClojureScript in Magento 2 - PHPUGMRNvinaikopp
 
Magento 2 TDD Code Kata
Magento 2 TDD Code KataMagento 2 TDD Code Kata
Magento 2 TDD Code Katavinaikopp
 
Magento 2 TDD Code Kata Intro
Magento 2 TDD Code Kata IntroMagento 2 TDD Code Kata Intro
Magento 2 TDD Code Kata Introvinaikopp
 
Testing Magento 2
Testing Magento 2Testing Magento 2
Testing Magento 2vinaikopp
 
ClojureScript in Magento 2 - MageTitansMCR 2017
ClojureScript in Magento 2 - MageTitansMCR 2017ClojureScript in Magento 2 - MageTitansMCR 2017
ClojureScript in Magento 2 - MageTitansMCR 2017vinaikopp
 
Lizards & Pumpkins Catalog Replacement at mm17de
Lizards & Pumpkins Catalog Replacement at mm17deLizards & Pumpkins Catalog Replacement at mm17de
Lizards & Pumpkins Catalog Replacement at mm17devinaikopp
 
Stories from the other side
Stories from the other sideStories from the other side
Stories from the other sidevinaikopp
 
Writing Testable Code (for Magento 1 and 2) 2016 Romaina
Writing Testable Code (for Magento 1 and 2)  2016 RomainaWriting Testable Code (for Magento 1 and 2)  2016 Romaina
Writing Testable Code (for Magento 1 and 2) 2016 Romainavinaikopp
 
Writing Testable Code (for Magento 1 and 2)
Writing Testable Code (for Magento 1 and 2)Writing Testable Code (for Magento 1 and 2)
Writing Testable Code (for Magento 1 and 2)vinaikopp
 
Writing testable Code (MageTitans Mini 2016)
Writing testable Code (MageTitans Mini 2016)Writing testable Code (MageTitans Mini 2016)
Writing testable Code (MageTitans Mini 2016)vinaikopp
 
Getting your Hands Dirty Testing Magento 2 (at London Meetup)
Getting your Hands Dirty Testing Magento 2 (at London Meetup)Getting your Hands Dirty Testing Magento 2 (at London Meetup)
Getting your Hands Dirty Testing Magento 2 (at London Meetup)vinaikopp
 
Getting your hands dirty testing Magento 2 (at MageTitansIT)
Getting your hands dirty testing Magento 2 (at MageTitansIT)Getting your hands dirty testing Magento 2 (at MageTitansIT)
Getting your hands dirty testing Magento 2 (at MageTitansIT)vinaikopp
 
Architecture in-the-small-slides
Architecture in-the-small-slidesArchitecture in-the-small-slides
Architecture in-the-small-slidesvinaikopp
 
Modern Module Architecture
Modern Module ArchitectureModern Module Architecture
Modern Module Architecturevinaikopp
 

More from vinaikopp (20)

Building Mage-OS - MageTitans 2023
Building Mage-OS - MageTitans 2023Building Mage-OS - MageTitans 2023
Building Mage-OS - MageTitans 2023
 
Hyvä: Compatibility Modules
Hyvä: Compatibility ModulesHyvä: Compatibility Modules
Hyvä: Compatibility Modules
 
Hyvä from a developer perspective
Hyvä from a developer perspectiveHyvä from a developer perspective
Hyvä from a developer perspective
 
Property based testing - MageTestFest 2019
Property based testing - MageTestFest 2019Property based testing - MageTestFest 2019
Property based testing - MageTestFest 2019
 
Becoming Certified - MageTitansMCR 2018
Becoming Certified - MageTitansMCR 2018Becoming Certified - MageTitansMCR 2018
Becoming Certified - MageTitansMCR 2018
 
SOS UiComponents
SOS UiComponentsSOS UiComponents
SOS UiComponents
 
ClojureScript in Magento 2 - PHPUGMRN
ClojureScript in Magento 2 - PHPUGMRNClojureScript in Magento 2 - PHPUGMRN
ClojureScript in Magento 2 - PHPUGMRN
 
Magento 2 TDD Code Kata
Magento 2 TDD Code KataMagento 2 TDD Code Kata
Magento 2 TDD Code Kata
 
Magento 2 TDD Code Kata Intro
Magento 2 TDD Code Kata IntroMagento 2 TDD Code Kata Intro
Magento 2 TDD Code Kata Intro
 
Testing Magento 2
Testing Magento 2Testing Magento 2
Testing Magento 2
 
ClojureScript in Magento 2 - MageTitansMCR 2017
ClojureScript in Magento 2 - MageTitansMCR 2017ClojureScript in Magento 2 - MageTitansMCR 2017
ClojureScript in Magento 2 - MageTitansMCR 2017
 
Lizards & Pumpkins Catalog Replacement at mm17de
Lizards & Pumpkins Catalog Replacement at mm17deLizards & Pumpkins Catalog Replacement at mm17de
Lizards & Pumpkins Catalog Replacement at mm17de
 
Stories from the other side
Stories from the other sideStories from the other side
Stories from the other side
 
Writing Testable Code (for Magento 1 and 2) 2016 Romaina
Writing Testable Code (for Magento 1 and 2)  2016 RomainaWriting Testable Code (for Magento 1 and 2)  2016 Romaina
Writing Testable Code (for Magento 1 and 2) 2016 Romaina
 
Writing Testable Code (for Magento 1 and 2)
Writing Testable Code (for Magento 1 and 2)Writing Testable Code (for Magento 1 and 2)
Writing Testable Code (for Magento 1 and 2)
 
Writing testable Code (MageTitans Mini 2016)
Writing testable Code (MageTitans Mini 2016)Writing testable Code (MageTitans Mini 2016)
Writing testable Code (MageTitans Mini 2016)
 
Getting your Hands Dirty Testing Magento 2 (at London Meetup)
Getting your Hands Dirty Testing Magento 2 (at London Meetup)Getting your Hands Dirty Testing Magento 2 (at London Meetup)
Getting your Hands Dirty Testing Magento 2 (at London Meetup)
 
Getting your hands dirty testing Magento 2 (at MageTitansIT)
Getting your hands dirty testing Magento 2 (at MageTitansIT)Getting your hands dirty testing Magento 2 (at MageTitansIT)
Getting your hands dirty testing Magento 2 (at MageTitansIT)
 
Architecture in-the-small-slides
Architecture in-the-small-slidesArchitecture in-the-small-slides
Architecture in-the-small-slides
 
Modern Module Architecture
Modern Module ArchitectureModern Module Architecture
Modern Module Architecture
 

Recently uploaded

My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
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
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
"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
 
"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
 
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
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
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
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
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
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
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
 

Recently uploaded (20)

My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 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...
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
"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
 
"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
 
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)
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
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
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
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
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
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
 

Property Based Testing in PHP

  • 1.
  • 3. Other schools of thinking
  • 4. Lots of inspiration for me Clojure
  • 6. Where Property Based Testing was invented Haskell
  • 7. “Don’t write tests. Generate them.” Prof. John Hughes, Inventor of QuickCheck
  • 8. Example Based Testing (EBT) • Think of an example • Call method(s) • Verify result Property Based Testing (PBT) • Think of range of inputs • Let computer generate inputs • Call method(s) • Verify properties of result • If a failure is found, shrink inputs Property Based Testing?
  • 9. Advantages of Property Based Testing • Replace many example-based tests • Find more bugs than example-based tests • Test complex systems • Test “black box” systems • Facilitates thinking about system under development
  • 10. QuickCheck Implementations PHP • https://github.com/steos/php-quickcheck composer require --dev steos/quickcheck:dev-master • https://github.com/giorgiosironi/eris composer require --dev giorgiosironi/eris
  • 11. What does it look like? class ExampleStringToUpperTest extends TestCase { public function testLengthStaysTheSame() { $property = Property::forAll( [ Generator::strings() ], function (string $input): bool { return mb_strlen($input) === mb_strlen(mb_strtoupper($input)); } ); $this->assertThat($property, PropertyConstraint::check(200)); }
  • 12. What does it look like? Failed asserting that property is true. Test runs: 7, seed: 1580127726247, smallest shrunk value(s): array ( 0 => ' ' . "0" . '', ) vendor/steos/quickcheck/src/QuickCheck/PHPUnit/PropertyConstraint.php:35 test/ExampleStringTest.php:22 Failed asserting that property is true. Test runs: 9, seed: 1580132863563, smallest shrunk value(s): array ( 0 => '' . "0" . ' ' . "0" . ‘‘, ) vendor/steos/quickcheck/src/QuickCheck/PHPUnit/PropertyConstraint.php:35 test/ExampleStringTest.php:22
  • 13. When to use Property Based Testing • During Design • During Implementation (like TDD) • After Implementation • Reproducing a bug
  • 14. Figuring out the properties to test • This is … not an easy thing (at first) • But there are strategies to follow
  • 15. Figuring out the properties to test • reverse? • depend on the order of an input sequence? • depend on grouping of arguments? (Associative) • depend on the order of arguments? (Commutative) • have an identity value? • change it’s output if it is called multiple times? (Idempotent) Algebraic Properties Does the Algorithm…
  • 16. Figuring out the properties to test Functionality Like TDD, but better: Generate the input values instead of hardcoding them. Do not re-implement functionality!
  • 17. Figuring out the properties to test 1. Generate names for directories and files 2. Create directories 3. Create files 4. Execute command (list files) 5. Assert number of files matches created files Functionality Example test for the ls CLI utility:
  • 18. Figuring out the properties to test Commerce is very stateful. Shopping Cart customizations tend to be stateful, too. Mostly stateful
  • 19. Figuring out the properties to test Model ó System Modelling Stateful Systems The model behaves like the System Under Test (SUT), but it doesn’t use persistence or have a REST API.
  • 20. Figuring out the properties to test 1. Create Model of System 2. Generate actions 3. Apply actions to Model and System 4. Check Model and System state match Modelling Stateful Systems The model behaves like the System Under Test (SUT), but it doesn’t use persistence or have a REST API.
  • 21. Property Based Testing in the Design Phase • New Systems: Create model before starting with the real implementation • Existing systems: The model can be partial (only the functionality to test) • The model development is guided by tests (TDD like) • Building the model gives me a better understanding of the real system
  • 22. Property Based Testing in the Design Phase Plan Create Model Generate Action Write Test Write Model
  • 23. Property Based Testing in the Design Phase My current task: Downloadable Products for a different system. I’ve used the same approach with Magento 2, too. For example...
  • 24. Property Based Testing in the Design Phase 1. Sketch out operations Admin • Create new • Add file • Replace file • Remove file • Delete product, keep downloads • Delete product, remove downloads Customer • Purchase downloadable • List available files • Download file Reporting • Downloads per file • …
  • 25. Property Based Testing in the Design Phase 2. Generate Action • Generate data for the initial operation on the system • Return it as an array • Write test for that operation
  • 26. Property Based Testing in the Design Phase 2. Generate Action private function genCreateDownloadableProductAction(): Gen { $contents = Gen::strings(); return Gen::tuples($this->genFileName(), $contents, $this->genLabel()) ->map(function (array $tuple): array { [$file, $contents, $label] = $tuple; return ['create', $this->makeFilePath($file, $contents), $label]; }); }
  • 27. Property Based Testing in the Design Phase 3. Write Test public function test_Create() { $property = Property::forAll( [$this->genCreateDownloadableProductAction()], function (array $createAction): bool { $model = new DownloadableProductModel(); $this->applyToModel($model, $createAction); return $model->listFileLabels() === [$createAction[2]]; } ); $this->assertThat($property, PropertyConstraint::check()); }
  • 28. Property Based Testing in the Design Phase 4. Build Model class DownloadableProductModel { // ... public function create(string $file, string $label): void { $id = 'file_' . (count($this->files) + 1); $this->files[$id] = [$file, $label]; }
  • 29. Property Based Testing in the Design Phase 1. Create generator for next action 2. Think of way to verify action on model 3. Write test applying action to model 4. Implement action on model 5. GOTO 1 Build next Action... All the while learning what I overlooked in the planning phase!
  • 30. Property Based Testing in the Design Phase When the model is complete ... the real work begins: Implement the System with Property Based Tests (and Example Based Tests where it makes sense). Finally: Use the model to check the system!
  • 31. Summary • Be curious! Lets look outside of our comfort zone what others are doing. • New skills require practice and patience. We need to be kind to ourselves if something doesn’t work at first, but persist! • PBT makes systems robust. It facilitates thinking as much as the coding process.
  • 32.