Add basic unit tests for IP geolocation service

- Test invalid IP validation returns None without API call
- Test caching behavior for repeated calls
- Test error handling for API failures
parent ddddc6d1
import pytest
from unittest.mock import patch, Mock
from geolocation import get_ip_country, _ip_country_cache
@pytest.mark.asyncio
async def test_invalid_ip_validation():
"""Test that invalid IPs return None without API call"""
_ip_country_cache.clear()
with patch('httpx.AsyncClient.get') as mock_get:
result = await get_ip_country("invalid")
assert result is None
assert _ip_country_cache["invalid"] is None
mock_get.assert_not_called()
@pytest.mark.asyncio
async def test_caching():
"""Test that results are cached and repeated calls return cached results"""
_ip_country_cache.clear()
with patch('httpx.AsyncClient.get') as mock_get:
mock_response = Mock()
mock_response.status_code = 200
mock_response.text = "US"
mock_get.return_value = mock_response
# First call
result1 = await get_ip_country("1.1.1.1")
assert result1 == "US"
assert _ip_country_cache["1.1.1.1"] == "US"
mock_get.assert_called_once()
# Second call should use cache
result2 = await get_ip_country("1.1.1.1")
assert result2 == "US"
mock_get.assert_called_once() # Still only one call
@pytest.mark.asyncio
async def test_error_handling():
"""Test error handling for valid IPs when API fails"""
_ip_country_cache.clear()
with patch('httpx.AsyncClient.get') as mock_get:
mock_get.side_effect = Exception("API fail")
result = await get_ip_country("1.1.1.1")
assert result is None
assert _ip_country_cache["1.1.1.1"] is None
mock_get.assert_called_once()
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment