Repository: hugovk/pypistats

Issue:
Improper IndexError handling
`File "/home/..../lib/python3.11/site-packages/pypistats/__init__.py", line 261, in _date_range
    first = data[0]["date"]
            ~~~~^^^
IndexError: list index out of range`

The exception does not handle the data list is empty.
The error will cause the program to stop without proper handling.


Discussion:

Patch:
diff --git a/src/pypistats/__init__.py b/src/pypistats/__init__.py
index 3bd7ac4..db31394 100644
--- a/src/pypistats/__init__.py
+++ b/src/pypistats/__init__.py
@@ -124,6 +124,9 @@ def pypi_stats_api(
 
         _save_cache(cache_file, res)
 
+    if not res.get("data", []):
+        return f"No data found for https://pypi.org/project/{res.get('package', '')}/"
+
     # Actual first and last dates of the fetched data
     first, last = _date_range(res["data"])
 


Test patch:
diff --git a/tests/test_pypistats.py b/tests/test_pypistats.py
index 470ab32..85a205b 100644
--- a/tests/test_pypistats.py
+++ b/tests/test_pypistats.py
@@ -747,3 +747,22 @@ Date range: 2020-05-01 - 2020-05-01
         # Assert
         assert isinstance(output, pandas.DataFrame)
         assert str(output).strip() == expected_output.strip()
+
+    @respx.mock
+    def test_package_not_exist(self) -> None:
+        # Arrange
+        package = "a" * 100
+        mocked_response = f"""{{
+            "data":[],
+            "package":"{package}",
+            "type":"python_major_downloads"
+        }}"""
+        mocked_url = f"https://pypistats.org/api/packages/{package}/python_major"
+        expected_output = f"No data found for https://pypi.org/project/{package}/"
+
+        # Act
+        respx.get(mocked_url).respond(content=mocked_response)
+        output = pypistats.python_major(package)
+
+        # Assert
+        assert output == expected_output