test_decorator.py 10KB

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