Skip to content

Commit 15e17c1

Browse files
authored
Raise in Time.add/3 for non-positive integer (#13122)
1 parent b89d855 commit 15e17c1

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

lib/elixir/lib/calendar/time.ex

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -515,10 +515,11 @@ defmodule Time do
515515

516516
def add(%{calendar: calendar, microsecond: {_, precision}} = time, amount_to_add, unit)
517517
when is_integer(amount_to_add) do
518-
if not is_integer(unit) and
518+
if (is_integer(unit) and unit < 1) or
519519
unit not in ~w(second millisecond microsecond nanosecond)a do
520520
raise ArgumentError,
521-
"unsupported time unit. Expected :hour, :minute, :second, :millisecond, :microsecond, :nanosecond, or a positive integer, got #{inspect(unit)}"
521+
"unsupported time unit. Expected :hour, :minute, :second, :millisecond, " <>
522+
":microsecond, :nanosecond, or a positive integer, got #{inspect(unit)}"
522523
end
523524

524525
amount_to_add = System.convert_time_unit(amount_to_add, unit, :microsecond)

lib/elixir/test/elixir/calendar/time_test.exs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,4 +90,14 @@ defmodule TimeTest do
9090

9191
assert Time.truncate(~T[01:01:01.123456], :second) == ~T[01:01:01]
9292
end
93+
94+
test "add/3" do
95+
time = ~T[00:00:00.0]
96+
97+
assert Time.add(time, 1, :hour) == ~T[01:00:00.0]
98+
99+
assert_raise ArgumentError, ~r/Expected :hour, :minute, :second/, fn ->
100+
Time.add(time, 1, 0)
101+
end
102+
end
93103
end

0 commit comments

Comments
 (0)