How do I replace a class variable for the duration of a single test in Python?
Question: I'm trying to test a cache class where old items should be automatically
deleted. The amount of items the cache can hold is controlled by a "constant"
class variable like this:

    
    
    class Cache(dict):
        MAX_ITEMS = 100
    

For testing purposes I would like to change that constant for the duration of
a single test case. Using `unittest.mock.patch` I could replace the class
variable with a `MagicMock` but that's not really what I'm trying to do. I
just need to replace it with a different number.

Is there an elegant way to do this in Python (like `patch`), or should I just
reset the variable myself on `tearDown`?

* * *

I'm using Python 3.4.3


Answer: patch can do this already. try:

    
    
    from unittest.mock import patch
    
    class A:
        val = 1
    
    assert A.val == 1
    with patch.object(A, "val", "patched_value"):
        assert A.val == "patched_value"
    
    assert A.val == 1
    

Of course you can use `patch.object` as a decorator as well.

