2013-10-29 30 views
-1

我做的和Django框架工作的一些應用程序的測試, 我有一個情況我測試,如果不活動的用戶可以登錄,我真的很喜歡這樣PEP343「與」上下文管理和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的函數?

+0

with語句中使用的對象必須支持上下文管理器協議,例如文件對象支持上下文管理器協議。 –

回答

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 
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 
+0

我做了這樣的事情 類notActive: 高清__init __(自我,VAL): self.test = VAL 高清__enter __(個體經營): self.test.is_active =假 高清__exit __(自我,TY,值,tb): self.test.is_active =真 但你的代碼似乎對我更實際,謝謝 – AmOs

+0

是的,我只是使用'contextmanager'裝飾器來保存一些基於類的腳手架,但你已經得到它了。 –