1# encoding: utf-8
2
3import random
4
5from marrow.mailer.exc import TransportFailedException, TransportExhaustedException
6
7from marrow.util.bunch import Bunch
8
9
10__all__ = ['MockTransport']
11
12log = __import__('logging').getLogger(__name__)
13
14
15
16class MockTransport(object):
17    """A no-op dummy transport.
18
19    Accepts two configuration directives:
20
21     * success - probability of successful delivery
22     * failure - probability of failure
23     * exhaustion - probability of exhaustion
24
25    All are represented as percentages between 0.0 and 1.0, inclusive.
26    (Setting failure or exhaustion to 1.0 means every delivery will fail
27    badly; do not do this except under controlled, unit testing scenarios!)
28    """
29
30    __slots__ = ('ephemeral', 'config')
31
32    def __init__(self, config):
33        base = {'success': 1.0, 'failure': 0.0, 'exhaustion': 0.0}
34        base.update(dict(config))
35        self.config = Bunch(base)
36
37    def startup(self):
38        pass
39
40    def deliver(self, message):
41        """Concrete message delivery."""
42
43        config = self.config
44        success = config.success
45        failure = config.failure
46        exhaustion = config.exhaustion
47
48        if getattr(message, 'die', False):
49            1/0
50
51        if failure:
52            chance = random.randint(0,100001) / 100000.0
53            if chance < failure:
54                raise TransportFailedException("Mock failure.")
55
56        if exhaustion:
57            chance = random.randint(0,100001) / 100000.0
58            if chance < exhaustion:
59                raise TransportExhaustedException("Mock exhaustion.")
60
61        if success == 1.0:
62            return True
63
64        chance = random.randint(0,100001) / 100000.0
65        if chance <= success:
66            return True
67
68        return False
69
70    def shutdown(self):
71        pass
72