【Selenium+Pytest+allure报告生成自动化测试框架】附带项目源码和项目部署 ...

嚴華  金牌会员 | 2022-6-25 15:19:54 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 549|帖子 549|积分 1647

目录

前言
【文章末尾给大家留下了大量的福利】
测试框架简介
首先管理时间
添加配置文件
conf.py
config.ini
读取配置文件
记录操作日志
简单理解POM模型
简单学习元素定位
管理页面元素
封装Selenium基类
创建页面对象
简单了解Pytest
pytest.ini
编写测试用例
conftest.py
执行用例
发送邮件
pytest使用allure测试报告
allure安装
allure初体验
allure装饰器介绍
报告的生成和展示
allure发生错误截图
开源地址#
 重点:学习资料学习当然离不开资料,这里当然也给你们准备了600G的学习资料

项目实战
大型电商项目
全套软件测试自动化测试教学视频
300G教程资料下载【视频教程+PPT+项目源码】
全套软件测试自动化测试大厂面经
python自动化测试++全套模板+性能测试


前言

      selenium自动化+ pytest测试框架+allure报告
   本章你需要
   

  • 一定的python基础——至少明白类与对象,封装继承
  • 一定的selenium基础——本篇不讲selenium,不会的可以自己去看selenium中文翻译网
  • 【文章末尾给大家留下了大量的福利】

  
   
   测试框架简介

   

  • 测试框架有什么优点呢:

    • 代码复用率高,如果不使用框架的话,代码会很冗余
    • 可以组装日志、报告、邮件等一些高级功能
    • 提高元素等数据的可维护性,元素发生变化时,只需要更新一下配置文件
    • 使用更灵活的PageObject设计模式

  • 测试框架的整体目录
               目录/文件说明是否为python包common这个包中存放的是常见的通用的类,如读取配置文件是config配置文件目录是logs日志目录page对selenium的方放进行深度的封装是page_element页面元素存放目录page_object页面对象POM设计模式,本人对这个的理解来自于苦叶子的博客是TestCase所有的测试用例集是utils工具类是script脚本文件conftest.pypytest胶水文件pytest.inipytest配置文件
    这样一个简单的框架结构就清晰了。
   知道了以上这些我们就开始吧!
   我们在项目中先按照上面的框架指引,建好每一项目录。
   注意:python包为是的,都需要添加一个__init__.py文件以标识此目录为一个python包。
   
  首先管理时间

   首先呢,因为我们很多的模块会用到时间戳,或者日期等等字符串,所以我们先单独把时间封装成一个模块。
   然后让其他模块来调用即可。在utils目录新建times.py模块
  
  1. <em>#!/usr/bin/env python3</em>
  2. <em># -*- coding:utf-8 -*-</em>
  3. import time
  4. import datetime
  5. from functools import wraps
  6. def timestamp():
  7.     """时间戳"""
  8.     return time.time()
  9. def dt_strftime(fmt="%Y%m"):
  10.     """
  11.     datetime格式化时间
  12.     :param fmt "%Y%m%d %H%M%S
  13.     """
  14.     return datetime.datetime.now().strftime(fmt)
  15. def sleep(seconds=1.0):
  16.     """
  17.     睡眠时间
  18.     """
  19.     time.sleep(seconds)
  20. def running_time(func):
  21.     """函数运行时间"""
  22.     @wraps(func)
  23.     def wrapper(*args, **kwargs):
  24.         start = timestamp()
  25.         res = func(*args, **kwargs)
  26.         print("校验元素done!用时%.3f秒!" % (timestamp() - start))
  27.         return res
  28.     return wrapper
  29. if __name__ == '__main__':
  30.     print(dt_strftime("%Y%m%d%H%M%S"))
复制代码
  
  添加配置文件

   配置文件总是项目中必不可少的部分!
   将固定不变的信息集中在固定的文件中
   conf.py

       项目中都应该有一个文件对整体的目录进行管理,我也在这个python项目中设置了此文件。
      在项目config目录创建conf.py文件,所有的目录配置信息写在这个文件里面。
  
  1. <em>#!/usr/bin/env python3</em>
  2. <em># -*- coding:utf-8 -*-</em>
  3. import os
  4. from selenium.webdriver.common.by import By
  5. from utils.times import dt_strftime
  6. class ConfigManager(object):
  7.     <em># 项目目录</em>
  8.     BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  9.     <em># 页面元素目录</em>
  10.     ELEMENT_PATH = os.path.join(BASE_DIR, 'page_element')
  11.     <em># 报告文件</em>
  12.     REPORT_FILE = os.path.join(BASE_DIR, 'report.html')
  13.     <em># 元素定位的类型</em>
  14.     LOCATE_MODE = {
  15.         'css': By.CSS_SELECTOR,
  16.         'xpath': By.XPATH,
  17.         'name': By.NAME,
  18.         'id': By.ID,
  19.         'class': By.CLASS_NAME
  20.     }
  21.     <em># 邮件信息</em>
  22.     EMAIL_INFO = {
  23.         'username': '1084502012@qq.com',  <em># 切换成你自己的地址</em>
  24.         'password': 'QQ邮箱授权码',
  25.         'smtp_host': 'smtp.qq.com',
  26.         'smtp_port': 465
  27.     }
  28.     <em># 收件人</em>
  29.     ADDRESSEE = [
  30.         '1084502012@qq.com',
  31.     ]
  32.     @property
  33.     def log_file(self):
  34.         """日志目录"""
  35.         log_dir = os.path.join(self.BASE_DIR, 'logs')
  36.         if not os.path.exists(log_dir):
  37.             os.makedirs(log_dir)
  38.         return os.path.join(log_dir, '{}.log'.format(dt_strftime()))
  39.     @property
  40.     def ini_file(self):
  41.         """配置文件"""
  42.         ini_file = os.path.join(self.BASE_DIR, 'config', 'config.ini')
  43.         if not os.path.exists(ini_file):
  44.             raise FileNotFoundError("配置文件%s不存在!" % ini_file)
  45.         return ini_file
  46. cm = ConfigManager()
  47. if __name__ == '__main__':
  48.     print(cm.BASE_DIR)
复制代码
      注意:QQ邮箱授权码:点击查看生成教程
          这个conf文件我模仿了Django的settings.py文件的设置风格,但是又有些许差异。
      在这个文件中我们可以设置自己的各个目录,也可以查看自己当前的目录。
   遵循了约定:不变的常量名全部大写,函数名小写。看起来整体美观。
   config.ini

   在项目config目录新建一个config.ini文件,里面暂时先放入我们的需要测试的URL
  
  1. [HOST]
  2. HOST = https://www.baidu.com
复制代码
  读取配置文件

   配置文件创建好了,接下来我们需要读取这个配置文件以使用里面的信息。
   我们在common目录中新建一个readconfig.py文件
  
  1. <em>#!/usr/bin/env python3</em>
  2. <em># -*- coding:utf-8 -*-</em>
  3. import configparser
  4. from config.conf import cm
  5. HOST = 'HOST'
  6. class ReadConfig(object):
  7.     """配置文件"""
  8.     def __init__(self):
  9.         self.config = configparser.RawConfigParser()  <em># 当有%的符号时请使用Raw读取</em>
  10.         self.config.read(cm.ini_file, encoding='utf-8')
  11.     def _get(self, section, option):
  12.         """获取"""
  13.         return self.config.get(section, option)
  14.     def _set(self, section, option, value):
  15.         """更新"""
  16.         self.config.set(section, option, value)
  17.         with open(cm.ini_file, 'w') as f:
  18.             self.config.write(f)
  19.     @property
  20.     def url(self):
  21.         return self._get(HOST, HOST)
  22. ini = ReadConfig()
  23. if __name__ == '__main__':
  24.     print(ini.url)
复制代码
  可以看到我们用python内置的configparser模块对config.ini文件进行了读取。
   对于url值的提取,我使用了高阶语法@property属性值,写法更简单。
   
  记录操作日志

   日志,大家应该都很熟悉这个名词,就是记录代码中的动作。
   在utils目录中新建logger.py文件。
   这个文件就是我们用来在自动化测试过程中记录一些操作步骤的。
  
  1. <em>#!/usr/bin/env python3</em>
  2. <em># -*- coding:utf-8 -*-</em>
  3. import logging
  4. from config.conf import cm
  5. class Log:
  6.     def __init__(self):
  7.         self.logger = logging.getLogger()
  8.         if not self.logger.handlers:
  9.             self.logger.setLevel(logging.DEBUG)
  10.             <em># 创建一个handle写入文件</em>
  11.             fh = logging.FileHandler(cm.log_file, encoding='utf-8')
  12.             fh.setLevel(logging.INFO)
  13.             <em># 创建一个handle输出到控制台</em>
  14.             ch = logging.StreamHandler()
  15.             ch.setLevel(logging.INFO)
  16.             <em># 定义输出的格式</em>
  17.             formatter = logging.Formatter(self.fmt)
  18.             fh.setFormatter(formatter)
  19.             ch.setFormatter(formatter)
  20.             <em># 添加到handle</em>
  21.             self.logger.addHandler(fh)
  22.             self.logger.addHandler(ch)
  23.     @property
  24.     def fmt(self):
  25.         return '%(levelname)s\t%(asctime)s\t[%(filename)s:%(lineno)d]\t%(message)s'
  26. log = Log().logger
  27. if __name__ == '__main__':
  28.     log.info('hello world')
复制代码
  在终端中运行该文件,就看到命令行打印出了:
  
  1. INFO        2020-12-01 16:00:05,467        [logger.py:38]        hello world
复制代码
  然后在项目logs目录下生成了当月的日志文件。
   
  简单理解POM模型

       由于下面要讲元素相关的,所以首先理解一下POM模型
      Page Object模式具有以下几个优点。
       该观点来自 《Selenium自动化测试——基于Python语言》
      

  • 抽象出对象可以最大程度地降低开发人员修改页面代码对测试的影响, 所以, 你仅需要对页
    面对象进行调整, 而对测试没有影响;
  • 可以在多个测试用例中复用一部分测试代码;
  • 测试代码变得更易读、 灵活、 可维护
  Page Object模式图
   
   

  • basepage ——selenium的基类,对selenium的方法进行封装
  • pageelements——页面元素,把页面元素单独提取出来,放入一个文件中
  • searchpage ——页面对象类,把selenium方法和页面元素进行整合
  • testcase ——使用pytest对整合的searchpage进行测试用例编写
  通过上图我们可以看出,通过POM模型思想,我们把:
   

  • selenium方法
  • 页面元素
  • 页面对象
  • 测试用例
  以上四种代码主体进行了拆分,虽然在用例很少的情况下做会增加代码,但是当用例多的时候意义很大,代码量会在用例增加的时候显著减少。我们维护代码变得更加直观明显,代码可读性也变得比工厂模式强很多,代码复用率也极大的得到了提高。
   
  简单学习元素定位

   在日常的工作中,我见过很多在浏览器中直接在浏览器中右键Copy Xpath复制元素的同学。这样获得的元素表达式放在 webdriver 中去运行往往是不够稳定的,像前端的一些微小改动,都会引起元素无法定位的NoSuchElementException报错。
   所以在实际工作和学习中我们应该加强自己的元素定位能力,尽可能的采用xpath和CSS selector 这种相对稳定的定位语法。由于CSS selector的语法生硬难懂,对新手很不友好,而且相比xpath缺少一些定位语法。所以我们选择xpath进行我们的元素定位语法。
   xpath#
   语法规则
       菜鸟教程中对于 xpath 的介绍是一门在 XML 文档中查找信息的语言。
          表达式介绍备注/根节点绝对路径//当前节点的所有子节点相对路径*所有节点元素的@属性名的前缀@class   @id*[1][] 下标运算符[][ ]谓词表达式//input[@id='kw']Following-sibling当前节点之后的同级preceding-sibling当前节点之前的同级parent当前节点的父级节点     定位工具
   

  • chropath

    • 优点:这是一个Chrome浏览器的测试定位插件,类似于firepath,本人试用了一下整体感觉非常好。对小白的友好度很好。
    • 缺点:安装这个插件需要FQ。

  • Katalon录制工具

    • 录制出来的脚本里面也会有定位元素的信息

  • 自己写——本人推荐这种

    • 优点:本人推荐的方式,因为当熟练到一定程度的时候,写出来的会更直观简洁,并且在运行自动化测试中出现问题时,能快速定位。
    • 缺点:需要一定xpath和CSS selector语法积累,不太容易上手。

  
  管理页面元素

       本教程选择的测试地址是百度首页,所以对应的元素也是百度首页的。
      项目框架设计中有一个目录page_element就是专门来存放定位元素的文件的。
   通过对各种配置文件的对比,我在这里选择的是YAML文件格式。其易读,交互性好。
   我们在page_element中新建一个search.yaml文件。
  
  1. 搜索框: "id==kw"
  2. 候选: "css==.bdsug-overflow"
  3. 搜索候选: "css==#form div li"
  4. 搜索按钮: "id==su"
复制代码
  元素定位文件创建好了,下来我们需要读取这个文件。
   在common目录中创建readelement.py文件。
  
  1. <em>#!/usr/bin/env python3</em>
  2. <em># -*- coding:utf-8 -*-</em>
  3. import os
  4. import yaml
  5. from config.conf import cm
  6. class Element(object):
  7.     """获取元素"""
  8.     def __init__(self, name):
  9.         self.file_name = '%s.yaml' % name
  10.         self.element_path = os.path.join(cm.ELEMENT_PATH, self.file_name)
  11.         if not os.path.exists(self.element_path):
  12.             raise FileNotFoundError("%s 文件不存在!" % self.element_path)
  13.         with open(self.element_path, encoding='utf-8') as f:
  14.             self.data = yaml.safe_load(f)
  15.     def __getitem__(self, item):
  16.         """获取属性"""
  17.         data = self.data.get(item)
  18.         if data:
  19.             name, value = data.split('==')
  20.             return name, value
  21.         raise ArithmeticError("{}中不存在关键字:{}".format(self.file_name, item))
  22. if __name__ == '__main__':
  23.     search = Element('search')
  24.     print(search['搜索框'])
复制代码
  通过特殊方法__getitem__实现调用任意属性,读取yaml中的值。
   这样我们就实现了定位元素的存储和调用。
   但是还有一个问题,我们怎么样才能确保我们写的每一项元素不出错,人为的错误是不可避免的,但是我们可以通过代码来运行对文件的审查。当前也不能所有问题都能发现。
   所以我们编写一个文件,在script脚本文件目录中创建inspect.py文件,对所有的元素yaml文件进行审查。
  
  1. <em>#!/usr/bin/env python3</em>
  2. <em># -*- coding:utf-8 -*-</em>
  3. import os
  4. import yaml
  5. from config.conf import cm
  6. from utils.times import running_time
  7. @running_time
  8. def inspect_element():
  9.     """检查所有的元素是否正确
  10.     只能做一个简单的检查
  11.     """
  12.     for files in os.listdir(cm.ELEMENT_PATH):
  13.         _path = os.path.join(cm.ELEMENT_PATH, files)
  14.         with open(_path, encoding='utf-8') as f:
  15.             data = yaml.safe_load(f)
  16.         for k in data.values():
  17.             try:
  18.                 pattern, value = k.split('==')
  19.             except ValueError:
  20.                 raise Exception("元素表达式中没有`==`")
  21.             if pattern not in cm.LOCATE_MODE:
  22.                 raise Exception('%s中元素【%s】没有指定类型' % (_path, k))
  23.             elif pattern == 'xpath':
  24.                 assert '//' in value,\
  25.                     '%s中元素【%s】xpath类型与值不配' % (_path, k)
  26.             elif pattern == 'css':
  27.                 assert '//' not in value, \
  28.                     '%s中元素【%s]css类型与值不配' % (_path, k)
  29.             else:
  30.                 assert value, '%s中元素【%s】类型与值不匹配' % (_path, k)
  31. if __name__ == '__main__':
  32.     inspect_element()
复制代码
  执行该文件:
  
  1. 校验元素done!用时0.002秒!
复制代码
  可以看到,很短的时间内,我们就对所填写的YAML文件进行了审查。
   现在我们基本所需要的组件已经大致完成了。
   接下来我们将进行最重要的一环,封装selenium。
   
  封装Selenium基类

   在工厂模式种我们是这样写的:
  
  1. <em>#!/usr/bin/env python3</em>
  2. <em># -*- coding:utf-8 -*-</em>
  3. import time
  4. from selenium import webdriver
  5. driver = webdriver.Chrome()
  6. driver.get('https://www.baidu.com')
  7. driver.find_element_by_xpath("//input[@id='kw']").send_keys('selenium')
  8. driver.find_element_by_xpath("//input[@id='su']").click()
  9. time.sleep(5)
  10. driver.quit()
复制代码
  很直白,简单,又明了。
   创建driver对象,打开百度网页,搜索selenium,点击搜索,然后停留5秒,查看结果,最后关闭浏览器。
   那我们为什么要封装selenium的方法呢。首先我们上述这种较为原始的方法,基本不适用于平时做UI自动化测试的,因为在UI界面实际运行情况远远比较复杂,可能因为网络原因,或者控件原因,我们元素还没有显示出来,就进行点击或者输入。所以我们需要封装selenium方法,通过内置的显式等待或一定的条件语句,才能构建一个稳定的方法。而且把selenium方法封装起来,有利于平时的代码维护。
   我们在page目录创建webpage.py文件。
  
  1. <em>#!/usr/bin/env python3</em>
  2. <em># -*- coding:utf-8 -*-</em>
  3. """
  4. selenium基类
  5. 本文件存放了selenium基类的封装方法
  6. """
  7. from selenium.webdriver.support import expected_conditions as EC
  8. from selenium.webdriver.support.ui import WebDriverWait
  9. from selenium.common.exceptions import TimeoutException
  10. from config.conf import cm
  11. from utils.times import sleep
  12. from utils.logger import log
  13. class WebPage(object):
  14.     """selenium基类"""
  15.     def __init__(self, driver):
  16.         <em># self.driver = webdriver.Chrome()</em>
  17.         self.driver = driver
  18.         self.timeout = 20
  19.         self.wait = WebDriverWait(self.driver, self.timeout)
  20.     def get_url(self, url):
  21.         """打开网址并验证"""
  22.         self.driver.maximize_window()
  23.         self.driver.set_page_load_timeout(60)
  24.         try:
  25.             self.driver.get(url)
  26.             self.driver.implicitly_wait(10)
  27.             log.info("打开网页:%s" % url)
  28.         except TimeoutException:
  29.             raise TimeoutException("打开%s超时请检查网络或网址服务器" % url)
  30.     @staticmethod
  31.     def element_locator(func, locator):
  32.         """元素定位器"""
  33.         name, value = locator
  34.         return func(cm.LOCATE_MODE[name], value)
  35.     def find_element(self, locator):
  36.         """寻找单个元素"""
  37.         return WebPage.element_locator(lambda *args: self.wait.until(
  38.             EC.presence_of_element_located(args)), locator)
  39.     def find_elements(self, locator):
  40.         """查找多个相同的元素"""
  41.         return WebPage.element_locator(lambda *args: self.wait.until(
  42.             EC.presence_of_all_elements_located(args)), locator)
  43.     def elements_num(self, locator):
  44.         """获取相同元素的个数"""
  45.         number = len(self.find_elements(locator))
  46.         log.info("相同元素:{}".format((locator, number)))
  47.         return number
  48.     def input_text(self, locator, txt):
  49.         """输入(输入前先清空)"""
  50.         sleep(0.5)
  51.         ele = self.find_element(locator)
  52.         ele.clear()
  53.         ele.send_keys(txt)
  54.         log.info("输入文本:{}".format(txt))
  55.     def is_click(self, locator):
  56.         """点击"""
  57.         self.find_element(locator).click()
  58.         sleep()
  59.         log.info("点击元素:{}".format(locator))
  60.     def element_text(self, locator):
  61.         """获取当前的text"""
  62.         _text = self.find_element(locator).text
  63.         log.info("获取文本:{}".format(_text))
  64.         return _text
  65.     @property
  66.     def get_source(self):
  67.         """获取页面源代码"""
  68.         return self.driver.page_source
  69.     def refresh(self):
  70.         """刷新页面F5"""
  71.         self.driver.refresh()
  72.         self.driver.implicitly_wait(30)
复制代码
  在文件中我们对主要用了显式等待对selenium的click,send_keys等方法,做了二次封装。提高了运行的成功率。
   好了我们完成了POM模型的一半左右的内容。接下来我们们进入页面对象。
   
  创建页面对象

   在page_object目录下创建一个searchpage.py文件。
  
  1. <em>#!/usr/bin/env python3</em>
  2. <em># -*- coding:utf-8 -*-</em>
  3. from page.webpage import WebPage, sleep
  4. from common.readelement import Element
  5. search = Element('search')
  6. class SearchPage(WebPage):
  7.     """搜索类"""
  8.     def input_search(self, content):
  9.         """输入搜索"""
  10.         self.input_text(search['搜索框'], txt=content)
  11.         sleep()
  12.     @property
  13.     def imagine(self):
  14.         """搜索联想"""
  15.         return [x.text for x in self.find_elements(search['候选'])]
  16.     def click_search(self):
  17.         """点击搜索"""
  18.         self.is_click(search['搜索按钮'])
复制代码
  在该文件中我们对,输入搜索关键词,点击搜索,搜索联想,进行了封装。
   并配置了注释。
       在平时中我们应该养成写注释的习惯,因为过一段时间后,没有注释,代码读起来很费劲。
      好了我们的页面对象此时业已完成了。下面我们开始编写测试用例。在开始测试用了之前我们先熟悉一下pytest测试框架。
   
  简单了解Pytest

   打开pytest框架的官网。pytest: helps you write better programs — pytest documentation
  
  1. <em># content of test_sample.py</em>
  2. def inc(x):
  3.     return x + 1
  4. def test_answer():
  5.     assert inc(3) == 5
复制代码
  
   pytest.ini

   pytest项目中的配置文件,可以对pytest执行过程中操作做全局控制。
   在项目根目录新建pytest.ini文件。
  
  1. [pytest]
  2. addopts = --html=report.html --self-contained-html
复制代码
  

  • addopts 指定执行时的其他参数说明:

    • --html=report/report.html --self-contained-html 生成pytest-html带样式的报告
    • -s 输出我们用例中的调式信息
    • -q 安静的进行测试
    • -v 可以输出用例更加详细的执行信息,比如用例所在的文件及用例名称等

  
  编写测试用例

   我们将使用pytest编写测试用例。
   在TestCase目录中创建test_search.py文件。
  
  1. <em>#!/usr/bin/env python3</em>
  2. <em># -*- coding:utf-8 -*-</em>
  3. import re
  4. import pytest
  5. from utils.logger import log
  6. from common.readconfig import ini
  7. from page_object.searchpage import SearchPage
  8. class TestSearch:
  9.     @pytest.fixture(scope='function', autouse=True)
  10.     def open_baidu(self, drivers):
  11.         """打开百度"""
  12.         search = SearchPage(drivers)
  13.         search.get_url(ini.url)
  14.     def test_001(self, drivers):
  15.         """搜索"""
  16.         search = SearchPage(drivers)
  17.         search.input_search("selenium")
  18.         search.click_search()
  19.         result = re.search(r'selenium', search.get_source)
  20.         log.info(result)
  21.         assert result
  22.     def test_002(self, drivers):
  23.         """测试搜索候选"""
  24.         search = SearchPage(drivers)
  25.         search.input_search("selenium")
  26.         log.info(list(search.imagine))
  27.         assert all(["selenium" in i for i in search.imagine])
  28. if __name__ == '__main__':
  29.     pytest.main(['TestCase/test_search.py'])
复制代码
  我们测试用了就编写好了。
   

  • pytest.fixture 这个实现了和unittest的setup,teardown一样的前置启动,后置清理的装饰器。
  • 第一个测试用例:

    • 我们实现了在百度selenium关键字,并点击搜索按钮,并在搜索结果中,用正则查找结果页源代码,返回数量大于10我们就认为通过。

  • 第二个测试用例:

    • 我们实现了,搜索selenium,然后断言搜索候选中的所有结果有没有selenium关键字。

  最后我们的在下面写一个执行启动的语句。
   这时候我们应该进入执行了,但是还有一个问题,我们还没有把driver传递。
   conftest.py

   我们在项目根目录下新建一个conftest.py文件。
  
  1. <em>#!/usr/bin/env python3</em>
  2. <em># -*- coding:utf-8 -*-</em>
  3. import pytest
  4. from py.xml import html
  5. from selenium import webdriver
  6. driver = None
  7. @pytest.fixture(scope='session', autouse=True)
  8. def drivers(request):
  9.     global driver
  10.     if driver is None:
  11.         driver = webdriver.Chrome()
  12.         driver.maximize_window()
  13.     def fn():
  14.         driver.quit()
  15.     request.addfinalizer(fn)
  16.     return driver
  17. @pytest.hookimpl(hookwrapper=True)
  18. def pytest_runtest_makereport(item):
  19.     """
  20.     当测试失败的时候,自动截图,展示到html报告中
  21.     :param item:
  22.     """
  23.     pytest_html = item.config.pluginmanager.getplugin('html')
  24.     outcome = yield
  25.     report = outcome.get_result()
  26.     report.description = str(item.function.__doc__)
  27.     extra = getattr(report, 'extra', [])
  28.     if report.when == 'call' or report.when == "setup":
  29.         xfail = hasattr(report, 'wasxfail')
  30.         if (report.skipped and xfail) or (report.failed and not xfail):
  31.             file_name = report.nodeid.replace("::", "_") + ".png"
  32.             screen_img = _capture_screenshot()
  33.             if file_name:
  34.                 html = '<img src="https://blog.csdn.net/data:image/png;base64,%s" alt="screenshot" style="width:1024px;height:768px;" ' \
  35.                        'onclick="window.open(this.src)" align="right"/>' % screen_img
  36.                 extra.append(pytest_html.extras.html(html))
  37.         report.extra = extra
  38. def pytest_html_results_table_header(cells):
  39.     cells.insert(1, html.th('用例名称'))
  40.     cells.insert(2, html.th('Test_nodeid'))
  41.     cells.pop(2)
  42. def pytest_html_results_table_row(report, cells):
  43.     cells.insert(1, html.td(report.description))
  44.     cells.insert(2, html.td(report.nodeid))
  45.     cells.pop(2)
  46. def pytest_html_results_table_html(report, data):
  47.     if report.passed:
  48.         del data[:]
  49.         data.append(html.div('通过的用例未捕获日志输出.', class_='empty log'))
  50. def _capture_screenshot():
  51.     '''
  52.     截图保存为base64
  53.     :return:
  54.     '''
  55.     return driver.get_screenshot_as_base64()
复制代码
  conftest.py测试框架pytest的胶水文件,里面用到了fixture的方法,封装并传递出了driver。
   
  执行用例

   以上我们已经编写完成了整个框架和测试用例。
   我们进入到当前项目的主目录执行命令:
  
  1. pytest
复制代码
  命令行输出:
  
  1. Test session starts (platform: win32, Python 3.7.7, pytest 5.3.2, pytest-sugar 0.9.2)
  2. cachedir: .pytest_cache
  3. metadata: {'Python': '3.7.7', 'Platform': 'Windows-10-10.0.18362-SP0', 'Packages': {'pytest': '5.3.2', 'py': '1.8.0', 'pluggy': '0.13.1'}, 'Plugins': {'forked': '1.1.3', 'html': '2.0.1', 'metadata': '1.8.0', 'ordering': '0.6', 'rerunfailures': '8.0', 'sugar': '0.9.2', 'xdist': '1.31.0'}, 'JAVA_HOME': 'D:\\Program Files\\Java\\jdk1.8.0_131'}
  4. rootdir: C:\Users\hoou\PycharmProjects\web-demotest, inifile: pytest.ini
  5. plugins: forked-1.1.3, html-2.0.1, metadata-1.8.0, ordering-0.6, rerunfailures-8.0, sugar-0.9.2, xdist-1.31.0
  6. collecting ...
  7. DevTools listening on ws://127.0.0.1:10351/devtools/browser/78bef34d-b94c-4087-b724-34fb6b2ef6d1
  8. TestCase\test_search.py::TestSearch.test_001 ✓                                                                                              50% █████     
  9. TestCase\test_search.py::TestSearch.test_002 ✓                                                                                             100% ██████████
  10. ------------------------------- generated html file: file://C:\Users\hoou\PycharmProjects\web-demotest\report\report.html --------------------------------
  11. Results (12.90s):
  12.        2 passed
复制代码
  可以看到两条用例已经执行成功了。
   项目的report目录中生成了一个report.html文件。
   这就是生成的测试报告文件。
   
  发送邮件

   当项目执行完成之后,需要发送到自己或者其他人邮箱里查看结果。
   我们编写发送邮件的模块。
   在utils目录中新建send_mail.py文件
  
  1. <em>#!/usr/bin/env python3</em>
  2. <em># -*- coding:utf-8 -*-</em>
  3. import zmail
  4. from config.conf import cm
  5. def send_report():
  6.     """发送报告"""
  7.     with open(cm.REPORT_FILE, encoding='utf-8') as f:
  8.         content_html = f.read()
  9.     try:
  10.         mail = {
  11.             'from': '1084502012@qq.com',
  12.             'subject': '最新的测试报告邮件',
  13.             'content_html': content_html,
  14.             'attachments': [cm.REPORT_FILE, ]
  15.         }
  16.         server = zmail.server(*cm.EMAIL_INFO.values())
  17.         server.send_mail(cm.ADDRESSEE, mail)
  18.         print("测试邮件发送成功!")
  19.     except Exception as e:
  20.         print("Error: 无法发送邮件,{}!", format(e))
  21. if __name__ == "__main__":
  22.     '''请先在config/conf.py文件设置QQ邮箱的账号和密码'''
  23.     send_report()
复制代码
  执行该文件:
  
  1. 测试邮件发送成功!
复制代码
  可以看到测试报告邮件已经发送成功了。打开邮箱。
   
   
   
   
   成功收到了邮件。
   这个demo项目就算是整体完工了;是不是很有心得,在发送邮件的那一刻很有成就感。
   最后,想必你已经对pytest+selenium框架有了一个整体的认知了,在自动化测试的道路上又上了一层台阶。
   
  pytest使用allure测试报告

            

  • 选用的项目为Selenium自动化测试Pytest框架实战,在这个项目的基础上说allure报告。
    allure安装

     

  • 首先安装python的allure-pytest包
   
  1. pip install allure-pytest
复制代码
   

  • 然后安装allure的command命令行程序
          MacOS直接使用homebrew工具执行 brew install allure 即可安装,不用配置下载包和配置环境
          在GitHub下载安装程序https://github.com/allure-framework/allure2/releases
     但是由于GitHub访问太慢,我已经下载好并放在了群文件里面
     下载完成后解压放到一个文件夹。我的路径是D:\Program Files\allure-2.13.3
     然后配置环境变量: 在系统变量path中添加D:\Program Files\allure-2.13.3\bin,然后确定保存。
     打开cmd,输入allure,如果结果显示如下则表示成功了:
   
  1. C:\Users\hoou>allure
  2. Usage: allure [options] [command] [command options]
  3.   Options:
  4.     --help
  5.       Print commandline help.
  6.     -q, --quiet
  7.       Switch on the quiet mode.
  8.       Default: false
  9.     -v, --verbose
  10.       Switch on the verbose mode.
  11.       Default: false
  12.     --version
  13.       Print commandline version.
  14.       Default: false
  15.   Commands:
  16.     generate      Generate the report
  17.       Usage: generate [options] The directories with allure results
  18.         Options:
  19.           -c, --clean
  20.             Clean Allure report directory before generating a new one.
  21.             Default: false
  22.           --config
  23.             Allure commandline config path. If specified overrides values from
  24.             --profile and --configDirectory.
  25.           --configDirectory
  26.             Allure commandline configurations directory. By default uses
  27.             ALLURE_HOME directory.
  28.           --profile
  29.             Allure commandline configuration profile.
  30.           -o, --report-dir, --output
  31.             The directory to generate Allure report into.
  32.             Default: allure-report
  33.     serve      Serve the report
  34.       Usage: serve [options] The directories with allure results
  35.         Options:
  36.           --config
  37.             Allure commandline config path. If specified overrides values from
  38.             --profile and --configDirectory.
  39.           --configDirectory
  40.             Allure commandline configurations directory. By default uses
  41.             ALLURE_HOME directory.
  42.           -h, --host
  43.             This host will be used to start web server for the report.
  44.           -p, --port
  45.             This port will be used to start web server for the report.
  46.             Default: 0
  47.           --profile
  48.             Allure commandline configuration profile.
  49.     open      Open generated report
  50.       Usage: open [options] The report directory
  51.         Options:
  52.           -h, --host
  53.             This host will be used to start web server for the report.
  54.           -p, --port
  55.             This port will be used to start web server for the report.
  56.             Default: 0
  57.     plugin      Generate the report
  58.       Usage: plugin [options]
  59.         Options:
  60.           --config
  61.             Allure commandline config path. If specified overrides values from
  62.             --profile and --configDirectory.
  63.           --configDirectory
  64.             Allure commandline configurations directory. By default uses
  65.             ALLURE_HOME directory.
  66.           --profile
  67.             Allure commandline configuration profile.
复制代码
    allure初体验

     改造一下之前的测试用例代码
   
  1. <em>#!/usr/bin/env python3</em>
  2. <em># -*- coding:utf-8 -*-</em>
  3. import re
  4. import pytest
  5. import allure
  6. from utils.logger import log
  7. from common.readconfig import ini
  8. from page_object.searchpage import SearchPage
  9. @allure.feature("测试百度模块")
  10. class TestSearch:
  11.     @pytest.fixture(scope='function', autouse=True)
  12.     def open_baidu(self, drivers):
  13.         """打开百度"""
  14.         search = SearchPage(drivers)
  15.         search.get_url(ini.url)
  16.     @allure.story("搜索selenium结果用例")
  17.     def test_001(self, drivers):
  18.         """搜索"""
  19.         search = SearchPage(drivers)
  20.         search.input_search("selenium")
  21.         search.click_search()
  22.         result = re.search(r'selenium', search.get_source)
  23.         log.info(result)
  24.         assert result
  25.     @allure.story("测试搜索候选用例")
  26.     def test_002(self, drivers):
  27.         """测试搜索候选"""
  28.         search = SearchPage(drivers)
  29.         search.input_search("selenium")
  30.         log.info(list(search.imagine))
  31.         assert all(["selenium" in i for i in search.imagine])
  32.         
  33. if __name__ == '__main__':
  34.     pytest.main(['TestCase/test_search.py', '--alluredir', './allure'])
  35.     os.system('allure serve allure')
复制代码
    然后运行一下:
     注意:如果你使用的是pycharm编辑器,请跳过该运行方式,直接使用.bat或.sh的方式运行
   
  1. ***
  2. ------------------------------- generated html file: file://C:\Users\hoou\PycharmProjects\web-demotest\report.html --------------------------------
  3. Results (12.97s):
  4.        2 passed
  5. Generating report to temp directory...
  6. Report successfully generated to C:\Users\hoou\AppData\Local\Temp\112346119265936111\allure-report
  7. Starting web server...
  8. 2020-06-18 22:52:44.500:INFO::main: Logging initialized @1958ms to org.eclipse.jetty.util.log.StdErrLog
  9. Server started at <http://172.18.47.241:6202/>. Press <Ctrl+C> to exit
复制代码
    命令行会出现如上提示,接着浏览器会自动打开:
     
     
     点击左下角En即可选择切换为中文。
     
     
     是不是很清爽很友好,比pytest-html更舒服。
     allure装饰器介绍

     
     
     报告的生成和展示

     刚才的两个命令:
     

  • 生成allure原始报告到report/allure目录下,生成的全部为json或txt文件。
   
  1. pytest TestCase/test_search.py --alluredir ./allure
复制代码
   

  • 在一个临时文件中生成报告并启动浏览器打开
   
  1. allure serve allure
复制代码
    但是在关闭浏览器之后这个报告就再也打不开了。不建议使用这种。
     所以我们必须使用其他的命令,让allure可以指定生成的报告目录。
     我们在项目的根目录中创建run_case.py文件,内容如下:
   
  1. <em>#!/usr/bin/env python3</em>
  2. <em># -*- coding:utf-8 -*-</em>
  3. import sys
  4. import subprocess
  5. WIN = sys.platform.startswith('win')
  6. def main():
  7.    """主函数"""
  8.    steps = [
  9.        "venv\\Script\\activate" if WIN else "source venv/bin/activate",
  10.        "pytest --alluredir allure-results --clean-alluredir",
  11.        "allure generate allure-results -c -o allure-report",
  12.        "allure open allure-report"
  13.    ]
  14.    for step in steps:
  15.        subprocess.run("call " + step if WIN else step, shell=True)
  16. if __name__ == "__main__":
  17.    main()
复制代码
    命令释义:
     1、使用pytest生成原始报告,里面大多数是一些原始的json数据,加入--clean-alluredir参数清除allure-results历史数据。
   
  1. pytest --alluredir allure-results --clean-alluredir
复制代码
   

  • --clean-alluredir 清除allure-results历史数据
    2、使用generate命令导出HTML报告到新的目录
   
  1. allure generate allure-results -o allure-report
复制代码
   

  • -c 在生成报告之前先清理之前的报告目录
  • -o 指定生成报告的文件夹
    3、使用open命令在浏览器中打开HTML报告
   
  1. allure open allure-report
复制代码
    好了我们运行一下该文件。
   
  1. Results (12.85s):
  2.        2 passed
  3. Report successfully generated to c:\Users\hoou\PycharmProjects\web-demotest\allure-report
  4. Starting web server...
  5. 2020-06-18 23:30:24.122:INFO::main: Logging initialized @260ms to org.eclipse.jetty.util.log.StdErrLog
  6. Server started at <http://172.18.47.241:7932/>. Press <Ctrl+C> to exit
复制代码
   
     
     可以看到运行成功了。
     在项目中的allure-report文件夹也生成了相应的报告。
     
     
     allure发生错误截图

     上面的用例全是运行成功的,没有错误和失败的,那么发生了错误怎么样在allure报告中生成错误截图呢,我们一起来看看。
     首先我们先在config/conf.py文件中添加一个截图目录和截图文件的配置。
   
  1. +++
  2. class ConfigManager(object):
  3.                 ...
  4.    
  5.     @property
  6.     def screen_path(self):
  7.         """截图目录"""
  8.         screenshot_dir = os.path.join(self.BASE_DIR, 'screen_capture')
  9.         if not os.path.exists(screenshot_dir):
  10.             os.makedirs(screenshot_dir)
  11.         now_time = dt_strftime("%Y%m%d%H%M%S")
  12.         screen_file = os.path.join(screenshot_dir, "{}.png".format(now_time))
  13.         return now_time, screen_file
  14.        
  15.           ...
  16. +++
复制代码
    然后我们修改项目目录中的conftest.py:
   
  1. <em>#!/usr/bin/env python3</em>
  2. <em># -*- coding:utf-8 -*-</em>
  3. import base64
  4. import pytest
  5. import allure
  6. from py.xml import html
  7. from selenium import webdriver
  8. from config.conf import cm
  9. from common.readconfig import ini
  10. from utils.times import timestamp
  11. from utils.send_mail import send_report
  12. driver = None
  13. @pytest.fixture(scope='session', autouse=True)
  14. def drivers(request):
  15.     global driver
  16.     if driver is None:
  17.         driver = webdriver.Chrome()
  18.         driver.maximize_window()
  19.     def fn():
  20.         driver.quit()
  21.     request.addfinalizer(fn)
  22.     return driver
  23. @pytest.hookimpl(hookwrapper=True)
  24. def pytest_runtest_makereport(item):
  25.     """
  26.     当测试失败的时候,自动截图,展示到html报告中
  27.     :param item:
  28.     """
  29.     pytest_html = item.config.pluginmanager.getplugin('html')
  30.     outcome = yield
  31.     report = outcome.get_result()
  32.     report.description = str(item.function.__doc__)
  33.     extra = getattr(report, 'extra', [])
  34.     if report.when == 'call' or report.when == "setup":
  35.         xfail = hasattr(report, 'wasxfail')
  36.         if (report.skipped and xfail) or (report.failed and not xfail):
  37.             screen_img = _capture_screenshot()
  38.             if screen_img:
  39.                 html = '<img src="https://blog.csdn.net/data:image/png;base64,%s" alt="screenshot" style="width:1024px;height:768px;" ' \
  40.                        'onclick="window.open(this.src)" align="right"/>' % screen_img
  41.                 extra.append(pytest_html.extras.html(html))
  42.         report.extra = extra
  43. def pytest_html_results_table_header(cells):
  44.     cells.insert(1, html.th('用例名称'))
  45.     cells.insert(2, html.th('Test_nodeid'))
  46.     cells.pop(2)
  47. def pytest_html_results_table_row(report, cells):
  48.     cells.insert(1, html.td(report.description))
  49.     cells.insert(2, html.td(report.nodeid))
  50.     cells.pop(2)
  51. def pytest_html_results_table_html(report, data):
  52.     if report.passed:
  53.         del data[:]
  54.         data.append(html.div('通过的用例未捕获日志输出.', class_='empty log'))
  55. def pytest_html_report_title(report):
  56.     report.title = "pytest示例项目测试报告"
  57. def pytest_configure(config):
  58.     config._metadata.clear()
  59.     config._metadata['测试项目'] = "测试百度官网搜索"
  60.     config._metadata['测试地址'] = ini.url
  61. def pytest_html_results_summary(prefix, summary, postfix):
  62.     <em># prefix.clear() # 清空summary中的内容</em>
  63.     prefix.extend([html.p("所属部门: XX公司测试部")])
  64.     prefix.extend([html.p("测试执行人: 随风挥手")])
  65. def pytest_terminal_summary(terminalreporter, exitstatus, config):
  66.     """收集测试结果"""
  67.     result = {
  68.         "total": terminalreporter._numcollected,
  69.         'passed': len(terminalreporter.stats.get('passed', [])),
  70.         'failed': len(terminalreporter.stats.get('failed', [])),
  71.         'error': len(terminalreporter.stats.get('error', [])),
  72.         'skipped': len(terminalreporter.stats.get('skipped', [])),
  73.         <em># terminalreporter._sessionstarttime 会话开始时间</em>
  74.         'total times': timestamp() - terminalreporter._sessionstarttime
  75.     }
  76.     print(result)
  77.     if result['failed'] or result['error']:
  78.         send_report()
  79. def _capture_screenshot():
  80.     """截图保存为base64"""
  81.     now_time, screen_file = cm.screen_path
  82.     driver.save_screenshot(screen_file)
  83.     allure.attach.file(screen_file,
  84.                        "失败截图{}".format(now_time),
  85.                        allure.attachment_type.PNG)
  86.     with open(screen_file, 'rb') as f:
  87.         imagebase64 = base64.b64encode(f.read())
  88.     return imagebase64.decode()
复制代码
    来看看我们修改了什么:
     

  • 我们修改了_capture_screenshot函数
    在里面我们使用了webdriver截图生成文件,并使用allure.attach.file方法将文件添加到了allure测试报告中。
     并且我们还返回了图片的base64编码,这样可以让pytest-html的错误截图和allure都能生效。
     运行一次得到两份报告,一份是简单的一份是好看内容丰富的。
     现在我们在测试用例中构建一个预期的错误测试一个我们的这个代码。
     
    修改test_002测试用例
   
  1.         assert not all(["selenium" in i for i in search.imagine])
复制代码
    运行一下:
     
     
     可以看到allure报告中已经有了这个错误的信息。
     再来看看pytest-html中生成的报告:
     
     
     可以看到两份生成的报告都附带了错误的截图,真是鱼和熊掌可以兼得呢。
     好了,到这里可以说allure的报告就先到这里了,以后发现allure其他的精彩之处我再来分享。
         
  开源地址#

   为了方便学习交流,本次的示例项目已经保存在网盘了,直接私信000
   
    重点:学习资料学习当然离不开资料,这里当然也给你们准备了600G的学习资料

   需要的私我关键字【000】免费获取哦 注意关键字是:000
   

   项目实战

   app项目,银行项目,医药项目,电商,金融
   
   
   
   大型电商项目

   
   
   
   全套软件测试自动化测试教学视频

   
   
   300G教程资料下载【视频教程+PPT+项目源码】

   
   
   ​
   全套软件测试自动化测试大厂面经

   
   
   ​
   python自动化测试++全套模板+性能测试

   
   
   ​
   
   
   
   ​
   听说关注我并三连的铁汁都已经升职加薪暴富了哦!!!!
   

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

嚴華

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表