~launchpad-pqm/launchpad/devel

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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# Copyright 2009-2011 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

"""Common helpers for codehosting tests."""

__metaclass__ = type
__all__ = [
    'AvatarTestCase',
    'adapt_suite',
    'CodeHostingTestProviderAdapter',
    'create_branch_with_one_revision',
    'deferToThread',
    'LoomTestMixin',
    'make_bazaar_branch_and_tree',
    'TestResultWrapper',
    ]

import os
import threading
import unittest

from bzrlib.bzrdir import BzrDir
from bzrlib.errors import FileExists
from bzrlib.plugins.loom import branch as loom_branch
from bzrlib.tests import (
    TestNotApplicable,
    TestSkipped,
    )
from testtools.deferredruntest import AsynchronousDeferredRunTest
from twisted.internet import (
    defer,
    threads,
    )
from twisted.python.util import mergeFunctionMetadata

from canonical.config import config
from lp.code.enums import BranchType
from lp.codehosting.vfs import branch_id_to_path
from lp.testing import TestCase


class AvatarTestCase(TestCase):
    """Base class for tests that need a LaunchpadAvatar with some basic sample
    data.
    """

    run_tests_with = AsynchronousDeferredRunTest

    def setUp(self):
        super(AvatarTestCase, self).setUp()
        # A basic user dict, 'alice' is a member of no teams (aside from the
        # user themself).
        self.aliceUserDict = {
            'id': 1,
            'name': 'alice',
            'teams': [{'id': 1, 'name': 'alice'}],
            'initialBranches': [(1, [])]
        }

        # An slightly more complex user dict for a user, 'bob', who is also a
        # member of a team.
        self.bobUserDict = {
            'id': 2,
            'name': 'bob',
            'teams': [{'id': 2, 'name': 'bob'},
                      {'id': 3, 'name': 'test-team'}],
            'initialBranches': [(2, []), (3, [])]
        }


class LoomTestMixin:
    """Mixin to provide Bazaar test classes with limited loom support."""

    def loomify(self, branch):
        tree = branch.create_checkout('checkout')
        tree.lock_write()
        try:
            tree.branch.nick = 'bottom-thread'
            loom_branch.loomify(tree.branch)
        finally:
            tree.unlock()
        loom_tree = tree.bzrdir.open_workingtree()
        loom_tree.lock_write()
        loom_tree.branch.new_thread('bottom-thread')
        loom_tree.commit('this is a commit', rev_id='commit-1')
        loom_tree.unlock()
        loom_tree.branch.record_loom('sample loom')
        self.get_transport().delete_tree('checkout')
        return loom_tree

    def makeLoomBranchAndTree(self, tree_directory):
        """Make a looms-enabled branch and working tree."""
        tree = self.make_branch_and_tree(tree_directory)
        tree.lock_write()
        try:
            tree.branch.nick = 'bottom-thread'
            loom_branch.loomify(tree.branch)
        finally:
            tree.unlock()
        loom_tree = tree.bzrdir.open_workingtree()
        loom_tree.lock_write()
        loom_tree.branch.new_thread('bottom-thread')
        loom_tree.commit('this is a commit', rev_id='commit-1')
        loom_tree.unlock()
        loom_tree.branch.record_loom('sample loom')
        return loom_tree


def deferToThread(f):
    """Run the given callable in a separate thread and return a Deferred which
    fires when the function completes.
    """
    def decorated(*args, **kwargs):
        d = defer.Deferred()

        def runInThread():
            return threads._putResultInDeferred(d, f, args, kwargs)

        t = threading.Thread(target=runInThread)
        t.start()
        return d
    return mergeFunctionMetadata(f, decorated)


def clone_test(test, new_id):
    """Return a clone of the given test."""
    from copy import deepcopy
    new_test = deepcopy(test)

    def make_new_test_id():
        return lambda: new_id

    new_test.id = make_new_test_id()
    return new_test


class CodeHostingTestProviderAdapter:
    """Test adapter to run a single test against many codehosting servers."""

    def __init__(self, schemes):
        self._schemes = schemes

    def adaptForServer(self, test, scheme):
        new_test = clone_test(test, '%s(%s)' % (test.id(), scheme))
        new_test.scheme = scheme
        return new_test

    def adapt(self, test):
        result = unittest.TestSuite()
        for scheme in self._schemes:
            new_test = self.adaptForServer(test, scheme)
            result.addTest(new_test)
        return result


def make_bazaar_branch_and_tree(db_branch):
    """Make a dummy Bazaar branch and working tree from a database Branch."""
    assert db_branch.branch_type == BranchType.HOSTED, (
        "Can only create branches for HOSTED branches: %r"
        % db_branch)
    branch_dir = os.path.join(
        config.codehosting.hosted_branches_root,
        branch_id_to_path(db_branch.id))
    return create_branch_with_one_revision(branch_dir)


def adapt_suite(adapter, base_suite):
    from bzrlib.tests import iter_suite_tests
    suite = unittest.TestSuite()
    for test in iter_suite_tests(base_suite):
        suite.addTests(adapter.adapt(test))
    return suite


def create_branch_with_one_revision(branch_dir, format=None):
    """Create a dummy Bazaar branch at the given directory."""
    if not os.path.exists(branch_dir):
        os.makedirs(branch_dir)
    try:
        tree = BzrDir.create_standalone_workingtree(branch_dir, format)
    except FileExists:
        return
    f = open(os.path.join(branch_dir, 'hello'), 'w')
    f.write('foo')
    f.close()
    tree.commit('message')
    return tree


class TestResultWrapper:
    """A wrapper for `TestResult` that knows about bzrlib's `TestSkipped`."""

    def __init__(self, result):
        self.result = result

    def addError(self, test_case, exc_info):
        if isinstance(exc_info[1], (TestSkipped, TestNotApplicable)):
            # If Bazaar says the test was skipped, or that it wasn't
            # applicable to this environment, then treat that like a success.
            # After all, it's not exactly an error, is it?
            self.result.addSuccess(test_case)
        else:
            self.result.addError(test_case, exc_info)

    def addFailure(self, test_case, exc_info):
        self.result.addFailure(test_case, exc_info)

    def addSuccess(self, test_case):
        self.result.addSuccess(test_case)

    def startTest(self, test_case):
        self.result.startTest(test_case)

    def stopTest(self, test_case):
        self.result.stopTest(test_case)