python - Pytest - yield inside for 仅适用于第一种方式
问题描述
我试图让相同的测试在不同的浏览器中运行。每个浏览器都可以完美运行(["Chrome"] 或 ["Firefox"]),但是如果 supportedBrowsers 数组接收两个元素,则在第二次迭代中 yield 根本不会做任何事情,执行不会转到测试和夹具的其余部分都没有,浏览器站在那里打开。我错过了什么?
@pytest.fixture(scope='module')
def driver():
url = "http://localhost:1234/"
supportedBrowsers = ["Chrome", "Firefox"]
for x in supportedBrowsers:
if x == "Firefox":
option = webdriver.firefox.options.Options()
driverObj = webdriver.Firefox(executable_path=GeckoDriverManager().install())
elif x == "Chrome":
option = webdriver.chrome.options.Options()
driverObj = webdriver.Chrome(ChromeDriverManager().install())
option.headless = True
driverObj.implicitly_wait(10) # seconds
driverObj.get(url)
yield driverObj
driverObj.quit()
解决方案
当您使用 yield 时,有必要在函数上显式调用 next 以便前进到循环的下一次迭代。这就是产量的工作原理。喜欢
@pytest.fixture(scope='module')
def driver():
url = "http://localhost:1234/"
supportedBrowsers = ["Chrome", "Firefox"]
for x in supportedBrowsers:
if x == "Firefox":
option = webdriver.firefox.options.Options()
driverObj = webdriver.Firefox(executable_path=GeckoDriverManager().install())
elif x == "Chrome":
option = webdriver.chrome.options.Options()
driverObj = webdriver.Chrome(ChromeDriverManager().install())
option.headless = True
driverObj.implicitly_wait(10) # seconds
driverObj.get(url)
yield driverObj
driverObj.quit()
d=driver()
next(d) # this is when the function will actually goto yield and #stop there
next(d) # next iteration of loop.
# you have call it as many times as you have browsers
或者,您可以使用
for driver in driver():
pass # automatically call next
推荐阅读
- angularjs - 如何在 Jest 中模拟 Onclose 事件?
- salesforce - 如何访问 Salesforce Lightning Web 组件中加载的脚本?
- java - Spring WebClient ExchangeFilterFunction 在 next.exchange() 之后再次运行
- c# - 不允许原始类型的通用约束
- javascript - Sails.js 计算模型/关联的成员
- azure - 如何使用 Azure PowerShell 创建 Azure 网络安全组流日志
- java - Spring Java JPA 将 String 保存为 tinyblob,导致 json 解析错误
- wpf - .NET 5.0 - 立即停止 WPF 应用程序中正在运行的线程
- python - pandas 通过从合并中排除某些列来合并
- scala - 加入一个 DF 和另外两个有条件的 - Scala Spark