SlideShare ist ein Scribd-Unternehmen logo
1 von 33
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

MySQL Indexing - Best practices for MySQL 5.6
MySQL Indexing - Best practices for MySQL 5.6MySQL Indexing - Best practices for MySQL 5.6
MySQL Indexing - Best practices for MySQL 5.6
MYXPLAIN
 

Was ist angesagt? (20)

MyBatis에서 JPA로
MyBatis에서 JPA로MyBatis에서 JPA로
MyBatis에서 JPA로
 
Reinventing the Transaction Script (NDC London 2020)
Reinventing the Transaction Script (NDC London 2020)Reinventing the Transaction Script (NDC London 2020)
Reinventing the Transaction Script (NDC London 2020)
 
MySQL partitions tutorial
MySQL partitions tutorialMySQL partitions tutorial
MySQL partitions tutorial
 
Deploying MariaDB databases with containers at Nokia Networks
Deploying MariaDB databases with containers at Nokia NetworksDeploying MariaDB databases with containers at Nokia Networks
Deploying MariaDB databases with containers at Nokia Networks
 
Nginx Internals
Nginx InternalsNginx Internals
Nginx Internals
 
MySQL 8.0 Optimizer Guide
MySQL 8.0 Optimizer GuideMySQL 8.0 Optimizer Guide
MySQL 8.0 Optimizer Guide
 
[Pgday.Seoul 2017] 8. PostgreSQL 10 새기능 소개 - 김상기
[Pgday.Seoul 2017] 8. PostgreSQL 10 새기능 소개 - 김상기[Pgday.Seoul 2017] 8. PostgreSQL 10 새기능 소개 - 김상기
[Pgday.Seoul 2017] 8. PostgreSQL 10 새기능 소개 - 김상기
 
redis 소개자료 - 네오클로바
redis 소개자료 - 네오클로바redis 소개자료 - 네오클로바
redis 소개자료 - 네오클로바
 
Cucumber and Spock Primer
Cucumber and Spock PrimerCucumber and Spock Primer
Cucumber and Spock Primer
 
Full Text Search In PostgreSQL
Full Text Search In PostgreSQLFull Text Search In PostgreSQL
Full Text Search In PostgreSQL
 
엘라스틱서치 실무 가이드_202204.pdf
엘라스틱서치 실무 가이드_202204.pdf엘라스틱서치 실무 가이드_202204.pdf
엘라스틱서치 실무 가이드_202204.pdf
 
MySQL Indexing - Best practices for MySQL 5.6
MySQL Indexing - Best practices for MySQL 5.6MySQL Indexing - Best practices for MySQL 5.6
MySQL Indexing - Best practices for MySQL 5.6
 
Percona toolkit
Percona toolkitPercona toolkit
Percona toolkit
 
[Pgday.Seoul 2020] SQL Tuning
[Pgday.Seoul 2020] SQL Tuning[Pgday.Seoul 2020] SQL Tuning
[Pgday.Seoul 2020] SQL Tuning
 
Fake It Outside-In TDD @XP2017
Fake It Outside-In TDD @XP2017Fake It Outside-In TDD @XP2017
Fake It Outside-In TDD @XP2017
 
Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patterns
 
Istqb 4-테스트설계기법-2015-3-배포
Istqb 4-테스트설계기법-2015-3-배포Istqb 4-테스트설계기법-2015-3-배포
Istqb 4-테스트설계기법-2015-3-배포
 
[Pgday.Seoul 2021] 2. Porting Oracle UDF and Optimization
[Pgday.Seoul 2021] 2. Porting Oracle UDF and Optimization[Pgday.Seoul 2021] 2. Porting Oracle UDF and Optimization
[Pgday.Seoul 2021] 2. Porting Oracle UDF and Optimization
 
MySQL 상태 메시지 분석 및 활용
MySQL 상태 메시지 분석 및 활용MySQL 상태 메시지 분석 및 활용
MySQL 상태 메시지 분석 및 활용
 
Jpa 잘 (하는 척) 하기
Jpa 잘 (하는 척) 하기Jpa 잘 (하는 척) 하기
Jpa 잘 (하는 척) 하기
 

Ähnlich wie Property Based Testing in PHP

Refactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartRefactoring In Tdd The Missing Part
Refactoring In Tdd The Missing Part
Gabriele Lana
 
Test in action – week 1
Test in action – week 1Test in action – week 1
Test in action – week 1
Yi-Huan Chan
 
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
Ortus Solutions, Corp
 
Testing for Pragmatic People
Testing for Pragmatic PeopleTesting for Pragmatic People
Testing for Pragmatic People
davismr
 

Ähnlich wie 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
 

Mehr von vinaikopp

Mehr von 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
 

Kürzlich hochgeladen

Kürzlich hochgeladen (20)

Connecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAKConnecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAK
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through Observability
 
Strategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering TeamsStrategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering Teams
 
Oauth 2.0 Introduction and Flows with MuleSoft
Oauth 2.0 Introduction and Flows with MuleSoftOauth 2.0 Introduction and Flows with MuleSoft
Oauth 2.0 Introduction and Flows with MuleSoft
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
 
AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and Planning
 
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří Karpíšek
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdf
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdf
 

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.