Repository navigation
Use fixture instance in non-test classes #11619
Replies: 1 comment
|
Hi @peppe-russo A session-scoped fixture already gives every requester the same fixture instance, but pytest fixtures are not globally importable singletons. The supported pattern is to keep the dependency explicit. If creating from dataclasses import dataclass
import pytest
@dataclass
class Area:
x: int
y: int
width: int
height: int
vnc: object
def capture(self):
return self.vnc.capture(
x=self.x,
y=self.y,
width=self.width,
height=self.height,
)
@pytest.fixture
def area_factory(qt_vnc):
def create(**kwargs):
return Area(vnc=qt_vnc, **kwargs)
return createThen: def test_something(area_factory):
area = area_factory(
x=0,
y=0,
width=100,
height=100,
)
area.capture()Because
If many classes need VNC, another clean option is to create one fixture-backed service/context object containing the VNC dependency and have those objects receive that context. Please mark this answer as accepted if it helped, thank you. |
Uh oh!
There was an error while loading. Please reload this page.
Hello everyone, I'm writing a pytest plugin that uses pytest-vnc as a dependency. The way I use it is to wrap it around my own custom fixture to override the
sleepmethod, like so:I then have an
Areaclass in another file that I use quite often around my plugin, which needs to use thatVNCinstance (or more precisely, theqt_vncfixture), example:The current way I'm doing this is to have an optional
vncfield to theAreaclass and just pass the fixture to it when I instanciate the class, which doesn't look very elegant and it's not always possible as I use this class from places where I can't easily access the fixture.Is there a "proper" way to make the
qt_vncfixture like a global singleton or something like that so I can access it from my custom classes? (TheAreaclass is not the only class that needs to use it).Thanks in advance,
Peppe
All reactions