~fabricematrat/charmworld/redirect-charm

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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
# Copyright 2012, 2013 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

from datetime import date
from logging import getLogger

from pyramid.httpexceptions import HTTPMovedPermanently

from charmworld.jobs.ingest import (
    add_files,
)
from charmworld.models import (
    Charm,
    CharmSource,
    QADataSource,
    getfs,
)
from charmworld.testing import (
    factory,
    login_request,
    ViewTestBase,
    WebTestBase,
)
from charmworld.testing.html import (
    find_answer_field,
    parse,
)
from charmworld.utils import quote_key
from charmworld.views.api import API3
from charmworld.views.charms import (
    _charm_view,
    _reconcile_revision,
    charm_collection,
    config,
    distro_charm,
    distro_charm_json,
    find_charm,
    found_charm_collection,
    hook,
    interface,
    personal_collection,
    personal_config,
    personal_hook,
    personal_series_collection,
    quality_edit,
    series_collection,
)


DISTRO_CHARM_DATA = {
    'address': 'cs:precise/foo',
    'name': 'foo',
    'series': 'precise',
    'owner': 'bar',
    'maintainer': 'John Doe <jdoe@example.com>',
    'maintainers': '',
    'summary': 'Remote terminal classroom over https',
    'description': 'foobar',
    'store_url': 'cs:precise/foo-1',
    'bzr_branch': '',
    'promulgated': True,
    'branch_deleted': False,
    'categories': [],
    'subordinate': False,
    'requires': {'database': {'interface': 'mongodb'}},
    'provides': {'website': {'interface': 'https'}},
    'config': {
        'options': {
            'script-interval': {
                'default': 5,
                'type': 'int',
                'description': 'The interval between script runs.'
            }
        }
    },
    'downloads': 0,
    'downloads_in_past_7_days': 0,
    'downloads_in_past_30_days': 0,
    'downloads_in_past_half_year': 0,
    'files': {
        'readme': {
            'subdir': '',
            'filename': 'README',
        },
        'install': {
            'subdir': 'hooks',
            'filename': 'install',
        },
    },
    'tests': {},
    'test_results': {},
    'proof': {
        'w': [
            ' no README file',
            ' (install:31) - hook accesses EC2 metadata service'
            ' directly'
        ]
    },
    'date_created': '2012-01-01',
    'error': '',
    'last_change': {
        'committer': u'John Doe <jdoe@example.com>',
        'message': u'maintainer',
        'revno': 12,
        'created': 1343082725.06
    },
    'hash': None,
}


class TestCharms(ViewTestBase):

    def test_found_charm_collection(self):
        """found_charm_collection() returns a dict of charm objects."""
        _id, one = factory.makeCharm(self.db, name='bee', promulgated=True)
        _id, two = factory.makeCharm(self.db, name='awk', promulgated=True)
        _id, three = factory.makeCharm(self.db, name='cat', promulgated=False)
        query = {"series": 'precise'}
        sub_only = False
        # The only_promulgated kwarg limits the sorted charms.
        collection = found_charm_collection(
            self.db, dict(query), sub_only, only_promulgated=True)
        promulgated_names = [charm.name for charm in collection['charms']]
        expected = [two['name'], one['name']]
        self.assertEqual(expected, promulgated_names)
        self.assertIs(False, collection['sub_only'])
        # The only_promulgated kwarg defaults to False, getting all sorted
        # charms.
        collection = found_charm_collection(self.db, dict(query), sub_only)
        all_names = [charm.name for charm in collection['charms']]
        expected = [two['name'], one['name'], three['name']]
        self.assertEqual(expected, all_names)

    def test_charm_collection_basic(self):
        """Simple sanity check."""
        one_id, one = factory.makeCharm(self.db, promulgated=True)
        two_id, two = factory.makeCharm(self.db, promulgated=True, owner='foo')
        three_id, three = factory.makeCharm(self.db, promulgated=False)

        response = charm_collection(self.getRequest())
        charm_names = set(charm.name for charm in response['charms'])
        expected = set((one['name'], two['name']))
        self.assertEqual(expected, charm_names)

    def test_charm_collection_sub_filter(self):
        """With the subordinate filter we limit out the non-sub charms."""
        one_id, one = factory.makeCharm(
            self.db, subordinate=True, promulgated=True)
        two_id, two = factory.makeCharm(self.db, promulgated=True)

        request = self.getRequest()
        request.GET['sub'] = 'true'
        response = charm_collection(request)
        charms = response['charms']
        self.assertEqual(1, len(charms))
        self.assertEqual(one['name'], charms[0].name)

    def test_charm_collection_charms_with_errors(self):
        """Charms with errors are not returned by charm_collection()."""
        one_id, one = factory.makeCharm(self.db, promulgated=True)
        two_id, two = factory.makeCharm(
            self.db, charm_error=True, promulgated=True)
        response = charm_collection(self.getRequest())
        charms = response['charms']
        self.assertEqual(1, len(charms))
        self.assertEqual(one['name'], charms[0].name)

    def test_personal_collection(self):
        request = self.getRequest()
        request.matchdict = {'owner': 'foo'}
        with self.assertRaises(HTTPMovedPermanently) as e:
            personal_collection(request)
        self.assertIn('/q/foo', e.exception.location)

    def test_series_collection(self):
        request = self.getRequest()
        request.matchdict = {'series': 'one'}
        with self.assertRaises(HTTPMovedPermanently) as e:
            series_collection(request)
        self.assertIn('/q/one', e.exception.location)

    def test_personal_series_collection(self):
        request = self.getRequest()
        request.matchdict = {'series': 'one', 'owner': 'me'}
        with self.assertRaises(HTTPMovedPermanently) as e:
            personal_series_collection(request)
        self.assertIn('/q/me/one', e.exception.location)

    def test_interface(self):
        # interface() returns all charms requiring or providing a given
        # interface.
        providing = Charm(factory.makeCharm(
            self.db, provides={'foo': {'interface': 'httpX'}})[1])
        requiring = Charm(factory.makeCharm(
            self.db, requires={'bar': {'interface': 'httpX'}})[1])
        ignore, other = factory.makeCharm(self.db)
        request = self.getRequest()
        request.matchdict = {'interface': 'httpX'}
        response = interface(request)
        self.assertEqual('httpX', response['interface'])
        found_providing = response['providers']
        self.assertEqual(1, len(found_providing))
        self.assertEqual(providing, found_providing[0])
        found_requiring = response['requirers']
        self.assertEqual(1, len(found_requiring))
        self.assertEqual(requiring, found_requiring[0])

    def test_interface_charm_with_errors(self):
        # Charms with errors are not returned by interface().
        providing = Charm(factory.makeCharm(
            self.db, provides={'foo': {'interface': 'httpX'}})[1])
        Charm(factory.makeCharm(
              self.db, requires={'bar': {'interface': 'httpX'}},
              charm_error=True)[1])
        request = self.getRequest()
        request.matchdict = {'interface': 'httpX'}
        response = interface(request)
        self.assertEqual('httpX', response['interface'])
        found_providing = response['providers']
        self.assertEqual(1, len(found_providing))
        self.assertEqual(providing, found_providing[0])
        found_requiring = response['requirers']
        self.assertEqual(0, len(found_requiring))

    def test_config(self):
        ignore, charm = factory.makeCharm(
            self.db, name='foo', owner='bar', series='precise',
            promulgated=True)
        request = self.getRequest()
        request.matchdict = {'charm': 'foo', 'series': 'precise'}
        response = config(request)
        expected = {"charm": Charm(charm), "onload": "prettyPrint()"}
        self.assertEqual(expected, response)

    def test_personal_config(self):
        ignore, charm = factory.makeCharm(
            self.db, name='foo', owner='bar', series='precise',
            promulgated=False)
        request = self.getRequest()
        request.matchdict = {
            'charm': 'foo',
            'series': 'precise',
            'owner': 'bar'
        }
        response = personal_config(request)
        expected = {"charm": Charm(charm), "onload": "prettyPrint()"}
        self.assertEqual(expected, response)

    def make_charm_with_files(self, promulgated):
        ignore, charm = factory.makeCharm(
            self.db, owner='bar', series='precise',
            promulgated=promulgated, with_real_files=True)
        branch_dir, revision, path = self.use_context(factory.charm_branch())
        charm['branch_dir'] = branch_dir
        charm['store_data'] = {'digest': revision, 'revision': 1}
        fs = getfs(self.db)
        log = getLogger('charm.scan')
        add_files(fs, branch_dir, charm, log)
        self.db.charms.update({'_id': charm['_id']}, charm)
        return charm

    def test_hook(self):
        charm = Charm(self.make_charm_with_files(promulgated=True))
        request = self.getRequest()
        request.matchdict = {
            'charm': 'sample_charm',
            'series': 'precise',
            'hook': 'install',
        }
        response = hook(request)
        self.assertEqual('Not Set.', response['project'])
        self.assertEqual('install', response['hook'])
        self.assertTrue(response['hook_raw'].startswith(
            '#!/bin/bash\nset -eux\n\n# This PPA is no longer required.'))
        self.assertEqual(charm, response['charm'])
        self.assertEqual('prettyPrint()', response['onload'])

    def test_personal_hook(self):
        charm = Charm(self.make_charm_with_files(promulgated=False))
        request = self.getRequest()
        request.matchdict = {
            'charm': 'sample_charm',
            'series': 'precise',
            'hook': 'install',
            'owner': 'bar',
        }
        response = personal_hook(request)
        self.assertEqual('Not Set.', response['project'])
        self.assertEqual('install', response['hook'])
        self.assertTrue(response['hook_raw'].startswith(
            '#!/bin/bash\nset -eux\n\n# This PPA is no longer required.'))
        self.assertEqual(charm, response['charm'])
        self.assertEqual('prettyPrint()', response['onload'])

    def test_distro_charm(self):
        self.enable_routes()
        self.make_charm_with_files(promulgated=True)
        request = self.getRequest()
        request.matchdict = {
            'charm': 'sample_charm',
            'series': 'precise',
        }
        with self.assertRaises(HTTPMovedPermanently):
            distro_charm(request)

    def test_distro_charm_json(self):
        ignore, charm = factory.makeCharm(
            self.db, name='foo', owner='bar', series='precise',
            description='foobar', promulgated=True,
            date_created=date(2012, 1, 1))
        request = self.getRequest()
        request.matchdict = {
            'charm': 'foo',
            'series': 'precise',
        }
        response = distro_charm_json(request)
        self.assertEqual(DISTRO_CHARM_DATA, response.json_body)

    def test_valid_others(self):
        charm = factory.makeCharm(self.db, files={})[1]
        other_charm = Charm(factory.makeCharm(
            self.db, series=charm['series'], name=charm['name'],
            owner='jrandom')[1])
        response = _charm_view(self.getRequest(), charm)
        self.assertEqual(1, len(response['others']))
        self.assertEqual(other_charm, response['others'][0])
        other_charm.store_data['errors'] = ['error']
        self.db.charms.save(other_charm._representation)
        response = _charm_view(self.getRequest(), charm)
        self.assertItemsEqual([], response['others'])

    def test_charm_icons(self):
        self.enable_routes()
        no_icon_charm = factory.makeCharm(self.db, files={})[1]
        response = _charm_view(self.getRequest(), no_icon_charm)
        self.assertEqual(None, response['icon_path'])

        files = {quote_key('icon.svg'): {'filename': 'icon.svg'}}
        icon_charm = factory.makeCharm(self.db, files=files)[1]
        response = _charm_view(self.getRequest(), icon_charm)
        expect = '/api/2/charm/%s/file/icon.svg' % API3._get_api_id(
            Charm(icon_charm))
        self.assertEqual(expect, response['icon_path'])


class TestFindCharm(ViewTestBase):

    def test_find_charm_selects_latest_revision(self):
        kwargs = dict(owner='foo', series='bar', name='baz')
        old_id, old_charm = factory.makeCharm(self.db, store_revision=1,
                                              **kwargs)
        new_id, new_charm = factory.makeCharm(self.db, store_revision=2,
                                              **kwargs)
        request = self.getRequest()
        request.matchdict.update(kwargs)
        request.matchdict['charm'] = kwargs['name']
        charm_data = find_charm(request)
        self.assertEqual(new_id, charm_data['_id'])


class CharmsViewHelpersTestCase(ViewTestBase):

    def test_reconcile_revision_with_dashed_name(self):
        # The charm name is reconstructed when a revision is wrongly matched.
        request = self.getRequest()
        request.matchdict = {
            'charm': 'charm',
            'revision': 'name',
        }
        _reconcile_revision(request)
        self.assertEqual('charm-name', request.matchdict['charm'])
        self.assertNotIn('revision', request.matchdict)

    def test_reconcile_revision_with_revision(self):
        # The charm name is reconstructed when a revision is wrongly matched.
        request = self.getRequest()
        request.matchdict = {
            'charm': 'charm',
            'revision': '1',
        }
        _reconcile_revision(request)
        self.assertEqual('charm', request.matchdict['charm'])
        self.assertEqual('1', request.matchdict['revision'])

    def test_reconcile_revision_with_head_revision(self):
        # The HEAD revision is dropped.
        request = self.getRequest()
        request.matchdict = {
            'charm': 'charm',
            'revision': 'HEAD',
        }
        _reconcile_revision(request)
        self.assertEqual('charm', request.matchdict['charm'])
        self.assertNotIn('revision', request.matchdict)
        request.matchdict = {
            'charm': 'charm',
            'revision': 'head',
        }
        _reconcile_revision(request)
        self.assertEqual('charm', request.matchdict['charm'])
        self.assertNotIn('revision', request.matchdict)


class CharmsWebTestCase(WebTestBase):

    def test_charm_collection_with_missing_data(self):
        """Charms with missing data are rendered."""
        one_id, one = factory.makeCharm(self.db, promulgated=True)
        two_id, two = factory.makeCharm(self.db, promulgated=True)
        del two['summary']
        self.db.charms.save(two)
        response = self.app.get('/charms/precise', status=301)
        self.assertIn('/q/precise', response.body)

    def test_route_personal_charm_with_revision(self):
        # The route /~owner/series/charm-1 finds charms using owner,
        # series, charm name, and revision. The deploy instruction
        # does not include the revision.
        ignore, charm = factory.makeCharm(
            self.db, owner='owner', series='series', name='charm', files={})
        response = self.app.get('/~owner/series/charm-1', status=301)
        self.assertIn('/u/owner/charm/series/1', response.body)

    def test_route_personal_charm_with_dash_and_revision(self):
        # /~owner/series/charm-name-1 route find the charm.
        # This is a corner-case where the revision and charm name are
        # ambigous because they are munged.
        ignore, charm = factory.makeCharm(
            self.db, owner='owner', series='series', name='charm-name',
            files={})
        response = self.app.get('/~owner/series/charm-name-1', status=301)
        self.assertIn('/u/owner/charm-name/series/1', response.body)

    def test_route_personal_charm_with_head_revision(self):
        # the /~owner/series/charm-name-HEAD route finds the charm.
        # The juju-gui apache rewrite versionless charm urls to help the GUI.
        ignore, charm = factory.makeCharm(
            self.db, owner='owner', series='series', name='charm', files={})
        response = self.app.get('/~owner/series/charm-HEAD', status=301)
        self.assertIn('/u/owner/charm/series', response.body)
        self.assertNotIn('HEAD', response.body)

    def test_route_personal_charm_without_revision(self):
        # The route /~owner/series/charm route finds the charm using owner
        # series, and charm name. Revision is ignored. The deploy instruction
        # matches the route.
        ignore, charm = factory.makeCharm(
            self.db, owner='owner', series='series', name='charm', files={})
        response = self.app.get('/~owner/series/charm', status=301)
        self.assertIn('/u/owner/charm/series', response.body)

    def test_route_personal_charm_json_with_revision(self):
        # The route /~owner/series/charm-1/json finds charms using owner,
        # series, charm name, and revision. The address key does not contain
        # the revision.
        ignore, charm = factory.makeCharm(
            self.db, owner='owner', series='series', name='charm', files={})
        response = self.app.get('/~owner/series/charm-1/json', status=200)
        self.assertEqual('cs:~owner/series/charm', response.json['address'])

    def test_route_personal_charm_json_without_revision(self):
        # The route /~owner/series/charm/json finds the charm using owner
        # series, and charm name. Revision is ignored. The address key matches
        # the route
        ignore, charm = factory.makeCharm(
            self.db, owner='owner', series='series', name='charm', files={})
        response = self.app.get('/~owner/series/charm/json', status=200)
        self.assertEqual('cs:~owner/series/charm', response.json['address'])

    def test_route_promulgated_charm_with_revision(self):
        # The route /series/charm-1 route finds promulgated charms using
        # The series, charm name and version. The deploy instruction does not
        # include the version.
        factory.makeCharm(
            self.db, promulgated=True, series='series', name='charm', files={})
        response = self.app.get('/series/charm-1', status=301)
        self.assertIn('/charm/series/1', response.body)

    def test_route_promulgated_charm_with_head_revision(self):
        # The route /series/charm-HEAD finds promulgated charms using
        # series, charm name, and head revision. The revision is not included
        # in the deploy instruction.
        ignore, charm = factory.makeCharm(
            self.db, promulgated=True, series='series', name='charm', files={})
        response = self.app.get('/series/charm-HEAD', status=301)
        self.assertNotIn('HEAD', response.body)
        self.assertIn('/charm/series', response.body)

    def test_route_promulgated_charm_without_revision(self):
        # The route /series/charm finds the promulgated charms using just
        # the series and charm name. The deploy instruction matches the route.
        factory.makeCharm(
            self.db, promulgated=True, series='series', name='charm', files={})
        self.app.get('/series/charm', status=301)

    def test_charm_short_url_route(self):
        ignore, charm_data = factory.makeCharm(
            self.db, promulgated=True, series='series', name='charm', files={})
        charm = Charm(charm_data)
        self.app.get(charm.short_url, status=301)


class TestQAForm(ViewTestBase):

    def setUp(self):
        """Need to load the question data."""
        super(TestQAForm, self).setUp()
        category = factory.makeQAQuestionGroup()
        self.db.qa.insert(category)

    def test_form_renders(self):
        """Sanity check that the form renders without errors."""
        cid, charm = factory.makeCharm(self.db, promulgated=True, owner='foo')
        request = self.getRequest()
        request.matchdict = {
            'charm': charm['name'],
            'series': charm['series'],
        }
        resp = quality_edit(request)

        self.assertIn('form', resp)
        self.assertIn('label', resp['form'])

    def test_form_renders_existing_data(self):
        charm = Charm(factory.makeCharm(self.db, promulgated=True)[1])
        qa = {
            'reliable': {
                '4847e034bb0a55fcbc8a3380d6a3ab80': '1',
                'a60b40bce263c47559d32435a89756fe': '0',
                '7ff6cc997b141399bcdf2c338fb4031c': '1',
                '9a736d9ab5ca1e16ddd942e7a62b8820': '0',
                '51dceb2909262166283ac17f2af504e7': '1',
                '9659919b570c6ef9a25df7261375e6bb': '',
            },
        }
        source = QADataSource.from_db(self.db)
        source.save_qa_data(charm, qa)
        request = self.getRequest()
        request.matchdict = {
            'charm': charm.name,
            'series': charm.series,
        }
        resp = quality_edit(request)
        parsed = parse(resp['form'])
        one = find_answer_field(parsed, '4847e034bb0a55fcbc8a3380d6a3ab80',
                                '1')
        self.assertIsNot(None, one.attrib.get('checked'))

    def test_charm_saves_data(self):
        """Verify good data causes the view to store qa data.

        This also verifies our schema a little bit as the fields are turned
        from strings in POST to int's per the schema to match the original
        factory generated data.

        """
        charm = factory.get_charm_json(promulgated=True)
        self.use_index_client()
        charm_source = CharmSource.from_request(self)
        charm_source.save(charm)
        post_data = factory.makeQAAssessment()
        # Add the submit button to trigger the right path through the view.
        post_data['submit'] = 'submit'
        request = self.getRequest(post=post_data)
        request.matchdict = {
            'charm': charm['name'],
            'series': charm['series'],
        }

        quality_edit(request)

        # Remove the submit button we added since it's not stored into the
        # document.
        del post_data['submit']

        # Now the stored QA data should match the data submitted.
        qa_data_source = QADataSource.from_db(self.db)
        found = qa_data_source.get_qa_data(Charm(charm))
        for key in post_data:
            # Ignore any form keys that start with __
            if key.startswith('__'):
                continue

            # Ignore the deform fields that make up the nested structure
            # for the qa questions.
            if key.startswith('deform'):
                continue

            self.assertEqual(
                post_data[key],
                found.charm_data[key])

            # The mapped/nested data needs to exist in the updated charm data.
            self.assertIn('reliable', found.charm_data)
        for stored_charm in charm_source._get_all(charm['_id']):
            self.assertNotIn('qa', stored_charm)


class TestQAFormFunc(WebTestBase):
    """Functional tests for the QA Form Views."""

    def test_form_403s_for_non_charmers(self):
        """The QA form is not permitted if you're not a charmer."""
        with login_request(self.app, groups=[]) as resp:
            cid, charm = factory.makeCharm(self.db)
            # The status force the check against the status code.
            resp = resp.goto(
                'charms/%s/%s/qa/edit' % (charm['series'], charm['name']),
                status=403)
            self.assertEqual(403, resp.status_code)

    def test_form_secured_from_users(self):
        """The qa form is only allowed to be edited/submitted by charmers."""
        with login_request(self.app, groups=['charmers']) as resp:
            cid, charm = factory.makeCharm(self.db, promulgated=True)
            resp = resp.goto(
                'charms/%s/%s/qa/edit' % (charm['series'],
                charm['name']),
                status=200)
            self.assertEqual(resp.status_code, 200)