Skip to content

Commit

Permalink
STY: Capitalize error messages (#2903)
Browse files Browse the repository at this point in the history
  • Loading branch information
j-t-1 authored Oct 15, 2024
1 parent 482a484 commit dd39992
Show file tree
Hide file tree
Showing 15 changed files with 42 additions and 42 deletions.
8 changes: 4 additions & 4 deletions pypdf/_doc_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@

def convert_to_int(d: bytes, size: int) -> Union[int, Tuple[Any, ...]]:
if size > 8:
raise PdfReadError("invalid size in convert_to_int")
raise PdfReadError("Invalid size in convert_to_int")
d = b"\x00\x00\x00\x00\x00\x00\x00\x00" + d
d = d[-8:]
return struct.unpack(">q", d)[0]
Expand Down Expand Up @@ -761,9 +761,9 @@ def _get_inherited(obj: DictionaryObject, key: str) -> Any:
# to cope with all types
field = cast(DictionaryObject, field.indirect_reference.get_object()) # type: ignore
except Exception as exc:
raise ValueError("field type is invalid") from exc
raise ValueError("Field type is invalid") from exc
if is_null_or_none(_get_inherited(field, "/FT")):
raise ValueError("field is not valid")
raise ValueError("Field is not valid")
ret = []
if field.get("/Subtype", "") == "/Widget":
if "/P" in field:
Expand Down Expand Up @@ -827,7 +827,7 @@ def open_destination(

@open_destination.setter
def open_destination(self, dest: Union[None, str, Destination, PageObject]) -> None:
raise NotImplementedError("no setter for open_destination")
raise NotImplementedError("No setter for open_destination")

@property
def outline(self) -> OutlineType:
Expand Down
16 changes: 8 additions & 8 deletions pypdf/_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -455,13 +455,13 @@ def __getitem__(
if isinstance(index, (str, list, tuple)):
return self.get_function(index)
if not isinstance(index, int):
raise TypeError("invalid sequence indices type")
raise TypeError("Invalid sequence indices type")
len_self = len(lst)
if index < 0:
# support negative indexes
index = len_self + index
if index < 0 or index >= len_self:
raise IndexError("sequence index out of range")
raise IndexError("Sequence index out of range")
return self.get_function(lst[index])

def __iter__(self) -> Iterator[ImageFile]:
Expand Down Expand Up @@ -641,7 +641,7 @@ def _get_image(
if self.inline_images is None:
self.inline_images = self._get_inline_images()
if self.inline_images is None: # pragma: no cover
raise KeyError("no inline image can be found")
raise KeyError("No inline image can be found")
return self.inline_images[id]

imgd = _xobj_to_image(cast(DictionaryObject, xobjs[id]))
Expand Down Expand Up @@ -986,7 +986,7 @@ def _content_stream_rename(
if isinstance(op, NameObject):
operands[i] = rename.get(op, op)
else:
raise KeyError(f"type of operands is {type(operands)}")
raise KeyError(f"Type of operands is {type(operands)}")
return stream

@staticmethod
Expand Down Expand Up @@ -2498,13 +2498,13 @@ def __getitem__(
cls = type(self)
return cls(indices.__len__, lambda idx: self[indices[idx]])
if not isinstance(index, int):
raise TypeError("sequence indices must be integers")
raise TypeError("Sequence indices must be integers")
len_self = len(self)
if index < 0:
# support negative indexes
index = len_self + index
if index < 0 or index >= len_self:
raise IndexError("sequence index out of range")
raise IndexError("Sequence index out of range")
return self.get_function(index)

def __delitem__(self, index: Union[int, slice]) -> None:
Expand All @@ -2517,13 +2517,13 @@ def __delitem__(self, index: Union[int, slice]) -> None:
del self[p] # recursive call
return
if not isinstance(index, int):
raise TypeError("index must be integers")
raise TypeError("Index must be integers")
len_self = len(self)
if index < 0:
# support negative indexes
index = len_self + index
if index < 0 or index >= len_self:
raise IndexError("index out of range")
raise IndexError("Index out of range")
ind = self[index].indirect_reference
assert ind is not None
parent: Optional[PdfObject] = cast(DictionaryObject, ind.get_object()).get(
Expand Down
6 changes: 3 additions & 3 deletions pypdf/_page_labels.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ def nums_insert(
nums: Nums array to modify
"""
if len(nums) % 2 != 0:
raise ValueError("a nums like array must have an even number of elements")
raise ValueError("A nums like array must have an even number of elements")

i = len(nums)
while i != 0 and key <= nums[i - 2]:
Expand Down Expand Up @@ -252,7 +252,7 @@ def nums_clear_range(
nums: Nums array to modify
"""
if len(nums) % 2 != 0:
raise ValueError("a nums like array must have an even number of elements")
raise ValueError("A nums like array must have an even number of elements")
if page_index_to < key:
raise ValueError("page_index_to must be greater or equal than key")

Expand All @@ -276,7 +276,7 @@ def nums_next(
nums: Nums array
"""
if len(nums) % 2 != 0:
raise ValueError("a nums like array must have an even number of elements")
raise ValueError("A nums like array must have an even number of elements")

i = nums.index(key) + 2
if i < len(nums):
Expand Down
4 changes: 2 additions & 2 deletions pypdf/_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -428,7 +428,7 @@ def get_object(
idnum != indirect_reference.idnum
or generation != indirect_reference.generation
):
raise PdfReadError("not matching, we parse the file for it")
raise PdfReadError("Not matching, we parse the file for it")
except Exception:
if hasattr(self.stream, "getbuffer"):
buf = bytes(self.stream.getbuffer())
Expand Down Expand Up @@ -972,7 +972,7 @@ def _read_xref_other_error(
self._rebuild_xref_table(stream)
return None
except Exception:
raise PdfReadError("can not rebuild xref")
raise PdfReadError("Cannot rebuild xref")
raise PdfReadError("Could not find xref table at specified location")

def _read_pdf15_xref_stream(
Expand Down
2 changes: 1 addition & 1 deletion pypdf/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ def _get_max_pdf_version_header(header1: str, header2: str) -> str:
if header2 in versions:
pdf_header_indices.append(versions.index(header2))
if len(pdf_header_indices) == 0:
raise ValueError(f"neither {header1!r} nor {header2!r} are proper headers")
raise ValueError(f"Neither {header1!r} nor {header2!r} are proper headers")
return versions[max(pdf_header_indices)]


Expand Down
6 changes: 3 additions & 3 deletions pypdf/_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -453,7 +453,7 @@ def _replace_object(
) -> PdfObject:
if isinstance(indirect_reference, IndirectObject):
if indirect_reference.pdf != self:
raise ValueError("pdf must be self")
raise ValueError("PDF must be self")
indirect_reference = indirect_reference.idnum
gen = self._objects[indirect_reference - 1].indirect_reference.generation # type: ignore
if (
Expand Down Expand Up @@ -1325,7 +1325,7 @@ def encrypt(
try:
alg = getattr(EncryptAlgorithm, algorithm.replace("-", "_"))
except AttributeError:
raise ValueError(f"algorithm '{algorithm}' NOT supported")
raise ValueError(f"Algorithm '{algorithm}' NOT supported")
else:
alg = EncryptAlgorithm.RC4_128
if not use_128bit:
Expand Down Expand Up @@ -1384,7 +1384,7 @@ def write(self, stream: Union[Path, StrByteType]) -> Tuple[bool, IO[Any]]:
my_file = False

if stream == "":
raise ValueError(f"Output(stream={stream}) is empty.")
raise ValueError(f"Output({stream=}) is empty.")

if isinstance(stream, (str, Path)):
stream = FileIO(stream, "wb")
Expand Down
2 changes: 1 addition & 1 deletion pypdf/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,7 @@ def decode(
index += 1
if length == 128:
if index < len(data):
raise PdfStreamError("early EOD in RunLengthDecode")
raise PdfStreamError("Early EOD in RunLengthDecode")
else:
break
elif length < 128:
Expand Down
2 changes: 1 addition & 1 deletion pypdf/generic/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -832,7 +832,7 @@ def unnumber(sin: bytes) -> bytes:
def read_from_stream(stream: StreamType, pdf: Any) -> "NameObject": # PdfReader
name = stream.read(1)
if name != NameObject.surfix:
raise PdfReadError("name read error")
raise PdfReadError("Name read error")
name += read_until_regex(stream, NameObject.delimiter_pattern)
try:
# Name objects should represent irregular characters
Expand Down
12 changes: 6 additions & 6 deletions pypdf/generic/_data_structures.py
Original file line number Diff line number Diff line change
Expand Up @@ -447,24 +447,24 @@ def get_inherited(self, key: str, default: Any = None) -> Any:
try:
if "/Parent" not in self:
return default
raise KeyError("not present")
raise KeyError("Not present")
except KeyError:
return cast("DictionaryObject", self["/Parent"].get_object()).get_inherited(
key, default
)

def __setitem__(self, key: Any, value: Any) -> Any:
if not isinstance(key, PdfObject):
raise ValueError("key must be PdfObject")
raise ValueError("Key must be a PdfObject")
if not isinstance(value, PdfObject):
raise ValueError("value must be PdfObject")
raise ValueError("Value must be a PdfObject")
return dict.__setitem__(self, key, value)

def setdefault(self, key: Any, value: Optional[Any] = None) -> Any:
if not isinstance(key, PdfObject):
raise ValueError("key must be PdfObject")
raise ValueError("Key must be a PdfObject")
if not isinstance(value, PdfObject):
raise ValueError("value must be PdfObject")
raise ValueError("Value must be a PdfObject")
return dict.setdefault(self, key, value) # type: ignore

def __getitem__(self, key: Any) -> PdfObject:
Expand Down Expand Up @@ -1109,7 +1109,7 @@ def set_data(self, data: bytes) -> None:

if self.get(SA.FILTER, "") in (FT.FLATE_DECODE, [FT.FLATE_DECODE]):
if not isinstance(data, bytes):
raise TypeError("data must be bytes")
raise TypeError("Data must be bytes")
if self.decoded_self is None:
self.get_data() # to create self.decoded_self
assert self.decoded_self is not None, "mypy"
Expand Down
2 changes: 1 addition & 1 deletion tests/test_encryption.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ def test_pdf_encrypt(pdf_file_path, alg, requires_aes):
owner_password=owner_password,
algorithm=alg,
)
assert exc.value.args[0] == "algorithm 'ABCD' NOT supported"
assert exc.value.args[0] == "Algorithm 'ABCD' NOT supported"
return

if requires_aes and not HAS_AES:
Expand Down
10 changes: 5 additions & 5 deletions tests/test_generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ def test_name_object(caplog):
stream = BytesIO(b"x")
with pytest.raises(PdfReadError) as exc:
NameObject.read_from_stream(stream, None)
assert exc.value.args[0] == "name read error"
assert exc.value.args[0] == "Name read error"
assert (
NameObject.read_from_stream(
BytesIO(b"/A;Name_With-Various***Characters?"), None
Expand Down Expand Up @@ -339,7 +339,7 @@ def test_dictionaryobject_key_is_no_pdfobject():
do = DictionaryObject({NameObject("/S"): NameObject("/GoTo")})
with pytest.raises(ValueError) as exc:
do["foo"] = NameObject("/GoTo")
assert exc.value.args[0] == "key must be PdfObject"
assert exc.value.args[0] == "Key must be a PdfObject"


def test_dictionaryobject_xmp_meta():
Expand All @@ -351,21 +351,21 @@ def test_dictionaryobject_value_is_no_pdfobject():
do = DictionaryObject({NameObject("/S"): NameObject("/GoTo")})
with pytest.raises(ValueError) as exc:
do[NameObject("/S")] = "/GoTo"
assert exc.value.args[0] == "value must be PdfObject"
assert exc.value.args[0] == "Value must be a PdfObject"


def test_dictionaryobject_setdefault_key_is_no_pdfobject():
do = DictionaryObject({NameObject("/S"): NameObject("/GoTo")})
with pytest.raises(ValueError) as exc:
do.setdefault("foo", NameObject("/GoTo"))
assert exc.value.args[0] == "key must be PdfObject"
assert exc.value.args[0] == "Key must be a PdfObject"


def test_dictionaryobject_setdefault_value_is_no_pdfobject():
do = DictionaryObject({NameObject("/S"): NameObject("/GoTo")})
with pytest.raises(ValueError) as exc:
do.setdefault(NameObject("/S"), "/GoTo")
assert exc.value.args[0] == "value must be PdfObject"
assert exc.value.args[0] == "Value must be a PdfObject"


def test_dictionaryobject_setdefault_value():
Expand Down
6 changes: 3 additions & 3 deletions tests/test_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -793,12 +793,12 @@ def test_pages_attribute():
with pytest.raises(IndexError) as exc:
reader.pages[-1000]

assert exc.value.args[0] == "sequence index out of range"
assert exc.value.args[0] == "Sequence index out of range"

with pytest.raises(IndexError):
reader.pages[1000]

assert exc.value.args[0] == "sequence index out of range"
assert exc.value.args[0] == "Sequence index out of range"


def test_convert_to_int():
Expand All @@ -808,7 +808,7 @@ def test_convert_to_int():
def test_convert_to_int_error():
with pytest.raises(PdfReadError) as exc:
convert_to_int(b"256", 16)
assert exc.value.args[0] == "invalid size in convert_to_int"
assert exc.value.args[0] == "Invalid size in convert_to_int"


@pytest.mark.enable_socket()
Expand Down
2 changes: 1 addition & 1 deletion tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ def test_read_previous_line2():
def test_get_max_pdf_version_header():
with pytest.raises(ValueError) as exc:
_get_max_pdf_version_header(b"", b"PDF-1.2")
assert exc.value.args[0] == "neither b'' nor b'PDF-1.2' are proper headers"
assert exc.value.args[0] == "Neither b'' nor b'PDF-1.2' are proper headers"


def test_read_block_backwards_exception():
Expand Down
4 changes: 2 additions & 2 deletions tests/test_workflows.py
Original file line number Diff line number Diff line change
Expand Up @@ -1197,7 +1197,7 @@ def test_get_page_showing_field():
reader.get_pages_showing_field(None)
with pytest.raises(ValueError) as exc:
writer.get_pages_showing_field(None)
assert "field type is invalid" in exc.value.args[0]
assert "Field type is invalid" in exc.value.args[0]

# Damage Field
del reader.trailer["/Root"]["/AcroForm"]["/Fields"][1].get_object()["/FT"]
Expand All @@ -1208,7 +1208,7 @@ def test_get_page_showing_field():
)
with pytest.raises(ValueError) as exc:
writer.get_pages_showing_field(writer._root_object["/AcroForm"]["/Fields"][1])
assert "field is not valid" in exc.value.args[0]
assert "Field is not valid" in exc.value.args[0]

# missing Parent in field
del reader.trailer["/Root"]["/AcroForm"]["/Fields"][99]["/Kids"][1].get_object()[
Expand Down
2 changes: 1 addition & 1 deletion tests/test_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -982,7 +982,7 @@ def test_write_empty_stream():

with pytest.raises(ValueError) as exc:
writer.write("")
assert exc.value.args[0] == "Output(stream=) is empty."
assert exc.value.args[0] == "Output(stream='') is empty."


def test_startup_dest():
Expand Down

0 comments on commit dd39992

Please sign in to comment.