# -*- coding: utf-8 -*- """ Unit-Tests fuer das LED-Modul (trixy_core.led). Testet Layouts, Hardware-Treiber (No-Op-Modus), Animations-Framework, alle 16 Animationen, die AnimationEngine und den LEDService. """ import asyncio import itertools import math import random from unittest.mock import MagicMock, AsyncMock, patch, PropertyMock import pytest from trixy_core.led.layouts import ( LEDLayout, LAYOUT_SINGLE, LAYOUT_JEWEL_7, LAYOUT_RING_12, LAYOUT_RING_16, LAYOUT_RING_24, LAYOUTS, get_layout, ) from trixy_core.led.driver import WS2812Driver from trixy_core.led.animations import IAnimation, AnimationRegistry, RGB from trixy_core.led.animations.static import ( SolidAnimation, SingleBlinkAnimation, DoubleBlinkAnimation, TripleBlinkAnimation, FlashAnimation, FillSequentialAnimation, ) from trixy_core.led.animations.continuous import ( BlinkAnimation, BreatheAnimation, PulseAnimation, BREATHE_STEPS, PULSE_STEPS, ) from trixy_core.led.animations.circular import ( CirculateAnimation, CircularFadeAnimation, ChaseAnimation, RadarAnimation, ) from trixy_core.led.animations.effects import ( RainbowAnimation, WaveAnimation, SparkleAnimation, ) from trixy_core.led.engine import AnimationEngine from trixy_core.led.service import LEDService, _DEFAULT_STATES from trixy_core.service.enums import ServicePriority, ServiceGroup # ── Schwarz-Konstante fuer Vergleiche ──────────────────────────────────── OFF: RGB = (0, 0, 0) # ── Hilfsfunktionen ───────────────────────────────────────────────────── def _collect_frames(anim: IAnimation, led_count: int, color: RGB, layout: LEDLayout, max_frames: int = 200, **opts: object) -> list[list[RGB]]: """Sammelt bis zu max_frames aus einem Animations-Generator.""" gen = anim.frames(led_count, color, 50, layout, **opts) return list(itertools.islice(gen, max_frames)) # ═══════════════════════════════════════════════════════════════════════ # TestLayouts # ═══════════════════════════════════════════════════════════════════════ class TestLayouts: """Tests fuer LED-Layout-Definitionen und Auto-Erkennung.""" def test_layout_single_werte(self): """LAYOUT_SINGLE hat 1 LED, kein Center, Ring=[0].""" assert LAYOUT_SINGLE.name == "single" assert LAYOUT_SINGLE.led_count == 1 assert LAYOUT_SINGLE.center_index is None assert LAYOUT_SINGLE.ring_indices == [0] def test_layout_jewel_7_werte(self): """LAYOUT_JEWEL_7 hat 7 LEDs, Center=0, Ring=[1..6].""" assert LAYOUT_JEWEL_7.name == "jewel_7" assert LAYOUT_JEWEL_7.led_count == 7 assert LAYOUT_JEWEL_7.center_index == 0 assert LAYOUT_JEWEL_7.ring_indices == [1, 2, 3, 4, 5, 6] def test_layout_ring_12_werte(self): """LAYOUT_RING_12 hat 12 LEDs, kein Center, Ring=[0..11].""" assert LAYOUT_RING_12.name == "ring_12" assert LAYOUT_RING_12.led_count == 12 assert LAYOUT_RING_12.center_index is None assert LAYOUT_RING_12.ring_indices == list(range(12)) def test_layout_ring_16_werte(self): """LAYOUT_RING_16 hat 16 LEDs, kein Center.""" assert LAYOUT_RING_16.led_count == 16 assert LAYOUT_RING_16.ring_indices == list(range(16)) assert not LAYOUT_RING_16.has_center def test_layout_ring_24_werte(self): """LAYOUT_RING_24 hat 24 LEDs, kein Center.""" assert LAYOUT_RING_24.led_count == 24 assert LAYOUT_RING_24.ring_indices == list(range(24)) def test_has_center_property(self): """has_center gibt True zurueck wenn center_index gesetzt ist.""" assert LAYOUT_JEWEL_7.has_center is True assert LAYOUT_SINGLE.has_center is False assert LAYOUT_RING_12.has_center is False def test_ring_count_property(self): """ring_count gibt die Anzahl der Ring-LEDs zurueck.""" assert LAYOUT_SINGLE.ring_count == 1 assert LAYOUT_JEWEL_7.ring_count == 6 assert LAYOUT_RING_12.ring_count == 12 def test_get_layout_by_name(self): """get_layout findet Layout anhand des Namens.""" layout = get_layout("jewel_7", 7) assert layout.name == "jewel_7" assert layout.led_count == 7 def test_get_layout_by_name_ring_12(self): """get_layout findet ring_12 anhand des Namens.""" layout = get_layout("ring_12", 12) assert layout is LAYOUT_RING_12 def test_get_layout_auto_detect_by_count(self): """get_layout erkennt Layout automatisch anhand der LED-Anzahl.""" layout = get_layout("", 7) assert layout.name == "jewel_7" def test_get_layout_auto_detect_single(self): """get_layout erkennt Single-Layout bei 1 LED.""" layout = get_layout("", 1) assert layout.name == "single" def test_get_layout_unknown_name_fallback_auto(self): """Unbekannter Name loest Auto-Erkennung aus.""" layout = get_layout("nicht_vorhanden", 12) assert layout.name == "ring_12" def test_get_layout_unknown_count_generisches_layout(self): """Unbekannte LED-Anzahl erzeugt generisches Ring-Layout.""" layout = get_layout("", 5) assert layout.name == "ring_5" assert layout.led_count == 5 assert layout.center_index is None assert layout.ring_indices == list(range(5)) def test_get_layout_name_count_mismatch_warnung(self): """Layout mit falscher LED-Anzahl wird trotzdem zurueckgegeben.""" layout = get_layout("jewel_7", 12) assert layout.name == "jewel_7" assert layout.led_count == 7 def test_layouts_lookup_tabelle_vollstaendig(self): """Alle vordefinierten Layouts sind in der Lookup-Tabelle.""" assert "single" in LAYOUTS assert "jewel_7" in LAYOUTS assert "ring_12" in LAYOUTS assert "ring_16" in LAYOUTS assert "ring_24" in LAYOUTS assert len(LAYOUTS) == 5 # ═══════════════════════════════════════════════════════════════════════ # TestDriver # ═══════════════════════════════════════════════════════════════════════ class TestDriver: """Tests fuer den WS2812-Hardware-Treiber (No-Op-Modus).""" def test_init_ohne_rpi_ws281x_gibt_false(self): """init() gibt False zurueck wenn rpi_ws281x nicht installiert ist.""" driver = WS2812Driver(gpio_pin=18, led_count=7, brightness=80) result = driver.init() assert result is False def test_available_nach_fehlgeschlagenem_init(self): """available ist False nach fehlgeschlagenem init().""" driver = WS2812Driver() driver.init() assert driver.available is False def test_available_initial_false(self): """available ist initial False vor init()-Aufruf.""" driver = WS2812Driver() assert driver.available is False def test_led_count_property(self): """led_count gibt den konfigurierten Wert zurueck.""" driver = WS2812Driver(led_count=12) assert driver.led_count == 12 def test_led_count_standard_wert(self): """led_count Standard ist 1.""" driver = WS2812Driver() assert driver.led_count == 1 def test_set_pixels_noop_ohne_init(self): """set_pixels ist No-Op wenn Treiber nicht initialisiert ist.""" driver = WS2812Driver(led_count=3) # Soll keine Exception werfen driver.set_pixels([(255, 0, 0), (0, 255, 0), (0, 0, 255)]) def test_set_pixel_noop_ohne_init(self): """set_pixel ist No-Op ohne Initialisierung.""" driver = WS2812Driver(led_count=3) driver.set_pixel(0, 255, 0, 0) def test_show_noop_ohne_init(self): """show() ist No-Op wenn Treiber nicht initialisiert ist.""" driver = WS2812Driver() driver.show() def test_clear_noop_ohne_init(self): """clear() ist No-Op wenn Treiber nicht initialisiert ist.""" driver = WS2812Driver() driver.clear() def test_cleanup_noop_ohne_init(self): """cleanup() ist No-Op wenn Treiber nicht initialisiert ist.""" driver = WS2812Driver() driver.cleanup() def test_brightness_clamping_ueber_255(self): """Helligkeit wird auf 255 begrenzt.""" driver = WS2812Driver(brightness=300) assert driver._brightness == 255 def test_brightness_clamping_unter_0(self): """Helligkeit wird auf 0 begrenzt.""" driver = WS2812Driver(brightness=-10) assert driver._brightness == 0 def test_brightness_normaler_wert(self): """Normaler Helligkeitswert wird uebernommen.""" driver = WS2812Driver(brightness=128) assert driver._brightness == 128 def test_set_brightness_clamping(self): """set_brightness clampt den Wert auf 0-255.""" driver = WS2812Driver() driver.set_brightness(999) assert driver._brightness == 255 driver.set_brightness(-50) assert driver._brightness == 0 def test_rgb_to_color_konvertierung(self): """_rgb_to_color erzeugt korrekte 24-Bit Integer.""" assert WS2812Driver._rgb_to_color(255, 0, 0) == 0xFF0000 assert WS2812Driver._rgb_to_color(0, 255, 0) == 0x00FF00 assert WS2812Driver._rgb_to_color(0, 0, 255) == 0x0000FF assert WS2812Driver._rgb_to_color(0, 0, 0) == 0x000000 assert WS2812Driver._rgb_to_color(255, 255, 255) == 0xFFFFFF def test_cleanup_setzt_available_false(self): """cleanup() setzt _available und _strip auf None/False.""" driver = WS2812Driver() # Manuell initialisieren um cleanup testen zu koennen driver._available = True mock_strip = MagicMock() driver._strip = mock_strip driver.cleanup() assert driver.available is False assert driver._strip is None mock_strip.show.assert_called_once() # ═══════════════════════════════════════════════════════════════════════ # TestAnimationRegistry # ═══════════════════════════════════════════════════════════════════════ class TestAnimationRegistry: """Tests fuer die Animations-Registry.""" def test_register_builtins_laedt_alle_animationen(self): """register_builtins registriert alle 16 eingebauten Animationen.""" registry = AnimationRegistry() registry.register_builtins() names = registry.list_names() assert len(names) == 16 def test_get_by_name_liefert_korrekte_klasse(self): """get() gibt die richtige Animations-Klasse zurueck.""" registry = AnimationRegistry() registry.register_builtins() assert registry.get("solid") is SolidAnimation assert registry.get("breathe") is BreatheAnimation assert registry.get("rainbow") is RainbowAnimation def test_get_unbekannter_name_gibt_none(self): """get() gibt None bei unbekanntem Namen zurueck.""" registry = AnimationRegistry() registry.register_builtins() assert registry.get("nicht_vorhanden") is None def test_list_names_sortiert(self): """list_names() gibt eine sortierte Liste zurueck.""" registry = AnimationRegistry() registry.register_builtins() names = registry.list_names() assert names == sorted(names) def test_alle_16_namen_vorhanden(self): """Alle 16 Animations-Namen sind registriert.""" registry = AnimationRegistry() registry.register_builtins() names = set(registry.list_names()) erwartete = { "solid", "single-blink", "double-blink", "triple-blink", "flash", "fill-sequential", "blink", "breathe", "pulse", "circulate", "circular-fade", "chase", "radar", "rainbow", "wave", "sparkle", } assert names == erwartete def test_register_einzelne_animation(self): """register() fuegt eine einzelne Animation hinzu.""" registry = AnimationRegistry() registry.register(SolidAnimation) assert registry.get("solid") is SolidAnimation def test_register_ohne_name_wird_ignoriert(self): """Animation ohne NAME wird nicht registriert.""" class OhneNameAnim(IAnimation): NAME = "" CONTINUOUS = False def frames(self, led_count, color, speed, layout, **opts): yield [] registry = AnimationRegistry() registry.register(OhneNameAnim) assert len(registry.list_names()) == 0 def test_register_ueberschreibt_bestehende(self): """Doppelte Registrierung ueberschreibt die vorherige Klasse.""" class SolidV2(IAnimation): NAME = "solid" CONTINUOUS = False def frames(self, led_count, color, speed, layout, **opts): yield [] registry = AnimationRegistry() registry.register(SolidAnimation) registry.register(SolidV2) assert registry.get("solid") is SolidV2 # ═══════════════════════════════════════════════════════════════════════ # TestStaticAnimations # ═══════════════════════════════════════════════════════════════════════ class TestStaticAnimations: """Tests fuer statische Animationen (CONTINUOUS=False).""" def test_solid_erzeugt_einen_frame(self): """SolidAnimation gibt genau 1 Frame zurueck.""" anim = SolidAnimation() frames = _collect_frames(anim, 7, (0, 255, 0), LAYOUT_JEWEL_7) assert len(frames) == 1 def test_solid_alle_leds_gleiche_farbe(self): """SolidAnimation setzt alle LEDs auf die gleiche Farbe.""" color = (255, 0, 0) anim = SolidAnimation() frames = _collect_frames(anim, 12, color, LAYOUT_RING_12) assert len(frames) == 1 assert all(pixel == color for pixel in frames[0]) def test_solid_jewel_center_color(self): """SolidAnimation mit center_color: Center-LED bekommt eigene Farbe.""" main = (0, 0, 255) center = (255, 255, 0) anim = SolidAnimation() frames = _collect_frames( anim, 7, main, LAYOUT_JEWEL_7, center_color=center ) assert len(frames) == 1 # Center-LED (Index 0) hat center_color assert frames[0][0] == center # Ring-LEDs haben Hauptfarbe for i in [1, 2, 3, 4, 5, 6]: assert frames[0][i] == main def test_solid_ohne_center_color_alle_gleich(self): """SolidAnimation ohne center_color: auch Center hat Hauptfarbe.""" color = (100, 200, 50) anim = SolidAnimation() frames = _collect_frames(anim, 7, color, LAYOUT_JEWEL_7) assert all(pixel == color for pixel in frames[0]) def test_single_blink_zwei_frames(self): """SingleBlinkAnimation gibt 2 Frames zurueck (an, aus).""" anim = SingleBlinkAnimation() frames = _collect_frames(anim, 7, (0, 255, 0), LAYOUT_JEWEL_7) assert len(frames) == 2 def test_single_blink_an_aus_muster(self): """SingleBlinkAnimation: erster Frame an, zweiter Frame aus.""" color = (255, 0, 0) anim = SingleBlinkAnimation() frames = _collect_frames(anim, 1, color, LAYOUT_SINGLE) # Erster Frame: alle LEDs an assert frames[0][0] == color # Zweiter Frame: alle LEDs aus assert frames[1][0] == OFF def test_double_blink_vier_frames(self): """DoubleBlinkAnimation gibt 4 Frames zurueck.""" anim = DoubleBlinkAnimation() frames = _collect_frames(anim, 7, (0, 0, 255), LAYOUT_JEWEL_7) assert len(frames) == 4 def test_double_blink_muster(self): """DoubleBlinkAnimation: an/aus/an/aus Reihenfolge.""" color = (0, 255, 0) anim = DoubleBlinkAnimation() frames = _collect_frames(anim, 1, color, LAYOUT_SINGLE) assert frames[0][0] == color # an assert frames[1][0] == OFF # aus assert frames[2][0] == color # an assert frames[3][0] == OFF # aus def test_triple_blink_sechs_frames(self): """TripleBlinkAnimation gibt 6 Frames zurueck.""" anim = TripleBlinkAnimation() frames = _collect_frames(anim, 12, (255, 0, 0), LAYOUT_RING_12) assert len(frames) == 6 def test_flash_zwei_frames(self): """FlashAnimation gibt 2 Frames zurueck (hell, aus).""" anim = FlashAnimation() frames = _collect_frames(anim, 7, (255, 255, 255), LAYOUT_JEWEL_7) assert len(frames) == 2 def test_flash_erster_frame_hell_zweiter_aus(self): """FlashAnimation: erster Frame mit Farbe, zweiter schwarz.""" color = (255, 200, 100) anim = FlashAnimation() frames = _collect_frames(anim, 1, color, LAYOUT_SINGLE) assert frames[0][0] == color assert frames[1][0] == OFF def test_fill_sequential_led_count_frames(self): """FillSequentialAnimation gibt led_count Frames zurueck.""" anim = FillSequentialAnimation() # Jewel: 6 Ring + 1 Center = 7 Frames frames = _collect_frames(anim, 7, (0, 255, 0), LAYOUT_JEWEL_7) assert len(frames) == 7 def test_fill_sequential_ring_12(self): """FillSequentialAnimation: Ring mit 12 LEDs gibt 12 Frames.""" anim = FillSequentialAnimation() frames = _collect_frames(anim, 12, (0, 0, 255), LAYOUT_RING_12) assert len(frames) == 12 def test_fill_sequential_progressiv(self): """FillSequentialAnimation: jeder Frame hat eine LED mehr an.""" color = (255, 0, 0) anim = FillSequentialAnimation() frames = _collect_frames(anim, 12, color, LAYOUT_RING_12) for i, frame in enumerate(frames): leuchtende = sum(1 for p in frame if p != OFF) assert leuchtende == i + 1 def test_fill_sequential_jewel_center_zuletzt(self): """FillSequentialAnimation Jewel: Center-LED wird zuletzt gefuellt.""" color = (0, 255, 0) anim = FillSequentialAnimation() frames = _collect_frames(anim, 7, color, LAYOUT_JEWEL_7) # Letzter Frame: alle LEDs an, inklusive Center assert all(p != OFF for p in frames[-1]) # Vorletzter Frame: Center (Index 0) noch aus assert frames[-2][0] == OFF def test_alle_statischen_continuous_false(self): """Alle statischen Animationen haben CONTINUOUS=False.""" klassen = [ SolidAnimation, SingleBlinkAnimation, DoubleBlinkAnimation, TripleBlinkAnimation, FlashAnimation, FillSequentialAnimation, ] for cls in klassen: assert cls.CONTINUOUS is False, f"{cls.__name__} hat CONTINUOUS != False" def test_alle_statischen_haben_name(self): """Alle statischen Animationen haben einen nicht-leeren NAME.""" klassen = [ SolidAnimation, SingleBlinkAnimation, DoubleBlinkAnimation, TripleBlinkAnimation, FlashAnimation, FillSequentialAnimation, ] for cls in klassen: assert cls.NAME, f"{cls.__name__} hat keinen NAME" def test_solid_frame_laenge_stimmt(self): """SolidAnimation Frame hat exakt led_count Pixel.""" anim = SolidAnimation() frames = _collect_frames(anim, 12, (255, 0, 0), LAYOUT_RING_12) assert len(frames[0]) == 12 # ═══════════════════════════════════════════════════════════════════════ # TestContinuousAnimations # ═══════════════════════════════════════════════════════════════════════ class TestContinuousAnimations: """Tests fuer kontinuierliche Animationen (CONTINUOUS=True).""" def test_breathe_continuous_true(self): """BreatheAnimation hat CONTINUOUS=True.""" assert BreatheAnimation.CONTINUOUS is True def test_breathe_erster_zyklus_60_frames(self): """BreatheAnimation: ein Zyklus hat 60 Frames.""" anim = BreatheAnimation() frames = _collect_frames(anim, 7, (0, 0, 255), LAYOUT_JEWEL_7, max_frames=BREATHE_STEPS) assert len(frames) == BREATHE_STEPS def test_breathe_helligkeit_variiert(self): """BreatheAnimation: Helligkeit aendert sich ueber den Zyklus.""" color = (255, 255, 255) anim = BreatheAnimation() frames = _collect_frames(anim, 12, color, LAYOUT_RING_12, max_frames=BREATHE_STEPS) # Sammle die Rot-Werte des ersten Pixels ueber den Zyklus rot_werte = [f[0][0] for f in frames] # Mindest- und Maximalwert muessen verschieden sein assert max(rot_werte) > min(rot_werte) # Am dunkelsten am Anfang (Sinus startet bei -pi/2 → Minimum) assert rot_werte[0] < max(rot_werte) def test_breathe_jewel_center_halbe_intensitaet(self): """BreatheAnimation Jewel: Center-LED hat halbe Intensitaet.""" color = (200, 200, 200) anim = BreatheAnimation() frames = _collect_frames(anim, 7, color, LAYOUT_JEWEL_7, max_frames=BREATHE_STEPS) # Bei maximaler Helligkeit (ca. Frame 15 = pi/2) # Ring-LEDs sollten heller als Center sein peak_frame = frames[BREATHE_STEPS // 4] # ~ Viertelpunkt, steigend center_brightness = sum(peak_frame[0]) # Center = Index 0 ring_brightness = sum(peak_frame[1]) # Erste Ring-LED # Center sollte dunkler sein (halbe Intensitaet) assert center_brightness <= ring_brightness def test_pulse_continuous_true(self): """PulseAnimation hat CONTINUOUS=True.""" assert PulseAnimation.CONTINUOUS is True def test_pulse_schneller_als_breathe(self): """PulseAnimation hat weniger Schritte pro Zyklus als BreatheAnimation.""" assert PULSE_STEPS < BREATHE_STEPS def test_pulse_dreieckswelle(self): """PulseAnimation: Helligkeit folgt linearer Dreieckswelle.""" color = (255, 0, 0) anim = PulseAnimation() frames = _collect_frames(anim, 1, color, LAYOUT_SINGLE, max_frames=PULSE_STEPS) rot_werte = [f[0][0] for f in frames] # Erster Frame: Helligkeit 0 (step=0, brightness=0/half=0) assert rot_werte[0] == 0 # Mitte: maximale Helligkeit mitte = PULSE_STEPS // 2 # Kurz vor der Mitte sollte hoch sein assert rot_werte[mitte - 1] > rot_werte[0] def test_blink_continuous_true(self): """BlinkAnimation hat CONTINUOUS=True.""" assert BlinkAnimation.CONTINUOUS is True def test_blink_wechsel_an_aus(self): """BlinkAnimation: wechselt zwischen an und aus.""" color = (0, 255, 0) anim = BlinkAnimation() frames = _collect_frames(anim, 1, color, LAYOUT_SINGLE, max_frames=4) assert frames[0][0] == color # an assert frames[1][0] == OFF # aus assert frames[2][0] == color # an assert frames[3][0] == OFF # aus def test_blink_jewel_center_color_bleibt(self): """BlinkAnimation Jewel: Center-LED behalt center_color auch im Aus-Frame.""" main = (0, 255, 0) center = (255, 0, 0) anim = BlinkAnimation() frames = _collect_frames(anim, 7, main, LAYOUT_JEWEL_7, max_frames=4, center_color=center) # An-Frame: Center hat center_color assert frames[0][0] == center # Aus-Frame: Center hat ebenfalls center_color assert frames[1][0] == center # Aus-Frame: Ring-LEDs sind aus assert frames[1][1] == OFF def test_alle_continuous_richtige_frame_laenge(self): """Alle kontinuierlichen Animationen liefern korrekte LED-Anzahl pro Frame.""" animationen = [BlinkAnimation(), BreatheAnimation(), PulseAnimation()] for anim in animationen: frames = _collect_frames(anim, 7, (255, 0, 0), LAYOUT_JEWEL_7, max_frames=5) for frame in frames: assert len(frame) == 7, ( f"{anim.__class__.__name__}: Frame hat {len(frame)} statt 7 Pixel" ) def test_breathe_frame_laenge_ring_12(self): """BreatheAnimation: Frame-Laenge stimmt mit Ring_12 ueberein.""" anim = BreatheAnimation() frames = _collect_frames(anim, 12, (100, 100, 100), LAYOUT_RING_12, max_frames=5) for frame in frames: assert len(frame) == 12 # ═══════════════════════════════════════════════════════════════════════ # TestCircularAnimations # ═══════════════════════════════════════════════════════════════════════ class TestCircularAnimations: """Tests fuer kreisfoermige Animationen.""" def test_circulate_eine_led_bewegt_sich(self): """CirculateAnimation: genau eine Ring-LED leuchtet pro Frame.""" color = (255, 0, 0) anim = CirculateAnimation() frames = _collect_frames(anim, 12, color, LAYOUT_RING_12, max_frames=12) for frame in frames: leuchtende = [i for i, p in enumerate(frame) if p != OFF] assert len(leuchtende) == 1 def test_circulate_besucht_alle_ring_leds(self): """CirculateAnimation: besucht alle Ring-LEDs in einem Zyklus.""" color = (255, 0, 0) anim = CirculateAnimation() frames = _collect_frames(anim, 12, color, LAYOUT_RING_12, max_frames=12) besuchte = set() for frame in frames: for i, p in enumerate(frame): if p != OFF: besuchte.add(i) assert besuchte == set(range(12)) def test_circulate_jewel_center_bleibt_konstant(self): """CirculateAnimation Jewel: Center-LED bleibt bei center_color.""" color = (0, 255, 0) center = (50, 50, 50) anim = CirculateAnimation() frames = _collect_frames(anim, 7, color, LAYOUT_JEWEL_7, max_frames=6, center_color=center) for frame in frames: assert frame[0] == center, "Center-LED sollte konstant bleiben" def test_circulate_single_led_fallback_blink(self): """CirculateAnimation Single-LED: faellt auf Blinken zurueck.""" color = (255, 0, 0) anim = CirculateAnimation() frames = _collect_frames(anim, 1, color, LAYOUT_SINGLE, max_frames=4) assert len(frames) >= 2 # Wechsel zwischen an und aus assert frames[0][0] == color assert frames[1][0] == OFF def test_circular_fade_kopf_und_schweif(self): """CircularFadeAnimation: Kopf-LED voll, Schweif dunkler.""" color = (255, 255, 255) anim = CircularFadeAnimation() frames = _collect_frames(anim, 12, color, LAYOUT_RING_12, max_frames=12) # Im ersten Frame: LED 0 ist Kopf mit voller Farbe assert frames[0][0] == color def test_circular_fade_schweif_helligkeit_nimmt_ab(self): """CircularFadeAnimation: Schweif-LEDs werden zum Ende hin dunkler.""" color = (255, 255, 255) anim = CircularFadeAnimation() # Zweiter Frame: Kopf bei Index 1, Schweif bei Index 0 frames = _collect_frames(anim, 12, color, LAYOUT_RING_12, max_frames=12) # Frame an Position 3: Kopf bei ring[3], Schweif bei ring[2], ring[1], ring[0] frame = frames[3] kopf = frame[3] # Volle Farbe schweif_1 = frame[2] # 60% Helligkeit schweif_2 = frame[1] # 30% Helligkeit schweif_3 = frame[0] # 10% Helligkeit assert kopf == color # Schweif wird dunkler assert sum(schweif_1) > sum(schweif_2) assert sum(schweif_2) > sum(schweif_3) def test_circular_fade_single_led_fallback(self): """CircularFadeAnimation Single-LED: faellt auf Blinken zurueck.""" anim = CircularFadeAnimation() frames = _collect_frames(anim, 1, (255, 0, 0), LAYOUT_SINGLE, max_frames=4) assert len(frames) >= 2 assert frames[0][0] == (255, 0, 0) assert frames[1][0] == OFF def test_chase_mehrere_leds_leuchten(self): """ChaseAnimation: mehrere LEDs leuchten gleichzeitig pro Frame.""" color = (0, 0, 255) anim = ChaseAnimation() frames = _collect_frames(anim, 12, color, LAYOUT_RING_12, max_frames=12) for frame in frames: leuchtende = sum(1 for p in frame if p != OFF) assert leuchtende >= 2, "Chase sollte mindestens 2 LEDs gleichzeitig zeigen" def test_chase_single_led_fallback(self): """ChaseAnimation Single-LED: faellt auf Blinken zurueck.""" anim = ChaseAnimation() frames = _collect_frames(anim, 1, (255, 0, 0), LAYOUT_SINGLE, max_frames=4) assert frames[0][0] == (255, 0, 0) assert frames[1][0] == OFF def test_radar_langer_schweif(self): """RadarAnimation: Schweif ueber halben Ring.""" color = (0, 255, 0) anim = RadarAnimation() # Bei Ring_12: Schweif = 6 LEDs (halber Ring) frames = _collect_frames(anim, 12, color, LAYOUT_RING_12, max_frames=12) # Nach genug Frames sollten viele LEDs leuchten frame = frames[6] # Kopf bei Index 6, Schweif ueber 0-5 leuchtende = sum(1 for p in frame if p != OFF) assert leuchtende >= 4, "Radar sollte langen Schweif haben" def test_radar_single_led_fallback(self): """RadarAnimation Single-LED: faellt auf Blinken zurueck.""" anim = RadarAnimation() frames = _collect_frames(anim, 1, (255, 0, 0), LAYOUT_SINGLE, max_frames=4) assert frames[0][0] == (255, 0, 0) assert frames[1][0] == OFF def test_alle_circular_continuous_true(self): """Alle kreisfoermigen Animationen haben CONTINUOUS=True.""" klassen = [ CirculateAnimation, CircularFadeAnimation, ChaseAnimation, RadarAnimation, ] for cls in klassen: assert cls.CONTINUOUS is True, f"{cls.__name__} hat CONTINUOUS != True" def test_circulate_frame_laenge(self): """CirculateAnimation: jeder Frame hat korrekte LED-Anzahl.""" anim = CirculateAnimation() frames = _collect_frames(anim, 12, (255, 0, 0), LAYOUT_RING_12, max_frames=12) for frame in frames: assert len(frame) == 12 # ═══════════════════════════════════════════════════════════════════════ # TestEffectAnimations # ═══════════════════════════════════════════════════════════════════════ class TestEffectAnimations: """Tests fuer Spezialeffekt-Animationen.""" def test_rainbow_alle_leds_verschiedene_farben(self): """RainbowAnimation: Ring-LEDs haben unterschiedliche Farben.""" anim = RainbowAnimation() frames = _collect_frames(anim, 12, (0, 0, 0), LAYOUT_RING_12, max_frames=1) frame = frames[0] # Alle 12 Farben sollten unterschiedlich sein einzigartige = set(frame) assert len(einzigartige) > 6, "Rainbow sollte viele verschiedene Farben haben" def test_rainbow_continuous_true(self): """RainbowAnimation hat CONTINUOUS=True.""" assert RainbowAnimation.CONTINUOUS is True def test_rainbow_jewel_center_weiss(self): """RainbowAnimation Jewel: Center-LED ist gedimmt weiss.""" anim = RainbowAnimation() frames = _collect_frames(anim, 7, (0, 0, 0), LAYOUT_JEWEL_7, max_frames=1) center = frames[0][0] assert center == (64, 64, 64), f"Center sollte gedimmt weiss sein, ist {center}" def test_wave_helligkeit_variiert(self): """WaveAnimation: Helligkeit variiert ueber die Ring-LEDs.""" color = (255, 255, 255) anim = WaveAnimation() frames = _collect_frames(anim, 12, color, LAYOUT_RING_12, max_frames=6) # Im ersten Frame: Position 0 ist am hellsten, danach abfallend frame = frames[0] helligkeiten = [sum(p) for p in frame] # Nicht alle gleich hell assert max(helligkeiten) > min(helligkeiten) def test_wave_continuous_true(self): """WaveAnimation hat CONTINUOUS=True.""" assert WaveAnimation.CONTINUOUS is True def test_sparkle_wenige_leds_hell(self): """SparkleAnimation: wenige LEDs sind hell, Rest dunkel.""" random.seed(42) # Reproduzierbare Ergebnisse color = (255, 255, 255) anim = SparkleAnimation() frames = _collect_frames(anim, 12, color, LAYOUT_RING_12, max_frames=10) for frame in frames: helle = sum(1 for p in frame if p == color) assert helle <= 2, f"Sparkle sollte max 2 helle LEDs haben, hat {helle}" def test_sparkle_continuous_true(self): """SparkleAnimation hat CONTINUOUS=True.""" assert SparkleAnimation.CONTINUOUS is True def test_sparkle_hintergrund_dimm(self): """SparkleAnimation: nicht-funkelnde LEDs haben leichtes Glimmen.""" random.seed(42) color = (200, 200, 200) anim = SparkleAnimation() frames = _collect_frames(anim, 12, color, LAYOUT_RING_12, max_frames=1) frame = frames[0] # Dunkle LEDs sollten nicht voellig schwarz sein (5% Glimmen) dunkle = [p for p in frame if p != color] for p in dunkle: assert p != OFF, "Dunkle LEDs sollten leicht glimmen" def test_alle_effekte_continuous_true(self): """Alle Effekt-Animationen haben CONTINUOUS=True.""" klassen = [RainbowAnimation, WaveAnimation, SparkleAnimation] for cls in klassen: assert cls.CONTINUOUS is True, f"{cls.__name__} hat CONTINUOUS != True" def test_alle_effekte_frame_laenge(self): """Alle Effekt-Animationen liefern korrekte Frame-Laenge.""" random.seed(42) animationen = [RainbowAnimation(), WaveAnimation(), SparkleAnimation()] for anim in animationen: frames = _collect_frames(anim, 12, (255, 0, 0), LAYOUT_RING_12, max_frames=3) for frame in frames: assert len(frame) == 12, ( f"{anim.__class__.__name__}: Frame hat {len(frame)} statt 12 Pixel" ) # ═══════════════════════════════════════════════════════════════════════ # TestEngine # ═══════════════════════════════════════════════════════════════════════ class TestEngine: """Tests fuer die AnimationEngine.""" def _make_mock_driver(self, led_count: int = 7) -> MagicMock: """Erstellt einen Mock-Treiber fuer Engine-Tests.""" driver = MagicMock(spec=WS2812Driver) driver.led_count = led_count driver.available = True return driver async def test_play_setzt_current_state(self): """play() setzt current_state auf den State-Namen.""" driver = self._make_mock_driver() engine = AnimationEngine(driver, LAYOUT_JEWEL_7) await engine.play("wakeword", { "color": {"r": 0, "g": 0, "b": 255}, "animation": "solid", }) # Kurz warten damit der Task starten kann await asyncio.sleep(0.05) assert engine.current_state == "wakeword" async def test_play_bricht_vorherige_animation_ab(self): """play() bricht laufende Animation ab bevor neue startet.""" driver = self._make_mock_driver() engine = AnimationEngine(driver, LAYOUT_JEWEL_7) await engine.play("listening", { "color": {"r": 255, "g": 0, "b": 0}, "animation": "breathe", }) await asyncio.sleep(0.05) # Zweiter play() soll die erste Animation abbrechen await engine.play("thinking", { "color": {"r": 255, "g": 165, "b": 0}, "animation": "pulse", }) await asyncio.sleep(0.05) assert engine.current_state == "thinking" async def test_stop_loescht_leds_und_state(self): """stop() setzt LEDs auf aus und leert current_state.""" driver = self._make_mock_driver() engine = AnimationEngine(driver, LAYOUT_JEWEL_7) await engine.play("standby", { "color": {"r": 0, "g": 60, "b": 0}, "animation": "solid", }) await asyncio.sleep(0.05) await engine.stop() assert engine.current_state == "" driver.clear.assert_called() async def test_available_animations_liste(self): """available_animations gibt sortierte Liste aller Animationen zurueck.""" driver = self._make_mock_driver() engine = AnimationEngine(driver, LAYOUT_JEWEL_7) names = engine.available_animations assert "solid" in names assert "breathe" in names assert "rainbow" in names assert names == sorted(names) async def test_parse_color_dict_zu_tupel(self): """_parse_color konvertiert Dict zu RGB-Tupel.""" driver = self._make_mock_driver() engine = AnimationEngine(driver, LAYOUT_JEWEL_7) result = engine._parse_color({"r": 255, "g": 128, "b": 0}) assert result == (255, 128, 0) async def test_parse_color_fehlende_werte(self): """_parse_color behandelt fehlende Werte als 0.""" driver = self._make_mock_driver() engine = AnimationEngine(driver, LAYOUT_JEWEL_7) result = engine._parse_color({"r": 100}) assert result == (100, 0, 0) async def test_parse_color_clamping(self): """_parse_color clampt Werte auf 0-255.""" driver = self._make_mock_driver() engine = AnimationEngine(driver, LAYOUT_JEWEL_7) result = engine._parse_color({"r": 300, "g": -10, "b": 128}) assert result == (255, 0, 128) async def test_parse_color_leeres_dict(self): """_parse_color mit leerem Dict gibt (0,0,0) zurueck.""" driver = self._make_mock_driver() engine = AnimationEngine(driver, LAYOUT_JEWEL_7) result = engine._parse_color({}) assert result == (0, 0, 0) async def test_continuous_animation_cancelbar(self): """Kontinuierliche Animation kann abgebrochen werden.""" driver = self._make_mock_driver() engine = AnimationEngine(driver, LAYOUT_JEWEL_7) await engine.play("listening", { "color": {"r": 255, "g": 0, "b": 0}, "animation": "breathe", "speed": 10, }) await asyncio.sleep(0.05) # Animation laeuft assert engine._current_task is not None assert not engine._current_task.done() await engine.stop() await asyncio.sleep(0.05) assert engine.current_state == "" async def test_oneshot_animation_ruft_on_complete_auf(self): """Einmalige Animation ruft on_complete-Callback auf.""" driver = self._make_mock_driver() engine = AnimationEngine(driver, LAYOUT_JEWEL_7) callback = MagicMock() await engine.play("wakeword", { "color": {"r": 0, "g": 0, "b": 255}, "animation": "solid", "speed": 10, }, on_complete=callback) # Warten bis die einmalige Animation fertig ist await asyncio.sleep(0.2) callback.assert_called_once() async def test_play_unbekannte_animation_kein_crash(self): """play() mit unbekannter Animation crasht nicht.""" driver = self._make_mock_driver() engine = AnimationEngine(driver, LAYOUT_JEWEL_7) # Soll keine Exception werfen await engine.play("test", { "color": {"r": 255, "g": 0, "b": 0}, "animation": "nicht_vorhanden", }) await asyncio.sleep(0.05) async def test_play_center_color_parsing(self): """play() parst center_color korrekt aus der Konfiguration.""" driver = self._make_mock_driver() engine = AnimationEngine(driver, LAYOUT_JEWEL_7) await engine.play("standby", { "color": {"r": 0, "g": 255, "b": 0}, "animation": "solid", "center_color": {"r": 255, "g": 255, "b": 255}, }) await asyncio.sleep(0.1) # Driver.set_pixels sollte aufgerufen worden sein driver.set_pixels.assert_called() async def test_engine_initial_state_leer(self): """AnimationEngine startet mit leerem current_state.""" driver = self._make_mock_driver() engine = AnimationEngine(driver, LAYOUT_JEWEL_7) assert engine.current_state == "" # ═══════════════════════════════════════════════════════════════════════ # TestLEDService # ═══════════════════════════════════════════════════════════════════════ class TestLEDService: """Tests fuer den LEDService (IService-Implementierung).""" def _make_mock_application(self) -> MagicMock: """Erstellt eine Mock-Application fuer Service-Tests.""" app = MagicMock() app.events = MagicMock() return app def test_service_name(self): """LEDService hat korrekten NAME.""" assert LEDService.NAME == "LEDService" def test_service_priority(self): """LEDService hat Prioritaet OPTIONAL.""" assert LEDService.PRIORITY == ServicePriority.OPTIONAL def test_service_group(self): """LEDService hat Gruppe UTILITY.""" assert LEDService.GROUP == ServiceGroup.UTILITY def test_service_dependencies(self): """LEDService haengt von EventManager ab.""" assert "EventManager" in LEDService.DEPENDENCIES async def test_start_ohne_hardware_deaktiviert(self): """start() deaktiviert Service wenn keine LED-Hardware vorhanden.""" app = self._make_mock_application() config = {"gpio_pin": 18, "led_count": 7, "brightness": 80, "type": "jewel_7"} service = LEDService(app, config) await service.start() # Ohne rpi_ws281x: _driver wird auf None gesetzt assert service._driver is None assert service._engine is None assert service.available is False async def test_available_false_ohne_hardware(self): """available ist False wenn keine Hardware vorhanden.""" app = self._make_mock_application() service = LEDService(app, {}) assert service.available is False async def test_current_state_initial_leer(self): """current_state ist initial leer.""" app = self._make_mock_application() service = LEDService(app, {}) assert service.current_state == "" async def test_set_state_ohne_engine_kein_fehler(self): """_set_state ohne Engine wirft keine Exception.""" app = self._make_mock_application() service = LEDService(app, {}) # Soll keine Exception werfen await service._set_state("standby") async def test_set_state_setzt_current_state(self): """_set_state aktualisiert current_state wenn Engine vorhanden.""" app = self._make_mock_application() config = {"gpio_pin": 18, "led_count": 7, "brightness": 80, "type": "jewel_7"} service = LEDService(app, config) # Engine manuell mocken service._engine = MagicMock(spec=AnimationEngine) service._engine.play = AsyncMock() service._states = dict(_DEFAULT_STATES) await service._set_state("listening") assert service.current_state == "listening" service._engine.play.assert_called_once() async def test_set_state_unbekannter_zustand(self): """_set_state mit unbekanntem Zustand aendert nichts.""" app = self._make_mock_application() service = LEDService(app, {}) service._engine = MagicMock(spec=AnimationEngine) service._states = {} await service._set_state("unbekannt") # current_state bleibt leer, engine.play wird nicht aufgerufen assert service.current_state == "" async def test_stop_raeumt_auf(self): """stop() stoppt Engine und raeumt Treiber auf.""" app = self._make_mock_application() service = LEDService(app, {}) mock_engine = MagicMock(spec=AnimationEngine) mock_engine.stop = AsyncMock() mock_driver = MagicMock(spec=WS2812Driver) service._engine = mock_engine service._driver = mock_driver await service.stop() mock_engine.stop.assert_called_once() mock_driver.cleanup.assert_called_once() assert service._driver is None assert service._engine is None async def test_health_check_ohne_hardware(self): """health_check gibt False ohne Hardware zurueck.""" app = self._make_mock_application() service = LEDService(app, {}) result = await service.health_check() assert result is False async def test_turn_off_setzt_state_off(self): """turn_off schaltet LEDs aus und setzt State auf 'off'.""" app = self._make_mock_application() service = LEDService(app, {}) mock_engine = MagicMock(spec=AnimationEngine) mock_engine.stop = AsyncMock() service._engine = mock_engine await service.turn_off() mock_engine.stop.assert_called_once() assert service.current_state == "off" async def test_set_color_api(self): """set_color spielt solid-Animation mit angegebener Farbe.""" app = self._make_mock_application() service = LEDService(app, {}) mock_engine = MagicMock(spec=AnimationEngine) mock_engine.play = AsyncMock() service._engine = mock_engine await service.set_color(255, 0, 128) mock_engine.play.assert_called_once() call_args = mock_engine.play.call_args assert call_args[0][0] == "custom" assert call_args[0][1]["color"] == {"r": 255, "g": 0, "b": 128} assert call_args[0][1]["animation"] == "solid" async def test_set_animation_api(self): """set_animation spielt beliebige Animation ab.""" app = self._make_mock_application() service = LEDService(app, {}) mock_engine = MagicMock(spec=AnimationEngine) mock_engine.play = AsyncMock() service._engine = mock_engine await service.set_animation("breathe", {"r": 0, "g": 100, "b": 255}, speed=60) mock_engine.play.assert_called_once() call_args = mock_engine.play.call_args assert call_args[0][1]["animation"] == "breathe" assert call_args[0][1]["speed"] == 60 async def test_default_states_vollstaendig(self): """Alle erwarteten Default-Zustaende sind definiert.""" erwartete = {"boot", "standby", "wakeword", "listening", "thinking", "speaking", "error", "disconnect"} assert set(_DEFAULT_STATES.keys()) == erwartete async def test_start_laedt_config_states(self): """start() merged Config-States mit Defaults.""" app = self._make_mock_application() custom_states = { "standby": {"color": {"r": 100, "g": 0, "b": 0}}, } config = { "gpio_pin": 18, "led_count": 7, "brightness": 80, "type": "jewel_7", "states": custom_states, } service = LEDService(app, config) await service.start() # Standby sollte gemergten Zustand haben (custom color + default animation) if "standby" in service._states: assert service._states["standby"]["color"] == {"r": 100, "g": 0, "b": 0} # Default-Animation bleibt erhalten assert "animation" in service._states["standby"] def test_event_handler_vorhanden(self): """LEDService hat alle erwarteten Event-Handler-Methoden.""" assert hasattr(LEDService, "_on_ready") assert hasattr(LEDService, "_on_wakeword") assert hasattr(LEDService, "_on_recording_started") assert hasattr(LEDService, "_on_recording_stopped") assert hasattr(LEDService, "_on_tts_started") assert hasattr(LEDService, "_on_done") assert hasattr(LEDService, "_on_connected") assert hasattr(LEDService, "_on_disconnected")