Flask单元测试会议d

2024-04-23 14:01:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试测试一个flaskapi,通过继承一个模板类(涵盖应用程序和数据库连接),我能够显著地最小化每个测试的样板文件。我还没弄明白如何在每次测试之前设置会话对象。在

我已经看过how to handle test sessions的示例,但如果可能的话,我希望将其隐藏在修饰符中或unittest类设置中。在

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()

失败测试等级:

^{pr2}$

引发的错误:

======================================================================
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

对于如何在没有double with语句样板的情况下在每次测试之前设置会话cookie有什么想法吗?在


Tags: inpytestselfapplocalhostdbtables
1条回答
网友
1楼 · 发布于 2024-04-23 14:01:17

我倾向于用helper方法来代替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的内容,它获取用户对象并为该用户正确设置会话:

^{pr2}$

相关问题 更多 >