Concept Explanation
Imagine you have a team of 10 developers. Every time someone makes a change, you need to:
- Check if the code matches the style (Linting).
- Run all 500 tests (Testing).
- If everything is perfect, upload it to the server (Deployment).
Doing this manually is slow and prone to errors. CI/CD (Continuous Integration / Continuous Deployment) handles this automatically using tools like GitHub Actions.
Syntax or Core Structure
The YAML Workflow
Most CI/CD tools use a simple text file (.yaml) to define the steps.
# Example GitHub Action
name: Run My Tests
on: [push] # Run every time I push code
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.10", "3.11", "3.12"]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
pip install -r requirements.txt
pip install pytest pytest-cov ruff
- name: Lint with Ruff
run: ruff check .
- name: Run tests
run: pytest --cov=app --cov-report=xml
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v3
Code Example #1 (Basic)
Using Ruff for super-fast linting.
# Install
pip install ruff
# Run it
ruff check . # Instantly finds bugs and style issues
Code Example #2 (Intermediate)
Testing with Code Coverage.
# Install
pip install pytest-cov
# Run and see exactly which lines of code are NOT tested
pytest --cov=my_app
Real World Example
The Safety Portal: When you open a "Pull Request" on GitHub, a bot immediately runs your tests. If a test fails, the "Merge" button turns red and is disabled. This prevents broken code from ever reaching your real users.
Common Mistakes
- Chasing 100% Coverage: Trying to test every single line, even simple things like
return x. Aim for 80%. Don't waste time testing trivial code. - Slow Pipelines: If your tests take 20 minutes to run, developers will stop running them. Use parallelism (
pytest-xdist) to make them fast. - Ignoring Linting: Tests prove the code works, but Linting prove the code is clean. You need both.
Best Practices
- Fail Fast: Run the fastest tests (Unit tests) first, and the slowest tests (Integration tests) last.
- Isolated Environments: Always use
pip install -r requirements.txtin your pipeline to ensure the tests run in a fresh, clean environment every time. - Automate Deployment: Once the tests pass on the
mainbranch, have your CI/CD bot automatically deploy the code to a "Staging" server for final review.
Practice Exercises
- The Ruff Check: Install
ruffand run it on one of your existing Python files. Fix all the errors it finds. - The Coverage Goal: Create a script with 3 functions. Write tests for only 2 of them. Run
pytest --covand observe the report. Then write the 3rd test to reach 100%. - The Action Simulator: Research how to create a
.github/workflows/main.ymlfile and write a simple YAML file that runsprint("Tests Passed")whenever code is pushed.