Property-based Testing

Kyle Marek-Spartz

https://kyle.marek-spartz.org

April 10, 2014

Unit testing

Property-based testing

Properties

Commutativity

Commutative properties of ints:

for_all(int, int)(lambda a, b: a + b == b + a)
for_all(int, int)(lambda a, b: a * b == b * a)

Associativity

More complicated properties:

def prop_associative(a, b, c):
    assert a * (b * c) == (a * b) * c
    return a + (b + c) == (a + b) + c


for_all(int, int, int)(prop_associative)
for_all(float, float, float)(prop_associative)

“Generators”

A “generator” is a specification of a set of possible Python objects. A “generator” is either:

ArbitraryInterface

class ArbitraryInterface(object):
    @classmethod
    def arbitrary(cls):
        raise NotImplementedError

arbitrary

class Tree(ArbitraryInterface):
    value = None
    children = []

    def __init__(self, value, children):
        self.value = value
        self.children = children

    @classmethod
    def arbitrary(cls):
        return cls(
            arbitrary(int),  # Value
            arbitrary(list_of(Tree)),  # Children
        )

“Generator” combinators

To Do

Other QuickCheck-like libraries for Python