Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
63 changes: 53 additions & 10 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,19 +31,30 @@ jobs:
run: uv sync

- name: Lint (ruff check)
run: uv run ruff check asyncvnc2.py test_asyncvnc2.py test_reseau_local.py test_decodage_video.py test_live_x11vnc.py test_live_xvnc.py test_loguru_regles.py test_licence.py scripts/audit_debug_sorties.py
run: uv run ruff check asyncvnc2.py test_asyncvnc2.py test_reseau_local.py test_decodage_video.py test_couverture_branches.py test_verifier_couverture.py test_live_x11vnc.py test_live_xvnc.py test_loguru_regles.py test_licence.py scripts/audit_debug_sorties.py scripts/verifier_couverture.py

- name: Formatage (ruff format --check)
run: uv run ruff format --check asyncvnc2.py test_asyncvnc2.py test_reseau_local.py test_decodage_video.py test_live_x11vnc.py test_live_xvnc.py test_loguru_regles.py test_licence.py scripts/audit_debug_sorties.py
run: uv run ruff format --check asyncvnc2.py test_asyncvnc2.py test_reseau_local.py test_decodage_video.py test_couverture_branches.py test_verifier_couverture.py test_live_x11vnc.py test_live_xvnc.py test_loguru_regles.py test_licence.py scripts/audit_debug_sorties.py scripts/verifier_couverture.py

- name: Tests et couverture (unittest, seuil lu dans pyproject.toml)
# Suite documentée dans CLAUDE.md « Commandes de qualité » : aucun
# vrai serveur VNC nécessaire (test_reseau_local.py dialogue avec un
# serveur RFB minimal sur 127.0.0.1). Couverture lignes + branches,
# seuil bloquant `fail_under` (issue #54).
run: |
uv run coverage run -m unittest test_asyncvnc2 test_reseau_local test_decodage_video -v
uv run coverage report
make test

- name: Préparer les données de couverture hors ligne
run: cp .coverage .coverage.unitaire

- name: Données de couverture hors ligne
uses: actions/upload-artifact@v4
with:
name: couverture-unitaire
path: .coverage.unitaire
include-hidden-files: true
if-no-files-found: error
retention-days: 2

- name: "Journalisation loguru (issue #55, SOCLE §8)"
# Règles AST (pas de logging stdlib, format {}, pas de secret, except
Expand Down Expand Up @@ -79,10 +90,10 @@ jobs:
uv sync -p 3.9

- name: Tests (unittest, Python 3.9)
run: uv run -p 3.9 python3 -m unittest test_asyncvnc2 test_reseau_local test_decodage_video test_loguru_regles test_licence -v
run: uv run -p 3.9 python3 -m unittest test_asyncvnc2 test_reseau_local test_decodage_video test_couverture_branches test_verifier_couverture test_loguru_regles test_licence -v

- name: Version minimale (vermin)
run: uvx vermin --no-tips --eval-annotations -t=3.9- --violations asyncvnc2.py test_asyncvnc2.py test_reseau_local.py test_decodage_video.py test_live_x11vnc.py test_live_xvnc.py test_live_qemu_sasl.py test_live_qemu_zywrle.py test_loguru_regles.py test_licence.py scripts/audit_debug_sorties.py
run: uvx vermin --no-tips --eval-annotations -t=3.9- --violations asyncvnc2.py test_asyncvnc2.py test_reseau_local.py test_decodage_video.py test_couverture_branches.py test_verifier_couverture.py test_live_x11vnc.py test_live_xvnc.py test_live_qemu_sasl.py test_live_qemu_zywrle.py test_loguru_regles.py test_licence.py scripts/audit_debug_sorties.py scripts/verifier_couverture.py

live:
# Issues #28 et #27 : repli de version et connexion inversée contre un
Expand Down Expand Up @@ -131,7 +142,7 @@ jobs:
- name: Tests contre x11vnc
env:
ASYNCVNC_LIVE: "1"
run: uv run python3 -m unittest test_live_x11vnc -v
run: uv run coverage run --parallel-mode -m unittest test_live_x11vnc -v

- name: TigerVNC (Xvnc, vncconfig)
run: |
Expand All @@ -147,7 +158,7 @@ jobs:
# la couleur posée par xsetroot.
env:
ASYNCVNC_LIVE: "1"
run: uv run python3 -m unittest test_live_xvnc -v
run: uv run coverage run --parallel-mode -m unittest test_live_xvnc -v

- name: QEMU et Cyrus SASL
run: |
Expand All @@ -162,11 +173,43 @@ jobs:
- name: Tests SASL contre QEMU
env:
ASYNCVNC_LIVE: "1"
run: uv run python3 -m unittest test_live_qemu_sasl -v
run: uv run coverage run --parallel-mode -m unittest test_live_qemu_sasl -v

- name: Tests ZYWRLE contre QEMU
# Issue #22 : tuiles à perte (lossy=on), niveaux 1 à 3, vérité
# terrain = screendump du moniteur QEMU.
env:
ASYNCVNC_LIVE: "1"
run: uv run python3 -m unittest test_live_qemu_zywrle -v
run: uv run coverage run --parallel-mode -m unittest test_live_qemu_zywrle -v

- name: Données de couverture des serveurs réels
uses: actions/upload-artifact@v4
with:
name: couverture-serveurs
path: .coverage.*
include-hidden-files: true
if-no-files-found: error
retention-days: 2

coverage:
name: Couverture combinée (lignes et branches)
needs: [quality, live]
runs-on: ${{ fromJSON(vars.RUNS_ON_LINUX || '"ubuntu-latest"') }}
steps:
- name: Checkout du dépôt
uses: actions/checkout@v7
- name: Installation de uv
uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
- name: Installation des dépendances
run: uv sync
- name: Données hors ligne et serveurs réels
uses: actions/download-artifact@v4
with:
pattern: couverture-*
path: donnees-couverture
- name: Combinaison et contrôles indépendants
run: |
uv run coverage combine --keep donnees-couverture/couverture-unitaire donnees-couverture/couverture-serveurs
uv run coverage report
uv run coverage json -o coverage.json
uv run python scripts/verifier_couverture.py coverage.json
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@ __pycache__/
*.pyc
.venv/
.coverage
.coverage.*
coverage.json
6 changes: 4 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -255,8 +255,10 @@ suspens.
```bash
uv sync # crée .venv/, installe numpy/loguru/cryptography/keysymdef + ruff (dev)
uv run python3 -m unittest test_asyncvnc2 -v # 62 tests
uv run coverage run -m unittest test_asyncvnc2 test_reseau_local test_decodage_video # 126 tests (27 sur socket locale, 37 décodeurs hors ligne, issue #54)
uv run coverage report # lignes + branches, échoue sous fail_under (pyproject.toml)
make test # suite complète, seuil indépendant lignes ET branches (#54)
uv run coverage report # total combiné (ne suffit pas seul)
uv run coverage json -o coverage.json
uv run python scripts/verifier_couverture.py coverage.json # lit fail_under dans pyproject.toml
uv run python3 -m unittest test_loguru_regles -v # 25 tests, règles de journalisation (issue #55)
uv run python3 scripts/audit_debug_sorties.py # 0 fonction non conforme (référence : 0)
uv run ruff check asyncvnc2.py test_asyncvnc2.py # 0 signalement
Expand Down
10 changes: 10 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
.PHONY: test

# Même seuil et mêmes contrôles que le job Qualité, sans valeur recopiée.
test:
uv run coverage erase
uv run coverage run --parallel-mode -m unittest test_asyncvnc2 test_reseau_local test_decodage_video test_couverture_branches test_verifier_couverture -v
uv run coverage combine --keep
uv run coverage report
uv run coverage json -o coverage.json
uv run python scripts/verifier_couverture.py coverage.json
9 changes: 6 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ include = ["asyncvnc2.py"]
[tool.coverage.run]
# Couverture des branches obligatoire (Mathilde-Team/.github#9).
branch = true
source = ["asyncvnc2"]
relative_files = true
source = ["asyncvnc2", "scripts.verifier_couverture"]

[tool.coverage.report]
# Seuil bloquant de l'équipe : 95 % visé (décision du 21/10/2026,
Expand All @@ -48,7 +49,9 @@ source = ["asyncvnc2"]
# simulés, serveur RA2 en mémoire), la montée TLS en boucle locale, EncList,
# clavier, souris et champs ARD/MSLogonII. Palier 4 (issue #54, PR #77) :
# 95,35 % au 31/10/2026 (ARD, MSLogonII, WebSocket, messages rares) ; seuil
# relevé à 95 le 03/11/2026 — objectif de l'équipe atteint, ne plus descendre.
# Déclaré ici seulement, lu par `coverage report` dans ci.yml.
# relevé à 95 le 03/11/2026. Le total combiné masquait encore 91,35 % de
# branches : les cas limites ajoutés pour #54 et verifier_couverture.py
# imposent désormais le seuil indépendamment aux lignes ET aux branches.
# Déclaré ici seulement, lu par coverage et le vérificateur dans CI/Makefile.
fail_under = 95
show_missing = true
49 changes: 49 additions & 0 deletions scripts/verifier_couverture.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Contrôle indépendant des lignes et branches, seuil unique du projet (#54)."""

from __future__ import annotations

import json
import sys
from pathlib import Path

from coverage import Coverage
from loguru import logger


def verifier_couverture(totaux: dict, seuil: float) -> bool:
"""Ne jamais laisser une moyenne masquer un défaut de branches."""
logger.debug('Vérification de la couverture : entrée seuil={}', seuil)
conforme = True
for nom, couverts, total in (
('lignes', 'covered_lines', 'num_statements'),
('branches', 'covered_branches', 'num_branches'),
):
nombre = totaux[total]
taux = 100.0 * totaux[couverts] / nombre if nombre else 100.0
logger.info('Couverture {} : {:.4f} %, seuil {} %', nom, taux, seuil)
if taux < seuil:
logger.error('Couverture {} insuffisante', nom)
conforme = False
logger.debug('Vérification de la couverture : sortie conforme={}', conforme)
return conforme


def main() -> int:
"""Lit le rapport JSON et le même fail_under que coverage report."""
logger.debug('Contrôle de couverture : entrée')
try:
chemin = Path(sys.argv[1] if len(sys.argv) > 1 else 'coverage.json')
totaux = json.loads(chemin.read_text(encoding='utf-8'))['totals']
seuil = Coverage().get_option('report:fail_under')
resultat = 0 if verifier_couverture(totaux, seuil) else 1
except (OSError, ValueError, KeyError, TypeError) as erreur:
logger.error('Rapport de couverture illisible : {!r}', erreur)
logger.debug('Contrôle de couverture : sortie 2')
return 2
logger.debug('Contrôle de couverture : sortie {}', resultat)
return resultat


if __name__ == '__main__':
sys.exit(main())
154 changes: 154 additions & 0 deletions test_couverture_branches.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Cas limites du protocole et de la vidéo, sans serveur externe (#54)."""

from __future__ import annotations

import asyncio
import unittest
from unittest.mock import AsyncMock, patch

import numpy as np

import asyncvnc2
from test_asyncvnc2 import _Ecrivain, _reader_from, make_client, make_video


class BornesVideoTests(unittest.TestCase):
def test_rectangle_hors_image_et_dimensions_negatives(self):
video = make_video()
self.assertEqual(video.get_rect(-3, -4), (0, 0, 64, 64))
self.assertEqual(video.get_rect(99, 99), (64, 64, 0, 0))
self.assertEqual(video.get_rect(1, 2, -1, -2), (1, 2, 0, 0))

def test_canal_alpha_en_premiere_position(self):
video = make_video(mode='argb')
video._update_rect(0, 1, 0, 1, np.array([[[1, 2, 3]]], dtype='B'))
self.assertEqual(video.data[0, 0].tolist(), [255, 1, 2, 3])

def test_compteur_eax_reboucle_apres_128_bits(self):
compteur = bytearray(b'\xff' * 16)
asyncvnc2._eax_increment_counter(compteur)
self.assertEqual(compteur, bytearray(16))

def test_prediction_gradient_superieure_a_255(self):
# Bas-droite : gauche + haut - haut-gauche = 400, borné à 255.
donnees = bytes([0, 0, 0, 200, 0, 0, 200, 0, 0, 7, 0, 0])
self.assertEqual(
asyncvnc2._tight_gradient_filter(donnees, 2, 2),
bytes([0, 0, 0, 200, 0, 0, 200, 0, 0, 6, 0, 0]),
)

def test_lzo_marqueur_de_fin_invalide(self):
with self.assertRaisesRegex(ValueError, 'marqueur de fin invalide'):
asyncvnc2._lzo1x_decompress(b'\x12a\x12\x00\x00', 1)


class BranchesProtocoleTests(unittest.IsolatedAsyncioTestCase):
async def test_lecteur_memoire_tronque(self):
lecteur = asyncvnc2._BytesReader(b'a')
with self.assertRaises(asyncio.IncompleteReadError) as erreur:
await lecteur.readexactly(2)
self.assertEqual(erreur.exception.partial, b'a')
self.assertEqual(erreur.exception.expected, 2)

async def test_longueur_tight_sur_deux_octets(self):
self.assertEqual(await asyncvnc2._tight_read_length(_reader_from(b'\x81\x01')), 129)

async def test_raw_pixel_recu_en_plusieurs_fragments(self):
lecteur = AsyncMock()
lecteur.read.side_effect = [b'\x01', b'\x02\x03\x04']
video = make_video(width=1, height=1)
await video.process_raw(lecteur, 0, 0, 1, 1)
self.assertEqual(video.data[0, 0].tolist(), [1, 2, 3, 255])
self.assertEqual(lecteur.read.await_count, 2)

async def test_ultra_indexe(self):
# LZO : un littéral (index de palette 1), puis marqueur de fin.
compresse = b'\x12\x01\x11\x00\x00'
lecteur = _reader_from(len(compresse).to_bytes(4, 'big') + compresse)
video = make_video(mode='indexed8', width=1, height=1)
video.palette = {1: (9, 8, 7)}
await video.process_ultra(lecteur, 0, 0, 1, 1)
self.assertEqual(video.data[0, 0].tolist(), [9, 8, 7, 255])

async def test_aiguillage_rre_et_corre(self):
for encodage in (asyncvnc2.Enc.RRE, asyncvnc2.Enc.CORRE):
with self.subTest(encodage=encodage):
rectangle = (
b'\x00\x00\x00\x00\x00\x01\x00\x01'
+ encodage.value.to_bytes(4, 'big', signed=True)
+ b'\x00\x00\x00\x00'
+ b'\x09\x08\x07\x00'
)
video = make_video(reader=_reader_from(rectangle))
self.assertFalse(await video.read())
self.assertEqual(video.data[0, 0].tolist(), [9, 8, 7, 255])

async def test_fence_acquitte_ne_declenche_pas_de_reponse(self):
client = make_client(reader=_reader_from(b'\x00' * 8))
await client.process_server_fence()
self.assertEqual(bytes(client.writer.sent), b'')

async def test_caps_presse_papiers_tronque_refuse(self):
flags = asyncvnc2.CLIPBOARD_ACTION_CAPS | asyncvnc2.CLIPBOARD_FORMAT_TEXT
client = make_client(reader=_reader_from(flags.to_bytes(4, 'big')))
with self.assertRaisesRegex(ValueError, 'Caps tronqué'):
await client.process_extended_clipboard(4)

async def test_action_presse_papiers_inconnue_conserve_alignement(self):
client = make_client(reader=_reader_from(b'\x00\x00\x00\x00excesfin'))
await client.process_extended_clipboard(9)
self.assertEqual(await client.reader.readexactly(3), b'fin')

async def test_xvp_echec_ne_retire_pas_le_support_annonce(self):
client = make_client(reader=_reader_from(b'\x00\x01\x00'))
client.xvp_supported = True
client.xvp_version = 1
await client.process_xvp()
self.assertTrue(client.xvp_supported)
self.assertEqual(client.xvp_version, 1)

async def test_pong_websocket_ignore(self):
lecteur = _reader_from(
asyncvnc2._ws_frame(b'pong', opcode=0xA)
+ asyncvnc2._ws_frame(b'donnee')
+ asyncvnc2._ws_frame(b'', opcode=0x8)
)
sortie = asyncio.StreamReader()
ecrivain = _Ecrivain()
await asyncvnc2._ws_pump(lecteur, ecrivain, sortie)
self.assertEqual(await sortie.read(), b'donnee')
self.assertEqual(bytes(ecrivain.sent), b'')

async def test_sous_protocole_websocket_avec_entrees_vides(self):
requete = (
b'GET / HTTP/1.1\r\nUpgrade: websocket\r\n'
b'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n'
b'Sec-WebSocket-Protocol: binary, , base64\r\n\r\n'
)
ecrivain = _Ecrivain()
await asyncvnc2._ws_handshake_server(_reader_from(requete), ecrivain)
self.assertIn(b'Sec-WebSocket-Protocol: binary\r\n', ecrivain.sent)
self.assertIn(b'Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=', ecrivain.sent)

async def test_capture_ignore_message_non_video(self):
client = make_client()
image = np.zeros((1, 1, 4), dtype='B')
with (
patch.object(
client,
'read',
AsyncMock(side_effect=[asyncvnc2.UpdateType.CLIPBOARD, asyncvnc2.UpdateType.VIDEO]),
) as lecture,
patch.object(asyncvnc2.Video, 'is_complete', return_value=True),
patch.object(asyncvnc2.Video, 'as_rgba', return_value=image),
):
self.assertIs(await client.screenshot(), image)
self.assertEqual(lecture.await_count, 2)

async def test_authentifications_exigeant_identifiants(self):
for authentification in (33, 113):
with self.subTest(authentification=authentification):
lecteur = _reader_from(b'RFB 003.008\n\x01' + bytes([authentification]))
with self.assertRaisesRegex(ValueError, 'requires username and password'):
await asyncvnc2.Client.create(lecteur, _Ecrivain())
4 changes: 4 additions & 0 deletions test_reseau_local.py
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,8 @@ async def accepter(reader, writer):
b'Connection: Upgrade\r\nSec-WebSocket-Accept: faux=\r\n\r\n'
)
await writer.drain()
writer.close()
await writer.wait_closed()

serveur = await asyncio.start_server(accepter, '127.0.0.1', 0)
try:
Expand All @@ -491,6 +493,8 @@ async def accepter(reader, writer):
pass
writer.write(b'HTTP/1.1 404 Not Found\r\n\r\n')
await writer.drain()
writer.close()
await writer.wait_closed()

serveur = await asyncio.start_server(accepter, '127.0.0.1', 0)
try:
Expand Down
Loading
Loading