aquil.abdullah
aquil.abdullah

Reputation: 3157

Unit testing classes that implement a collection Interface?

I've written a storage interface that can use different storage backends. As a demonstration I've written an implementation that stores objects as a key/value pair in a standard Python dictionary.

class MyStorageInterface(object):
    def store(self, key, value):
        raise NotImplementedError("Class must be subclassed")

    def get(self, key):
        raise NotImplementedError("Class must be subclassed")

# Example implementation
class DictStorage(MyStorageInterface):
    def __init__(self):
        self._cache = dict()

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

    def get(self, key):
        return self._cache[key]

Now, I want to write some unit tests for my DictStorage implementation. My question is whether or not something like:

storage = DictStorage()
value = 8
key = 'foo'
storage.store(key, value)
actual = storage.get(key)
assert actual == 8, "cache value for %s is %s, expected %s" % (key, str(actual), str(value))

is a suitable unit test for the get method or whether or not there is a Pythonic pattern for testing classes that implement collection type objects.

Upvotes: 1

Views: 82

Answers (1)

Tagc
Tagc

Reputation: 9072

I don't know if there's anything "collection-specific" but the structure of your test looks good to me. The only difference is that I'd make use of the unittest package and define it as test case:

import unittest


class MyStorageInterface(object):
    def store(self, key, value):
        raise NotImplementedError("Class must be subclassed")

    def get(self, key):
        raise NotImplementedError("Class must be subclassed")


class DictStorage(MyStorageInterface):
    def __init__(self):
        self._cache = dict()

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

    def get(self, key):
        return self._cache[key]


class DictStorageTests(unittest.TestCase):
    def setUp(self):
        self._sut = DictStorage()

    def test_storing_and_retrieving_value(self):
        value_in = 8
        key = 'foo'
        self._sut.store(key, value_in)
        value_out = self._sut.get(key)
        self.assertEqual(value_in, value_out)


if __name__ == '__main__':
    unittest.main()

Output

.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

Upvotes: 2

Related Questions