SlideShare una empresa de Scribd logo
1 de 18
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!

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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
 

Similar a ScalaCheck

Testing in Scala. Adform Research
Testing in Scala. Adform ResearchTesting in Scala. Adform Research
Testing in Scala. Adform ResearchVasil Remeniuk
 
Testing in Scala by Adform research
Testing in Scala by Adform researchTesting in Scala by Adform research
Testing in Scala by 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
 

Similar a ScalaCheck (20)

Testing in Scala. Adform Research
Testing in Scala. Adform ResearchTesting in Scala. Adform Research
Testing in Scala. Adform Research
 
Testing in Scala by Adform research
Testing in Scala by Adform researchTesting in Scala by Adform research
Testing in Scala by 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)
 

Último

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
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 

Último (20)

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
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 

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