You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在类的方法中获取Pytest Fixture的ws连接对象?

解决方案

问题根源

  1. 使用global ws共享连接对象不符合pytest的依赖注入设计,类无法直接访问该全局变量导致NameError。
  2. @pytest.mark.usefixture(name=setup)用法错误:name参数需传入字符串形式的fixture名称,且该装饰器仅会触发fixture执行,不会将fixture对象注入类中。

正确实现方式

步骤1:修改fixture,返回WebSocket连接对象

放弃global,改为在fixture中yield连接对象,让pytest的依赖注入机制管理它:

# conftest.py
@pytest.fixture(scope="session", autouse=True)
def setup(server):
    # 根据server参数创建对应连接
    if server == "Test1":
        ws = create_connection(base_class.server1)
    elif server == "Test2":
        ws = create_connection(base_class.server2)
    elif server == "Test3":
        ws = create_connection(base_class.server3)
    print("Websocket Connection Established successfully")
    yield ws  # 返回连接对象供其他用例/类使用
    ws.close()
    print("Websocket Connection Closed successfully")

步骤2:调整ABC类,通过构造函数接收连接对象

让POM类依赖连接对象,通过初始化参数传入:

# 单独的POM文件
import json

class ABC:
    def __init__(self, ws):
        self.ws = ws  # 将连接对象保存为实例属性

    def response(self, status):
        self.ws.send(json.dumps([3, 12345, {"status": f'{status}'}]))

步骤3:在测试用例中注入fixture并传递给POM实例

测试用例通过参数注入fixture,再将连接对象传给ABC类实例:

# 测试文件
def test_case1(setup):
    tc = ABC(setup)  # 将fixture返回的连接对象传入
    tc.response("Accepted")

补充说明

  • 这种方式遵循pytest的依赖注入设计,避免了全局变量的弊端,同时符合POM模式中类依赖外部资源的合理逻辑。
  • 如果需要在多个测试用例中复用ABC实例,可以再封装一个fixture来创建ABC对象:
    @pytest.fixture(scope="function")
    def abc(setup):
        return ABC(setup)
    
    测试用例直接使用abc fixture即可:
    def test_case1(abc):
        abc.response("Accepted")
    

内容的提问来源于stack exchange,提问作者AK1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 16:40:03