接口测试 给大佬们,有使用 Python 测试 thfift 协议接口的库吗?

zhang · 2023年03月30日 · 最后由 LTV 回复于 2023年04月01日 · 6143 次阅读

之前公司用的是 Dubbo 协议的接口,也有 Python 专门的测试 dubbo 协议的库,也看到了各种对 dubbo 的封装,
但是当前公司使用的是 thfift 协议,目前有个 thfift 文件,怎么实现 Python 调用 thfift 接口呢?
试了各种神奇的方法,好像都不行额,求助各位打咯啊

共收到 4 条回复 时间 点赞

以下是一些关于如何使用 Thrift 的简单步骤:

安装 Thrift
可以使用 pip 安装 Thrift:

pip install thrift
编写 thrift 文件
在 thrift 文件中定义服务接口和数据结构,例如:

namespace py my.test

typedef i32 UserId

struct User {
1: UserId id,
2: string name,
3: string email
}

service UserService {
User getUser(1: UserId id),
void addUser(1: User user)
}
生成 Python 代码
使用 Thrift 的命令行工具生成 Python 客户端代码:

thrift -r --gen py my_test.thrift
这将生成一个名为 gen-py 的目录,其中包含了自动生成的 Python 代码文件。

编写测试脚本
在 Python 中,导入自动生成的代码,并创建 Thrift 客户端:

import sys
sys.path.append('gen-py')

from my.test import UserService
from my.test.ttypes import User

from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol

连接 Thrift 服务

transport = TSocket.TSocket('localhost', 9090)
transport = TTransport.TBufferedTransport(transport)
protocol = TBinaryProtocol.TBinaryProtocol(transport)
client = UserService.Client(protocol)

打开连接

transport.open()

调用服务接口

user = client.getUser(123)

关闭连接

transport.close()
这是一个简单的示例,其中通过 Thrift 客户端调用了 getUser 接口。在实际使用中,还需要根据需要编写更详细的测试代码。

希望这些信息能对你有所帮助。

ccf 回复

from thrift.transport import TSocket 这一行要注意,如果公司封装过 http,需要换成 THttpClient

MeterSphere 有 thrift 插件,可以去官网咨询看看

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册