@@ -179,3 +179,90 @@ def test_load_json_list(temp_json_file):
179179 # Act
180180 with pytest .raises (ValueError ):
181181 JSONConfig (temp_json_file )
182+
183+
184+ def test_json_schema_validation_success (temp_json_file , monkeypatch ):
185+ # Arrange
186+ schema = {
187+ "type" : "object" ,
188+ "properties" : {
189+ "foo" : {"type" : "string" }
190+ },
191+ "required" : ["foo" ]
192+ }
193+
194+ content = {"$schema" : "http://example.com/schema" , "foo" : "bar" }
195+ with open (temp_json_file , "w" , encoding = "utf-8" ) as f :
196+ json .dump (content , f )
197+
198+ class DummyResponse :
199+ def raise_for_status (self ):
200+ return None
201+
202+ def json (self ):
203+ return schema
204+
205+ monkeypatch .setattr ("requests.get" , lambda url : DummyResponse ())
206+
207+ # Act / Assert - should not raise
208+ JSONConfig (temp_json_file )
209+
210+
211+ def test_json_schema_fetch_failure (temp_json_file , monkeypatch ):
212+ # Arrange
213+ content = {"$schema" : "http://example.com/schema" , "foo" : "bar" }
214+ with open (temp_json_file , "w" , encoding = "utf-8" ) as f :
215+ json .dump (content , f )
216+
217+ def raise_exc (url ):
218+ raise Exception ("network error" )
219+
220+ monkeypatch .setattr ("requests.get" , raise_exc )
221+
222+ # Act / Assert
223+ with pytest .raises (ValueError ) as exc :
224+ JSONConfig (temp_json_file )
225+ assert "An error occurred during schema validation" in str (exc .value )
226+
227+
228+ def test_json_schema_validation_failure (temp_json_file , monkeypatch ):
229+ # Arrange: schema requires foo to be integer but file has string
230+ schema = {
231+ "type" : "object" ,
232+ "properties" : {
233+ "foo" : {"type" : "integer" }
234+ },
235+ "required" : ["foo" ]
236+ }
237+
238+ content = {"$schema" : "http://example.com/schema" , "foo" : "not-an-int" }
239+ with open (temp_json_file , "w" , encoding = "utf-8" ) as f :
240+ json .dump (content , f )
241+
242+ class DummyResponse :
243+ def raise_for_status (self ):
244+ return None
245+
246+ def json (self ):
247+ return schema
248+
249+ monkeypatch .setattr ("requests.get" , lambda url : DummyResponse ())
250+
251+ # Act / Assert - validation should fail and raise ValueError
252+ with pytest .raises (ValueError ) as exc :
253+ JSONConfig (temp_json_file )
254+ assert "Configuration validation against schema failed" in str (exc .value )
255+
256+
257+ def test_require_validation_without_schema (tmp_path ):
258+ # Arrange
259+ file_path = tmp_path / "no_schema.json"
260+ with open (file_path , "w" , encoding = "utf-8" ) as f :
261+ json .dump ({"foo" : "bar" }, f )
262+
263+ # Act / Assert
264+ with pytest .raises (ValueError ) as exc :
265+ JSONConfig (str (file_path ), True )
266+ assert "JSON schema validation is required but no '$schema' key found in configuration" in str (exc .value )
267+
268+
0 commit comments