目标:我正在尝试创建一个函数装饰器,它将 Playwright Page(playwright.sync_api._generated.Page)对象传递给包装函数。
问题:对于大多数函数调用,我将能够返回函数调用返回的值。但是,由于 Playwright 需要browser.close()调用,我不能简单地返回Page对象。我不确定问题出在(1)我定义的函数装饰器,还是(2)我对函数装饰器的使用。
我试图在pytest固定装置之后为我的装饰器建模。使用pytest,我会做这样的事情:
@pytest.fixture(scope="module")
def playwright_page():
with sync_playwright() as play:
browser = play.chromium.launch()
page = browser.new_page()
yield page
browser.close()
接着
def open_google(playwright_page):
playwright_page.goto("https://google.com")
函数解码器:
>>> from playwright.sync_api import sync_playwright
>>> def playwright_page(func):
def wrapper(*args, **kwargs):
with sync_playwright() as play:
browser = play.chromium.launch()
page = browser.new_page()
yield page
browser.close()
return wrapper
尝试 1:
>>> @playwright_page
def open_google():
page.goto("https://google.com")
>>> open_google()
<generator object playwright_page.<locals>.wrapper at 0x0000015C5F6CBC10>
尝试 2:
>>> @playwright_page
def open_google():
page = next(page)
page.goto("https://google.com")
>>> open_google()
<generator object playwright_page.<locals>.wrapper at 0x0000015C5FDB7F90>