首先,我们得知道PO模式是什么,P(Page)O(Object)
1.打开浏览器
2.输入网易云主页的网址
3.点击登陆按钮,等待页面跳转
4.点击同意协议,点击跳转qq登录
5 点击QQ账号密码登录
6输入账号密码,回到网易云音乐页面
我们可以先创建几个文件夹,base(用于存放父类) page(用来定位操作页面上的元素) data(用于存放测试数据) log(用于打印日志) report(用于存放测试报告) screenshot(用于页面截图存放) script(用于存放测试脚本) tools(放置测试报告模板) config(日志初始化) runsuite(执行测试套件) utils)(创建工具类)
base
from utils import DriverUtil
import logging
import time
import os
from config import BASE_DIR
class BasePage:
"""
对象库层-基类
"""
def __init__(self):
self.driver = DriverUtil.GetDriver()
def find_element(self, location):
logging.info("location={}".format(location))
return self.driver.find_element(location[0], location[1])
class BaseHandle:
"""
操作层-基类
"""
def input_text(self, element, text):
"""
在输入框里输入文本内容,先清空再输入
:param element: 要操作的元素
:param text: 要输入的文本内容
"""
element.clear()
element.send_keys(text)
def click_object(self,element):
"定位元素并点击"
element.click()
class BaseProxy:
"""
业务层-基类
"""
def __init__(self):
self.driver = DriverUtil.GetDriver()
def ScreenShot(self):
try:
t = time.strftime("%Y-%m-%d-%H-%M-%S")
print(t)
img_path = "{}/screenshot/-{}.png".format(BASE_DIR,t)
print(img_path)
self.driver.get_screenshot_as_file(img_path)
except BaseException as msg:
print("%s:截图失败!!!!!!!!!!!!!!" %msg)
def obtain_title(self):
self.driver.title()
# 获取当前句柄切换
def Windows_switch(self):
driver = DriverUtil.GetDriver()
handle = driver.window_handles
print(handle)
driver.switch_to_window(handle[1])
def Windows_switch_return(self):
driver = DriverUtil.GetDriver()
handle = driver.window_handles
driver.switch_to_window(handle[0])
page
import unittest
from base.base_page import BasePage, BaseHandle,BaseProxy
from utils import DriverUtil
from selenium.webdriver.common.by import By
import time
##登录网易云音乐
class login_page(BasePage):
def __init__(self):
super().__init__()
##点击登录按钮
self.login_one =(By.XPATH,"//a[@class='link s-fc3']")
##点击勾选服务条款
self.Check_the_service =(By.XPATH,"//input[@id='j-official-terms']")
##QQ登录
self.QQ_login =(By.LINK_TEXT,"QQ登录")
##账号密码登录
self.userpwd_login =(By.ID,"switcher_plogin")
##定位输入账号框
self.username =(By.ID,"u")
##定位输入密码框
self.password =(By.ID,"p")
##定位登录按钮
self.button =(By.ID,"login_button")
def find_login_one(self):
return self.find_element(self.login_one)
def find_Check_the_service(self):
return self.find_element(self.Check_the_service)
def find_QQ_login(self):
return self.find_element(self.QQ_login)
def find_userpwd_login(self):
return self.find_element(self.userpwd_login)
def find_username(self):
return self.find_element(self.username)
def find_password(self):
return self.find_element(self.password)
def find_button(self):
return self.find_element(self.button)
class Login_Handle(BaseHandle):
def __init__(self):
self.Login_Page = login_page()
def click_login_one(self):
self.click_object(self.Login_Page.find_login_one())
def click_Check_the_service(self,):
self.click_object(self.Login_Page.find_Check_the_service())
def click_QQ_login(self):
self.click_object(self.Login_Page.find_QQ_login())
def click_userpwd_login(self):
self.click_object(self.Login_Page.find_userpwd_login())
def input_username(self,user):
self.input_text(self.Login_Page.find_username(),user)
def input_password(self,pwd):
self.input_text(self.Login_Page.find_password(),pwd)
def click_button(self):
self.click_object(self.Login_Page.find_button())
class LoginProxy(BaseProxy):
def __init__(self):
super().__init__()
self.login_handle = Login_Handle()
#登录业务
def login_music(self,user,pwd):
music_handle=self.driver.current_window_handle
self.login_handle.click_login_one()
self.login_handle.click_Check_the_service()
self.login_handle.click_QQ_login()
time.sleep(1)
self.Windows_switch()
self.driver.switch_to.frame("ptlogin_iframe")
self.login_handle.click_userpwd_login()
self.login_handle.input_username(user)
self.login_handle.input_password(pwd)
self.login_handle.click_button()
self.driver.switch_to_window(music_handle)
self.driver.switch_to.frame("g_iframe")
time.sleep(2)
self.ScreenShot()
script
import unittest
from selenium.webdriver.common.by import By
import utils
import time
from page.A_login import LoginProxy
from utils import DriverUtil
from config import init_log_config
import logging
class TestLogin(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.driver = DriverUtil.GetDriver()
cls.login_proxy = LoginProxy()
@classmethod
def tearDownClass(cls):
time.sleep(3)
DriverUtil.QuitDriver()
def test_A_usmpwd_login(self):
driver = self.driver
self.login_proxy.login_music(账号,密码)
init_log_config()
logging.info("登录")
time.sleep(3)
config
import logging.handlers
import os
# 工程目录
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
def init_log_config():
"""
初始化日志配置
"""
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# 日志输出格式
fmt = "%(asctime)s %(levelname)s [%(filename)s(%(funcName)s:%(lineno)d)] - %(message)s"
formatter = logging.Formatter(fmt)
# 输出到控制台
sh = logging.StreamHandler()
sh.setFormatter(formatter)
logger.addHandler(sh)
# 输出到文件,每日一个文件
log_path = os.path.join("{}/log/WMSlog.txt").format(BASE_DIR)
fh = logging.handlers.TimedRotatingFileHandler(log_path, when='MIDNIGHT', interval=1,
backupCount=3, encoding="UTF-8")
fh.setFormatter(formatter)
logger.addHandler(fh)
utils
from selenium import webdriver
import time
# 驱动操作工具类
class DriverUtil:
_driver=None #驱动对象
_auto_quit = True
# 获取驱动,并完成初始化
@classmethod
def GetDriver(cls):
if cls._driver is None:
cls._driver=webdriver.Chrome()
cls._driver.maximize_window()
cls._driver.implicitly_wait(30)
cls._driver.get("https://music.163.com/")
return cls._driver
# 关闭驱动
@classmethod
def QuitDriver(cls):
if cls._auto_quit and cls._driver:
cls._driver.quit()
cls._driver = None
@classmethod
def set_auto_quit(cls, auto_quit):
"""设置是否自动退出驱动"""
cls._auto_quit = auto_quit
# 滚动条下拉致最下
def roll():
driver=DriverUtil.GetDriver()
js="window.scrollTo(0, 10000000)"
driver.execute_script(js)
#
run_suite
import logging
import time
import unittest
from script.test_A_login import TestLogin
from script.test_B_user_settinngs import Test_user_settings
from script.test_C_seek_play import Test_seek_play
from tools.HTMLTestRunner import HTMLTestRunner
from utils import DriverUtil
from config import init_log_config
##构建测试套件
try:
DriverUtil.set_auto_quit(False)
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestLogin))
time.sleep(3)
suite.addTest(unittest.makeSuite(Test_user_settings))
report_file = "./report/report{}.html".format(time.strftime("%Y%m%d-%H%M%S"))
with open(report_file, "wb") as f:
runner = HTMLTestRunner(f, title="自动化测试报告", description="Win10.Chrome")
runner.run(suite)
except Exception as e:
logging.exception(e)
finally:
DriverUtil.set_auto_quit(True)
DriverUtil.QuitDriver()