How to simulate GitLab CI stages in Python
Build a lightweight Python mock of GitLab CI pipeline stages to test job sequencing and output locally.
Python code
32 linesdef mock_gitlab_ci_stages():
stages = ["build", "test", "deploy"]
stage_status = {}
for stage in stages:
jobs = []
if stage == "build":
jobs = ["compile", "package"]
elif stage == "test":
jobs = ["unit", "integration", "e2e"]
elif stage == "deploy":
jobs = ["staging", "production"]
stage_status[stage] = {
"jobs": jobs,
"status": None
}
for stage, info in stage_status.items():
for job in info["jobs"]:
print(f"{stage}:{job}:running")
print("mock pipeline executed")
return stage_status
if __name__ == "__main__":
result = mock_gitlab_ci_stages()
for stage, config in result.items():
print(f"Stage {stage} has {len(config['jobs'])} jobs")
Output
build:compile:running
build:package:running
test:unit:running
test:integration:running
test:e2e:running
deploy:staging:running
deploy:production:running
mock pipeline executed
Stage build has 2 jobs
Stage test has 3 jobs
Stage deploy has 2 jobs
How it works
This mock represents a GitLab CI pipeline as a dictionary mapping stage names to job lists and statuses. The loop assigns jobs per stage, then iterates all stages and jobs to simulate execution order. Statuses are set to None as placeholders for real results. The script prints each job as it runs, then saves the full structure for further assertions. Using nested dicts makes it easy to extend with statuses like 'success' or 'failed'.
Common mistakes
- Forgetting to set status per job, leaving None in final reports
- Hardcoding stage order instead of reading from .gitlab-ci.yml
- Using list of tuples instead of dicts, making updates clunky
- Not checking that all stages run in correct sequence
Variations
- Use dataclasses to model Stage and Job objects for type safety
- Read stage definitions from a YAML file using PyYAML for closer simulation
Real-world use cases
- Testing CI pipeline logic locally before pushing to GitLab, speeding up feedback loops.
- Simulating deployment steps in development environments to validate job order without running containers.
- Training new team members on CI stages with a safe, interactive demo.
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.