提问人:Ziwdigforbugs 提问时间:11/16/2023 更新时间:11/17/2023 访问量:46
获取 WebSocket 消息进行测试
get a websocket message to test it
问:
我对使用 pyhton 测试 Web 套接字很陌生,我需要测试我无法更改的现有代码。代码使用的是 websocket-client===0.57.0,这是一个相当旧的版本。 我可能错过了一个简单的修复
以下是该类的 init 函数:
class Client():
def __init__(self):
# create websocket connection
self.ws = websocket.WebSocketApp(
url="wss://stream.********:9443/ws/********",
on_message=self.on_message,
on_error=self.on_error,
on_close=self.on_close,
on_open=self.on_open
)
我需要读取另一个测试 python 模块中 web-socket 接收的消息,然后断言数据值。我的问题是我不知道如何从课外访问它。现有代码可以通过以下方式访问类内的数据:
def on_message(self, message):
data = loads(message)
现在我想在一个单独的模块中使用pytest编写测试,这是我到目前为止不起作用的代码:
from **** import Client
import pytest
@pytest.fixture
def my_client():
return Client().ws
@pytest.mark.asyncio
async def test_url(my_client):
# how can I get the data in this code level???
# data = my_client??
答:
0赞
Jagdish Devarajan
11/16/2023
#1
若要访问类外部的 web-socket 接收的数据,可以在 Client 类中创建一个返回数据的新方法。
class Client():
def __init__(self):
# create websocket connection
self.ws = websocket.WebSocketApp(
url="wss://stream.********:9443/ws/********",
on_message=self.on_message,
on_error=self.on_error,
on_close=self.on_close,
on_open=self.on_open
)
self.data = None
def on_message(self, message):
self.data = loads(message)
def get_data(self):
return self.data
在上面的代码中,我使用了一个新方法,它返回 web-socket 接收的数据。可以从类外部调用此方法来访问数据。以下是在测试中使用它的方法:get_data
from **** import Client
import pytest
@pytest.fixture
def my_client():
return Client()
@pytest.mark.asyncio
async def test_url(my_client):
client = my_client
await client.ws.run_forever()
data = client.get_data()
# assert data values here
我从夹具中删除了 并在测试中创建了 Client 类的新实例。然后,我在对象上调用了该方法来启动 web-socket 连接。最后,我调用了该方法来访问 web-socket 接收的数据并断言数据值。.ws
my_client
run_forever
ws
get_data
评论
0赞
Ziwdigforbugs
11/18/2023
不,它不起作用,应该通过调用 ws 对象来获取数据。您只是将数据设置为 non,因此它会将 non 保留为值。
评论