项目实践
登陆项目测试
get_driver
import page
from selenium import webdriverclass GetDriver:driver = None@classmethoddef get_driver(cls):if cls.driver is None:cls.driver = webdriver.Edge()cls.driver.maximize_window()cls.driver.get(page.url)return cls.driver@classmethoddef quit_driver(cls):if cls.driver:cls.driver.quit()cls.driver = None
get_logger
import logging.handlersclass GetLogger:logger = None@classmethoddef get_logger(cls):if cls.logger is None:cls.logger = logging.getLogger()cls.logger.setLevel(logging.INFO)sh = logging.StreamHandler()th = logging.handlers.TimedRotatingFileHandler(filename="../log/login.log",when="midnight",interval=1,backupCount=3,encoding="utf-8")fmt = '%(asctime)s %(levelname)s [%(name)s] [%(filename)s(%(funcName)s:%(lineno)d)] - %(message)s'fm = logging.Formatter(fmt)sh.setFormatter(fm)th.setFormatter(fm)cls.logger.addHandler(sh)cls.logger.addHandler(th)return cls.logger
base
from selenium.webdriver.support.wait import WebDriverWait
import timefrom base.get_logger import GetLoggerlog = GetLogger().get_logger()class Base:def __init__(self, driver):log.info("正在初始化driver{}".format(driver))self.driver = driverdef base_find_element(self, loc, timeout=30, poll=0.5):log.info("正在查找元素{}".format(loc))return WebDriverWait(self.driver, timeout=timeout, poll_frequency=poll).until(lambda x: x.find_element(*loc))def base_click(self, loc):log.info("正在点击元素{}".format(loc))self.base_find_element(loc).click()def base_input(self, loc, value):log.info("正在给元素输入内容{}".format(loc))el = self.base_find_element(loc)# 清空log.info("正在给元素{}清空".format(loc))el.clear()# 输入log.info("正在给元素{}输入内容".format(loc))el.send_keys(value)def base_get_text(self, loc):# 注意:一定要返回元素的文本信息log.info("正在获取元素{}文本".format(loc))return self.base_find_element(loc).text# 截图def base_get_screen_shot(self):self.driver.get_screenshot_as_file("../image/{}.png".format(time.strftime("%Y_%m_%d %H_%M_%S")))# 封装判断元素是否存在def base_if_exist(self, loc):try:self.base_find_element(loc, timeout=2)log.info("元素{}存在".format(loc))return Trueexcept:log.info("元素{}不存在".format(loc))return False
__init__
from selenium.webdriver.common.by import By"""项目配置地址"""
url = "https://demo5.tp-shop.cn/""""以下为登录页面元素配置信息"""# 用户名
login_username = By.ID, "username"
# 密码
login_pwd = By.ID, "password"
# 验证码
login_verify_code = By.ID, "verify_code"
# 登录按钮
login_btn = By.CSS_SELECTOR, ".J-login-submit"
# 获取异常文本信息
login_err_info = By.CSS_SELECTOR, ".layui-layer-content"
# 点击异常提示框 按钮
login_err_btn_ok = By.CSS_SELECTOR, ".layui-layer-btn0"
# 安全退出
login_logout = By.PARTIAL_LINK_TEXT, "安全退出"# 登录链接
login_link = By.PARTIAL_LINK_TEXT, "登录"
page_login 继承Base
from base.base import Base
import pageclass PageLogin(Base):# 点击登录链接def page_click_login_link(self):self.base_click(page.login_link)# 输入用户名def page_input_username(self, username):self.base_input(page.login_username, username)# 输入密码def page_input_password(self, pwd):self.base_input(page.login_pwd, pwd)# 输入验证def page_input_verify_code(self, code):self.base_input(page.login_verify_code, code)# 点击登录按钮def page_click_login_btn(self):self.base_click(page.login_btn)# 获取异常提示信息def page_get_error_info(self):return self.base_get_text(page.login_err_info)# 点击异常信息框 确定def page_click_err_btn_ok(self):self.base_click(page.login_err_btn_ok)# 截图def page_get_img(self):self.base_get_screen_shot()# 点击 安全退出 --》退出使用def page_click_logout(self):self.base_click(page.login_logout)# 判断是否登录成功def page_is_login_success(self):return self.base_if_exist(page.login_logout)# 判断是否退出成功def page_is_logout_success(self):return self.base_if_exist(page.login_link)# 组合业务方法def page_login(self, username, pwd,code):self.page_input_username(username)self.page_input_password(pwd)self.page_input_verify_code(code)self.page_click_login_btn()
数据准备
json:
{"login_001":{"username":"138000011112","password":"123456","verify_code":"8888","expect_result":"账号不存在!","success": false},"login_002":{"username":"13800001111","password":"1234567","verify_code":"8888","expect_result":"密码错误!","success": false},"login_003":{"username":"","password":"123456","verify_code":"8888","expect_result":"用户名不能为空!","success": false},"login_004":{"username":"13800001111","password":"","verify_code":"8888","expect_result":"密码不能为空!","success": false},"login_005":{"username":"13800001111","password":"123456","verify_code":"","expect_result":"验证码不能为空!","success": false},"login_006":{"username":"13800001111","password":"123456","verify_code":"8888","expect_result":"安全退出","success": true}
}
txt:
138000011112,123456,8888,账号不存在!,false
13800001111,1234567,8888,密码错误!,false
,123456,8888,用户名不能为空!,false
13800001111,,8888,密码不能为空!,false
13800001111,123456,,验证码不能为空!,false
13800001111,123456,8888,安全退出,true
数据驱动方法
json:
# 导包
import jsondef read_json(filename):filepath = "../data/" + filename# 打开文件并调用 load方法with open(filepath, "r", encoding="utf-8")as f:return json.load(f)
txt:
def read_txt(filename):filepath = "../data/" + filenamewith open(filepath, "r", encoding="utf-8")as f:return f.readlines()
业务层
# 导包
import unittest
from time import sleepfrom base.get_driver import GetDriver
from page.page_login import PageLogin
from parameterized import parameterized
from tool.read_json import read_json
from tool.read_txt import read_txt
from base.get_logger import GetLoggerlog = GetLogger().get_logger()def get_data():arr = []for data in read_json("login.json").values():arr.append((data.get("username"),data.get("password"),data.get("verify_code"),data.get("expect_result"),data.get("success")))return arr # 注意:必须进行return 返回# def get_data():
# arr = []
# for data in read_txt("login.txt"):
# arr.append(tuple(data.strip().split(",")))
# return arr# 新建测试类
class TestLogin(unittest.TestCase):login = None@classmethoddef setUpClass(cls):try:# 实例化 获取页面对象 PageLogincls.login = PageLogin(GetDriver().get_driver())# 点击登录连接cls.login.page_click_login_link()except Exception as e:log.error(e)# tearDown@classmethoddef tearDownClass(cls):sleep(3)# 关闭 driver驱动对象GetDriver().quit_driver()def tearDown(self):self.login.driver.refresh()# 登录测试方法@parameterized.expand(get_data())def test_login(self, username, pwd, code, expect_result, success):# 调用登录方法self.login.page_login(username, pwd, code)if success:try:# 判断安全退出是否存在self.assertTrue(self.login.page_is_login_success())# 点击退出self.login.page_click_logout()try:# 判断登录是否存在self.assertTrue(self.login.page_is_logout_success)except:# 截图self.login.page_get_img()# 点击登录连接self.login.page_click_login_link()except Exception as e:# 截图self.login.page_get_img()log.error(e)else:# 获取登录提示信息msg = self.login.page_get_error_info()try:# 断言self.assertEqual(msg, expect_result)except AssertionError:# 截图self.login.page_get_img()# 点击 确认框self.login.page_click_err_btn_ok()
生成测试报告
from tool.HTMLTestRunner import HTMLTestRunner
import unittestsuite = unittest.defaultTestLoader.discover("./", "test_login.py")
# 网页要wb
with open("../report/report_html.html", "wb") as f:HTMLTestRunner(stream=f).run(suite)