# py-scopes: tests.test_core """ Tests for scopes.core modules, including e.g. actor, message""" import asyncio import pytest from scopes import core from scopes.core import actor, environ from scopes.core.message import Message from scopes.util import keywords as k k('data', 'hello', 'person', 'show', 'switch', 'quit', 'test') @pytest.fixture def collector(): return [] def show(msg, coll): coll.append(msg) def handle_basic(coll): async def handle(msg): match msg: case k.show: show(msg, coll) case k.switch: return handle_alt(coll) case _: show(msg, coll) return handle def handle_alt(coll): async def handle(msg): match msg: case k.show: show('switched', coll) case _: await asyncio.sleep(0.01); show(msg, coll) return handle @pytest.mark.anyio async def test_actor(collector): mb1 = actor.create(handle_basic(collector)) mb2 = actor.create(handle_basic(collector)) msgs = [Message(k.test, k.hello), k.show, k.switch, k.show, "actor 1: Goodbye"] await asyncio.gather(*[actor.send(mb1, m) for m in msgs]) await actor.send(mb2, "actor 2") await actor.send(mb2, k.show) await actor.send(mb2, k.quit) await actor.send(mb2, k.quit) await asyncio.sleep(0.01) #print(collector) assert len(collector) == 6 assert collector[-1] == 'actor 1: Goodbye' def test_message(): msg = Message(k.test, k.data, 'person', '4711', data=dict(firstName='Bob', lastName='Miller')) assert msg.head['class'] is k.person assert msg.addr() == (k.test, k.person, '4711') assert msg.categ() == (k.test, k.person) @pytest.fixture async def meta_env(collector): async def collect(msg): collector.append(msg) return actor.create(collect) @pytest.mark.anyio async def test_core(meta_env, collector): env = environ.create_env(meta_env) zero = await core.create_zero(env) await actor.send(env, Message(k.env, k.hello)) await actor.send(zero, Message(k.csys, k.hello)) await actor.send(zero, Message(k.csys, k.create, data={k.connect: k.pred, k.address: (1, 1)})) await asyncio.sleep(0.01) assert len(collector) == 4 assert collector[0].action is k.created assert collector[1].domain is k.env assert collector[2].domain is k.csys assert collector[3].action is k.created #print(collector)