forked from pydantic/pydantic-settings
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_settings.py
1877 lines (1343 loc) · 51.6 KB
/
test_settings.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import dataclasses
import os
import sys
import uuid
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Callable, Dict, Generic, List, Optional, Set, Tuple, Type, TypeVar, Union
import pytest
from annotated_types import MinLen
from pydantic import (
AliasChoices,
AliasPath,
BaseModel,
Field,
HttpUrl,
Json,
RootModel,
SecretStr,
ValidationError,
)
from pydantic import (
dataclasses as pydantic_dataclasses,
)
from pydantic.fields import FieldInfo
from typing_extensions import Annotated
from pydantic_settings import (
BaseSettings,
DotEnvSettingsSource,
EnvSettingsSource,
InitSettingsSource,
PydanticBaseSettingsSource,
SecretsSettingsSource,
SettingsConfigDict,
)
from pydantic_settings.sources import SettingsError, read_env_file
try:
import dotenv
except ImportError:
dotenv = None
class SimpleSettings(BaseSettings):
apple: str
class SettingWithIgnoreEmpty(BaseSettings):
apple: str = 'default'
model_config = SettingsConfigDict(env_ignore_empty=True)
def test_sub_env(env):
env.set('apple', 'hello')
s = SimpleSettings()
assert s.apple == 'hello'
def test_sub_env_override(env):
env.set('apple', 'hello')
s = SimpleSettings(apple='goodbye')
assert s.apple == 'goodbye'
def test_sub_env_missing():
with pytest.raises(ValidationError) as exc_info:
SimpleSettings()
assert exc_info.value.errors(include_url=False) == [
{'type': 'missing', 'loc': ('apple',), 'msg': 'Field required', 'input': {}}
]
def test_other_setting():
with pytest.raises(ValidationError):
SimpleSettings(apple='a', foobar=42)
def test_ignore_empty_when_empty_uses_default(env):
env.set('apple', '')
s = SettingWithIgnoreEmpty()
assert s.apple == 'default'
def test_ignore_empty_when_not_empty_uses_value(env):
env.set('apple', 'a')
s = SettingWithIgnoreEmpty()
assert s.apple == 'a'
def test_ignore_empty_with_dotenv_when_empty_uses_default(tmp_path):
p = tmp_path / '.env'
p.write_text('a=')
class Settings(BaseSettings):
a: str = 'default'
model_config = SettingsConfigDict(env_file=p, env_ignore_empty=True)
s = Settings()
assert s.a == 'default'
def test_ignore_empty_with_dotenv_when_not_empty_uses_value(tmp_path):
p = tmp_path / '.env'
p.write_text('a=b')
class Settings(BaseSettings):
a: str = 'default'
model_config = SettingsConfigDict(env_file=p, env_ignore_empty=True)
s = Settings()
assert s.a == 'b'
def test_with_prefix(env):
class Settings(BaseSettings):
apple: str
model_config = SettingsConfigDict(env_prefix='foobar_')
with pytest.raises(ValidationError):
Settings()
env.set('foobar_apple', 'has_prefix')
s = Settings()
assert s.apple == 'has_prefix'
def test_nested_env_with_basemodel(env):
class TopValue(BaseModel):
apple: str
banana: str
class Settings(BaseSettings):
top: TopValue
with pytest.raises(ValidationError):
Settings()
env.set('top', '{"banana": "secret_value"}')
s = Settings(top={'apple': 'value'})
assert s.top.apple == 'value'
assert s.top.banana == 'secret_value'
def test_merge_dict(env):
class Settings(BaseSettings):
top: Dict[str, str]
with pytest.raises(ValidationError):
Settings()
env.set('top', '{"banana": "secret_value"}')
s = Settings(top={'apple': 'value'})
assert s.top == {'apple': 'value', 'banana': 'secret_value'}
def test_nested_env_delimiter(env):
class SubSubValue(BaseSettings):
v6: str
class SubValue(BaseSettings):
v4: str
v5: int
sub_sub: SubSubValue
class TopValue(BaseSettings):
v1: str
v2: str
v3: str
sub: SubValue
class Cfg(BaseSettings):
v0: str
v0_union: Union[SubValue, int]
top: TopValue
model_config = SettingsConfigDict(env_nested_delimiter='__')
env.set('top', '{"v1": "json-1", "v2": "json-2", "sub": {"v5": "xx"}}')
env.set('top__sub__v5', '5')
env.set('v0', '0')
env.set('top__v2', '2')
env.set('top__v3', '3')
env.set('v0_union', '0')
env.set('top__sub__sub_sub__v6', '6')
env.set('top__sub__v4', '4')
cfg = Cfg()
assert cfg.model_dump() == {
'v0': '0',
'v0_union': 0,
'top': {
'v1': 'json-1',
'v2': '2',
'v3': '3',
'sub': {'v4': '4', 'v5': 5, 'sub_sub': {'v6': '6'}},
},
}
def test_nested_env_delimiter_with_prefix(env):
class Subsettings(BaseSettings):
banana: str
class Settings(BaseSettings):
subsettings: Subsettings
model_config = SettingsConfigDict(env_nested_delimiter='_', env_prefix='myprefix_')
env.set('myprefix_subsettings_banana', 'banana')
s = Settings()
assert s.subsettings.banana == 'banana'
class Settings(BaseSettings):
subsettings: Subsettings
model_config = SettingsConfigDict(env_nested_delimiter='_', env_prefix='myprefix__')
env.set('myprefix__subsettings_banana', 'banana')
s = Settings()
assert s.subsettings.banana == 'banana'
def test_nested_env_delimiter_complex_required(env):
class Cfg(BaseSettings):
v: str = 'default'
model_config = SettingsConfigDict(env_nested_delimiter='__')
env.set('v__x', 'x')
env.set('v__y', 'y')
cfg = Cfg()
assert cfg.model_dump() == {'v': 'default'}
def test_nested_env_delimiter_aliases(env):
class SubModel(BaseSettings):
v1: str
v2: str
class Cfg(BaseSettings):
sub_model: SubModel = Field(validation_alias=AliasChoices('foo', 'bar'))
model_config = SettingsConfigDict(env_nested_delimiter='__')
env.set('foo__v1', '-1-')
env.set('bar__v2', '-2-')
assert Cfg().model_dump() == {'sub_model': {'v1': '-1-', 'v2': '-2-'}}
class DateModel(BaseModel):
pips: bool = False
class ComplexSettings(BaseSettings):
apples: List[str] = []
bananas: Set[int] = set()
carrots: dict = {}
date: DateModel = DateModel()
def test_list(env):
env.set('apples', '["russet", "granny smith"]')
s = ComplexSettings()
assert s.apples == ['russet', 'granny smith']
assert s.date.pips is False
def test_annotated_list(env):
class AnnotatedComplexSettings(BaseSettings):
apples: Annotated[List[str], MinLen(2)] = []
env.set('apples', '["russet", "granny smith"]')
s = AnnotatedComplexSettings()
assert s.apples == ['russet', 'granny smith']
env.set('apples', '["russet"]')
with pytest.raises(ValidationError) as exc_info:
AnnotatedComplexSettings()
assert exc_info.value.errors(include_url=False) == [
{
'ctx': {'actual_length': 1, 'field_type': 'List', 'min_length': 2},
'input': ['russet'],
'loc': ('apples',),
'msg': 'List should have at least 2 items after validation, not 1',
'type': 'too_short',
}
]
def test_set_dict_model(env):
env.set('bananas', '[1, 2, 3, 3]')
env.set('CARROTS', '{"a": null, "b": 4}')
env.set('daTE', '{"pips": true}')
s = ComplexSettings()
assert s.bananas == {1, 2, 3}
assert s.carrots == {'a': None, 'b': 4}
assert s.date.pips is True
def test_invalid_json(env):
env.set('apples', '["russet", "granny smith",]')
with pytest.raises(SettingsError, match='error parsing value for field "apples" from source "EnvSettingsSource"'):
ComplexSettings()
def test_required_sub_model(env):
class Settings(BaseSettings):
foobar: DateModel
with pytest.raises(ValidationError):
Settings()
env.set('FOOBAR', '{"pips": "TRUE"}')
s = Settings()
assert s.foobar.pips is True
def test_non_class(env):
class Settings(BaseSettings):
foobar: Optional[str]
env.set('FOOBAR', 'xxx')
s = Settings()
assert s.foobar == 'xxx'
@pytest.mark.parametrize('dataclass_decorator', (pydantic_dataclasses.dataclass, dataclasses.dataclass))
def test_generic_dataclass(env, dataclass_decorator):
T = TypeVar('T')
@dataclass_decorator
class GenericDataclass(Generic[T]):
x: T
class ComplexSettings(BaseSettings):
field: GenericDataclass[int]
env.set('field', '{"x": 1}')
s = ComplexSettings()
assert s.field.x == 1
env.set('field', '{"x": "a"}')
with pytest.raises(ValidationError) as exc_info:
ComplexSettings()
assert exc_info.value.errors(include_url=False) == [
{
'input': 'a',
'loc': ('field', 'x'),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'type': 'int_parsing',
}
]
def test_generic_basemodel(env):
T = TypeVar('T')
class GenericModel(BaseModel, Generic[T]):
x: T
class ComplexSettings(BaseSettings):
field: GenericModel[int]
env.set('field', '{"x": 1}')
s = ComplexSettings()
assert s.field.x == 1
env.set('field', '{"x": "a"}')
with pytest.raises(ValidationError) as exc_info:
ComplexSettings()
assert exc_info.value.errors(include_url=False) == [
{
'input': 'a',
'loc': ('field', 'x'),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'type': 'int_parsing',
}
]
def test_annotated(env):
T = TypeVar('T')
class GenericModel(BaseModel, Generic[T]):
x: T
class ComplexSettings(BaseSettings):
field: GenericModel[int]
env.set('field', '{"x": 1}')
s = ComplexSettings()
assert s.field.x == 1
env.set('field', '{"x": "a"}')
with pytest.raises(ValidationError) as exc_info:
ComplexSettings()
assert exc_info.value.errors(include_url=False) == [
{
'input': 'a',
'loc': ('field', 'x'),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'type': 'int_parsing',
}
]
def test_env_str(env):
class Settings(BaseSettings):
apple: str = Field(None, validation_alias='BOOM')
env.set('BOOM', 'hello')
assert Settings().apple == 'hello'
def test_env_list(env):
class Settings(BaseSettings):
foobar: str = Field(validation_alias=AliasChoices('different1', 'different2'))
env.set('different1', 'value 1')
env.set('different2', 'value 2')
s = Settings()
assert s.foobar == 'value 1'
def test_env_list_field(env):
class Settings(BaseSettings):
foobar: str = Field(validation_alias='foobar_env_name')
env.set('FOOBAR_ENV_NAME', 'env value')
s = Settings()
assert s.foobar == 'env value'
def test_env_list_last(env):
class Settings(BaseSettings):
foobar: str = Field(validation_alias=AliasChoices('different2'))
env.set('different1', 'value 1')
env.set('different2', 'value 2')
s = Settings()
assert s.foobar == 'value 2'
def test_env_inheritance_field(env):
class SettingsParent(BaseSettings):
foobar: str = Field('parent default', validation_alias='foobar_env')
class SettingsChild(SettingsParent):
foobar: str = 'child default'
assert SettingsParent().foobar == 'parent default'
assert SettingsChild().foobar == 'child default'
assert SettingsChild(foobar='abc').foobar == 'abc'
env.set('foobar_env', 'env value')
assert SettingsParent().foobar == 'env value'
assert SettingsChild().foobar == 'child default'
assert SettingsChild(foobar='abc').foobar == 'abc'
def test_env_inheritance_config(env):
env.set('foobar', 'foobar')
env.set('prefix_foobar', 'prefix_foobar')
env.set('foobar_parent_from_field', 'foobar_parent_from_field')
env.set('prefix_foobar_parent_from_field', 'prefix_foobar_parent_from_field')
env.set('foobar_parent_from_config', 'foobar_parent_from_config')
env.set('foobar_child_from_config', 'foobar_child_from_config')
env.set('foobar_child_from_field', 'foobar_child_from_field')
# a. Child class config overrides prefix
class Parent(BaseSettings):
foobar: str = Field(None, validation_alias='foobar_parent_from_field')
model_config = SettingsConfigDict(env_prefix='p_')
class Child(Parent):
model_config = SettingsConfigDict(env_prefix='prefix_')
assert Child().foobar == 'foobar_parent_from_field'
# b. Child class overrides field
class Parent(BaseSettings):
foobar: str = Field(None, validation_alias='foobar_parent_from_config')
class Child(Parent):
foobar: str = Field(None, validation_alias='foobar_child_from_config')
assert Child().foobar == 'foobar_child_from_config'
# . Child class overrides parent prefix and field
class Parent(BaseSettings):
foobar: Optional[str]
model_config = SettingsConfigDict(env_prefix='p_')
class Child(Parent):
foobar: str = Field(None, validation_alias='foobar_child_from_field')
model_config = SettingsConfigDict(env_prefix='prefix_')
assert Child().foobar == 'foobar_child_from_field'
def test_invalid_validation_alias(env):
with pytest.raises(
TypeError, match='Invalid `validation_alias` type. it should be `str`, `AliasChoices`, or `AliasPath`'
):
class Settings(BaseSettings):
foobar: str = Field(validation_alias=123)
def test_validation_aliases(env):
class Settings(BaseSettings):
foobar: str = Field('default value', validation_alias='foobar_alias')
assert Settings().foobar == 'default value'
assert Settings(foobar_alias='42').foobar == '42'
env.set('foobar_alias', 'xxx')
assert Settings().foobar == 'xxx'
assert Settings(foobar_alias='42').foobar == '42'
def test_validation_aliases_alias_path(env):
class Settings(BaseSettings):
foobar: str = Field(validation_alias=AliasPath('foo', 'bar', 1))
env.set('foo', '{"bar": ["val0", "val1"]}')
assert Settings().foobar == 'val1'
def test_validation_aliases_alias_choices(env):
class Settings(BaseSettings):
foobar: str = Field(validation_alias=AliasChoices('foo', AliasPath('foo1', 'bar', 1), AliasPath('bar', 2)))
env.set('foo', 'val1')
assert Settings().foobar == 'val1'
env.pop('foo')
env.set('foo1', '{"bar": ["val0", "val2"]}')
assert Settings().foobar == 'val2'
env.pop('foo1')
env.set('bar', '["val1", "val2", "val3"]')
assert Settings().foobar == 'val3'
def test_validation_alias_with_env_prefix(env):
class Settings(BaseSettings):
foobar: str = Field(validation_alias='foo')
model_config = SettingsConfigDict(env_prefix='p_')
env.set('p_foo', 'bar')
with pytest.raises(ValidationError) as exc_info:
Settings()
assert exc_info.value.errors(include_url=False) == [
{'type': 'missing', 'loc': ('foo',), 'msg': 'Field required', 'input': {}}
]
env.set('foo', 'bar')
assert Settings().foobar == 'bar'
def test_case_sensitive(monkeypatch):
class Settings(BaseSettings):
foo: str
model_config = SettingsConfigDict(case_sensitive=True)
# Need to patch os.environ to get build to work on Windows, where os.environ is case insensitive
monkeypatch.setattr(os, 'environ', value={'Foo': 'foo'})
with pytest.raises(ValidationError) as exc_info:
Settings()
assert exc_info.value.errors(include_url=False) == [
{'type': 'missing', 'loc': ('foo',), 'msg': 'Field required', 'input': {}}
]
def test_nested_dataclass(env):
@pydantic_dataclasses.dataclass
class MyDataclass:
foo: int
bar: str
class Settings(BaseSettings):
n: MyDataclass
env.set('N', '{"foo": 123, "bar": "bar value"}')
s = Settings()
assert isinstance(s.n, MyDataclass)
assert s.n.foo == 123
assert s.n.bar == 'bar value'
def test_env_takes_precedence(env):
class Settings(BaseSettings):
foo: int
bar: str
@classmethod
def settings_customise_sources(
cls,
settings_cls: Type[BaseSettings],
init_settings: PydanticBaseSettingsSource,
env_settings: PydanticBaseSettingsSource,
dotenv_settings: PydanticBaseSettingsSource,
file_secret_settings: PydanticBaseSettingsSource,
) -> Tuple[PydanticBaseSettingsSource, ...]:
return env_settings, init_settings
env.set('BAR', 'env setting')
s = Settings(foo='123', bar='argument')
assert s.foo == 123
assert s.bar == 'env setting'
def test_env_deep_override(env):
class DeepSubModel(BaseModel):
v4: str
class SubModel(BaseModel):
v1: str
v2: bytes
v3: int
deep: DeepSubModel
class Settings(BaseSettings, env_nested_delimiter='__'):
v0: str
sub_model: SubModel
@classmethod
def settings_customise_sources(
cls, settings_cls, init_settings, env_settings, dotenv_settings, file_secret_settings
):
return env_settings, dotenv_settings, init_settings, file_secret_settings
env.set('SUB_MODEL__DEEP__V4', 'override-v4')
s_final = {'v0': '0', 'sub_model': {'v1': 'init-v1', 'v2': b'init-v2', 'v3': 3, 'deep': {'v4': 'override-v4'}}}
s = Settings(v0='0', sub_model={'v1': 'init-v1', 'v2': b'init-v2', 'v3': 3, 'deep': {'v4': 'init-v4'}})
assert s.model_dump() == s_final
s = Settings(v0='0', sub_model=SubModel(v1='init-v1', v2=b'init-v2', v3=3, deep=DeepSubModel(v4='init-v4')))
assert s.model_dump() == s_final
s = Settings(v0='0', sub_model=SubModel(v1='init-v1', v2=b'init-v2', v3=3, deep={'v4': 'init-v4'}))
assert s.model_dump() == s_final
s = Settings(v0='0', sub_model={'v1': 'init-v1', 'v2': b'init-v2', 'v3': 3, 'deep': DeepSubModel(v4='init-v4')})
assert s.model_dump() == s_final
def test_config_file_settings_nornir(env):
"""
See https://github.com/pydantic/pydantic/pull/341#issuecomment-450378771
"""
def nornir_settings_source() -> Dict[str, Any]:
return {'param_a': 'config a', 'param_b': 'config b', 'param_c': 'config c'}
class Settings(BaseSettings):
param_a: str
param_b: str
param_c: str
@classmethod
def settings_customise_sources(
cls,
settings_cls: Type[BaseSettings],
init_settings: PydanticBaseSettingsSource,
env_settings: PydanticBaseSettingsSource,
dotenv_settings: PydanticBaseSettingsSource,
file_secret_settings: PydanticBaseSettingsSource,
) -> Tuple[PydanticBaseSettingsSource, ...]:
return env_settings, init_settings, nornir_settings_source
env.set('PARAM_C', 'env setting c')
s = Settings(param_b='argument b', param_c='argument c')
assert s.param_a == 'config a'
assert s.param_b == 'argument b'
assert s.param_c == 'env setting c'
def test_env_union_with_complex_subfields_parses_json(env):
class A(BaseModel):
a: str
class B(BaseModel):
b: int
class Settings(BaseSettings):
content: Union[A, B, int]
env.set('content', '{"a": "test"}')
s = Settings()
assert s.content == A(a='test')
def test_env_union_with_complex_subfields_parses_plain_if_json_fails(env):
class A(BaseModel):
a: str
class B(BaseModel):
b: int
class Settings(BaseSettings):
content: Union[A, B, datetime]
env.set('content', '{"a": "test"}')
s = Settings()
assert s.content == A(a='test')
env.set('content', '2020-07-05T00:00:00Z')
s = Settings()
assert s.content == datetime(2020, 7, 5, 0, 0, tzinfo=timezone.utc)
def test_env_union_without_complex_subfields_does_not_parse_json(env):
class Settings(BaseSettings):
content: Union[datetime, str]
env.set('content', '2020-07-05T00:00:00Z')
s = Settings()
assert s.content == '2020-07-05T00:00:00Z'
test_env_file = """\
# this is a comment
A=good string
# another one, followed by whitespace
b='better string'
c="best string"
"""
def test_env_file_config(env, tmp_path):
p = tmp_path / '.env'
p.write_text(test_env_file)
class Settings(BaseSettings):
a: str
b: str
c: str
model_config = SettingsConfigDict(env_file=p)
env.set('A', 'overridden var')
s = Settings()
assert s.a == 'overridden var'
assert s.b == 'better string'
assert s.c == 'best string'
prefix_test_env_file = """\
# this is a comment
prefix_A=good string
# another one, followed by whitespace
prefix_b='better string'
prefix_c="best string"
f="random value"
"""
def test_env_file_with_env_prefix(env, tmp_path):
p = tmp_path / '.env'
p.write_text(prefix_test_env_file)
class Settings(BaseSettings):
a: str
b: str
c: str
model_config = SettingsConfigDict(env_file=p, env_prefix='prefix_')
env.set('prefix_A', 'overridden var')
s = Settings()
assert s.a == 'overridden var'
assert s.b == 'better string'
assert s.c == 'best string'
def test_env_file_config_case_sensitive(tmp_path):
p = tmp_path / '.env'
p.write_text(test_env_file)
class Settings(BaseSettings):
a: str
b: str
c: str
model_config = SettingsConfigDict(env_file=p, case_sensitive=True, extra='ignore')
with pytest.raises(ValidationError) as exc_info:
Settings()
assert exc_info.value.errors(include_url=False) == [
{
'type': 'missing',
'loc': ('a',),
'msg': 'Field required',
'input': {'b': 'better string', 'c': 'best string', 'A': 'good string'},
}
]
def test_env_file_export(env, tmp_path):
p = tmp_path / '.env'
p.write_text(
"""\
export A='good string'
export B=better-string
export C="best string"
"""
)
class Settings(BaseSettings):
a: str
b: str
c: str
model_config = SettingsConfigDict(env_file=p)
env.set('A', 'overridden var')
s = Settings()
assert s.a == 'overridden var'
assert s.b == 'better-string'
assert s.c == 'best string'
def test_env_file_export_validation_alias(env, tmp_path):
p = tmp_path / '.env'
p.write_text("""export a='{"b": ["1", "2"]}'""")
class Settings(BaseSettings):
a: str = Field(validation_alias=AliasChoices(AliasPath('a', 'b', 1)))
model_config = SettingsConfigDict(env_file=p)
s = Settings()
assert s.a == '2'
def test_env_file_config_custom_encoding(tmp_path):
p = tmp_path / '.env'
p.write_text('pika=p!±@', encoding='latin-1')
class Settings(BaseSettings):
pika: str
model_config = SettingsConfigDict(env_file=p, env_file_encoding='latin-1')
s = Settings()
assert s.pika == 'p!±@'
@pytest.fixture
def home_tmp():
tmp_filename = f'{uuid.uuid4()}.env'
home_tmp_path = Path.home() / tmp_filename
yield home_tmp_path, tmp_filename
home_tmp_path.unlink()
def test_env_file_home_directory(home_tmp):
home_tmp_path, tmp_filename = home_tmp
home_tmp_path.write_text('pika=baz')
class Settings(BaseSettings):
pika: str
model_config = SettingsConfigDict(env_file=f'~/{tmp_filename}')
assert Settings().pika == 'baz'
def test_env_file_none(tmp_path):
p = tmp_path / '.env'
p.write_text('a')
class Settings(BaseSettings):
a: str = 'xxx'
s = Settings(_env_file=p)
assert s.a == 'xxx'
def test_env_file_override_file(tmp_path):
p1 = tmp_path / '.env'
p1.write_text(test_env_file)
p2 = tmp_path / '.env.prod'
p2.write_text('A="new string"')
class Settings(BaseSettings):
a: str
model_config = SettingsConfigDict(env_file=str(p1))
s = Settings(_env_file=p2)
assert s.a == 'new string'
def test_env_file_override_none(tmp_path):
p = tmp_path / '.env'
p.write_text(test_env_file)
class Settings(BaseSettings):
a: Optional[str] = None
model_config = SettingsConfigDict(env_file=p)
s = Settings(_env_file=None)
assert s.a is None
def test_env_file_not_a_file(env):
class Settings(BaseSettings):
a: str = None
env.set('A', 'ignore non-file')
s = Settings(_env_file='tests/')
assert s.a == 'ignore non-file'
def test_read_env_file_case_sensitive(tmp_path):
p = tmp_path / '.env'
p.write_text('a="test"\nB=123')
assert read_env_file(p) == {'a': 'test', 'b': '123'}
assert read_env_file(p, case_sensitive=True) == {'a': 'test', 'B': '123'}
def test_read_env_file_syntax_wrong(tmp_path):
p = tmp_path / '.env'
p.write_text('NOT_AN_ASSIGNMENT')
assert read_env_file(p, case_sensitive=True) == {'NOT_AN_ASSIGNMENT': None}
def test_env_file_example(tmp_path):
p = tmp_path / '.env'
p.write_text(
"""\
# ignore comment
ENVIRONMENT="production"
REDIS_ADDRESS=localhost:6379
MEANING_OF_LIFE=42
MY_VAR='Hello world'
"""
)
class Settings(BaseSettings):
environment: str
redis_address: str
meaning_of_life: int
my_var: str
s = Settings(_env_file=str(p))
assert s.model_dump() == {
'environment': 'production',
'redis_address': 'localhost:6379',
'meaning_of_life': 42,
'my_var': 'Hello world',
}
def test_env_file_custom_encoding(tmp_path):
p = tmp_path / '.env'
p.write_text('pika=p!±@', encoding='latin-1')
class Settings(BaseSettings):
pika: str
with pytest.raises(UnicodeDecodeError):
Settings(_env_file=str(p))
s = Settings(_env_file=str(p), _env_file_encoding='latin-1')
assert s.model_dump() == {'pika': 'p!±@'}
test_default_env_file = """\
debug_mode=true
host=localhost
Port=8000
"""
test_prod_env_file = """\
debug_mode=false
host=https://example.com/services
"""