美文网首页
Flask-SocketIO单元测试中创建连接时添加HTTP H

Flask-SocketIO单元测试中创建连接时添加HTTP H

作者: JianMing | 来源:发表于2018-01-02 16:31 被阅读45次

在使用flask-socketio中,有时候需要在创建连接时检查HTTP Header中是否有相关的信息。但在flask-socketio的单元测试工具中,并没有方法添加HTTP Header,但可以对框架进行简单的修改,就可以了。

改动的地方如下:

# 1. flask_socketio/__init__.py
def test_client(self, app, namespace=None, headers=None):
        """Return a simple SocketIO client that can be used for unit tests."""
        return SocketIOTestClient(app, self, namespace, headers)
# flask_socketio/test_client.py

    def __init__(self, app, socketio, namespace=None, headers=None):
        def _mock_send_packet(sid, pkt):
            if pkt.packet_type == packet.EVENT or \
                    pkt.packet_type == packet.BINARY_EVENT:
                if sid not in self.queue:
                    self.queue[sid] = []
                if pkt.data[0] == 'message' or pkt.data[0] == 'json':
                    self.queue[sid].append({'name': pkt.data[0],
                                            'args': pkt.data[1],
                                            'namespace': pkt.namespace or '/'})
                else:
                    self.queue[sid].append({'name': pkt.data[0],
                                            'args': pkt.data[1:],
                                            'namespace': pkt.namespace or '/'})
            elif pkt.packet_type == packet.ACK or \
                    pkt.packet_type == packet.BINARY_ACK:
                self.ack = {'args': pkt.data,
                            'namespace': pkt.namespace or '/'}

        self.app = app
        self.sid = uuid.uuid4().hex
        self.queue[self.sid] = []
        self.callback_counter = 0
        self.socketio = socketio
        socketio.server._send_packet = _mock_send_packet
        socketio.server.environ[self.sid] = {}
        if isinstance(socketio.server.manager, PubSubManager):
            raise RuntimeError('Test client cannot be used with a message '
                               'queue. Disable the queue on your test '
                               'configuration.')
        socketio.server.manager.initialize()
        self.connect(namespace, headers)

    def connect(self, namespace=None, headers=None):
        """Connect the client.

        :param namespace: The namespace for the client. If not provided, the
                          client connects to the server on the global
                          namespace.

        Note that it is usually not necessary to explicitly call this method,
        since a connection is automatically established when an instance of
        this class is created. An example where it this method would be useful
        is when the application accepts multiple namespace connections.
        """
        environ = EnvironBuilder('/socket.io').get_environ()
        environ['flask.app'] = self.app

        if isinstance(headers, dict):
            for k, v in headers.items():
                environ['HTTP_' + str(k).upper()] = str(v)

        self.socketio.server._handle_eio_connect(self.sid, environ)
        if namespace is not None and namespace != '/':
            pkt = packet.Packet(packet.CONNECT, namespace=namespace)
            with self.app.app_context():
                self.socketio.server._handle_eio_message(self.sid,
                                                         pkt.encode())

单元测试的代码:

import unittest
from flask_socketio import test_client
from test_app import app, socket_io


class FlaskTestCase(unittest.TestCase):

    def setUp(self):
        self.app = app
        self.app.config['TESTING'] = True

        self.socket_io_client = socket_io.test_client(self.app, headers={"self_header": "test_header_content"})

    def test_socket_io(self):
        pass

    def tearDown(self):
        pass

if __name__ == '__main__':
    unittest.main()

原理是根据uwsgi的PEP333定义,environ中以HTTP_开头的变量,是客户端提供的HTTP请求头。

相关文章

  • Flask-SocketIO单元测试中创建连接时添加HTTP H

    在使用flask-socketio中,有时候需要在创建连接时检查HTTP Header中是否有相关的信息。但在fl...

  • gorm-V1-连接和建表

    1. 连接数据库 1.1 v1 版本 2 创建表 连接代码同上,main函数中添加创建代码如下: 添加一个结构体 ...

  • Spring Boot WebFlux(二):使用MongoDB

    实现 创建UserRepository 添加MongoDB的配置 单元测试 在单元测试的时候,我们使用Embedd...

  • Framework的制作流程

    1.新建Framework项目 2.删除原有的.h文件,创建与工程同名的类 在新建类.h中添加接口,.m中添加实现...

  • 单元测试

    单元测试参考 添加单元测试框架新建立项目时添加 如果新建项目时, 忘记添加, 在项目中添加 新建测试类 新建 Pe...

  • 简单的看一下render函数的设计

    h函数作为创建vnode对象的函数的封装, 在vnode创建时确定其flag 为了让h函数更灵活,我们可以添加参数...

  • Swift 与 OC 混合开发

    ①.先把OC代码拖到 Swift 工程中添加OC代码 ②.创建桥接文件创建桥接文件 ③. 在刚刚创建的.h文件中,...

  • Python 学习笔记 066

    单元测试 对函数进行单元测试 对类进行单元测试 文档测试 创建函数的解释和介绍 使用Telnet命令远程连接别人的...

  • glance服务介绍及配置swift作为后端存储

    镜像中的几种状态: 创建服务同名用户并添加admin权限: 创建服务: 创建endpoint:http://192...

  • XCode 8中使用UITest

    1: 在podfile中添加单元测试依赖库 1:在pod file添加依赖库 不添加单元测试会报file not ...

网友评论

      本文标题:Flask-SocketIO单元测试中创建连接时添加HTTP H

      本文链接:https://www.haomeiwen.com/subject/kmhqnxtx.html