Skip to content

Practice project: testing notes_chat_app from model to Selenium

After this file, you will assemble a complete learning scenario for testing a Django notes app: model, form, URL, view, permissions, a service with email, mock, Selenium E2E, Docker headless, and coverage.


1. Why you need this

Individual examples are useful, but in real learning a student needs a route.

Not just:

Here is a model test.
Here is a mock.
Here is Selenium.

But like this:

1. Here is a small notes app.
2. Here is the behavior we expect.
3. Here are the tests we write first.
4. Here is how to run them.
5. Here is what a failure looks like.
6. Here is when we add Selenium.

This file is the final practical lesson. It brings all the previous topics together into one project.


2. Mental model

Testing an application is like checking a delivery route.

First we check the small things:

  • whether the box has the right label;
  • whether the address is valid;
  • whether the courier does not take someone else's parcel.

Then we check the bigger route:

  • the user logs in;
  • creates a note;
  • sees it in the list;
  • does not see other people's notes.

And only one or two of the most important routes are checked through a real browser with Selenium.


3. What we are building

Project: notes_chat_app

App: notes

Functionality:

  1. a user can create a note;
  2. a note has title, content, owner, is_archived;
  3. the list shows only the current user's notes;
  4. the form strips spaces from the title;
  5. the title admin is forbidden;
  6. creating a note calls an email service;
  7. Selenium checks the main path: login -> create note -> note appears.

Structure:

notes_chat_app/
├── manage.py
├── notes_chat_app/
│   ├── settings.py
│   └── urls.py
└── notes/
    ├── models.py
    ├── forms.py
    ├── services.py
    ├── views.py
    ├── urls.py
    ├── templates/
    │   └── notes/
    │       ├── note_form.html
    │       └── note_list.html
    └── tests/
        ├── test_models.py
        ├── test_forms.py
        ├── test_urls.py
        ├── test_views.py
        ├── test_services.py
        └── test_e2e.py

4. Application code

4.1 Model

# notes/models.py
from django.conf import settings
from django.db import models


class Note(models.Model):
    owner = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name="notes",
    )
    title = models.CharField(max_length=120)
    content = models.TextField()
    is_archived = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

    def archive(self):
        self.is_archived = True
        self.save(update_fields=["is_archived"])

What is ours here:

  • __str__;
  • archive;
  • ownership via owner.

The mere fact that a CharField stores a string does not need testing. Django already tests that.

4.2 Form

# notes/forms.py
from django import forms

from notes.models import Note


class NoteForm(forms.ModelForm):
    class Meta:
        model = Note
        fields = ["title", "content"]

    def clean_title(self):
        title = self.cleaned_data["title"].strip()

        if title.lower() == "admin":
            raise forms.ValidationError("Title cannot be admin.")

        return title

What to test:

  • valid data;
  • missing title;
  • strip spaces;
  • reserved title.

4.3 Service

# notes/services.py
from django.core.mail import send_mail


def send_note_created_email(email, title):
    send_mail(
        subject="Note created",
        message=f"Your note '{title}' was created.",
        from_email="noreply@example.com",
        recipient_list=[email],
    )

We will mock email in the tests.

4.4 Views

# notes/views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render

from notes.forms import NoteForm
from notes.models import Note
from notes.services import send_note_created_email


@login_required
def note_list(request):
    notes = Note.objects.filter(
        owner=request.user,
        is_archived=False,
    ).order_by("-created_at")

    return render(request, "notes/note_list.html", {"notes": notes})


@login_required
def note_create(request):
    if request.method == "POST":
        form = NoteForm(request.POST)

        if form.is_valid():
            note = form.save(commit=False)
            note.owner = request.user
            note.save()
            send_note_created_email(request.user.email, note.title)
            return redirect("note_list")
    else:
        form = NoteForm()

    return render(request, "notes/note_form.html", {"form": form})

4.5 URLs

# notes/urls.py
from django.urls import path

from notes import views


urlpatterns = [
    path("notes/", views.note_list, name="note_list"),
    path("notes/new/", views.note_create, name="note_create"),
]

In the project urls:

# notes_chat_app/urls.py
from django.contrib import admin
from django.urls import include, path


urlpatterns = [
    path("admin/", admin.site.urls),
    path("", include("django.contrib.auth.urls")),
    path("", include("notes.urls")),
]

5. Test plan

We write tests not chaotically, but in layers.

Step File What we check
1 test_models.py __str__, archive()
2 test_forms.py valid/invalid form, clean_title()
3 test_urls.py URL names lead to the right views
4 test_views.py GET/POST, redirects, templates, ownership
5 test_services.py the email service via mock
6 test_e2e.py the main path in a browser
7 coverage what actually ran

6. Model tests

# notes/tests/test_models.py
from django.contrib.auth import get_user_model
from django.test import TestCase

from notes.models import Note


User = get_user_model()


class NoteModelTest(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(
            username="student",
            email="student@example.com",
            password="pw",
        )

    def test_note_str_returns_title(self):
        note = Note.objects.create(
            owner=self.user,
            title="First note",
            content="Hello",
        )

        self.assertEqual(str(note), "First note")

    def test_archive_marks_note_as_archived(self):
        note = Note.objects.create(
            owner=self.user,
            title="Archive me",
            content="Hello",
        )

        note.archive()
        note.refresh_from_db()

        self.assertTrue(note.is_archived)

Running:

python manage.py test notes.tests.test_models

7. Form tests

# notes/tests/test_forms.py
from django.test import TestCase

from notes.forms import NoteForm


class NoteFormTest(TestCase):
    def test_form_is_valid_with_title_and_content(self):
        form = NoteForm(data={
            "title": "My note",
            "content": "Hello",
        })

        self.assertTrue(form.is_valid())

    def test_form_is_invalid_without_title(self):
        form = NoteForm(data={
            "title": "",
            "content": "Hello",
        })

        self.assertFalse(form.is_valid())
        self.assertIn("title", form.errors)

    def test_form_strips_title_spaces(self):
        form = NoteForm(data={
            "title": "  My note  ",
            "content": "Hello",
        })

        self.assertTrue(form.is_valid())
        self.assertEqual(form.cleaned_data["title"], "My note")

    def test_form_rejects_reserved_admin_title(self):
        form = NoteForm(data={
            "title": "admin",
            "content": "Hello",
        })

        self.assertFalse(form.is_valid())
        self.assertIn("title", form.errors)

What the student should notice:

  • a form test does not need a browser;
  • a form test does not need to create a Note in the DB;
  • we check the validation logic directly.

8. URL tests

# notes/tests/test_urls.py
from django.test import SimpleTestCase
from django.urls import resolve, reverse

from notes.views import note_create, note_list


class NoteUrlsTest(SimpleTestCase):
    def test_note_list_url_resolves_to_note_list_view(self):
        match = resolve(reverse("note_list"))

        self.assertEqual(match.func, note_list)

    def test_note_create_url_resolves_to_note_create_view(self):
        match = resolve(reverse("note_create"))

        self.assertEqual(match.func, note_create)

We use SimpleTestCase here because no database is needed.


9. View tests: list

# notes/tests/test_views.py
from unittest.mock import patch

from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse

from notes.models import Note


User = get_user_model()


class NoteListViewTest(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(
            username="student",
            email="student@example.com",
            password="pw",
        )

    def test_anonymous_user_redirects_to_login(self):
        response = self.client.get(reverse("note_list"))

        self.assertEqual(response.status_code, 302)

    def test_logged_user_can_open_note_list(self):
        self.client.login(username="student", password="pw")

        response = self.client.get(reverse("note_list"))

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, "notes/note_list.html")

    def test_note_list_shows_only_current_user_notes(self):
        other_user = User.objects.create_user(username="other", password="pw")
        own_note = Note.objects.create(
            owner=self.user,
            title="Mine",
            content="Hello",
        )
        Note.objects.create(
            owner=other_user,
            title="Other user note",
            content="Secret",
        )

        self.client.login(username="student", password="pw")
        response = self.client.get(reverse("note_list"))

        notes = list(response.context["notes"])
        self.assertIn(own_note, notes)
        self.assertEqual(len(notes), 1)

    def test_archived_notes_are_hidden(self):
        Note.objects.create(
            owner=self.user,
            title="Archived",
            content="Hello",
            is_archived=True,
        )

        self.client.login(username="student", password="pw")
        response = self.client.get(reverse("note_list"))

        self.assertEqual(list(response.context["notes"]), [])

These tests matter more than just status_code == 200, because they check business rules.


10. View tests: create + mock email

# notes/tests/test_views.py
class NoteCreateViewTest(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(
            username="student",
            email="student@example.com",
            password="pw",
        )

    def test_anonymous_user_cannot_open_create_page(self):
        response = self.client.get(reverse("note_create"))

        self.assertEqual(response.status_code, 302)

    def test_logged_user_can_open_create_page(self):
        self.client.login(username="student", password="pw")

        response = self.client.get(reverse("note_create"))

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, "notes/note_form.html")

    @patch("notes.views.send_note_created_email")
    def test_logged_user_can_create_note(self, mock_send_email):
        self.client.login(username="student", password="pw")

        response = self.client.post(reverse("note_create"), {
            "title": "Created from test",
            "content": "Hello",
        })

        self.assertRedirects(response, reverse("note_list"))
        note = Note.objects.get(title="Created from test")
        self.assertEqual(note.owner, self.user)
        mock_send_email.assert_called_once_with(
            "student@example.com",
            "Created from test",
        )

    @patch("notes.views.send_note_created_email")
    def test_invalid_form_does_not_create_note_or_send_email(self, mock_send_email):
        self.client.login(username="student", password="pw")

        response = self.client.post(reverse("note_create"), {
            "title": "",
            "content": "Hello",
        })

        self.assertEqual(response.status_code, 200)
        self.assertFalse(Note.objects.exists())
        mock_send_email.assert_not_called()

Why patch exactly notes.views.send_note_created_email?

Because the view imports and uses that name in the notes/views.py file. We mock the place where it is used.


11. Service test

You can test the email service separately:

# notes/tests/test_services.py
from unittest.mock import patch

from django.test import SimpleTestCase

from notes.services import send_note_created_email


class NoteEmailServiceTest(SimpleTestCase):
    @patch("notes.services.send_mail")
    def test_send_note_created_email_calls_send_mail(self, mock_send_mail):
        send_note_created_email("student@example.com", "My note")

        mock_send_mail.assert_called_once_with(
            subject="Note created",
            message="Your note 'My note' was created.",
            from_email="noreply@example.com",
            recipient_list=["student@example.com"],
        )

No database is needed here, so we use SimpleTestCase.


12. Selenium E2E smoke test

You do not need to write Selenium tests for every little thing. But one smoke test for the main route is useful.

Installation:

pip install selenium

Test:

# notes/tests/test_e2e.py
from django.contrib.auth import get_user_model
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait


User = get_user_model()


class NoteAppE2ETest(StaticLiveServerTestCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.browser = webdriver.Firefox()
        cls.browser.implicitly_wait(3)

    @classmethod
    def tearDownClass(cls):
        cls.browser.quit()
        super().tearDownClass()

    def setUp(self):
        User.objects.create_user(
            username="student",
            email="student@example.com",
            password="password123",
        )

    def test_user_can_login_and_create_note(self):
        self.browser.get(f"{self.live_server_url}/login/")

        self.browser.find_element(By.NAME, "username").send_keys("student")
        self.browser.find_element(By.NAME, "password").send_keys("password123")
        self.browser.find_element(By.CSS_SELECTOR, "button[type='submit']").click()

        create_link = WebDriverWait(self.browser, 5).until(
            EC.element_to_be_clickable((By.ID, "create-note-link"))
        )
        create_link.click()

        self.browser.find_element(By.NAME, "title").send_keys("Selenium Note")
        self.browser.find_element(By.NAME, "content").send_keys("E2E works")
        self.browser.find_element(By.ID, "submit-note").click()

        note_title = WebDriverWait(self.browser, 5).until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, ".note-title"))
        )

        self.assertEqual(note_title.text, "Selenium Note")

What you need to add to the HTML:

<!-- notes/note_list.html -->
<a id="create-note-link" href="{% url 'note_create' %}">Create note</a>

{% for note in notes %}
  <h2 class="note-title">{{ note.title }}</h2>
{% endfor %}
<!-- notes/note_form.html -->
<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button id="submit-note" type="submit">Save</button>
</form>

Stable selectors are part of UI testability.


13. Selenium in Docker/CI headless

A CI server has no monitor. There are three strategies for running Selenium without a physical display.


13.1 Strategy A — install geckodriver/chromedriver in the Dockerfile

Firefox + geckodriver — download the binary from GitHub Releases:

ARG GECKODRIVER_VERSION=0.35.0

RUN apt-get update && apt-get install -y firefox-esr wget \
    && rm -rf /var/lib/apt/lists/* \
    && wget -q "https://github.com/mozilla/geckodriver/releases/download/v${GECKODRIVER_VERSION}/geckodriver-v${GECKODRIVER_VERSION}-linux64.tar.gz" \
    && tar -xzf geckodriver-v${GECKODRIVER_VERSION}-linux64.tar.gz \
    && mv geckodriver /usr/local/bin/ \
    && rm geckodriver-v${GECKODRIVER_VERSION}-linux64.tar.gz

Chrome + chromedriver — simpler via a package:

RUN apt-get update && apt-get install -y \
    chromium \
    chromium-driver \
    && rm -rf /var/lib/apt/lists/*

In the tests, use headless mode:

# Firefox headless
from selenium.webdriver.firefox.options import Options as FirefoxOptions
options = FirefoxOptions()
options.add_argument("--headless")
driver = webdriver.Firefox(options=options)

# Chrome headless
from selenium.webdriver.chrome.options import Options as ChromeOptions
options = ChromeOptions()
options.add_argument("--headless=new")
options.add_argument("--no-sandbox")             # required in Docker
options.add_argument("--disable-dev-shm-usage")  # shared memory in the container
driver = webdriver.Chrome(options=options)
Argument Why
--headless=new Run without a GUI window (the new headless implementation, Chrome 112+)
--no-sandbox The Chrome sandbox conflicts with Docker namespaces
--disable-dev-shm-usage /dev/shm is 64 MB by default in Docker → Chrome crashes

How to run it (if you have xvfb for old Firefox versions without --headless):

xvfb-run -s "-screen 0 1024x768x24" python manage.py test

selenium/standalone-chrome and selenium/standalone-firefox are ready-made images from the Selenium Project. They already contain: browser + driver + VNC server. Nothing to install or download.

docker-compose.yml — two services: web (Django tests) + selenium (browser):

version: "3.9"
services:
  web:
    build: .
    command: python manage.py test
    environment:
      - SELENIUM_REMOTE_URL=http://selenium:4444/wd/hub
    depends_on:
      selenium:
        condition: service_healthy
    networks:
      - test-net

  selenium:
    image: selenium/standalone-chrome:latest
    shm_size: "2gb"   # Chrome needs shared memory for rendering
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:4444/status"]
      interval: 5s
      timeout: 3s
      retries: 5
    networks:
      - test-net

networks:
  test-net:

In the tests, a function that switches between Local and Remote via an env var:

import os
from selenium import webdriver
from selenium.webdriver.firefox.options import Options as FirefoxOptions

SELENIUM_REMOTE_URL = os.environ.get("SELENIUM_REMOTE_URL")


def _make_driver():
    if SELENIUM_REMOTE_URL:
        # CI / docker-compose → Remote WebDriver to the Selenium container
        options = webdriver.ChromeOptions()
        return webdriver.Remote(
            command_executor=SELENIUM_REMOTE_URL,
            options=options,
        )
    # Locally → headless Firefox (if geckodriver is installed)
    options = FirefoxOptions()
    options.add_argument("--headless")
    return webdriver.Firefox(options=options)

Running:

docker compose up --build --abort-on-container-exit

Bonus: VNC is available at http://localhost:7900 (password: secret) — you can watch what the browser is doing.


13.3 Strategy C — a ready-made GitHub Actions recipe

# .github/workflows/tests.yml
name: Django Tests

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest

    services:
      selenium:
        image: selenium/standalone-chrome:latest
        options: --shm-size=2gb
        ports:
          - 4444:4444

    steps:
      - uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.12"

      - name: Install dependencies
        run: pip install -r requirements.txt selenium

      - name: Run tests
        env:
          SELENIUM_REMOTE_URL: http://localhost:4444/wd/hub
        run: python manage.py test

The same SELENIUM_REMOTE_URL env var is picked up by _make_driver() — the code is identical locally and in CI.


13.4 Which strategy to choose

Strategy Where geckodriver lives Complexity Recommended for
xvfb + Firefox installed locally ⭐⭐ CI without Docker, Linux
Dockerfile + wget geckodriver in the Dockerfile ⭐⭐ your own Docker image
selenium/standalone-chrome + Remote in the Selenium image ⭐ docker-compose, GitHub Actions

For new projects: selenium/standalone-chrome + webdriver.Remote() — the simplest option; the browser is always the same in every environment.


14. Coverage

Running:

pip install coverage
coverage run manage.py test
coverage report
coverage html

How to read it:

Name                    Stmts   Miss  Cover
-------------------------------------------
notes/models.py            18      0   100%
notes/forms.py             20      2    90%
notes/views.py             45      8    82%

Do not blindly chase 100%. Ask:

  • are permissions checked?
  • are there invalid form tests?
  • are there edge cases?
  • is payment/email/API checked via mock?
  • is there at least one Selenium smoke test for the main route?

15. Mermaid diagram

flowchart TD
    A["Model: Note"] --> B["test_models.py"]
    C["Form: NoteForm"] --> D["test_forms.py"]
    E["URLs"] --> F["test_urls.py"]
    G["Views: list/create"] --> H["test_views.py"]
    I["Email service"] --> J["test_services.py with mock"]
    K["Browser flow"] --> L["test_e2e.py Selenium"]
    B --> M["Fast tests of the core logic"]
    D --> M
    F --> M
    H --> M
    J --> M
    L --> N["High confidence in the main user flow"]

    classDef step     fill:#eceff1,stroke:#546e7a,stroke-width:1px;
    classDef success  fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px;
    classDef warning  fill:#fff8e1,stroke:#e65100,stroke-width:2px;
    class A,C,E,G,I,K step;
    class B,D,F,H,J,L warning;
    class M,N success;

16. Common beginner mistakes

Mistake Why it happens How to fix it
Starting with Selenium It looks the “most complete” Model/form/view tests first
Not testing ownership Thinking only about your own user Create User A and User B
Mocking the form/model Wanting isolation Form/model are better tested for real via the test DB
Not adding stable selectors HTML is written only for human eyes Add an id or data-test-id for E2E
Using time.sleep() An easy way to wait Use WebDriverWait
Coverage is there, but assertions are weak Looking only at the number Check what the tests actually contain

17. Practice

  1. Implement the Note model.
  2. Write model tests.
  3. Implement NoteForm.
  4. Write form tests.
  5. Implement note_list and note_create.
  6. Write view tests:
  7. anonymous redirect;
  8. logged user 200;
  9. User A does not see User B's notes;
  10. POST creates a note;
  11. an invalid POST does not create a note.
  12. Add a mock for email.
  13. Add a Selenium smoke test.
  14. Run:
python manage.py test
  1. Run:
coverage run manage.py test
coverage report

18. Self-check questions

  1. Why are ownership tests critically important in this project?
  2. Why should email be mocked in a view test?
  3. Why is it better to test form validation without Selenium?
  4. What does a Selenium smoke test check that the Django Client does not?
  5. Why do we need StaticLiveServerTestCase?
  6. Why are stable selectors important for E2E?
  7. What can coverage show, and what can it not?

19. CI/CD and GitHub Actions

19.1 What CI is and why you need it

CI (Continuous Integration) is the practice of automatically running tests every time code lands in the repository.

Without CI:

Developer writes code → push → tests are run manually (or not at all) → the bug lands in main

With CI:

Developer writes code → push → GitHub runs the tests automatically → if a test fails → merge is blocked

GitHub Actions is the CI/CD built into GitHub. It is free for public repositories and for private ones within a quota.

19.2 Where the file must live — IMPORTANT

GitHub Actions reads .yml files only from the repository root folder:

<repo-root>/.github/workflows/*.yml   ← GitHub sees and runs these

A file anywhere else is ignored:

docs/08_testing_and_quality/.github/workflows/  ← DOES NOT WORK

The correct structure for our project (the notes_chat_app repository, with the Django project right in the root):

notes_chat_app/                        ← repository root
├── .github/
│   └── workflows/
│       └── django-tests.yml           ← HERE, not inside docs/
├── manage.py
├── requirements.txt
├── notes_project/
├── notes_app/
└── docs/

Since manage.py sits in the repository root, our workflow does not need working-directory. If the Django project lives in a subfolder of the repository, you point to it with working-directory:

defaults:
  run:
    working-directory: path/to/django_project   # the folder that contains manage.py

YAML format — GitHub Actions uses YAML to describe the pipeline.

19.3 The full workflow file, explained

# .github/workflows/django-tests.yml

name: Django Tests       # pipeline name in the GitHub UI

# ── Triggers ─────────────────────────────────────────────────────────────────
on:
  push:
    branches: [ main, master ]   # run on push to main
  pull_request:
    branches: [ main, master ]   # run on a PR to main
  workflow_dispatch:             # the "Run workflow" button in the GitHub UI

# ── Jobs ─────────────────────────────────────────────────────────────────────
jobs:

  # ── Job 1: Unit + Integration (fast tests without a browser) ──────────────
  test:
    name: Unit & Integration Tests
    runs-on: ubuntu-latest       # runner type (a VM from GitHub)

    steps:
      # Step 1: download the code
      - name: Checkout code
        uses: actions/checkout@v4

      # Step 2: install Python
      - name: Set up Python 3.12
        uses: actions/setup-python@v5
        with:
          python-version: "3.12"

      # Step 3: pip cache (speeds up repeated runs)
      - name: Cache pip
        uses: actions/cache@v4
        with:
          path: ~/.cache/pip
          key: ${{ runner.os }}-pip-${{ hashFiles('requirements.txt') }}

      # Step 4: install dependencies
      - name: Install dependencies
        run: pip install -r requirements.txt

      # Step 5: check the Django configuration
      - name: Django system check
        run: python manage.py check

      # Step 6: run the tests without Selenium
      - name: Run tests
        run: |
          python manage.py test \
            notes_app.tests.test_models \
            notes_app.tests.test_services \
            notes_app.tests.test_forms \
            notes_app.tests.test_views \
            -v 2

      # Step 7: coverage
      - name: Coverage report
        run: |
          coverage run manage.py test notes_app.tests.test_models \
            notes_app.tests.test_services \
            notes_app.tests.test_forms \
            notes_app.tests.test_views
          coverage report
          coverage xml

      # Step 8: save coverage as an artifact
      - name: Upload coverage
        uses: actions/upload-artifact@v4
        with:
          name: coverage-report
          path: coverage.xml


  # ── Job 2: Selenium E2E tests ─────────────────────────────────────────────
  test-selenium:
    name: Selenium E2E Tests
    runs-on: ubuntu-latest
    needs: test              # run only after Job 1 succeeds

    # Selenium as a separate Docker service
    services:
      selenium:
        image: selenium/standalone-chrome:latest
        options: --shm-size=2gb
        ports:
          - 4444:4444

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up Python 3.12
        uses: actions/setup-python@v5
        with:
          python-version: "3.12"

      - name: Install dependencies
        run: pip install -r requirements.txt

      # SELENIUM_REMOTE_URL → _make_driver() will use Remote WebDriver
      - name: Run Selenium tests
        env:
          SELENIUM_REMOTE_URL: http://localhost:4444/wd/hub
        run: python manage.py test notes_app.tests.test_selenium -v 2

19.4 How GitHub runs the pipeline

sequenceDiagram
    participant Dev as Developer
    participant GH as GitHub
    participant Runner as Ubuntu Runner
    participant Selenium as Selenium Container

    Dev->>GH: git push main
    GH->>Runner: Start Job 1 (test)
    Runner->>Runner: checkout code
    Runner->>Runner: setup-python 3.12
    Runner->>Runner: pip install -r requirements.txt
    Runner->>Runner: manage.py test (123 tests)
    Runner-->>GH: ✅ Job 1 passed

    GH->>Runner: Start Job 2 (test-selenium)
    Runner->>Selenium: start selenium/standalone-chrome
    Runner->>Runner: pip install -r requirements.txt
    Runner->>Selenium: webdriver.Remote(SELENIUM_REMOTE_URL)
    Selenium-->>Runner: 6 E2E tests passed
    Runner-->>GH: ✅ Job 2 passed

    GH-->>Dev: ✅ All checks passed — PR can be merged

19.5 How to see the results on GitHub

  1. Open the repository on GitHub
  2. Click the Actions tab
  3. On the left is the list of workflows, on the right is the run history
  4. Click a specific run → you see the jobs → click a job → you see the steps

If a test fails:

❌ Run tests
  FAILED: notes_app.tests.test_views.NoteAuthorizationTest.test_bob_cannot_edit_alice_note
  AssertionError: 200 != 403
  ...

The error text is visible right in the GitHub UI.

19.6 Status badge

Add this to README.md to show whether the tests pass:

![Django Tests](https://github.com/YOUR_USERNAME/YOUR_REPO/actions/workflows/django-tests.yml/badge.svg)

It looks like this:

[passing] Django Tests

Colleagues and employers immediately see that the project has CI and the tests are green.

19.7 Branch Protection

In the repository settings:

Settings → Branches → Add branch protection rule
  ☑ Require status checks to pass before merging
  ☑ Require branches to be up to date before merging
      Status checks: "Unit & Integration Tests"

After this, merging into main is blocked if the tests fail.

❌ Cannot merge — "Unit & Integration Tests" check failed

19.8 Diagram: what CI checks on every push

flowchart TD
    A["git push / PR"] --> B["GitHub Actions trigger"]
    B --> C["Job 1: Unit + Integration<br>123 tests, ~2-3 minutes"]
    C -->|pass| D["Job 2: Selenium E2E<br>6 tests, ~1-2 minutes"]
    C -->|fail| E["❌ Merge blocked<br>PR gets a red cross"]
    D -->|pass| F["✅ Merge allowed<br>PR gets a green check mark"]
    D -->|fail| E

    classDef step     fill:#eceff1,stroke:#546e7a,stroke-width:1px;
    classDef success  fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px;
    classDef error    fill:#ffebee,stroke:#c62828,stroke-width:3px;
    class A,B,C,D step;
    class E error;
    class F success;

19.9 Where to store secrets (SECRET_KEY, passwords)

For production-like tests where SECRET_KEY must not be committed to the code:

GitHub repository → Settings → Secrets and variables → Actions → New secret
  Name:  SECRET_KEY
  Value: super-secret-value

In the workflow:

- name: Run tests
  env:
    SECRET_KEY: ${{ secrets.SECRET_KEY }}
    DATABASE_URL: ${{ secrets.DATABASE_URL }}
  run: python manage.py test

In settings.py:

import os
SECRET_KEY = os.environ.get("SECRET_KEY", "django-insecure-dev-only")

19.10 Matrix Testing: checking against several Python versions

jobs:
  test:
    strategy:
      matrix:
        python-version: ["3.11", "3.12", "3.13"]

    runs-on: ubuntu-latest
    name: Test on Python ${{ matrix.python-version }}

    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: ${{ matrix.python-version }}
      - run: pip install -r requirements.txt
      - run: python manage.py test

Result: three parallel jobs — Test on Python 3.11, 3.12, 3.13.


20. Self-check questions (CI/CD)

  1. What happens if a test fails in GitHub Actions?
  2. Where on GitHub can you see the results of a test run?
  3. Why do we need needs: test in Job 2?
  4. Why use selenium/standalone-chrome as a service instead of installing Chrome on the runner?
  5. How does SELENIUM_REMOTE_URL let a single test_selenium.py work both locally and in CI?
  6. What is Branch Protection and how is it related to CI?
  7. Why must you not store SECRET_KEY directly in the YAML file?
  8. What is matrix.python-version for?