conftest.py 37 KB

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