~launchpad-pqm/launchpad/devel

« back to all changes in this revision

Viewing changes to lib/lp/services/longpoll/testing.py

  • Committer: Jelmer Vernooij
  • Date: 2011-09-21 14:28:02 UTC
  • mfrom: (14006 devel)
  • mto: This revision was merged to the branch mainline in revision 14010.
  • Revision ID: jelmer@canonical.com-20110921142802-7ggkc204igsy532w
MergeĀ lp:launchpad

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright 2011 Canonical Ltd.  This software is licensed under the
 
2
# GNU Affero General Public License version 3 (see the file LICENSE).
 
3
 
 
4
"""Things that help with testing of longpoll."""
 
5
 
 
6
__metaclass__ = type
 
7
__all__ = [
 
8
    "capture_longpoll_emissions",
 
9
    ]
 
10
 
 
11
from collections import namedtuple
 
12
from contextlib import contextmanager
 
13
from functools import partial
 
14
 
 
15
from lp.services.longpoll.adapters import event
 
16
 
 
17
 
 
18
LongPollEventRecord = namedtuple(
 
19
    "LongPollEventRecord", ("event_key", "data"))
 
20
 
 
21
 
 
22
class LoggingRouter:
 
23
    """A test double for instances of `RabbitRoutingKey`.
 
24
 
 
25
    Saves messages as `LongPollEventRecord` tuples to a log.
 
26
 
 
27
    :param log: A callable accepting a single `LongPollEventRecord`.
 
28
    :param routing_key: See `RabbitRoutingKey.__init__`.
 
29
    """
 
30
 
 
31
    def __init__(self, log, routing_key):
 
32
        self.log = log
 
33
        self.routing_key = routing_key
 
34
 
 
35
    def send(self, data):
 
36
        record = LongPollEventRecord(self.routing_key, data)
 
37
        self.log(record)
 
38
 
 
39
 
 
40
@contextmanager
 
41
def capture_longpoll_emissions():
 
42
    """Capture longpoll emissions while this context is in force.
 
43
 
 
44
    This returns a list in which `LongPollEventRecord` tuples will be
 
45
    recorded, in the order they're emitted.
 
46
 
 
47
    Note that normal event emission is *suppressed globally* while this
 
48
    context is in force; *all* events will be stored in the log.
 
49
    """
 
50
    log = []
 
51
    original_router_factory = event.router_factory
 
52
    event.router_factory = partial(LoggingRouter, log.append)
 
53
    try:
 
54
        yield log
 
55
    finally:
 
56
        event.router_factory = original_router_factory