Projet

Général

Profil

0001-provisionning-agent-12910.patch

Serghei Mihai, 08 juin 2017 16:20

Télécharger (12,1 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                                  | 84 ++++++++++++++++++++++
 tests/settings.py                                  |  2 +
 tests/test_notify.py                               | 80 +++++++++++++++++++++
 tox.ini                                            |  2 +
 9 files changed, 221 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.filter(uuid__isnull=False).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'}]
7 19

  
8 20

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

  
58

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

  
67

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

  
80

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

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

  
91

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

  
97
    @pytest.mark.django_db
98
    def make_tenant(name):
99
        tenant_dir = os.path.join(base, name)
100
        os.mkdir(tenant_dir)
101
        with open(os.path.join(tenant_dir, 'hobo.json'), 'w') as fd:
102
            json.dump({
103
                'variables': {
104
                    'hobo_test_variable': True,
105
                    'other_variable': 'foo',
106
                },
107
                'services': [
108
                    {'slug': 'test',
109
                     'service-id': 'corbo',
110
                     'title': 'Test',
111
                     'this': True,
112
                     'secret_key': '12345',
113
                     'base_url': 'http://%s' % name,
114
                     'saml-sp-metadata-url': 'http://%s/metadata/' % name,
115
                     'variables': {
116
                         'other_variable': 'bar',
117
                     }
118
                    },
119
                    {'slug': 'passerelle',
120
                     'title': 'Webserivces',
121
                     'service-id': 'passerelle',
122
                     'secret_key': 'abcdef',
123
                     'base_url': 'http://passerelle.example.net',
124
                     'saml-sp-metadata-url': 'http://passerelle.example.net/metadata/' },
125
                    ]}, fd)
126
        return Tenant(domain_url=name,
127
                      schema_name=name.replace('-', '_').replace('.', '_'))
128
    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
    print deprovision_notification
44
    command.process_notification(tenant, deprovision_notification)
45
    assert Subscription.objects.count() == 0
46

  
47

  
48
def test_notify_full(tenant, subscriptions, categories):
49
    for category in categories:
50
        Subscription.objects.create(category=category, uuid='uuid3', identifier='mailto:uuid3@example.net')
51
        Subscription.objects.create(category=category, uuid='uuid3', identifier='sms:0303030303')
52
    assert Subscription.objects.count() == 8
53
    full_notification = deepcopy(NOTIFICATION)
54
    full_notification['full'] = True
55
    command = Command()
56
    command.process_notification(tenant, full_notification)
57
    assert Subscription.objects.count() == len(subscriptions)
58
    assert Subscription.objects.filter(uuid='uuid3').count() == 0
59

  
60

  
61
def test_notify_emails_only(tenant, subscriptions):
62
    email_notification = deepcopy(NOTIFICATION)
63
    for user in email_notification['objects']['data']:
64
        user['mobile'] = None
65
        user['email'] = 'new-%(email)s' % user
66
    command = Command()
67
    command.process_notification(tenant, email_notification)
68
    assert Subscription.objects.count() == len(subscriptions) / 2
69
    assert Subscription.objects.exclude(identifier__startswith='sms:').exists()
70

  
71

  
72
def test_notify_mobiles_only(tenant, subscriptions):
73
    mobile_notification = deepcopy(NOTIFICATION)
74
    for user in mobile_notification['objects']['data']:
75
        user['email'] = None
76
        user['mobile'] = '0(mobile)s' % user
77
    command = Command()
78
    command.process_notification(tenant, mobile_notification)
79
    assert Subscription.objects.count() == len(subscriptions) / 2
80
    assert Subscription.objects.exclude(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
-