5-minute intro to property-based testing in Python with hypothesis

4,474 views

Published on

Slides for 5-minute lightning talk at Pittsburgh Python meetup, 2013-06-26, about the Python module "hypothesis".

Published in: Travel
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
4,474
On SlideShare
0
From Embeds
0
Number of Embeds
1,264
Actions
Shares
0
Downloads
0
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide

5-minute intro to property-based testing in Python with hypothesis

  1. 1. 5-minute intro to property-based testing inPython with hypothesisFranklin Chenhttp://FranklinChen.com/http://ConscientiousProgrammer.com/Pittsburgh Python MeetupJune 26, 2013
  2. 2. Property-based testing vs. example-based testingExample-based testing: assert that a property is true for somevalues.Are list appends associative?Write some examplesdef test_list_append_associative_example1():x, y, z = [2], [3, 4, 5], [6, 7]assert (x + y) + z == x + (y + z)def test_list_append_associative_example2():x, y, z = [2, 3], [], [6, 7]assert (x + y) + z == x + (y + z)# ...
  3. 3. Better: reduce boilerplate with parameterspytest allows parameterization of arguments in tests.Rewrite multiple examples as a single exampleimport pytest@pytest.mark.parametrize (("x", "y", "z"), [([2], [3, 4, 5], [6, 7]),([2, 3], [], [6, 7])])def test_list_append_associative_parametrized(x, y, z):assert (x + y) + z == x + (y + z)
  4. 4. Introduction to property-based hypothesis testingfrom hypothesis.testdecorators import given@given ([int], [int], [int])def test_list_append_associative(x, y, z):assert (x + y) + z == x + (y + z)Passes!hypothesis generates a “large” number of examplesGenerationBased on the type of the argumentNot exhaustive: failure to falsify does not mean true!Default generators providedYou can write your own generators
  5. 5. A sample falsified hypothesis@given (int, int)def test_multiply_then_divide_is_same(x, y):assert (x * y) / y == xResult:... falsifying_example = ((0, 0), {})
  6. 6. Some linkshypothesis documentationpytest-quickcheckMy Pittsburgh Scala meetup talk on property-based testingusing ScalaCheckNat Pryce’s blog post on June 23, 2013
  7. 7. ConclusionProperty-based testing is a useful addition to your toolboxTry it out in Python!All materials for this talk available at https://github.com/franklinchen/lightning-talk-on-hypothesisWill write more about property-based testing on new bloghttp://ConscientiousProgrammer.com/

×