Extracted from:

Property-Based Testing withPropEr, Erlang, and Elixir
Find Bugs Before Your Users Do

This PDF file contains pages extracted from Property-Based Testing with PropEr,Erlang, and Elixir, published by the Pragmatic Bookshelf. For more informationor to purchase a paperback or PDF copy, please visit http://www.pragprog.com.
Note: This extract contains some colored text (particularly in code listing). Thisis available only in online versions of the books. The printed versions are blackand white. Pagination might vary between the online and printed versions; thecontent is otherwise identical.
Copyright © 2019 The Pragmatic Programmers, LLC.
All rights reserved.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise,
without the prior consent of the publisher.

The Pragmatic Bookshelf
Raleigh, North Carolina

Property-Based Testing with
PropEr, Erlang, and Elixir
Find Bugs Before Your Users Do

Fred Hebert

The Pragmatic Bookshelf
Raleigh, North Carolina

Many of the designations used by manufacturers and sellers to distinguish their products
are claimed as trademarks. Where those designations appear in this book, and The PragmaticProgrammers, LLC was aware of a trademark claim, the designations have been printed ininitial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer,
Pragmatic Programming, Pragmatic Bookshelf, PragProg and the linking g device are trademarks of The Pragmatic Programmers, LLC.
Every precaution was taken in the preparation of this book. However, the publisher assumes
no responsibility for errors or omissions, or for damages that may result from the use ofinformation (including program listings) contained herein.
Our Pragmatic books, screencasts, and audio books can help you and your team create
better software and have more fun. Visit us at https://pragprog.com.
The team that produced this book includes:
Publisher: Andy Hunt
VP of Operations: Janet Furlow
Managing Editor: Susan Conant
Development Editor: Jacquelyn Carter
Copy Editor: L. Sakhi MacMillan
Indexing: Potomac Indexing, LLC
Layout: Gilson Graphics
For sales, volume licensing, and support, please contact support@pragprog.com.
For international rights, please contact rights@pragprog.com.

Copyright © 2019 The Pragmatic Programmers, LLC.
All rights reserved. No part of this publication may be reproduced, stored in a retrieval system,or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording,or otherwise, without the prior consent of the publisher.
ISBN-13: 978-1-68050-621-1
Book version: P1.0—January 2019Acknowledgments
I want to thank everyone who offered their time to review this book: SeanCribbs, Chris Keathley (who also has been a huge cheerleader of this workon the Elixir Outlaws podcast), Gabrielle Denhez, Jamu Kakar, Maurice Kelly,
Xavier Shay, Ben Wilson, Evan Vigil-McClanahan, Ben Marx, Bruce Williams,
Kim Shrier, and folks who got the beta versions of this book and then sent
feedback or filed errata, or both.
There’s also an obvious list of people to thank at PragProg, including Andy,
Bruce Tate, and more particularly Jackie Carter, who edited this book andwithout whom it wouldn’t be nearly as readable as it is.
I need to thank Jenn, who tolerated me writing this on weeknights on andoff for over a year. I should finally thank Drew Fradette, who suggested I pitch
my early draft to PragProg, which started the whole process of turning it intothis book.

• Click HERE to purchase this book now. discuss

Introduction
When I finished my first book, Learn You Some Erlang, I told myself “neveragain.” There’s something distressing about spending months and years ofwork writing a book, spending all bits of free time you can find on it, putting
aside other projects and hobbies, and rewriting your own texts close to adozen times. You reach the point where before you’re even done, you’re tiredof writing about the topic you chose to write about.
I knew all of that was waiting for me if I ever wanted to write another book.
I decided to do it anyway because I truly believe property-based testing issomething amazing, worth learning and using. In fact, part of the reason whyI wanted to write a book was that I wanted to use property-based testing in
projects at work and online, and it’s generally a bad idea to introduce atechnology when only one person in the team knows how it works.
It’s a better compromise to spend all that time and effort writing a book thannever using property-based testing in a team when I know what it can do andbring to a project. Hopefully, you’ll feel that learning about it here is worth
your time as well.

Who Is This Book For
If you know enough of Erlang or Elixir to feel comfortable writing a small
project, you’re fit for this book. There’re a few things that might be a bit confusing, but you should be able to pull through.
If you have experience with unit testing and TDD, you’ll feel comfortable withmost of this book’s testing concepts. While the text does not advocate using
TDD or not (we avoid this whole debate), techniques that use properties tohelp design your programs are still shown and constitute a valuable option
to explore a new problem space.
If you are, like me, one of these grumpy people who are annoyed with thequality of software and feel that you can’t trust yourself to deliver high-quality• Click HERE to purchase this book now. discuss

Introduction • viii

code every time—you know your code will come back to haunt you sooner orlater—then you will probably consider property-based testing a godsend.

Why Both Elixir and Erlang
The Erlang and Elixir communities possibly suffer from a kind of narcissismof minor differences; a kind of hostility exists based on small differences
between the two languages and how developers do things, despite Elixir andErlang being so much closer to each other than any other language or platform
out there.
This book represents a conscious effort to bridge the gap between the twocommunities and see both groups join strengths rather than compete witheach other; it is one small part, attempting to use one property-based testing
tool, with one resource, to improve the code and tests of one community.

What’s in This Book
This book covers pretty much everything you need to get started, up to thepoint where you feel confident enough to use the most advanced features ofPropEr. We’ll start smoothly, with the basic and foundational principles ofproperty-based testing, see what the framework offers us to get started, makeour way through thinking in properties, write our own custom data generators,
and then really start going wild. You’ll see how property-based testing can beused in a realistic project (and where it should not be used) and learn various
techniques to make the best use of it possible to get the most value out of it.
We’ll also cover properties to test more complex stateful systems, a practicethat is useful for integration and system tests.
Those are the topics covered, but more than anything, you may get a set ofstrategies to think about new approaches to test your software. Rather thanjust writing repetitive examples for tests, or just generating random data tothrow at the code, you’ll learn new techniques to find new bugs you neverthought could be hiding in your code. You’ll also gain tools to reason about
how to build software, how to explore the problem space, and how to evaluate
the fitness of the solutions you choose.

How to Read This Book
You should feel comfortable just reading all chapters in order. The first partof the book contains truly essential material to get your fundamentals rightand get started properly. The second part applies properties in more realistic
scenarios to gain comfort, and the last part covers stateful tests.

• Click HERE to purchase this book now. discussAbout the Code • ix

But really, it’s easiest to read things in order. Some chapters have questions
and exercises at the end. You can skip these if you want, but going throughthem will be a good way to reinforce your understanding of the material covered.
The exercises are added particularly when a lot of theory is introduced in thechapter and when the material will come back again and again in following
chapters. Going through them may sometimes be tricky, but they will makethe following chapters easier to go through. And because exercises left for thereader with no guidance are annoying as hell, all solutions are provided.

About the Code
Code is provided in both languages in most places where it makes sense to
do so. Code samples may look like the following:Erlang❶%% This is some random code for demonstration purposespath(_Current, Acc, _Seen, [_,_,_,_]) ->Acc;path(Current, Acc, Seen, Ignore) ->frequency([{1, Acc}, % probabilistic stop
{15, increase_path(Current, Acc, Seen, Ignore)}]).
Elixir❶code/path/to/file.erl

code/path/to/file.ex# This is some random code for demonstration purposesdef path(_current, acc, _seen, [_,_,_,_]) do
acc
end
def path(current, acc, seen, ignore) do
frequency([{1, acc}, # probabilistic stop
{15, increase_path(current, acc, seen, ignore)}])
end

Code references such as ❶ will be used to point to locations in both languages
at once.
Exceptions to this norm will include code that should be treated as pseudocode, shell session output (which will be in Erlang only), and longer code
samples that would take a lot of space, which will instead be located within
an appendix to ease the reading flow. Otherwise, things should be quite
readable for both languages at once.

• Click HERE to purchase this book now. discuss

Introduction • xWhen mentioned, file names for a code snippet point to where you shouldput the code if you’re following along. Frequent reminders about this will beadded, just in case. Downloadable code for this book contains the final codefor each module and may not contain intermediary steps shown in the text.

Online Resources
The apps and examples shown in this book can be found at the Pragmatic
Programmers website for this book.1 You’ll also find a link there where you
can provide feedback by submitting errata entries.
The book relies on the PropEr2 library. Its online documentation3 will invariably
prove useful.
Elixir users will use the PropCheck4 wrapper library, which also has its own
online documentation.5Fred Hebert
January 2019

1.
2.
3.
4.
5.

https://pragprog.com/book/fhproper/property-based-testing-with-proper-erlang-and-elixir
https://github.com/proper-testing/proper
https://proper-testing.github.io/
https://github.com/alfert/propcheckhttps://hexdocs.pm/propcheck• Click HERE to purchase this book now. discuss