Skip to content
This repository was archived by the owner on Jan 10, 2023. It is now read-only.

Commit 64ee083

Browse files
Waren Longmina86
Waren Long
authored andcommitted
Add empty separator check and tests
str.split method does not accept an empty string as a separator: >>> 'foo'.split('') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: empty separator >>> Add an explicit test in the StringTrie constructor so we fail early when constructing the object. (As an aside, str.split allows None as a separator. StringTrie could allow None separator but _key_from_path would have to be changed. If anyone needs that feature it’s fairly easy to implement). [mina86@mina86.com: expanded commit message]
1 parent 0e1a9b8 commit 64ee083

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

pygtrie.py

+11-1
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,11 @@ def _sorted_iteritems(d):
5656
_iteritems = lambda d: iter(d.items()) # pylint: disable=invalid-name
5757
_iterkeys = lambda d: iter(d.keys()) # pylint: disable=invalid-name
5858

59+
try:
60+
_basestring = basestring
61+
except NameError:
62+
_basestring = str
63+
5964

6065
class ShortKeyError(KeyError):
6166
"""Raised when given key is a prefix of a longer key."""
@@ -1220,7 +1225,12 @@ def __init__(self, *args, **kwargs):
12201225
named argument is not specified on the function's prototype
12211226
because of Python's limitations.
12221227
"""
1223-
self._separator = kwargs.pop('separator', '/')
1228+
separator = kwargs.pop('separator', '/')
1229+
if not isinstance(separator, _basestring):
1230+
raise TypeError('separator must be a string')
1231+
if not separator:
1232+
raise ValueError('separator can not be empty')
1233+
self._separator = separator
12241234
super(StringTrie, self).__init__(*args, **kwargs)
12251235

12261236
@classmethod

test.py

+13
Original file line numberDiff line numberDiff line change
@@ -428,6 +428,19 @@ def path_from_key(cls, key):
428428
def key_from_path(cls, path):
429429
return '/'.join(path)
430430

431+
def test_valid_separator(self):
432+
t = pygtrie.StringTrie()
433+
t['foo/bar'] = 42
434+
self.assertTrue(bool(t.has_node('foo') & pygtrie.Trie.HAS_SUBTRIE))
435+
436+
t = pygtrie.StringTrie(separator='.')
437+
t['foo.bar'] = 42
438+
self.assertTrue(bool(t.has_node('foo') & pygtrie.Trie.HAS_SUBTRIE))
439+
440+
def test_invalid_separator(self):
441+
self.assertRaises(TypeError, pygtrie.StringTrie, separator=42)
442+
self.assertRaises(ValueError, pygtrie.StringTrie, separator='')
443+
431444

432445
class SortTest(unittest.TestCase):
433446

0 commit comments

Comments
 (0)