Mock locale defaults

Written by Miguel González on 2013-06-29

I need to test a piece of code with different behaviour depending on system locale LANG configuration. Instead of change environment, I'm using mock

This is an snippet (test.py):

import unittest
import locale

from mock import patch


class LocaleTest(unittest.TestCase):
    LOCALE = ('hi_IN', 'UTF-8')

    def setUp(self):
        locale_patcher = patch('locale.getdefaultlocale')
        locale_mock = locale_patcher.start()
        locale_mock.return_value = self.LOCALE
        self.addCleanup(locale_patcher.stop)

    def test_locale(self):
        locale_defaults = locale.getdefaultlocale()
        self.assertEqual(locale_defaults[0], 'hi_IN')
        self.assertEqual(locale_defaults[1], 'UTF-8')
$ python -m unittest test
.
---------------------------------------------------------------------
Ran 1 test in 0.001s

OK

mock is now part of the Python standard library, available as unittest.mock in Python 3.3 onwards. It could be installed in other versions with pip install mock.

Links

Social