Lines 90.16% 110 / 122
Functions and Methods 75.67% 28 / 37
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
RecordingHaContext 90.16% 110 / 122 75.67% 28 / 37 54.57 0.00% 0 / 1
 __construct 100.00% 15 / 15 100.00% 1 / 1 1
 seedState 100.00% 5 / 5 100.00% 1 / 1 1
 seedHistoricalState 100.00% 2 / 2 100.00% 1 / 1 1
 stubHistoryFailure 100.00% 2 / 2 100.00% 1 / 1 1
 stubActionAnswer 100.00% 2 / 2 100.00% 1 / 1 1
 stubActionFailure 100.00% 2 / 2 100.00% 1 / 1 1
 stubEventFireFailure 100.00% 2 / 2 100.00% 1 / 1 1
 cancelSubscriptions 0.00% 0 / 2 0.00% 0 / 1 6
 pushStateChange 80.00% 4 / 5 0.00% 0 / 1 2.03
 pushState 100.00% 10 / 10 100.00% 1 / 1 2
 pushEvent 0.00% 0 / 1 0.00% 0 / 1 2
 pushTrigger 100.00% 1 / 1 100.00% 1 / 1 1
 listWatchedTriggers 100.00% 1 / 1 100.00% 1 / 1 1
 pushConnection 100.00% 2 / 2 100.00% 1 / 1 1
 getLastCall 0.00% 0 / 1 0.00% 0 / 1 2
 getState 100.00% 1 / 1 100.00% 1 / 1 1
 getEntity 100.00% 1 / 1 100.00% 1 / 1 1
 requireState 100.00% 2 / 2 100.00% 1 / 1 1
 getHeldStateDuration 100.00% 2 / 2 100.00% 1 / 1 2
 hasHeldStateFor 100.00% 2 / 2 100.00% 1 / 1 2
 getHistory 100.00% 8 / 8 100.00% 1 / 1 3
 listStates 66.66% 2 / 3 0.00% 0 / 1 4.59
 watchStateChanges 100.00% 6 / 6 100.00% 1 / 1 2
 waitForState 100.00% 1 / 1 100.00% 1 / 1 1
 getRegistry 100.00% 1 / 1 100.00% 1 / 1 1
 watchEvents 100.00% 3 / 3 100.00% 1 / 1 1
 watchTrigger 100.00% 5 / 5 100.00% 1 / 1 1
 callAction 100.00% 1 / 1 100.00% 1 / 1 1
 callActionForResponse 100.00% 1 / 1 100.00% 1 / 1 1
 fireEvent 100.00% 9 / 9 100.00% 1 / 1 3
 wasCausedByStewart 100.00% 1 / 1 100.00% 1 / 1 1
 publish 100.00% 3 / 3 100.00% 1 / 1 1
 watchTopic 0.00% 0 / 3 0.00% 0 / 1 2
 watchConnection 0.00% 0 / 1 0.00% 0 / 1 2
 isConnected 0.00% 0 / 1 0.00% 0 / 1 2
 callStubbedAction 92.30% 12 / 13 0.00% 0 / 1 3.00
 issueContext 100.00% 1 / 1 100.00% 1 / 1 1
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Testing\HaContext;
6
7use LogicException;
8use Stewart\Contracts\Action\ActionName;
9use Stewart\Contracts\Action\ActionResponse;
10use Stewart\Contracts\Action\ActionTargetSource;
11use Stewart\Contracts\App\AppId;
12use Stewart\Contracts\Connection\ConnectionEvent;
13use Stewart\Contracts\Connection\ConnectionLost;
14use Stewart\Contracts\Entity\Entity;
15use Stewart\Contracts\Entity\EntityId;
16use Stewart\Contracts\Event\EventOrigin;
17use Stewart\Contracts\Event\HaEvent;
18use Stewart\Contracts\EventStream;
19use Stewart\Contracts\Exception\ActionCallException;
20use Stewart\Contracts\Exception\EventFireException;
21use Stewart\Contracts\Exception\HistoryException;
22use Stewart\Contracts\Exception\StateException;
23use Stewart\Contracts\HaContext;
24use Stewart\Contracts\History\EntityStateHistory;
25use Stewart\Contracts\History\HistoryQuery;
26use Stewart\Contracts\Registry\EntityFilter;
27use Stewart\Contracts\Registry\Registry;
28use Stewart\Contracts\Selector\Collection\SelectorCollection;
29use Stewart\Contracts\Selector\Selector;
30use Stewart\Contracts\State\Collection\EntityStateCollection;
31use Stewart\Contracts\State\EntityState;
32use Stewart\Contracts\State\EventContext;
33use Stewart\Contracts\State\StateChange;
34use Stewart\Contracts\StateChangeStream;
35use Stewart\Contracts\Time\Duration;
36use Stewart\Contracts\Time\Instant;
37use Stewart\Contracts\Topic\Collection\TopicEventCollection;
38use Stewart\Contracts\Topic\TopicEvent;
39use Stewart\Contracts\Trigger\Collection\HaTriggerCollection;
40use Stewart\Contracts\Trigger\HaTrigger;
41use Stewart\Contracts\Trigger\TriggerEvent;
42use Stewart\Support\State\StewartIdentity;
43use Stewart\Support\Stream\OperatorStream;
44use Stewart\Support\Stream\StateChanges;
45use Stewart\Support\Wire\ActionFields;
46use Stewart\Support\Wire\EventPayload;
47use Stewart\Support\Wire\EventTypeSelector;
48use Stewart\Support\Wire\TopicPayload;
49use Stewart\Support\Wire\TriggerSpec;
50use Stewart\Testing\HaContext\Collection\RecordedActionCallCollection;
51use Stewart\Testing\HaContext\Collection\RecordedEventFireCollection;
52use Stewart\Testing\HaContext\Collection\RecordedHistoryQueryCollection;
53use Stewart\Testing\HaContext\Collection\WatchedTriggerCollection;
54use Stewart\Testing\Registry\InMemoryRegistry;
55use Stewart\Testing\Stream\PushSource;
56use Stewart\Testing\Time\ManualTimers;
57use Stewart\Testing\Time\VirtualClock;
58
59final class RecordingHaContext implements HaContext
60{
61    public const string STEWART_USER_ID = 'stewart-user';
62
63    private const string CONTEXT_ID_PREFIX = 'recorded-';
64
65    public private(set) RecordedActionCallCollection $calls;
66
67    public private(set) TopicEventCollection $published;
68
69    public private(set) RecordedEventFireCollection $firedEvents;
70
71    public private(set) RecordedHistoryQueryCollection $historyQueries;
72
73    private EntityStateCollection $states;
74
75    private readonly SeededHistory $history;
76
77    /** @var array<string, HistoryException> */
78    private array $historyFailures = [];
79
80    /** @var array<string, array<string, mixed>|ActionCallException> */
81    private array $actionOutcomes = [];
82
83    /** @var array<string, EventFireException> */
84    private array $eventFireFailures = [];
85
86    private int $issuedContextCount = 0;
87
88    /** @var PushSource<StateChange> */
89    private readonly PushSource $stateChanges;
90
91    /** @var PushSource<HaEvent> */
92    private readonly PushSource $events;
93
94    /** @var PushSource<TopicEvent> */
95    private readonly PushSource $topics;
96
97    /** @var PushSource<ConnectionEvent> */
98    private readonly PushSource $connectionEvents;
99
100    /** @var PushSource<PushedTrigger> */
101    private readonly PushSource $triggers;
102
103    private WatchedTriggerCollection $watchedTriggers;
104
105    private readonly StewartIdentity $identity;
106
107    public private(set) bool $connected = true;
108
109    public readonly VirtualClock $clock;
110
111    public readonly InMemoryRegistry $registry;
112
113    public function __construct(private readonly ManualTimers $timers = new ManualTimers())
114    {
115        $this->clock = $timers->clock;
116        $this->registry = new InMemoryRegistry();
117        $this->calls = RecordedActionCallCollection::empty();
118        $this->published = TopicEventCollection::empty();
119        $this->firedEvents = RecordedEventFireCollection::empty();
120        $this->states = EntityStateCollection::empty();
121        $this->historyQueries = RecordedHistoryQueryCollection::empty();
122        $this->history = new SeededHistory();
123        $this->stateChanges = new PushSource($timers->handlerFibers);
124        $this->events = new PushSource($timers->handlerFibers);
125        $this->topics = new PushSource($timers->handlerFibers);
126        $this->connectionEvents = new PushSource($timers->handlerFibers);
127        $this->triggers = new PushSource($timers->handlerFibers);
128        $this->watchedTriggers = WatchedTriggerCollection::empty();
129        $this->identity = new StewartIdentity(self::STEWART_USER_ID);
130    }
131
132    /** @param array<string, mixed> $attributes */
133    public function seedState(string $entityId, string $state, array $attributes = [], ?Instant $changedAt = null): self
134    {
135        $changedAt ??= $this->clock->getNow();
136        $seeded = new EntityState(new EntityId($entityId), $state, $attributes, $changedAt, $changedAt);
137        $this->states = $this->states->withState($seeded);
138        $this->history->recordState($seeded, $changedAt);
139
140        return $this;
141    }
142
143    /** @param array<string, mixed> $attributes */
144    public function seedHistoricalState(string $entityId, string $state, Instant $changedAt, array $attributes = []): self
145    {
146        $this->history->recordState(new EntityState(new EntityId($entityId), $state, $attributes, $changedAt, $changedAt), $changedAt);
147
148        return $this;
149    }
150
151    public function stubHistoryFailure(string $entityId, HistoryException $failure): self
152    {
153        $this->historyFailures[new EntityId($entityId)->value] = $failure;
154
155        return $this;
156    }
157
158    /**
159     * @param array<string, mixed> $response
160     * @throws ActionCallException
161     */
162    public function stubActionAnswer(string $action, array $response): self
163    {
164        $this->actionOutcomes[new ActionName($action)->value] = $response;
165
166        return $this;
167    }
168
169    /** @throws ActionCallException */
170    public function stubActionFailure(string $action, ActionCallException $failure): self
171    {
172        $this->actionOutcomes[new ActionName($action)->value] = $failure;
173
174        return $this;
175    }
176
177    public function stubEventFireFailure(string $eventType, EventFireException $failure): self
178    {
179        $this->eventFireFailures[$eventType] = $failure;
180
181        return $this;
182    }
183
184    public function cancelSubscriptions(): void
185    {
186        foreach ([$this->stateChanges, $this->events, $this->topics, $this->connectionEvents, $this->triggers] as $source) {
187            $source->cancelAttachments();
188        }
189    }
190
191    public function pushStateChange(StateChange $change): void
192    {
193        if ($change->to === null) {
194            $this->states = $this->states->withoutState($change->entityId);
195        } else {
196            $this->states = $this->states->withState($change->to);
197            $this->history->recordState($change->to, $this->clock->getNow());
198        }
199
200        $this->stateChanges->push($change);
201    }
202
203    /** @param array<string, mixed> $attributes */
204    public function pushState(string $entityId, string $state, array $attributes = [], ?EventContext $context = null): void
205    {
206        $id = new EntityId($entityId);
207        $previous = $this->states->find($id);
208        $now = $this->clock->getNow();
209        $changedAt = $previous?->state === $state ? $previous->lastChangedAt ?? $now : $now;
210
211        $this->pushStateChange(new StateChange(
212            $id,
213            $previous,
214            new EntityState($id, $state, $attributes, $changedAt, $now, $context),
215            context: $context,
216        ));
217    }
218
219    public function pushEvent(HaEvent $event): void
220    {
221        $this->events->push($event);
222    }
223
224    public function pushTrigger(HaTrigger|HaTriggerCollection $trigger, TriggerEvent $event): void
225    {
226        $this->triggers->push(new PushedTrigger(TriggerSpec::fromSpec($trigger), $event));
227    }
228
229    public function listWatchedTriggers(): WatchedTriggerCollection
230    {
231        return $this->watchedTriggers;
232    }
233
234    public function pushConnection(ConnectionEvent $event): void
235    {
236        $this->connected = !$event instanceof ConnectionLost;
237        $this->connectionEvents->push($event);
238    }
239
240    /** @throws LogicException */
241    public function getLastCall(): RecordedActionCall
242    {
243        return $this->calls->getLast() ?? throw new LogicException('No action has been called.');
244    }
245
246    public function getState(EntityId|string $entityId): ?EntityState
247    {
248        return $this->states->find(EntityId::fromStringOrId($entityId));
249    }
250
251    public function getEntity(EntityId|string $entityId): Entity
252    {
253        return new Entity($this, EntityId::fromStringOrId($entityId));
254    }
255
256    public function requireState(EntityId|string $entityId): EntityState
257    {
258        $id = EntityId::fromStringOrId($entityId);
259
260        return $this->states->find($id) ?? throw StateException::entityNotFound($id);
261    }
262
263    public function getHeldStateDuration(EntityId|string $entityId): ?Duration
264    {
265        $changedAt = $this->getState($entityId)?->lastChangedAt;
266
267        return $changedAt === null ? null : $this->clock->getNow()->elapsedSince($changedAt);
268    }
269
270    public function hasHeldStateFor(EntityId|string $entityId, Duration $duration): bool
271    {
272        $held = $this->getHeldStateDuration($entityId);
273
274        return $held !== null && !$duration->isLongerThan($held);
275    }
276
277    public function getHistory(EntityId|string $entityId, HistoryQuery $query): EntityStateHistory
278    {
279        $id = EntityId::fromStringOrId($entityId);
280        $window = $query->resolveWindowAt($this->clock->getNow());
281        $this->historyQueries = $this->historyQueries->withRecordedQuery(new RecordedHistoryQuery($id, $window, $query->detail));
282
283        if (!$this->connected) {
284            throw HistoryException::unreachable($id, 'Home Assistant is disconnected');
285        }
286
287        if (isset($this->historyFailures[$id->value])) {
288            throw $this->historyFailures[$id->value];
289        }
290
291        return $this->history->sliceForWindow($id, $window, $query->detail);
292    }
293
294    public function listStates(string|EntityId|Selector|SelectorCollection|EntityFilter|null $selector = null): EntityStateCollection
295    {
296        return match (true) {
297            $selector === null => $this->states,
298            $selector instanceof EntityFilter => $this->states->filterByEntityFilter($selector, $this->registry),
299            default => $this->states->filterBySelector(Selector::fromSpec($selector)),
300        };
301    }
302
303    public function watchStateChanges(string|EntityId|Selector|SelectorCollection|EntityFilter $selector): StateChangeStream
304    {
305        $registry = $this->registry;
306
307        if ($selector instanceof EntityFilter) {
308            $matches = static fn(StateChange $change): bool => $selector->matchesEntity($change->entityId, $registry);
309        } else {
310            $matcher = Selector::fromSpec($selector);
311            $matches = static fn(StateChange $change): bool => $matcher->matches($change->entityId->value);
312        }
313
314        return new StateChanges($this->stateChanges, $this->timers, new RecordedStateReader($this, $selector))->filter($matches);
315    }
316
317    public function waitForState(EntityId|string $entityId, string $state, ?Duration $timeout = null): ?EntityState
318    {
319        return $this->getEntity($entityId)->waitForState($state, $timeout);
320    }
321
322    public function getRegistry(): Registry
323    {
324        return $this->registry;
325    }
326
327    public function watchEvents(string|Selector|SelectorCollection $eventType): EventStream
328    {
329        $matcher = EventTypeSelector::fromSpec($eventType)->selector;
330
331        return new OperatorStream($this->events, $this->timers)
332            ->filter(static fn(HaEvent $event): bool => $matcher->matches($event->type));
333    }
334
335    public function watchTrigger(HaTrigger|HaTriggerCollection|array $trigger, array $variables = []): EventStream
336    {
337        $spec = TriggerSpec::fromSpec($trigger, $variables);
338        $this->watchedTriggers = $this->watchedTriggers->withWatchedTrigger(new WatchedTrigger($spec->triggers, $spec->variables));
339
340        return new OperatorStream($this->triggers, $this->timers)
341            ->filter(static fn(PushedTrigger $pushed): bool => $pushed->spec->hasSameTriggersAs($spec))
342            ->map(static fn(PushedTrigger $pushed): TriggerEvent => $pushed->event);
343    }
344
345    public function callAction(string $action, array $data = [], ?ActionTargetSource $target = null): EventContext
346    {
347        return $this->callStubbedAction(new ActionName($action), $data, $target, false)->context ?? EventContext::unknown();
348    }
349
350    public function callActionForResponse(string $action, array $data = [], ?ActionTargetSource $target = null): ActionResponse
351    {
352        return $this->callStubbedAction(new ActionName($action), $data, $target, true);
353    }
354
355    public function fireEvent(string $eventType, array $data = []): EventContext
356    {
357        $payload = new EventPayload($eventType, $data);
358
359        if (!$this->connected) {
360            throw EventFireException::unreachable($eventType, 'Home Assistant is disconnected');
361        }
362
363        $fire = new RecordedEventFire($payload->eventType, $payload->data, $this->issueContext());
364        $this->firedEvents = $this->firedEvents->withRecordedFire($fire);
365
366        if (isset($this->eventFireFailures[$eventType])) {
367            throw $this->eventFireFailures[$eventType];
368        }
369
370        $this->events->push(new HaEvent($fire->eventType, $fire->data, EventOrigin::Remote, $this->clock->getNow(), $fire->context));
371
372        return $fire->context;
373    }
374
375    public function wasCausedByStewart(StateChange|EntityState|HaEvent $subject): bool
376    {
377        return $this->identity->wasCausedByStewart($subject);
378    }
379
380    public function publish(string $topic, bool|int|float|string|array|null $payload = null): void
381    {
382        $event = new TopicEvent($topic, new TopicPayload($payload)->value, new AppId('test'), $this->clock->getNow());
383
384        $this->published = $this->published->withTopicEvent($event);
385        $this->topics->push($event);
386    }
387
388    public function watchTopic(string|Selector|SelectorCollection $topic): EventStream
389    {
390        $matcher = Selector::fromSpec($topic);
391
392        return new OperatorStream($this->topics, $this->timers)
393            ->filter(static fn(TopicEvent $event): bool => $matcher->matches($event->topic));
394    }
395
396    public function watchConnection(): EventStream
397    {
398        return new OperatorStream($this->connectionEvents, $this->timers);
399    }
400
401    public function isConnected(): bool
402    {
403        return $this->connected;
404    }
405
406    /**
407     * @param array<string, mixed> $data
408     * @throws ActionCallException
409     */
410    private function callStubbedAction(ActionName $action, array $data, ?ActionTargetSource $target, bool $returnsResponse): ActionResponse
411    {
412        if (!$this->connected) {
413            throw ActionCallException::unreachable($action->domain, $action->action, 'Home Assistant is disconnected');
414        }
415
416        $call = new RecordedActionCall(
417            $action->domain,
418            $action->action,
419            ActionFields::fromFieldsDroppingNulls($data)->fields,
420            $target?->toActionTarget(),
421            $returnsResponse,
422            $this->issueContext(),
423        );
424
425        $this->calls = $this->calls->withRecordedCall($call);
426        $outcome = $this->actionOutcomes[$action->value] ?? [];
427
428        return $outcome instanceof ActionCallException ? throw $outcome : new ActionResponse($action->domain, $action->action, $outcome, $call->context);
429    }
430
431    private function issueContext(): EventContext
432    {
433        return new EventContext(self::CONTEXT_ID_PREFIX . ++$this->issuedContextCount, userId: self::STEWART_USER_ID);
434    }
435}