GitLab CI Pipeline for Python Projects
Production-ready .gitlab-ci.yml for Python projects with flake8 linting, pytest testing, pip caching, and JUnit report artifacts.
Detailed Explanation
Setting Up Python CI in GitLab
Python CI pipelines in GitLab benefit from pip caching and JUnit-formatted test reports that GitLab can render natively in merge requests.
Pipeline Configuration
stages:
- lint
- test
variables:
PIP_CACHE_DIR: "$CI_PROJECT_DIR/.cache/pip"
flake8:
stage: lint
image: python:3.12-slim
script:
- pip install flake8
- flake8 . --max-line-length=120 --statistics
cache:
key: pip-cache
paths:
- .cache/pip/
policy: pull-push
pytest:
stage: test
image: python:3.12-slim
script:
- pip install -r requirements.txt
- pytest --junitxml=report.xml --cov=src --cov-report=html
cache:
key: pip-cache
paths:
- .cache/pip/
policy: pull-push
artifacts:
paths:
- report.xml
- htmlcov/
expire_in: 30 days
reports:
junit: report.xml
Pip Cache Configuration
Setting PIP_CACHE_DIR to a project-relative path is essential. By default, pip caches to ~/.cache/pip, which is outside the project directory and cannot be cached by GitLab CI. By redirecting to .cache/pip/ inside the project, the cache keyword can preserve downloaded wheels across pipeline runs.
JUnit Reports
The reports: junit: report.xml directive tells GitLab to parse the JUnit XML and display test results directly in merge requests. Developers see which tests failed without opening the job log.
Coverage Reports
Using --cov-report=html generates an HTML coverage report saved as an artifact. GitLab can also extract coverage percentages from job logs if you add a coverage regex to the job configuration.
Use Case
Ideal for Django, Flask, FastAPI, or any Python project using pytest. The pipeline provides immediate lint feedback and detailed test reports visible in GitLab merge requests.
Try It — GitLab CI Config Generator
Related Topics
GitLab CI Pipeline for Node.js Projects
Language Pipelines
GitLab CI Caching Strategies for Faster Pipelines
Caching & Artifacts
Managing Artifacts in GitLab CI Pipelines
Caching & Artifacts
Multi-Stage GitLab CI Pipeline Architecture
Pipeline Architecture
GitLab CI Pipeline for Go Projects
Language Pipelines