前言
软件测试之接口测试实验
一、Postman+Fiddler实验
Postman
Fiddler
二、Flask框架开发接口实验
导入Flask
pip install Flask
导入pymysql
pip install pymysql
SQL语句
select * from test
insert into test(number,name) values (%s,%s)
delete from test where number = %s and name = %s
update test set name = %s where number = %s
代码:
from flask import Flask,request,redirect, url_for
import pymysql
import json
app = Flask(__name__)
@app.route('/selectAccount', methods=['POST', 'GET'])
def selectAccount():
conn = pymysql.connect(host='localhost', user='root', passwd='123456', db='test', port=3306, charset='utf8')
cur = conn.cursor()
cur.execute('select * from test')
data = cur.fetchall()
data1 = []
result = {
'msg': '',
'code':0,
'data': []
}
for d in data:
data2 = {
'id':0,
'number':"",
'name':""
}
data2['id'] = d[0]
data2['number'] = d[1]
data2['name'] = d[2]
data1.append(data2)
result['data'] = data1
result['msg'] = "success"
conn.close()
return result
@app.route('/addAccount', methods=['POST', 'GET'])
def addAccount():
conn = pymysql.connect(host='localhost', user='root', passwd='123456', db='test', port=3306, charset='utf8')
cur = conn.cursor()
number = request.values.get("number")
name = request.values.get("name")
result = {
'msg': '',
'code': 0,
}
try:
cur.execute('insert into test(number,name) values (%s,%s)',(number,name))
conn.commit()
result['msg'] = '添加成功'
except:
conn.rollback()
result['msg'] = '添加失败'
result['code'] = -1
conn.close()
return result
@app.route('/deleteAccount', methods=['POST', 'GET'])
def deleteAccount():
conn = pymysql.connect(host='localhost', user='root', passwd='123456', db='test', port=3306, charset='utf8')
cur = conn.cursor()
number = request.values.get("number")
name = request.values.get("name")
result = {
'msg': '',
'code': 0,
}
try:
cur.execute('delete from test where number = %s and name = %s',(number,name))
conn.commit()
result['msg'] = '删除成功'
except:
conn.rollback()
result['msg'] = '删除失败'
result['code'] = -1
conn.close()
return result
@app.route('/updateAccount', methods=['POST', 'GET'])
def updateAccount():
conn = pymysql.connect(host='localhost', user='root', passwd='123456', db='test', port=3306, charset='utf8')
cur = conn.cursor()
number = request.values.get("number")
name = request.values.get("name")
result = {
'msg': '',
'code': 0,
}
try:
cur.execute('update test set name = %s where number = %s',(name,number))
conn.commit()
result['msg'] = '修改成功'
except:
conn.rollback()
result['msg'] = '修改失败'
result['code'] = -1
conn.close()
return result
if __name__ == '__main__':
app.run(debug=True)
三、Unittest+requests接口测试实验
代码:
import unittest
import os
import requests
import xlrd
from parameterized import parameterized
base_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
def pustRequests(path,query,method):
url ="http://127.0.0.1:5000%s"%path
number = ''
name = ''
if query != '':
number = query.split('&')[0].split('=')[1]
name = query.split('&')[1].split('=')[1]
print(number)
if method == 'post' or method == 'POST':
return requests.post(url=url,params={'number':number,'name':name}).json()
if method == 'get' or method =='GET':
return requests.get(url=url,params={'number':number,'name':name}).json()
def readExcel(file_name):
path = base_path + '\\FlaskTest\\' + file_name
work_book = xlrd.open_workbook(path)
sheets = work_book.sheet_names()
DatasList = []
for sheet in sheets:
sheets = work_book.sheet_by_name(sheet)
nrows = sheets.nrows
for i in range(0, nrows):
values = sheets.row_values(i)
DatasList.append(values)
title_list = DatasList[0]
content_list = DatasList[1:]
return content_list
class testCase(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
print('开始写入接口自动化测试用例')
@classmethod
def tearDownClass(cls) -> None:
print('自动化接口用例结束')
def setUp(self) -> None:
print()
print('开始本条接口用例')
def tearDown(self) -> None:
print('结束本条用例')
print()
@parameterized.expand(readExcel("AccountCase.xls"))
def test_account(self,case_name,path,query,method):
print("此次用例名为:" + str(case_name))
print("路径为:" + str(path))
print("参数为:" + str(query))
print("方法为:" + str(method))
print("返回结果为:" + str(pustRequests(path,query,method)))
if __name__ == '__main__':
load = unittest.TestLoader().loadTestsFromTestCase(TestLogin)
suite = unittest.TestSuite([load, ])
parameterized只能对于数组有效,对于Json不太管用,所以获取表中测试实例的代码注释的那一段就是多余的!!!
四、Robotframework框架实验
安装Robotframework 安装Robotframework-ride 启动ride
新建测试用例: 用例代码:
*** Settings ***
Library RequestsLibrary
Library Collections
*** Test Cases ***
addAccount
create session webindex http://127.0.0.1:5000
${para} create dictionary number=xxx name=xxx
${res} get request webindex /addAccount params=${para}
${json} to json ${res.text}
${code} get from dictionary ${json} code
${msg} get from dictionary ${json} msg
${msg} convert to String ${msg}
Should Be Equal As Strings 添加成功 ${msg}
selectAccont
create session webindex http://127.0.0.1:5000
${res} get request webindex /selectAccount
${json} to json ${res.text}
${code} get from dictionary ${json} code
${msg} get from dictionary ${json} msg
${msg} convert to String ${msg}
Should Be Equal As Strings 查找成功 ${msg}
updateAccount
create session webindex http://127.0.0.1:5000
${para} create dictionary number=xxx name=xxx
${res} get request webindex /updateAccount params=${para}
${json} to json ${res.text}
${code} get from dictionary ${json} code
${msg} get from dictionary ${json} msg
${msg} convert to String ${msg}
Should Be Equal As Strings 修改成功 ${msg}
deleteAccount
create session webindex http://127.0.0.1:5000
${para} create dictionary number=xxx name=xxx
${res} get request webindex /deleteAccount params=${para}
${json} to json ${res.text}
${code} get from dictionary ${json} code
${msg} get from dictionary ${json} msg
${msg} convert to String ${msg}
Should Be Equal As Strings 删除成功 ${msg}
运行结果:
五、持续集成实验(Jenkins)
安装
运行
实验三定时: 构建命令: PyCharm复制就行 实验四在实验三之后构建:
构建命令在ride运行的command,复制就行 运行效果:
POST是实验3的请求,GET是实验4的请求
六、Selenium(Python版本)
Win+R命令行输入pip install selenium
2、功能说明: Selenium是ThoughtWork专门为Web应用程序编写的一个验收测试工具。支持的浏览器包括IE、Mozilla Firefox、MozillaSuite等。框架底层使用JavaScript模拟真实用户对浏览器进行操作。 功能: (1)测试与浏览器的兼容性—测试你的应用程序看是否能够很好得工作在不同的浏览器和操作系统之上。 (2)测试系统功能—创建回归测试检验软件功能和用户需求。支持自动录制动作和自动生成.net、java、perl等不同语言的测试脚本。 3、使用Demo: 下载对应浏览器的驱动: 测试接口:
测试UI: 访问页面链接 获取对应id的输入框并进行输入 获取对应id的按钮并点击 使用代码:
driver = webdriver.Chrome(executable_path = chrome_driver)
url = ' http://localhost:8081/'
driver.get(url)
driver.find_element_by_id('account').send_keys('123456')
driver.find_element_by_id('login').click()
driver.find_element_by_xpath('/html/body/div/section/section/main/div[1]/div/div[3]/div[4]/div[2]/table/tbody/tr[1]/td[4]/div/button[1]').click()
当实在不知道怎么找到某个控件的时候,可以尝试xpath,或者说,直接用xpath就完了,谁用谁上瘾
指定控件的xpath的获取方法(谷歌为例): 在想要获取控件xpath的页面按下Fn+F12或者右键点击检查 选择指针工具,点击你想要的那个控件,会自动跳到该控件的html代码 右键相应的html代码,选择复制->复制完整XPath,就复制完毕了
|