Skip to content

Commit

Permalink
pytest style
Browse files Browse the repository at this point in the history
  • Loading branch information
MartinThoma committed Apr 30, 2022
1 parent de69c50 commit 16699cc
Show file tree
Hide file tree
Showing 11 changed files with 73 additions and 63 deletions.
59 changes: 32 additions & 27 deletions PyPDF2/merger.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,9 @@ def __init__(self, pagedata, src, id):

class PdfFileMerger(object):
"""
Initializes a ``PdfFileMerger`` object. ``PdfFileMerger`` merges multiple PDFs
into a single PDF. It can concatenate, slice, insert, or any combination
of the above.
Initializes a ``PdfFileMerger`` object. ``PdfFileMerger`` merges multiple
PDFs into a single PDF. It can concatenate, slice, insert, or any
combination of the above.
See the functions :meth:`merge()<merge>` (or :meth:`append()<append>`)
and :meth:`write()<write>` for usage information.
Expand Down Expand Up @@ -95,19 +95,21 @@ def merge(
:param int position: The *page number* to insert this file. File will
be inserted after the given number.
:param fileobj: A File Object or an object that supports the standard read
and seek methods similar to a File Object. Could also be a
:param fileobj: A File Object or an object that supports the standard
read and seek methods similar to a File Object. Could also be a
string representing a path to a PDF file.
:param str bookmark: Optionally, you may specify a bookmark to be applied at
the beginning of the included file by supplying the text of the bookmark.
:param str bookmark: Optionally, you may specify a bookmark to be
applied at the beginning of the included file by supplying the text
of the bookmark.
:param pages: can be a :class:`PageRange<PyPDF2.pagerange.PageRange>` or a ``(start, stop[, step])`` tuple
:param pages: can be a :class:`PageRange<PyPDF2.pagerange.PageRange>`
or a ``(start, stop[, step])`` tuple
to merge only the specified range of pages from the source
document into the output document.
:param bool import_bookmarks: You may prevent the source document's bookmarks
from being imported by specifying this as ``False``.
:param bool import_bookmarks: You may prevent the source document's
bookmarks from being imported by specifying this as ``False``.
"""

# This parameter is passed to self.inputs.append and means
Expand Down Expand Up @@ -135,7 +137,10 @@ def merge(
orig_tell = fileobj.stream.tell()
fileobj.stream.seek(0)
filecontent = StreamIO(fileobj.stream.read())
fileobj.stream.seek(orig_tell) # reset the stream to its original location

# reset the stream to its original location
fileobj.stream.seek(orig_tell)

fileobj = filecontent
my_file = True

Expand Down Expand Up @@ -199,22 +204,25 @@ def merge(

def append(self, fileobj, bookmark=None, pages=None, import_bookmarks=True):
"""
Identical to the :meth:`merge()<merge>` method, but assumes you want to concatenate
all pages onto the end of the file instead of specifying a position.
Identical to the :meth:`merge()<merge>` method, but assumes you want to
concatenate all pages onto the end of the file instead of specifying a
position.
:param fileobj: A File Object or an object that supports the standard read
and seek methods similar to a File Object. Could also be a
:param fileobj: A File Object or an object that supports the standard
read and seek methods similar to a File Object. Could also be a
string representing a path to a PDF file.
:param str bookmark: Optionally, you may specify a bookmark to be applied at
the beginning of the included file by supplying the text of the bookmark.
:param str bookmark: Optionally, you may specify a bookmark to be
applied at the beginning of the included file by supplying the text
of the bookmark.
:param pages: can be a :class:`PageRange<PyPDF2.pagerange.PageRange>` or a ``(start, stop[, step])`` tuple
:param pages: can be a :class:`PageRange<PyPDF2.pagerange.PageRange>`
or a ``(start, stop[, step])`` tuple
to merge only the specified range of pages from the source
document into the output document.
:param bool import_bookmarks: You may prevent the source document's bookmarks
from being imported by specifying this as ``False``.
:param bool import_bookmarks: You may prevent the source document's
bookmarks from being imported by specifying this as ``False``.
"""
self.merge(len(self.pages), fileobj, bookmark, pages, import_bookmarks)

Expand All @@ -231,7 +239,8 @@ def write(self, fileobj):
my_file = True

# Add pages to the PdfFileWriter
# The commented out line below was replaced with the two lines below it to allow PdfFileMerger to work with PyPdf 1.13
# The commented out line below was replaced with the two lines below it
# to allow PdfFileMerger to work with PyPdf 1.13
for page in self.pages:
self.output.addPage(page.pagedata)
page.out_pagedata = self.output.getReference(
Expand Down Expand Up @@ -390,11 +399,10 @@ def _write_bookmarks(self, bookmarks=None, parent=None):
continue

page_no = None
pdf = None
if "/Page" in bookmark:
for page_no, page in enumerate(self.pages):
for page_no, page in enumerate(self.pages): # noqa: B007
if page.id == bookmark["/Page"]:
pdf = self._write_bookmark_on_page(bookmark, page)
self._write_bookmark_on_page(bookmark, page)
break
if page_no is not None:
del bookmark["/Page"], bookmark["/Type"]
Expand Down Expand Up @@ -461,9 +469,6 @@ def _write_bookmark_on_page(self, bookmark, page):
{NameObject("/S"): NameObject("/GoTo"), NameObject("/D"): ArrayObject(args)}
)

pdf = page.src # noqa: F841
return pdf

def _associate_dests_to_pages(self, pages):
for nd in self.named_dests:
pageno = None
Expand Down
12 changes: 7 additions & 5 deletions Tests/test_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@
)


@pytest.mark.parametrize("predictor, s", list(cartesian_product([1], filter_inputs)))
@pytest.mark.parametrize(
("predictor", "s"), list(cartesian_product([1], filter_inputs))
)
def test_FlateDecode(predictor, s):
"""
Tests FlateDecode decode() and encode() methods.
Expand All @@ -46,7 +48,7 @@ def test_FlateDecode_unsupported_predictor():


@pytest.mark.parametrize(
"input,expected",
("input", "expected"),
[
(">", ""),
(
Expand Down Expand Up @@ -80,7 +82,7 @@ def test_FlateDecode_unsupported_predictor():
"whitespace",
],
)
@pytest.mark.no_py27
@pytest.mark.no_py27()
def test_ASCIIHexDecode(input, expected):
"""
Feeds a bunch of values to ASCIIHexDecode.decode() and ensures the
Expand All @@ -100,7 +102,7 @@ def test_ASCIIHexDecode_no_eod():
assert exc.value.args[0] == "Unexpected EOD in ASCIIHexDecode"


@pytest.mark.xfail
@pytest.mark.xfail()
def test_ASCII85Decode_with_overflow():
inputs = (
v + "~>"
Expand All @@ -119,7 +121,7 @@ def test_ASCII85Decode_with_overflow():
assert exc.value.args[0] == ""


@pytest.mark.no_py27
@pytest.mark.no_py27()
def test_ASCII85Decode_five_zero_bytes():
"""
From ISO 32000 (2008) §7.4.3:
Expand Down
6 changes: 3 additions & 3 deletions Tests/test_generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def test_createStringObject_exception():


@pytest.mark.parametrize(
"value, expected, tell", [(b"true", b"true", 4), (b"false", b"false", 5)]
("value", "expected", "tell"), [(b"true", b"true", 4), (b"false", b"false", 5)]
)
def test_boolean_object(value, expected, tell):
stream = BytesIO(value)
Expand Down Expand Up @@ -179,7 +179,7 @@ def test_bookmark_write_to_stream():
assert stream.read() == b"<<\n/Title title\n/Dest [ /FitV 0 ]\n>>"


@pytest.mark.no_py27
@pytest.mark.no_py27()
def test_encode_pdfdocencoding_keyerror():
with pytest.raises(UnicodeEncodeError) as exc:
encode_pdfdocencoding("😀")
Expand All @@ -201,7 +201,7 @@ def test_readObject_comment():
assert out == 1


@pytest.mark.no_py27
@pytest.mark.no_py27()
def test_ByteStringObject():
bo = ByteStringObject("stream", encoding="utf-8")
stream = BytesIO(b"")
Expand Down
2 changes: 1 addition & 1 deletion Tests/test_javascript.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
RESOURCE_ROOT = os.path.join(PROJECT_ROOT, "Resources")


@pytest.fixture
@pytest.fixture()
def pdf_file_writer():
reader = PdfFileReader(os.path.join(RESOURCE_ROOT, "crazyones.pdf"))
writer = PdfFileWriter()
Expand Down
6 changes: 3 additions & 3 deletions Tests/test_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def get_all_sample_files():
all_files_meta = get_all_sample_files()


@pytest.mark.external
@pytest.mark.external()
@pytest.mark.parametrize(
"meta",
[m for m in all_files_meta["data"] if not m["encrypted"]],
Expand All @@ -36,7 +36,7 @@ def test_read(meta):


@pytest.mark.parametrize(
"pdf_path, password",
("pdf_path", "password"),
[
("crazyones.pdf", None),
("attachment.pdf", None),
Expand Down Expand Up @@ -76,7 +76,7 @@ def test_page_operations(pdf_path, password):


@pytest.mark.parametrize(
"pdf_path, password",
("pdf_path", "password"),
[
(os.path.join(RESOURCE_ROOT, "crazyones.pdf"), None),
(os.path.join(RESOURCE_ROOT, "attachment.pdf"), None),
Expand Down
8 changes: 4 additions & 4 deletions Tests/test_pagerange.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@ def test_equality():


@pytest.mark.parametrize(
"page_range,expected",
("page_range", "expected"),
[(slice(0, 5), "0:5"), (slice(0, 5, 2), "0:5:2"), ("-1", "-1:"), ("0", "0")],
)
def test_str(page_range, expected):
assert str(PageRange(page_range)) == expected


@pytest.mark.parametrize(
"page_range,expected",
("page_range", "expected"),
[(slice(0, 5), "PageRange('0:5')"), (slice(0, 5, 2), "PageRange('0:5:2')")],
)
def test_repr(page_range, expected):
Expand All @@ -38,7 +38,7 @@ def test_idempotency():


@pytest.mark.parametrize(
"range_str,expected",
("range_str", "expected"),
[
("42", slice(42, 43)),
("1:2", slice(1, 2)),
Expand All @@ -59,7 +59,7 @@ def test_str_init_error():


@pytest.mark.parametrize(
"params,expected",
("params", "expected"),
[
(["foo.pdf", "1:5"], [("foo.pdf", PageRange("1:5"))]),
(
Expand Down
3 changes: 2 additions & 1 deletion Tests/test_papersizes.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ def test_din_a_ratio(dimensions):


@pytest.mark.parametrize(
"dimensions_a, dimensions_b", list(zip(papersizes._din_a, papersizes._din_a[1:]))
("dimensions_a", "dimensions_b"),
list(zip(papersizes._din_a, papersizes._din_a[1:])),
)
def test_din_a_doubling(dimensions_a, dimensions_b):
assert abs(dimensions_a.height - 2 * dimensions_b.width) <= 4
23 changes: 12 additions & 11 deletions Tests/test_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@


@pytest.mark.parametrize(
"src,num_pages", [("selenium-PyPDF2-issue-177.pdf", 1), ("pdflatex-outline.pdf", 4)]
("src", "num_pages"),
[("selenium-PyPDF2-issue-177.pdf", 1), ("pdflatex-outline.pdf", 4)],
)
def test_get_num_pages(src, num_pages):
src = os.path.join(RESOURCE_ROOT, src)
Expand All @@ -36,7 +37,7 @@ def test_get_num_pages(src, num_pages):


@pytest.mark.parametrize(
"pdf_path, expected",
("pdf_path", "expected"),
[
(
os.path.join(RESOURCE_ROOT, "crazyones.pdf"),
Expand Down Expand Up @@ -129,7 +130,7 @@ def test_get_attachments(src):


@pytest.mark.parametrize(
"src,outline_elements",
("src", "outline_elements"),
[
(os.path.join(RESOURCE_ROOT, "pdflatex-outline.pdf"), 9),
(os.path.join(RESOURCE_ROOT, "crazyones.pdf"), 0),
Expand All @@ -142,7 +143,7 @@ def test_get_outlines(src, outline_elements):


@pytest.mark.parametrize(
"src,nb_images",
("src", "nb_images"),
[
("pdflatex-outline.pdf", 0),
("crazyones.pdf", 0),
Expand Down Expand Up @@ -184,7 +185,7 @@ def test_get_images(src, nb_images):


@pytest.mark.parametrize(
"strict,with_prev_0,startx_correction,should_fail",
("strict", "with_prev_0", "startx_correction", "should_fail"),
[
(True, False, -1, False), # all nominal => no fail
(True, True, -1, True), # Prev=0 => fail expected
Expand Down Expand Up @@ -248,8 +249,8 @@ def test_get_images_raw(strict, with_prev_0, startx_correction, should_fail):

def test_issue297():
path = os.path.join(RESOURCE_ROOT, "issue-297.pdf")
reader = PdfFileReader(path, strict=True)
with pytest.raises(PdfReadError) as exc:
reader = PdfFileReader(path, strict=True)
reader.getPage(0)
assert "Broken xref table" in exc.value.args[0]
reader = PdfFileReader(path, strict=False)
Expand All @@ -273,7 +274,7 @@ def test_get_page_of_encrypted_file():


@pytest.mark.parametrize(
"src,expected,expected_get_fields",
("src", "expected", "expected_get_fields"),
[
(
"form.pdf",
Expand Down Expand Up @@ -324,7 +325,7 @@ def test_get_form(src, expected, expected_get_fields):


@pytest.mark.parametrize(
"src,page_nb",
("src", "page_nb"),
[
("form.pdf", 0),
("pdflatex-outline.pdf", 2),
Expand All @@ -338,7 +339,7 @@ def test_get_page_number(src, page_nb):


@pytest.mark.parametrize(
"src,expected",
("src", "expected"),
[
("form.pdf", None),
],
Expand All @@ -350,7 +351,7 @@ def test_get_page_layout(src, expected):


@pytest.mark.parametrize(
"src,expected",
("src", "expected"),
[
("form.pdf", "/UseNone"),
("crazyones.pdf", None),
Expand Down Expand Up @@ -483,8 +484,8 @@ def test_read_unknown_zero_pages():
pdf_data.find(b"xref") - 1,
)
pdf_stream = io.BytesIO(pdf_data)
reader = PdfFileReader(pdf_stream, strict=True)
with pytest.raises(PdfReadError) as exc:
reader = PdfFileReader(pdf_stream, strict=True)
reader.numPages

assert exc.value.args[0] == "Could not find object."
Expand Down
Loading

0 comments on commit 16699cc

Please sign in to comment.