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.

Easy Python 3.9+ Aug 9, 2026 Production deployment patterns 14 views 0 copies

Python code

32 lines
Python 3.9+
def 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

stdout
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

  1. Use dataclasses to model Stage and Job objects for type safety
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Production deployment patterns

Related tutorials and quizzes for this topic.