1
+ from datetime import datetime
2
+ import pytest
3
+ import asyncio
4
+ from unittest .mock import patch , AsyncMock
5
+ from growthbook_client import (
6
+ GrowthBookClient ,
7
+ Options ,
8
+ UserContext ,
9
+ FeatureRefreshStrategy ,
10
+ EnhancedFeatureRepository
11
+ )
12
+
13
+ @pytest .fixture
14
+ def mock_features_response ():
15
+ return {
16
+ "features" : {
17
+ "test-feature" : {
18
+ "defaultValue" : True ,
19
+ "rules" : []
20
+ }
21
+ },
22
+ "savedGroups" : {}
23
+ }
24
+
25
+ @pytest .fixture
26
+ def mock_options ():
27
+ return Options (
28
+ api_host = "https://test.growthbook.io" ,
29
+ client_key = "test_key" ,
30
+ decryption_key = "test_decrypt" ,
31
+ cache_ttl = 60 ,
32
+ enabled = True ,
33
+ refresh_strategy = FeatureRefreshStrategy .STALE_WHILE_REVALIDATE
34
+ )
35
+
36
+
37
+ @pytest .fixture
38
+ def mock_sse_data ():
39
+ return {
40
+ 'type' : 'features' ,
41
+ 'data' : {
42
+ 'features' : {
43
+ 'feature-1' : {'defaultValue' : True },
44
+ 'feature-2' : {'defaultValue' : False }
45
+ }
46
+ }
47
+ }
48
+
49
+ @pytest .mark .asyncio
50
+ async def test_initialization_with_retries (mock_options , mock_features_response ):
51
+ with patch ('growthbook_client.EnhancedFeatureRepository.load_features_async' ) as mock_load :
52
+ mock_load .side_effect = [
53
+ Exception ("Network error" ),
54
+ mock_features_response
55
+ ]
56
+
57
+ client = GrowthBookClient (mock_options )
58
+ success = await client .initialize ()
59
+
60
+ assert success == False
61
+ assert mock_load .call_count == 1
62
+
63
+ @pytest .mark .asyncio
64
+ async def test_sse_connection_lifecycle (mock_options , mock_features_response ):
65
+ with patch ('growthbook_client.EnhancedFeatureRepository.load_features_async' ) as mock_load :
66
+ mock_load .return_value = mock_features_response
67
+
68
+ client = GrowthBookClient (
69
+ Options (** {** mock_options .__dict__ ,
70
+ "refresh_strategy" : FeatureRefreshStrategy .SERVER_SENT_EVENTS })
71
+ )
72
+
73
+ with patch ('growthbook_client.EnhancedFeatureRepository._maintain_sse_connection' ) as mock_sse :
74
+ await client .initialize ()
75
+ assert mock_sse .called
76
+ await client .close ()
0 commit comments