summaryrefslogtreecommitdiff
path: root/internal/openmeteo/openmeteo_test.go
blob: 758920c7a61214dea46f5354518142aa6907cbfb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
package openmeteo

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"
)

// serve returns a server replying with a recorded fixture, and records the
// query it was asked for so tests can assert on the request as well as the
// parsing.
func serve(t *testing.T, fixture string, gotQuery *string) *httptest.Server {
	t.Helper()
	body, err := os.ReadFile(filepath.Join("testdata", fixture))
	if err != nil {
		t.Fatal(err)
	}
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if gotQuery != nil {
			*gotQuery = r.URL.RawQuery
		}
		w.Header().Set("Content-Type", "application/json")
		w.Write(body)
	}))
	t.Cleanup(srv.Close)
	return srv
}

// fixtureStart is the first hour in the recorded forecast, so tests can pin the
// clock relative to real recorded data.
func fixtureStart(t *testing.T) time.Time {
	t.Helper()
	body, err := os.ReadFile(filepath.Join("testdata", "forecast.json"))
	if err != nil {
		t.Fatal(err)
	}
	var r struct {
		Hourly struct {
			Time []string `json:"time"`
		} `json:"hourly"`
	}
	if err := json.Unmarshal(body, &r); err != nil {
		t.Fatal(err)
	}
	when, err := time.Parse("2006-01-02T15:04", r.Hourly.Time[0])
	if err != nil {
		t.Fatal(err)
	}
	return when
}

func pinClock(t *testing.T, at time.Time) {
	t.Helper()
	old := now
	now = func() time.Time { return at.UTC() }
	t.Cleanup(func() { now = old })
}

// The hourly array begins at 00:00 local, so slicing from the front reports the
// small hours of this morning rather than the hours ahead -- the bug that made
// the Python version report the wrong pollen peak.
//
// It also pins the timezone contract: the clock is real UTC, and the offset in
// the response converts it to the *location's* local time. That is what makes
// "prognosis -l krakow" start at the right hour when run from another zone.
func TestForecastWindowStartsAtTheCurrentLocalHourNotMidnight(t *testing.T) {
	offset := fixtureOffset(t) // +02:00 for the recorded Polish forecast
	if offset == 0 {
		t.Skip("fixture has no UTC offset; the conversion cannot be exercised")
	}
	// 11:00 UTC is 13:00 in a +02:00 location.
	utcNoon := fixtureStart(t).Add(13*time.Hour - time.Duration(offset)*time.Second)
	pinClock(t, utcNoon)

	srv := serve(t, "forecast.json", nil)
	forecastURL = srv.URL
	d, err := Forecast(50.0617, 19.9373, 6, "metric", []string{"temperature_2m"})
	if err != nil {
		t.Fatal(err)
	}
	if got := d.Rows[0].When.Hour(); got != 13 {
		t.Fatalf("first row is %02d:00, want 13:00 local (clock was %s UTC, offset %+ds)",
			got, utcNoon.Format("15:04"), offset)
	}
	if len(d.Rows) != 6 {
		t.Fatalf("got %d rows, want 6", len(d.Rows))
	}
	// Rows must be consecutive hours from there.
	for i, r := range d.Rows {
		if want := 13 + i; r.When.Hour() != want {
			t.Fatalf("row %d is %02d:00, want %02d:00", i, r.When.Hour(), want)
		}
	}
}

// fixtureOffset is the recorded response's utc_offset_seconds.
func fixtureOffset(t *testing.T) int {
	t.Helper()
	body, err := os.ReadFile(filepath.Join("testdata", "forecast.json"))
	if err != nil {
		t.Fatal(err)
	}
	var r struct {
		Offset int `json:"utc_offset_seconds"`
	}
	if err := json.Unmarshal(body, &r); err != nil {
		t.Fatal(err)
	}
	return r.Offset
}

func TestForecastRequestsOnlySelectedFields(t *testing.T) {
	pinClock(t, fixtureStart(t))
	var query string
	srv := serve(t, "forecast.json", &query)
	forecastURL = srv.URL

	if _, err := Forecast(50, 21, 3, "metric", []string{"temperature_2m", "wind_speed_10m"}); err != nil {
		t.Fatal(err)
	}
	hourly := queryValue(t, query, "hourly")
	for _, want := range []string{"temperature_2m", "wind_speed_10m", "weather_code"} {
		if !strings.Contains(hourly, want) {
			t.Errorf("hourly=%q is missing %q", hourly, want)
		}
	}
	// A field nobody asked for costs response size for nothing.
	for _, unwanted := range []string{"relative_humidity_2m", "pressure_msl", "uv_index"} {
		if strings.Contains(hourly, unwanted) {
			t.Errorf("hourly=%q requests %q, which was not selected", hourly, unwanted)
		}
	}
}

func TestForecastUnitsArePassedToTheProvider(t *testing.T) {
	pinClock(t, fixtureStart(t))
	cases := map[string]map[string]string{
		"metric":   {"temperature_unit": "", "wind_speed_unit": ""},
		"imperial": {"temperature_unit": "fahrenheit", "wind_speed_unit": "mph"},
		"si":       {"wind_speed_unit": "ms"},
	}
	for units, want := range cases {
		t.Run(units, func(t *testing.T) {
			var query string
			srv := serve(t, "forecast.json", &query)
			forecastURL = srv.URL
			if _, err := Forecast(50, 21, 3, units, []string{"temperature_2m"}); err != nil {
				t.Fatal(err)
			}
			for k, v := range want {
				if got := queryValue(t, query, k); got != v {
					t.Errorf("%s=%q, want %q", k, got, v)
				}
			}
		})
	}
}

func TestForecastRequestsEnoughDaysAndRespectsTheCap(t *testing.T) {
	pinClock(t, fixtureStart(t))
	for hours, wantDays := range map[int]string{12: "2", 24: "3", 48: "4", 400: "16"} {
		var query string
		srv := serve(t, "forecast.json", &query)
		forecastURL = srv.URL
		if _, err := Forecast(50, 21, hours, "metric", []string{"temperature_2m"}); err != nil {
			t.Fatal(err)
		}
		if got := queryValue(t, query, "forecast_days"); got != wantDays {
			t.Errorf("%d hours asked for forecast_days=%s, want %s", hours, got, wantDays)
		}
	}
}

func TestForecastParsesDailyAndSun(t *testing.T) {
	pinClock(t, fixtureStart(t))
	srv := serve(t, "forecast.json", nil)
	forecastURL = srv.URL
	d, err := Forecast(50, 21, 3, "metric", []string{"temperature_2m"})
	if err != nil {
		t.Fatal(err)
	}
	if len(d.Sun) == 0 {
		t.Error("no sunrise/sunset parsed")
	}
	for _, day := range d.Sun {
		if len(day[0]) != 5 || len(day[1]) != 5 {
			t.Errorf("sun times must be HH:MM, got %v", day)
		}
	}
	for _, f := range DailyFields {
		if _, ok := d.Daily[f]; !ok {
			t.Errorf("daily field %q missing", f)
		}
	}
}

func TestForecastErrors(t *testing.T) {
	pinClock(t, fixtureStart(t))
	t.Run("http error", func(t *testing.T) {
		srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			http.Error(w, "nope", http.StatusInternalServerError)
		}))
		defer srv.Close()
		forecastURL = srv.URL
		if _, err := Forecast(50, 21, 3, "metric", nil); err == nil {
			t.Fatal("expected an error on HTTP 500")
		}
	})
	t.Run("bad json", func(t *testing.T) {
		srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.Write([]byte("{not json"))
		}))
		defer srv.Close()
		forecastURL = srv.URL
		if _, err := Forecast(50, 21, 3, "metric", nil); err == nil {
			t.Fatal("expected an error on malformed JSON")
		}
	})
}

// Pollen peaks around midday, so a 3-hour request must still look 12 hours
// ahead or it understates the day for someone with an allergy.
func TestPollenAlwaysLooksAtLeastTwelveHoursAhead(t *testing.T) {
	start := fixtureStart(t)
	pinClock(t, start.Add(6*time.Hour))
	srv := serve(t, "pollen.json", nil)
	airURL = srv.URL

	short, err := Pollen(50, 21, 3, []string{"grass"})
	if err != nil {
		t.Fatal(err)
	}
	long, err := Pollen(50, 21, 12, []string{"grass"})
	if err != nil {
		t.Fatal(err)
	}
	if short["grass"] != long["grass"] {
		t.Fatalf("3-hour window gave %v but 12-hour gave %v; the short window must "+
			"still cover 12 hours", short["grass"], long["grass"])
	}
}

// Outside Europe the API returns nulls. Treating those as 0.0 reports a
// confident "grass 0.0 none" where the truth is "no data".
func TestPollenNullsAreAbsentNotZero(t *testing.T) {
	pinClock(t, fixtureStart(t))
	srv := serve(t, "pollen_nulls.json", nil)
	airURL = srv.URL
	peaks, err := Pollen(-54.8, -68.3, 12, []string{"grass"})
	if err != nil {
		t.Fatal(err)
	}
	if v, ok := peaks["grass"]; ok {
		t.Fatalf("grass reported as %v, but the fixture has no readings there", v)
	}
}

func TestPollenCapsDaysAtTheAirQualityLimit(t *testing.T) {
	pinClock(t, fixtureStart(t))
	var query string
	srv := serve(t, "pollen.json", &query)
	airURL = srv.URL
	if _, err := Pollen(50, 21, 15*24, []string{"grass"}); err != nil {
		t.Fatal(err)
	}
	if got := queryValue(t, query, "forecast_days"); got != "7" {
		t.Fatalf("forecast_days=%s, want 7 (the air-quality API rejects more)", got)
	}
}

func TestPollenWithNoSpeciesMakesNoRequest(t *testing.T) {
	called := false
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		called = true
	}))
	defer srv.Close()
	airURL = srv.URL
	peaks, err := Pollen(50, 21, 12, nil)
	if err != nil || len(peaks) != 0 {
		t.Fatalf("got %v, %v", peaks, err)
	}
	if called {
		t.Error("requested pollen despite no species being selected")
	}
}

func TestGeocodeReportsAlternatives(t *testing.T) {
	srv := serve(t, "geocode_ambiguous.json", nil)
	geoURL = srv.URL
	cands, err := Geocode("krakow")
	if err != nil {
		t.Fatal(err)
	}
	if len(cands) < 2 {
		t.Fatalf("got %d candidates, want several: the fixture is ambiguous", len(cands))
	}
	g := cands[0].Geo
	if g.Country == "" || g.Label == "" {
		t.Errorf("incomplete geo: %+v", g)
	}
	if !strings.Contains(g.Label, g.Country) {
		t.Errorf("label %q should carry the country %q", g.Label, g.Country)
	}
}

// Selecting a place other than the first one is impossible unless its
// coordinates survive the call, which is exactly what the old API discarded.
func TestGeocodeKeepsCoordinatesForEveryCandidate(t *testing.T) {
	srv := serve(t, "geocode_ambiguous.json", nil)
	geoURL = srv.URL
	cands, err := Geocode("krakow")
	if err != nil {
		t.Fatal(err)
	}
	for i, c := range cands {
		if c.Geo.Lat == 0 || c.Geo.Lon == 0 {
			t.Errorf("candidate %d (%s) has no coordinates, so it cannot be picked", i+1, c.Geo.Label)
		}
		if c.Admin1 == "" {
			t.Errorf("candidate %d (%s) has no region, so the list cannot tell duplicates apart", i+1, c.Geo.Label)
		}
	}
}

func TestGeocodeNoResultsIsAnError(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`{"generationtime_ms":0.1}`))
	}))
	defer srv.Close()
	geoURL = srv.URL
	if _, err := Geocode("zzzznowhere"); err == nil {
		t.Fatal("expected an error when nothing matched")
	}
}

func TestWindowStartFallsBackToZeroWhenEverythingIsPast(t *testing.T) {
	pinClock(t, time.Date(2030, 1, 1, 0, 0, 0, 0, time.UTC))
	if got := WindowStart([]string{"2026-08-10T00:00", "2026-08-10T01:00"}, 0); got != 0 {
		t.Fatalf("got %d, want 0", got)
	}
}

func queryValue(t *testing.T, rawQuery, key string) string {
	t.Helper()
	for _, pair := range strings.Split(rawQuery, "&") {
		k, v, _ := strings.Cut(pair, "=")
		if k == key {
			unescaped, err := urlUnescape(v)
			if err != nil {
				t.Fatal(err)
			}
			return unescaped
		}
	}
	return ""
}

func urlUnescape(s string) (string, error) { return url.QueryUnescape(s) }