Skip to content

Commit

Permalink
ens cure max iters
Browse files Browse the repository at this point in the history
  • Loading branch information
Carbon225 committed Apr 7, 2023
1 parent 33c14be commit 65546ed
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
14 changes: 9 additions & 5 deletions ens_normalize/normalization.py
Original file line number Diff line number Diff line change
Expand Up @@ -1069,15 +1069,19 @@ def ens_normalize(text: str) -> str:

def _ens_cure(text: str) -> Tuple[str, List[CurableError]]:
cures = []
while True:
# Protect against infinite loops.
# The assumption is that n iterations are enough to cure the input (2n just in case).
# +1 is for the last iteration that should raise DisallowedNameError.
# All cures currently implemented remove a character so this assumption seems reasonable.
for _ in range(2 * len(text) + 1):
try:
return ens_normalize(text), cures
except CurableError as e:
new_text = text[:e.index] + e.suggested + text[e.index + len(e.disallowed):]
# protect against infinite loops
assert new_text != text, 'ens_cure() entered an infinite loop'
text = new_text
text = text[:e.index] + e.suggested + text[e.index + len(e.disallowed):]
cures.append(e)
# DisallowedNameError is not caught here because it is not curable
# this should never happen
raise Exception('ens_cure() exceeded max iterations. Please report this as a bug.')


def ens_cure(text: str) -> str:
Expand Down
8 changes: 7 additions & 1 deletion tests/test_normalization.py
Original file line number Diff line number Diff line change
Expand Up @@ -378,5 +378,11 @@ def test_error_meta():
def test_unicode_version_check(mocker):
mocker.patch('ens_normalize.normalization.UNICODE_VERSION', '15.0.1')
warnings.filterwarnings('error')
with pytest.raises(UnicodeWarning):
with pytest.raises(UnicodeWarning, match=r'Unicode version mismatch'):
ens_normalize_module.normalization.check_spec_unicode_version()


def test_ens_cure_max_iters(mocker):
mocker.patch('ens_normalize.normalization.ens_normalize', lambda _: ens_normalize('?'))
with pytest.raises(Exception, match=r'ens_cure\(\) exceeded max iterations'):
ens_cure('???')

0 comments on commit 65546ed

Please # to comment.