如何对需要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
@R_58_4045@ion about how to avoid this problem.

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

解决方法

您要使用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'})

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