簡單搭建UI自動化框架
阿新 • • 發佈:2021-08-04
1、環境:
語言:python
IDE:pycharn
測試工具:selenium+unittest+beautifulreport
測試頁面:某網路裝置
2、框架目錄:
3、下載chrome瀏覽器對應版本驅動:driver\chromedriver.exe
https://npm.taobao.org/mirrors/chromedriver
4、完成登入與登出的動作(話不多說、直接上程式碼)
瀏覽器驅動,放到common下:common\browser_engine.py
from selenium import webdriver from common.conf_manage import config_manager class BrowserEngine(object): def __init__(self): self.driver = webdriver.Chrome(executable_path=config_manager.CHROME_DRIVER) # Chrome瀏覽器驅動 # self.driver = webdriver.Edge(executable_path=config_manager.EDGE_DRIVER) # Edge瀏覽器驅動 browser_engine = BrowserEngine().driver
資料檔案:data\url.ini
[HOST]
host = http://1.1.1.1
[USERNAME]
username = admin
[PASSWORD]
password = admin
配置檔案管理:common\config_manage.py
import os from utils.time import dt_strftime class ConfigManager(object): # 專案目錄 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 頁面元素目錄 ELEMENT_PATH = os.path.join(BASE_DIR, 'page_element') # 配置檔案目錄 CSV_PATH = os.path.join(BASE_DIR, 'data') # driver檔案 CHROME_DRIVER = os.path.join(BASE_DIR, 'driver\\chromedriver.exe') EDGE_DRIVER = os.path.join(BASE_DIR, 'driver\\msedgedriver.exe') # 報告檔案 REPORT_FILE = os.path.join(BASE_DIR, 'report') REPORT_NAME = '**測試報告' # 截圖 IMG_FILE = os.path.join(BASE_DIR, 'img') @property def log_file(self): """日誌目錄""" log_dir = os.path.join(self.BASE_DIR, 'logs') if not os.path.exists(log_dir): os.makedirs(log_dir) return os.path.join(log_dir, '{}.log'.format(dt_strftime())) @property def ini_file(self): """配置檔案""" ini_file = os.path.join(self.BASE_DIR, 'data', 'url.ini') if not os.path.exists(ini_file): raise FileNotFoundError("配置檔案%s不存在!" % ini_file) return ini_file config_manager = ConfigManager() if __name__ == '__main__': print(config_manager.BASE_DIR) print(config_manager.IMG_FILE)
讀取ini檔案:common\readini.py
import configparser from common.conf_manage import config_manager class ReadIni(object): """讀取配置檔案""" def __init__(self): self.config = configparser.RawConfigParser() self.config.read(config_manager.ini_file, encoding='utf-8') def get(self, section, option): return self.config.get(section, option) @property def url(self): return self.get('HOST', 'host') @property def username(self): return self.get('USERNAME', 'username') @property def password(self): return self.get('PASSWORD', 'password') ini = ReadIni() if __name__ == '__main__': print(ini.url)
瀏覽器操作基類:page\web_page.py
from selenium.common.exceptions import TimeoutException
from common.browser_engine import browser_engine
from utils.logger import log
class WebPage(object):
def __init__(self):
self.driver = browser_engine
# self.driver = driver
def get_url(self, url):
"""
開啟網址
:param url: 網址
:return:
"""
self.driver.maximize_window()
self.driver.set_page_load_timeout(10)
try:
self.driver.get(url)
self.driver.implicitly_wait(10)
log.info("開啟網頁:%s" % url)
except TimeoutException:
raise TimeoutException("開啟%s超時" % url)
def refresh(self):
"""
重新整理頁面
:return:
"""
log.info("重新整理頁面")
self.driver.refresh()
self.driver.implicitly_wait(10)
web_page = WebPage()
if __name__ == '__main__':
web_page.get_url("http://172.30.12.183")
工具類:utils\logger.py
import logging
from common.conf_manage import config_manager
class Log:
def __init__(self):
self.logger = logging.getLogger()
if not self.logger.handlers:
self.logger.setLevel(logging.DEBUG)
# 寫入檔案
fh = logging.FileHandler(config_manager.log_file, encoding='utf-8')
fh.setLevel(logging.INFO)
# 輸出到控制檯
sh = logging.StreamHandler()
sh.setLevel(logging.INFO)
# 定義輸出的格式
formatter = logging.Formatter(self.fmt)
fh.setFormatter(formatter)
sh.setFormatter(formatter)
# 新增到handler
self.logger.addHandler(fh)
self.logger.addHandler(sh)
@property
def fmt(self):
return '%(levelname)s\t%(asctime)s\t[%(filename)s:%(lineno)d]\t%(message)s'
log = Log().logger
if __name__ == '__main__':
log.info('hello world')
工具類:utils\time.py
import datetime
def dt_strftime(fmt="%Y%m%d"):
"""
格式化時間
:param fmt "%Y%m%d %H%M%S
"""
return datetime.datetime.now().strftime(fmt)
if __name__ == '__main__':
print(dt_strftime("%Y%m%d%H%M%S"))
元素定位:page_element\ele_login_logout.py
class ElementLoginLogout:
UserName = 'username'
Password = 'pass_word'
Login = 'loginIn'
Admin = 'user_td'
Logout = '//*[@id="user_popup"]/div[2]/div/span[3]/a'
element_login_logout = ElementLoginLogout()
頁面操作:action\login_logout.py
from selenium.webdriver.common.by import By
from page_element.ele_login_logout import element_login_logout
from page.web_page import WebPage
import time
class LoginLogout(WebPage):
def s6_login(self, username, password):
driver = self.driver
driver.find_element(By.ID, element_login_logout.UserName).send_keys(username)
driver.find_element(By.ID, element_login_logout.Password).send_keys(password)
time.sleep(2)
driver.find_element(By.ID, element_login_logout.Login).click()
def s6_logout(self):
driver = self.driver
driver.switch_to.default_content()
driver.find_element(By.ID, element_login_logout.Admin).click()
driver.find_element(By.XPATH, element_login_logout.Logout).click()
driver.switch_to.alert.accept()
形成測試用例:test_function\test_login.py
import unittest
from action.login_logout import LoginLogout
from common.read_ini import ini
from utils.logger import log
class TestLoginLogout(unittest.TestCase):
def test_login(self):
login = LoginLogout()
login.get_url(ini.url)
login.s6_login(ini.username, ini.password)
log.info("登入")
def test_logout(self):
logout = LoginLogout()
logout.s6_logout()
log.info("退出")
執行測試例:test_suites\test_suites_login_logout.py
import unittest
from common.conf_manage import config_manager
from test_function.test_login import TestLoginLogout
from BeautifulReport import BeautifulReport as bf
if __name__ == '__main__':
suite = unittest.TestSuite()
suite.addTest(TestLoginLogout('test_login'))
run = bf(suite)
run.report(filename=config_manager.REPORT_NAME, description='測試', report_dir=config_manager.REPORT_FILE)
執行結果:
以上!