2013-11-28 133 views
2

我一直在試圖測試Flask 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 

如何在未對每次測試前設置會話cookie的任何想法雙聲明樣板文件?

+0

建議發佈不起作用的完整測試代碼。不僅僅是裝飾器和Exception字符串。 – akaRem

+0

謝謝,我匆忙發佈這個。我添加了所有與此測試相關的代碼 –

回答

2

我傾向於做這樣的事情有一個輔助方法來代替GET/POST方法:

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), 
     ) 
     .... 

你也可以有類似request_as_user,這需要用戶對象並正確設置會話對於該用戶:

​​