test_decorator.py 9.1KB

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