Ensure html_for_tweet() works if symbols is missing

Some Tweets, such as those in a downloaded archive, don't have a
`symbols` element in their `entities` dict.

This fix ensures `html_for_tweet()` still works if that is missing.
This commit is contained in:
Phil Gyford 2017-08-22 08:53:38 +01:00
parent 5a87fc7d84
commit 4a99ec0157
2 changed files with 20 additions and 6 deletions

View file

@ -327,6 +327,19 @@ class TwythonAPITestCase(unittest.TestCase):
self.assertTrue('<a href="https://twitter.com/search?q=%24AAPL" class="twython-symbol">$AAPL</a>' in tweet_text)
self.assertTrue('<a href="https://twitter.com/search?q=%24ANOTHER" class="twython-symbol">$ANOTHER</a>' not in tweet_text)
def test_html_for_tweet_no_symbols(self):
"""Should still work if tweet object has no symbols list"""
tweet = test_tweet_symbols_object
# Save a copy:
symbols = tweet['entities']['symbols']
del tweet['entities']['symbols']
tweet_text = self.api.html_for_tweet(tweet)
self.assertTrue('symbols: $AAPL and' in tweet_text)
self.assertTrue('and $ANOTHER and $A.' in tweet_text)
# Put the symbols back:
test_tweet_symbols_object['entities']['symbols'] = symbols
def test_html_for_tweet_compatmode(self):
tweet_text = self.api.html_for_tweet(test_tweet_compat_object)
# link to compat web status link

View file

@ -581,13 +581,14 @@ class Twython(EndpointsMixin, object):
hashtag_html % {'hashtag': entity['text']}, display_text)
# Symbols
for entity in sorted(entities['symbols'],
key=lambda symbol: len(symbol['text']), reverse=True):
start, end = entity['indices'][0], entity['indices'][1]
if 'symbols' in entities:
for entity in sorted(entities['symbols'],
key=lambda symbol: len(symbol['text']), reverse=True):
start, end = entity['indices'][0], entity['indices'][1]
symbol_html = '<a href="https://twitter.com/search?q=%%24%(symbol)s" class="twython-symbol">$%(symbol)s</a>'
display_text = re.sub(r'(?<!>)' + re.escape(orig_tweet_text[start:end]) + r'\b(?!</a>)',
symbol_html % {'symbol': entity['text']}, display_text)
symbol_html = '<a href="https://twitter.com/search?q=%%24%(symbol)s" class="twython-symbol">$%(symbol)s</a>'
display_text = re.sub(r'(?<!>)' + re.escape(orig_tweet_text[start:end]) + r'\b(?!</a>)',
symbol_html % {'symbol': entity['text']}, display_text)
# Urls
for entity in entities['urls']: