Slide 1

Slide 1 text

Hardening Applications with Property Tests

Slide 2

Slide 2 text

Hardening a Library with Property Tests

Slide 3

Slide 3 text

Parker Selbert @sorentwo Soren / Dscout

Slide 4

Slide 4 text

Adopting Elixir and a library named Kiq

Slide 5

Slide 5 text

Nobody likes finding bugs in production.

Slide 6

Slide 6 text

Kiq Oban Initially, an experiment to model queues as streams.

Slide 7

Slide 7 text

Starting over meant building up new example tests, with many possible regressions.

Slide 8

Slide 8 text

Property-Based Testing • PropEr • StreamData
 • Proper Book

Slide 9

Slide 9 text

Properties Aspects of code that hold for a set of randomized test data Functions that dynamically generate infinite streams of data Generators

Slide 10

Slide 10 text

EX1 Reliable Execution

Slide 11

Slide 11 text

What is absolute?

Slide 12

Slide 12 text

What is absolute? All inserted jobs are attempted at least once.

Slide 13

Slide 13 text

property "inserted jobs are executed at least once" do check all jobs <- list_of(job()) do for %{id: id, args: %{"ref" => ref}} <- Oban.insert_all(jobs) do assert_receive {:ok, ^ref} assert %{attempt: 1, attempted_at: %DateTime{}} = Repo.get(Job, job.id) end end end

Slide 14

Slide 14 text

property "inserted jobs are executed at least once" do check all jobs <- list_of(job()) do for %{id: id, args: %{"ref" => ref}} <- Oban.insert_all(jobs) do assert_receive {:ok, ^ref} assert %{attempt: 1, attempted_at: %DateTime{}} = Repo.get(Job, job.id) end end end

Slide 15

Slide 15 text

defp job do gen all queue <- member_of(~w(alpha beta gamma delta)), ref <- integer() do Job.new(%{ref: ref}, queue: queue, worker: Worker) end end

Slide 16

Slide 16 text

property "inserted jobs are executed at least once" do check all jobs <- list_of(job()) do for %{id: id, args: %{"ref" => ref}} <- Oban.insert_all(jobs) do assert_receive {:ok, ^ref} assert %{attempt: 1, attempted_at: %DateTime{}} = Repo.get(Job, job.id) end end end

Slide 17

Slide 17 text

1) property inserted jobs are executed at least once (Oban.ExecutingTest) Failed with generated values (after 13 successful runs): * Clause: jobs <- list_of(job()) Generated: [#Ecto.Changeset] Assertion with == failed code: assert job.attempt == 1 left: 0 right: 1

Slide 18

Slide 18 text

✂ Make Oban Work…

Slide 19

Slide 19 text

. Finished in 1.4 seconds 1 property, 0 tests, 0 failures

Slide 20

Slide 20 text

Additional Absolutes •Record errors on failure •Schedule failed jobs for retry •Discard jobs without more attempts

Slide 21

Slide 21 text

case job.state do "completed" -> assert job.completed_at "discarded" -> refute job.completed_at assert job.discarded_at "retryable" -> refute job.completed_at assert DateTime.compare(job.scheduled_at, DateTime.utc_now()) == :gt assert length(job.errors) > 0 assert [%{"attempt" => 1, "at" => _, "error" => _} | _] = job.errors "scheduled" -> refute job.completed_at assert DateTime.compare(job.scheduled_at, DateTime.utc_now()) == :gt assert job.max_attempts > 1 end

Slide 22

Slide 22 text

case job.state do "completed" -> assert job.completed_at "discarded" -> refute job.completed_at assert job.discarded_at "retryable" -> refute job.completed_at assert DateTime.compare(job.scheduled_at, DateTime.utc_now()) == :gt assert length(job.errors) > 0 assert [%{"attempt" => 1, "at" => _, "error" => _} | _] = job.errors "scheduled" -> refute job.completed_at assert DateTime.compare(job.scheduled_at, DateTime.utc_now()) == :gt assert job.max_attempts > 1 end

Slide 23

Slide 23 text

defp job do gen all queue <- member_of(~w(alpha beta gamma delta)), action <- member_of(~w(OK DISCARD ERROR EXIT FAIL SNOOZE)), max_attempts <- integer(1..20), ref <- integer() do args = %{ref: ref, action: action} opts = [queue: queue, max_attempts: max_attempts, worker: Worker] Job.new(args, opts) end end

Slide 24

Slide 24 text

1 generator
 1 semi-stateful property test ~2000 lines of library code

Slide 25

Slide 25 text

EX2 Unique Jobs

Slide 26

Slide 26 text

The Blog Recipe •Partial Index •Insert Helper •Manual Implementation

Slide 27

Slide 27 text

What is absolute?

Slide 28

Slide 28 text

What is absolute? Duplicate jobs are never inserted, regardless of concurrency.

Slide 29

Slide 29 text

property "preventing multiple inserts” do check all args <- arg_map(), runs <- integer(2..5) do fun = fn -> unique_insert!(args) end ids = 1..runs |> Enum.map(fn _ -> Task.async(fun) end) |> Enum.map(&Task.await/1) |> Enum.map(fn %Job{id: id} -> id end) |> Enum.reject(&is_nil/1) |> Enum.uniq() assert 1 == length(ids) end end

Slide 30

Slide 30 text

property "preventing multiple inserts” do check all args <- arg_map(), runs <- integer(2..5) do fun = fn -> unique_insert!(args) end ids = 1..runs |> Enum.map(fn _ -> Task.async(fun) end) |> Enum.map(&Task.await/1) |> Enum.map(fn %Job{id: id} -> id end) |> Enum.reject(&is_nil/1) |> Enum.uniq() assert 1 == length(ids) end end

Slide 31

Slide 31 text

def arg_map, do: map_of(arg_key(), arg_val()) def arg_key, do: one_of([integer(), string(:ascii)]) def arg_val, do: one_of([integer(), float(), string(:ascii), list_of(integer())])

Slide 32

Slide 32 text

property "preventing multiple inserts” do check all args <- arg_map(), runs <- integer(2..5) do fun = fn -> unique_insert!(args) end ids = 1..runs |> Enum.map(fn _ -> Task.async(fun) end) |> Enum.map(&Task.await/1) |> Enum.map(fn %Job{id: id} -> id end) |> Enum.reject(&is_nil/1) |> Enum.uniq() assert 1 == length(ids) end end

Slide 33

Slide 33 text

defmodule UniqueWorker do use Oban.Worker, unique: [period: 30] @impl Worker def perform(_job), do: :ok end defp unique_insert!(args, opts \\ []) do args |> UniqueWorker.new(opts) |> Oban.insert!() end

Slide 34

Slide 34 text

property "preventing multiple inserts” do check all args <- arg_map(), runs <- integer(2..5) do fun = fn -> unique_insert!(args) end ids = 1..runs |> Enum.map(fn _ -> Task.async(fun) end) |> Enum.map(&Task.await/1) |> Enum.map(fn %Job{id: id} -> id end) |> Enum.reject(&is_nil/1) |> Enum.uniq() assert 1 == length(ids) end end

Slide 35

Slide 35 text

1) property preventing multiple inserts (Oban.UniquenessTest) Failed with generated values (after 0 successful runs): * Clause: args <- arg_map() Generated: %{"" => 0} * Clause: runs <- integer(2..5) Generated: 2 Assertion with == failed code: assert 1 == length(ids) left: 1 right: 4

Slide 36

Slide 36 text

✂ Prevent concurrent writes…

Slide 37

Slide 37 text

. Finished in 0.7 seconds 1 property, 0 tests, 0 failures

Slide 38

Slide 38 text

3 generators
 1 property test 2+ concurrent inserts 0 reported† bugs † if you don’t count that prefix thing…

Slide 39

Slide 39 text

EX3 Safe Migrations

Slide 40

Slide 40 text

Progressive Migrations, v1..v8 •Tables •Columns •Functions •Triggers •Indexes

Slide 41

Slide 41 text

What is absolute?

Slide 42

Slide 42 text

What is absolute? Migrating up or down between any two versions is successful.

Slide 43

Slide 43 text

@base_migration 100_000
 @current_version 8 
 property "migrating up and down between arbitrary versions" do check all up <- integer(1..@current_version), down <- integer(1..(@current_version - 1)) do Application.put_env(:oban, :up_version, up) Application.put_env(:oban, :down_version, down) assert :ok = Ecto.Migrator.up(Repo, @base_migration, StepMigration) assert :ok = Ecto.Migrator.down(Repo, @base_migration, StepMigration) clear_migrated() end end

Slide 44

Slide 44 text

@base_migration 100_000
 @current_version 8 
 property "migrating up and down between arbitrary versions" do check all up <- integer(1..@current_version), down <- integer(1..(@current_version - 1)) do Application.put_env(:oban, :up_version, up) Application.put_env(:oban, :down_version, down) assert :ok = Ecto.Migrator.up(Repo, @base_migration, StepMigration) assert :ok = Ecto.Migrator.down(Repo, @base_migration, StepMigration) clear_migrated() end end

Slide 45

Slide 45 text

defmodule StepMigration do use Ecto.Migration def up do up_version = Application.get_env(:oban, :up_version) Oban.Migrations.up(version: up_version) end def down do down_version = Application.get_env(:oban, :up_version) 
 Oban.Migrations.down(version: down_version) end end

Slide 46

Slide 46 text

1) property migrating up and down between arbitrary versions (Oban.MigratingTest) Failed with generated values (after 1 successful run): * Clause: up <- integer(2..current_version()) Generated: 8 * Clause: down <- integer(1..current_version() - 1) Generated: 1 got exception: ** (Postgrex.Error) ERROR 42P07 (duplicate_table) relation already exists

Slide 47

Slide 47 text

✂ Ensure up/down safety…

Slide 48

Slide 48 text

. Finished in 5.7 seconds 1 property, 0 tests, 0 failures

Slide 49

Slide 49 text

@base_migration 100_000
 @current_version 8 
 property "migrating up and down between arbitrary versions" do check all up <- integer(1..@current_version), down <- integer(1..(@current_version - 1)) do Application.put_env(:oban, :up_version, up) Application.put_env(:oban, :down_version, down) assert :ok = Ecto.Migrator.up(Repo, @base_migration, StepMigration) assert :ok = Ecto.Migrator.down(Repo, @base_migration, StepMigration) clear_migrated() end end

Slide 50

Slide 50 text

iex> length(for x <- 1..8, y <- 1..7, do: {x, y}) 56 ⏲ How many permutations are there?

Slide 51

Slide 51 text

@base_migration 100_000
 @current_version 8 
 test "migrating up and down between arbitrary versions" do for up <- 1..@current_version, down <- 1..(@current_version - 1) do Application.put_env(:oban, :up_version, up) Application.put_env(:oban, :down_version, down) assert :ok = Ecto.Migrator.up(Repo, @base_migration, StepMigration) assert :ok = Ecto.Migrator.down(Repo, @base_migration, StepMigration) clear_migrated() end end

Slide 52

Slide 52 text

. Finished in 1.7 seconds 1 test, 0 failures, 0 excluded

Slide 53

Slide 53 text

1 test for up 1 test for up+down
 120 permutations

Slide 54

Slide 54 text

EX4 Cron Parsing

Slide 55

Slide 55 text

Barrier to Adoption •We depend on periodic jobs… •Periodic jobs depends on unique jobs… •Unique jobs shipped…

Slide 56

Slide 56 text

* 0-5,*/3 7-14 */2 MON,TUE “At every minute past every hour from 0 through 5 and every 3rd hour on every day-of-month from 7 through 14 and on Monday and Tuesday in every 2nd month”

Slide 57

Slide 57 text

property "literal values and aliases are parsed" do check all minutes <- expression(), hours <- integer(0..23), days <- integer(1..31), months <- months(), weekdays <- weekdays(), spaces <- spaces() do spacing = :erlang.iolist_to_binary(spaces) [minutes, hours, days, months, weekdays] |> Enum.join(spacing) |> Cron.parse!() end end

Slide 58

Slide 58 text

property “valid cron expressions are parsed" do check all minutes <- expression(), hours <- integer(0..23), days <- integer(1..31), months <- months(), weekdays <- weekdays(), spaces <- spaces() do spacing = :erlang.iolist_to_binary(spaces) [minutes, hours, days, months, weekdays] |> Enum.join(spacing) |> Cron.parse!() end end

Slide 59

Slide 59 text

defp months do one_of([integer(1..12), constant("JAN"), ...]) end defp weekdays do one_of([integer(0..6), constant("MON"), ...]) end defp spaces do list_of(one_of([constant(" "), constant("\t")]), min_length: 1) end

Slide 60

Slide 60 text

defp expression do one_of([ constant("*"), map(integer(1..59), &"*/#{&1}"), map(integer(1..58), &"#{&1}-#{&1 + 1}"), map(integer(1..57), &"#{&1}-#{&1 + 2}/2"), list_of(integer(0..59), length: 1..10) ]) end

Slide 61

Slide 61 text

property "literal values and aliases are parsed" do check all minutes <- integer(0..59), hours <- integer(0..23), days <- integer(1..31), months <- months(), weekdays <- weekdays(), spaces <- spaces() do spacing = :erlang.iolist_to_binary(spaces) [minutes, hours, days, months, weekdays] |> Enum.join(spacing) |> Cron.parse!() end end

Slide 62

Slide 62 text

1) property valid expressions and aliases are parsed (Oban.CronTest) ** (ExUnitProperties.Error) failed with generated values (after 1 successful run): * Clause: minutes <- integer(0..59) Generated: 44 * Clause: hours <- integer(0..23) Generated: 14 * Clause: days <- integer(1..31) Generated: 5 * Clause: months <- months() Generated: "JUL" * Clause: weekdays <- weekdays() Generated: 0 * Clause: spaces <- spaces() Generated: [" ", " "] got exception: ** (ArgumentError) expected string "*" or ASCII character in the range '0' to '9'...

Slide 63

Slide 63 text

✂ Write and Refine Cron Parser…

Slide 64

Slide 64 text

. Finished in 0.1 seconds 1 property, 0 tests, 0 failures

Slide 65

Slide 65 text

test "parsing expressions that are out of bounds fails" do invalid_expressions = [ "60 * * * *", "* 24 * * *", "* * 32 * *", "* * * 13 *", "* * * * 7", "*/0 * * * *", "ONE * * * *", "* * * jan *", "* * * * sun" ] for expression <- invalid_expressions, do: assert_unparsable(expression) end defp assert_unparsable(expression) do assert_raise ArgumentError, fn -> Cron.parse!(expression) end end

Slide 66

Slide 66 text

1 property for valid expressions 1 test for invalid expressions
 1 reported bug

Slide 67

Slide 67 text

Look for absolute truths. Once you understand them the properties and generators fall out naturally.

Slide 68

Slide 68 text

Write fewer, more expressive tests. Not just for your libraries, but your applications too.

Slide 69

Slide 69 text

Oban Web+Pro UI / Plugins / Workers getoban.pro