ermes-cli 1.4.0__tar.gz → 1.5.1__tar.gz

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.
Files changed (74) hide show
  1. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/PKG-INFO +2 -1
  2. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/README.md +1 -0
  3. ermes_cli-1.5.1/ermes_cli/__init__.py +1 -0
  4. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/commands/campaigns.py +114 -0
  5. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/commands/export.py +9 -0
  6. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/export_utils.py +24 -0
  7. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/keyring_store.py +25 -2
  8. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/skill/SKILL.md +22 -0
  9. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/pyproject.toml +1 -1
  10. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_auth_cmds.py +29 -0
  11. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_commands/test_campaigns.py +160 -0
  12. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_commands/test_export.py +66 -0
  13. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_keyring_store.py +48 -0
  14. ermes_cli-1.4.0/ermes_cli/__init__.py +0 -1
  15. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/.gitignore +0 -0
  16. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/admin_api.py +0 -0
  17. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/auth0.py +0 -0
  18. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/client.py +0 -0
  19. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/commands/__init__.py +0 -0
  20. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/commands/auth_cmds.py +0 -0
  21. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/commands/config_cmd.py +0 -0
  22. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/commands/data_paths.py +0 -0
  23. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/commands/ingest.py +0 -0
  24. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/commands/journeys.py +0 -0
  25. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/commands/keys.py +0 -0
  26. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/commands/lists.py +0 -0
  27. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/commands/metrics.py +0 -0
  28. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/commands/projects.py +0 -0
  29. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/commands/providers.py +0 -0
  30. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/commands/skill.py +0 -0
  31. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/commands/subscriptions.py +0 -0
  32. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/commands/tags.py +0 -0
  33. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/commands/templates.py +0 -0
  34. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/commands/users.py +0 -0
  35. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/commands/write_cmds.py +0 -0
  36. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/config.py +0 -0
  37. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/errors.py +0 -0
  38. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/main.py +0 -0
  39. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/output.py +0 -0
  40. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/rules.py +0 -0
  41. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/update.py +0 -0
  42. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/ermes_cli/write_mode.py +0 -0
  43. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/scripts/install-cli.sh +0 -0
  44. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/__init__.py +0 -0
  45. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/conftest.py +0 -0
  46. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_admin_api.py +0 -0
  47. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_auth0.py +0 -0
  48. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_client.py +0 -0
  49. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_commands/__init__.py +0 -0
  50. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_commands/test_data_paths.py +0 -0
  51. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_commands/test_ingest.py +0 -0
  52. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_commands/test_journeys.py +0 -0
  53. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_commands/test_keys.py +0 -0
  54. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_commands/test_lists.py +0 -0
  55. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_commands/test_metrics.py +0 -0
  56. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_commands/test_projects.py +0 -0
  57. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_commands/test_projects_list.py +0 -0
  58. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_commands/test_providers.py +0 -0
  59. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_commands/test_subscriptions.py +0 -0
  60. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_commands/test_tags.py +0 -0
  61. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_commands/test_templates.py +0 -0
  62. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_commands/test_users.py +0 -0
  63. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_config.py +0 -0
  64. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_connection_errors.py +0 -0
  65. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_export_utils.py +0 -0
  66. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_output.py +0 -0
  67. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_projects_config.py +0 -0
  68. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_rules.py +0 -0
  69. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_skill_command.py +0 -0
  70. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_update.py +0 -0
  71. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_version.py +0 -0
  72. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_whoami.py +0 -0
  73. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_write_cmds.py +0 -0
  74. {ermes_cli-1.4.0 → ermes_cli-1.5.1}/tests/test_write_mode.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: ermes-cli
3
- Version: 1.4.0
3
+ Version: 1.5.1
4
4
  Summary: CLI-first access to Ermes marketing automation with Auth0 multi-project auth.
5
5
  Project-URL: Homepage, https://ermes.publinker.com
6
6
  Project-URL: Repository, https://github.com/Martech-DM/ermes
@@ -268,6 +268,7 @@ is legible.
268
268
  | Group | Commands |
269
269
  |---|---|
270
270
  | `campaigns` | list, get, create, update, delete, trigger (`--external-id`, optional `--email`/`--phone`/`--device-token`/`--locale`/`--timezone`) |
271
+ | `campaigns split-test` | set (`--percent`/`--window`/`--metric open\|click`), disable (`--yes`), results — A/B tests on draft blasts; `export campaigns` adds per-variant `split_test` |
271
272
  | `templates` | list, get, create, update, delete |
272
273
  | `lists` | list, get, create, update, delete |
273
274
  | `journeys` | list, get, create, update, delete |
@@ -238,6 +238,7 @@ is legible.
238
238
  | Group | Commands |
239
239
  |---|---|
240
240
  | `campaigns` | list, get, create, update, delete, trigger (`--external-id`, optional `--email`/`--phone`/`--device-token`/`--locale`/`--timezone`) |
241
+ | `campaigns split-test` | set (`--percent`/`--window`/`--metric open\|click`), disable (`--yes`), results — A/B tests on draft blasts; `export campaigns` adds per-variant `split_test` |
241
242
  | `templates` | list, get, create, update, delete |
242
243
  | `lists` | list, get, create, update, delete |
243
244
  | `journeys` | list, get, create, update, delete |
@@ -0,0 +1 @@
1
+ __version__ = "1.5.1"
@@ -319,3 +319,117 @@ def campaigns_trigger(
319
319
  except ErmesAPIError as e:
320
320
  typer.echo(str(e), err=True)
321
321
  raise typer.Exit(code=1)
322
+
323
+
324
+ split_test_app = typer.Typer(help="A/B split tests on blasts", no_args_is_help=True)
325
+ campaigns_app.add_typer(split_test_app, name="split-test")
326
+
327
+ SPLIT_TEST_DEFAULTS = {"percent": 10, "window_minutes": 60, "metric": "email_open"}
328
+ _METRICS = {"open": "email_open", "click": "email_click"}
329
+ _RESULT_COLUMNS = ["label", "template_id", "subject", "assigned", "sent", "opens", "clicks", "open_rate", "click_rate", "winner"]
330
+
331
+
332
+ @split_test_app.command("set")
333
+ def split_test_set(
334
+ campaign_id: int = typer.Argument(..., help="Blast campaign ID (must be a draft)"),
335
+ percent: Optional[int] = typer.Option(None, "--percent", min=1, max=50, help="Test group size, % of the list split between A and B (default 10)"),
336
+ window: Optional[int] = typer.Option(None, "--window", help="Minutes before the winner is picked: 30, 60, 90, 120, 150 or 180 (default 60)"),
337
+ metric: Optional[str] = typer.Option(None, "--metric", help="Winner metric: open or click (default open)"),
338
+ ):
339
+ """Enable or change a split test. Enabling creates variant A (current template) and B (a copy to edit)."""
340
+ client, st, _, _, _ = _get_deps()
341
+ if metric is not None and metric not in _METRICS:
342
+ typer.echo("--metric must be 'open' or 'click'", err=True)
343
+ raise typer.Exit(code=1)
344
+ if window is not None and window not in (30, 60, 90, 120, 150, 180):
345
+ typer.echo("--window must be one of 30, 60, 90, 120, 150, 180", err=True)
346
+ raise typer.Exit(code=1)
347
+ try:
348
+ campaign = client.get(f"/campaigns/{campaign_id}")
349
+ if campaign.get("type") != "blast":
350
+ typer.echo(f"Split tests run on blasts only; campaign {campaign_id} is a {campaign.get('type')}.", err=True)
351
+ raise typer.Exit(code=1)
352
+ current = campaign.get("split_test_config") or {}
353
+ base = current if current.get("enabled") else SPLIT_TEST_DEFAULTS
354
+ config = {
355
+ "enabled": True,
356
+ "percent": percent if percent is not None else base["percent"],
357
+ "window_minutes": window if window is not None else base["window_minutes"],
358
+ "metric": _METRICS[metric] if metric else base["metric"],
359
+ # Server-managed: the API overwrites these from the stored row.
360
+ "picker_state": current.get("picker_state") or "pending",
361
+ "extended_once": bool(current.get("extended_once")),
362
+ }
363
+ result = client.patch(f"/campaigns/{campaign_id}", json={"split_test_config": config})
364
+ except ErmesAPIError as e:
365
+ typer.echo(str(e), err=True)
366
+ raise typer.Exit(code=1)
367
+ variants = [
368
+ {"label": v.get("label"), "variant_id": v.get("id"), "template_id": v.get("template_id")}
369
+ for v in result.get("variants") or []
370
+ ]
371
+ if st.use_json:
372
+ print(json_lib.dumps({"split_test_config": result.get("split_test_config"), "variants": variants}, indent=2))
373
+ return
374
+ cfg = result.get("split_test_config") or config
375
+ typer.echo(f"Split test on campaign {campaign_id}: {cfg['percent']}% test group, {cfg['window_minutes']} min window, winner by {cfg['metric']}.")
376
+ for v in variants:
377
+ typer.echo(f" {v['label']}: variant {v['variant_id']}, template {v['template_id']}")
378
+ b = next((v for v in variants if v["label"] == "B"), None)
379
+ if b:
380
+ typer.echo(f"Edit B with: ermes templates update {b['template_id']} --type email --data '{{...}}'")
381
+
382
+
383
+ @split_test_app.command("disable")
384
+ def split_test_disable(
385
+ campaign_id: int = typer.Argument(..., help="Blast campaign ID (must be a draft)"),
386
+ yes: bool = typer.Option(False, "--yes", help="Confirm: disabling deletes variant B and its template"),
387
+ ):
388
+ """Disable a split test. Deletes variant B and its template; A stays as the campaign template."""
389
+ client, st, _, _, render_message = _get_deps()
390
+ if not yes:
391
+ typer.echo("Disabling deletes variant B and its template (any edits to B are lost). Re-run with --yes.", err=True)
392
+ raise typer.Exit(code=1)
393
+ try:
394
+ current = client.get(f"/campaigns/{campaign_id}").get("split_test_config") or {}
395
+ if not current.get("enabled"):
396
+ render_message(f"Campaign {campaign_id} has no split test enabled.", use_json=st.use_json)
397
+ return
398
+ config = {
399
+ "enabled": False,
400
+ "percent": current["percent"],
401
+ "window_minutes": current["window_minutes"],
402
+ "metric": current["metric"],
403
+ "picker_state": current.get("picker_state") or "pending",
404
+ "extended_once": bool(current.get("extended_once")),
405
+ }
406
+ client.patch(f"/campaigns/{campaign_id}", json={"split_test_config": config})
407
+ render_message(f"Split test disabled on campaign {campaign_id}.", use_json=st.use_json)
408
+ except ErmesAPIError as e:
409
+ typer.echo(str(e), err=True)
410
+ raise typer.Exit(code=1)
411
+
412
+
413
+ @split_test_app.command("results")
414
+ def split_test_results(campaign_id: int = typer.Argument(..., help="Campaign ID")):
415
+ """Per-variant sends, opens and clicks for the test group, plus the rest of the list (sent the winner)."""
416
+ from ermes_cli.export_utils import summarize_split_test
417
+
418
+ client, st, render, _, render_message = _get_deps()
419
+ try:
420
+ summary = summarize_split_test(client.get(f"/campaigns/{campaign_id}/split-test/results"))
421
+ except ErmesAPIError as e:
422
+ typer.echo(str(e), err=True)
423
+ raise typer.Exit(code=1)
424
+ if st.use_json:
425
+ print(json_lib.dumps(summary, indent=2, default=str))
426
+ return
427
+ if not summary["enabled"]:
428
+ render_message(f"Campaign {campaign_id} has no split test enabled.", use_json=False)
429
+ return
430
+ rows = summary["variants"] + [{"label": "rest", **summary["remainder"]}]
431
+ cfg = summary["config"] or {}
432
+ title = f"{cfg.get('percent')}% test group, winner by {cfg.get('metric')} ({cfg.get('picker_state')}). Rates are % of sent."
433
+ title += ' "rest" = the rest of the list, sent the winner.'
434
+ labels = {"label": "variant", "template_id": "template", "open_rate": "open %", "click_rate": "click %"}
435
+ render(rows, columns=_RESULT_COLUMNS, use_json=False, title=title, column_labels=labels)
@@ -9,6 +9,7 @@ from ermes_cli.client import ErmesAPIError, ErmesClient
9
9
  from ermes_cli.export_utils import (
10
10
  extract_campaign_record,
11
11
  is_within_date_range,
12
+ summarize_split_test,
12
13
  )
13
14
 
14
15
  export_app = typer.Typer(
@@ -79,6 +80,14 @@ def _enrich_campaigns(
79
80
  detail = client.get(f"/campaigns/{c['id']}")
80
81
  record = extract_campaign_record(detail, project_timezone)
81
82
  if record:
83
+ # Per-variant counts cost one extra request, so only split-test blasts pay it.
84
+ if (detail.get("split_test_config") or {}).get("enabled"):
85
+ try:
86
+ results = client.get(f"/campaigns/{c['id']}/split-test/results")
87
+ record["split_test"] = summarize_split_test(results)
88
+ except ErmesAPIError as e:
89
+ # Keep the campaign row; only its per-variant block is missing.
90
+ record["split_test"] = {"error": str(e)}
82
91
  enriched.append(record)
83
92
  except ErmesAPIError:
84
93
  skipped += 1
@@ -261,3 +261,27 @@ def sanitize_filename(subject: str, date_str: str) -> str:
261
261
 
262
262
  return f"blast_{date_formatted}_{clean}.html" if clean else f"blast_{date_formatted}.html"
263
263
 
264
+
265
+ def _with_rates(counts: dict) -> dict:
266
+ sent = counts.get("sent", 0) or 0
267
+ opens = counts.get("opens", 0) or 0
268
+ clicks = counts.get("clicks", 0) or 0
269
+ return {
270
+ **counts,
271
+ "open_rate": round(opens / sent * 100, 2) if sent else 0,
272
+ "click_rate": round(clicks / sent * 100, 2) if sent else 0,
273
+ }
274
+
275
+
276
+ def summarize_split_test(results: dict) -> dict:
277
+ """Add open/click rates (percent of sent) to a split-test results payload.
278
+
279
+ `variants` are the test group only; `remainder` is the rest of the list,
280
+ sent the winner after the decision, so it never counts toward a variant.
281
+ """
282
+ return {
283
+ "enabled": results.get("enabled", False),
284
+ "config": results.get("config"),
285
+ "variants": [_with_rates(v) for v in results.get("variants", [])],
286
+ "remainder": _with_rates(results.get("remainder") or {}),
287
+ }
@@ -71,9 +71,32 @@ class TokenBundle:
71
71
  )
72
72
 
73
73
  def is_expired(self, now: int | None = None, leeway: int = 60) -> bool:
74
- """True if the access token has expired (with `leeway` seconds buffer)."""
74
+ """True if the access token OR the id_token has expired (with `leeway` seconds buffer).
75
+
76
+ The id_token counts because `/api/cli/exchange` verifies it to read the admin's
77
+ email (the access token has no email claim), and Auth0 issues it for 10h against
78
+ the access token's 24h. Checking only the access token made every admin command
79
+ fail with 1010 from hour 10 to hour 24 after login (DEV-2497).
80
+ """
75
81
  now = now if now is not None else int(time.time())
76
- return now + leeway >= self.expires_at
82
+ id_exp = _jwt_exp(self.id_token)
83
+ deadline = min(self.expires_at, id_exp) if id_exp is not None else self.expires_at
84
+ return now + leeway >= deadline
85
+
86
+
87
+ def _jwt_exp(token: str) -> int | None:
88
+ """The unverified `exp` claim of a JWT, or None if it can't be read.
89
+
90
+ Only a local "time to refresh?" hint; the server still verifies the signature.
91
+ """
92
+ try:
93
+ payload = token.split(".")[1]
94
+ exp = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))).get("exp")
95
+ # bool is an int subclass: `"exp": true` would read as epoch 1 and refresh every command.
96
+ return int(exp) if isinstance(exp, (int, float)) and not isinstance(exp, bool) else None
97
+ except (IndexError, ValueError, AttributeError, OverflowError, RecursionError):
98
+ # int(inf) -> OverflowError, int(nan) -> ValueError, deeply nested JSON -> RecursionError
99
+ return None
77
100
 
78
101
 
79
102
  @functools.cache
@@ -60,6 +60,28 @@ Commands that create, change or delete data are blocked by default. Before a wri
60
60
  4. Read the value again and show the user the result. If a write times out,
61
61
  read before retrying; it may have gone through.
62
62
 
63
+ ## Split tests (A/B on a blast)
64
+
65
+ A split test sends two versions of a draft blast to a test group, then sends
66
+ the winner (by opens or clicks) to the rest of the list.
67
+
68
+ ```bash
69
+ # Enable on a draft blast: creates A (current template) and B (a copy). Defaults 10% / 60 min / open.
70
+ ERMES_PROJECT=<project> ERMES_ALLOW_WRITES=1 ermes --json campaigns split-test set <id> --percent 20 --window 120 --metric click
71
+ # Edit B's copy with the template_id the command printed:
72
+ ERMES_PROJECT=<project> ERMES_ALLOW_WRITES=1 ermes templates update <b-template-id> --type email --data '{...}'
73
+ # Per-variant sent/opens/clicks and rates for the test group; `remainder` is the rest of the list:
74
+ ERMES_PROJECT=<project> ermes --json campaigns split-test results <id>
75
+ ```
76
+
77
+ Settings change only while the blast is a draft. `split-test disable <id> --yes`
78
+ deletes B and its template. `campaigns duplicate` copies A and B but not the
79
+ split-test settings: run `split-test set` on the copy before scheduling it.
80
+ `ermes --json export campaigns` adds a `split_test` block to each split-test
81
+ blast, for pooling results across sends. Counts use the winner picker's rule
82
+ (only delivered `sent` rows), so they do not add up to the Métricas totals;
83
+ before the decision the remainder is held (`assigned` > 0, `sent` 0).
84
+
63
85
  ## Errors
64
86
 
65
87
  - `401` / no login: the user runs `ermes login`.
@@ -5,7 +5,7 @@ build-backend = "hatchling.build"
5
5
  [project]
6
6
  name = "ermes-cli"
7
7
  # Keep in lockstep with ermes_cli/__init__.py::__version__ — tests/test_version.py fails if they drift.
8
- version = "1.4.0"
8
+ version = "1.5.1"
9
9
  description = "CLI-first access to Ermes marketing automation with Auth0 multi-project auth."
10
10
  readme = "README.md"
11
11
  requires-python = ">=3.10"
@@ -248,6 +248,35 @@ def test_ensure_admin_session_refreshes_expired_token(monkeypatch):
248
248
  assert saved["bundle"].access_token == "NEW"
249
249
 
250
250
 
251
+ @responses.activate
252
+ def test_ensure_admin_session_refreshes_when_only_the_id_token_expired(monkeypatch):
253
+ """DEV-2497: access token valid for 14h more, id_token (10h) already expired.
254
+ The exchange needs a live id_token, so the session must refresh first."""
255
+ import base64
256
+
257
+ def _jwt(exp):
258
+ body = base64.urlsafe_b64encode(json.dumps({"exp": exp}).encode()).rstrip(b"=").decode()
259
+ return f"h.{body}.s"
260
+
261
+ now = int(time.time())
262
+ stale = keyring_store.TokenBundle(
263
+ access_token="OLD", refresh_token="RT", id_token=_jwt(now - 1), expires_at=now + 14 * 3600
264
+ )
265
+ refreshed = keyring_store.TokenBundle(
266
+ access_token="NEW", refresh_token="RT2", id_token=_jwt(now + 36000), expires_at=now + 86400
267
+ )
268
+ saved = {}
269
+ monkeypatch.setattr(auth_cmds.keyring_store, "load", lambda: stale)
270
+ monkeypatch.setattr(auth_cmds.keyring_store, "save", lambda b: saved.update(bundle=b))
271
+ monkeypatch.setattr(auth_cmds.auth0, "refresh_access_token", lambda rt: refreshed)
272
+ responses.add(responses.POST, f"{BASE}/api/cli/exchange", json=EXCHANGE_OK, status=200)
273
+ auth_cmds._ensure_admin_session(BASE)
274
+ sent = json.loads(responses.calls[0].request.body)
275
+ assert sent["access_token"] == "NEW"
276
+ assert sent["id_token"] == refreshed.id_token
277
+ assert saved["bundle"].id_token == refreshed.id_token
278
+
279
+
251
280
  def test_ensure_admin_session_refresh_failure_exits(monkeypatch):
252
281
  expired = keyring_store.TokenBundle(
253
282
  access_token="OLD", refresh_token="RT", id_token="IT", expires_at=0
@@ -406,3 +406,163 @@ class TestCampaignsTrigger:
406
406
  result = invoke(["campaigns", "trigger", "7", "--external-id", "x", "--event", "{"])
407
407
  assert result.exit_code == 1
408
408
  assert httpx_mock.get_request() is None
409
+
410
+
411
+ # DEV-2496: split tests from the CLI.
412
+ CAMPAIGN_URL = "https://ermes.test/api/client/campaigns/5"
413
+ VARIANTS = [
414
+ {"id": 7, "label": "A", "template_id": 70, "position": 0},
415
+ {"id": 8, "label": "B", "template_id": 80, "position": 1},
416
+ ]
417
+ ENABLED_CONFIG = {
418
+ "enabled": True, "percent": 20, "window_minutes": 120, "metric": "email_click",
419
+ "test_started_at": None, "picker_state": "pending", "winner_variant_id": None,
420
+ "decided_at": None, "extended_once": False,
421
+ }
422
+
423
+
424
+ def _patch_body(httpx_mock: HTTPXMock) -> dict:
425
+ (patch,) = [r for r in httpx_mock.get_requests() if r.method == "PATCH"]
426
+ return json.loads(patch.content)
427
+
428
+
429
+ class TestCampaignsGetSplitTest:
430
+ def test_get_shows_split_test_config_and_variants(self, invoke, httpx_mock: HTTPXMock):
431
+ httpx_mock.add_response(
432
+ url=CAMPAIGN_URL,
433
+ json={"id": 5, "type": "blast", "split_test_config": ENABLED_CONFIG, "variants": VARIANTS},
434
+ )
435
+ result = invoke(["--json", "campaigns", "get", "5"])
436
+ assert result.exit_code == 0
437
+ data = json.loads(result.output)
438
+ assert data["split_test_config"]["percent"] == 20
439
+ assert [v["template_id"] for v in data["variants"]] == [70, 80]
440
+
441
+
442
+ class TestSplitTestSet:
443
+ def test_enable_uses_ui_defaults(self, invoke, httpx_mock: HTTPXMock):
444
+ httpx_mock.add_response(url=CAMPAIGN_URL, method="GET", json={"id": 5, "type": "blast", "split_test_config": None})
445
+ httpx_mock.add_response(
446
+ url=CAMPAIGN_URL, method="PATCH",
447
+ json={"id": 5, "split_test_config": {"enabled": True, "percent": 10, "window_minutes": 60, "metric": "email_open"},
448
+ "variants": VARIANTS},
449
+ )
450
+ result = invoke(["campaigns", "split-test", "set", "5"])
451
+ assert result.exit_code == 0, result.output
452
+ assert _patch_body(httpx_mock) == {"split_test_config": {
453
+ "enabled": True, "percent": 10, "window_minutes": 60, "metric": "email_open",
454
+ "picker_state": "pending", "extended_once": False,
455
+ }}
456
+ assert "ermes templates update 80" in result.output
457
+
458
+ def test_change_keeps_existing_settings(self, invoke, httpx_mock: HTTPXMock):
459
+ httpx_mock.add_response(url=CAMPAIGN_URL, method="GET", json={"id": 5, "type": "blast", "split_test_config": ENABLED_CONFIG})
460
+ httpx_mock.add_response(url=CAMPAIGN_URL, method="PATCH", json={"id": 5, "split_test_config": ENABLED_CONFIG, "variants": VARIANTS})
461
+ result = invoke(["--json", "campaigns", "split-test", "set", "5", "--percent", "30"])
462
+ assert result.exit_code == 0, result.output
463
+ sent = _patch_body(httpx_mock)["split_test_config"]
464
+ assert (sent["percent"], sent["window_minutes"], sent["metric"]) == (30, 120, "email_click")
465
+ assert json.loads(result.output)["variants"][1] == {"label": "B", "variant_id": 8, "template_id": 80}
466
+
467
+ def test_metric_click_maps_to_email_click(self, invoke, httpx_mock: HTTPXMock):
468
+ httpx_mock.add_response(url=CAMPAIGN_URL, method="GET", json={"id": 5, "type": "blast", "split_test_config": None})
469
+ httpx_mock.add_response(url=CAMPAIGN_URL, method="PATCH", json={"id": 5, "variants": VARIANTS})
470
+ result = invoke(["campaigns", "split-test", "set", "5", "--metric", "click", "--window", "30"])
471
+ assert result.exit_code == 0, result.output
472
+ sent = _patch_body(httpx_mock)["split_test_config"]
473
+ assert (sent["metric"], sent["window_minutes"]) == ("email_click", 30)
474
+
475
+ @pytest.mark.parametrize("args", [
476
+ ["--metric", "revenue"], ["--window", "45"], ["--percent", "51"], ["--percent", "0"],
477
+ ])
478
+ def test_invalid_options_send_nothing(self, invoke, httpx_mock: HTTPXMock, args):
479
+ result = invoke(["campaigns", "split-test", "set", "5", *args])
480
+ assert result.exit_code != 0
481
+ assert httpx_mock.get_requests() == []
482
+
483
+ def test_api_refusal_exits_1(self, invoke, httpx_mock: HTTPXMock):
484
+ httpx_mock.add_response(url=CAMPAIGN_URL, method="GET", json={"id": 5, "type": "blast", "state": "scheduled", "split_test_config": None})
485
+ httpx_mock.add_response(
486
+ url=CAMPAIGN_URL, method="PATCH", status_code=422,
487
+ json={"error": "Split-test settings can only be edited while the campaign is in draft."},
488
+ )
489
+ result = invoke(["campaigns", "split-test", "set", "5"])
490
+ assert result.exit_code == 1
491
+ assert "draft" in result.output
492
+
493
+ def test_write_gate_blocks_set(self, invoke, httpx_mock: HTTPXMock, monkeypatch):
494
+ monkeypatch.delenv("ERMES_ALLOW_WRITES", raising=False)
495
+ httpx_mock.add_response(url=CAMPAIGN_URL, method="GET", json={"id": 5, "type": "blast", "split_test_config": None})
496
+ result = invoke(["campaigns", "split-test", "set", "5"])
497
+ assert result.exit_code != 0
498
+ assert not any(r.method == "PATCH" for r in httpx_mock.get_requests())
499
+
500
+ def test_non_blast_is_refused_before_any_write(self, invoke, httpx_mock: HTTPXMock):
501
+ httpx_mock.add_response(url=CAMPAIGN_URL, method="GET", json={"id": 5, "type": "trigger", "split_test_config": None})
502
+ result = invoke(["campaigns", "split-test", "set", "5"])
503
+ assert result.exit_code == 1
504
+ assert "blasts only" in result.output
505
+ assert not any(r.method == "PATCH" for r in httpx_mock.get_requests())
506
+
507
+
508
+ class TestSplitTestDisable:
509
+ def test_requires_yes(self, invoke, httpx_mock: HTTPXMock):
510
+ result = invoke(["campaigns", "split-test", "disable", "5"])
511
+ assert result.exit_code == 1
512
+ assert "--yes" in result.output
513
+ assert httpx_mock.get_requests() == []
514
+
515
+ def test_disable_keeps_settings_and_sends_enabled_false(self, invoke, httpx_mock: HTTPXMock):
516
+ httpx_mock.add_response(url=CAMPAIGN_URL, method="GET", json={"id": 5, "split_test_config": ENABLED_CONFIG})
517
+ httpx_mock.add_response(url=CAMPAIGN_URL, method="PATCH", json={"id": 5})
518
+ result = invoke(["campaigns", "split-test", "disable", "5", "--yes"])
519
+ assert result.exit_code == 0, result.output
520
+ assert _patch_body(httpx_mock) == {"split_test_config": {
521
+ "enabled": False, "percent": 20, "window_minutes": 120, "metric": "email_click",
522
+ "picker_state": "pending", "extended_once": False,
523
+ }}
524
+
525
+ def test_disable_without_test_is_a_no_op(self, invoke, httpx_mock: HTTPXMock):
526
+ httpx_mock.add_response(url=CAMPAIGN_URL, method="GET", json={"id": 5, "split_test_config": None})
527
+ result = invoke(["campaigns", "split-test", "disable", "5", "--yes"])
528
+ assert result.exit_code == 0
529
+ assert "no split test" in result.output
530
+ assert not any(r.method == "PATCH" for r in httpx_mock.get_requests())
531
+
532
+
533
+ class TestSplitTestResults:
534
+ RESULTS = {
535
+ "enabled": True,
536
+ "config": {**ENABLED_CONFIG, "picker_state": "completed", "winner_variant_id": 8},
537
+ "variants": [
538
+ {"variant_id": 7, "label": "A", "template_id": 70, "subject": "Hi", "winner": False,
539
+ "assigned": 10, "sent": 8, "opens": 2, "clicks": 1},
540
+ {"variant_id": 8, "label": "B", "template_id": 80, "subject": "Hey", "winner": True,
541
+ "assigned": 10, "sent": 10, "opens": 5, "clicks": 3},
542
+ ],
543
+ "remainder": {"assigned": 80, "sent": 0, "opens": 0, "clicks": 0},
544
+ }
545
+
546
+ def test_json_adds_rates(self, invoke, httpx_mock: HTTPXMock):
547
+ httpx_mock.add_response(url=f"{CAMPAIGN_URL}/split-test/results", json=self.RESULTS)
548
+ result = invoke(["--json", "campaigns", "split-test", "results", "5"])
549
+ assert result.exit_code == 0, result.output
550
+ data = json.loads(result.output)
551
+ assert [(v["open_rate"], v["click_rate"]) for v in data["variants"]] == [(25.0, 12.5), (50.0, 30.0)]
552
+ # Zero sent must not divide by zero.
553
+ assert (data["remainder"]["open_rate"], data["remainder"]["click_rate"]) == (0, 0)
554
+
555
+ def test_table_shows_variants_and_rest_of_list(self, invoke, httpx_mock: HTTPXMock):
556
+ httpx_mock.add_response(url=f"{CAMPAIGN_URL}/split-test/results", json=self.RESULTS)
557
+ result = invoke(["campaigns", "split-test", "results", "5"])
558
+ assert result.exit_code == 0, result.output
559
+ assert "rest" in result.output and "Hey" in result.output and "50.0" in result.output
560
+
561
+ def test_not_enabled(self, invoke, httpx_mock: HTTPXMock):
562
+ httpx_mock.add_response(
563
+ url=f"{CAMPAIGN_URL}/split-test/results",
564
+ json={"enabled": False, "config": None, "variants": [], "remainder": {"assigned": 0, "sent": 0, "opens": 0, "clicks": 0}},
565
+ )
566
+ result = invoke(["campaigns", "split-test", "results", "5"])
567
+ assert result.exit_code == 0
568
+ assert "no split test" in result.output
@@ -303,3 +303,69 @@ class TestExportHtml:
303
303
  result = invoke(["export", "html", "1"])
304
304
  assert result.exit_code == 0
305
305
  assert "<mjml>" in result.output
306
+
307
+
308
+ SPLIT_TEST_RESULTS = {
309
+ "enabled": True,
310
+ "config": {"enabled": True, "percent": 10, "window_minutes": 60, "metric": "email_open",
311
+ "picker_state": "completed", "winner_variant_id": 8},
312
+ "variants": [
313
+ {"variant_id": 7, "label": "A", "template_id": 70, "subject": "A", "winner": False,
314
+ "assigned": 25, "sent": 20, "opens": 5, "clicks": 1},
315
+ {"variant_id": 8, "label": "B", "template_id": 80, "subject": "B", "winner": True,
316
+ "assigned": 25, "sent": 25, "opens": 10, "clicks": 0},
317
+ ],
318
+ "remainder": {"assigned": 450, "sent": 455, "opens": 135, "clicks": 29},
319
+ }
320
+
321
+
322
+ class TestExportSplitTest:
323
+ """DEV-2496: a split-test blast carries its per-variant counts; others make no extra request."""
324
+
325
+ def test_split_test_block_on_enabled_blast(self, invoke, httpx_mock: HTTPXMock):
326
+ httpx_mock.add_response(url="https://ermes.test/api/client/", json=PROJECT_RESPONSE)
327
+ httpx_mock.add_response(json={"results": [CAMPAIGN_LIST_RESPONSE["results"][0]], "limit": 100})
328
+ httpx_mock.add_response(
329
+ url="https://ermes.test/api/client/campaigns/1",
330
+ json={**CAMPAIGN_DETAIL_1, "split_test_config": SPLIT_TEST_RESULTS["config"]},
331
+ )
332
+ httpx_mock.add_response(
333
+ url="https://ermes.test/api/client/campaigns/1/split-test/results",
334
+ json=SPLIT_TEST_RESULTS,
335
+ )
336
+ result = invoke(["--json", "export", "campaigns"])
337
+ assert result.exit_code == 0, result.output
338
+ split = json.loads(result.output)["campaigns"][0]["split_test"]
339
+ a, b = split["variants"]
340
+ assert (a["open_rate"], a["click_rate"]) == (25.0, 5.0)
341
+ assert (b["open_rate"], b["click_rate"], b["winner"]) == (40.0, 0, True)
342
+ assert split["remainder"]["open_rate"] == round(135 / 455 * 100, 2)
343
+
344
+ def test_no_results_request_without_split_test(self, invoke, httpx_mock: HTTPXMock):
345
+ httpx_mock.add_response(url="https://ermes.test/api/client/", json=PROJECT_RESPONSE)
346
+ httpx_mock.add_response(json={"results": [CAMPAIGN_LIST_RESPONSE["results"][0]], "limit": 100})
347
+ httpx_mock.add_response(
348
+ url="https://ermes.test/api/client/campaigns/1",
349
+ json={**CAMPAIGN_DETAIL_1, "split_test_config": None},
350
+ )
351
+ result = invoke(["--json", "export", "campaigns"])
352
+ assert result.exit_code == 0, result.output
353
+ assert "split_test" not in json.loads(result.output)["campaigns"][0]
354
+ assert not any("split-test" in str(r.url) for r in httpx_mock.get_requests())
355
+
356
+ def test_results_error_keeps_the_campaign(self, invoke, httpx_mock: HTTPXMock):
357
+ httpx_mock.add_response(url="https://ermes.test/api/client/", json=PROJECT_RESPONSE)
358
+ httpx_mock.add_response(json={"results": [CAMPAIGN_LIST_RESPONSE["results"][0]], "limit": 100})
359
+ httpx_mock.add_response(
360
+ url="https://ermes.test/api/client/campaigns/1",
361
+ json={**CAMPAIGN_DETAIL_1, "split_test_config": SPLIT_TEST_RESULTS["config"]},
362
+ )
363
+ httpx_mock.add_response(
364
+ url="https://ermes.test/api/client/campaigns/1/split-test/results",
365
+ status_code=500, json={"error": "boom"},
366
+ )
367
+ result = invoke(["--json", "export", "campaigns"])
368
+ assert result.exit_code == 0, result.output
369
+ campaign = json.loads(result.output)["campaigns"][0]
370
+ assert campaign["id"] == 1
371
+ assert "error" in campaign["split_test"]
@@ -128,6 +128,54 @@ def test_token_bundle_is_expired_with_leeway():
128
128
  assert not almost.is_expired(now=now, leeway=10)
129
129
 
130
130
 
131
+ def _jwt(claims: dict) -> str:
132
+ import base64
133
+
134
+ body = base64.urlsafe_b64encode(json.dumps(claims).encode()).rstrip(b"=").decode()
135
+ return f"h.{body}.s"
136
+
137
+
138
+ def test_expired_id_token_marks_the_bundle_expired_before_the_access_token():
139
+ # DEV-2497: Auth0 id_token lives 10h, the access token 24h; the exchange needs both.
140
+ now = int(time.time())
141
+ stale_id = _bundle(expires_at=now + 14 * 3600, id_token=_jwt({"exp": now - 1}))
142
+ live_id = _bundle(expires_at=now + 14 * 3600, id_token=_jwt({"exp": now + 3600}))
143
+ assert stale_id.is_expired(now=now)
144
+ assert not live_id.is_expired(now=now)
145
+ # the same leeway applies to the id_token deadline
146
+ assert _bundle(expires_at=now + 3600, id_token=_jwt({"exp": now + 30})).is_expired(now=now)
147
+ # the EARLIER deadline wins: an expired access token with a live id_token is still expired
148
+ assert _bundle(expires_at=now - 1, id_token=_jwt({"exp": now + 36000})).is_expired(now=now)
149
+
150
+
151
+ def _deeply_nested_jwt() -> str:
152
+ import base64
153
+
154
+ body = base64.urlsafe_b64encode(b"[" * 100_000).rstrip(b"=").decode()
155
+ return f"h.{body}.s"
156
+
157
+
158
+ @pytest.mark.parametrize(
159
+ "id_token",
160
+ [
161
+ "",
162
+ "IT",
163
+ "a.!!!.c",
164
+ "a.e30.c",
165
+ _jwt({"exp": "soon"}),
166
+ _jwt([1]),
167
+ _jwt({"exp": float("inf")}),
168
+ _jwt({"exp": float("nan")}),
169
+ _jwt({"exp": True}),
170
+ _deeply_nested_jwt(),
171
+ ],
172
+ )
173
+ def test_unreadable_id_token_falls_back_to_the_access_token_expiry(id_token):
174
+ now = int(time.time())
175
+ assert not _bundle(expires_at=now + 3600, id_token=id_token).is_expired(now=now)
176
+ assert _bundle(expires_at=now - 1, id_token=id_token).is_expired(now=now)
177
+
178
+
131
179
  def test_from_token_response_computes_expires_at():
132
180
  bundle = keyring_store.TokenBundle.from_token_response(
133
181
  {"access_token": "AT", "refresh_token": "RT", "id_token": "IT", "expires_in": 3600},
@@ -1 +0,0 @@
1
- __version__ = "1.4.0"
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes