diff --git a/moulinette/utils/serialize.py b/moulinette/utils/serialize.py index 06981d6e..a4492cba 100644 --- a/moulinette/utils/serialize.py +++ b/moulinette/utils/serialize.py @@ -12,9 +12,10 @@ class JSONExtendedEncoder(JSONEncoder): """Extended JSON encoder - Extend default JSON encoder to recognize more types and classes. It - will never raise if the object can't be encoded and return its repr + Extend default JSON encoder to recognize more types and classes. It will + never raise an exception if the object can't be encoded and return its repr instead. + The following objects and types are supported: - set: converted into list diff --git a/moulinette/utils/text.py b/moulinette/utils/text.py index 4c39e0f3..984e2e89 100644 --- a/moulinette/utils/text.py +++ b/moulinette/utils/text.py @@ -10,7 +10,7 @@ def search(pattern, text, count=0, flags=0): """Search for pattern in a text Scan through text looking for all locations where the regular - expresion pattern matches, and return them as a list of strings. + expression pattern matches, and return them as a list of strings. The optional argument count is the maximum number of pattern occurences to return; count must be an integer. If omitted or zero, diff --git a/test/test_serialize.py b/test/test_serialize.py new file mode 100644 index 00000000..0e761064 --- /dev/null +++ b/test/test_serialize.py @@ -0,0 +1,14 @@ +from datetime import datetime as dt +from moulinette.utils.serialize import JSONExtendedEncoder + + +def test_json_extended_encoder(caplog): + encoder = JSONExtendedEncoder() + + assert encoder.default(set([1, 2, 3])) == [1, 2, 3] + + assert encoder.default(dt(1917, 3, 8)) == '1917-03-08T00:00:00+00:00' + + assert encoder.default(None) == 'None' + for message in caplog.messages: + assert 'cannot properly encode in JSON' in message diff --git a/test/test_text.py b/test/test_text.py new file mode 100644 index 00000000..7ccc901f --- /dev/null +++ b/test/test_text.py @@ -0,0 +1,21 @@ +from moulinette.utils.text import search, searchf, prependlines, random_ascii + + +def test_search(): + assert search('a', 'a a a') == ['a', 'a', 'a'] + assert search('a', 'a a a', count=2) == ['a', 'a'] + assert not search('a', 'c c d') + + +def test_searchf(test_file): + assert searchf('bar', str(test_file)) == ['bar'] + assert not searchf('baz', str(test_file)) + + +def test_prependlines(): + assert prependlines('abc\nedf\nghi', 'XXX') == 'XXXabc\nXXXedf\nXXXghi' + assert prependlines('', 'XXX') == 'XXX' + + +def test_random_ascii(): + assert isinstance(random_ascii(length=2), unicode)