python实现测试工具(二)――简单的ui测试工具

这篇文章主要介绍了python如何实现简单的ui测试工具,帮助大家更好的利用python进行测试工作,感兴趣的朋友可以了解下

本系列教程使用的python版本是3.6.3。

背景

这一节我们实现一个简单的ui测试工具。

该工具的作用是访问某个页面,然后根据css选择器去定位页面上的元素,最后判断页面上元素的个数与我们的预期是否相符。

举一个具体的例子,比如我们去访问www.itest.info这个页面,我们需要判断页面上class = thumbnail-img的元素存在,并且有4个。因为每一个元素代表一门课程,所以这个断言的意思是重定向科技主页上应该有4门主要课程。

视频讲解在这里。

工具设计

我们设计一个命令行工具,给工具传3个参数。

  • 被访问页面的url
  • 页面上元素的css选择器
  • 预期的元素数量,页面上可以存在n个元素,如果传入0,则表示元素不存在,做反向断言

所以工具大概是这样用的: python script_name.py url css_selector length

代码实现

简单起见,我们会用到requests-html库。安装文档在这里。

 from requests_html import HTMLSession from sys import argv DEBUG = True USAGE = ''' USAGE: python html_assertion.py www.itest.info .thumbnail-img 4 ''' if len(argv) != 4: print(USAGE) exit(1) script_name, url, css_selector, length = argv if url[:4] != 'http': url = 'http://' + url session = HTMLSession() r = session.get(url) elements = r.html.find(css_selector) def debug(): if DEBUG: print('*' * 100) print(f"css选择器: {css_selector}, 共找到{len(elements)}个元素\n") for element in elements: print(element.html) print(element.attrs) print() if len(elements) != int(length): print(f"失败! 预期{length}个元素,实际存在{len(elements)}个元素\n") debug() exit(1) else: print(f"成功!\n") debug()

精讲

用例失败之后使用exit(1)表示异常退出,这样在使用jenkins运行的时候,用例失败jenkins的job结果也会相应失败
requests-html库的基本使用参考这里

运行示例

 # 失败情况 python html_assertion.py www.itest.info .thumbnail-img 1 失败! 预期1个元素,实际存在4个元素 **************************************************************************************************** css选择器: .thumbnail-img, 共找到4个元素  {'class': ('thumbnail-img',)}  {'class': ('thumbnail-img',)}  {'class': ('thumbnail-img',)}  {'class': ('thumbnail-img',)} # 成功情况 python html_assertion.py www.itest.info .thumbnail-img 4 成功! **************************************************************************************************** css选择器: .thumbnail-img, 共找到4个元素  {'class': ('thumbnail-img',)}  {'class': ('thumbnail-img',)}  {'class': ('thumbnail-img',)}  {'class': ('thumbnail-img',)}

动手时间

  • 抄一遍代码,看自己能不能运行起来
  • 给这段代码每一行都加上注释,理解代码做了些什么

扩展阅读

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors

源码地址

github地址

以上就是python实现测试工具(二)――简单的ui测试工具的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » python