98b1c5ae85
Punto 10. Sceglere una ricetta apriva la lista completa dei task e chiedeva all'operatore di decidere da dove cominciare prima ancora di aver fatto qualcosa. Ora AVVIA IN SEQUENZA porta dentro il primo task; la lista resta, un livello sotto, per quando serve vederla tutta o tornare indietro. - nuova rotta /measure/start/<ricetta>: memorizza lotto e seriale (prima lo faceva la lista, che ora si salta), verifica la tracciabilità obbligatoria e apre il primo task - GET /api/measurements/task-progress: quante quote ha già preso ogni task di misura, contate per quota e non per tentativo, delimitate dalla produzione aperta o, fuori produzione, dall'operatore - la lista distingue «Incompiuto 1/3» da «Completato 3/3»: un task lasciato a metà non somigliava più a uno mai aperto - «Visualizza singolo TASK» non è più riservato al Maker — dire «incompiuto» senza dare la strada per tornarci sarebbe una lamentela, non una funzione - nel task «Riepilogo» diventa «Completato» e si apre solo quando il ciclo è chiuso: altrimenti sarebbe la scorciatoia che rende facoltative le quote - «Fine ciclo misura» si vede da subito, spento, e dice quante quote mancano; prima compariva a task già finito, quando non serviva più saperlo Il pulsante verde del footer diventa «Task successivo»: due bottoni con la stessa parola addosso sono uno di troppo. Test: 334 (erano 309). Il side effect dei mock del client Flask ora risponde per endpoint invece che per turno — una lista posizionale si rompe appena una pagina fa una domanda in più al server, che è come crescono tutte. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
126 lines
3.9 KiB
Python
126 lines
3.9 KiB
Python
"""Shared test fixtures for Flask client tests.
|
|
|
|
Creates a Flask test client and mocks the API client (requests to FastAPI server).
|
|
"""
|
|
import sys
|
|
from pathlib import Path
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
import pytest
|
|
|
|
# Ensure the client package is importable
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
|
|
|
from app import create_app
|
|
|
|
# All blueprint modules that import api_client at module level.
|
|
# We must patch at the *use-site* (blueprint namespace) so the local name
|
|
# ``api_client`` in each module points to the mock, not the real singleton.
|
|
_API_CLIENT_PATCH_TARGETS = [
|
|
"blueprints.auth.api_client",
|
|
"blueprints.maker.api_client",
|
|
"blueprints.measure.api_client",
|
|
"blueprints.statistics.api_client",
|
|
]
|
|
|
|
|
|
@pytest.fixture
|
|
def flask_app():
|
|
"""Create a Flask application configured for testing."""
|
|
app = create_app()
|
|
app.config["TESTING"] = True
|
|
app.config["WTF_CSRF_ENABLED"] = False
|
|
app.config["SECRET_KEY"] = "test-secret-key"
|
|
|
|
# Provide default template variables that are normally set inside
|
|
# specific Jinja2 blocks and therefore not visible to sibling blocks.
|
|
@app.context_processor
|
|
def _inject_template_defaults():
|
|
return {
|
|
"versions": [],
|
|
"current_version": None,
|
|
}
|
|
|
|
return app
|
|
|
|
|
|
@pytest.fixture
|
|
def client(flask_app):
|
|
"""Yield a Flask test client."""
|
|
with flask_app.test_client() as test_client:
|
|
yield test_client
|
|
|
|
|
|
@pytest.fixture
|
|
def logged_in_client(flask_app):
|
|
"""Yield a Flask test client with a logged-in session."""
|
|
with flask_app.test_client() as test_client:
|
|
with test_client.session_transaction() as sess:
|
|
sess["api_key"] = "test-api-key-12345"
|
|
sess["user"] = {
|
|
"id": 1,
|
|
"username": "testuser",
|
|
"display_name": "Test User",
|
|
"roles": ["Maker", "MeasurementTec", "Metrologist"],
|
|
"is_admin": True,
|
|
"language_pref": "en",
|
|
"theme_pref": "light",
|
|
"active": True,
|
|
}
|
|
sess["user_id"] = 1
|
|
sess["language"] = "en"
|
|
sess["theme"] = "light"
|
|
yield test_client
|
|
|
|
|
|
def api_get_router(routes: dict, default=None):
|
|
"""A ``get`` side effect that answers by endpoint instead of by turn.
|
|
|
|
A list of responses in call order breaks the moment a page asks the server one
|
|
more question - which is how every page grows. Matching on the endpoint says
|
|
what a test actually means: this is what /api/recipes/3 replies.
|
|
|
|
Keys are matched as substrings of the endpoint, longest first, so
|
|
``/api/recipes/3/tasks`` wins over ``/api/recipes/3``.
|
|
"""
|
|
ordered = sorted(routes.items(), key=lambda kv: -len(kv[0]))
|
|
|
|
def _get(endpoint, *args, **kwargs):
|
|
for prefix, response in ordered:
|
|
if prefix in endpoint:
|
|
return response() if callable(response) else response
|
|
return {} if default is None else default
|
|
|
|
return _get
|
|
|
|
|
|
@pytest.fixture
|
|
def mock_api_client():
|
|
"""Patch the api_client singleton used in blueprints.
|
|
|
|
Patches every blueprint module that does
|
|
``from services.api_client import api_client`` so the local name
|
|
in each module resolves to the same MagicMock instance.
|
|
|
|
Yields the mocked APIClient instance so tests can configure responses:
|
|
|
|
mock_api_client.get.return_value = {"items": [...], "total": 1}
|
|
mock_api_client.post.return_value = {"user": {...}, "api_key": "..."}
|
|
"""
|
|
mock = MagicMock()
|
|
# Default: all methods return empty success dict
|
|
mock.get.return_value = {}
|
|
mock.post.return_value = {}
|
|
mock.put.return_value = {}
|
|
mock.delete.return_value = {}
|
|
|
|
# Stack patches for every blueprint that imports api_client
|
|
patchers = [patch(target, mock) for target in _API_CLIENT_PATCH_TARGETS]
|
|
for p in patchers:
|
|
p.start()
|
|
|
|
yield mock
|
|
|
|
for p in patchers:
|
|
p.stop()
|