Skip to content

Commit

Permalink
ZennerIoT#14 Validates precision is set for recorded_at
Browse files Browse the repository at this point in the history
  • Loading branch information
neodevelop committed Mar 20, 2021
1 parent 937918a commit 4732039
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
9 changes: 8 additions & 1 deletion lib/tracking/tracking.ex
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ defmodule ExAudit.Tracking do
end

def insert_versions(module, changes, opts) do
now = DateTime.utc_now()
now = DateTime.utc_now() |> with_precision()

custom_fields =
Keyword.get(opts, :ex_audit_custom, [])
Expand Down Expand Up @@ -111,6 +111,13 @@ defmodule ExAudit.Tracking do
insert_versions(module, deleted_structs, opts)
end

defp with_precision(date) do
case precision = Application.get_env(:ex_audit, :precision) do
nil -> date
precision -> DateTime.truncate(date, precision)
end
end

defp tracked_schemas do
Application.get_env(:ex_audit, :tracked_schemas, [])
end
Expand Down
31 changes: 31 additions & 0 deletions test/precision_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
defmodule PrecisionTest do
use ExUnit.Case

import Ecto.Query

alias ExAudit.Test.{Repo, User, Version, Util}

setup_all do
current = Application.get_env(:ex_audit, :precision)

Application.put_env(:ex_audit, :precision, :microsecond)

on_exit(fn -> Application.put_env(:ex_audit, :precision, current) end)
end

test "adjust the precision to `second` in the field `recorded_at`" do
user = Util.create_user("Juan Zuñiga")

changeset = User.changeset(user, %{name: "@neodevelop"})

assert {:ok, user} = Repo.update(changeset)

query =
from(v in Version,
where: v.entity_id == ^user.id,
where: v.entity_schema == ^User
)

assert 2 = Repo.aggregate(query, :count, :id)
end
end

0 comments on commit 4732039

Please sign in to comment.