目录
前言
项目框架
首先管理时间
!/usr/bin/env python3
-- coding:utf-8 --
配置文件
conf.py
config.ini#
读取配置文件
记录操作日志
简单理解POM模型
管理页面元素
封装Selenium基类
创建页面对象
熟悉unittest测试框架
编写测试用例
执行用例
生成测试报告
执行并生成报告
发送结果邮件
前言
selenium自动化+unittest测试框架
- 本章你需要
-
一定的python基础——至少明白类与对象,封装继承
-
一定的selenium基础——不讲selenium,
-
项目框架
开始之前先简单介绍一下框架体系吧:
目录/文件 | 说明 | 是否为python包 |
---|---|---|
common | 常见的通用类。如:读取config文件,元素文件 | 是 |
config | 配置文件目录 | 是 |
logs | 日志文件目录 | |
page | selenium基类 | 是 |
page_element | 页面元素 | |
page_object | 页面对象POM设计模式,本人对这个的理解来自于苦叶子的博客 | 是 |
report | 报告目录 | |
TestCase | 测试用例 | 是 |
utils | 工具类。如:邮箱、日志 | 是 |
run_case.py | 总执行文件 | |
script | 常用脚本目录 |
- 框架有什么优点呢?
- 代码复用率高,如果不使用框架的话,代码会很冗余
- 可以组装日志、报告、邮件等一些高级功能
- 提高元素等数据的可维护性,元素发生变化时,只需要更新一下配置文件
- 使用更灵活的PageObject设计模式
知道了以上这些我们就开始吧!
我们在项目中先按照上面的框架指引,建好每一项目录。
注意:python包为是的,都需要添加一个__init__.py
文件以标识此目录为一个python包。
selenium自动化测试视频教程:2023最新的Selenium自动化测试实战,没有比这个更详细的了_哔哩哔哩_bilibilihttps://www.bilibili.com/video/BV1xv4y1D7ku/?spm_id_from=333.999.0.0
首先管理时间
<span style="color:#596172"><span style="background-color:#ffffff"><code class="language-go">首先呢,因为用到时间的地方可能会比较多,所以我们也单独把时间封装成一个模块。让其他模块来调用即可。在<span style="color:#98c379">`utils`</span>目录中新建<span style="color:#98c379">`times.py`</span>文件。填入以下内容。<span style="color:#98c379">``</span><span style="color:#98c379">`python
</span></code></span></span>
!/usr/bin/env python3
-- coding:utf-8 --
import time
import datetime
from functools import wraps
def timestamp():
"""时间戳"""
return time.time()
def datetime_strftime(fmt="%Y%m"):
"""datetime格式化时间"""
return datetime.datetime.now().strftime(fmt)
def sleep(seconds=1.0):
"""
睡眠时间
"""
time.sleep(seconds)
def run_time(func):
"""运行时长"""
<span style="color:#596172"><span style="background-color:#ffffff"><code class="language-python"><span style="color:#61aeee"> @wraps(func)</span><span style="color:#7171bf">def</span> <span style="color:#61aeee">wrapper</span>(*args, **kwargs):start_time = timestamp()res = func(*args, **kwargs)<span style="color:#7171bf">print</span>(<span style="color:#98c379">"Done!用时%.3f秒!"</span> % (timestamp() - start_time))<span style="color:#7171bf">return</span> res<span style="color:#7171bf">return</span> wrapper
</code></span></span>
if name == 'main':
print(timestamp())
<span style="color:#596172"><span style="background-color:#ffffff"><code class="language-go"><span style="color:#98c379">``</span><span style="color:#98c379">`
</span></code></span></span>
配置文件
配置文件总是一个项目的重要组成部分!
在项目中我们创建config
文件目录,里面存放我们本次项目所需要的配置文件。包括我们常用的目录管理和一些设置。
conf.py
在项目config
目录创建conf.py
文件,所有的目录配置或者基本不变的配置信息写在这个文件里面。
<span style="color:#596172"><span style="background-color:#ffffff"><code class="language-python"><span style="color:#5c6370"><em>#!/usr/bin/env python3</em></span>
<span style="color:#5c6370"><em># -*- coding:utf-8 -*-</em></span>
<span style="color:#7171bf">import</span> os
<span style="color:#7171bf">from</span> selenium.webdriver.common.by <span style="color:#7171bf">import</span> By
<span style="color:#7171bf">from</span> utils.times <span style="color:#7171bf">import</span> datetime_strftime<span style="color:#7171bf">class</span> <span style="color:#61aeee">ConfigManager</span>(<span style="color:#61aeee">object</span>):<span style="color:#5c6370"><em># 项目目录</em></span>BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))<span style="color:#5c6370"><em># 配置文件</em></span>INI_PATH = os.path.join(BASE_DIR, <span style="color:#98c379">'config'</span>, <span style="color:#98c379">'config.ini'</span>)<span style="color:#5c6370"><em># 页面元素目录</em></span>ELEMENT_PATH = os.path.join(BASE_DIR, <span style="color:#98c379">'page_element'</span>)<span style="color:#5c6370"><em># 报告目录</em></span>REPORT_PATH = os.path.join(BASE_DIR, <span style="color:#98c379">'report'</span>)<span style="color:#5c6370"><em># 测试用例</em></span>TEST_SUITES = os.path.join(BASE_DIR, <span style="color:#98c379">"TestCase"</span>)<span style="color:#5c6370"><em># 元素定位的类型</em></span>LOCATE_MODE = {<span style="color:#98c379">'css'</span>: By.CSS_SELECTOR,<span style="color:#98c379">'xpath'</span>: By.XPATH,<span style="color:#98c379">'name'</span>: By.NAME,<span style="color:#98c379">'id'</span>: By.ID,<span style="color:#98c379">'class'</span>: By.CLASS_NAME}<span style="color:#5c6370"><em># 邮件信息</em></span>EMAIL_INFO = {<span style="color:#98c379">'username'</span>: <span style="color:#98c379">'1084502012@qq.com'</span>, <span style="color:#5c6370"><em># 切换成你自己的地址</em></span><span style="color:#98c379">'password'</span>: <span style="color:#98c379">'QQ邮箱授权码'</span>,<span style="color:#98c379">'smtp_host'</span>: <span style="color:#98c379">'smtp.qq.com'</span>,<span style="color:#98c379">'smtp_port'</span>: <span style="color:#d19a66">465</span>}<span style="color:#5c6370"><em># 收件人</em></span>ADDRESSEE = [<span style="color:#98c379">'1084502012@qq.com'</span>, ]<span style="color:#61aeee"> @property</span><span style="color:#7171bf">def</span> <span style="color:#61aeee">log_path</span>(self):<span style="color:#5c6370"><em># 日志目录</em></span>log_path = os.path.join(self.BASE_DIR, <span style="color:#98c379">'logs'</span>)<span style="color:#7171bf">if</span> <span style="color:#7171bf">not</span> os.path.exists(log_path):os.makedirs(log_path)<span style="color:#7171bf">return</span> os.path.join(log_path, <span style="color:#98c379">'{}.log'</span>.<span style="color:#7171bf">format</span>(datetime_strftime()))<span style="color:#61aeee"> @property</span><span style="color:#7171bf">def</span> <span style="color:#61aeee">report_path</span>(self):<span style="color:#98c379">"""报告文件"""</span>_path = self.REPORT_PATH<span style="color:#7171bf">if</span> <span style="color:#7171bf">not</span> os.path.exists(_path):os.makedirs(_path)<span style="color:#7171bf">return</span> os.path.join(_path, <span style="color:#98c379">'{}.html'</span>.<span style="color:#7171bf">format</span>(datetime_strftime(<span style="color:#98c379">"%Y%m%d_%H%M%S"</span>)))<span style="color:#61aeee"> @property</span><span style="color:#7171bf">def</span> <span style="color:#61aeee">get_new_report</span>(self):<span style="color:#98c379">"""获取最新的报告"""</span>_path = self.REPORT_PATHreport_path = os.listdir(_path)report_new_path = <span style="color:#7171bf">sorted</span>(report_path,key=<span style="color:#7171bf">lambda</span> x: os.path.getmtime(os.path.join(_path, x)))report_new_file = os.path.join(_path, report_new_path[-<span style="color:#d19a66">1</span>])<span style="color:#7171bf">with</span> <span style="color:#7171bf">open</span>(report_new_file, encoding=<span style="color:#98c379">'utf-8'</span>) <span style="color:#7171bf">as</span> f:<span style="color:#7171bf">return</span> f.read()cm = ConfigManager()
<span style="color:#7171bf">if</span> __name__ == <span style="color:#98c379">'__main__'</span>:<span style="color:#7171bf">print</span>(cm.BASE_DIR)
</code></span></span>
这个conf文件我模仿了Django的settings.py文件风格。
在这个文件中我们可以设置自己的各个目录,也可以查看自己当前的目录。
遵循了约定:不变的常量名全部大写,变量名称小写的规范。看起来整体美观。
config.ini#
然后在config
目录中新建一个config.ini
文件,里面暂时先放入我们的需要测试的URL
<span style="color:#596172"><span style="background-color:#ffffff"><code class="language-ini"><span style="color:#e06c75">[HOST]</span>
<span style="color:#d19a66">HOST</span> = https://www.baidu.com
</code></span></span>
配置文件创建好了,接下来我们需要读取这个配置文件以使用里面的信息。
读取配置文件
在common
目录新建一个readconfig.py
文件。这个文件就是我们用来读取config.ini
文件里面的配置信息的。
<span style="color:#596172"><span style="background-color:#ffffff"><code class="language-python"><span style="color:#5c6370"><em>#!/usr/bin/env python3</em></span>
<span style="color:#5c6370"><em># -*- coding:utf-8 -*-</em></span>
<span style="color:#7171bf">import</span> os
<span style="color:#7171bf">import</span> configparser
<span style="color:#7171bf">from</span> config.conf <span style="color:#7171bf">import</span> cmHOST = <span style="color:#98c379">'HOST'</span><span style="color:#7171bf">class</span> <span style="color:#61aeee">ReadConfig</span>:<span style="color:#98c379">"""配置文件"""</span><span style="color:#7171bf">def</span> <span style="color:#61aeee">__init__</span>(self):self.path = cm.INI_PATH<span style="color:#7171bf">if</span> <span style="color:#7171bf">not</span> os.path.exists(self.path):<span style="color:#7171bf">raise</span> FileNotFoundError(<span style="color:#98c379">"配置文件%s不存在!"</span> % self.path)self.config = configparser.RawConfigParser() <span style="color:#5c6370"><em># 当有%的符号时请使用Raw读取</em></span>self.config.read(self.path, encoding=<span style="color:#98c379">'utf-8'</span>)<span style="color:#7171bf">def</span> <span style="color:#61aeee">_get</span>(self, section, option):<span style="color:#98c379">"""获取"""</span><span style="color:#7171bf">return</span> self.config.get(section, option)<span style="color:#7171bf">def</span> <span style="color:#61aeee">_set</span>(self, section, option, value):<span style="color:#98c379">"""更新"""</span>self.config.<span style="color:#7171bf">set</span>(section, option, value)<span style="color:#7171bf">with</span> <span style="color:#7171bf">open</span>(self.path, <span style="color:#98c379">'w'</span>) <span style="color:#7171bf">as</span> f:self.config.write(f)<span style="color:#61aeee"> @property</span><span style="color:#7171bf">def</span> <span style="color:#61aeee">url</span>(self):<span style="color:#7171bf">return</span> self._get(HOST, HOST)ini = ReadConfig()<span style="color:#7171bf">if</span> __name__ == <span style="color:#98c379">'__main__'</span>:<span style="color:#7171bf">print</span>(ini.url)
</code></span></span>
可以看到我们用python内置的configparser模块对config.ini
文件进行了读取。
对于url值的提取,我使用了高阶语法@property将方法改写为属性值,调用更简单。
记录操作日志
日志,大家应该都很熟悉这个名词,就是记录代码中的动作。
在utils
目录中新建logger.py
文件。
这个文件就是我们用来在自动化测试过程中记录一些操作步骤的。
<span style="color:#596172"><span style="background-color:#ffffff"><code class="language-python"><span style="color:#5c6370"><em>#!/usr/bin/env python3</em></span>
<span style="color:#5c6370"><em># -*- coding:utf-8 -*-</em></span>
<span style="color:#7171bf">import</span> logging
<span style="color:#7171bf">from</span> config.conf <span style="color:#7171bf">import</span> cm<span style="color:#7171bf">class</span> <span style="color:#61aeee">Logger</span>:<span style="color:#7171bf">def</span> <span style="color:#61aeee">__init__</span>(self, name=<span style="color:#56b6c2">None</span>):self.logger = logging.getLogger(name)<span style="color:#7171bf">if</span> <span style="color:#7171bf">not</span> self.logger.handlers:self.logger.setLevel(logging.DEBUG)<span style="color:#5c6370"><em># 创建一个handle写入文件</em></span>fh = logging.FileHandler(cm.log_path, encoding=<span style="color:#98c379">'utf-8'</span>)fh.setLevel(logging.INFO)<span style="color:#5c6370"><em># 创建一个handle输出到控制台</em></span>ch = logging.StreamHandler()ch.setLevel(logging.INFO)<span style="color:#5c6370"><em># 定义输出的格式</em></span>formatter = logging.Formatter(self.fmt)fh.setFormatter(formatter)ch.setFormatter(formatter)<span style="color:#5c6370"><em># 添加到handle</em></span>self.logger.addHandler(fh)self.logger.addHandler(ch)<span style="color:#61aeee"> @property</span><span style="color:#7171bf">def</span> <span style="color:#61aeee">fmt</span>(self):<span style="color:#7171bf">return</span> <span style="color:#98c379">'%(levelname)s\t%(asctime)s\t%(name)s:%(lineno)d\t%(message)s'</span><span style="color:#7171bf">if</span> __name__ == <span style="color:#98c379">'__main__'</span>:log = Logger(__name__).loggerlog.info(<span style="color:#98c379">'hello world'</span>)
</code></span></span>
在终端中运行该文件,就看到命令行打印出了:
<span style="color:#596172"><span style="background-color:#ffffff"><code class="language-shell">INFO 2020-1-16 20:37:19,726 __main__:37 hello world
</code></span></span>
然后在项目logs
目录下生成了当月的日志文件。
话不多说,进入正题!
简单理解POM模型
由于下面要讲元素相关的,所以首先理解一下POM模型
Page Object模式具有以下几个优点。
该观点来自 《Selenium自动化测试——基于Python语言》
- 抽象出对象可以最大程度地降低开发人员修改页面代码对测试的影响, 所以, 你仅需要对页
面对象进行调整, 而对测试没有影响; - 可以在多个测试用例中复用一部分测试代码;
- 测试代码变得更易读、 灵活、 可维护
Page Object模式图
- basepage ——selenium的基类,对selenium的方法进行封装
- pageelements——页面元素,把页面元素单独提取出来,放入一个文件中
- searchpage ——页面对象类,把selenium方法和页面元素进行整合
- testcase ——使用pytest对整合的searchpage进行测试用例编写
通过上图我们可以看出,通过POM模型思想,我们把:
-
selenium方法
-
页面元素
-
页面对象
-
测试用例
以上四种代码主体进行了拆分,虽然在用例很少的情况下做会增加代码,但是当用例多的时候意义很大,代码量会在用例增加的时候显著减少。我们维护代码变得更加直观明显,代码可读性也变得比工厂模式强很多,代码复用率也极大的得到了提高。
管理页面元素
本教程选择的测试地址是百度首页,所以对应的元素也是百度首页的。
项目框架设计中有一个目录page_element
就是专门来存放定位元素的文件的。
通过对各种配置文件的对比,我在这里选择的是YAML文件格式。其支持与python数据类型堪称无缝对接,且易读,交互性好。
我们在page_element
目录中新建一个search.yaml
文件。
<span style="color:#596172"><span style="background-color:#ffffff"><code class="language-yaml"><span style="color:#98c379">搜索框:</span> <span style="color:#98c379">"id==kw"</span>
<span style="color:#98c379">候选:</span> <span style="color:#98c379">"css==.bdsug-overflow"</span>
<span style="color:#98c379">搜索候选:</span> <span style="color:#98c379">"css==#form div li"</span>
<span style="color:#98c379">搜索按钮:</span> <span style="color:#98c379">"id==su"</span>
</code></span></span>
元素定位文件创建好了,下来我们需要读取这个文件。
在common
中创建readelement.py
文件。
<span style="color:#596172"><span style="background-color:#ffffff"><code class="language-python"><span style="color:#5c6370"><em>#!/usr/bin/env python3</em></span>
<span style="color:#5c6370"><em># -*- coding:utf-8 -*-</em></span>
<span style="color:#7171bf">import</span> os
<span style="color:#7171bf">import</span> yaml
<span style="color:#7171bf">from</span> config.conf <span style="color:#7171bf">import</span> cm<span style="color:#7171bf">class</span> <span style="color:#61aeee">Element</span>:<span style="color:#98c379">"""获取元素"""</span><span style="color:#7171bf">def</span> <span style="color:#61aeee">__init__</span>(self, name):self.file_name = <span style="color:#98c379">'%s.yaml'</span> % nameself.element_path = os.path.join(cm.ELEMENT_PATH, self.file_name)<span style="color:#7171bf">if</span> <span style="color:#7171bf">not</span> os.path.exists(self.element_path):<span style="color:#7171bf">raise</span> FileNotFoundError(<span style="color:#98c379">"%s 文件不存在!"</span> % self.element_path)<span style="color:#7171bf">with</span> <span style="color:#7171bf">open</span>(self.element_path, encoding=<span style="color:#98c379">'utf-8'</span>) <span style="color:#7171bf">as</span> f:self.data = yaml.safe_load(f)<span style="color:#7171bf">def</span> <span style="color:#61aeee">__getitem__</span>(self, item):<span style="color:#98c379">"""获取属性"""</span>data = self.data.get(item)<span style="color:#7171bf">if</span> data:name, value = data.split(<span style="color:#98c379">'=='</span>)<span style="color:#7171bf">return</span> name, value<span style="color:#7171bf">raise</span> ArithmeticError(<span style="color:#98c379">"{}中不存在关键字:{}"</span>.<span style="color:#7171bf">format</span>(self.file_name, item))<span style="color:#7171bf">if</span> __name__ == <span style="color:#98c379">'__main__'</span>:search = Element(<span style="color:#98c379">'search'</span>)<span style="color:#7171bf">print</span>(search[<span style="color:#98c379">'搜索框'</span>])</code></span></span>
通过特殊方法__getitem__
实现调用任意属性,读取yaml中的值。
这样我们就实现了定位元素的存储和调用。
但是还有一个问题,我们怎么样才能确保我们写的每一项元素不出错,人为的错误是不可避免的,但是我们可以通过代码来运行对文件的审查。但是也不能检查出所有的问题,所以还是要细心。
所以我们编写一个文件,在script
目录中创建inspect.py
文件,对所有的元素yaml文件进行一次大概的审查。
<span style="color:#596172"><span style="background-color:#ffffff"><code class="language-python"><span style="color:#5c6370"><em>#!/usr/bin/env python3</em></span>
<span style="color:#5c6370"><em># -*- coding:utf-8 -*-</em></span>
<span style="color:#7171bf">import</span> os
<span style="color:#7171bf">import</span> yaml
<span style="color:#7171bf">from</span> utils.times <span style="color:#7171bf">import</span> run_time
<span style="color:#7171bf">from</span> config.conf <span style="color:#7171bf">import</span> cm<span style="color:#61aeee">@run_time</span>
<span style="color:#7171bf">def</span> <span style="color:#61aeee">inspect_element</span>():<span style="color:#98c379">"""审查所有的元素是否正确"""</span><span style="color:#7171bf">for</span> i <span style="color:#7171bf">in</span> os.listdir(cm.ELEMENT_PATH):_path = os.path.join(cm.ELEMENT_PATH, i)<span style="color:#7171bf">if</span> os.path.isfile(_path):<span style="color:#7171bf">with</span> <span style="color:#7171bf">open</span>(_path, encoding=<span style="color:#98c379">'utf-8'</span>) <span style="color:#7171bf">as</span> f:data = yaml.safe_load(f)<span style="color:#7171bf">for</span> k <span style="color:#7171bf">in</span> data.values():pattern, value = k.split(<span style="color:#98c379">'=='</span>)<span style="color:#7171bf">if</span> pattern <span style="color:#7171bf">not</span> <span style="color:#7171bf">in</span> cm.LOCATE_MODE:<span style="color:#7171bf">raise</span> AttributeError(<span style="color:#98c379">'【%s】路径中【%s]元素没有指定类型'</span> % (i, k))<span style="color:#7171bf">if</span> pattern == <span style="color:#98c379">'xpath'</span>:<span style="color:#7171bf">assert</span> <span style="color:#98c379">'//'</span> <span style="color:#7171bf">in</span> value, <span style="color:#98c379">'【%s】路径中【%s]元素xpath类型与值不配'</span> % (i, k)<span style="color:#7171bf">if</span> pattern == <span style="color:#98c379">'css'</span>:<span style="color:#7171bf">assert</span> <span style="color:#98c379">'//'</span> <span style="color:#7171bf">not</span> <span style="color:#7171bf">in</span> value, <span style="color:#98c379">'【%s】路径中【%s]元素css类型与值不配'</span> % (i, k)<span style="color:#7171bf">if</span> pattern <span style="color:#7171bf">in</span> (<span style="color:#98c379">'id'</span>, <span style="color:#98c379">'name'</span>, <span style="color:#98c379">'class'</span>):<span style="color:#7171bf">assert</span> value, <span style="color:#98c379">'【%s】路径中【%s]元素类型与值不匹配'</span> % (i, k)<span style="color:#7171bf">if</span> __name__ == <span style="color:#98c379">'__main__'</span>:inspect_element()</code></span></span>
执行该文件:
<span style="color:#596172"><span style="background-color:#ffffff"><code class="language-powershell">Done!用时<span style="color:#d19a66">0.015</span>秒!
</code></span></span>
可以看到,很短的时间内,我们就对所填写的YAML文件进行了审查。
selenium自动化测试视频教程:2023最新的Selenium自动化测试实战,没有比这个更详细的了_哔哩哔哩_bilibilihttps://www.bilibili.com/video/BV1xv4y1D7ku/?spm_id_from=333.999.0.0&vd_source=6e2d6c374fd551babe1ac6a5e60c5a75
封装Selenium基类
在工厂模式种我们是这样写的:
<span style="color:#596172"><span style="background-color:#ffffff"><code class="language-python"><span style="color:#5c6370"><em>#!/usr/bin/env python3</em></span>
<span style="color:#5c6370"><em># -*- coding:utf-8 -*-</em></span>
<span style="color:#7171bf">import</span> time
<span style="color:#7171bf">from</span> selenium <span style="color:#7171bf">import</span> webdriverdriver = webdriver.Chrome()
driver.get(<span style="color:#98c379">'https://www.baidu.com'</span>)
driver.find_element_by_xpath(<span style="color:#98c379">"//input[@id='kw']"</span>).send_keys(<span style="color:#98c379">'selenium'</span>)
driver.find_element_by_xpath(<span style="color:#98c379">"//input[@id='su']"</span>).click()
time.sleep(<span style="color:#d19a66">5</span>)
driver.quit()
</code></span></span>
很直白,简单,又明了。
创建driver对象,打开百度网页,搜索selenium,点击搜索,然后停留5秒,查看结果,最后关闭浏览器。
那我们为什么要封装selenium的方法呢。首先我们上述这种较为原始的方法,基本不适用于平时做UI自动化测试的,因为在UI界面实际运行情况远远比较复杂,可能因为网络原因,或者控件原因,我们元素还没有显示出来,就进行点击或者输入。所以我们需要封装selenium方法,通过内置的显式等待或一定的条件语句,才能构建一个稳定的方法。而且把selenium方法封装起来,有利于平时的代码维护。
我们在page
目录创建webpage.py
文件。
<span style="color:#596172"><span style="background-color:#ffffff"><code class="language-python"><span style="color:#5c6370"><em>#!/usr/bin/env python3</em></span>
<span style="color:#5c6370"><em># -*- coding:utf-8 -*-</em></span>
<span style="color:#98c379">"""
selenium基类
本文件存放了selenium基类的封装方法
"""</span>
<span style="color:#7171bf">from</span> selenium.webdriver.support <span style="color:#7171bf">import</span> expected_conditions <span style="color:#7171bf">as</span> EC
<span style="color:#7171bf">from</span> selenium.webdriver.support.ui <span style="color:#7171bf">import</span> WebDriverWait
<span style="color:#7171bf">from</span> selenium.common.exceptions <span style="color:#7171bf">import</span> TimeoutException
<span style="color:#7171bf">from</span> config.conf <span style="color:#7171bf">import</span> cm
<span style="color:#7171bf">from</span> utils.times <span style="color:#7171bf">import</span> sleep
<span style="color:#7171bf">from</span> utils.logger <span style="color:#7171bf">import</span> Loggerlog = Logger(__name__).logger<span style="color:#7171bf">class</span> <span style="color:#61aeee">WebPage</span>(<span style="color:#61aeee">object</span>):<span style="color:#98c379">"""selenium基类"""</span><span style="color:#7171bf">def</span> <span style="color:#61aeee">__init__</span>(self, driver):<span style="color:#5c6370"><em># self.driver = webdriver.Chrome()</em></span>self.driver = driverself.timeout = <span style="color:#d19a66">20</span> <span style="color:#5c6370"><em># 查找元素的超时时间</em></span>self.wait = WebDriverWait(self.driver, self.timeout)<span style="color:#7171bf">def</span> <span style="color:#61aeee">get_url</span>(self, url):<span style="color:#98c379">"""打开网址并验证"""</span>self.driver.maximize_window()self.driver.set_page_load_timeout(<span style="color:#d19a66">60</span>)<span style="color:#7171bf">try</span>:self.driver.get(url)self.driver.implicitly_wait(<span style="color:#d19a66">10</span>)log.info(<span style="color:#98c379">"打开网页:%s"</span> % url)<span style="color:#7171bf">except</span> TimeoutException:<span style="color:#7171bf">raise</span> TimeoutException(<span style="color:#98c379">"打开%s超时请检查网络或网址服务器"</span> % url)<span style="color:#61aeee"> @staticmethod</span><span style="color:#7171bf">def</span> <span style="color:#61aeee">element_locator</span>(func, locator):<span style="color:#98c379">"""元素定位器"""</span>name, value = locator<span style="color:#7171bf">return</span> func(cm.ELEMENT_PATH[name], value)<span style="color:#7171bf">def</span> <span style="color:#61aeee">find_element</span>(self, locator):<span style="color:#98c379">"""寻找单个元素"""</span><span style="color:#7171bf">return</span> WebPage.element_locator(<span style="color:#7171bf">lambda</span> *args: self.wait.until(EC.presence_of_element_located(args)), locator)<span style="color:#7171bf">def</span> <span style="color:#61aeee">find_elements</span>(self, locator):<span style="color:#98c379">"""查找多个相同的元素"""</span><span style="color:#7171bf">return</span> WebPage.element_locator(<span style="color:#7171bf">lambda</span> *args: self.wait.until(EC.presence_of_all_elements_located(args)), locator)<span style="color:#7171bf">def</span> <span style="color:#61aeee">ele_num</span>(self, locator): <span style="color:#5c6370"><em># 获取相同元素的个数</em></span><span style="color:#98c379">"""获取相同元素的个数"""</span>number = <span style="color:#7171bf">len</span>(self.find_elements(locator))log.info(<span style="color:#98c379">"相同元素:{}"</span>.<span style="color:#7171bf">format</span>((locator, number)))<span style="color:#7171bf">return</span> number<span style="color:#7171bf">def</span> <span style="color:#61aeee">input_text</span>(self, locator, txt):<span style="color:#98c379">"""输入(输入前先清空)"""</span>sleep(<span style="color:#d19a66">0.5</span>)ele = self.find_element(locator)ele.clear()ele.send_keys(txt)log.info(<span style="color:#98c379">"输入文本:{}"</span>.<span style="color:#7171bf">format</span>(txt))<span style="color:#7171bf">def</span> <span style="color:#61aeee">is_click</span>(self, locator):<span style="color:#98c379">"""点击"""</span>self.find_element(locator).click()sleep()log.info(<span style="color:#98c379">"点击元素:{}"</span>.<span style="color:#7171bf">format</span>(locator))<span style="color:#7171bf">def</span> <span style="color:#61aeee">get_text</span>(self, locator):<span style="color:#98c379">"""获取当前的text"""</span>ele_text = self.find_element(locator).textlog.info(<span style="color:#98c379">"获取文本:{}"</span>.<span style="color:#7171bf">format</span>(ele_text))<span style="color:#7171bf">return</span> ele_text<span style="color:#61aeee"> @property</span><span style="color:#7171bf">def</span> <span style="color:#61aeee">get_source</span>(self):<span style="color:#98c379">"""获取页面源代码"""</span><span style="color:#7171bf">return</span> self.driver.page_source<span style="color:#7171bf">def</span> <span style="color:#61aeee">shot_file</span>(self, path):<span style="color:#98c379">"""文件截图"""</span><span style="color:#7171bf">return</span> self.driver.save_screenshot(path)<span style="color:#7171bf">def</span> <span style="color:#61aeee">refresh</span>(self):<span style="color:#98c379">"""刷新页面F5"""</span>self.driver.refresh()self.driver.implicitly_wait(<span style="color:#d19a66">30</span>)<span style="color:#7171bf">if</span> __name__ == <span style="color:#98c379">"__main__"</span>:<span style="color:#7171bf">pass</span>
</code></span></span>
在文件中我们对主要用了显式等待对selenium的click,send_keys等方法,做了二次封装。提高了运行的成功率。
好了我们完成了POM模型的一半工作了。接下来我们们进入页面对象。
创建页面对象
我们开始创建searchpage页面对象类。
在page_object
目录下创建一个searchpage.py
文件。
<span style="color:#596172"><span style="background-color:#ffffff"><code class="language-python"><span style="color:#5c6370"><em>#!/usr/bin/env python3</em></span>
<span style="color:#5c6370"><em># -*- coding:utf-8 -*-</em></span>
<span style="color:#7171bf">from</span> page.webpage <span style="color:#7171bf">import</span> WebPage, sleep
<span style="color:#7171bf">from</span> common.readelement <span style="color:#7171bf">import</span> Elementsearch = Element(<span style="color:#98c379">'search'</span>)<span style="color:#7171bf">class</span> <span style="color:#61aeee">SearchPage</span>(<span style="color:#61aeee">WebPage</span>):<span style="color:#98c379">"""搜索类"""</span><span style="color:#7171bf">def</span> <span style="color:#61aeee">input_search</span>(self, content):<span style="color:#98c379">"""输入搜索"""</span>self.input_text(search[<span style="color:#98c379">'搜索框'</span>], txt=content)sleep()<span style="color:#61aeee"> @property</span><span style="color:#7171bf">def</span> <span style="color:#61aeee">imagine</span>(self):<span style="color:#98c379">"""搜索联想"""</span><span style="color:#7171bf">return</span> [x.text <span style="color:#7171bf">for</span> x <span style="color:#7171bf">in</span> self.find_elements(search[<span style="color:#98c379">'候选'</span>])]<span style="color:#7171bf">def</span> <span style="color:#61aeee">click_search</span>(self):<span style="color:#98c379">"""点击搜索"""</span>self.is_click(search[<span style="color:#98c379">'搜索按钮'</span>])<span style="color:#7171bf">if</span> __name__ == <span style="color:#98c379">'__main__'</span>:<span style="color:#7171bf">pass</span>
</code></span></span>
在该文件中我们对,输入搜索关键词,点击搜索,搜索联想,进行了封装。
并配置了注释。
在平时中我们应该养成写注释的习惯,因为过一段时间后,没有注释,代码读起来很费劲。
好了我们的页面对象此时业已完成了。
下面我们开始编写测试用例。
熟悉unittest测试框架
unittest是python标准库中自带的测试框架。
学习unittest最好的教程应该是python官方文档了。
不细说了,自己去看吧。
编写测试用例
我们将使用unittest
编写测试用例。
在TestCase
目录中创建test_search.py
文件。
<span style="color:#596172"><span style="background-color:#ffffff"><code class="language-python"><span style="color:#5c6370"><em>#!/usr/bin/env python3</em></span>
<span style="color:#5c6370"><em># -*- coding:utf-8 -*-</em></span>
<span style="color:#7171bf">import</span> re
<span style="color:#7171bf">import</span> unittest
<span style="color:#7171bf">from</span> selenium <span style="color:#7171bf">import</span> webdriver<span style="color:#7171bf">from</span> utils.logger <span style="color:#7171bf">import</span> Logger
<span style="color:#7171bf">from</span> common.readconfig <span style="color:#7171bf">import</span> ini
<span style="color:#7171bf">from</span> page_object.searchpage <span style="color:#7171bf">import</span> SearchPage
<span style="color:#7171bf">from</span> chromedriver_py <span style="color:#7171bf">import</span> binary_pathlog = Logger(__name__).logger<span style="color:#7171bf">class</span> <span style="color:#61aeee">TestSearch</span>(unittest.TestCase):<span style="color:#98c379">"""搜索测试"""</span><span style="color:#61aeee"> @classmethod</span><span style="color:#7171bf">def</span> <span style="color:#61aeee">setUpClass</span>(cls) -> <span style="color:#56b6c2">None</span>:cls.driver = webdriver.Chrome(executable_path=binary_path)cls.search = SearchPage(cls.driver)cls.search.get_url(ini.url)<span style="color:#61aeee"> @classmethod</span><span style="color:#7171bf">def</span> <span style="color:#61aeee">tearDownClass</span>(cls) -> <span style="color:#56b6c2">None</span>:cls.driver.quit()<span style="color:#7171bf">def</span> <span style="color:#61aeee">setUp</span>(self) -> <span style="color:#56b6c2">None</span>:self.imgs = [] <span style="color:#5c6370"><em># 注意:添加此行用于报告中失败截图</em></span><span style="color:#7171bf">def</span> <span style="color:#61aeee">test_001</span>(self):<span style="color:#98c379">"""搜索"""</span>self.search.input_search(<span style="color:#98c379">"selenium"</span>)self.search.click_search()result = re.search(<span style="color:#98c379">r'selenium'</span>, self.search.get_source)log.info(result)<span style="color:#7171bf">assert</span> result<span style="color:#7171bf">def</span> <span style="color:#61aeee">test_002</span>(self):<span style="color:#98c379">"""测试搜索候选"""</span>self.search.input_search(<span style="color:#98c379">"selenium"</span>)log.info(<span style="color:#7171bf">list</span>(self.search.imagine))<span style="color:#7171bf">assert</span> <span style="color:#7171bf">all</span>([<span style="color:#98c379">"selenium"</span> <span style="color:#7171bf">in</span> i <span style="color:#7171bf">for</span> i <span style="color:#7171bf">in</span> self.search.imagine])<span style="color:#7171bf">if</span> __name__ == <span style="color:#98c379">'__main__'</span>:unittest.main(verbosity=<span style="color:#d19a66">2</span>)
</code></span></span>
我们测试用例就编写好了。
- 第一个测试用例:
- 我们实现了在百度selenium关键字,并点击搜索按钮,并在搜索结果中,用正则查找结果页源代码,返回数量大于10我们就认为通过。
- 第二个测试用例:
- 我们实现了,搜索selenium,然后断言搜索候选中的所有结果有没有selenium关键字。
执行用例
以上我们已经编写完成了整个框架和测试用例。
我们进入到当前项目的主目录执行文件:
<span style="color:#596172"><span style="background-color:#ffffff"><code class="language-shell">DevTools listening on ws://127.0.0.1:7341/devtools/browser/09ec4049-0745-4048-8fe2-ece53457d8c0
INFO 2020-06-10 16:21:20,021 [webpage.py:37] 打开网页:https://www.baidu.com
test_001 (__main__.TestSearch)
搜索 ... INFO 2020-06-10 16:21:20,667 [webpage.py:69] 输入文本:selenium
INFO 2020-06-10 16:21:22,738 [webpage.py:75] 点击元素:('id', 'su')
INFO 2020-06-10 16:21:22,785 [test_search.py:43] <re.Match object; span=(326, 334), match='selenium'>
ok
test_002 (__main__.TestSearch)
测试搜索候选 ... INFO 2020-06-10 16:21:23,407 [webpage.py:69] 输入文本:selenium
INFO 2020-06-10 16:21:24,466 [test_search.py:49] ['selenium', 'selenium python', 'selenium面试题', 'selenium中文文档']
ok----------------------------------------------------------------------
Ran 2 tests in 12.531sOK
</code></span></span>
可以看到两条用例已经执行成功了。
生成测试报告
unittest无法像pytest一样直接添加命令行参数就可以生成报告。
但是可以通过第三方模块HTMLTestRunner_cn去生成报告。我们需要下载该模块去生成报告。
生成的报告结果图:
这个模块我已保存在群文件中。左上角加群。
然后将下载的HTMLTestRunner_cn.py文件放在项目的tools
目录。
执行并生成报告
我们在项目根目录下创建run_case.py文件作为项目的运行文件。
<span style="color:#596172"><span style="background-color:#ffffff"><code class="language-python"><span style="color:#5c6370"><em>#!/usr/bin/env python3</em></span>
<span style="color:#5c6370"><em># -*- coding:utf-8 -*-</em></span>
<span style="color:#7171bf">import</span> unittest
<span style="color:#7171bf">from</span> config.conf <span style="color:#7171bf">import</span> cm
<span style="color:#7171bf">from</span> utils.send_mail <span style="color:#7171bf">import</span> send_report_mail
<span style="color:#7171bf">from</span> utils.HTMLTestRunner_cn <span style="color:#7171bf">import</span> HTMLTestRunnerdiscover = unittest.defaultTestLoader.discover(cm.TEST_SUITES, pattern=<span style="color:#98c379">"test*.py"</span>)<span style="color:#7171bf">def</span> <span style="color:#61aeee">main</span>():<span style="color:#98c379">"""主函数"""</span><span style="color:#7171bf">try</span>:<span style="color:#7171bf">with</span> <span style="color:#7171bf">open</span>(cm.report_path, <span style="color:#98c379">'wb+'</span>) <span style="color:#7171bf">as</span> fp:runner = HTMLTestRunner(stream=fp,title=<span style="color:#98c379">"测试结果"</span>,description=<span style="color:#98c379">"用例执行情况"</span>,verbosity=<span style="color:#d19a66">2</span>,retry=<span style="color:#d19a66">1</span>,save_last_try=<span style="color:#56b6c2">True</span>)result = runner.run(discover)<span style="color:#7171bf">except</span> Exception <span style="color:#7171bf">as</span> e:<span style="color:#7171bf">print</span>(<span style="color:#98c379">"用例执行失败:{}"</span>.<span style="color:#7171bf">format</span>(e))<span style="color:#7171bf">else</span>:<span style="color:#7171bf">if</span> result.failure_count <span style="color:#7171bf">or</span> result.error_count:<span style="color:#5c6370"><em># 如果测试有错误,就发送邮件</em></span>send_report_mail()<span style="color:#7171bf">if</span> __name__ == <span style="color:#98c379">"__main__"</span>:main()
</code></span></span>
发送结果邮件
当项目执行完成之后,需要发送到自己或者其他人邮箱里查看结果。
我们编写发送邮件的模块。
在tools
目录中新建send_mail.py
文件
<span style="color:#596172"><span style="background-color:#ffffff"><code class="language-python"><span style="color:#5c6370"><em>#!/usr/bin/env python3</em></span>
<span style="color:#5c6370"><em># -*- coding: utf-8 -*-</em></span>
<span style="color:#7171bf">import</span> smtplib
<span style="color:#7171bf">from</span> email.header <span style="color:#7171bf">import</span> Header
<span style="color:#7171bf">from</span> email.mime.text <span style="color:#7171bf">import</span> MIMEText
<span style="color:#7171bf">from</span> email.utils <span style="color:#7171bf">import</span> parseaddr, formataddr
<span style="color:#7171bf">from</span> email.mime.multipart <span style="color:#7171bf">import</span> MIMEMultipart
<span style="color:#7171bf">from</span> config.conf <span style="color:#7171bf">import</span> cm<span style="color:#7171bf">def</span> <span style="color:#61aeee">_format_addr</span>(s):<span style="color:#98c379">"""格式化邮件地址"""</span>name, addr = parseaddr(s)<span style="color:#7171bf">return</span> formataddr((Header(name, <span style="color:#98c379">'utf-8'</span>).encode(), addr))<span style="color:#7171bf">def</span> <span style="color:#61aeee">send_report_mail</span>():<span style="color:#98c379">"""发送最新的测试报告"""</span><span style="color:#5c6370"><em># email地址和口令:</em></span>email_info = cm.EMAIL_INFOuser = email_info[<span style="color:#98c379">'username'</span>]pwd = email_info[<span style="color:#98c379">'password'</span>]<span style="color:#5c6370"><em># 收件人地址</em></span>to_addr = cm.ADDRESSEE<span style="color:#5c6370"><em># SMTP服务器地址</em></span>smtp_server = email_info[<span style="color:#98c379">'smtp_host'</span>]smtp_port = email_info[<span style="color:#98c379">'smtp_port'</span>]<span style="color:#7171bf">try</span>:<span style="color:#5c6370"><em># 初始化邮件对象</em></span>msg = MIMEMultipart()msg[<span style="color:#98c379">'From'</span>] = _format_addr(<span style="color:#98c379">"selenium爱好者<%s>"</span> % user)msg[<span style="color:#98c379">'To'</span>] = _format_addr(<span style="color:#98c379">'管理员 <%s>'</span> % <span style="color:#98c379">','</span>.join(to_addr))msg[<span style="color:#98c379">'Subject'</span>] = Header(<span style="color:#98c379">"unittest演示测试最新的测试报告"</span>, <span style="color:#98c379">'utf-8'</span>).encode()<span style="color:#5c6370"><em># 发送HTML文件</em></span>msg.attach(MIMEText(cm.get_new_report, <span style="color:#98c379">'html'</span>, <span style="color:#98c379">'utf-8'</span>))<span style="color:#5c6370"><em># 发件人邮箱中的SMTP服务器,端口</em></span><span style="color:#7171bf">with</span> smtplib.SMTP_SSL(smtp_server, smtp_port) <span style="color:#7171bf">as</span> server:<span style="color:#5c6370"><em># 括号中对应的是发件人邮箱账号、邮箱密码</em></span>server.login(user, pwd)<span style="color:#5c6370"><em># 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件</em></span>server.sendmail(user, to_addr, msg.as_string())<span style="color:#7171bf">print</span>(<span style="color:#98c379">"测试结果邮件发送成功!"</span>)<span style="color:#7171bf">except</span> smtplib.SMTPException <span style="color:#7171bf">as</span> e:<span style="color:#7171bf">print</span>(<span style="color:#98c379">u"Error: 无法发送邮件"</span>, <span style="color:#7171bf">format</span>(e))<span style="color:#7171bf">if</span> __name__ == <span style="color:#98c379">'__main__'</span>:send_report_mail()
</code></span></span>
执行该文件:
<span style="color:#596172"><span style="background-color:#ffffff"><code class="language-powershell">测试邮件发送成功!</code></span></span>
可以看到测试报告邮件已经发送成功了。
打开邮箱。
成功收到了邮件,只是样式丢失了。
这个unittest框架的selenium—demo项目就算是整体完工了。
selenium自动化测试:
2023最新的Selenium自动化测试实战,没有比这个更详细的了_哔哩哔哩_bilibilihttps://www.bilibili.com/video/BV1xv4y1D7ku/?spm_id_from=333.999.0.0&vd_source=6e2d6c374fd551babe1ac6a5e60c5a75