1# -*- coding: utf-8 -*-
2
3from mock import Mock
4from twisted.internet.defer import inlineCallbacks
5from twisted.python.failure import Failure
6
7from pyee import TwistedEventEmitter
8
9
10class PyeeTestError(Exception):
11    pass
12
13
14def test_propagates_failure():
15    """Test that TwistedEventEmitters can propagate failures
16    from twisted Deferreds
17    """
18    ee = TwistedEventEmitter()
19
20    should_call = Mock()
21
22    @ee.on("event")
23    @inlineCallbacks
24    def event_handler():
25        yield Failure(PyeeTestError())
26
27    @ee.on("failure")
28    def handle_failure(f):
29        assert isinstance(f, Failure)
30        should_call(f)
31
32    ee.emit("event")
33
34    should_call.assert_called_once()
35
36
37def test_propagates_sync_failure():
38    """Test that TwistedEventEmitters can propagate failures
39    from twisted Deferreds
40    """
41    ee = TwistedEventEmitter()
42
43    should_call = Mock()
44
45    @ee.on("event")
46    def event_handler():
47        raise PyeeTestError()
48
49    @ee.on("failure")
50    def handle_failure(f):
51        assert isinstance(f, Failure)
52        should_call(f)
53
54    ee.emit("event")
55
56    should_call.assert_called_once()
57
58
59def test_propagates_exception():
60    """Test that TwistedEventEmitters propagate failures as exceptions to
61    the error event when no failure handler
62    """
63
64    ee = TwistedEventEmitter()
65
66    should_call = Mock()
67
68    @ee.on("event")
69    @inlineCallbacks
70    def event_handler():
71        yield Failure(PyeeTestError())
72
73    @ee.on("error")
74    def handle_error(exc):
75        assert isinstance(exc, Exception)
76        should_call(exc)
77
78    ee.emit("event")
79
80    should_call.assert_called_once()
81