conftest.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827
  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. """Hand the ``printer_manager`` singleton back the way the test found it.
  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. Only ids this test added are dropped, so a client registered by a wider
  143. fixture stays registered. ``disconnect_printer`` is what clears the model
  144. and printer-info caches too, and it stops the paho thread the leaked client
  145. would otherwise keep retrying on for the rest of the run.
  146. """
  147. from backend.app.services.printer_manager import printer_manager
  148. before = set(printer_manager._clients)
  149. yield
  150. for printer_id in set(printer_manager._clients) - before:
  151. printer_manager.disconnect_printer(printer_id)
  152. @pytest.fixture(scope="session")
  153. def event_loop():
  154. """Create an instance of the default event loop for each test session."""
  155. loop = asyncio.get_event_loop_policy().new_event_loop()
  156. yield loop
  157. # Dispose the module-level engine so aiosqlite worker threads finish
  158. # before the event loop closes, preventing "Event loop is closed" errors.
  159. from backend.app.core.database import engine
  160. loop.run_until_complete(engine.dispose())
  161. loop.run_until_complete(asyncio.sleep(0.05))
  162. loop.close()
  163. @pytest.fixture
  164. async def test_engine():
  165. """Create a test database engine."""
  166. engine = create_async_engine(TEST_DATABASE_URL, echo=False)
  167. # Import all models to register them
  168. from backend.app.models import (
  169. active_print_session, # noqa: F401
  170. ams_history,
  171. ams_label,
  172. api_key,
  173. archive,
  174. auth_ephemeral,
  175. color_catalog,
  176. external_link,
  177. filament,
  178. group,
  179. kprofile_note,
  180. maintenance,
  181. notification,
  182. notification_template,
  183. oidc_provider,
  184. print_log,
  185. print_queue,
  186. printer,
  187. project,
  188. project_bom,
  189. scheduled_drying,
  190. settings,
  191. slot_preset,
  192. smart_plug,
  193. smart_plug_energy_snapshot, # noqa: F401
  194. sponsor_toast_state, # noqa: F401
  195. spool,
  196. spool_assignment,
  197. spool_catalog,
  198. spool_k_profile,
  199. spool_usage_history,
  200. spoolbuddy_device,
  201. spoolman_k_profile,
  202. spoolman_slot_assignment,
  203. user,
  204. user_email_pref,
  205. user_otp_code,
  206. user_totp,
  207. virtual_printer,
  208. )
  209. async with engine.begin() as conn:
  210. await conn.run_sync(Base.metadata.create_all)
  211. yield engine
  212. async with engine.begin() as conn:
  213. await conn.run_sync(Base.metadata.drop_all)
  214. await engine.dispose()
  215. # Allow aiosqlite's background thread to finish processing the close
  216. # response before the per-function event loop shuts down, preventing
  217. # "RuntimeError: Event loop is closed" in call_soon_threadsafe.
  218. await asyncio.sleep(0.1)
  219. @pytest.fixture
  220. async def db_session(test_engine) -> AsyncGenerator[AsyncSession, None]:
  221. """Create a test database session."""
  222. async_session_maker = async_sessionmaker(test_engine, class_=AsyncSession, expire_on_commit=False)
  223. async with async_session_maker() as session:
  224. yield session
  225. @pytest.fixture
  226. async def async_client(test_engine, db_session) -> AsyncGenerator[AsyncClient, None]:
  227. """Create an async test client."""
  228. from backend.app.core.database import async_session, get_db
  229. from backend.app.main import app
  230. # Create a new session maker for the test engine
  231. test_async_session = async_sessionmaker(test_engine, class_=AsyncSession, expire_on_commit=False)
  232. async def override_get_db():
  233. # Mirror production get_db (core/database.py): commit on success,
  234. # rollback on error. Endpoints that rely on the request-scoped
  235. # implicit commit (e.g. create_project, which only flushes) would
  236. # otherwise silently lose their writes in tests (#1897).
  237. async with test_async_session() as session:
  238. try:
  239. yield session
  240. await session.commit()
  241. except BaseException:
  242. await session.rollback()
  243. raise
  244. app.dependency_overrides[get_db] = override_get_db
  245. # Mock init_printer_connections to prevent MQTT connection attempts during tests
  246. async def mock_init_printer_connections(db):
  247. pass # No-op - don't connect to real printers
  248. # Also patch the module-level async_session used by services, auth, and middleware
  249. with (
  250. patch("backend.app.core.database.async_session", test_async_session),
  251. patch("backend.app.core.auth.async_session", test_async_session),
  252. patch("backend.app.main.async_session", test_async_session),
  253. # Obico endpoints load settings through the service's module-level binding;
  254. # without this patch they'd read whatever DB the cwd resolves to (#1546).
  255. patch("backend.app.services.obico_detection.async_session", test_async_session),
  256. patch("backend.app.main.init_printer_connections", mock_init_printer_connections),
  257. ):
  258. # Seed default groups for tests that need them
  259. from backend.app.core.database import seed_default_groups
  260. await seed_default_groups()
  261. async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
  262. yield client
  263. # The app lifespan called init_db() which used the module-level engine
  264. # (not the test engine), creating aiosqlite connections. Dispose those
  265. # connections so their background threads finish before the event loop closes.
  266. from backend.app.core.database import engine as real_engine
  267. await real_engine.dispose()
  268. app.dependency_overrides.clear()
  269. # ============================================================================
  270. # Mock External Services
  271. # ============================================================================
  272. @pytest.fixture
  273. def mock_tasmota_service():
  274. """Mock the Tasmota service for smart plug tests."""
  275. # Patch both the module where it's defined and where it's imported
  276. with (
  277. patch("backend.app.services.tasmota.tasmota_service") as mock,
  278. patch("backend.app.api.routes.smart_plugs.tasmota_service") as mock2,
  279. ):
  280. mock.turn_on = AsyncMock(return_value=True)
  281. mock.turn_off = AsyncMock(return_value=True)
  282. mock.toggle = AsyncMock(return_value=True)
  283. mock.get_status = AsyncMock(return_value={"state": "ON", "reachable": True, "device_name": "Test Plug"})
  284. mock.get_energy = AsyncMock(
  285. return_value={
  286. "power": 150.5,
  287. "voltage": 120.0,
  288. "current": 1.25,
  289. "today": 2.5,
  290. "total": 100.0,
  291. "factor": 0.95,
  292. }
  293. )
  294. mock.test_connection = AsyncMock(return_value={"success": True, "state": "ON", "device_name": "Test Plug"})
  295. # Copy mocks to second patch target
  296. mock2.turn_on = mock.turn_on
  297. mock2.turn_off = mock.turn_off
  298. mock2.toggle = mock.toggle
  299. mock2.get_status = mock.get_status
  300. mock2.get_energy = mock.get_energy
  301. mock2.test_connection = mock.test_connection
  302. yield mock
  303. @pytest.fixture
  304. def mock_homeassistant_service():
  305. """Mock the Home Assistant service for smart plug tests."""
  306. # Patch both the module where it's defined and where it's imported
  307. with (
  308. patch("backend.app.services.homeassistant.homeassistant_service") as mock,
  309. patch("backend.app.api.routes.smart_plugs.homeassistant_service") as mock2,
  310. ):
  311. mock.turn_on = AsyncMock(return_value=True)
  312. mock.turn_off = AsyncMock(return_value=True)
  313. mock.toggle = AsyncMock(return_value=True)
  314. mock.get_status = AsyncMock(return_value={"state": "ON", "reachable": True, "device_name": "Test HA Entity"})
  315. mock.get_energy = AsyncMock(return_value=None) # Most HA entities don't have power monitoring
  316. mock.test_connection = AsyncMock(return_value={"success": True, "message": "API running", "error": None})
  317. mock.list_entities = AsyncMock(
  318. return_value=[
  319. {
  320. "entity_id": "switch.printer_plug",
  321. "friendly_name": "Printer Plug",
  322. "state": "on",
  323. "domain": "switch",
  324. },
  325. {"entity_id": "switch.test", "friendly_name": "Test Switch", "state": "off", "domain": "switch"},
  326. ]
  327. )
  328. mock.configure = MagicMock()
  329. # Copy mocks to second patch target
  330. mock2.turn_on = mock.turn_on
  331. mock2.turn_off = mock.turn_off
  332. mock2.toggle = mock.toggle
  333. mock2.get_status = mock.get_status
  334. mock2.get_energy = mock.get_energy
  335. mock2.test_connection = mock.test_connection
  336. mock2.list_entities = mock.list_entities
  337. mock2.configure = mock.configure
  338. yield mock
  339. @pytest.fixture
  340. def mock_mqtt_client():
  341. """Mock the MQTT client for printer communication tests."""
  342. with patch("backend.app.services.bambu_mqtt.BambuMQTTClient") as mock:
  343. instance = MagicMock()
  344. instance.state = MagicMock(connected=True, state="IDLE", progress=0, temperatures={"nozzle": 25, "bed": 25})
  345. instance.connect = MagicMock()
  346. instance.disconnect = MagicMock()
  347. mock.return_value = instance
  348. yield mock
  349. @pytest.fixture
  350. def mock_mqtt_smart_plug_service():
  351. """Mock the MQTT smart plug service for MQTT plug tests."""
  352. with patch("backend.app.api.routes.smart_plugs.mqtt_relay") as mock:
  353. # Create a mock smart_plug_service
  354. mock_service = MagicMock()
  355. mock_service.is_configured = MagicMock(return_value=True)
  356. mock_service.has_broker_settings = MagicMock(return_value=True)
  357. mock_service.configure = AsyncMock(return_value=True)
  358. mock_service.subscribe = MagicMock()
  359. mock_service.unsubscribe = MagicMock()
  360. mock_service.get_plug_data = MagicMock(return_value=None)
  361. mock_service.is_reachable = MagicMock(return_value=False)
  362. mock.smart_plug_service = mock_service
  363. yield mock
  364. @pytest.fixture
  365. def mock_ftp_client():
  366. """Mock the FTP client for file transfer tests."""
  367. with (
  368. patch("backend.app.services.bambu_ftp.download_file_async") as download_mock,
  369. patch("backend.app.services.bambu_ftp.list_files_async") as list_mock,
  370. ):
  371. download_mock.return_value = True
  372. list_mock.return_value = []
  373. yield {"download": download_mock, "list": list_mock}
  374. @pytest.fixture
  375. def mock_httpx_client():
  376. """Mock httpx for webhook/notification HTTP calls."""
  377. with patch("httpx.AsyncClient") as mock_class:
  378. mock_instance = AsyncMock()
  379. mock_response = MagicMock()
  380. mock_response.status_code = 200
  381. mock_response.text = "OK"
  382. mock_response.json.return_value = {}
  383. mock_instance.get = AsyncMock(return_value=mock_response)
  384. mock_instance.post = AsyncMock(return_value=mock_response)
  385. mock_instance.__aenter__ = AsyncMock(return_value=mock_instance)
  386. mock_instance.__aexit__ = AsyncMock()
  387. mock_class.return_value = mock_instance
  388. yield mock_instance
  389. @pytest.fixture
  390. def mock_printer_manager():
  391. """Mock the printer manager for status checks."""
  392. with patch("backend.app.services.printer_manager.printer_manager") as mock:
  393. mock.get_status = MagicMock(
  394. return_value=MagicMock(
  395. connected=True,
  396. state="IDLE",
  397. progress=0,
  398. temperatures={"nozzle": 25, "bed": 25, "chamber": 25},
  399. raw_data={},
  400. )
  401. )
  402. mock.mark_printer_offline = MagicMock()
  403. yield mock
  404. # ============================================================================
  405. # Factory Fixtures for Test Data
  406. # ============================================================================
  407. @pytest.fixture
  408. def smart_plug_factory(db_session):
  409. """Factory to create test smart plugs."""
  410. async def _create_plug(**kwargs):
  411. from backend.app.models.smart_plug import SmartPlug
  412. # Determine defaults based on plug_type
  413. plug_type = kwargs.get("plug_type", "tasmota")
  414. defaults = {
  415. "name": "Test Plug",
  416. "plug_type": plug_type,
  417. "enabled": True,
  418. "auto_on": True,
  419. "auto_off": True,
  420. "off_delay_mode": "time",
  421. "off_delay_minutes": 5,
  422. "off_temp_threshold": 70,
  423. "schedule_enabled": False,
  424. "power_alert_enabled": False,
  425. }
  426. # Set required fields based on plug_type
  427. if plug_type == "homeassistant":
  428. defaults["ha_entity_id"] = "switch.test"
  429. defaults["ip_address"] = None
  430. elif plug_type == "mqtt":
  431. # Legacy fields (for backward compatibility tests)
  432. defaults["mqtt_topic"] = kwargs.get("mqtt_topic", "test/topic")
  433. defaults["mqtt_multiplier"] = kwargs.get("mqtt_multiplier", 1.0)
  434. # New separate topic/path/multiplier fields
  435. defaults["mqtt_power_topic"] = kwargs.get("mqtt_power_topic")
  436. defaults["mqtt_power_path"] = kwargs.get("mqtt_power_path", "power")
  437. defaults["mqtt_power_multiplier"] = kwargs.get("mqtt_power_multiplier", 1.0)
  438. defaults["mqtt_energy_topic"] = kwargs.get("mqtt_energy_topic")
  439. defaults["mqtt_energy_path"] = kwargs.get("mqtt_energy_path")
  440. defaults["mqtt_energy_multiplier"] = kwargs.get("mqtt_energy_multiplier", 1.0)
  441. defaults["mqtt_state_topic"] = kwargs.get("mqtt_state_topic")
  442. defaults["mqtt_state_path"] = kwargs.get("mqtt_state_path")
  443. defaults["mqtt_state_on_value"] = kwargs.get("mqtt_state_on_value")
  444. defaults["ip_address"] = None
  445. defaults["ha_entity_id"] = None
  446. elif plug_type == "rest":
  447. defaults["rest_on_url"] = kwargs.get("rest_on_url", "http://192.168.1.100/api/plug/on")
  448. defaults["rest_off_url"] = kwargs.get("rest_off_url", "http://192.168.1.100/api/plug/off")
  449. defaults["rest_method"] = kwargs.get("rest_method", "POST")
  450. defaults["ip_address"] = None
  451. defaults["ha_entity_id"] = None
  452. else:
  453. defaults["ip_address"] = "192.168.1.100"
  454. defaults["ha_entity_id"] = None
  455. defaults.update(kwargs)
  456. plug = SmartPlug(**defaults)
  457. db_session.add(plug)
  458. await db_session.commit()
  459. await db_session.refresh(plug)
  460. return plug
  461. return _create_plug
  462. @pytest.fixture
  463. def printer_factory(db_session):
  464. """Factory to create test printers."""
  465. _counter = [0] # Use list to allow mutation in nested function
  466. async def _create_printer(**kwargs):
  467. from backend.app.models.printer import Printer
  468. _counter[0] += 1
  469. counter = _counter[0]
  470. defaults = {
  471. "name": "Test Printer",
  472. "serial_number": f"00M09A{counter:09d}", # Unique serial per printer
  473. "ip_address": f"192.168.1.{100 + counter}", # Unique IP per printer
  474. "access_code": "12345678",
  475. "is_active": True,
  476. "auto_archive": True,
  477. "model": "X1C",
  478. }
  479. defaults.update(kwargs)
  480. printer = Printer(**defaults)
  481. db_session.add(printer)
  482. await db_session.commit()
  483. await db_session.refresh(printer)
  484. return printer
  485. return _create_printer
  486. @pytest.fixture
  487. def notification_provider_factory(db_session):
  488. """Factory to create test notification providers."""
  489. async def _create_provider(**kwargs):
  490. from backend.app.models.notification import NotificationProvider
  491. config = kwargs.pop("config", {"server": "https://ntfy.sh", "topic": "test-topic"})
  492. if isinstance(config, dict):
  493. config = json.dumps(config)
  494. defaults = {
  495. "name": "Test Provider",
  496. "provider_type": "ntfy",
  497. "enabled": True,
  498. "config": config,
  499. "on_print_start": True,
  500. "on_print_complete": True,
  501. "on_print_failed": True,
  502. "on_print_stopped": True,
  503. "on_print_progress": False,
  504. "on_print_missing_spool_assignment": False,
  505. "on_billing_charge_failed": True,
  506. "on_printer_offline": False,
  507. "on_printer_error": False,
  508. "on_filament_low": False,
  509. "on_maintenance_due": False,
  510. "on_ams_humidity_high": False,
  511. "on_ams_temperature_high": False,
  512. "on_bed_cooled": False,
  513. "quiet_hours_enabled": False,
  514. "daily_digest_enabled": False,
  515. }
  516. defaults.update(kwargs)
  517. provider = NotificationProvider(**defaults)
  518. db_session.add(provider)
  519. await db_session.commit()
  520. await db_session.refresh(provider)
  521. return provider
  522. return _create_provider
  523. @pytest.fixture
  524. def archive_factory(db_session):
  525. """Factory to create test archives.
  526. Also synthesizes one PrintLogEntry per archive (matching the production
  527. flow where statistics are aggregated from PrintLogEntry, not PrintArchive,
  528. per #1378). Pass ``with_run=False`` to skip — useful for testing the
  529. "archived but never printed" state. Pass ``run_status=...`` to override
  530. the run's status independently of the archive's status field.
  531. """
  532. async def _create_archive(printer_id: int, **kwargs):
  533. from backend.app.models.archive import PrintArchive
  534. from backend.app.models.print_log import PrintLogEntry
  535. with_run = kwargs.pop("with_run", True)
  536. run_status = kwargs.pop("run_status", None)
  537. defaults = {
  538. "printer_id": printer_id,
  539. "filename": "test_print.gcode.3mf",
  540. "print_name": "Test Print",
  541. "file_path": "archives/test/test_print.gcode.3mf",
  542. "file_size": 1024000,
  543. "status": "completed",
  544. "filament_type": "PLA",
  545. "filament_used_grams": 50.0,
  546. "print_time_seconds": 3600,
  547. }
  548. defaults.update(kwargs)
  549. archive = PrintArchive(**defaults)
  550. db_session.add(archive)
  551. await db_session.commit()
  552. await db_session.refresh(archive)
  553. if with_run:
  554. duration = None
  555. if archive.started_at and archive.completed_at:
  556. duration = int((archive.completed_at - archive.started_at).total_seconds()) or None
  557. run = PrintLogEntry(
  558. archive_id=archive.id,
  559. printer_id=archive.printer_id,
  560. status=run_status or archive.status,
  561. started_at=archive.started_at,
  562. completed_at=archive.completed_at,
  563. duration_seconds=duration,
  564. filament_type=archive.filament_type,
  565. filament_color=archive.filament_color,
  566. filament_used_grams=archive.filament_used_grams,
  567. cost=archive.cost,
  568. energy_kwh=archive.energy_kwh,
  569. energy_cost=archive.energy_cost,
  570. failure_reason=archive.failure_reason,
  571. print_name=archive.print_name,
  572. created_by_id=archive.created_by_id,
  573. # Sync the event's created_at with the archive's so date-range
  574. # filtered tests that backdate an archive still find its event.
  575. created_at=archive.created_at,
  576. )
  577. db_session.add(run)
  578. await db_session.commit()
  579. return archive
  580. return _create_archive
  581. # ============================================================================
  582. # Sample Data Fixtures
  583. # ============================================================================
  584. @pytest.fixture
  585. def sample_mqtt_print_start():
  586. """Sample MQTT message for print start."""
  587. return {
  588. "print": {
  589. "command": "project_file",
  590. "param": "/sdcard/test.gcode.3mf",
  591. "subtask_name": "test_print",
  592. "gcode_state": "RUNNING",
  593. "mc_percent": 0,
  594. }
  595. }
  596. @pytest.fixture
  597. def sample_mqtt_print_complete():
  598. """Sample MQTT message for print complete."""
  599. return {
  600. "print": {
  601. "gcode_state": "FINISH",
  602. "mc_percent": 100,
  603. "subtask_name": "test_print",
  604. }
  605. }
  606. @pytest.fixture
  607. def sample_printer_status():
  608. """Sample printer status data."""
  609. return {
  610. "connected": True,
  611. "state": "IDLE",
  612. "progress": 0,
  613. "layer_num": 0,
  614. "total_layers": 0,
  615. "temperatures": {
  616. "nozzle": 25.0,
  617. "bed": 25.0,
  618. "chamber": 25.0,
  619. },
  620. "remaining_time": 0,
  621. "filename": None,
  622. }
  623. # ============================================================================
  624. # Log Capture Fixtures for Error Detection
  625. # ============================================================================
  626. class LogCapture(logging.Handler):
  627. """Handler that captures log records for testing."""
  628. def __init__(self):
  629. super().__init__()
  630. self.records: list[logging.LogRecord] = []
  631. def emit(self, record: logging.LogRecord):
  632. self.records.append(record)
  633. def clear(self):
  634. self.records.clear()
  635. def get_errors(self) -> list[logging.LogRecord]:
  636. """Get all ERROR and CRITICAL level records."""
  637. return [r for r in self.records if r.levelno >= logging.ERROR]
  638. def get_warnings(self) -> list[logging.LogRecord]:
  639. """Get all WARNING level records."""
  640. return [r for r in self.records if r.levelno == logging.WARNING]
  641. def has_errors(self) -> bool:
  642. """Check if any errors were logged."""
  643. return len(self.get_errors()) > 0
  644. def format_errors(self) -> str:
  645. """Format all errors as a string for assertion messages."""
  646. errors = self.get_errors()
  647. if not errors:
  648. return "No errors"
  649. formatter = logging.Formatter("%(name)s - %(levelname)s - %(message)s")
  650. return "\n".join(formatter.format(r) for r in errors)
  651. @pytest.fixture
  652. def capture_logs():
  653. """Fixture that captures log output during a test.
  654. Usage:
  655. def test_something(capture_logs):
  656. # Do something that might log errors
  657. some_function()
  658. # Check no errors were logged
  659. assert not capture_logs.has_errors(), capture_logs.format_errors()
  660. """
  661. handler = LogCapture()
  662. handler.setLevel(logging.DEBUG)
  663. # Attach to root logger to capture all logs
  664. root_logger = logging.getLogger()
  665. root_logger.addHandler(handler)
  666. yield handler
  667. root_logger.removeHandler(handler)
  668. @pytest.fixture
  669. def assert_no_log_errors(capture_logs):
  670. """Fixture that automatically asserts no errors were logged.
  671. Usage:
  672. def test_something(assert_no_log_errors):
  673. # If any ERROR logs occur during this test, it will fail
  674. some_function()
  675. """
  676. yield capture_logs
  677. errors = capture_logs.get_errors()
  678. if errors:
  679. pytest.fail(f"Unexpected log errors:\n{capture_logs.format_errors()}")