Skip to content

Commit

Permalink
Pass in locales as a normal parameter
Browse files Browse the repository at this point in the history
  • Loading branch information
oschwald committed Jan 16, 2025
1 parent 00482e0 commit 165d40a
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 27 deletions.
12 changes: 7 additions & 5 deletions minfraud/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"""

# pylint:disable=too-many-lines,too-many-instance-attributes,too-many-locals
from typing import Dict, List, Optional
from typing import Dict, List, Optional, Sequence

from geoip2.mixins import SimpleEquality
import geoip2.models
Expand Down Expand Up @@ -202,16 +202,16 @@ class IPAddress(geoip2.models.Insights):

def __init__(
self,
locales: Sequence[str],
*,
locales: Optional[List[str]] = None,
country: Optional[Dict] = None,
location: Optional[Dict] = None,
risk: Optional[float] = None,
risk_reasons: Optional[List[Dict]] = None,
**kwargs,
) -> None:

super().__init__(kwargs, locales=locales)
super().__init__(kwargs, locales=list(locales))
self.country = GeoIP2Country(locales, **(country or {}))
self.location = GeoIP2Location(**(location or {}))
self.risk = risk
Expand Down Expand Up @@ -1356,6 +1356,7 @@ class Factors(SimpleEquality):

def __init__(
self,
locales: Sequence[str],
*,
billing_address: Optional[Dict] = None,
billing_phone: Optional[Dict] = None,
Expand Down Expand Up @@ -1384,7 +1385,7 @@ def __init__(
self.device = Device(**(device or {}))
self.email = Email(**(email or {}))
self.id = id
self.ip_address = IPAddress(**(ip_address or {}))
self.ip_address = IPAddress(locales, **(ip_address or {}))
self.queries_remaining = queries_remaining
self.risk_score = risk_score
self.shipping_address = ShippingAddress(**(shipping_address or {}))
Expand Down Expand Up @@ -1521,6 +1522,7 @@ class Insights(SimpleEquality):

def __init__(
self,
locales: Sequence[str],
*,
billing_address: Optional[Dict] = None,
billing_phone: Optional[Dict] = None,
Expand All @@ -1547,7 +1549,7 @@ def __init__(
self.email = Email(**(email or {}))
self.funds_remaining = funds_remaining
self.id = id
self.ip_address = IPAddress(**(ip_address or {}))
self.ip_address = IPAddress(locales, **(ip_address or {}))
self.queries_remaining = queries_remaining
self.risk_score = risk_score
self.shipping_address = ShippingAddress(**(shipping_address or {}))
Expand Down
27 changes: 13 additions & 14 deletions minfraud/webservice.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
"""

import json
from typing import Any, cast, Dict, Optional, Tuple, Type, Union
from functools import partial
from typing import Any, Callable, cast, Dict, Optional, Sequence, Union

import aiohttp
import aiohttp.http
Expand Down Expand Up @@ -39,7 +40,7 @@
class BaseClient:
_account_id: str
_license_key: str
_locales: Tuple[str, ...]
_locales: Sequence[str]
_timeout: float

_score_uri: str
Expand All @@ -52,7 +53,7 @@ def __init__(
account_id: int,
license_key: str,
host: str = "minfraud.maxmind.com",
locales: Tuple[str, ...] = ("en",),
locales: Sequence[str] = ("en",),
timeout: float = 60,
) -> None:
self._locales = locales
Expand All @@ -69,7 +70,7 @@ def _handle_success(
self,
raw_body: str,
uri: str,
model_class: Union[Type[Factors], Type[Score], Type[Insights]],
model_class: Callable,
) -> Union[Score, Factors, Insights]:
"""Handle successful response."""
try:
Expand All @@ -81,8 +82,6 @@ def _handle_success(
200,
uri,
) from ex
if "ip_address" in decoded_body:
decoded_body["ip_address"]["locales"] = self._locales
return model_class(**decoded_body) # type: ignore

def _exception_for_error(
Expand Down Expand Up @@ -210,7 +209,7 @@ def __init__(
account_id: int,
license_key: str,
host: str = "minfraud.maxmind.com",
locales: Tuple[str, ...] = ("en",),
locales: Sequence[str] = ("en",),
timeout: float = 60,
proxy: Optional[str] = None,
) -> None:
Expand Down Expand Up @@ -269,7 +268,7 @@ async def factors(
Factors,
await self._response_for(
self._factors_uri,
Factors,
partial(Factors, self._locales),
transaction,
validate,
hash_email,
Expand Down Expand Up @@ -308,7 +307,7 @@ async def insights(
Insights,
await self._response_for(
self._insights_uri,
Insights,
partial(Insights, self._locales),
transaction,
validate,
hash_email,
Expand Down Expand Up @@ -387,7 +386,7 @@ async def report(
async def _response_for(
self,
uri: str,
model_class: Union[Type[Factors], Type[Score], Type[Insights]],
model_class: Callable,
request: Dict[str, Any],
validate: bool,
hash_email: bool,
Expand Down Expand Up @@ -445,7 +444,7 @@ def __init__(
account_id: int,
license_key: str,
host: str = "minfraud.maxmind.com",
locales: Tuple[str, ...] = ("en",),
locales: Sequence[str] = ("en",),
timeout: float = 60,
proxy: Optional[str] = None,
) -> None:
Expand Down Expand Up @@ -518,7 +517,7 @@ def factors(
Factors,
self._response_for(
self._factors_uri,
Factors,
partial(Factors, self._locales),
transaction,
validate,
hash_email,
Expand Down Expand Up @@ -557,7 +556,7 @@ def insights(
Insights,
self._response_for(
self._insights_uri,
Insights,
partial(Insights, self._locales),
transaction,
validate,
hash_email,
Expand Down Expand Up @@ -634,7 +633,7 @@ def report(self, report: Dict[str, Optional[str]], validate: bool = True) -> Non
def _response_for(
self,
uri: str,
model_class: Union[Type[Factors], Type[Score], Type[Insights]],
model_class: Callable,
request: Dict[str, Any],
validate: bool,
hash_email: bool,
Expand Down
9 changes: 5 additions & 4 deletions tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ def test_geoip2_location(self):
def test_ip_address(self):
time = "2015-04-19T12:59:23-01:00"
address = IPAddress(
["en"],
country={
"is_high_risk": True,
"is_in_european_union": True,
Expand Down Expand Up @@ -180,7 +181,7 @@ def test_ip_address(self):
)

def test_empty_address(self):
address = IPAddress()
address = IPAddress([])
self.assertEqual([], address.risk_reasons)

def test_score_ip_address(self):
Expand All @@ -189,7 +190,7 @@ def test_score_ip_address(self):

def test_ip_address_locales(self):
loc = IPAddress(
locales=["fr"],
["fr"],
country={"names": {"fr": "Country"}},
city={"names": {"fr": "City"}},
)
Expand Down Expand Up @@ -279,12 +280,12 @@ def test_score(self):
def test_insights(self):
response = self.factors_response()
del response["subscores"]
insights = Insights(**response)
insights = Insights(None, **response)
self.check_insights_data(insights, response["id"])

def test_factors(self):
response = self.factors_response()
factors = Factors(**response)
factors = Factors(None, **response)
self.check_insights_data(factors, response["id"])
self.check_risk_score_reasons_data(factors.risk_score_reasons)
self.assertEqual(0.01, factors.subscores.avs_result)
Expand Down
11 changes: 7 additions & 4 deletions tests/test_webservice.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import asyncio
import json
import os
from functools import partial
from io import open
from typing import Type, Union
from pytest_httpserver import HTTPServer
Expand Down Expand Up @@ -181,9 +182,10 @@ def has_ip_location(self):
def test_200(self):
model = self.create_success()
response = json.loads(self.response)
cls = self.cls
if self.has_ip_location():
response["ip_address"]["locales"] = ("en",)
self.assertEqual(self.cls(**response), model)
cls = partial(cls, ("en",))
self.assertEqual(cls(**response), model)
if self.has_ip_location():
self.assertEqual("United Kingdom", model.ip_address.country.name)
self.assertEqual(True, model.ip_address.traits.is_residential_proxy)
Expand Down Expand Up @@ -240,9 +242,10 @@ def test_200_with_locales(self):
)
model = self.create_success(client=client)
response = json.loads(self.response)
cls = self.cls
if self.has_ip_location():
response["ip_address"]["locales"] = locales
self.assertEqual(self.cls(**response), model)
cls = partial(cls, locales)
self.assertEqual(cls(**response), model)
if self.has_ip_location():
self.assertEqual("Royaume-Uni", model.ip_address.country.name)
self.assertEqual("Londres", model.ip_address.city.name)
Expand Down

0 comments on commit 165d40a

Please sign in to comment.