天天看點

python+selenium+unittest基于po架構實作登入網易雲音樂

首先,我們得知道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()