Просмотр исходного кода

support global exceptions handlings for pyramid + test

Guénaël Muller 6 лет назад
Родитель
Сommit
f5d1a8e3a0
2 измененных файлов: 46 добавлений и 1 удалений
  1. 20 1
      hapic/ext/pyramid/context.py
  2. 26 0
      tests/func/test_exception_handling.py

+ 20 - 1
hapic/ext/pyramid/context.py Просмотреть файл

@@ -188,4 +188,23 @@ class PyramidContext(BaseContext):
188 188
         exception_class: typing.Type[Exception],
189 189
         http_code: int,
190 190
     ) -> None:
191
-        raise NotImplementedError('TODO')
191
+
192
+        def factory_view_func(exception_class, http_code):
193
+            def view_func(exc, request):
194
+                # TODO BS 2018-05-04: How to be attentive to hierarchy ?
195
+                error_builder = self.get_default_error_builder()
196
+                error_body = error_builder.build_from_exception(exc)
197
+                return self.get_response(
198
+                    json.dumps(error_body),
199
+                    http_code
200
+                )
201
+            return view_func
202
+
203
+        self.configurator.add_view(
204
+            view=factory_view_func(
205
+                exception_class,
206
+                http_code,
207
+            ),
208
+            context=exception_class,
209
+        )
210
+

+ 26 - 0
tests/func/test_exception_handling.py Просмотреть файл

@@ -1,8 +1,10 @@
1 1
 # coding: utf-8
2 2
 import bottle
3
+from pyramid.config import Configurator
3 4
 from webtest import TestApp
4 5
 
5 6
 from hapic import Hapic
7
+from hapic.ext.pyramid import PyramidContext
6 8
 from tests.base import Base
7 9
 from tests.base import MyContext
8 10
 
@@ -25,3 +27,27 @@ class TestExceptionHandling(Base):
25 27
         response = test_app.get('/my-view', status='*')
26 28
 
27 29
         assert 400 == response.status_code
30
+
31
+    def test_func__catch_one_exception__ok__pyramid(self):
32
+        # TODO - G.M - 17-05-2018 - Move/refactor this test
33
+        # in order to have here only framework agnostic test
34
+        # and framework_specific
35
+        # test somewhere else.
36
+        hapic = Hapic()
37
+        configurator = Configurator(autocommit=True)
38
+        context = PyramidContext(configurator)
39
+        hapic.set_context(context)
40
+
41
+        def my_view(context, request):
42
+            raise ZeroDivisionError('An exception message')
43
+
44
+        configurator.add_route('my_view','/my-view', request_method='GET')
45
+        configurator.add_view(my_view, route_name='my_view', renderer='json')
46
+
47
+        context.handle_exception(ZeroDivisionError, http_code=400)
48
+
49
+        app = configurator.make_wsgi_app()
50
+        test_app = TestApp(app)
51
+        response = test_app.get('/my-view', status='*')
52
+
53
+        assert 400 == response.status_code