Question

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?

Was it helpful?

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

OTHER TIPS

You'd have to write your own context manager. Here's one for your case (using contextlib):

import contextlib
@contextlib.contextmanager
def toggle_active_user(user):
    user.is_active = False
    yield
    user.is_active = True

with toggle_active_user(self.testuser):
    // Do testing

Even better, would be to save the state prior and then restore:

import contextlib
@contextlib.contextmanager
def toggle_active_user(user, new_value):
    previous_is_active = user.is_active
    user.is_active = new_value
    yield
    user.is_active = previous_is_active

with toggle_active_user(self.testuser, False):
    // Do testing
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top