Tzdata initialization in phoenix (in unit testing)

Hello,
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

IO.puts("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")
IO.inspect(DateTime.now("Europe/Stockholm"))
# .... other stuff

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

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

and my [doc] test failed:

 1) doctest Scraper.WiredDayParser.parse_date!/1 (1) (Scraper.WiredDayParserTest)
     test/scrapper/wired_day_parser_test.exs:4
     ** (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
         "Europe/Stockholm"
     
         # 3
         Tzdata.TimeZoneDatabase
     
     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
     
     stacktrace:
       (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.