SlideShare a Scribd company logo
Property-based Testing
for Everyone
Dmitriy Morozov / Zoomdata Tech Lunch
Why is testing hard?
Example-based
Testing
• set up one input scenario
• run the code under test
• check the output

(and any other effects the code is supposed to have)
Imagine we needed to
implement a custom ADD
function
@Test

public void testSum() {

assertThat(sum(1, 2), equalTo(3));

}
private int sum(int a, int b) {

if (a == 1 && b == 2) {

return 3;

} else {

return 0;

}

}
@Test

public void testSum() {

assertThat(sum(2, 2), equalTo(4));

}
private int sum(int a, int b) {

if (a == 1 && b == 2) {

return 3;

} else if (a == 2 && b == 2) {

return 4;

} else {

return 0;

}

}
Enterprise Developer
@Test

public void testSum3() {

// When I add two numbers I expect their sum

for (int i = 0; i < 100; i++) {

int x = randomInt();

int y = randomInt();

assertThat(sum(x, y), equalTo(x + y));

}

}
@Test

public void testSum3() {

// When I add two numbers I expect their sum

for (int i = 0; i < 100; i++) {

int x = randomInt();

int y = randomInt();

assertThat(sum(x, y), equalTo(x + y));

}

}
@Test

public void testSumUsingCommutativityProperty() {

// Changing the order of arguments
// shouldn’t change their sum 

for (int i = 0; i < 100; i++) {

int x = randomInt();

int y = randomInt();

assertThat(sum(x, y), equalTo(sum(y, x)));

}

}
// unfortunately that's not enough



private int sum(int a, int b) {

return a * b;

}
@Test

// `x + 2` is the same as `x + 1 + 1` 

public void testSumWithAdditiveProperty() {

for (int i = 0; i < 100; i++) {

int x = randomInt();

int result1 = sum(sum(x , 1), 1);

int result2 = sum(x, 2);

assertEquals(result1, result2);

}

}
// WTF?!
private int sum(int a, int b) {

return 0;

}
@Test

// `x + 1` = `x`

public void testSumWithIdentityProperty() {

for (int i = 0; i < 100; i++) {

int x = randomInt();

assertEquals(x, sum(x, 0));

}

}
Testing Specification with properties
• Commutativity property
• Associativity property
• Identity property
Testing Specification with properties
By using specifications, we have understood the
requirements in a deeper way
QuickCheck
Property-based testing
QuickCheck in a nutshell
John Hughes - Testing the Hard Stuff and Staying Sane
Property-based testing
Benefits
• Less time spent writing test code

- One property replaces many tests
• Better testing

- Lots of combinations you’d never test by hand
• Less time spent on diagnosis

- Failures minimized automatically
3,000 pages of specifications
20,000 lines of QuickCheck
1,000,000 LoC from 6 suppliers
200 bugs
100 bugs in the standard
junit-quickcheck
@RunWith(JUnitQuickcheck.class)

public class AdditionPropertyTest {



@Property

public void commutativityProperty(int x, int y) {

assertThat(sum(x, y), equalTo(sum(y, x)));

}



@Property

public void additiveProperty(int x) {

int result1 = sum(sum(x , 1), 1);

int result2 = sum(x, 2);

assertEquals(result1, result2); }



@Property

public void identityProperty(int x) {

assertEquals(x, sum(x, 0));

}


}
java.lang.AssertionError: Property identityProperty
falsified via shrinking: expected:<1> but was:<0>
Shrunken args: [1]
Original failure message: [expected:<98> but was:<0>]
Original args: [98]
Seeds: [7329045779044418918]
@RunWith(JUnitQuickcheck.class)

public class MoneyChangerTest {



@Property

public void sumOfCoinsEqualsAmount(

@InRange(min = "0", max = "500") int amountToChange,

Set<@InRange(min = "1", max = "100") Integer> denominations) {



assumeThat(denominations.size(), greaterThan(0));

denominations.add(1);



MoneyChanger moneyChanger = new MoneyChanger();

List<Integer> coins = moneyChanger.change(amountToChange, denominations);


int sum = coins.stream().mapToInt(coin -> coin).sum();

assertThat(sum, equalTo(amountToChange));

}



}
JSVerify
npm install jsverify
describe("sort", function () {

jsc.property(

"idempotent", "array nat", function (arr) {

return _.isEqual(sort(sort(arr)), sort(arr));

});

});
How to handle state?
How to handle state?
• Generate actions changing the state
• Apply each action to the state, if possible
• After each application, verify the model
Where can we benefit
from
property-based tests?
Spark Proxy on DataFrame
API
• Generate random DataReadRequest
• Execute request with RDD-based code
• Execute same request with DataFrame based code
• Compare the results
SDK
• Send START_VIS
• Generate random request, change metric, group-
by, filter, sort, etc
• Validate responses based on the test model
• Send STOP_VIS
• QuickCheck
• Testing Telecoms Software with Quviq QuickCheck
• Testing the hard stuff and staying sane
• The Mysteries of Dropbox
• Jepsen IV: Hope Springs Eternal
• Java Examples from this talk

More Related Content

PDF
C++ prgms 3rd unit
Ananda Kumar HN
 
PDF
Property-Based Testing
Shai Geva
 
PPTX
Introduction to julia
岳華 杜
 
PPTX
Exceptional exceptions
Llewellyn Falco
 
PDF
Pybelsberg — Constraint-based Programming in Python
Christoph Matthies
 
PPTX
New presentation oop
Ch shampi Ch shampi
 
DOCX
VISUALIZAR REGISTROS EN UN JTABLE
Darwin Durand
 
PPTX
C sharp 8
Germán Küber
 
C++ prgms 3rd unit
Ananda Kumar HN
 
Property-Based Testing
Shai Geva
 
Introduction to julia
岳華 杜
 
Exceptional exceptions
Llewellyn Falco
 
Pybelsberg — Constraint-based Programming in Python
Christoph Matthies
 
New presentation oop
Ch shampi Ch shampi
 
VISUALIZAR REGISTROS EN UN JTABLE
Darwin Durand
 
C sharp 8
Germán Küber
 

What's hot (20)

DOCX
JAVA AND MYSQL QUERIES
Aditya Shah
 
PDF
C++ L08-Classes Part1
Mohammad Shaker
 
PPTX
Groovy grails types, operators, objects
Husain Dalal
 
DOCX
Example of JAVA Program
Trenton Asbury
 
DOC
code for quiz in my sql
JOYITAKUNDU1
 
PDF
C++ L09-Classes Part2
Mohammad Shaker
 
PDF
Por qué usar Spock en lugar de JUnit / Mockito para tus tests Java - Codemoti...
Andrés Viedma Peláez
 
PPTX
ES6(ES2015) is beautiful
monikagupta18jan
 
PDF
Java Basics - Part1
Vani Kandhasamy
 
PDF
Voce Tem Orgulho Do Seu Codigo
Victor Hugo Germano
 
PPTX
Lexical environment in ecma 262 5
Kim Hunmin
 
PDF
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
ssuserd6b1fd
 
ODP
XML-RPC vs Psycopg2
Associazione Odoo Italia
 
PPTX
Ip project visual mobile
Kendriya vidyalaya no.1 cantt shahjahanpur
 
PDF
Static and const members
mohamed sikander
 
PDF
C++ L01-Variables
Mohammad Shaker
 
PDF
C++ L04-Array+String
Mohammad Shaker
 
PDF
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
ssuserd6b1fd
 
PDF
Javascript
Vlad Ifrim
 
PDF
c programming
Arun Umrao
 
JAVA AND MYSQL QUERIES
Aditya Shah
 
C++ L08-Classes Part1
Mohammad Shaker
 
Groovy grails types, operators, objects
Husain Dalal
 
Example of JAVA Program
Trenton Asbury
 
code for quiz in my sql
JOYITAKUNDU1
 
C++ L09-Classes Part2
Mohammad Shaker
 
Por qué usar Spock en lugar de JUnit / Mockito para tus tests Java - Codemoti...
Andrés Viedma Peláez
 
ES6(ES2015) is beautiful
monikagupta18jan
 
Java Basics - Part1
Vani Kandhasamy
 
Voce Tem Orgulho Do Seu Codigo
Victor Hugo Germano
 
Lexical environment in ecma 262 5
Kim Hunmin
 
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
ssuserd6b1fd
 
XML-RPC vs Psycopg2
Associazione Odoo Italia
 
Static and const members
mohamed sikander
 
C++ L01-Variables
Mohammad Shaker
 
C++ L04-Array+String
Mohammad Shaker
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
ssuserd6b1fd
 
Javascript
Vlad Ifrim
 
c programming
Arun Umrao
 
Ad

Viewers also liked (11)

PDF
ScalaCheckでProperty-based Testing
Koji Agawa
 
DOC
Pino coviello, rodriguez
alvaropinocoviello
 
PDF
Making property-based testing easier to read for humans
Laura M. Castro
 
PDF
Property-based testing
Peter Gromov
 
PPTX
Property Based Testing
Shishir Dwivedi
 
PDF
Property-Based Testing for Services
jessitron
 
PDF
Property based testing - Less is more
Ho Tien VU
 
PDF
Better Tests, Less Code: Property-based Testing
C4Media
 
PDF
Property based Testing - generative data & executable domain rules
Debasish Ghosh
 
PDF
An introduction to property based testing
Scott Wlaschin
 
PPTX
UNIT TESTING PPT
suhasreddy1
 
ScalaCheckでProperty-based Testing
Koji Agawa
 
Pino coviello, rodriguez
alvaropinocoviello
 
Making property-based testing easier to read for humans
Laura M. Castro
 
Property-based testing
Peter Gromov
 
Property Based Testing
Shishir Dwivedi
 
Property-Based Testing for Services
jessitron
 
Property based testing - Less is more
Ho Tien VU
 
Better Tests, Less Code: Property-based Testing
C4Media
 
Property based Testing - generative data & executable domain rules
Debasish Ghosh
 
An introduction to property based testing
Scott Wlaschin
 
UNIT TESTING PPT
suhasreddy1
 
Ad

Similar to Property-based testing (20)

PPT
2012 JDays Bad Tests Good Tests
Tomek Kaczanowski
 
PDF
Java 8 - Nuts and Bold - SFEIR Benelux
yohanbeschi
 
PDF
C++ TUTORIAL 9
Farhan Ab Rahman
 
PDF
public class TrequeT extends AbstractListT { .pdf
info30292
 
PDF
An introduction to Google test framework
Abner Chih Yi Huang
 
PDF
여자개발자모임터 6주년 개발 세미나 - Scala Language
Ashal aka JOKER
 
PDF
Flink Forward Berlin 2017: David Rodriguez - The Approximate Filter, Join, an...
Flink Forward
 
PDF
Leet Code May Coding Challenge - DataStructure and Algorithm Problems
Sunil Yadav
 
PDF
Ruslan Shevchenko - Property based testing
Ievgenii Katsan
 
PDF
"Java Concurrency Stress tests Tool" at IT Tage 2017 by Vadym Kazulkin/Rodion...
Vadym Kazulkin
 
PDF
Mutation @ Spotify
STAMP Project
 
PPTX
JavaScript Advanced - Useful methods to power up your code
Laurence Svekis ✔
 
PDF
Pemrograman visual
Univ. State of Surabaya
 
PDF
It is the main program that implement the min(), max(), floor(), cei.pdf
annaindustries
 
PDF
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 
PPT
OBJECTS IN Object Oriented Programming .ppt
SaadAsim11
 
PDF
Deterministic simulation testing
FoundationDB
 
DOCX
QA Auotmation Java programs,theory
archana singh
 
PDF
생산적인 개발을 위한 지속적인 테스트
기룡 남
 
ODP
Akka
Tim Dalton
 
2012 JDays Bad Tests Good Tests
Tomek Kaczanowski
 
Java 8 - Nuts and Bold - SFEIR Benelux
yohanbeschi
 
C++ TUTORIAL 9
Farhan Ab Rahman
 
public class TrequeT extends AbstractListT { .pdf
info30292
 
An introduction to Google test framework
Abner Chih Yi Huang
 
여자개발자모임터 6주년 개발 세미나 - Scala Language
Ashal aka JOKER
 
Flink Forward Berlin 2017: David Rodriguez - The Approximate Filter, Join, an...
Flink Forward
 
Leet Code May Coding Challenge - DataStructure and Algorithm Problems
Sunil Yadav
 
Ruslan Shevchenko - Property based testing
Ievgenii Katsan
 
"Java Concurrency Stress tests Tool" at IT Tage 2017 by Vadym Kazulkin/Rodion...
Vadym Kazulkin
 
Mutation @ Spotify
STAMP Project
 
JavaScript Advanced - Useful methods to power up your code
Laurence Svekis ✔
 
Pemrograman visual
Univ. State of Surabaya
 
It is the main program that implement the min(), max(), floor(), cei.pdf
annaindustries
 
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 
OBJECTS IN Object Oriented Programming .ppt
SaadAsim11
 
Deterministic simulation testing
FoundationDB
 
QA Auotmation Java programs,theory
archana singh
 
생산적인 개발을 위한 지속적인 테스트
기룡 남
 

Recently uploaded (20)

PPT
Activate_Methodology_Summary presentatio
annapureddyn
 
PPTX
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
PPTX
Presentation about variables and constant.pptx
kr2589474
 
PPTX
Can You Build Dashboards Using Open Source Visualization Tool.pptx
Varsha Nayak
 
PPTX
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
PPTX
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
PDF
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
PPTX
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
PPTX
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
PDF
Using licensed Data Loss Prevention (DLP) as a strategic proactive data secur...
Q-Advise
 
PDF
Exploring AI Agents in Process Industries
amoreira6
 
PPTX
Explanation about Structures in C language.pptx
Veeral Rathod
 
PPTX
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
PPTX
Presentation about variables and constant.pptx
safalsingh810
 
DOCX
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 
PPT
Why Reliable Server Maintenance Service in New York is Crucial for Your Business
Sam Vohra
 
PDF
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
PPTX
The-Dawn-of-AI-Reshaping-Our-World.pptxx
parthbhanushali307
 
PDF
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
PDF
49784907924775488180_LRN2959_Data_Pump_23ai.pdf
Abilash868456
 
Activate_Methodology_Summary presentatio
annapureddyn
 
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
Presentation about variables and constant.pptx
kr2589474
 
Can You Build Dashboards Using Open Source Visualization Tool.pptx
Varsha Nayak
 
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
Using licensed Data Loss Prevention (DLP) as a strategic proactive data secur...
Q-Advise
 
Exploring AI Agents in Process Industries
amoreira6
 
Explanation about Structures in C language.pptx
Veeral Rathod
 
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
Presentation about variables and constant.pptx
safalsingh810
 
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 
Why Reliable Server Maintenance Service in New York is Crucial for Your Business
Sam Vohra
 
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
The-Dawn-of-AI-Reshaping-Our-World.pptxx
parthbhanushali307
 
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
49784907924775488180_LRN2959_Data_Pump_23ai.pdf
Abilash868456
 

Property-based testing

  • 1. Property-based Testing for Everyone Dmitriy Morozov / Zoomdata Tech Lunch
  • 3. Example-based Testing • set up one input scenario • run the code under test • check the output
 (and any other effects the code is supposed to have)
  • 4. Imagine we needed to implement a custom ADD function
  • 5. @Test
 public void testSum() {
 assertThat(sum(1, 2), equalTo(3));
 }
  • 6. private int sum(int a, int b) {
 if (a == 1 && b == 2) {
 return 3;
 } else {
 return 0;
 }
 }
  • 7. @Test
 public void testSum() {
 assertThat(sum(2, 2), equalTo(4));
 }
  • 8. private int sum(int a, int b) {
 if (a == 1 && b == 2) {
 return 3;
 } else if (a == 2 && b == 2) {
 return 4;
 } else {
 return 0;
 }
 }
  • 10. @Test
 public void testSum3() {
 // When I add two numbers I expect their sum
 for (int i = 0; i < 100; i++) {
 int x = randomInt();
 int y = randomInt();
 assertThat(sum(x, y), equalTo(x + y));
 }
 }
  • 11. @Test
 public void testSum3() {
 // When I add two numbers I expect their sum
 for (int i = 0; i < 100; i++) {
 int x = randomInt();
 int y = randomInt();
 assertThat(sum(x, y), equalTo(x + y));
 }
 }
  • 12. @Test
 public void testSumUsingCommutativityProperty() {
 // Changing the order of arguments // shouldn’t change their sum 
 for (int i = 0; i < 100; i++) {
 int x = randomInt();
 int y = randomInt();
 assertThat(sum(x, y), equalTo(sum(y, x)));
 }
 }
  • 13. // unfortunately that's not enough
 
 private int sum(int a, int b) {
 return a * b;
 }
  • 14. @Test
 // `x + 2` is the same as `x + 1 + 1` 
 public void testSumWithAdditiveProperty() {
 for (int i = 0; i < 100; i++) {
 int x = randomInt();
 int result1 = sum(sum(x , 1), 1);
 int result2 = sum(x, 2);
 assertEquals(result1, result2);
 }
 }
  • 15. // WTF?! private int sum(int a, int b) {
 return 0;
 }
  • 16. @Test
 // `x + 1` = `x`
 public void testSumWithIdentityProperty() {
 for (int i = 0; i < 100; i++) {
 int x = randomInt();
 assertEquals(x, sum(x, 0));
 }
 }
  • 17. Testing Specification with properties • Commutativity property • Associativity property • Identity property
  • 18. Testing Specification with properties By using specifications, we have understood the requirements in a deeper way
  • 21. QuickCheck in a nutshell
  • 22. John Hughes - Testing the Hard Stuff and Staying Sane
  • 24. Benefits • Less time spent writing test code
 - One property replaces many tests • Better testing
 - Lots of combinations you’d never test by hand • Less time spent on diagnosis
 - Failures minimized automatically
  • 25. 3,000 pages of specifications 20,000 lines of QuickCheck 1,000,000 LoC from 6 suppliers 200 bugs 100 bugs in the standard
  • 27. @RunWith(JUnitQuickcheck.class)
 public class AdditionPropertyTest {
 
 @Property
 public void commutativityProperty(int x, int y) {
 assertThat(sum(x, y), equalTo(sum(y, x)));
 }
 
 @Property
 public void additiveProperty(int x) {
 int result1 = sum(sum(x , 1), 1);
 int result2 = sum(x, 2);
 assertEquals(result1, result2); }
 
 @Property
 public void identityProperty(int x) {
 assertEquals(x, sum(x, 0));
 } 
 }
  • 28. java.lang.AssertionError: Property identityProperty falsified via shrinking: expected:<1> but was:<0> Shrunken args: [1] Original failure message: [expected:<98> but was:<0>] Original args: [98] Seeds: [7329045779044418918]
  • 29. @RunWith(JUnitQuickcheck.class)
 public class MoneyChangerTest {
 
 @Property
 public void sumOfCoinsEqualsAmount(
 @InRange(min = "0", max = "500") int amountToChange,
 Set<@InRange(min = "1", max = "100") Integer> denominations) {
 
 assumeThat(denominations.size(), greaterThan(0));
 denominations.add(1);
 
 MoneyChanger moneyChanger = new MoneyChanger();
 List<Integer> coins = moneyChanger.change(amountToChange, denominations); 
 int sum = coins.stream().mapToInt(coin -> coin).sum();
 assertThat(sum, equalTo(amountToChange));
 }
 
 }
  • 31. describe("sort", function () {
 jsc.property(
 "idempotent", "array nat", function (arr) {
 return _.isEqual(sort(sort(arr)), sort(arr));
 });
 });
  • 32. How to handle state?
  • 33. How to handle state? • Generate actions changing the state • Apply each action to the state, if possible • After each application, verify the model
  • 34. Where can we benefit from property-based tests?
  • 35. Spark Proxy on DataFrame API • Generate random DataReadRequest • Execute request with RDD-based code • Execute same request with DataFrame based code • Compare the results
  • 36. SDK • Send START_VIS • Generate random request, change metric, group- by, filter, sort, etc • Validate responses based on the test model • Send STOP_VIS
  • 37. • QuickCheck • Testing Telecoms Software with Quviq QuickCheck • Testing the hard stuff and staying sane • The Mysteries of Dropbox • Jepsen IV: Hope Springs Eternal • Java Examples from this talk