用python写一个带界面的接口测试工具
时间: 2023-10-09 20:12:08 浏览: 49
好的,下面是一个使用Python和PyQt5库编写的简单的接口测试工具GUI示例代码:
```python
import sys
import requests
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QLabel, QLineEdit, QTextEdit, QPushButton, QVBoxLayout, QHBoxLayout
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
# 创建主窗口部件
widget = QWidget()
self.setCentralWidget(widget)
# 创建窗口部件的子部件
self.url_label = QLabel('URL:')
self.url_edit = QLineEdit()
self.method_label = QLabel('Method:')
self.method_edit = QLineEdit()
self.headers_label = QLabel('Headers:')
self.headers_edit = QTextEdit()
self.params_label = QLabel('Params:')
self.params_edit = QTextEdit()
self.body_label = QLabel('Body:')
self.body_edit = QTextEdit()
self.response_label = QLabel('Response:')
self.response_edit = QTextEdit()
self.send_button = QPushButton('Send')
# 创建布局
main_layout = QVBoxLayout()
form_layout = QHBoxLayout()
form_layout.addWidget(self.url_label)
form_layout.addWidget(self.url_edit)
form_layout.addWidget(self.method_label)
form_layout.addWidget(self.method_edit)
main_layout.addLayout(form_layout)
main_layout.addWidget(self.headers_label)
main_layout.addWidget(self.headers_edit)
main_layout.addWidget(self.params_label)
main_layout.addWidget(self.params_edit)
main_layout.addWidget(self.body_label)
main_layout.addWidget(self.body_edit)
main_layout.addWidget(self.response_label)
main_layout.addWidget(self.response_edit)
main_layout.addWidget(self.send_button)
# 设置布局
widget.setLayout(main_layout)
# 设置窗口属性
self.setGeometry(300, 300, 800, 600)
self.setWindowTitle('API Test Tool')
# 绑定事件
self.send_button.clicked.connect(self.send_request)
def send_request(self):
url = self.url_edit.text()
method = self.method_edit.text()
headers = eval(self.headers_edit.toPlainText())
params = eval(self.params_edit.toPlainText())
body = self.body_edit.toPlainText()
if method == 'GET':
response = requests.get(url, headers=headers, params=params)
elif method == 'POST':
response = requests.post(url, headers=headers, params=params, json=eval(body))
else:
return
self.response_edit.setText(response.text)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
```
这个工具界面比较简单,包括了URL、Method、Headers、Params、Body和Response等几个常见的接口测试参数,用户可以在界面上填写参数,然后点击Send按钮,程序会发送请求并显示响应结果。需要注意的是,这个工具只是一个示例,实际使用时需要根据具体的需求进行修改和扩展。