diff --git a/internal/renderer/v2/block_rain.go b/internal/renderer/v2/block_rain.go index a538b7da..cc1c624b 100644 --- a/internal/renderer/v2/block_rain.go +++ b/internal/renderer/v2/block_rain.go @@ -5,13 +5,15 @@ import ( "fmt" "math" "strings" + + "github.com/chubin/wttr.in/internal/options" ) // sparkBars as []rune — correct Unicode handling var sparkBars = []rune(" _▁▂▃▄▅▇█") // drawRainSpark — now matches Python v2 label position (TOP of the sparkline) -func drawRainSpark(data, chanceData []float64, height, width int) string { +func drawRainSpark(data, chanceData []float64, height, width int, opts *options.Options) string { if len(data) == 0 || width == 0 { return strings.Repeat(" ", width) + "\n" } @@ -27,9 +29,13 @@ func drawRainSpark(data, chanceData []float64, height, width int) string { for i := 0; i < height; i++ { for j := 0; j < width; j++ { rowFromBottom := height - i - 1 - character := box(rowFromBottom, data[j], maxValue, height) + var val float64 + if j < len(data) { + val = data[j] + } + character := box(rowFromBottom, val, maxValue, height) - if data[j] != 0 && j < len(chanceData) && chanceData[j] > 0 { + if val != 0 && j < len(chanceData) && chanceData[j] > 0 { chanceOfRain := math.Min(1.0, chanceData[j]/100.0*2.0) colorIndex := int(5 * chanceOfRain) colorCode := 16 + colorIndex @@ -51,7 +57,17 @@ func drawRainSpark(data, chanceData []float64, height, width int) string { } } - label := fmt.Sprintf("%3.2fmm|%d%%", maxValue, int(chanceData[maxCol])) + unit := "mm" + if opts != nil && (opts.UseImperial || opts.UseUscs) { + unit = "in" + } + + chance := 0 + if maxCol < len(chanceData) { + chance = int(chanceData[maxCol]) + } + + label := fmt.Sprintf("%3.2f%s|%d%%", maxValue, unit, chance) coloredLabel := fmt.Sprintf("\033[38;5;33m%s\033[0m", label) // Python-style alignment diff --git a/internal/renderer/v2/block_rain_test.go b/internal/renderer/v2/block_rain_test.go new file mode 100644 index 00000000..367bed07 --- /dev/null +++ b/internal/renderer/v2/block_rain_test.go @@ -0,0 +1,136 @@ +package v2 + +import ( + "strings" + "testing" + + "github.com/chubin/wttr.in/internal/options" +) + +func TestDrawRainSparkMetricUnits(t *testing.T) { + testCases := []struct { + name string + opts *options.Options + expectedUnit string + }{ + { + name: "nil options defaults to metric mm", + opts: nil, + expectedUnit: "mm|", + }, + { + name: "empty options defaults to metric mm", + opts: &options.Options{}, + expectedUnit: "mm|", + }, + { + name: "explicit use_metric true", + opts: &options.Options{UseMetric: true}, + expectedUnit: "mm|", + }, + { + name: "use_metric with use_ms_for_wind", + opts: &options.Options{UseMetric: true, UseMsForWind: true}, + expectedUnit: "mm|", + }, + } + + data := []float64{0.0, 2.5, 12.7, 5.0, 0.0} + chance := []float64{0, 20, 80, 40, 0} + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + output := drawRainSpark(data, chance, 5, 20, tc.opts) + if !strings.Contains(output, "12.70mm|80%") { + t.Fatalf("expected output to contain %q, got:\n%s", "12.70mm|80%", output) + } + if !strings.Contains(output, tc.expectedUnit) { + t.Fatalf("expected output to contain unit %q, got:\n%s", tc.expectedUnit, output) + } + }) + } +} + +func TestDrawRainSparkImperialUnits(t *testing.T) { + testCases := []struct { + name string + opts *options.Options + expectedUnit string + }{ + { + name: "use_imperial true", + opts: &options.Options{UseImperial: true}, + expectedUnit: "in|", + }, + { + name: "use_uscs true", + opts: &options.Options{UseUscs: true}, + expectedUnit: "in|", + }, + { + name: "both use_imperial and use_uscs true", + opts: &options.Options{UseImperial: true, UseUscs: true}, + expectedUnit: "in|", + }, + } + + data := []float64{0.0, 0.1, 0.5, 0.2, 0.0} + chance := []float64{0, 20, 80, 40, 0} + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + output := drawRainSpark(data, chance, 5, 20, tc.opts) + if !strings.Contains(output, "0.50in|80%") { + t.Fatalf("expected output to contain %q, got:\n%s", "0.50in|80%", output) + } + if !strings.Contains(output, tc.expectedUnit) { + t.Fatalf("expected output to contain unit %q, got:\n%s", tc.expectedUnit, output) + } + }) + } +} + +func TestDrawRainSparkEdgeCases(t *testing.T) { + t.Run("empty data slice", func(t *testing.T) { + out := drawRainSpark([]float64{}, []float64{}, 5, 20, nil) + expected := strings.Repeat(" ", 20) + "\n" + if out != expected { + t.Fatalf("expected %q, got %q", expected, out) + } + }) + + t.Run("zero width", func(t *testing.T) { + out := drawRainSpark([]float64{1.0, 2.0}, []float64{10, 20}, 5, 0, nil) + if out != "\n" { + t.Fatalf("expected %q, got %q", "\n", out) + } + }) + + t.Run("all zero data values", func(t *testing.T) { + out := drawRainSpark([]float64{0.0, 0.0, 0.0}, []float64{10, 20, 30}, 5, 15, nil) + expected := strings.Repeat(" ", 15) + "\n" + if out != expected { + t.Fatalf("expected %q, got %q", expected, out) + } + }) + + t.Run("chanceData shorter than maxCol", func(t *testing.T) { + // maxValue at index 3, chanceData only has 2 elements + data := []float64{0.0, 1.0, 2.0, 8.5} + chance := []float64{10, 20} + out := drawRainSpark(data, chance, 5, 20, &options.Options{UseMetric: true}) + if !strings.Contains(out, "8.50mm|0%") { + t.Fatalf("expected %q with fallback 0%% chance, got:\n%s", "8.50mm|0%", out) + } + }) + + t.Run("label alignment near right edge", func(t *testing.T) { + // maxValue at the very end of line + data := []float64{0.0, 0.0, 0.0, 0.0, 0.0, 5.0} + chance := []float64{0, 0, 0, 0, 0, 90} + out := drawRainSpark(data, chance, 3, 12, &options.Options{UseMetric: true}) + if !strings.Contains(out, "5.00mm|90%") { + t.Fatalf("expected right aligned label in output, got:\n%s", out) + } + }) +} diff --git a/internal/renderer/v2/renderer.go b/internal/renderer/v2/renderer.go index 09cdd4c5..f5f9da5d 100644 --- a/internal/renderer/v2/renderer.go +++ b/internal/renderer/v2/renderer.go @@ -40,8 +40,11 @@ func (r *V2Renderer) Render(q domain.Query, localizer localization.Localizer) (d } opts := q.Options + if opts == nil { + opts = &options.Options{} + } loc := q.Location - l10n := localization.New(localizer, q.Options) + l10n := localization.New(localizer, opts) var buf bytes.Buffer @@ -65,11 +68,17 @@ func (r *V2Renderer) Render(q domain.Query, localizer localization.Localizer) (d buf.WriteString("\n") // Rain sparkline - precipValues := extractAllHourlyFloat(weather, func(h domain.Hourly) string { return h.PrecipMM }) + isImperial := opts.UseImperial || opts.UseUscs + precipValues := extractAllHourlyFloat(weather, func(h domain.Hourly) string { + if isImperial { + return h.PrecipInches + } + return h.PrecipMM + }) chanceValues := extractAllHourlyFloat(weather, func(h domain.Hourly) string { return h.ChanceOfRain }) precipInterp := interpolate(precipValues, 72) chanceInterp := interpolate(chanceValues, 72) - buf.WriteString(drawRainSpark(precipInterp, chanceInterp, 5, 72)) + buf.WriteString(drawRainSpark(precipInterp, chanceInterp, 5, 72, opts)) buf.WriteString("\n") // Weather emojis diff --git a/internal/renderer/v2/renderer_test.go b/internal/renderer/v2/renderer_test.go new file mode 100644 index 00000000..d3d30ac9 --- /dev/null +++ b/internal/renderer/v2/renderer_test.go @@ -0,0 +1,197 @@ +package v2 + +import ( + "fmt" + "strings" + "testing" + + "github.com/chubin/wttr.in/internal/domain" + "github.com/chubin/wttr.in/internal/options" +) + +type mockLocalizer struct{} + +func (m *mockLocalizer) Text(lang, key string) string { + return key +} + +func (m *mockLocalizer) Condition(lang string, code int) string { + return "" +} + +func (m *mockLocalizer) ConditionByName(lang, englishName string) string { + return englishName +} + +func (m *mockLocalizer) File(lang, name string) (string, error) { + return "", nil +} + +func buildTestWeatherJSON(precipMM, precipInches string) domain.WeatherRaw { + hourlyEntries := make([]string, 0, 8) + for i := 0; i < 8; i++ { + hourlyEntries = append(hourlyEntries, fmt.Sprintf(`{ + "time": "%d", + "tempC": "15", + "tempF": "59", + "precipMM": "%s", + "precipInches": "%s", + "chanceofrain": "65", + "weatherCode": "116", + "windspeedKmph": "12", + "windspeedMiles": "7", + "winddirDegree": "180" + }`, i*300, precipMM, precipInches)) + } + + dayJSON := fmt.Sprintf(`{ + "date": "2026-10-05", + "hourly": [%s], + "astronomy": [{ + "sunrise": "06:00 AM", + "sunset": "06:00 PM", + "moonrise": "08:00 PM", + "moonset": "07:00 AM" + }] + }`, strings.Join(hourlyEntries, ",")) + + raw := fmt.Sprintf(`{ + "current_condition": [{ + "temp_C": "15", + "temp_F": "59", + "precipMM": "%s", + "precipInches": "%s", + "weatherCode": "116", + "weatherDesc": [{"value": "Partly cloudy"}], + "humidity": "60", + "pressure": "1013", + "windspeedKmph": "12", + "windspeedMiles": "7" + }], + "weather": [%s, %s, %s] + }`, precipMM, precipInches, dayJSON, dayJSON, dayJSON) + + return domain.WeatherRaw(raw) +} + +func TestV2Renderer_RenderPrecipitationMetric(t *testing.T) { + testCases := []struct { + name string + opts *options.Options + }{ + { + name: "default options without flags", + opts: &options.Options{Location: "Berlin", Lang: "en"}, + }, + { + name: "explicit metric option", + opts: &options.Options{Location: "Berlin", Lang: "en", UseMetric: true}, + }, + { + name: "metric option with ms wind", + opts: &options.Options{Location: "Berlin", Lang: "en", UseMetric: true, UseMsForWind: true}, + }, + } + + weatherRaw := buildTestWeatherJSON("12.7", "0.50") + renderer := NewV2Renderer() + localizer := &mockLocalizer{} + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + query := domain.Query{ + Location: &domain.Location{Name: "Berlin", TimeZone: "UTC"}, + Options: tc.opts, + Weather: &weatherRaw, + } + + out, err := renderer.Render(query, localizer) + if err != nil { + t.Fatalf("unexpected render error: %v", err) + } + + content := string(out.Content) + if !strings.Contains(content, "12.70mm|65%") { + t.Fatalf("expected output to contain metric precip label %q, but got:\n%s", "12.70mm|65%", content) + } + if strings.Contains(content, "0.50in|") { + t.Fatalf("metric output should not contain imperial precip label '0.50in|'") + } + }) + } +} + +func TestV2Renderer_RenderPrecipitationImperial(t *testing.T) { + testCases := []struct { + name string + opts *options.Options + }{ + { + name: "use_imperial flag", + opts: &options.Options{Location: "Pittsburgh", Lang: "en", UseImperial: true}, + }, + { + name: "use_uscs flag", + opts: &options.Options{Location: "Pittsburgh", Lang: "en", UseUscs: true}, + }, + { + name: "both imperial and uscs flags", + opts: &options.Options{Location: "Pittsburgh", Lang: "en", UseImperial: true, UseUscs: true}, + }, + } + + weatherRaw := buildTestWeatherJSON("12.7", "0.50") + renderer := NewV2Renderer() + localizer := &mockLocalizer{} + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + query := domain.Query{ + Location: &domain.Location{Name: "Pittsburgh", TimeZone: "America/New_York"}, + Options: tc.opts, + Weather: &weatherRaw, + } + + out, err := renderer.Render(query, localizer) + if err != nil { + t.Fatalf("unexpected render error: %v", err) + } + + content := string(out.Content) + if !strings.Contains(content, "0.50in|65%") { + t.Fatalf("expected output to contain imperial precip label %q, but got:\n%s", "0.50in|65%", content) + } + if strings.Contains(content, "12.70mm|") { + t.Fatalf("imperial output should not contain metric precip label '12.70mm|'") + } + }) + } +} + +func TestV2Renderer_RenderErrors(t *testing.T) { + renderer := NewV2Renderer() + localizer := &mockLocalizer{} + + t.Run("nil weather", func(t *testing.T) { + _, err := renderer.Render(domain.Query{}, localizer) + if err == nil { + t.Fatal("expected error for nil weather") + } + }) + + t.Run("invalid weather JSON", func(t *testing.T) { + invalidJSON := domain.WeatherRaw("{invalid") + _, err := renderer.Render(domain.Query{Weather: &invalidJSON}, localizer) + if err == nil { + t.Fatal("expected error for malformed weather JSON") + } + }) + + t.Run("empty forecast days", func(t *testing.T) { + emptyDays := domain.WeatherRaw(`{"weather": []}`) + _, err := renderer.Render(domain.Query{Weather: &emptyDays}, localizer) + if err == nil { + t.Fatal("expected error for empty forecast days") + } + }) +} diff --git a/test/test_v2_precipitation.py b/test/test_v2_precipitation.py new file mode 100644 index 00000000..fb7bfb65 --- /dev/null +++ b/test/test_v2_precipitation.py @@ -0,0 +1,25 @@ +"""Automated unit test verifying format v2 precipitation output formatting.""" +import subprocess +import unittest + + +class TestV2Precipitation(unittest.TestCase): + def test_v2_renderer_precipitation_metric_and_imperial(self): + result = subprocess.run( + ["go", "test", "-v", "./internal/renderer/v2/..."], + capture_output=True, + text=True, + ) + self.assertEqual( + result.returncode, + 0, + f"go test failed:\nstdout:\n{result.stdout}\nstderr:\n{result.stderr}", + ) + self.assertIn("PASS: TestDrawRainSparkMetricUnits", result.stdout) + self.assertIn("PASS: TestDrawRainSparkImperialUnits", result.stdout) + self.assertIn("PASS: TestV2Renderer_RenderPrecipitationMetric", result.stdout) + self.assertIn("PASS: TestV2Renderer_RenderPrecipitationImperial", result.stdout) + + +if __name__ == "__main__": + unittest.main()