Projet

Général

Profil

0001-provisionning-agent-12910.patch

Serghei Mihai, 15 juin 2017 17:00

Télécharger (12 ko)

Voir les différences:

Subject: [PATCH] provisionning agent (#12910)

 corbo/hobo_agent/__init__.py                       |  0
 corbo/hobo_agent/management/__init__.py            |  0
 corbo/hobo_agent/management/commands/__init__.py   |  0
 .../hobo_agent/management/commands/hobo_notify.py  | 51 +++++++++++++
 debian/debian_config.py                            |  2 +
 tests/conftest.py                                  | 85 ++++++++++++++++++++++
 tests/settings.py                                  |  2 +
 tests/test_notify.py                               | 77 ++++++++++++++++++++
 tox.ini                                            |  2 +
 9 files changed, 219 insertions(+)
 create mode 100644 corbo/hobo_agent/__init__.py
 create mode 100644 corbo/hobo_agent/management/__init__.py
 create mode 100644 corbo/hobo_agent/management/commands/__init__.py
 create mode 100644 corbo/hobo_agent/management/commands/hobo_notify.py
 create mode 100644 tests/settings.py
 create mode 100644 tests/test_notify.py
corbo/hobo_agent/management/commands/hobo_notify.py
1
# corbo - Announces Manager
2
# Copyright (C) 2017 Entr'ouvert
3
#
4
# This program is free software: you can redistribute it and/or modify it
5
# under the terms of the GNU Affero General Public License as published
6
# by the Free Software Foundation, either version 3 of the License, or
7
# (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU Affero General Public License for more details.
13
#
14
# You should have received a copy of the GNU Affero General Public License
15
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
16

  
17
from hobo.agent.common.management.commands import hobo_notify
18

  
19
from corbo.models import Subscription
20

  
21
class Command(hobo_notify.Command):
22

  
23
    def process_notification(self, tenant, notification):
24
        super(Command, self).process_notification(tenant, notification)
25
        object_type = notification['objects']['@type']
26
        if object_type != 'user':
27
            return
28
        users = notification['objects']['data']
29
        action = notification['@type']
30
        if notification.get('full'):
31
            uuids = [user['uuid'] for user in users]
32
            Subscription.objects.exclude(uuid__in=uuids).delete()
33

  
34
        for user in users:
35
            for subscription in Subscription.objects.filter(uuid=user['uuid']):
36
                if action == 'provision':
37
                    if subscription.identifier.startswith('mailto:'):
38
                        if user.get('email'):
39
                            subscription.identifier = 'mailto:%s' % user['email']
40
                        else:
41
                            subscription.delete()
42
                            continue
43
                    elif subscription.identifier.startswith('sms:'):
44
                        if user.get('mobile'):
45
                            subscription.identifier = 'sms:%s' % user['mobile']
46
                        else:
47
                            subscription.delete()
48
                            continue
49
                    subscription.save()
50
                elif action == 'deprovision':
51
                    subscription.delete()
debian/debian_config.py
12 12
#
13 13
execfile('/usr/lib/hobo/debian_config_common.py')
14 14

  
15
INSTALLED_APPS = ('corbo.hobo_agent', ) + INSTALLED_APPS
16

  
15 17
#
16 18
# local settings
17 19
#
tests/conftest.py
1 1
import pytest
2 2
import django_webtest
3 3
import copy
4
import tempfile
5
import os
6
import json
7
import shutil
4 8

  
5 9
import django.core.mail.backends.locmem
6 10
from django.core.mail.backends.locmem import EmailBackend as DjangoEmailBackend
11
from django.utils.text import slugify
12

  
13
from corbo.models import Category, Announce, Broadcast, Subscription
14

  
15
CATEGORIES = ('Alerts', 'News')
16

  
17
SUBSCRIBERS = [{'uuid': 'uuid1', 'email': 'foo@example.net', 'mobile': '0102030405'},
18
               {'uuid': 'uuid2', 'email': 'bar@example.net', 'mobile': '0607080900'},
19
               {'uuid': '', 'email': 'john@example.net', 'mobile': '0304050607'}]
7 20

  
8 21

  
9 22
class MockedEmailBackend(object):
......
42 55
    wtm._patch_settings()
43 56
    request.addfinalizer(wtm._unpatch_settings)
44 57
    return django_webtest.DjangoTestApp()
58

  
59

  
60
@pytest.fixture
61
def categories():
62
    categories = []
63
    for category in CATEGORIES:
64
        c, created = Category.objects.get_or_create(name=category, slug=slugify(category))
65
        categories.append(c)
66
    return categories
67

  
68

  
69
@pytest.fixture
70
def subscriptions(categories):
71
    subscriptions = []
72
    for category in categories:
73
        for subscriber in SUBSCRIBERS:
74
            uuid = subscriber['uuid']
75
            subscriptions.append(Subscription.objects.create(category=category, uuid=uuid,
76
                                    identifier='mailto:%(email)s' % subscriber))
77
            subscriptions.append(Subscription.objects.create(category=category, uuid=uuid,
78
                                    identifier='sms:%(mobile)s' % subscriber))
79
    return subscriptions
80

  
81

  
82
@pytest.fixture
83
def tenant_base(request, settings):
84
    base = tempfile.mkdtemp('corbo-tenant-base')
85
    settings.TENANT_BASE = base
86

  
87
    def fin():
88
        shutil.rmtree(base)
89
    request.addfinalizer(fin)
90
    return base
91

  
92

  
93
@pytest.fixture(scope='function')
94
def tenant(transactional_db, request, tenant_base):
95
    from hobo.multitenant.models import Tenant
96
    base = tenant_base
97

  
98
    @pytest.mark.django_db
99
    def make_tenant(name):
100
        tenant_dir = os.path.join(base, name)
101
        os.mkdir(tenant_dir)
102
        with open(os.path.join(tenant_dir, 'hobo.json'), 'w') as fd:
103
            json.dump({
104
                'variables': {
105
                    'hobo_test_variable': True,
106
                    'other_variable': 'foo',
107
                },
108
                'services': [
109
                    {'slug': 'test',
110
                     'service-id': 'corbo',
111
                     'title': 'Test',
112
                     'this': True,
113
                     'secret_key': '12345',
114
                     'base_url': 'http://%s' % name,
115
                     'saml-sp-metadata-url': 'http://%s/metadata/' % name,
116
                     'variables': {
117
                         'other_variable': 'bar',
118
                     }
119
                    },
120
                    {'slug': 'passerelle',
121
                     'title': 'Webserivces',
122
                     'service-id': 'passerelle',
123
                     'secret_key': 'abcdef',
124
                     'base_url': 'http://passerelle.example.net',
125
                     'saml-sp-metadata-url': 'http://passerelle.example.net/metadata/' },
126
                    ]}, fd)
127
        return Tenant(domain_url=name,
128
                      schema_name=name.replace('-', '_').replace('.', '_'))
129
    return make_tenant('corbo.example.net')
tests/settings.py
1
# Add corbo hobo agent
2
INSTALLED_APPS = ('corbo.hobo_agent', ) + INSTALLED_APPS
tests/test_notify.py
1
import pytest
2
from copy import deepcopy
3
import json
4

  
5
from corbo.models import Subscription
6
from corbo.hobo_agent.management.commands.hobo_notify import Command
7
from django.core.management import call_command
8

  
9
NOTIFICATION = {'@type': 'provision',
10
                'objects': {'@type': 'user',
11
                            'data': [
12
                                {'uuid': 'uuid1', 'email': 'foo1@example.net', 'mobile': '0504030201'},
13
                                {'uuid': 'uuid2', 'email': 'bar1@example.net', 'mobile': '0009080706'},
14
                            ]},
15
                'audience': [],
16
                'full': False
17
}
18

  
19

  
20
def test_notify_provision(tenant, subscriptions):
21
    command = Command()
22
    command.process_notification(tenant, NOTIFICATION)
23
    assert Subscription.objects.count() == len(subscriptions)
24
    for user in NOTIFICATION['objects']['data']:
25
        assert Subscription.objects.filter(uuid=user['uuid'], identifier='mailto:%(email)s' % user).exists()
26
        assert Subscription.objects.filter(uuid=user['uuid'], identifier='sms:%(mobile)s' % user).exists()
27

  
28

  
29
def test_notify_other_provision(tenant, subscriptions):
30
    role_notification = deepcopy(NOTIFICATION)
31
    role_notification['objects']['@type'] = 'role'
32
    command = Command()
33
    command.process_notification(tenant, role_notification)
34
    assert Subscription.objects.count() == len(subscriptions)
35
    for subscription in subscriptions:
36
        assert Subscription.objects.filter(uuid=subscription.uuid, identifier=subscription.identifier)
37

  
38

  
39
def test_notify_deprovision(tenant, subscriptions):
40
    deprovision_notification = deepcopy(NOTIFICATION)
41
    deprovision_notification['@type'] = 'deprovision'
42
    command = Command()
43
    command.process_notification(tenant, deprovision_notification)
44
    for user in deprovision_notification['objects']['data']:
45
        assert not Subscription.objects.filter(uuid=user['uuid']).exists()
46

  
47

  
48
def test_notify_full(tenant, subscriptions):
49
    full_notification = deepcopy(NOTIFICATION)
50
    full_notification['full'] = True
51
    command = Command()
52
    command.process_notification(tenant, full_notification)
53
    assert not Subscription.objects.filter(uuid__isnull=True).exists()
54
    assert not Subscription.objects.filter(uuid='').exists()
55
    assert Subscription.objects.count() == 8
56

  
57

  
58
def test_notify_emails_only(tenant, subscriptions):
59
    email_notification = deepcopy(NOTIFICATION)
60
    for user in email_notification['objects']['data']:
61
        user['mobile'] = None
62
        user['email'] = 'new-%(email)s' % user
63
    command = Command()
64
    command.process_notification(tenant, email_notification)
65
    for user in email_notification['objects']['data']:
66
        assert not Subscription.objects.filter(uuid=user['uuid'], identifier__startswith='sms:').exists()
67

  
68

  
69
def test_notify_mobiles_only(tenant, subscriptions):
70
    mobile_notification = deepcopy(NOTIFICATION)
71
    for user in mobile_notification['objects']['data']:
72
        user['email'] = None
73
        user['mobile'] = '0%(mobile)s' % user
74
    command = Command()
75
    command.process_notification(tenant, mobile_notification)
76
    for user in mobile_notification['objects']['data']:
77
        assert not Subscription.objects.filter(uuid=user['uuid'], identifier__startswith='mailto:').exists()
tox.ini
6 6
  coverage: True
7 7
setenv =
8 8
  DJANGO_SETTINGS_MODULE=corbo.settings
9
  CORBO_SETTINGS_FILE=tests/settings.py
9 10
  coverage: COVERAGE=--junitxml=test_results.xml --cov-report xml --cov=corbo/ --cov-config .coveragerc
10 11
deps =
11 12
  django18: django>=1.8,<1.9
13
  http://git.entrouvert.org/hobo.git/snapshot/hobo-master.tar.gz
12 14
  pytest-cov
13 15
  pytest-django>=3.1.1
14 16
  pytest>=3.0.4
15
-