From c8072839448dcedc31a2353242bbf5687842f76b Mon Sep 17 00:00:00 2001 From: Oliver Sherouse Date: Thu, 7 Mar 2024 10:21:16 -0500 Subject: [PATCH] fix: secretly be a bit kinder with dates param Allow sequences of length 2 for dates even though it should *really* be a tuple. Contributes to #71. Signed-off-by: Oliver Sherouse --- tests/test_dates.py | 18 ++++++++++++++++++ wbdata/dates.py | 9 +++++++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/tests/test_dates.py b/tests/test_dates.py index 086b56b..1b83f8a 100644 --- a/tests/test_dates.py +++ b/tests/test_dates.py @@ -122,7 +122,25 @@ def test_parse_and_format_date(): "2020Q1:2021Q4", id="two strings", ), + pytest.param( + ["2020M01", "2021M12"], + "Q", + "2020Q1:2021Q4", + id="two strings in a list", + ), ], ) def test_format_dates(dates_, freq, expected): assert dates.format_dates(dates_, freq) == expected + + +@pytest.mark.parametrize( + ["dates_"], + ( + (1234,), + (["Why", "Hello", "There"],), + ), +) +def test_bad_dates(dates_): + with pytest.raises(ValueError, match="dates argument"): + dates.format_dates(dates_, "Y") diff --git a/wbdata/dates.py b/wbdata/dates.py index 660a27e..b95cb04 100644 --- a/wbdata/dates.py +++ b/wbdata/dates.py @@ -114,9 +114,14 @@ def format_dates(dates: Dates, freq: str) -> str: A string representing a date or date range according to the specified frequency in the form the World Bank API expects. """ - if isinstance(dates, tuple): + if isinstance(dates, (str, dt.datetime)): + return _parse_and_format_date(dates, freq) + if isinstance(dates, Sequence) and len(dates) == 2: return ( f"{_parse_and_format_date(dates[0], freq)}" f":{_parse_and_format_date(dates[1], freq)}" ) - return _parse_and_format_date(dates, freq) + raise ValueError( + "dates argument must be a string, datetime object, or 2-tuple of" + " strings or datetime objects." + )