-1

我正在使用 django 框架工作进行一些应用程序测试,我有一个案例我测试非活动用户是否可以登录,我确实喜欢这样

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

我的问题是,通过使用PEP343提供的上下文管理器, 我尝试这样做,但我失败了

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

然后我试着做

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

它也失败了

有没有办法解决这个问题?还是我必须定义一个将 is_active 设置为 false 的函数?

4

2 回答 2

0

您必须编写自己的上下文管理器。这是您的案例(使用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

更好的是,先保存状态然后恢复:

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
于 2013-10-29T07:43:09.897 回答
0

这是一个从 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
于 2013-10-29T07:58:52.400 回答