anthonycmartin-bicep-testing 0.1.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.
@@ -0,0 +1,27 @@
1
+ Metadata-Version: 2.4
2
+ Name: anthonycmartin-bicep-testing
3
+ Version: 0.1.0
4
+ Summary: Test Bicep infrastructure by evaluating deployment snapshots locally.
5
+ Author: Anthony Martin
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/anthony-c-martin/bicep-testing
8
+ Project-URL: Repository, https://github.com/anthony-c-martin/bicep-testing
9
+ Project-URL: Issues, https://github.com/anthony-c-martin/bicep-testing/issues
10
+ Requires-Python: >=3.11
11
+ Description-Content-Type: text/markdown
12
+ Requires-Dist: anthonycmartin-bicep-rpc-client>=0.1.0
13
+ Requires-Dist: azure-mgmt-resource-deploymentstacks==1.0.0
14
+ Provides-Extra: test
15
+ Requires-Dist: pytest>=8.0; extra == "test"
16
+
17
+ # Bicep Testing for Python
18
+
19
+ `anthonycmartin-bicep-testing` evaluates Bicep deployment snapshots locally and supports opt-in live deployment tests through idiomatic Python APIs.
20
+
21
+ ## Install
22
+
23
+ ```sh
24
+ python -m pip install anthonycmartin-bicep-testing
25
+ ```
26
+
27
+ See the [Python documentation](https://github.com/anthony-c-martin/bicep-testing/blob/main/docs/python.md) for usage and lifecycle examples.
@@ -0,0 +1,11 @@
1
+ # Bicep Testing for Python
2
+
3
+ `anthonycmartin-bicep-testing` evaluates Bicep deployment snapshots locally and supports opt-in live deployment tests through idiomatic Python APIs.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ python -m pip install anthonycmartin-bicep-testing
9
+ ```
10
+
11
+ See the [Python documentation](https://github.com/anthony-c-martin/bicep-testing/blob/main/docs/python.md) for usage and lifecycle examples.
@@ -0,0 +1,33 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "anthonycmartin-bicep-testing"
7
+ version = "0.1.0"
8
+ description = "Test Bicep infrastructure by evaluating deployment snapshots locally."
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "MIT"
12
+ authors = [{ name = "Anthony Martin" }]
13
+ dependencies = [
14
+ "anthonycmartin-bicep-rpc-client>=0.1.0",
15
+ "azure-mgmt-resource-deploymentstacks==1.0.0",
16
+ ]
17
+
18
+ [project.urls]
19
+ Homepage = "https://github.com/anthony-c-martin/bicep-testing"
20
+ Repository = "https://github.com/anthony-c-martin/bicep-testing"
21
+ Issues = "https://github.com/anthony-c-martin/bicep-testing/issues"
22
+
23
+ [project.optional-dependencies]
24
+ test = ["pytest>=8.0"]
25
+
26
+ [tool.pytest.ini_options]
27
+ testpaths = ["tests"]
28
+
29
+ [tool.setuptools.packages.find]
30
+ where = ["src"]
31
+
32
+ [tool.setuptools.package-data]
33
+ "anthonycmartin.bicep_testing" = ["py.typed"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,13 @@
1
+ """Test Bicep infrastructure by evaluating deployment snapshots locally."""
2
+
3
+ from .models import DeployResult, DeploymentResource, SnapshotMetadata, SnapshotResource, SnapshotResult
4
+ from .session import BicepTestSession
5
+
6
+ __all__ = [
7
+ "BicepTestSession",
8
+ "DeployResult",
9
+ "DeploymentResource",
10
+ "SnapshotMetadata",
11
+ "SnapshotResource",
12
+ "SnapshotResult",
13
+ ]
@@ -0,0 +1,129 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from collections.abc import Callable
5
+ from threading import Lock
6
+ from typing import Any, Self
7
+
8
+
9
+ @dataclass(frozen=True, slots=True)
10
+ class DeploymentResource:
11
+ """A resource managed by a Deployment Stack."""
12
+
13
+ id: str
14
+ type: str | None = None
15
+
16
+
17
+ @dataclass(frozen=True, slots=True, init=False)
18
+ class DeployResult:
19
+ """Outputs and resources from a deployment, with deterministic cleanup."""
20
+
21
+ outputs: dict[str, Any]
22
+ resources: tuple[DeploymentResource, ...]
23
+ _teardown: Callable[[], None] = field(repr=False, compare=False)
24
+ _lock: Lock = field(repr=False, compare=False)
25
+ _closed: list[bool] = field(repr=False, compare=False)
26
+ _teardown_error: list[BaseException | None] = field(repr=False, compare=False)
27
+
28
+ @classmethod
29
+ def _create(
30
+ cls,
31
+ outputs: dict[str, Any],
32
+ resources: tuple[DeploymentResource, ...],
33
+ teardown: Callable[[], None],
34
+ ) -> DeployResult:
35
+ result = object.__new__(cls)
36
+ object.__setattr__(result, "outputs", outputs)
37
+ object.__setattr__(result, "resources", resources)
38
+ object.__setattr__(result, "_teardown", teardown)
39
+ object.__setattr__(result, "_lock", Lock())
40
+ object.__setattr__(result, "_closed", [False])
41
+ object.__setattr__(result, "_teardown_error", [None])
42
+ return result
43
+
44
+ def close(self) -> None:
45
+ """Delete the Deployment Stack and all resources it manages."""
46
+ with self._lock:
47
+ if self._closed[0]:
48
+ if self._teardown_error[0] is not None:
49
+ raise self._teardown_error[0]
50
+ return
51
+ self._closed[0] = True
52
+ try:
53
+ self._teardown()
54
+ except BaseException as error:
55
+ self._teardown_error[0] = error
56
+ raise
57
+
58
+ def __enter__(self) -> Self:
59
+ return self
60
+
61
+ def __exit__(self, *_: object) -> None:
62
+ self.close()
63
+
64
+
65
+ @dataclass(frozen=True, slots=True)
66
+ class SnapshotMetadata:
67
+ """Azure deployment context used to evaluate a snapshot."""
68
+
69
+ tenant_id: str | None = None
70
+ subscription_id: str | None = None
71
+ resource_group: str | None = None
72
+ location: str | None = None
73
+ deployment_name: str | None = None
74
+
75
+ def _as_rpc_dict(self) -> dict[str, str]:
76
+ values = {
77
+ "tenantId": self.tenant_id,
78
+ "subscriptionId": self.subscription_id,
79
+ "resourceGroup": self.resource_group,
80
+ "location": self.location,
81
+ "deploymentName": self.deployment_name,
82
+ }
83
+ return {name: value for name, value in values.items() if value is not None}
84
+
85
+
86
+ @dataclass(frozen=True, slots=True)
87
+ class SnapshotResource:
88
+ """A resource predicted by a Bicep snapshot."""
89
+
90
+ id: str
91
+ type: str
92
+ name: str
93
+ api_version: str
94
+ location: str | None = None
95
+ properties: dict[str, Any] = field(default_factory=dict)
96
+ additional_properties: dict[str, Any] = field(default_factory=dict)
97
+
98
+ @classmethod
99
+ def _from_dict(cls, value: dict[str, Any]) -> SnapshotResource:
100
+ known = {"id", "type", "name", "apiVersion", "location", "properties"}
101
+ return cls(
102
+ id=value["id"],
103
+ type=value["type"],
104
+ name=value["name"],
105
+ api_version=value["apiVersion"],
106
+ location=value.get("location"),
107
+ properties=value.get("properties", {}),
108
+ additional_properties={key: item for key, item in value.items() if key not in known},
109
+ )
110
+
111
+
112
+ @dataclass(frozen=True, slots=True)
113
+ class SnapshotResult:
114
+ """The predicted result of evaluating a Bicep parameters file."""
115
+
116
+ predicted_resources: tuple[SnapshotResource, ...]
117
+ diagnostics: tuple[str, ...]
118
+ outputs: dict[str, Any]
119
+
120
+ @classmethod
121
+ def _from_dict(cls, value: dict[str, Any]) -> SnapshotResult:
122
+ return cls(
123
+ predicted_resources=tuple(
124
+ SnapshotResource._from_dict(resource)
125
+ for resource in value.get("predictedResources", [])
126
+ ),
127
+ diagnostics=tuple(value.get("diagnostics", [])),
128
+ outputs=value.get("outputs", {}),
129
+ )
@@ -0,0 +1 @@
1
+ # Marker file for PEP 561.
@@ -0,0 +1,171 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ from typing import Any, Protocol, Self
7
+
8
+ from anthonycmartin.bicep_rpc_client import (
9
+ BicepClient,
10
+ BicepClientConfiguration,
11
+ BicepClientFactory,
12
+ CompileParamsRequest,
13
+ GetSnapshotRequest,
14
+ SnapshotMetadata as RpcSnapshotMetadata,
15
+ )
16
+
17
+ from .models import DeployResult, DeploymentResource, SnapshotMetadata, SnapshotResult
18
+
19
+
20
+ class _DeploymentStacksOperations(Protocol):
21
+ def begin_create_or_update_at_resource_group(
22
+ self, resource_group: str, stack_name: str, deployment_stack: dict[str, Any]
23
+ ) -> Any: ...
24
+
25
+ def begin_delete_at_resource_group(
26
+ self, resource_group: str, stack_name: str, **kwargs: Any
27
+ ) -> Any: ...
28
+
29
+
30
+ def _create_deployment_stacks_operations(credential: Any, subscription_id: str) -> _DeploymentStacksOperations:
31
+ from azure.mgmt.resource.deploymentstacks import DeploymentStacksClient
32
+
33
+ return DeploymentStacksClient(credential, subscription_id).deployment_stacks
34
+
35
+
36
+ class BicepTestSession:
37
+ """Installs and invokes a pinned Bicep CLI for infrastructure tests."""
38
+
39
+ def __init__(self, client: BicepClient) -> None:
40
+ self._client = client
41
+
42
+ @classmethod
43
+ def create(cls, bicep_version: str) -> Self:
44
+ """Install a Bicep CLI version if needed and start its RPC client."""
45
+ if not bicep_version.strip():
46
+ raise ValueError("bicep_version must not be empty")
47
+ client = BicepClientFactory().initialize(
48
+ BicepClientConfiguration(bicep_version=bicep_version)
49
+ )
50
+ version = client.get_version()
51
+ if _version_tuple(version) < (0, 36, 1):
52
+ client.close()
53
+ raise RuntimeError(f"Bicep CLI 0.36.1 or later is required; detected {version}")
54
+ return cls(client)
55
+
56
+ def snapshot(
57
+ self,
58
+ file_path: str | os.PathLike[str],
59
+ metadata: SnapshotMetadata | None = None,
60
+ ) -> SnapshotResult:
61
+ """Evaluate a Bicep parameters file without deploying it."""
62
+ path = Path(file_path).resolve()
63
+ snapshot_metadata = metadata or SnapshotMetadata()
64
+ response = self._client.get_snapshot(
65
+ GetSnapshotRequest(
66
+ path,
67
+ RpcSnapshotMetadata(
68
+ tenant_id=snapshot_metadata.tenant_id,
69
+ subscription_id=snapshot_metadata.subscription_id,
70
+ resource_group=snapshot_metadata.resource_group,
71
+ location=snapshot_metadata.location,
72
+ deployment_name=snapshot_metadata.deployment_name,
73
+ ),
74
+ )
75
+ )
76
+ return SnapshotResult._from_dict(json.loads(response.snapshot))
77
+
78
+ def deploy(
79
+ self,
80
+ credential: Any,
81
+ file_path: str | os.PathLike[str],
82
+ subscription_id: str,
83
+ resource_group: str,
84
+ stack_name: str,
85
+ parameter_overrides: dict[str, Any] | None = None,
86
+ ) -> DeployResult:
87
+ """Compile and deploy a Bicep parameters file as a resource-group Deployment Stack."""
88
+ if credential is None:
89
+ raise ValueError("credential must not be None")
90
+ if not subscription_id or not resource_group or not stack_name:
91
+ raise ValueError("subscription_id, resource_group, and stack_name must not be empty")
92
+ compilation = self._client.compile_params(
93
+ CompileParamsRequest(
94
+ Path(file_path).resolve(), parameter_overrides or {}
95
+ )
96
+ )
97
+ if not compilation.success or not compilation.template or not compilation.parameters:
98
+ diagnostics = json.dumps(compilation.diagnostics)
99
+ raise RuntimeError(f"Bicep parameter compilation failed: {diagnostics}")
100
+
101
+ template = json.loads(compilation.template)
102
+ parameter_file = json.loads(compilation.parameters)
103
+ operations = _create_deployment_stacks_operations(credential, subscription_id)
104
+ stack = operations.begin_create_or_update_at_resource_group(
105
+ resource_group,
106
+ stack_name,
107
+ {
108
+ "properties": {
109
+ "template": template,
110
+ "parameters": parameter_file.get("parameters", {}),
111
+ "actionOnUnmanage": {
112
+ "resources": "delete",
113
+ "resourceGroups": "delete",
114
+ "managementGroups": "delete",
115
+ "resourcesWithoutDeleteSupport": "fail",
116
+ },
117
+ "denySettings": {"mode": "none"},
118
+ }
119
+ },
120
+ ).result()
121
+
122
+ outputs = {
123
+ name: value.get("value", value) if isinstance(value, dict) else value
124
+ for name, value in (getattr(stack, "outputs", None) or {}).items()
125
+ }
126
+ resources = tuple(
127
+ DeploymentResource(id=resource.id, type=_resource_type(resource.id))
128
+ for resource in (getattr(stack, "resources", None) or ())
129
+ if getattr(resource, "id", None)
130
+ )
131
+
132
+ def teardown() -> None:
133
+ operations.begin_delete_at_resource_group(
134
+ resource_group,
135
+ stack_name,
136
+ unmanage_action_resources="delete",
137
+ unmanage_action_resource_groups="delete",
138
+ unmanage_action_management_groups="delete",
139
+ unmanage_action_resources_without_delete_support="fail",
140
+ ).result()
141
+
142
+ return DeployResult._create(outputs, resources, teardown)
143
+
144
+ def close(self) -> None:
145
+ """Disconnect from the Bicep CLI and terminate its process."""
146
+ self._client.close()
147
+
148
+ def __enter__(self) -> Self:
149
+ return self
150
+
151
+ def __exit__(self, *_: object) -> None:
152
+ self.close()
153
+
154
+
155
+ def _version_tuple(version: str) -> tuple[int, ...]:
156
+ return tuple(int(part.split("-")[0]) for part in version.split("."))
157
+
158
+
159
+ def _resource_type(resource_id: str) -> str | None:
160
+ parts = resource_id.strip("/").split("/")
161
+ try:
162
+ provider_index = next(
163
+ index for index, part in enumerate(parts) if part.lower() == "providers"
164
+ )
165
+ except StopIteration:
166
+ return None
167
+ if provider_index + 2 >= len(parts):
168
+ return None
169
+ return "/".join(
170
+ [parts[provider_index + 1], *parts[provider_index + 2 :: 2]]
171
+ )
@@ -0,0 +1,27 @@
1
+ Metadata-Version: 2.4
2
+ Name: anthonycmartin-bicep-testing
3
+ Version: 0.1.0
4
+ Summary: Test Bicep infrastructure by evaluating deployment snapshots locally.
5
+ Author: Anthony Martin
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/anthony-c-martin/bicep-testing
8
+ Project-URL: Repository, https://github.com/anthony-c-martin/bicep-testing
9
+ Project-URL: Issues, https://github.com/anthony-c-martin/bicep-testing/issues
10
+ Requires-Python: >=3.11
11
+ Description-Content-Type: text/markdown
12
+ Requires-Dist: anthonycmartin-bicep-rpc-client>=0.1.0
13
+ Requires-Dist: azure-mgmt-resource-deploymentstacks==1.0.0
14
+ Provides-Extra: test
15
+ Requires-Dist: pytest>=8.0; extra == "test"
16
+
17
+ # Bicep Testing for Python
18
+
19
+ `anthonycmartin-bicep-testing` evaluates Bicep deployment snapshots locally and supports opt-in live deployment tests through idiomatic Python APIs.
20
+
21
+ ## Install
22
+
23
+ ```sh
24
+ python -m pip install anthonycmartin-bicep-testing
25
+ ```
26
+
27
+ See the [Python documentation](https://github.com/anthony-c-martin/bicep-testing/blob/main/docs/python.md) for usage and lifecycle examples.
@@ -0,0 +1,13 @@
1
+ README.md
2
+ pyproject.toml
3
+ src/anthonycmartin/bicep_testing/__init__.py
4
+ src/anthonycmartin/bicep_testing/models.py
5
+ src/anthonycmartin/bicep_testing/py.typed
6
+ src/anthonycmartin/bicep_testing/session.py
7
+ src/anthonycmartin_bicep_testing.egg-info/PKG-INFO
8
+ src/anthonycmartin_bicep_testing.egg-info/SOURCES.txt
9
+ src/anthonycmartin_bicep_testing.egg-info/dependency_links.txt
10
+ src/anthonycmartin_bicep_testing.egg-info/requires.txt
11
+ src/anthonycmartin_bicep_testing.egg-info/top_level.txt
12
+ tests/test_deployment.py
13
+ tests/test_snapshot.py
@@ -0,0 +1,5 @@
1
+ anthonycmartin-bicep-rpc-client>=0.1.0
2
+ azure-mgmt-resource-deploymentstacks==1.0.0
3
+
4
+ [test]
5
+ pytest>=8.0
@@ -0,0 +1,89 @@
1
+ from pathlib import Path
2
+ from types import SimpleNamespace
3
+ from unittest.mock import patch
4
+
5
+ from anthonycmartin.bicep_rpc_client import CompileParamsRequest, CompileParamsResponse
6
+ from anthonycmartin.bicep_testing import BicepTestSession
7
+
8
+
9
+ class FakeRpcClient:
10
+ def __init__(self) -> None:
11
+ self.request: CompileParamsRequest | None = None
12
+
13
+ def compile_params(self, request: CompileParamsRequest) -> CompileParamsResponse:
14
+ self.request = request
15
+ return CompileParamsResponse(
16
+ success=True,
17
+ diagnostics=(),
18
+ template='{"resources":[]}',
19
+ parameters='{"parameters":{"message":{"value":"hello"}}}',
20
+ )
21
+
22
+ def close(self) -> None:
23
+ pass
24
+
25
+
26
+ class FakePoller:
27
+ def __init__(self, value: object = None) -> None:
28
+ self.value = value
29
+
30
+ def result(self) -> object:
31
+ return self.value
32
+
33
+
34
+ class FakeOperations:
35
+ def __init__(self) -> None:
36
+ self.request: dict[str, object] = {}
37
+ self.delete_calls = 0
38
+
39
+ def begin_create_or_update_at_resource_group(
40
+ self, resource_group: str, stack_name: str, deployment_stack: dict[str, object]
41
+ ) -> FakePoller:
42
+ self.request = deployment_stack
43
+ resource = SimpleNamespace(
44
+ id="/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Storage/storageAccounts/example"
45
+ )
46
+ stack = SimpleNamespace(
47
+ outputs={"endpoint": {"value": "https://example.test"}},
48
+ resources=[resource],
49
+ )
50
+ return FakePoller(stack)
51
+
52
+ def begin_delete_at_resource_group(
53
+ self, resource_group: str, stack_name: str, **kwargs: object
54
+ ) -> FakePoller:
55
+ self.delete_calls += 1
56
+ assert kwargs["unmanage_action_resources_without_delete_support"] == "fail"
57
+ return FakePoller()
58
+
59
+
60
+ def test_deploy_compiles_deploys_and_tears_down_once() -> None:
61
+ rpc = FakeRpcClient()
62
+ operations = FakeOperations()
63
+ session = BicepTestSession(rpc) # type: ignore[arg-type]
64
+
65
+ with patch(
66
+ "anthonycmartin.bicep_testing.session._create_deployment_stacks_operations",
67
+ return_value=operations,
68
+ ):
69
+ result = session.deploy(
70
+ object(),
71
+ "main.bicepparam",
72
+ "subscription",
73
+ "resource-group",
74
+ "stack",
75
+ {"message": "override"},
76
+ )
77
+
78
+ assert rpc.request is not None
79
+ assert Path(rpc.request.path).is_absolute()
80
+ assert rpc.request.parameter_overrides == {"message": "override"}
81
+ properties = operations.request["properties"]
82
+ assert isinstance(properties, dict)
83
+ assert properties["parameters"] == {"message": {"value": "hello"}}
84
+ assert result.outputs == {"endpoint": "https://example.test"}
85
+ assert result.resources[0].type == "Microsoft.Storage/storageAccounts"
86
+
87
+ result.close()
88
+ result.close()
89
+ assert operations.delete_calls == 1
@@ -0,0 +1,25 @@
1
+ from pathlib import Path
2
+
3
+ from anthonycmartin.bicep_testing import BicepTestSession, SnapshotMetadata
4
+
5
+
6
+ def test_snapshot_matches_reference_behavior() -> None:
7
+ fixture = Path(__file__).parents[3] / "samples" / "infra" / "main.bicepparam"
8
+ metadata = SnapshotMetadata(
9
+ tenant_id="00000000-0000-0000-0000-000000000000",
10
+ subscription_id="00000000-0000-0000-0000-000000000000",
11
+ resource_group="sample-rg",
12
+ location="eastus",
13
+ deployment_name="sample-deployment",
14
+ )
15
+
16
+ with BicepTestSession.create("0.43.1") as session:
17
+ snapshot = session.snapshot(fixture, metadata)
18
+
19
+ assert snapshot.diagnostics == ()
20
+ assert len(snapshot.predicted_resources) == 3
21
+ assert {resource.name for resource in snapshot.predicted_resources} == {
22
+ "sampleprimary",
23
+ "samplebackup",
24
+ "samplekv",
25
+ }