You cannot avoid flushing the cache here. If you are fond of this class, then your unittest should have a deep knowledge of the internal workings of the class, so just reset the cache. You rarely can change the way your class works without changing your unittests.
If you feel that this will create a load on the service anyway, then make the cache processing explicit by adding a class method:
class MyClass: cache_dict = {} @classmethod def _clear_cache(cls):
Notice that I nevertheless gave him a name with a leading underscore; this is not a method that a third-party should call, it is available only for tests. But now you have centralized cache flushing, which gives you control over how it is implemented.
If you use the unittest framework to run tests, clear the cache before each test in the TestCase.setUp() method. If you use a different testing structure, this structure will have a similar hook. Clearing the cache before each test ensures that you always have a clean state.
Please note that your cache is not thread safe, if you use tests in parallel with stream processing, you will have problems. Since this also applies to the cache implementation itself, this is probably not what you are worried about right now.
source share