Kaynağa Gözat

Use hapic error schema for alls Exception + Test 500 NoDB for login

Guénaël Muller 6 yıl önce
ebeveyn
işleme
db9c4aecb6

+ 7 - 1
tracim/__init__.py Dosyayı Görüntüle

@@ -15,6 +15,7 @@ from tracim.lib.utils.authorization import AcceptAllAuthorizationPolicy
15 15
 from tracim.lib.utils.authorization import TRACIM_DEFAULT_PERM
16 16
 from tracim.views.core_api.session_controller import SessionController
17 17
 from tracim.views.default.default_controller import DefaultController
18
+from tracim.views.errors import Error
18 19
 
19 20
 
20 21
 def main(global_config, **settings):
@@ -44,7 +45,12 @@ def main(global_config, **settings):
44 45
     # Add SqlAlchemy DB
45 46
     configurator.include('.models')
46 47
     # set Hapic
47
-    hapic.set_context(PyramidContext(configurator))
48
+    hapic.set_context(
49
+        PyramidContext(
50
+            configurator=configurator,
51
+            default_error_builder=Error()
52
+        )
53
+    )
48 54
     # Add controllers
49 55
     default_controllers = DefaultController()
50 56
     default_controllers.bind(configurator)

+ 19 - 3
tracim/tests/__init__.py Dosyayı Görüntüle

@@ -27,10 +27,14 @@ def eq_(a, b, msg=None):
27 27
 
28 28
 
29 29
 class FunctionalTest(unittest.TestCase):
30
+
31
+    fixtures = [BaseFixture]
32
+    sqlalchemy_url = 'sqlite:///tracim_test.sqlite'
33
+
30 34
     def setUp(self):
31 35
         DepotManager._clear()
32 36
         settings = {
33
-            'sqlalchemy.url': 'sqlite:///tracim_test.sqlite',
37
+            'sqlalchemy.url': self.sqlalchemy_url,
34 38
             'user.auth_token.validity': '604800',
35 39
             'depot_storage_dir': '/tmp/test/depot',
36 40
             'depot_storage_name': 'test',
@@ -51,7 +55,7 @@ class FunctionalTest(unittest.TestCase):
51 55
             dbsession = get_tm_session(session_factory, transaction.manager)
52 56
             try:
53 57
                 fixtures_loader = FixturesLoader(dbsession, app_config)
54
-                fixtures_loader.loads([BaseFixture])
58
+                fixtures_loader.loads(self.fixtures)
55 59
                 transaction.commit()
56 60
                 print("Database initialized.")
57 61
             except IntegrityError:
@@ -72,10 +76,22 @@ class FunctionalTest(unittest.TestCase):
72 76
         DepotManager._clear()
73 77
 
74 78
 
79
+class FunctionalTestEmptyDB(FunctionalTest):
80
+    fixtures = []
81
+
82
+
83
+class FunctionalTestNoDB(FunctionalTest):
84
+    sqlalchemy_url = 'sqlite://'
85
+
86
+    def init_database(self, settings):
87
+        self.engine = get_engine(settings)
88
+
89
+
75 90
 class BaseTest(unittest.TestCase):
76 91
     """
77 92
     Pyramid default test.
78 93
     """
94
+
79 95
     def setUp(self):
80 96
         logger.debug(self, 'Setup Test...')
81 97
         self.config = testing.setUp(settings={
@@ -97,7 +113,7 @@ class BaseTest(unittest.TestCase):
97 113
             get_engine,
98 114
             get_session_factory,
99 115
             get_tm_session,
100
-            )
116
+        )
101 117
 
102 118
         self.engine = get_engine(settings)
103 119
         session_factory = get_session_factory(self.engine)

+ 15 - 2
tracim/tests/functional/test_session.py Dosyayı Görüntüle

@@ -1,7 +1,6 @@
1 1
 # coding=utf-8
2
-import pytest
3
-
4 2
 from tracim.tests import FunctionalTest
3
+from tracim.tests import FunctionalTestNoDB
5 4
 
6 5
 
7 6
 class TestLogoutEndpoint(FunctionalTest):
@@ -13,6 +12,20 @@ class TestLogoutEndpoint(FunctionalTest):
13 12
         res = self.testapp.get('/api/v2/sessions/logout', status=204)
14 13
 
15 14
 
15
+class TestLoginEndpointUnititedDB(FunctionalTestNoDB):
16
+
17
+    def test_api__try_login_enpoint__err_500__no_inited_db(self):
18
+        params = {
19
+            'email': 'admin@admin.admin',
20
+            'password': 'admin@admin.admin',
21
+        }
22
+        res = self.testapp.post_json(
23
+            '/api/v2/sessions/login',
24
+            params=params,
25
+            status=500,
26
+        )
27
+
28
+
16 29
 class TestLoginEndpoint(FunctionalTest):
17 30
 
18 31
     def test_api__try_login_enpoint__ok_204__nominal_case(self):

+ 39 - 4
tracim/views/default/default_controller.py Dosyayı Görüntüle

@@ -1,16 +1,46 @@
1 1
 # coding=utf-8
2
+from pyramid.httpexceptions import HTTPNotFound
3
+
2 4
 from tracim import TracimRequest
3 5
 from tracim.extensions import hapic
4 6
 from tracim.views.controllers import Controller
7
+from tracim.views.errors import Error
5 8
 from pyramid.config import Configurator
6
-from pyramid.exceptions import NotFound
7 9
 
8 10
 
9 11
 class DefaultController(Controller):
10 12
 
11
-    def notfound_view(self, request: TracimRequest):
13
+    def notfound_view(
14
+            self,
15
+            exception: HTTPNotFound,
16
+            request: TracimRequest
17
+    ):
18
+        """
19
+        Catch Not Found Exception
20
+        :param exception: Exception Object
21
+        :param request: current Request
22
+        :return: 500 Internal Server Error with same format as others errors
23
+        """
12 24
         request.response.status = 404
13
-        return {}
25
+        return hapic.context.get_default_error_builder().build_from_exception(
26
+            exception=exception
27
+        )
28
+
29
+    def exception_view(
30
+            self,
31
+            exception: Exception,
32
+            request: TracimRequest
33
+    ):
34
+        """
35
+        Catch all exceptions not handled in view
36
+        :param exception: Exception Object
37
+        :param request: current Request
38
+        :return: 500 Internal Server Error with same format as others errors
39
+        """
40
+        request.response.status = 500
41
+        return hapic.context.get_default_error_builder().build_from_exception(
42
+            exception=exception
43
+        )
14 44
 
15 45
     def swagger_doc(self, request: TracimRequest):
16 46
         return hapic.generate_doc(
@@ -22,7 +52,12 @@ class DefaultController(Controller):
22 52
         configurator.add_view(
23 53
             self.notfound_view,
24 54
             renderer='json',
25
-            context=NotFound,
55
+            context=HTTPNotFound,
56
+        )
57
+        configurator.add_view(
58
+            self.exception_view,
59
+            renderer='json',
60
+            context=Exception,
26 61
         )
27 62
         configurator.add_route(
28 63
             'swagger_doc',

+ 5 - 0
tracim/views/errors.py Dosyayı Görüntüle

@@ -0,0 +1,5 @@
1
+from hapic.error import DefaultErrorBuilder
2
+
3
+
4
+class Error(DefaultErrorBuilder):
5
+    pass