work around Python's graceless handling of invalid LANG

This commit is contained in:
Adrian Sampson 2010-12-31 17:41:50 -08:00
parent dd08f63e17
commit 43b8235a4c
3 changed files with 31 additions and 3 deletions

3
NEWS
View file

@ -7,6 +7,9 @@
applied was always just alphabetical by filename, which is frequently
but not always what you want.
* Fix crash in lastid when the artist name is not available.
* Fixed a spurious crash when LANG or a related environment variable is
set to an invalid value (such as 'UTF-8' on some installations of Mac
OS X).
1.0b5
-----

View file

@ -59,7 +59,12 @@ def print_(*strings):
else:
txt = u''
if isinstance(txt, unicode):
encoding = locale.getdefaultlocale()[1] or 'utf8'
try:
encoding = locale.getdefaultlocale()[1] or 'utf8'
except ValueError:
# Invalid locale environment variable setting. To avoid
# failing entirely for no good reason, assume UTF-8.
encoding = 'utf8'
txt = txt.encode(encoding, 'replace')
print txt

View file

@ -78,9 +78,29 @@ class PrintTest(unittest.TestCase):
ui.print_(u'something')
except TypeError:
self.fail('TypeError during print')
finally:
if lang:
os.environ['LANG'] = lang
if lang:
os.environ['LANG'] = lang
def test_print_with_invalid_locale(self):
old_lang = os.environ.get('LANG')
os.environ['LANG'] = ''
old_ctype = os.environ.get('LC_CTYPE')
os.environ['LC_CTYPE'] = 'UTF-8'
try:
ui.print_(u'something')
except ValueError:
self.fail('ValueError during print')
finally:
if old_lang:
os.environ['LANG'] = old_lang
else:
del os.environ['LANG']
if old_ctype:
os.environ['LC_CTYPE'] = old_ctype
else:
del os.environ['LC_CTYPE']
def suite():
return unittest.TestLoader().loadTestsFromName(__name__)