from unittest import mock import pytest from pytest_mock import MockerFixture from starlette.testclient import TestClient from location.test.faker import FakerTyped @pytest.fixture def ip2location_mock(mocker: MockerFixture) -> mock.MagicMock: return mocker.patch("location.api.routers.location.ip2location", autospec=True) def test_lookup_location( ip2location_mock: mock.MagicMock, test_client: TestClient, fake: FakerTyped ) -> None: record = fake.ip2location_record() ip2location_mock.lookup.return_value = record response = test_client.get(f"/lookup/{record.ip}") assert response.status_code == 200 assert response.json() == { "ip": record.ip, "resolved": True, "country_long": record.country_long, "country_short": record.country_short, "region": record.region, "city": record.city, "latitude": float(record.latitude), "longitude": float(record.longitude), } def test_lookup_location_batch( ip2location_mock: mock.MagicMock, test_client: TestClient, fake: FakerTyped ) -> None: record_1 = fake.ip2location_record() record_2 = fake.ip2location_record() ip2location_mock.lookup_batch.return_value = { record_1.ip: record_1, record_2.ip: record_2, } response = test_client.post( "/lookup/batch", json={"ips": [record_1.ip, record_2.ip]} ) assert response.status_code == 200 assert response.json() == { record_1.ip: { "ip": record_1.ip, "resolved": True, "country_long": record_1.country_long, "country_short": record_1.country_short, "region": record_1.region, "city": record_1.city, "latitude": float(record_1.latitude), "longitude": float(record_1.longitude), }, record_2.ip: { "ip": record_2.ip, "resolved": True, "country_long": record_2.country_long, "country_short": record_2.country_short, "region": record_2.region, "city": record_2.city, "latitude": float(record_2.latitude), "longitude": float(record_2.longitude), }, }