diff --git a/test/towerops/workers/weather_sync_worker_test.exs b/test/towerops/workers/weather_sync_worker_test.exs index 5ff1442a..6e8452b7 100644 --- a/test/towerops/workers/weather_sync_worker_test.exs +++ b/test/towerops/workers/weather_sync_worker_test.exs @@ -1,6 +1,7 @@ defmodule Towerops.Workers.WeatherSyncWorkerTest do use Towerops.DataCase, async: false + alias Towerops.Weather.Client alias Towerops.Workers.WeatherSyncWorker setup do @@ -37,5 +38,55 @@ defmodule Towerops.Workers.WeatherSyncWorkerTest do # through cleanup_old_observations and schedule_next. assert :ok = WeatherSyncWorker.perform(%Oban.Job{}) end + + test "logs and fetches weather for a site with coordinates" do + Application.put_env(:towerops, :openweathermap_api_key, "test-key") + + # Stub OpenWeatherMap so fetch_and_store succeeds. + Req.Test.stub(Client, fn conn -> + Req.Test.json(conn, %{ + "main" => %{"temp" => 290.0, "humidity" => 60, "pressure" => 1013}, + "wind" => %{"speed" => 3.5}, + "weather" => [%{"main" => "Clear", "description" => "clear sky"}] + }) + end) + + user = Towerops.AccountsFixtures.user_fixture() + organization = Towerops.OrganizationsFixtures.organization_fixture(user.id) + + {:ok, _site} = + Towerops.Sites.create_site(%{ + name: "Sunny Site", + organization_id: organization.id, + latitude: 30.27, + longitude: -97.74 + }) + + # The worker spawns the sync logic synchronously inside :ok branch. + # Note: the per-site rate-limit Process.sleep only fires for idx > 1, so + # with a single site we don't pay that 1.1s tax in tests. + assert :ok = WeatherSyncWorker.perform(%Oban.Job{}) + end + + test "still returns :ok when fetch_and_store fails for the site" do + Application.put_env(:towerops, :openweathermap_api_key, "test-key") + + Req.Test.stub(Client, fn conn -> + conn |> Plug.Conn.put_status(401) |> Req.Test.json(%{"error" => "invalid"}) + end) + + user = Towerops.AccountsFixtures.user_fixture() + organization = Towerops.OrganizationsFixtures.organization_fixture(user.id) + + {:ok, _site} = + Towerops.Sites.create_site(%{ + name: "Failing Site", + organization_id: organization.id, + latitude: 30.27, + longitude: -97.74 + }) + + assert :ok = WeatherSyncWorker.perform(%Oban.Job{}) + end end end