commit 3d2cefe9ffaacd36da803afb3609c63608b75759 Author: Damian Johnson atagar@torproject.org Date: Sun Jun 18 19:19:15 2017 -0700
Add a _split_by_length() helper
Seems we're gonna need to split strings into 64 character lines. Adding a helper to do so. --- stem/util/str_tools.py | 18 ++++++++++++++++++ test/unit/doctest.py | 1 + test/unit/util/str_tools.py | 8 ++++++++ 3 files changed, 27 insertions(+)
diff --git a/stem/util/str_tools.py b/stem/util/str_tools.py index 8c6463a..4a76dc4 100644 --- a/stem/util/str_tools.py +++ b/stem/util/str_tools.py @@ -161,6 +161,24 @@ def _to_camel_case(label, divider = '_', joiner = ' '): return joiner.join(words)
+def _split_by_length(msg, size): + """ + Splits a string into a list of strings up to the given size. + + :: + + >>> _split_by_length('hello', 2) + ['he', 'll', 'o'] + + :param str msg: string to split + :param int size: number of characters to chunk into + + :returns: **list** with chunked string components + """ + + return [msg[i:i + size] for i in range(0, len(msg), size)] + + # This needs to be defined after _to_camel_case() to avoid a circular # dependency with the enum module.
diff --git a/test/unit/doctest.py b/test/unit/doctest.py index fb74d92..7e40e87 100644 --- a/test/unit/doctest.py +++ b/test/unit/doctest.py @@ -66,6 +66,7 @@ class TestDocumentation(unittest.TestCase): elif path.endswith('/stem/util/str_tools.py'): args['globs'] = { '_to_camel_case': stem.util.str_tools._to_camel_case, + '_split_by_length': stem.util.str_tools._split_by_length, 'crop': stem.util.str_tools.crop, 'size_label': stem.util.str_tools.size_label, 'time_label': stem.util.str_tools.time_label, diff --git a/test/unit/util/str_tools.py b/test/unit/util/str_tools.py index 00e5c55..1576c06 100644 --- a/test/unit/util/str_tools.py +++ b/test/unit/util/str_tools.py @@ -42,6 +42,14 @@ class TestStrTools(unittest.TestCase): self.assertEqual('Hello\tworld', str_tools._to_camel_case('hello\tWORLD')) self.assertEqual('Hello\t\tWorld', str_tools._to_camel_case('hello__world', '_', '\t'))
+ def test_split_by_length(self): + self.assertEqual(['h', 'e', 'l', 'l', 'o'], str_tools._split_by_length('hello', 1)) + self.assertEqual(['he', 'll', 'o'], str_tools._split_by_length('hello', 2)) + self.assertEqual(['hel', 'lo'], str_tools._split_by_length('hello', 3)) + self.assertEqual(['hell', 'o'], str_tools._split_by_length('hello', 4)) + self.assertEqual(['hello'], str_tools._split_by_length('hello', 5)) + self.assertEqual(['hello'], str_tools._split_by_length('hello', 6)) + def test_crop(self): # test the pydoc examples self.assertEqual('This is a looo...', str_tools.crop('This is a looooong message', 17))
tor-commits@lists.torproject.org