Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TST: Reader and page attributes #835

Merged
merged 2 commits into from
Apr 28, 2022
Merged
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
12 changes: 7 additions & 5 deletions PyPDF2/pdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -1422,11 +1422,13 @@ def getPage(self, pageNumber):
self._flatten()
return self.flattenedPages[pageNumber]

namedDestinations = property(lambda self: self.getNamedDestinations(), None, None)
"""
Read-only property that accesses the
:meth:`getNamedDestinations()<PdfFileReader.getNamedDestinations>` function.
"""
@property
def namedDestinations(self):
"""
Read-only property that accesses the
:meth:`getNamedDestinations()<PdfFileReader.getNamedDestinations>` function.
"""
return self.getNamedDestinations()

# A select group of relevant field attributes. For the complete list,
# see section 8.6.2 of the PDF 1.7 reference.
Expand Down
2 changes: 1 addition & 1 deletion Scripts/2-up.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def main():
print("2-up input " + sys.argv[1])
reader = PdfFileReader(sys.argv[1])
writer = PdfFileWriter()
for iter in range(0, reader.getNumPages() - 1, 2):
for iter in range(0, reader.numPages - 1, 2):
lhs = reader.getPage(iter)
rhs = reader.getPage(iter + 1)
lhs.mergeTranslatedPage(rhs, lhs.mediaBox.getUpperRight_x(), 0, True)
Expand Down
2 changes: 1 addition & 1 deletion Scripts/booklet.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def main():
args = parser.parse_args()

reader = PyPDF2.PdfFileReader(args.input)
numPages = reader.getNumPages()
numPages = reader.numPages
print("Pages in file:", numPages)

pagesPerSheet = 4
Expand Down
2 changes: 1 addition & 1 deletion Tests/test_basic_features.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def test_basic_features():
reader = PdfFileReader(pdf_path)
writer = PdfFileWriter()

reader.getNumPages()
assert reader.numPages == 1

# add page 1 from input1 to output document, unchanged
writer.addPage(reader.getPage(0))
Expand Down
19 changes: 19 additions & 0 deletions Tests/test_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import pytest

from PyPDF2 import PdfFileReader
from PyPDF2.generic import RectangleObject

TESTS_ROOT = os.path.abspath(os.path.dirname(__file__))
PROJECT_ROOT = os.path.dirname(TESTS_ROOT)
Expand Down Expand Up @@ -92,3 +93,21 @@ def test_compress_content_streams(pdf_path, password):
reader.decrypt(password)
for page in reader.pages:
page.compressContentStreams()


def test_page_properties():
reader = PdfFileReader(os.path.join(RESOURCE_ROOT, "crazyones.pdf"))
page = reader.pages[0]
assert page.mediaBox == RectangleObject([0, 0, 612, 792])
assert page.cropBox == RectangleObject([0, 0, 612, 792])
assert page.bleedBox == RectangleObject([0, 0, 612, 792])
assert page.trimBox == RectangleObject([0, 0, 612, 792])
assert page.artBox == RectangleObject([0, 0, 612, 792])


def test_page_rotation_non90():
reader = PdfFileReader(os.path.join(RESOURCE_ROOT, "crazyones.pdf"))
page = reader.pages[0]
with pytest.raises(ValueError) as exc:
page.rotateClockwise(91)
assert exc.value.args[0] == "Rotation angle must be a multiple of 90"
5 changes: 4 additions & 1 deletion Tests/test_pagerange.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,11 @@ def test_parse_filename_page_ranges(params, expected):


def test_parse_filename_page_ranges_err():
with pytest.raises(ValueError):
with pytest.raises(ValueError) as exc:
parse_filename_page_ranges(["1:5", "foo.pdf"])
assert (
exc.value.args[0] == "The first argument must be a filename, not a page range."
)


def test_page_range_help():
Expand Down
43 changes: 37 additions & 6 deletions Tests/test_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
def test_get_num_pages(src, num_pages):
src = os.path.join(RESOURCE_ROOT, src)
reader = PdfFileReader(src)
assert reader.getNumPages() == num_pages
assert reader.numPages == num_pages


@pytest.mark.parametrize(
Expand Down Expand Up @@ -71,7 +71,7 @@ def test_get_num_pages(src, num_pages):
def test_read_metadata(pdf_path, expected):
with open(pdf_path, "rb") as inputfile:
reader = PdfFileReader(inputfile)
docinfo = reader.getDocumentInfo()
docinfo = reader.documentInfo
metadict = dict(docinfo)
assert metadict == expected
docinfo.title
Expand Down Expand Up @@ -117,7 +117,7 @@ def test_get_attachments(src):
reader = PdfFileReader(src)

attachments = {}
for i in range(reader.getNumPages()):
for i in range(reader.numPages):
page = reader.getPage(i)
if PG.ANNOTS in page:
for annotation in page[PG.ANNOTS]:
Expand Down Expand Up @@ -485,20 +485,20 @@ def test_read_unknown_zero_pages():
pdf_stream = io.BytesIO(pdf_data)
with pytest.raises(PdfReadError) as exc:
reader = PdfFileReader(pdf_stream, strict=True)
reader.getNumPages()
reader.numPages

assert exc.value.args[0] == "Could not find object."
reader = PdfFileReader(pdf_stream, strict=False)
with pytest.raises(AttributeError) as exc:
reader.getNumPages()
reader.numPages
assert exc.value.args[0] == "'NoneType' object has no attribute 'getObject'"


def test_read_encrypted_without_decryption():
src = os.path.join(RESOURCE_ROOT, "libreoffice-writer-password.pdf")
reader = PdfFileReader(src)
with pytest.raises(PdfReadError) as exc:
reader.getNumPages()
reader.numPages
assert exc.value.args[0] == "File has not been decrypted"


Expand Down Expand Up @@ -537,3 +537,34 @@ def test_PdfReaderDecryptWhenNoID():
ipdf = PdfFileReader(inputfile)
ipdf.decrypt("")
assert ipdf.getDocumentInfo() == {"/Producer": "European Patent Office"}


def test_reader_properties():
reader = PdfFileReader(os.path.join(RESOURCE_ROOT, "crazyones.pdf"))
assert reader.outlines == []
assert len(reader.pages) == 1
assert reader.pageLayout is None
assert reader.pageMode is None
assert reader.isEncrypted is False


def test_decode_permissions():
reader = PdfFileReader(os.path.join(RESOURCE_ROOT, "crazyones.pdf"))
base = {
"accessability": False,
"annotations": False,
"assemble": False,
"copy": False,
"forms": False,
"modify": False,
"print_high_quality": False,
"print": False,
}

print_ = base.copy()
print_["print"] = True
assert reader.decode_permissions(4) == print_

modify = base.copy()
modify["modify"] = True
assert reader.decode_permissions(8) == modify
2 changes: 1 addition & 1 deletion Tests/test_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -343,7 +343,7 @@ def test_io_streams():

# Read from bytes stream
reader = PdfFileReader(bytes_stream)
assert reader.getNumPages() == 4
assert reader.numPages == 4

# Write to bytes stream
writer = PdfFileWriter()
Expand Down
8 changes: 7 additions & 1 deletion Tests/test_xmp.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
)
def test_read_xmp(src, has_xmp):
reader = PdfFileReader(src)
xmp = reader.getXmpMetadata()
xmp = reader.xmpMetadata
assert (xmp is None) == (not has_xmp)
if has_xmp:
for el in xmp.getElement(
Expand Down Expand Up @@ -48,3 +48,9 @@ def test_regression_issue774():
cls = PyPDF2.xmp.XmpInformation
date = cls._converter_date("2021-04-28T12:23:34.123Z")
assert date.year == 2021
assert date.month == 4
assert date.day == 28
assert date.hour == 12
assert date.minute == 23
assert date.second == 34
assert date.microsecond == 123000