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 311 312 313 314 315 316
|
# --------------------------------------------------------------------------------------
# Copyright (c) 2022-2024, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# --------------------------------------------------------------------------------------
from datetime import datetime
import pytest
from atom.api import Atom, Bool, Constant, Float, GetState, Int, List, Range, Str, Typed
try:
import pytest_benchmark # noqa: F401
BENCHMARK_INSTALLED = True
except ImportError:
BENCHMARK_INSTALLED = False
class AtomBase(Atom):
def __getstate_py__(self):
state = {}
state.update(getattr(self, "__dict__", {}))
for name in self.__class__.__slotnames__:
state[name] = getattr(self, name)
for key in self.members():
state[key] = getattr(self, key)
return state
def __setstate_py__(self, state):
for key, value in state.items():
setattr(self, key, value)
def test_getstate_member_slots_error():
class Test(Atom):
__slots__ = ("a", "b")
Test.__slotnames__ = None
v = Test()
with pytest.raises(SystemError):
v.__getstate__()
def test_getstate_member_error():
class Test(Atom):
created = Typed(datetime, optional=False)
Test.created.set_getstate_mode(GetState.Include, None)
v = Test()
with pytest.raises(ValueError):
v.__getstate__()
def test_getstate():
class Test(Atom):
x = Int(3)
y = Int(2)
t = Test()
assert t.__getstate__() == {"x": 3, "y": 2}
def test_getstate_constant():
class Test(Atom):
x = Int(3)
y = Int(2)
z = Constant(4)
t = Test()
assert "z" not in t.__getstate__()
def test_getstate_frozen():
class Test(Atom):
x = Int(3)
y = Int(2)
t = Test()
t.freeze()
assert t.__getstate__() == {"x": 3, "y": 2, "--frozen": None}
def test_setstate_frozen():
class Test(Atom):
x = Int(3)
y = Int(2)
t = Test()
t.__setstate__({"x": 3, "y": 2, "--frozen": None})
with pytest.raises(AttributeError):
t.x = 5
# Setting again does not work
t.__setstate__({"--frozen": 0})
with pytest.raises(AttributeError):
t.x = 5
# Check that it can be modified if frozen flag is missing
t = Test()
t.__setstate__({"x": 3, "y": 2})
t.x = 5
def test_setstate_non_str_key():
class Test(Atom):
x = Int(3)
y = Int(2)
t = Test()
with pytest.raises(TypeError):
t.__setstate__({0: "yes"})
class Foo:
def __eq__(self, other):
raise ValueError("Do not compare me")
with pytest.raises(TypeError):
t.__setstate__({Foo(): "yes"})
@pytest.mark.skipif(not BENCHMARK_INSTALLED, reason="benchmark is not installed")
@pytest.mark.benchmark(group="getstate")
@pytest.mark.parametrize("fn", ("c", "py"))
def test_bench_getstate(benchmark, fn):
class Test(AtomBase):
first_name = Str("First")
last_name = Str("Last")
age = Range(low=0)
debug = Bool(False)
items = List(default=[1, 2, 3])
expected = {
"first_name": "First",
"last_name": "Last",
"age": 0,
"debug": False,
"items": [1, 2, 3],
}
p = Test()
if fn == "py":
func = p.__getstate_py__
else:
func = p.__getstate__
def task():
assert func() == expected
benchmark(task)
@pytest.mark.skipif(not BENCHMARK_INSTALLED, reason="benchmark is not installed")
@pytest.mark.benchmark(group="loopback")
@pytest.mark.parametrize("fn", ("c", "py"))
def test_bench_loopback(benchmark, fn):
class Test(AtomBase):
first_name = Str("First")
last_name = Str("Last")
age = Range(low=0)
debug = Bool(False)
items = List(default=[1, 2, 3])
expected = {
"first_name": "First",
"last_name": "Last",
"age": 0,
"debug": False,
"items": [1, 2, 3],
}
if fn == "py":
def task():
t = Test()
t.__setstate_py__(expected)
assert t.__getstate_py__() == expected
else:
def task():
t = Test()
t.__setstate__(expected)
assert t.__getstate__() == expected
benchmark(task)
@pytest.mark.skipif(not BENCHMARK_INSTALLED, reason="benchmark is not installed")
@pytest.mark.benchmark(group="getstate-dict")
@pytest.mark.parametrize("fn", ("c", "py"))
def test_bench_getstate_dict(benchmark, fn):
class Foo:
def __init__(self):
self.count = 1
class Test(AtomBase, Foo):
title = Str("Title")
enabled = Bool(True)
category = Str("Main")
tags = List(default=["foo", "bar"])
expected = {
"count": 1,
"title": "Title",
"enabled": True,
"category": "Main",
"tags": ["foo", "bar"],
}
p = Test()
p.count = 1
if fn == "py":
func = p.__getstate_py__
else:
func = p.__getstate__
def task():
assert func() == expected
benchmark(task)
@pytest.mark.skipif(not BENCHMARK_INSTALLED, reason="benchmark is not installed")
@pytest.mark.benchmark(group="getstate-slots")
@pytest.mark.parametrize("fn", ("c", "py"))
def test_bench_getstate_slots(benchmark, fn):
class Test(AtomBase):
__slots__ = ("bar", "foo")
name = Str("Name")
enabled = Bool(True)
rating = Float()
created = Typed(datetime)
tags = List(default=["foo", "bar"])
now = datetime.now()
expected = {
"foo": 1,
"bar": True,
"name": "Name",
"enabled": True,
"rating": 0.0,
"created": now,
"tags": ["foo", "bar"],
}
p = Test()
p.foo = 1
p.bar = True
p.created = now
if fn == "py":
func = p.__getstate_py__
else:
func = p.__getstate__
def task():
assert func() == expected
benchmark(task)
@pytest.mark.skipif(not BENCHMARK_INSTALLED, reason="benchmark is not installed")
@pytest.mark.benchmark(group="state")
@pytest.mark.parametrize("fn", ("c", "py"))
def test_bench_setstate(benchmark, fn):
class Test(AtomBase):
x = Int()
y = Int()
if fn == "py":
def task():
t = Test()
t.__setstate_py__({"x": 1, "y": 2})
assert t.x == 1
assert t.y == 2
else:
def task():
t = Test()
t.__setstate__({"x": 1, "y": 2})
assert t.x == 1
assert t.y == 2
benchmark(task)
def test_setstate():
class Test(Atom):
x = Int()
y = Int()
t = Test()
t.__setstate__({"x": 1, "y": 2})
assert t.x == 1
assert t.y == 2
def test_setstate_errors(caplog):
class Test(AtomBase):
x = Int()
y = Int()
t = Test()
with pytest.raises(TypeError):
t.__setstate__() # Incorrect number of args
with pytest.raises(TypeError):
t.__setstate__({}, False) # Incorrect number of args
with pytest.raises(TypeError):
t.__setstate__(None) # Not a mapping (no items() method)
with pytest.raises(TypeError):
t.__setstate__(["z"]) # Not a mapping (has no items() method)
with pytest.raises(AttributeError):
t.__setstate__({"z": 3}) # Invalid attribute
|