WebDriver+Pytest自动化框架SeleniumBase介绍

简介:

  • SeleniumBase是一个基于Selenium-WebDriver和Pytest的Web自动化测试框架
  • gitbub地址:https://github.com/seleniumbase/SeleniumBase
  • 特点:
    • 封装了WebDriver API 可以很方便的调用
    • 提供 —demo_mode 模式,使脚本执行的过程变得很慢,并让操作的元素高亮显示,方便定位问题
    • 可以加 --pdb -s 参数,错误时可以暂停脚本
    • 可以生成带截图的测试报告

安装

通过pip安装

pip install seleniumbase

安装浏览器驱动

seleniumbase install chromedriver

Demo

1、使用自带的示例:my_first_test.py
可以在这个路径下载到本地: https://github.com/seleniumbase/SeleniumBase/blob/master/examples/my_first_test.py

也可以收到新建一个:my_first_test.py,代码如下:

from seleniumbase import BaseCase


class MyTestClass(BaseCase):

    def test_basic(self):
        self.open("https://xkcd.com/353/")           # Navigate browser to page
        self.assert_element('img[alt="Python"]')       # Assert element on page
        self.click('a[rel="license"]')                  # Click element on page
        self.assert_text("free to copy", "div center")    # Assert text in area
        self.open("https://xkcd.com/1481/")
        title = self.get_attribute("#comic img", "title")    # Get an attribute
        self.assert_true("86,400 seconds per day" in title)
        self.click("link=Blag")                                 # Click on link
        self.assert_text("The blag of the webcomic", "h2")
        self.update_text("input#s", "Robots!\n")                    # Type text
        self.assert_text("Hooray robots!", "#content")
        self.open("https://xkcd.com/1319/")
        self.assert_exact_text("Automation", "#ctitle")

2、打开命令行,进入my_first_test.py所在目录,执行命令:

pytest my_first_test.py --browser=chrome

3、执行时让元素高亮显示,命令如下:

pytest my_first_test.py --demo_mode

4、执行完后生成测试报告的命令如下:

pytest test_suite.py --html=report.html

  • test_suite.py 代码如下:
''' NOTE: This test suite contains 2 passing tests and 2 failing tests. '''

import pytest
from seleniumbase import BaseCase


class MyTestSuite(BaseCase):

    def test_1(self):
        self.open("https://xkcd.com/1663/")
        self.assert_text("Garden", "div#ctitle", timeout=3)
        for p in range(4):
            self.click('a[rel="next"]')
        self.assert_text("Algorithms", "div#ctitle", timeout=3)

    @pytest.mark.expected_failure
    def test_2(self):
        print("\n(This test fails on purpose)")
        self.open("https://xkcd.com/1675/")
        raise Exception("FAKE EXCEPTION: This test fails on purpose.")

    def test_3(self):
        self.open("https://xkcd.com/1406/")
        self.assert_text("Universal Converter Box", "div#ctitle", timeout=3)
        self.open("https://xkcd.com/608/")
        self.assert_text("Form", "div#ctitle", timeout=3)

    @pytest.mark.expected_failure
    def test_4(self):
        print("\n(This test fails on purpose)")
        self.open("https://xkcd.com/1670/")
        self.assert_element("FakeElement.DoesNotExist", timeout=0.5)
  • 生成的报告如下:
    WebDriver+Pytest自动化框架SeleniumBase介绍_第1张图片

你可能感兴趣的:(python,自动化测试,自动化测试)