[英]How to write generic selenium tests executed by multiple webdrivers
我对 python 和 selenium 测试都是新手,我遇到了一个可能有标准解决方案但我找不到的问题。
假设我正在开发的项目支持 Google Chrome 和 Firefox。 为每个支持的浏览器编写单独的测试似乎是多余的,所以我一直在尝试编写通用测试方法,这些方法将使用不同的 webdrivers 单独执行。
我目前的方法如下
from selenium import webdriver
def construct_chrome_webdriver () :
driver = webdriver.Chrome()
driver.implicitly_wait(10)
return driver
def construct_firefox_webdriver () :
driver = webdriver.Firefox()
driver.implicitly_wait(10)
return driver
def actual_test_method_implementation (construct_webdriver) :
webdriver = construct_webdriver()
webdriver.get('http://localhost:3333')
# do some testing
def test_method_that_is_executed_by_pytest () :
actual_test_method_implementation(construct_chrome_webdriver)
actual_test_method_implementation(construct_firefox_webdriver)
并且使用命令pytest filename.py
执行测试
这种方法需要大量样板文件——每个测试有两种方法。 有没有更好的方法来实现这一目标?
为了简化您的调用,您可以像这样直接调用您的驱动程序:(使用 getattr)
from selenium import webdriver
driver = getattr(webdriver, "Firefox")(options=youroptions, executable_path="path\\geckodriver.exe" )
或者
driver = getattr(webdriver, "Chrome")(options=options, executable_path="path\\chromedriver.exe" )
getattr(webdriver, "Chrome")(options=options, executable_path="path\\chromedriver.exe" )
相当于
webdriver.Chrome(options=options, executable_path="path\\chromedriver.exe" )
for nav in ["Chrome", "Firefox"]:
driver = getattr(webdriver, nav)
driver.implicitly_wait(10)
driver.get('http://localhost:3333')
好吧,我找到了更好的解决方案,但我仍然不确定这是否是最好的选择,所以几天内我不会将该答案标记为已接受的答案。
conftest.py
import pytest
def pytest_addoption (parser):
parser.addoption("--webdriver", action="store", default="chrome", help="chrome | firefox")
@pytest.fixture
def webdriver_name (request) :
return request.config.getoption('--webdriver')
test_utils.py
from selenium import webdriver
def construct_webdriver (webdriver_name) :
if webdriver_name == 'firefox' :
driver = webdriver.Firefox()
else :
driver = webdriver.Chrome() # chrome is also the default choice
# further webdriver initialization
driver.implicitly_wait(10)
driver.get('http://localhost:3333')
return driver
test_file.py
from test_utils import construct_webdriver
def test_method_that_is_executed_by_pytest (webdriver_name) :
print('webdriver_name = ' + webdriver_name)
webdriver = construct_webdriver(webdriver_name)
# do some testing
测试调用
pytest filename.py --webdriver=chrome
pytest filename.py --webdriver=firefox
在conftest.py
我定义了一个名为webdriver
的测试参数,该参数是在从命令行调用测试时设置的。
名为webdriver_name
的 Fixture 将被注入到 pytest 管理的每个测试方法中。
construct_webdriver
函数将根据 webdriver_name 的值选择一个webdriver_name
实现。
不需要大量样板代码 - 每个测试只需要一种方法
这仍然不是一种标准化的做事方式,我觉得我正在重新发明轮子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.