前几天逛 GitHub 发现一个基于 Selenium 和 unittest 单元测试框架的一个测试框架 SeleniumBase.
GitHub 地址: https://github.com/seleniumbase/SeleniumBase
大概看了一个它的 API, 它的设计思想与我的 pyse 很像.
GitHub 地址: https://github.com/defnngj/pyse
但是, 提供了更加丰富的 API, 和一些强大的功能.
首先, SeleniumBase 支持 pip 安装:
> pip install seleniumbase
它依赖的库比较多, 包括 pytest,nose 这些第三方单元测试框架, 是为更方便的运行测试用例, 因为这两个测试框架是支持 unittest 测试用例的执行的.
SeleniumBase 还生成了 "seleniumbase" 命令, 主要是为了方便我们安装浏览器驱动.
你可以通过下面的命令安装不同的浏览器驱动.
- seleniumbase install chromedriver
- seleniumbase install geckodriver
- seleniumbase install edgedriver
- seleniumbase install iedriver
- seleniumbase install operadriver
在项目的 examples / 目录下面提供了丰富的例子. 其中 my_first_test.py 如下:
- from seleniumbase import BaseCase
- class MyTestClass(BaseCase):
- def test_basic(self):
- self.open("https://xkcd.com/353/")
- self.assert_element('img[alt="Python"]')
- self.click('a[rel="license"]')
- self.assert_text("free to copy", "div center")
- self.open("https://xkcd.com/1481/")
- title = self.get_attribute("#comic img", "title")
- self.assert_true("86,400 seconds per day" in title)
- self.click("link=Blag")
- self.assert_text("The blag of the webcomic", "h2")
- self.update_text("input#s", "Robots!\n")
- self.assert_text("Hooray robots!", "#content")
- self.open("https://xkcd.com/1319/")
- self.assert_exact_text("Automation", "#ctitle")
如果你很熟悉 Selenium 的话, 我想这些 API 对你来说并没什么难度. 脚本中的元素定位默认使用的 CSS.
接下来是脚本的执行, 你可以使用 pytest 或 nose, 因为 SeleniumBase 已经帮你装好了:
- > pytest my_first_test.py --browser=Chrome
- > nosetests my_first_test.py --browser=Firefox
它还提供的有 -demo_mode 模式, 使脚本执行的过程变得很慢, 而且还会让操作的元素高亮显示, 方便你查看和定位问题.
pytest my_first_test.py --demo_mode
在调试 Selenium 脚本的时候, 我们希望错误时可以暂停脚本, 那么可以加 --pdb -s 参数.
pytest my_first_test.py --pdb -s
当脚本报错时是这样的:
上面的代码将使浏览器窗口保持打开状态, 以防出现故障. 你可以继续输入命令:
"c": 继续
"s": 步骤
"n": 下一步
你还可以利用 pytest 的 pytest-thml 插件生成测试报告.
pytest test_suite.py --html=report.HTML
当用例运行失败时自动截图!
其他就没什么亮点了, 不过提供的 API 非常丰富, 而且作者非常积极的在维护项目. 你可以在项目说明中查看, 或者通过提供的 examples / 的例子来学习.
来源: https://www.cnblogs.com/fnng/p/10934588.html