[Sugar-devel] Unit testing in sugar platform: using python mock

Miguel González migonzalvar at activitycentral.com
Wed Jul 10 11:15:29 EDT 2013

TL;DR: Python mock library is very useful. I share with you an example.
Could it be added on sugar-build?

While I was working on bringing 3G database support to sugar platform, I
needed to test persistent storage on GConf and locale environment variables.

At the end I didn't include the test for this functionality in the pull
request [1] but I would like to share with the list my approach.

Sorry because it is a long message. I will appreciate to get some feedback
about including mock library to sugar testing.

- First of all, I had to install mock [2]. I don't know how to do it
properly using osbuild. I do think it would be very useful for testing.
BTW, this library is on Python 3.3 standard library as unittest.mock.

- Then I imported patch function:

from mock import patch

- Next, I imported GConf keys an create a fake GConf client. It just a key
data store with initializable values:

from cpsection.modemconfiguration.model import (

class FakeGConfClient(object):
    store = {
        GCONF_SP_COUNTRY: '',
        GCONF_SP_PROVIDER: '',
        GCONF_SP_PLAN: '',

    def __init__(self, **kwargs):

    def get_string(self, key):
        return self.store[key]

    def set_string(self, key, value):
        self.store[key] = value

    def get_int(self, key):
        return self.store[key]

    def set_int(self, key, value):
        self.store[key] = value

- The test suite has 3 parts.

1. On setUp() I patch GConf.Client.get_default to use my false client:
2. On test_guess_country() I patch locale.getdefaultlocale() to return an
arbitrary value.
3. Finally I instantiate the main class and assert default country is the
expected one

class ServiceProvidersGuessCountry(unittest.TestCase):
    def setUp(self):  # (1)
        gconf_patcher = patch('gi.repository.GConf.Client.get_default')
        gconf_mock = gconf_patcher.start()
        gconf_mock.return_value = FakeGConfClient(GCONF_SP_COUNTRY=None)

    def test_guess_country(self):
        LOCALE = ('hi_IN', 'UTF-8')
        default_country_code = LOCALE[0][3:5].lower()

        with patch('locale.getdefaultlocale') as locale_mock:  # (2)
            locale_mock.return_value = LOCALE

            db = ServiceProvidersDatabase()
            country = db.get_country()
            self.assertEqual(country.code, default_country_code)  # (3)

What do you think?

[1] https://github.com/sugarlabs/sugar/pull/58

[2] http://www.voidspace.org.uk/python/mock/
Miguel González
Activity Central: http://www.activitycentral.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.sugarlabs.org/archive/sugar-devel/attachments/20130710/bc2eb886/attachment.html>

More information about the Sugar-devel mailing list