Skip to content

Commit

Permalink
Port sandbox auto_allow into start_supervised_oban
Browse files Browse the repository at this point in the history
  • Loading branch information
sorentwo committed Sep 14, 2022
1 parent 61549ac commit ac757e7
Showing 1 changed file with 54 additions and 17 deletions.
71 changes: 54 additions & 17 deletions test/support/case.ex
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@ defmodule Oban.Case do
alias Oban.Job
alias Oban.Test.Repo

defmodule Peer do
@moduledoc false

def start_link(opts), do: Agent.start_link(fn -> true end, name: opts[:name])

def leader?(pid, _timeout), do: Agent.get(pid, & &1)
end

using do
quote do
use ExUnitProperties
Expand Down Expand Up @@ -49,16 +57,44 @@ defmodule Oban.Case do
opts =
opts
|> Keyword.put_new(:name, make_ref())
|> Keyword.put_new(:notifier, Oban.Notifiers.PG)
|> Keyword.put_new(:peer, Oban.Case.Peer)
|> Keyword.put_new(:poll_interval, :infinity)
|> Keyword.put_new(:repo, Repo)
|> Keyword.put_new(:shutdown_grace_period, 1)
|> Keyword.put_new(:shutdown_grace_period, 250)

name = Keyword.fetch!(opts, :name)
repo = Keyword.fetch!(opts, :repo)

name = opts[:name]
attach_auto_allow(repo, name)

start_supervised!({Oban, opts})

name
end

def with_backoff(opts \\ [], fun) do
total = Keyword.get(opts, :total, 100)
sleep = Keyword.get(opts, :sleep, 10)

with_backoff(fun, 0, total, sleep)
end

def with_backoff(fun, count, total, sleep) do
fun.()
rescue
exception in [ExUnit.AssertionError] ->
if count < total do
Process.sleep(sleep)

with_backoff(fun, count + 1, total, sleep)
else
reraise(exception, __STACKTRACE__)
end
end

# Building

def build(args, opts \\ []) do
if opts[:worker] do
Job.new(args, opts)
Expand All @@ -79,6 +115,8 @@ defmodule Oban.Case do
Oban.insert!(oban, changeset)
end

# Time

def seconds_from_now(seconds) do
DateTime.add(DateTime.utc_now(), seconds, :second)
end
Expand All @@ -87,23 +125,22 @@ defmodule Oban.Case do
DateTime.add(DateTime.utc_now(), -seconds)
end

def with_backoff(opts \\ [], fun) do
total = Keyword.get(opts, :total, 100)
sleep = Keyword.get(opts, :sleep, 10)
# Attaching

with_backoff(fun, 0, total, sleep)
end
defp attach_auto_allow(repo, name) do
telemetry_name = "oban-auto-allow-#{inspect(name)}"

def with_backoff(fun, count, total, sleep) do
fun.()
rescue
exception in [ExUnit.AssertionError] ->
if count < total do
Process.sleep(sleep)
auto_allow = fn _event, _measure, %{conf: conf}, {name, repo, test_pid} ->
if conf.name == name, do: Sandbox.allow(repo, test_pid, self())
end

with_backoff(fun, count + 1, total, sleep)
else
reraise(exception, __STACKTRACE__)
end
:telemetry.attach_many(
telemetry_name,
[[:oban, :engine, :init, :start], [:oban, :plugin, :init]],
auto_allow,
{name, repo, self()}
)

on_exit(name, fn -> :telemetry.detach(telemetry_name) end)
end
end

0 comments on commit ac757e7

Please sign in to comment.