SECTION 04 · 45 MIN READ & EXPLORE
Test and publish the visitor application
Run unit and PostgreSQL integration tests, then publish a commit-tagged container image.
A pipeline with real feedback
Upload the extracted module to a practice GitLab project and build a passing test-and-image pipeline.
Your mission
- Upload the extracted module to a practice GitLab project and build a passing test-and-image pipeline.
Download and extract the archive. Work inside 07-gitlab-ci; upload its contents to the root of a GitLab project when a pipeline is involved.
Copy mini-project/.gitlab-ci.yml to the repository root; keep mini-project as a subdirectory. Register or select a runner capable of running the configured Docker jobs.
Build confidence one job at a time
Inspect the application and tests
Read the connection environment variables and compare the unit and integration tests. The integration test uses PostgreSQL, not the old generated SQLite file.
Run the test jobs
Push a practice branch, inspect each job log, then deliberately break a unit assertion and confirm that the pipeline reports the failure. Revert the change.
Publish the image
Merge a passing change into the main branch. The image job needs a Docker-in-Docker capable runner and the project’s container registry. Inspect the commit-tagged image in the registry.
How to know it worked
- Unit and integration jobs pass independently.
- The main branch builds an image tagged with its commit SHA.
Explore the files
.gitlab-ci.yml
stages:
- build-deps
- test
- deploy
variables:
PIP_CACHE_DIR: "$CI_PROJECT_DIR/.pip-cache"
POSTGRES_DB: visitors
POSTGRES_USER: postgres
POSTGRES_PASSWORD: password
POSTGRES_HOST: postgres
.mini-project-base:
image: python:3.11-slim
variables:
PROJECT_DIR: "mini-project"
cache:
key:
files:
- mini-project/requirements.txt
paths:
- .pip-cache/
before_script:
- cd $PROJECT_DIR
- pip install --cache-dir $PIP_CACHE_DIR -r requirements.txt
install-deps:
extends: .mini-project-base
stage: build-deps
script:
- echo "Dependencies installed via base job"
unit-test:
extends: .mini-project-base
stage: test
script:
- python -m pytest tests/test_unit.py
integration-test:
extends: .mini-project-base
stage: test
services:
- postgres:13
script:
- python -m pytest tests/test_integration.py
report-tests:
stage: test
needs: ["unit-test", "integration-test"]
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
script:
- echo "Tests completed successfully."
build-image:
stage: deploy
image: docker:latest
services:
- docker:dind
rules:
- if: $CI_COMMIT_BRANCH == "main"
before_script:
- export PROJECT_DIR="mini-project"
- cd $PROJECT_DIR
script:
- printf '%s' "$CI_REGISTRY_PASSWORD" | docker login -u "$CI_REGISTRY_USER" --password-stdin "$CI_REGISTRY"
- docker build -t $CI_REGISTRY_IMAGE/mini-project:$CI_COMMIT_SHA .
- docker push $CI_REGISTRY_IMAGE/mini-project:$CI_COMMIT_SHAapp.py
import os
import psycopg2
from flask import Flask, g
from datetime import datetime
app = Flask(__name__)
# Target Date: CAN 2025 Kickoff - December 21, 2025
TARGET_DATE = datetime(2025, 12, 21, 20, 0, 0)
def get_db_connection():
conn = psycopg2.connect(
host=os.environ.get('POSTGRES_HOST', 'localhost'),
database=os.environ.get('POSTGRES_DB', 'visitors'),
user=os.environ.get('POSTGRES_USER', 'postgres'),
password=os.environ.get('POSTGRES_PASSWORD', 'password')
)
return conn
def get_db():
if 'db' not in g:
g.db = get_db_connection()
return g.db
@app.teardown_appcontext
def close_db(error):
db = g.pop('db', None)
if db is not None:
db.close()
def init_db():
conn = get_db_connection()
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS visitors (count INTEGER)")
cur.execute("SELECT count FROM visitors")
if cur.fetchone() is None:
cur.execute("INSERT INTO visitors (count) VALUES (0)")
conn.commit()
cur.close()
conn.close()
@app.route("/")
def home():
# 1. Update Visitor Count
conn = get_db()
cur = conn.cursor()
cur.execute("UPDATE visitors SET count = count + 1")
conn.commit()
cur.execute("SELECT count FROM visitors")
count = cur.fetchone()[0]
cur.close()
# 2. Calculate Countdown
now = datetime.now()
remaining = TARGET_DATE - now
if remaining.total_seconds() < 0:
timer_text = "KICKOFF HAS STARTED!"
else:
days = remaining.days
hours, remainder = divmod(remaining.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
timer_text = f"{days} Days, {hours} Hours, {minutes} Minutes, {seconds} Seconds"
# 3. Simple HTML Template
html_content = f"""
<html>
<head>
<title>CAN 2025 Countdown</title>
<style>
body {{ font-family: 'Verdana', sans-serif; text-align: center; padding-top: 50px; background-color: #c1272d; color: white; }}
h1 {{ font-size: 4em; margin-bottom: 0; }}
.timer {{ font-size: 2em; background: #006233; padding: 20px; border-radius: 10px; display: inline-block; margin-top: 20px; }}
.visitor {{ margin-top: 30px; font-size: 1.2em; color: #ffbf00; }}
</style>
</head>
<body>
<h1>DIMA MAGHRIB! 🇲🇦</h1>
<h3>Countdown to CAN 2025 Kickoff</h3>
<div class="timer">{timer_text}</div>
<div class="visitor">Visitor Count: {count}</div>
</body>
</html>
"""
return html_content
if __name__ == "__main__":
# In a real scenario, we might want to wait for DB to be ready
try:
init_db()
except Exception as e:
print(f"DB Init failed: {e}")
app.run(host="0.0.0.0", port=5000)test_unit.py
import pytest
from unittest.mock import MagicMock, patch
from app import app
@pytest.fixture
def client():
app.config['TESTING'] = True
with app.test_client() as client:
yield client
@patch('app.get_db_connection')
def test_home_page(mock_get_db_conn, client):
"""Test that the home page loads correctly."""
# Mock the database connection and cursor
mock_conn = MagicMock()
mock_cursor = MagicMock()
mock_get_db_conn.return_value = mock_conn
mock_conn.cursor.return_value = mock_cursor
# Mock fetchone for visitor count
mock_cursor.fetchone.return_value = (42,) # Return a fake count
rv = client.get('/')
assert rv.status_code == 200
assert b"CAN 2025" in rv.data
assert b"DIMA MAGHRIB" in rv.data
assert b"Visitor Count: 42" in rv.data
test_integration.py
import pytest
from app import app, init_db
@pytest.fixture
def client():
# POSTGRES_* environment variables select the disposable CI service database.
app.config['TESTING'] = True
with app.app_context():
init_db()
with app.test_client() as client:
yield client
def test_visitor_counter(client):
"""Test that the visitor counter increments."""
# First request
rv = client.get('/')
assert rv.status_code == 200
first_count = get_count_from_response(rv.data)
# Second request
rv = client.get('/')
assert rv.status_code == 200
second_count = get_count_from_response(rv.data)
assert second_count == first_count + 1
def get_count_from_response(data):
"""Extract visitor count from HTML."""
# Simple string parsing
content = data.decode('utf-8')
start = content.find("Visitor Count: ") + len("Visitor Count: ")
end = content.find("</div>", start)
return int(content[start:end])Dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .
# Initialize DB during build or ensure it's created at runtime.
# For simplicity, we'll let the app create it if missing, but we need write permissions.
# In a real app, we'd use a volume. Here it's inside the container.
EXPOSE 5000
CMD ["python", "app.py"]Pause and predict
Why use a commit SHA in an image tag?
Try your own explanation first. These notes stay on this page and are not saved or graded.
Show explanation
It connects the built image to a specific source revision. A moving latest tag does not identify that revision by itself.
Take a moment to explain the idea in your own words.