SlideShare a Scribd company logo
1 of 55
Download to read offline
SOFTWARE ENGINEERING ⊇
SOFTWARE TESTING
"The application of a
systematic, disciplined,
quantifiable approach to the
development, operation, and
maintenance of software"
⊆
⊂
GENERIC INVARIANT OR POST
CONDITION OF YOUR CODE, GIVEN
SOME PRECONDITION
“Property-Based Testing in Java”, http://jqwik.net
PROPERTIES
DEFINED
PROPERTY-BASED TESTING
▸ It’s still testing
▸ Moves away from programmer-supplied examples
▸ Captures broader invariants ("properties") about programs
▸ Occupies lower part of test pyramid
▸ Why do we care about it?
REQUIREMENTS FOR PBT
WHAT DO WE NEED TO IMPLEMENT IT?
▸ Input generation
▸ Assertions about properties that holde
▸ Implies: identification of useful and desirable
properties!
▸ [Optional] Counter-example shrinking
EXAMPLE-BASED TESTING
INPUT DOMAIN MAPPED TO PASS/FAIL RESULT
PROPERTY-BASED TESTING
INPUT DOMAIN, VALIDITY TESTING FUNCTION PER PROPERTY
vs.
THE GRANDDADDY
QUICKCHECK
▸ Built in Haskell, released in 2000
▸ Strongly typed language enables elegant generator/
combinator DSL
THE IMITATORS
JVM-BASED LANGUAGE ALTERNATIVES
▸ ScalaCheck
▸ Clojure test.generative
▸ Frege QuickCheck
▸ Java
▸ Theories
▸ JUnit 4: junit-quickcheck
▸ JUnit 5: jqwik
class FizzBuzzes {
/**
* @param length desired size of sequence
* @return a FizzBuzz sequence with specified size
* starting from 1, e.g. for {@code length} == 15:
* <code>["1", "2", "Fizz", "4", "Buzz", "Fizz", "7",
* "8", "Fizz", "Buzz", "11", "Fizz", "13", "14",
* "FizzBuzz"]</code>
*/
static List<String> fizzBuzz(int length) {
return fizzBuzz().limit(length)
.collect(Collectors.toList());
}
}
@Test
public void produces_empty_sequence() {
assertThat(FizzBuzzes.fizzBuzz(0)).containsExactly();
}
@Test
public void produces_one_element() {
assertThat(FizzBuzzes.fizzBuzz(1)).containsExactly("1");
}
@Test
public void produces_fizzes_and_buzzes() {
assertThat(FizzBuzzes.fizzBuzz(15)).containsExactly(
"1", "2", "Fizz", "4", "Buzz", "Fizz", "7",
"8", "Fizz", "Buzz", "11", "Fizz", "13", "14",
"FizzBuzz");
}
@RunWith(JUnitQuickcheck.class)
public class PropertyTest {
}
http://pholser.github.io/junit-quickcheck/
class FizzBuzzGenerator extends Generator<List> {
public FizzBuzzGenerator() {
super(List.class);
}
@Override
public List<String> generate(SourceOfRandomness random, GenerationStatus status) {
return FizzBuzzes.fizzBuzz(status.size());
}
@Override
public List<List> doShrink(SourceOfRandomness random, List larger) {
return IntStream.rangeClosed(0, larger.size() - 1)
.mapToObj(maxIdx -> larger.subList(0, maxIdx))
.collect(Collectors.toList());
}
}
/**
* Checks that every third element is the literal
* <code>"Fizz"</code>.
*
* @param sequence valid FizzBuzz sequence
*/
@Property
public void fizzes(@From(FizzBuzzGenerator.class)
List<String> sequence) {
for (int i = 3; i <= sequence.size(); i += 3) {
assertThat(sequence.get(i - 1))
.contains(“Fizz");
}
}
Verifying property fizzes from demo.PropertyTest_2 with these values:
[demo.PropertyTest_2.fizzes:arg0 = [[]], seed = 7270277137548939525]
Verifying property fizzes from demo.PropertyTest_2 with these values:
[demo.PropertyTest_2.fizzes:arg0 = [[1]], seed = 7270277137548939525]
Verifying property fizzes from demo.PropertyTest_2 with these values:
[demo.PropertyTest_2.fizzes:arg0 = [[1, 2, Fizz, 4, Buzz, Fizz]], seed
= 7270277137548939525]
…
Verifying property fizzes from demo.PropertyTest_2 with these values:
[demo.PropertyTest_2.fizzes:arg0 = [[1, 2, Fizz, 4, Buzz, Fizz, 7, 8,
Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16, 17, Fizz, 19, Buzz, Fizz,
22, 23, Fizz, Buzz, 26, Fizz, 28, 29, FizzBuzz, 31, 32, Fizz, 34, Buzz,
Fizz, 37, 38, Fizz, Buzz, 41, Fizz, 43, 44, FizzBuzz, 46, 47, Fizz, 49,
Buzz, Fizz, 52, 53, Fizz, Buzz, 56, Fizz, 58, 59, FizzBuzz, 61, 62,
Fizz, 64, Buzz, Fizz, 67, 68, Fizz, Buzz, 71, Fizz, 73, 74, FizzBuzz,
76, 77, Fizz, 79, Buzz, Fizz, 82, 83, Fizz, Buzz, 86]], seed =
7270277137548939525]
@RunWith(JUnitQuickcheck.class)
public class IntegerProperties {
@Property(shrink = true)
public void primality(@InRange(minInt = 2) int i) {
assertTrue(String.valueOf(i), IntMath.isPrime(i));
}
}
http://pholser.github.io/junit-quickcheck/
java.lang.AssertionError: Property primality falsified.
Original failure message: [422886279]
Original args: [422886279]
Args shrunken to: [4]
Seeds: [8922134899668966991]
http://pholser.github.io/junit-quickcheck/
THE DEVELOPER IS FORCED TO THINK ABOUT
WHAT THE CODE SHOULD DO AT A HIGH LEVEL
RATHER THAN GRUNT OUT A FEW UNMOTIVATED
TEST CASES.
Joe Nelson, “The Design and Use of QuickCheck”
THINKING ABOUT PROPERTIES
WHERE DOES IT FIT?
Red
✅ Green
Refactor
WHERE DOES IT FIT?
Feature
Spot check
Property? ✅
http://pitest.org
class BrokenReporter {
volatile boolean written = false;
void endReport() {
if (written) {
return;
}
written = true; // must only happen once
}
}
class BrokenReporter {
volatile boolean written = false;
AtomicInteger numWrites = new AtomicInteger();
void endReport() {
if (written) {
return;
}
written = true; // must only happen once
numWrites.incrementAndGet();
}
}
http://openjdk.java.net/projects/code-tools/jcstress/
@JCStressTest
@State
@Outcome(id = "1", expect = Expect.ACCEPTABLE)
class ReporterFixedStressTest {
private Reporter reporter = new Reporter();
private final Object lock = new Object();
@Actor
public void publisher1(IntResult1 result) {
reporter.endReport();
synchronized (lock) {
result.r1 = Math.max(
result.r1,
reporter.numWrites.get());
}
}
// additional actors omitted
}
*** FAILED tests
Strong asserts were violated. Correct implementations
should have no assert failures here.
1 matching test results.
[FAILED] ReporterBrokenStressTest
(JVM args: [])
Observed state Occurrences Expectation
1 42,206 ACCEPTABLE
2 174 FORBIDDEN
http://openjdk.java.net/projects/code-tools/jcstress/
class FixedReporter {
AtomicBoolean written = new AtomicBoolean(false);
void endReport() {
if (written.compareAndSet(false, true)) {
// happens only once, lock-free
}
}
}
http://jepsen.io
https://github.com/javapathfinder/
https://github.com/javapathfinder/
gov.nasa.jpf.listener.PreciseRaceDetector
race for field AtomicFail@15b.written
Thread-1 at AtomicFail.onCompletion(AtomicFail.java:23)
"written = true;" WRITE: putfield AtomicFail.written
Thread-2 at AtomicFail.onCompletion(AtomicFail.java:18)
"if (written) {" READ: getfield AtomicFail.written
thread java.lang.Thread:{id:0,name:main,status:WAITING,priority:5,isDaemon:false,lockCount:0,suspendCount:0}
waiting on: java.lang.Thread@15c
call stack:
at java.lang.Thread.join(Thread.java)
at AtomicFail.main(AtomicFail.java:13)
thread java.lang.Thread:{id:1,name:Thread-1,status:RUNNING,priority:5,isDaemon:false,lockCount:0,suspendCount:0}
call stack:
at AtomicFail.onCompletion(AtomicFail.java:26)
at AtomicFail$$Lambda$0.run(pc 5)
thread java.lang.Thread:{id:2,name:Thread-2,status:RUNNING,priority:5,isDaemon:false,lockCount:0,suspendCount:0}
call stack:
at AtomicFail.onCompletion(AtomicFail.java:18)
at AtomicFail$$Lambda$0.run(pc 5)
http://lamport.azurewebsites.net/tla/tla.html
---- MODULE Transfer ----
EXTENDS Naturals, TLC
(* --algorithm transfer
variables alice_account = 10, bob_account = 10,
account_total = alice_account + bob_account;
process Transfer in 1..2
variable money in 1..20;
begin
Transfer:
if alice_account >= money then
A: alice_account := alice_account - money;
bob_account := bob_account + money;
end if;
C: assert alice_account >= 0;
end process
end algorithm *)
MoneyNotNegative == money >= 0
MoneyInvariant == alice_account + bob_account = account_total
====
https://learntla.com
https://learntla.com
Property-Based Testing with JQwik

More Related Content

What's hot

Making the most of your gradle build - Greach 2017
Making the most of your gradle build - Greach 2017Making the most of your gradle build - Greach 2017
Making the most of your gradle build - Greach 2017Andres Almiray
 
Making the most of your gradle build - Gr8Conf 2017
Making the most of your gradle build - Gr8Conf 2017Making the most of your gradle build - Gr8Conf 2017
Making the most of your gradle build - Gr8Conf 2017Andres Almiray
 
Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Roberto Franchini
 
Durable functions
Durable functionsDurable functions
Durable functions명신 김
 
Azure Durable Functions (2019-04-27)
Azure Durable Functions (2019-04-27)Azure Durable Functions (2019-04-27)
Azure Durable Functions (2019-04-27)Paco de la Cruz
 
Front end unit testing using jasmine
Front end unit testing using jasmineFront end unit testing using jasmine
Front end unit testing using jasmineGil Fink
 
Redux for ReactJS Programmers
Redux for ReactJS ProgrammersRedux for ReactJS Programmers
Redux for ReactJS ProgrammersDavid Rodenas
 
OrientDB - The 2nd generation of (multi-model) NoSQL
OrientDB - The 2nd generation of  (multi-model) NoSQLOrientDB - The 2nd generation of  (multi-model) NoSQL
OrientDB - The 2nd generation of (multi-model) NoSQLRoberto Franchini
 
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)David Gómez García
 
JavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsJavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsKonrad Malawski
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSJim Lynch
 
Serverless APIs, the Good, the Bad and the Ugly (2019-09-19)
Serverless APIs, the Good, the Bad and the Ugly (2019-09-19)Serverless APIs, the Good, the Bad and the Ugly (2019-09-19)
Serverless APIs, the Good, the Bad and the Ugly (2019-09-19)Paco de la Cruz
 
Thomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-finalThomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-finalDroidcon Berlin
 
Kotlinでテストコードを書く
Kotlinでテストコードを書くKotlinでテストコードを書く
Kotlinでテストコードを書くShoichi Matsuda
 
Una Critica a Rails by Luca Guidi
Una Critica a Rails by Luca GuidiUna Critica a Rails by Luca Guidi
Una Critica a Rails by Luca GuidiCodemotion
 
Test or Go Fishing - a guide on how to write better Swift for iOS
Test or Go Fishing - a guide on how to write better Swift for iOSTest or Go Fishing - a guide on how to write better Swift for iOS
Test or Go Fishing - a guide on how to write better Swift for iOSPaul Ardeleanu
 
Testing in android
Testing in androidTesting in android
Testing in androidjtrindade
 

What's hot (20)

Making the most of your gradle build - Greach 2017
Making the most of your gradle build - Greach 2017Making the most of your gradle build - Greach 2017
Making the most of your gradle build - Greach 2017
 
Making the most of your gradle build - Gr8Conf 2017
Making the most of your gradle build - Gr8Conf 2017Making the most of your gradle build - Gr8Conf 2017
Making the most of your gradle build - Gr8Conf 2017
 
Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!
 
Durable functions
Durable functionsDurable functions
Durable functions
 
Azure Durable Functions (2019-04-27)
Azure Durable Functions (2019-04-27)Azure Durable Functions (2019-04-27)
Azure Durable Functions (2019-04-27)
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
 
Front end unit testing using jasmine
Front end unit testing using jasmineFront end unit testing using jasmine
Front end unit testing using jasmine
 
Redux for ReactJS Programmers
Redux for ReactJS ProgrammersRedux for ReactJS Programmers
Redux for ReactJS Programmers
 
OrientDB - The 2nd generation of (multi-model) NoSQL
OrientDB - The 2nd generation of  (multi-model) NoSQLOrientDB - The 2nd generation of  (multi-model) NoSQL
OrientDB - The 2nd generation of (multi-model) NoSQL
 
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
 
JavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsJavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good Parts
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJS
 
Serverless APIs, the Good, the Bad and the Ugly (2019-09-19)
Serverless APIs, the Good, the Bad and the Ugly (2019-09-19)Serverless APIs, the Good, the Bad and the Ugly (2019-09-19)
Serverless APIs, the Good, the Bad and the Ugly (2019-09-19)
 
Javantura v2 - Making Java web-apps Groovy - Franjo Žilić
Javantura v2 - Making Java web-apps Groovy - Franjo ŽilićJavantura v2 - Making Java web-apps Groovy - Franjo Žilić
Javantura v2 - Making Java web-apps Groovy - Franjo Žilić
 
Thomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-finalThomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-final
 
Kotlinでテストコードを書く
Kotlinでテストコードを書くKotlinでテストコードを書く
Kotlinでテストコードを書く
 
Una Critica a Rails by Luca Guidi
Una Critica a Rails by Luca GuidiUna Critica a Rails by Luca Guidi
Una Critica a Rails by Luca Guidi
 
Js tacktalk team dev js testing performance
Js tacktalk team dev js testing performanceJs tacktalk team dev js testing performance
Js tacktalk team dev js testing performance
 
Test or Go Fishing - a guide on how to write better Swift for iOS
Test or Go Fishing - a guide on how to write better Swift for iOSTest or Go Fishing - a guide on how to write better Swift for iOS
Test or Go Fishing - a guide on how to write better Swift for iOS
 
Testing in android
Testing in androidTesting in android
Testing in android
 

Similar to Property-Based Testing with JQwik

Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleThierry Wasylczenko
 
In search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testingIn search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testingAnna Khabibullina
 
Keep your Wicket application in production
Keep your Wicket application in productionKeep your Wicket application in production
Keep your Wicket application in productionMartijn Dashorst
 
Taking Jenkins Pipeline to the Extreme
Taking Jenkins Pipeline to the ExtremeTaking Jenkins Pipeline to the Extreme
Taking Jenkins Pipeline to the Extremeyinonavraham
 
Testing the frontend
Testing the frontendTesting the frontend
Testing the frontendHeiko Hardt
 
Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Paco de la Cruz
 
Android testing
Android testingAndroid testing
Android testingSean Tsai
 
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade ServerlessKatyShimizu
 
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade ServerlessKatyShimizu
 
Testing for fun in production Into The Box 2018
Testing for fun in production Into The Box 2018Testing for fun in production Into The Box 2018
Testing for fun in production Into The Box 2018Ortus Solutions, Corp
 
Improving android experience for both users and developers
Improving android experience for both users and developersImproving android experience for both users and developers
Improving android experience for both users and developersPavel Lahoda
 
Droidcon2013 android experience lahoda
Droidcon2013 android experience lahodaDroidcon2013 android experience lahoda
Droidcon2013 android experience lahodaDroidcon Berlin
 
Unit test candidate solutions
Unit test candidate solutionsUnit test candidate solutions
Unit test candidate solutionsbenewu
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockRobot Media
 
An introduction to Test Driven Development on MapReduce
An introduction to Test Driven Development on MapReduceAn introduction to Test Driven Development on MapReduce
An introduction to Test Driven Development on MapReduceAnanth PackkilDurai
 
Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineGil Fink
 
Integration Testing With ScalaTest and MongoDB
Integration Testing With ScalaTest and MongoDBIntegration Testing With ScalaTest and MongoDB
Integration Testing With ScalaTest and MongoDBMichal Bigos
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
Bang-Bang, you have been hacked - Yonatan Levin, KolGene
Bang-Bang, you have been hacked - Yonatan Levin, KolGeneBang-Bang, you have been hacked - Yonatan Levin, KolGene
Bang-Bang, you have been hacked - Yonatan Levin, KolGeneDroidConTLV
 

Similar to Property-Based Testing with JQwik (20)

Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
In search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testingIn search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testing
 
Keep your Wicket application in production
Keep your Wicket application in productionKeep your Wicket application in production
Keep your Wicket application in production
 
Taking Jenkins Pipeline to the Extreme
Taking Jenkins Pipeline to the ExtremeTaking Jenkins Pipeline to the Extreme
Taking Jenkins Pipeline to the Extreme
 
Tdd & unit test
Tdd & unit testTdd & unit test
Tdd & unit test
 
Testing the frontend
Testing the frontendTesting the frontend
Testing the frontend
 
Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)
 
Android testing
Android testingAndroid testing
Android testing
 
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless
 
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
 
Testing for fun in production Into The Box 2018
Testing for fun in production Into The Box 2018Testing for fun in production Into The Box 2018
Testing for fun in production Into The Box 2018
 
Improving android experience for both users and developers
Improving android experience for both users and developersImproving android experience for both users and developers
Improving android experience for both users and developers
 
Droidcon2013 android experience lahoda
Droidcon2013 android experience lahodaDroidcon2013 android experience lahoda
Droidcon2013 android experience lahoda
 
Unit test candidate solutions
Unit test candidate solutionsUnit test candidate solutions
Unit test candidate solutions
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
 
An introduction to Test Driven Development on MapReduce
An introduction to Test Driven Development on MapReduceAn introduction to Test Driven Development on MapReduce
An introduction to Test Driven Development on MapReduce
 
Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmine
 
Integration Testing With ScalaTest and MongoDB
Integration Testing With ScalaTest and MongoDBIntegration Testing With ScalaTest and MongoDB
Integration Testing With ScalaTest and MongoDB
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Bang-Bang, you have been hacked - Yonatan Levin, KolGene
Bang-Bang, you have been hacked - Yonatan Levin, KolGeneBang-Bang, you have been hacked - Yonatan Levin, KolGene
Bang-Bang, you have been hacked - Yonatan Levin, KolGene
 

Recently uploaded

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 

Recently uploaded (20)

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 

Property-Based Testing with JQwik

  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8. "The application of a systematic, disciplined, quantifiable approach to the development, operation, and maintenance of software"
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14. GENERIC INVARIANT OR POST CONDITION OF YOUR CODE, GIVEN SOME PRECONDITION “Property-Based Testing in Java”, http://jqwik.net PROPERTIES
  • 15. DEFINED PROPERTY-BASED TESTING ▸ It’s still testing ▸ Moves away from programmer-supplied examples ▸ Captures broader invariants ("properties") about programs ▸ Occupies lower part of test pyramid ▸ Why do we care about it?
  • 16. REQUIREMENTS FOR PBT WHAT DO WE NEED TO IMPLEMENT IT? ▸ Input generation ▸ Assertions about properties that holde ▸ Implies: identification of useful and desirable properties! ▸ [Optional] Counter-example shrinking
  • 17. EXAMPLE-BASED TESTING INPUT DOMAIN MAPPED TO PASS/FAIL RESULT
  • 18. PROPERTY-BASED TESTING INPUT DOMAIN, VALIDITY TESTING FUNCTION PER PROPERTY vs.
  • 19. THE GRANDDADDY QUICKCHECK ▸ Built in Haskell, released in 2000 ▸ Strongly typed language enables elegant generator/ combinator DSL
  • 20. THE IMITATORS JVM-BASED LANGUAGE ALTERNATIVES ▸ ScalaCheck ▸ Clojure test.generative ▸ Frege QuickCheck ▸ Java ▸ Theories ▸ JUnit 4: junit-quickcheck ▸ JUnit 5: jqwik
  • 21. class FizzBuzzes { /** * @param length desired size of sequence * @return a FizzBuzz sequence with specified size * starting from 1, e.g. for {@code length} == 15: * <code>["1", "2", "Fizz", "4", "Buzz", "Fizz", "7", * "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", * "FizzBuzz"]</code> */ static List<String> fizzBuzz(int length) { return fizzBuzz().limit(length) .collect(Collectors.toList()); } }
  • 22. @Test public void produces_empty_sequence() { assertThat(FizzBuzzes.fizzBuzz(0)).containsExactly(); } @Test public void produces_one_element() { assertThat(FizzBuzzes.fizzBuzz(1)).containsExactly("1"); } @Test public void produces_fizzes_and_buzzes() { assertThat(FizzBuzzes.fizzBuzz(15)).containsExactly( "1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz"); }
  • 23. @RunWith(JUnitQuickcheck.class) public class PropertyTest { } http://pholser.github.io/junit-quickcheck/
  • 24. class FizzBuzzGenerator extends Generator<List> { public FizzBuzzGenerator() { super(List.class); } @Override public List<String> generate(SourceOfRandomness random, GenerationStatus status) { return FizzBuzzes.fizzBuzz(status.size()); } @Override public List<List> doShrink(SourceOfRandomness random, List larger) { return IntStream.rangeClosed(0, larger.size() - 1) .mapToObj(maxIdx -> larger.subList(0, maxIdx)) .collect(Collectors.toList()); } }
  • 25. /** * Checks that every third element is the literal * <code>"Fizz"</code>. * * @param sequence valid FizzBuzz sequence */ @Property public void fizzes(@From(FizzBuzzGenerator.class) List<String> sequence) { for (int i = 3; i <= sequence.size(); i += 3) { assertThat(sequence.get(i - 1)) .contains(“Fizz"); } }
  • 26. Verifying property fizzes from demo.PropertyTest_2 with these values: [demo.PropertyTest_2.fizzes:arg0 = [[]], seed = 7270277137548939525] Verifying property fizzes from demo.PropertyTest_2 with these values: [demo.PropertyTest_2.fizzes:arg0 = [[1]], seed = 7270277137548939525] Verifying property fizzes from demo.PropertyTest_2 with these values: [demo.PropertyTest_2.fizzes:arg0 = [[1, 2, Fizz, 4, Buzz, Fizz]], seed = 7270277137548939525] … Verifying property fizzes from demo.PropertyTest_2 with these values: [demo.PropertyTest_2.fizzes:arg0 = [[1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16, 17, Fizz, 19, Buzz, Fizz, 22, 23, Fizz, Buzz, 26, Fizz, 28, 29, FizzBuzz, 31, 32, Fizz, 34, Buzz, Fizz, 37, 38, Fizz, Buzz, 41, Fizz, 43, 44, FizzBuzz, 46, 47, Fizz, 49, Buzz, Fizz, 52, 53, Fizz, Buzz, 56, Fizz, 58, 59, FizzBuzz, 61, 62, Fizz, 64, Buzz, Fizz, 67, 68, Fizz, Buzz, 71, Fizz, 73, 74, FizzBuzz, 76, 77, Fizz, 79, Buzz, Fizz, 82, 83, Fizz, Buzz, 86]], seed = 7270277137548939525]
  • 27. @RunWith(JUnitQuickcheck.class) public class IntegerProperties { @Property(shrink = true) public void primality(@InRange(minInt = 2) int i) { assertTrue(String.valueOf(i), IntMath.isPrime(i)); } } http://pholser.github.io/junit-quickcheck/
  • 28. java.lang.AssertionError: Property primality falsified. Original failure message: [422886279] Original args: [422886279] Args shrunken to: [4] Seeds: [8922134899668966991] http://pholser.github.io/junit-quickcheck/
  • 29. THE DEVELOPER IS FORCED TO THINK ABOUT WHAT THE CODE SHOULD DO AT A HIGH LEVEL RATHER THAN GRUNT OUT A FEW UNMOTIVATED TEST CASES. Joe Nelson, “The Design and Use of QuickCheck” THINKING ABOUT PROPERTIES
  • 30. WHERE DOES IT FIT? Red ✅ Green Refactor
  • 31. WHERE DOES IT FIT? Feature Spot check Property? ✅
  • 32.
  • 33.
  • 34.
  • 36.
  • 37. class BrokenReporter { volatile boolean written = false; void endReport() { if (written) { return; } written = true; // must only happen once } }
  • 38. class BrokenReporter { volatile boolean written = false; AtomicInteger numWrites = new AtomicInteger(); void endReport() { if (written) { return; } written = true; // must only happen once numWrites.incrementAndGet(); } }
  • 39. http://openjdk.java.net/projects/code-tools/jcstress/ @JCStressTest @State @Outcome(id = "1", expect = Expect.ACCEPTABLE) class ReporterFixedStressTest { private Reporter reporter = new Reporter(); private final Object lock = new Object(); @Actor public void publisher1(IntResult1 result) { reporter.endReport(); synchronized (lock) { result.r1 = Math.max( result.r1, reporter.numWrites.get()); } } // additional actors omitted }
  • 40. *** FAILED tests Strong asserts were violated. Correct implementations should have no assert failures here. 1 matching test results. [FAILED] ReporterBrokenStressTest (JVM args: []) Observed state Occurrences Expectation 1 42,206 ACCEPTABLE 2 174 FORBIDDEN http://openjdk.java.net/projects/code-tools/jcstress/
  • 41. class FixedReporter { AtomicBoolean written = new AtomicBoolean(false); void endReport() { if (written.compareAndSet(false, true)) { // happens only once, lock-free } } }
  • 42.
  • 44.
  • 45.
  • 46.
  • 48.
  • 50. gov.nasa.jpf.listener.PreciseRaceDetector race for field AtomicFail@15b.written Thread-1 at AtomicFail.onCompletion(AtomicFail.java:23) "written = true;" WRITE: putfield AtomicFail.written Thread-2 at AtomicFail.onCompletion(AtomicFail.java:18) "if (written) {" READ: getfield AtomicFail.written
  • 51. thread java.lang.Thread:{id:0,name:main,status:WAITING,priority:5,isDaemon:false,lockCount:0,suspendCount:0} waiting on: java.lang.Thread@15c call stack: at java.lang.Thread.join(Thread.java) at AtomicFail.main(AtomicFail.java:13) thread java.lang.Thread:{id:1,name:Thread-1,status:RUNNING,priority:5,isDaemon:false,lockCount:0,suspendCount:0} call stack: at AtomicFail.onCompletion(AtomicFail.java:26) at AtomicFail$$Lambda$0.run(pc 5) thread java.lang.Thread:{id:2,name:Thread-2,status:RUNNING,priority:5,isDaemon:false,lockCount:0,suspendCount:0} call stack: at AtomicFail.onCompletion(AtomicFail.java:18) at AtomicFail$$Lambda$0.run(pc 5)
  • 53. ---- MODULE Transfer ---- EXTENDS Naturals, TLC (* --algorithm transfer variables alice_account = 10, bob_account = 10, account_total = alice_account + bob_account; process Transfer in 1..2 variable money in 1..20; begin Transfer: if alice_account >= money then A: alice_account := alice_account - money; bob_account := bob_account + money; end if; C: assert alice_account >= 0; end process end algorithm *) MoneyNotNegative == money >= 0 MoneyInvariant == alice_account + bob_account = account_total ==== https://learntla.com