flagcov 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- flagcov/__init__.py +9 -0
- flagcov/analyze.py +395 -0
- flagcov/cli.py +115 -0
- flagcov/environment.py +72 -0
- flagcov/override.py +76 -0
- flagcov/pytest_plugin.py +136 -0
- flagcov/recorder.py +184 -0
- flagcov/report.py +201 -0
- flagcov/scan.py +104 -0
- flagcov-0.1.0.dist-info/METADATA +248 -0
- flagcov-0.1.0.dist-info/RECORD +14 -0
- flagcov-0.1.0.dist-info/WHEEL +4 -0
- flagcov-0.1.0.dist-info/entry_points.txt +5 -0
- flagcov-0.1.0.dist-info/licenses/LICENSE +21 -0
flagcov/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""FlagCov: code coverage for feature flags."""
|
|
2
|
+
|
|
3
|
+
from flagcov.analyze import Report, analyze
|
|
4
|
+
from flagcov.environment import load_document
|
|
5
|
+
from flagcov.override import OFF
|
|
6
|
+
from flagcov.recorder import Record, recorder
|
|
7
|
+
|
|
8
|
+
__all__ = ["OFF", "Record", "Report", "analyze", "load_document", "recorder"]
|
|
9
|
+
__version__ = "0.1.0"
|
flagcov/analyze.py
ADDED
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
"""Compare what the tests evaluated with what Flagsmith serves in production."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Any, Iterable
|
|
7
|
+
|
|
8
|
+
from flagcov.recorder import Record
|
|
9
|
+
|
|
10
|
+
OPERATORS = {
|
|
11
|
+
"EQUAL": "==",
|
|
12
|
+
"NOT_EQUAL": "!=",
|
|
13
|
+
"GREATER_THAN": ">",
|
|
14
|
+
"GREATER_THAN_INCLUSIVE": ">=",
|
|
15
|
+
"LESS_THAN": "<",
|
|
16
|
+
"LESS_THAN_INCLUSIVE": "<=",
|
|
17
|
+
"CONTAINS": "contains",
|
|
18
|
+
"NOT_CONTAINS": "does not contain",
|
|
19
|
+
"REGEX": "matches",
|
|
20
|
+
"IN": "in",
|
|
21
|
+
"IS_SET": "is set",
|
|
22
|
+
"IS_NOT_SET": "is not set",
|
|
23
|
+
"MODULO": "mod",
|
|
24
|
+
"PERCENTAGE_SPLIT": "% split",
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class FlagState:
|
|
30
|
+
flag: str
|
|
31
|
+
kind: str # default | variant | segment | identity | kill_switch
|
|
32
|
+
enabled: bool
|
|
33
|
+
value: Any
|
|
34
|
+
weight: float | None = None # share of production traffic, in percent
|
|
35
|
+
variant_key: str | None = None
|
|
36
|
+
segment: str | None = None
|
|
37
|
+
rule: str | None = None
|
|
38
|
+
identifier: str | None = None
|
|
39
|
+
covered: bool = False
|
|
40
|
+
hits: int = 0
|
|
41
|
+
tests: list[str] = field(default_factory=list)
|
|
42
|
+
targeting_verified: bool | None = None
|
|
43
|
+
|
|
44
|
+
stale: bool = False # no scanned code reads this flag, so there is no code path to test
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def required(self) -> bool:
|
|
48
|
+
return self.kind != "kill_switch" and not self.stale
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def label(self) -> str:
|
|
52
|
+
if self.kind == "kill_switch":
|
|
53
|
+
return "off (kill switch)"
|
|
54
|
+
if not self.enabled:
|
|
55
|
+
return "off"
|
|
56
|
+
if self.value is None:
|
|
57
|
+
return "on"
|
|
58
|
+
return _display(self.value)
|
|
59
|
+
|
|
60
|
+
@property
|
|
61
|
+
def where(self) -> str:
|
|
62
|
+
if self.kind == "segment":
|
|
63
|
+
return f'segment "{self.segment}" ({self.rule})'
|
|
64
|
+
if self.kind == "identity":
|
|
65
|
+
return f'identity override "{self.identifier}"'
|
|
66
|
+
if self.kind == "kill_switch":
|
|
67
|
+
return "used when someone turns the flag off"
|
|
68
|
+
return f"{_pct(self.weight)} of prod traffic"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class FlagSummary:
|
|
73
|
+
flag: str
|
|
74
|
+
evaluated: bool
|
|
75
|
+
states: list[FlagState]
|
|
76
|
+
stale: bool = False
|
|
77
|
+
|
|
78
|
+
@property
|
|
79
|
+
def untested_traffic(self) -> float:
|
|
80
|
+
"""Percent of this flag's default population that lands on an untested state."""
|
|
81
|
+
if self.stale:
|
|
82
|
+
return 0.0
|
|
83
|
+
population = [s for s in self.states if s.kind in ("default", "variant") and s.weight is not None]
|
|
84
|
+
return sum(s.weight or 0 for s in population if not s.covered)
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def untested_rules(self) -> list[FlagState]:
|
|
88
|
+
return [s for s in self.states if s.kind in ("segment", "identity") and not s.covered]
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@dataclass
|
|
92
|
+
class Report:
|
|
93
|
+
flags: list[FlagSummary]
|
|
94
|
+
environment: str = ""
|
|
95
|
+
unknown_flags: dict[str, list[str]] = field(default_factory=dict) # read in code, missing in Flagsmith
|
|
96
|
+
unreferenced_flags: list[str] = field(default_factory=list) # in Flagsmith, never read in code
|
|
97
|
+
records: int = 0
|
|
98
|
+
|
|
99
|
+
@property
|
|
100
|
+
def states(self) -> list[FlagState]:
|
|
101
|
+
return [s for f in self.flags for s in f.states]
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def required_states(self) -> list[FlagState]:
|
|
105
|
+
return [s for s in self.states if s.required]
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def state_coverage(self) -> float:
|
|
109
|
+
req = self.required_states
|
|
110
|
+
return 100.0 if not req else 100.0 * sum(s.covered for s in req) / len(req)
|
|
111
|
+
|
|
112
|
+
@property
|
|
113
|
+
def live_flags(self) -> list[FlagSummary]:
|
|
114
|
+
return [f for f in self.flags if not f.stale]
|
|
115
|
+
|
|
116
|
+
@property
|
|
117
|
+
def fully_tested(self) -> list[FlagSummary]:
|
|
118
|
+
return [f for f in self.live_flags if f.untested_traffic == 0 and not f.untested_rules]
|
|
119
|
+
|
|
120
|
+
@property
|
|
121
|
+
def untested_traffic(self) -> float:
|
|
122
|
+
"""Worst case: the largest share of one flag's production traffic that hits untested code."""
|
|
123
|
+
return max((f.untested_traffic for f in self.live_flags), default=0.0)
|
|
124
|
+
|
|
125
|
+
@property
|
|
126
|
+
def worst_flag(self) -> FlagSummary | None:
|
|
127
|
+
return max(self.flags, key=lambda f: f.untested_traffic, default=None)
|
|
128
|
+
|
|
129
|
+
@property
|
|
130
|
+
def never_evaluated(self) -> list[str]:
|
|
131
|
+
return [f.flag for f in self.flags if not f.evaluated]
|
|
132
|
+
|
|
133
|
+
def to_dict(self) -> dict[str, Any]:
|
|
134
|
+
return {
|
|
135
|
+
"environment": self.environment,
|
|
136
|
+
"records": self.records,
|
|
137
|
+
"state_coverage": round(self.state_coverage, 2),
|
|
138
|
+
"untested_traffic": round(self.untested_traffic, 2),
|
|
139
|
+
"fully_tested_flags": len(self.fully_tested),
|
|
140
|
+
"live_flags": len(self.live_flags),
|
|
141
|
+
"never_evaluated": self.never_evaluated,
|
|
142
|
+
"unknown_flags": self.unknown_flags,
|
|
143
|
+
"unreferenced_flags": self.unreferenced_flags,
|
|
144
|
+
"flags": [
|
|
145
|
+
{
|
|
146
|
+
"flag": f.flag,
|
|
147
|
+
"evaluated": f.evaluated,
|
|
148
|
+
"untested_traffic": f.untested_traffic,
|
|
149
|
+
"states": [
|
|
150
|
+
{
|
|
151
|
+
"kind": s.kind,
|
|
152
|
+
"label": s.label,
|
|
153
|
+
"where": s.where,
|
|
154
|
+
"enabled": s.enabled,
|
|
155
|
+
"value": s.value,
|
|
156
|
+
"weight": s.weight,
|
|
157
|
+
"segment": s.segment,
|
|
158
|
+
"rule": s.rule,
|
|
159
|
+
"identifier": s.identifier,
|
|
160
|
+
"covered": s.covered,
|
|
161
|
+
"hits": s.hits,
|
|
162
|
+
"tests": s.tests[:5],
|
|
163
|
+
"targeting_verified": s.targeting_verified,
|
|
164
|
+
}
|
|
165
|
+
for s in f.states
|
|
166
|
+
],
|
|
167
|
+
}
|
|
168
|
+
for f in self.flags
|
|
169
|
+
],
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
# --------------------------------------------------------------------------- states
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def extract_states(doc: dict[str, Any]) -> dict[str, list[FlagState]]:
|
|
177
|
+
"""Every flag state production can serve, from an environment document."""
|
|
178
|
+
states: dict[str, list[FlagState]] = {}
|
|
179
|
+
|
|
180
|
+
for fs in doc.get("feature_states", []):
|
|
181
|
+
name = fs["feature"]["name"]
|
|
182
|
+
enabled = bool(fs.get("enabled"))
|
|
183
|
+
variants = fs.get("multivariate_feature_state_values") or []
|
|
184
|
+
flag_states = states.setdefault(name, [])
|
|
185
|
+
if enabled and variants:
|
|
186
|
+
control = max(0.0, 100.0 - sum(float(v.get("percentage_allocation") or 0) for v in variants))
|
|
187
|
+
flag_states.append(FlagState(name, "default", True, fs.get("feature_state_value"), weight=control, variant_key="control"))
|
|
188
|
+
for v in sorted(variants, key=lambda v: v.get("id") or 0):
|
|
189
|
+
option = v.get("multivariate_feature_option") or {}
|
|
190
|
+
flag_states.append(
|
|
191
|
+
FlagState(
|
|
192
|
+
name,
|
|
193
|
+
"variant",
|
|
194
|
+
True,
|
|
195
|
+
option.get("value"),
|
|
196
|
+
weight=float(v.get("percentage_allocation") or 0),
|
|
197
|
+
variant_key=option.get("key"),
|
|
198
|
+
)
|
|
199
|
+
)
|
|
200
|
+
else:
|
|
201
|
+
flag_states.append(FlagState(name, "default", enabled, fs.get("feature_state_value"), weight=100.0))
|
|
202
|
+
if enabled:
|
|
203
|
+
flag_states.append(FlagState(name, "kill_switch", False, None))
|
|
204
|
+
|
|
205
|
+
for segment in (doc.get("project") or {}).get("segments", []):
|
|
206
|
+
rule = describe_rules(segment.get("rules") or [])
|
|
207
|
+
for fs in segment.get("feature_states") or []:
|
|
208
|
+
name = fs["feature"]["name"]
|
|
209
|
+
states.setdefault(name, []).append(
|
|
210
|
+
FlagState(name, "segment", bool(fs.get("enabled")), fs.get("feature_state_value"), segment=segment.get("name"), rule=rule)
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
for override in doc.get("identity_overrides") or []:
|
|
214
|
+
for fs in override.get("identity_features") or []:
|
|
215
|
+
name = fs["feature"]["name"]
|
|
216
|
+
states.setdefault(name, []).append(
|
|
217
|
+
FlagState(name, "identity", bool(fs.get("enabled")), fs.get("feature_state_value"), identifier=override.get("identifier"))
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
for name, flag_states in states.items():
|
|
221
|
+
states[name] = _dedupe(flag_states)
|
|
222
|
+
return states
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _dedupe(flag_states: list[FlagState]) -> list[FlagState]:
|
|
226
|
+
seen: set[tuple[Any, ...]] = set()
|
|
227
|
+
out = []
|
|
228
|
+
for s in flag_states:
|
|
229
|
+
key = (s.kind, s.enabled, _norm(s.value), s.segment, s.identifier, s.variant_key)
|
|
230
|
+
if key not in seen:
|
|
231
|
+
seen.add(key)
|
|
232
|
+
out.append(s)
|
|
233
|
+
return out
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def describe_rules(rules: list[dict[str, Any]]) -> str:
|
|
237
|
+
parts = [_describe_rule(r) for r in rules]
|
|
238
|
+
parts = [p for p in parts if p]
|
|
239
|
+
return " AND ".join(parts) if parts else "always"
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _describe_rule(rule: dict[str, Any]) -> str:
|
|
243
|
+
items = [_describe_condition(c) for c in rule.get("conditions") or []]
|
|
244
|
+
items += [f"({x})" if " " in x and ("AND" in x or "OR" in x) else x for x in (_describe_rule(r) for r in rule.get("rules") or []) if x]
|
|
245
|
+
if not items:
|
|
246
|
+
return ""
|
|
247
|
+
rule_type = (rule.get("type") or "ALL").upper()
|
|
248
|
+
if rule_type == "ANY":
|
|
249
|
+
return " OR ".join(items)
|
|
250
|
+
if rule_type == "NONE":
|
|
251
|
+
return "NOT (" + " OR ".join(items) + ")"
|
|
252
|
+
return " AND ".join(items)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _describe_condition(condition: dict[str, Any]) -> str:
|
|
256
|
+
prop = condition.get("property_") or condition.get("property") or "?"
|
|
257
|
+
op = condition.get("operator") or "EQUAL"
|
|
258
|
+
value = condition.get("value")
|
|
259
|
+
symbol = OPERATORS.get(op, op.lower())
|
|
260
|
+
if op in ("IS_SET", "IS_NOT_SET"):
|
|
261
|
+
return f"{prop} {symbol}"
|
|
262
|
+
if op == "PERCENTAGE_SPLIT":
|
|
263
|
+
return f"{value}% of identities"
|
|
264
|
+
return f"{prop} {symbol} {value}"
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
# --------------------------------------------------------------------------- matching
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _norm(value: Any) -> str:
|
|
271
|
+
if isinstance(value, bool):
|
|
272
|
+
return "true" if value else "false"
|
|
273
|
+
if value is None:
|
|
274
|
+
return "null"
|
|
275
|
+
if isinstance(value, float) and value.is_integer():
|
|
276
|
+
return str(int(value))
|
|
277
|
+
return str(value)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def matches(state: FlagState, record: Record) -> bool:
|
|
281
|
+
"""Did this evaluation exercise the code path behind this flag state?"""
|
|
282
|
+
if record.flag != state.flag:
|
|
283
|
+
return False
|
|
284
|
+
if record.value_type == "boolean":
|
|
285
|
+
if state.kind == "kill_switch" or not state.enabled:
|
|
286
|
+
return record.value is False
|
|
287
|
+
# A boolean read only tells us the flag was on, not which variant was served,
|
|
288
|
+
# so it covers simple on/off flags but never a multivariate value.
|
|
289
|
+
return record.value is True and state.kind == "default" and state.weight == 100.0
|
|
290
|
+
if state.kind == "kill_switch" or not state.enabled:
|
|
291
|
+
# Disabled flags fall back to the default value written in the code.
|
|
292
|
+
return record.reason == "DISABLED" or (
|
|
293
|
+
record.default_value is not None and _norm(record.value) == _norm(record.default_value) and record.variant in (None, "")
|
|
294
|
+
and record.source != "flagsmith"
|
|
295
|
+
)
|
|
296
|
+
if state.kind == "identity" and record.targeting_key != state.identifier:
|
|
297
|
+
return False
|
|
298
|
+
return _norm(record.value) == _norm(state.value)
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
class _SegmentMatcher:
|
|
302
|
+
"""Uses Flagsmith's own engine (when installed) to check segment targeting."""
|
|
303
|
+
|
|
304
|
+
def __init__(self, doc: dict[str, Any]) -> None:
|
|
305
|
+
self._context = None
|
|
306
|
+
self._cache: dict[tuple[Any, ...], set[str]] = {}
|
|
307
|
+
try:
|
|
308
|
+
from flag_engine.engine import get_evaluation_result # noqa: F401
|
|
309
|
+
from flagsmith.mappers import map_environment_document_to_context
|
|
310
|
+
|
|
311
|
+
self._context = map_environment_document_to_context(doc) # type: ignore[arg-type]
|
|
312
|
+
except Exception: # noqa: BLE001 - engine missing or document too old/new: targeting stays unknown
|
|
313
|
+
self._context = None
|
|
314
|
+
|
|
315
|
+
@property
|
|
316
|
+
def available(self) -> bool:
|
|
317
|
+
return self._context is not None
|
|
318
|
+
|
|
319
|
+
def segments_for(self, record: Record) -> set[str] | None:
|
|
320
|
+
if self._context is None or not (record.targeting_key or record.traits):
|
|
321
|
+
return None
|
|
322
|
+
key = (record.targeting_key, tuple(sorted((k, _norm(v)) for k, v in record.traits.items())))
|
|
323
|
+
if key not in self._cache:
|
|
324
|
+
from flag_engine.engine import get_evaluation_result
|
|
325
|
+
|
|
326
|
+
context = {
|
|
327
|
+
**self._context,
|
|
328
|
+
"identity": {"identifier": record.targeting_key or "flagcov-anonymous", "traits": dict(record.traits)},
|
|
329
|
+
}
|
|
330
|
+
try:
|
|
331
|
+
result = get_evaluation_result(context) # type: ignore[arg-type]
|
|
332
|
+
self._cache[key] = {s["name"] for s in result.get("segments", [])}
|
|
333
|
+
except Exception: # noqa: BLE001
|
|
334
|
+
self._cache[key] = set()
|
|
335
|
+
return self._cache[key]
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def analyze(
|
|
339
|
+
doc: dict[str, Any],
|
|
340
|
+
records: Iterable[Record],
|
|
341
|
+
referenced_flags: dict[str, list[str]] | None = None,
|
|
342
|
+
) -> Report:
|
|
343
|
+
"""Build a coverage report.
|
|
344
|
+
|
|
345
|
+
``referenced_flags`` (optional, from :mod:`flagcov.scan`) maps flag keys found
|
|
346
|
+
in source code to their locations; it enables the unknown/unreferenced checks.
|
|
347
|
+
"""
|
|
348
|
+
records = list(records)
|
|
349
|
+
by_flag: dict[str, list[Record]] = {}
|
|
350
|
+
for r in records:
|
|
351
|
+
by_flag.setdefault(r.flag, []).append(r)
|
|
352
|
+
|
|
353
|
+
matcher = _SegmentMatcher(doc)
|
|
354
|
+
summaries = []
|
|
355
|
+
for name, flag_states in sorted(extract_states(doc).items()):
|
|
356
|
+
flag_records = by_flag.get(name, [])
|
|
357
|
+
for state in flag_states:
|
|
358
|
+
for r in flag_records:
|
|
359
|
+
if matches(state, r):
|
|
360
|
+
state.covered = True
|
|
361
|
+
state.hits += 1
|
|
362
|
+
if r.test and r.test not in state.tests:
|
|
363
|
+
state.tests.append(r.test)
|
|
364
|
+
if state.kind == "segment" and matcher.available:
|
|
365
|
+
verified = False
|
|
366
|
+
for r in flag_records:
|
|
367
|
+
segs = matcher.segments_for(r)
|
|
368
|
+
if segs and state.segment in segs:
|
|
369
|
+
verified = True
|
|
370
|
+
break
|
|
371
|
+
state.targeting_verified = verified
|
|
372
|
+
summaries.append(FlagSummary(name, evaluated=bool(flag_records), states=flag_states))
|
|
373
|
+
|
|
374
|
+
report = Report(flags=summaries, environment=str(doc.get("name") or ""), records=len(records))
|
|
375
|
+
if referenced_flags is not None:
|
|
376
|
+
known = {f.flag for f in summaries}
|
|
377
|
+
report.unknown_flags = {k: v for k, v in sorted(referenced_flags.items()) if k not in known}
|
|
378
|
+
report.unreferenced_flags = sorted(known - set(referenced_flags))
|
|
379
|
+
for f in summaries:
|
|
380
|
+
if f.flag in report.unreferenced_flags and not f.evaluated:
|
|
381
|
+
f.stale = True
|
|
382
|
+
for s in f.states:
|
|
383
|
+
s.stale = True
|
|
384
|
+
return report
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def _display(value: Any) -> str:
|
|
388
|
+
text = _norm(value)
|
|
389
|
+
return text if len(text) <= 24 else text[:21] + "..."
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def _pct(value: float | None) -> str:
|
|
393
|
+
if value is None:
|
|
394
|
+
return "-"
|
|
395
|
+
return f"{value:.0f}%" if float(value).is_integer() else f"{value:.1f}%"
|
flagcov/cli.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""``flagcov`` command line.
|
|
2
|
+
|
|
3
|
+
flagcov fetch --api-url http://localhost:8000/api/v1/ --key ser.xxx -o environment.json
|
|
4
|
+
flagcov report --env environment.json [--evaluations .flagcov/evaluations.json] [--scan src] [--format table|md|json]
|
|
5
|
+
flagcov scan src/
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import json
|
|
12
|
+
import sys
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from flagcov import __version__
|
|
16
|
+
from flagcov.analyze import analyze
|
|
17
|
+
from flagcov.environment import EnvironmentError_, load_document
|
|
18
|
+
from flagcov.recorder import Recorder
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _report(args: argparse.Namespace) -> int:
|
|
22
|
+
doc = load_document(args.env, args.key, args.api_url)
|
|
23
|
+
evaluations = Path(args.evaluations)
|
|
24
|
+
records = Recorder.load(evaluations) if evaluations.is_file() else []
|
|
25
|
+
referenced = None
|
|
26
|
+
if args.scan:
|
|
27
|
+
from flagcov.scan import scan_paths
|
|
28
|
+
|
|
29
|
+
referenced = scan_paths(args.scan)
|
|
30
|
+
report = analyze(doc, records, referenced)
|
|
31
|
+
from flagcov import report as render
|
|
32
|
+
|
|
33
|
+
changed = set(args.only_flags.split(",")) if args.only_flags else None
|
|
34
|
+
if args.diff_base:
|
|
35
|
+
from flagcov.scan import changed_flags
|
|
36
|
+
|
|
37
|
+
changed = (changed or set()) | changed_flags(args.diff_base)
|
|
38
|
+
if args.out:
|
|
39
|
+
render.write_all(report, args.out)
|
|
40
|
+
if args.format == "md":
|
|
41
|
+
print(render.markdown(report, changed))
|
|
42
|
+
elif args.format == "json":
|
|
43
|
+
print(json.dumps(report.to_dict(), indent=2, default=str))
|
|
44
|
+
elif args.format == "stubs":
|
|
45
|
+
print(render.stubs(report, changed))
|
|
46
|
+
else:
|
|
47
|
+
print(render.terminal(report, show_covered=not args.untested_only))
|
|
48
|
+
if args.fail_untested is not None and report.untested_traffic > args.fail_untested:
|
|
49
|
+
print(f"FAIL: untested production traffic {report.untested_traffic:.1f}% > {args.fail_untested}%", file=sys.stderr)
|
|
50
|
+
return 2
|
|
51
|
+
return 0
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _fetch(args: argparse.Namespace) -> int:
|
|
55
|
+
doc = load_document(None, args.key, args.api_url)
|
|
56
|
+
Path(args.output).write_text(json.dumps(doc, indent=2), encoding="utf-8")
|
|
57
|
+
print(f"Saved environment document '{doc.get('name', '')}' ({len(doc['feature_states'])} flags) to {args.output}")
|
|
58
|
+
return 0
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _scan(args: argparse.Namespace) -> int:
|
|
62
|
+
from flagcov.scan import scan_paths
|
|
63
|
+
|
|
64
|
+
refs = scan_paths(args.paths)
|
|
65
|
+
if args.json:
|
|
66
|
+
print(json.dumps(refs, indent=2))
|
|
67
|
+
else:
|
|
68
|
+
for key, where in refs.items():
|
|
69
|
+
print(f"{key} ({len(where)}x) {where[0]}")
|
|
70
|
+
print(f"\n{len(refs)} flag keys found")
|
|
71
|
+
return 0
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def main(argv: list[str] | None = None) -> int:
|
|
75
|
+
parser = argparse.ArgumentParser(prog="flagcov", description="Code coverage for feature flags (Flagsmith).")
|
|
76
|
+
parser.add_argument("--version", action="version", version=f"flagcov {__version__}")
|
|
77
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
78
|
+
|
|
79
|
+
def env_args(p: argparse.ArgumentParser) -> None:
|
|
80
|
+
p.add_argument("--key", help="Server-side environment key (or FLAGSMITH_SERVER_KEY)")
|
|
81
|
+
p.add_argument("--api-url", help="Flagsmith API URL, e.g. http://localhost:8000/api/v1/ (or FLAGSMITH_API_URL)")
|
|
82
|
+
|
|
83
|
+
r = sub.add_parser("report", help="Report flag coverage from recorded evaluations")
|
|
84
|
+
r.add_argument("--env", help="Environment document JSON file (omit to fetch from the API)")
|
|
85
|
+
env_args(r)
|
|
86
|
+
r.add_argument("--evaluations", default=".flagcov/evaluations.json")
|
|
87
|
+
r.add_argument("--scan", action="append", help="Source path to scan for flag keys (repeatable)")
|
|
88
|
+
r.add_argument("--format", choices=["table", "md", "json", "stubs"], default="table")
|
|
89
|
+
r.add_argument("--only-flags", help="Comma-separated flags to focus on (e.g. flags touched by a PR)")
|
|
90
|
+
r.add_argument("--diff-base", help="Focus on flags touched since this git ref (e.g. origin/main)")
|
|
91
|
+
r.add_argument("--untested-only", action="store_true")
|
|
92
|
+
r.add_argument("--out", help="Also write report.json, report.md, badge.svg and stubs here")
|
|
93
|
+
r.add_argument("--fail-untested", type=float, help="Exit 2 if untested production traffic is above this percent")
|
|
94
|
+
r.set_defaults(func=_report)
|
|
95
|
+
|
|
96
|
+
f = sub.add_parser("fetch", help="Download the environment document from Flagsmith")
|
|
97
|
+
env_args(f)
|
|
98
|
+
f.add_argument("-o", "--output", default="environment.json")
|
|
99
|
+
f.set_defaults(func=_fetch)
|
|
100
|
+
|
|
101
|
+
s = sub.add_parser("scan", help="List flag keys read in source code")
|
|
102
|
+
s.add_argument("paths", nargs="+")
|
|
103
|
+
s.add_argument("--json", action="store_true")
|
|
104
|
+
s.set_defaults(func=_scan)
|
|
105
|
+
|
|
106
|
+
args = parser.parse_args(argv)
|
|
107
|
+
try:
|
|
108
|
+
return args.func(args)
|
|
109
|
+
except EnvironmentError_ as exc:
|
|
110
|
+
print(f"flagcov: {exc}", file=sys.stderr)
|
|
111
|
+
return 1
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
if __name__ == "__main__": # pragma: no cover
|
|
115
|
+
sys.exit(main())
|
flagcov/environment.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Load a Flagsmith environment document from a file or a (self-hosted) Flagsmith API.
|
|
2
|
+
|
|
3
|
+
The environment document is what Flagsmith's server-side SDKs use for local
|
|
4
|
+
evaluation. It holds every flag's live state, multivariate weights, segment
|
|
5
|
+
rules, segment overrides and identity overrides, which is all FlagCov needs.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import urllib.error
|
|
13
|
+
import urllib.request
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
DEFAULT_API_URL = "https://edge.api.flagsmith.com/api/v1/"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class EnvironmentError_(RuntimeError):
|
|
21
|
+
"""Raised when the environment document cannot be loaded."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def fetch_document(server_key: str, api_url: str = DEFAULT_API_URL, timeout: float = 15) -> dict[str, Any]:
|
|
25
|
+
"""Fetch the environment document with a server-side environment key.
|
|
26
|
+
|
|
27
|
+
Works against Flagsmith Cloud and self-hosted Flagsmith alike
|
|
28
|
+
(``api_url`` is e.g. ``http://localhost:8000/api/v1/``).
|
|
29
|
+
"""
|
|
30
|
+
if not server_key:
|
|
31
|
+
raise EnvironmentError_("A server-side environment key (ser.xxx) is required to fetch the document.")
|
|
32
|
+
url = api_url.rstrip("/") + "/environment-document/"
|
|
33
|
+
request = urllib.request.Request(url, headers={"X-Environment-Key": server_key, "Accept": "application/json"})
|
|
34
|
+
try:
|
|
35
|
+
with urllib.request.urlopen(request, timeout=timeout) as response: # noqa: S310 (user-supplied API URL)
|
|
36
|
+
return _validate(json.loads(response.read().decode("utf-8")), url)
|
|
37
|
+
except urllib.error.HTTPError as exc:
|
|
38
|
+
raise EnvironmentError_(f"Flagsmith returned HTTP {exc.code} for {url}. Is the key a server-side key?") from exc
|
|
39
|
+
except urllib.error.URLError as exc:
|
|
40
|
+
raise EnvironmentError_(f"Could not reach Flagsmith at {url}: {exc.reason}") from exc
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def read_document(path: str | os.PathLike[str]) -> dict[str, Any]:
|
|
44
|
+
p = Path(path)
|
|
45
|
+
if not p.is_file():
|
|
46
|
+
raise EnvironmentError_(f"Environment document not found: {p}")
|
|
47
|
+
return _validate(json.loads(p.read_text(encoding="utf-8")), str(p))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def load_document(
|
|
51
|
+
source: str | os.PathLike[str] | None = None,
|
|
52
|
+
server_key: str | None = None,
|
|
53
|
+
api_url: str | None = None,
|
|
54
|
+
) -> dict[str, Any]:
|
|
55
|
+
"""Load from a file path, or fetch from the API when ``source`` is None or a URL.
|
|
56
|
+
|
|
57
|
+
Environment variables are used as fallbacks: ``FLAGSMITH_SERVER_KEY`` (or
|
|
58
|
+
``FLAGSMITH_ENVIRONMENT_KEY``) and ``FLAGSMITH_API_URL``.
|
|
59
|
+
"""
|
|
60
|
+
if source and not str(source).startswith(("http://", "https://")):
|
|
61
|
+
return read_document(source)
|
|
62
|
+
key = server_key or os.environ.get("FLAGSMITH_SERVER_KEY") or os.environ.get("FLAGSMITH_ENVIRONMENT_KEY") or ""
|
|
63
|
+
url = str(source) if source else (api_url or os.environ.get("FLAGSMITH_API_URL") or DEFAULT_API_URL)
|
|
64
|
+
return fetch_document(key, url)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _validate(doc: Any, where: str) -> dict[str, Any]:
|
|
68
|
+
if not isinstance(doc, dict) or "feature_states" not in doc:
|
|
69
|
+
raise EnvironmentError_(f"{where} is not a Flagsmith environment document (no 'feature_states').")
|
|
70
|
+
doc.setdefault("project", {}).setdefault("segments", [])
|
|
71
|
+
doc.setdefault("identity_overrides", [])
|
|
72
|
+
return doc
|
flagcov/override.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Force a flag to a given state inside one test, through OpenFeature.
|
|
2
|
+
|
|
3
|
+
Used by the ``flag_override`` pytest fixture and by the test stubs FlagCov
|
|
4
|
+
generates. It patches the *current provider instance* for the duration of a test
|
|
5
|
+
(no provider re-registration), so it works with the Flagsmith provider,
|
|
6
|
+
OpenFeature's InMemoryProvider, or any other provider.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class _Off:
|
|
15
|
+
def __repr__(self) -> str: # pragma: no cover - cosmetic
|
|
16
|
+
return "flagcov.OFF"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
#: Pass as the value to simulate the flag being turned off (the kill-switch path).
|
|
20
|
+
OFF = _Off()
|
|
21
|
+
|
|
22
|
+
_METHODS = (
|
|
23
|
+
"resolve_boolean_details",
|
|
24
|
+
"resolve_string_details",
|
|
25
|
+
"resolve_integer_details",
|
|
26
|
+
"resolve_float_details",
|
|
27
|
+
"resolve_object_details",
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class FlagOverrides:
|
|
32
|
+
def __init__(self) -> None:
|
|
33
|
+
self._values: dict[int, dict[str, Any]] = {}
|
|
34
|
+
self._patched: list[tuple[Any, str, Any]] = []
|
|
35
|
+
|
|
36
|
+
def set(self, flag: str, value: Any, domain: str | None = None) -> None:
|
|
37
|
+
from openfeature.provider._registry import provider_registry
|
|
38
|
+
|
|
39
|
+
provider = provider_registry.get_provider(domain)
|
|
40
|
+
table = self._values.get(id(provider))
|
|
41
|
+
if table is None:
|
|
42
|
+
table = self._values[id(provider)] = {}
|
|
43
|
+
self._patch(provider, table)
|
|
44
|
+
table[flag] = value
|
|
45
|
+
|
|
46
|
+
def _patch(self, provider: Any, table: dict[str, Any]) -> None:
|
|
47
|
+
from openfeature.flag_evaluation import FlagResolutionDetails, Reason
|
|
48
|
+
|
|
49
|
+
for name in _METHODS:
|
|
50
|
+
original = getattr(provider, name, None)
|
|
51
|
+
if original is None:
|
|
52
|
+
continue
|
|
53
|
+
|
|
54
|
+
def wrapper(flag_key, default_value, evaluation_context=None, *args, _original=original, **kwargs): # noqa: ANN001, ANN202
|
|
55
|
+
if flag_key in table:
|
|
56
|
+
value = table[flag_key]
|
|
57
|
+
if value is OFF:
|
|
58
|
+
return FlagResolutionDetails(value=default_value, reason=Reason.DISABLED)
|
|
59
|
+
return FlagResolutionDetails(value=value, reason=Reason.STATIC, variant="flagcov-override")
|
|
60
|
+
return _original(flag_key, default_value, evaluation_context, *args, **kwargs)
|
|
61
|
+
|
|
62
|
+
had_own = name in vars(provider)
|
|
63
|
+
self._patched.append((provider, name, original if had_own else None))
|
|
64
|
+
setattr(provider, name, wrapper)
|
|
65
|
+
|
|
66
|
+
def restore(self) -> None:
|
|
67
|
+
for provider, name, original in reversed(self._patched):
|
|
68
|
+
if original is None:
|
|
69
|
+
try:
|
|
70
|
+
delattr(provider, name)
|
|
71
|
+
except AttributeError: # pragma: no cover
|
|
72
|
+
pass
|
|
73
|
+
else:
|
|
74
|
+
setattr(provider, name, original)
|
|
75
|
+
self._patched.clear()
|
|
76
|
+
self._values.clear()
|