博客
关于我
Python selenium自动化测试框架实战 —— 登录测试案例
阅读量:799 次
发布时间:2023-03-06

本文共 7228 字,大约阅读时间需要 24 分钟。

基于Selenium的自动化测试框架构建与应用

作为一名从事软件测试工作的开发人员,你可能曾经尝试过 Selenium 这个强大的自动化测试工具,但在实际项目中却没有找到一个适合自己的测试框架,导致测试代码难以维护和扩展。本文将详细介绍一个基于 POM 模式、Selenium、Unittest 框架、ConfigParser 配置文件、SmtpLib 邮件发送以及 HTMLTestRunner 测试报告模块的完整自动化测试框架实现方案。

项目主要包含以下几个部分

1. 配置文件管理

配置文件是自动化测试项目的核心管理模块。在项目中,我们采用 configparser 库来管理测试环境的配置信息。通过读取配置文件,可以灵活配置测试环境的参数,如 URL、浏览器驱动路径、电子邮件服务器信息等。例如:

[base]url= https://www.example.combrowser= chrome

这样可以让测试代码更加灵活,方便进行多环境下的测试场景切换。

2. 浏览器操作代码

myunit.py 文件中,我们定义了浏览器操作的通用代码。通过 Unittest 框架,我们实现了测试用例的管理与执行。测试用例的初始化部分包括浏览器驱动的创建、隐式等待设置以及窗口最大化等操作。例如:

from selenium import webdriverfrom unittest import TestCaseclass MyTest(TestCase):    def setUp(self):        self.driver = webdriver.Chrome()        self.driver.implicitly_wait(10)        self.driver.maximize_window()        def tearDown(self):        self.driver.quit()

这个类可以作为其他测试类的基类,提供通用的浏览器操作功能。

3. 通用页面操作代码

base.py 文件中,我们定义了浏览器操作的通用功能模块。通过页面对象的方式,实现了元素定位、元素交互(如输入、点击、清除等操作)以及页面切换等功能。例如:

from selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.support.wait import WebDriverWaitimport osfrom configparser import ConfigParserclass Page(object):    path = os.path.dirname(os.path.abspath("."))    cfpath = os.path.join(path, 'autoparker/config/conf.ini')    conf = ConfigParser()    conf.read(cfpath)    url = conf.get('base', 'url')    def __init__(self, driver, url=url):        self.driver = driver        self.url = url    def open(self):        self.driver.get(self.url)    def find_element(self, *loc):        try:            WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located(loc))            return self.driver.find_element(*loc)        except:            print(f'页面中未找到 {loc} 元素')            raise    def find_elements(self, *loc):        return self.driver.find_elements(*loc)    def send_keys(self, loc, value):        self.find_element(*loc).send_keys(value)    def click(self, loc):        self.find_element(*loc).click()    def clear(self, loc):        self.find_element(*loc).clear()

这个类通过继承自定义页面类,实现了对页面元素的高效定位与操作。

4. 登录模块实现

loginpage.py 文件中,我们定义了通用的登录功能模块。通过继承自定义的 Page 类,我们实现了对用户名和密码的输入、登录按钮的点击以及登录提示信息的获取等功能。例如:

from selenium.webdriver.common.by import Byfrom time import sleepfrom objpage.base import Pageclass Login(Page):    username_loc = (By.NAME, 'accounts')    password_loc = (By.NAME, 'pwd')    login_button_loc = (By.XPATH, '/html/body/div[5]/div/form/fieldset/p/button')    login_error_loc = (By.XPATH, '//*[@id="common-prompt"]/p')    def login_username(self, username):        self.find_element(*self.username_loc).clear()        self.find_element(*self.username_loc).send_keys(username)    def login_password(self, password):        self.find_element(*self.password_loc).clear()        self.find_element(*self.password_loc).send_keys(password)    def login_button(self):        self.find_element(*self.login_button_loc).click()    def user_login(self, username, password):        self.open()        self.login_username(username)        self.login_password(password)        self.login_button()        sleep(2)    def login_error_text(self):        return self.find_element(*self.login_error_loc).text

这个类通过继承 Page 类,实现了对登录界面元素的精准定位与操作。

5. 公共元素操作代码

parker.py 文件中,我们定义了浏览器操作的通用功能模块。通过 Parker 类,我们实现了对浏览器操作的丰富功能,如隐式等待、元素定位、窗口切换、右键操作、拖拽操作、提交事件等。例如:

from selenium import webdriverfrom selenium.webdriver.common.action_chains import ActionChainsfrom selenium.webdriver.support.select import Selectclass Parker(object):    def __init__(self, browser='chrome'):        if browser == 'ie' or browser == 'internet explorer':            self.driver = webdriver.Ie()        elif browser == 'firefox' or browser == 'ff':            self.driver = webdriver.Firefox()        elif browser == 'chrome':            self.driver = webdriver.Chrome()        else:            raise Exception('没有找到浏览器,请输入"ie","chrome","ff"')        try:            self.driver = self.driver        except Exception:            raise NameError('没有找到浏览器,请输入"ie","chrome","ff"')    def wait(self, secs=5):        self.driver.implicitly_wait(secs)    def to_element(self, key):        if '->' not in key:            raise NameError('参数类型输入错误')        by = key.split('->')[0]        val = key.split('->')[1]        if by == 'id':            element = self.driver.find_element_by_id(val)        elif by == 'name':            element = self.driver.find_element_by_name(val)        elif by == 'class':            element = self.driver.find_element_by_class_name(val)        elif by == 'link_text':            element = self.driver.find_element_by_link_text(val)        elif by == 'xpath':            element = self.driver.find_element_by_xpath(val)        elif by == 'css':            element = self.driver.find_element_by_css_selector(val)        else:            raise NameError('请输入正确的定位方式:id,name,class,link_text,xpath,css')        return element

这个类通过简单的方式实现了对浏览器操作的丰富功能,极大地降低了代码的复杂度。

6. 邮件发送模块

send_email.py 文件中,我们定义了邮件发送功能模块。通过使用 smtplibemail 模块,我们实现了邮件的发送功能,支持邮件的内容和附件添加。例如:

import smtplibfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartimport configparserimport osdef sendEmail(file_path):    path = os.path.dirname(os.path.abspath("."))    cfpath = os.path.join(path, 'autoparker/config/conf.ini')    conf = configparser.ConfigParser()    conf.read(cfpath)    smtpserver = conf.get('emailqq', 'smtpserver')    sender = conf.get('emailqq', 'sender')    pwd = conf.get('emailqq', 'pwd')    receiver = []    email_to = conf.get('emailqq', 'receiver')    email_array = email_to.split(';')    for i in range(len(email_array)):        receiver.append(email_array[i])        with open(file_path, 'rb') as fp:        mail_body = fp.read()        msg = MIMEMultipart()        msg['From'] = sender        msg['To'] = ",".join(receiver)        msg['Subject'] = '我曾把完整的镜子打碎'        body = MIMEText(mail_body, 'html', 'utf-8')        msg.attach(body)        att = MIMEText(mail_body, 'html', 'utf-8')        att['Content-Type'] = 'application/octet-stream'        att['Content-Disposition'] = 'attachment; filename="test_result.html"'        msg.attach(att)        try:        smtp = smtplib.SMTP()        smtp.connect(smtpserver)        smtp.login(sender, pwd)    except:        try:            smtp = smtplib.SMTP_SSL(smtpserver, 465)            smtp.login(sender, pwd)        except:            raise NameError('邮件服务器配置错误,请检查SMTP服务器信息')    smtp.sendmail(sender, receiver, msg.as_string())    smtp.quit()    sendEmail('D:\\report.html')

这个函数通过读取配置文件,实现了邮件的发送功能,支持多个收件人,并支持附件的添加。

7. 主运行文件

main.py 文件中,我们实现了测试用例的执行和测试报告的生成。通过使用 HTMLTestRunner,我们实现了测试结果的可视化报告生成。例如:

import HTMLTestRunnerimport unittestfrom test_case.login import LoginTestfrom public.send_email import sendEmailif __name__ == '__main__':    testunit = unittest.TestLoader().loadTestsFromTestCase(LoginTest)    suite = unittest.TestSuite(testunit)    file_path = "D:\\html_report.html"    fp = open(file_path, 'wb')    runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title='登录测试', description='测试执行结果')    runner.run(suite)    fp.close()    sendEmail(file_path)

这个文件实现了测试用例的执行和测试报告的生成,支持测试结果的可视化展示。

结语

通过以上实现,我们构建了一个完整的自动化测试框架,涵盖了从配置文件管理到测试用例执行的各个环节。这个框架不仅支持多浏览器驱动的使用,还支持邮件的发送功能,适用于多种测试场景的需求。希望以上内容能为你提供一些思路和参考,帮助你快速搭建自己的自动化测试框架。

转载地址:http://fhafk.baihongyu.com/

你可能感兴趣的文章