测试游记

简单一行代码截图记录每次页面错误

来呀~

欢迎关注我的公众号

在进行Web UI的自动化测试的时候,有些错误无法简单地通过文字描述清楚,还是需要进行页面截图。但为了让该优化不需要投入过多的时间,采用装饰器进行装饰。

基本思路:正常执行脚本,当异常或断言报错时,触发截图,再抛出原异常

编写装饰器

虚构园艺画面的证据纸条被收进报告,报告上仍保留清晰的失败叉。
截图是失败的附件,不是对结果的修复。即使收集了现场画面,也要让报告继续显示原用例失败。

大概装饰器代码如下

  1. def error_screenshot(func):

  2. @wraps(func)

  3. def decorator(*args, **kwargs):

  4. try:

  5. obj = func(*args, **kwargs)

  6. except Exception as e:

  7. 截图操作

  8. raise Exception(e)

  9. return obj

  10. return decorator

使用 tryexcept可以捕获到异常,使用 raiseException(e)完成截图后把异常继续抛出。

因为每次的 driver对象所处的 类名可能不一致,所以进行一定的判断。假设进行界面操作的类名都是以 ui结尾。

  1. for key, value in locals()['kwargs'].items():

  2. if key.endswith('ui'):

  3. pic_name = f'{str(time.time())}.png'

  4. value.driver.save_screenshot(pic_name)

  5. allure.attach.file(f'{pic_name}', attachment_type=allure.attachment_type.PNG)

循环当前的 locals()['kwargs']拿到该类名,再使用该类中的 driver对象进行截图操作,并使用 allure将图片显示在报告中。

编写操作类

本次测试将 百度当做测试目标

简单的封装一个操作百度的界面操作类:BaiDuActionUi

包含了:

  • 打开百度 open_web

  • 在输入栏输入指定内容 input_message

  • 在定位错误的输入栏输入指定内容 input_message_bug

  • 点击查找按钮 search

  • 关闭浏览器 close

  1. class BaiDuActionUi():

  2. def __init__(self):

  3. self.url = 'https://www.baidu.com'

  4. self.driver = webdriver.Chrome(executable_path='./chromedriver')

  5. self.driver.implicitly_wait(3)

  6. self.input = 'kw' # 搜索栏

  7. self.search_btn = 'su' # 查找按钮

  8. def __str__(self):

  9. return '百度'

  10. @allure.step('打开页面')

  11. def open_web(self):

  12. self.driver.get(self.url)

  13. @allure.step('输入内容')

  14. def input_message(self, message):

  15. self.driver.find_element_by_id(self.input).clear()

  16. self.driver.find_element_by_id(self.input).send_keys(message)

  17. @allure.step('有异常的输入内容')

  18. def input_message_bug(self, message):

  19. self.driver.find_element_by_id(f'{self.input}1').clear()

  20. self.driver.find_element_by_id(f'{self.input}1').send_keys(message)

  21. @allure.step('点击查找')

  22. def search(self):

  23. self.driver.find_element_by_id(self.search_btn).click()

  24. @allure.step('关闭浏览器')

  25. def close(self):

  26. try:

  27. self.driver.close()

  28. except Exception as e:

  29. print(f'关闭浏览器失败:{e}')

编写测试代码

使用 fixture编写测试前浏览器的开启,测试后浏览器的关闭

  • 正常测试: test_selenium

  • 抛出断言错误的测试: test_selenium1

  • 定位异常的测试: test_selenium2

  1. @pytest.fixture()

  2. def baiduactionui():

  3. baidu = BaiDuActionUi()

  4. baidu.open_web()

  5. yield baidu

  6. baidu.close()

  7. @error_screenshot

  8. def test_selenium(baiduactionui):

  9. """

  10. 正常

  11. """

  12. with allure.step(f'测试输入python点击查找'):

  13. baiduactionui.input_message('python')

  14. baiduactionui.search()

  15. @error_screenshot

  16. def test_selenium1(baiduactionui):

  17. """

  18. assert 异常

  19. """

  20. with allure.step(f'测试输入python点击查找'):

  21. baiduactionui.input_message('python')

  22. baiduactionui.search()

  23. assert 0, '瞎报的异常'

  24. @error_screenshot

  25. def test_selenium2(baiduactionui):

  26. """

  27. driver 查找元素异常

  28. """

  29. with allure.step(f'测试输入python点击查找'):

  30. baiduactionui.input_message_bug('python')

  31. baiduactionui.search()

  32. if __name__ == '__main__':

  33. pytest.main([

  34. '-v', 'test_selenium.py', '--alluredir', './allure_report'

  35. ])

  36. os.system("allure generate -c allure_report/ -o report --clean")

测试结果

两个虚构页面分别停在空白网格和结果已出现的网格,两边有不同的提示标记。
找不到控件时界面可能还没进入结果页;校验失败时则可能已经显示结果。把截图和失败步骤一起看,能帮助区分这两种情况。
  1. ============================= test session starts ==============================

  2. platform darwin -- Python 3.7.1, pytest-5.0.1, py-1.8.0, pluggy-0.12.0 -- /usr/local/bin/python3.7

  3. cachedir: .pytest_cache

  4. rootdir: /Users/zhongxin/Desktop/py/zx/test

  5. plugins: allure-pytest-2.8.5

  6. collecting ... collected 3 items

  7. test_selenium.py::test_selenium PASSED [ 33%]

  8. test_selenium.py::test_selenium1 FAILED [ 66%]

  9. test_selenium.py::test_selenium2 FAILED [100%]

  10. =================================== FAILURES ===================================

点击 测试套找到错误的脚本 test_selenium1

找到错误的脚本 test_selenium2

test_selenium没有错误,报告中没有截图

test_selenium1在完成输入和查找后断言报错,页面截图停留在搜索完成页面

test_selenium2在输入栏的位置定位元素错误,页面截图停留在搜索开始页面

完整代码

  1. # -*- coding:utf-8 -*-

  2. """

  3. @Describe: selenium_test

  4. @Author: zhongxin

  5. @Time: 2019-09-29 22:50

  6. @File: test_selenium.py

  7. @Email: 490336534@qq.com

  8. """

  9. import os

  10. import time

  11. import allure

  12. import pytest

  13. from selenium import webdriver

  14. from functools import wraps

  15. def error_screenshot(func):

  16. @wraps(func)

  17. def decorator(*args, **kwargs):

  18. obj = ''

  19. try:

  20. obj = func(*args, **kwargs)

  21. except Exception as e:

  22. for key, value in locals()['kwargs'].items():

  23. if key.endswith('ui'):

  24. pic_name = f'{str(time.time())}.png'

  25. value.driver.save_screenshot(pic_name)

  26. allure.attach.file(f'{pic_name}', attachment_type=allure.attachment_type.PNG)

  27. raise Exception(e)

  28. return obj

  29. return decorator

  30. class BaiDuActionUi():

  31. def __init__(self):

  32. self.url = 'https://www.baidu.com'

  33. self.driver = webdriver.Chrome(executable_path='./chromedriver')

  34. self.driver.implicitly_wait(3)

  35. self.input = 'kw' # 搜索栏

  36. self.search_btn = 'su' # 查找按钮

  37. def __str__(self):

  38. return '百度'

  39. @allure.step('打开页面')

  40. def open_web(self):

  41. self.driver.get(self.url)

  42. @allure.step('输入内容')

  43. def input_message(self, message):

  44. self.driver.find_element_by_id(self.input).clear()

  45. self.driver.find_element_by_id(self.input).send_keys(message)

  46. @allure.step('有异常的输入内容')

  47. def input_message_bug(self, message):

  48. self.driver.find_element_by_id(f'{self.input}1').clear()

  49. self.driver.find_element_by_id(f'{self.input}1').send_keys(message)

  50. @allure.step('点击查找')

  51. def search(self):

  52. self.driver.find_element_by_id(self.search_btn).click()

  53. @allure.step('关闭浏览器')

  54. def close(self):

  55. try:

  56. self.driver.close()

  57. except Exception as e:

  58. print(f'关闭浏览器失败:{e}')

  59. @pytest.fixture()

  60. def baiduactionui():

  61. baidu = BaiDuActionUi()

  62. baidu.open_web()

  63. yield baidu

  64. baidu.close()

  65. @error_screenshot

  66. def test_selenium(baiduactionui):

  67. """

  68. 正常

  69. """

  70. with allure.step(f'测试输入python点击查找'):

  71. baiduactionui.input_message('python')

  72. baiduactionui.search()

  73. @error_screenshot

  74. def test_selenium1(baiduactionui):

  75. """

  76. assert 异常

  77. """

  78. with allure.step(f'测试输入python点击查找'):

  79. baiduactionui.input_message('python')

  80. baiduactionui.search()

  81. assert 0, '瞎报的异常'

  82. @error_screenshot

  83. def test_selenium2(baiduactionui):

  84. """

  85. driver 查找元素异常

  86. """

  87. with allure.step(f'测试输入python点击查找'):

  88. baiduactionui.input_message_bug('python')

  89. baiduactionui.search()

  90. if __name__ == '__main__':

  91. pytest.main([

  92. '-v', 'test_selenium.py', '--alluredir', './allure_report'

  93. ])

  94. os.system("allure generate -c allure_report/ -o report --clean")

本文视频讲解

打开或下载 MP4 ↗

评论与讨论

使用 GitHub 账号留言,评论公开显示。

搜索文章