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

Dangerous on ClickHouse in 30 minutes, by Robert Hodges, Altinity CEO
Dangerous on ClickHouse in 30 minutes, by Robert Hodges, Altinity CEODangerous on ClickHouse in 30 minutes, by Robert Hodges, Altinity CEO
Dangerous on ClickHouse in 30 minutes, by Robert Hodges, Altinity CEOAltinity Ltd
 
성장을 좋아하는 사람이, 성장하고 싶은 사람에게
성장을 좋아하는 사람이, 성장하고 싶은 사람에게성장을 좋아하는 사람이, 성장하고 싶은 사람에게
성장을 좋아하는 사람이, 성장하고 싶은 사람에게Seongyun Byeon
 
10 Good Reasons to Use ClickHouse
10 Good Reasons to Use ClickHouse10 Good Reasons to Use ClickHouse
10 Good Reasons to Use ClickHouserpolat
 
Mysql Explain Explained
Mysql Explain ExplainedMysql Explain Explained
Mysql Explain ExplainedJeremy Coates
 
Building ClickHouse and Making Your First Contribution: A Tutorial_06.10.2021
Building ClickHouse and Making Your First Contribution: A Tutorial_06.10.2021Building ClickHouse and Making Your First Contribution: A Tutorial_06.10.2021
Building ClickHouse and Making Your First Contribution: A Tutorial_06.10.2021Altinity Ltd
 
Data Lineage, Property Based Testing & Neo4j
Data Lineage, Property Based Testing & Neo4j Data Lineage, Property Based Testing & Neo4j
Data Lineage, Property Based Testing & Neo4j Neo4j
 
ClickHouse Mark Cache, by Mik Kocikowski, Cloudflare
ClickHouse Mark Cache, by Mik Kocikowski, CloudflareClickHouse Mark Cache, by Mik Kocikowski, Cloudflare
ClickHouse Mark Cache, by Mik Kocikowski, CloudflareAltinity Ltd
 
Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)Scott Wlaschin
 
Glass fish performance tuning tips from the field
Glass fish performance tuning tips from the fieldGlass fish performance tuning tips from the field
Glass fish performance tuning tips from the fieldPayara
 
OFFENSIVE: Exploiting DNS servers changes BlackHat Asia 2014
OFFENSIVE: Exploiting DNS servers changes BlackHat Asia 2014OFFENSIVE: Exploiting DNS servers changes BlackHat Asia 2014
OFFENSIVE: Exploiting DNS servers changes BlackHat Asia 2014Leonardo Nve Egea
 
Windows IOCP vs Linux EPOLL Performance Comparison
Windows IOCP vs Linux EPOLL Performance ComparisonWindows IOCP vs Linux EPOLL Performance Comparison
Windows IOCP vs Linux EPOLL Performance ComparisonSeungmo Koo
 
Pipeline oriented programming
Pipeline oriented programmingPipeline oriented programming
Pipeline oriented programmingScott Wlaschin
 
The Power of Composition (NDC Oslo 2020)
The Power of Composition (NDC Oslo 2020)The Power of Composition (NDC Oslo 2020)
The Power of Composition (NDC Oslo 2020)Scott Wlaschin
 
MySQL_MariaDB-성능개선-202201.pptx
MySQL_MariaDB-성능개선-202201.pptxMySQL_MariaDB-성능개선-202201.pptx
MySQL_MariaDB-성능개선-202201.pptxNeoClova
 
Flink Batch Processing and Iterations
Flink Batch Processing and IterationsFlink Batch Processing and Iterations
Flink Batch Processing and IterationsSameer Wadkar
 
Apache Calcite: A Foundational Framework for Optimized Query Processing Over ...
Apache Calcite: A Foundational Framework for Optimized Query Processing Over ...Apache Calcite: A Foundational Framework for Optimized Query Processing Over ...
Apache Calcite: A Foundational Framework for Optimized Query Processing Over ...Julian Hyde
 

What's hot (20)

Dangerous on ClickHouse in 30 minutes, by Robert Hodges, Altinity CEO
Dangerous on ClickHouse in 30 minutes, by Robert Hodges, Altinity CEODangerous on ClickHouse in 30 minutes, by Robert Hodges, Altinity CEO
Dangerous on ClickHouse in 30 minutes, by Robert Hodges, Altinity CEO
 
성장을 좋아하는 사람이, 성장하고 싶은 사람에게
성장을 좋아하는 사람이, 성장하고 싶은 사람에게성장을 좋아하는 사람이, 성장하고 싶은 사람에게
성장을 좋아하는 사람이, 성장하고 싶은 사람에게
 
10 Good Reasons to Use ClickHouse
10 Good Reasons to Use ClickHouse10 Good Reasons to Use ClickHouse
10 Good Reasons to Use ClickHouse
 
PostgreSQL ile Zaman Serileri
PostgreSQL ile Zaman SerileriPostgreSQL ile Zaman Serileri
PostgreSQL ile Zaman Serileri
 
PostgreSQL: Advanced indexing
PostgreSQL: Advanced indexingPostgreSQL: Advanced indexing
PostgreSQL: Advanced indexing
 
Sql
SqlSql
Sql
 
Mysql Explain Explained
Mysql Explain ExplainedMysql Explain Explained
Mysql Explain Explained
 
Building ClickHouse and Making Your First Contribution: A Tutorial_06.10.2021
Building ClickHouse and Making Your First Contribution: A Tutorial_06.10.2021Building ClickHouse and Making Your First Contribution: A Tutorial_06.10.2021
Building ClickHouse and Making Your First Contribution: A Tutorial_06.10.2021
 
Data Lineage, Property Based Testing & Neo4j
Data Lineage, Property Based Testing & Neo4j Data Lineage, Property Based Testing & Neo4j
Data Lineage, Property Based Testing & Neo4j
 
ClickHouse Mark Cache, by Mik Kocikowski, Cloudflare
ClickHouse Mark Cache, by Mik Kocikowski, CloudflareClickHouse Mark Cache, by Mik Kocikowski, Cloudflare
ClickHouse Mark Cache, by Mik Kocikowski, Cloudflare
 
Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)
 
Glass fish performance tuning tips from the field
Glass fish performance tuning tips from the fieldGlass fish performance tuning tips from the field
Glass fish performance tuning tips from the field
 
OFFENSIVE: Exploiting DNS servers changes BlackHat Asia 2014
OFFENSIVE: Exploiting DNS servers changes BlackHat Asia 2014OFFENSIVE: Exploiting DNS servers changes BlackHat Asia 2014
OFFENSIVE: Exploiting DNS servers changes BlackHat Asia 2014
 
Windows IOCP vs Linux EPOLL Performance Comparison
Windows IOCP vs Linux EPOLL Performance ComparisonWindows IOCP vs Linux EPOLL Performance Comparison
Windows IOCP vs Linux EPOLL Performance Comparison
 
Pipeline oriented programming
Pipeline oriented programmingPipeline oriented programming
Pipeline oriented programming
 
The Power of Composition (NDC Oslo 2020)
The Power of Composition (NDC Oslo 2020)The Power of Composition (NDC Oslo 2020)
The Power of Composition (NDC Oslo 2020)
 
Sql query patterns, optimized
Sql query patterns, optimizedSql query patterns, optimized
Sql query patterns, optimized
 
MySQL_MariaDB-성능개선-202201.pptx
MySQL_MariaDB-성능개선-202201.pptxMySQL_MariaDB-성능개선-202201.pptx
MySQL_MariaDB-성능개선-202201.pptx
 
Flink Batch Processing and Iterations
Flink Batch Processing and IterationsFlink Batch Processing and Iterations
Flink Batch Processing and Iterations
 
Apache Calcite: A Foundational Framework for Optimized Query Processing Over ...
Apache Calcite: A Foundational Framework for Optimized Query Processing Over ...Apache Calcite: A Foundational Framework for Optimized Query Processing Over ...
Apache Calcite: A Foundational Framework for Optimized Query Processing Over ...
 

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

Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
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
 

Recently uploaded (20)

Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
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...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.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
 

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.