2013-11-28 3 views
2

나는 플라스크 API를 테스트하려했기 때문에 응용 프로그램과 데이터베이스 연결을 다루는 템플릿 클래스를 상속하여 각 테스트의 상용구를 상당히 줄일 수있었습니다. 내가 알아 내지 못한 것은 각 테스트 전에 세션 객체를 설정하는 방법입니다.플라스크 유닛 테스팅 세션 데코레이터

예를 들어 how to handle test sessions을 보았지만 가능한 경우 데코레이터 또는 unittest 클래스 설정에 숨기려고합니다.

유닛 테스트 클래스 설정 :

class TestingTemplate(unittest.TestCase): 

    @classmethod 
    def setUpClass(self): 
     """ Sets up a test database before each set of tests """ 
     setup_db('localhost', 28015, 'TEST', 
      datasets = test_dataset, 
      app_tables = test_tables) 
     self.rdb = rethinkdb.connect(
       host = 'localhost', 
       port = 28015, 
       db = 'TEST') 
     self.rdb.use('TEST') 
     app.config['RDB_DB'] = 'TEST' 
     self.app = app.test_client() 

실패 테스트 클래스 : 던져

def admin_session(fn): 
    def run_test(self): 
     with self.app.session_transaction() as sess: 
      sess['role'] = 'admin' 
     fn(self) 
    return run_test 


class TestReview(template.TestingTemplate): 
    """ Tests the API endpoints associated with handling reviews. """ 


    @admin_session 
    def test_create_success(self): 
     """ Tests a successful review creation """ 
     # creating review 
     review = {'company': 'test', 'rating':10} 
     resp = self.app.post('/review/create/123', data=json.dumps(review)) 

     # testing creation 
     self.assertEqual(resp.status_code, 201) 
     resp_data = json.loads(resp.data) 
     self.assertEqual(resp_data['message'], 'review created') 

오류 :없이 각 테스트하기 전에 세션 쿠키를 설정하는 방법에 대한

====================================================================== 
ERROR: test_create_success (test_reviews.TestReview) 
---------------------------------------------------------------------- 
Traceback (most recent call last): 
    File "/vagrant/src/server/testing/test_reviews.py", line 11, in run_test 
    with self.app.session_transaction() as sess: 
    File "/usr/lib/python2.7/contextlib.py", line 17, in __enter__ 
    return self.gen.next() 
    File "/usr/local/lib/python2.7/dist-packages/flask/testing.py", line 74, in session_transaction 
    raise RuntimeError('Session backend did not open a session. ' 
RuntimeError: Session backend did not open a session. Check the configuration 

어떤 아이디어 성명 상용구와 함께 두 번?

+0

작동하지 않는 전체 테스트 코드를 게시 할 것을 제안하십시오. 데코레이터와 예외 문자열이 아닙니다. – akaRem

+0

고마워, 나는 성급하게 이것을 게시했다. 이 테스트와 관련된 모든 코드를 추가했습니다. –

답변

2

나는 가져 오기/포스트 방법을 대체 할 도우미 방법으로 이런 종류의 작업을 수행하는 경향이 :

또한 사용자 오브젝트를 올바르게 세션을 설정 request_as_user 같은 것을 가질 수
class MyTestCase(unittest.TestCase): 

    def request_with_role(self, path, method='GET', role='admin', *args, **kwargs): 
     ''' 
     Make an http request with the given role in the session 
     ''' 
     with self.app.test_client() as c: 
      with c.session_transaction() as sess: 
       sess['role'] = role 
      kwargs['method'] = method 
      kwargs['path'] = path 
      return c.open(*args, **kwargs) 

    def test_my_thing(self): 
     review = {'company': 'test', 'rating':10} 
     resp = self.request_with_role(
      '/review/create/123', 
      method='POST', 
      data=json.dumps(review), 
     ) 
     .... 

그 사용자의 경우 :

session['_id'] = user.id 
session['role'] = user.role