Przeglądaj źródła

better tests for user commands + tests for group_api + some fixe in group_api lib

Guénaël Muller 6 lat temu
rodzic
commit
de19c9e634

+ 2 - 1
tracim/command/__init__.py Wyświetl plik

9
 
9
 
10
 from pyramid.paster import bootstrap
10
 from pyramid.paster import bootstrap
11
 from pyramid.scripting import AppEnvironment
11
 from pyramid.scripting import AppEnvironment
12
-from tracim.exceptions import CommandAbortedError
12
+from tracim.exceptions import BadCommandError
13
 from tracim.lib.utils.utils import DEFAULT_TRACIM_CONFIG_FILE
13
 from tracim.lib.utils.utils import DEFAULT_TRACIM_CONFIG_FILE
14
 
14
 
15
 
15
 
56
                 with app_context['request'].tm:
56
                 with app_context['request'].tm:
57
                     self.take_app_action(parsed_args, app_context)
57
                     self.take_app_action(parsed_args, app_context)
58
 
58
 
59
+
59
     def get_parser(self, prog_name: str) -> argparse.ArgumentParser:
60
     def get_parser(self, prog_name: str) -> argparse.ArgumentParser:
60
         parser = super(AppContextCommand, self).get_parser(prog_name)
61
         parser = super(AppContextCommand, self).get_parser(prog_name)
61
 
62
 

+ 18 - 8
tracim/command/user.py Wyświetl plik

3
 from pyramid.scripting import AppEnvironment
3
 from pyramid.scripting import AppEnvironment
4
 import transaction
4
 import transaction
5
 from sqlalchemy.exc import IntegrityError
5
 from sqlalchemy.exc import IntegrityError
6
+from sqlalchemy.orm.exc import NoResultFound
6
 
7
 
7
 from tracim import CFG
8
 from tracim import CFG
8
 from tracim.command import AppContextCommand
9
 from tracim.command import AppContextCommand
11
 #from tracim.lib.daemons import DaemonsManager
12
 #from tracim.lib.daemons import DaemonsManager
12
 #from tracim.lib.daemons import RadicaleDaemon
13
 #from tracim.lib.daemons import RadicaleDaemon
13
 #from tracim.lib.email import get_email_manager
14
 #from tracim.lib.email import get_email_manager
14
-from tracim.exceptions import AlreadyExistError
15
+from tracim.exceptions import UserAlreadyExistError, GroupNotExist
15
 from tracim.exceptions import NotificationNotSend
16
 from tracim.exceptions import NotificationNotSend
16
-from tracim.exceptions import CommandAbortedError
17
+from tracim.exceptions import BadCommandError
17
 from tracim.lib.core.group import GroupApi
18
 from tracim.lib.core.group import GroupApi
18
 from tracim.lib.core.user import UserApi
19
 from tracim.lib.core.user import UserApi
19
 from tracim.models import User
20
 from tracim.models import User
85
         return self._user_api.user_with_email_exists(login)
86
         return self._user_api.user_with_email_exists(login)
86
 
87
 
87
     def _get_group(self, name: str) -> Group:
88
     def _get_group(self, name: str) -> Group:
89
+        groups_availables = [group.group_name
90
+                             for group in self._group_api.get_all()]
91
+        if name not in groups_availables:
92
+            msg = "Group '{}' does not exist, choose a group name in : ".format(name)  # nopep8
93
+            for group in groups_availables:
94
+                msg+= "'{}',".format(group)
95
+            self._session.rollback()
96
+            raise GroupNotExist(msg)
88
         return self._group_api.get_one_with_name(name)
97
         return self._group_api.get_one_with_name(name)
89
 
98
 
90
     def _add_user_to_named_group(
99
     def _add_user_to_named_group(
92
             user: str,
101
             user: str,
93
             group_name: str
102
             group_name: str
94
     ) -> None:
103
     ) -> None:
104
+
95
         group = self._get_group(group_name)
105
         group = self._get_group(group_name)
96
         if user not in group.users:
106
         if user not in group.users:
97
             group.users.append(user)
107
             group.users.append(user)
116
     ) -> User:
126
     ) -> User:
117
         if not password:
127
         if not password:
118
             if self._password_required():
128
             if self._password_required():
119
-                raise CommandAbortedError(
129
+                raise BadCommandError(
120
                     "You must provide -p/--password parameter"
130
                     "You must provide -p/--password parameter"
121
                 )
131
                 )
122
             password = ''
132
             password = ''
135
             self._user_api.execute_created_user_actions(user)
145
             self._user_api.execute_created_user_actions(user)
136
         except IntegrityError:
146
         except IntegrityError:
137
             self._session.rollback()
147
             self._session.rollback()
138
-            raise AlreadyExistError()
148
+            raise UserAlreadyExistError()
139
         except NotificationNotSend as exception:
149
         except NotificationNotSend as exception:
140
             self._session.rollback()
150
             self._session.rollback()
141
             raise exception
151
             raise exception
181
                     password=parsed_args.password,
191
                     password=parsed_args.password,
182
                     do_notify=parsed_args.send_email,
192
                     do_notify=parsed_args.send_email,
183
                 )
193
                 )
184
-            except AlreadyExistError:
185
-                raise CommandAbortedError("Error: User already exist (use `user update` command instead)")
194
+            except UserAlreadyExistError:
195
+                raise UserAlreadyExistError("Error: User already exist (use `user update` command instead)")
186
             except NotificationNotSend:
196
             except NotificationNotSend:
187
-                raise CommandAbortedError("Error: Cannot send email notification, user not created.")
197
+                raise NotificationNotSend("Error: Cannot send email notification, user not created.")
188
             # TODO - G.M - 04-04-2018 - [Email] Check this code
198
             # TODO - G.M - 04-04-2018 - [Email] Check this code
189
             # if parsed_args.send_email:
199
             # if parsed_args.send_email:
190
             #     email_manager = get_email_manager()
200
             #     email_manager = get_email_manager()
242
     action = UserCommand.ACTION_UPDATE
252
     action = UserCommand.ACTION_UPDATE
243
 
253
 
244
 
254
 
245
-class LDAPUserUnknown(CommandAbortedError):
255
+class LDAPUserUnknown(BadCommandError):
246
     pass
256
     pass

+ 6 - 6
tracim/exceptions.py Wyświetl plik

25
     pass
25
     pass
26
 
26
 
27
 
27
 
28
-class AlreadyExistError(TracimError):
28
+class UserAlreadyExistError(TracimError):
29
     pass
29
     pass
30
 
30
 
31
 
31
 
32
-class CommandError(TracimError):
33
-    pass
34
-
35
-
36
-class CommandAbortedError(CommandError):
32
+class BadCommandError(TracimError):
37
     pass
33
     pass
38
 
34
 
39
 
35
 
99
 
95
 
100
 class NotificationNotSend(TracimException):
96
 class NotificationNotSend(TracimException):
101
     pass
97
     pass
98
+
99
+
100
+class GroupNotExist(TracimError):
101
+    pass

+ 17 - 2
tracim/lib/core/group.py Wyświetl plik

1
 # -*- coding: utf-8 -*-
1
 # -*- coding: utf-8 -*-
2
 import typing
2
 import typing
3
 
3
 
4
+from sqlalchemy.orm.exc import NoResultFound
5
+
6
+from tracim.exceptions import GroupNotExist
7
+
4
 __author__ = 'damien'
8
 __author__ = 'damien'
5
 
9
 
6
 from tracim.models.auth import Group, User
10
 from tracim.models.auth import Group, User
22
         return self._session.query(Group)
26
         return self._session.query(Group)
23
 
27
 
24
     def get_one(self, group_id) -> Group:
28
     def get_one(self, group_id) -> Group:
25
-        return self._base_query().filter(Group.group_id == group_id).one()
29
+        try:
30
+            group = self._base_query().filter(Group.group_id == group_id).one()
31
+            return group
32
+        except NoResultFound:
33
+            raise GroupNotExist()
26
 
34
 
27
     def get_one_with_name(self, group_name) -> Group:
35
     def get_one_with_name(self, group_name) -> Group:
28
-        return self._base_query().filter(Group.group_name == group_name).one()
36
+        try:
37
+            group = self._base_query().filter(Group.group_name == group_name).one()
38
+            return group
39
+        except NoResultFound:
40
+            raise GroupNotExist()
41
+
42
+    def get_all(self):
43
+        return self._base_query().order_by(Group.group_id).all()

+ 123 - 6
tracim/tests/commands/test_commands.py Wyświetl plik

10
 import tracim
10
 import tracim
11
 from tracim.command import TracimCLI
11
 from tracim.command import TracimCLI
12
 from tracim.command.user import UserCommand
12
 from tracim.command.user import UserCommand
13
-from tracim.exceptions import UserNotExist
13
+from tracim.exceptions import UserAlreadyExistError, BadCommandError, \
14
+    GroupNotExist
14
 from tracim.lib.core.user import UserApi
15
 from tracim.lib.core.user import UserApi
15
 from tracim.tests import CommandFunctionalTest
16
 from tracim.tests import CommandFunctionalTest
16
 
17
 
22
 
23
 
23
     config_section = 'app:command_test'
24
     config_section = 'app:command_test'
24
 
25
 
25
-    def test_func__check_commands_list__ok__nominal_case(self):
26
+    def test_func__check_commands_list__ok__nominal_case(self) -> None:
26
         """
27
         """
27
         Test listing of tracimcli command: Tracim commands must be listed
28
         Test listing of tracimcli command: Tracim commands must be listed
28
         :return:
29
         :return:
38
         assert output.find('db delete') > 0
39
         assert output.find('db delete') > 0
39
         assert output.find('webdav start') > 0
40
         assert output.find('webdav start') > 0
40
 
41
 
41
-    def test_func__user_create_command__ok__nominal_case(self):
42
+    def test_func__user_create_command__ok__nominal_case(self) -> None:
42
         """
43
         """
43
         Test User creation
44
         Test User creation
44
         """
45
         """
54
             'user', 'create',
55
             'user', 'create',
55
             '-c', 'tests_configs.ini#command_test',
56
             '-c', 'tests_configs.ini#command_test',
56
             '-l', 'command_test@user',
57
             '-l', 'command_test@user',
57
-            '-p', 'new_password'
58
+            '-p', 'new_password',
59
+            '--debug',
58
         ])
60
         ])
59
         new_user = api.get_one_by_email('command_test@user')
61
         new_user = api.get_one_by_email('command_test@user')
60
         assert new_user.email == 'command_test@user'
62
         assert new_user.email == 'command_test@user'
61
         assert new_user.validate_password('new_password')
63
         assert new_user.validate_password('new_password')
64
+        assert new_user.profile.name == 'users'
62
 
65
 
63
-    def test_func__user_update_command__ok__nominal_case(self):
66
+    def test_func__user_create_command__ok__in_admin_group(self) -> None:
67
+        """
68
+        Test User creation with admin as group
69
+        """
70
+        api = UserApi(
71
+            current_user=None,
72
+            session=self.session,
73
+            config=self.app_config,
74
+        )
75
+        with pytest.raises(NoResultFound):
76
+            api.get_one_by_email('command_test@user')
77
+        app = TracimCLI()
78
+        result = app.run([
79
+            'user', 'create',
80
+            '-c', 'tests_configs.ini#command_test',
81
+            '-l', 'command_test@user',
82
+            '-p', 'new_password',
83
+            '-g', 'administrators',
84
+            '--debug',
85
+        ])
86
+        new_user = api.get_one_by_email('command_test@user')
87
+        assert new_user.email == 'command_test@user'
88
+        assert new_user.validate_password('new_password')
89
+        assert new_user.profile.name == 'administrators'
90
+
91
+    def test_func__user_create_command__err__in_unknown_group(self) -> None:
92
+        """
93
+        Test User creation with an unknown group
94
+        """
95
+        api = UserApi(
96
+            current_user=None,
97
+            session=self.session,
98
+            config=self.app_config,
99
+        )
100
+        app = TracimCLI()
101
+        with pytest.raises(GroupNotExist):
102
+            result = app.run([
103
+                'user', 'create',
104
+                '-c', 'tests_configs.ini#command_test',
105
+                '-l', 'command_test@user',
106
+                '-p', 'new_password',
107
+                '-g', 'unknown',
108
+                '--debug',
109
+            ])
110
+
111
+    def test_func__user_create_command__err_user_already_exist(self) -> None:
112
+        """
113
+        Test User creation with existing user login
114
+        """
115
+        api = UserApi(
116
+            current_user=None,
117
+            session=self.session,
118
+            config=self.app_config,
119
+        )
120
+        app = TracimCLI()
121
+        with pytest.raises(UserAlreadyExistError):
122
+            result = app.run([
123
+                '--debug',
124
+                'user', 'create',
125
+                '-c', 'tests_configs.ini#command_test',
126
+                '-l', 'admin@admin.admin',
127
+                '-p', 'new_password',
128
+                '--debug',
129
+            ])
130
+
131
+    def test_func__user_create_command__err__password_required(self) -> None:
132
+        """
133
+        Test User creation without filling password
134
+        """
135
+        api = UserApi(
136
+            current_user=None,
137
+            session=self.session,
138
+            config=self.app_config,
139
+        )
140
+        app = TracimCLI()
141
+        with pytest.raises(BadCommandError):
142
+            result = app.run([
143
+                '--debug',
144
+                'user', 'create',
145
+                '-c', 'tests_configs.ini#command_test',
146
+                '-l', 'admin@admin.admin',
147
+                '--debug',
148
+            ])
149
+
150
+    def test_func__user_update_command__ok__nominal_case(self) -> None:
64
         """
151
         """
65
         Test user password update
152
         Test user password update
66
         """
153
         """
79
             'user', 'update',
166
             'user', 'update',
80
             '-c', 'tests_configs.ini#command_test',
167
             '-c', 'tests_configs.ini#command_test',
81
             '-l', 'admin@admin.admin',
168
             '-l', 'admin@admin.admin',
82
-            '-p', 'new_password'
169
+            '-p', 'new_password',
170
+            '--debug',
171
+        ])
172
+        new_user = api.get_one_by_email('admin@admin.admin')
173
+        assert new_user.email == 'admin@admin.admin'
174
+        assert new_user.validate_password('new_password')
175
+        assert not new_user.validate_password('admin@admin.admin')
176
+
177
+    def test_func__user_update_command__ok__remove_group(self) -> None:
178
+        """
179
+        Test user password update
180
+        """
181
+        api = UserApi(
182
+            current_user=None,
183
+            session=self.session,
184
+            config=self.app_config,
185
+        )
186
+        user = api.get_one_by_email('admin@admin.admin')
187
+        assert user.email == 'admin@admin.admin'
188
+        assert user.validate_password('admin@admin.admin')
189
+        assert not user.validate_password('new_password')
190
+        assert user.profile.name == 'administrators'
191
+        app = TracimCLI()
192
+        result = app.run([
193
+            'user', 'update',
194
+            '-c', 'tests_configs.ini#command_test',
195
+            '-l', 'admin@admin.admin',
196
+            '-p', 'new_password',
197
+            '-rmg', 'administrators',
198
+            '--debug',
83
         ])
199
         ])
84
         new_user = api.get_one_by_email('admin@admin.admin')
200
         new_user = api.get_one_by_email('admin@admin.admin')
85
         assert new_user.email == 'admin@admin.admin'
201
         assert new_user.email == 'admin@admin.admin'
86
         assert new_user.validate_password('new_password')
202
         assert new_user.validate_password('new_password')
87
         assert not new_user.validate_password('admin@admin.admin')
203
         assert not new_user.validate_password('admin@admin.admin')
204
+        assert new_user.profile.name == 'managers'

+ 69 - 0
tracim/tests/library/test_group_api.py Wyświetl plik

1
+# coding=utf-8
2
+import pytest
3
+
4
+from tracim.exceptions import GroupNotExist
5
+from tracim.lib.core.group import GroupApi
6
+from tracim.tests import DefaultTest
7
+from tracim.fixtures.users_and_groups import Base as BaseFixture
8
+from tracim.fixtures.content import Content as ContentFixture
9
+
10
+
11
+class TestGroupApi(DefaultTest):
12
+    fixtures = [BaseFixture, ContentFixture]
13
+
14
+    def test_unit__get_one__ok_nominal_case(self) -> None:
15
+        """
16
+        Get one group by id
17
+        """
18
+        api = GroupApi(
19
+            current_user=None,
20
+            session=self.session,
21
+        )
22
+        group = api.get_one(1)
23
+        assert group.group_id == 1
24
+        assert group.group_name == 'users'
25
+
26
+    def test_unit__get_one__err__group_not_exist(self) -> None:
27
+        """
28
+        Get one group who does not exist by id
29
+        """
30
+        api = GroupApi(
31
+            current_user=None,
32
+            session=self.session,
33
+        )
34
+        with pytest.raises(GroupNotExist):
35
+            group = api.get_one(10)
36
+
37
+    def test_unit__get_one_group_with_name__nominal_case(self) -> None:
38
+        """
39
+        get one group by name
40
+        """
41
+        api = GroupApi(
42
+            current_user=None,
43
+            session=self.session,
44
+        )
45
+        group = api.get_one_with_name('administrators')
46
+        assert group.group_id == 3
47
+        assert group.group_name == 'administrators'
48
+
49
+    def test_unit__get_one_with_name__err__group_not_exist(self) -> None:
50
+        """
51
+        get one group by name who does not exist
52
+        """
53
+        api = GroupApi(
54
+            current_user=None,
55
+            session=self.session,
56
+        )
57
+        with pytest.raises(GroupNotExist):
58
+            group = api.get_one_with_name('unknown_group')
59
+
60
+    def test_unit__get_all__ok__nominal_case(self):
61
+        """
62
+        get all groups
63
+        """
64
+        api = GroupApi(
65
+            current_user=None,
66
+            session=self.session,
67
+        )
68
+        groups = api.get_all()
69
+        assert ['users', 'managers', 'administrators'] == [group.group_name for group in groups]  # nopep8