Last active
October 28, 2015 08:40
-
-
Save yohanboniface/ceaa1a901948924a5f8b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import pytest | |
def smart_struncate(s, length=100, suffix='…'): | |
# Be smart here. | |
return s | |
@pytest.mark.parametrize('given,expected,length,suffix', [ | |
[u'Ceci est une longue phrase qui pourrait éventuellement servir de titre à billet de blog mais est vraiment beaucoup trop longue', # noqa | |
u'Ceci est une longue phrase qui pourrait éventuellement servir de titre à billet de blog mais est…', None, None], # noqa | |
['A short sentence', 'A short sentence', None, None], | |
['A short sentence', u'A short…', 10, None], | |
['A short sentence', u'A short.', 10, '.'], | |
['A short sentence', u'A short', 10, ''], | |
[u"أكثر من خمسين لغة،", u"أكثر من خمسين لغة،", None, None], | |
[u"أكثر من خمسين لغة،", u"أكثر…", 5, None], | |
["I'm 17 chars long", "I'm 17 chars long", 17, None], | |
["I've a space at 13", u"I've a space…", 13, None], | |
["I've a space at 13", u"I've a space…", 12, None], | |
["I've a space at 13", u"I've a space…", 14, None], | |
['Anticonstitutionnellement', u'Anticon…', 7, None], | |
["I've a comma, at 13", u"I've a comma…", 13, None], | |
]) | |
def test_smart_struncate(given, expected, length, suffix): | |
kwargs = {} | |
if length is not None: | |
kwargs['length'] = length | |
if suffix is not None: | |
kwargs['suffix'] = suffix | |
assert smart_truncate(given, **kwargs) == expected |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def smart_truncate(s, length=100, suffix=u'…'): | |
if len(s) > length: | |
s = s[:length+1] | |
if ' ' in s: | |
s = u' '.join(s.split(u' ')[0:-1]) | |
else: | |
s = s[:-1] | |
# We don't want to add a punctuation after another punctuation. | |
while not s[-1].isalnum(): | |
s = s[:-1] | |
s = s + suffix | |
return s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment