From 3094b4ec9977486d9b3647e71e39ab15dad9ad51 Mon Sep 17 00:00:00 2001 From: Martin Thoma Date: Sun, 22 May 2022 07:55:29 +0200 Subject: [PATCH] Add test --- PyPDF2/generic.py | 8 ++++++++ tests/test_page.py | 45 ++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/PyPDF2/generic.py b/PyPDF2/generic.py index 60c842862..98359c87f 100644 --- a/PyPDF2/generic.py +++ b/PyPDF2/generic.py @@ -100,6 +100,14 @@ class BooleanObject(PdfObject): def __init__(self, value: Any) -> None: self.value = value + def __eq__(self, __o: object) -> bool: + if isinstance(__o, BooleanObject): + return self.value == __o.value + elif isinstance(__o, bool): + return self.value == __o + else: + return False + def writeToStream( self, stream: StreamType, encryption_key: Union[None, str, bytes] ) -> None: diff --git a/tests/test_page.py b/tests/test_page.py index a9b4f3c82..1f93bbf0a 100644 --- a/tests/test_page.py +++ b/tests/test_page.py @@ -1,11 +1,13 @@ import json import os +from copy import deepcopy import pytest from PyPDF2 import PdfFileReader, Transformation from PyPDF2._page import PageObject -from PyPDF2.generic import RectangleObject +from PyPDF2.constants import PageAttributes as PG +from PyPDF2.generic import DictionaryObject, NameObject, RectangleObject TESTS_ROOT = os.path.abspath(os.path.dirname(__file__)) PROJECT_ROOT = os.path.dirname(TESTS_ROOT) @@ -74,6 +76,47 @@ def test_page_operations(pdf_path, password): page.extractText() +def test_transformation_equivalence(): + pdf_path = os.path.join(RESOURCE_ROOT, "labeled-edges-center-image.pdf") + reader_base = PdfFileReader(pdf_path) + page_base = reader_base.pages[0] + + pdf_path = os.path.join(RESOURCE_ROOT, "box.pdf") + reader_add = PdfFileReader(pdf_path) + page_box = reader_add.pages[0] + + op = Transformation().scale(2).rotate(45) + + # Option 1: The new way + page_box1 = deepcopy(page_box) + page_base1 = deepcopy(page_base) + page_box1.add_transformation(op, expand=True) + page_base1.mergePage(page_box1, expand=False) + + # Option 2: The old way + page_box2 = deepcopy(page_box) + page_base2 = deepcopy(page_base) + page_base2.mergeTransformedPage(page_box2, op, expand=False) + + # Should be the smae + assert page_base1[NameObject(PG.CONTENTS)] == page_base2[NameObject(PG.CONTENTS)] + assert page_base1.mediaBox == page_base2.mediaBox + assert page_base1.trimBox == page_base2.trimBox + assert page_base1[NameObject(PG.ANNOTS)] == page_base2[NameObject(PG.ANNOTS)] + compare_dict_objects( + page_base1[NameObject(PG.RESOURCES)], page_base2[NameObject(PG.RESOURCES)] + ) + + +def compare_dict_objects(d1, d2): + assert sorted(d1.keys()) == sorted(d2.keys()) + for k in d1.keys(): + if isinstance(d1[k], DictionaryObject): + compare_dict_objects(d1[k], d2[k]) + else: + assert d1[k] == d2[k] + + def test_page_transformations(): pdf_path = os.path.join(RESOURCE_ROOT, "crazyones.pdf") reader = PdfFileReader(pdf_path)