Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
b39ffbb
feat(links): check the external links of the courses
TimmyWeatherhead Dec 5, 2026
6c23174
feat(format): add the course layout checker and first fixes
TimmyWeatherhead Dec 5, 2026
b3e415a
fix(maths): add meaning drawings and pivot exercise drawings
TimmyWeatherhead Dec 5, 2026
ff637d2
ci(format): check the course layout on every PR and push to main
TimmyWeatherhead Dec 5, 2026
bf40225
docs(tests): list every test, what it checks and what it mocks
TimmyWeatherhead Dec 5, 2026
5d0fd7c
docs(tests): move the inventory to tests/README.md; check drawings in…
TimmyWeatherhead Dec 5, 2026
2c16e98
docs(format): every writing rule comes with its check and its test
TimmyWeatherhead Dec 5, 2026
1999d63
feat(format): links between courses must lead to an existing file
TimmyWeatherhead Dec 5, 2026
c8b991f
chore: merge the format branch
TimmyWeatherhead Dec 5, 2026
9bd3a83
feat(links): weekly archive.org repair and dead links issue, nothing …
TimmyWeatherhead Dec 5, 2026
15af1ec
refactor(format): English code, content rules in format-rules.json
TimmyWeatherhead Dec 6, 2026
95a0647
chore: merge the format branch
TimmyWeatherhead Dec 6, 2026
e6dfe93
refactor(links): English test names and JSON keys, --repair flag
TimmyWeatherhead Dec 6, 2026
0d61e52
ci(commits): check PR commit messages, Marklhor as only author
TimmyWeatherhead Dec 6, 2026
5842b0a
chore: merge the format branch
TimmyWeatherhead Dec 6, 2026
c0223de
docs(tests): update the inventory (683 tests, French docstrings)
TimmyWeatherhead Dec 6, 2026
50effa8
chore: merge main
TimmyWeatherhead Dec 6, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions .github/workflows/check-links.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# Checks every web link of the courses (tools/check_links.py): pages that
# answer, YouTube videos that can still be played.
# - On each pull request that changes a course: report only, nothing blocked.
# - Every Monday morning (and on demand): dead pages are replaced by their
# archive.org copy in a pull request « Liens morts remplacés par leur
# archive », and the issue « Liens morts » lists what was found (choice of
# Timmy, 2026-12-06: A + C). Nothing is merged without Timmy.
name: Check the links

on:
pull_request:
paths: ['**.md', 'tools/check_links.py', '.github/workflows/check-links.yml']
schedule:
- cron: '17 6 * * 1'
workflow_dispatch:

permissions:
contents: read

jobs:
report:
name: Check the links (report)
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check every link
run: python3 tools/check_links.py .

weekly:
name: Replace dead links and update the issue
if: github.event_name != 'pull_request'
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: write
pull-requests: write
issues: write
env:
GH_TOKEN: ${{ github.token }}
BRANCH: liens-morts-archive
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check every link and repair what archive.org keeps
run: python3 tools/check_links.py . --repair
- name: Open a pull request with the replaced links
run: |
if git diff --quiet -- '*.md'; then echo "Aucun lien remplacé."; exit 0; fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git switch -C "$BRANCH"
git add -- '*.md'
git commit -m "Liens morts remplacés par leur copie sur archive.org"
git push --force "https://x-access-token:${GH_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" "$BRANCH"
gh pr view "$BRANCH" >/dev/null 2>&1 || gh pr create --head "$BRANCH" --title "Liens morts remplacés par leur archive" --body-file verif-liens.md
- name: Update the issue « Liens morts »
run: |
numero=$(gh issue list --state open --search 'in:title "Liens morts"' --json number --jq '.[0].number')
if [ -n "$numero" ]; then gh issue edit "$numero" --body-file verif-liens.md
else gh issue create --title "Liens morts" --body-file verif-liens.md; fi
- name: Keep the report
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: verif-liens
path: |
verif-liens.json
verif-liens.md
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
__pycache__/
*.pyc
verif-liens.json
verif-liens.md
169 changes: 169 additions & 0 deletions tests/test_check_links.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
"""Tests of the external link checker (tools/check_links.py).

No network access: the answers of the sites, of YouTube and of archive.org
are mocked (unittest.mock) and the courses are written in a temporary fake
repository. Each test's docstring says in French what it checks.

Run: python3 -m unittest discover -s tests -v
"""

from __future__ import annotations

import contextlib
import io
import json
import os
import sys
import tempfile
import unittest
from pathlib import Path
from unittest import mock

sys.path.insert(0, str(Path(__file__).resolve().parent.parent / 'tools'))

import check_links as cl # noqa: E402

COURSE = """---
titre: Un cours
---

Voir [la norme](https://exemple.fr/norme), [la vidéo](https://www.youtube.com/watch?v=abc123),
[une recherche](https://www.youtube.com/results?search_query=derivee) et [le site mort](https://mort.fr/page).
"""

# Mocked answers: HTTP status by address.
RESPONSES = {
'https://exemple.fr/norme': 200,
'https://mort.fr/page': 404,
}
ARCHIVE = 'https://web.archive.org/web/20250101000000/https://mort.fr/page'


def fake_status(url: str) -> int:
if url.startswith('https://www.youtube.com/oembed'):
return 404 if 'abc123' in url and FakeNetwork.video_morte else 200
return RESPONSES.get(url, 200)


class FakeNetwork:
dead_video = False


class BaseTest(unittest.TestCase):
def setUp(self) -> None:
self._folder = tempfile.TemporaryDirectory()
self.addCleanup(self._folder.cleanup)
self.root = Path(self._folder.name)
(self.root / 'maths').mkdir()
self.course = self.root / 'maths' / 'cours.md'
self.course.write_text(COURSE, encoding='utf-8')
self._cwd = os.getcwd()
os.chdir(self.root) # the reports are written in the current folder
self.addCleanup(os.chdir, self._cwd)
FakeNetwork.video_morte = False

def run_checker(self, *options: str, archive: str | None = ARCHIVE) -> tuple[int, dict]:
with mock.patch.object(cl, 'status', side_effect=fake_status), \
mock.patch.object(cl, 'archived', return_value=archive) as fake_archive, \
mock.patch.object(sys, 'argv', ['check_links.py', str(self.root), *options]), \
contextlib.redirect_stdout(io.StringIO()):
code = cl.main()
self.fake_archive = fake_archive
return code, json.loads((self.root / 'verif-liens.json').read_text(encoding='utf-8'))


class TestVerdicts(BaseTest):
def test_classifies_links(self):
"""Classe les liens (bons, morts, recherches)."""
_, report = self.run_checker()
self.assertEqual(report['broken'], ['https://mort.fr/page'])
self.assertIn('https://exemple.fr/norme', report['ok'])
self.assertIn('https://www.youtube.com/watch?v=abc123', report['ok'])
self.assertEqual(report['search'], ['https://www.youtube.com/results?search_query=derivee'])

def test_deleted_video_is_dead(self):
"""Vidéo supprimée est morte."""
FakeNetwork.video_morte = True
_, report = self.run_checker()
self.assertIn('https://www.youtube.com/watch?v=abc123', report['broken'])

def test_site_refusing_robots_needs_manual_check(self):
"""Site qui refuse les robots est à vérifier."""
RESPONSES['https://exemple.fr/norme'] = 403
self.addCleanup(RESPONSES.__setitem__, 'https://exemple.fr/norme', 200)
_, report = self.run_checker()
self.assertEqual(report['robots'], ['https://exemple.fr/norme'])


class TestHandling(BaseTest):
def test_nothing_blocked_by_default(self):
"""Rien n'est bloqué par défaut."""
code, _ = self.run_checker()
self.assertEqual(code, 0)

def test_strict_fails_on_dead_link(self):
"""Avec --strict, un lien mort fait échouer."""
code, _ = self.run_checker('--strict')
self.assertEqual(code, 1)

def test_without_repair_course_unchanged(self):
"""Sans réparer le cours ne change pas."""
self.run_checker()
self.assertEqual(self.course.read_text(encoding='utf-8'), COURSE)
self.fake_archive.assert_not_called()

def test_repair_replaces_with_archived_copy(self):
"""Réparer remplace par la copie archivée."""
_, report = self.run_checker('--repair')
text = self.course.read_text(encoding='utf-8')
self.assertIn(f'[le site mort]({ARCHIVE})', text)
self.assertNotIn('](https://mort.fr/page)', text)
self.assertEqual(report['archive'], [{'before': 'https://mort.fr/page', 'after': ARCHIVE}])
self.assertEqual(report['broken'], [])

def test_repair_without_archive_keeps_dead_link(self):
"""Réparer sans copie archivée laisse le lien mort."""
_, report = self.run_checker('--repair', archive=None)
self.assertIn('](https://mort.fr/page)', self.course.read_text(encoding='utf-8'))
self.assertEqual(report['broken'], ['https://mort.fr/page'])

def test_video_never_replaced_by_archive(self):
"""Une vidéo n'est jamais remplacée par une archive."""
FakeNetwork.video_morte = True
_, report = self.run_checker('--repair')
self.assertIn('https://www.youtube.com/watch?v=abc123', report['broken'])
self.assertIn('](https://www.youtube.com/watch?v=abc123)', self.course.read_text(encoding='utf-8'))

def test_report_for_issue(self):
"""Rapport pour le ticket."""
self.run_checker('--repair')
issue = (self.root / 'verif-liens.md').read_text(encoding='utf-8')
self.assertIn('Remplacés par leur copie sur archive.org (1)', issue)
self.assertIn('Liens cassés (0)', issue)


class TestArchive(unittest.TestCase):
def response(self, data: dict):
fake = mock.MagicMock()
fake.__enter__.return_value = io.BytesIO(json.dumps(data).encode())
return fake

def test_reads_closest_copy(self):
"""Lit la copie la plus proche."""
data = {'archived_snapshots': {'closest': {'available': True, 'status': '200', 'url': 'http://web.archive.org/web/1/https://mort.fr/page'}}}
with mock.patch.object(cl.urllib.request, 'urlopen', return_value=self.response(data)):
self.assertEqual(cl.archived('https://mort.fr/page'), 'https://web.archive.org/web/1/https://mort.fr/page')

def test_no_copy(self):
"""Aucune copie."""
with mock.patch.object(cl.urllib.request, 'urlopen', return_value=self.response({'archived_snapshots': {}})):
self.assertIsNone(cl.archived('https://mort.fr/page'))

def test_archive_unreachable(self):
"""Archive injoignable."""
with mock.patch.object(cl.urllib.request, 'urlopen', side_effect=OSError('réseau')):
self.assertIsNone(cl.archived('https://mort.fr/page'))


if __name__ == '__main__':
unittest.main()
Loading