test_decorator.py 9.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. # -*- coding: utf-8 -*-
  2. import typing
  3. try: # Python 3.5+
  4. from http import HTTPStatus
  5. except ImportError:
  6. from http import client as HTTPStatus
  7. import marshmallow
  8. from multidict import MultiDict
  9. from hapic.data import HapicData
  10. from hapic.decorator import ExceptionHandlerControllerWrapper
  11. from hapic.decorator import InputQueryControllerWrapper
  12. from hapic.decorator import InputControllerWrapper
  13. from hapic.decorator import InputOutputControllerWrapper
  14. from hapic.decorator import OutputControllerWrapper
  15. from hapic.hapic import ErrorResponseSchema
  16. from hapic.processor import MarshmallowOutputProcessor
  17. from hapic.processor import ProcessValidationError
  18. from hapic.processor import ProcessorInterface
  19. from hapic.processor import RequestParameters
  20. from tests.base import Base
  21. from tests.base import MyContext
  22. class MyProcessor(ProcessorInterface):
  23. def process(self, value):
  24. return value + 1
  25. def get_validation_error(
  26. self,
  27. request_context: RequestParameters,
  28. ) -> ProcessValidationError:
  29. return ProcessValidationError(
  30. details={
  31. 'original_request_context': request_context,
  32. },
  33. message='ERROR',
  34. )
  35. class MySimpleProcessor(ProcessorInterface):
  36. def process(self, value):
  37. return value
  38. def get_validation_error(
  39. self,
  40. request_context: RequestParameters,
  41. ) -> ProcessValidationError:
  42. return ProcessValidationError(
  43. details={
  44. 'original_request_context': request_context,
  45. },
  46. message='ERROR',
  47. )
  48. class MyControllerWrapper(InputOutputControllerWrapper):
  49. def before_wrapped_func(
  50. self,
  51. func_args: typing.Tuple[typing.Any, ...],
  52. func_kwargs: typing.Dict[str, typing.Any],
  53. ) -> typing.Union[None, typing.Any]:
  54. if func_args and func_args[0] == 666:
  55. return {
  56. 'error_response': 'we are testing'
  57. }
  58. func_kwargs['added_parameter'] = 'a value'
  59. def after_wrapped_function(self, response: typing.Any) -> typing.Any:
  60. return response * 2
  61. class MyInputQueryControllerWrapper(InputControllerWrapper):
  62. def get_processed_data(
  63. self,
  64. request_parameters: RequestParameters,
  65. ) -> typing.Any:
  66. return request_parameters.query_parameters
  67. def update_hapic_data(
  68. self,
  69. hapic_data: HapicData,
  70. processed_data: typing.Dict[str, typing.Any],
  71. ) -> typing.Any:
  72. hapic_data.query = processed_data
  73. class MySchema(marshmallow.Schema):
  74. name = marshmallow.fields.String(required=True)
  75. class TestControllerWrapper(Base):
  76. def test_unit__base_controller_wrapper__ok__no_behaviour(self):
  77. context = MyContext(app=None)
  78. processor = MyProcessor()
  79. wrapper = InputOutputControllerWrapper(context, processor)
  80. @wrapper.get_wrapper
  81. def func(foo):
  82. return foo
  83. result = func(42)
  84. assert result == 42
  85. def test_unit__base_controller__ok__replaced_response(self):
  86. context = MyContext(app=None)
  87. processor = MyProcessor()
  88. wrapper = MyControllerWrapper(context, processor)
  89. @wrapper.get_wrapper
  90. def func(foo):
  91. return foo
  92. # see MyControllerWrapper#before_wrapped_func
  93. result = func(666)
  94. # result have been replaced by MyControllerWrapper#before_wrapped_func
  95. assert {'error_response': 'we are testing'} == result
  96. def test_unit__controller_wrapper__ok__overload_input(self):
  97. context = MyContext(app=None)
  98. processor = MyProcessor()
  99. wrapper = MyControllerWrapper(context, processor)
  100. @wrapper.get_wrapper
  101. def func(foo, added_parameter=None):
  102. # see MyControllerWrapper#before_wrapped_func
  103. assert added_parameter == 'a value'
  104. return foo
  105. result = func(42)
  106. # See MyControllerWrapper#after_wrapped_function
  107. assert result == 84
  108. class TestInputControllerWrapper(Base):
  109. def test_unit__input_data_wrapping__ok__nominal_case(self):
  110. context = MyContext(
  111. app=None,
  112. fake_query_parameters=MultiDict(
  113. (
  114. ('foo', 'bar',),
  115. )
  116. )
  117. )
  118. processor = MyProcessor()
  119. wrapper = MyInputQueryControllerWrapper(context, processor)
  120. @wrapper.get_wrapper
  121. def func(foo, hapic_data=None):
  122. assert hapic_data
  123. assert isinstance(hapic_data, HapicData)
  124. # see MyControllerWrapper#before_wrapped_func
  125. assert hapic_data.query == {'foo': 'bar'}
  126. return foo
  127. result = func(42)
  128. assert result == 42
  129. def test_unit__multi_query_param_values__ok__use_as_list(self):
  130. context = MyContext(
  131. app=None,
  132. fake_query_parameters=MultiDict(
  133. (
  134. ('user_id', 'abc'),
  135. ('user_id', 'def'),
  136. ),
  137. )
  138. )
  139. processor = MySimpleProcessor()
  140. wrapper = InputQueryControllerWrapper(
  141. context,
  142. processor,
  143. as_list=['user_id'],
  144. )
  145. @wrapper.get_wrapper
  146. def func(hapic_data=None):
  147. assert hapic_data
  148. assert isinstance(hapic_data, HapicData)
  149. # see MyControllerWrapper#before_wrapped_func
  150. assert ['abc', 'def'] == hapic_data.query.get('user_id')
  151. return hapic_data.query.get('user_id')
  152. result = func()
  153. assert result == ['abc', 'def']
  154. def test_unit__multi_query_param_values__ok__without_as_list(self):
  155. context = MyContext(
  156. app=None,
  157. fake_query_parameters=MultiDict(
  158. (
  159. ('user_id', 'abc'),
  160. ('user_id', 'def'),
  161. ),
  162. )
  163. )
  164. processor = MySimpleProcessor()
  165. wrapper = InputQueryControllerWrapper(
  166. context,
  167. processor,
  168. )
  169. @wrapper.get_wrapper
  170. def func(hapic_data=None):
  171. assert hapic_data
  172. assert isinstance(hapic_data, HapicData)
  173. # see MyControllerWrapper#before_wrapped_func
  174. assert 'abc' == hapic_data.query.get('user_id')
  175. return hapic_data.query.get('user_id')
  176. result = func()
  177. assert result == 'abc'
  178. class TestOutputControllerWrapper(Base):
  179. def test_unit__output_data_wrapping__ok__nominal_case(self):
  180. context = MyContext(app=None)
  181. processor = MyProcessor()
  182. wrapper = OutputControllerWrapper(context, processor)
  183. @wrapper.get_wrapper
  184. def func(foo, hapic_data=None):
  185. # If no use of input wrapper, no hapic_data is given
  186. assert not hapic_data
  187. return foo
  188. result = func(42)
  189. # see MyProcessor#process
  190. assert {
  191. 'http_code': HTTPStatus.OK,
  192. 'original_response': 43,
  193. } == result
  194. def test_unit__output_data_wrapping__fail__error_response(self):
  195. context = MyContext(app=None)
  196. processor = MarshmallowOutputProcessor()
  197. processor.schema = MySchema()
  198. wrapper = OutputControllerWrapper(context, processor)
  199. @wrapper.get_wrapper
  200. def func(foo):
  201. return 'wrong result format'
  202. result = func(42)
  203. # see MyProcessor#process
  204. assert isinstance(result, dict)
  205. assert 'http_code' in result
  206. assert result['http_code'] == HTTPStatus.INTERNAL_SERVER_ERROR
  207. assert 'original_error' in result
  208. assert result['original_error'].details == {
  209. 'name': ['Missing data for required field.']
  210. }
  211. class TestExceptionHandlerControllerWrapper(Base):
  212. def test_unit__exception_handled__ok__nominal_case(self):
  213. context = MyContext(app=None)
  214. wrapper = ExceptionHandlerControllerWrapper(
  215. ZeroDivisionError,
  216. context,
  217. schema=ErrorResponseSchema(),
  218. http_code=HTTPStatus.INTERNAL_SERVER_ERROR,
  219. )
  220. @wrapper.get_wrapper
  221. def func(foo):
  222. raise ZeroDivisionError('We are testing')
  223. response = func(42)
  224. assert 'http_code' in response
  225. assert response['http_code'] == HTTPStatus.INTERNAL_SERVER_ERROR
  226. assert 'original_response' in response
  227. assert response['original_response'] == {
  228. 'message': 'We are testing',
  229. 'code': None,
  230. 'detail': {},
  231. }
  232. def test_unit__exception_handled__ok__exception_error_dict(self):
  233. class MyException(Exception):
  234. def __init__(self, *args, **kwargs):
  235. super().__init__(*args, **kwargs)
  236. self.error_dict = {}
  237. context = MyContext(app=None)
  238. wrapper = ExceptionHandlerControllerWrapper(
  239. MyException,
  240. context,
  241. schema=ErrorResponseSchema(),
  242. http_code=HTTPStatus.INTERNAL_SERVER_ERROR,
  243. )
  244. @wrapper.get_wrapper
  245. def func(foo):
  246. exc = MyException('We are testing')
  247. exc.error_detail = {'foo': 'bar'}
  248. raise exc
  249. response = func(42)
  250. assert 'http_code' in response
  251. assert response['http_code'] == HTTPStatus.INTERNAL_SERVER_ERROR
  252. assert 'original_response' in response
  253. assert response['original_response'] == {
  254. 'message': 'We are testing',
  255. 'code': None,
  256. 'detail': {'foo': 'bar'},
  257. }