forked from faif/python-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_publish_subscribe.py
78 lines (68 loc) · 2.87 KB
/
test_publish_subscribe.py
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sys import version_info
from publish_subscribe import Provider, Publisher, Subscriber
if version_info < (2, 7): # pragma: no cover
import unittest2 as unittest
else:
import unittest
try:
from unittest.mock import patch, call
except ImportError:
from mock import patch, call
class TestProvider(unittest.TestCase):
"""
Integration tests ~ provider class with as little mocking as possible.
"""
def test_subscriber_shall_be_attachable_to_subscriptions(cls):
subscription = 'sub msg'
pro = Provider()
cls.assertEqual(len(pro.subscribers), 0)
sub = Subscriber('sub name', pro)
sub.subscribe(subscription)
cls.assertEqual(len(pro.subscribers[subscription]), 1)
def test_subscriber_shall_be_detachable_from_subscriptions(cls):
subscription = 'sub msg'
pro = Provider()
sub = Subscriber('sub name', pro)
sub.subscribe(subscription)
cls.assertEqual(len(pro.subscribers[subscription]), 1)
sub.unsubscribe(subscription)
cls.assertEqual(len(pro.subscribers[subscription]), 0)
def test_publisher_shall_append_subscription_message_to_queue(cls):
''' msg_queue ~ Provider.notify(msg) ~ Publisher.publish(msg) '''
expected_msg = 'expected msg'
pro = Provider()
pub = Publisher(pro)
sub = Subscriber('sub name', pro)
cls.assertEqual(len(pro.msg_queue), 0)
pub.publish(expected_msg)
cls.assertEqual(len(pro.msg_queue), 1)
cls.assertEqual(pro.msg_queue[0], expected_msg)
def test_provider_shall_update_affected_subscribers_with_published_subscription(cls):
pro = Provider()
pub = Publisher(pro)
sub1 = Subscriber('sub 1 name', pro)
sub1.subscribe('sub 1 msg 1')
sub1.subscribe('sub 1 msg 2')
sub2 = Subscriber('sub 2 name', pro)
sub2.subscribe('sub 2 msg 1')
sub2.subscribe('sub 2 msg 2')
with patch.object(sub1, 'run') as mock_subscriber1_run,\
patch.object(sub2, 'run') as mock_subscriber2_run:
pro.update()
cls.assertEqual(mock_subscriber1_run.call_count, 0)
cls.assertEqual(mock_subscriber2_run.call_count, 0)
pub.publish('sub 1 msg 1')
pub.publish('sub 1 msg 2')
pub.publish('sub 2 msg 1')
pub.publish('sub 2 msg 2')
with patch.object(sub1, 'run') as mock_subscriber1_run,\
patch.object(sub2, 'run') as mock_subscriber2_run:
pro.update()
expected_sub1_calls = [call('sub 1 msg 1'), call('sub 1 msg 2')]
mock_subscriber1_run.assert_has_calls(expected_sub1_calls)
expected_sub2_calls = [call('sub 2 msg 1'), call('sub 2 msg 2')]
mock_subscriber2_run.assert_has_calls(expected_sub2_calls)
if __name__ == "__main__":
unittest.main()