File tree Expand file tree Collapse file tree 2 files changed +37
-1
lines changed 
pydantic_settings/sources/providers Expand file tree Collapse file tree 2 files changed +37
-1
lines changed Original file line number Diff line number Diff line change @@ -55,7 +55,12 @@ def __init__(
5555        self .yaml_data  =  self ._read_files (self .yaml_file_path )
5656
5757        if  self .yaml_config_section :
58-             self .yaml_data  =  self .yaml_data [self .yaml_config_section ]
58+             try :
59+                 self .yaml_data  =  self .yaml_data [self .yaml_config_section ]
60+             except  KeyError :
61+                 raise  KeyError (
62+                     f'yaml_config_section key "{ self .yaml_config_section } { self .yaml_file_path }  
63+                 )
5964        super ().__init__ (settings_cls , self .yaml_data )
6065
6166    def  _read_file (self , file_path : Path ) ->  dict [str , Any ]:
Original file line number Diff line number Diff line change @@ -197,3 +197,34 @@ def settings_customise_sources(
197197
198198    s  =  Settings ()
199199    assert  s .nested_field  ==  'world!' 
200+ 
201+ 
202+ @pytest .mark .skipif (yaml  is  None , reason = 'pyYAML is not installed' ) 
203+ def  test_invalid_yaml_config_section (tmp_path ):
204+     p  =  tmp_path  /  '.env' 
205+     p .write_text (
206+         """ 
207+     foobar: "Hello" 
208+     nested: 
209+         nested_field: "world!" 
210+     """ 
211+     )
212+ 
213+     class  Settings (BaseSettings ):
214+         nested_field : str 
215+ 
216+         model_config  =  SettingsConfigDict (yaml_file = p , yaml_config_section = 'invalid_key' )
217+ 
218+         @classmethod  
219+         def  settings_customise_sources (
220+             cls ,
221+             settings_cls : type [BaseSettings ],
222+             init_settings : PydanticBaseSettingsSource ,
223+             env_settings : PydanticBaseSettingsSource ,
224+             dotenv_settings : PydanticBaseSettingsSource ,
225+             file_secret_settings : PydanticBaseSettingsSource ,
226+         ) ->  tuple [PydanticBaseSettingsSource , ...]:
227+             return  (YamlConfigSettingsSource (settings_cls ),)
228+ 
229+     with  pytest .raises (KeyError ):
230+         Settings ()
 
 
   
 
     
   
   
          
    
    
     
    
      
     
     
    You can’t perform that action at this time.
  
 
    
  
    
      
        
     
       
      
     
   
 
    
    
  
 
  
 
     
    
0 commit comments