测开之路六十六:UI测试平台之处理逻辑和蓝图添加到程序入口
from selenium import webdriver
from common import get_case_id
from common.mongo import Mongo
class Logic(object):
""" 每一个方法名对应前端的操作的元素,方便反射 """
def __init__(self):
self.mongo = Mongo()
def browser(self, params):
""" 打开网页 """
url = params.get('value', None)
self.driver.get(url)
def find(self, params):
""" 查找元素 接收选择器和元素内容"""
selector = params.get('selector', None)
value = params.get('value', None)
return self.driver.find_element(selector, value)
def send(self, element, params):
""" 输入内容 """
text = params.get('value', "默认值")
element.send_keys(text)
def click(self, element, params):
""" 点击操作 """
element.click()
def close(self):
""" 关闭浏览器 """
self.driver.quit()
def execute(self, data):
""" 执行测试,把前端传过来的指令映射为selenium的操作方法 """
# 防止每次调logic都初始化driver,这里放到执行时才初始化driver
self.driver = webdriver.Chrome()
# 取data的commands(所有的元素和操作的dict)
'''
{'casename': 'zz',
'commands':
[
{'command': 'browser', 'parameter': {'value': 'http://127.0.0.1:8000/automation/create'}},
{'command': 'find', 'parameter': {'selector': 'xpath', 'value': '//*[@id="command"]'}}
]}
'''
commands = data.get("commands")
# {'command': 'find', 'parameter': {'selector': 'xpath', 'value': '//*[@id="command"]'}}
element = None
for command in commands:
print(command)
# print(command['command'])
# print(command['parameter'])
cmd = command['command'] # 获取操作方法,对应selenium的方法
params = command['parameter'] # 获取参数:元素、操作对应的值
print(f"run command: [{cmd}] with param: [{params}] and element: [{element}]")
if element:
# 第二步,拿到element,对元素执行相应的操作
element = getattr(self, cmd)(element, params)
else:
# 第一步,element为空,查找元素并返回
element = getattr(self, cmd)(params) # 把操作方法反射为selenium的方法,传入params对应的参数
self.close()
def save(self, data):
""" 保存功能 """
data.setdefault('_id', get_case_id())
self.mongo.insert("2019", "automation", data)
return data['_id']
def trigger(self, data):
""" 触发执行测试,用于持续集成 """
id = data.get('id')
cases = list(self.mongo.search("2019", "automation", {'_id': id}))
print(cases[0])
self.execute(cases[0])
from flask import Flask
from interface import interface
from automation import automation
app = Flask(__name__)
app.register_blueprint(interface)
app.register_blueprint(automation)
if __name__ == '__main__':
app.run(
host="0.0.0.0",
port=8000,
debug=True,
)
讨论群:249728408