您打算使用什么测试框架?这将完全改变您用于在测试(或整个测试套件)之前/之后运行此逻辑的语法。
其他注意事项:
您要进行什么类型的测试?
- “单元测试”? (配额 b/c 你不能*在 python 中为网页进行单元测试)
- 集成测试
- 压力/性能测试?
如果您将 Selenium 视为一种对 Web 应用程序 UI 进行单元测试的方法,您可能需要查看一些 JavaScript 测试框架。如果您在 UI 中使用 any JavaScript,请务必检查 JavaScript 框架。使用 JavaScript 来操作 DOM,并尝试使用 Selenium 来操作 DOM 是对 DOM 的一个巨大竞争条件。
您打算使用 Selenium 测试什么?
- 检查您的 UI 按钮是否正确连接?
- Web 应用的业务规则?
我强烈建议您使用 Selenium 来验证您的网络应用程序中的幸福路径(即我可以点击此按钮),并不测试您的业务规则;锤击 API 来执行这些业务规则。与 UI 相比,API 更改的可能性要小得多,并且 UI 的更改经常会在您的 Selenium 测试中导致误报(测试中断会导致失败,而不是应用中的真正失败)。
请不要因此而气馁!您正在编写测试真是太棒了!
如果使用得当,Selenium 是一个很好的工具,它很容易重载并导致测试不一致(取决于 JS 的数量和 JS 框架)。
关于您的代码的指针:
使类成为您可以根据需要实例化和绑定的东西 - 使跨框架使用代码更容易,调试更容易 b/c 您只需打开 python 解释器并使用它。
# file named my_webdriver.py
import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')))
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
class MyDriver():
def __init__(self):
self.driver = webdriver.Firefox()
self.base_url = "www.google.com"
self.driver.implicitly_wait(30)
#self.verificationErrors = [] # delete this line, and deal with errors in the framework
self.accept_next_alert = True
self.driver.maximize_window()
self.reset()
def reset(self):
"""So I can be lazy and reset to a know starting point before each test case"""
self.driver.get(self.base_url)
self.driver.delete_all_cookies()
def teardown(self):
self.driver.quit()
使用它:
from my_webdriver import MyDriver
driver = MyDriver()
driver.get('http://my-awesome-app.org')
element = driver.find_element_by_id('some-id')
element.click()
在单元测试框架中绑定它:
import unittest
from my_webdriver import MyDriver
class AwesomeTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
"""Runs once per suite"""
cls.driver = MyDriver()
def setUp(self):
"""Runs before each test case"""
self.driver.reset()
@classmethod
def tearDownClass(cls):
cls.driver.teardown()
def test_stuff(self):
"""a test case!"""
# stuff
pass
祝你好运!希望这有帮助/有用。
*我在 PyCon 上看到了一些关于使用 Python 操作 DOM 的内容,但我认为没有人在生产中这样做。