-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathtest_xmp.py
274 lines (232 loc) · 8.22 KB
/
test_xmp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
"""Test the pypdf.xmp module."""
from datetime import datetime
from io import BytesIO
from pathlib import Path
import pytest
import pypdf.generic
import pypdf.xmp
from pypdf import PdfReader, PdfWriter
from pypdf.errors import PdfReadError
from . import get_data_from_url
TESTS_ROOT = Path(__file__).parent.resolve()
PROJECT_ROOT = TESTS_ROOT.parent
RESOURCE_ROOT = PROJECT_ROOT / "resources"
SAMPLE_ROOT = Path(PROJECT_ROOT) / "sample-files"
@pytest.mark.samples
@pytest.mark.parametrize(
"src",
[
(SAMPLE_ROOT / "020-xmp/output_with_metadata_pymupdf.pdf"),
],
)
def test_read_xmp_metadata_samples(src):
reader = PdfReader(src)
xmp = reader.xmp_metadata
assert xmp
assert xmp.dc_contributor == []
assert xmp.dc_creator == ["John Doe"]
assert xmp.dc_source == "Martin Thoma" # attribute node
assert xmp.dc_description == {"x-default": "This is a text"}
assert xmp.dc_date == [datetime(1990, 4, 28, 0, 0)]
assert xmp.dc_title == {"x-default": "Sample PDF with XMP Metadata"}
assert xmp.custom_properties == {
"Style": "FooBarStyle",
"other": "worlds",
"⏰": "time",
}
@pytest.mark.samples
def test_writer_xmp_metadata_samples():
writer = PdfWriter(SAMPLE_ROOT / "020-xmp/output_with_metadata_pymupdf.pdf")
xmp = writer.xmp_metadata
assert xmp
assert xmp.dc_contributor == []
assert xmp.dc_creator == ["John Doe"]
assert xmp.dc_source == "Martin Thoma" # attribute node
assert xmp.dc_description == {"x-default": "This is a text"}
assert xmp.dc_date == [datetime(1990, 4, 28, 0, 0)]
assert xmp.dc_title == {"x-default": "Sample PDF with XMP Metadata"}
assert xmp.custom_properties == {
"Style": "FooBarStyle",
"other": "worlds",
"⏰": "time",
}
co = pypdf.generic.ContentStream(None, None)
co.set_data(
xmp.stream.get_data().replace(
b'dc:source="Martin Thoma"', b'dc:source="Pubpub-Zz"'
)
)
writer.xmp_metadata = pypdf.xmp.XmpInformation(co)
b = BytesIO()
writer.write(b)
reader = PdfReader(b)
xmp2 = reader.xmp_metadata
assert xmp2.dc_source == "Pubpub-Zz"
@pytest.mark.parametrize(
("src", "has_xmp"),
[
(RESOURCE_ROOT / "commented-xmp.pdf", True),
(RESOURCE_ROOT / "crazyones.pdf", False),
],
)
def test_read_xmp_metadata(src, has_xmp):
"""Read XMP metadata from PDF files."""
reader = PdfReader(src)
xmp = reader.xmp_metadata
assert (xmp is None) == (not has_xmp)
if has_xmp:
for _ in xmp.get_element(
about_uri="", namespace=pypdf.xmp.RDF_NAMESPACE, name="Artist"
):
pass
assert get_all_tiff(xmp) == {"tiff:Artist": ["me"]}
assert xmp.dc_contributor == []
def get_all_tiff(xmp: pypdf.xmp.XmpInformation):
"""Return all TIFF metadata as a dictionary."""
data = {}
tiff_ns = xmp.get_nodes_in_namespace(
about_uri="", namespace="http://ns.adobe.com/tiff/1.0/"
)
for tag in tiff_ns:
contents = [content.data for content in tag.childNodes]
data[tag.tagName] = contents
return data
def test_converter_date():
"""
_converter_date returns the correct datetime.
This is a regression test for issue #774.
"""
date = pypdf.xmp._converter_date("2021-04-28T12:23:34.123Z")
assert date == datetime(2021, 4, 28, 12, 23, 34, 123000)
with pytest.raises(ValueError) as exc:
pypdf.xmp._converter_date("today")
assert exc.value.args[0].startswith("Invalid date format")
date = pypdf.xmp._converter_date("2021-04-28T12:23:01-03:00")
assert date == datetime(2021, 4, 28, 15, 23, 1)
def test_modify_date():
"""
xmp_modify_date is extracted correctly.
This is a regression test for issue #914.
"""
path = RESOURCE_ROOT / "issue-914-xmp-data.pdf"
reader = PdfReader(path)
assert reader.xmp_metadata.xmp_modify_date == datetime(2022, 4, 9, 15, 22, 43)
@pytest.mark.parametrize(
"x",
["a", 42, 3.141, False, True],
)
def test_identity_function(x):
"""The identity is returning its input."""
assert pypdf.xmp._identity(x) == x
@pytest.mark.enable_socket
@pytest.mark.parametrize(
("url", "name", "xmpmm_instance_id"),
[
(
None,
"tika-955562.pdf",
"uuid:ca96e032-c2af-49bd-a71c-95889bafbf1d",
)
],
)
def test_xmpmm_instance_id(url, name, xmpmm_instance_id):
"""XMPMM instance id is correctly extracted."""
reader = PdfReader(BytesIO(get_data_from_url(url, name=name)))
xmp_metadata = reader.xmp_metadata
assert xmp_metadata.xmpmm_instance_id == xmpmm_instance_id
# cache hit:
assert xmp_metadata.xmpmm_instance_id == xmpmm_instance_id
@pytest.mark.enable_socket
def test_xmp_dc_description_extraction():
"""XMP dc_description is correctly extracted."""
url = "https://github.com/user-attachments/files/18381721/tika-953770.pdf"
name = "tika-953770.pdf"
reader = PdfReader(BytesIO(get_data_from_url(url, name=name)))
xmp_metadata = reader.xmp_metadata
assert xmp_metadata.dc_description == {
"x-default": "U.S. Title 50 Certification Form"
}
# cache hit:
assert xmp_metadata.dc_description == {
"x-default": "U.S. Title 50 Certification Form"
}
@pytest.mark.enable_socket
def test_dc_creator_extraction():
"""XMP dc_creator is correctly extracted."""
url = "https://github.com/user-attachments/files/18381721/tika-953770.pdf"
name = "tika-953770.pdf"
reader = PdfReader(BytesIO(get_data_from_url(url, name=name)))
xmp_metadata = reader.xmp_metadata
assert xmp_metadata.dc_creator == ["U.S. Fish and Wildlife Service"]
# cache hit:
assert xmp_metadata.dc_creator == ["U.S. Fish and Wildlife Service"]
@pytest.mark.enable_socket
def test_custom_properties_extraction():
"""XMP custom_properties is correctly extracted."""
url = "https://github.com/user-attachments/files/18381764/tika-986065.pdf"
name = "tika-986065.pdf"
reader = PdfReader(BytesIO(get_data_from_url(url, name=name)))
xmp_metadata = reader.xmp_metadata
assert xmp_metadata.custom_properties == {"Style": "Searchable Image (Exact)"}
# cache hit:
assert xmp_metadata.custom_properties == {"Style": "Searchable Image (Exact)"}
@pytest.mark.enable_socket
def test_dc_subject_extraction():
"""XMP dc_subject is correctly extracted."""
url = "https://github.com/user-attachments/files/18381730/tika-959519.pdf"
name = "tika-959519.pdf"
reader = PdfReader(BytesIO(get_data_from_url(url, name=name)))
xmp_metadata = reader.xmp_metadata
assert xmp_metadata.dc_subject == [
"P&P",
"manual",
"1240.2325",
"CVM",
"PROCEDURES ON MEDIA INQUIRIES",
"animal",
"media",
"procedures",
"inquiries",
]
# Cache hit:
assert xmp_metadata.dc_subject == [
"P&P",
"manual",
"1240.2325",
"CVM",
"PROCEDURES ON MEDIA INQUIRIES",
"animal",
"media",
"procedures",
"inquiries",
]
@pytest.mark.enable_socket
def test_invalid_xmp_information_handling():
"""
Invalid XML in xmp_metadata is gracefully handled.
This is a regression test for issue #585.
"""
url = "https://github.com/py-pdf/pypdf/files/5536984/test.pdf"
name = "pypdf-5536984.pdf"
reader = PdfReader(BytesIO(get_data_from_url(url, name=name)))
with pytest.raises(PdfReadError) as exc:
reader.xmp_metadata
assert exc.value.args[0].startswith("XML in XmpInformation was invalid")
def test_xmp_getter_bag_function():
"""xmp._getter_bag does not crash."""
f = pypdf.xmp._getter_bag("namespace", "name")
class Tst: # to replace pdf
strict = False
reader = PdfReader(RESOURCE_ROOT / "commented-xmp.pdf")
xmp_info = reader.xmp_metadata
# <?xpacket begin='' id='W5M0MpCehiHzreSzNTczkc9d'?>
# <x:xmpmeta xmlns:x='adobe:ns:meta/' x:xmptk='Image::ExifTool 11.88'>
# <rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>
# <rdf:Description rdf:about=''
# xmlns:tiff='http://ns.adobe.com/tiff/1.0/'>
# <tiff:Artist>me</tiff:Artist>
# </rdf:Description>
# </rdf:RDF>
# </x:xmpmeta>
assert xmp_info is not None
f(xmp_info)