1、环境:

语言:python

IDE:pycharn

测试工具:selenium+unittest+beautifulreport

测试页面:某网络设备

2、框架目录:

简单搭建UI自动化框架_配置文件

 

3、下载chrome浏览器对应版本驱动:driver\chromedriver.exe

 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)


执行结果:

简单搭建UI自动化框架_chrome_02

 

以上!