Source

bloodhound-dashboard / bhdashboard / tests / test_report.py

Full commit
  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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
#!/usr/bin/env python
# -*- coding: UTF-8 -*-

#  Licensed to the Apache Software Foundation (ASF) under one
#  or more contributor license agreements.  See the NOTICE file
#  distributed with this work for additional information
#  regarding copyright ownership.  The ASF licenses this file
#  to you under the Apache License, Version 2.0 (the
#  "License"); you may not use this file except in compliance
#  with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing,
#  software distributed under the License is distributed on an
#  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
#  KIND, either express or implied.  See the License for the
#  specific language governing permissions and limitations
#  under the License.


r"""Project dashboard for Apache(TM) Bloodhound

In this file you'll find part of the tests written to ensure that
widgets displaying contents generated by TracReports behave as expected.

Only the tests requiring minimal setup effort are included below. 
This means that the environment used to run these tests contains the 
barely minimal information included in an environment (i.e. only the 
data specified by `trac.db_default.get_data`.).

Once the tests are started all built-in components (except 
trac.versioncontrol.* ) as well as widget system and extensions
are loaded. Besides the following values are (auto-magically)
made available in the global namespace (i.e. provided that 
the test name be written like `|widget_name: Descriptive message`):

  - req         A dummy request object setup for anonymous access.
  - auth_req    A dummy request object setup like if user `murphy` was  
                accessing the site.
  - env         the Trac environment used as a stub for testing purposes.
                This object is an instance of 
                `bhdashboard.tests.EnvironmentStub`.
  - widget      the widget provider under test.
  - ctx         context used to render widget for anonymous user.
  - ctx_auth    context used to render widget for `murphy` user.
  - ticket_data A set of tickets used for testing purposes.
"""

#------------------------------------------------------
#    Test artifacts
#------------------------------------------------------

def test_suite():
  from doctest import NORMALIZE_WHITESPACE, ELLIPSIS, REPORT_UDIFF
  from dutest import MultiTestLoader
  from unittest import defaultTestLoader

  from bhdashboard.tests import DocTestWidgetLoader, ticket_data, trac_version

  magic_vars = dict(ticket_data=ticket_data)
  if trac_version < (0, 13): # FIXME: Should it be (0, 12) ?
    kwargs = {'enable': ['trac.[a-uw-z]*', 'tracrpc.*', 'bhdashboard.*']}
  else:
    kwargs = {
            'enable': ['trac.*', 'tracrpc.*', 'bhdashboard.*'],
            'disable': ['trac.versioncontrol.*']
        }

  l = MultiTestLoader(
        [defaultTestLoader, \
          DocTestWidgetLoader(extraglobs=magic_vars, \
                            default_data=True, \
                            optionflags=ELLIPSIS | REPORT_UDIFF | \
                                        NORMALIZE_WHITESPACE, \
                            **kwargs) \
        ])

  import sys
  return l.loadTestsFromModule(sys.modules[__name__])

#------------------------------------------------------
#    Helper functions
#------------------------------------------------------

from datetime import datetime, time, date
from itertools import izip
from pprint import pprint

from __init__ import clear_perm_cache

def print_report_metadata(report_desc):
  for attrnm in ('id', 'title', 'description', 'query'):
    print attrnm.capitalize()
    print '-' * len(attrnm)
    print report_desc[attrnm]

def print_report_columns(cols):
  for coldsc in cols:
    print 'Column:', coldsc[0], 'Type:', coldsc[1] or '_', \
          'Label:', 
    try :
      print coldsc[2] or '_'
    except IndexError :
      print '_'

def print_report_result(cols, data):
  for i, row in enumerate(data):
    print '= Row', i, '='
    for coldsc in cols:
      colnm = coldsc[0]
      print 'Column:', colnm, 'Value:', row.get(colnm) or None, ''

TICKET_ATTRS = ('summary', 'description', 'priority', \
                'milestone', 'type', 'owner', 'status', \
                'component', 'version')

def prepare_ticket_workflow(tcktrpc, ticket_data, auth_req):
  r"""Set ticket status considering the actions defined in standard 
  ticket workflow. Needed for TracRpc>=1.0.6
  """
  from time import sleep

  TICKET_ACTIONS = {'accepted': 'accept', 'closed' : 'resolve',
                    'assigned': 'reassign'}
  sleep(1)
  for idx, (_, __, td) in enumerate(ticket_data) :
    action = TICKET_ACTIONS.get(td.get('status'))
    if action is not None :
      aux_attrs = {'action' : action}
      aux_attrs.update(td)
      tcktrpc.update(auth_req, idx + 1, "", aux_attrs)
  sleep(1)
  for idx, (_, __, td) in enumerate(ticket_data) :
    tcktrpc.update(auth_req, idx + 1, "", td)

__test__ = {
    'Initialization: Report widgets' : r"""
      >>> from trac.core import ComponentMeta
      >>> from bhdashboard.api import IWidgetProvider
      >>> from bhdashboard.widgets.report import *
      >>> allcls = ComponentMeta._registry.get(IWidgetProvider, [])
      >>> [wpcls in allcls for wpcls in (TicketReportWidget,)]
      [True]
      """,
    '|TicketReport: Metadata' : r"""
      >>> list(widget.get_widgets())
      ['TicketReport']
      >>> params = widget.get_widget_params('TicketReport')
      >>> pprint(params)
      {'id': {'desc': 'Report number',
                  'required': True,
                  'type': <type 'int'>},
       'limit': {'default': 0,
                  'desc': 'Number of results to retrieve',
                  'type': <type 'int'>}}
      """,
    '|TicketReport: Render My Tickets report' : r"""

      Add tickets

      >>> from tracrpc.ticket import TicketRPC
      >>> tcktrpc = TicketRPC(env)
      >>> for td in ticket_data :
      ...   tcktrpc.create(auth_req, *td)
      ... 
      1
      2
      3
      4
      5
      6
      7
      8
      9

      >>> if all(tcktrpc.get(auth_req, tid)[-1].get('status') == 'new' \
      ...            for tid in xrange(1, 10)):
      ...   # RPC considers ticket workflow
      ...   prepare_ticket_workflow(tcktrpc, ticket_data, auth_req)
      ...

      Check everything is ok with tickets

      >>> for tid in xrange(1, 10):
      ...   d = tcktrpc.get(auth_req, tid)[-1]
      ...   print tuple(d.get(attr) or '' for attr in TICKET_ATTRS)
      ...
      (u'Ticket 1', u'Description 1', u'major', u'milestone1', 
          u'defect', u'murphy', u'accepted', u'component1', u'1.0')
      (u'Ticket 2', u'Description 2', u'major', u'milestone4', 
          u'task', u'murphy', u'accepted', '', '')
      (u'Ticket 3', u'Description 3', u'critical', u'milestone3', 
          u'enhancement', u'tester', u'new', '', u'2.0')
      (u'Ticket 4', u'Description 4', u'minor', u'milestone3', 
          u'task', u'murphy', u'closed', u'component1', u'1.0')
      (u'Ticket 5', u'Description 5', u'minor', u'milestone3', 
          u'task', u'murphy', u'new', '', u'2.0')
      (u'Ticket 6', u'Description 6', u'minor', u'milestone1', 
          u'task', u'tester', u'assigned', u'component2', u'1.0')
      (u'Ticket 7', u'Description 7', u'critical', '', u'enhancement', 
          u'murphy', u'closed', '', '')
      (u'Ticket 8', u'Description 8', u'major', '', u'task', 
          u'murphy', u'closed', u'component1', '')
      (u'Ticket 9', u'Description 9', u'minor', '', u'enhancement', 
          u'tester', u'closed', '', u'2.0')

      >>> pprint(widget.render_widget('TicketReport', ctx, {
      ...     'args' : {'id' : 7}
      ...   }))
      ...
      ('widget_grid.html', [], <...Context >)

      >>> template, data, rptctx = widget.render_widget('TicketReport', auth_ctx, {
      ...     'args' : {'id' : 7}
      ...   })
      ...
      >>> template
      'widget_grid.html'

      In Trac=0.13 (0.12 ?) My Tickets report adds another group
      So perform common check in here.

      >>> pprint([x for x in data if x.get('__group__') != 'Reported'])
      [{u'__color__': u'3',
        u'__group__': u'Accepted',
        u'_changetime': ...,
        u'_description': u'Description 1',
        u'_reporter': u'murphy',
        u'component': u'component1',
        u'created': ...,
        u'milestone': u'milestone1',
        u'priority': u'major',
        u'summary': u'Ticket 1',
        u'ticket': 1,
        u'type': u'defect',
        u'version': u'1.0'},
       {u'__color__': u'3',
        u'__group__': u'Accepted',
        u'_changetime': ...,
        u'_description': u'Description 2',
        u'_reporter': u'murphy',
        u'component': None,
        u'created': ...,
        u'milestone': u'milestone4',
        u'priority': u'major',
        u'summary': u'Ticket 2',
        u'ticket': 2,
        u'type': u'task',
        u'version': None},
       {u'__color__': u'4',
        u'__group__': u'Owned',
        u'_changetime': ...,
        u'_description': u'Description 5',
        u'_reporter': u'murphy',
        u'component': None,
        u'created': ...,
        u'milestone': u'milestone3',
        u'priority': u'minor',
        u'summary': u'Ticket 5',
        u'ticket': 5,
        u'type': u'task',
        u'version': u'2.0'}]
      >>> rptctx is auth_ctx
      True
      """,
    '|TicketReport: Render a subset of My Tickets report' : r"""

      Add tickets

      >>> from tracrpc.ticket import TicketRPC
      >>> tcktrpc = TicketRPC(env)
      >>> for td in ticket_data :
      ...   tcktrpc.create(auth_req, *td)
      ... 
      1
      2
      3
      4
      5
      6
      7
      8
      9

      >>> if all(tcktrpc.get(auth_req, tid)[-1].get('status') == 'new' \
      ...            for tid in xrange(1, 10)):
      ...   # RPC considers ticket workflow
      ...   prepare_ticket_workflow(tcktrpc, ticket_data, auth_req)
      ...

      Check everything is ok with tickets

      >>> for tid in xrange(1, 10):
      ...   d = tcktrpc.get(auth_req, tid)[-1]
      ...   print tuple(d.get(attr) or '' for attr in TICKET_ATTRS)
      (u'Ticket 1', u'Description 1', u'major', u'milestone1', 
          u'defect', u'murphy', u'accepted', u'component1', u'1.0')
      (u'Ticket 2', u'Description 2', u'major', u'milestone4', 
          u'task', u'murphy', u'accepted', '', '')
      (u'Ticket 3', u'Description 3', u'critical', u'milestone3', 
          u'enhancement', u'tester', u'new', '', u'2.0')
      (u'Ticket 4', u'Description 4', u'minor', u'milestone3', 
          u'task', u'murphy', u'closed', u'component1', u'1.0')
      (u'Ticket 5', u'Description 5', u'minor', u'milestone3', 
          u'task', u'murphy', u'new', '', u'2.0')
      (u'Ticket 6', u'Description 6', u'minor', u'milestone1', 
          u'task', u'tester', u'assigned', u'component2', u'1.0')
      (u'Ticket 7', u'Description 7', u'critical', '', u'enhancement', 
          u'murphy', u'closed', '', '')
      (u'Ticket 8', u'Description 8', u'major', '', u'task', 
          u'murphy', u'closed', u'component1', '')
      (u'Ticket 9', u'Description 9', u'minor', '', u'enhancement', 
          u'tester', u'closed', '', u'2.0')

      >>> pprint(widget.render_widget('TicketReport', auth_ctx, {
      ...     'args' : {'id' : 7, 'limit' : 2}
      ...   }))
      ...
      ('widget_grid.html',
       [{u'__color__': u'3',
         u'__group__': u'Accepted',
         u'_changetime': ...,
         u'_description': u'Description 1',
         u'_reporter': u'murphy',
         u'component': u'component1',
         u'created': ...,
         u'milestone': u'milestone1',
         u'priority': u'major',
         u'summary': u'Ticket 1',
         u'ticket': 1,
         u'type': u'defect',
         u'version': u'1.0'},
        {u'__color__': u'3',
         u'__group__': u'Accepted',
         u'_changetime': ...,
         u'_description': u'Description 2',
         u'_reporter': u'murphy',
         u'component': None,
         u'created': ...,
         u'milestone': u'milestone4',
         u'priority': u'major',
         u'summary': u'Ticket 2',
         u'ticket': 2,
         u'type': u'task',
         u'version': None}],
       <...Context >)
      """,
    '|TicketReport: Invalid widget name' : r"""
      >>> widget.render_widget('OlkswSk', ctx, {
      ...     'args' : {'id' : 1, 'limit' : 8}
      ...   })
      ...
      Traceback (most recent call last):
        ...
      InvalidIdentifier: Widget name MUST match any of TicketReport
      """,
    '|TicketReport: Invalid report ID in arguments' : r"""
      >>> widget.render_widget('TicketReport', ctx, {
      ...     'args' : {'id' : 99999}
      ...   })
      ...
      Traceback (most recent call last):
        ...
      InvalidIdentifier: Report 99999 does not exist
      """,
    '|TicketReport: Missing required arguments' : r"""
      >>> widget.render_widget('TicketReport', ctx, {
      ...     'args' : {}
      ...   })
      ...
      Traceback (most recent call last):
        ...
      InvalidWidgetArgument: Invalid argument `id`. Required parameter expected

      >>> widget.render_widget('TicketReport', ctx, {
      ...     'args' : {'limit' : 4}
      ...   })
      ...
      Traceback (most recent call last):
        ...
      InvalidWidgetArgument: Invalid argument `id`. Required parameter expected
      """,
    '|TicketReport: Invalid widget parameter' : r"""

      Add tickets

      >>> from tracrpc.ticket import TicketRPC
      >>> tcktrpc = TicketRPC(env)
      >>> for td in ticket_data :
      ...   tcktrpc.create(auth_req, *td)
      ... 
      1
      2
      3
      4
      5
      6
      7
      8
      9

      >>> if all(tcktrpc.get(auth_req, tid)[-1].get('status') == 'new' \
      ...            for tid in xrange(1, 10)):
      ...   # RPC considers ticket workflow
      ...   prepare_ticket_workflow(tcktrpc, ticket_data, auth_req)
      ...

      Check everything is ok with tickets

      >>> for tid in xrange(1, 10):
      ...   d = tcktrpc.get(auth_req, tid)[-1]
      ...   print tuple(d.get(attr) or '' for attr in TICKET_ATTRS)
      (u'Ticket 1', u'Description 1', u'major', u'milestone1', 
          u'defect', u'murphy', u'accepted', u'component1', u'1.0')
      (u'Ticket 2', u'Description 2', u'major', u'milestone4', 
          u'task', u'murphy', u'accepted', '', '')
      (u'Ticket 3', u'Description 3', u'critical', u'milestone3', 
          u'enhancement', u'tester', u'new', '', u'2.0')
      (u'Ticket 4', u'Description 4', u'minor', u'milestone3', 
          u'task', u'murphy', u'closed', u'component1', u'1.0')
      (u'Ticket 5', u'Description 5', u'minor', u'milestone3', 
          u'task', u'murphy', u'new', '', u'2.0')
      (u'Ticket 6', u'Description 6', u'minor', u'milestone1', 
          u'task', u'tester', u'assigned', u'component2', u'1.0')
      (u'Ticket 7', u'Description 7', u'critical', '', u'enhancement', 
          u'murphy', u'closed', '', '')
      (u'Ticket 8', u'Description 8', u'major', '', u'task', 
          u'murphy', u'closed', u'component1', '')
      (u'Ticket 9', u'Description 9', u'minor', '', u'enhancement', 
          u'tester', u'closed', '', u'2.0')

      >>> pprint(widget.render_widget('TicketReport', auth_ctx, {
      ...     'args' : {'newjums' : 7, 'id' : 7, 'limit' : 1}
      ...   }))
      ...
      ('widget_grid.html',
       [{u'__color__': u'3',
         u'__group__': u'Accepted',
         u'_changetime': ...,
         u'_description': u'Description 1',
         u'_reporter': u'murphy',
         u'component': u'component1',
         u'created': ...,
         u'milestone': u'milestone1',
         u'priority': u'major',
         u'summary': u'Ticket 1',
         u'ticket': 1,
         u'type': u'defect',
         u'version': u'1.0'}],
       <...Context >)
      """,
    '|TicketReport: Invalid report definition' : r"""
      >>> raise NotImplementedError()
      """,
  }