Coverage for amazonorders/entity/parsable.py: 83.33%
18 statements
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-18 14:34 +0000
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-18 14:34 +0000
1import logging
2from typing import Callable, Any
4from bs4 import Tag
6from amazonorders.exception import AmazonOrdersError
8__author__ = "Alex Laird"
9__copyright__ = "Copyright 2024, Alex Laird"
10__version__ = "1.0.0"
12logger = logging.getLogger(__name__)
15class Parsable:
16 """
18 """
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
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.
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_`")
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)