简体   繁体   中英

How much should a unit test know about the function it is testing?

I'm writing a test for a caching mechanism. The mechanism has two cache layers, the request cache and redis. The request cache uses Flask.g , an object that stores values for the duration of the request. It does this by creating a dictionary, on the Flask.g._cache attribute.

However, I think that the exact attribute is an implementation detail that my unit test shouldn't care about. I want to make sure it stores its values on Flask.g, but I don't care about how it does that. What would be a good way to test this?

I'm using the Python mock module, so I know I can mock out `Flask.g, but I'm not sure if there's a way to test whether there has been any property access on it, without caring about which property it is.

Is this even the right approach for tests like this?

Personally you shouldn't be mocking Flask.g if you are testing endpoints. since you would be creating a self.app (I may be unsure about this portion)

Secondly you will need to mock the redis client with something like this being the returned structure.

class RedisTestCase(object):
    saved_dictionary = {}
    def keys(self, pattern):
        found_keys = []
        for key in RedisTestCase.saved_dictionary: #loop keys for pattern
            if pattern:
                found_keys.append(key)
        return found_keys

    def delete(self, keys):
        for key in keys:
            if key in RedisTestCase.saved_dictionary:
                del RedisTestCase.saved_dictionary[key]

    def mset(self, items):
        RedisTestCase.saved_dictionary.update(items)

    def pipeline(self):
        return RedisTestCase()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM