2013-10-29 2 views
-1

나는 비활성 사용자가 로그인 할 수 있는지 테스트 어디서 경우가 있고, 내가 그렇게PEP343는

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

내 질문에 같이 할 장고 프레임 워크와 일부 응용 프로그램 테스트, 을하고있는 중이 야 PEP343 에 의해 제공되는 컨텍스트 매니저와 함께 사용하여, 이다 내가이 일을 시도하지만 난 다음

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

실패 내가

을하려고 노력 이 주위에 방법이 16,
with self.settings(self.__set_attr(self.testuser.is_active = False)): 
//code 

그것은 또한

실패인가? 또는 is_active를 false로 설정하는 함수를 정의해야합니까?

+0

문에 사용 된 개체는 컨텍스트 관리자 프로토콜을 지원해야합니다. 예를 들어 파일 개체는 컨텍스트 관리자 프로토콜을 지원합니다. 데프 __init __ (자기, 발) : –

답변

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 같은했다 을 self.test = 발 데프 __enter __ (자기) : self.test.is_active = 거짓 데프 __exit __ (자기, 타이, 값, tb) : self.test.is_active = True 코드가 더 실용적으로 보입니다. 감사합니다. – AmOs

+0

그래, 방금 일부 클래스 기반 스캐 폴딩을 저장하기 위해'contextmanager' 데코레이터를 사용했지만, 알았다. –