Search code examples
pythondjangowith-statementcontextmanager

PEP343 'with' context manager and django


I am doing some application testing with django frame work , i have a case where i test if inactive users can login , and i do like so

self.testuser.is_active = False
//DO testing
self.testuser.is_active = True
//Proceed 

my question is , by using with context manager provided by PEP343 i tried to do this but i failed

with self.testuser.is_active = False :
//code

then i tried to do

with self.settings(self.__set_attr(self.testuser.is_active = False)):
//code

it also fails

is there is a way around this ? or do i have to define a function that sets is_active to false?


Solution

  • Here is is a more generic context manager built from contextlib.

    from contextlib import contextmanager
    
    @contextmanager
    def temporary_changed_attr(object, attr, value):
        if hasattr(object, attr):
            old = getattr(object, attr)
            setattr(object, attr, value)
            yield
            setattr(object, attr, old)
        else:
            setattr(object, attr, value)
            yield
            delattr(object, attr)
    
    # Example usage
    with temporary_changed_attr(self.testuser, 'is_active', False):
        # self.testuser.is_active will be false in here