1+ import os
2+ from unittest import mock
3+
4+ import pytest
5+ from pydantic import ValidationError
6+
7+ from app .config import Settings
8+
9+
10+ class TestSettingsValidation :
11+ def test_secret_key_missing (self ):
12+ with mock .patch .dict (os .environ , {}, clear = True ):
13+ with pytest .raises (ValidationError ) as exc_info :
14+ Settings ()
15+
16+ errors = exc_info .value .errors ()
17+ assert len (errors ) == 1
18+ assert errors [0 ]["loc" ] == ("SECRET_KEY" ,)
19+ assert "JWT_SECRET_KEY environment variable must be set" in errors [0 ]["msg" ]
20+
21+ def test_secret_key_too_short (self ):
22+ with mock .patch .dict (os .environ , {"JWT_SECRET_KEY" : "short_key" }, clear = True ):
23+ with pytest .raises (ValidationError ) as exc_info :
24+ Settings ()
25+
26+ errors = exc_info .value .errors ()
27+ assert len (errors ) == 1
28+ assert errors [0 ]["loc" ] == ("SECRET_KEY" ,)
29+ assert "JWT_SECRET_KEY must be at least 32 characters long" in errors [0 ]["msg" ]
30+
31+ def test_secret_key_default_placeholder (self ):
32+ test_cases = ["your_secret_key_here" , "default_secret_key" ]
33+
34+ for placeholder in test_cases :
35+ with mock .patch .dict (os .environ , {"JWT_SECRET_KEY" : placeholder }, clear = True ):
36+ with pytest .raises (ValidationError ) as exc_info :
37+ Settings ()
38+
39+ errors = exc_info .value .errors ()
40+ assert len (errors ) == 1
41+ assert errors [0 ]["loc" ] == ("SECRET_KEY" ,)
42+ assert "JWT_SECRET_KEY must not use default placeholder values" in errors [0 ]["msg" ]
43+
44+ def test_secret_key_valid (self ):
45+ valid_key = "a" * 32 # 32 character key
46+ with mock .patch .dict (os .environ , {"JWT_SECRET_KEY" : valid_key }, clear = True ):
47+ settings = Settings ()
48+ assert settings .SECRET_KEY == valid_key
49+
50+ def test_secret_key_longer_than_minimum (self ):
51+ long_key = "a" * 64 # 64 character key
52+ with mock .patch .dict (os .environ , {"JWT_SECRET_KEY" : long_key }, clear = True ):
53+ settings = Settings ()
54+ assert settings .SECRET_KEY == long_key
0 commit comments