conftest.py 37 KB

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