首页 > 解决方案 > 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()

标签: pythonpytestyield

解决方案


当您使用 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

推荐阅读