1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
|
import operator
import sys
from dataclasses import dataclass
from typing import TYPE_CHECKING, ClassVar, no_type_check
from unittest.mock import Mock
import numpy as np
import pytest
from psygnal import SignalInstance
from psygnal._group import SignalRelay
try:
import pydantic.version
PYDANTIC_V2 = pydantic.version.VERSION.startswith("2")
except ImportError:
PYDANTIC_V2 = False
from psygnal import (
SignalGroupDescriptor,
evented,
get_evented_namespace,
is_evented,
)
from psygnal._group import SignalGroup
decorated_or_descriptor = pytest.mark.parametrize(
"decorator", [True, False], ids=["decorator", "descriptor"]
)
@no_type_check
def _check_events(cls, events_ns="events"):
obj = cls(bar=1, baz="2", qux=np.zeros(3))
assert is_evented(obj)
assert is_evented(cls)
assert get_evented_namespace(cls) == events_ns
assert isinstance(getattr(cls, events_ns), SignalGroupDescriptor)
events = getattr(obj, events_ns)
assert isinstance(events, SignalGroup)
assert set(events) == {"bar", "baz", "qux"}
mock = Mock()
events.bar.connect(mock)
assert obj.bar == 1
obj.bar = 2
assert obj.bar == 2
mock.assert_called_once_with(2, 1)
mock.reset_mock()
obj.baz = "3"
mock.assert_not_called()
mock.reset_mock()
events.qux.connect(mock)
obj.qux = np.ones(3)
mock.assert_called_once()
assert np.array_equal(obj.qux, np.ones(3))
DCLASS_KWARGS = []
if sys.version_info >= (3, 10):
DCLASS_KWARGS.extend([{"slots": True}, {"slots": False}])
@decorated_or_descriptor
@pytest.mark.parametrize("kwargs", DCLASS_KWARGS)
def test_native_dataclass(decorator: bool, kwargs: dict) -> None:
@dataclass(**kwargs)
class Base:
bar: int
baz: str
qux: np.ndarray
if decorator:
@evented(equality_operators={"qux": operator.eq}) # just for test coverage
class Foo(Base): ...
else:
class Foo(Base): # type: ignore [no-redef]
events: ClassVar[SignalGroupDescriptor] = SignalGroupDescriptor(
equality_operators={"qux": operator.eq}
)
_check_events(Foo)
@decorated_or_descriptor
@pytest.mark.parametrize("slots", [True, False])
def test_attrs_dataclass(decorator: bool, slots: bool) -> None:
from attrs import define
@define(slots=slots) # type: ignore [misc]
class Base:
bar: int
baz: str
qux: np.ndarray
if decorator:
@evented
class Foo(Base): ...
else:
class Foo(Base): # type: ignore [no-redef]
events: ClassVar[SignalGroupDescriptor] = SignalGroupDescriptor()
_check_events(Foo)
if PYDANTIC_V2:
Config = {"arbitrary_types_allowed": True}
else:
class Config:
arbitrary_types_allowed = True
@decorated_or_descriptor
def test_pydantic_dataclass(decorator: bool) -> None:
pytest.importorskip("pydantic")
from pydantic.dataclasses import dataclass
@dataclass(config=Config)
class Base:
bar: int
baz: str
qux: np.ndarray
if decorator:
@evented
class Foo(Base): ...
else:
class Foo(Base): # type: ignore [no-redef]
events: ClassVar[SignalGroupDescriptor] = SignalGroupDescriptor()
_check_events(Foo)
@decorated_or_descriptor
def test_pydantic_base_model(decorator: bool) -> None:
pytest.importorskip("pydantic")
from pydantic import BaseModel
class Base(BaseModel):
bar: int
baz: str
qux: np.ndarray
if PYDANTIC_V2:
model_config = Config
else:
Config = Config # type: ignore
if decorator:
@evented(events_namespace="my_events")
class Foo(Base): ...
else:
class Foo(Base): # type: ignore [no-redef]
my_events: ClassVar[SignalGroupDescriptor] = SignalGroupDescriptor()
_check_events(Foo, "my_events")
@pytest.mark.parametrize("decorator", [True, False], ids=["decorator", "descriptor"])
def test_msgspec_struct(decorator: bool) -> None:
if TYPE_CHECKING:
import msgspec
else:
msgspec = pytest.importorskip("msgspec") # remove when py37 is dropped
if decorator:
@evented
class Foo(msgspec.Struct):
bar: int
baz: str
qux: np.ndarray
else:
class Foo(msgspec.Struct): # type: ignore [no-redef]
bar: int
baz: str
qux: np.ndarray
events: ClassVar[SignalGroupDescriptor] = SignalGroupDescriptor()
_check_events(Foo)
def test_no_signals_warn() -> None:
with pytest.warns(UserWarning, match="No mutable fields found on class"):
@evented
class Foo: ...
_ = Foo().events # type: ignore
with pytest.warns(UserWarning, match="No mutable fields found on class"):
class Foo2:
events = SignalGroupDescriptor()
_ = Foo2().events
@dataclass
class Foo3:
events = SignalGroupDescriptor(warn_on_no_fields=False)
# no warning
_ = Foo3().events
@dataclass
class FooPicklable:
bar: int
events: ClassVar[SignalGroupDescriptor] = SignalGroupDescriptor(
cache_on_instance=False
)
def test_pickle() -> None:
"""Make sure that evented classes are still picklable."""
import pickle
obj = FooPicklable(1)
obj2 = pickle.loads(pickle.dumps(obj))
assert obj2.bar == 1
def test_get_namespace() -> None:
@evented(events_namespace="my_events")
@dataclass
class Foo:
x: int
assert get_evented_namespace(Foo) == "my_events"
assert is_evented(Foo)
def test_name_conflicts() -> None:
# https://github.com/pyapp-kit/psygnal/pull/269
from dataclasses import field
@evented
@dataclass
class Foo:
name: str
all: bool = False
is_uniform: bool = True
signals: list = field(default_factory=list)
obj = Foo("foo")
assert obj.name == "foo"
with pytest.warns(
UserWarning, match=r"Names \['all', 'is_uniform', 'signals'\] are reserved"
):
group = obj.events
assert isinstance(group, SignalGroup)
assert "name" in group
assert isinstance(group.name, SignalInstance)
assert group["name"] is group.name
assert "is_uniform" in group and isinstance(group["is_uniform"], SignalInstance)
assert "signals" in group and isinstance(group["signals"], SignalInstance)
# group.all is always a relay
assert isinstance(group.all, SignalRelay)
# getitem returns the signal
assert "all" in group and isinstance(group["all"], SignalInstance)
assert not isinstance(group["all"], SignalRelay)
with pytest.raises(AttributeError): # it's not writeable
group.all = SignalRelay({})
assert group.psygnals_uniform() is False
@evented
@dataclass
class Foo2:
psygnals_uniform: bool = True
obj2 = Foo2()
with pytest.warns(match=r"Name \['psygnals_uniform'\] is reserved"):
_ = obj2.events
@dataclass
class Foo3:
field: int = 1
_psygnal_signals: str = "signals"
with pytest.raises(
TypeError, match="Fields on an evented class cannot start with '_psygnal'"
):
_ = evented(Foo3)
|