-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathtest_unit_tests.py
More file actions
6717 lines (5679 loc) · 266 KB
/
test_unit_tests.py
File metadata and controls
6717 lines (5679 loc) · 266 KB
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2023 Adobe. All rights reserved.
# This file is licensed to you under the Apache License,
# Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
# or the MIT license (http://opensource.org/licenses/MIT),
# at your option.
# Unless required by applicable law or agreed to in writing,
# this software is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
# implied. See the LICENSE-MIT and LICENSE-APACHE files for the
# specific language governing permissions and limitations under
# each license.
import os
import io
import json
import unittest
import ctypes
import warnings
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.backends import default_backend
import tempfile
import shutil
import ctypes
import toml
import threading
# Suppress deprecation warnings
warnings.simplefilter("ignore", category=DeprecationWarning)
from c2pa import Builder, C2paError as Error, Reader, C2paSigningAlg as SigningAlg, C2paSignerInfo, Signer, sdk_version, C2paBuilderIntent, C2paDigitalSourceType
from c2pa import Settings, Context, ContextBuilder, ContextProvider
from c2pa.c2pa import Stream, LifecycleState, read_ingredient_file, read_file, sign_file, load_settings, create_signer, create_signer_from_info, ed25519_sign, format_embeddable
PROJECT_PATH = os.getcwd()
FIXTURES_DIR = os.path.join(os.path.dirname(__file__), "fixtures")
DEFAULT_TEST_FILE_NAME = "C.jpg"
INGREDIENT_TEST_FILE_NAME = "A.jpg"
DEFAULT_TEST_FILE = os.path.join(FIXTURES_DIR, DEFAULT_TEST_FILE_NAME)
INGREDIENT_TEST_FILE = os.path.join(FIXTURES_DIR, INGREDIENT_TEST_FILE_NAME)
ALTERNATIVE_INGREDIENT_TEST_FILE = os.path.join(FIXTURES_DIR, "cloud.jpg")
def load_test_settings_json():
"""
Load default (legacy) trust configuration test settings from a
JSON config file and return its content as JSON-compatible dict.
The return value is used to load settings (thread_local) in tests.
Returns:
dict: The parsed JSON content as a Python dictionary (JSON-compatible).
Raises:
FileNotFoundError: If trust_config_test_settings.json is not found.
json.JSONDecodeError: If the JSON file is malformed.
"""
# Locate the file which contains default settings for tests
tests_dir = os.path.dirname(os.path.abspath(__file__))
settings_path = os.path.join(tests_dir, 'trust_config_test_settings.json')
# Load the located default test settings
with open(settings_path, 'r') as f:
settings_data = json.load(f)
return settings_data
class TestC2paSdk(unittest.TestCase):
def test_sdk_version(self):
# This test verifies the native libraries used match the expected version.
self.assertIn("0.79.0", sdk_version())
class TestReader(unittest.TestCase):
def setUp(self):
warnings.filterwarnings("ignore", message="load_settings\\(\\) is deprecated")
self.data_dir = FIXTURES_DIR
self.testPath = DEFAULT_TEST_FILE
def test_can_retrieve_reader_supported_mimetypes(self):
result1 = Reader.get_supported_mime_types()
self.assertTrue(len(result1) > 0)
# Cache hit
result2 = Reader.get_supported_mime_types()
self.assertTrue(len(result2) > 0)
self.assertEqual(result1, result2)
def test_stream_read_nothing_to_read(self):
# The ingredient test file has no manifest
# So if we instantiate directly, the Reader instance should throw
with open(INGREDIENT_TEST_FILE, "rb") as file:
with self.assertRaises(Error) as context:
reader = Reader("image/jpeg", file)
self.assertIn("ManifestNotFound: no JUMBF data found", str(context.exception))
def test_try_create_reader_nothing_to_read(self):
# The ingredient test file has no manifest
# So if we use Reader.try_create, in this case we'll get None
# And no error should be raised
with open(INGREDIENT_TEST_FILE, "rb") as file:
reader = Reader.try_create("image/jpeg", file)
self.assertIsNone(reader)
def test_stream_read(self):
with open(self.testPath, "rb") as file:
reader = Reader("image/jpeg", file)
json_data = reader.json()
self.assertIn(DEFAULT_TEST_FILE_NAME, json_data)
def test_try_create_reader_from_stream(self):
with open(self.testPath, "rb") as file:
reader = Reader.try_create("image/jpeg", file)
self.assertIsNotNone(reader)
json_data = reader.json()
self.assertIn(DEFAULT_TEST_FILE_NAME, json_data)
def test_try_create_reader_from_stream_context_manager(self):
with open(self.testPath, "rb") as file:
reader = Reader.try_create("image/jpeg", file)
self.assertIsNotNone(reader)
# Check that a Reader returned by try_create is not None,
# before using it in a context manager pattern (with)
if reader is not None:
with reader:
json_data = reader.json()
self.assertIn(DEFAULT_TEST_FILE_NAME, json_data)
def test_stream_read_detailed(self):
with open(self.testPath, "rb") as file:
reader = Reader("image/jpeg", file)
json_data = reader.detailed_json()
self.assertIn(DEFAULT_TEST_FILE_NAME, json_data)
def test_get_active_manifest(self):
with open(self.testPath, "rb") as file:
reader = Reader("image/jpeg", file)
active_manifest = reader.get_active_manifest()
# Check the returned manifest label/key
expected_label = "contentauth:urn:uuid:c85a2b90-f1a0-4aa4-b17f-f938b475804e"
self.assertEqual(active_manifest["label"], expected_label)
def test_get_manifest(self):
with open(self.testPath, "rb") as file:
reader = Reader("image/jpeg", file)
# Test getting manifest by the specific label
label = "contentauth:urn:uuid:c85a2b90-f1a0-4aa4-b17f-f938b475804e"
manifest = reader.get_manifest(label)
self.assertEqual(manifest["label"], label)
# It should be the active manifest too, so cross-check
active_manifest = reader.get_active_manifest()
self.assertEqual(manifest, active_manifest)
def test_stream_get_non_active_manifest_by_label(self):
video_path = os.path.join(FIXTURES_DIR, "video1.mp4")
with open(video_path, "rb") as file:
reader = Reader("video/mp4", file)
non_active_label = "urn:uuid:54281c07-ad34-430e-bea5-112a18facf0b"
non_active_manifest = reader.get_manifest(non_active_label)
self.assertEqual(non_active_manifest["label"], non_active_label)
# Verify it's not the active manifest
# (that test case has only one other manifest that is not the active manifest)
active_manifest = reader.get_active_manifest()
self.assertNotEqual(non_active_manifest, active_manifest)
self.assertNotEqual(non_active_manifest["label"], active_manifest["label"])
def test_stream_get_non_active_manifest_by_label_not_found(self):
video_path = os.path.join(FIXTURES_DIR, "video1.mp4")
with open(video_path, "rb") as file:
reader = Reader("video/mp4", file)
# Try to get a manifest with a label that clearly doesn't exist...
non_existing_label = "urn:uuid:clearly-not-existing"
with self.assertRaises(KeyError):
reader.get_manifest(non_existing_label)
def test_stream_read_get_validation_state(self):
with open(self.testPath, "rb") as file:
reader = Reader("image/jpeg", file)
validation_state = reader.get_validation_state()
self.assertIsNotNone(validation_state)
self.assertEqual(validation_state, "Valid")
def test_stream_read_get_validation_state_with_trust_config(self):
# Run in a separate thread to isolate thread-local settings
result = {}
exception = {}
def read_with_trust_config():
try:
# Load trust configuration
settings_dict = load_test_settings_json()
# Apply the settings (including trust configuration)
# Settings are thread-local, so they won't affect other tests
# And that is why we also run the test in its own thread, so tests are isolated
load_settings(settings_dict)
with open(self.testPath, "rb") as file:
reader = Reader("image/jpeg", file)
validation_state = reader.get_validation_state()
result['validation_state'] = validation_state
except Exception as e:
exception['error'] = e
# Create and start thread
thread = threading.Thread(target=read_with_trust_config)
thread.start()
thread.join()
# Check for exceptions
if 'error' in exception:
raise exception['error']
# Assertions run in main thread
self.assertIsNotNone(result.get('validation_state'))
# With trust configuration loaded, manifest is Trusted
self.assertEqual(result.get('validation_state'), "Trusted")
def test_stream_read_get_validation_results(self):
with open(self.testPath, "rb") as file:
reader = Reader("image/jpeg", file)
validation_results = reader.get_validation_results()
self.assertIsNotNone(validation_results)
self.assertIsInstance(validation_results, dict)
self.assertIn("activeManifest", validation_results)
active_manifest_results = validation_results["activeManifest"]
self.assertIsInstance(active_manifest_results, dict)
def test_reader_detects_unsupported_mimetype_on_stream(self):
with open(self.testPath, "rb") as file:
with self.assertRaises(Error.NotSupported):
Reader("mimetype/does-not-exist", file)
def test_stream_read_and_parse(self):
with open(self.testPath, "rb") as file:
reader = Reader("image/jpeg", file)
manifest_store = json.loads(reader.json())
title = manifest_store["manifests"][manifest_store["active_manifest"]]["title"]
self.assertEqual(title, DEFAULT_TEST_FILE_NAME)
def test_stream_read_detailed_and_parse(self):
with open(self.testPath, "rb") as file:
reader = Reader("image/jpeg", file)
manifest_store = json.loads(reader.detailed_json())
title = manifest_store["manifests"][manifest_store["active_manifest"]]["claim"]["dc:title"]
self.assertEqual(title, DEFAULT_TEST_FILE_NAME)
def test_stream_read_string_stream_path_only(self):
with Reader(self.testPath) as reader:
json_data = reader.json()
self.assertIn(DEFAULT_TEST_FILE_NAME, json_data)
def test_try_create_from_path(self):
test_path = os.path.join(self.data_dir, "C.dng")
# Create reader with the file content
reader = Reader.try_create(test_path)
self.assertIsNotNone(reader)
# Just run and verify there is no crash
json.loads(reader.json())
def test_stream_read_string_stream_mimetype_not_supported(self):
with self.assertRaises(Error.NotSupported):
# xyz is actually an extension that is recognized
# as mimetype chemical/x-xyz
Reader(os.path.join(FIXTURES_DIR, "C.xyz"))
def test_try_create_raises_mimetype_not_supported(self):
with self.assertRaises(Error.NotSupported):
# xyz is actually an extension that is recognized
# as mimetype chemical/x-xyz, but we don't support it
Reader.try_create(os.path.join(FIXTURES_DIR, "C.xyz"))
def test_stream_read_string_stream_mimetype_not_recognized(self):
with self.assertRaises(Error.NotSupported):
Reader(os.path.join(FIXTURES_DIR, "C.test"))
def test_try_create_raises_mimetype_not_recognized(self):
with self.assertRaises(Error.NotSupported):
Reader.try_create(os.path.join(FIXTURES_DIR, "C.test"))
def test_stream_read_string_stream(self):
with Reader("image/jpeg", self.testPath) as reader:
json_data = reader.json()
self.assertIn(DEFAULT_TEST_FILE_NAME, json_data)
def test_reader_detects_unsupported_mimetype_on_file(self):
with self.assertRaises(Error.NotSupported):
Reader("mimetype/does-not-exist", self.testPath)
def test_stream_read_filepath_as_stream_and_parse(self):
with Reader("image/jpeg", self.testPath) as reader:
manifest_store = json.loads(reader.json())
title = manifest_store["manifests"][manifest_store["active_manifest"]]["title"]
self.assertEqual(title, DEFAULT_TEST_FILE_NAME)
def test_reader_double_close(self):
with open(self.testPath, "rb") as file:
reader = Reader("image/jpeg", file)
reader.close()
# Second close should not raise an exception
reader.close()
# Verify reader is closed
with self.assertRaises(Error):
reader.json()
def test_reader_streams_with_nested(self):
with open(self.testPath, "rb") as file:
with Reader("image/jpeg", file) as reader:
manifest_store = json.loads(reader.json())
title = manifest_store["manifests"][manifest_store["active_manifest"]]["title"]
self.assertEqual(title, DEFAULT_TEST_FILE_NAME)
def test_reader_close_cleanup(self):
with open(self.testPath, "rb") as file:
reader = Reader("image/jpeg", file)
# Close the reader
reader.close()
# Verify all resources are cleaned up
self.assertIsNone(reader._handle)
self.assertIsNone(reader._own_stream)
# Verify reader is marked as closed
self.assertEqual(reader._lifecycle_state, LifecycleState.CLOSED)
def test_resource_to_stream_on_closed_reader(self):
"""Test that resource_to_stream correctly raises error on closed."""
reader = Reader("image/jpeg", self.testPath)
reader.close()
with self.assertRaises(Error):
reader.resource_to_stream("", io.BytesIO(bytearray()))
def test_read_dng_from_stream(self):
test_path = os.path.join(self.data_dir, "C.dng")
with open(test_path, "rb") as file:
file_content = file.read()
with Reader("dng", io.BytesIO(file_content)) as reader:
# Just run and verify there is no crash
json.loads(reader.json())
def test_read_dng_upper_case_from_stream(self):
test_path = os.path.join(self.data_dir, "C.dng")
with open(test_path, "rb") as file:
file_content = file.read()
with Reader("DNG", io.BytesIO(file_content)) as reader:
# Just run and verify there is no crash
json.loads(reader.json())
def test_read_dng_file_from_path(self):
test_path = os.path.join(self.data_dir, "C.dng")
# Create reader with the file content
with Reader(test_path) as reader:
# Just run and verify there is no crash
json.loads(reader.json())
def test_read_all_files(self):
"""Test reading C2PA metadata from all files in the fixtures/files-for-reading-tests directory"""
reading_dir = os.path.join(self.data_dir, "files-for-reading-tests")
# Map of file extensions to MIME types
mime_types = {
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.png': 'image/png',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.heic': 'image/heic',
'.heif': 'image/heif',
'.avif': 'image/avif',
'.tif': 'image/tiff',
'.tiff': 'image/tiff',
'.mp4': 'video/mp4',
'.avi': 'video/x-msvideo',
'.mp3': 'audio/mpeg',
'.m4a': 'audio/mp4',
'.wav': 'audio/wav',
'.pdf': 'application/pdf',
}
# Skip system files
skip_files = {
'.DS_Store'
}
for filename in os.listdir(reading_dir):
if filename in skip_files:
continue
file_path = os.path.join(reading_dir, filename)
if not os.path.isfile(file_path):
continue
# Get file extension and corresponding MIME type
_, ext = os.path.splitext(filename)
ext = ext.lower()
if ext not in mime_types:
continue
mime_type = mime_types[ext]
try:
with open(file_path, "rb") as file:
reader = Reader(mime_type, file)
json_data = reader.json()
reader.close()
self.assertIsInstance(json_data, str)
# Verify the manifest contains expected fields
manifest = json.loads(json_data)
self.assertIn("manifests", manifest)
self.assertIn("active_manifest", manifest)
except Exception as e:
self.fail(f"Failed to read metadata from {filename}: {str(e)}")
def test_try_create_all_files(self):
"""Test reading C2PA metadata using Reader.try_create from all files in the fixtures/files-for-reading-tests directory"""
reading_dir = os.path.join(self.data_dir, "files-for-reading-tests")
# Map of file extensions to MIME types
mime_types = {
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.png': 'image/png',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.heic': 'image/heic',
'.heif': 'image/heif',
'.avif': 'image/avif',
'.tif': 'image/tiff',
'.tiff': 'image/tiff',
'.mp4': 'video/mp4',
'.avi': 'video/x-msvideo',
'.mp3': 'audio/mpeg',
'.m4a': 'audio/mp4',
'.wav': 'audio/wav',
'.pdf': 'application/pdf',
}
# Skip system files
skip_files = {
'.DS_Store'
}
for filename in os.listdir(reading_dir):
if filename in skip_files:
continue
file_path = os.path.join(reading_dir, filename)
if not os.path.isfile(file_path):
continue
# Get file extension and corresponding MIME type
_, ext = os.path.splitext(filename)
ext = ext.lower()
if ext not in mime_types:
continue
mime_type = mime_types[ext]
try:
with open(file_path, "rb") as file:
reader = Reader.try_create(mime_type, file)
# try_create returns None if no manifest found, otherwise a Reader
self.assertIsNotNone(reader, f"Expected Reader for {filename}")
json_data = reader.json()
reader.close()
self.assertIsInstance(json_data, str)
# Verify the manifest contains expected fields
manifest = json.loads(json_data)
self.assertIn("manifests", manifest)
self.assertIn("active_manifest", manifest)
except Exception as e:
self.fail(f"Failed to read metadata from {filename}: {str(e)}")
def test_try_create_all_files_using_extension(self):
"""
Test reading C2PA metadata using Reader.try_create
from files in the fixtures/files-for-reading-tests directory
"""
reading_dir = os.path.join(self.data_dir, "files-for-reading-tests")
# Map of file extensions to MIME types
extensions = {
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.png': 'image/png',
}
# Skip system files
skip_files = {
'.DS_Store'
}
for filename in os.listdir(reading_dir):
if filename in skip_files:
continue
file_path = os.path.join(reading_dir, filename)
if not os.path.isfile(file_path):
continue
# Get file extension and corresponding MIME type
_, ext = os.path.splitext(filename)
ext = ext.lower()
if ext not in extensions:
continue
try:
with open(file_path, "rb") as file:
# Remove the leading dot
parsed_extension = ext[1:]
reader = Reader.try_create(parsed_extension, file)
# try_create returns None if no manifest found, otherwise a Reader
self.assertIsNotNone(reader, f"Expected Reader for {filename}")
json_data = reader.json()
reader.close()
self.assertIsInstance(json_data, str)
# Verify the manifest contains expected fields
manifest = json.loads(json_data)
self.assertIn("manifests", manifest)
self.assertIn("active_manifest", manifest)
except Exception as e:
self.fail(f"Failed to read metadata from {filename}: {str(e)}")
def test_read_all_files_using_extension(self):
"""Test reading C2PA metadata from files in the fixtures/files-for-reading-tests directory"""
reading_dir = os.path.join(self.data_dir, "files-for-reading-tests")
# Map of file extensions to MIME types
extensions = {
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.png': 'image/png',
}
# Skip system files
skip_files = {
'.DS_Store'
}
for filename in os.listdir(reading_dir):
if filename in skip_files:
continue
file_path = os.path.join(reading_dir, filename)
if not os.path.isfile(file_path):
continue
# Get file extension and corresponding MIME type
_, ext = os.path.splitext(filename)
ext = ext.lower()
if ext not in extensions:
continue
try:
with open(file_path, "rb") as file:
# Remove the leading dot
parsed_extension = ext[1:]
reader = Reader(parsed_extension, file)
json_data = reader.json()
reader.close()
self.assertIsInstance(json_data, str)
# Verify the manifest contains expected fields
manifest = json.loads(json_data)
self.assertIn("manifests", manifest)
self.assertIn("active_manifest", manifest)
except Exception as e:
self.fail(f"Failed to read metadata from {filename}: {str(e)}")
def test_read_cached_all_files(self):
"""Test reading C2PA metadata with cache functionality from all files in the fixtures/files-for-reading-tests directory"""
reading_dir = os.path.join(self.data_dir, "files-for-reading-tests")
# Map of file extensions to MIME types
mime_types = {
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.png': 'image/png',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.heic': 'image/heic',
'.heif': 'image/heif',
'.avif': 'image/avif',
'.tif': 'image/tiff',
'.tiff': 'image/tiff',
'.mp4': 'video/mp4',
'.avi': 'video/x-msvideo',
'.mp3': 'audio/mpeg',
'.m4a': 'audio/mp4',
'.wav': 'audio/wav',
'.pdf': 'application/pdf',
}
# Skip system files
skip_files = {
'.DS_Store'
}
for filename in os.listdir(reading_dir):
if filename in skip_files:
continue
file_path = os.path.join(reading_dir, filename)
if not os.path.isfile(file_path):
continue
# Get file extension and corresponding MIME type
_, ext = os.path.splitext(filename)
ext = ext.lower()
if ext not in mime_types:
continue
mime_type = mime_types[ext]
try:
with open(file_path, "rb") as file:
reader = Reader(mime_type, file)
# Test 1: Verify cache variables are initially None
self.assertIsNone(reader._manifest_json_str_cache, f"JSON cache should be None initially for {filename}")
self.assertIsNone(reader._manifest_data_cache, f"Manifest data cache should be None initially for {filename}")
# Test 2: Multiple calls to json() should return the same result and use cache
json_data_1 = reader.json()
self.assertIsNotNone(reader._manifest_json_str_cache, f"JSON cache not set after first json() call for {filename}")
self.assertEqual(json_data_1, reader._manifest_json_str_cache, f"JSON cache doesn't match return value for {filename}")
json_data_2 = reader.json()
self.assertEqual(json_data_1, json_data_2, f"JSON inconsistency for {filename}")
self.assertIsInstance(json_data_1, str)
# Test 3: Test methods that use the cache
try:
# Test get_active_manifest() which uses _get_cached_manifest_data()
active_manifest = reader.get_active_manifest()
self.assertIsInstance(active_manifest, dict, f"Active manifest not dict for {filename}")
# Test 4: Verify cache is set after calling cache-using methods
self.assertIsNotNone(reader._manifest_json_str_cache, f"JSON cache not set after get_active_manifest for {filename}")
self.assertIsNotNone(reader._manifest_data_cache, f"Manifest data cache not set after get_active_manifest for {filename}")
# Test 5: Multiple calls to cache-using methods should return the same result
active_manifest_2 = reader.get_active_manifest()
self.assertEqual(active_manifest, active_manifest_2, f"Active manifest cache inconsistency for {filename}")
# Test get_validation_state() which uses the cache
validation_state = reader.get_validation_state()
# validation_state can be None, so just check it doesn't crash
# Test get_validation_results() which uses the cache
validation_results = reader.get_validation_results()
# validation_results can be None, so just check it doesn't crash
# Test 6: Multiple calls to validation methods should return the same result
validation_state_2 = reader.get_validation_state()
self.assertEqual(validation_state, validation_state_2, f"Validation state cache inconsistency for {filename}")
validation_results_2 = reader.get_validation_results()
self.assertEqual(validation_results, validation_results_2, f"Validation results cache inconsistency for {filename}")
except KeyError as e:
# Some files might not have active manifests or validation data
# This is expected for some test files, so we'll skip cache testing for those
pass
# Test 7: Verify the manifest contains expected fields
manifest = json.loads(json_data_1)
self.assertIn("manifests", manifest)
self.assertIn("active_manifest", manifest)
# Test 8: Test cache clearing on close
reader.close()
self.assertIsNone(reader._manifest_json_str_cache, f"JSON cache not cleared for {filename}")
self.assertIsNone(reader._manifest_data_cache, f"Manifest data cache not cleared for {filename}")
except Exception as e:
self.fail(f"Failed to read cached metadata from {filename}: {str(e)}")
def test_reader_context_manager_with_exception(self):
"""Test Reader state after exception in context manager."""
try:
with Reader(self.testPath) as reader:
# Inside context - should be valid
self.assertEqual(reader._lifecycle_state, LifecycleState.ACTIVE)
self.assertIsNotNone(reader._handle)
self.assertIsNotNone(reader._own_stream)
self.assertIsNotNone(reader._backing_file)
raise ValueError("Test exception")
except ValueError:
pass
# After exception - should still be closed
self.assertEqual(reader._lifecycle_state, LifecycleState.CLOSED)
self.assertIsNone(reader._handle)
self.assertIsNone(reader._own_stream)
self.assertIsNone(reader._backing_file)
def test_reader_partial_initialization_states(self):
"""Test Reader behavior with partial initialization failures."""
# Test with _reader = None but lifecycle state = ACTIVE
reader = Reader.__new__(Reader)
reader._lifecycle_state = LifecycleState.ACTIVE
reader._handle = None
reader._own_stream = None
reader._backing_file = None
with self.assertRaises(Error):
reader._ensure_valid_state()
def test_reader_cleanup_state_transitions(self):
"""Test Reader state during cleanup operations."""
reader = Reader(self.testPath)
reader._cleanup_resources()
self.assertEqual(reader._lifecycle_state, LifecycleState.CLOSED)
self.assertIsNone(reader._handle)
self.assertIsNone(reader._own_stream)
self.assertIsNone(reader._backing_file)
def test_reader_cleanup_idempotency(self):
"""Test that cleanup operations are idempotent."""
reader = Reader(self.testPath)
# First cleanup
reader._cleanup_resources()
self.assertEqual(reader._lifecycle_state, LifecycleState.CLOSED)
# Second cleanup should not change state
reader._cleanup_resources()
self.assertEqual(reader._lifecycle_state, LifecycleState.CLOSED)
self.assertIsNone(reader._handle)
self.assertIsNone(reader._own_stream)
self.assertIsNone(reader._backing_file)
def test_reader_state_with_invalid_native_pointer(self):
"""Test Reader state handling with invalid native pointer."""
reader = Reader(self.testPath)
# Simulate invalid native pointer
reader._handle = 0
# Operations should fail gracefully
with self.assertRaises(Error):
reader.json()
def test_reader_is_embedded(self):
"""Test the is_embedded method returns correct values for embedded and remote manifests."""
# Test with a fixture which has an embedded manifest
with open(self.testPath, "rb") as file:
reader = Reader("image/jpeg", file)
self.assertTrue(reader.is_embedded())
reader.close()
# Test with cloud.jpg fixture which has a remote manifest (not embedded)
cloud_fixture_path = os.path.join(self.data_dir, "cloud.jpg")
with Reader("image/jpeg", cloud_fixture_path) as reader:
self.assertFalse(reader.is_embedded())
def test_sign_and_read_is_not_embedded(self):
"""Test the is_embedded method returns correct values for remote manifests."""
with open(os.path.join(self.data_dir, "es256_certs.pem"), "rb") as cert_file:
certs = cert_file.read()
with open(os.path.join(self.data_dir, "es256_private.key"), "rb") as key_file:
key = key_file.read()
# Create signer info and signer
signer_info = C2paSignerInfo(
alg=b"es256",
sign_cert=certs,
private_key=key,
ta_url=b"http://timestamp.digicert.com"
)
signer = Signer.from_info(signer_info)
# Define a simple manifest
manifest_definition = {
"claim_generator": "python_test",
"claim_generator_info": [{
"name": "python_test",
"version": "0.0.1",
}],
"format": "image/jpeg",
"title": "Python Test Image",
"ingredients": [],
"assertions": [
{
"label": "c2pa.actions",
"data": {
"actions": [
{
"action": "c2pa.created",
"digitalSourceType": "http://cv.iptc.org/newscodes/digitalsourcetype/digitalCreation"
}
]
}
}
]
}
# Create a temporary directory for the signed file
with tempfile.TemporaryDirectory() as temp_dir:
temp_file_path = os.path.join(temp_dir, "signed_test_file_no_embed.jpg")
with open(self.testPath, "rb") as file:
builder = Builder(manifest_definition)
# Direct the Builder not to embed the manifest into the asset
builder.set_no_embed()
with open(temp_file_path, "wb") as temp_file:
manifest_data = builder.sign(
signer, "image/jpeg", file, temp_file)
with Reader("image/jpeg", temp_file_path, manifest_data) as reader:
self.assertFalse(reader.is_embedded())
def test_reader_get_remote_url(self):
"""Test the get_remote_url method returns correct values for embedded and remote manifests."""
# Test get_remote_url for file with embedded manifest (should return None)
with open(self.testPath, "rb") as file:
reader = Reader("image/jpeg", file)
self.assertIsNone(reader.get_remote_url())
reader.close()
# Test remote manifest using cloud.jpg fixture which has a remote URL
cloud_fixture_path = os.path.join(self.data_dir, "cloud.jpg")
with Reader("image/jpeg", cloud_fixture_path) as reader:
remote_url = reader.get_remote_url()
self.assertEqual(remote_url, "https://cai-manifests.adobe.com/manifests/adobe-urn-uuid-5f37e182-3687-462e-a7fb-573462780391")
self.assertFalse(reader.is_embedded())
def test_stream_read_and_parse_cached(self):
"""Test reading and parsing with cache verification by repeating operations multiple times"""
with open(self.testPath, "rb") as file:
reader = Reader("image/jpeg", file)
# Verify cache starts as None
self.assertIsNone(reader._manifest_json_str_cache, "JSON cache should be None initially")
self.assertIsNone(reader._manifest_data_cache, "Manifest data cache should be None initially")
# First operation - should populate cache
manifest_store_1 = json.loads(reader.json())
title_1 = manifest_store_1["manifests"][manifest_store_1["active_manifest"]]["title"]
self.assertEqual(title_1, DEFAULT_TEST_FILE_NAME)
# Verify cache is populated after first json() call
self.assertIsNotNone(reader._manifest_json_str_cache, "JSON cache should be set after first json() call")
self.assertEqual(manifest_store_1, json.loads(reader._manifest_json_str_cache), "Cached JSON should match parsed result")
# Repeat the same operation multiple times to verify cache usage
for i in range(5):
manifest_store = json.loads(reader.json())
title = manifest_store["manifests"][manifest_store["active_manifest"]]["title"]
self.assertEqual(title, DEFAULT_TEST_FILE_NAME, f"Title should be consistent on iteration {i+1}")
# Verify cache is still populated and consistent
self.assertIsNotNone(reader._manifest_json_str_cache, f"JSON cache should remain set on iteration {i+1}")
self.assertEqual(manifest_store, json.loads(reader._manifest_json_str_cache), f"Cached JSON should match parsed result on iteration {i+1}")
# Test methods that use the cache
# Test get_active_manifest() which uses _get_cached_manifest_data()
active_manifest_1 = reader.get_active_manifest()
self.assertIsInstance(active_manifest_1, dict, "Active manifest should be a dict")
# Verify manifest data cache is populated
self.assertIsNotNone(reader._manifest_data_cache, "Manifest data cache should be set after get_active_manifest()")
# Repeat get_active_manifest() multiple times to verify cache usage
for i in range(3):
active_manifest = reader.get_active_manifest()
self.assertEqual(active_manifest_1, active_manifest, f"Active manifest should be consistent on iteration {i+1}")
# Verify cache remains populated
self.assertIsNotNone(reader._manifest_data_cache, f"Manifest data cache should remain set on iteration {i+1}")
# Test get_validation_state() and get_validation_results() with cache
validation_state_1 = reader.get_validation_state()
validation_results_1 = reader.get_validation_results()
# Repeat validation methods to verify cache usage
for i in range(3):
validation_state = reader.get_validation_state()
validation_results = reader.get_validation_results()
self.assertEqual(validation_state_1, validation_state, f"Validation state should be consistent on iteration {i+1}")
self.assertEqual(validation_results_1, validation_results, f"Validation results should be consistent on iteration {i+1}")
# Verify cache clearing on close
reader.close()
self.assertIsNone(reader._manifest_json_str_cache, "JSON cache should be cleared on close")
self.assertIsNone(reader._manifest_data_cache, "Manifest data cache should be cleared on close")
# TODO: Unskip once fixed configuration to read data is clarified
# def test_read_cawg_data_file(self):
# """Test reading C2PA metadata from C_with_CAWG_data.jpg file."""
# file_path = os.path.join(self.data_dir, "C_with_CAWG_data.jpg")
# with open(file_path, "rb") as file:
# reader = Reader("image/jpeg", file)
# json_data = reader.json()
# self.assertIsInstance(json_data, str)
# # Parse the JSON and verify specific fields
# manifest_data = json.loads(json_data)
# # Verify basic manifest structure
# self.assertIn("manifests", manifest_data)
# self.assertIn("active_manifest", manifest_data)
# # Get the active manifest
# active_manifest_id = manifest_data["active_manifest"]
# active_manifest = manifest_data["manifests"][active_manifest_id]
# # Verify manifest is not null or empty
# assert active_manifest is not None, "Active manifest should not be null"
# assert len(active_manifest) > 0, "Active manifest should not be empty"
class TestBuilderWithSigner(unittest.TestCase):
def setUp(self):
# Use the fixtures_dir fixture to set up paths
self.data_dir = FIXTURES_DIR
self.testPath = DEFAULT_TEST_FILE
self.testPath2 = INGREDIENT_TEST_FILE
with open(os.path.join(self.data_dir, "es256_certs.pem"), "rb") as cert_file:
self.certs = cert_file.read()
with open(os.path.join(self.data_dir, "es256_private.key"), "rb") as key_file:
self.key = key_file.read()
# Create a local Es256 signer with certs and a timestamp server
self.signer_info = C2paSignerInfo(
alg=b"es256",
sign_cert=self.certs,
private_key=self.key,
ta_url=b"http://timestamp.digicert.com"
)
self.signer = Signer.from_info(self.signer_info)
self.testPath3 = os.path.join(self.data_dir, "A_thumbnail.jpg")
self.testPath4 = ALTERNATIVE_INGREDIENT_TEST_FILE
# Define a manifest as a dictionary
self.manifestDefinition = {
"claim_generator": "python_test",
"claim_generator_info": [{
"name": "python_test",
"version": "0.0.1",
}],
"claim_version": 1,
"format": "image/jpeg",
"title": "Python Test Image",
"ingredients": [],
"assertions": [
{
"label": "c2pa.actions",
"data": {
"actions": [
{
"action": "c2pa.created",
"digitalSourceType": "http://cv.iptc.org/newscodes/digitalsourcetype/digitalCreation"
}
]
}
}
]
}
# Define a V2 manifest as a dictionary
self.manifestDefinitionV2 = {
"claim_generator_info": [{
"name": "python_test",
"version": "0.0.1",
}],
# claim version 2 is the default
# "claim_version": 2,
"format": "image/jpeg",
"title": "Python Test Image V2",
"ingredients": [],
"assertions": [
{
"label": "c2pa.actions",
"data": {
"actions": [
{
"action": "c2pa.created",