conftest.py 31 KB

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