Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds Deadline.time_exceeded\1 #5

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions lib/deadline.ex
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,21 @@ defmodule Deadline do
end
end

@doc """
Returns the time past the deadline, in a given unit. Defaults to `:millisecond` units.
If the deadline has not been exceeded then the time exceeded will be 0.
If there is no deadline then the time exceeded will be nil.
"""
def time_exceeded(unit \\ :millisecond) do
case Process.get(@key) do
nil ->
nil

ctx ->
max(0, to_unit(unit, current_time() - ctx.deadline))
end
end

@doc """
Checks if a deadline has been reached or exceeded.
"""
Expand Down
26 changes: 22 additions & 4 deletions test/deadline_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,25 @@ defmodule DeadlineTest do
assert 0 < new_remaining && new_remaining < remaining
end

test "time_remaining/1 returns infinity if there is no deadline set" do
assert Deadline.time_remaining == :infinity
test "time_remaining/1 returns :infinity if there is no deadline set" do
assert Deadline.time_remaining() == :infinity
end

test "time_exceeded/1 returns 0 if the deadline has not been reached" do
Deadline.set(5_000)
exceeded = Deadline.time_exceeded()
assert 0 == exceeded
end

test "time_exceeded/1 returns nil if there is not context" do
assert Deadline.time_exceeded() == nil
end

test "time_exceeded/1 returns the time past the deadline when the deadline is exceeded" do
Deadline.set(10)
Process.sleep(20)
exceeded = Deadline.time_exceeded()
assert exceeded > 0
end

test "can determine if a deadline has been reached" do
Expand All @@ -109,8 +126,9 @@ defmodule DeadlineTest do
test "doesn't explode if there is no deadline context set" do
ctx = Deadline.get()
assert Deadline.set(ctx) == nil
assert Deadline.time_remaining == :infinity
assert Deadline.reached? == false
assert Deadline.time_remaining() == :infinity
assert Deadline.time_exceeded() == nil
assert Deadline.reached?() == false
end

test "time_remaining/1 always returns 0 if the deadline has been exceeded" do
Expand Down