From a650aaab264dabcfd939967668231643556b83aa Mon Sep 17 00:00:00 2001 From: Jose Juan Reyes Date: Mon, 11 Jan 2021 23:37:48 -0600 Subject: [PATCH] #14 Validates precision is set for recorded_at --- lib/tracking/tracking.ex | 9 ++++++++- test/precision_test.exs | 31 +++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 test/precision_test.exs diff --git a/lib/tracking/tracking.ex b/lib/tracking/tracking.ex index 9fd1772..e8db5fe 100644 --- a/lib/tracking/tracking.ex +++ b/lib/tracking/tracking.ex @@ -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, []) @@ -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 diff --git a/test/precision_test.exs b/test/precision_test.exs new file mode 100644 index 0000000..b99cbe0 --- /dev/null +++ b/test/precision_test.exs @@ -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