Test Utils
Test utilities for hassette apps.
Tier 1 APIs (AppTestHarness, RecordingApi, make_test_config, event factories) are stable and documented for end users.
Tier 2 symbols (HassetteHarness, SimpleTestServer, fixtures, web helpers, etc.)
are re-exported from hassette.test_utils._internal for backward compatibility
with hassette's own internal test suite. They are not in __all__ and may
change without notice.
ApiCall
dataclass
Record of a single API method invocation.
Write methods (call_service, set_state, fire_event) record their
positional arguments in both args and kwargs so that
:meth:RecordingApi.assert_called can use kwargs-only matching uniformly::
recorder.assert_called("turn_on", entity_id="light.kitchen")
args is available for direct positional inspection when needed, but
assert_called does not check it — use kwargs for assertions.
Attributes:
| Name | Type | Description |
|---|---|---|
method |
str
|
Name of the method that was called (e.g. "turn_on"). |
args |
tuple[Any, ...]
|
Positional arguments passed to the method (for inspection only). |
kwargs |
dict[str, Any]
|
Keyword arguments — the primary assertion surface. Write methods include positional args here as well for uniform kwargs-based matching. |
Source code in src/hassette/test_utils/api_call.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | |
AppConfigurationError
Bases: Exception
Raised when the config dict fails validation against the app's AppConfig subclass.
Attributes:
| Name | Type | Description |
|---|---|---|
app_cls |
type[App]
|
The App class whose config failed validation. |
original_error |
ValidationError
|
The underlying pydantic ValidationError. |
Source code in src/hassette/test_utils/app_harness.py
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | |
AppTestHarness
Bases: SimulationMixin, TimeControlMixin
Async context manager that wires an App class into Hassette test infrastructure.
Provides a fully initialized app instance with access to its bus, scheduler, api_recorder, and states. Handles teardown in the correct LIFO order via AsyncExitStack.
Usage::
async with AppTestHarness(MyApp, config={"my_setting": "value"}) as harness:
harness.app # MyApp instance
harness.bus # test Bus
harness.scheduler # test Scheduler
harness.api_recorder # RecordingApi — records calls your app makes
harness.states # StateManager
Note
Mutates class-level attributes (app_manifest) with save/restore under a narrow per-class asyncio.Lock. Safe for sequential tests, xdist workers, and concurrent use via asyncio.gather for the same App class.
Source code in src/hassette/test_utils/app_harness.py
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 | |
app: App
property
The fully initialized App instance.
bus: Bus
property
The test Bus owned by the app.
scheduler: Scheduler
property
The test Scheduler owned by the app.
api_recorder: RecordingApi
property
The RecordingApi injected into the app (records calls the app makes).
states: StateManager
property
The StateManager owned by the app.
__init__(app_cls: type[App], config: dict[str, Any], *, tmp_path: Path | None = None) -> None
Store args. No resource allocation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app_cls
|
type[App]
|
The App subclass to instantiate and test. |
required |
config
|
dict[str, Any]
|
Dict of config values to validate against app_cls.app_config_cls. |
required |
tmp_path
|
Path | None
|
Optional directory for Hassette data. Auto-created and cleaned up if not provided. |
None
|
Source code in src/hassette/test_utils/app_harness.py
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 | |
__aenter__() -> AppTestHarness
async
Set up the full harness in 11 steps with LIFO teardown via AsyncExitStack.
Source code in src/hassette/test_utils/app_harness.py
265 266 267 268 269 270 271 272 273 274 275 276 277 | |
__aexit__(exc_type: Any, exc: Any, tb: Any) -> None
async
Delegate teardown to the AsyncExitStack (LIFO order).
Source code in src/hassette/test_utils/app_harness.py
425 426 427 428 429 | |
set_state(entity_id: str, state: str, **attributes: Any) -> None
async
Seed an entity's state in the StateProxy.
Uses make_state_dict() internally with a past sentinel timestamp
(1970-01-01T00:00:00Z). Simulated events sent via simulate_state_change
bypass StateProxy's staleness guard entirely (they use
harness.seed_state()), so the epoch timestamp does not play a protective
ordering role — it simply marks seeded state as obviously synthetic.
Call set_state before simulate_state_change for the same entity.
Calling it afterward will overwrite the simulated state with the seeded value.
This is for pre-test setup only and does NOT fire bus events.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
str
|
The entity ID to seed (e.g., "light.kitchen"). |
required |
state
|
str
|
The state value (e.g., "on", "off", "25.5"). |
required |
**attributes
|
Any
|
Entity attribute key/value pairs. |
{}
|
Source code in src/hassette/test_utils/app_harness.py
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 | |
seed_helper(record: BaseModel) -> None
Seed a stored helper config for tests that read helper CRUD.
Domain is derived from the record class. Passing a record of a type not registered in RECORD_TYPE_TO_DOMAIN raises ValueError immediately.
The record is deep-copied before storage, so later mutations of the
caller's record object will not leak into harness state — matching
the isolation guarantees of list_* / create_* / update_*.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
record
|
BaseModel
|
A helper Record model instance (e.g., InputBooleanRecord). |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the record's type is not a known helper record type, or if a record with the same id is already seeded. |
Source code in src/hassette/test_utils/app_harness.py
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 | |
set_states(states: dict[str, str | tuple[str, dict]]) -> None
async
Seed multiple entities at once.
Example::
await harness.set_states({
"light.kitchen": "on",
"sensor.temp": ("25.5", {"unit_of_measurement": "°C"}),
})
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
states
|
dict[str, str | tuple[str, dict]]
|
Dict mapping entity_id to state string or (state, attrs) tuple. |
required |
Source code in src/hassette/test_utils/app_harness.py
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 | |
DrainError
Bases: DrainFailure
Raised when AppTestHarness drain surfaces handler task exceptions.
Aggregates all non-cancellation exceptions from completed tasks during drain so test failures report the real cause instead of silently masking handler crashes with misleading assertion failures.
Attributes:
| Name | Type | Description |
|---|---|---|
task_exceptions |
list[tuple[str, BaseException]]
|
List of |
Source code in src/hassette/test_utils/exceptions.py
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | |
DrainFailure
Bases: Exception
Base class for all AppTestHarness drain failures.
Lets callers catch both handler exceptions and drain deadline timeouts
uniformly with except DrainFailure:. Do not raise this class directly —
raise one of its subclasses (:class:DrainError or :class:DrainTimeout).
Note
The Failure suffix is intentional and deviates from the project's
*Error-suffix convention for exceptions. It signals that this
class is a hierarchy root, not something to raise directly. The two
concrete subclasses below use the conventional Error / Timeout
suffixes.
Source code in src/hassette/test_utils/exceptions.py
25 26 27 28 29 30 31 32 33 34 35 36 37 38 | |
DrainTimeout
Bases: DrainFailure
Raised when AppTestHarness drain does not reach quiescence within its deadline.
Carries a diagnostic message built by _raise_drain_timeout that
includes pending task counts, pending task names, and — when applicable —
a hint about debounce windows.
Does NOT inherit from :class:TimeoutError. Callers that previously
caught TimeoutError around drain calls should catch DrainTimeout
(or the broader DrainFailure) instead.
Source code in src/hassette/test_utils/exceptions.py
73 74 75 76 77 78 79 80 81 82 83 | |
RecordingApi
Bases: Resource
Test double for hassette.api.Api.
Records write-method calls for assertion in tests. Delegates read methods to StateProxy so tests see seeded state values. get_state() raises EntityNotFoundError for unseeded entities (matching real Api behavior).
on_initialize() calls self.mark_ready() — required for the Resource lifecycle.
sync attribute is a RecordingSyncFacade instance. Write calls via api.sync.*
are recorded to the same calls list as the async side. Read methods delegate
to the StateProxy. Methods not covered by the facade raise NotImplementedError.
Unstubbed methods raise NotImplementedError with guidance on alternatives.
Authoring constraints (enforced by the RecordingSyncFacade generator):
-
Methods must not call other
async defmethods onselfdirectly; use sync helpers (_get_raw_state,_convert_state) instead. Violating this constraint will fail the generator with a clear error pointing at the offending call site. -
Stub methods — those that should raise
NotImplementedErroron the sync side rather than be body-copied into the facade — should useself.not_implemented(name)for the canonical helpful error message on the async side. TheRecordingSyncFacadegenerator detects stub-tier methods by recognizing any body that contains only docstrings,raisestatements, and/ornot_implemented()calls, soraise NotImplementedError(...)works too, butself.not_implemented(name)is preferred because the helper returns an exception with the project's standard seed-state guidance.
Example::
async with AppTestHarness(MotionLights, config={}) as harness:
await harness.simulate_state_change("sensor.test", old_value="off", new_value="on")
harness.api_recorder.assert_called("turn_on", entity_id="light.kitchen")
Source code in src/hassette/test_utils/recording_api.py
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 | |
on_initialize() -> None
async
Mark this resource ready. Called by Resource.initialize().
Source code in src/hassette/test_utils/recording_api.py
386 387 388 | |
turn_on(entity_id: str | StrEnum, domain: str = 'homeassistant', **data: Any) -> None
async
Record a turn_on call directly under its own method name.
Source code in src/hassette/test_utils/recording_api.py
416 417 418 419 420 421 422 423 424 425 | |
turn_off(entity_id: str | StrEnum, domain: str = 'homeassistant') -> None
async
Record a turn_off call directly under its own method name.
Source code in src/hassette/test_utils/recording_api.py
427 428 429 430 431 432 433 434 435 436 | |
toggle_service(entity_id: str | StrEnum, domain: str = 'homeassistant') -> None
async
Record a toggle_service call directly under its own method name.
Source code in src/hassette/test_utils/recording_api.py
438 439 440 441 442 443 444 445 446 447 | |
call_service(domain: str, service: str, target: dict[str, str] | dict[str, list[str]] | None = None, return_response: bool | None = False, **data: Any) -> ServiceResponse | None
async
Record a call_service call. Returns stub ServiceResponse when return_response=True.
Source code in src/hassette/test_utils/recording_api.py
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 | |
set_state(entity_id: str | StrEnum, state: Any, attributes: dict[str, Any] | None = None) -> dict
async
Record a set_state call. Returns an empty dict stub.
Source code in src/hassette/test_utils/recording_api.py
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 | |
fire_event(event_type: str, event_data: dict[str, Any] | None = None) -> dict[str, Any]
async
Record a fire_event call. Returns an empty dict stub.
Source code in src/hassette/test_utils/recording_api.py
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 | |
get_state(entity_id: str) -> BaseState
async
Return the typed state for entity_id. Raises EntityNotFoundError if not seeded.
Source code in src/hassette/test_utils/recording_api.py
538 539 540 541 | |
get_states() -> list[BaseState]
async
Return typed states for all seeded entities.
Source code in src/hassette/test_utils/recording_api.py
543 544 545 546 547 | |
get_entity(entity_id: str, model: type[BaseEntity]) -> BaseEntity
async
Return a pydantic-validated entity wrapper for entity_id.
Matches the real Api.get_entity signature exactly — model is required
and must be a :class:~hassette.models.entities.base.BaseEntity subclass.
Callers that want registry-converted state without a specific entity model
should call :meth:get_state instead.
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
EntityNotFoundError
|
If |
Source code in src/hassette/test_utils/recording_api.py
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 | |
get_entity_or_none(entity_id: str, model: type[BaseEntity]) -> BaseEntity | None
async
Return a pydantic-validated entity wrapper for entity_id, or None if not seeded.
Inlines the logic from :meth:get_entity using sync helpers only — no peer
async def calls on self — to satisfy the authoring constraint required
by the RecordingSyncFacade generator. Matches the real
Api.get_entity_or_none signature; see :meth:get_entity for semantics.
Source code in src/hassette/test_utils/recording_api.py
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 | |
entity_exists(entity_id: str) -> bool
async
Return True if entity_id is seeded in the StateProxy.
Source code in src/hassette/test_utils/recording_api.py
584 585 586 | |
get_state_or_none(entity_id: str) -> BaseState | None
async
Return the typed state for entity_id, or None if not seeded.
Inlines the logic from :meth:get_state using sync helpers only — no peer
async def calls on self — to satisfy the authoring constraint required
by the RecordingSyncFacade generator.
Source code in src/hassette/test_utils/recording_api.py
588 589 590 591 592 593 594 595 596 597 598 599 | |
get_state_raw(entity_id: str) -> dict
async
Not implemented — raises NotImplementedError.
Source code in src/hassette/test_utils/recording_api.py
601 602 603 | |
get_states_raw() -> list[dict]
async
Not implemented — raises NotImplementedError.
Source code in src/hassette/test_utils/recording_api.py
605 606 607 | |
get_history(entity_id: str, *args: Any, **kwargs: Any) -> list
async
Not implemented — raises NotImplementedError.
Source code in src/hassette/test_utils/recording_api.py
609 610 611 | |
render_template(template: str, variables: dict | None = None) -> str
async
Not implemented — raises NotImplementedError.
Source code in src/hassette/test_utils/recording_api.py
613 614 615 | |
ws_send_and_wait(**data: Any) -> Any
async
Not implemented — raises NotImplementedError.
Source code in src/hassette/test_utils/recording_api.py
617 618 619 | |
ws_send_json(**data: Any) -> None
async
Not implemented — raises NotImplementedError.
Source code in src/hassette/test_utils/recording_api.py
621 622 623 | |
rest_request(method: str, url: str, **kwargs: Any) -> Any
async
Not implemented — raises NotImplementedError.
Source code in src/hassette/test_utils/recording_api.py
625 626 627 | |
delete_entity(entity_id: str) -> None
async
Not implemented — raises NotImplementedError.
Source code in src/hassette/test_utils/recording_api.py
629 630 631 | |
list_input_booleans() -> list[InputBooleanRecord]
async
Return all seeded input_boolean helpers. Delegates to _list_helper.
Source code in src/hassette/test_utils/recording_api.py
747 748 749 | |
create_input_boolean(params: CreateInputBooleanParams) -> InputBooleanRecord
async
Record the call and add a record to helper_definitions. Delegates to _create_helper.
Source code in src/hassette/test_utils/recording_api.py
751 752 753 | |
update_input_boolean(helper_id: str, params: UpdateInputBooleanParams) -> InputBooleanRecord
async
Record the call and mutate the seeded record. Delegates to _update_helper.
Source code in src/hassette/test_utils/recording_api.py
755 756 757 758 759 | |
delete_input_boolean(helper_id: str) -> None
async
Record the call and remove the seeded record. Delegates to _delete_helper.
Source code in src/hassette/test_utils/recording_api.py
761 762 763 | |
list_input_numbers() -> list[InputNumberRecord]
async
Return all seeded input_number helpers. Delegates to _list_helper.
Source code in src/hassette/test_utils/recording_api.py
765 766 767 | |
create_input_number(params: CreateInputNumberParams) -> InputNumberRecord
async
Record the call and add a record to helper_definitions. Delegates to _create_helper.
Source code in src/hassette/test_utils/recording_api.py
769 770 771 | |
update_input_number(helper_id: str, params: UpdateInputNumberParams) -> InputNumberRecord
async
Record the call and mutate the seeded record. Delegates to _update_helper.
Source code in src/hassette/test_utils/recording_api.py
773 774 775 776 777 | |
delete_input_number(helper_id: str) -> None
async
Record the call and remove the seeded record. Delegates to _delete_helper.
Source code in src/hassette/test_utils/recording_api.py
779 780 781 | |
list_input_texts() -> list[InputTextRecord]
async
Return all seeded input_text helpers. Delegates to _list_helper.
Source code in src/hassette/test_utils/recording_api.py
783 784 785 | |
create_input_text(params: CreateInputTextParams) -> InputTextRecord
async
Record the call and add a record to helper_definitions. Delegates to _create_helper.
Source code in src/hassette/test_utils/recording_api.py
787 788 789 | |
update_input_text(helper_id: str, params: UpdateInputTextParams) -> InputTextRecord
async
Record the call and mutate the seeded record. Delegates to _update_helper.
Source code in src/hassette/test_utils/recording_api.py
791 792 793 | |
delete_input_text(helper_id: str) -> None
async
Record the call and remove the seeded record. Delegates to _delete_helper.
Source code in src/hassette/test_utils/recording_api.py
795 796 797 | |
list_input_selects() -> list[InputSelectRecord]
async
Return all seeded input_select helpers as deep-isolated copies.
Delegates to _list_helper. Uses model_copy(deep=True) because
InputSelectRecord.options is a list[str] — the deep_copy=True
flag in RECORD_TYPE_TO_DOMAIN ensures the list is not aliased.
Source code in src/hassette/test_utils/recording_api.py
799 800 801 802 803 804 805 806 | |
create_input_select(params: CreateInputSelectParams) -> InputSelectRecord
async
Record the call and add a record to helper_definitions. Delegates to _create_helper.
Source code in src/hassette/test_utils/recording_api.py
808 809 810 | |
update_input_select(helper_id: str, params: UpdateInputSelectParams) -> InputSelectRecord
async
Record the call and mutate the seeded record. Delegates to _update_helper.
Source code in src/hassette/test_utils/recording_api.py
812 813 814 815 816 | |
delete_input_select(helper_id: str) -> None
async
Record the call and remove the seeded record. Delegates to _delete_helper.
Source code in src/hassette/test_utils/recording_api.py
818 819 820 | |
list_input_datetimes() -> list[InputDatetimeRecord]
async
Return all seeded input_datetime helpers. Delegates to _list_helper.
Source code in src/hassette/test_utils/recording_api.py
822 823 824 | |
create_input_datetime(params: CreateInputDatetimeParams) -> InputDatetimeRecord
async
Record the call and add a record to helper_definitions. Delegates to _create_helper.
Source code in src/hassette/test_utils/recording_api.py
826 827 828 | |
update_input_datetime(helper_id: str, params: UpdateInputDatetimeParams) -> InputDatetimeRecord
async
Record the call and mutate the seeded record. Delegates to _update_helper.
Source code in src/hassette/test_utils/recording_api.py
830 831 832 833 834 | |
delete_input_datetime(helper_id: str) -> None
async
Record the call and remove the seeded record. Delegates to _delete_helper.
Source code in src/hassette/test_utils/recording_api.py
836 837 838 | |
list_input_buttons() -> list[InputButtonRecord]
async
Return all seeded input_button helpers. Delegates to _list_helper.
Source code in src/hassette/test_utils/recording_api.py
840 841 842 | |
create_input_button(params: CreateInputButtonParams) -> InputButtonRecord
async
Record the call and add a record to helper_definitions. Delegates to _create_helper.
Source code in src/hassette/test_utils/recording_api.py
844 845 846 | |
update_input_button(helper_id: str, params: UpdateInputButtonParams) -> InputButtonRecord
async
Record the call and mutate the seeded record. Delegates to _update_helper.
Source code in src/hassette/test_utils/recording_api.py
848 849 850 851 852 | |
delete_input_button(helper_id: str) -> None
async
Record the call and remove the seeded record. Delegates to _delete_helper.
Source code in src/hassette/test_utils/recording_api.py
854 855 856 | |
list_counters() -> list[CounterRecord]
async
Return all seeded counter helpers. Delegates to _list_helper.
Source code in src/hassette/test_utils/recording_api.py
858 859 860 | |
create_counter(params: CreateCounterParams) -> CounterRecord
async
Record the call and add a record to helper_definitions. Delegates to _create_helper.
Source code in src/hassette/test_utils/recording_api.py
862 863 864 | |
update_counter(helper_id: str, params: UpdateCounterParams) -> CounterRecord
async
Record the call and mutate the seeded record. Delegates to _update_helper.
Source code in src/hassette/test_utils/recording_api.py
866 867 868 | |
delete_counter(helper_id: str) -> None
async
Record the call and remove the seeded record. Delegates to _delete_helper.
Source code in src/hassette/test_utils/recording_api.py
870 871 872 | |
list_timers() -> list[TimerRecord]
async
Return all seeded timer helpers. Delegates to _list_helper.
Source code in src/hassette/test_utils/recording_api.py
874 875 876 | |
create_timer(params: CreateTimerParams) -> TimerRecord
async
Record the call and add a record to helper_definitions. Delegates to _create_helper.
Source code in src/hassette/test_utils/recording_api.py
878 879 880 | |
update_timer(helper_id: str, params: UpdateTimerParams) -> TimerRecord
async
Record the call and mutate the seeded record. Delegates to _update_helper.
Source code in src/hassette/test_utils/recording_api.py
882 883 884 | |
delete_timer(helper_id: str) -> None
async
Record the call and remove the seeded record. Delegates to _delete_helper.
Source code in src/hassette/test_utils/recording_api.py
886 887 888 | |
increment_counter(entity_id: str) -> None
async
Record an increment_counter call directly (not via call_service).
Source code in src/hassette/test_utils/recording_api.py
890 891 892 893 894 895 896 897 898 | |
decrement_counter(entity_id: str) -> None
async
Record a decrement_counter call directly (not via call_service).
Source code in src/hassette/test_utils/recording_api.py
900 901 902 903 904 905 906 907 908 | |
reset_counter(entity_id: str) -> None
async
Record a reset_counter call directly (not via call_service).
Source code in src/hassette/test_utils/recording_api.py
910 911 912 913 914 915 916 917 918 | |
__getattr__(name: str) -> Any
Raise NotImplementedError for public attributes not defined on RecordingApi.
Private/dunder attributes fall through to the default AttributeError so that
Resource internals (e.g. _unique_name) and Python machinery work correctly.
State-conversion methods (get_state_value, get_state_value_typed, get_attribute)
get a tailored message directing users to await self.api.get_state(entity_id).
All other unimplemented methods get the generic "Seed state" guidance.
Source code in src/hassette/test_utils/recording_api.py
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 | |
get_calls(method: str | None = None) -> list[ApiCall]
Return all recorded calls, optionally filtered by method name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str | None
|
If given, return only calls for this method name. |
None
|
Returns:
| Type | Description |
|---|---|
list[ApiCall]
|
List of ApiCall records (a copy — callers may modify safely). |
Source code in src/hassette/test_utils/recording_api.py
943 944 945 946 947 948 949 950 951 952 953 954 | |
assert_called(method: str, **kwargs: Any) -> None
Assert that method was called at least once with matching kwargs.
Performs partial (subset) matching: the call passes if all specified
kwargs are present in the recorded call's kwargs with matching values.
Extra kwargs in the recorded call are ignored. Positional arguments
recorded in call.args are also checked via the recorded kwargs
dict — write methods record their positional args as both args and
kwargs so assertions like
assert_called("turn_on", entity_id="light.kitchen") work.
This is a partial-match alias. See also :meth:assert_called_partial
(identical semantics, explicit name) and :meth:assert_called_exact
(no extra kwargs allowed in the recorded call).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
Method name to check. |
required |
**kwargs
|
Any
|
Expected keyword arguments that must appear in at least one call. |
{}
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If no call matches. |
Source code in src/hassette/test_utils/recording_api.py
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 | |
assert_called_partial(method: str, **kwargs: Any) -> None
Assert that method was called at least once with matching kwargs (partial match).
Non-deprecated alias for :meth:assert_called. Performs partial
(subset) matching: the call passes if all specified kwargs are
present in the recorded call's kwargs with matching values. Extra kwargs
in the recorded call are ignored.
Use this name when you want to make the partial-match intent explicit in
test code. Both assert_called and assert_called_partial behave
identically; they differ only in name clarity.
See also :meth:assert_called_exact for exact (no-extra-kwargs) matching.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
Method name to check. |
required |
**kwargs
|
Any
|
Expected keyword arguments that must appear in at least one call. |
{}
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If no call matches. |
Source code in src/hassette/test_utils/recording_api.py
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 | |
assert_called_exact(method: str, **kwargs: Any) -> None
Assert that method was called at least once with exactly the specified kwargs.
Performs exact matching: the call passes only when the recorded
call's kwargs dict is exactly equal to the provided kwargs —
no extra keys are allowed. This is stricter than :meth:assert_called
and :meth:assert_called_partial, which allow extra keys in the
recorded call.
Use this when you need to verify that no unexpected kwargs were passed.
For example, if a method should be called only with entity_id
and nothing else, use assert_called_exact("turn_off", entity_id="light.x")
rather than assert_called("turn_off", entity_id="light.x") — the latter
would pass even if domain="homeassistant" was also recorded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
Method name to check. |
required |
**kwargs
|
Any
|
The exact keyword arguments expected in at least one call. |
{}
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If no call was recorded with exactly the specified kwargs. |
Example::
await api.turn_off("light.x")
# Passes — recorded kwargs are {"entity_id": "light.x", "domain": "homeassistant"}
api.assert_called("turn_off", entity_id="light.x") # partial: OK
# Fails — extra "domain" key is present
api.assert_called_exact("turn_off", entity_id="light.x") # exact: fails
# Passes — matches exactly
api.assert_called_exact("turn_off", entity_id="light.x", domain="homeassistant")
Source code in src/hassette/test_utils/recording_api.py
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 | |
assert_not_called(method: str, **kwargs: Any) -> None
Assert that method was never called.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
Method name to check. |
required |
**kwargs
|
Any
|
If provided, only calls whose recorded kwargs match all of these key/value pairs count as a violation (partial match, consistent with assert_called). This lets you assert "turn_on was never called for light.bedroom" even when turn_on was called for other entities. |
{}
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If a matching call was recorded. |
Source code in src/hassette/test_utils/recording_api.py
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 | |
assert_call_count(method: str, count: int, **kwargs: Any) -> None
Assert that method was called exactly count times.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
Method name to check. |
required |
count
|
int
|
Expected number of calls (positional). With kwargs, only calls matching all the given keyword arguments are counted. |
required |
**kwargs
|
Any
|
If provided, only calls whose recorded kwargs match all of these
key/value pairs are counted toward |
{}
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the call count does not match. |
Source code in src/hassette/test_utils/recording_api.py
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 | |
reset() -> None
Clear all recorded calls and reset helper_definitions to empty-per-domain state.
Replaces the calls list with a new empty list rather than mutating the
existing list in place. This preserves any snapshots callers hold
(e.g., saved = api.calls before a simulate_* call) — they
will still see the original calls after reset, as expected.
Source code in src/hassette/test_utils/recording_api.py
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 | |
make_test_config(*, data_dir: Path | str, **overrides: Any) -> HassetteConfig
Create a minimal :class:~hassette.config.config.HassetteConfig for testing.
No TOML file, no env file, no CLI args — only the provided overrides are read. All Pydantic validation still runs.
Defaults
token:"test-token"base_url:"http://test.invalid:8123"(unreachable by design)disable_state_proxy_polling:Trueapps:{"autodetect": False}web_api:{"run": False}run_app_precheck:False
Overrides are merged on top of these defaults before validation. Nested group overrides can be passed as dicts or model instances::
make_test_config(data_dir=tmp_path, database={"retention_days": 14})
make_test_config(data_dir=tmp_path, database=DatabaseConfig(retention_days=14))
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_dir
|
Path | str
|
Directory for Hassette data (caches, etc.). In pytest, pass
|
required |
**overrides
|
Any
|
Any |
{}
|
Returns:
| Type | Description |
|---|---|
HassetteConfig
|
A validated :class: |
Example::
config = make_test_config(data_dir=tmp_path)
config = make_test_config(data_dir=tmp_path, base_url="http://192.168.1.1:8123")
config = make_test_config(data_dir=tmp_path, database={"retention_days": 14})
Source code in src/hassette/test_utils/config.py
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | |
create_call_service_event(*, domain: str, service: str, service_data: dict[str, Any] | None = None) -> CallServiceEvent
Create a call service event for testing.
Source code in src/hassette/test_utils/helpers.py
94 95 96 97 98 99 100 101 102 103 104 105 106 | |
create_state_change_event(*, entity_id: str, old_value: Any, new_value: Any, old_attrs: dict[str, Any] | None = None, new_attrs: dict[str, Any] | None = None) -> RawStateChangeEvent
Create a state change event for testing.
Pass None for old_value or new_value to simulate entity creation or removal
(produces None for that state dict, not {"state": None, ...}).
Source code in src/hassette/test_utils/helpers.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | |
make_light_state_dict(entity_id: str = 'light.kitchen', state: str = 'on', brightness: int | None = None, color_temp: int | None = None, **kwargs: Any) -> dict[str, Any]
Factory for creating light state dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
str
|
The light entity ID |
'light.kitchen'
|
state
|
str
|
"on" or "off" |
'on'
|
brightness
|
int | None
|
Brightness value 0-255 |
None
|
color_temp
|
int | None
|
Color temperature in mireds |
None
|
**kwargs
|
Any
|
Additional attributes or state dict fields |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary matching Home Assistant light state format |
Source code in src/hassette/test_utils/helpers.py
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 | |
make_sensor_state_dict(entity_id: str = 'sensor.temperature', state: str = '25.5', unit_of_measurement: str | None = None, device_class: str | None = None, **kwargs: Any) -> dict[str, Any]
Factory for creating sensor state dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
str
|
The sensor entity ID |
'sensor.temperature'
|
state
|
str
|
The sensor value as string |
'25.5'
|
unit_of_measurement
|
str | None
|
Unit string (e.g., "°C", "%") |
None
|
device_class
|
str | None
|
Device class (e.g., "temperature", "humidity") |
None
|
**kwargs
|
Any
|
Additional attributes or state dict fields |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary matching Home Assistant sensor state format |
Source code in src/hassette/test_utils/helpers.py
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 | |
make_state_dict(entity_id: str, state: str, attributes: dict[str, Any] | None = None, last_changed: str | None = None, last_updated: str | None = None, context: dict[str, Any] | None = None) -> dict[str, Any]
Factory for creating state dictionary in Home Assistant format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
str
|
The entity ID (e.g., "light.kitchen") |
required |
state
|
str
|
The state value (e.g., "on", "off", "25.5") |
required |
attributes
|
dict[str, Any] | None
|
Entity attributes dict |
None
|
last_changed
|
str | None
|
ISO timestamp string |
None
|
last_updated
|
str | None
|
ISO timestamp string |
None
|
context
|
dict[str, Any] | None
|
Event context dict |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary matching Home Assistant state format |
Source code in src/hassette/test_utils/helpers.py
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 | |
make_switch_state_dict(entity_id: str = 'switch.outlet', state: str = 'on', **kwargs: Any) -> dict[str, Any]
Factory for creating switch state dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
str
|
The switch entity ID |
'switch.outlet'
|
state
|
str
|
"on" or "off" |
'on'
|
**kwargs
|
Any
|
Additional attributes or state dict fields |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary matching Home Assistant switch state format |
Source code in src/hassette/test_utils/helpers.py
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 | |
make_mock_hassette(*, data_dir: Path | str | None = None, set_ready: bool = True, set_loop: bool = True, sealed: bool = True, **config_overrides: Any) -> AsyncMock
Create a fully-wired :class:unittest.mock.AsyncMock that stands in for Hassette.
The mock combines a real, Pydantic-validated :class:~hassette.config.config.HassetteConfig
(via :func:~hassette.test_utils.config.make_test_config) with AsyncMock shells for all
non-configuration attributes. This eliminates config drift across test files while keeping
unit tests lightweight — no real Hassette __init__ side effects.
After wiring all standard attributes, :func:unittest.mock.seal is applied so that
accessing any attribute not explicitly set here raises AttributeError. Tests that need
additional attributes beyond the defaults pass sealed=False, set their extras, and
optionally seal the mock themselves.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_dir
|
Path | str | None
|
Directory for Hassette data. Defaults to |
None
|
set_ready
|
bool
|
If |
True
|
set_loop
|
bool
|
If |
True
|
sealed
|
bool
|
If |
True
|
**config_overrides
|
Any
|
Any :class: |
{}
|
Returns:
| Type | Description |
|---|---|
AsyncMock
|
A sealed (by default) :class: |
AsyncMock
|
|
AsyncMock
|
|
AsyncMock
|
|
AsyncMock
|
|
AsyncMock
|
|
AsyncMock
|
|
AsyncMock
|
|
AsyncMock
|
|
AsyncMock
|
|
AsyncMock
|
|
AsyncMock
|
|
AsyncMock
|
|
AsyncMock
|
|
AsyncMock
|
|
AsyncMock
|
|
Example::
async def test_something():
hassette = make_mock_hassette()
assert hassette.config.token == "test-token"
async def test_strict(tmp_path):
hassette = make_mock_hassette(data_dir=tmp_path, strict_lifecycle=True)
assert hassette.config.strict_lifecycle is True
Source code in src/hassette/test_utils/mock_hassette.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | |