Automating the creation of test cases
by Daniel Bachler (@danyx23)
https://slides.com/danielbachler/pbt
Unit tests
Integration tests
End-to-End tests
Manual tests
Automated test generation
Every example that is tested is created by a human
def add(a, b):
return a + b
def test_add():
assert add(1, 1) == 2
def test_add():
assert add(2, 2) == 4
This code fragment has 100% code coverage of the add function
But only a single point in the possible state space is tested
def add(a, b):
return a + b
def test_add():
assert add(1, 1) == 2
Find properties that should be true about your code
With any arguments
Then create test data automatically and test these properties
def add(a, b):
return a + b
@given(integers())
def test_adds_zero(a):
assert add(a, 0) == a
WWWWBBBA
4W3BA
def rle_encode(input):
...
def rle_decode(input):
...
@given(text())
def test_decode_inverts_encode(s):
assert rle_decode(rle_encode(s)) == s
Works great for any kind of serialisation
def amazing_sort(items):
...
@given(lists(integers()))
def test_is_sorted(items):
amazing_sort(items) == sorted(items)
def amazing_sort(items):
...
def is_sorted(items):
return all(items[i] <= items[i+1] for i in range(len(items)-1))
@given(lists(integers()))
def test_is_sorted(items):
return is_sorted(amazing_sort(items))
Generate random values (many of them)
e.g. text(), integers()
Usually they try "tricky" values
"", "#\0äz象形😂", ...
{-# LANGUAGE DeriveGeneric #-}
import GHC.Generics
import Generic.Random.Generic
data MyType = MyType {
foo :: Int
, bar :: Bool
, baz :: Float
} deriving (Show, Generic)
generate (genericArbitrary :: Gen MyType)
Many PBT libraries offer shrinking
Find simpler test cases if a test fails
Instead of 3KB of text, tells you "象" makes the test fail
e.g. for image classification
hard to write a random generator for pixels and know what classification it should be
but easy to pick example "input" images for known labels
Web service that extracts tables from PDF into CSV
Generate PDFs from randomly generated CSV
extract_csv_from_pdf(csv_to_pdf(csv)) == csv
Oskar Wickströms book and blog
FSharp For Fun and Profit
https://fsharpforfunandprofit.com/posts/property-based-testing/
Hillel Waynes blog
e.g. https://www.hillelwayne.com/post/hypothesis-oracles/
Joe "begriffs" Nelson
https://begriffs.com/posts/2017-01-14-design-use-quickcheck.html
follow me on Twitter: @danyx23
These slides:
https://slides.com/danielbachler/pbt