cookie操作
cookie操作 def login(self): self.driver.get("https://......").. self.l.login_element() # 登录函数 sleep(5) # 必须睡眠5秒,否则获取不到登陆后的cookie cookie = self.driver.get_cookies() # 获取cookie write_file("cookie", json.dumps(cookie)) # 写入到文件中 def gotoproject(self): cookie = json.loads(read_file("cookie")) # 读取文件中的cookie self.driver.get( "https://........") # 直接访问首页 for c in cookie: 循环cookie dict = {} dict["name"] = c["name"] dict["value"] = c["value"] self.driver.add_cookie(dict) # 添加cookie # 涮新页面 self.driver.refresh() self.l.goto_project() # 进入首页成功 sleep(3)
基础层: base 用来封装selenium原生方法
baseutil.py: 初始化
import unittestclass BaseUtil(unittest.TestCase): def setUp(self): global driver # 打开浏览器 self.driver = webdriver.Chrome() driver = self.driver # 加载网页 driver.get("http://www.baidu.com") def tearDown(self): pass
basepage.py
import timefrom selenium import webdriver# 基础层from selenium.webdriver.support.select import Selectclass BasePage: def __init__(self,driver): self.driver = driver # 定位元素关键字 def locat_element(self, loc): return self.driver.find_element(*loc) # 设置值的关键字 def send_keys(self, loc, value): self.locat_element(loc).send_keys(value) # 单击的关键字 def click(self, loc): self.locat_element(loc).click() # 进入框架的关键字 def goto_frame(self, frame_name): self.driver.switch_to.frame(frame_name) # 出框架的关键字 def quit_frame(self): self.driver.switch_to.default_content() # 封装选中下拉框关键字 def choice_select(self, loc, value): sel = Select(self.locat_element(loc)) # 第三步,定位下拉框元素 sel.select_by_value(value) # 根据value定位(推荐) # 获取文本值 def get_value(self, loc): return self.locat_element(loc).text # 截屏 def getScreenShots(self, strInfo): # 获取一个时间字符串用于给图片命名(区分每一张图片的截取时间) t = time.strftime("%Y%m%d%H%M%S", time.localtime()) self.driver.get_screenshot_as_file("../screen_shots/" + strInfo + t + ".jpg")
页面对象层: 页面的元素和操作(一个页面一个文件)
login_page.py
# 页面对象层from selenium.webdriver.common.by import Byfrom web_data.test_03_pom.base.base_page import BasePageclass LoginPage(BasePage): # 1. 页面的元素 username_loc = (By.NAME, "username") password_loc = (By.NAME, "password") submit_loc = (By.XPATH, '//input[@value="登 录"]') tuichu_loc = (By.LINK_TEXT, "首页") # 2. 页面的动作 def login_element(self, username="admin", password="123456"): self.send_keys(LoginPage.username_loc, username) # 输入用户名 self.send_keys(LoginPage.password_loc, password) # 输入密码 self.click(LoginPage.submit_loc) # 点击 # 获取元素内容,进行断言使用 def get_except_result(self): return self.get_value(LoginPage.tuichu_loc)
测试用例层: testcase 准备测试用例和数据
import unittestfrom ddt import ddt, data, unpackfrom web_data.test_03_pom.base.BaseUtil import BaseUtilfrom web_data.test_03_pom.common.read_excel import ExcelUtil@ddtclass TestCase(BaseUtil): @data(*ExcelUtil().read_excel()) # 拆包成 [],[],[] @unpack # 解包后需要多个参数接收 def test_01_login(self, index, user, pwd): print(index, user, pwd) '''登录''' from web_data.test_03_pom.pageobject.login_page import LoginPage lg = LoginPage(self.driver) lg.login_element(user, pwd) print(lg.get_except_result()) # 断言 if index == 1: self.assertEqual(lg.get_except_result(), "首页")if __name__ == '__main__': unittest.main()
数据驱动层: 读取测试数据excel
import osimport openpyxlclass ExcelUtil: # 获取项目路径 def get_object_path(self): return os.path.abspath(os.path.dirname(__file__)).split("common")[0] def read_excel(self): # 加载excel工作薄 wb = openpyxl.load_workbook(self.get_object_path() + "/data/login.xlsx") # 获取sheet对象 sheet = wb["Sheet1"] # 获取excel的行数和列数 # print(sheet.max_row, sheet.max_column) # 循环 all_list = [] for rows in range(2, sheet.max_row + 1): # 循环最大行 temp_list = [] for cols in range(1, sheet.max_column + 1): # 循环最大列 temp_list.append(sheet.cell(rows, cols).value) # 添加行 # print(sheet.cell(rows, cols).value) all_list.append(temp_list) return all_list # 返回格式 [[ ],[ ],[ ]]if __name__ == '__main__': ExcelUtil().read_excel()
5. 网上下载: HTMLTestRunner.py 用于生成html报告
# -*- coding: utf-8 -*-"""A TestRunner for use with the Python unit testing framework. Itgenerates a HTML report to show the result at a glance.The simplest way to use this is to invoke its main method. E.g. import unittest import HTMLTestRunner ... define your tests ... if __name__ == '__main__': HTMLTestRunner.main()For more customization options, instantiates a HTMLTestRunner object.HTMLTestRunner is a counterpart to unittest's TextTestRunner. E.g. # output to a file fp = file('my_report.html', 'wb') runner = HTMLTestRunner.HTMLTestRunner( stream=fp, title='My unit test', description='This demonstrates the report output by HTMLTestRunner.' ) # Use an external stylesheet. # See the Template_mixin class for more customizable options runner.STYLESHEET_TMPL = '来源地址:https://blog.csdn.net/m0_58250910/article/details/127594194