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的任何想法雙聲明樣板文件?
建議發佈不起作用的完整測試代碼。不僅僅是裝飾器和Exception字符串。 – akaRem
謝謝,我匆忙發佈這個。我添加了所有與此測試相關的代碼 –