@@ -839,12 +839,11 @@ class Settings(BaseSettings):
839
839
840
840
model_config = SettingsConfigDict (env_file = p , env_prefix = 'prefix_' )
841
841
842
- err_msg = (
843
- "unable to load environment variables from dotenv file "
844
- "due to the presence of variables without the specified prefix - 'prefix_'"
845
- )
846
- with pytest .raises (SettingsError , match = err_msg ):
842
+ with pytest .raises (ValidationError ) as exc_info :
847
843
Settings ()
844
+ assert exc_info .value .errors (include_url = False ) == [
845
+ {'type' : 'extra_forbidden' , 'loc' : ('f' ,), 'msg' : 'Extra inputs are not permitted' , 'input' : 'random value' }
846
+ ]
848
847
849
848
850
849
def test_ignore_env_file_with_env_prefix_invalid (tmp_path ):
@@ -2310,3 +2309,48 @@ def settings_customise_sources(
2310
2309
2311
2310
s = Settings ()
2312
2311
assert s .model_dump () == {'json5' : 5 , 'json6' : 6 }
2312
+
2313
+
2314
+ def test_dotenv_with_alias_and_env_prefix (tmp_path ):
2315
+ p = tmp_path / '.env'
2316
+ p .write_text ('xxx__foo=1\n xxx__bar=2' )
2317
+
2318
+ class Settings (BaseSettings ):
2319
+ model_config = SettingsConfigDict (env_file = p , env_prefix = 'xxx__' )
2320
+
2321
+ foo : str = ''
2322
+ bar_alias : str = Field ('' , validation_alias = 'xxx__bar' )
2323
+
2324
+ s = Settings ()
2325
+ assert s .model_dump () == {'foo' : '1' , 'bar_alias' : '2' }
2326
+
2327
+ class Settings1 (BaseSettings ):
2328
+ model_config = SettingsConfigDict (env_file = p , env_prefix = 'xxx__' )
2329
+
2330
+ foo : str = ''
2331
+ bar_alias : str = Field ('' , alias = 'bar' )
2332
+
2333
+ with pytest .raises (ValidationError ) as exc_info :
2334
+ Settings1 ()
2335
+ assert exc_info .value .errors (include_url = False ) == [
2336
+ {'type' : 'extra_forbidden' , 'loc' : ('xxx__bar' ,), 'msg' : 'Extra inputs are not permitted' , 'input' : '2' }
2337
+ ]
2338
+
2339
+
2340
+ def test_dotenv_with_alias_and_env_prefix_nested (tmp_path ):
2341
+ p = tmp_path / '.env'
2342
+ p .write_text ('xxx__bar=0\n xxx__nested__a=1\n xxx__nested__b=2' )
2343
+
2344
+ class NestedSettings (BaseModel ):
2345
+ a : str = 'a'
2346
+ b : str = 'b'
2347
+
2348
+ class Settings (BaseSettings ):
2349
+ model_config = SettingsConfigDict (env_prefix = 'xxx__' , env_nested_delimiter = '__' , env_file = p )
2350
+
2351
+ foo : str = ''
2352
+ bar_alias : str = Field ('' , alias = 'xxx__bar' )
2353
+ nested_alias : NestedSettings = Field (default_factory = NestedSettings , alias = 'xxx__nested' )
2354
+
2355
+ s = Settings ()
2356
+ assert s .model_dump () == {'foo' : '' , 'bar_alias' : '0' , 'nested_alias' : {'a' : '1' , 'b' : '2' }}
0 commit comments