How to Attach an SBOM to a Release in Python (Mock)
A mock function that attaches a Software Bill of Materials (SBOM) to a GitHub-style release by counting its components and marking the upload as attached.
Python code
24 linesimport json
from pathlib import Path
def attach_sbom_mock(sbom_path: Path, release_tag: str, artifact_name: str) -> dict:
"""Mock attaching an SBOM to a release, returning the simulated upload result."""
sbom = json.loads(sbom_path.read_text())
return {
"release_tag": release_tag,
"artifact": artifact_name,
"sbom_components": len(sbom.get("components", [])),
"status": "attached",
"mock": True,
}
if __name__ == "__main__":
sample_sbom = Path("sample_sbom.json")
sample_sbom.write_text(
json.dumps({"components": [{"name": "requests"}, {"name": "flask"}]})
)
result = attach_sbom_mock(sample_sbom, "v1.2.3", "release-sbom.json")
print(json.dumps(result, indent=2))
sample_sbom.unlink()
Output
{
"release_tag": "v1.2.3",
"artifact": "release-sbom.json",
"sbom_components": 2,
"status": "attached",
"mock": true
}
How it works
The function reads the SBOM file from disk using Path.read_text and parses it with the standard json module. It extracts the list of components from the SBOM's components key, which is a common field in CycloneDX or SPDX formats. The mock returns a dictionary shaped like a real upload response, including the release tag, artifact name, and component count. Because it's a mock, it sidesteps network calls and writable API permissions, making it ideal for CI tests and local development.
Common mistakes
- Assuming all SBOMs have a top-level `components` key — always use `.get(..., [])`
- Forgetting to delete temp files (like `sample_sbom.json`) in tests, leaving dirty state
- Hardcoding file paths instead of accepting a `Path` parameter
Variations
- Replace the mock with a real `requests.post` call to a GitHub Release API endpoint
- Use `json.loads(sbom_path.read_text(encoding='utf-8'))` to specify encoding for Windows compat
Real-world use cases
- Simulating SBOM attach behavior in CI scripts before deploying the actual API integration.
- Testing release pipeline logic in local development without hitting the network or using credentials.
- Validating SBOM component counts and artifact naming before rolling out to production release tooling.
Sponsored
More from Production deployment patterns
- Auto Rollback on Error Rate Exceeded in Python medium
- Automate Semantic Versioning with Conventional Commits in Python medium
- Design a Data Helper for Beginners in Python easy
- Docker healthcheck CMD mock in Python easy
- Generate a Mock Artifact Version Tag in Python easy
- Generate a docker-compose.yml with mock services in Python easy
Keep learning
Related tutorials and quizzes for this topic.