From 4a99ec0157e142f73afcac8690a8bc1f3b83b8c9 Mon Sep 17 00:00:00 2001 From: Phil Gyford Date: Tue, 22 Aug 2017 08:53:38 +0100 Subject: [PATCH] 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. --- tests/test_core.py | 13 +++++++++++++ twython/api.py | 13 +++++++------ 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/tests/test_core.py b/tests/test_core.py index c7cf2a2..b71baa0 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -327,6 +327,19 @@ class TwythonAPITestCase(unittest.TestCase): self.assertTrue('$AAPL' in tweet_text) self.assertTrue('$ANOTHER' 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 diff --git a/twython/api.py b/twython/api.py index f806cea..42a7380 100644 --- a/twython/api.py +++ b/twython/api.py @@ -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 = '$%(symbol)s' - display_text = re.sub(r'(?)' + re.escape(orig_tweet_text[start:end]) + r'\b(?!)', - symbol_html % {'symbol': entity['text']}, display_text) + symbol_html = '$%(symbol)s' + display_text = re.sub(r'(?)' + re.escape(orig_tweet_text[start:end]) + r'\b(?!)', + symbol_html % {'symbol': entity['text']}, display_text) # Urls for entity in entities['urls']: