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 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
|
import asyncio
import weakref
import pytest
from trame_server.core import Translator
from trame_server.state import State
class FakeServer:
def __init__(self):
self._change_callbacks = {}
self._events = []
self.translator = Translator()
def _push_state(self, delta_state):
self._events.append({"type": "push", "content": {**delta_state}})
def add_event(self, content, type="msg"):
self._events.append({"type": type, "content": content})
def __repr__(self) -> str:
lines = [""]
for line_nb, entry in enumerate(self._events):
lines.append(f"{line_nb:6} {entry.get('type'):5}: {entry.get('content')}")
lines.append("")
return "\n".join(lines)
def test_minimum_change_detection():
"""
0 msg : test_minimum_change_detection
1 msg : Before server ready
2 push : {'a': 2}
3 exec : 2
4 msg : After server ready
5 msg : (prev=2) After 2, 3, 3, 4, 4
6 msg : (prev=4) Before Flush
7 push : {'a': 4}
8 exec : 4
9 msg : (prev=4) After Flush
10 msg : Enter with a=4
11 msg : About to exit a=4
12 msg : (prev=4) After with state + same value
13 msg : Enter with a=4
14 msg : About to exit a=5
15 push : {'a': 5}
16 exec : 5
17 msg : (prev=5) After with state + 3,4,5
18 msg : Enter with a=5
19 msg : About to exit a=5
20 msg : (prev=5) After with state + 3,5,4,5
21 msg : Enter with a=5
22 msg : About to exit a=5
23 push : {'b': 3, 'c': 2}
24 msg : (prev=5) After with state + a:1,5 b:2,3 c:3,2
25 msg : Enter with a=5
26 msg : About to exit a=1
27 push : {'a': 1, 'b': 2, 'c': 3}
28 exec : 1
"""
server = FakeServer()
server.add_event("test_minimum_change_detection")
state = State(commit_fn=server._push_state)
@state.change("a")
def on_change_exec(a, **_):
server.add_event(type="exec", content=a)
state.a = 1
state.a = 1
state.a = 2
state.a = 2
server.add_event("Before server ready")
state.ready()
server.add_event("After server ready")
state.a = 2
state.a = 3
state.a = 3
state.a = 4
state.a = 4
server.add_event("(prev=2) After 2, 3, 3, 4, 4")
# Flush
server.add_event("(prev=4) Before Flush")
state.flush()
server.add_event("(prev=4) After Flush")
# This should be a NoOp
with state:
server.add_event(f"Enter with a={state.a}")
state.a = 4
server.add_event(f"About to exit a={state.a}")
server.add_event("(prev=4) After with state + same value")
with state:
server.add_event(f"Enter with a={state.a}")
state.a = 3
state.a = 4
state.a = 5
server.add_event(f"About to exit a={state.a}")
server.add_event("(prev=5) After with state + 3,4,5")
# Even though it changed, finally it is the same value
with state:
server.add_event(f"Enter with a={state.a}")
state.a = 3
state.a = 5
state.a = 4
state.a = 5
server.add_event(f"About to exit a={state.a}")
server.add_event("(prev=5) After with state + 3,5,4,5")
# Use update to set {a: 1, b: 2, c: 3}
with state:
server.add_event(f"Enter with a={state.a}")
state.update({"a": 1, "b": 2, "c": 3})
state.update({"a": 5, "b": 3, "c": 2})
server.add_event(f"About to exit a={state.a}")
server.add_event("(prev=5) After with state + a:1,5 b:2,3 c:3,2")
# Use update to set {a: 1, b: 2, c: 3}
with state:
server.add_event(f"Enter with a={state.a}")
state.update({"a": 1, "b": 2, "c": 3})
server.add_event(f"About to exit a={state.a}")
# Validate event
result = [line.strip() for line in str(server).split("\n")]
expected = [
line.strip() for line in str(test_minimum_change_detection.__doc__).split("\n")
]
# Grab new scenario output
# print(expected)
# print("-"*60)
# print(result)
assert expected == result
def test_client_only():
server = FakeServer()
server.add_event("test_client_only")
state = State(commit_fn=server._push_state)
state.ready()
state.aa = 1
state.client_only("aa")
def test_dict_api():
server = FakeServer()
server.add_event("test_dict_api")
state = State(commit_fn=server._push_state)
state.flush() # should return right away since not ready
state.ready()
state.a = 1
state.c = []
assert state.has("a")
assert not state.has("b")
state.setdefault("a", 10)
state.setdefault("b", 20)
assert state.has("b")
assert state.a == 1
assert state.b == 20
assert state.is_dirty_all("a", "b")
assert state.is_dirty("a", "b")
state.flush()
assert not state.is_dirty("a", "b")
assert state.setdefault("a", 30) == 1
state.c.append("item")
assert not state.is_dirty("c")
state.dirty("c")
assert state.is_dirty("c")
assert state.initial == {"a": 1, "b": 20, "c": ["item"]}
@pytest.mark.asyncio
async def test_change_detection():
"""
0 msg : test_change_detection
1 push : {'a': 2}
2 msg : a changed (sync)
3 msg : a changed (async)
"""
server = FakeServer()
server.add_event("test_change_detection")
state = State(commit_fn=server._push_state, hot_reload=True)
state.ready()
state.a = 1
@state.change("a")
def regular_callback(**__kwargs):
server.add_event("a changed (sync)")
@state.change("a")
async def coroutine_callback(**__kwargs):
server.add_event("a changed (async)")
assert "a" in state._pending_update
state.clean("a")
assert "a" not in state._pending_update
with state:
state.a = 2
await asyncio.sleep(0.1)
result = [line.strip() for line in str(server).split("\n")]
expected = [line.strip() for line in str(test_change_detection.__doc__).split("\n")]
# Grab new scenario output
# print(expected)
# print("-"*60)
# print(result)
assert expected == result
def test_dunder():
server = FakeServer()
server.add_event("test_dunder")
state = State(commit_fn=server._push_state, hot_reload=True)
state.ready()
# get dunder
assert state.__dict__ != state.__getattr__("__dict__")
# get private (not in state)
assert state._something is None
# set private (not in state)
state._something = 1
assert state._something == 1
state.flush()
assert state.to_dict() == {}
@pytest.mark.asyncio
async def test_modified_keys():
"""
0 msg : test_modified_keys
1 push : {'a': 1, 'b': 2, 'c': 3}
2 msg : get initial a,b,c
3 msg : changed should be => a
4 push : {'a': 2}
5 msg : changed ['a']
6 msg : End of flush 1
7 msg : changed should be => a, b
8 push : {'a': 3, 'b': 4}
9 msg : changed ['a', 'b']
10 msg : End of flush 2
11 msg : changed should be => a, b, c
12 push : {'a': 4, 'b': 6, 'c': 6}
13 msg : changed ['a', 'b', 'c']
14 msg : side effect c => a + b
15 push : {'a': 4.5, 'b': 6.5}
16 msg : changed ['a', 'b']
17 msg : End of flush 3
"""
server = FakeServer()
server.add_event("test_modified_keys")
state = State(commit_fn=server._push_state)
NAMES = ["a", "b", "c"]
state.update(
{
"a": 1,
"b": 2,
"c": 3,
}
)
state.ready()
server.add_event("get initial a,b,c")
await asyncio.sleep(0.01)
@state.change(*NAMES)
def on_change(**_):
m_keys = list(state.modified_keys)
m_keys.sort()
server.add_event(f"changed {m_keys}")
@state.change("c")
def trigger_side_effect(**_):
server.add_event("side effect c => a + b")
state.a += 0.5
state.b += 0.5
with state:
state.a += 1
server.add_event("changed should be => a")
# yield
await asyncio.sleep(0.01)
server.add_event("End of flush 1")
with state:
state.a += 1
state.b += 2
server.add_event("changed should be => a, b")
# yield
await asyncio.sleep(0.01)
server.add_event("End of flush 2")
with state:
state.a += 1
state.b += 2
state.c += 3
server.add_event("changed should be => a, b, c")
# yield
await asyncio.sleep(0.1)
server.add_event("End of flush 3")
result = [line.strip() for line in str(server).split("\n")]
expected = [line.strip() for line in str(test_modified_keys.__doc__).split("\n")]
# sometime 13 and 14 could have a reverse execution order
# as trame does not guaranty the execution order of the callbacks.
result.pop(14)
result.pop(14)
expected.pop(14)
expected.pop(14)
print(result)
assert expected == result
def test_weakref():
server = FakeServer()
state = State(commit_fn=server._push_state, hot_reload=True)
state.ready()
class Obj:
method_call_count = 0
destructor_call_count = 0
def __del__(self):
Obj.destructor_call_count += 1
def fn(self, *_args, **_kwargs):
Obj.method_call_count += 1
print("Obj.fn called")
return 1
o = Obj()
state.a = 1
state.change("a")(weakref.WeakMethod(o.fn))
state.a = 2
state.flush()
assert Obj.method_call_count == 1
del o
assert Obj.destructor_call_count == 1
state.a = 3
state.flush()
assert Obj.method_call_count == 1
|