Skip to content

Setup e2e test with 20 rounds #83

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions game.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
class Game:
def __init__(self, seed=None):
self.bus = bus
self.bus.reset()
self.seed = seed
if self.seed is not None:
random.seed(self.seed)
Expand Down
45 changes: 29 additions & 16 deletions message_bus_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,38 +39,45 @@ class MessageBus():
registering a callback function that will be called when that message is published.
'''
def __init__(self, debug=True):
self.subscribers = dict(dict()) # noqa: C408
self.debug = debug
self.death_messages = [] # what is this?
self.reset()

def reset(self):
self.subscribers: dict[Message, dict[callable, int]] = dict(dict())
self.death_messages = []
self.unsubscribe_set = set()
self.subscribe_set = set()
self.lock_count = 0

def _clear_subscribes(self):
if self.lock_count > 0:
return
for event_type, callback, uid in self.subscribe_set:
self.subscribe(event_type, callback, uid)
for event_type, callback, uid, priority in self.subscribe_set:
self.subscribe(event_type, callback, uid, priority)
self.subscribe_set.clear()

def subscribe(self, event_type: Message, callback, uid):
def subscribe(self, event_type: Message, callback, uid, priority=50):
'''Subscribes a callback to a message. The callback will be called when the message is published.
Priority is a number from 1 to 100, with 1 being the highest priority and 100 being the lowest.
'''
assert 1 <= priority <= 100, "Priority must be between 1 and 100"
if self.lock_count > 0:
if self.debug:
ansiprint(f"<basic>MESSAGEBUS</basic>: <blue>{event_type}</blue> | Locked. Adding <bold>{callback.__qualname__}</bold> to subscribe list.")
self.subscribe_set.add((event_type, callback, uid))
self.subscribe_set.add((event_type, callback, uid, priority))
else:
if event_type not in self.subscribers:
self.subscribers[event_type] = {}
self.subscribers[event_type][uid] = callback
self.subscribers[event_type][uid] = (callback, priority)
if self.debug:
ansiprint(f"<basic>MESSAGEBUS</basic>: <blue>{event_type}</blue> | Subscribed <bold>{callback.__qualname__}</bold>")
ansiprint(f"<basic>MESSAGEBUS</basic>: <blue>{event_type}</blue> | Subscribed <bold>{callback.__qualname__}</bold> with priority <bold>{priority}</bold>")

def _clear_unsubscribes(self):
if self.lock_count > 0:
return
for event_type, uid in self.unsubscribe_set:
if self.debug:
ansiprint(f"<basic>MESSAGEBUS</basic>: Unsubscribing <bold>{self.subscribers[event_type][uid].__qualname__}</bold> from {', '.join(event_type).replace(', ', '')}")
ansiprint(f"<basic>MESSAGEBUS</basic>: Unsubscribing <bold>{self.subscribers[event_type][uid][0].__qualname__}</bold> from {', '.join(event_type).replace(', ', '')}")
self.unsubscribe(event_type, uid)
self.unsubscribe_set.clear()

Expand All @@ -80,18 +87,18 @@ def unsubscribe(self, event_type, uid):
ansiprint(f"<basic>MESSAGEBUS</basic>: Locked. Adding <bold>{event_type} - {uid}</bold> to unsubscribe list.")
self.unsubscribe_set.add((event_type, uid))
else:
if uid in self.subscribers[event_type]:
if event_type in self.subscribers and uid in self.subscribers[event_type]:
if self.debug:
ansiprint(f"<basic>MESSAGEBUS</basic>: Unsubscribed <bold>{self.subscribers[event_type][uid].__qualname__}</bold> from {', '.join(event_type).replace(', ', '')}")
ansiprint(f"<basic>MESSAGEBUS</basic>: Unsubscribed <bold>{self.subscribers[event_type][uid][0].__qualname__}</bold> from {', '.join(event_type).replace(', ', '')}")
del self.subscribers[event_type][uid]

def publish(self, event_type: Message, data):
self.lock_count += 1
if event_type in self.subscribers:
for uid, callback in self.subscribers[event_type].items():
_ = uid
sorted_callbacks = sorted([(x[1][0], x[1][1]) for x in self.subscribers[event_type].items()], key=lambda x: x[1])
for callback, priority in sorted_callbacks:
if self.debug:
ansiprint(f"<basic>MESSAGEBUS</basic>: <blue>{event_type}</blue> | Calling <bold>{callback.__qualname__}</bold>")
ansiprint(f"<basic>MESSAGEBUS</basic>: <blue>{event_type}</blue> | Calling <bold>{callback.__qualname__}</bold> with priority <bold>{priority}</bold>")
callback(event_type, data)
self.lock_count -= 1
self._clear_subscribes()
Expand All @@ -100,10 +107,16 @@ def publish(self, event_type: Message, data):

class Registerable():
registers = []
priorities = []

def register(self, bus):
for message in self.registers:
bus.subscribe(message, self.callback, self.uid)
if self.priorities:
assert len(self.registers) == len(self.priorities), "Registers and priorities must be the same length."
for message, priority in zip(self.registers, self.priorities):
bus.subscribe(message, self.callback, self.uid, priority)
else:
for message in self.registers:
bus.subscribe(message, self.callback, self.uid)
self.subscribed = True

def unsubscribe(self, event_types: list[Message]=None):
Expand Down
9 changes: 5 additions & 4 deletions tests/test_game.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def repeat_check(repeat_catcher, last_return, current_return) -> tuple[int, bool
def autoplayer(game: game.Game):
'''Returns a patched input function that can play the game, maybe.

Usage:
Usage:
with monkeypatch.context() as m:
m.setattr('builtins.input', autoplayer(game))
'''
Expand All @@ -53,7 +53,7 @@ def patched_input(*args, **kwargs):
# Handle Start Node
if mygame.game_map.current.type == definitions.EncounterType.START:
choice, reason = str(random.choice(range(1, len(mygame.game_map.current.children)))), "Start node"

# Handle dead
player = mygame.player
if player.state == definitions.State.DEAD:
Expand Down Expand Up @@ -88,7 +88,7 @@ def patched_input(*args, **kwargs):
tmp = all_possible_choices.copy()
tmp.remove(choice)
choice, reason = random.choice(tmp), "Player is stuck in a loop"

last_return = choice
print(f"AutoPlayer: {choice} ({reason})")
return choice
Expand All @@ -97,7 +97,7 @@ def patched_input(*args, **kwargs):


@pytest.mark.timeout(10)
@pytest.mark.parametrize("seed", list(range(3)))
@pytest.mark.parametrize("seed", list(range(20)))
def test_e2e(seed, monkeypatch, sleepless):
'''Test the game from start to finish
Plays with (more or less) random inputs to test the game.
Expand All @@ -111,6 +111,7 @@ def test_e2e(seed, monkeypatch, sleepless):

try:
start = time.time()
assert len(mygame.bus.subscribers) == 0
mygame.start()
except Exception as e:
ansiprint(f"<red><bold>Failed with seed: {seed}</bold></red>")
Expand Down
32 changes: 26 additions & 6 deletions tests/test_message_bus.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ def side_effect(*args, **kwargs):
bus.publish(Message.BEFORE_ATTACK, "second time")

assert callbackA.call_count == 2, "Callback A should have been called twice"
callbackB.assert_called_once_with(Message.BEFORE_ATTACK, "second time")
callbackB.assert_called_once_with(Message.BEFORE_ATTACK, "second time")


def test_can_unsubscribe_during_publish(self):
Expand All @@ -134,7 +134,7 @@ def side_effect(*args, **kwargs):

callbackA.assert_called_once_with(Message.BEFORE_ATTACK, "data")
assert callbackB.call_count == 2, "Callback B should have been called twice"

def test_can_unsubscribe_during_nested_publish(self):
# What happens when you try to unsubscribe from a nested publish?
bus = MessageBus(debug=True)
Expand All @@ -143,9 +143,9 @@ def side_effect_A(*args, **kwargs):
bus.publish(Message.AFTER_ATTACK, "calls B")
bus.unsubscribe(Message.BEFORE_ATTACK, 1)
callbackA = MagicMock(__qualname__="callbackA", side_effect=side_effect_A)

def side_effect_B(*args, **kwargs):
print("B called.")
print("B called.")
bus.unsubscribe(Message.AFTER_ATTACK, 2)
callbackB = MagicMock(__qualname__="callbackB", side_effect=side_effect_B)

Expand All @@ -160,5 +160,25 @@ def side_effect_B(*args, **kwargs):
bus.publish(Message.BEFORE_ATTACK, "data")

# No additional calls should be made (i.e. unsubscribe was successful)
callbackA.assert_called_once()
callbackB.assert_called_once()
callbackA.assert_called_once()
callbackB.assert_called_once()

def test_priority_calls_are_respected(self):
bus = MessageBus(debug=True)
ordering = []
def callbackA(_, data):
ordering.append("A")
def callbackB(_, data):
ordering.append("B")
def callbackC(_, data):
ordering.append("C")

bus.subscribe(Message.BEFORE_ATTACK, callbackC, uid=1, priority=100)
bus.subscribe(Message.BEFORE_ATTACK, callbackA, uid=2, priority=50)
bus.subscribe(Message.BEFORE_ATTACK, callbackB, uid=3, priority=1)

bus.publish(Message.BEFORE_ATTACK, "data")

# Need to assert that the order is correct
assert ordering == ["B", "A", "C"], "Callbacks should be called in order of priority"

Loading