首页 > 解决方案 > 如何对需要 HTTP 请求的函数进行单元测试?

问题描述

我的 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 请求进行单元测试,以生成会话以便代码运行?

标签: pythonunit-testingflask

解决方案


你想使用 Flask 的测试客户端

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'})

Flask 文档通常建议您使用 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'])

但简短的回答是,只需调用test_client()您的app对象即可。


推荐阅读