Coverage for amazonorders/entity/parsable.py: 83.33%

18 statements  

« prev     ^ index     » next       coverage.py v7.4.0, created at 2024-01-25 22:50 +0000

1import logging 

2from typing import Callable, Any 

3 

4from bs4 import Tag 

5 

6from amazonorders.exception import AmazonOrdersError 

7 

8__author__ = "Alex Laird" 

9__copyright__ = "Copyright 2024, Alex Laird" 

10__version__ = "1.0.3" 

11 

12logger = logging.getLogger(__name__) 

13 

14 

15class Parsable: 

16 """ 

17 A base class that contains a parsed representation of the entity in ``parsed``. 

18 """ 

19 

20 def __init__(self, 

21 parsed: Tag) -> None: 

22 #: Parsed HTML data that can be used to populate the fields of the entity. 

23 self.parsed: Tag = parsed 

24 

25 def safe_parse(self, 

26 parse_function: Callable[[], Any]) -> Any: 

27 """ 

28 Execute the given parse function, handling any common parse exceptions and passing them as 

29 warnings to the logger, suppressing them as exceptions. 

30 

31 :param parse_function: The parse function to attempt safe execution. 

32 :return: The return value from ``parse_function``. 

33 """ 

34 if not parse_function.__name__.startswith("_parse_"): 

35 raise AmazonOrdersError("This name of the `parse_function` passed to this method must start with `_parse_`") 

36 

37 try: 

38 return parse_function() 

39 except (AttributeError, IndexError, ValueError): 

40 logger.warning("When building {}, `{}` could not be parsed.".format(self.__class__.__name__, 

41 parse_function.__name__.split( 

42 "_parse_")[1]), 

43 exc_info=True)