conftest.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  1. """Shared test fixtures for BamBuddy backend tests."""
  2. import asyncio
  3. import atexit
  4. import json
  5. import logging
  6. import os
  7. import shutil
  8. import tempfile
  9. from collections.abc import AsyncGenerator
  10. from pathlib import Path
  11. from unittest.mock import AsyncMock, MagicMock, patch
  12. import pytest
  13. # IMPORTANT: Set environment variables BEFORE any app imports
  14. # This must happen before settings/config are loaded
  15. os.environ["LOG_TO_FILE"] = "false"
  16. os.environ["DEBUG"] = "false"
  17. # Point the app's own engine at a throwaway database before anything reads
  18. # DATABASE_URL.
  19. #
  20. # The fixtures below build their own SQLite engine, but that is not the only
  21. # engine in play: `core/config.py` snapshots ``DATABASE_URL`` at import time and
  22. # `core/database.py` builds a module-level ``engine`` / ``async_session`` from
  23. # it. Any app code that opens its own session rather than receiving the fixture
  24. # one therefore talks to whatever database the developer's `.env` names. The
  25. # clearest example is ``run_with_retry`` (used by the print-completion path),
  26. # whose sessions come from ``backend.app.core.database`` — so the widespread
  27. # ``patch("backend.app.main.async_session")`` does not intercept them.
  28. #
  29. # Left alone that is not a hypothetical: on a plain checkout it means the suite
  30. # writes to the developer's real SQLite file, and with a PostgreSQL `.env` it
  31. # means a live install. A completion test calling ``on_print_complete(1, ...)``
  32. # closed a queue item belonging to an actual running print that way.
  33. _TEST_APP_DB_DIR = Path(tempfile.mkdtemp(prefix="bambuddy_test_appdb_"))
  34. APP_DATABASE_URL = f"sqlite+aiosqlite:///{_TEST_APP_DB_DIR / 'app.db'}"
  35. os.environ["DATABASE_URL"] = APP_DATABASE_URL
  36. def _cleanup_test_app_db_dir():
  37. shutil.rmtree(_TEST_APP_DB_DIR, ignore_errors=True)
  38. atexit.register(_cleanup_test_app_db_dir)
  39. def _assert_disposable_database(url, source: str) -> None:
  40. """Abort the run unless *url* is the throwaway database created above.
  41. A guard rather than a comment because the failure it prevents is silent and
  42. destructive: the suite would appear to pass while having mutated real print
  43. history. Anything that reintroduces a real ``DATABASE_URL`` — an `.env` read
  44. later in the import order, a fixture rebuilding the engine — trips this
  45. instead of reaching the database.
  46. """
  47. database = str(getattr(url, "database", "") or "")
  48. if not str(getattr(url, "drivername", "")).startswith("sqlite") or not database.startswith(str(_TEST_APP_DB_DIR)):
  49. raise RuntimeError(
  50. f"Refusing to run tests: {source} resolves to {url!r}, which is not the "
  51. f"disposable SQLite database under {_TEST_APP_DB_DIR}. Tests must never "
  52. f"open a session against a real Bambuddy database."
  53. )
  54. from httpx import ASGITransport, AsyncClient # noqa: E402
  55. from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine # noqa: E402
  56. # Ensure settings use our env vars - import and override before database import
  57. from backend.app.core.config import settings # noqa: E402
  58. settings.log_to_file = False
  59. if settings.database_url != APP_DATABASE_URL:
  60. raise RuntimeError(
  61. f"Refusing to run tests: settings.database_url is {settings.database_url!r} "
  62. f"rather than the disposable test database. Something read DATABASE_URL "
  63. f"before conftest could override it."
  64. )
  65. # Use a temp directory for plate calibration to avoid deleting real calibration files
  66. _test_plate_cal_dir = Path(tempfile.mkdtemp(prefix="bambuddy_test_plate_cal_"))
  67. settings.plate_calibration_dir = _test_plate_cal_dir
  68. # Clean up temp directory when tests finish
  69. def _cleanup_test_plate_cal_dir():
  70. if _test_plate_cal_dir.exists():
  71. shutil.rmtree(_test_plate_cal_dir, ignore_errors=True)
  72. atexit.register(_cleanup_test_plate_cal_dir)
  73. from backend.app.core.database import Base, engine as _app_engine # noqa: E402
  74. # The engine is built at import time from the URL above, so this catches the
  75. # case where that override did not take effect for whatever reason.
  76. _assert_disposable_database(_app_engine.url, "backend.app.core.database.engine")
  77. # Use in-memory SQLite for tests
  78. TEST_DATABASE_URL = "sqlite+aiosqlite:///:memory:"
  79. @pytest.fixture(autouse=True)
  80. def mfa_encryption_isolation(monkeypatch, tmp_path):
  81. """Per-test isolation for MFA encryption state.
  82. - Sets ``DATA_DIR`` to an isolated tmp path so the auto-bootstrap can
  83. never write ``.mfa_encryption_key`` into the repo or share state
  84. across tests / xdist workers.
  85. - Removes any inherited ``MFA_ENCRYPTION_KEY`` env var.
  86. - With ``DATA_DIR`` pointing at a writable ``tmp_path``, the default
  87. bootstrap path on first ``_get_fernet()`` call is **auto-generation**
  88. (key_source='generated'), NOT plaintext fallback. Tests that need the
  89. plaintext fallback path must monkeypatch ``_load_or_generate_key`` to
  90. return ``(None, 'none')`` (or 'none_write_failed' / 'none_corrupted')
  91. explicitly — see ``test_plaintext_passthrough_without_key`` for an
  92. example.
  93. - Resets the ``encryption`` module-level singletons before AND after the
  94. test so reorder doesn't leak cached Fernet instances.
  95. Tests that want to exercise an active key should call
  96. ``monkeypatch.setenv("MFA_ENCRYPTION_KEY", valid_key)`` and
  97. ``enc_mod._fernet_instance = None`` inside the test body — the autouse
  98. fixture only sets defaults, it doesn't lock them in.
  99. """
  100. from backend.app.core import encryption as enc_mod
  101. monkeypatch.setenv("DATA_DIR", str(tmp_path))
  102. monkeypatch.delenv("MFA_ENCRYPTION_KEY", raising=False)
  103. enc_mod._fernet_instance = None
  104. enc_mod._warn_shown = False
  105. enc_mod._key_source = None
  106. yield
  107. enc_mod._fernet_instance = None
  108. enc_mod._warn_shown = False
  109. enc_mod._key_source = None
  110. @pytest.fixture(autouse=True)
  111. def reset_spoolman_location_sync_cache():
  112. """Drop the per-URL Spoolman location-sync TTL cache between tests.
  113. Without this, a test that runs the sync against `http://localhost:7912`
  114. will skip the sync in any later test that uses the same URL within 60
  115. real seconds — test ordering would then leak assertions across runs."""
  116. from backend.app.services.location_service import _spoolman_location_sync_cache_clear
  117. _spoolman_location_sync_cache_clear()
  118. yield
  119. _spoolman_location_sync_cache_clear()
  120. @pytest.fixture(autouse=True)
  121. def reset_auth_enabled_cache():
  122. """Drop the module-level auth-enabled cache between tests (issue #2572).
  123. ``is_auth_enabled`` caches an enabled=True result for a TTL. Without this
  124. reset a test that enables auth would leave ``True`` cached, so a later test
  125. running in auth-disabled mode (without going through ``set_auth_enabled``)
  126. would wrongly see auth as enabled until the TTL expired — order-dependent
  127. flakiness."""
  128. from backend.app.core.auth import invalidate_auth_enabled_cache
  129. invalidate_auth_enabled_cache()
  130. yield
  131. invalidate_auth_enabled_cache()
  132. @pytest.fixture(autouse=True)
  133. def disconnect_printers_registered_during_a_test():
  134. """Give every test an empty ``printer_manager`` singleton.
  135. ``POST /api/v1/printers`` really calls ``connect_printer``, so a test that
  136. creates a printer through the API parks a live client in the singleton --
  137. and the singleton outlives the per-test in-memory database. The next test
  138. on the same xdist worker gets a fresh database whose first printer is handed
  139. the same primary key, and reads that leftover client as its own live status.
  140. ``test_scheduled_drying_routes`` saw exactly that: an "online" printer with
  141. no firmware version, so scheduling a dry came back 400 instead of 200.
  142. Snapshotting the ids at test entry was insufficient: a client leaked by a
  143. previous module became part of that snapshot and therefore survived every
  144. later cleanup on the same xdist worker. Clear both before and after each
  145. test. ``disconnect_printer`` also clears model/printer-info caches and stops
  146. any paho thread owned by the leaked client.
  147. """
  148. from backend.app.services.printer_manager import printer_manager
  149. for printer_id in list(printer_manager._clients):
  150. printer_manager.disconnect_printer(printer_id)
  151. yield
  152. for printer_id in list(printer_manager._clients):
  153. printer_manager.disconnect_printer(printer_id)
  154. @pytest.fixture(scope="session")
  155. def event_loop():
  156. """Create an instance of the default event loop for each test session."""
  157. loop = asyncio.get_event_loop_policy().new_event_loop()
  158. yield loop
  159. # Dispose the module-level engine so aiosqlite worker threads finish
  160. # before the event loop closes, preventing "Event loop is closed" errors.
  161. from backend.app.core.database import engine
  162. loop.run_until_complete(engine.dispose())
  163. loop.run_until_complete(asyncio.sleep(0.05))
  164. loop.close()
  165. @pytest.fixture
  166. async def test_engine():
  167. """Create a test database engine."""
  168. engine = create_async_engine(TEST_DATABASE_URL, echo=False)
  169. # Import all models to register them
  170. from backend.app.models import (
  171. active_print_session, # noqa: F401
  172. ams_history,
  173. ams_label,
  174. api_key,
  175. archive,
  176. auth_ephemeral,
  177. color_catalog,
  178. external_link,
  179. filament,
  180. group,
  181. kprofile_note,
  182. maintenance,
  183. notification,
  184. notification_template,
  185. oidc_provider,
  186. print_log,
  187. print_queue,
  188. printer,
  189. project,
  190. project_bom,
  191. scheduled_drying,
  192. settings,
  193. slot_preset,
  194. smart_plug,
  195. smart_plug_energy_snapshot, # noqa: F401
  196. sponsor_toast_state, # noqa: F401
  197. spool,
  198. spool_assignment,
  199. spool_catalog,
  200. spool_k_profile,
  201. spool_usage_history,
  202. spoolbuddy_device,
  203. spoolman_k_profile,
  204. spoolman_slot_assignment,
  205. user,
  206. user_email_pref,
  207. user_otp_code,
  208. user_totp,
  209. virtual_printer,
  210. )
  211. async with engine.begin() as conn:
  212. await conn.run_sync(Base.metadata.create_all)
  213. yield engine
  214. async with engine.begin() as conn:
  215. await conn.run_sync(Base.metadata.drop_all)
  216. await engine.dispose()
  217. # Allow aiosqlite's background thread to finish processing the close
  218. # response before the per-function event loop shuts down, preventing
  219. # "RuntimeError: Event loop is closed" in call_soon_threadsafe.
  220. await asyncio.sleep(0.1)
  221. @pytest.fixture
  222. async def db_session(test_engine) -> AsyncGenerator[AsyncSession, None]:
  223. """Create a test database session."""
  224. async_session_maker = async_sessionmaker(test_engine, class_=AsyncSession, expire_on_commit=False)
  225. async with async_session_maker() as session:
  226. yield session
  227. @pytest.fixture
  228. async def async_client(test_engine, db_session) -> AsyncGenerator[AsyncClient, None]:
  229. """Create an async test client."""
  230. from backend.app.core.database import async_session, get_db
  231. from backend.app.main import app
  232. # Create a new session maker for the test engine
  233. test_async_session = async_sessionmaker(test_engine, class_=AsyncSession, expire_on_commit=False)
  234. async def override_get_db():
  235. # Mirror production get_db (core/database.py): commit on success,
  236. # rollback on error. Endpoints that rely on the request-scoped
  237. # implicit commit (e.g. create_project, which only flushes) would
  238. # otherwise silently lose their writes in tests (#1897).
  239. async with test_async_session() as session:
  240. try:
  241. yield session
  242. await session.commit()
  243. except BaseException:
  244. await session.rollback()
  245. raise
  246. app.dependency_overrides[get_db] = override_get_db
  247. # Mock init_printer_connections to prevent MQTT connection attempts during tests
  248. async def mock_init_printer_connections(db):
  249. pass # No-op - don't connect to real printers
  250. # Also patch the module-level async_session used by services, auth, and middleware
  251. with (
  252. patch("backend.app.core.database.async_session", test_async_session),
  253. patch("backend.app.core.auth.async_session", test_async_session),
  254. patch("backend.app.main.async_session", test_async_session),
  255. # Obico endpoints load settings through the service's module-level binding;
  256. # without this patch they'd read whatever DB the cwd resolves to (#1546).
  257. patch("backend.app.services.obico_detection.async_session", test_async_session),
  258. patch("backend.app.main.init_printer_connections", mock_init_printer_connections),
  259. ):
  260. # Seed default groups for tests that need them
  261. from backend.app.core.database import seed_default_groups
  262. await seed_default_groups()
  263. async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
  264. yield client
  265. # The app lifespan called init_db() which used the module-level engine
  266. # (not the test engine), creating aiosqlite connections. Dispose those
  267. # connections so their background threads finish before the event loop closes.
  268. from backend.app.core.database import engine as real_engine
  269. await real_engine.dispose()
  270. app.dependency_overrides.clear()
  271. # ============================================================================
  272. # Mock External Services
  273. # ============================================================================
  274. @pytest.fixture
  275. def mock_tasmota_service():
  276. """Mock the Tasmota service for smart plug tests."""
  277. # Patch both the module where it's defined and where it's imported
  278. with (
  279. patch("backend.app.services.tasmota.tasmota_service") as mock,
  280. patch("backend.app.api.routes.smart_plugs.tasmota_service") as mock2,
  281. ):
  282. mock.turn_on = AsyncMock(return_value=True)
  283. mock.turn_off = AsyncMock(return_value=True)
  284. mock.toggle = AsyncMock(return_value=True)
  285. mock.get_status = AsyncMock(return_value={"state": "ON", "reachable": True, "device_name": "Test Plug"})
  286. mock.get_energy = AsyncMock(
  287. return_value={
  288. "power": 150.5,
  289. "voltage": 120.0,
  290. "current": 1.25,
  291. "today": 2.5,
  292. "total": 100.0,
  293. "factor": 0.95,
  294. }
  295. )
  296. mock.test_connection = AsyncMock(return_value={"success": True, "state": "ON", "device_name": "Test Plug"})
  297. # Copy mocks to second patch target
  298. mock2.turn_on = mock.turn_on
  299. mock2.turn_off = mock.turn_off
  300. mock2.toggle = mock.toggle
  301. mock2.get_status = mock.get_status
  302. mock2.get_energy = mock.get_energy
  303. mock2.test_connection = mock.test_connection
  304. yield mock
  305. @pytest.fixture
  306. def mock_homeassistant_service():
  307. """Mock the Home Assistant service for smart plug tests."""
  308. # Patch both the module where it's defined and where it's imported
  309. with (
  310. patch("backend.app.services.homeassistant.homeassistant_service") as mock,
  311. patch("backend.app.api.routes.smart_plugs.homeassistant_service") as mock2,
  312. ):
  313. mock.turn_on = AsyncMock(return_value=True)
  314. mock.turn_off = AsyncMock(return_value=True)
  315. mock.toggle = AsyncMock(return_value=True)
  316. mock.get_status = AsyncMock(return_value={"state": "ON", "reachable": True, "device_name": "Test HA Entity"})
  317. mock.get_energy = AsyncMock(return_value=None) # Most HA entities don't have power monitoring
  318. mock.test_connection = AsyncMock(return_value={"success": True, "message": "API running", "error": None})
  319. mock.list_entities = AsyncMock(
  320. return_value=[
  321. {
  322. "entity_id": "switch.printer_plug",
  323. "friendly_name": "Printer Plug",
  324. "state": "on",
  325. "domain": "switch",
  326. },
  327. {"entity_id": "switch.test", "friendly_name": "Test Switch", "state": "off", "domain": "switch"},
  328. ]
  329. )
  330. mock.configure = MagicMock()
  331. # Copy mocks to second patch target
  332. mock2.turn_on = mock.turn_on
  333. mock2.turn_off = mock.turn_off
  334. mock2.toggle = mock.toggle
  335. mock2.get_status = mock.get_status
  336. mock2.get_energy = mock.get_energy
  337. mock2.test_connection = mock.test_connection
  338. mock2.list_entities = mock.list_entities
  339. mock2.configure = mock.configure
  340. yield mock
  341. @pytest.fixture
  342. def mock_mqtt_client():
  343. """Mock the MQTT client for printer communication tests."""
  344. with patch("backend.app.services.bambu_mqtt.BambuMQTTClient") as mock:
  345. instance = MagicMock()
  346. instance.state = MagicMock(connected=True, state="IDLE", progress=0, temperatures={"nozzle": 25, "bed": 25})
  347. instance.connect = MagicMock()
  348. instance.disconnect = MagicMock()
  349. mock.return_value = instance
  350. yield mock
  351. @pytest.fixture
  352. def mock_mqtt_smart_plug_service():
  353. """Mock the MQTT smart plug service for MQTT plug tests."""
  354. with patch("backend.app.api.routes.smart_plugs.mqtt_relay") as mock:
  355. # Create a mock smart_plug_service
  356. mock_service = MagicMock()
  357. mock_service.is_configured = MagicMock(return_value=True)
  358. mock_service.has_broker_settings = MagicMock(return_value=True)
  359. mock_service.configure = AsyncMock(return_value=True)
  360. mock_service.subscribe = MagicMock()
  361. mock_service.unsubscribe = MagicMock()
  362. mock_service.get_plug_data = MagicMock(return_value=None)
  363. mock_service.is_reachable = MagicMock(return_value=False)
  364. mock.smart_plug_service = mock_service
  365. yield mock
  366. @pytest.fixture
  367. def mock_ftp_client():
  368. """Mock the FTP client for file transfer tests."""
  369. with (
  370. patch("backend.app.services.bambu_ftp.download_file_async") as download_mock,
  371. patch("backend.app.services.bambu_ftp.list_files_async") as list_mock,
  372. ):
  373. download_mock.return_value = True
  374. list_mock.return_value = []
  375. yield {"download": download_mock, "list": list_mock}
  376. @pytest.fixture
  377. def mock_httpx_client():
  378. """Mock httpx for webhook/notification HTTP calls."""
  379. with patch("httpx.AsyncClient") as mock_class:
  380. mock_instance = AsyncMock()
  381. mock_response = MagicMock()
  382. mock_response.status_code = 200
  383. mock_response.text = "OK"
  384. mock_response.json.return_value = {}
  385. mock_instance.get = AsyncMock(return_value=mock_response)
  386. mock_instance.post = AsyncMock(return_value=mock_response)
  387. mock_instance.__aenter__ = AsyncMock(return_value=mock_instance)
  388. mock_instance.__aexit__ = AsyncMock()
  389. mock_class.return_value = mock_instance
  390. yield mock_instance
  391. @pytest.fixture
  392. def mock_printer_manager():
  393. """Mock the printer manager for status checks."""
  394. with patch("backend.app.services.printer_manager.printer_manager") as mock:
  395. mock.get_status = MagicMock(
  396. return_value=MagicMock(
  397. connected=True,
  398. state="IDLE",
  399. progress=0,
  400. temperatures={"nozzle": 25, "bed": 25, "chamber": 25},
  401. raw_data={},
  402. )
  403. )
  404. mock.mark_printer_offline = MagicMock()
  405. yield mock
  406. # ============================================================================
  407. # Factory Fixtures for Test Data
  408. # ============================================================================
  409. @pytest.fixture
  410. def smart_plug_factory(db_session):
  411. """Factory to create test smart plugs."""
  412. async def _create_plug(**kwargs):
  413. from backend.app.models.smart_plug import SmartPlug
  414. # Determine defaults based on plug_type
  415. plug_type = kwargs.get("plug_type", "tasmota")
  416. defaults = {
  417. "name": "Test Plug",
  418. "plug_type": plug_type,
  419. "enabled": True,
  420. "auto_on": True,
  421. "auto_off": True,
  422. "off_delay_mode": "time",
  423. "off_delay_minutes": 5,
  424. "off_temp_threshold": 70,
  425. "schedule_enabled": False,
  426. "power_alert_enabled": False,
  427. }
  428. # Set required fields based on plug_type
  429. if plug_type == "homeassistant":
  430. defaults["ha_entity_id"] = "switch.test"
  431. defaults["ip_address"] = None
  432. elif plug_type == "mqtt":
  433. # Legacy fields (for backward compatibility tests)
  434. defaults["mqtt_topic"] = kwargs.get("mqtt_topic", "test/topic")
  435. defaults["mqtt_multiplier"] = kwargs.get("mqtt_multiplier", 1.0)
  436. # New separate topic/path/multiplier fields
  437. defaults["mqtt_power_topic"] = kwargs.get("mqtt_power_topic")
  438. defaults["mqtt_power_path"] = kwargs.get("mqtt_power_path", "power")
  439. defaults["mqtt_power_multiplier"] = kwargs.get("mqtt_power_multiplier", 1.0)
  440. defaults["mqtt_energy_topic"] = kwargs.get("mqtt_energy_topic")
  441. defaults["mqtt_energy_path"] = kwargs.get("mqtt_energy_path")
  442. defaults["mqtt_energy_multiplier"] = kwargs.get("mqtt_energy_multiplier", 1.0)
  443. defaults["mqtt_state_topic"] = kwargs.get("mqtt_state_topic")
  444. defaults["mqtt_state_path"] = kwargs.get("mqtt_state_path")
  445. defaults["mqtt_state_on_value"] = kwargs.get("mqtt_state_on_value")
  446. defaults["ip_address"] = None
  447. defaults["ha_entity_id"] = None
  448. elif plug_type == "rest":
  449. defaults["rest_on_url"] = kwargs.get("rest_on_url", "http://192.168.1.100/api/plug/on")
  450. defaults["rest_off_url"] = kwargs.get("rest_off_url", "http://192.168.1.100/api/plug/off")
  451. defaults["rest_method"] = kwargs.get("rest_method", "POST")
  452. defaults["ip_address"] = None
  453. defaults["ha_entity_id"] = None
  454. else:
  455. defaults["ip_address"] = "192.168.1.100"
  456. defaults["ha_entity_id"] = None
  457. defaults.update(kwargs)
  458. plug = SmartPlug(**defaults)
  459. db_session.add(plug)
  460. await db_session.commit()
  461. await db_session.refresh(plug)
  462. return plug
  463. return _create_plug
  464. @pytest.fixture
  465. def printer_factory(db_session):
  466. """Factory to create test printers."""
  467. _counter = [0] # Use list to allow mutation in nested function
  468. async def _create_printer(**kwargs):
  469. from backend.app.models.printer import Printer
  470. _counter[0] += 1
  471. counter = _counter[0]
  472. defaults = {
  473. "name": "Test Printer",
  474. "serial_number": f"00M09A{counter:09d}", # Unique serial per printer
  475. "ip_address": f"192.168.1.{100 + counter}", # Unique IP per printer
  476. "access_code": "12345678",
  477. "is_active": True,
  478. "auto_archive": True,
  479. "model": "X1C",
  480. }
  481. defaults.update(kwargs)
  482. printer = Printer(**defaults)
  483. db_session.add(printer)
  484. await db_session.commit()
  485. await db_session.refresh(printer)
  486. return printer
  487. return _create_printer
  488. @pytest.fixture
  489. def notification_provider_factory(db_session):
  490. """Factory to create test notification providers."""
  491. async def _create_provider(**kwargs):
  492. from backend.app.models.notification import NotificationProvider
  493. config = kwargs.pop("config", {"server": "https://ntfy.sh", "topic": "test-topic"})
  494. if isinstance(config, dict):
  495. config = json.dumps(config)
  496. defaults = {
  497. "name": "Test Provider",
  498. "provider_type": "ntfy",
  499. "enabled": True,
  500. "config": config,
  501. "on_print_start": True,
  502. "on_print_complete": True,
  503. "on_print_failed": True,
  504. "on_print_stopped": True,
  505. "on_print_progress": False,
  506. "on_print_missing_spool_assignment": False,
  507. "on_billing_charge_failed": True,
  508. "on_printer_offline": False,
  509. "on_printer_error": False,
  510. "on_filament_low": False,
  511. "on_maintenance_due": False,
  512. "on_ams_humidity_high": False,
  513. "on_ams_temperature_high": False,
  514. "on_bed_cooled": False,
  515. "quiet_hours_enabled": False,
  516. "daily_digest_enabled": False,
  517. }
  518. defaults.update(kwargs)
  519. provider = NotificationProvider(**defaults)
  520. db_session.add(provider)
  521. await db_session.commit()
  522. await db_session.refresh(provider)
  523. return provider
  524. return _create_provider
  525. @pytest.fixture
  526. def archive_factory(db_session):
  527. """Factory to create test archives.
  528. Also synthesizes one PrintLogEntry per archive (matching the production
  529. flow where statistics are aggregated from PrintLogEntry, not PrintArchive,
  530. per #1378). Pass ``with_run=False`` to skip — useful for testing the
  531. "archived but never printed" state. Pass ``run_status=...`` to override
  532. the run's status independently of the archive's status field.
  533. """
  534. async def _create_archive(printer_id: int, **kwargs):
  535. from backend.app.models.archive import PrintArchive
  536. from backend.app.models.print_log import PrintLogEntry
  537. with_run = kwargs.pop("with_run", True)
  538. run_status = kwargs.pop("run_status", None)
  539. defaults = {
  540. "printer_id": printer_id,
  541. "filename": "test_print.gcode.3mf",
  542. "print_name": "Test Print",
  543. "file_path": "archives/test/test_print.gcode.3mf",
  544. "file_size": 1024000,
  545. "status": "completed",
  546. "filament_type": "PLA",
  547. "filament_used_grams": 50.0,
  548. "print_time_seconds": 3600,
  549. }
  550. defaults.update(kwargs)
  551. archive = PrintArchive(**defaults)
  552. db_session.add(archive)
  553. await db_session.commit()
  554. await db_session.refresh(archive)
  555. if with_run:
  556. duration = None
  557. if archive.started_at and archive.completed_at:
  558. duration = int((archive.completed_at - archive.started_at).total_seconds()) or None
  559. run = PrintLogEntry(
  560. archive_id=archive.id,
  561. printer_id=archive.printer_id,
  562. status=run_status or archive.status,
  563. started_at=archive.started_at,
  564. completed_at=archive.completed_at,
  565. duration_seconds=duration,
  566. filament_type=archive.filament_type,
  567. filament_color=archive.filament_color,
  568. filament_used_grams=archive.filament_used_grams,
  569. cost=archive.cost,
  570. energy_kwh=archive.energy_kwh,
  571. energy_cost=archive.energy_cost,
  572. failure_reason=archive.failure_reason,
  573. print_name=archive.print_name,
  574. created_by_id=archive.created_by_id,
  575. # Sync the event's created_at with the archive's so date-range
  576. # filtered tests that backdate an archive still find its event.
  577. created_at=archive.created_at,
  578. )
  579. db_session.add(run)
  580. await db_session.commit()
  581. return archive
  582. return _create_archive
  583. # ============================================================================
  584. # Sample Data Fixtures
  585. # ============================================================================
  586. @pytest.fixture
  587. def sample_mqtt_print_start():
  588. """Sample MQTT message for print start."""
  589. return {
  590. "print": {
  591. "command": "project_file",
  592. "param": "/sdcard/test.gcode.3mf",
  593. "subtask_name": "test_print",
  594. "gcode_state": "RUNNING",
  595. "mc_percent": 0,
  596. }
  597. }
  598. @pytest.fixture
  599. def sample_mqtt_print_complete():
  600. """Sample MQTT message for print complete."""
  601. return {
  602. "print": {
  603. "gcode_state": "FINISH",
  604. "mc_percent": 100,
  605. "subtask_name": "test_print",
  606. }
  607. }
  608. @pytest.fixture
  609. def sample_printer_status():
  610. """Sample printer status data."""
  611. return {
  612. "connected": True,
  613. "state": "IDLE",
  614. "progress": 0,
  615. "layer_num": 0,
  616. "total_layers": 0,
  617. "temperatures": {
  618. "nozzle": 25.0,
  619. "bed": 25.0,
  620. "chamber": 25.0,
  621. },
  622. "remaining_time": 0,
  623. "filename": None,
  624. }
  625. # ============================================================================
  626. # Log Capture Fixtures for Error Detection
  627. # ============================================================================
  628. class LogCapture(logging.Handler):
  629. """Handler that captures log records for testing."""
  630. def __init__(self):
  631. super().__init__()
  632. self.records: list[logging.LogRecord] = []
  633. def emit(self, record: logging.LogRecord):
  634. self.records.append(record)
  635. def clear(self):
  636. self.records.clear()
  637. def get_errors(self) -> list[logging.LogRecord]:
  638. """Get all ERROR and CRITICAL level records."""
  639. return [r for r in self.records if r.levelno >= logging.ERROR]
  640. def get_warnings(self) -> list[logging.LogRecord]:
  641. """Get all WARNING level records."""
  642. return [r for r in self.records if r.levelno == logging.WARNING]
  643. def has_errors(self) -> bool:
  644. """Check if any errors were logged."""
  645. return len(self.get_errors()) > 0
  646. def format_errors(self) -> str:
  647. """Format all errors as a string for assertion messages."""
  648. errors = self.get_errors()
  649. if not errors:
  650. return "No errors"
  651. formatter = logging.Formatter("%(name)s - %(levelname)s - %(message)s")
  652. return "\n".join(formatter.format(r) for r in errors)
  653. @pytest.fixture
  654. def capture_logs():
  655. """Fixture that captures log output during a test.
  656. Usage:
  657. def test_something(capture_logs):
  658. # Do something that might log errors
  659. some_function()
  660. # Check no errors were logged
  661. assert not capture_logs.has_errors(), capture_logs.format_errors()
  662. """
  663. handler = LogCapture()
  664. handler.setLevel(logging.DEBUG)
  665. # Attach to root logger to capture all logs
  666. root_logger = logging.getLogger()
  667. root_logger.addHandler(handler)
  668. yield handler
  669. root_logger.removeHandler(handler)
  670. @pytest.fixture
  671. def assert_no_log_errors(capture_logs):
  672. """Fixture that automatically asserts no errors were logged.
  673. Usage:
  674. def test_something(assert_no_log_errors):
  675. # If any ERROR logs occur during this test, it will fail
  676. some_function()
  677. """
  678. yield capture_logs
  679. errors = capture_logs.get_errors()
  680. if errors:
  681. pytest.fail(f"Unexpected log errors:\n{capture_logs.format_errors()}")