【发布时间】:2021-08-11 01:47:57
【问题描述】:
我有一系列pytest 灯具,它们在本质上非常相似。固定装置被传递给验证某些 CSS 选择器是否正常工作的测试。每个夹具中的代码几乎相同;唯一的区别是每个灯具的page.goto() 函数都传递了不同的 URL。
每个灯具看起来像这样:
import pytest
@pytest.fixture(scope="module")
def goto_pagename():
with sync_playwright() as play:
browser = play.chromium.launch()
page = browser.new_page()
page.goto(TestScrapeWebsite.address)
yield page
browser.close()
我尝试使用一个装饰器,它涵盖了除page.goto() 和yield page 之外的所有代码,如下所示:
from playwright.sync_api import sync_playwright
def get_page(func):
def wrapper(*args, **kwargs):
with sync_playwright() as play:
browser = play.chromium.launch(*args, **kwargs)
page = browser.new_page()
func(page)
browser.close()
return wrapper
然后,固定装置和测试看起来像这样:
import pytest
@pytest.fixture(scope="module")
@get_page
def google_page(page):
page.goto(TestScrapeGoogle.address)
yield page
@pytest.fixture(scope="module")
@get_page
def stackoverflow_page(page):
page.goto(TestScrapeStackOverflow.address)
yield page
@pytest.fixture(scope="module")
@get_page
def github_page(page):
page.goto(TestScrapeGitHub.address)
yield page
class TestScrapeGoogle:
address = "https://google.com/"
def test_selectors(self, google_page):
assert google_page.url == self.address
class TestScrapeStackOverflow:
address = "https://stackoverflow.com/"
def test_selectors(self, stackoverflow_page):
assert stackoverflow_page.url == self.address
class TestScrapeGitHub:
address = "https://github.com/"
def test_selectors(self, github_page):
assert github_page.url == self.address
但是,在运行 pytest 测试运行程序时,引发了有关夹具的异常:
$ pytest test_script.py
...
============================================================================================ short test summary info =============================================================================================
FAILED test_script.py::TestScrapeGoogle::test_selectors - AttributeError: 'NoneType' object has no attribute 'url'
FAILED test_script.py::TestScrapeStackOverflow::test_selectors - AttributeError: 'NoneType' object has no attribute 'url'
FAILED test_script.py::TestScrapeGitHub::test_selectors - AttributeError: 'NoneType' object has no attribute 'url'
有没有办法修改我为简化每个固定装置而采取的方法?或者,我在问pytest 的功能吗,我是否只需要完整地写出每个夹具?
类似问题:
下面我添加了一些 Stack Overflow 问题,这些问题会在搜索我的问题的标题时出现。我还说明了为什么该问题的答案不是我的问题的理想解决方案。
-
Multiple copies of a pytest fixture:
pytest夹具的所有副本都用于相同的测试。就我而言,我希望每个测试都有一个单独的夹具。 - Run a test with two different pytest fixtures:虽然有多个夹具,但每个测试(很可能)只有一个夹具来装饰测试。
【问题讨论】:
标签: python python-3.x pytest