Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions bibtexparser/middlewares/names.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,17 @@ class InvalidNameError(ValueError):
"""Exception raised by :py:func:`parse_single_name_into_parts` when facing an invalid name."""

def __init__(self, name: str, reason: str):
self.name = name
self.reason = reason
message: str = f"Cannot split the following name `{name}` into parts: {reason}"
super().__init__(message)

def __reduce__(self):
# Rebuild from name and reason so the exception stays copyable and
# picklable; the base ValueError stores only the formatted message in
# args, which does not match this two-argument __init__.
return (self.__class__, (self.name, self.reason))


class _NameTransformerMiddleware(BlockMiddleware, abc.ABC):
"""Internal utility class - superclass for all name-transforming middlewares.
Expand Down
18 changes: 18 additions & 0 deletions tests/middleware_tests/test_names.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,24 @@ def test_name_splitting_strict_mode(name: str, reason: str):
parse_single_name_into_parts(name, strict=True)


def test_invalid_name_error_is_copyable():
# A MiddlewareErrorBlock stores the InvalidNameError, and later middlewares
# (for example SortBlocksByTypeAndKeyMiddleware) deepcopy the library, so
# the exception has to survive copy and pickle. It could not before: its
# two-argument __init__ did not match the single message stored in args.
import pickle

with pytest.raises(InvalidNameError) as exc_info:
parse_single_name_into_parts("AA, BB, CC, DD", strict=True)
error = exc_info.value

for clone in (deepcopy(error), pickle.loads(pickle.dumps(error))):
assert isinstance(clone, InvalidNameError)
assert str(clone) == str(error)
assert clone.name == error.name
assert clone.reason == error.reason


def _dict_to_nameparts(as_dict):
return NameParts(
first=as_dict["first"],
Expand Down