Coverage for app/backend/src/tests/test_experimentation.py: 100%

173 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-10 09:48 +0000

1import json 

2 

3import pytest 

4from growthbook.common_types import FeatureResult 

5from sqlalchemy import select 

6 

7from couchers import experimentation 

8from couchers.config import config 

9from couchers.context import make_background_user_context, make_logged_out_context 

10from couchers.db import session_scope 

11from couchers.experimentation import ( 

12 GrowthBookUnavailableError, 

13 _load_local_flags, 

14 _record_feature_usage, 

15 setup_experimentation, 

16) 

17from couchers.i18n import LocalizationContext 

18from couchers.metrics import feature_flag_evaluations_counter 

19from couchers.models.logging import ExperimentExposure, ExposureSource, FeatureUsage 

20from couchers.proto import bugs_pb2 

21from tests.fixtures.feature_flags import FeatureFlags, Flags 

22from tests.fixtures.sessions import bugs_session 

23 

24 

25def _flag_eval_count(flag_key: str, source: str, value: str) -> float: 

26 return sum( 

27 s.value 

28 for m in feature_flag_evaluations_counter.collect() 

29 for s in m.samples 

30 if s.name == "couchers_feature_flag_evaluations_total" 

31 and s.labels.get("flag_key") == flag_key 

32 and s.labels.get("source") == source 

33 and s.labels.get("value") == value 

34 ) 

35 

36 

37# Raw GrowthBook feature definitions for exercising the framework's own bucketing/exposure mechanics. 

38# Most tests just need feature_flags.set(key, value); these go through feature_flags.set_definition(). 

39# A rollout with explicit coverage: bucketing needs a hash, so anonymous (logged-out) users are 

40# excluded even at 100% coverage and get the feature's default value instead. 

41_ROLLOUT_FLAG = {"defaultValue": "control", "rules": [{"force": "treatment", "coverage": 1.0}]} 

42# A global force with no coverage: applies to everyone, including anonymous users. 

43_GLOBAL_FORCE_FLAG = {"defaultValue": False, "rules": [{"force": True}]} 

44# An actual experiment: a logged-in user gets bucketed (coverage 1), which fires the exposure callback. 

45_EXPERIMENT_FLAG = { 

46 "defaultValue": "control", 

47 "rules": [{"key": "my_experiment", "variations": ["control", "treatment"], "coverage": 1.0}], 

48} 

49 

50 

51def test_logged_in_user_is_bucketed_into_rollout(db, feature_flags: FeatureFlags): 

52 feature_flags.set_definition("rollout_flag", _ROLLOUT_FLAG) 

53 context = make_background_user_context(123) 

54 assert context.get_string_value("rollout_flag", "fallback") == "treatment" 

55 

56 

57def test_anonymous_user_excluded_from_rollout_gets_feature_default(feature_flags: FeatureFlags): 

58 feature_flags.set_definition("rollout_flag", _ROLLOUT_FLAG) 

59 context = make_logged_out_context(LocalizationContext.en_utc()) 

60 # Previously this raised NotLoggedInContextException via context.user_id. 

61 assert context.get_string_value("rollout_flag", "fallback") == "control" 

62 

63 

64def test_anonymous_user_still_gets_global_force_on_flag(feature_flags: FeatureFlags): 

65 feature_flags.set_definition("global_flag", _GLOBAL_FORCE_FLAG) 

66 context = make_logged_out_context(LocalizationContext.en_utc()) 

67 assert context.get_boolean_value("global_flag", default=False) is True 

68 

69 

70def test_unknown_feature_returns_in_code_default(feature_flags: FeatureFlags): 

71 context = make_logged_out_context(LocalizationContext.en_utc()) 

72 assert context.get_string_value("does_not_exist", "my_default") == "my_default" 

73 

74 

75def test_evaluating_an_experiment_flag_records_exactly_one_exposure(db, feature_flags: FeatureFlags): 

76 # Evaluating an experiment-backed flag for a bucketed user records exactly one exposure - this is 

77 # the whole point of per-flag evaluation: exposure is logged only for flags the user actually hits. 

78 feature_flags.set_definition("experiment_flag", _EXPERIMENT_FLAG) 

79 context = make_background_user_context(123) 

80 assert context.get_object_value("experiment_flag", "control") in {"control", "treatment"} 

81 

82 with session_scope() as session: 

83 rows = session.execute(select(ExperimentExposure).where(ExperimentExposure.user_id == 123)).scalars().all() 

84 assert len(rows) == 1 

85 assert rows[0].experiment_key == "my_experiment" 

86 assert rows[0].source == ExposureSource.backend 

87 

88 

89def test_evaluate_feature_flag_servicer_returns_value(feature_flags: FeatureFlags, db): 

90 feature_flags.set("global_flag", True) 

91 with bugs_session() as bugs: 

92 res = bugs.EvaluateFeatureFlag(bugs_pb2.EvaluateFeatureFlagReq(flag_key="global_flag")) 

93 assert res.value.bool_value is True 

94 

95 

96def test_evaluate_feature_flag_servicer_unknown_leaves_value_unset(feature_flags: FeatureFlags, db): 

97 with bugs_session() as bugs: 

98 res = bugs.EvaluateFeatureFlag(bugs_pb2.EvaluateFeatureFlagReq(flag_key="does_not_exist")) 

99 assert not res.HasField("value") 

100 

101 

102def _get_usage(session, user_id): 

103 return ( 

104 session.execute(select(FeatureUsage).where(FeatureUsage.user_id == user_id).order_by(FeatureUsage.id)) 

105 .scalars() 

106 .all() 

107 ) 

108 

109 

110def test_record_feature_usage_appends_a_row(db): 

111 _record_feature_usage(1, "my_feature", FeatureResult(value=True, source="defaultValue")) 

112 

113 with session_scope() as session: 

114 rows = _get_usage(session, 1) 

115 assert len(rows) == 1 

116 assert rows[0].feature_key == "my_feature" 

117 assert rows[0].value is True 

118 assert rows[0].time is not None 

119 

120 

121def test_record_feature_usage_appends_a_row_per_check(db): 

122 # every check appends - the log is append-only, not deduplicated per (user, feature) 

123 _record_feature_usage(1, "my_feature", FeatureResult(value="first", source="force")) 

124 _record_feature_usage(1, "my_feature", FeatureResult(value="second", source="force")) 

125 

126 with session_scope() as session: 

127 rows = _get_usage(session, 1) 

128 assert len(rows) == 2 

129 assert [row.value for row in rows] == ["first", "second"] 

130 

131 

132def test_record_feature_usage_records_each_user_and_feature(db): 

133 _record_feature_usage(1, "feature_a", FeatureResult(value=1, source="force")) 

134 _record_feature_usage(1, "feature_b", FeatureResult(value=2, source="force")) 

135 _record_feature_usage(2, "feature_a", FeatureResult(value=3, source="force")) 

136 

137 with session_scope() as session: 

138 assert {row.feature_key for row in _get_usage(session, 1)} == {"feature_a", "feature_b"} 

139 assert len(_get_usage(session, 2)) == 1 

140 

141 

142def test_record_feature_usage_none_value(db): 

143 # unknown features evaluate to a None value - must persist without violating NOT NULL 

144 _record_feature_usage(1, "unknown_feature", FeatureResult(value=None, source="unknownFeature")) 

145 

146 with session_scope() as session: 

147 rows = _get_usage(session, 1) 

148 assert len(rows) == 1 

149 assert rows[0].value is None 

150 

151 

152def test_global_evaluation_excluded_from_rollout_gets_feature_default(feature_flags: FeatureFlags): 

153 # global (no-user) evaluation can't bucket into a rollout, so it gets the feature default 

154 feature_flags.set_definition("rollout_flag", _ROLLOUT_FLAG) 

155 assert experimentation.get_global_string_value("rollout_flag", "fallback") == "control" 

156 

157 

158def test_global_evaluation_gets_global_force_on_flag(feature_flags: FeatureFlags): 

159 feature_flags.set_definition("global_flag", _GLOBAL_FORCE_FLAG) 

160 assert experimentation.get_global_boolean_value("global_flag", default=False) is True 

161 

162 

163def test_global_evaluation_unknown_feature_returns_in_code_default(feature_flags: FeatureFlags): 

164 assert experimentation.get_global_string_value("does_not_exist", "my_default") == "my_default" 

165 

166 

167def test_evaluation_increments_metric_with_source_and_value(feature_flags: FeatureFlags): 

168 feature_flags.set("metric_flag", "yes") 

169 before = _flag_eval_count("metric_flag", "defaultValue", "yes") 

170 assert experimentation.get_global_string_value("metric_flag", "no") == "yes" 

171 assert _flag_eval_count("metric_flag", "defaultValue", "yes") == before + 1 

172 

173 

174def test_unknown_feature_increments_metric_with_unknown_source(feature_flags: FeatureFlags): 

175 before = _flag_eval_count("metric_unknown_flag", "unknownFeature", "fallback") 

176 assert experimentation.get_global_string_value("metric_unknown_flag", "fallback") == "fallback" 

177 assert _flag_eval_count("metric_unknown_flag", "unknownFeature", "fallback") == before + 1 

178 

179 

180@pytest.fixture 

181def setup_isolation(monkeypatch, tmp_path): 

182 """Run setup_experimentation() against a clean module state and a tmp cache path, and make sure the 

183 background refresh thread it starts is stopped afterwards.""" 

184 monkeypatch.setattr(experimentation, "_initialized", False) 

185 monkeypatch.setattr(experimentation, "_last_fetch_time", None) 

186 monkeypatch.setattr(experimentation, "_state", {"features": {}, "savedGroups": {}}) 

187 monkeypatch.setitem(config, "FEATURE_FLAGS_FILE_OVERRIDE_PATH", "") 

188 monkeypatch.setitem(config, "GROWTHBOOK_CACHE_PATH", str(tmp_path / "cache.json")) 

189 yield tmp_path / "cache.json" 

190 experimentation._refresh_stop.set() 

191 if experimentation._refresh_thread is not None: 

192 experimentation._refresh_thread.join(timeout=5) 

193 experimentation._refresh_stop.clear() 

194 experimentation._refresh_thread = None 

195 

196 

197def test_setup_writes_cache_and_records_fetch_time(setup_isolation, monkeypatch): 

198 cache = setup_isolation 

199 payload = {"features": {"f": {"defaultValue": True}}, "savedGroups": {}} 

200 monkeypatch.setattr(experimentation, "_fetch_features", lambda: payload) 

201 

202 setup_experimentation() 

203 

204 assert experimentation._state["features"] == {"f": {"defaultValue": True}} 

205 assert experimentation.seconds_since_last_fetch() is not None 

206 written = json.loads(cache.read_text()) 

207 assert written["response"] == payload 

208 assert "fetched_at" in written 

209 

210 

211def test_setup_falls_back_to_disk_cache_when_fetch_fails(setup_isolation, monkeypatch): 

212 cache = setup_isolation 

213 cached_payload = {"features": {"cached": {"defaultValue": "x"}}, "savedGroups": {}} 

214 cache.write_text(json.dumps({"fetched_at": 1000.0, "response": cached_payload})) 

215 monkeypatch.setattr(experimentation, "_fetch_features", lambda: None) 

216 

217 setup_experimentation() 

218 

219 assert experimentation._state["features"] == {"cached": {"defaultValue": "x"}} 

220 # fetch time reflects the cached pull time, so staleness is large immediately 

221 staleness = experimentation.seconds_since_last_fetch() 

222 assert staleness is not None and staleness > 0 

223 

224 

225def test_setup_raises_when_fetch_fails_and_no_cache(setup_isolation, monkeypatch): 

226 monkeypatch.setattr(experimentation, "_fetch_features", lambda: None) 

227 

228 with pytest.raises(GrowthBookUnavailableError): 

229 setup_experimentation() 

230 

231 

232def test_setup_raises_on_corrupt_cache(setup_isolation, monkeypatch): 

233 cache = setup_isolation 

234 cache.write_text("this is not json") 

235 monkeypatch.setattr(experimentation, "_fetch_features", lambda: None) 

236 

237 with pytest.raises(json.JSONDecodeError): 

238 setup_experimentation() 

239 

240 

241def test_seconds_since_last_fetch_none_when_never_fetched(setup_isolation): 

242 assert experimentation.seconds_since_last_fetch() is None 

243 

244 

245def test_flags_value_returned(flags: Flags): 

246 flags.set_string("my_flag", "from_file") 

247 context = make_logged_out_context(LocalizationContext.en_utc()) 

248 assert context.get_string_value("my_flag", "fallback") == "from_file" 

249 

250 

251def test_flags_missing_key_returns_in_code_default(flags: Flags): 

252 context = make_logged_out_context(LocalizationContext.en_utc()) 

253 assert context.get_string_value("missing_flag", "fallback") == "fallback" 

254 

255 

256def test_flags_boolean_value(flags: Flags): 

257 flags.set_boolean("bool_flag", False) 

258 context = make_logged_out_context(LocalizationContext.en_utc()) 

259 assert context.get_boolean_value("bool_flag", default=True) is False 

260 

261 

262def test_load_local_flags_from_file(tmp_path): 

263 path = tmp_path / "flags.json" 

264 path.write_text(json.dumps({"flag_a": True, "flag_b": "hello", "flag_c": 42})) 

265 assert _load_local_flags(str(path)) == {"flag_a": True, "flag_b": "hello", "flag_c": 42} 

266 

267 

268def test_load_local_flags_rejects_non_object(tmp_path): 

269 path = tmp_path / "flags.json" 

270 path.write_text(json.dumps(["not", "an", "object"])) 

271 with pytest.raises(ValueError, match="must contain a JSON object"): 

272 _load_local_flags(str(path)) 

273 

274 

275def test_setup_in_local_file_mode_loads_file_and_skips_growthbook(monkeypatch, tmp_path): 

276 path = tmp_path / "flags.json" 

277 path.write_text(json.dumps({"flag_x": "from_file"})) 

278 monkeypatch.setattr(experimentation, "_initialized", False) 

279 monkeypatch.setitem(config, "FEATURE_FLAGS_FILE_OVERRIDE_PATH", str(path)) 

280 # If GrowthBook were touched, this would blow up. 

281 monkeypatch.setattr(experimentation, "_fetch_features", lambda: pytest.fail("GrowthBook should not be touched")) 

282 

283 setup_experimentation() 

284 

285 assert _load_local_flags(str(path)) == {"flag_x": "from_file"} 

286 assert experimentation._refresh_thread is None