diff --git a/src/cl_sii/rut/__init__.py b/src/cl_sii/rut/__init__.py index 4b12b74e..40345573 100644 --- a/src/cl_sii/rut/__init__.py +++ b/src/cl_sii/rut/__init__.py @@ -10,6 +10,8 @@ """ +from __future__ import annotations + import itertools import random import re @@ -50,7 +52,7 @@ class Rut: """ - def __init__(self, value: str, validate_dv: bool = False) -> None: + def __init__(self, value: str | Rut, validate_dv: bool = False) -> None: """ Constructor. @@ -79,8 +81,7 @@ def __init__(self, value: str, validate_dv: bool = False) -> None: self._dv = match_groups['dv'] if validate_dv: - if Rut.calc_dv(self._digits) != self._dv: - raise ValueError("RUT's \"digito verificador\" is incorrect.", value) + self.validate_dv(raise_exception=True) ############################################################################ # properties @@ -137,6 +138,22 @@ def __hash__(self) -> int: # Objects are hashable so they can be used in hashable collections. return hash(self.canonical) + ############################################################################ + # custom methods + ############################################################################ + + def validate_dv(self, raise_exception: bool = False) -> bool: + """ + Whether the "digito verificador" of the RUT is correct. + + :param raise_exception: Whether to raise an exception if validation fails. + :raises ValueError: + """ + is_valid = self.calc_dv(self._digits) == self._dv + if not is_valid and raise_exception: + raise ValueError("RUT's \"digito verificador\" is incorrect.", self.canonical) + return is_valid + ############################################################################ # class methods ############################################################################ diff --git a/src/tests/test_rut.py b/src/tests/test_rut.py index e7dd2e47..505264d3 100644 --- a/src/tests/test_rut.py +++ b/src/tests/test_rut.py @@ -261,6 +261,25 @@ def test__hash__(self) -> None: rut_hash = hash(self.valid_rut_instance.canonical) self.assertEqual(self.valid_rut_instance.__hash__(), rut_hash) + ############################################################################ + # custom methods + ############################################################################ + + def test_validate_dv(self) -> None: + self.assertIs(self.valid_rut_instance.validate_dv(), True) + self.assertIs(self.invalid_rut_instance.validate_dv(), False) + + def test_validate_dv_raises_exception(self) -> None: + try: + self.valid_rut_instance.validate_dv(raise_exception=True) + except ValueError as exc: + self.fail(f'{exc.__class__.__name__} raised') + + with self.assertRaisesRegex( + ValueError, r'''('RUT\\'s "digito verificador" is incorrect.', '6824160-0')''' + ): + self.invalid_rut_instance.validate_dv(raise_exception=True) + ############################################################################ # class methods ############################################################################