From d27e6a5dfa023c6578f167b1d0383c2e556afc75 Mon Sep 17 00:00:00 2001 From: tzutalin Date: Fri, 28 Dec 2018 10:07:59 -0800 Subject: [PATCH] fix the crash when providing invalid locale in env --- libs/stringBundle.py | 10 ++++++++-- tests/test_stringBundle.py | 11 +++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/libs/stringBundle.py b/libs/stringBundle.py index 0ea28079..6cbc3e44 100644 --- a/libs/stringBundle.py +++ b/libs/stringBundle.py @@ -15,7 +15,6 @@ except ImportError: sip.setapi('QVariant', 2) from PyQt4.QtCore import * -DEFAULT_LOCALE = locale.getlocale()[0] if locale.getlocale() and len(locale.getlocale()) > 0 else os.getenv('LANG') class StringBundle: @@ -29,7 +28,14 @@ class StringBundle: self.__loadBundle(path) @classmethod - def getBundle(cls, localeStr=DEFAULT_LOCALE): + def getBundle(cls, localeStr=None): + if localeStr is None: + try: + localeStr = locale.getlocale()[0] if locale.getlocale() and len( + locale.getlocale()) > 0 else os.getenv('LANG') + except: + print('Invalid locale') + locale = 'en' return StringBundle(cls.__create_key, localeStr) def getString(self, stringId): diff --git a/tests/test_stringBundle.py b/tests/test_stringBundle.py index 2ae63fa7..c67af137 100644 --- a/tests/test_stringBundle.py +++ b/tests/test_stringBundle.py @@ -13,5 +13,16 @@ class TestStringBundle(unittest.TestCase): strBundle = StringBundle.getBundle('zh-TW') self.assertEqual(strBundle.getString("openDir"), u'\u958B\u555F\u76EE\u9304', 'Fail to load the zh-TW bundle') + def test_setInvaleLocaleToEnv_printErrorMsg(self): + prev_lc = os.environ['LC_ALL'] + prev_lang = os.environ['LANG'] + os.environ['LC_ALL'] = 'UTF-8' + os.environ['LANG'] = 'UTF-8' + strBundle = StringBundle.getBundle() + self.assertEqual(strBundle.getString("openDir"), 'Open Dir', 'Fail to load the default bundle') + os.environ['LC_ALL'] = prev_lc + os.environ['LANG'] = prev_lang + + if __name__ == '__main__': unittest.main()