SlideShare une entreprise Scribd logo
1  sur  18
Télécharger pour lire hors ligne
import org.scalacheck._

  BeScala – February 2012
         Gilles Scouvart
Once upon a time…
• Three scientists (an astrophysicist, a physicist and a
  mathematician) are in a bus to a conference in
  Scotland
• Shortly after the border, they see a black sheep on a
  hillside.
• The astrophysicist declares: « In Scotland, all sheep are
  black! »
• The physicist then says: « Hm, all we can say is that in
  Scotland, some sheep are black. »
• The mathematician sighs and concludes: « All we can
  tell is that in Scotland, there exists one sheep with at
  least one black side! »
The moral of the story
• We’re often relying on a limited set of simple
  examples to validate our assumptions
• But our implementation might totally overfit
  our test set (particularly in TDD)
• And edge cases might go completely
  unnoticed…



     Can we do better?
How can we be sure?
• We would like to check our assumptions for a « general
  case » (intension)
   – This can only be done through formal verification of the code
   – This cannot be automatized for Turing-complete languages (cf.
     halting problem)
• The alternative is then to generate explicitly all possible
  configurations (extension) and test each of them
   – But the number of configurations can be huge or infinite
• Now if our code passes the test on 100 randomly chosen
  examples, we might still get some good level of confidence
  in our implementation
   – This is just what ScalaCheck proposes
Main idea



In ScalaCheck, we check properties on random
         datasets created by generators.
Properties
• Logical statements that the function must satisfy, e.g.
                 Math                                   Scala

 i  , 2*i == i+i                        forAll((i:Int) => 2*i == i+i)
                                           exists((i:Int) => 2*i == 2)
 i  , such that 2*i==2                  forAll{(i:Int,j:Int)=>
 i,j  , (i*j) == 0  i == 0 || j == 0            (i*j)==0 ==> (i==0 || j==0)}
                                                                Try those, you might have some surprises…




• Elements
     – Quantifier: forall, exists, atLeast, iff, imply…
     – Assertion: boolean function
• org.scalacheck.Prop
Generators
• org.scalacheck.Gen
• Basically a function Params => Option[T]
   – Params: size + random number generator
• Built-in generators
   –   choose: integer in range
   –   oneOf : element from sequence of T or Gen[T]
   –   frequency : oneOf taking weights into account
   –   arbitrary : arbitrary instance (incl. edge cases)
• Gen is a Monad!
   – map, flatMap, filter
Generator example
• Suppose we have
   case class Person(name:String,age:Int)
• We can construct a Gen for Person
   val personGen = for (n<-arbitrary[String];a<-
     choose(1,125)) yield Person(n,a)
• We can test it using the sample function
   personGen.sample
                                        Not «?», but Unicode!
   res: Option[Person] = Some(Person(???????????????,85))
• We can use it to test properties on Person
   Prop.forAll(personGen)((p:Person) => p.age>0)
• If we want to use it implicitly we can declare it as an
  arbitrary generator
   implicit val arbPerson = Arbitrary(personGen)
   Prop.forAll((p:Person) => p.age>0)
Generator example (cont’d)
• Now if we only want young people
  val youngPeople = personGen.filter(_.age<31)

• We can use it for some specific tests
  Prop.forAll(youngPeople)((p:Person) => p.age<50)

• If we want a list of 3 young people, we can
  write
  val trio = Gen.listOfN(3,youngPeople)
  trio.sample
  res: Option[List[Person]] =
    Some(List(Person(????????????????????????,4), Person(
    ???????????????,9), Person(???????????,20))))
Complex failures
• Suppose you have a property that relies on
  complex data (e.g. a list)
   (l:List[Int]) => l.size==l.distinct.size
• Now this obviously fails for list with duplicates
• ScalaCheck could give the first failure
   ! Falsified after 5 passed tests.
   > ARG_0: List("-2147483648", "1", "1933529754", "-726958561", "-
      2147483648”, "750300922", "841716922", "-
      2147483648", "1671473995")

• But it gives instead
   ! Falsified after 8 passed tests.
   > ARG_0: List("-1", "-1")
How did this happen?
• ScalaCheck applies shrinking strategies to
  gradually simplify the problem to a simplest
  failing case
• Standard shrinking strategies are provided for
  most common cases
  –   List
  –   Tuple
  –   String
  –   Int
  –   Container
Integration with Scala frameworks
• ScalaTest
  – prop.Checkers trait
    • check method
      (but cannot use the should/must matcher
      syntax)


• Specs2
  – check function
Example
• Scampi               class AlgebraTest extends FeatureSpec with Checkers with Algebra {

  – Library for         // [Generators for E…]
                        def associativity(op: (E, E) => E) =
                         (a: E, b: E, c: E) => simplify(op(op(a, b), c)) == simplify(op(a, op(b, c)))
    Operations
    Research               def commutativity(op: (E, E) => E) =
                            (a: E, b: E) => simplify(op(a, b)) == simplify(op(b, a))
  – Abstract algebra       feature ("Addition") {
    using GADTs              val addition = (e1: E, e2: E) => e1 + e2
                             scenario ("scalars") {
  – Very                     }
                               check((i: Int, j: Int) => Const(i) + Const(j) == Const(i + j))

    mathematical             scenario ("associativity") {
                               check(associativity(addition))
  – Perfect fit              }
                             scenario ("commutativity") {
                               check(commutativity(addition))
                             }
                           }
                           //…
                       }




                                  hg clone https://bitbucket.org/pschaus/scampi
Other nice stuff
• collect to store generated values
• classify to make histograms
• Stateful testing
  – Finite State Machines
  – Types
     • State
     • Command
Pros
• Enhance readability
  – Very declarative, appeals to mathematically-inclined
  – Domain experts can read and comment
• Focuses on properties of input and output
  – Instead of concrete examples
• Automatically explores edge cases
  – Instead of tedious, incomplete and error-prone code
• Shrinks to simplest failing examples
     Domain knowledge          Active documentation
Cons
• It can be difficult to
    – Find « good » properties
        • Not trivially satisfied        Reflection on the domain
        • Not too complex to observe
    – Create « good » generators
        • Relevant edge cases            Reflection on the specifications
    – Write checking functions
        • Implementing the check might be as error-prone as writing the function!

                                         Focus on variations/set of properties

• Requires functional code
                                         Good programming practice

• Beware of shrinking
    – If your property relies on the size of your instances
Credits
• Inspiration
   – Haskell library QuickCheck (Koen Claessen, John Hughes)
• Main contributors
   –   Ricky Nilsson
   –   Tony Morris
   –   Paul Phillips
   –   Yuvi Masonry
• Links
   – GitHub: https://github.com/rickynils/scalacheck
   – User guide:
     http://code.google.com/p/scalacheck/wiki/UserGuide
   – Articles:
     http://code.google.com/p/scalacheck/wiki/ScalaCheckArticles
Thank you!

Contenu connexe

Tendances

Live coding scala 'the java of the future'
Live coding scala 'the java of the future'Live coding scala 'the java of the future'
Live coding scala 'the java of the future'Xebia Nederland BV
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Developmentvito jeng
 
Scala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldScala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldWerner Hofstra
 
High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scaladjspiewak
 
Working with Cocoa and Objective-C
Working with Cocoa and Objective-CWorking with Cocoa and Objective-C
Working with Cocoa and Objective-CKazunobu Tasaka
 
JavaScript Robotics
JavaScript RoboticsJavaScript Robotics
JavaScript RoboticsAnna Gerber
 
Scala - just good for Java shops?
Scala - just good for Java shops?Scala - just good for Java shops?
Scala - just good for Java shops?Sarah Mount
 
Few simple-type-tricks in scala
Few simple-type-tricks in scalaFew simple-type-tricks in scala
Few simple-type-tricks in scalaRuslan Shevchenko
 
Compiled Python UDFs for Impala
Compiled Python UDFs for ImpalaCompiled Python UDFs for Impala
Compiled Python UDFs for ImpalaCloudera, Inc.
 
Serializing EMF models with Xtext
Serializing EMF models with XtextSerializing EMF models with Xtext
Serializing EMF models with Xtextmeysholdt
 
Scala introduction
Scala introductionScala introduction
Scala introductionvito jeng
 
Scala / Technology evolution
Scala  / Technology evolutionScala  / Technology evolution
Scala / Technology evolutionRuslan Shevchenko
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scalashinolajla
 
Ponies and Unicorns With Scala
Ponies and Unicorns With ScalaPonies and Unicorns With Scala
Ponies and Unicorns With ScalaTomer Gabel
 
The essence of Reactive Programming
The essence of Reactive ProgrammingThe essence of Reactive Programming
The essence of Reactive ProgrammingEddy Bertoluzzo
 
Introduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformIntroduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformEastBanc Tachnologies
 

Tendances (20)

Quick swift tour
Quick swift tourQuick swift tour
Quick swift tour
 
Live coding scala 'the java of the future'
Live coding scala 'the java of the future'Live coding scala 'the java of the future'
Live coding scala 'the java of the future'
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Development
 
EMF Tips n Tricks
EMF Tips n TricksEMF Tips n Tricks
EMF Tips n Tricks
 
Scala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldScala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereld
 
High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scala
 
Kotlin
KotlinKotlin
Kotlin
 
Working with Cocoa and Objective-C
Working with Cocoa and Objective-CWorking with Cocoa and Objective-C
Working with Cocoa and Objective-C
 
JavaScript Robotics
JavaScript RoboticsJavaScript Robotics
JavaScript Robotics
 
Scala - just good for Java shops?
Scala - just good for Java shops?Scala - just good for Java shops?
Scala - just good for Java shops?
 
Few simple-type-tricks in scala
Few simple-type-tricks in scalaFew simple-type-tricks in scala
Few simple-type-tricks in scala
 
Coscup
CoscupCoscup
Coscup
 
Compiled Python UDFs for Impala
Compiled Python UDFs for ImpalaCompiled Python UDFs for Impala
Compiled Python UDFs for Impala
 
Serializing EMF models with Xtext
Serializing EMF models with XtextSerializing EMF models with Xtext
Serializing EMF models with Xtext
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Scala / Technology evolution
Scala  / Technology evolutionScala  / Technology evolution
Scala / Technology evolution
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 
Ponies and Unicorns With Scala
Ponies and Unicorns With ScalaPonies and Unicorns With Scala
Ponies and Unicorns With Scala
 
The essence of Reactive Programming
The essence of Reactive ProgrammingThe essence of Reactive Programming
The essence of Reactive Programming
 
Introduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformIntroduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platform
 

Similaire à ScalaCheck

Testing in Scala by Adform research
Testing in Scala by Adform researchTesting in Scala by Adform research
Testing in Scala by Adform researchVasil Remeniuk
 
Testing in Scala. Adform Research
Testing in Scala. Adform ResearchTesting in Scala. Adform Research
Testing in Scala. Adform ResearchVasil Remeniuk
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java ProgrammersEric Pederson
 
Google guava overview
Google guava overviewGoogle guava overview
Google guava overviewSteve Min
 
CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!Ortus Solutions, Corp
 
Stress test your backend with Gatling
Stress test your backend with GatlingStress test your backend with Gatling
Stress test your backend with GatlingAndrzej Ludwikowski
 
Beyond xUnit example-based testing: property-based testing with ScalaCheck
Beyond xUnit example-based testing: property-based testing with ScalaCheckBeyond xUnit example-based testing: property-based testing with ScalaCheck
Beyond xUnit example-based testing: property-based testing with ScalaCheckFranklin Chen
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basicsLovelitJose
 
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...Andrew Phillips
 
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Andrew Phillips
 
Scala in the Wild
Scala in the WildScala in the Wild
Scala in the WildTomer Gabel
 
JSLT: JSON querying and transformation
JSLT: JSON querying and transformationJSLT: JSON querying and transformation
JSLT: JSON querying and transformationLars Marius Garshol
 
Performance tests with Gatling (extended)
Performance tests with Gatling (extended)Performance tests with Gatling (extended)
Performance tests with Gatling (extended)Andrzej Ludwikowski
 
楽々Scalaプログラミング
楽々Scalaプログラミング楽々Scalaプログラミング
楽々ScalaプログラミングTomoharu ASAMI
 
Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)mircodotta
 

Similaire à ScalaCheck (20)

Testing in Scala by Adform research
Testing in Scala by Adform researchTesting in Scala by Adform research
Testing in Scala by Adform research
 
Testing in Scala. Adform Research
Testing in Scala. Adform ResearchTesting in Scala. Adform Research
Testing in Scala. Adform Research
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
Excellent
ExcellentExcellent
Excellent
 
Lexyacc
LexyaccLexyacc
Lexyacc
 
Google guava overview
Google guava overviewGoogle guava overview
Google guava overview
 
CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!
 
Stress test your backend with Gatling
Stress test your backend with GatlingStress test your backend with Gatling
Stress test your backend with Gatling
 
Beyond xUnit example-based testing: property-based testing with ScalaCheck
Beyond xUnit example-based testing: property-based testing with ScalaCheckBeyond xUnit example-based testing: property-based testing with ScalaCheck
Beyond xUnit example-based testing: property-based testing with ScalaCheck
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basics
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
 
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
 
Scala in the Wild
Scala in the WildScala in the Wild
Scala in the Wild
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 
JSLT: JSON querying and transformation
JSLT: JSON querying and transformationJSLT: JSON querying and transformation
JSLT: JSON querying and transformation
 
Performance tests with Gatling (extended)
Performance tests with Gatling (extended)Performance tests with Gatling (extended)
Performance tests with Gatling (extended)
 
楽々Scalaプログラミング
楽々Scalaプログラミング楽々Scalaプログラミング
楽々Scalaプログラミング
 
Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)
 

Dernier

Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsYoss Cohen
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfAarwolf Industries LLC
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...BookNet Canada
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxAna-Maria Mihalceanu
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 

Dernier (20)

Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platforms
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdf
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance Toolbox
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 

ScalaCheck

  • 1. import org.scalacheck._ BeScala – February 2012 Gilles Scouvart
  • 2. Once upon a time… • Three scientists (an astrophysicist, a physicist and a mathematician) are in a bus to a conference in Scotland • Shortly after the border, they see a black sheep on a hillside. • The astrophysicist declares: « In Scotland, all sheep are black! » • The physicist then says: « Hm, all we can say is that in Scotland, some sheep are black. » • The mathematician sighs and concludes: « All we can tell is that in Scotland, there exists one sheep with at least one black side! »
  • 3. The moral of the story • We’re often relying on a limited set of simple examples to validate our assumptions • But our implementation might totally overfit our test set (particularly in TDD) • And edge cases might go completely unnoticed… Can we do better?
  • 4. How can we be sure? • We would like to check our assumptions for a « general case » (intension) – This can only be done through formal verification of the code – This cannot be automatized for Turing-complete languages (cf. halting problem) • The alternative is then to generate explicitly all possible configurations (extension) and test each of them – But the number of configurations can be huge or infinite • Now if our code passes the test on 100 randomly chosen examples, we might still get some good level of confidence in our implementation – This is just what ScalaCheck proposes
  • 5. Main idea In ScalaCheck, we check properties on random datasets created by generators.
  • 6. Properties • Logical statements that the function must satisfy, e.g. Math Scala  i  , 2*i == i+i forAll((i:Int) => 2*i == i+i) exists((i:Int) => 2*i == 2)  i  , such that 2*i==2 forAll{(i:Int,j:Int)=>  i,j  , (i*j) == 0  i == 0 || j == 0 (i*j)==0 ==> (i==0 || j==0)} Try those, you might have some surprises… • Elements – Quantifier: forall, exists, atLeast, iff, imply… – Assertion: boolean function • org.scalacheck.Prop
  • 7. Generators • org.scalacheck.Gen • Basically a function Params => Option[T] – Params: size + random number generator • Built-in generators – choose: integer in range – oneOf : element from sequence of T or Gen[T] – frequency : oneOf taking weights into account – arbitrary : arbitrary instance (incl. edge cases) • Gen is a Monad! – map, flatMap, filter
  • 8. Generator example • Suppose we have case class Person(name:String,age:Int) • We can construct a Gen for Person val personGen = for (n<-arbitrary[String];a<- choose(1,125)) yield Person(n,a) • We can test it using the sample function personGen.sample Not «?», but Unicode! res: Option[Person] = Some(Person(???????????????,85)) • We can use it to test properties on Person Prop.forAll(personGen)((p:Person) => p.age>0) • If we want to use it implicitly we can declare it as an arbitrary generator implicit val arbPerson = Arbitrary(personGen) Prop.forAll((p:Person) => p.age>0)
  • 9. Generator example (cont’d) • Now if we only want young people val youngPeople = personGen.filter(_.age<31) • We can use it for some specific tests Prop.forAll(youngPeople)((p:Person) => p.age<50) • If we want a list of 3 young people, we can write val trio = Gen.listOfN(3,youngPeople) trio.sample res: Option[List[Person]] = Some(List(Person(????????????????????????,4), Person( ???????????????,9), Person(???????????,20))))
  • 10. Complex failures • Suppose you have a property that relies on complex data (e.g. a list) (l:List[Int]) => l.size==l.distinct.size • Now this obviously fails for list with duplicates • ScalaCheck could give the first failure ! Falsified after 5 passed tests. > ARG_0: List("-2147483648", "1", "1933529754", "-726958561", "- 2147483648”, "750300922", "841716922", "- 2147483648", "1671473995") • But it gives instead ! Falsified after 8 passed tests. > ARG_0: List("-1", "-1")
  • 11. How did this happen? • ScalaCheck applies shrinking strategies to gradually simplify the problem to a simplest failing case • Standard shrinking strategies are provided for most common cases – List – Tuple – String – Int – Container
  • 12. Integration with Scala frameworks • ScalaTest – prop.Checkers trait • check method (but cannot use the should/must matcher syntax) • Specs2 – check function
  • 13. Example • Scampi class AlgebraTest extends FeatureSpec with Checkers with Algebra { – Library for // [Generators for E…] def associativity(op: (E, E) => E) = (a: E, b: E, c: E) => simplify(op(op(a, b), c)) == simplify(op(a, op(b, c))) Operations Research def commutativity(op: (E, E) => E) = (a: E, b: E) => simplify(op(a, b)) == simplify(op(b, a)) – Abstract algebra feature ("Addition") { using GADTs val addition = (e1: E, e2: E) => e1 + e2 scenario ("scalars") { – Very } check((i: Int, j: Int) => Const(i) + Const(j) == Const(i + j)) mathematical scenario ("associativity") { check(associativity(addition)) – Perfect fit } scenario ("commutativity") { check(commutativity(addition)) } } //… } hg clone https://bitbucket.org/pschaus/scampi
  • 14. Other nice stuff • collect to store generated values • classify to make histograms • Stateful testing – Finite State Machines – Types • State • Command
  • 15. Pros • Enhance readability – Very declarative, appeals to mathematically-inclined – Domain experts can read and comment • Focuses on properties of input and output – Instead of concrete examples • Automatically explores edge cases – Instead of tedious, incomplete and error-prone code • Shrinks to simplest failing examples Domain knowledge Active documentation
  • 16. Cons • It can be difficult to – Find « good » properties • Not trivially satisfied Reflection on the domain • Not too complex to observe – Create « good » generators • Relevant edge cases Reflection on the specifications – Write checking functions • Implementing the check might be as error-prone as writing the function! Focus on variations/set of properties • Requires functional code Good programming practice • Beware of shrinking – If your property relies on the size of your instances
  • 17. Credits • Inspiration – Haskell library QuickCheck (Koen Claessen, John Hughes) • Main contributors – Ricky Nilsson – Tony Morris – Paul Phillips – Yuvi Masonry • Links – GitHub: https://github.com/rickynils/scalacheck – User guide: http://code.google.com/p/scalacheck/wiki/UserGuide – Articles: http://code.google.com/p/scalacheck/wiki/ScalaCheckArticles