11import os
22import pytest
3- from customize_schema import validate_metadata as validator43
4- from helpers import load_json_path
53import logging
6- from tqdm import tqdm
4+ from caltechdata_api import validate_metadata as validator43
5+ from helpers import load_json_path
76
8- # Directories for valid and invalid JSON files
9- VALID_DATACITE43_DIR = "../tests/data/datacite43/"
10- INVALID_DATACITE43_DIR = "../tests/data/invalid_datacite43/"
7+ # Configure logging
8+ logging .basicConfig (level = logging .DEBUG )
9+ logger = logging .getLogger (__name__ )
10+
11+ # Dynamically determine the base path
12+ BASE_DIR = os .path .dirname (os .path .abspath (__file__ ))
13+ INVALID_DATACITE43_DIR = os .path .join (BASE_DIR , "data" , "invalid_datacite43" )
14+ DATACITE43_DIR = os .path .join (BASE_DIR , "data" )
1115
1216
1317# Function to get all JSON files in the directory
@@ -17,58 +21,85 @@ def get_all_json_files(directory):
1721 ]
1822
1923
20- # Get list of all valid JSON files in the directory
21- VALID_DATACITE43_FILES = get_all_json_files (VALID_DATACITE43_DIR )
24+ # Get list of all valid and invalid JSON files
25+ VALID_DATACITE43_FILES = get_all_json_files (
26+ os .path .join (BASE_DIR , "data" , "datacite43" )
27+ )
2228INVALID_DATACITE43_FILES = get_all_json_files (INVALID_DATACITE43_DIR )
2329
2430
2531@pytest .mark .parametrize ("valid_file" , VALID_DATACITE43_FILES )
2632def test_valid_json (valid_file ):
2733 """Test that valid example files validate successfully."""
28- print (f"\n Validating file: { valid_file } " ) # Log for file being tested
34+ print (f"\n Validating file: { valid_file } " )
2935 json_data = load_json_path (valid_file )
3036 validation_errors = None
3137 try :
3238 validation_errors = validator43 (json_data )
3339 except ValueError as e :
3440 pytest .fail (f"Validation failed for: { valid_file } \n Errors: { str (e )} " )
3541
36- if validation_errors :
37- pytest . fail ( f"Validation failed for: { valid_file } \n Errors: { validation_errors } " )
38- else :
39- print (f"Validation passed for: { valid_file } " )
42+ assert (
43+ not validation_errors
44+ ), f"Validation failed for: { valid_file } \n Errors: { validation_errors } "
45+ print (f"Validation passed for: { valid_file } " )
4046
4147
4248@pytest .mark .parametrize ("invalid_file" , INVALID_DATACITE43_FILES )
4349def test_invalid_json (invalid_file ):
4450 """Test that invalid example files do not validate successfully."""
45- print (f"\n Validating file: { invalid_file } " ) # Log for file being tested
51+ logger .debug (f"Attempting to validate invalid file: { invalid_file } " )
52+
4653 json_data = load_json_path (invalid_file )
47- validation_errors = None
48- try :
49- validation_errors = validator43 (json_data )
50- except ValueError :
51- print (f"Validation failed as expected for: { invalid_file } " )
52- return # Test passes if validation raises a ValueError
5354
54- if validation_errors :
55- print (f"Validation failed as expected for: { invalid_file } " )
56- else :
57- pytest .fail (f"Validation passed unexpectedly for: { invalid_file } " )
55+ def validate_wrapper ():
56+ try :
57+ validation_errors = validator43 (json_data )
58+
59+ logger .debug (f"Validation result for { invalid_file } : { validation_errors } " )
60+
61+ if validation_errors :
62+ logger .debug (f"Found validation errors in { invalid_file } " )
63+ return
64+
65+ logger .error (
66+ f"No validation errors found for supposedly invalid file: { invalid_file } "
67+ )
68+ raise ValueError (
69+ f"Validation did not fail for invalid file: { invalid_file } "
70+ )
71+
72+ except Exception as e :
73+ logger .error (f"Validation exception for { invalid_file } : { str (e )} " )
74+ raise
75+
76+ with pytest .raises ((ValueError , KeyError , AssertionError , TypeError )):
77+ validate_wrapper ()
5878
5979
6080@pytest .mark .parametrize (
6181 "missing_field_file" ,
6282 [
63- {"file" : "../tests/data/missing_creators.json" , "missing_field" : "creators" },
64- {"file" : "../tests/data/missing_titles.json" , "missing_field" : "titles" },
83+ {
84+ "file" : os .path .join (DATACITE43_DIR , "missing_creators.json" ),
85+ "missing_field" : "creators" ,
86+ },
87+ {
88+ "file" : os .path .join (DATACITE43_DIR , "missing_titles.json" ),
89+ "missing_field" : "titles" ,
90+ },
6591 ],
6692)
6793def test_missing_required_fields (missing_field_file ):
6894 """Test that JSON files missing required fields fail validation."""
6995 print (
7096 f"\n Testing missing field: { missing_field_file ['missing_field' ]} in file: { missing_field_file ['file' ]} "
7197 )
98+
99+ # Skip the test if the file doesn't exist
100+ if not os .path .exists (missing_field_file ["file" ]):
101+ pytest .skip (f"Test file not found: { missing_field_file ['file' ]} " )
102+
72103 json_data = load_json_path (missing_field_file ["file" ])
73104 with pytest .raises (
74105 ValueError ,
@@ -80,15 +111,26 @@ def test_missing_required_fields(missing_field_file):
80111@pytest .mark .parametrize (
81112 "type_error_file" ,
82113 [
83- {"file" : "../tests/data/type_error_creators.json" , "field" : "creators" },
84- {"file" : "../tests/data/type_error_dates.json" , "field" : "dates" },
114+ {
115+ "file" : os .path .join (DATACITE43_DIR , "type_error_creators.json" ),
116+ "field" : "creators" ,
117+ },
118+ {
119+ "file" : os .path .join (DATACITE43_DIR , "type_error_dates.json" ),
120+ "field" : "dates" ,
121+ },
85122 ],
86123)
87124def test_incorrect_field_types (type_error_file ):
88125 """Test that JSON files with incorrect field types fail validation."""
89126 print (
90127 f"\n Testing incorrect type in field: { type_error_file ['field' ]} for file: { type_error_file ['file' ]} "
91128 )
129+
130+ # Skip the test if the file doesn't exist
131+ if not os .path .exists (type_error_file ["file" ]):
132+ pytest .skip (f"Test file not found: { type_error_file ['file' ]} " )
133+
92134 json_data = load_json_path (type_error_file ["file" ])
93135 with pytest .raises (
94136 ValueError , match = f"Incorrect type for field: { type_error_file ['field' ]} "
@@ -98,55 +140,27 @@ def test_incorrect_field_types(type_error_file):
98140
99141def test_multiple_errors ():
100142 """Test JSON file with multiple issues to check all errors are raised."""
101- json_data = load_json_path ("../tests/data/multiple_errors.json" )
143+ multiple_errors_file = os .path .join (DATACITE43_DIR , "multiple_errors.json" )
144+
145+ # Skip the test if the file doesn't exist
146+ if not os .path .exists (multiple_errors_file ):
147+ pytest .skip (f"Test file not found: { multiple_errors_file } " )
148+
149+ json_data = load_json_path (multiple_errors_file )
102150 with pytest .raises (ValueError , match = "Multiple validation errors" ):
103151 validator43 (json_data )
104152
105153
106154def test_error_logging (caplog ):
107155 """Test that errors are logged correctly during validation."""
108- json_data = load_json_path (
109- "../tests/data/invalid_datacite43/some_invalid_file.json"
110- )
156+ some_invalid_file = os .path .join (INVALID_DATACITE43_DIR , "some_invalid_file.json" )
157+
158+ # Skip the test if the file doesn't exist
159+ if not os .path .exists (some_invalid_file ):
160+ pytest .skip (f"Test file not found: { some_invalid_file } " )
161+
162+ json_data = load_json_path (some_invalid_file )
111163 with caplog .at_level (logging .ERROR ):
112164 with pytest .raises (ValueError ):
113165 validator43 (json_data )
114166 assert "Validation failed" in caplog .text
115-
116-
117- if __name__ == "__main__" :
118- # Manual test runner for valid files
119- failed_valid_files = []
120- print ("\n Running validation for valid files..." )
121- for file in tqdm (VALID_DATACITE43_FILES , desc = "Valid files" ):
122- try :
123- test_valid_json (file )
124- except AssertionError as e :
125- failed_valid_files .append (file )
126- print (f"Error occurred in valid file: { file } \n Error details: { e } " )
127-
128- if not failed_valid_files :
129- print ("\n ✅ All valid files passed validation. Test complete." )
130- else :
131- print ("\n ❌ The following valid files failed validation:" )
132- for failed_file in failed_valid_files :
133- print (f"- { failed_file } " )
134-
135- # Manual test runner for invalid files
136- passed_invalid_files = []
137- print ("\n Running validation for invalid files..." )
138- for file in tqdm (INVALID_DATACITE43_FILES , desc = "Invalid files" ):
139- try :
140- test_invalid_json (file )
141- except AssertionError as e :
142- passed_invalid_files .append (file )
143- print (f"Error occurred in invalid file: { file } \n Error details: { e } " )
144-
145- if not passed_invalid_files :
146- print (
147- "\n ✅ All invalid files failed validation as expected. Test is a success."
148- )
149- else :
150- print ("\n ❌ The following invalid files unexpectedly passed validation:" )
151- for passed_file in passed_invalid_files :
152- print (f"- { passed_file } " )
0 commit comments