Coverage for audoma/hooks.py: 93%

29 statements  

« prev     ^ index     » next       coverage.py v6.4.2, created at 2022-08-04 07:22 +0000

1from inspect import isclass 

2from typing import ( 

3 Callable, 

4 List, 

5 Tuple, 

6) 

7 

8from rest_framework.settings import api_settings 

9 

10from django.conf import settings as project_settings 

11from django.utils.module_loading import import_string 

12 

13from audoma import settings as audoma_settings 

14 

15 

16def preprocess_include_path_format( 

17 endpoints: Tuple[str, str, str, Callable], **kwargs 

18) -> List[Tuple[str, str, str, Callable]]: 

19 """ 

20 Preprocessing hook that filters {format} prefdixed paths, in case 

21 schema pattern prefix is used and {format} path params are wanted. 

22 """ 

23 format_path = project_settings.SCHEMA_PATTERN_PREFIX 

24 

25 return [ 

26 (path, path_regex, method, callback) 

27 for path, path_regex, method, callback in endpoints 

28 if ( 

29 path.startswith(format_path) 

30 or path.startswith(format_path + "/") 

31 or path.startswith("/" + format_path) 

32 ) 

33 ] 

34 

35 

36def postprocess_common_errors_section(result: dict, request, **kwargs) -> dict: 

37 """ 

38 Postprocessing hook which adds COMMON_API_ERRORS description to the API description. 

39 """ 

40 common_exceptions = audoma_settings.COMMON_API_ERRORS + getattr( 

41 project_settings, "COMMON_API_ERRORS", [] 

42 ) 

43 

44 renderer = project_settings.REST_FRAMEWORK.get( 

45 "DEFAULT_RENDERER_CLASSES", api_settings.DEFAULT_RENDERER_CLASSES 

46 )[0] 

47 

48 if not callable(renderer): 

49 renderer = import_string(renderer) 

50 

51 renderer = renderer() 

52 

53 def generate_exception_desc(error): 

54 exc_desc = "" 

55 exc_desc = f"Status Code: `{error.status_code}` \n\n" 

56 rendered_error_data = renderer.render( 

57 data=vars(error), renderer_context={"indent": 4} 

58 ).decode("utf-8") 

59 

60 exc_desc += f"``` \n {rendered_error_data} \n ``` \n\n" 

61 return exc_desc 

62 

63 result["info"] = result.get("info", {}) 

64 

65 description = "### Common API Errors \n" 

66 for error in common_exceptions: 

67 if isclass(error): 

68 error = error() 

69 description += generate_exception_desc(error) 

70 

71 result["info"]["description"] = ( 

72 result["info"].get("description", "") + "\n\n" + description 

73 ) 

74 

75 return result