PEP343“with”上下文管理器和djang

2024-04-25 12:48:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用django框架做一些应用程序测试, 我有一个例子,我测试不活跃的用户是否可以登录,我喜欢这样做

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

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

^{pr2}$

然后我试着

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

它也失败了

有办法解决这个问题吗?或者我必须定义一个函数,将isactive设置为false?在


Tags: django用户self框架falsetrue应用程序is
2条回答

这是一个从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

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

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

^{pr2}$

相关问题 更多 >