Page Object是Selenium自动化测试项目开发实践的最佳设计模式之一,通过对界面元素的封装减少冗余代码,同时在后期维护中,若元素定位发生变化,只需要调整页面元素封装的代码,提高测试用例的可维护性。

  本项目以163邮箱登录为例,163登录脚本(非PO模式)请查看博客中的随笔信息。

1、项目目录结构及相关介绍

test_programe 测试项目

  • driver:用于存放驱动
  • mail:用于存放163登录项目的测试用例、测试报告以及测试数据等
  • run_all_test.py:用于运行项目自动化用例

mail目录

  • data:存放测试数据
  • report:存放HTML测试不报告,其中该目录下的image目录用于存放测试过程中的截图
  • test_case:用于存放测试用例

test_case目录

  • model:存放配置函数及公共类
  • page_object:用于存放页面对象
  • login_case.py:测试对象用例

2、编写公共模块:

编写驱动文件...\test_programe\mail\test_case\model\driver.py

1 from selenium.webdriver importRemote2 from selenium importwebdriver3 #启动浏览器驱动
4 defbrowser():5     driver =webdriver.Chrome()6     '''
7 #可以启动到远程主机中,运行自动化测试8 host = '127.0.0.1:4444' #运行主机:端口号(本机默认:127.0.0.1:4444)9 dc = {'browserName': 'chrome'}  #指定浏览器10 driver = Remote(command_execute='http://' + host + '/wd/hub',11 desired_capabilities=dc)12     '''
13     returndriver14 '''
15 #用于测试该脚本是否有效16 if __name__ == '__main__':17 dr = browser()18 '''

编写测试公共类...\test_programe\mail\test_case\model\myunit.py

from time importsleepfrom .function importinsert_imgimportunittestfrom .driver importbrowserclassMyTest(unittest.TestCase):defsetUp(self):self.driver=browser()self.driver.implicitly_wait(10)self.driver.maximize_window()deftearDown(self):self.driver.quit()

myunit.py

定义截图函数...\test_programe\mail\test_case\model\function.py

1 from selenium importwebdriver2 importos3 #截图函数
4 definsert_img(driver, file_name):5     base_dir = os.path.dirname(os.path.dirname(__file__))6     #print(base_dir)
7     base_dir =str(base_dir)8     #print(base_dir)
9     base_dir = base_dir.replace('\\','/')10     #print(base_dir)
11     base = base_dir.split('/mail')[0]12     #print(base)
13     file_path = base + '/mail/report/image/' +file_name14 driver.get_screenshot_as_file(file_path)15
16 '''
17 #用于验证该脚本是否有效18 if __name__ == '__main__':19 driver = webdriver.Chrome()20 driver.get('http://www.baidu.com')21 insert_img(driver, 'baidu.jpg')22 driver.quit()23 '''

function.py

3、编写Page Object

创建基础类...\test_programe\mail\test_case\page_object\base.py

1 from selenium importwebdriver2 from selenium.webdriver.common.by importBy3 from time importsleep4 importunittest5 #基本层
6 classBase(object):7
8
9     def __init__(self, driver, base_url = 'http://mail.163.com'):10         self.driver =driver11         self.base_url =base_url12         self.timeout = 30
13
14     def_open(self, url):15         url_ = self.base_url +url16         #print(url_)
17 self.driver.maximize_window()18 self.driver.get(url_)19         sleep(2)20         assert self.driver.current_url == url_, 'Did ont land on %s' %url_21
22     defopen(self):23 self._open(self.url)24
25     #*参数个数不是固定的(By.ID, 'kw')
26     def find_element(self, *loc):27         return self.driver.find_element(*loc)28
29     defiframe(self, iframeid):30         returnself.driver.switch_to.frame(iframeid)31
32     defiframe_out(self):33         returnself.driver.switch_to.default_content()34
35     

View Code

创建163邮箱登录对象类...\test_programe\mail\test_case\page_object\login_page.py

1 from selenium.webdriver.common.action_chains importActionChains2 from selenium.webdriver.common.by importBy3 from time importsleep4 from .base importBase5
6 #页面对象(PO)登录页面
7 classLoginPage(Base):8     url = '/'
9     login_iframe_loc = 'x-URS-iframe'
10     login_username_text_loc = (By.NAME, 'email')11     login_password_text_loc = (By.NAME, 'password')12     login_button_loc = (By.ID, 'dologin')13     login_erro_hint_loc = (By.CLASS_NAME, 'ferrorhead')14
15     #把每一个元素封装成一个方法
16     deflogin_iframe(self):17 self.iframe(self.login_iframe_loc)18
19     deflogin_iframe_out(self):20 self.iframe_out()21
22     deflogin_username(self, text):23         self.find_element(*self.login_username_text_loc).send_keys(text)24
25     deflogin_password(self, text):26         self.find_element(*self.login_password_text_loc).send_keys(text)27
28     deflogin_button(self):29         self.find_element(*self.login_button_loc).click()30
31     deflogin_error_hint(self):32 self.login_iframe()33         return self.find_element(*self.login_erro_hint_loc).text34 self.login_iframe_out()35
36     deflogin_action(self, username, password):37 self.login_iframe()38 self.login_username(username)39 self.login_password(password)40 self.login_button()41         self.login_iframe_out()

login_page.py

创建163邮箱登录成功后对象类...\test_programe\mail\test_case\page_object\mail_page.py

1 from selenium.webdriver.common.action_chains importActionChains2 from selenium.webdriver.common.by importBy3 from time importsleep4 from .base importBase5
6 classMailPage(Base):7     url = '/'
8     login_success_user_loc = (By.ID, 'spnUid')9
10     deflogin_success_user(self):11         return self.find_element(*self.login_success_user_loc).text

mail_page.py

4、编写测试用例

创建mail登录类...\test_programe\mail\test_case\login_case.py

1 from time importsleep2 importunittest, random, sys3 from model importmyunit, function4 from page_object.login_page importLoginPage5 from page_object.mail_page importMailPage6 sys.path.append('./model')7 sys.path.append('./page_obj')8
9 classLoginTest(myunit.MyTest):10
11     deftest_login_user_pwd_null(self):12         '''用户名、密码为空登录'''
13         po =LoginPage(self.driver)14 po.open()15         po.login_action('','')16         sleep(2)17         self.assertEqual(po.login_error_hint(),'请输入帐号')18         function.insert_img(self.driver, 'user_pwd_null.jpg')19
20     deftest_login_pwd_null(self):21         '''密码为空登录'''
22         po =LoginPage(self.driver)23 po.open()24         po.login_action('abc','')25         sleep(2)26         self.assertEqual(po.login_error_hint(),'请输入密码')27         function.insert_img(self.driver, 'pwd_null.jpg')28
29     deftest_login_user_pwd_error(self):30         '''用户名或密码错误'''
31         po =LoginPage(self.driver)32 po.open()33         character = random.choice('zyxwvutsrqponmlkjihgfedcba')34         username = "test" +character35         po.login_action(username,"$#%#")36         sleep(2)37         #print(po.login_error_hint())
38         self.assertEqual(po.login_error_hint(),'帐号或密码错误')39         function.insert_img(self.driver, "user_pwd_error.jpg")40
41     deftest_login_success(self):42         '''用户名、密码正确,登录成功'''
43         po =LoginPage(self.driver)44 po.open()45         user = "ldq791918813"
46         po.login_action(user,"xiuxiu060801zhu")47         sleep(2)48         po2 =MailPage(self.driver)49         #print(po2.login_success_user())
50         self.assertEqual(po2.login_success_user(),user+"@163.com")51         function.insert_img(self.driver, "success.jpg")

login_case.py

5、执行测试用例

创建用例执行代码...\test_programe\

1 importunittest, time2 from HTMLTestRunner importHTMLTestRunner3 from email.mime.text importMIMEText4 from email.header importHeader5 importsmtplib, os6
7 #发送测试报告,需要配置你的邮箱账号
8 defsend_mail(file_new):9     f = open(file_new, 'rb')10     mail_body =f.read()11 f.close()12     msg = MIMEText(mail_body, 'html', 'utf-8')13     msg['Subject'] = Header("自动化测试报告", 'utf-8')14     msg['From']= 'ldq791918813@163.com'
15     msg['To']= '791918813@qq.com'
16     smtp =smtplib.SMTP()17     smtp.connect("smtp.163.com")18     smtp.login("ldq791918813@163.com", "密码")19     smtp.sendmail("ldq791918813@163.com","791918813@qq.com",msg.as_string())20 smtp.quit()21     print('email has send out!')22
23 #查找测试报告目录,找到最新生成的测试报告文件
24 defnew_report(testreport):25     lists =os.listdir(testreport)26     lists.sort(key=lambda fn: os.path.getmtime(testreport + '\\' +fn))27     file_new = os.path.join(testreport, lists[-1])28     print(file_new)29     returnfile_new30
31 #指定测试用例为当前文件夹下的test_case目录
32 test_dir = './mail/test_case'
33 test_report = 'D:\\sublimePython\\test_programe\\mail\\report'
34 discover = unittest.defaultTestLoader.discover(test_dir, pattern = '*_case.py')35
36 if __name__ == "__main__":37
38     now = time.strftime("%Y-%m-%d %H_%M_%S")39     filename = test_report + '/' + now + 'result.html'
40     fp = open(filename, 'wb')41     #runner = unittest.TextTestRunner()
42     runner = HTMLTestRunner(stream=fp,43                             title='测试报告',44                             description="运行环境:windows 7, Chrome")45 runner.run(discover)46 fp.close()47
48     new_report =new_report(test_report)49     send_mail(new_report)

run_all_test.py

6、HTML测试报告:

7、截图信息:

转载于:https://www.cnblogs.com/diaosicai/p/6370321.html

Page Object设计模式实践相关推荐

  1. 18、Page Object 设计模式

    Page Object 设计模式的优点如下: 减少代码的重复. 提高测试用例的可读性. 提高测试用例的可维护性, 特别是针对 UI 频繁变化的项目. 当你针对网页编写测试时,你需要引用该网页中的元素, ...

  2. ide循环执行用例 selenium_Selenium Web自动化Page Object设计模式——循环执行测试用例...

    继续优化上一篇博客的设计 Selenium Web自动化Page Object设计模式--driver初始化 https://www.cnblogs.com/Ravenna/p/14172411.ht ...

  3. java page object_Selenium+java - Page Object设计模式

    前言 Page Object(页面对象)模式,是Selenium实战中最为流行,并且被自动化测试同学所熟悉和推崇的一种设计模式之一.在设计测试时,把页面元素定位和元素操作方法按照页面抽象出来,分离成一 ...

  4. Page object设计模式

    网上看了很多文章,充斥了大量代码.理解起来不容易,在此就我的理解谈谈PageObject设计模式到底是什么东西. 所谓的Page object模式,主要是编写不同层级的脚本,然后一层一层的继承来完成对 ...

  5. python+ seleniumAPPium自动化 page Object 设计模式

    题记: 之前公司项目比较稳定, 在进行了系统测试,想用自动化测试进行冒烟测试,或者对主要功能进行测试, 因此用到了PO模式 因此做个记录: Page Object Page Object模式是使用Se ...

  6. Python+Selenium自动化测试:Page Object模式

    Page Objects是selenium的一种测试设计模式,主要将每个页面看作是一个class.class的内容主要包括属性和方法,属性不难理解,就是这个页面中的元素对象,比如输入用户名的输入框,输 ...

  7. 【转载】Selenium使用Page Object实现页面自动测试

    点击这里查看原文 ======================================= Page Object模式是Selenium中的一种测试设计模式,主要是将每一个页面设计为一个Clas ...

  8. python selenium 框架说明_UI自动化框架bok-choy(selenium+python+page object)使用介绍

    前言 bok choy是一个开源的使用python语言,以Page Object模式封装selenium的验收测试框架.在工作中可以用它来做UI层面的自动化.为了更好地理解本文,您需要有seleniu ...

  9. 关于page object(PO)模型的介绍

    所谓的PO就是page object,通俗解释一下就是每个页面当成一个对象,给这些页面写一个类,主要就是完成元素定位和业务操作:至于测试脚本要和ta区别开来,需要什么去这些页面类去调用即可.这样的好处 ...

最新文章

  1. BZOJ2339: [HNOI2011]卡农(dp 容斥)
  2. fflush(stdin)与fflush(stdout)
  3. 将字符串中的URL 解析,获取内容
  4. npm run serve后台运行的命令写法
  5. QML 性能优化建议(一)
  6. python 输入10个整数_2019-07-18 python练习:编写一个程序,要求用户输入10个整数,然后输出其中最大的奇数,如果用户没有输入奇数,则输出一个消息进行说明。...
  7. hive load data外部表报错_生产SparkSQL如何读写本地外部数据源及排错
  8. 包裹点云位姿估计_基于点云位姿平均的非合作目标三维重构
  9. fasta文件中DNA to RNA
  10. [转]网易云音乐Android版使用的开源组件
  11. android Camera framework层解析
  12. Devexpress WPF教程
  13. python中的对数_python中计算log对数的方法
  14. 让设计师哭笑不得的文案
  15. html正则邮箱格式,JS正则表达式判断邮箱格式是否正确
  16. ES对比两个索引的数据差
  17. IE及系统诸多问题的修复方法
  18. 抽奖转盘,实现后台概率控制
  19. nonce值是什么?(Number once)(Number used once)cnonce(client nonce)(一个只被使用一次的任意或非重复的随机数值)
  20. sql server 统计表信息

热门文章

  1. 交换二叉树中所有结点的左右子树的位置
  2. 汇编语言(王爽 第三版)检测点
  3. 关于FileSystemWatcher监听文件创建
  4. TQuery组件的Open方法与ExecSQL的区别
  5. Django获取多个复选框的值,并插入对应表底下
  6. elementUI表单验证
  7. 30. 包含min函数的栈
  8. Hadoop单点安装(伪分布式)
  9. Symbol学习与回忆
  10. Django Bootstrap开发笔记03 - Bootstrap环境配置