test_led.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212
  1. # -*- coding: utf-8 -*-
  2. """
  3. Unit-Tests fuer das LED-Modul (trixy_core.led).
  4. Testet Layouts, Hardware-Treiber (No-Op-Modus), Animations-Framework,
  5. alle 16 Animationen, die AnimationEngine und den LEDService.
  6. """
  7. import asyncio
  8. import itertools
  9. import math
  10. import random
  11. from unittest.mock import MagicMock, AsyncMock, patch, PropertyMock
  12. import pytest
  13. from trixy_core.led.layouts import (
  14. LEDLayout,
  15. LAYOUT_SINGLE,
  16. LAYOUT_JEWEL_7,
  17. LAYOUT_RING_12,
  18. LAYOUT_RING_16,
  19. LAYOUT_RING_24,
  20. LAYOUTS,
  21. get_layout,
  22. )
  23. from trixy_core.led.driver import WS2812Driver
  24. from trixy_core.led.animations import IAnimation, AnimationRegistry, RGB
  25. from trixy_core.led.animations.static import (
  26. SolidAnimation,
  27. SingleBlinkAnimation,
  28. DoubleBlinkAnimation,
  29. TripleBlinkAnimation,
  30. FlashAnimation,
  31. FillSequentialAnimation,
  32. )
  33. from trixy_core.led.animations.continuous import (
  34. BlinkAnimation,
  35. BreatheAnimation,
  36. PulseAnimation,
  37. BREATHE_STEPS,
  38. PULSE_STEPS,
  39. )
  40. from trixy_core.led.animations.circular import (
  41. CirculateAnimation,
  42. CircularFadeAnimation,
  43. ChaseAnimation,
  44. RadarAnimation,
  45. )
  46. from trixy_core.led.animations.effects import (
  47. RainbowAnimation,
  48. WaveAnimation,
  49. SparkleAnimation,
  50. )
  51. from trixy_core.led.engine import AnimationEngine
  52. from trixy_core.led.service import LEDService, _DEFAULT_STATES
  53. from trixy_core.service.enums import ServicePriority, ServiceGroup
  54. # ── Schwarz-Konstante fuer Vergleiche ────────────────────────────────────
  55. OFF: RGB = (0, 0, 0)
  56. # ── Hilfsfunktionen ─────────────────────────────────────────────────────
  57. def _collect_frames(anim: IAnimation, led_count: int, color: RGB,
  58. layout: LEDLayout, max_frames: int = 200,
  59. **opts: object) -> list[list[RGB]]:
  60. """Sammelt bis zu max_frames aus einem Animations-Generator."""
  61. gen = anim.frames(led_count, color, 50, layout, **opts)
  62. return list(itertools.islice(gen, max_frames))
  63. # ═══════════════════════════════════════════════════════════════════════
  64. # TestLayouts
  65. # ═══════════════════════════════════════════════════════════════════════
  66. class TestLayouts:
  67. """Tests fuer LED-Layout-Definitionen und Auto-Erkennung."""
  68. def test_layout_single_werte(self):
  69. """LAYOUT_SINGLE hat 1 LED, kein Center, Ring=[0]."""
  70. assert LAYOUT_SINGLE.name == "single"
  71. assert LAYOUT_SINGLE.led_count == 1
  72. assert LAYOUT_SINGLE.center_index is None
  73. assert LAYOUT_SINGLE.ring_indices == [0]
  74. def test_layout_jewel_7_werte(self):
  75. """LAYOUT_JEWEL_7 hat 7 LEDs, Center=0, Ring=[1..6]."""
  76. assert LAYOUT_JEWEL_7.name == "jewel_7"
  77. assert LAYOUT_JEWEL_7.led_count == 7
  78. assert LAYOUT_JEWEL_7.center_index == 0
  79. assert LAYOUT_JEWEL_7.ring_indices == [1, 2, 3, 4, 5, 6]
  80. def test_layout_ring_12_werte(self):
  81. """LAYOUT_RING_12 hat 12 LEDs, kein Center, Ring=[0..11]."""
  82. assert LAYOUT_RING_12.name == "ring_12"
  83. assert LAYOUT_RING_12.led_count == 12
  84. assert LAYOUT_RING_12.center_index is None
  85. assert LAYOUT_RING_12.ring_indices == list(range(12))
  86. def test_layout_ring_16_werte(self):
  87. """LAYOUT_RING_16 hat 16 LEDs, kein Center."""
  88. assert LAYOUT_RING_16.led_count == 16
  89. assert LAYOUT_RING_16.ring_indices == list(range(16))
  90. assert not LAYOUT_RING_16.has_center
  91. def test_layout_ring_24_werte(self):
  92. """LAYOUT_RING_24 hat 24 LEDs, kein Center."""
  93. assert LAYOUT_RING_24.led_count == 24
  94. assert LAYOUT_RING_24.ring_indices == list(range(24))
  95. def test_has_center_property(self):
  96. """has_center gibt True zurueck wenn center_index gesetzt ist."""
  97. assert LAYOUT_JEWEL_7.has_center is True
  98. assert LAYOUT_SINGLE.has_center is False
  99. assert LAYOUT_RING_12.has_center is False
  100. def test_ring_count_property(self):
  101. """ring_count gibt die Anzahl der Ring-LEDs zurueck."""
  102. assert LAYOUT_SINGLE.ring_count == 1
  103. assert LAYOUT_JEWEL_7.ring_count == 6
  104. assert LAYOUT_RING_12.ring_count == 12
  105. def test_get_layout_by_name(self):
  106. """get_layout findet Layout anhand des Namens."""
  107. layout = get_layout("jewel_7", 7)
  108. assert layout.name == "jewel_7"
  109. assert layout.led_count == 7
  110. def test_get_layout_by_name_ring_12(self):
  111. """get_layout findet ring_12 anhand des Namens."""
  112. layout = get_layout("ring_12", 12)
  113. assert layout is LAYOUT_RING_12
  114. def test_get_layout_auto_detect_by_count(self):
  115. """get_layout erkennt Layout automatisch anhand der LED-Anzahl."""
  116. layout = get_layout("", 7)
  117. assert layout.name == "jewel_7"
  118. def test_get_layout_auto_detect_single(self):
  119. """get_layout erkennt Single-Layout bei 1 LED."""
  120. layout = get_layout("", 1)
  121. assert layout.name == "single"
  122. def test_get_layout_unknown_name_fallback_auto(self):
  123. """Unbekannter Name loest Auto-Erkennung aus."""
  124. layout = get_layout("nicht_vorhanden", 12)
  125. assert layout.name == "ring_12"
  126. def test_get_layout_unknown_count_generisches_layout(self):
  127. """Unbekannte LED-Anzahl erzeugt generisches Ring-Layout."""
  128. layout = get_layout("", 5)
  129. assert layout.name == "ring_5"
  130. assert layout.led_count == 5
  131. assert layout.center_index is None
  132. assert layout.ring_indices == list(range(5))
  133. def test_get_layout_name_count_mismatch_warnung(self):
  134. """Layout mit falscher LED-Anzahl wird trotzdem zurueckgegeben."""
  135. layout = get_layout("jewel_7", 12)
  136. assert layout.name == "jewel_7"
  137. assert layout.led_count == 7
  138. def test_layouts_lookup_tabelle_vollstaendig(self):
  139. """Alle vordefinierten Layouts sind in der Lookup-Tabelle."""
  140. assert "single" in LAYOUTS
  141. assert "jewel_7" in LAYOUTS
  142. assert "ring_12" in LAYOUTS
  143. assert "ring_16" in LAYOUTS
  144. assert "ring_24" in LAYOUTS
  145. assert len(LAYOUTS) == 5
  146. # ═══════════════════════════════════════════════════════════════════════
  147. # TestDriver
  148. # ═══════════════════════════════════════════════════════════════════════
  149. class TestDriver:
  150. """Tests fuer den WS2812-Hardware-Treiber (No-Op-Modus)."""
  151. def test_init_ohne_rpi_ws281x_gibt_false(self):
  152. """init() gibt False zurueck wenn rpi_ws281x nicht installiert ist."""
  153. driver = WS2812Driver(gpio_pin=18, led_count=7, brightness=80)
  154. result = driver.init()
  155. assert result is False
  156. def test_available_nach_fehlgeschlagenem_init(self):
  157. """available ist False nach fehlgeschlagenem init()."""
  158. driver = WS2812Driver()
  159. driver.init()
  160. assert driver.available is False
  161. def test_available_initial_false(self):
  162. """available ist initial False vor init()-Aufruf."""
  163. driver = WS2812Driver()
  164. assert driver.available is False
  165. def test_led_count_property(self):
  166. """led_count gibt den konfigurierten Wert zurueck."""
  167. driver = WS2812Driver(led_count=12)
  168. assert driver.led_count == 12
  169. def test_led_count_standard_wert(self):
  170. """led_count Standard ist 1."""
  171. driver = WS2812Driver()
  172. assert driver.led_count == 1
  173. def test_set_pixels_noop_ohne_init(self):
  174. """set_pixels ist No-Op wenn Treiber nicht initialisiert ist."""
  175. driver = WS2812Driver(led_count=3)
  176. # Soll keine Exception werfen
  177. driver.set_pixels([(255, 0, 0), (0, 255, 0), (0, 0, 255)])
  178. def test_set_pixel_noop_ohne_init(self):
  179. """set_pixel ist No-Op ohne Initialisierung."""
  180. driver = WS2812Driver(led_count=3)
  181. driver.set_pixel(0, 255, 0, 0)
  182. def test_show_noop_ohne_init(self):
  183. """show() ist No-Op wenn Treiber nicht initialisiert ist."""
  184. driver = WS2812Driver()
  185. driver.show()
  186. def test_clear_noop_ohne_init(self):
  187. """clear() ist No-Op wenn Treiber nicht initialisiert ist."""
  188. driver = WS2812Driver()
  189. driver.clear()
  190. def test_cleanup_noop_ohne_init(self):
  191. """cleanup() ist No-Op wenn Treiber nicht initialisiert ist."""
  192. driver = WS2812Driver()
  193. driver.cleanup()
  194. def test_brightness_clamping_ueber_255(self):
  195. """Helligkeit wird auf 255 begrenzt."""
  196. driver = WS2812Driver(brightness=300)
  197. assert driver._brightness == 255
  198. def test_brightness_clamping_unter_0(self):
  199. """Helligkeit wird auf 0 begrenzt."""
  200. driver = WS2812Driver(brightness=-10)
  201. assert driver._brightness == 0
  202. def test_brightness_normaler_wert(self):
  203. """Normaler Helligkeitswert wird uebernommen."""
  204. driver = WS2812Driver(brightness=128)
  205. assert driver._brightness == 128
  206. def test_set_brightness_clamping(self):
  207. """set_brightness clampt den Wert auf 0-255."""
  208. driver = WS2812Driver()
  209. driver.set_brightness(999)
  210. assert driver._brightness == 255
  211. driver.set_brightness(-50)
  212. assert driver._brightness == 0
  213. def test_rgb_to_color_konvertierung(self):
  214. """_rgb_to_color erzeugt korrekte 24-Bit Integer."""
  215. assert WS2812Driver._rgb_to_color(255, 0, 0) == 0xFF0000
  216. assert WS2812Driver._rgb_to_color(0, 255, 0) == 0x00FF00
  217. assert WS2812Driver._rgb_to_color(0, 0, 255) == 0x0000FF
  218. assert WS2812Driver._rgb_to_color(0, 0, 0) == 0x000000
  219. assert WS2812Driver._rgb_to_color(255, 255, 255) == 0xFFFFFF
  220. def test_cleanup_setzt_available_false(self):
  221. """cleanup() setzt _available und _strip auf None/False."""
  222. driver = WS2812Driver()
  223. # Manuell initialisieren um cleanup testen zu koennen
  224. driver._available = True
  225. mock_strip = MagicMock()
  226. driver._strip = mock_strip
  227. driver.cleanup()
  228. assert driver.available is False
  229. assert driver._strip is None
  230. mock_strip.show.assert_called_once()
  231. # ═══════════════════════════════════════════════════════════════════════
  232. # TestAnimationRegistry
  233. # ═══════════════════════════════════════════════════════════════════════
  234. class TestAnimationRegistry:
  235. """Tests fuer die Animations-Registry."""
  236. def test_register_builtins_laedt_alle_animationen(self):
  237. """register_builtins registriert alle 16 eingebauten Animationen."""
  238. registry = AnimationRegistry()
  239. registry.register_builtins()
  240. names = registry.list_names()
  241. assert len(names) == 16
  242. def test_get_by_name_liefert_korrekte_klasse(self):
  243. """get() gibt die richtige Animations-Klasse zurueck."""
  244. registry = AnimationRegistry()
  245. registry.register_builtins()
  246. assert registry.get("solid") is SolidAnimation
  247. assert registry.get("breathe") is BreatheAnimation
  248. assert registry.get("rainbow") is RainbowAnimation
  249. def test_get_unbekannter_name_gibt_none(self):
  250. """get() gibt None bei unbekanntem Namen zurueck."""
  251. registry = AnimationRegistry()
  252. registry.register_builtins()
  253. assert registry.get("nicht_vorhanden") is None
  254. def test_list_names_sortiert(self):
  255. """list_names() gibt eine sortierte Liste zurueck."""
  256. registry = AnimationRegistry()
  257. registry.register_builtins()
  258. names = registry.list_names()
  259. assert names == sorted(names)
  260. def test_alle_16_namen_vorhanden(self):
  261. """Alle 16 Animations-Namen sind registriert."""
  262. registry = AnimationRegistry()
  263. registry.register_builtins()
  264. names = set(registry.list_names())
  265. erwartete = {
  266. "solid", "single-blink", "double-blink", "triple-blink",
  267. "flash", "fill-sequential",
  268. "blink", "breathe", "pulse",
  269. "circulate", "circular-fade", "chase", "radar",
  270. "rainbow", "wave", "sparkle",
  271. }
  272. assert names == erwartete
  273. def test_register_einzelne_animation(self):
  274. """register() fuegt eine einzelne Animation hinzu."""
  275. registry = AnimationRegistry()
  276. registry.register(SolidAnimation)
  277. assert registry.get("solid") is SolidAnimation
  278. def test_register_ohne_name_wird_ignoriert(self):
  279. """Animation ohne NAME wird nicht registriert."""
  280. class OhneNameAnim(IAnimation):
  281. NAME = ""
  282. CONTINUOUS = False
  283. def frames(self, led_count, color, speed, layout, **opts):
  284. yield []
  285. registry = AnimationRegistry()
  286. registry.register(OhneNameAnim)
  287. assert len(registry.list_names()) == 0
  288. def test_register_ueberschreibt_bestehende(self):
  289. """Doppelte Registrierung ueberschreibt die vorherige Klasse."""
  290. class SolidV2(IAnimation):
  291. NAME = "solid"
  292. CONTINUOUS = False
  293. def frames(self, led_count, color, speed, layout, **opts):
  294. yield []
  295. registry = AnimationRegistry()
  296. registry.register(SolidAnimation)
  297. registry.register(SolidV2)
  298. assert registry.get("solid") is SolidV2
  299. # ═══════════════════════════════════════════════════════════════════════
  300. # TestStaticAnimations
  301. # ═══════════════════════════════════════════════════════════════════════
  302. class TestStaticAnimations:
  303. """Tests fuer statische Animationen (CONTINUOUS=False)."""
  304. def test_solid_erzeugt_einen_frame(self):
  305. """SolidAnimation gibt genau 1 Frame zurueck."""
  306. anim = SolidAnimation()
  307. frames = _collect_frames(anim, 7, (0, 255, 0), LAYOUT_JEWEL_7)
  308. assert len(frames) == 1
  309. def test_solid_alle_leds_gleiche_farbe(self):
  310. """SolidAnimation setzt alle LEDs auf die gleiche Farbe."""
  311. color = (255, 0, 0)
  312. anim = SolidAnimation()
  313. frames = _collect_frames(anim, 12, color, LAYOUT_RING_12)
  314. assert len(frames) == 1
  315. assert all(pixel == color for pixel in frames[0])
  316. def test_solid_jewel_center_color(self):
  317. """SolidAnimation mit center_color: Center-LED bekommt eigene Farbe."""
  318. main = (0, 0, 255)
  319. center = (255, 255, 0)
  320. anim = SolidAnimation()
  321. frames = _collect_frames(
  322. anim, 7, main, LAYOUT_JEWEL_7, center_color=center
  323. )
  324. assert len(frames) == 1
  325. # Center-LED (Index 0) hat center_color
  326. assert frames[0][0] == center
  327. # Ring-LEDs haben Hauptfarbe
  328. for i in [1, 2, 3, 4, 5, 6]:
  329. assert frames[0][i] == main
  330. def test_solid_ohne_center_color_alle_gleich(self):
  331. """SolidAnimation ohne center_color: auch Center hat Hauptfarbe."""
  332. color = (100, 200, 50)
  333. anim = SolidAnimation()
  334. frames = _collect_frames(anim, 7, color, LAYOUT_JEWEL_7)
  335. assert all(pixel == color for pixel in frames[0])
  336. def test_single_blink_zwei_frames(self):
  337. """SingleBlinkAnimation gibt 2 Frames zurueck (an, aus)."""
  338. anim = SingleBlinkAnimation()
  339. frames = _collect_frames(anim, 7, (0, 255, 0), LAYOUT_JEWEL_7)
  340. assert len(frames) == 2
  341. def test_single_blink_an_aus_muster(self):
  342. """SingleBlinkAnimation: erster Frame an, zweiter Frame aus."""
  343. color = (255, 0, 0)
  344. anim = SingleBlinkAnimation()
  345. frames = _collect_frames(anim, 1, color, LAYOUT_SINGLE)
  346. # Erster Frame: alle LEDs an
  347. assert frames[0][0] == color
  348. # Zweiter Frame: alle LEDs aus
  349. assert frames[1][0] == OFF
  350. def test_double_blink_vier_frames(self):
  351. """DoubleBlinkAnimation gibt 4 Frames zurueck."""
  352. anim = DoubleBlinkAnimation()
  353. frames = _collect_frames(anim, 7, (0, 0, 255), LAYOUT_JEWEL_7)
  354. assert len(frames) == 4
  355. def test_double_blink_muster(self):
  356. """DoubleBlinkAnimation: an/aus/an/aus Reihenfolge."""
  357. color = (0, 255, 0)
  358. anim = DoubleBlinkAnimation()
  359. frames = _collect_frames(anim, 1, color, LAYOUT_SINGLE)
  360. assert frames[0][0] == color # an
  361. assert frames[1][0] == OFF # aus
  362. assert frames[2][0] == color # an
  363. assert frames[3][0] == OFF # aus
  364. def test_triple_blink_sechs_frames(self):
  365. """TripleBlinkAnimation gibt 6 Frames zurueck."""
  366. anim = TripleBlinkAnimation()
  367. frames = _collect_frames(anim, 12, (255, 0, 0), LAYOUT_RING_12)
  368. assert len(frames) == 6
  369. def test_flash_zwei_frames(self):
  370. """FlashAnimation gibt 2 Frames zurueck (hell, aus)."""
  371. anim = FlashAnimation()
  372. frames = _collect_frames(anim, 7, (255, 255, 255), LAYOUT_JEWEL_7)
  373. assert len(frames) == 2
  374. def test_flash_erster_frame_hell_zweiter_aus(self):
  375. """FlashAnimation: erster Frame mit Farbe, zweiter schwarz."""
  376. color = (255, 200, 100)
  377. anim = FlashAnimation()
  378. frames = _collect_frames(anim, 1, color, LAYOUT_SINGLE)
  379. assert frames[0][0] == color
  380. assert frames[1][0] == OFF
  381. def test_fill_sequential_led_count_frames(self):
  382. """FillSequentialAnimation gibt led_count Frames zurueck."""
  383. anim = FillSequentialAnimation()
  384. # Jewel: 6 Ring + 1 Center = 7 Frames
  385. frames = _collect_frames(anim, 7, (0, 255, 0), LAYOUT_JEWEL_7)
  386. assert len(frames) == 7
  387. def test_fill_sequential_ring_12(self):
  388. """FillSequentialAnimation: Ring mit 12 LEDs gibt 12 Frames."""
  389. anim = FillSequentialAnimation()
  390. frames = _collect_frames(anim, 12, (0, 0, 255), LAYOUT_RING_12)
  391. assert len(frames) == 12
  392. def test_fill_sequential_progressiv(self):
  393. """FillSequentialAnimation: jeder Frame hat eine LED mehr an."""
  394. color = (255, 0, 0)
  395. anim = FillSequentialAnimation()
  396. frames = _collect_frames(anim, 12, color, LAYOUT_RING_12)
  397. for i, frame in enumerate(frames):
  398. leuchtende = sum(1 for p in frame if p != OFF)
  399. assert leuchtende == i + 1
  400. def test_fill_sequential_jewel_center_zuletzt(self):
  401. """FillSequentialAnimation Jewel: Center-LED wird zuletzt gefuellt."""
  402. color = (0, 255, 0)
  403. anim = FillSequentialAnimation()
  404. frames = _collect_frames(anim, 7, color, LAYOUT_JEWEL_7)
  405. # Letzter Frame: alle LEDs an, inklusive Center
  406. assert all(p != OFF for p in frames[-1])
  407. # Vorletzter Frame: Center (Index 0) noch aus
  408. assert frames[-2][0] == OFF
  409. def test_alle_statischen_continuous_false(self):
  410. """Alle statischen Animationen haben CONTINUOUS=False."""
  411. klassen = [
  412. SolidAnimation, SingleBlinkAnimation, DoubleBlinkAnimation,
  413. TripleBlinkAnimation, FlashAnimation, FillSequentialAnimation,
  414. ]
  415. for cls in klassen:
  416. assert cls.CONTINUOUS is False, f"{cls.__name__} hat CONTINUOUS != False"
  417. def test_alle_statischen_haben_name(self):
  418. """Alle statischen Animationen haben einen nicht-leeren NAME."""
  419. klassen = [
  420. SolidAnimation, SingleBlinkAnimation, DoubleBlinkAnimation,
  421. TripleBlinkAnimation, FlashAnimation, FillSequentialAnimation,
  422. ]
  423. for cls in klassen:
  424. assert cls.NAME, f"{cls.__name__} hat keinen NAME"
  425. def test_solid_frame_laenge_stimmt(self):
  426. """SolidAnimation Frame hat exakt led_count Pixel."""
  427. anim = SolidAnimation()
  428. frames = _collect_frames(anim, 12, (255, 0, 0), LAYOUT_RING_12)
  429. assert len(frames[0]) == 12
  430. # ═══════════════════════════════════════════════════════════════════════
  431. # TestContinuousAnimations
  432. # ═══════════════════════════════════════════════════════════════════════
  433. class TestContinuousAnimations:
  434. """Tests fuer kontinuierliche Animationen (CONTINUOUS=True)."""
  435. def test_breathe_continuous_true(self):
  436. """BreatheAnimation hat CONTINUOUS=True."""
  437. assert BreatheAnimation.CONTINUOUS is True
  438. def test_breathe_erster_zyklus_60_frames(self):
  439. """BreatheAnimation: ein Zyklus hat 60 Frames."""
  440. anim = BreatheAnimation()
  441. frames = _collect_frames(anim, 7, (0, 0, 255), LAYOUT_JEWEL_7,
  442. max_frames=BREATHE_STEPS)
  443. assert len(frames) == BREATHE_STEPS
  444. def test_breathe_helligkeit_variiert(self):
  445. """BreatheAnimation: Helligkeit aendert sich ueber den Zyklus."""
  446. color = (255, 255, 255)
  447. anim = BreatheAnimation()
  448. frames = _collect_frames(anim, 12, color, LAYOUT_RING_12,
  449. max_frames=BREATHE_STEPS)
  450. # Sammle die Rot-Werte des ersten Pixels ueber den Zyklus
  451. rot_werte = [f[0][0] for f in frames]
  452. # Mindest- und Maximalwert muessen verschieden sein
  453. assert max(rot_werte) > min(rot_werte)
  454. # Am dunkelsten am Anfang (Sinus startet bei -pi/2 → Minimum)
  455. assert rot_werte[0] < max(rot_werte)
  456. def test_breathe_jewel_center_halbe_intensitaet(self):
  457. """BreatheAnimation Jewel: Center-LED hat halbe Intensitaet."""
  458. color = (200, 200, 200)
  459. anim = BreatheAnimation()
  460. frames = _collect_frames(anim, 7, color, LAYOUT_JEWEL_7,
  461. max_frames=BREATHE_STEPS)
  462. # Bei maximaler Helligkeit (ca. Frame 15 = pi/2)
  463. # Ring-LEDs sollten heller als Center sein
  464. peak_frame = frames[BREATHE_STEPS // 4] # ~ Viertelpunkt, steigend
  465. center_brightness = sum(peak_frame[0]) # Center = Index 0
  466. ring_brightness = sum(peak_frame[1]) # Erste Ring-LED
  467. # Center sollte dunkler sein (halbe Intensitaet)
  468. assert center_brightness <= ring_brightness
  469. def test_pulse_continuous_true(self):
  470. """PulseAnimation hat CONTINUOUS=True."""
  471. assert PulseAnimation.CONTINUOUS is True
  472. def test_pulse_schneller_als_breathe(self):
  473. """PulseAnimation hat weniger Schritte pro Zyklus als BreatheAnimation."""
  474. assert PULSE_STEPS < BREATHE_STEPS
  475. def test_pulse_dreieckswelle(self):
  476. """PulseAnimation: Helligkeit folgt linearer Dreieckswelle."""
  477. color = (255, 0, 0)
  478. anim = PulseAnimation()
  479. frames = _collect_frames(anim, 1, color, LAYOUT_SINGLE,
  480. max_frames=PULSE_STEPS)
  481. rot_werte = [f[0][0] for f in frames]
  482. # Erster Frame: Helligkeit 0 (step=0, brightness=0/half=0)
  483. assert rot_werte[0] == 0
  484. # Mitte: maximale Helligkeit
  485. mitte = PULSE_STEPS // 2
  486. # Kurz vor der Mitte sollte hoch sein
  487. assert rot_werte[mitte - 1] > rot_werte[0]
  488. def test_blink_continuous_true(self):
  489. """BlinkAnimation hat CONTINUOUS=True."""
  490. assert BlinkAnimation.CONTINUOUS is True
  491. def test_blink_wechsel_an_aus(self):
  492. """BlinkAnimation: wechselt zwischen an und aus."""
  493. color = (0, 255, 0)
  494. anim = BlinkAnimation()
  495. frames = _collect_frames(anim, 1, color, LAYOUT_SINGLE, max_frames=4)
  496. assert frames[0][0] == color # an
  497. assert frames[1][0] == OFF # aus
  498. assert frames[2][0] == color # an
  499. assert frames[3][0] == OFF # aus
  500. def test_blink_jewel_center_color_bleibt(self):
  501. """BlinkAnimation Jewel: Center-LED behalt center_color auch im Aus-Frame."""
  502. main = (0, 255, 0)
  503. center = (255, 0, 0)
  504. anim = BlinkAnimation()
  505. frames = _collect_frames(anim, 7, main, LAYOUT_JEWEL_7,
  506. max_frames=4, center_color=center)
  507. # An-Frame: Center hat center_color
  508. assert frames[0][0] == center
  509. # Aus-Frame: Center hat ebenfalls center_color
  510. assert frames[1][0] == center
  511. # Aus-Frame: Ring-LEDs sind aus
  512. assert frames[1][1] == OFF
  513. def test_alle_continuous_richtige_frame_laenge(self):
  514. """Alle kontinuierlichen Animationen liefern korrekte LED-Anzahl pro Frame."""
  515. animationen = [BlinkAnimation(), BreatheAnimation(), PulseAnimation()]
  516. for anim in animationen:
  517. frames = _collect_frames(anim, 7, (255, 0, 0), LAYOUT_JEWEL_7,
  518. max_frames=5)
  519. for frame in frames:
  520. assert len(frame) == 7, (
  521. f"{anim.__class__.__name__}: Frame hat {len(frame)} statt 7 Pixel"
  522. )
  523. def test_breathe_frame_laenge_ring_12(self):
  524. """BreatheAnimation: Frame-Laenge stimmt mit Ring_12 ueberein."""
  525. anim = BreatheAnimation()
  526. frames = _collect_frames(anim, 12, (100, 100, 100), LAYOUT_RING_12,
  527. max_frames=5)
  528. for frame in frames:
  529. assert len(frame) == 12
  530. # ═══════════════════════════════════════════════════════════════════════
  531. # TestCircularAnimations
  532. # ═══════════════════════════════════════════════════════════════════════
  533. class TestCircularAnimations:
  534. """Tests fuer kreisfoermige Animationen."""
  535. def test_circulate_eine_led_bewegt_sich(self):
  536. """CirculateAnimation: genau eine Ring-LED leuchtet pro Frame."""
  537. color = (255, 0, 0)
  538. anim = CirculateAnimation()
  539. frames = _collect_frames(anim, 12, color, LAYOUT_RING_12, max_frames=12)
  540. for frame in frames:
  541. leuchtende = [i for i, p in enumerate(frame) if p != OFF]
  542. assert len(leuchtende) == 1
  543. def test_circulate_besucht_alle_ring_leds(self):
  544. """CirculateAnimation: besucht alle Ring-LEDs in einem Zyklus."""
  545. color = (255, 0, 0)
  546. anim = CirculateAnimation()
  547. frames = _collect_frames(anim, 12, color, LAYOUT_RING_12, max_frames=12)
  548. besuchte = set()
  549. for frame in frames:
  550. for i, p in enumerate(frame):
  551. if p != OFF:
  552. besuchte.add(i)
  553. assert besuchte == set(range(12))
  554. def test_circulate_jewel_center_bleibt_konstant(self):
  555. """CirculateAnimation Jewel: Center-LED bleibt bei center_color."""
  556. color = (0, 255, 0)
  557. center = (50, 50, 50)
  558. anim = CirculateAnimation()
  559. frames = _collect_frames(anim, 7, color, LAYOUT_JEWEL_7,
  560. max_frames=6, center_color=center)
  561. for frame in frames:
  562. assert frame[0] == center, "Center-LED sollte konstant bleiben"
  563. def test_circulate_single_led_fallback_blink(self):
  564. """CirculateAnimation Single-LED: faellt auf Blinken zurueck."""
  565. color = (255, 0, 0)
  566. anim = CirculateAnimation()
  567. frames = _collect_frames(anim, 1, color, LAYOUT_SINGLE, max_frames=4)
  568. assert len(frames) >= 2
  569. # Wechsel zwischen an und aus
  570. assert frames[0][0] == color
  571. assert frames[1][0] == OFF
  572. def test_circular_fade_kopf_und_schweif(self):
  573. """CircularFadeAnimation: Kopf-LED voll, Schweif dunkler."""
  574. color = (255, 255, 255)
  575. anim = CircularFadeAnimation()
  576. frames = _collect_frames(anim, 12, color, LAYOUT_RING_12, max_frames=12)
  577. # Im ersten Frame: LED 0 ist Kopf mit voller Farbe
  578. assert frames[0][0] == color
  579. def test_circular_fade_schweif_helligkeit_nimmt_ab(self):
  580. """CircularFadeAnimation: Schweif-LEDs werden zum Ende hin dunkler."""
  581. color = (255, 255, 255)
  582. anim = CircularFadeAnimation()
  583. # Zweiter Frame: Kopf bei Index 1, Schweif bei Index 0
  584. frames = _collect_frames(anim, 12, color, LAYOUT_RING_12, max_frames=12)
  585. # Frame an Position 3: Kopf bei ring[3], Schweif bei ring[2], ring[1], ring[0]
  586. frame = frames[3]
  587. kopf = frame[3] # Volle Farbe
  588. schweif_1 = frame[2] # 60% Helligkeit
  589. schweif_2 = frame[1] # 30% Helligkeit
  590. schweif_3 = frame[0] # 10% Helligkeit
  591. assert kopf == color
  592. # Schweif wird dunkler
  593. assert sum(schweif_1) > sum(schweif_2)
  594. assert sum(schweif_2) > sum(schweif_3)
  595. def test_circular_fade_single_led_fallback(self):
  596. """CircularFadeAnimation Single-LED: faellt auf Blinken zurueck."""
  597. anim = CircularFadeAnimation()
  598. frames = _collect_frames(anim, 1, (255, 0, 0), LAYOUT_SINGLE, max_frames=4)
  599. assert len(frames) >= 2
  600. assert frames[0][0] == (255, 0, 0)
  601. assert frames[1][0] == OFF
  602. def test_chase_mehrere_leds_leuchten(self):
  603. """ChaseAnimation: mehrere LEDs leuchten gleichzeitig pro Frame."""
  604. color = (0, 0, 255)
  605. anim = ChaseAnimation()
  606. frames = _collect_frames(anim, 12, color, LAYOUT_RING_12, max_frames=12)
  607. for frame in frames:
  608. leuchtende = sum(1 for p in frame if p != OFF)
  609. assert leuchtende >= 2, "Chase sollte mindestens 2 LEDs gleichzeitig zeigen"
  610. def test_chase_single_led_fallback(self):
  611. """ChaseAnimation Single-LED: faellt auf Blinken zurueck."""
  612. anim = ChaseAnimation()
  613. frames = _collect_frames(anim, 1, (255, 0, 0), LAYOUT_SINGLE, max_frames=4)
  614. assert frames[0][0] == (255, 0, 0)
  615. assert frames[1][0] == OFF
  616. def test_radar_langer_schweif(self):
  617. """RadarAnimation: Schweif ueber halben Ring."""
  618. color = (0, 255, 0)
  619. anim = RadarAnimation()
  620. # Bei Ring_12: Schweif = 6 LEDs (halber Ring)
  621. frames = _collect_frames(anim, 12, color, LAYOUT_RING_12, max_frames=12)
  622. # Nach genug Frames sollten viele LEDs leuchten
  623. frame = frames[6] # Kopf bei Index 6, Schweif ueber 0-5
  624. leuchtende = sum(1 for p in frame if p != OFF)
  625. assert leuchtende >= 4, "Radar sollte langen Schweif haben"
  626. def test_radar_single_led_fallback(self):
  627. """RadarAnimation Single-LED: faellt auf Blinken zurueck."""
  628. anim = RadarAnimation()
  629. frames = _collect_frames(anim, 1, (255, 0, 0), LAYOUT_SINGLE, max_frames=4)
  630. assert frames[0][0] == (255, 0, 0)
  631. assert frames[1][0] == OFF
  632. def test_alle_circular_continuous_true(self):
  633. """Alle kreisfoermigen Animationen haben CONTINUOUS=True."""
  634. klassen = [
  635. CirculateAnimation, CircularFadeAnimation,
  636. ChaseAnimation, RadarAnimation,
  637. ]
  638. for cls in klassen:
  639. assert cls.CONTINUOUS is True, f"{cls.__name__} hat CONTINUOUS != True"
  640. def test_circulate_frame_laenge(self):
  641. """CirculateAnimation: jeder Frame hat korrekte LED-Anzahl."""
  642. anim = CirculateAnimation()
  643. frames = _collect_frames(anim, 12, (255, 0, 0), LAYOUT_RING_12,
  644. max_frames=12)
  645. for frame in frames:
  646. assert len(frame) == 12
  647. # ═══════════════════════════════════════════════════════════════════════
  648. # TestEffectAnimations
  649. # ═══════════════════════════════════════════════════════════════════════
  650. class TestEffectAnimations:
  651. """Tests fuer Spezialeffekt-Animationen."""
  652. def test_rainbow_alle_leds_verschiedene_farben(self):
  653. """RainbowAnimation: Ring-LEDs haben unterschiedliche Farben."""
  654. anim = RainbowAnimation()
  655. frames = _collect_frames(anim, 12, (0, 0, 0), LAYOUT_RING_12, max_frames=1)
  656. frame = frames[0]
  657. # Alle 12 Farben sollten unterschiedlich sein
  658. einzigartige = set(frame)
  659. assert len(einzigartige) > 6, "Rainbow sollte viele verschiedene Farben haben"
  660. def test_rainbow_continuous_true(self):
  661. """RainbowAnimation hat CONTINUOUS=True."""
  662. assert RainbowAnimation.CONTINUOUS is True
  663. def test_rainbow_jewel_center_weiss(self):
  664. """RainbowAnimation Jewel: Center-LED ist gedimmt weiss."""
  665. anim = RainbowAnimation()
  666. frames = _collect_frames(anim, 7, (0, 0, 0), LAYOUT_JEWEL_7, max_frames=1)
  667. center = frames[0][0]
  668. assert center == (64, 64, 64), f"Center sollte gedimmt weiss sein, ist {center}"
  669. def test_wave_helligkeit_variiert(self):
  670. """WaveAnimation: Helligkeit variiert ueber die Ring-LEDs."""
  671. color = (255, 255, 255)
  672. anim = WaveAnimation()
  673. frames = _collect_frames(anim, 12, color, LAYOUT_RING_12, max_frames=6)
  674. # Im ersten Frame: Position 0 ist am hellsten, danach abfallend
  675. frame = frames[0]
  676. helligkeiten = [sum(p) for p in frame]
  677. # Nicht alle gleich hell
  678. assert max(helligkeiten) > min(helligkeiten)
  679. def test_wave_continuous_true(self):
  680. """WaveAnimation hat CONTINUOUS=True."""
  681. assert WaveAnimation.CONTINUOUS is True
  682. def test_sparkle_wenige_leds_hell(self):
  683. """SparkleAnimation: wenige LEDs sind hell, Rest dunkel."""
  684. random.seed(42) # Reproduzierbare Ergebnisse
  685. color = (255, 255, 255)
  686. anim = SparkleAnimation()
  687. frames = _collect_frames(anim, 12, color, LAYOUT_RING_12, max_frames=10)
  688. for frame in frames:
  689. helle = sum(1 for p in frame if p == color)
  690. assert helle <= 2, f"Sparkle sollte max 2 helle LEDs haben, hat {helle}"
  691. def test_sparkle_continuous_true(self):
  692. """SparkleAnimation hat CONTINUOUS=True."""
  693. assert SparkleAnimation.CONTINUOUS is True
  694. def test_sparkle_hintergrund_dimm(self):
  695. """SparkleAnimation: nicht-funkelnde LEDs haben leichtes Glimmen."""
  696. random.seed(42)
  697. color = (200, 200, 200)
  698. anim = SparkleAnimation()
  699. frames = _collect_frames(anim, 12, color, LAYOUT_RING_12, max_frames=1)
  700. frame = frames[0]
  701. # Dunkle LEDs sollten nicht voellig schwarz sein (5% Glimmen)
  702. dunkle = [p for p in frame if p != color]
  703. for p in dunkle:
  704. assert p != OFF, "Dunkle LEDs sollten leicht glimmen"
  705. def test_alle_effekte_continuous_true(self):
  706. """Alle Effekt-Animationen haben CONTINUOUS=True."""
  707. klassen = [RainbowAnimation, WaveAnimation, SparkleAnimation]
  708. for cls in klassen:
  709. assert cls.CONTINUOUS is True, f"{cls.__name__} hat CONTINUOUS != True"
  710. def test_alle_effekte_frame_laenge(self):
  711. """Alle Effekt-Animationen liefern korrekte Frame-Laenge."""
  712. random.seed(42)
  713. animationen = [RainbowAnimation(), WaveAnimation(), SparkleAnimation()]
  714. for anim in animationen:
  715. frames = _collect_frames(anim, 12, (255, 0, 0), LAYOUT_RING_12,
  716. max_frames=3)
  717. for frame in frames:
  718. assert len(frame) == 12, (
  719. f"{anim.__class__.__name__}: Frame hat {len(frame)} statt 12 Pixel"
  720. )
  721. # ═══════════════════════════════════════════════════════════════════════
  722. # TestEngine
  723. # ═══════════════════════════════════════════════════════════════════════
  724. class TestEngine:
  725. """Tests fuer die AnimationEngine."""
  726. def _make_mock_driver(self, led_count: int = 7) -> MagicMock:
  727. """Erstellt einen Mock-Treiber fuer Engine-Tests."""
  728. driver = MagicMock(spec=WS2812Driver)
  729. driver.led_count = led_count
  730. driver.available = True
  731. return driver
  732. async def test_play_setzt_current_state(self):
  733. """play() setzt current_state auf den State-Namen."""
  734. driver = self._make_mock_driver()
  735. engine = AnimationEngine(driver, LAYOUT_JEWEL_7)
  736. await engine.play("wakeword", {
  737. "color": {"r": 0, "g": 0, "b": 255},
  738. "animation": "solid",
  739. })
  740. # Kurz warten damit der Task starten kann
  741. await asyncio.sleep(0.05)
  742. assert engine.current_state == "wakeword"
  743. async def test_play_bricht_vorherige_animation_ab(self):
  744. """play() bricht laufende Animation ab bevor neue startet."""
  745. driver = self._make_mock_driver()
  746. engine = AnimationEngine(driver, LAYOUT_JEWEL_7)
  747. await engine.play("listening", {
  748. "color": {"r": 255, "g": 0, "b": 0},
  749. "animation": "breathe",
  750. })
  751. await asyncio.sleep(0.05)
  752. # Zweiter play() soll die erste Animation abbrechen
  753. await engine.play("thinking", {
  754. "color": {"r": 255, "g": 165, "b": 0},
  755. "animation": "pulse",
  756. })
  757. await asyncio.sleep(0.05)
  758. assert engine.current_state == "thinking"
  759. async def test_stop_loescht_leds_und_state(self):
  760. """stop() setzt LEDs auf aus und leert current_state."""
  761. driver = self._make_mock_driver()
  762. engine = AnimationEngine(driver, LAYOUT_JEWEL_7)
  763. await engine.play("standby", {
  764. "color": {"r": 0, "g": 60, "b": 0},
  765. "animation": "solid",
  766. })
  767. await asyncio.sleep(0.05)
  768. await engine.stop()
  769. assert engine.current_state == ""
  770. driver.clear.assert_called()
  771. async def test_available_animations_liste(self):
  772. """available_animations gibt sortierte Liste aller Animationen zurueck."""
  773. driver = self._make_mock_driver()
  774. engine = AnimationEngine(driver, LAYOUT_JEWEL_7)
  775. names = engine.available_animations
  776. assert "solid" in names
  777. assert "breathe" in names
  778. assert "rainbow" in names
  779. assert names == sorted(names)
  780. async def test_parse_color_dict_zu_tupel(self):
  781. """_parse_color konvertiert Dict zu RGB-Tupel."""
  782. driver = self._make_mock_driver()
  783. engine = AnimationEngine(driver, LAYOUT_JEWEL_7)
  784. result = engine._parse_color({"r": 255, "g": 128, "b": 0})
  785. assert result == (255, 128, 0)
  786. async def test_parse_color_fehlende_werte(self):
  787. """_parse_color behandelt fehlende Werte als 0."""
  788. driver = self._make_mock_driver()
  789. engine = AnimationEngine(driver, LAYOUT_JEWEL_7)
  790. result = engine._parse_color({"r": 100})
  791. assert result == (100, 0, 0)
  792. async def test_parse_color_clamping(self):
  793. """_parse_color clampt Werte auf 0-255."""
  794. driver = self._make_mock_driver()
  795. engine = AnimationEngine(driver, LAYOUT_JEWEL_7)
  796. result = engine._parse_color({"r": 300, "g": -10, "b": 128})
  797. assert result == (255, 0, 128)
  798. async def test_parse_color_leeres_dict(self):
  799. """_parse_color mit leerem Dict gibt (0,0,0) zurueck."""
  800. driver = self._make_mock_driver()
  801. engine = AnimationEngine(driver, LAYOUT_JEWEL_7)
  802. result = engine._parse_color({})
  803. assert result == (0, 0, 0)
  804. async def test_continuous_animation_cancelbar(self):
  805. """Kontinuierliche Animation kann abgebrochen werden."""
  806. driver = self._make_mock_driver()
  807. engine = AnimationEngine(driver, LAYOUT_JEWEL_7)
  808. await engine.play("listening", {
  809. "color": {"r": 255, "g": 0, "b": 0},
  810. "animation": "breathe",
  811. "speed": 10,
  812. })
  813. await asyncio.sleep(0.05)
  814. # Animation laeuft
  815. assert engine._current_task is not None
  816. assert not engine._current_task.done()
  817. await engine.stop()
  818. await asyncio.sleep(0.05)
  819. assert engine.current_state == ""
  820. async def test_oneshot_animation_ruft_on_complete_auf(self):
  821. """Einmalige Animation ruft on_complete-Callback auf."""
  822. driver = self._make_mock_driver()
  823. engine = AnimationEngine(driver, LAYOUT_JEWEL_7)
  824. callback = MagicMock()
  825. await engine.play("wakeword", {
  826. "color": {"r": 0, "g": 0, "b": 255},
  827. "animation": "solid",
  828. "speed": 10,
  829. }, on_complete=callback)
  830. # Warten bis die einmalige Animation fertig ist
  831. await asyncio.sleep(0.2)
  832. callback.assert_called_once()
  833. async def test_play_unbekannte_animation_kein_crash(self):
  834. """play() mit unbekannter Animation crasht nicht."""
  835. driver = self._make_mock_driver()
  836. engine = AnimationEngine(driver, LAYOUT_JEWEL_7)
  837. # Soll keine Exception werfen
  838. await engine.play("test", {
  839. "color": {"r": 255, "g": 0, "b": 0},
  840. "animation": "nicht_vorhanden",
  841. })
  842. await asyncio.sleep(0.05)
  843. async def test_play_center_color_parsing(self):
  844. """play() parst center_color korrekt aus der Konfiguration."""
  845. driver = self._make_mock_driver()
  846. engine = AnimationEngine(driver, LAYOUT_JEWEL_7)
  847. await engine.play("standby", {
  848. "color": {"r": 0, "g": 255, "b": 0},
  849. "animation": "solid",
  850. "center_color": {"r": 255, "g": 255, "b": 255},
  851. })
  852. await asyncio.sleep(0.1)
  853. # Driver.set_pixels sollte aufgerufen worden sein
  854. driver.set_pixels.assert_called()
  855. async def test_engine_initial_state_leer(self):
  856. """AnimationEngine startet mit leerem current_state."""
  857. driver = self._make_mock_driver()
  858. engine = AnimationEngine(driver, LAYOUT_JEWEL_7)
  859. assert engine.current_state == ""
  860. # ═══════════════════════════════════════════════════════════════════════
  861. # TestLEDService
  862. # ═══════════════════════════════════════════════════════════════════════
  863. class TestLEDService:
  864. """Tests fuer den LEDService (IService-Implementierung)."""
  865. def _make_mock_application(self) -> MagicMock:
  866. """Erstellt eine Mock-Application fuer Service-Tests."""
  867. app = MagicMock()
  868. app.events = MagicMock()
  869. return app
  870. def test_service_name(self):
  871. """LEDService hat korrekten NAME."""
  872. assert LEDService.NAME == "LEDService"
  873. def test_service_priority(self):
  874. """LEDService hat Prioritaet OPTIONAL."""
  875. assert LEDService.PRIORITY == ServicePriority.OPTIONAL
  876. def test_service_group(self):
  877. """LEDService hat Gruppe UTILITY."""
  878. assert LEDService.GROUP == ServiceGroup.UTILITY
  879. def test_service_dependencies(self):
  880. """LEDService haengt von EventManager ab."""
  881. assert "EventManager" in LEDService.DEPENDENCIES
  882. async def test_start_ohne_hardware_deaktiviert(self):
  883. """start() deaktiviert Service wenn keine LED-Hardware vorhanden."""
  884. app = self._make_mock_application()
  885. config = {"gpio_pin": 18, "led_count": 7, "brightness": 80, "type": "jewel_7"}
  886. service = LEDService(app, config)
  887. await service.start()
  888. # Ohne rpi_ws281x: _driver wird auf None gesetzt
  889. assert service._driver is None
  890. assert service._engine is None
  891. assert service.available is False
  892. async def test_available_false_ohne_hardware(self):
  893. """available ist False wenn keine Hardware vorhanden."""
  894. app = self._make_mock_application()
  895. service = LEDService(app, {})
  896. assert service.available is False
  897. async def test_current_state_initial_leer(self):
  898. """current_state ist initial leer."""
  899. app = self._make_mock_application()
  900. service = LEDService(app, {})
  901. assert service.current_state == ""
  902. async def test_set_state_ohne_engine_kein_fehler(self):
  903. """_set_state ohne Engine wirft keine Exception."""
  904. app = self._make_mock_application()
  905. service = LEDService(app, {})
  906. # Soll keine Exception werfen
  907. await service._set_state("standby")
  908. async def test_set_state_setzt_current_state(self):
  909. """_set_state aktualisiert current_state wenn Engine vorhanden."""
  910. app = self._make_mock_application()
  911. config = {"gpio_pin": 18, "led_count": 7, "brightness": 80, "type": "jewel_7"}
  912. service = LEDService(app, config)
  913. # Engine manuell mocken
  914. service._engine = MagicMock(spec=AnimationEngine)
  915. service._engine.play = AsyncMock()
  916. service._states = dict(_DEFAULT_STATES)
  917. await service._set_state("listening")
  918. assert service.current_state == "listening"
  919. service._engine.play.assert_called_once()
  920. async def test_set_state_unbekannter_zustand(self):
  921. """_set_state mit unbekanntem Zustand aendert nichts."""
  922. app = self._make_mock_application()
  923. service = LEDService(app, {})
  924. service._engine = MagicMock(spec=AnimationEngine)
  925. service._states = {}
  926. await service._set_state("unbekannt")
  927. # current_state bleibt leer, engine.play wird nicht aufgerufen
  928. assert service.current_state == ""
  929. async def test_stop_raeumt_auf(self):
  930. """stop() stoppt Engine und raeumt Treiber auf."""
  931. app = self._make_mock_application()
  932. service = LEDService(app, {})
  933. mock_engine = MagicMock(spec=AnimationEngine)
  934. mock_engine.stop = AsyncMock()
  935. mock_driver = MagicMock(spec=WS2812Driver)
  936. service._engine = mock_engine
  937. service._driver = mock_driver
  938. await service.stop()
  939. mock_engine.stop.assert_called_once()
  940. mock_driver.cleanup.assert_called_once()
  941. assert service._driver is None
  942. assert service._engine is None
  943. async def test_health_check_ohne_hardware(self):
  944. """health_check gibt False ohne Hardware zurueck."""
  945. app = self._make_mock_application()
  946. service = LEDService(app, {})
  947. result = await service.health_check()
  948. assert result is False
  949. async def test_turn_off_setzt_state_off(self):
  950. """turn_off schaltet LEDs aus und setzt State auf 'off'."""
  951. app = self._make_mock_application()
  952. service = LEDService(app, {})
  953. mock_engine = MagicMock(spec=AnimationEngine)
  954. mock_engine.stop = AsyncMock()
  955. service._engine = mock_engine
  956. await service.turn_off()
  957. mock_engine.stop.assert_called_once()
  958. assert service.current_state == "off"
  959. async def test_set_color_api(self):
  960. """set_color spielt solid-Animation mit angegebener Farbe."""
  961. app = self._make_mock_application()
  962. service = LEDService(app, {})
  963. mock_engine = MagicMock(spec=AnimationEngine)
  964. mock_engine.play = AsyncMock()
  965. service._engine = mock_engine
  966. await service.set_color(255, 0, 128)
  967. mock_engine.play.assert_called_once()
  968. call_args = mock_engine.play.call_args
  969. assert call_args[0][0] == "custom"
  970. assert call_args[0][1]["color"] == {"r": 255, "g": 0, "b": 128}
  971. assert call_args[0][1]["animation"] == "solid"
  972. async def test_set_animation_api(self):
  973. """set_animation spielt beliebige Animation ab."""
  974. app = self._make_mock_application()
  975. service = LEDService(app, {})
  976. mock_engine = MagicMock(spec=AnimationEngine)
  977. mock_engine.play = AsyncMock()
  978. service._engine = mock_engine
  979. await service.set_animation("breathe", {"r": 0, "g": 100, "b": 255}, speed=60)
  980. mock_engine.play.assert_called_once()
  981. call_args = mock_engine.play.call_args
  982. assert call_args[0][1]["animation"] == "breathe"
  983. assert call_args[0][1]["speed"] == 60
  984. async def test_default_states_vollstaendig(self):
  985. """Alle erwarteten Default-Zustaende sind definiert."""
  986. erwartete = {"boot", "standby", "wakeword", "listening",
  987. "thinking", "speaking", "error", "disconnect"}
  988. assert set(_DEFAULT_STATES.keys()) == erwartete
  989. async def test_start_laedt_config_states(self):
  990. """start() merged Config-States mit Defaults."""
  991. app = self._make_mock_application()
  992. custom_states = {
  993. "standby": {"color": {"r": 100, "g": 0, "b": 0}},
  994. }
  995. config = {
  996. "gpio_pin": 18, "led_count": 7,
  997. "brightness": 80, "type": "jewel_7",
  998. "states": custom_states,
  999. }
  1000. service = LEDService(app, config)
  1001. await service.start()
  1002. # Standby sollte gemergten Zustand haben (custom color + default animation)
  1003. if "standby" in service._states:
  1004. assert service._states["standby"]["color"] == {"r": 100, "g": 0, "b": 0}
  1005. # Default-Animation bleibt erhalten
  1006. assert "animation" in service._states["standby"]
  1007. def test_event_handler_vorhanden(self):
  1008. """LEDService hat alle erwarteten Event-Handler-Methoden."""
  1009. assert hasattr(LEDService, "_on_ready")
  1010. assert hasattr(LEDService, "_on_wakeword")
  1011. assert hasattr(LEDService, "_on_recording_started")
  1012. assert hasattr(LEDService, "_on_recording_stopped")
  1013. assert hasattr(LEDService, "_on_tts_started")
  1014. assert hasattr(LEDService, "_on_done")
  1015. assert hasattr(LEDService, "_on_connected")
  1016. assert hasattr(LEDService, "_on_disconnected")