Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 29 additions & 19 deletions libredte/api_client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,12 +276,7 @@ def set_contribuyente(self, rut: int | str | None = None) -> int | None:
if valor is None or valor == '':
self.rut = None
return self.rut
valor = _rut_sin_dv(valor)
try:
self.rut = int(valor)
except ValueError as error:
msg = f'Valor de RUT inválido: {valor}'
raise ApiException(msg) from error
self.rut = _parsear_rut(valor)
return self.rut

def set_hash(self, api_hash: str | None) -> None:
Expand Down Expand Up @@ -582,14 +577,11 @@ def create_link(
recibe truncado: su router separa la ruta por '/' antes de
decodificarla.
"""
valor = rut or self.rut
msg = f'Valor de RUT inválido: {valor}'
valor = rut if rut is not None else self.rut
if valor is None:
msg = f'Valor de RUT inválido: {valor}'
raise ApiException(msg)
try:
rut_numero = int(_rut_sin_dv(valor))
except ValueError as error:
raise ApiException(msg) from error
rut_numero = _parsear_rut(valor)
link = f'{self.url}/dte/contribuyentes/seleccionar/{rut_numero}'
if resource:
resource_base64 = base64.b64encode(
Expand All @@ -600,18 +592,36 @@ def create_link(
return link


def _rut_sin_dv(rut: int | str) -> int | str:
def _parsear_rut(rut: int | str) -> int:
"""
Quita los puntos y el dígito verificador de un RUT en texto con DV.
Valida y convierte un RUT (con o sin dígito verificador) a entero positivo.

:param rut: RUT, por ejemplo 76192083 o '76.192.083-9'.
:type rut: int, str
:return: RUT sin dígito verificador (sin convertir a entero).
:rtype: int, str
:return: Cuerpo numérico positivo del RUT, sin dígito verificador.
:rtype: int
:raises ApiException: Si el RUT es booleano, no positivo o mal formado.
"""
if isinstance(rut, str) and '-' in rut:
return rut.replace('.', '').split('-')[0]
return rut
msg = f'Valor de RUT inválido: {rut}'
if isinstance(rut, bool):
raise ApiException(msg)
if isinstance(rut, int):
if rut <= 0:
raise ApiException(msg)
return rut
texto = rut.strip().replace('.', '')
if '-' in texto:
cuerpo, _, dv = texto.partition('-')
if not (len(dv) == 1 and (dv.isdigit() or dv in 'kK')):
raise ApiException(msg)
else:
cuerpo = texto
if not cuerpo.isdigit():
raise ApiException(msg)
numero = int(cuerpo)
if numero <= 0:
raise ApiException(msg)
return numero


def _is_dict(value: object) -> TypeIs[dict[str, object]]:
Expand Down
19 changes: 16 additions & 3 deletions tests/api_client/test_configuracion.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,22 @@ def test_contribuyente_vacio_lo_quita(self) -> None:
self.assertIsNone(self.client.rut)

def test_contribuyente_invalido(self) -> None:
"""Un RUT que no es número es un error."""
with self.assertRaises(ApiException):
self.client.set_contribuyente('abc')
"""Un RUT no numérico, booleano, no positivo o mal formado falla."""
invalidos: tuple[int | str, ...] = (
'abc',
True,
False,
0,
-76192083,
'76192083-',
'1-2-3',
)
for invalido in invalidos:
with (
self.subTest(invalido=invalido),
self.assertRaises(ApiException),
):
self.client.set_contribuyente(invalido)

def test_ambiente_sin_distinguir_mayusculas(self) -> None:
"""'Produccion' o ' TEST ' son válidos, como en minúsculas."""
Expand Down
10 changes: 10 additions & 0 deletions tests/api_client/test_url.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,16 @@ def test_recurso_en_base64_se_escapa(self) -> None:
+ recurso_base64.replace('+', '%2B'),
)

def test_rut_explicito_invalido_no_usa_el_configurado(self) -> None:
"""Un RUT explícito vacío o 0 falla en vez de usar self.rut."""
self.client.set_contribuyente(76192083)
for rut_invalido in ('', 0, False, -1, '76192083-'):
with (
self.subTest(rut_invalido=rut_invalido),
self.assertRaises(ApiException),
):
self.client.create_link('/dte/dte_emitidos', rut_invalido)


if __name__ == '__main__':
unittest.main(verbosity=2)