如何对需要HTTP请求的函数进行单元测试?

2024-04-25 08:12:09 发布

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

我的Flask应用程序中有一些基于会话管理的功能。例如,当来自会话的请求传入时,更新字典中的值(datetime.now()值)

def update_existing_session(active_sessions):
    """[Updates the value of the session in the management dictionary with
    a current timestamp]

    Args:
        active_sessions ([dictionary]): [Dictionary containing session info.
        key = session token, value = last request timestamp]

    Returns:
        active_sessions ([dictionary]): [Updated dictionary of active sessions.
        Key = session token, value = last request timestamp]
    """
    session_name = session.get('public_user')
    logging.info("New request from " + str(session_name))
    active_sessions[session_name] = datetime.now()
    return active_sessions

当我尝试单元测试这个或类似的方法(也使用会话)时,例如下面的例子,我得到以下错误:

    def test_generate_new_session(self):
        active_sessions = {}
        active_sessions = session_management.generate_new_session(active_sessions)
        self.assertEqual(len(active_sessions), 1)
 

RuntimeError: Working outside of request context.

This typically means that you attempted to use functionality that needed
an active HTTP request.  Consult the documentation on testing for
information about how to avoid this problem.

如何使用活动HTTP请求进行单元测试,以生成会话,从而使代码运行


Tags: ofthenameinfodatetimedictionaryvaluerequest
1条回答
网友
1楼 · 发布于 2024-04-25 08:12:09

您要使用Flask的test client

from your_flask_app import app   # Flask app object


with app.test_client() as client:
    response = client.get('/your-controller-endpoint')
    response = client.post('/your-controller-endpoint', data={'post': 'params'})

烧瓶文档通常建议您使用PyTest,这样可以更轻松地设置夹具。文档中的示例:

import os
import tempfile

import pytest

from flaskr import flaskr


@pytest.fixture
def client():
    db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()
    flaskr.app.config['TESTING'] = True

    with flaskr.app.test_client() as client:
        with flaskr.app.app_context():
            flaskr.init_db()
        yield client

    os.close(db_fd)
    os.unlink(flaskr.app.config['DATABASE'])

但简单的回答是,只需在app对象上调用test_client()

相关问题 更多 >