@@ -767,7 +767,6 @@ class Settings(BaseSettings):
767
767
768
768
prefix_b='better string'
769
769
prefix_c="best string"
770
- f="random value"
771
770
"""
772
771
773
772
@@ -790,6 +789,54 @@ class Settings(BaseSettings):
790
789
assert s .c == 'best string'
791
790
792
791
792
+ prefix_test_env_invalid_file = """\
793
+ # this is a comment
794
+ prefix_A=good string
795
+ # another one, followed by whitespace
796
+
797
+ prefix_b='better string'
798
+ prefix_c="best string"
799
+ f="random value"
800
+ """
801
+
802
+
803
+ def test_env_file_with_env_prefix_invalid (tmp_path ):
804
+ p = tmp_path / '.env'
805
+ p .write_text (prefix_test_env_invalid_file )
806
+
807
+ class Settings (BaseSettings ):
808
+ a : str
809
+ b : str
810
+ c : str
811
+
812
+ model_config = SettingsConfigDict (env_file = p , env_prefix = 'prefix_' )
813
+
814
+ err_msg = (
815
+ "unable to load environment variables from dotenv file "
816
+ "due to the presence of variables without the specified prefix - 'prefix_'"
817
+ )
818
+ with pytest .raises (SettingsError , match = err_msg ):
819
+ Settings ()
820
+
821
+
822
+ def test_ignore_env_file_with_env_prefix_invalid (tmp_path ):
823
+ p = tmp_path / '.env'
824
+ p .write_text (prefix_test_env_invalid_file )
825
+
826
+ class Settings (BaseSettings ):
827
+ a : str
828
+ b : str
829
+ c : str
830
+
831
+ model_config = SettingsConfigDict (env_file = p , env_prefix = 'prefix_' , extra = 'ignore' )
832
+
833
+ s = Settings ()
834
+
835
+ assert s .a == 'good string'
836
+ assert s .b == 'better string'
837
+ assert s .c == 'best string'
838
+
839
+
793
840
def test_env_file_config_case_sensitive (tmp_path ):
794
841
p = tmp_path / '.env'
795
842
p .write_text (test_env_file )
0 commit comments