diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..84c048a --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/build/ diff --git a/FAQ.md b/FAQ.md new file mode 100644 index 0000000..f21bcf7 --- /dev/null +++ b/FAQ.md @@ -0,0 +1,288 @@ +Last Edit: Claude Sonnet 4.6 - 2026-03-09 - Motive: Updated pydantic_helpers module name (pydantic.py → pydantic_helpers.py) in all FAQ entries. + +# FAQ — `ovoscope` + +## What is `ovoscope`? +`ovoscope` is End-to-end test framework for OpenVoiceOS skills. + +## How do I install it? +```bash +pip install ovoscope +``` +Or for development: +```bash +uv pip install -e ovoscope/ +``` + +## Where do I report bugs? +Open an issue on the GitHub repository. Ensure you are targeting the `dev` branch for fixes. + +## How do I run tests? +```bash +uv run pytest ovoscope/test/ --cov=ovoscope +``` + +## How do I contribute? +1. Fork the repository and create a feature branch from `dev`. +2. Write tests for your changes. +3. Open a PR targeting the `dev` branch. +4. Ensure CI passes before requesting review. + +## What Python versions are supported? +See `QUICK_FACTS.md` — currently `>=3.10`. + +## My tests pass locally but fail on CI — why? + +Usually one of three causes: + +1. **Different pipeline plugins installed** — The default session pipeline includes whatever + pipeline plugins happen to be installed. On CI, Gemma/Ollama/persona plugins may not be + installed (or vice versa), changing which plugin handles the utterance. + **Fix**: always pass an explicit `default_pipeline` to `get_minicroft()` (or use the default + `DEFAULT_TEST_PIPELINE` by leaving `isolate_config=True`). + +2. **User locale affecting intent matching** — `isolate_config=True` (the default) removes the + user's `~/.config/mycroft/mycroft.conf` from the config chain so the test environment locale + does not affect results. Always leave this enabled. + +3. **Skill plugin not discoverable** — The skill must be registered under the `opm.skill` entry + point group. Old-style `ovos.plugin.skill` entries are warned but not loaded by + `find_skill_plugins()`. Use `extra_skills={SKILL_ID: SkillClass}` to inject skills that + lack a proper entry point. + +## A persona / AI plugin is intercepting my test utterances + +This happens because `SessionManager.default_session` is initialized at import time from the +full system config (which may include persona pipeline stages). + +`MiniCroft` solves this with `default_pipeline` (default: `DEFAULT_TEST_PIPELINE`): + +```python +from ovoscope import get_minicroft, DEFAULT_TEST_PIPELINE, ADAPT_PIPELINE + +# Default — all standard stages, no AI/persona/OCP (recommended) +mc = get_minicroft([]) + +# Adapt-only for fast unit-style end2end tests +mc = get_minicroft([SKILL_ID], default_pipeline=ADAPT_PIPELINE) + +# Opt in to persona explicitly +from ovoscope import PERSONA_PIPELINE +mc = get_minicroft([SKILL_ID], default_pipeline=DEFAULT_TEST_PIPELINE + PERSONA_PIPELINE) +``` + +`DEFAULT_TEST_PIPELINE` excludes persona, Ollama, OCP, and m2v stages. +The original pipeline is restored when `mc.stop()` is called. + +## Why does `SessionManager.default_session.pipeline` matter? + +When a message is emitted without an explicit `session` in its context, ovos-core creates a +session by copying `SessionManager.default_session`. That copy inherits its `pipeline` list, +which controls which pipeline plugins are consulted for intent matching. + +`MiniCroft.run()` overrides `SessionManager.default_session.pipeline` to `default_pipeline` +(set after FakeBus init messages are processed, just before `READY`), and restores it on +`stop()`. + +## How is `isolate_config` different from `default_pipeline`? + +- `isolate_config=True` — clears `Configuration.xdg_configs` so `~/.config/mycroft/mycroft.conf` + is not read. Prevents user locale, custom wake words, and user-level pipeline *config* from + affecting tests. +- `default_pipeline` — overrides `SessionManager.default_session.pipeline` directly. Necessary + because the default session is initialized at module import time (before config isolation takes + effect) and may already have the user's pipeline. + +Both are enabled by default. They are complementary. + +## How do I know whether to use ADAPT_PIPELINE or PADATIOUS_PIPELINE for my test? + +It depends on how the skill registers its intent: + +| Decorator | Pipeline | +|-----------|----------| +| `@intent_handler(IntentBuilder(...))` | `ADAPT_PIPELINE` | +| `@intent_handler("my.intent")` (string ending in `.intent`) | `PADATIOUS_PIPELINE` | +| `@fallback_handler(priority=N)` | `FALLBACK_PIPELINE` | +| `@converse_handler` | `CONVERSE_PIPELINE` | + +When in doubt, look at the intent files in `locale/en-us/` — if there is a file named `*.intent`, +it is Padatious. If there is a file named `*.voc` or `*.rx`, it is Adapt. + +## My skill emits extra messages (enclosure.eyes.*, add_context, configuration.patch) — how do I handle them? + +Some skills emit low-level hardware events or internal context messages that are not part of the +utterance handling protocol. Add them to `ignore_messages`: + +```python +test = End2EndTest( + ... + ignore_messages=[ + "enclosure.eyes.level", # Mark 1 LED animation + "enclosure.eyes.look", + "add_context", # set_context() calls + "configuration.patch", # disable_confirm_listening() etc. + ], + ... +) +``` + +## A skill emits a raw message (no source/dest) like recognizer_loop:sleep — how do I test it? + +Some skills call `self.bus.emit(Message("some.message"))` without inheriting source/dest. +These messages have `source=None` and will fail source-checking in the framework. + +Use `async_messages` to assert they were received without checking order or source: + +```python +test = End2EndTest( + ... + ignore_messages=["recognizer_loop:sleep"], # exclude from ordered sequence + async_messages=["recognizer_loop:sleep"], # assert it was received somewhere + ... +) +``` + +## My test passes locally but the user's blacklisted skills cause failures on CI + +Users may have skills like `skill-ovos-stop.openvoiceos` in `blacklisted_skills` in their +`~/.config/mycroft/mycroft.conf`. `Session.__init__` reads this from the live +`Configuration()` singleton dict cache (not invalidated by `reload()`). + +`MiniCroft` solves this: when `isolate_config=True` (the default), it patches +`Configuration()["skills"]["blacklisted_skills"] = []` and +`Configuration()["intents"]["blacklisted_intents"] = []` in `run()`, and restores them in `stop()`. +This is complementary to the `xdg_configs = []` isolation applied in `__init__`. + +## Can I use typed pydantic models instead of raw Message objects? + +Yes. Install the optional pydantic extras: + +```bash +pip install ovoscope[pydantic] +``` + +Then use the bridge in `ovoscope.pydantic_helpers`: + +```python +from ovoscope.pydantic_helpers import to_bus_message, from_bus_message +from ovos_pydantic_models import RecognizerLoopUtteranceMessage, RecognizerLoopUtteranceData, SpeakMessage + +# Build a typed source message — validated at construction +utterance = to_bus_message(RecognizerLoopUtteranceMessage( + data=RecognizerLoopUtteranceData(utterances=["hello"], lang="en-us") +)) + +# Parse a received message into a typed model for richer assertions +messages = test.execute() +speak = from_bus_message(messages[0], SpeakMessage) +assert "hello" in speak.data.utterance.lower() +``` + +A typo in a field name (`"utterance"` vs `"utterances"`) raises `ValidationError` at +construction time instead of silently producing a wrong test. + +## How do I validate a JSON fixture file before loading it? + +Use `validate_fixture()` from `ovoscope.pydantic_helpers` (requires `ovoscope[pydantic]`): + +```python +from ovoscope.pydantic_helpers import validate_fixture +from ovoscope import End2EndTest + +test = End2EndTest.deserialize(validate_fixture("test/fixtures/hello_world.json")) +test.execute() +``` + +If any message in the fixture is malformed, a clear `ValidationError` is raised pointing +to the offending field — instead of a cryptic `KeyError` inside `deserialize()`. + +## How do I trigger non-utterance events during a test? + +Use `MiniCroft.inject_message(msg)`: + +```python +from ovos_bus_client.message import Message + +mc.inject_message(Message("mycroft.gui.connected", {"connected": True})) +``` + +This emits an arbitrary message on the FakeBus during a test without going through the +utterance pipeline — useful for timer events, GUI events, or skill API calls. + +## How do I assert a skill spoke a specific phrase without checking the full message sequence? + +Use `End2EndTest.assert_spoke(text, lang)`: + +```python +test = End2EndTest( + skill_ids=["my-skill.author"], + source_message=Message("recognizer_loop:utterance", {"utterances": ["hello"], "lang": "en-US"}, {}), + expected_messages=[], # not used by assert_spoke +) +test.assert_spoke("Hello, world!", lang="en-US") +``` + +`assert_spoke()` calls `execute()` internally and scans captured messages for a `speak` +message with the matching utterance and lang. + +## `get_minicroft()` hangs forever — what do I do? + +Pass `max_wait` to set a timeout: + +```python +mc = get_minicroft(["my-skill.author"], max_wait=30) +``` + +If `MiniCroft` does not reach `READY` within `max_wait` seconds, a `TimeoutError` is raised +with the skill IDs — pointing you at the skill startup logs. The default is 60 seconds. + +## How do I use the `minicroft` pytest fixture? + +The fixture is registered automatically when ovoscope is installed (via the `pytest11` entry +point). Just declare `skill_ids` on your test class: + +```python +class TestMySkill: + skill_ids = ["my-skill.author"] + + def test_something(self, minicroft): + from ovoscope import End2EndTest + from ovos_bus_client.message import Message + + test = End2EndTest( + minicroft=minicroft, + skill_ids=self.skill_ids, + source_message=Message( + "recognizer_loop:utterance", + {"utterances": ["hello"], "lang": "en-US"}, + {}, + ), + expected_messages=[...], + ) + test.execute() +``` + +The `MiniCroft` is started once per class and stopped in teardown — no `setUp`/`tearDown` +boilerplate needed. + +## How do I test a pipeline plugin (not a skill) like PersonaService? + +Pipeline plugins are loaded by `MiniCroft` automatically via `IntentService`. Access them via: + +```python +mc = get_minicroft([], default_pipeline=PERSONA_PIPELINE) +persona_svc = mc.intents.pipeline_plugins["ovos-persona-pipeline-plugin"] +``` + +Inject mocks directly into the plugin's state before each test: + +```python +def setUp(self): + persona_svc.personas.clear() # remove real solvers (Gemma, Ollama, etc.) + persona_svc.active_persona = None # reset pipeline state + persona_svc.personas["TestBot"] = MockPersona("TestBot", "forty two") +``` + +The `skill_ids=[]` parameter tells MiniCroft to load no skills — only pipeline plugins. +See `ovos-persona/test/end2end/test_persona.py` for a full working example. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..8dcef9c --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 Casimiro Ferreira + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/MAINTENANCE_REPORT.md b/MAINTENANCE_REPORT.md new file mode 100644 index 0000000..e0faa16 --- /dev/null +++ b/MAINTENANCE_REPORT.md @@ -0,0 +1,281 @@ +Last Edit: Claude Sonnet 4.6 - 2026-03-09 - Motive: pytest_plugin: safe teardown with try/finally + mc=None guard to prevent NameError masking get_minicroft failures. + +# Maintenance Report — `ovoscope` + +## [2026-03-09] — pytest_plugin: safe teardown guard + +### Changes +- `ovoscope/pytest_plugin.py` — `minicroft` fixture: initialise `mc = None` before calling + `get_minicroft()`, then wrap `yield mc` in `try/finally` with `if mc is not None: mc.stop()`. + Previously, if `get_minicroft()` raised (e.g. `TimeoutError`), teardown would hit a + `NameError: name 'mc' is not defined`, masking the original exception in pytest output. + +### AI Transparency Report +- **AI Model**: Claude Sonnet 4.6 +- **Actions Taken**: Applied targeted edit to `pytest_plugin.py` lines 57–62. +- **Oversight**: No logic change — only teardown safety. Existing tests unaffected. + +--- + +## [2026-03-09] — pydantic_helpers: typing, docstrings, tests, bug fix, pyproject.toml migration + +### Changes + +**`ovoscope/pydantic_helpers.py`** (new module, renamed from the initial `pydantic.py`): +- Full module docstring with install instructions and usage example. +- `TYPE_CHECKING`-guarded import of `OpenVoiceOSMessage` — type checkers see full annotations; + no `ImportError` at runtime when `ovos-pydantic-models` is absent. +- All three public functions have complete Google-style docstrings with `Args`, `Returns`, + `Raises`, and `Example` blocks; all parameter and return types are annotated. +- **Bug fixed** in `validate_fixture()`: was constructing `raise ValidationError(str, ...)` which + pydantic v2 does not support (it is not user-constructible). Changed to `raise ValueError(...) from exc`. +- **Bug fixed** in `validate_fixture()`: normalisation fallback changed from `""` to `None` so + messages missing both `"type"` and `"message_type"` keys are correctly rejected by pydantic + (an empty string passes `message_type: str = Field(...)` validation silently). + +**`test/unittests/test_pydantic_helpers.py`** (new, 20 tests): + +| Class | Tests | What is covered | +|-------|-------|----------------| +| `TestToBusMessage` | 6 | `msg_type`, data fields, return type, utterance msg, empty context, roundtrip | +| `TestFromBusMessage` | 5 | valid speak, valid utterance, return type, invalid raises `ValidationError`, base model leniency | +| `TestValidateFixture` | 9 | valid fixture, source/expected preserved, missing file, malformed source, malformed expected, error chains `ValidationError`, `message_type` key accepted, empty lists | + +All 20 tests pass. Full suite now 58 tests (38 pre-existing + 20 new), all passing. + +**`pyproject.toml`** — completed migration: +- `build-backend` changed from `setuptools.backends.legacy:build` to `setuptools.build_meta`. +- `dynamic = ["version"]` added; `[tool.setuptools.dynamic] version = {attr = "ovoscope.version.__version__"}`. +- `[project.optional-dependencies] pydantic = ["ovos-pydantic-models>=0.1.0"]` added. +- `setup.py` removed. + +**`ovoscope/version.py`**: +- Added `__version__` computed from `VERSION_MAJOR`, `VERSION_MINOR`, `VERSION_BUILD`, `VERSION_ALPHA` + so `pyproject.toml` dynamic versioning works without `setup.py`. + +**`AUDIT.md`**, **`SUGGESTIONS.md`**, **`FAQ.md`**: +- All module references updated from `ovoscope.pydantic` → `ovoscope.pydantic_helpers`. +- AUDIT unit-test count updated to 58; setup.py fix marked fully complete. +- SUGGESTIONS.md item 6 file path corrected. +- FAQ.md pydantic section import paths corrected. + +### AI Transparency Report +- **AI Model**: Claude Sonnet 4.6 +- **Actions Taken**: Read existing module and all test files; identified two bugs in `validate_fixture()` + via live `python -c` verification; wrote 20 tests and iterated until all pass; migrated pyproject.toml. +- **Oversight**: `validate_fixture()` validates top-level message structure only (`message_type`, + `data`, `context` shape) via `OpenVoiceOSMessage` — it does not validate data-field-level schemas + (e.g. `utterances` type). Use `from_bus_message(msg, SpecificModel)` for field-level validation. + +--- + +## [2026-03-09] — End2end tests written for ovos-persona (11 tests) + +### Tests Created +New `ovos-persona/test/end2end/test_persona.py` — 4 test classes, 11 tests: + +| Class | Tests | Intents/triggers | +|-------|-------|-----------------| +| `TestPersonaList` | 2 | `list_personas.intent` (no personas / 2 personas) | +| `TestPersonaCheck` | 2 | `active_persona.intent` (no active / active) | +| `TestPersonaSummon` | 2 | `summon.intent` (known / unknown persona) | +| `TestPersonaRelease` | 1 | `Release.voc` via `voc_match()` | +| `TestPersonaQuery` | 4 | `ask.intent` explicit / active fallback / error / no-match | + +### Key Patterns Discovered +- Pipeline plugins accessed via `mc.intents.pipeline_plugins["ovos-persona-pipeline-plugin"]` +- Inject mock personas into `persona_svc.personas` dict — bypasses real solver loading +- `setUp()` clears real personas (Gemma etc.) and resets `active_persona = None` +- `skill_ids=[]` — no skills needed; pipeline plugin loads automatically +- `ovos.utterance.handled` data is `{"name": "PersonaService.handle_persona_*"}` — not empty +- `speak` with dialog template checked only by `context={"skill_id": SKILL_ID}` (text varies) +- Direct speaks from query answers checked with `data={"utterance": "forty two"}` + +### AI Transparency Report +- **AI Model**: Claude Sonnet 4.6 +- **Actions Taken**: Traced all message sequences via live FakeBus capture; wrote tests iteratively; all 11 pass. +- **Oversight**: Dialog text assertions omitted — locale-dependent. `test_list_two_personas` relies on dict insertion order (Python 3.7+). + +--- + +## [2026-03-09] — End2end tests written for 6 skills (18 tests) + +### Skills Covered +New `test/end2end/` directories and test files created for: + +| Skill | Test file | Tests | Intents tested | +|-------|-----------|-------|----------------| +| `ovos-skill-hello-world` | `test_hello_world.py` | 4 | HelloWorldIntent (Adapt), Greetings.intent (Padatious), no-match cases | +| `ovos-skill-fallback-unknown` | `test_fallback_unknown.py` | 2 | fallback-low match, Adapt no-match | +| `ovos-skill-naptime` | `test_naptime.py` | 2 | naptime.intent (Padatious), no-match | +| `ovos-skill-volume` | `test_volume.py` | 4 | volume.max.intent, volume.mute.intent, volume.unmute.intent (Padatious), no-match | +| `ovos-skill-count` | `test_count.py` | 3 | count_to_N.intent (Padatious), no-match | +| `ovos-skill-parrot` | `test_parrot.py` | 3 | speak.intent, repeat.tts.intent, no-match | + +### Key Patterns Discovered +- Intents registered with string `"name.intent"` → Padatious; `IntentBuilder(...)` → Adapt +- Skills emitting raw `Message(...)` without `forward()`/`reply()` have `source=None` — use `async_messages` + `ignore_messages` +- Enclosure/LED messages and `add_context`/`configuration.patch` must be in `ignore_messages` +- `message.forward(...)` inherits the post-flip source/dest — do NOT add these to `keep_original_src` + +### AI Transparency Report +- **AI Model**: Claude Sonnet 4.6 +- **Actions Taken**: Read each skill's `__init__.py` and locale files; wrote tests iteratively with test runs to fix pipeline selection, ignore_messages, meta dict content. All 18 tests pass. +- **Oversight**: naptime test skips dialog content check (varies with `listener.wake_word` config). + +--- + +## [2026-03-09] — Config isolation extended: blacklisted_skills + blacklisted_intents + +### Problem Addressed +After pipeline isolation, `test_stop.py` (6 tests) and `test_cancel_plugin.py` (1 test) still failed. +Root cause: `Session.__init__` reads `Configuration()["skills"]["blacklisted_skills"]` and +`Configuration()["intents"]["blacklisted_intents"]` from the live singleton dict cache, same problem +as the pipeline. The user had `skill-ovos-stop.openvoiceos` blacklisted in `~/.config/mycroft/mycroft.conf`. +Additionally, `ovos-skill-count` and `ovos-utterance-plugin-cancel` were not installed in the workspace venv. + +### Changes +- `ovoscope/__init__.py` — `MiniCroft.__init__`: added `_original_blacklisted_skills` and + `_original_blacklisted_intents` state variables. +- `ovoscope/__init__.py` — `MiniCroft.run()`: when `isolate_config=True`, patches + `Configuration()["skills"]["blacklisted_skills"] = []` and + `Configuration()["intents"]["blacklisted_intents"] = []` in the live singleton dict cache. +- `ovoscope/__init__.py` — `MiniCroft.stop()`: restores both lists from saved originals. +- `ovos-core/test/end2end/test_stop.py` — Added `"ovos-hivemind-pipeline-plugin.stop.response"` to + `ignore_messages` in both `TestStopNoSkills` and `TestCountSkills` (hivemind responds to `mycroft.stop`). +- Installed `Skills/ovos-skill-count` and `Transformer plugins/ovos-utterance-plugin-cancel` with `uv pip install --no-deps -e`. + +### Result +27/27 ovos-core end2end tests pass (was 20/27). + +### AI Transparency Report +- **AI Model**: Claude Sonnet 4.6 +- **Actions Taken**: Diagnosed `blacklisted_skills` stale cache issue; extended `run()`/`stop()` patch pattern; + identified hivemind stop response as uncaught message; installed missing plugins. +- **Oversight**: `blacklisted_skills` patch only runs when `isolate_config=True` (same condition as xdg isolation). + +--- + +## [2026-03-09] — Pipeline isolation and reproducible test pipelines + +### Problem Addressed +`MiniCroft.isolate_config=True` cleared `Configuration.xdg_configs` to remove the user's +`~/.config/mycroft/mycroft.conf`, but `SessionManager.default_session` is a singleton +initialised at module import time — it already held the user's pipeline (which could include +`ovos-persona-pipeline-plugin-high`, Ollama, OCP, etc.). Any utterance emitted without an +explicit session in its context would inherit this pipeline and be intercepted by AI plugins +non-deterministically, making tests environment-dependent. + +### Changes +- `ovoscope/__init__.py` — Added pipeline stage constants: + `STOP_PIPELINE`, `CONVERSE_PIPELINE`, `ADAPT_PIPELINE`, `PADATIOUS_PIPELINE`, + `FALLBACK_PIPELINE`, `COMMON_QUERY_PIPELINE`, `PERSONA_PIPELINE`. +- `ovoscope/__init__.py` — Added `DEFAULT_TEST_PIPELINE`: all standard built-in pipeline stages + (stop/converse/adapt/padatious/fallback/common-query), **no** AI/LLM/persona/OCP stages. +- `ovoscope/__init__.py` — `MiniCroft.__init__`: added `default_pipeline: Optional[List[str]]` + parameter (default `DEFAULT_TEST_PIPELINE`). Stored as `_default_pipeline`; original + pipeline stored for restoration. +- `ovoscope/__init__.py` — `MiniCroft.run()`: after `load_plugin_skills()` and before + `set_ready()`, sets `SessionManager.default_session.pipeline = self._default_pipeline` when + not `None`. Setting it here (post-FakeBus-sync) is the correct point — after all init bus + messages have been processed. +- `ovoscope/__init__.py` — `MiniCroft.stop()`: restores `SessionManager.default_session.pipeline` + to its pre-test value, enabling test isolation within a single process. +- `test/unittests/test_minicroft.py` — Added `TestMiniCroftPipelineIsolation` (5 tests): + pipeline overrides default session, restored after stop, `isolate_config=True` uses + `DEFAULT_TEST_PIPELINE`, persona/ollama/m2v absent from `DEFAULT_TEST_PIPELINE`, + `default_pipeline=None` leaves session unchanged. + +### Use Cases Unblocked +- `get_minicroft([])` → `complete_intent_failure` tests now pass without Gemma/persona intercepting. +- `get_minicroft([SKILL_ID], default_pipeline=ADAPT_PIPELINE)` — Adapt-only testing. +- `get_minicroft([SKILL_ID], default_pipeline=ADAPT_PIPELINE + FALLBACK_PIPELINE)` — intent+fallback. +- `get_minicroft([SKILL_ID], default_pipeline=PERSONA_PIPELINE)` — explicitly test persona behaviour. +- `get_minicroft([SKILL_ID], default_pipeline=None)` — use system default (includes all installed plugins). + +### AI Transparency Report +- **AI Model**: Claude Sonnet 4.6 +- **Actions Taken**: Diagnosed root cause (singleton default_session pre-initialised from user config); + added constants + `default_pipeline` param; updated `run()` and `stop()`; added 5 unit tests. +- **Oversight**: `DEFAULT_TEST_PIPELINE` does not include OCP or m2v stages — repos that test + media skills should pass an explicit pipeline including those stages. + +--- + +## [2026-03-08] — Code improvements from SUGGESTIONS.md + +### Changes +- `ovoscope/__init__.py` — `get_minicroft()`: added `max_wait: float = 60` parameter; raises + `TimeoutError` if MiniCroft does not reach READY within the deadline. Return type annotated + as `-> MiniCroft`. +- `ovoscope/__init__.py` — `MiniCroft.inject_message(msg: Message) -> None`: new helper method + for emitting arbitrary messages during a test without going through the utterance pipeline. +- `ovoscope/__init__.py` — `End2EndTest.execute()`: now returns `List[Message]` (was `None`). + Return type annotated. Enables test composition and `assert_spoke()`. +- `ovoscope/__init__.py` — `End2EndTest.assert_spoke(text, lang, timeout)`: new sugar method; + calls `execute()` and asserts a matching `speak` message was emitted. +- `ovoscope/__init__.py` — `End2EndTest.save()`: return type annotated as `-> None`. +- `ovoscope/pytest_plugin.py` (NEW): class-scoped `minicroft` pytest fixture; reads `skill_ids` + from the test class attribute; handles startup and teardown automatically. +- `setup.py`: registered `pytest11` entry point so the fixture is auto-discovered. +- `pyproject.toml` (NEW): `[build-system]`, `[project]`, `[project.entry-points."pytest11"]`, + and `[tool.pytest.ini_options]` tables. `setup.py` retained for dynamic version reading. +- `AUDIT.md`: marked 3 issues as FIXED; updated Next Steps. + +### AI Transparency Report +- **AI Model**: Claude Sonnet 4.6 +- **Actions Taken**: Read `__init__.py` fully; made targeted edits; created `pytest_plugin.py` + and `pyproject.toml`. No logic was changed — only additions and the `return messages` fix. +- **Oversight**: `assert_spoke()` depends on `execute()` returning messages — verify against + a live install. `pyproject.toml` dynamic version section has a TODO comment for when + `version.py` exports `__version__`. + +--- + +## [2026-03-08] — Documentation enrichment and audit deepening + +### Changes +- Created `docs/usage-guide.md` — full tutorial from install to 8 test patterns; references + hello-world canonical examples and real class/method signatures from `ovoscope/__init__.py`. +- Created `docs/ci-integration.md` — directory layout, pytest config, GitHub Actions job + template, fixture management, and CI gotchas. +- Updated `docs/index.md` — added `usage-guide.md` and `ci-integration.md` to navigation table; + added "Who Uses ovoscope" section; added gh-automations cross-reference. +- Replaced `AUDIT.md` — shallow CI-pin findings replaced with 7 evidence-based issues + (CRITICAL/MAJOR/MODERATE/MINOR) all traced to specific lines in `__init__.py`. +- Replaced `SUGGESTIONS.md` — 4 generic stubs replaced with 7 concrete, repo-specific proposals + with code snippets pointing to specific lines. + +### Rationale +The previous docs scaffold was boilerplate with no practical value. This pass enriches docs to the +level where every OVOS repo can adopt ovoscope end-to-end testing without reading source code. + +### Verification +- `ls ovoscope/docs/` shows 7 files (5 pre-existing + `usage-guide.md` + `ci-integration.md`). +- All code examples in `usage-guide.md` use real imports and class names verified from source. +- All `AUDIT.md` findings reference specific file:line evidence. + +### AI Transparency Report +- **AI Model**: Claude Sonnet 4.6 +- **Actions Taken**: Read `ovoscope/__init__.py` (485 lines), `test/test_helloworld.py`, + `ovos-core/test/end2end/test_adapt.py`, and all existing docs; then generated enriched content. +- **Oversight**: Code examples are illustrative but not executed. Verify against live skill install before treating as runnable. + +--- + +## [2026-03-08] — Initial compliance scaffold + +### Changes +- Created `QUICK_FACTS.md` with machine-readable package metadata. +- Created `FAQ.md` with common Q&A. +- Created `MAINTENANCE_REPORT.md` (this file) as the change log. +- Created `SUGGESTIONS.md` with initial improvement proposals. +- Created `docs/index.md` as the documentation entry point (if missing). + +### Rationale +Establishing the required file set mandated by `AGENTS.md` for all active workspace repositories. + +### AI Transparency Report +- **AI Model**: Claude Sonnet 4.6 +- **Actions Taken**: Generated boilerplate compliance scaffold (QUICK_FACTS, FAQ, MAINTENANCE_REPORT, SUGGESTIONS, docs/index). +- **Oversight**: Files were stubs — enriched in the 2026-03-08 documentation pass above. diff --git a/README.md b/README.md index 55bdae0..0373edf 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,15 @@ [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/TigreGotico/ovoscope) +[![PyPI](https://img.shields.io/pypi/v/ovoscope)](https://pypi.org/project/ovoscope/) +[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE) +[![Python](https://img.shields.io/badge/python-3.10%2B-blue)](https://pypi.org/project/ovoscope/) # OvoScope -**OvoScope** is an end-to-end testing framework for [OVOS](https://openvoiceos.org) skills. +**End-to-end testing for [OVOS](https://openvoiceos.org) skills.** -It contains the full core runtime environment using a lightweight in-process `ovos-core`, allowing skill developers to test the full skill message flow, from utterance to intent handling to final bus responses — without launching a full assistant stack. +OvoScope runs a full OVOS Core pipeline in-process using a `FakeBus` — no server, no audio +stack, no network. Load real skill plugins, emit a test utterance, and assert on every bus +message that comes back: type, data, routing context, session state, and message ordering. ![image](https://github.com/user-attachments/assets/10a10ff5-64b7-42fd-86bd-cb6a5db769dd) @@ -14,11 +19,17 @@ It contains the full core runtime environment using a lightweight in-process `ov ## Features -- Simulates OVOS Core messagebus interactions -- Sends test `Message` objects and captures responses -- Verifies message types, data, routing, session handling, and language -- Automatically flips message direction when configured -- Designed to integrate cleanly into `unittest` or `pytest` workflows +| | | +|---|---| +| **Full pipeline** | Runs real intent pipeline plugins (Adapt, Padatious, Fallback, Converse, Common Query) | +| **Isolated** | Config isolation strips user preferences; deterministic `DEFAULT_TEST_PIPELINE` excludes AI/persona/OCP stages | +| **Ordered assertions** | Assert message type, data keys, routing context, and session state in sequence | +| **Recording mode** | Capture a live message sequence and save it as a JSON fixture — no manual construction needed | +| **Multi-turn** | Pass a list of utterances to test full conversational flows | +| **pytest fixture** | `minicroft` class-scoped fixture auto-discovered via the `pytest11` entry point | +| **Inject skills** | `extra_skills={id: SkillClass}` to load inline test skills without a PyPI entry point | +| **Inject messages** | `MiniCroft.inject_message()` to trigger non-utterance handlers (GUI events, timers, API calls) | +| **Typed models** | Optional `ovoscope[pydantic]` bridge to `ovos-pydantic-models` for schema-validated messages | --- @@ -26,46 +37,134 @@ It contains the full core runtime environment using a lightweight in-process `ov ```bash pip install ovoscope -```` +``` ---- +With optional typed message model support: + +```bash +pip install ovoscope[pydantic] +``` -## Usage Example +--- -Testing scenario of complete intent failure (no skills installed) +## Quick Start ```python -from ovoscope import End2EndTest +import unittest from ovos_bus_client.message import Message from ovos_bus_client.session import Session +from ovoscope import End2EndTest + +SKILL_ID = "ovos-skill-hello-world.openvoiceos" + +session = Session("test-session") +utterance = Message( + "recognizer_loop:utterance", + {"utterances": ["hello world"], "lang": "en-US"}, + {"session": session.serialize(), "source": "A", "destination": "B"}, +) + +class TestHelloWorld(unittest.TestCase): + def test_intent_match(self): + End2EndTest( + skill_ids=[SKILL_ID], + source_message=utterance, + expected_messages=[ + utterance, + Message(f"{SKILL_ID}.activate", context={"skill_id": SKILL_ID}), + Message(f"{SKILL_ID}:HelloWorldIntent", + data={"utterance": "hello world"}, context={"skill_id": SKILL_ID}), + Message("mycroft.skill.handler.start", context={"skill_id": SKILL_ID}), + Message("speak", data={"lang": "en-US"}, context={"skill_id": SKILL_ID}), + Message("mycroft.skill.handler.complete", context={"skill_id": SKILL_ID}), + Message("ovos.utterance.handled", context={"skill_id": SKILL_ID}), + ], + ).execute(timeout=10) +``` + +Only keys you specify in `expected.data` and `expected.context` are checked — extra keys in the +received message are ignored. + +--- + +## Recording Mode + +Don't know the exact message sequence yet? Record it from a live run: +```python +from ovoscope import End2EndTest -session = Session("123") # change lang, pipeline, etc. as needed -message = Message("recognizer_loop:utterance", - {"utterances": ["hello world"]}, - {"session": session.serialize(), "source": "A", "destination": "B"}) - -test = End2EndTest( - skill_ids=[], - source_message=message, - expected_messages=[ - message, - Message("mycroft.audio.play_sound", {"uri": "snd/error.mp3"}), - Message("complete_intent_failure", {}), - Message("ovos.utterance.handled", {}), - ] +test = End2EndTest.from_message( + message=utterance, + skill_ids=[SKILL_ID], + timeout=20, ) +test.save("tests/fixtures/hello_world.json") # anonymises location data by default +``` + +Replay in CI: + +```python +End2EndTest.from_path("tests/fixtures/hello_world.json").execute(timeout=10) +``` + +--- + +## pytest Fixture + +The `minicroft` class-scoped fixture is auto-registered when ovoscope is installed. +No `setUp`/`tearDown` boilerplate needed: + +```python +class TestMySkill: + skill_ids = ["my-skill.author"] + + def test_something(self, minicroft): + End2EndTest( + minicroft=minicroft, + skill_ids=self.skill_ids, + source_message=utterance, + expected_messages=[...], + ).execute(timeout=10) +``` + +--- + +## Pipeline Control + +OvoScope exposes composable pipeline stage lists so tests are deterministic regardless of which +AI plugins are installed on the host: -test.execute() +```python +from ovoscope import ADAPT_PIPELINE, PADATIOUS_PIPELINE, FALLBACK_PIPELINE, PERSONA_PIPELINE + +# Adapt only — fastest +mc = get_minicroft([SKILL_ID], default_pipeline=ADAPT_PIPELINE) + +# Full intent chain +mc = get_minicroft([SKILL_ID], + default_pipeline=ADAPT_PIPELINE + PADATIOUS_PIPELINE + FALLBACK_PIPELINE) + +# Opt in to persona for AI testing +mc = get_minicroft([SKILL_ID], default_pipeline=DEFAULT_TEST_PIPELINE + PERSONA_PIPELINE) ``` +`DEFAULT_TEST_PIPELINE` (the default when `isolate_config=True`) includes all standard built-in +stages and deliberately excludes persona, Ollama, OCP, and m2v plugins. + --- -## Why OvoScope? +## Documentation -* Lightweight: No need to launch a full messagebus or audio stack -* Isolated: Use `FakeBus` and `MiniCroft` for fast, reliable test environments -* Flexible: Works with any skill that conforms to OVOS skill loading +| Document | | +|---|---| +| [docs/usage-guide.md](docs/usage-guide.md) | **Start here** — 8 test patterns with full worked examples | +| [docs/ci-integration.md](docs/ci-integration.md) | Wiring ovoscope into GitHub Actions | +| [docs/minicroft.md](docs/minicroft.md) | `MiniCroft` and `get_minicroft()` reference | +| [docs/capture-session.md](docs/capture-session.md) | `CaptureSession` internals | +| [docs/end2end-test.md](docs/end2end-test.md) | `End2EndTest` full parameter reference | +| [docs/pydantic-integration.md](docs/pydantic-integration.md) | Typed message models with `ovos-pydantic-models` | +| [FAQ.md](FAQ.md) | Common questions and gotchas | --- @@ -78,3 +177,22 @@ test.execute() ## Contributing PRs are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines. + +--- + +## AI Disclosure + +Parts of this project are developed with the assistance of AI tools. +In the interest of transparency, two files are maintained as a public record of AI involvement: + +- **[FAQ.md](FAQ.md)** — Frequently asked questions that emerged from real development sessions, + including design rationale, gotchas, and usage patterns. Many entries were authored or + refined with AI assistance during the process of building and testing this framework. + +- **[MAINTENANCE_REPORT.md](MAINTENANCE_REPORT.md)** — A chronological log of changes made to + this repository. Each entry records what was changed, why, which AI model was involved, what + actions it took, and what human oversight was applied. This log is updated after every + significant AI-assisted session. + +These files are intentionally published so that contributors and users can understand how the +project evolves and where AI assistance has been applied. diff --git a/docs/capture-session.md b/docs/capture-session.md new file mode 100644 index 0000000..a0469e3 --- /dev/null +++ b/docs/capture-session.md @@ -0,0 +1,122 @@ +# CaptureSession + +`CaptureSession` subscribes to all messages on the `FakeBus` and records them during a single test interaction. It handles synchronous responses (ordered, from the intent pipeline) and asynchronous responses (from external threads, unordered). + +## Class: `CaptureSession` + +```python +from ovoscope import CaptureSession +``` + +A `dataclass` that wraps a `MiniCroft` and manages message collection for one test interaction. + +### Fields + +| Field | Type | Default | Description | +|---|---|---|---| +| `minicroft` | `MiniCroft` | required | The runtime to capture from | +| `responses` | `list[Message]` | `[]` | Ordered synchronous messages captured | +| `async_responses` | `list[Message]` | `[]` | Async messages (arrive from external threads, unordered) | +| `eof_msgs` | `list[str]` | `["ovos.utterance.handled"]` | Message types that signal end of interaction | +| `ignore_messages` | `list[str]` | `["ovos.skills.settings_changed"]` | Message types to discard | +| `async_messages` | `list[str]` | `[]` | Message types to route to `async_responses` instead | +| `done` | `threading.Event` | — | Set when an EOF message is received | + +### Methods + +#### `capture(source_message, timeout=20)` + +Emits `source_message` on the bus and waits for an EOF message (or timeout). Subsequent calls on the same session accumulate into `responses`. + +```python +capture = CaptureSession(croft, eof_msgs=["ovos.utterance.handled"]) +capture.capture(utterance_msg, timeout=10) +``` + +#### `finish() -> list[Message]` + +Signals end of capture, unsubscribes from the bus, and returns the collected `responses`. + +--- + +## Message Routing + +Messages are sorted into three buckets on arrival: + +``` +incoming message + │ + ├─ msg_type in async_messages? → async_responses (unordered) + ├─ msg_type in ignore_messages? → discarded + └─ otherwise → responses (ordered) + +eof_msgs trigger done.set() → capture.wait() returns +``` + +### Default ignored messages + +```python +DEFAULT_IGNORED = ["ovos.skills.settings_changed"] +``` + +### Default GUI ignored (when `ignore_gui=True` on `End2EndTest`) + +```python +GUI_IGNORED = [ + "gui.clear.namespace", + "gui.value.set", + "mycroft.gui.screen.close", + "gui.page.show", +] +``` + +These are excluded by default because GUI namespace updates are frequent and rarely the focus of skill logic tests. + +--- + +## Direct Usage + +`CaptureSession` can be used without `End2EndTest` for lower-level scenarios: + +```python +from ovoscope import get_minicroft, CaptureSession +from ovos_bus_client.message import Message +from ovos_bus_client.session import Session + +croft = get_minicroft(["skill-weather.openvoiceos"]) + +session = Session("test-123") +utterance = Message( + "recognizer_loop:utterance", + {"utterances": ["what is the weather?"], "lang": "en-us"}, + {"session": session.serialize(), "source": "A", "destination": "B"}, +) + +capture = CaptureSession(croft) +capture.capture(utterance, timeout=15) +messages = capture.finish() + +for msg in messages: + print(msg.msg_type, msg.data) + +croft.stop() +``` + +--- + +## Multi-turn Capture + +Emit multiple source messages into the same `CaptureSession` to simulate a multi-turn conversation. The session from the last received message is propagated into each subsequent source message: + +```python +capture = CaptureSession(croft, eof_msgs=["ovos.utterance.handled"]) + +capture.capture(first_utterance, timeout=10) +# inject session from last received message into follow-up +follow_up.context["session"] = capture.responses[-1].context["session"] +capture.capture(follow_up, timeout=10) + +all_messages = capture.finish() +``` + +`End2EndTest` does this automatically when `source_message` is a list. diff --git a/docs/ci-integration.md b/docs/ci-integration.md new file mode 100644 index 0000000..1281dc4 --- /dev/null +++ b/docs/ci-integration.md @@ -0,0 +1,245 @@ +Last Edit: Claude Sonnet 4.6 - 2026-03-08 - Motive: CI integration guide for gh-automations and standalone use. + +# CI Integration — ovoscope + +This document explains how to wire ovoscope end-to-end tests into a repo's CI pipeline using +`gh-automations` reusable workflows, and how to structure test files and fixtures. + +--- + +## Directory Layout + +The workspace convention is: + +``` +my-skill-repo/ +├── test/ +│ └── end2end/ +│ ├── test_intent_match.py # TestCase classes using ovoscope +│ ├── test_session_state.py +│ └── fixtures/ +│ ├── hello_world_adapt.json # committed fixture files (optional) +│ └── hello_world_padatious.json +├── setup.py (or pyproject.toml) +└── ... +``` + +Separate `end2end/` from `unittests/` so they can be run independently — end2end tests are +slower (they spin up a MiniCroft) and may require extra dependencies. + +--- + +## pytest / unittest Configuration + +### Using `pyproject.toml` + +```toml +[tool.pytest.ini_options] +testpaths = ["test"] + +# Run only unit tests (fast): +# pytest test/unittests/ + +# Run only end2end tests (slow, requires skill installed): +# pytest test/end2end/ +``` + +### Using `pytest.ini` + +```ini +[pytest] +testpaths = test +``` + +End2end tests are standard `unittest.TestCase` subclasses and work with both `pytest` and plain +`python -m unittest discover`. + +--- + +## Install Dependencies in CI + +End2end tests need ovoscope **and** all skills under test installed. Add an install step before +running tests: + +```bash +pip install ovoscope +pip install -e . # install the skill from source (editable) +``` + +Or if testing multiple skills together: + +```bash +pip install ovoscope \ + ovos-skill-hello-world \ + ovos-skill-weather +``` + +Verify the skills are discoverable before running: + +```bash +python -c " +from ovos_plugin_manager.skills import find_skill_plugins +plugins = list(find_skill_plugins()) +print('Found skills:', plugins) +assert 'ovos-skill-hello-world.openvoiceos' in plugins +" +``` + +--- + +## Fixture JSON Files + +Fixture files generated by `End2EndTest.save()` (see [usage-guide.md](usage-guide.md) Pattern 4) +contain the expected message sequence serialised as JSON. + +**When to commit fixtures:** + +- Commit fixtures that test stable, deterministic interactions (e.g., a specific dialog line). +- Do NOT commit fixtures where the `speak` utterance varies randomly — either omit the + `utterance` key from expected data or use manual assertion instead. +- Always generate fixtures with `anonymize=True` (the default) — this strips real location data. + +**`.gitignore` pattern** (if you generate fixtures locally but don't want to commit them): + +```gitignore +test/end2end/fixtures/*.json +``` + +Or selectively ignore only generated/recording artifacts: + +```gitignore +test/end2end/fixtures/recorded_*.json +``` + +--- + +## GitHub Actions — End2End Job + +Add an end2end job to your `release_workflow.yml` or a dedicated workflow. This example follows +the `gh-automations` conventions used across all 203+ OVOS repos: + +```yaml +# .github/workflows/release_workflow.yml +name: Release workflow + +on: + pull_request: + types: [closed] + branches: [dev] + workflow_dispatch: + +jobs: + build_tests: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.11' + - name: Install dependencies + run: | + pip install build pytest + pip install ovoscope + pip install -e . + - name: Run unit tests + run: pytest test/unittests/ -v + - name: Run end2end tests + run: pytest test/end2end/ -v --timeout=60 + + publish_alpha: + needs: build_tests + if: github.event.pull_request.merged == true || github.event_name == 'workflow_dispatch' + uses: TigreGotico/gh-automations/.github/workflows/publish-alpha.yml@master + with: + propose_release: true + secrets: inherit +``` + +The `build_tests` job runs before `publish_alpha` — a failing end2end test blocks the release. + +--- + +## Standalone End2End Workflow + +If your repo only needs end2end tests (no release automation), use a simpler workflow: + +```yaml +# .github/workflows/end2end.yml +name: End2End Tests + +on: + push: + branches: [dev, master] + pull_request: + branches: [dev] + +jobs: + end2end: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.11' + - name: Install + run: | + pip install ovoscope pytest + pip install -e . + - name: Test + run: pytest test/end2end/ -v --timeout=60 +``` + +--- + +## Known CI Gotchas + +### Skill plugin not found on PATH + +**Symptom**: `get_minicroft()` hangs or `find_skill_plugins()` returns an empty list. + +**Cause**: The skill was not installed in editable mode (`pip install -e .`) or the entry point +was not registered. + +**Fix**: Always install the skill package in the same environment as ovoscope: + +```bash +pip install -e . # registers entry points +pip install ovoscope +``` + +### Missing `.venv` in CI + +If you use `uv` locally, your `.venv` is not present in CI. Use `pip` directly in CI or add a +`uv pip install` step. Do not rely on `.venv` being pre-activated. + +### MiniCroft hangs for >30 seconds + +Padatious intent training can be slow on a cold CI runner. Set a generous `--timeout` in pytest +and pass `timeout=30` (or higher) to `test.execute()`. + +### Flaky tests from session ID collisions + +Each test that uses `Session("same-id")` shares session state with other tests using the same +session ID. Use unique session IDs per test class, or generate them: + +```python +import uuid +session = Session(str(uuid.uuid4())) +``` + +### GUI messages causing assertion failures + +By default `ignore_gui=True` strips GUI namespace messages from the captured sequence. If you see +unexpected messages related to `gui.*`, check whether a skill emits GUI messages unconditionally +and whether your `expected_messages` list accounts for them. + +--- + +## See Also + +- [usage-guide.md](usage-guide.md) — tutorial walkthrough with all patterns +- [gh-automations/docs/workflow-reference.md](../../gh-automations/docs/workflow-reference.md) — full reusable workflow reference +- [gh-automations/docs/repo-setup.md](../../gh-automations/docs/repo-setup.md) — per-repo workflow setup +- Canonical examples: `Skills/ovos-skill-hello-world/test/test_helloworld.py` +- Core examples: `ovos-core/test/end2end/` diff --git a/docs/end2end-test.md b/docs/end2end-test.md new file mode 100644 index 0000000..0b1985e --- /dev/null +++ b/docs/end2end-test.md @@ -0,0 +1,259 @@ +# End2EndTest + +`End2EndTest` is the primary API. It wires together `MiniCroft`, `CaptureSession`, and all assertion logic into a single declarative test object. + +## Class: `End2EndTest` + +```python +from ovoscope import End2EndTest +``` + +A `dataclass`. Configure once, call `.execute()` to run. + +--- + +## Fields + +### Core + +| Field | Type | Default | Description | +|---|---|---|---| +| `skill_ids` | `list[str]` | required | Skill plugin IDs to load | +| `source_message` | `Message \| list[Message]` | required | Input message(s). Standardized to list on init. | +| `expected_messages` | `list[Message]` | required | Ordered expected response sequence | +| `expected_boot_sequence` | `list[Message]` | `[]` | Startup messages to validate before running | + +### Message Filtering + +| Field | Type | Default | Description | +|---|---|---|---| +| `eof_msgs` | `list[str]` | `["ovos.utterance.handled"]` | Message types that end capture | +| `ignore_messages` | `list[str]` | `["ovos.skills.settings_changed"]` | Message types to discard | +| `ignore_gui` | `bool` | `True` | Discard GUI namespace messages | +| `async_messages` | `list[str]` | `[]` | Message types arriving from external threads (collected separately, unordered) | + +### Routing Tracking + +| Field | Type | Default | Description | +|---|---|---|---| +| `flip_points` | `list[str]` | `[]` | After receiving this message type, swap expected source↔destination | +| `entry_points` | `list[str]` | `["recognizer_loop:utterance"]` | On this message type, extract new expected source/destination from the received message context (reversed) | +| `keep_original_src` | `list[str]` | `["ovos.skills.fallback.ping"]` | For these message types, always compare against the original source/destination | + +### Active Skill Tracking + +| Field | Type | Default | Description | +|---|---|---|---| +| `inject_active` | `list[str]` | `[]` | Pre-activate these skill IDs before the test runs (modifies session) | +| `disallow_extra_active_skills` | `bool` | `False` | Fail if any unexpected skill is active | +| `activation_points` | `list[str]` | `[]` | After this message type, `context.skill_id` must remain active | +| `deactivation_points` | `list[str]` | `["intent.service.skills.deactivate"]` | After this message type, `context.skill_id` must NOT be active | +| `final_session` | `Session \| None` | `None` | If set, compare last-message session against this | + +### Sub-test Toggles + +All default to `True`. Set to `False` to skip individual assertion categories: + +| Flag | What it checks | +|---|---| +| `test_message_number` | `len(received) == len(expected)` | +| `test_async_messages` | All `async_messages` types were received | +| `test_async_message_number` | Async message count matches | +| `test_boot_sequence` | Boot messages match `expected_boot_sequence` | +| `test_msg_type` | Each `msg_type` matches | +| `test_msg_data` | Each expected data key/value is present in received | +| `test_msg_context` | Each expected context key/value is present in received | +| `test_active_skills` | Active skills in session match expectations | +| `test_routing` | `context.source` and `context.destination` match | +| `test_final_session` | Final session matches `final_session` | + +### Internals + +| Field | Default | Description | +|---|---|---| +| `verbose` | `True` | Print pass/fail for each assertion | +| `minicroft` | `None` | Provide an existing `MiniCroft` to reuse across tests | +| `managed` | `False` | Set automatically; if `True`, `execute()` stops the minicroft after running | + +--- + +## `execute(timeout=30)` + +Runs the test. Raises `AssertionError` on the first failing assertion. + +If `minicroft` is `None`, creates one automatically (managed mode — stops it after the test). To run multiple tests against the same loaded skills, pass your own `MiniCroft`: + +```python +from ovoscope import get_minicroft, End2EndTest + +croft = get_minicroft(["skill-weather.openvoiceos"]) + +test1 = End2EndTest(skill_ids=[], source_message=msg1, expected_messages=[...], minicroft=croft) +test2 = End2EndTest(skill_ids=[], source_message=msg2, expected_messages=[...], minicroft=croft) + +test1.execute() +test2.execute() + +croft.stop() +``` + +--- + +## Assertion Logic Detail + +### Message count + +``` +assert len(expected_messages) == len(received_messages) +``` + +On failure, prints the first differing message type for debugging. + +### Per-message assertions + +For each `(expected, received)` pair: + +**Type check:** +```python +assert expected.msg_type == received.msg_type +``` + +**Data check** — subset match (expected keys must be present with matching values): +```python +for k, v in expected.data.items(): + assert received.data[k] == v +``` + +**Context check** — same subset pattern: +```python +for k, v in expected.context.items(): + assert received.context[k] == v +``` + +**Routing check** — tracks rolling expected source/destination: + +- Starts from `source_message[0].context["source"]` and `["destination"]` +- On `entry_points` message: flips (`e_src, e_dst = r_dst, r_src`) — the reply comes back the other way +- On `flip_points` message: updates expected from received, then swaps +- `keep_original_src` always uses the original, regardless of flips + +### Active skill tracking + +Session is read from each received message's context. For messages after an `activation_point`, `context.skill_id` is added to the expected active set. For messages after a `deactivation_point`, it's removed. The test then verifies all expected active skill IDs appear in the session. + +### Final session check + +Compares `active_skills`, `lang`, `pipeline`, `system_unit`, `date_format`, `time_format`, `site_id`, `session_id`, `blacklisted_skills`, `blacklisted_intents` from the session in the last received message against `final_session`. + +--- + +## Recording Mode: `from_message()` + +Runs a live capture against real skills and returns a ready-to-use `End2EndTest` with the captured messages as `expected_messages`. + +```python +test = End2EndTest.from_message( + message=utterance, # Message or list[Message] + skill_ids=["skill-weather.openvoiceos"], + eof_msgs=None, # use defaults + flip_points=None, + ignore_messages=None, + async_messages=None, + timeout=20, +) +test.save("tests/weather_test.json") +``` + +Use this to bootstrap test fixtures from real behavior, then commit the JSON and replay in CI. + +--- + +## Serialization + +### `serialize(anonymize=True) -> dict` + +Returns a JSON-serializable dict. With `anonymize=True`, scrubs location data from sessions. + +### `save(path, anonymize=True)` + +Writes the serialized test to a JSON file. + +### `End2EndTest.deserialize(data) -> End2EndTest` + +Loads from a dict or JSON string. + +### `End2EndTest.from_path(path) -> End2EndTest` + +Loads from a JSON file path. + +--- + +## Examples + +### Testing complete intent failure (no skills) + +```python +from ovoscope import End2EndTest +from ovos_bus_client.message import Message +from ovos_bus_client.session import Session + +session = Session("test-123") +utterance = Message( + "recognizer_loop:utterance", + {"utterances": ["zorbax flibnork"], "lang": "en-us"}, + {"session": session.serialize(), "source": "A", "destination": "B"}, +) + +End2EndTest( + skill_ids=[], + source_message=utterance, + expected_messages=[ + utterance, + Message("mycroft.audio.play_sound", {"uri": "snd/error.mp3"}), + Message("complete_intent_failure", {}), + Message("ovos.utterance.handled", {}), + ], +).execute() +``` + +### Testing a skill with pre-activated converse + +```python +End2EndTest( + skill_ids=["skill-timer.openvoiceos"], + source_message=utterance, + expected_messages=[...], + inject_active=["skill-timer.openvoiceos"], # timer already in converse + activation_points=["speak"], # stays active after speaking + deactivation_points=["intent.service.skills.deactivate"], +).execute() +``` + +### Multi-turn test + +```python +End2EndTest( + skill_ids=["skill-weather.openvoiceos"], + source_message=[first_utterance, follow_up], # two turns + expected_messages=[...all messages from both turns...], + eof_msgs=["ovos.utterance.handled"], # reset between turns +).execute() +``` + +### Reusing MiniCroft across tests + +```python +from ovoscope import get_minicroft, End2EndTest + +croft = get_minicroft(["skill-weather.openvoiceos"]) +try: + for utterance, expected in test_cases: + End2EndTest( + skill_ids=[], + source_message=utterance, + expected_messages=expected, + minicroft=croft, + ).execute() +finally: + croft.stop() +``` diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 0000000..9f9bb09 --- /dev/null +++ b/docs/index.md @@ -0,0 +1,136 @@ +Last Edit: Claude Sonnet 4.6 - 2026-03-08 - Motive: Added usage-guide, ci-integration, Who Uses, and Cross-References sections. + +# OvoScope Documentation + +**OvoScope** is an end-to-end testing framework for OVOS skills. It runs a lightweight in-process OVOS Core using a `FakeBus`, loads real skill plugins, and captures every bus message produced in response to a test utterance — then asserts against the captured sequence. + +## Contents + +| Document | Description | +|---|---| +| [usage-guide.md](usage-guide.md) | **Start here** — tutorial: from zero to your first end2end test | +| [ci-integration.md](ci-integration.md) | Wiring ovoscope into GitHub Actions CI with gh-automations | +| [minicroft.md](minicroft.md) | `MiniCroft` — in-process skill runtime | +| [capture-session.md](capture-session.md) | `CaptureSession` — message capture during a test | +| [end2end-test.md](end2end-test.md) | `End2EndTest` — full test runner reference | +| [pydantic-integration.md](pydantic-integration.md) | Using `ovos-pydantic-models` with OvoScope | + +## Conceptual Model + +``` +Test FakeBus +──── ─────── +source_message ──emit──► [MiniCroft + loaded skills] + │ + ◄──capture────┤ all emitted messages + │ until EOF message + ▼ + assert against expected_messages[] +``` + +The key insight is that OVOS skill behaviour is fully observable through bus messages. OvoScope intercepts every message on the in-process `FakeBus`, so the entire skill interaction — intent matching, converse, fallback, speak, session changes — is captured and verifiable. + +## Quick Start + +```bash +pip install ovoscope +``` + +```python +from ovoscope import End2EndTest +from ovos_bus_client.message import Message +from ovos_bus_client.session import Session + +session = Session("test-123") +utterance = Message( + "recognizer_loop:utterance", + {"utterances": ["hello world"], "lang": "en-us"}, + {"session": session.serialize(), "source": "A", "destination": "B"}, +) + +test = End2EndTest( + skill_ids=["skill-hello-world.openvoiceos"], + source_message=utterance, + expected_messages=[ + utterance, + Message("speak", {"utterance": "Hello!"}), + Message("ovos.utterance.handled", {}), + ], +) +test.execute() +``` + +## Recording Mode + +Instead of writing expected messages by hand, record them from a live run: + +```python +test = End2EndTest.from_message( + message=utterance, + skill_ids=["skill-hello-world.openvoiceos"], +) +test.save("tests/hello_world.json") +``` + +Then replay later: + +```python +test = End2EndTest.from_path("tests/hello_world.json") +test.execute() +``` + +## Public API + +All primary classes and the factory function are importable from `ovoscope` directly: + +```python +from ovoscope import ( + MiniCroft, # in-process skill runtime + get_minicroft, # factory: create + wait for READY + CaptureSession, # message recorder for a single interaction + End2EndTest, # declarative test runner +) +``` + +Type aliases also exported: + +```python +from ovoscope import SerializedMessage, SerializedTest +``` + +## Dependencies + +| Package | Role | +|---|---| +| `ovos-core >= 2.0.4a2` | `SkillManager`, `IntentService`, `FakeBus`, `SessionManager` | + +Python 3.10+ is required (uses `match`/structural typing in ovos-core). + +## What OvoScope Does NOT Do + +- Does not start a real WebSocket MessageBus server — uses `FakeBus` (in-process pub/sub). +- Does not load PHAL plugins or the audio service — only skills and the intent pipeline. +- Does not test GUI rendering — GUI namespace messages are ignored by default (`ignore_gui=True`). +- Does not test STT or TTS — operates at the `recognizer_loop:utterance` level. + +## Quick Links + +| Resource | Path | +|---|---| +| Common questions | [`../FAQ.md`](../FAQ.md) | +| Change log | [`../CHANGELOG.md`](../CHANGELOG.md) | + +## Who Uses ovoscope + +| Repo | Test location | Notes | +|---|---|---| +| `ovos-core` | `ovos-core/test/end2end/` | Adapt + Padatious pipeline tests, blacklist tests | +| `Skills/ovos-skill-hello-world` | `Skills/ovos-skill-hello-world/test/test_helloworld.py` | Canonical example — Adapt + Padatious match + no-match | + +## Cross-References + +- [ovos-core](https://github.com/OpenVoiceOS/ovos-core) — `SkillManager`, `IntentService` (runtime dependency) +- [ovos-utils](https://github.com/OpenVoiceOS/ovos-utils) — `FakeBus`, `ProcessState` +- [ovos-workshop](https://github.com/OpenVoiceOS/ovos-workshop) — `OVOSSkill` base class +- [ovos-bus-client](https://github.com/OpenVoiceOS/ovos-bus-client) — `Message`, `Session`, `SessionManager` +- [ovos-pydantic-models](https://github.com/OpenVoiceOS/ovos-pydantic-models) — optional typed message models (see [pydantic-integration.md](pydantic-integration.md)) diff --git a/docs/minicroft.md b/docs/minicroft.md new file mode 100644 index 0000000..99dcf25 --- /dev/null +++ b/docs/minicroft.md @@ -0,0 +1,102 @@ +# MiniCroft + +`MiniCroft` is a minimal, in-process OVOS Core that loads real skill plugins and runs the full intent pipeline on a `FakeBus`. It is the execution engine behind every OvoScope test. + +## Class: `MiniCroft` + +```python +from ovoscope import MiniCroft +``` + +Subclass of `ovos_core.skill_manager.SkillManager`. Replaces the real WebSocket bus with `FakeBus`, disables components not needed for testing, and only loads the skills you specify. + +### Constructor + +```python +MiniCroft( + skill_ids: list[str], + enable_installer: bool = False, + enable_intent_service: bool = True, + enable_event_scheduler: bool = False, + enable_file_watcher: bool = False, + enable_skill_api: bool = True, + extra_skills: dict[str, OVOSSkill] | None = None, + *args, **kwargs, +) +``` + +| Parameter | Default | Description | +|---|---|---| +| `skill_ids` | required | Skill plugin IDs to load (from installed entry points) | +| `enable_installer` | `False` | Enable the runtime pip installer service | +| `enable_intent_service` | `True` | Enable intent matching pipeline | +| `enable_event_scheduler` | `False` | Enable scheduled event service | +| `enable_file_watcher` | `False` | Enable settings file watcher | +| `enable_skill_api` | `True` | Enable skill API exposure | +| `extra_skills` | `None` | Inject skill instances directly (useful for testing a skill class before packaging) | + +### Key attributes + +| Attribute | Type | Description | +|---|---|---| +| `bus` | `FakeBus` | The in-process message bus | +| `boot_messages` | `list[Message]` | All messages captured during startup | +| `status` | `ProcessState` | Current lifecycle state | + +### `MiniCroft.run()` + +Loads plugins and marks the runtime as ready. Called internally by `start()`. Does not block — returns after all skills are loaded. + +### `MiniCroft.stop()` + +Shuts down skills and closes the bus. + +--- + +## Factory: `get_minicroft()` + +```python +from ovoscope import get_minicroft + +croft = get_minicroft( + skill_ids: list[str] | str, + **kwargs # forwarded to MiniCroft constructor +) +``` + +Creates, starts, and waits for a `MiniCroft` to reach `READY` state. Returns the ready instance. + +```python +croft = get_minicroft(["skill-weather.openvoiceos", "skill-timer.openvoiceos"]) +# croft.status.state == ProcessState.READY +``` + +--- + +## Injecting Skills Under Test + +To test a skill class that isn't installed as a plugin, inject it directly via `extra_skills`: + +```python +from my_skill import MySkill + +croft = get_minicroft( + skill_ids=[], + extra_skills={"my-skill.test": MySkill}, +) +``` + +The skill ID key must match what the skill would normally register under. + +--- + +## Boot Sequence + +On startup, MiniCroft captures all messages emitted during skill loading into `boot_messages`. These can be asserted in `End2EndTest.expected_boot_sequence`. The typical boot sequence includes: + +1. `mycroft.skills.train` — intent pipeline training request +2. `mycroft.skills.initialized` — skills initialized +3. `mycroft.skills.ready` — skills service ready +4. `mycroft.ready` — all core services ready + +Skills that participate in `converse` or `fallback` registration also emit messages during boot (e.g. `ovos.skills.fallback.register`). diff --git a/docs/pydantic-integration.md b/docs/pydantic-integration.md new file mode 100644 index 0000000..3241118 --- /dev/null +++ b/docs/pydantic-integration.md @@ -0,0 +1,252 @@ +# OvoScope + ovos-pydantic-models Integration + +OvoScope currently operates on untyped `ovos_bus_client.message.Message` objects — dicts with string keys. `ovos-pydantic-models` provides typed Pydantic v2 models for every OVOS message type. This document describes how they can be used together and what a deeper integration could look like. + +--- + +## The Problem Today + +Writing test fixtures by hand is verbose and error-prone: + +```python +# untyped — no validation, any typo silently passes +expected = Message("recognizer_loop:utterance", {"utterances": ["hello"], "lang": "en-us"}, {}) +``` + +`Message` is a raw dict wrapper. There is no validation of field names, no type checking, and no autocomplete. A typo in a field name (`"utterance"` instead of `"utterances"`) silently produces a wrong test. + +--- + +## Bridge: Converting Between Message and Pydantic + +`ovos_bus_client.message.Message` and `OpenVoiceOSMessage` share the same three-field structure (`type`/`message_type`, `data`, `context`). A bridge needs only two functions: + +```python +from ovos_bus_client.message import Message +from ovos_pydantic_models.message import OpenVoiceOSMessage + + +def to_bus_message(pydantic_msg: OpenVoiceOSMessage) -> Message: + """Convert a pydantic model to an ovos-bus-client Message.""" + d = pydantic_msg.model_dump() + return Message( + d["message_type"], + d["data"], + d["context"], + ) + + +def from_bus_message(bus_msg: Message, model: type[OpenVoiceOSMessage]) -> OpenVoiceOSMessage: + """Parse a received bus Message into a typed pydantic model.""" + return model.model_validate({ + "message_type": bus_msg.msg_type, + "data": bus_msg.data, + "context": bus_msg.context, + }) +``` + +These two functions are all that's needed to use typed models with OvoScope today, without any changes to OvoScope itself. + +--- + +## Usage Pattern 1: Typed Source Messages + +Use pydantic models to construct source messages, then convert: + +```python +from ovoscope import End2EndTest +from ovos_bus_client.message import Message +from ovos_bus_client.session import Session +from ovos_pydantic_models import RecognizerLoopUtteranceMessage, RecognizerLoopUtteranceData + +# typed construction — validated at instantiation +utterance_model = RecognizerLoopUtteranceMessage( + data=RecognizerLoopUtteranceData(utterances=["what is the weather?"], lang="en-us"), +) + +session = Session("test-123") +bus_msg = to_bus_message(utterance_model) +bus_msg.context["session"] = session.serialize() +bus_msg.context["source"] = "A" +bus_msg.context["destination"] = "B" + +End2EndTest( + skill_ids=["skill-weather.openvoiceos"], + source_message=bus_msg, + expected_messages=[...], +).execute() +``` + +Benefit: `RecognizerLoopUtteranceData` validates that `utterances` is a `list[str]` and `lang` is a string. A missing `utterances` field raises `ValidationError` at construction time, not a silent wrong test. + +--- + +## Usage Pattern 2: Typed Expected Messages + +Use pydantic models to build expected messages. This documents intent and catches field-name mistakes: + +```python +from ovos_pydantic_models import SpeakMessage, SpeakData, CompleteIntentFailureMessage, CompleteIntentFailureData + +expected = [ + to_bus_message(RecognizerLoopUtteranceMessage( + data=RecognizerLoopUtteranceData(utterances=["what is the weather?"], lang="en-us") + )), + to_bus_message(SpeakMessage( + data=SpeakData(utterance="It is 22 degrees in London.") + )), + to_bus_message(OvosUtteranceHandledMessage()), +] + +End2EndTest( + skill_ids=["skill-weather.openvoiceos"], + source_message=bus_msg, + expected_messages=expected, +).execute() +``` + +Because `End2EndTest` checks only the data keys you specify (subset match), you can omit optional fields in expected messages — this works the same as before, but field names are now validated at Python parse time. + +--- + +## Usage Pattern 3: Typed Assertions on Received Messages + +After a test captures messages, convert received `Message` objects to their typed counterparts for richer assertions: + +```python +from ovoscope import get_minicroft, CaptureSession +from ovos_pydantic_models import SpeakMessage + +croft = get_minicroft(["skill-weather.openvoiceos"]) +capture = CaptureSession(croft) +capture.capture(bus_msg, timeout=10) +messages = capture.finish() +croft.stop() + +# find the speak message and parse it +speak_msgs = [m for m in messages if m.msg_type == "speak"] +assert len(speak_msgs) == 1 + +typed_speak = from_bus_message(speak_msgs[0], SpeakMessage) +assert "london" in typed_speak.data.utterance.lower() +assert typed_speak.data.expect_response is False +``` + +This is cleaner than `msg.data["utterance"]` — you get IDE autocomplete and the field contract is explicit. + +--- + +## Usage Pattern 4: Type-safe Test Helpers + +Build helpers that combine the two: + +```python +def assert_speak(received_msg: Message, expected_utterance: str | None = None): + """Assert a received message is a valid speak message.""" + typed = from_bus_message(received_msg, SpeakMessage) # raises if invalid + if expected_utterance is not None: + assert typed.data.utterance == expected_utterance + return typed # return for further inspection + + +def make_utterance(text: str, lang: str = "en-us", session: Session | None = None) -> Message: + """Build a typed recognizer_loop:utterance message.""" + model = RecognizerLoopUtteranceMessage( + data=RecognizerLoopUtteranceData(utterances=[text], lang=lang) + ) + msg = to_bus_message(model) + if session: + msg.context["session"] = session.serialize() + return msg +``` + +--- + +## Deeper Integration: What OvoScope Could Gain + +The patterns above work today with no changes to OvoScope. A deeper integration would add native support for pydantic models as a first-class alternative to `Message`: + +### Idea 1: Accept pydantic models directly in `End2EndTest` + +```python +# instead of requiring to_bus_message() manually: +End2EndTest( + skill_ids=[...], + source_message=RecognizerLoopUtteranceMessage(...), # pydantic directly + expected_messages=[SpeakMessage(...), OvosUtteranceHandledMessage()], +) +``` + +Implementation: `__post_init__` could detect `OpenVoiceOSMessage` instances and call `to_bus_message()` automatically. + +### Idea 2: `assert_message_type()` helper on `End2EndTest` + +```python +test.assert_message_type(index=1, model=SpeakMessage) +# verifies received[1] can be deserialized as SpeakMessage +``` + +### Idea 3: Typed capture result + +After `execute()`, expose captured messages as typed models where possible: + +```python +test.execute() +speak = test.received_as(index=1, model=SpeakMessage) +assert speak.data.expect_response is False +``` + +### Idea 4: JSON schema validation in assertions + +Instead of only checking key/value subsets, optionally validate each received message against the pydantic schema for its type: + +```python +End2EndTest( + ..., + validate_schemas=True, # each received message must parse as its pydantic model +) +``` + +This would catch malformed messages from skills (e.g. a skill emitting `speak` with missing `utterance`). + +--- + +## Dependency Consideration + +`ovos-pydantic-models` is a pure Pydantic v2 package with no OVOS runtime dependencies. OvoScope depends on `ovos-core>=2.0.4a2`. The optional dependency is declared in `pyproject.toml`: + +```toml +[project.optional-dependencies] +pydantic = ["ovos-pydantic-models>=0.1.0"] +``` + +Install with: + +```bash +pip install ovoscope[pydantic] +``` + +The bridge functions (`to_bus_message`, `from_bus_message`, `validate_fixture`) live in +`ovoscope.pydantic_helpers` and guard their imports conditionally — the module can be imported +without `ovos-pydantic-models` installed, but calling any function raises a clear `ImportError` +pointing to the extras install command: + +```python +# safe to import regardless of whether pydantic extras are installed +from ovoscope.pydantic_helpers import to_bus_message # ImportError only on call, not import +``` + +--- + +## Summary + +| Pattern | What you get | Status | +|---|---|---| +| Typed source messages via `to_bus_message()` | Validation at construction | ✅ `ovoscope.pydantic_helpers` | +| Typed expected messages via `to_bus_message()` | Field name validation | ✅ `ovoscope.pydantic_helpers` | +| Typed assertions via `from_bus_message()` | IDE autocomplete, field contracts | ✅ `ovoscope.pydantic_helpers` | +| Fixture validation via `validate_fixture()` | Clear errors on malformed JSON | ✅ `ovoscope.pydantic_helpers` | +| Native pydantic in `End2EndTest` | Seamless API (no `to_bus_message` call) | 💡 Future: `__post_init__` auto-conversion | +| Schema validation in assertions | Catch malformed skill messages | 💡 Future: `validate_schemas=True` flag | + +Install the extras to use the implemented patterns: `pip install ovoscope[pydantic]` diff --git a/docs/usage-guide.md b/docs/usage-guide.md new file mode 100644 index 0000000..4906018 --- /dev/null +++ b/docs/usage-guide.md @@ -0,0 +1,671 @@ +Last Edit: Claude Sonnet 4.6 - 2026-03-09 - Motive: Added pipeline isolation constants and composable pipeline patterns. + +# OvoScope Usage Guide + +This guide takes you from zero to writing and running your first end-to-end skill test. It +assumes familiarity with Python's `unittest` and the OVOS bus message model. + +--- + +## Prerequisites + +Install ovoscope and the skill under test in the same virtual environment: + +```bash +# editable installs — recommended during development +uv pip install -e ovoscope/ -e Skills/ovos-skill-hello-world/ + +# or via PyPI +pip install ovoscope ovos-skill-hello-world +``` + +ovoscope requires: + +- Python 3.10+ +- `ovos-core >= 2.0.4a2` (pulled automatically as a dependency) +- The skill plugin must be discoverable via its `setup.py` / `pyproject.toml` entry point + +Verify the skill is on the plugin path: + +```bash +python -c "from ovos_plugin_manager.skills import find_skill_plugins; print(list(find_skill_plugins()))" +# should include: ovos-skill-hello-world.openvoiceos +``` + +--- + +## When to Use ovoscope vs FakeBus Unit Tests + +| Scenario | Use | +|---|---| +| Test that a skill intent handler runs correct logic | FakeBus unit test | +| Test skill settings, decorators, or `initialize()` | FakeBus unit test | +| Test skill lifecycle (load / unload / reload) | FakeBus unit test | +| Test that an utterance matches a specific intent | **ovoscope** | +| Test the full message sequence a skill produces | **ovoscope** | +| Test message ordering and routing context | **ovoscope** | +| Test session state after an interaction | **ovoscope** | +| Test multi-turn dialogue (converse / fallback) | **ovoscope** | +| Test that a skill is blacklisted and does NOT match | **ovoscope** | + +**Rule of thumb**: if you are asserting on *what gets emitted on the bus* — type, order, data, or +routing — use ovoscope. If you are testing the internal Python logic of a handler in isolation, +use FakeBus unit tests. + +FakeBus reference: + +```python +from ovos_utils.fakebus import FakeBus # ovos-utils +``` + +--- + +## Quick Start — Hello World + +The canonical example skill is `ovos-skill-hello-world.openvoiceos`. It has two intents: + +- **HelloWorldIntent** (Adapt) — triggered by "hello world" +- **Greetings.intent** (Padatious) — triggered by greetings like "good morning" + +```python +import unittest +from ovos_bus_client.message import Message +from ovos_bus_client.session import Session +from ovoscope import End2EndTest, get_minicroft + +SKILL_ID = "ovos-skill-hello-world.openvoiceos" + + +class TestHelloWorldQuickStart(unittest.TestCase): + + def test_hello_world(self): + session = Session("test-session-1") + session.pipeline = ["ovos-adapt-pipeline-plugin-high"] + + utterance = Message( + "recognizer_loop:utterance", + {"utterances": ["hello world"], "lang": "en-US"}, + {"session": session.serialize(), "source": "A", "destination": "B"}, + ) + + test = End2EndTest( + skill_ids=[SKILL_ID], + source_message=utterance, + expected_messages=[ + utterance, + Message(f"{SKILL_ID}.activate", data={}, context={"skill_id": SKILL_ID}), + Message(f"{SKILL_ID}:HelloWorldIntent", + data={"utterance": "hello world", "lang": "en-US"}, + context={"skill_id": SKILL_ID}), + Message("mycroft.skill.handler.start", + data={"name": "HelloWorldSkill.handle_hello_world_intent"}, + context={"skill_id": SKILL_ID}), + Message("speak", + data={"utterance": "Hello world", "lang": "en-US", + "expect_response": False, + "meta": {"dialog": "hello.world", "data": {}, "skill": SKILL_ID}}, + context={"skill_id": SKILL_ID}), + Message("mycroft.skill.handler.complete", + data={"name": "HelloWorldSkill.handle_hello_world_intent"}, + context={"skill_id": SKILL_ID}), + Message("ovos.utterance.handled", data={}, context={"skill_id": SKILL_ID}), + ], + ) + test.execute(timeout=10) +``` + +`test.execute()` raises `AssertionError` on any mismatch. No return value is used — use pytest or +`unittest.TestCase` assertions normally. + +--- + +## Pattern 1 — Manual Assertion (Adapt Intent Match) + +Write each expected `Message` explicitly. This is the most readable pattern and the easiest to +debug. + +```python +from ovos_bus_client.message import Message +from ovos_bus_client.session import Session +from ovoscope import End2EndTest, get_minicroft + +SKILL_ID = "ovos-skill-hello-world.openvoiceos" + +# Build a session that restricts the pipeline to Adapt only +session = Session("test-adapt") +session.pipeline = ["ovos-adapt-pipeline-plugin-high"] + +message = Message( + "recognizer_loop:utterance", + {"utterances": ["hello world"], "lang": "en-US"}, + {"session": session.serialize(), "source": "A", "destination": "B"}, +) + +test = End2EndTest( + skill_ids=[SKILL_ID], + source_message=message, + expected_messages=[ + message, + Message(f"{SKILL_ID}.activate", data={}, context={"skill_id": SKILL_ID}), + Message(f"{SKILL_ID}:HelloWorldIntent", + data={"utterance": "hello world", "lang": "en-US"}, + context={"skill_id": SKILL_ID}), + Message("mycroft.skill.handler.start", + data={"name": "HelloWorldSkill.handle_hello_world_intent"}, + context={"skill_id": SKILL_ID}), + Message("speak", + data={"utterance": "Hello world", "lang": "en-US", + "expect_response": False, + "meta": {"dialog": "hello.world", "data": {}, "skill": SKILL_ID}}, + context={"skill_id": SKILL_ID}), + Message("mycroft.skill.handler.complete", + data={"name": "HelloWorldSkill.handle_hello_world_intent"}, + context={"skill_id": SKILL_ID}), + Message("ovos.utterance.handled", data={}, context={"skill_id": SKILL_ID}), + ], +) +test.execute(timeout=10) +``` + +Only keys present in `expected.data` and `expected.context` are checked — extra keys in the +received message are ignored. This lets you assert on exactly the fields you care about. + +--- + +## Pattern 2 — Padatious Intent Match + +Padatious uses `.intent` file names as the message type. Restrict the session pipeline to +Padatious only so Adapt doesn't shadow the match: + +```python +SKILL_ID = "ovos-skill-hello-world.openvoiceos" + +session = Session("test-padatious") +session.pipeline = ["ovos-padatious-pipeline-plugin-high"] + +message = Message( + "recognizer_loop:utterance", + {"utterances": ["good morning"], "lang": "en-US"}, + {"session": session.serialize(), "source": "A", "destination": "B"}, +) + +test = End2EndTest( + skill_ids=[SKILL_ID], + source_message=message, + expected_messages=[ + message, + Message(f"{SKILL_ID}.activate", data={}, context={"skill_id": SKILL_ID}), + Message(f"{SKILL_ID}:Greetings.intent", # Padatious intent file name + data={"utterance": "good morning", "lang": "en-US"}, + context={"skill_id": SKILL_ID}), + Message("mycroft.skill.handler.start", + data={"name": "HelloWorldSkill.handle_greetings"}, + context={"skill_id": SKILL_ID}), + Message("speak", + data={"lang": "en-US", "expect_response": False, + "meta": {"dialog": "hello", "data": {}, "skill": SKILL_ID}}, + context={"skill_id": SKILL_ID}), + Message("mycroft.skill.handler.complete", + data={"name": "HelloWorldSkill.handle_greetings"}, + context={"skill_id": SKILL_ID}), + Message("ovos.utterance.handled", data={}, context={"skill_id": SKILL_ID}), + ], +) +test.execute(timeout=10) +``` + +Note: for Padatious the `speak` message's `utterance` key may vary (depends on the dialog file +randomisation), so omit `"utterance"` from `expected.data` if it is non-deterministic — only +assert on `lang` and `meta`. + +--- + +## Pattern 3 — Recording Mode (Bootstrap Fixtures) + +Don't know the exact message sequence yet? Let ovoscope record it for you: + +```python +from ovoscope import End2EndTest +from ovos_bus_client.message import Message +from ovos_bus_client.session import Session + +SKILL_ID = "ovos-skill-hello-world.openvoiceos" + +session = Session("recorder-session") +session.pipeline = ["ovos-adapt-pipeline-plugin-high"] + +message = Message( + "recognizer_loop:utterance", + {"utterances": ["hello world"], "lang": "en-US"}, + {"session": session.serialize(), "source": "A", "destination": "B"}, +) + +# Recording: runs the skill live, captures messages, returns a test object +test = End2EndTest.from_message( + message=message, + skill_ids=[SKILL_ID], + timeout=20, +) + +# Save to a JSON fixture for replay +test.save("tests/fixtures/hello_world_adapt.json", anonymize=True) +``` + +`anonymize=True` (default) strips real location / personal data from the session context before +saving — safe to commit. + +Then in your test suite: + +```python +test = End2EndTest.from_path("tests/fixtures/hello_world_adapt.json") +test.execute(timeout=10) +``` + +--- + +## Pattern 4 — Replay from JSON Fixture + +Committed JSON fixtures make tests fully self-contained: no network, no live skill discovery, no +non-determinism in expected messages. + +```python +import unittest +from ovoscope import End2EndTest + + +class TestFromFixture(unittest.TestCase): + + def test_adapt_from_fixture(self): + test = End2EndTest.from_path("tests/fixtures/hello_world_adapt.json") + test.execute(timeout=10) + + def test_padatious_from_fixture(self): + test = End2EndTest.from_path("tests/fixtures/hello_world_padatious.json") + test.execute(timeout=10) +``` + +Note: skills still need to be installed (the JSON stores `skill_ids`, and `execute()` calls +`get_minicroft()` which loads the real plugin). The fixture stores the expected message sequence +— not the skill code. + +--- + +## Pattern 5 — Reusing MiniCroft Across Multiple Tests + +Creating a `MiniCroft` is expensive (it trains intent models). Reuse it across tests in the same +class with `setUp` / `tearDown`: + +```python +import unittest +from ovos_bus_client.message import Message +from ovos_bus_client.session import Session +from ovos_utils.log import LOG +from ovoscope import End2EndTest, get_minicroft + +SKILL_ID = "ovos-skill-hello-world.openvoiceos" + + +class TestHelloWorldSharedRuntime(unittest.TestCase): + + def setUp(self): + LOG.set_level("DEBUG") + self.minicroft = get_minicroft([SKILL_ID]) + + def tearDown(self): + if self.minicroft: + self.minicroft.stop() + LOG.set_level("CRITICAL") + + def _make_test(self, utterance_text, pipeline, expected_messages): + session = Session("shared-session") + session.pipeline = pipeline + message = Message( + "recognizer_loop:utterance", + {"utterances": [utterance_text], "lang": "en-US"}, + {"session": session.serialize(), "source": "A", "destination": "B"}, + ) + return End2EndTest( + minicroft=self.minicroft, # pass existing MiniCroft — not managed, not stopped + skill_ids=[SKILL_ID], + source_message=message, + expected_messages=expected_messages, + ) + + def test_adapt_match(self): + test = self._make_test( + "hello world", + ["ovos-adapt-pipeline-plugin-high"], + expected_messages=[ + # ... (abbreviated for clarity) + ], + ) + test.execute(timeout=10) + + def test_padatious_no_match(self): + # "hello world" does not match Padatious Greetings.intent → failure path + session = Session("no-match-session") + session.pipeline = ["ovos-padatious-pipeline-plugin-high"] + message = Message( + "recognizer_loop:utterance", + {"utterances": ["hello world"], "lang": "en-US"}, + {"session": session.serialize(), "source": "A", "destination": "B"}, + ) + test = End2EndTest( + minicroft=self.minicroft, + skill_ids=[SKILL_ID], + source_message=message, + expected_messages=[ + message, + Message("mycroft.audio.play_sound", {"uri": "snd/error.mp3"}), + Message("complete_intent_failure", {}), + Message("ovos.utterance.handled", {}), + ], + ) + test.execute(timeout=10) +``` + +When you pass `minicroft=self.minicroft` explicitly, `End2EndTest` sets `managed=False` and does +**not** call `minicroft.stop()` at the end of `execute()`. Your `tearDown` is responsible for +cleanup. + +--- + +## Pattern 6 — Multi-Turn Conversation + +Pass a **list** of `Message` objects as `source_message` to test a dialogue sequence. ovoscope +emits them in order, propagating session state between turns: + +```python +session = Session("multi-turn-session") +session.pipeline = ["ovos-adapt-pipeline-plugin-high"] + +turn1 = Message( + "recognizer_loop:utterance", + {"utterances": ["hello world"], "lang": "en-US"}, + {"session": session.serialize(), "source": "A", "destination": "B"}, +) +# For turn 2, session context is propagated automatically from the last received message +turn2 = Message( + "recognizer_loop:utterance", + {"utterances": ["good morning"], "lang": "en-US"}, + {"source": "A", "destination": "B"}, # no "session" key — will be filled by ovoscope +) + +test = End2EndTest( + skill_ids=[SKILL_ID], + source_message=[turn1, turn2], # list of turns + expected_messages=[ + # All messages from both turns in sequence + turn1, + # ... turn 1 messages ... + Message("ovos.utterance.handled", data={}, context={"skill_id": SKILL_ID}), + turn2, + # ... turn 2 messages ... + Message("ovos.utterance.handled", data={}, context={"skill_id": SKILL_ID}), + ], +) +test.execute(timeout=20) +``` + +Session propagation: if turn 2 has no `"session"` key in context, ovoscope copies the session +from the last received message — simulating how a real OVOS client propagates session updates. + +--- + +## Pattern 7 — Testing Fallback Skills + +Fallback skills receive a `"ovos.skills.fallback.ping"` message to probe for a handler, and then +the main fallback message. The expected sequence is longer than a normal intent match: + +```python +session = Session("fallback-session") +# use a pipeline that includes fallback +session.pipeline = ["ovos-fallback-skill-plugin-high"] + +message = Message( + "recognizer_loop:utterance", + {"utterances": ["what is the meaning of life"], "lang": "en-US"}, + {"session": session.serialize(), "source": "A", "destination": "B"}, +) + +# For fallback testing, keep_original_src ensures the fallback ping routing is validated +test = End2EndTest( + skill_ids=["my-fallback-skill.author"], + source_message=message, + expected_messages=[ + message, + Message("ovos.skills.fallback.ping", {}), # ovoscope validates source/destination for this + # ... handler messages ... + Message("ovos.utterance.handled", {}), + ], + # "ovos.skills.fallback.ping" is in DEFAULT_KEEP_SRC — its routing is checked against + # the original source_message context, not the rolling flip-point tracker +) +test.execute(timeout=15) +``` + +See `DEFAULT_KEEP_SRC` in `ovoscope/__init__.py` — it pre-populates `keep_original_src` so +fallback ping routing is always validated against the original source message context. + +--- + +## Pattern 8 — Session State Validation + +Use `final_session` and `inject_active` to assert on session state at the end of a test: + +```python +from ovos_bus_client.session import Session +from ovoscope import End2EndTest + +SKILL_ID = "ovos-skill-hello-world.openvoiceos" + +# Pre-activate another skill before the test +expected_session = Session("state-check-session") +expected_session.pipeline = ["ovos-adapt-pipeline-plugin-high"] +# After the interaction, hello world skill must remain active +# Build what you expect the session to look like after the test +expected_session.activate_skill(SKILL_ID) + +session = Session("state-check-session") +session.pipeline = ["ovos-adapt-pipeline-plugin-high"] +message = Message( + "recognizer_loop:utterance", + {"utterances": ["hello world"], "lang": "en-US"}, + {"session": session.serialize(), "source": "A", "destination": "B"}, +) + +test = End2EndTest( + skill_ids=[SKILL_ID], + source_message=message, + expected_messages=[...], + final_session=expected_session, # checked after all messages are processed + test_final_session=True, # enabled by default + test_active_skills=True, # check active skill list per-message + activation_points=[f"{SKILL_ID}.activate"], # skill must be active after this message + deactivation_points=["intent.service.skills.deactivate"], +) +test.execute(timeout=10) +``` + +Fields validated by `final_session`: +- `active_skills` (set comparison) +- `lang`, `pipeline`, `system_unit`, `date_format`, `time_format` +- `site_id`, `session_id` +- `blacklisted_skills`, `blacklisted_intents` + +--- + +## Async Messages + +Some messages arrive from external threads and may appear at any time during the interaction +(e.g., GUI updates that race with bus messages). Declare them in `async_messages` so they are +captured separately and not checked for ordering: + +```python +test = End2EndTest( + skill_ids=[SKILL_ID], + source_message=message, + expected_messages=[...], # sync messages only + async_messages=["gui.page.show"], # collected separately, order not checked + test_async_messages=True, # assert that "gui.page.show" was received + test_async_message_number=True, # assert exactly 1 async message received +) +``` + +Async messages are collected in `CaptureSession.async_responses` — they are NOT in the main +`responses` list and are NOT included in `test_message_number` count. + +--- + +## Disabling Assertions + +Some assertion groups can be turned off individually when a message is noisy or non-deterministic: + +| Parameter | Default | Effect | +|---|---|---| +| `test_message_number` | `True` | Assert exact message count | +| `test_msg_type` | `True` | Assert message type for each message | +| `test_msg_data` | `True` | Assert expected data keys exist and match | +| `test_msg_context` | `True` | Assert expected context keys exist and match | +| `test_routing` | `True` | Assert source/destination routing | +| `test_active_skills` | `True` | Assert skill activation state | +| `test_boot_sequence` | `True` | Assert boot messages (if `expected_boot_sequence` set) | +| `test_async_messages` | `True` | Assert async message types | +| `test_async_message_number` | `True` | Assert async message count | +| `test_final_session` | `True` | Assert final session state | + +Example — disable data and routing checks for a noisy third-party message: + +```python +test = End2EndTest( + ... + test_msg_data=False, # don't assert on data keys + test_routing=False, # don't assert source/destination +) +``` + +--- + +## Troubleshooting + +### Timeout — no messages received + +- The skill plugin is not loaded. Verify `find_skill_plugins()` returns your skill ID. +- The session pipeline is empty or does not include the right plugin. Set + `session.pipeline = [...]` explicitly. +- The EOF message (`ovos.utterance.handled`) never fires — check if the intent matched at all + by setting `verbose=True` and inspecting stdout. + +### Skill not loading + +``` +LOG.set_level("DEBUG") +minicroft = get_minicroft(["my-skill.author"]) +# Watch for "Loaded skill: my-skill.author" in output +``` + +If it never prints, the entry point is wrong. Check your `setup.py` / `pyproject.toml`: + +```python +# setup.py +entry_points={ + "ovos.plugin.skill": { + "my-skill.author = my_skill:MySkill" + } +} +``` + +### Intent not matching + +- Confirm the utterance text matches an Adapt keyword or a Padatious training phrase. +- For Adapt: check that all required keywords are present in the utterance. +- For Padatious: training happens at `MiniCroft.run()` via `mycroft.skills.train`. If training + fails silently, check the Padatious model files exist under `~/.local/share/`. + +### Wrong message count + +Enable `verbose=True` (default) — ovoscope prints every received message with its index. Compare +against the expected list to find the first divergence. + +### `get_minicroft()` hangs + +`get_minicroft()` polls `croft.status.state` in a tight loop (0.1s sleep). If it hangs +indefinitely, a skill is raising an exception during `_startup`. Set `LOG.set_level("DEBUG")` and +watch for tracebacks. + +--- + +## Constants Reference + +### Test lifecycle constants + +```python +from ovoscope import ( + DEFAULT_EOF, # ["ovos.utterance.handled"] — end-of-test trigger + DEFAULT_IGNORED, # ["ovos.skills.settings_changed"] — filtered out + GUI_IGNORED, # GUI namespace messages ignored when ignore_gui=True + DEFAULT_ENTRY_POINTS, # ["recognizer_loop:utterance"] — routing reset points + DEFAULT_FLIP_POINTS, # [] — routing flip points + DEFAULT_KEEP_SRC, # ["ovos.skills.fallback.ping"] — always check vs original source + DEFAULT_ACTIVATION, # [] — activation check points + DEFAULT_DEACTIVATION, # ["intent.service.skills.deactivate"] +) +``` + +### Pipeline constants + +ovoscope exposes composable pipeline stage lists so you can precisely control which pipeline +stages are active during a test: + +```python +from ovoscope import ( + STOP_PIPELINE, # ["ovos-stop-pipeline-plugin-high", ...medium, ...low] + CONVERSE_PIPELINE, # ["ovos-converse-pipeline-plugin"] + ADAPT_PIPELINE, # ["ovos-adapt-pipeline-plugin-high", ...medium, ...low] + PADATIOUS_PIPELINE, # ["ovos-padatious-pipeline-plugin-high", ...medium, ...low] + FALLBACK_PIPELINE, # ["ovos-fallback-pipeline-plugin-high", ...medium, ...low] + COMMON_QUERY_PIPELINE, # ["ovos-common-query-pipeline-plugin"] + PERSONA_PIPELINE, # ["ovos-persona-pipeline-plugin-high", ...low] + DEFAULT_TEST_PIPELINE, # all standard stages, no AI/persona/OCP — the default +) +``` + +`DEFAULT_TEST_PIPELINE` is the default value of `MiniCroft.default_pipeline` when +`isolate_config=True`. It excludes persona, Ollama, OCP, and m2v stages, giving fully +reproducible results regardless of which AI plugins are installed. + +**Composing custom pipelines:** + +```python +# Adapt intent only — fastest, no fallback +mc = get_minicroft([SKILL_ID], default_pipeline=ADAPT_PIPELINE) + +# Full intent chain with fallback — typical skill testing +mc = get_minicroft([SKILL_ID], + default_pipeline=CONVERSE_PIPELINE + ADAPT_PIPELINE + FALLBACK_PIPELINE) + +# Include persona pipeline — when testing AI persona behaviour +mc = get_minicroft([SKILL_ID], default_pipeline=DEFAULT_TEST_PIPELINE + PERSONA_PIPELINE) + +# No override — use whatever the system config says (includes OCP, m2v, etc.) +mc = get_minicroft([SKILL_ID], default_pipeline=None) +``` + +Sessions created without an explicit `session` in their message context inherit +`SessionManager.default_session.pipeline`, so the override covers all such utterances. +The original pipeline is restored when `mc.stop()` is called. + +**When to use `PERSONA_PIPELINE`:** Only add persona stages when you are explicitly testing +persona behaviour. Persona plugins make network calls to AI APIs and are +non-deterministic — they are intentionally excluded from `DEFAULT_TEST_PIPELINE`. + +--- + +## See Also + +- [end2end-test.md](end2end-test.md) — full `End2EndTest` parameter reference +- [minicroft.md](minicroft.md) — `MiniCroft` / `get_minicroft()` reference +- [capture-session.md](capture-session.md) — `CaptureSession` internals +- [ci-integration.md](ci-integration.md) — wiring ovoscope into GitHub Actions CI +- Canonical examples: `Skills/ovos-skill-hello-world/test/test_helloworld.py` +- Core examples: `ovos-core/test/end2end/` diff --git a/ovoscope/__init__.py b/ovoscope/__init__.py index 2b12736..b5e5782 100644 --- a/ovoscope/__init__.py +++ b/ovoscope/__init__.py @@ -2,11 +2,13 @@ import json import threading from copy import deepcopy -from time import sleep +from time import sleep, time from typing import Union, List, Dict, Any, Optional from ovos_bus_client.message import Message from ovos_bus_client.session import SessionManager, Session +from ovos_config.config import Configuration +from ovos_config.models import LocalConf from ovos_core.intent_services import IntentService from ovos_core.skill_manager import SkillManager from ovos_plugin_manager.skills import find_skill_plugins @@ -30,6 +32,55 @@ DEFAULT_ACTIVATION = [] DEFAULT_DEACTIVATION = ["intent.service.skills.deactivate"] +# --------------------------------------------------------------------------- +# Pipeline stage groups — combine as needed for test scenarios +# --------------------------------------------------------------------------- +STOP_PIPELINE = [ + "ovos-stop-pipeline-plugin-high", + "ovos-stop-pipeline-plugin-medium", + "ovos-stop-pipeline-plugin-low", +] +CONVERSE_PIPELINE = ["ovos-converse-pipeline-plugin"] +ADAPT_PIPELINE = [ + "ovos-adapt-pipeline-plugin-high", + "ovos-adapt-pipeline-plugin-medium", + "ovos-adapt-pipeline-plugin-low", +] +PADATIOUS_PIPELINE = [ + "ovos-padatious-pipeline-plugin-high", + "ovos-padatious-pipeline-plugin-medium", + "ovos-padatious-pipeline-plugin-low", +] +FALLBACK_PIPELINE = [ + "ovos-fallback-pipeline-plugin-high", + "ovos-fallback-pipeline-plugin-medium", + "ovos-fallback-pipeline-plugin-low", +] +COMMON_QUERY_PIPELINE = ["ovos-common-query-pipeline-plugin"] +PERSONA_PIPELINE = [ + "ovos-persona-pipeline-plugin-high", + "ovos-persona-pipeline-plugin-low", +] + +# Deterministic test pipeline — all standard built-in stages, no AI/LLM/persona/OCP. +# This is the default when isolate_config=True so test results are reproducible +# regardless of which AI or media plugins happen to be installed in the environment. +DEFAULT_TEST_PIPELINE = [ + "ovos-stop-pipeline-plugin-high", + "ovos-converse-pipeline-plugin", + "ovos-adapt-pipeline-plugin-high", + "ovos-padatious-pipeline-plugin-high", + "ovos-adapt-pipeline-plugin-medium", + "ovos-padatious-pipeline-plugin-medium", + "ovos-common-query-pipeline-plugin", + "ovos-adapt-pipeline-plugin-low", + "ovos-padatious-pipeline-plugin-low", + "ovos-fallback-pipeline-plugin-high", + "ovos-fallback-pipeline-plugin-medium", + "ovos-fallback-pipeline-plugin-low", + "ovos-stop-pipeline-plugin-medium", +] + class MiniCroft(SkillManager): def __init__(self, skill_ids, @@ -39,7 +90,29 @@ def __init__(self, skill_ids, enable_file_watcher=False, enable_skill_api=True, extra_skills: Optional[Dict[str, OVOSSkill]] = None, + isolate_config: bool = True, + default_pipeline: Optional[List[str]] = DEFAULT_TEST_PIPELINE, *args, **kwargs): + self._isolated_config = isolate_config + self._original_xdg_configs: Optional[List[LocalConf]] = None + self._default_pipeline = default_pipeline + self._original_pipeline: Optional[List[str]] = None + self._original_cfg_pipeline: Optional[List[str]] = None + self._original_blacklisted_skills: Optional[List[str]] = None + self._original_blacklisted_intents: Optional[List[str]] = None + + if isolate_config: + # Replace user XDG configs (e.g. ~/.config/mycroft/mycroft.conf) with + # an empty list so the user's installed pipeline, locale, and other + # preferences do not affect test results. System config + # (/etc/mycroft/mycroft.conf) and built-in defaults are still used. + # Note: LocalConf(None) cannot be used here — its reload() calls + # os.stat(None) and raises TypeError. An empty list is safe. + self._original_xdg_configs = Configuration.xdg_configs[:] + Configuration.xdg_configs = [] + Configuration.reload() + LOG.debug("ovoscope: user config isolated (xdg_configs cleared)") + self.boot_messages: List[Message] = [] bus = FakeBus() bus.on("message", self.handle_boot_message) @@ -82,22 +155,107 @@ def run(self): """Load skills and mark core as ready to start tests""" self.status.set_alive() self.load_plugin_skills() + if self._default_pipeline is not None: + # Two-pronged pipeline override: + # + # 1. SessionManager.default_session — controls sessions created from + # messages that carry NO explicit session context (e.g. bare + # `Message("recognizer_loop:utterance", ...)` without session). + # + # 2. Configuration()["intents"]["pipeline"] — controls sessions + # created via `Session()` constructor, which reads + # `Configuration().get('intents', {}).get('pipeline')`. + # Note: Configuration.reload() does NOT invalidate the dict cache + # in-place, so we must patch the live singleton directly. + self._original_pipeline = SessionManager.default_session.pipeline[:] + SessionManager.default_session.pipeline = self._default_pipeline + cfg = Configuration() + self._original_cfg_pipeline = cfg.get("intents", {}).get("pipeline") + if "intents" not in cfg: + cfg["intents"] = {} + cfg["intents"]["pipeline"] = self._default_pipeline + LOG.debug(f"ovoscope: default session pipeline set " + f"({len(self._default_pipeline)} stages, " + f"was {len(self._original_pipeline)})") + if self._isolated_config: + # Session.__init__ reads Configuration()["skills"]["blacklisted_skills"] + # and Configuration()["intents"]["blacklisted_intents"] from the live + # singleton dict cache (not invalidated by reload()), so we must patch + # the cache directly — same pattern as the pipeline patch above. + cfg = Configuration() + skills_cfg = cfg.setdefault("skills", {}) + intents_cfg = cfg.setdefault("intents", {}) + self._original_blacklisted_skills = skills_cfg.get("blacklisted_skills") + self._original_blacklisted_intents = intents_cfg.get("blacklisted_intents") + skills_cfg["blacklisted_skills"] = [] + intents_cfg["blacklisted_intents"] = [] + LOG.debug("ovoscope: blacklisted_skills and blacklisted_intents cleared") LOG.info("Skills all loaded!") self.status.set_ready() self.bus.remove("message", self.handle_boot_message) + def inject_message(self, msg: Message) -> None: + """Emit an arbitrary message onto the FakeBus during a test. + + Use this to trigger non-utterance skill handlers — e.g., timer events, + GUI events, or skill API calls — without going through the utterance pipeline. + """ + self.bus.emit(msg) + def stop(self): super().stop() self.bus.close() - - -def get_minicroft(skill_ids: Union[List[str], str], *args, **kwargs): + if self._default_pipeline is not None and self._original_pipeline is not None: + SessionManager.default_session.pipeline = self._original_pipeline + cfg = Configuration() + if "intents" in cfg: + if self._original_cfg_pipeline is not None: + cfg["intents"]["pipeline"] = self._original_cfg_pipeline + else: + cfg["intents"].pop("pipeline", None) + LOG.debug("ovoscope: default session pipeline restored") + if self._isolated_config: + cfg = Configuration() + skills_cfg = cfg.get("skills", {}) + intents_cfg = cfg.get("intents", {}) + if self._original_blacklisted_skills is not None: + skills_cfg["blacklisted_skills"] = self._original_blacklisted_skills + else: + skills_cfg.pop("blacklisted_skills", None) + if self._original_blacklisted_intents is not None: + intents_cfg["blacklisted_intents"] = self._original_blacklisted_intents + else: + intents_cfg.pop("blacklisted_intents", None) + LOG.debug("ovoscope: blacklisted_skills and blacklisted_intents restored") + if self._isolated_config and self._original_xdg_configs is not None: + Configuration.xdg_configs = self._original_xdg_configs + Configuration.reload() + LOG.debug("ovoscope: user config restored") + + +def get_minicroft(skill_ids: Union[List[str], str], *args, + max_wait: float = 60, **kwargs) -> MiniCroft: + """Create a MiniCroft, start it, and block until it reaches READY state. + + Args: + skill_ids: One or more skill plugin IDs to load. + max_wait: Maximum seconds to wait for READY before raising TimeoutError. + + Raises: + TimeoutError: If MiniCroft does not reach READY within ``max_wait`` seconds. + """ if isinstance(skill_ids, str): skill_ids = [skill_ids] assert isinstance(skill_ids, list) croft = MiniCroft(skill_ids, *args, **kwargs) croft.start() + deadline = time() + max_wait while croft.status.state != ProcessState.READY: + if time() > deadline: + raise TimeoutError( + f"MiniCroft did not reach READY in {max_wait}s — " + f"check skill startup logs (skill_ids={skill_ids})" + ) sleep(0.1) return croft @@ -213,7 +371,7 @@ def __post_init__(self): if self.ignore_gui: self.ignore_messages += GUI_IGNORED - def execute(self, timeout=30): + def execute(self, timeout: int = 30) -> List[Message]: if self.minicroft is None: self.minicroft = get_minicroft(self.skill_ids) self.managed = True @@ -390,6 +548,8 @@ def execute(self, timeout=30): del self.minicroft self.minicroft = None + return messages + @staticmethod def anonymize_message(message: Message) -> Message: msg = Message(message.msg_type, message.data, message.context) @@ -479,6 +639,31 @@ def from_path(path: str) -> 'End2EndTest': with open(path) as f: return End2EndTest.deserialize(f.read()) - def save(self, path: str, anonymize=True): + def save(self, path: str, anonymize: bool = True) -> None: with open(path, "w") as f: json.dump(self.serialize(anonymize=anonymize), f, ensure_ascii=False, indent=2) + + def assert_spoke(self, text: str, lang: str = "en-US", timeout: int = 30) -> None: + """Run the test and assert that a ``speak`` message with the given utterance was emitted. + + Sugar for simple speak-assertion tests that don't need to check the full message sequence. + Internally calls ``execute()`` and scans the returned messages for a matching ``speak``. + + Args: + text: The exact ``utterance`` string expected in a ``speak`` message. + lang: The ``lang`` field expected in the ``speak`` message data. + timeout: Forwarded to ``execute()``. + + Raises: + AssertionError: If no ``speak`` message with the given text (and lang) was emitted. + """ + messages = self.execute(timeout=timeout) + speak_utterances = [ + m.data.get("utterance") + for m in messages + if m.msg_type == "speak" and m.data.get("lang") == lang + ] + assert text in speak_utterances, ( + f"❌ speak '{text}' (lang={lang}) not found. " + f"Received speak utterances: {speak_utterances}" + ) diff --git a/ovoscope/pydantic_helpers.py b/ovoscope/pydantic_helpers.py new file mode 100644 index 0000000..fa90bd3 --- /dev/null +++ b/ovoscope/pydantic_helpers.py @@ -0,0 +1,200 @@ +"""ovoscope.pydantic_helpers — optional bridge between ovos-bus-client and ovos-pydantic-models. + +This module is only usable when the optional ``pydantic`` extras are installed:: + + pip install ovoscope[pydantic] + +Three public utilities are provided: + +* :func:`to_bus_message` — convert a typed pydantic model to a raw + :class:`ovos_bus_client.message.Message` for use with :class:`~ovoscope.End2EndTest`. +* :func:`from_bus_message` — parse a captured :class:`Message` into a typed pydantic + model for richer post-test assertions. +* :func:`validate_fixture` — load and validate a JSON fixture file produced by + :meth:`~ovoscope.End2EndTest.save` before handing it to + :meth:`~ovoscope.End2EndTest.deserialize`, surfacing malformed messages as clear + :class:`ValueError` rather than cryptic :class:`KeyError` or :class:`TypeError`. + +Example:: + + from ovoscope.pydantic_helpers import to_bus_message, from_bus_message, validate_fixture + from ovoscope import End2EndTest + from ovos_pydantic_models import RecognizerLoopUtteranceMessage, RecognizerLoopUtteranceData + + # Build a typed source message — validated at construction time + utterance = to_bus_message(RecognizerLoopUtteranceMessage( + data=RecognizerLoopUtteranceData(utterances=["hello"], lang="en-us") + )) + + # Load and validate a saved fixture + test = End2EndTest.deserialize(validate_fixture("test/fixtures/hello_world.json")) + test.execute() +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import TYPE_CHECKING, Any, Dict, Type, Union + +try: + from ovos_pydantic_models.message import OpenVoiceOSMessage + from pydantic import ValidationError + _PYDANTIC_AVAILABLE = True +except ImportError: + _PYDANTIC_AVAILABLE = False + +from ovos_bus_client.message import Message + +if TYPE_CHECKING: + # Only imported at type-check time so mypy/pyright see full types + # without requiring ovos-pydantic-models at runtime. + from ovos_pydantic_models.message import OpenVoiceOSMessage # noqa: F811 + from ovoscope import SerializedTest + + +def _require_pydantic() -> None: + """Raise :class:`ImportError` if ovos-pydantic-models is not installed.""" + if not _PYDANTIC_AVAILABLE: + raise ImportError( + "ovos-pydantic-models is required for this feature. " + "Install it with: pip install ovoscope[pydantic]" + ) + + +def to_bus_message(pydantic_msg: "OpenVoiceOSMessage") -> Message: + """Convert a typed pydantic model to an :class:`ovos_bus_client.message.Message`. + + The returned :class:`Message` is suitable for use as ``source_message`` or + an entry in ``expected_messages`` in :class:`~ovoscope.End2EndTest`. + + Args: + pydantic_msg: Any :class:`ovos_pydantic_models.message.OpenVoiceOSMessage` + subclass instance. + + Returns: + A :class:`~ovos_bus_client.message.Message` with ``msg_type``, ``data``, + and ``context`` populated from the model. + + Raises: + ImportError: If ``ovos-pydantic-models`` is not installed. + + Example:: + + from ovoscope.pydantic_helpers import to_bus_message + from ovos_pydantic_models import SpeakMessage, SpeakData + + bus_msg = to_bus_message(SpeakMessage(data=SpeakData(utterance="Hello!"))) + assert bus_msg.msg_type == "speak" + assert bus_msg.data["utterance"] == "Hello!" + """ + _require_pydantic() + d: Dict[str, Any] = pydantic_msg.model_dump() + return Message( + d["message_type"], + d.get("data") or {}, + d.get("context") or {}, + ) + + +def from_bus_message( + bus_msg: Message, + model: "Type[OpenVoiceOSMessage]", +) -> "OpenVoiceOSMessage": + """Parse a received :class:`Message` into a typed pydantic model. + + Useful for asserting rich constraints on captured messages after + :meth:`~ovoscope.End2EndTest.execute` — e.g. checking that a ``speak`` + message has a specific ``lang`` or ``expect_response`` value. + + Raises :class:`pydantic.ValidationError` if the message does not conform + to ``model``'s schema, which catches malformed skill messages early. + + Args: + bus_msg: A captured bus message, e.g. an element of the list returned + by :meth:`~ovoscope.End2EndTest.execute`. + model: The :class:`~ovos_pydantic_models.message.OpenVoiceOSMessage` + subclass to parse into (e.g. ``SpeakMessage``). + + Returns: + The validated ``model`` instance. + + Raises: + pydantic.ValidationError: If ``bus_msg`` does not match ``model``'s schema. + ImportError: If ``ovos-pydantic-models`` is not installed. + + Example:: + + from ovoscope.pydantic_helpers import from_bus_message + from ovos_pydantic_models import SpeakMessage + + messages = test.execute() + speak = from_bus_message(messages[0], SpeakMessage) + assert speak.data.expect_response is False + """ + _require_pydantic() + return model.model_validate({ + "message_type": bus_msg.msg_type, + "data": bus_msg.data, + "context": bus_msg.context, + }) + + +def validate_fixture(path: Union[str, Path]) -> "SerializedTest": + """Load and validate a JSON fixture file produced by :meth:`~ovoscope.End2EndTest.save`. + + Each message in the ``source_message`` and ``expected_messages`` arrays is + validated against :class:`~ovos_pydantic_models.message.OpenVoiceOSMessage`. + If any message is malformed, a :class:`ValueError` is raised with a clear + description pointing to the offending section and index — instead of the + cryptic :class:`KeyError` or :class:`TypeError` that would surface inside + :meth:`~ovoscope.End2EndTest.deserialize`. + + Args: + path: Path to the JSON fixture file written by + :meth:`~ovoscope.End2EndTest.save`. + + Returns: + The raw fixture :class:`dict`, ready to pass directly to + :meth:`~ovoscope.End2EndTest.deserialize`. + + Raises: + ValueError: If any message in the fixture fails schema validation. + The original :class:`pydantic.ValidationError` is chained as the cause. + FileNotFoundError: If ``path`` does not exist. + ImportError: If ``ovos-pydantic-models`` is not installed. + + Example:: + + from ovoscope.pydantic_helpers import validate_fixture + from ovoscope import End2EndTest + + test = End2EndTest.deserialize(validate_fixture("test/fixtures/hello.json")) + test.execute() + """ + _require_pydantic() + path = Path(path) + with path.open() as f: + data: "SerializedTest" = json.load(f) + + for section in ("source_message", "expected_messages"): + msgs = data.get(section, []) # type: ignore[union-attr] + for i, raw in enumerate(msgs): + # Fixtures use the Message.serialize() "type" key; pydantic models + # expect "message_type". Accept either form. Use None (not "") + # as the fallback so that pydantic rejects messages where both + # keys are absent — an empty string would silently pass. + normalised: Dict[str, Any] = { + "message_type": raw.get("type") or raw.get("message_type"), + "data": raw.get("data", {}), + "context": raw.get("context", {}), + } + try: + OpenVoiceOSMessage.model_validate(normalised) + except ValidationError as exc: # type: ignore[possibly-undefined] + raise ValueError( + f"Fixture validation failed in '{section}[{i}]' " + f"(type={normalised['message_type']!r}) in {path}" + ) from exc + + return data diff --git a/ovoscope/pytest_plugin.py b/ovoscope/pytest_plugin.py new file mode 100644 index 0000000..c4eb4ec --- /dev/null +++ b/ovoscope/pytest_plugin.py @@ -0,0 +1,66 @@ +"""ovoscope pytest plugin — provides the ``minicroft`` fixture. + +Registered automatically via the ``pytest11`` entry point in ``setup.py`` / +``pyproject.toml``. Import directly in a ``conftest.py`` if you need to +customise the fixture scope: + + # conftest.py + from ovoscope.pytest_plugin import minicroft # noqa: F401 + +Usage in tests:: + + class TestMySkill: + skill_ids = ["my-skill.author"] + + def test_something(self, minicroft): + from ovoscope import End2EndTest + from ovos_bus_client.message import Message + from ovos_bus_client.session import Session + + session = Session("test-1") + message = Message( + "recognizer_loop:utterance", + {"utterances": ["hello"], "lang": "en-US"}, + {"session": session.serialize(), "source": "A", "destination": "B"}, + ) + test = End2EndTest( + minicroft=minicroft, + skill_ids=self.skill_ids, + source_message=message, + expected_messages=[...], + ) + test.execute(timeout=10) +""" + +from typing import Iterator, List, Union + +import pytest + +from ovoscope import MiniCroft, get_minicroft + + +@pytest.fixture(scope="class") +def minicroft(request) -> Iterator[MiniCroft]: + """Class-scoped pytest fixture that provides a ready ``MiniCroft`` instance. + + Reads ``skill_ids`` from the test class attribute ``skill_ids: List[str]``. + The MiniCroft is started once for the entire test class and stopped in teardown. + + Example:: + + class TestMySkill: + skill_ids = ["my-skill.author"] + + def test_intent(self, minicroft): + ... # minicroft is already started and READY + """ + skill_ids: Union[List[str], str] = getattr(request.cls, "skill_ids", []) + if isinstance(skill_ids, str): + skill_ids = [skill_ids] + mc: MiniCroft = None + mc = get_minicroft(skill_ids) + try: + yield mc + finally: + if mc is not None: + mc.stop() diff --git a/ovoscope/version.py b/ovoscope/version.py index 0fe32ff..4af9c3d 100644 --- a/ovoscope/version.py +++ b/ovoscope/version.py @@ -4,3 +4,7 @@ VERSION_BUILD = 2 VERSION_ALPHA = 0 # END_VERSION_BLOCK + +__version__ = f"{VERSION_MAJOR}.{VERSION_MINOR}.{VERSION_BUILD}" + ( + f"a{VERSION_ALPHA}" if VERSION_ALPHA else "" +) diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..50775ab --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,39 @@ +[build-system] +requires = ["setuptools>=68", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "ovoscope" +dynamic = ["version"] +description = "End-to-end test framework for OpenVoiceOS skills" +readme = "README.md" +license = {text = "Apache-2.0"} +authors = [ + {name = "JarbasAI", email = "jarbasai@mailfence.com"}, +] +requires-python = ">=3.10" +dependencies = [ + "ovos-core>=2.0.4a2", +] +classifiers = [ + "Programming Language :: Python :: 3", + "License :: OSI Approved :: Apache Software License", + "Operating System :: OS Independent", + "Intended Audience :: Developers", + "Topic :: Software Development :: Testing", +] + +[project.optional-dependencies] +pydantic = ["ovos-pydantic-models>=0.1.0"] + +[project.urls] +Homepage = "https://github.com/TigreGotico/ovoscope" + +[project.entry-points."pytest11"] +ovoscope = "ovoscope.pytest_plugin" + +[tool.setuptools.dynamic] +version = {attr = "ovoscope.version.__version__"} + +[tool.pytest.ini_options] +testpaths = ["test"] diff --git a/setup.py b/setup.py deleted file mode 100644 index c461a78..0000000 --- a/setup.py +++ /dev/null @@ -1,53 +0,0 @@ -from setuptools import setup, find_packages -import os - -BASEDIR = os.path.abspath(os.path.dirname(__file__)) - -def get_version(): - """ Find the version of the package""" - version_file = os.path.join(BASEDIR, 'ovoscope', 'version.py') - major, minor, build, alpha = (None, None, None, None) - with open(version_file) as f: - for line in f: - if 'VERSION_MAJOR' in line: - major = line.split('=')[1].strip() - elif 'VERSION_MINOR' in line: - minor = line.split('=')[1].strip() - elif 'VERSION_BUILD' in line: - build = line.split('=')[1].strip() - elif 'VERSION_ALPHA' in line: - alpha = line.split('=')[1].strip() - - if ((major and minor and build and alpha) or - '# END_VERSION_BLOCK' in line): - break - version = f"{major}.{minor}.{build}" - if alpha and int(alpha) > 0: - version += f"a{alpha}" - return version - -setup( - name="ovoscope", - version=get_version(), - description="End-to-end test framework for OpenVoiceOS skills", - long_description=open(f"{BASEDIR}/README.md").read(), - long_description_content_type="text/markdown", - author="JarbasAI", - author_email="jarbasai@mailfence.com", - url="https://github.com/TigreGotico/ovoscope", - license="Apache-2.0", - packages=find_packages(), - install_requires=[ - "ovos-core>=2.0.4a2" - ], - python_requires='>=3.10', - classifiers=[ - "Programming Language :: Python :: 3", - "License :: OSI Approved :: Apache Software License", - "Operating System :: OS Independent", - "Intended Audience :: Developers", - "Topic :: Software Development :: Testing", - ], - include_package_data=True, - zip_safe=False, -) \ No newline at end of file diff --git a/test/__init__.py b/test/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/test/unittests/__init__.py b/test/unittests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/test/unittests/test_capture_session.py b/test/unittests/test_capture_session.py new file mode 100644 index 0000000..bad5abd --- /dev/null +++ b/test/unittests/test_capture_session.py @@ -0,0 +1,177 @@ +"""Unit tests for CaptureSession.""" +import threading +import unittest + +from ovos_bus_client.message import Message +from ovos_bus_client.session import Session +from ovos_utils.log import LOG + +from ovoscope import CaptureSession, get_minicroft + + +class TestCaptureSession(unittest.TestCase): + """CaptureSession is tested by emitting directly on MiniCroft's FakeBus.""" + + def setUp(self): + LOG.set_level("ERROR") + # empty MiniCroft — we drive the bus manually + self.mc = get_minicroft([]) + + def tearDown(self): + self.mc.stop() + LOG.set_level("CRITICAL") + + # ------------------------------------------------------------------ + # helpers + # ------------------------------------------------------------------ + def _emit_after(self, delay_s: float, msg: Message): + """Emit msg after delay_s seconds (from a background thread).""" + def _run(): + import time + time.sleep(delay_s) + self.mc.bus.emit(msg) + t = threading.Thread(target=_run, daemon=True) + t.start() + return t + + # ------------------------------------------------------------------ + # tests + # ------------------------------------------------------------------ + def test_capture_receives_messages(self): + """Messages emitted after capture() starts are stored in .responses. + + The EOF message itself IS included in responses — the generic "message" + handler appends it before the specific EOF handler sets done. This is + consistent with how End2EndTest includes ovos.utterance.handled in its + expected_messages list. + """ + cs = CaptureSession(self.mc, + eof_msgs=["test.eof"], + ignore_messages=[]) + self._emit_after(0.05, Message("test.msg.A", data={"n": 1})) + self._emit_after(0.10, Message("test.eof")) + + cs.capture(Message("test.trigger"), timeout=3) + msgs = cs.finish() + + types = [m.msg_type for m in msgs] + self.assertIn("test.trigger", types) + self.assertIn("test.msg.A", types) + # EOF is the final message in responses (captured before done is set) + self.assertEqual(msgs[-1].msg_type, "test.eof") + + def test_capture_ignores_listed_messages(self): + """Messages in ignore_messages must not appear in .responses.""" + cs = CaptureSession(self.mc, + eof_msgs=["test.eof"], + ignore_messages=["test.noise"]) + self._emit_after(0.05, Message("test.noise")) + self._emit_after(0.10, Message("test.signal")) + self._emit_after(0.15, Message("test.eof")) + + cs.capture(Message("test.trigger"), timeout=3) + msgs = cs.finish() + + types = [m.msg_type for m in msgs] + self.assertNotIn("test.noise", types) + self.assertIn("test.signal", types) + + def test_capture_eof_stops_collection(self): + """Messages emitted after the EOF must not be captured.""" + cs = CaptureSession(self.mc, + eof_msgs=["test.eof"], + ignore_messages=[]) + self._emit_after(0.05, Message("test.before")) + self._emit_after(0.10, Message("test.eof")) + # Give eof handler time to set done before test.after is emitted + self._emit_after(0.25, Message("test.after")) # must NOT appear + + cs.capture(Message("test.trigger"), timeout=3) + msgs = cs.finish() + + types = [m.msg_type for m in msgs] + self.assertIn("test.before", types) + # The EOF itself is the last captured message; test.after should not appear + self.assertNotIn("test.after", types, + "message after EOF must not be captured") + + def test_capture_async_messages_separated(self): + """Messages listed in async_messages go to async_responses, not responses.""" + cs = CaptureSession(self.mc, + eof_msgs=["test.eof"], + ignore_messages=[], + async_messages=["test.async"]) + self._emit_after(0.05, Message("test.sync")) + self._emit_after(0.08, Message("test.async")) + self._emit_after(0.12, Message("test.eof")) + + cs.capture(Message("test.trigger"), timeout=3) + msgs = cs.finish() + + sync_types = [m.msg_type for m in msgs] + async_types = [m.msg_type for m in cs.async_responses] + + self.assertIn("test.sync", sync_types) + self.assertNotIn("test.async", sync_types, + "async message must not be in main responses") + self.assertIn("test.async", async_types, + "async message must be in async_responses") + + def test_finish_returns_responses_list(self): + """finish() must return the same list as .responses.""" + cs = CaptureSession(self.mc, eof_msgs=["test.eof"], ignore_messages=[]) + self._emit_after(0.05, Message("test.x")) + self._emit_after(0.10, Message("test.eof")) + + cs.capture(Message("test.trigger"), timeout=3) + returned = cs.finish() + + self.assertIsInstance(returned, list) + self.assertTrue(len(returned) >= 1, + "at least the trigger message must be in the list") + + def test_finish_stops_future_capture(self): + """After finish(), further bus messages must not append to responses.""" + cs = CaptureSession(self.mc, eof_msgs=["test.eof"], ignore_messages=[]) + self._emit_after(0.05, Message("test.eof")) # trigger finish quickly + cs.capture(Message("test.trigger"), timeout=3) + responses_before = cs.finish() + count_before = len(responses_before) + + # emit another message after finish — should be ignored + self.mc.bus.emit(Message("test.post.finish")) + import time; time.sleep(0.05) + + self.assertEqual(len(cs.responses), count_before, + "no new messages should be captured after finish()") + + def test_multiple_eof_types(self): + """Any message in the eof_msgs list should stop capture.""" + cs = CaptureSession(self.mc, + eof_msgs=["eof.alpha", "eof.beta"], + ignore_messages=[]) + self._emit_after(0.05, Message("test.x")) + self._emit_after(0.10, Message("eof.beta")) # second eof type + self._emit_after(0.20, Message("test.late")) # must not appear + + cs.capture(Message("test.trigger"), timeout=3) + msgs = cs.finish() + types = [m.msg_type for m in msgs] + + self.assertIn("test.x", types) + self.assertNotIn("test.late", types) + + def test_capture_timeout_returns_partial_results(self): + """If the EOF never fires, capture() must return after the timeout + and finish() must still return whatever was captured.""" + cs = CaptureSession(self.mc, eof_msgs=["never.fires"], ignore_messages=[]) + self._emit_after(0.05, Message("test.partial")) + # timeout=0.2 — EOF never fires + cs.capture(Message("test.trigger"), timeout=0.2) + msgs = cs.finish() + types = [m.msg_type for m in msgs] + self.assertIn("test.partial", types) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/unittests/test_end2end.py b/test/unittests/test_end2end.py new file mode 100644 index 0000000..b3696f5 --- /dev/null +++ b/test/unittests/test_end2end.py @@ -0,0 +1,531 @@ +"""Unit tests for End2EndTest — execute(), assertions, serialization, helpers.""" +import json +import os +import tempfile +import unittest + +from ovos_bus_client.message import Message +from ovos_bus_client.session import Session +from ovos_utils.log import LOG +from ovos_workshop.skills.ovos import OVOSSkill + +from ovoscope import End2EndTest, get_minicroft + +# --------------------------------------------------------------------------- +# Shared inline skill +# --------------------------------------------------------------------------- +SKILL_ID = "ovoscope-unittest-e2e.test" + +# Handler lifecycle messages emitted by add_event() wrappers. +# Tests that don't care about lifecycle use this to filter noise. +HANDLER_LIFECYCLE = ["mycroft.skill.handler.start", + "mycroft.skill.handler.complete"] + +# Minimal pipeline: only Adapt-high so we get predictable no-match / match +ADAPT_ONLY = ["ovos-adapt-pipeline-plugin-high"] + + +class EchoSkill(OVOSSkill): + """Handles 'unittest.echo': speaks the 'text' field, then emits EOF.""" + + def initialize(self): + self.add_event("unittest.echo", self.handle_echo) + + def handle_echo(self, message: Message): + text = message.data.get("text", "echo") + self.speak(text) + self.bus.emit(Message("ovos.utterance.handled", context=message.context)) + + +class SilentSkill(OVOSSkill): + """Handles 'unittest.silent': emits only EOF — no speak.""" + + def initialize(self): + self.add_event("unittest.silent", self.handle_silent) + + def handle_silent(self, message: Message): + self.bus.emit(Message("ovos.utterance.handled", context=message.context)) + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- +def _session(session_id: str = "unit-test-session", + pipeline=None) -> Session: + s = Session(session_id) + s.lang = "en-US" # explicit lang so tests don't depend on system locale + s.pipeline = pipeline or ADAPT_ONLY + return s + + +def _make_utterance(text: str = "hello world", + session_id: str = "unit-test-session", + pipeline=None) -> Message: + """Build a recognizer_loop:utterance message with an explicit pipeline.""" + sess = _session(session_id, pipeline) + return Message("recognizer_loop:utterance", + {"utterances": [text], "lang": "en-US"}, + {"session": sess.serialize(), + "source": "A", "destination": "B"}) + + +def _make_custom(msg_type: str, data=None, + session_id: str = "unit-test-session") -> Message: + """Build a custom event message (bypasses utterance pipeline).""" + sess = _session(session_id) + return Message(msg_type, data or {}, + {"session": sess.serialize(), + "source": "A", "destination": "B"}) + + +# Expected 4-message failure sequence for any utterance that matches nothing +_FAILURE_SEQ = [ + # message itself is index 0 (caller provides it) + Message("mycroft.audio.play_sound", {"uri": "snd/error.mp3"}), + Message("complete_intent_failure", {}), + Message("ovos.utterance.handled", {}), +] + + +# --------------------------------------------------------------------------- +# Tests: execute() return value +# --------------------------------------------------------------------------- +class TestExecuteReturnValue(unittest.TestCase): + + def setUp(self): + LOG.set_level("ERROR") + self.mc = get_minicroft([SKILL_ID], extra_skills={SKILL_ID: EchoSkill}) + + def tearDown(self): + self.mc.stop() + LOG.set_level("CRITICAL") + + def test_execute_returns_list(self): + """execute() must return a list (not None).""" + src = _make_custom("unittest.echo", {"text": "hello"}) + test = End2EndTest( + minicroft=self.mc, + skill_ids=[SKILL_ID], + source_message=src, + expected_messages=[src], # exact list doesn't matter here + test_message_number=False, + test_msg_type=False, + test_msg_data=False, + test_msg_context=False, + test_routing=False, + test_active_skills=False, + test_final_session=False, + test_async_messages=False, + test_async_message_number=False, + verbose=False, + ) + result = test.execute(timeout=10) + self.assertIsNotNone(result, "execute() must not return None") + self.assertIsInstance(result, list) + + def test_execute_returns_captured_messages(self): + """The returned list contains the actual Message objects.""" + src = _make_custom("unittest.echo", {"text": "world"}) + test = End2EndTest( + minicroft=self.mc, + skill_ids=[SKILL_ID], + source_message=src, + expected_messages=[src], + test_message_number=False, + test_msg_type=False, + test_msg_data=False, + test_msg_context=False, + test_routing=False, + test_active_skills=False, + test_final_session=False, + test_async_messages=False, + test_async_message_number=False, + verbose=False, + ) + result = test.execute(timeout=10) + types = [m.msg_type for m in result] + self.assertIn("unittest.echo", types) + self.assertIn("speak", types) + self.assertIn("ovos.utterance.handled", types) + + def test_execute_result_length_matches_expected(self): + """The returned list has exactly N messages when all are present. + + EchoSkill sequence (filtering handler lifecycle): + 1. unittest.echo (the source message) + 2. speak + 3. ovos.utterance.handled + """ + src = _make_custom("unittest.echo", {"text": "count test"}) + test = End2EndTest( + minicroft=self.mc, + skill_ids=[SKILL_ID], + source_message=src, + expected_messages=[ + src, + Message("speak", {"utterance": "count test"}), + Message("ovos.utterance.handled", {}), + ], + # filter out handler.start / handler.complete so count is 3 + ignore_messages=["ovos.skills.settings_changed"] + HANDLER_LIFECYCLE, + test_routing=False, + test_active_skills=False, + test_final_session=False, + test_async_messages=False, + test_async_message_number=False, + verbose=False, + ) + result = test.execute(timeout=10) + self.assertEqual(len(result), 3) + + +# --------------------------------------------------------------------------- +# Tests: assertion failures raise AssertionError +# --------------------------------------------------------------------------- +class TestAssertions(unittest.TestCase): + + def setUp(self): + LOG.set_level("ERROR") + self.mc = get_minicroft([SKILL_ID], extra_skills={SKILL_ID: EchoSkill}) + + def tearDown(self): + self.mc.stop() + LOG.set_level("CRITICAL") + + def _base_flags(self, **overrides): + defaults = dict( + test_message_number=False, + test_msg_type=False, + test_msg_data=False, + test_msg_context=False, + test_routing=False, + test_active_skills=False, + test_final_session=False, + test_async_messages=False, + test_async_message_number=False, + ignore_messages=["ovos.skills.settings_changed"] + HANDLER_LIFECYCLE, + verbose=False, + ) + defaults.update(overrides) + return defaults + + def test_wrong_message_count_raises(self): + """test_message_number=True raises AssertionError on count mismatch.""" + src = _make_custom("unittest.echo", {"text": "count"}) + test = End2EndTest( + minicroft=self.mc, + skill_ids=[SKILL_ID], + source_message=src, + expected_messages=[src], # only 1 but 3 will be captured + **self._base_flags(test_message_number=True), + ) + with self.assertRaises(AssertionError): + test.execute(timeout=10) + + def test_wrong_message_type_raises(self): + """test_msg_type=True raises AssertionError when msg_type doesn't match.""" + src = _make_custom("unittest.echo", {"text": "type test"}) + test = End2EndTest( + minicroft=self.mc, + skill_ids=[SKILL_ID], + source_message=src, + expected_messages=[ + src, + Message("WRONG.TYPE", {}), # actual is "speak" + Message("ovos.utterance.handled", {}), + ], + **self._base_flags(test_msg_type=True), + ) + with self.assertRaises(AssertionError): + test.execute(timeout=10) + + def test_wrong_message_data_raises(self): + """test_msg_data=True raises AssertionError on data key mismatch.""" + src = _make_custom("unittest.echo", {"text": "data test"}) + test = End2EndTest( + minicroft=self.mc, + skill_ids=[SKILL_ID], + source_message=src, + expected_messages=[ + src, + Message("speak", {"utterance": "WRONG TEXT"}), + Message("ovos.utterance.handled", {}), + ], + **self._base_flags(test_msg_data=True), + ) + with self.assertRaises(AssertionError): + test.execute(timeout=10) + + def test_disable_data_assertion_ignores_wrong_data(self): + """test_msg_data=False passes even with wrong expected data values.""" + src = _make_custom("unittest.echo", {"text": "data off"}) + test = End2EndTest( + minicroft=self.mc, + skill_ids=[SKILL_ID], + source_message=src, + expected_messages=[ + src, + Message("speak", {"utterance": "WRONG TEXT"}), + Message("ovos.utterance.handled", {}), + ], + **self._base_flags(test_msg_data=False), + ) + # must not raise + test.execute(timeout=10) + + def test_disable_count_assertion_allows_count_mismatch(self): + """test_message_number=False allows more or fewer messages than expected.""" + src = _make_custom("unittest.echo", {"text": "count off"}) + test = End2EndTest( + minicroft=self.mc, + skill_ids=[SKILL_ID], + source_message=src, + expected_messages=[src], # only 1; 3+ will be received + **self._base_flags(test_message_number=False), + ) + test.execute(timeout=10) + + def test_ignore_messages_excluded_from_captured_list(self): + """Messages in ignore_messages do not appear in the captured sequence.""" + src = _make_custom("unittest.echo", {"text": "filter"}) + # Add "speak" to ignored — only 2 messages remain: src + eof + test = End2EndTest( + minicroft=self.mc, + skill_ids=[SKILL_ID], + source_message=src, + expected_messages=[ + src, + Message("ovos.utterance.handled", {}), + ], + ignore_messages=["ovos.skills.settings_changed", "speak"] + + HANDLER_LIFECYCLE, + test_routing=False, + test_active_skills=False, + test_final_session=False, + test_async_messages=False, + test_async_message_number=False, + verbose=False, + ) + test.execute(timeout=10) + + +# --------------------------------------------------------------------------- +# Tests: managed lifecycle (no minicroft pre-supplied) +# --------------------------------------------------------------------------- +class TestManagedLifecycle(unittest.TestCase): + + def setUp(self): + LOG.set_level("ERROR") + + def tearDown(self): + LOG.set_level("CRITICAL") + + def test_execute_creates_and_stops_minicroft_when_unmanaged(self): + """If minicroft is not supplied, execute() creates and stops one.""" + # Explicit pipeline so persona/OCP/fallback don't interfere + message = _make_utterance("hello world", pipeline=ADAPT_ONLY) + test = End2EndTest( + skill_ids=[], + source_message=message, + expected_messages=[ + message, + Message("mycroft.audio.play_sound", {"uri": "snd/error.mp3"}), + Message("complete_intent_failure", {}), + Message("ovos.utterance.handled", {}), + ], + flip_points=["recognizer_loop:utterance"], + test_routing=False, + test_active_skills=False, + test_final_session=False, + test_async_messages=False, + test_async_message_number=False, + verbose=False, + ) + result = test.execute(timeout=15) + self.assertIsInstance(result, list) + self.assertIsNone(test.minicroft, + "managed minicroft must be cleaned up after execute()") + + +# --------------------------------------------------------------------------- +# Tests: assert_spoke() sugar method +# --------------------------------------------------------------------------- +class TestAssertSpoke(unittest.TestCase): + + def setUp(self): + LOG.set_level("ERROR") + self.mc = get_minicroft([SKILL_ID], extra_skills={SKILL_ID: EchoSkill}) + + def tearDown(self): + self.mc.stop() + LOG.set_level("CRITICAL") + + def _spoke_test(self, text: str) -> End2EndTest: + """Build an End2EndTest configured for assert_spoke (all checks disabled).""" + src = _make_custom("unittest.echo", {"text": text}) + return End2EndTest( + minicroft=self.mc, + skill_ids=[SKILL_ID], + source_message=src, + expected_messages=[src], # doesn't matter — all checks off + test_message_number=False, + test_msg_type=False, + test_msg_data=False, + test_msg_context=False, + test_routing=False, + test_active_skills=False, + test_final_session=False, + test_async_messages=False, + test_async_message_number=False, + verbose=False, + ) + + def test_assert_spoke_passes_correct_utterance(self): + """assert_spoke does not raise when the speak utterance matches.""" + self._spoke_test("correct text").assert_spoke("correct text", timeout=10) + + def test_assert_spoke_fails_wrong_utterance(self): + """assert_spoke raises AssertionError when the speak utterance is absent.""" + with self.assertRaises(AssertionError): + self._spoke_test("correct text").assert_spoke("WRONG TEXT", timeout=10) + + +# --------------------------------------------------------------------------- +# Tests: serialization round-trip (serialize / deserialize / save / from_path) +# --------------------------------------------------------------------------- +class TestSerialization(unittest.TestCase): + + def setUp(self): + LOG.set_level("ERROR") + + def tearDown(self): + LOG.set_level("CRITICAL") + + def _make_simple_test(self) -> End2EndTest: + """A deterministic no-match test with an explicit Adapt-only pipeline. + + test_msg_context=False: anonymize_message() replaces session context in + expected_messages with the default SessionManager session, which would + cause context mismatches on replay. Disabling context checks avoids that. + """ + src = _make_utterance("hello world", session_id="serial-session", + pipeline=ADAPT_ONLY) + return End2EndTest( + skill_ids=[], + source_message=src, + expected_messages=[ + src, + Message("mycroft.audio.play_sound", {"uri": "snd/error.mp3"}), + Message("complete_intent_failure", {}), + Message("ovos.utterance.handled", {}), + ], + flip_points=["recognizer_loop:utterance"], + test_msg_context=False, # see docstring + ) + + def test_serialize_returns_dict(self): + data = self._make_simple_test().serialize() + self.assertIsInstance(data, dict) + self.assertIn("skill_ids", data) + self.assertIn("source_message", data) + self.assertIn("expected_messages", data) + + def test_deserialize_round_trip(self): + original = self._make_simple_test() + data = original.serialize(anonymize=False) + restored = End2EndTest.deserialize(data) + + self.assertEqual(restored.skill_ids, original.skill_ids) + self.assertEqual(len(restored.source_message), len(original.source_message)) + for e, r in zip(original.expected_messages, restored.expected_messages): + self.assertEqual(e.msg_type, r.msg_type) + + def test_save_and_from_path(self): + """save() then from_path() produces an executable End2EndTest.""" + original = self._make_simple_test() + with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f: + path = f.name + try: + original.save(path, anonymize=True) + with open(path) as f: + data = json.load(f) + self.assertIn("skill_ids", data) + + restored = End2EndTest.from_path(path) + result = restored.execute(timeout=15) + self.assertIsInstance(result, list) + self.assertEqual(len(result), 4) + finally: + os.unlink(path) + + def test_anonymize_strips_location(self): + """save(anonymize=True) replaces location data with N/A.""" + original = self._make_simple_test() + with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f: + path = f.name + try: + original.save(path, anonymize=True) + with open(path) as f: + data = json.load(f) + src_ctx = data["source_message"][0].get("context", {}) + loc = src_ctx.get("session", {}).get("location_preferences", {}) + if loc: + self.assertEqual(loc.get("city", {}).get("name"), "N/A") + finally: + os.unlink(path) + + +# --------------------------------------------------------------------------- +# Tests: multi-turn (list of source messages) +# --------------------------------------------------------------------------- +class TestMultiTurn(unittest.TestCase): + + def setUp(self): + LOG.set_level("ERROR") + self.mc = get_minicroft([]) + + def tearDown(self): + self.mc.stop() + LOG.set_level("CRITICAL") + + def test_multi_turn_two_failures(self): + """Two turns that both fail produce 8 messages total.""" + # Explicit Adapt-only pipeline so persona doesn't intercept + sess = _session("multi-turn", pipeline=ADAPT_ONLY) + turn1 = Message("recognizer_loop:utterance", + {"utterances": ["turn one"], "lang": "en-US"}, + {"session": sess.serialize(), + "source": "A", "destination": "B"}) + # turn2 has no session — ovoscope propagates from last received message + turn2 = Message("recognizer_loop:utterance", + {"utterances": ["turn two"], "lang": "en-US"}, + {"source": "A", "destination": "B"}) + + test = End2EndTest( + minicroft=self.mc, + skill_ids=[], + source_message=[turn1, turn2], + expected_messages=[ + turn1, + Message("mycroft.audio.play_sound", {"uri": "snd/error.mp3"}), + Message("complete_intent_failure", {}), + Message("ovos.utterance.handled", {}), + turn2, + Message("mycroft.audio.play_sound", {"uri": "snd/error.mp3"}), + Message("complete_intent_failure", {}), + Message("ovos.utterance.handled", {}), + ], + flip_points=["recognizer_loop:utterance"], + test_routing=False, + test_active_skills=False, + test_final_session=False, + test_async_messages=False, + test_async_message_number=False, + verbose=False, + ) + result = test.execute(timeout=20) + self.assertEqual(len(result), 8) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/unittests/test_minicroft.py b/test/unittests/test_minicroft.py new file mode 100644 index 0000000..f71d8e1 --- /dev/null +++ b/test/unittests/test_minicroft.py @@ -0,0 +1,212 @@ +"""Unit tests for MiniCroft and get_minicroft().""" +import threading +import unittest + +from ovos_bus_client.message import Message +from ovos_utils.log import LOG +from ovos_workshop.skills.ovos import OVOSSkill + +from ovos_bus_client.session import SessionManager + +from ovoscope import MiniCroft, get_minicroft, DEFAULT_TEST_PIPELINE, ADAPT_PIPELINE + + +# --------------------------------------------------------------------------- +# Minimal inline skill used across tests +# --------------------------------------------------------------------------- +SKILL_ID = "ovoscope-unittest-minicroft.test" + + +class PingSkill(OVOSSkill): + """Emits 'unittest.pong' in response to 'unittest.ping'.""" + + def initialize(self): + self.add_event("unittest.ping", self.handle_ping) + + def handle_ping(self, message: Message): + self.bus.emit(Message("unittest.pong", + data={"reply": "pong"}, + context=message.context)) + + +# --------------------------------------------------------------------------- +# Tests +# --------------------------------------------------------------------------- +class TestGetMiniCroft(unittest.TestCase): + + def setUp(self): + LOG.set_level("ERROR") + + def tearDown(self): + LOG.set_level("CRITICAL") + + def test_empty_skills_reaches_ready(self): + """get_minicroft([]) should start successfully with no skills.""" + mc = get_minicroft([]) + try: + from ovos_utils.process_utils import ProcessState + self.assertEqual(mc.status.state, ProcessState.READY) + finally: + mc.stop() + + def test_extra_skill_is_loaded(self): + """An inline skill passed via extra_skills must appear in plugin_skills.""" + mc = get_minicroft([SKILL_ID], extra_skills={SKILL_ID: PingSkill}) + try: + self.assertIn(SKILL_ID, mc.plugin_skills, + "extra skill should be registered in plugin_skills") + finally: + mc.stop() + + def test_max_wait_timeout_raises(self): + """max_wait=0 should raise TimeoutError because MiniCroft can't be + instantaneous — the underlying thread needs time to start.""" + with self.assertRaises(TimeoutError): + get_minicroft([], max_wait=0) + + def test_skill_ids_string_normalised_to_list(self): + """Passing a bare string is equivalent to passing a single-element list.""" + mc = get_minicroft(SKILL_ID, extra_skills={SKILL_ID: PingSkill}) + try: + self.assertIn(SKILL_ID, mc.plugin_skills) + finally: + mc.stop() + + def test_returns_minicroft_instance(self): + mc = get_minicroft([]) + try: + self.assertIsInstance(mc, MiniCroft) + finally: + mc.stop() + + +class TestMiniCroftPipelineIsolation(unittest.TestCase): + """Tests for MiniCroft default_pipeline override.""" + + def setUp(self): + LOG.set_level("ERROR") + + def tearDown(self): + LOG.set_level("CRITICAL") + + def test_default_pipeline_overrides_default_session(self): + """default_pipeline is applied to SessionManager.default_session.""" + mc = get_minicroft([], default_pipeline=ADAPT_PIPELINE) + try: + self.assertEqual(SessionManager.default_session.pipeline, ADAPT_PIPELINE) + finally: + mc.stop() + + def test_default_pipeline_restored_after_stop(self): + """After stop(), default_session.pipeline is restored to its previous value.""" + original = SessionManager.default_session.pipeline[:] + mc = get_minicroft([], default_pipeline=ADAPT_PIPELINE) + mc.stop() + self.assertEqual(SessionManager.default_session.pipeline, original) + + def test_isolate_config_uses_default_test_pipeline(self): + """isolate_config=True with no explicit default_pipeline uses DEFAULT_TEST_PIPELINE.""" + mc = get_minicroft([]) + try: + self.assertEqual(SessionManager.default_session.pipeline, DEFAULT_TEST_PIPELINE) + finally: + mc.stop() + + def test_persona_stages_absent_from_default_test_pipeline(self): + """DEFAULT_TEST_PIPELINE must not contain any persona or LLM pipeline stage.""" + for stage in DEFAULT_TEST_PIPELINE: + self.assertNotIn("persona", stage, f"persona stage found: {stage}") + self.assertNotIn("ollama", stage, f"ollama stage found: {stage}") + self.assertNotIn("m2v", stage, f"m2v stage found: {stage}") + + def test_no_pipeline_override_when_none(self): + """default_pipeline=None must not alter the existing default session pipeline.""" + before = SessionManager.default_session.pipeline[:] + mc = get_minicroft([], isolate_config=False, default_pipeline=None) + try: + self.assertEqual(SessionManager.default_session.pipeline, before) + finally: + mc.stop() + + +class TestMiniCroftInjectMessage(unittest.TestCase): + """Tests for MiniCroft.inject_message().""" + + def setUp(self): + LOG.set_level("ERROR") + self.skill_id = SKILL_ID + self.mc = get_minicroft([self.skill_id], + extra_skills={self.skill_id: PingSkill}) + + def tearDown(self): + self.mc.stop() + LOG.set_level("CRITICAL") + + def test_inject_message_delivers_to_skill(self): + """inject_message() should cause the skill handler to fire.""" + received = threading.Event() + pong_msgs = [] + + # Named message handlers on FakeBus receive Message objects directly; + # only the generic "message" wildcard receives raw serialised strings. + def on_pong(msg: Message): + pong_msgs.append(msg) + received.set() + + self.mc.bus.on("unittest.pong", on_pong) + try: + self.mc.inject_message(Message("unittest.ping", + context={"source": "A", "destination": "B"})) + received.wait(timeout=5) + self.assertTrue(received.is_set(), "pong not received within 5s") + self.assertEqual(len(pong_msgs), 1) + self.assertEqual(pong_msgs[0].data["reply"], "pong") + finally: + self.mc.bus.remove("unittest.pong", on_pong) + + def test_inject_message_does_not_go_through_utterance_pipeline(self): + """inject_message() bypasses the intent pipeline — no utterance.handled.""" + handled = threading.Event() + + def on_handled(msg: Message): + handled.set() + + self.mc.bus.on("ovos.utterance.handled", on_handled) + try: + self.mc.inject_message( + Message("some.arbitrary.event", context={"source": "A"})) + # give it a moment + handled.wait(timeout=1) + self.assertFalse(handled.is_set(), + "inject_message should NOT trigger utterance pipeline") + finally: + self.mc.bus.remove("ovos.utterance.handled", on_handled) + + def test_inject_message_with_data(self): + """Data and context passed to inject_message are forwarded intact.""" + received = threading.Event() + captured = [] + + def on_ping(raw: str): + captured.append(Message.deserialize(raw)) + received.set() + + self.mc.bus.on("message", on_ping) + try: + self.mc.inject_message( + Message("test.data.check", + data={"key": "value"}, + context={"ctx": "test"})) + received.wait(timeout=2) + # find our message + match = [m for m in captured + if m.msg_type == "test.data.check"] + self.assertTrue(match, "injected message not found on bus") + self.assertEqual(match[0].data["key"], "value") + self.assertEqual(match[0].context["ctx"], "test") + finally: + self.mc.bus.remove("message", on_ping) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/unittests/test_pydantic_helpers.py b/test/unittests/test_pydantic_helpers.py new file mode 100644 index 0000000..b4c3431 --- /dev/null +++ b/test/unittests/test_pydantic_helpers.py @@ -0,0 +1,269 @@ +"""Unit tests for ovoscope.pydantic_helpers. + +All tests require ovos-pydantic-models (ovoscope[pydantic]). +The suite is skipped as a whole if that optional dependency is missing. +""" +import json +import tempfile +import unittest +from pathlib import Path + +from ovos_bus_client.message import Message +from ovos_utils.log import LOG + +try: + from ovos_pydantic_models import ( + RecognizerLoopUtteranceData, + RecognizerLoopUtteranceMessage, + SpeakData, + SpeakMessage, + ) + from ovos_pydantic_models.message import OpenVoiceOSMessage + from pydantic import ValidationError + _PYDANTIC_AVAILABLE = True +except ImportError: + _PYDANTIC_AVAILABLE = False + +from ovoscope.pydantic_helpers import ( + from_bus_message, + to_bus_message, + validate_fixture, +) + + +@unittest.skipUnless(_PYDANTIC_AVAILABLE, "ovos-pydantic-models not installed") +class TestToBusMessage(unittest.TestCase): + """Tests for to_bus_message().""" + + def setUp(self) -> None: + LOG.set_level("ERROR") + + def test_msg_type_is_set(self) -> None: + """msg_type on the returned Message must match the pydantic model's message_type.""" + model = SpeakMessage(data=SpeakData(utterance="hello")) + msg = to_bus_message(model) + self.assertEqual(msg.msg_type, "speak") + + def test_data_fields_are_preserved(self) -> None: + """Data fields from the pydantic model must appear in Message.data.""" + model = SpeakMessage(data=SpeakData(utterance="hello world")) + msg = to_bus_message(model) + self.assertEqual(msg.data["utterance"], "hello world") + + def test_returns_message_instance(self) -> None: + """Return type must be ovos_bus_client.message.Message.""" + model = SpeakMessage(data=SpeakData(utterance="hi")) + result = to_bus_message(model) + self.assertIsInstance(result, Message) + + def test_utterance_message_type(self) -> None: + """recognizer_loop:utterance message type is preserved.""" + model = RecognizerLoopUtteranceMessage( + data=RecognizerLoopUtteranceData(utterances=["hello"], lang="en-us") + ) + msg = to_bus_message(model) + self.assertEqual(msg.msg_type, "recognizer_loop:utterance") + self.assertEqual(msg.data["utterances"], ["hello"]) + + def test_empty_context_defaults_to_dict(self) -> None: + """Context must be a dict even when the model has no context fields set.""" + model = SpeakMessage(data=SpeakData(utterance="hi")) + msg = to_bus_message(model) + self.assertIsInstance(msg.context, dict) + + def test_roundtrip_preserves_utterance(self) -> None: + """to_bus_message followed by from_bus_message yields the same utterance.""" + original = SpeakMessage(data=SpeakData(utterance="round trip")) + bus_msg = to_bus_message(original) + recovered = from_bus_message(bus_msg, SpeakMessage) + self.assertEqual(recovered.data.utterance, "round trip") + + +@unittest.skipUnless(_PYDANTIC_AVAILABLE, "ovos-pydantic-models not installed") +class TestFromBusMessage(unittest.TestCase): + """Tests for from_bus_message().""" + + def setUp(self) -> None: + LOG.set_level("ERROR") + + def test_valid_speak_message(self) -> None: + """A well-formed speak Message parses into SpeakMessage without errors.""" + bus_msg = Message("speak", {"utterance": "hello", "lang": "en-us"}, {}) + result = from_bus_message(bus_msg, SpeakMessage) + self.assertIsInstance(result, SpeakMessage) + self.assertEqual(result.data.utterance, "hello") + + def test_valid_utterance_message(self) -> None: + """A well-formed recognizer_loop:utterance parses into the typed model.""" + bus_msg = Message( + "recognizer_loop:utterance", + {"utterances": ["what time is it"], "lang": "en-us"}, + {}, + ) + result = from_bus_message(bus_msg, RecognizerLoopUtteranceMessage) + self.assertEqual(result.data.utterances, ["what time is it"]) + + def test_returns_correct_model_type(self) -> None: + """The returned object must be an instance of the requested model class.""" + bus_msg = Message("speak", {"utterance": "test"}, {}) + result = from_bus_message(bus_msg, SpeakMessage) + self.assertIsInstance(result, SpeakMessage) + + def test_invalid_message_raises_validation_error(self) -> None: + """A message whose data violates the schema must raise ValidationError.""" + # RecognizerLoopUtteranceMessage requires 'utterances' to be a list, not a string + bus_msg = Message( + "recognizer_loop:utterance", + {"utterances": "not-a-list", "lang": "en-us"}, + {}, + ) + with self.assertRaises(ValidationError): + from_bus_message(bus_msg, RecognizerLoopUtteranceMessage) + + def test_base_model_accepts_any_well_formed_message(self) -> None: + """OpenVoiceOSMessage accepts any message_type + dict data.""" + bus_msg = Message("custom.event", {"key": "value"}, {}) + result = from_bus_message(bus_msg, OpenVoiceOSMessage) + self.assertEqual(result.message_type, "custom.event") + + +@unittest.skipUnless(_PYDANTIC_AVAILABLE, "ovos-pydantic-models not installed") +class TestValidateFixture(unittest.TestCase): + """Tests for validate_fixture().""" + + def setUp(self) -> None: + LOG.set_level("ERROR") + + # ------------------------------------------------------------------ + # helpers + # ------------------------------------------------------------------ + def _write_fixture(self, data: dict) -> Path: + """Write data as JSON to a temp file and return its Path.""" + f = tempfile.NamedTemporaryFile( + mode="w", suffix=".json", delete=False + ) + json.dump(data, f) + f.close() + return Path(f.name) + + def _valid_fixture(self) -> dict: + """Minimal valid fixture dict matching End2EndTest.serialize() format.""" + return { + "skill_ids": ["test-skill.author"], + "source_message": [ + { + "type": "recognizer_loop:utterance", + "data": {"utterances": ["hello"], "lang": "en-us"}, + "context": {}, + } + ], + "expected_messages": [ + { + "type": "speak", + "data": {"utterance": "Hello!", "lang": "en-us"}, + "context": {}, + } + ], + "eof_msgs": ["ovos.utterance.handled"], + "flip_points": [], + "test_msg_type": True, + "test_msg_data": True, + "test_msg_context": False, + "test_routing": False, + } + + # ------------------------------------------------------------------ + # tests + # ------------------------------------------------------------------ + def test_valid_fixture_returns_dict(self) -> None: + """validate_fixture returns the raw fixture dict on success.""" + fixture = self._valid_fixture() + path = self._write_fixture(fixture) + result = validate_fixture(path) + self.assertEqual(result["skill_ids"], ["test-skill.author"]) + + def test_valid_fixture_source_preserved(self) -> None: + """source_message entries are preserved verbatim in the returned dict.""" + fixture = self._valid_fixture() + path = self._write_fixture(fixture) + result = validate_fixture(path) + self.assertEqual( + result["source_message"][0]["type"], + "recognizer_loop:utterance", + ) + + def test_valid_fixture_expected_preserved(self) -> None: + """expected_messages entries are preserved verbatim in the returned dict.""" + fixture = self._valid_fixture() + path = self._write_fixture(fixture) + result = validate_fixture(path) + self.assertEqual(result["expected_messages"][0]["data"]["utterance"], "Hello!") + + def test_missing_file_raises_file_not_found(self) -> None: + """validate_fixture raises FileNotFoundError for a non-existent path.""" + with self.assertRaises(FileNotFoundError): + validate_fixture("/tmp/ovoscope_nonexistent_fixture_xyz.json") + + def test_malformed_source_message_raises_value_error(self) -> None: + """A source_message without any type key must raise ValueError. + + validate_fixture uses OpenVoiceOSMessage which requires 'message_type'. + When both 'type' and 'message_type' are absent the field is missing + and pydantic raises ValidationError, which is chained into ValueError. + """ + fixture = self._valid_fixture() + # Remove both 'type' and 'message_type' — normalised dict will be missing + # the required 'message_type' field and pydantic will reject it. + fixture["source_message"][0] = {"data": {"utterances": ["hi"]}, "context": {}} + path = self._write_fixture(fixture) + with self.assertRaises(ValueError) as ctx: + validate_fixture(path) + self.assertIn("source_message[0]", str(ctx.exception)) + + def test_malformed_expected_message_raises_value_error(self) -> None: + """A malformed expected_message must raise ValueError with section info.""" + fixture = self._valid_fixture() + # context must be a dict — providing a non-dict triggers MessageContext + # validation error inside OpenVoiceOSMessage, which is chained into ValueError. + fixture["expected_messages"][0] = { + "type": "speak", + "data": {"utterance": "hi"}, + "context": "not-a-dict", + } + path = self._write_fixture(fixture) + with self.assertRaises(ValueError) as ctx: + validate_fixture(path) + self.assertIn("expected_messages[0]", str(ctx.exception)) + + def test_error_chains_validation_error(self) -> None: + """The ValueError raised must chain the original pydantic ValidationError.""" + fixture = self._valid_fixture() + # Remove both type keys so message_type is missing from normalised dict + fixture["source_message"][0] = {"data": {"utterances": ["hi"]}, "context": {}} + path = self._write_fixture(fixture) + with self.assertRaises(ValueError) as ctx: + validate_fixture(path) + self.assertIsInstance(ctx.exception.__cause__, ValidationError) + + def test_accepts_message_type_key(self) -> None: + """validate_fixture accepts both 'type' and 'message_type' as the key.""" + fixture = self._valid_fixture() + # Use 'message_type' instead of 'type' + msg = fixture["source_message"][0] + msg["message_type"] = msg.pop("type") + path = self._write_fixture(fixture) + result = validate_fixture(path) + self.assertIsNotNone(result) + + def test_empty_messages_lists_pass(self) -> None: + """Fixtures with empty source/expected lists must pass validation.""" + fixture = self._valid_fixture() + fixture["source_message"] = [] + fixture["expected_messages"] = [] + path = self._write_fixture(fixture) + result = validate_fixture(path) + self.assertEqual(result["source_message"], []) + + +if __name__ == "__main__": + unittest.main()