# tests/test_smhi.py import pytest import requests from datetime import datetime from environment.smhi import SMHI from tools.geometry import Coordinate @pytest.fixture def smhi_client(): session = requests.Session() location = Coordinate(56.2006, 12.5553) return SMHI(location, session) def test_smhi_fire_warning_success(requests_mock, smhi_client): # Mock a successful API response mock_response = { "timeSeries": [{"parameters": [{"name": "fwiindex", "values": [4]}]}] } # Intercept the exact URL your code generates url = smhi_client.fire_warning_api.format(lon=12.5553, lat=56.2006) requests_mock.get(url, json=mock_response, status_code=200) # Run the function result = smhi_client._get_fire_warning() # Assert it succeeded and parsed the data correctly assert result is True assert smhi_client._data["fire_index"]["data"] == 4 assert isinstance(smhi_client._data["fire_index"]["valid_time"], datetime) def test_smhi_fire_warning_http_error(requests_mock, smhi_client, caplog): # Mock SMHI's servers crashing (500 Internal Server Error) url = smhi_client.fire_warning_api.format(lon=12.5553, lat=56.2006) requests_mock.get(url, status_code=500) result = smhi_client._get_fire_warning() # Assert the function returned False instead of crashing the app assert result is False # Assert that our logger caught the HTTP error assert "Network error getting SMHI Fire index" in caplog.text def test_smhi_fire_warning_timeout(requests_mock, smhi_client, caplog): # Mock a network timeout url = smhi_client.fire_warning_api.format(lon=12.5553, lat=56.2006) requests_mock.get(url, exc=requests.exceptions.ConnectTimeout) result = smhi_client._get_fire_warning() assert result is False assert "Network error getting SMHI Fire index" in caplog.text def test_smhi_bad_json_parsing(requests_mock, smhi_client, caplog): # Mock SMHI returning incomplete/bad JSON that is missing the "parameters" key mock_response = {"timeSeries": [{"wrong_key": "data"}]} url = smhi_client.fire_warning_api.format(lon=12.5553, lat=56.2006) requests_mock.get(url, json=mock_response, status_code=200) result = smhi_client._get_fire_warning() assert result is False assert "Parsing error for SMHI Fire index" in caplog.text