api.py 10.8 KB
Newer Older
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
# -*- coding: utf-8 -*-
#
#   __init__.py — Helpful classes for plugins
#
#   This file is part of debexpo - https://alioth.debian.org/projects/debexpo/
#
#   Copyright © 2008 Jonny Lamb <jonny@debian.org>
#   Copyright © 2012 Clément Schreiner <clement@mux.me>
#
#   Permission is hereby granted, free of charge, to any person
#   obtaining a copy of this software and associated documentation
#   files (the "Software"), to deal in the Software without
#   restriction, including without limitation the rights to use,
#   copy, modify, merge, publish, distribute, sublicense, and/or sell
#   copies of the Software, and to permit persons to whom the
#   Software is furnished to do so, subject to the following
#   conditions:
#
#   The above copyright notice and this permission notice shall be
#   included in all copies or substantial portions of the Software.
#
#   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
#   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
#   OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
#   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
#   HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
#   WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
#   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
#   OTHER DEALINGS IN THE SOFTWARE.

"""
32
Holds some helpful classes and functions for plugins to extend or use.
33
34
35
"""

__author__ = 'Jonny Lamb'
Clément Schreiner's avatar
Clément Schreiner committed
36
37
__copyright__ = ', '.join(('Copyright © 2008 Jonny Lamb',
                          'Copyright © 2012 Clément Schreiner'))
38
39
40
41
42
43
__license__ = 'MIT'

__all__ = ['importercmd',
           'test_result',
           'BasePlugin',
           'QAPlugin',
44
45
           'PluginResult',
           'bool_field',
Clément Schreiner's avatar
Clément Schreiner committed
46
47
           'int_field',
           'string_field']
48
49
50
51

import os.path
import logging
from inspect import getmembers, ismethod
Clément Schreiner's avatar
Clément Schreiner committed
52
import operator
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

from pylons import config
# template rendering
from mako.lookup import TemplateLookup
from mako.exceptions import TopLevelLookupException

from debexpo.lib import constants, helpers
from debexpo.model.meta import session
from debexpo.model.plugin_results import PluginResult


log = logging.getLogger(__name__)

# FIXME: there is probably a better way to define this
PLUGINS_TEMPLATE_DIRS = [os.path.join(path, "plugins")
                         for path in config["pylons.paths"]["templates"]]


#
# Decorators simplifying the writing of plugins
#

def importercmd(func):
    """
    Makes a plugin method an importer command.
    (i.e. the importer will call the method)
    """
    func.importercmd = True
    return func

Clément Schreiner's avatar
Clément Schreiner committed
83

84
85
86
87
88
89
90
def test_result(cls):
    """
    Makes a plugin result model the result of a QA test.
    """
    cls.test_result = True
    return cls

91

92
93
94
95
96
#
# Property factories for PluginResult subclasses
#
# FIXME: move this somewhere else
# FIXME: some of that could be abstracted
97
#
98

99
100
101
102
103
104
105
106
def _fdel(name):
    """
    Returns a function for deleting the dictionary's item with the
    given key. For use in properties below.
    """
    def fdel(instance):
        del instance[name]
    return fdel
Clément Schreiner's avatar
Clément Schreiner committed
107

108
def bool_field(name):
109
110
111
112
113
114
115
    """
    Property exposing an item ('true' or 'false') from the plugin
    result's dictionary as a bool.

    If the dictionary does not have the requested item yet, the getter
    will return False.
    """
116
    def fget(instance):
117
        return True if instance.get(name, 'false') == 'true' else False
118
119
120
121

    def fset(instance, value):
        if not isinstance(value, bool):
            raise ValueError('Expected bool')
122
        instance[name] = u'true' if value else u'false'
123

124
    return property(fget, fset, _fdel(name),
125
126
127
                    "Read-write property exposing a string ('true' or 'false')"
                    " as a bool.")

Clément Schreiner's avatar
Clément Schreiner committed
128

129
def int_field(name):
130
131
132
133
134
135
136
    """
    Property exposing a numeric item from the plugin result's dictionary as
    an int.

    If the dictionary does not have the requested item yet, the getter
    will return 0.
    """
137
    def fget(instance):
138
139
        # FIXME: better error handling
        return int(instance.get(name, 0))
140
141
142
143
144
145

    def fset(instance, value):
        if not isinstance(value, int):
            raise ValueError('Expected int')
        instance[name] = unicode(value)

146
    return property(fget, fset, _fdel(name),
147
                    'Read-write property exposing a string as an int')
Clément Schreiner's avatar
Clément Schreiner committed
148

149
150
151
152
153
154
155
156
def string_field(name):
    """
    Property for accessing a string item from the plugin result's dictionary.
    """

    def fset(instance, value):
        instance[name] = value

Clément Schreiner's avatar
Clément Schreiner committed
157
    return property(operator.itemgetter(name), fset, _fdel(name))
158

Clément Schreiner's avatar
Clément Schreiner committed
159

160
161
162
163
#
# Bases classes for plugins
#

Clément Schreiner's avatar
Clément Schreiner committed
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
class BasePlugin(object):
    """
    Base class for importer plugins.
    """

    def __init__(self, name, package_version, models=None, **kw):
        """
        Constructor for a plugin.
        """

        self.name = name

        # PackageVersion object for the package we're looking at
        self.package_version = package_version

        self.models = []
        if models is not None:
            self._load_models(models)

        # for storing results retrieved from the database
        self.results = {}

        # other argumnets
        for key in kw:
            setattr(self, key, kw[key])

        # sqlalchemy session
        self.session = session

    def run(self):
        """
        Import data from the package.
        """

        for name, method in getmembers(self, ismethod):
            if getattr(method, 'importercmd', False):
                method()

    def load(self):
        """
        Load all data previously imported into the database by this
        plugin.
        """
        for model in self.models:
            q = self.session.query(model)
Clément Schreiner's avatar
Clément Schreiner committed
210
            q = q.filter_by(package_version=self.package_version)
211
212
213
214
215
216
217
218
219
220
            for result in q.all():
                self._load_result(result)

        return self.results

    def _load_result(self, result):
        self.results.setdefault(result.entity, list()).append(result)

    def save(self):
        """ Save DB changes """
Clément Schreiner's avatar
Clément Schreiner committed
221

222
        self.session.commit()
Clément Schreiner's avatar
Clément Schreiner committed
223
        log.debug('Added results to the database for {}'.format(self.name))
224
225
226
227
228
229

    def new_result(self, result_cls, **data):
        """
        Add a new result to the list of db objects. Returns the
        instance of the result.
        """
Clément Schreiner's avatar
Clément Schreiner committed
230
        result = result_cls(package_version=self.package_version)
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
        for k, v in data.iteritems():
            result[k] = v

        self.session.add(result)
        return result

    @property
    def nb_results(self):
        """
        Number of results that have been retrieved from the DB.
        """
        return sum(len(l) for l in self.results.itervalues())

    def _find_template(self, name, render_format):
        # Files to try out for plugin data rendering
        try_files = [
            "%s/%s.mako" % (name, render_format),
            "%s/text.mako" % (name),
            "default/%s.mako" % render_format,
            "default/text.mako",
            ]

        lookup = TemplateLookup(
Clément Schreiner's avatar
Clément Schreiner committed
254
            directories=PLUGINS_TEMPLATE_DIRS,
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
            input_encoding='utf-8',
            output_encoding='utf-8',
            )

        for basefile in try_files:
            try:
                template = lookup.get_template(basefile)
            except TopLevelLookupException:
                continue
            else:
                break
        else:
            # No template file found, something weird happened
            return "(!! no template found for %s plugin data)" % name

        return template

    def _load_model(self, model):
        """
        Adds the given model to the ``models`` list attribute.

        This is separated from the ``_load_models`` method to simplify
        overriding in derived plugin classes, which might handle
        models classes differently.

        For example, QAPlugin instances have a ``test_result``
        attribute.
        """

        self.models.append(model)

    def _load_models(self, models):
        """
        Calls ``_load_model`` on all PluginResult subclasses found in
        the given ``models`` sequence.
        """
        for model in models:
            if issubclass(model, PluginResult):
                self._load_model(model)

    def render(self, render_format, **render_args):
        """Render the plugin data to the given format"""

        template = self._find_template(self.name, render_format)
Clément Schreiner's avatar
Clément Schreiner committed
299
        return template.render_unicode(results=self.results,
300
                                       nb_results=self.nb_results,
Clément Schreiner's avatar
Clément Schreiner committed
301
                                       h=helpers,
302
303
                                       **render_args)

Clément Schreiner's avatar
Clément Schreiner committed
304

305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
class QAPlugin(BasePlugin):
    """
    Class for implementing QA plugins.

    QA plugins have the concept of a test that can be passed or
    failed.

    Also, their templates look alike and could be abstracted
    (i.e. having a standard 'simple test template' that work sith any
    SimpleTestPlugin's results.  'tests results' can be considered the
    main result, with other results giving complementary information.

    The ``test_entity`` class attribute must be set the
    PluginResult-class which represents this test result.
    """

    # the PluginResult-derived class representing the result of the
    # test
    test_model = None
Clément Schreiner's avatar
Clément Schreiner committed
324
    test_result = None  # instance of that class, set by ``load``
325
326
327
328
329
330
331
332

    @property
    def test_severity(self):
        """
        Returns the severity of the test result.
        """

        if self.test_result is None:
Clément Schreiner's avatar
Clément Schreiner committed
333
334
            log.debug("'%s' plugin's data has not been loaded, "
                      "or this plugin does not define a test" % self.name)
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
            return None

        # FIXME: ugly
        if self.test_result.severity == 0:
            return 1
        return self.test_result.severity

    def new_test_result(self, **data):
        """
        Returns an instance of the sqlalchemy object for the result of
        the test.
        """
        return self.new_result(self.test_model, **data)

    def render(self, render_format, **render_args):
        """
        Render the QA test's template.
        """
        return super(QAPlugin, self).render(render_format,
Clément Schreiner's avatar
Clément Schreiner committed
354
                                            test_result=self.test_result,
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
                                            **render_args)

    def _load_model(self, model):
        """
        Overridding BasePlugin's ``_load_model`` to set the
        ``test_model`` attribute if found.
        """
        if (self.test_result is None and
            getattr(model, 'test_result', False)):
            self.test_model = model
        super(QAPlugin, self)._load_model(model)

    def _load_result(self, result):
        """
        Overridding BasePlugin's ``_load_result`` to set the
        ``test_result`` attribute if found.
        """

        log.debug('Loading %s' % result)
        if isinstance(result, self.test_model):
            self.test_result = result
        super(QAPlugin, self)._load_result(result)