From 90ce5d46bf62a74d7c78a61c1a7bab64f7cb1735 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Suliga?= Date: Mon, 4 Apr 2016 20:18:11 +0200 Subject: [PATCH] Fixed #26462 -- Fixed Python 2 UnicodeEncodeError when warning about long cache keys. --- django/core/cache/backends/base.py | 2 +- tests/cache/tests.py | 20 ++++++++++++++++++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/django/core/cache/backends/base.py b/django/core/cache/backends/base.py index 0b13a881bf..76e98a25b6 100644 --- a/django/core/cache/backends/base.py +++ b/django/core/cache/backends/base.py @@ -235,7 +235,7 @@ class BaseCache(object): """ if len(key) > MEMCACHE_MAX_KEY_LENGTH: warnings.warn('Cache key will cause errors if used with memcached: ' - '%s (longer than %s)' % (key, MEMCACHE_MAX_KEY_LENGTH), + '%r (longer than %s)' % (key, MEMCACHE_MAX_KEY_LENGTH), CacheKeyWarning) for char in key: if ord(char) < 33 or ord(char) == 127: diff --git a/tests/cache/tests.py b/tests/cache/tests.py index ee27d71563..ee1501a029 100644 --- a/tests/cache/tests.py +++ b/tests/cache/tests.py @@ -585,15 +585,31 @@ class BaseCacheTests(object): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") # memcached does not allow whitespace or control characters in keys - cache.set('key with spaces', 'value') + key = 'key with spaces and 清' + cache.set(key, 'value') self.assertEqual(len(w), 1) self.assertIsInstance(w[0].message, CacheKeyWarning) + self.assertEqual( + # warnings.warn() crashes on Python 2 if message isn't + # coercible to str. + str(w[0].message.args[0]), + "Cache key contains characters that will cause errors if used " + "with memcached: %r" % key, + ) with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") # memcached limits key length to 250 - cache.set('a' * 251, 'value') + key = ('a' * 250) + '清' + cache.set(key, 'value') self.assertEqual(len(w), 1) self.assertIsInstance(w[0].message, CacheKeyWarning) + self.assertEqual( + # warnings.warn() crashes on Python 2 if message isn't + # coercible to str. + str(w[0].message.args[0]), + 'Cache key will cause errors if used with memcached: ' + '%r (longer than %s)' % (key, 250), + ) finally: cache.key_func = old_func