package main import ( "os" "path/filepath" "testing" "time" ) func TestCacheLocationRoundTrip(t *testing.T) { tmp := t.TempDir() t.Setenv("WEATHER_CACHE_DIR", tmp) cache := NewCache(tmp) loc := Location{Lat: 1.23, Lon: 4.56, City: "Testville", State: "TS"} if err := cache.SaveLocation("Testville", loc); err != nil { t.Fatalf("save location failed: %v", err) } loaded, ok, err := cache.LoadLocation() if err != nil { t.Fatalf("load location failed: %v", err) } if !ok { t.Fatalf("expected cached location") } if loaded.City != loc.City || loaded.Lat != loc.Lat || loaded.Lon != loc.Lon { t.Fatalf("loaded location mismatch: %+v", loaded) } } func TestCacheForecastExpiry(t *testing.T) { tmp := t.TempDir() cache := NewCache(tmp) loc := Location{Lat: 1.23, Lon: 4.56} period := ForecastPeriod{Temp: 70, Unit: "F"} if err := cache.SaveForecast(loc, "F", period); err != nil { t.Fatalf("save forecast failed: %v", err) } path := filepath.Join(tmp, forecastCacheFile) var payload ForecastCache if err := readJSON(path, &payload); err != nil { t.Fatalf("read forecast cache failed: %v", err) } payload.FetchedAt = time.Now().Add(-2 * time.Hour) if err := writeJSON(path, payload); err != nil { t.Fatalf("write forecast cache failed: %v", err) } _, ok, err := cache.LoadForecast(loc, "F", 10*time.Minute) if err != nil { t.Fatalf("load forecast failed: %v", err) } if ok { t.Fatalf("expected expired forecast to be ignored") } } func TestCacheClear(t *testing.T) { tmp := t.TempDir() cache := NewCache(tmp) loc := Location{Lat: 1.23, Lon: 4.56} period := ForecastPeriod{Temp: 70, Unit: "F"} if err := cache.SaveLocation("Testville", loc); err != nil { t.Fatalf("save location failed: %v", err) } if err := cache.SaveForecast(loc, "F", period); err != nil { t.Fatalf("save forecast failed: %v", err) } if err := cache.Clear(); err != nil { t.Fatalf("clear cache failed: %v", err) } if _, err := os.Stat(filepath.Join(tmp, locationCacheFile)); !os.IsNotExist(err) { t.Fatalf("expected location cache removed, got %v", err) } if _, err := os.Stat(filepath.Join(tmp, forecastCacheFile)); !os.IsNotExist(err) { t.Fatalf("expected forecast cache removed, got %v", err) } }