conftest.py 31 KB

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