Fundamentals 10 min read

WebSocket Protocol Overview and Practical Interface Testing with Python

This article introduces the WebSocket protocol, explains its principles and differences from HTTP, outlines typical real‑time application scenarios, and provides a step‑by‑step guide with code examples for testing WebSocket interfaces using Python, including request/response formats and automated test scripts.

FunTester
FunTester
FunTester
WebSocket Protocol Overview and Practical Interface Testing with Python

WebSocket is a TCP‑based application‑layer protocol standardized as RFC 6455 in 2011, with extensions in RFC 7936, and its API is defined by the W3C. It enables a persistent, full‑duplex connection after a single handshake, allowing servers to push data to clients without repeated request/response cycles.

Principle

The protocol establishes a direct, long‑lived connection between client and server, using frames for data transmission, which are ordered and do not require HTTP request messages after the handshake.

Comparison with HTTP

Both are TCP‑based application‑layer protocols.

Both use a request/response model for establishing the connection.

Error handling during connection setup is similar; WebSocket may return the same status codes as HTTP.

Both can transmit data over the network.

Differences include:

WebSocket defines additional header fields not used by standard HTTP.

The connection must be direct and cannot be forwarded by intermediaries.

After establishment, either side can send data at any time.

Data is transmitted in frames, eliminating the need for request messages.

Frames are ordered.

Typical application scenarios requiring high real‑time performance include social chat, bullet comments, multiplayer games, collaborative editing, live stock quotes, sports updates, video conferencing, location‑based services, online education, and smart home control.

WebSocket interface testing – practical example

Using a full‑stack project, the WebSocket endpoint /pinter/imserver/{userId} supports two main actions:

Interface Name

Type

URL

Parameters (JSON)

Match interface

websocket

/pinter/imserver/{userId}

{"type":"match","from":"sender","to":"system"}

Send chat message

websocket

/pinter/imserver/{userId}

{"msgId":"...","type":"normal","from":"sender","to":"teacherId","msg":"message content"}

Example request payload for matching a customer service representative:

{
  "type": "match",
  "from": "发送者",
  "to": "system"
}

Server response after a successful match:

{
  "code": "0",
  "from": "system",
  "msg": "cf2137234f3943e3898df8fcd14f099a__mtx",
  "msgId": "4c7ff9b3-ce6b-4891-8c14-41e0f45e0bd0",
  "timestamp": "1665630374482",
  "to": "admin",
  "type": "match"
}

Client sends a normal chat message:

{
  "type": "normal",
  "from": "admin",
  "to": "cf2137234f3943e3898df8fcd14f099a__mtx",
  "msg": "你好"
}

Server pushes a success receipt back to the client:

{
  "code": "0",
  "from": "system",
  "msg": "push success",
  "msgId": "130f4370-6b2b-4634-b3f1-59a9728eb8f1",
  "timestamp": "1665631227681",
  "to": "admin",
  "type": "receipt"
}

Teacher replies to the client:

{
  "code": "0",
  "from": "cf2137234f3943e3898df8fcd14f099a__mtx",
  "msg": "同学,你好,非常高兴为你服务,有什么需要我帮忙的呢?",
  "msgId": "8486956c-e804-42b9-bb9b-d1574f1ca23f",
  "timestamp": "1665631228807",
  "to": "admin",
  "type": "normal"
}

Python automation

Install the required third‑party library, then create websocket.yml in the config directory (content omitted for brevity) and add the client implementation in client.py (image omitted).

Encapsulate the WebSocket API layer in api/websoket_api/imserver_api.py (image omitted).

Write test cases in testcases/websocketapi/test_websocket_api.py:

# !/usr/bin python3
# encoding: utf-8
# @file     : test_websocket_api.py
# @author   : 沙陌 Matongxue_2
# @Time     : 2022-10-19 16:07
# @Copyright: 北京码同学

import json
import pytest

from api.websoket_api.imserver_api import ImServerApi

class TestImServerApi:
    kfid = ''  # global variable for the matched teacher id

    def setup_class(self):
        self.im = ImServerApi()  # create a WebSocket interface object

    # Test teacher matching
    def test_match(self):
        params = {
            "msgId": "111",
            "type": "match",
            "from": "shamo",
            "to": "system"
        }
        self.im.send(json.dumps(params))
        res = self.im.recv()
        res = json.loads(res)
        assert res['code'] == '0'
        self.__class__.kfid = res['msg']

    # Test sending a normal chat message
    def test_message(self):
        params = {
            "msgId": "111",
            "type": "normal",
            "from": "admin",
            "to": f"{self.__class__.kfid}",
            "msg": "你好"
        }
        self.im.send(json.dumps(params))
        res = json.loads(self.im.recv())
        pytest.assume(res['code'] == '0', f'期望值是0,实际结果是{res["code"]}')
        pytest.assume(res['msg'] == 'push success', f'期望值是0,实际结果是{res["msg"]}')
        # Receive teacher's reply
        res = json.loads(self.im.recv())
        pytest.assume(res['code'] == '0', f'期望值是0,实际结果是{res["code"]}')
        pytest.assume(res['msg'] == '同学,你好,非常高兴为你服务,有什么需要我帮忙的呢?', f'期望值是0,实际结果是{res["msg"]}')

    # Test sending a message with empty content
    def test_message_msgisnull(self):
        params = {
            "msgId": "111",
            "type": "normal",
            "from": "admin",
            "to": f"{self.kfid}",
            "msg": ""
        }
        self.im.send(json.dumps(params))
        res = json.loads(self.im.recv())
        pytest.assume(res['code'] == '1', f'期望值是1,实际结果是{res["code"]}')
        pytest.assume(res['msg'] == '消息内容为空', f'期望值是0,实际结果是{res["msg"]}')

The article concludes with a set of curated links to related testing topics and resources.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Real-TimePythonWebSocketAPIprotocol
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.