Tzdata initialization in phoenix (in unit testing)

I have just started with elixir and phoenix recently with my pet project.
In code I am trying to use tzdata.

I have set the initialization of tzdata database in the config/test.exs

import Config

config :elixir, :time_zone_database, Tzdata.TimeZoneDatabase

# .... other stuff

but it seems it is not properly initialized since i see in the test run

Running tests...
{:error, :utc_only_time_zone_database}

and my [doc] test failed:

 1) doctest Scraper.WiredDayParser.parse_date!/1 (1) (Scraper.WiredDayParserTest)
     ** (FunctionClauseError) no function clause matching in DateTime.from_naive/3

     The following arguments were given to DateTime.from_naive/3:
         # 1
         {:ok, ~N[2023-04-07 23:21:20]}
         # 2
         # 3
     Attempted function clauses (showing 3 out of 3):
         def from_naive(naive_datetime, "Etc/UTC", _)
         def from_naive(%{calendar: Calendar.ISO} = naive_datetime, time_zone, time_zone_database)
         def from_naive(%{calendar: calendar} = naive_datetime, time_zone, time_zone_database) when calendar != Calendar.ISO
       (elixir 1.14.3) lib/calendar/datetime.ex:496: DateTime.from_naive/3
       (elixir 1.14.3) lib/calendar/datetime.ex:618: DateTime.from_naive!/3
       (for doctest at) lib/scraper/wired_dates_parser.ex:8: (test)

Appreciate if someone could give me a clue about what might be missed.

Two separate issues:

  • files like config/test.exs are loaded before the whole system is up; IIRC the TZ database isn’t available from them. They aren’t generally good places to “try out” code.

  • your test failure appears to be caused by passing an {:ok, %NaiveDateTime} tuple as the first argument to DateTime.from_naive!, when it expects only the NaiveDateTime structure.

1 Like

ha, that was a dumb mistake.

Thank you for helping me with that @al2o3cr. Very much appreciated.