Coverage for src\zapy\requests\hooks.py: 100%

1 from typing import Callable

2 from dataclasses import dataclass

3 from unittest import TestCase

4

5 from zapy.utils.functools import empty_function

6

7

8@dataclass

9 class RequestHook:

10 pre_request: Callable = empty_function

11 post_request: Callable = empty_function

12 test: TestCase | None = None

13

14

15 class RequestHookBlueprint:

16

17 def __init__(self):

18 self.request_hook = RequestHook()

19

20 def pre_request(self, func):

21 '''

22 `pre_request` is a decorator used to intercept and modify `httpx` arguments **before** sending the request.

23 This can be used globally or locally, under a request file.

24

25 Read more about it in the

26 [Zapy docs - Hooks](https://docs.zapy.dev/sdk/hooks/).

27

28

29 ## Example

30

31 ```python

32 from zapy.requests import hooks, HttpxArguments

33

34 @hooks.pre_request

35 async def on_each_request(httpx_args: HttpxArguments):

36 httpx_args['auth'] = ('alice', 'ecila123')

37 print(httpx_args)

38 ```

39 '''

40 self.request_hook.pre_request = func

41 return func

42

43 def post_request(self, func):

44 '''

45 `pre_request` is a decorator used to intercept and modify `httpx` arguments **after** sending the request.

46 This can be used globally or locally, under a request file.

47

48 Read more about it in the

49 [Zapy docs - Hooks](https://docs.zapy.dev/sdk/hooks/).

50

51

52 ## Example

53

54 ```python

55 from zapy.requests import hooks, HttpxResponse

56

57 @hooks.post_request

58 async def after_each_request(httpx_response: HttpxResponse):

59 print(httpx_response.data)

60 ```

61 '''

62 self.request_hook.post_request = func

63 return func

64

65 def test(self, cls):

66 self.request_hook.test = cls

67 return cls

68

69

70 _global_blueprint = RequestHookBlueprint()

71 def use_global_hook():

72 return _global_blueprint.request_hook

73

74 pre_request = _global_blueprint.pre_request

75 post_request = _global_blueprint.post_request