lib: Add a class for doing the Publisher / Subscriber pattern

This will eventually replace my current notifications system. Hopefully
it'll be a little easier to work with and maintain

Signed-off-by: Anna Schumaker <Anna@NoWheyCreamery.com>
This commit is contained in:
Anna Schumaker 2020-10-04 10:30:52 -04:00
parent f7318f0bc7
commit 54d7ba6556
4 changed files with 51 additions and 0 deletions

View File

@ -1,5 +1,6 @@
#!/usr/bin/python
# Copyright 2019 (c) Anna Schumaker.
import lib
import curds
import rind
import sys

2
lib/__init__.py Normal file
View File

@ -0,0 +1,2 @@
# Copyright 2020 (c) Anna Schumaker.
from . import publisher

18
lib/publisher.py Normal file
View File

@ -0,0 +1,18 @@
# Copyright 2020 (c) Anna Schumaker.
class Publisher:
def __init__(self):
self.subscribers = set()
def publish(self, *args):
for func in self.subscribers:
func(*args)
def register(self, func):
self.subscribers.add(func)
def reset(self):
self.subscribers.clear()
def unregister(self, func):
self.subscribers.discard(func)

30
lib/test_publisher.py Normal file
View File

@ -0,0 +1,30 @@
# Copyright 2020 (c) Anna Schumaker.
from . import publisher
import unittest
class TestPublisher(unittest.TestCase):
def on_test(self, text):
self.test_arg = text
def test_publisher_init(self):
pub = publisher.Publisher()
self.assertIsInstance(pub.subscribers, set)
self.assertEqual(pub.subscribers, set())
def test_publisher_register(self):
pub = publisher.Publisher()
pub.register(self.on_test)
self.assertEqual(pub.subscribers, { self.on_test })
pub.unregister(self.on_test)
self.assertEqual(pub.subscribers, set())
pub.subscribers = set([ 1, 2, 3 ])
pub.reset()
self.assertEqual(pub.subscribers, set())
def test_publisher_publish(self):
pub = publisher.Publisher()
pub.register(self.on_test)
pub.publish("Test Arg")
self.assertEqual(self.test_arg, "Test Arg")