charisma-cli 0.6.4__tar.gz → 0.7.0__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 (41) hide show
  1. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/.gitignore +7 -0
  2. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/PKG-INFO +2 -1
  3. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/pyproject.toml +2 -1
  4. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/src/charisma_cli/__init__.py +1 -1
  5. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/src/charisma_cli/main.py +78 -2
  6. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/src/charisma_cli/read_models.py +6 -3
  7. charisma_cli-0.7.0/src/charisma_cli/s3_replica.py +174 -0
  8. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/tests/test_read_client_pagination.py +11 -6
  9. charisma_cli-0.7.0/tests/test_s3_replica.py +399 -0
  10. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/README.md +0 -0
  11. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/src/charisma_cli/config.py +0 -0
  12. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/src/charisma_cli/launch_url.py +0 -0
  13. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/src/charisma_cli/models.py +0 -0
  14. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/src/charisma_cli/parser.py +0 -0
  15. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/src/charisma_cli/read_client.py +0 -0
  16. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/src/charisma_cli/retry.py +0 -0
  17. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/src/charisma_cli/subprocess_mgr.py +0 -0
  18. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/src/charisma_cli/uploader.py +0 -0
  19. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/src/charisma_cli/watcher.py +0 -0
  20. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/tests/__init__.py +0 -0
  21. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/tests/conftest.py +0 -0
  22. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/tests/test_bamboo_labels.py +0 -0
  23. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/tests/test_cli.py +0 -0
  24. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/tests/test_config.py +0 -0
  25. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/tests/test_integration.py +0 -0
  26. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/tests/test_launch_url.py +0 -0
  27. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/tests/test_models.py +0 -0
  28. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/tests/test_open_launch_payload.py +0 -0
  29. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/tests/test_parser.py +0 -0
  30. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/tests/test_read_client.py +0 -0
  31. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/tests/test_read_client_attachments.py +0 -0
  32. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/tests/test_read_client_integration.py +0 -0
  33. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/tests/test_read_client_launches.py +0 -0
  34. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/tests/test_read_client_results.py +0 -0
  35. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/tests/test_read_client_single_result.py +0 -0
  36. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/tests/test_retry.py +0 -0
  37. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/tests/test_silent_mode.py +0 -0
  38. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/tests/test_subprocess_mgr.py +0 -0
  39. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/tests/test_testplan_cmd.py +0 -0
  40. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/tests/test_uploader.py +0 -0
  41. {charisma_cli-0.6.4 → charisma_cli-0.7.0}/tests/test_watcher.py +0 -0
@@ -152,3 +152,10 @@ allure-results-live/
152
152
 
153
153
  # sql files for locally run DB queries
154
154
  /*.sql
155
+
156
+ # testmon local selection cache (per machine, rebuilt from the working tree)
157
+ .testmondata
158
+ backend/.testmondata
159
+
160
+ # Local MCP server config (contains credentials)
161
+ .mcp.json
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: charisma-cli
3
- Version: 0.6.4
3
+ Version: 0.7.0
4
4
  Summary: CLI tool that watches allure-results and streams test results + attachments to Charisma.
5
5
  Author: Charisma Team
6
6
  License-Expression: MIT
@@ -14,6 +14,7 @@ Classifier: Programming Language :: Python :: 3.11
14
14
  Classifier: Programming Language :: Python :: 3.12
15
15
  Classifier: Topic :: Software Development :: Testing
16
16
  Requires-Python: >=3.10
17
+ Requires-Dist: boto3<2.0,>=1.26
17
18
  Requires-Dist: click<9.0,>=8.0
18
19
  Requires-Dist: httpx<1.0,>=0.24
19
20
  Requires-Dist: pydantic<3.0,>=2.0
@@ -5,7 +5,7 @@ build-backend = "hatchling.build"
5
5
 
6
6
  [project]
7
7
  name = "charisma-cli"
8
- version = "0.6.4"
8
+ version = "0.7.0"
9
9
  description = "CLI tool that watches allure-results and streams test results + attachments to Charisma."
10
10
  readme = "README.md"
11
11
  license = "MIT"
@@ -25,6 +25,7 @@ classifiers = [
25
25
  "Topic :: Software Development :: Testing",
26
26
  ]
27
27
  dependencies = [
28
+ "boto3>=1.26,<2.0",
28
29
  "click>=8.0,<9.0",
29
30
  "httpx>=0.24,<1.0",
30
31
  "pydantic>=2.0,<3.0",
@@ -4,4 +4,4 @@
4
4
  # is generated from pyproject.toml [project].version, so keeping this literal
5
5
  # equal to pyproject guarantees `--version` reports the published version. The
6
6
  # prepare-commit step owns the PATCH bump — do not hand-bump here.
7
- __version__ = "0.6.4"
7
+ __version__ = "0.7.0"
@@ -15,6 +15,7 @@ from charisma_cli.launch_url import build_launch_url, emit_github_output
15
15
  from charisma_cli.models import FileEvent
16
16
  from charisma_cli.parser import parse_environment_properties
17
17
  from charisma_cli.read_client import CharismaReadClient, CharismaReadError
18
+ from charisma_cli.s3_replica import _DEFAULT_CHARISMA_ACCOUNT_ID, build_s3_metadata, upload_results_to_s3
18
19
  from charisma_cli.subprocess_mgr import SubprocessManager
19
20
  from charisma_cli.uploader import Uploader
20
21
  from charisma_cli.watcher import ResultsWatcher, classify_file
@@ -169,8 +170,10 @@ def _common_options(func: Callable) -> Callable:
169
170
  order below.
170
171
  """
171
172
  options = [
172
- click.option("--endpoint", envvar="CHARISMA_ENDPOINT", default=None, help="Charisma API endpoint."),
173
- click.option("--token", envvar="CHARISMA_TOKEN", default=None, help="Bearer token."),
173
+ click.option(
174
+ "--endpoint", envvar="CHARISMA_ENDPOINT", default=None, required=True, help="Charisma API endpoint."
175
+ ),
176
+ click.option("--token", envvar="CHARISMA_TOKEN", default=None, required=True, help="Bearer token."),
174
177
  click.option(
175
178
  "--results", envvar="CHARISMA_RESULTS", default="allure-results", help="Allure results directory."
176
179
  ),
@@ -421,6 +424,79 @@ def upload(
421
424
  sys.exit(1)
422
425
 
423
426
 
427
+ @cli.command()
428
+ @click.option("--results", envvar="CHARISMA_RESULTS", default="allure-results", help="Allure results directory.")
429
+ @click.option("--project", envvar="CHARISMA_PROJECT_ID", required=True, help="Project alias.")
430
+ @click.option("--component", default=None, help="Component alias within the project.")
431
+ @click.option("--launch-name", default=None, help="Launch name / run key for the S3 key prefix.")
432
+ @click.option(
433
+ "--charisma-account-id",
434
+ envvar="CHARISMA_ACCOUNT_ID",
435
+ default=None,
436
+ help="AWS account ID owning the replica buckets and upload roles.",
437
+ )
438
+ def replica(
439
+ results: str,
440
+ project: str,
441
+ component: str | None,
442
+ launch_name: str | None,
443
+ charisma_account_id: str | None,
444
+ ) -> None:
445
+ """Upload allure-results to the regional S3 replica bucket.
446
+
447
+ Bucket: charisma-replica-{region}-prod. Key prefix: {project}/{component}/{launch_name}/.
448
+
449
+ Usage: charismactl replica --project my-project --component my-component
450
+ """
451
+ config = Config.from_env(
452
+ project=project,
453
+ results=results,
454
+ component=component,
455
+ )
456
+
457
+ resolved_launch_name = (launch_name or "").strip() or config.name or config.run_key
458
+ if not resolved_launch_name:
459
+ click.echo(
460
+ "Error: launch name is required for replica. Set LAUNCH_NAME, CHARISMA_LAUNCH_NAME, or CHARISMA_RUN_KEY.",
461
+ err=True,
462
+ )
463
+ sys.exit(1)
464
+
465
+ if not Path(config.results_dir).exists():
466
+ click.echo(f"Error: Results directory '{config.results_dir}' does not exist.", err=True)
467
+ sys.exit(1)
468
+
469
+ metadata = build_s3_metadata({
470
+ "run_key": config.run_key,
471
+ "job_run_id": config.job_run_id,
472
+ "source_url": config.source_url,
473
+ "build_plan_key": config.build_plan_key,
474
+ "build_id": config.build_id,
475
+ "environment": config.environment,
476
+ "commit_sha": config.commit_sha,
477
+ "branch": config.branch,
478
+ "tags": config.tags,
479
+ })
480
+
481
+ try:
482
+ uploaded = upload_results_to_s3(
483
+ config.results_dir,
484
+ config.project,
485
+ config.component,
486
+ resolved_launch_name,
487
+ metadata=metadata or None,
488
+ account_id=charisma_account_id or _DEFAULT_CHARISMA_ACCOUNT_ID,
489
+ )
490
+ except RuntimeError as exc:
491
+ click.echo(f"Error: {exc}", err=True)
492
+ sys.exit(1)
493
+ except Exception as exc:
494
+ click.echo(f"Error: S3 upload failed: {exc}", err=True)
495
+ sys.exit(1)
496
+
497
+ click.echo(f"Summary: files_uploaded={uploaded}")
498
+
499
+
424
500
  @cli.group()
425
501
  def testplan() -> None:
426
502
  """Fetch the rerun test plan of a launch (failed/broken variants)."""
@@ -53,9 +53,7 @@ class _CamelModel(BaseModel):
53
53
  new server fields. Dump the wire form with ``model_dump(by_alias=True)``.
54
54
  """
55
55
 
56
- model_config = ConfigDict(
57
- alias_generator=to_camel, populate_by_name=True, extra="allow"
58
- )
56
+ model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, extra="allow")
59
57
 
60
58
 
61
59
  class _SnakeModel(BaseModel):
@@ -157,6 +155,8 @@ class TestResultRecord(_CamelModel):
157
155
  populated; from the single-result path they are always empty lists.
158
156
  """
159
157
 
158
+ __test__ = False
159
+
160
160
  id: str
161
161
  launch_id: str
162
162
  launch_created_at: datetime | None = None
@@ -303,6 +303,7 @@ class StabilityResultRecord(_SnakeModel):
303
303
  class TestCaseHistoryRecord(_SnakeModel):
304
304
  """Composite cross-run history: executions + stability + badge."""
305
305
 
306
+ __test__ = False
306
307
  history_id: str
307
308
  name: str
308
309
  executions: list[ExecutionEntryRecord]
@@ -318,6 +319,7 @@ class TestCaseHistoryRecord(_SnakeModel):
318
319
  class TestPlanEntry(_CamelModel):
319
320
  """One planned test: exact node ID (``selector``) or a fallback identity."""
320
321
 
322
+ __test__ = False
321
323
  selector: str | None = None
322
324
  full_name: str | None = None
323
325
  name: str
@@ -338,5 +340,6 @@ class TestPlanEntry(_CamelModel):
338
340
  class TestPlan(_CamelModel):
339
341
  """The rerun test plan served by ``GET .../launches/{launchId}/test-plan``."""
340
342
 
343
+ __test__ = False
341
344
  version: str
342
345
  tests: list[TestPlanEntry]
@@ -0,0 +1,174 @@
1
+ """S3 replica upload — copies allure-results to a regional S3 bucket."""
2
+
3
+ import logging
4
+ import tempfile
5
+ import uuid
6
+ import zipfile
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ import boto3
11
+ import boto3.session
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ # Replica bucket topology (prod only):
16
+ #
17
+ # charisma-replica-us-east-2-prod ─┐
18
+ # charisma-replica-us-west-2-prod ─┤ CRR ──► charisma-replica-us-east-1-prod (MAIN)
19
+ # charisma-replica-ap-south-1-prod ─┤ │
20
+ # charisma-replica-ap-northeast-1-prod ┘ Charisma processor reads from here
21
+ #
22
+ # CI workers upload to the bucket matching their AWS_DEFAULT_REGION.
23
+ # charisma-replica-us-east-1-prod is the CRR destination — it is the MAIN bucket.
24
+ # All other regional buckets replicate into it automatically.
25
+ # The Charisma processor (backend) reads only from the main bucket.
26
+ #
27
+ # Bucket name convention: charisma-replica-{region}-prod
28
+ # Main bucket constant: _MAIN_REPLICA_REGION = "us-east-1"
29
+
30
+ _BUCKET_PREFIX = "charisma-replica"
31
+ _BUCKET_SUFFIX = "prod"
32
+ _MAIN_REPLICA_REGION = "us-east-1" # CRR destination — Charisma processor reads from this bucket
33
+
34
+ # Charisma AWS account — owner of all replica buckets and upload roles.
35
+ # Can be overridden via --charisma-account-id CLI option.
36
+ _DEFAULT_CHARISMA_ACCOUNT_ID = "492776708255"
37
+
38
+
39
+ def _replica_upload_role_arn(region: str, account_id: str) -> str:
40
+ """Build the ReplicaUploadRole ARN for the given region.
41
+
42
+ Convention mirrors the bucket name: charisma-replica-upload-{region}-prod.
43
+ us-east-1 is the main bucket region; its role omits the region segment
44
+ (created by storage/storage.yaml as charisma-replica-upload-prod).
45
+ """
46
+ if region == _MAIN_REPLICA_REGION:
47
+ role_name = "charisma-replica-upload-prod"
48
+ else:
49
+ role_name = f"charisma-replica-upload-{region}-prod"
50
+ return f"arn:aws:iam::{account_id}:role/{role_name}"
51
+
52
+
53
+ _session = boto3.session.Session()
54
+
55
+ # Mapping of Config attribute name -> S3 metadata key for optional launch
56
+ # context fields. Only non-None, non-empty values are included.
57
+ _METADATA_FIELDS: dict[str, str] = {
58
+ "run_key": "charisma-run-key",
59
+ "job_run_id": "charisma-job-run-id",
60
+ "source_url": "charisma-source-url",
61
+ "build_plan_key": "charisma-build-plan-key",
62
+ "build_id": "charisma-build-id",
63
+ "environment": "charisma-environment",
64
+ "commit_sha": "charisma-commit-sha",
65
+ "branch": "charisma-branch",
66
+ "tags": "charisma-tags",
67
+ }
68
+
69
+
70
+ def build_s3_metadata(config_fields: dict[str, str | list[str] | None]) -> dict[str, str]:
71
+ """Build S3 object metadata dict from resolved config fields.
72
+
73
+ Only includes fields that are non-None and non-empty. List values
74
+ (tags) are joined with commas. S3 metadata values must be strings.
75
+
76
+ Args:
77
+ config_fields: Mapping of config attribute name to its resolved value.
78
+
79
+ Returns:
80
+ Dict of S3 metadata key -> string value, ready to pass as ``Metadata``.
81
+ """
82
+ metadata: dict[str, str] = {}
83
+ for attr, s3_key in _METADATA_FIELDS.items():
84
+ value = config_fields.get(attr)
85
+ if value is None:
86
+ continue
87
+ if isinstance(value, list):
88
+ joined = ",".join(value)
89
+ if joined:
90
+ metadata[s3_key] = joined
91
+ elif value:
92
+ metadata[s3_key] = value
93
+ return metadata
94
+
95
+
96
+ def _assume_upload_role(region: str, account_id: str) -> boto3.session.Session:
97
+ """Assume the Charisma replica upload role and return a session with temporary credentials."""
98
+ role_arn = _replica_upload_role_arn(region, account_id)
99
+ sts = _session.client("sts", region_name=region)
100
+ credentials = sts.assume_role(
101
+ RoleArn=role_arn,
102
+ RoleSessionName="charismactl-replica",
103
+ )["Credentials"]
104
+ return boto3.session.Session(
105
+ aws_access_key_id=credentials["AccessKeyId"],
106
+ aws_secret_access_key=credentials["SecretAccessKey"],
107
+ aws_session_token=credentials["SessionToken"],
108
+ region_name=region,
109
+ )
110
+
111
+
112
+ def upload_results_to_s3(
113
+ results_dir: str,
114
+ project: str,
115
+ component: str | None,
116
+ launch_name: str,
117
+ metadata: dict[str, str] | None = None,
118
+ account_id: str = _DEFAULT_CHARISMA_ACCOUNT_ID,
119
+ ) -> int:
120
+ """Pack allure-results into a ZIP and upload it to the regional S3 replica bucket.
121
+
122
+ Assumes the Charisma replica upload role before writing to S3.
123
+ Bucket: ``charisma-replica-{region}-prod``.
124
+ S3 key: ``{project}/{component}/{launch_name}/{uuid}.zip``.
125
+ When ``component`` is ``None``, the key segment falls back to ``"default"``.
126
+
127
+ Args:
128
+ results_dir: Path to the allure-results directory.
129
+ project: Project alias (used as the first S3 key segment).
130
+ component: Component alias (second S3 key segment). ``None`` → ``"default"``.
131
+ launch_name: Launch name / run key (used as the third S3 key segment).
132
+ metadata: Optional S3 object metadata dict (string keys and values).
133
+ account_id: AWS account ID owning the replica buckets and upload roles.
134
+ Defaults to the Charisma prod account. Override for dev/testing.
135
+
136
+ Returns:
137
+ Number of files packed into the archive.
138
+
139
+ Raises:
140
+ RuntimeError: If no AWS region can be determined.
141
+ botocore.exceptions.BotoCoreError: On AWS credential or S3 errors.
142
+ """
143
+ region = _session.region_name
144
+ if not region:
145
+ raise RuntimeError(
146
+ "Cannot determine AWS region. Set AWS_DEFAULT_REGION or configure ~/.aws/config."
147
+ )
148
+
149
+ results_path = Path(results_dir)
150
+ files = [p for p in results_path.iterdir() if p.is_file()]
151
+
152
+ if not files:
153
+ logger.warning("No allure-results files found in %s — nothing uploaded.", results_dir)
154
+ return 0
155
+
156
+ assumed_session = _assume_upload_role(region, account_id)
157
+ bucket = f"{_BUCKET_PREFIX}-{region}-{_BUCKET_SUFFIX}"
158
+ key = f"{project}/{component or 'default'}/{launch_name}/{uuid.uuid4()}.zip"
159
+ extra_args: dict[str, Any] = {"Metadata": metadata} if metadata else {}
160
+
161
+ with tempfile.NamedTemporaryFile(suffix=".zip", delete=True) as tmp:
162
+ with zipfile.ZipFile(tmp, mode="w", compression=zipfile.ZIP_DEFLATED, compresslevel=5) as zf:
163
+ for filepath in files:
164
+ zf.write(filepath, arcname=filepath.name)
165
+ tmp.flush()
166
+
167
+ s3 = assumed_session.client("s3", region_name=region)
168
+ if extra_args:
169
+ s3.upload_file(tmp.name, bucket, key, ExtraArgs=extra_args)
170
+ else:
171
+ s3.upload_file(tmp.name, bucket, key)
172
+
173
+ logger.debug("Uploaded %d file(s) -> s3://%s/%s", len(files), bucket, key)
174
+ return len(files)
@@ -45,6 +45,14 @@ def _make_client() -> CharismaReadClient:
45
45
  return CharismaReadClient(ENDPOINT, TOKEN, PROJECT_UUID)
46
46
 
47
47
 
48
+ # Built once: client construction is slow (~0.5s) and would exceed Hypothesis' per-example deadline.
49
+ _PROPERTY_CLIENT = _make_client()
50
+
51
+
52
+ # Built once: client construction is slow (~0.5s) and would exceed Hypothesis' per-example deadline.
53
+ _PROPERTY_CLIENT = _make_client()
54
+
55
+
48
56
  class _FakePagedEndpoint:
49
57
  """In-memory ``fetch`` callable emulating the server's offset/limit paging.
50
58
 
@@ -94,9 +102,8 @@ class TestIterPagesProperty:
94
102
  """
95
103
  items = list(range(n_items))
96
104
  fetch = _FakePagedEndpoint(items)
97
- client = _make_client()
98
105
 
99
- collected = list(client.iter_pages(fetch, page_size=page_size))
106
+ collected = list(_PROPERTY_CLIENT.iter_pages(fetch, page_size=page_size))
100
107
 
101
108
  assert collected == items
102
109
 
@@ -118,9 +125,8 @@ class TestIterPagesProperty:
118
125
  """
119
126
  items = list(range(n_items))
120
127
  fetch = _FakePagedEndpoint(items)
121
- client = _make_client()
122
128
 
123
- list(client.iter_pages(fetch, page_size=page_size))
129
+ list(_PROPERTY_CLIENT.iter_pages(fetch, page_size=page_size))
124
130
 
125
131
  full_pages = n_items // page_size
126
132
  has_remainder = n_items % page_size != 0
@@ -143,9 +149,8 @@ class TestIterPagesProperty:
143
149
  """
144
150
  items = list(range(n_items))
145
151
  fetch = _FakePagedEndpoint(items)
146
- client = _make_client()
147
152
 
148
- list(client.iter_pages(fetch, page_size=page_size))
153
+ list(_PROPERTY_CLIENT.iter_pages(fetch, page_size=page_size))
149
154
 
150
155
  offsets = [offset for offset, _, _ in fetch.calls]
151
156
  expected_offsets = [i * page_size for i in range(len(offsets))]
@@ -0,0 +1,399 @@
1
+ """Unit tests for charisma_cli.s3_replica: metadata, role ARN, upload logic."""
2
+
3
+ import zipfile
4
+ from pathlib import Path
5
+ from unittest.mock import MagicMock, patch
6
+
7
+ import pytest
8
+
9
+ import charisma_cli.s3_replica as s3_replica_module
10
+ from charisma_cli.s3_replica import (
11
+ _DEFAULT_CHARISMA_ACCOUNT_ID,
12
+ _MAIN_REPLICA_REGION,
13
+ _replica_upload_role_arn,
14
+ build_s3_metadata,
15
+ upload_results_to_s3,
16
+ )
17
+
18
+ # ---------------------------------------------------------------------------
19
+ # build_s3_metadata — pure logic, zero mocks
20
+ # ---------------------------------------------------------------------------
21
+
22
+
23
+ class TestBuildS3Metadata:
24
+ """build_s3_metadata maps config fields to charisma-* S3 metadata keys."""
25
+
26
+ @pytest.mark.unit
27
+ def test_all_scalar_fields_included(self) -> None:
28
+ """All non-None scalar fields are mapped to their charisma-* keys.
29
+
30
+ Catches: missing key in _METADATA_FIELDS, wrong key name.
31
+ """
32
+ result = build_s3_metadata({
33
+ "run_key": "run-123",
34
+ "job_run_id": "jr-456",
35
+ "source_url": "https://ci/build/1",
36
+ "build_plan_key": "PROJ-PLAN",
37
+ "build_id": "build-789",
38
+ "environment": "qat",
39
+ "commit_sha": "abc123",
40
+ "branch": "main",
41
+ "tags": None,
42
+ })
43
+
44
+ assert result["charisma-run-key"] == "run-123", "run_key must map to charisma-run-key"
45
+ assert result["charisma-job-run-id"] == "jr-456"
46
+ assert result["charisma-source-url"] == "https://ci/build/1"
47
+ assert result["charisma-build-plan-key"] == "PROJ-PLAN"
48
+ assert result["charisma-build-id"] == "build-789"
49
+ assert result["charisma-environment"] == "qat"
50
+ assert result["charisma-commit-sha"] == "abc123"
51
+ assert result["charisma-branch"] == "main"
52
+ assert "charisma-tags" not in result
53
+
54
+ @pytest.mark.unit
55
+ def test_tags_list_joined_with_comma(self) -> None:
56
+ """A list of tags is joined into a comma-separated string.
57
+
58
+ Catches: S3 metadata values must be strings, not lists.
59
+ """
60
+ result = build_s3_metadata({"tags": ["smoke", "regression", "ci"]})
61
+
62
+ assert result["charisma-tags"] == "smoke,regression,ci", (
63
+ "tags list must be joined with commas for S3 metadata"
64
+ )
65
+
66
+ @pytest.mark.unit
67
+ def test_none_fields_excluded(self) -> None:
68
+ """None values are not included in the metadata dict.
69
+
70
+ Catches: S3 rejects None metadata values.
71
+ """
72
+ result = build_s3_metadata({
73
+ "run_key": None,
74
+ "branch": None,
75
+ "commit_sha": "abc",
76
+ })
77
+
78
+ assert "charisma-run-key" not in result, "None fields must be excluded"
79
+ assert "charisma-branch" not in result
80
+ assert result["charisma-commit-sha"] == "abc"
81
+
82
+ @pytest.mark.unit
83
+ def test_empty_string_fields_excluded(self) -> None:
84
+ """Empty string values are not included in the metadata dict.
85
+
86
+ Catches: empty S3 metadata values cause validation errors on some clients.
87
+ """
88
+ result = build_s3_metadata({"run_key": "", "branch": "main"})
89
+
90
+ assert "charisma-run-key" not in result, "empty string fields must be excluded"
91
+ assert result["charisma-branch"] == "main"
92
+
93
+ @pytest.mark.unit
94
+ def test_empty_tags_list_excluded(self) -> None:
95
+ """An empty tags list produces no charisma-tags key.
96
+
97
+ Catches: empty comma-join yields "" which is an invalid metadata value.
98
+ """
99
+ result = build_s3_metadata({"tags": []})
100
+
101
+ assert "charisma-tags" not in result, "empty tags list must not produce a metadata key"
102
+
103
+ @pytest.mark.unit
104
+ def test_all_none_returns_empty_dict(self) -> None:
105
+ """All-None input returns an empty dict (nothing to attach).
106
+
107
+ Catches: caller passing metadata={} vs metadata=None to ExtraArgs.
108
+ """
109
+ result = build_s3_metadata({k: None for k in [
110
+ "run_key", "job_run_id", "source_url", "build_plan_key",
111
+ "build_id", "environment", "commit_sha", "branch", "tags",
112
+ ]})
113
+
114
+ assert result == {}, f"all-None input must yield empty dict, got {result}"
115
+
116
+
117
+ # ---------------------------------------------------------------------------
118
+ # _replica_upload_role_arn — pure logic, zero mocks
119
+ # ---------------------------------------------------------------------------
120
+
121
+
122
+ class TestReplicaUploadRoleArn:
123
+ """_replica_upload_role_arn builds the IAM role ARN by convention."""
124
+
125
+ @pytest.mark.unit
126
+ def test_main_region_omits_region_segment(self) -> None:
127
+ """us-east-1 (main bucket region) uses charisma-replica-upload-prod.
128
+
129
+ Catches: wrong role name for the main bucket (created by storage.yaml).
130
+ """
131
+ arn = _replica_upload_role_arn(_MAIN_REPLICA_REGION, _DEFAULT_CHARISMA_ACCOUNT_ID)
132
+
133
+ assert arn == f"arn:aws:iam::{_DEFAULT_CHARISMA_ACCOUNT_ID}:role/charisma-replica-upload-prod", (
134
+ f"main region role ARN is wrong: {arn}"
135
+ )
136
+
137
+ @pytest.mark.unit
138
+ @pytest.mark.parametrize("region,expected_role", [
139
+ ("us-east-2", "charisma-replica-upload-us-east-2-prod"),
140
+ ("us-west-2", "charisma-replica-upload-us-west-2-prod"),
141
+ ("ap-south-1", "charisma-replica-upload-ap-south-1-prod"),
142
+ ("ap-northeast-1", "charisma-replica-upload-ap-northeast-1-prod"),
143
+ ])
144
+ def test_regional_bucket_includes_region_in_role_name(self, region: str, expected_role: str) -> None:
145
+ """Regional buckets use charisma-replica-upload-{region}-prod.
146
+
147
+ Catches: wrong role name → assume_role fails with NoSuchEntity.
148
+ """
149
+ arn = _replica_upload_role_arn(region, _DEFAULT_CHARISMA_ACCOUNT_ID)
150
+
151
+ assert arn == f"arn:aws:iam::{_DEFAULT_CHARISMA_ACCOUNT_ID}:role/{expected_role}", (
152
+ f"regional role ARN for {region} is wrong: {arn}"
153
+ )
154
+
155
+ @pytest.mark.unit
156
+ def test_arn_account_id_is_charisma_account(self) -> None:
157
+ """All role ARNs reference the Charisma account 492776708255.
158
+
159
+ Catches: wrong account ID → assume_role targets wrong account.
160
+ """
161
+ for region in ["us-east-1", "us-east-2", "us-west-2", "ap-south-1", "ap-northeast-1"]:
162
+ arn = _replica_upload_role_arn(region, _DEFAULT_CHARISMA_ACCOUNT_ID)
163
+ assert _DEFAULT_CHARISMA_ACCOUNT_ID in arn, f"Charisma account ID missing from ARN for {region}: {arn}"
164
+
165
+
166
+ # ---------------------------------------------------------------------------
167
+ # upload_results_to_s3 — mocked I/O boundary (boto3 session)
168
+ # ---------------------------------------------------------------------------
169
+
170
+
171
+ @pytest.fixture()
172
+ def mock_s3_setup() -> tuple[MagicMock, MagicMock, MagicMock]:
173
+ """Return (mock_session, assumed_session, s3_client) wired for us-east-2.
174
+
175
+ mock_session: replaces the module-level _session singleton.
176
+ assumed_session: returned by boto3.session.Session() after assume_role.
177
+ s3_client: the S3 client created from assumed_session.
178
+ """
179
+ mock_session = MagicMock()
180
+ mock_session.region_name = "us-east-2"
181
+
182
+ sts_client = MagicMock()
183
+ sts_client.assume_role.return_value = {
184
+ "Credentials": {
185
+ "AccessKeyId": "AKIA-TEST",
186
+ "SecretAccessKey": "secret",
187
+ "SessionToken": "token",
188
+ }
189
+ }
190
+ mock_session.client.return_value = sts_client
191
+
192
+ assumed_session = MagicMock()
193
+ s3_client = MagicMock()
194
+ assumed_session.client.return_value = s3_client
195
+
196
+ return mock_session, assumed_session, s3_client
197
+
198
+
199
+ class TestUploadResultsToS3:
200
+ """upload_results_to_s3 packs files into a ZIP and uploads to S3."""
201
+
202
+ @pytest.mark.unit
203
+ def test_no_allure_files_returns_zero_and_skips_upload(self, tmp_path: Path) -> None:
204
+ """An empty results dir returns 0 and never calls S3.
205
+
206
+ Catches: uploading an empty ZIP wastes a request and confuses the processor.
207
+ """
208
+ results_dir = tmp_path / "allure-results"
209
+ results_dir.mkdir()
210
+ mock_session = MagicMock()
211
+ mock_session.region_name = "us-east-2"
212
+
213
+ with patch.object(s3_replica_module, "_session", mock_session), \
214
+ patch.object(s3_replica_module, "_assume_upload_role") as mock_assume:
215
+ count = upload_results_to_s3(str(results_dir), "proj", "comp", "launch-1")
216
+
217
+ assert count == 0, "empty results dir must return 0"
218
+ mock_assume.assert_not_called(), "assume_role must not be called when there are no files"
219
+
220
+ @pytest.mark.unit
221
+ def test_no_region_raises_runtime_error(self, tmp_path: Path) -> None:
222
+ """Missing AWS region raises RuntimeError with a helpful message.
223
+
224
+ Catches: silent failure when AWS_DEFAULT_REGION is not set.
225
+ """
226
+ results_dir = tmp_path / "allure-results"
227
+ results_dir.mkdir()
228
+
229
+ mock_session = MagicMock()
230
+ mock_session.region_name = None
231
+
232
+ with patch.object(s3_replica_module, "_session", mock_session):
233
+ with pytest.raises(RuntimeError, match="AWS_DEFAULT_REGION"):
234
+ upload_results_to_s3(str(results_dir), "proj", "comp", "launch-1")
235
+
236
+ @pytest.mark.unit
237
+ def test_allure_files_zipped_and_uploaded(
238
+ self, tmp_path: Path, mock_s3_setup: tuple[MagicMock, MagicMock, MagicMock]
239
+ ) -> None:
240
+ """Allure result files are packed into a ZIP and uploaded to the correct bucket/key.
241
+
242
+ Catches: wrong bucket name, wrong key prefix, files not included in ZIP.
243
+ """
244
+ mock_session, assumed_session, s3_client = mock_s3_setup
245
+ results_dir = tmp_path / "allure-results"
246
+ results_dir.mkdir()
247
+ (results_dir / "abc-result.json").write_text('{"uuid": "abc"}')
248
+ (results_dir / "def-container.json").write_text('{"uuid": "def"}')
249
+
250
+ with patch.object(s3_replica_module, "_session", mock_session), \
251
+ patch("charisma_cli.s3_replica.boto3.session.Session", return_value=assumed_session):
252
+ count = upload_results_to_s3(str(results_dir), "my-proj", "my-comp", "launch-42")
253
+
254
+ assert count == 2, f"expected 2 files uploaded, got {count}"
255
+
256
+ s3_client.upload_file.assert_called_once()
257
+ call_args = s3_client.upload_file.call_args
258
+ bucket = call_args[0][1]
259
+ key = call_args[0][2]
260
+
261
+ assert bucket == "charisma-replica-us-east-2-prod", f"wrong bucket: {bucket}"
262
+ assert key.startswith("my-proj/my-comp/launch-42/"), f"wrong key prefix: {key}"
263
+ assert key.endswith(".zip"), f"key must end with .zip: {key}"
264
+
265
+ @pytest.mark.unit
266
+ def test_zip_contains_all_allure_files(
267
+ self, tmp_path: Path, mock_s3_setup: tuple[MagicMock, MagicMock, MagicMock]
268
+ ) -> None:
269
+ """The uploaded ZIP contains exactly the allure-classified files, not rejected ones.
270
+
271
+ Catches: files silently dropped from the archive, or rejected files included.
272
+ """
273
+ mock_session, assumed_session, s3_client = mock_s3_setup
274
+ results_dir = tmp_path / "allure-results"
275
+ results_dir.mkdir()
276
+ (results_dir / "r1-result.json").write_text('{"uuid": "r1"}')
277
+ (results_dir / "c1-container.json").write_text('{"uuid": "c1"}')
278
+ zip_out = tmp_path / "captured.zip"
279
+ captured: list[str] = []
280
+
281
+ def _capture_upload(local_path: str, bucket: str, key: str, **kwargs: object) -> None:
282
+ import shutil
283
+ shutil.copy(local_path, zip_out)
284
+ captured.append(local_path)
285
+
286
+ s3_client.upload_file.side_effect = _capture_upload
287
+
288
+ with patch.object(s3_replica_module, "_session", mock_session), \
289
+ patch("charisma_cli.s3_replica.boto3.session.Session", return_value=assumed_session):
290
+ upload_results_to_s3(str(results_dir), "proj", "comp", "launch-1")
291
+
292
+ assert zip_out.exists(), "upload_file must have been called with a ZIP path"
293
+ with zipfile.ZipFile(zip_out) as zf:
294
+ names = set(zf.namelist())
295
+ assert names == {"r1-result.json", "c1-container.json"}, (
296
+ f"ZIP must contain exactly the uploaded files, got: {names}"
297
+ )
298
+
299
+ @pytest.mark.unit
300
+ def test_metadata_passed_to_s3_extra_args(
301
+ self, tmp_path: Path, mock_s3_setup: tuple[MagicMock, MagicMock, MagicMock]
302
+ ) -> None:
303
+ """Metadata dict is forwarded as ExtraArgs to upload_file.
304
+
305
+ Catches: metadata silently dropped, processor cannot read launch context.
306
+ """
307
+ mock_session, assumed_session, s3_client = mock_s3_setup
308
+ results_dir = tmp_path / "allure-results"
309
+ results_dir.mkdir()
310
+ (results_dir / "r1-result.json").write_text('{"uuid": "r1"}')
311
+
312
+ metadata = {"charisma-branch": "main", "charisma-run-key": "run-123"}
313
+
314
+ with patch.object(s3_replica_module, "_session", mock_session), \
315
+ patch("charisma_cli.s3_replica.boto3.session.Session", return_value=assumed_session):
316
+ upload_results_to_s3(str(results_dir), "proj", "comp", "launch-1", metadata=metadata)
317
+
318
+ call_kwargs = s3_client.upload_file.call_args[1]
319
+ assert call_kwargs.get("ExtraArgs") == {"Metadata": metadata}, (
320
+ f"metadata not forwarded to ExtraArgs: {call_kwargs}"
321
+ )
322
+
323
+ @pytest.mark.unit
324
+ def test_no_metadata_omits_extra_args(
325
+ self, tmp_path: Path, mock_s3_setup: tuple[MagicMock, MagicMock, MagicMock]
326
+ ) -> None:
327
+ """When metadata is None, ExtraArgs is not passed to upload_file.
328
+
329
+ Catches: passing ExtraArgs={} causes S3 to reject the request.
330
+ """
331
+ mock_session, assumed_session, s3_client = mock_s3_setup
332
+ results_dir = tmp_path / "allure-results"
333
+ results_dir.mkdir()
334
+ (results_dir / "r1-result.json").write_text('{"uuid": "r1"}')
335
+
336
+ with patch.object(s3_replica_module, "_session", mock_session), \
337
+ patch("charisma_cli.s3_replica.boto3.session.Session", return_value=assumed_session):
338
+ upload_results_to_s3(str(results_dir), "proj", "comp", "launch-1", metadata=None)
339
+
340
+ call_kwargs = s3_client.upload_file.call_args[1]
341
+ assert "ExtraArgs" not in call_kwargs, (
342
+ f"no metadata must not produce ExtraArgs, got: {call_kwargs}"
343
+ )
344
+
345
+ @pytest.mark.unit
346
+ def test_no_component_uses_default_key_segment(
347
+ self, tmp_path: Path, mock_s3_setup: tuple[MagicMock, MagicMock, MagicMock]
348
+ ) -> None:
349
+ """When component is None the S3 key uses 'default' as the second segment.
350
+
351
+ Catches: KeyError / wrong key when component is omitted.
352
+ """
353
+ mock_session, assumed_session, s3_client = mock_s3_setup
354
+ results_dir = tmp_path / "allure-results"
355
+ results_dir.mkdir()
356
+ (results_dir / "r1-result.json").write_text('{"uuid": "r1"}')
357
+
358
+ with patch.object(s3_replica_module, "_session", mock_session), \
359
+ patch("charisma_cli.s3_replica.boto3.session.Session", return_value=assumed_session):
360
+ upload_results_to_s3(str(results_dir), "my-proj", None, "launch-1")
361
+
362
+ key = s3_client.upload_file.call_args[0][2]
363
+ assert key.startswith("my-proj/default/launch-1/"), f"expected 'default' segment, got: {key}"
364
+
365
+ @pytest.mark.unit
366
+ def test_assume_role_called_with_correct_arn(self, tmp_path: Path) -> None:
367
+ """STS assume_role is called with the role ARN matching the region.
368
+
369
+ Catches: wrong role ARN → assume_role fails in prod.
370
+ """
371
+ results_dir = tmp_path / "allure-results"
372
+ results_dir.mkdir()
373
+ (results_dir / "r1-result.json").write_text('{"uuid": "r1"}')
374
+
375
+ mock_session = MagicMock()
376
+ mock_session.region_name = "ap-south-1"
377
+
378
+ sts_client = MagicMock()
379
+ sts_client.assume_role.return_value = {
380
+ "Credentials": {
381
+ "AccessKeyId": "AKIA-TEST",
382
+ "SecretAccessKey": "secret",
383
+ "SessionToken": "token",
384
+ }
385
+ }
386
+ mock_session.client.return_value = sts_client
387
+
388
+ assumed_session = MagicMock()
389
+ assumed_session.client.return_value = MagicMock()
390
+
391
+ with patch.object(s3_replica_module, "_session", mock_session), \
392
+ patch("charisma_cli.s3_replica.boto3.session.Session", return_value=assumed_session):
393
+ upload_results_to_s3(str(results_dir), "proj", "comp", "launch-1")
394
+
395
+ assume_call = sts_client.assume_role.call_args
396
+ assert assume_call[1]["RoleArn"] == (
397
+ f"arn:aws:iam::{_DEFAULT_CHARISMA_ACCOUNT_ID}:role/charisma-replica-upload-ap-south-1-prod"
398
+ ), f"wrong role ARN: {assume_call[1]['RoleArn']}"
399
+ assert assume_call[1]["RoleSessionName"] == "charismactl-replica"
File without changes