diff --git a/.github/workflows/unit_tests.yml b/.github/workflows/unit_tests.yml index 843f75a7bda5..689d63e675bf 100644 --- a/.github/workflows/unit_tests.yml +++ b/.github/workflows/unit_tests.yml @@ -60,7 +60,6 @@ jobs: pip install ./test/end2end/skill-new-stop pip install ./test/end2end/skill-old-stop pip install ./test/end2end/skill-fake-fm - pip install ./test/end2end/skill-fake-fm-legacy pip install ./test/end2end/skill-ovos-fakewiki pip install ./test/end2end/metadata-test-plugin - name: Install core repo @@ -72,7 +71,7 @@ jobs: # NOTE: additional pytest invocations should also add the --cov-append flag # or they will overwrite previous invocations' coverage reports # (for an example, see OVOS Skill Manager's workflow) - - name: Run full core unittests + - name: Run end2end tests run: | pytest --cov-append --cov=ovos_core --cov-report xml test/end2end - name: Run integration tests diff --git a/test/end2end/session/test_ocp.py b/test/end2end/session/test_ocp.py index 8fc82ae4dbe9..c7aa7570a41b 100644 --- a/test/end2end/session/test_ocp.py +++ b/test/end2end/session/test_ocp.py @@ -1182,85 +1182,3 @@ def wait_for_n_messages(n): for idx, m in enumerate(messages): self.assertEqual(m.msg_type, expected_messages[idx]) - -class TestLegacyCPSPipeline(TestCase): - - def setUp(self): - self.skill_id = "skill-fake-fm-legacy.openvoiceos" - self.core = get_minicroft(self.skill_id) - self.core.intent_service.ocp.config = {"legacy_cps": True} - - def tearDown(self) -> None: - self.core.stop() - - def test_legacy_cps(self): - self.assertIsNotNone(self.core.intent_service.ocp) - - messages = [] - - def new_msg(msg): - nonlocal messages - m = Message.deserialize(msg) - if m.msg_type in ["ovos.skills.settings_changed", "gui.status.request"]: - return # skip these, only happen in 1st run - messages.append(m) - print(len(messages), msg) - - def wait_for_n_messages(n): - nonlocal messages - t = time.time() - while len(messages) < n: - sleep(0.1) - if time.time() - t > 10: - raise RuntimeError("did not get the number of expected messages under 10 seconds") - - self.core.bus.on("message", new_msg) - - sess = Session("test-session", - pipeline=[ - "ocp_legacy" - ]) - utt = Message("recognizer_loop:utterance", - {"utterances": ["play rammstein"]}, - {"session": sess.serialize(), # explicit - }) - self.core.bus.emit(utt) - - # confirm all expected messages are sent - expected_messages = [ - "recognizer_loop:utterance", - "intent.service.skills.activated", - "ovos.common_play.activate", - "ocp:legacy_cps", - # legacy cps api - "play:query", - "play:query.response", # searching - "play:query.response", # report results - "play:start", # skill selected - "mycroft.audio.service.track_info", # check is legacy audio service is playing - # global stop signal - "mycroft.stop", - "common_query.openvoiceos.stop", - "common_query.openvoiceos.stop.response", - "ovos.common_play.stop", - "ovos.common_play.stop.response", - "skill-fake-fm-legacy.openvoiceos.stop", - "skill-fake-fm-legacy.openvoiceos.stop.response", - "mycroft.audio.service.track_info", # check is legacy audio service is playing - # activate skill - "intent.service.skills.activate", - "intent.service.skills.activated", - f"{self.skill_id}.activate", - # skill callback code - "mycroft.audio.service.play", - "ovos.utterance.handled" # handle_utterance returned (intent service) - ] - wait_for_n_messages(len(expected_messages)) - - #self.assertEqual(len(expected_messages), len(messages)) - - for idx, m in enumerate(messages): - self.assertEqual(m.msg_type, expected_messages[idx]) - - play = messages[-2] - self.assertEqual(play.data["tracks"], ["https://fake.mp3"]) diff --git a/test/end2end/skill-fake-fm-legacy/__init__.py b/test/end2end/skill-fake-fm-legacy/__init__.py deleted file mode 100644 index f5bdbad46c7c..000000000000 --- a/test/end2end/skill-fake-fm-legacy/__init__.py +++ /dev/null @@ -1,36 +0,0 @@ -from typing import Tuple - -from mycroft.skills.common_play_skill import CommonPlaySkill, CPSMatchLevel - - -class FakeFMLegacySkill(CommonPlaySkill): - - def CPS_match_query_phrase(self, phrase: str) -> Tuple[str, float, dict]: - """Respond to Common Play Service query requests. - - Args: - phrase: utterance request to parse - - Returns: - Tuple(Name of station, confidence, Station information) - """ - score = 50 - if "fake" in phrase: - score += 35 - - # Translate match confidence levels to CPSMatchLevels - if score >= 90: - match_level = CPSMatchLevel.EXACT - elif score >= 70: - match_level = CPSMatchLevel.ARTIST - elif score >= 50: - match_level = CPSMatchLevel.CATEGORY - else: - return None - - cb = {"uri": f"https://fake.mp3", "foo": "bar"} - return phrase, match_level, cb - - def CPS_start(self, phrase, data): - """Handle request from Common Play System to start playback.""" - self.audioservice.play(data["uri"]) diff --git a/test/end2end/skill-fake-fm-legacy/setup.py b/test/end2end/skill-fake-fm-legacy/setup.py deleted file mode 100755 index c20d9dfce5c7..000000000000 --- a/test/end2end/skill-fake-fm-legacy/setup.py +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env python3 -from os import walk, path - -from setuptools import setup - -URL = "https://github.com/OpenVoiceOS/skill-fake-fm-legacy" -SKILL_CLAZZ = "FakeFMLegacySkill" # needs to match __init__.py class name - -# below derived from github url to ensure standard skill_id -SKILL_AUTHOR, SKILL_NAME = URL.split(".com/")[-1].split("/") -SKILL_PKG = SKILL_NAME.lower().replace('-', '_') -PLUGIN_ENTRY_POINT = f'{SKILL_NAME.lower()}.{SKILL_AUTHOR.lower()}={SKILL_PKG}:{SKILL_CLAZZ}' - - -# skill_id=package_name:SkillClass - - -def find_resource_files(): - resource_base_dirs = ("locale", "ui", "vocab", "dialog", "regex", "skill") - base_dir = path.dirname(__file__) - package_data = ["*.json"] - for res in resource_base_dirs: - if path.isdir(path.join(base_dir, res)): - for (directory, _, files) in walk(path.join(base_dir, res)): - if files: - package_data.append( - path.join(directory.replace(base_dir, "").lstrip('/'), - '*')) - return package_data - - -setup( - name="skill-fake-fm-legacy", - version="0.0.0", - long_description="test", - description='OVOS test plugin', - author_email='jarbasai@mailfence.com', - license='Apache-2.0', - package_dir={SKILL_PKG: ""}, - package_data={SKILL_PKG: find_resource_files()}, - packages=[SKILL_PKG], - include_package_data=True, - install_requires=["ovos-workshop>=0.0.16a8"], - keywords='ovos skill plugin', - entry_points={'ovos.plugin.skill': PLUGIN_ENTRY_POINT} -) diff --git a/test/integrationtests/__init__.py b/test/integrationtests/__init__.py deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/test/integrationtests/ovos_tskill_abort/__init__.py b/test/integrationtests/ovos_tskill_abort/__init__.py deleted file mode 100644 index 4cb618ccffbd..000000000000 --- a/test/integrationtests/ovos_tskill_abort/__init__.py +++ /dev/null @@ -1,60 +0,0 @@ -from ovos_workshop.decorators import killable_intent -from ovos_workshop.skills.ovos import OVOSSkill -from mycroft.skills import intent_file_handler -from time import sleep - - -class TestAbortSkill(OVOSSkill): - """ - send "mycroft.skills.abort_question" and confirm only get_response is aborted - send "mycroft.skills.abort_execution" and confirm the full intent is aborted, except intent3 - send "my.own.abort.msg" and confirm intent3 is aborted - say "stop" and confirm all intents are aborted - """ - def __init__(self, *args, **kwargs): - super(TestAbortSkill, self).__init__(*args, **kwargs) - self.my_special_var = "default" - self.stop_called = False - - def handle_intent_aborted(self): - self.speak("I am dead") - # handle any cleanup the skill might need, since intent was killed - # at an arbitrary place of code execution some variables etc. might - # end up in unexpected states - self.my_special_var = "default" - - @killable_intent(callback=handle_intent_aborted) - @intent_file_handler("test.intent") - def handle_test_abort_intent(self, message): - self.stop_called = False - self.my_special_var = "changed" - while True: - sleep(1) - self.speak("still here") - - @intent_file_handler("test2.intent") - @killable_intent(callback=handle_intent_aborted) - def handle_test_get_response_intent(self, message): - self.stop_called = False - self.my_special_var = "CHANGED" - ans = self.get_response("question", num_retries=99999) - self.log.debug("get_response returned: " + str(ans)) - if ans is None: - self.speak("question aborted") - - @killable_intent(msg="my.own.abort.msg", callback=handle_intent_aborted) - @intent_file_handler("test3.intent") - def handle_test_msg_intent(self, message): - self.stop_called = False - if self.my_special_var != "default": - self.speak("someone forgot to cleanup") - while True: - sleep(1) - self.speak("you can't abort me") - - def stop(self): - self.stop_called = True - - -def create_skill(): - return TestAbortSkill() diff --git a/test/integrationtests/ovos_tskill_abort/locale/en-us/question.dialog b/test/integrationtests/ovos_tskill_abort/locale/en-us/question.dialog deleted file mode 100644 index f0fb83cc4f33..000000000000 --- a/test/integrationtests/ovos_tskill_abort/locale/en-us/question.dialog +++ /dev/null @@ -1 +0,0 @@ -this is a question \ No newline at end of file diff --git a/test/integrationtests/ovos_tskill_abort/locale/en-us/test.intent b/test/integrationtests/ovos_tskill_abort/locale/en-us/test.intent deleted file mode 100644 index 30d74d258442..000000000000 --- a/test/integrationtests/ovos_tskill_abort/locale/en-us/test.intent +++ /dev/null @@ -1 +0,0 @@ -test \ No newline at end of file diff --git a/test/integrationtests/ovos_tskill_abort/locale/en-us/test2.intent b/test/integrationtests/ovos_tskill_abort/locale/en-us/test2.intent deleted file mode 100644 index 5161aff42996..000000000000 --- a/test/integrationtests/ovos_tskill_abort/locale/en-us/test2.intent +++ /dev/null @@ -1 +0,0 @@ -test again \ No newline at end of file diff --git a/test/integrationtests/ovos_tskill_abort/locale/en-us/test3.intent b/test/integrationtests/ovos_tskill_abort/locale/en-us/test3.intent deleted file mode 100644 index 1fec3fd265bf..000000000000 --- a/test/integrationtests/ovos_tskill_abort/locale/en-us/test3.intent +++ /dev/null @@ -1 +0,0 @@ -one more test \ No newline at end of file diff --git a/test/integrationtests/ovos_tskill_abort/readme.md b/test/integrationtests/ovos_tskill_abort/readme.md deleted file mode 100644 index add1af272c68..000000000000 --- a/test/integrationtests/ovos_tskill_abort/readme.md +++ /dev/null @@ -1 +0,0 @@ -skill for testing https://github.com/OpenVoiceOS/ovos_utils/pull/34 \ No newline at end of file diff --git a/test/integrationtests/ovos_tskill_abort/setup.py b/test/integrationtests/ovos_tskill_abort/setup.py deleted file mode 100755 index fb2af9105142..000000000000 --- a/test/integrationtests/ovos_tskill_abort/setup.py +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env python3 -from setuptools import setup - -# skill_id=package_name:SkillClass -PLUGIN_ENTRY_POINT = 'ovos-tskill-abort.openvoiceos=ovos_tskill_abort:TestAbortSkill' - -setup( - # this is the package name that goes on pip - name='ovos-tskill-abort', - version='0.0.1', - description='this is a OVOS test skill for the killable_intents decorator', - url='https://github.com/OpenVoiceOS/skill-abort-test', - author='JarbasAi', - author_email='jarbasai@mailfence.com', - license='Apache-2.0', - package_dir={"ovos_tskill_abort": ""}, - package_data={'ovos_tskill_abort': ['locale/*']}, - packages=['ovos_tskill_abort'], - include_package_data=True, - install_requires=["ovos-workshop"], - keywords='ovos skill plugin', - entry_points={'ovos.plugin.skill': PLUGIN_ENTRY_POINT} -) diff --git a/test/integrationtests/test_lock.py b/test/integrationtests/test_lock.py deleted file mode 100644 index 2816ce1e1432..000000000000 --- a/test/integrationtests/test_lock.py +++ /dev/null @@ -1,70 +0,0 @@ -# Copyright 2017 Mycroft AI Inc. -# -# 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. -# -import signal -import unittest -from shutil import rmtree - -from unittest.mock import patch -import os -from os.path import exists, isfile - -from ovos_utils.process_utils import PIDLock as Lock -from ovos_utils.file_utils import get_temp_path -from ovos_config.meta import get_xdg_base - - -class TestLock(unittest.TestCase): - def setUp(self): - if exists(get_temp_path(get_xdg_base())): - rmtree(get_temp_path(get_xdg_base())) - - def test_create_lock(self): - l1 = Lock('test') - self.assertTrue( - isfile(get_temp_path(get_xdg_base(), 'test.pid'))) - - def test_delete_lock(self): - l1 = Lock('test') - self.assertTrue( - isfile(get_temp_path(get_xdg_base(), 'test.pid'))) - l1.delete() - self.assertFalse( - isfile(get_temp_path(get_xdg_base(), 'test.pid'))) - - @patch('os.kill') - def test_existing_lock(self, mock_kill): - """ Test that an existing lock will kill the old pid. """ - l1 = Lock('test') - self.assertTrue( - isfile(get_temp_path(get_xdg_base(), 'test.pid'))) - l2 = Lock('test2') - self.assertFalse(mock_kill.called) - l2 = Lock('test') - self.assertTrue(mock_kill.called) - - def test_keyboard_interrupt(self): - l1 = Lock('test') - self.assertTrue( - isfile(get_temp_path(get_xdg_base(), 'test.pid'))) - try: - os.kill(os.getpid(), signal.SIGINT) - except KeyboardInterrupt: - pass - self.assertFalse( - isfile(get_temp_path(get_xdg_base(), 'test.pid'))) - - -if __name__ == '__main__': - unittest.main() diff --git a/test/integrationtests/test_ocp.py b/test/integrationtests/test_ocp.py deleted file mode 100644 index 0a3f704ccf75..000000000000 --- a/test/integrationtests/test_ocp.py +++ /dev/null @@ -1,484 +0,0 @@ -import json -import unittest - -import pytest - -import ovos_config.config -import mycroft.audio.audioservice -from os.path import dirname, join -from unittest.mock import patch - -import ovos_plugin_common_play -from ovos_plugin_common_play import OCPAudioBackend, OCP, PlayerState, MediaState, TrackState, PlaybackType -from mycroft.audio.interface import AudioService as MycroftAudioService -# from ovos_plugin_common_play.ocp.mycroft_cps import MycroftAudioService - -from mycroft.audio.audioservice import AudioService -# from mycroft.configuration import Configuration -from mycroft.skills.intent_service import IntentService -from mycroft.skills.skill_loader import SkillLoader -from ovos_utils.messagebus import FakeBus - -# Patch Configuration in the audioservice module to ensure its patched -from ovos_config.config import Configuration -mycroft.audio.audioservice.Configuration = Configuration - -BASE_CONF = {"Audio": - { - "native_sources": ["debug_cli", "audio"], - "default-backend": "OCP", # only used by mycroft-core - "preferred_audio_services": ["ovos_test", "mycroft_test"], - "backends": { - "OCP": { - "type": "ovos_common_play", - "active": True, - "mode": "local", - "disable_mpris": True - }, - "mycroft_test": { - "type": "mycroft_test", - "active": True - }, - "ovos_test": { - "type": "ovos_test", - "active": True - } - } - } -} - - -class TestOCPLoad(unittest.TestCase): - - @classmethod - @patch.object(ovos_config.config.Configuration, 'load_all_configs') - def setUpClass(self, mock) -> None: - mock.return_value = BASE_CONF - self.bus = FakeBus() - self.bus.emitted_msgs = [] - - def get_msg(msg): - msg = json.loads(msg) - msg.pop("context") - self.bus.emitted_msgs.append(msg) - - self.bus.on("message", get_msg) - - self.audio = AudioService(self.bus) - - @pytest.mark.skip - def test_native_ocp(self): - # assert that OCP is the selected default backend - self.assertTrue(isinstance(self.audio.default, OCPAudioBackend)) - - # assert that OCP is in "local" mode - self.assertEqual(self.audio.default.config["mode"], "local") - - # assert that OCP is loaded - self.assertTrue(self.audio.default.ocp is not None) - self.assertTrue(isinstance(self.audio.default.ocp, OCP)) - - # assert that test backends also loaded - # NOTE: "service" is a list, should be named "services" - # not renamed for backwards compat but its a typo! - loaded_services = [s.name for s in self.audio.service] - self.assertIn("mycroft_test", loaded_services) - self.assertIn("ovos_test", loaded_services) - - def tearDown(self) -> None: - self.audio.shutdown() - - -class TestCPS(unittest.TestCase): - bus = FakeBus() - - @classmethod - @patch.object(Configuration, 'load_all_configs') - def setUpClass(cls, mock) -> None: - mock.return_value = BASE_CONF - cls.bus.emitted_msgs = [] - - def get_msg(msg): - msg = json.loads(msg) - msg.pop("context") - cls.bus.emitted_msgs.append(msg) - - cls.bus.on("message", get_msg) - - @pytest.mark.skip # TODO? - def test_auto_unload(self): - intents = IntentService(self.bus) - skill = SkillLoader(self.bus, f"{dirname(__file__)}/ovos_tskill_mycroft_cps") - skill.skill_id = "skill-playback-control.mycroftai" - skill.load() - - # assert that mycroft common play intents registered - cps_msgs = [ - {'type': 'register_intent', - 'data': {'name': 'skill-playback-control.mycroftai:play', - 'requires': [['skill_playback_control_mycroftaiPlay', - 'skill_playback_control_mycroftaiPlay'], - ['skill_playback_control_mycroftaiPhrase', - 'skill_playback_control_mycroftaiPhrase']], - 'at_least_one': [], 'optional': []}}, - {'type': 'register_intent', - 'data': {'name': 'skill-playback-control.mycroftai:handle_prev', - 'requires': [['skill_playback_control_mycroftaiPrev', - 'skill_playback_control_mycroftaiPrev'], - ['skill_playback_control_mycroftaiTrack', - 'skill_playback_control_mycroftaiTrack']], - 'at_least_one': [], 'optional': []}}, - {'type': 'register_intent', - 'data': {'name': 'skill-playback-control.mycroftai:handle_pause', - 'requires': [['skill_playback_control_mycroftaiPause', - 'skill_playback_control_mycroftaiPause']], - 'at_least_one': [], 'optional': []}}, - {'type': 'register_intent', - 'data': {'name': 'skill-playback-control.mycroftai:handle_next', - 'requires': [['skill_playback_control_mycroftaiNext', - 'skill_playback_control_mycroftaiNext'], - ['skill_playback_control_mycroftaiTrack', - 'skill_playback_control_mycroftaiTrack']], - 'at_least_one': [], 'optional': []}}, - {'type': 'register_intent', - 'data': {'name': 'skill-playback-control.mycroftai:handle_play', 'requires': [], - 'at_least_one': [['skill_playback_control_mycroftaiPlayResume', - 'skill_playback_control_mycroftaiResume']], 'optional': []}} - ] - for intent in cps_msgs: - self.assertIn(intent, self.bus.emitted_msgs) - - # assert that mycroft common play intents loaded - cps_intents = [ - {'name': 'skill-playback-control.mycroftai:handle_prev', - 'requires': [('skill_playback_control_mycroftaiPrev', 'skill_playback_control_mycroftaiPrev'), - ('skill_playback_control_mycroftaiTrack', 'skill_playback_control_mycroftaiTrack')], - 'at_least_one': [], 'optional': []}, - {'name': 'skill-playback-control.mycroftai:handle_play', 'requires': [], - 'at_least_one': [('skill_playback_control_mycroftaiPlayResume', 'skill_playback_control_mycroftaiResume')], - 'optional': []}, - {'name': 'skill-playback-control.mycroftai:handle_pause', - 'requires': [('skill_playback_control_mycroftaiPause', 'skill_playback_control_mycroftaiPause')], - 'at_least_one': [], 'optional': []}, - {'name': 'skill-playback-control.mycroftai:play', - 'requires': [('skill_playback_control_mycroftaiPlay', 'skill_playback_control_mycroftaiPlay'), - ('skill_playback_control_mycroftaiPhrase', 'skill_playback_control_mycroftaiPhrase')], - 'at_least_one': [], 'optional': []}, - {'name': 'skill-playback-control.mycroftai:handle_next', - 'requires': [('skill_playback_control_mycroftaiNext', 'skill_playback_control_mycroftaiNext'), - ('skill_playback_control_mycroftaiTrack', 'skill_playback_control_mycroftaiTrack')], - 'at_least_one': [], 'optional': []} - ] - for intent in cps_intents: - self.assertIn(intent, intents.registered_intents) - - # load ocp - self.bus.emitted_msgs = [] - cfg = {} - ocp = OCPAudioBackend(cfg, self.bus) - - # assert that mycroft common play was deregistered - disable_msgs = [ - {'type': 'skillmanager.deactivate', - 'data': {'skill': 'skill-playback-control.mycroftai'}}, - {'type': 'skillmanager.deactivate', - 'data': {'skill': 'mycroft-playback-control.mycroftai'}}, - {'type': 'skillmanager.deactivate', - 'data': {'skill': 'mycroft-playback-control'}}, - {'type': 'skillmanager.deactivate', - 'data': {'skill': 'skill-playback-control'}} - ] # possible skill-ids for mycroft skill - for msg in disable_msgs: - self.assertIn(msg, self.bus.emitted_msgs) - # skill manager would call this if connected to bus - if msg["data"]["skill"] == skill.skill_id: - skill.deactivate() - - # assert that OCP intents registered - locale_folder = join(dirname(ovos_plugin_common_play.__file__), - "ocp", "res", "locale", "en-us") - ocp_msgs = [ - {'type': 'padatious:register_intent', - 'data': { - 'file_name': f'{locale_folder}/play.intent', - 'name': 'ovos.common_play:play.intent', 'lang': 'en-us'}}, - {'type': 'padatious:register_intent', - 'data': { - 'file_name': f'{locale_folder}/read.intent', - 'name': 'ovos.common_play:read.intent', 'lang': 'en-us'}}, - {'type': 'padatious:register_intent', - 'data': { - 'file_name': f'{locale_folder}/open.intent', - 'name': 'ovos.common_play:open.intent', 'lang': 'en-us'}}, - {'type': 'padatious:register_intent', - 'data': { - 'file_name': f'{locale_folder}/next.intent', - 'name': 'ovos.common_play:next.intent', 'lang': 'en-us'}}, - {'type': 'padatious:register_intent', - 'data': { - 'file_name': f'{locale_folder}/prev.intent', - 'name': 'ovos.common_play:prev.intent', 'lang': 'en-us'}}, - {'type': 'padatious:register_intent', - 'data': { - 'file_name': f'{locale_folder}/pause.intent', - 'name': 'ovos.common_play:pause.intent', 'lang': 'en-us'}}, - {'type': 'padatious:register_intent', - 'data': { - 'file_name': f'{locale_folder}/resume.intent', - 'name': 'ovos.common_play:resume.intent', 'lang': 'en-us'}}, - {'type': 'ovos.common_play.skills.get', - 'data': {}} - ] - for intent in ocp_msgs: - self.assertIn(intent, self.bus.emitted_msgs) - - # assert that mycroft common play intents unloaded - detach_msg = {'type': 'detach_skill', - 'data': {'skill_id': 'skill-playback-control.mycroftai:'}} - self.assertIn(detach_msg, self.bus.emitted_msgs) - for intent in cps_intents: - self.assertNotIn(intent, intents.registered_intents) - - ocp.shutdown() - - -class TestAudioServiceApi(unittest.TestCase): - bus = FakeBus() - - @classmethod - @patch.object(Configuration, 'load_all_configs') - def setUpClass(cls, mock) -> None: - mock.return_value = BASE_CONF - cls.bus.emitted_msgs = [] - - def get_msg(msg): - msg = json.loads(msg) - msg.pop("context") - cls.bus.emitted_msgs.append(msg) - - cls.bus.on("message", get_msg) - - cls.api = MycroftAudioService(cls.bus) - cls.audio = AudioService(cls.bus) - - @pytest.mark.skip # Also skipped in OCP Plugin tests - def test_ocp_plugin_compat_layer(self): - self.bus.emitted_msgs = [] - - # test play track from single uri - test_uri = "file://path/to/music.mp3" - self.api.play([test_uri]) - expected = [ - {'type': 'mycroft.audio.service.play', - 'data': {'tracks': [test_uri], - 'utterance': '', 'repeat': False}}, - {'type': 'ovos.common_play.playlist.clear', 'data': {}}, - {'type': 'ovos.common_play.media.state', 'data': {'state': 3}}, - {'type': 'ovos.common_play.track.state', 'data': {'state': 31}}, - {'type': 'ovos.common_play.playlist.queue', - 'data': { - 'tracks': [{'uri': test_uri, - 'title': 'music.mp3', 'playback': 2, 'status': 1, - 'skill_id': 'mycroft.audio_interface'}]}}, - {'type': 'ovos.common_play.play', - 'data': { - 'repeat': False, - 'media': { - 'uri': test_uri, - 'title': 'music.mp3', 'playback': 2, 'status': 1, 'skill_id': 'mycroft.audio_interface', - 'skill': 'mycroft.audio_interface', 'position': 0, 'length': None, 'skill_icon': None, - 'artist': None, 'is_cps': False, 'cps_data': {}}, - 'playlist': [ - {'uri': test_uri, - 'title': 'music.mp3', 'playback': 2, 'status': 1, 'skill_id': 'mycroft.audio_interface', - 'skill': 'mycroft.audio_interface', 'position': 0, 'length': None, 'skill_icon': None, - 'artist': None, 'is_cps': False, 'cps_data': {}}]}} - ] - for m in expected: - self.assertIn(m, self.bus.emitted_msgs) - - # test pause - self.bus.emitted_msgs = [] - self.api.pause() - expected = [ - {'type': 'mycroft.audio.service.pause', 'data': {}}, - {'type': 'ovos.common_play.pause', 'data': {}} - ] - for m in expected: - self.assertIn(m, self.bus.emitted_msgs) - - # test resume - self.bus.emitted_msgs = [] - self.api.resume() - expected = [ - {'type': 'mycroft.audio.service.resume', 'data': {}}, - {'type': 'ovos.common_play.resume', 'data': {}} - ] - for m in expected: - self.assertIn(m, self.bus.emitted_msgs) - - # test next - self.bus.emitted_msgs = [] - self.api.next() - expected = [ - {'type': 'mycroft.audio.service.next', 'data': {}}, - {'type': 'ovos.common_play.next', 'data': {}} - ] - for m in expected: - self.assertIn(m, self.bus.emitted_msgs) - - # test prev - self.bus.emitted_msgs = [] - self.api.prev() - expected = [ - {'type': 'mycroft.audio.service.prev', 'data': {}}, - {'type': 'ovos.common_play.previous', 'data': {}} - ] - for m in expected: - self.assertIn(m, self.bus.emitted_msgs) - - # test queue - self.bus.emitted_msgs = [] - playlist = ["file://path/to/music2.mp3", "file://path/to/music3.mp3"] - self.api.queue(playlist) - expected = [ - {'type': 'mycroft.audio.service.queue', - 'data': {'tracks': ['file://path/to/music2.mp3', 'file://path/to/music3.mp3']}}, - {'type': 'ovos.common_play.playlist.queue', - 'data': {'tracks': [ - {'uri': 'file://path/to/music2.mp3', 'title': 'music2.mp3', 'playback': 2, 'status': 1, - 'skill_id': 'mycroft.audio_interface'}, - {'uri': 'file://path/to/music3.mp3', 'title': 'music3.mp3', 'playback': 2, 'status': 1, - 'skill_id': 'mycroft.audio_interface'}] - }} - ] - for m in expected: - self.assertIn(m, self.bus.emitted_msgs) - - # test play playlist - self.bus.emitted_msgs = [] - self.api.play([test_uri] + playlist) - expected = [ - {'type': 'mycroft.audio.service.play', - 'data': {'tracks': ['file://path/to/music.mp3', 'file://path/to/music2.mp3', 'file://path/to/music3.mp3'], - 'utterance': '', - 'repeat': False}}, - {'type': 'ovos.common_play.playlist.queue', - 'data': {'tracks': [ - {'uri': 'file://path/to/music.mp3', 'title': 'music.mp3', 'playback': 2, 'status': 1, - 'skill_id': 'mycroft.audio_interface'}, - {'uri': 'file://path/to/music2.mp3', 'title': 'music2.mp3', 'playback': 2, 'status': 1, - 'skill_id': 'mycroft.audio_interface'}, - {'uri': 'file://path/to/music3.mp3', 'title': 'music3.mp3', 'playback': 2, 'status': 1, - 'skill_id': 'mycroft.audio_interface'}]}}, - {'type': 'ovos.common_play.play', - 'data': {'repeat': False, - 'media': {'uri': 'file://path/to/music.mp3', - 'title': 'music.mp3', 'playback': 2, - 'status': 1, - 'skill_id': 'mycroft.audio_interface', - 'skill': 'mycroft.audio_interface', - 'position': 0, 'length': None, - 'skill_icon': None, 'artist': None, - 'is_cps': False, 'cps_data': {}}, - 'playlist': [ - {'uri': 'file://path/to/music.mp3', 'title': 'music.mp3', - 'playback': 2, 'status': 1, - 'skill_id': 'mycroft.audio_interface', - 'skill': 'mycroft.audio_interface', 'position': 0, - 'length': None, 'skill_icon': None, 'artist': None, - 'is_cps': False, 'cps_data': {}}, - {'uri': 'file://path/to/music2.mp3', 'title': 'music2.mp3', - 'playback': 2, 'status': 1, - 'skill_id': 'mycroft.audio_interface', - 'skill': 'mycroft.audio_interface', 'position': 0, - 'length': None, 'skill_icon': None, 'artist': None, - 'is_cps': False, 'cps_data': {}}, - {'uri': 'file://path/to/music3.mp3', 'title': 'music3.mp3', - 'playback': 2, 'status': 1, - 'skill_id': 'mycroft.audio_interface', - 'skill': 'mycroft.audio_interface', 'position': 0, - 'length': None, 'skill_icon': None, 'artist': None, - 'is_cps': False, 'cps_data': {}}]}} - ] - for m in expected: - self.assertIn(m, self.bus.emitted_msgs) - - @pytest.mark.skip # Also skipped in OCP Plugin tests - def test_play_mycroft_backend(self): - self.bus.emitted_msgs = [] - selected = "mycroft_test" - tracks = ["file://path/to/music.mp3", "file://path/to/music2.mp3"] - - # assert OCP not in use - self.assertNotEqual(self.audio.default.ocp.player.state, PlayerState.PLAYING) - - self.api.play(tracks, repeat=True, utterance=selected) - - # correct service selected - self.assertEqual(self.audio.current.name, selected) - self.assertTrue(self.audio.current.playing) - - # OCP is not aware of internal player state - state events not emitted by mycroft plugins - self.assertNotEqual(self.audio.default.ocp.player.state, PlayerState.PLAYING) - - # but track state is partially accounted for - self.assertEqual(self.audio.default.ocp.player.now_playing.uri, tracks[0]) - self.assertEqual(self.audio.default.ocp.player.now_playing.playback, PlaybackType.AUDIO_SERVICE) - self.assertEqual(self.audio.default.ocp.player.now_playing.status, TrackState.QUEUED_AUDIOSERVICE) - self.assertEqual(self.audio.default.ocp.player.now_playing.skill_id, "mycroft.audio_interface") - - self.audio.current._track_start_callback("track_name") - self.assertEqual(self.audio.default.ocp.player.now_playing.status, TrackState.PLAYING_AUDIOSERVICE) - - @pytest.mark.skip # Also skipped in OCP Plugin tests - def test_play_ocp_backend(self): - self.bus.emitted_msgs = [] - - selected = "ovos_test" - tracks = ["file://path/to/music.mp3", "file://path/to/music2.mp3"] - - # assert OCP not in use - self.assertNotEqual(self.audio.default.ocp.player.state, PlayerState.PLAYING) - - # NOTE: this usage is equivalent to what OCP itself - # does internally to select audio_service, where "utterance" is also used - self.api.play(tracks, repeat=True, utterance=selected) - - # correct service selected - self.assertEqual(self.audio.current.name, selected) - - # ocp state events emitted - exptected = [ - {'type': 'mycroft.audio.service.play', - 'data': {'tracks': ['file://path/to/music.mp3', 'file://path/to/music2.mp3'], 'utterance': 'ovos_test', - 'repeat': True}}, - {'type': 'ovos.common_play.playlist.clear', 'data': {}}, # TODO - maybe this is unwanted (?) - {'type': 'ovos.common_play.media.state', 'data': {'state': 3}}, - {'type': 'ovos.common_play.track.state', 'data': {'state': 31}}, - {'type': 'ovos.common_play.playlist.queue', 'data': {'tracks': [ - {'uri': 'file://path/to/music.mp3', 'title': 'music.mp3', 'playback': 2, 'status': 1, - 'skill_id': 'mycroft.audio_interface'}, - {'uri': 'file://path/to/music2.mp3', 'title': 'music2.mp3', 'playback': 2, 'status': 1, - 'skill_id': 'mycroft.audio_interface'}]}}, - {'type': 'ovos.common_play.repeat.set', 'data': {}}, - {'type': 'ovos.common_play.player.state', 'data': {'state': 1}}, - {'type': 'ovos.common_play.media.state', 'data': {'state': 3}}, - {'type': 'ovos.common_play.track.state', 'data': {'state': 21}} - ] - for m in exptected: - self.assertIn(m, self.bus.emitted_msgs) - - # assert OCP is tracking state - self.assertEqual(self.audio.default.ocp.player.state, PlayerState.PLAYING) - self.assertEqual(self.audio.default.ocp.player.media_state, MediaState.LOADED_MEDIA) - self.assertEqual(self.audio.default.ocp.player.now_playing.uri, tracks[0]) - self.assertEqual(self.audio.default.ocp.player.now_playing.playback, PlaybackType.AUDIO_SERVICE) - self.assertEqual(self.audio.default.ocp.player.now_playing.status, TrackState.PLAYING_AUDIOSERVICE) - - def tearDown(self) -> None: - self.audio.shutdown() - - -if __name__ == '__main__': - unittest.main() diff --git a/test/integrationtests/test_selene_api.py b/test/integrationtests/test_selene_api.py deleted file mode 100644 index f063af1a2b0e..000000000000 --- a/test/integrationtests/test_selene_api.py +++ /dev/null @@ -1,383 +0,0 @@ -# Copyright 2017 Mycroft AI Inc. -# -# 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. -# -import unittest -import ovos_backend_client -from ovos_backend_client.backends import BackendType -import ovos_backend_client.backends -import ovos_backend_client.pairing -from unittest.mock import MagicMock, patch - -ovos_backend_client.backends.base.requests.post = MagicMock() - - -def create_identity(uuid, expired=False): - mock_identity = MagicMock() - mock_identity.is_expired.return_value = expired - mock_identity.uuid = uuid - return mock_identity - - -def create_response(status, json=None, url='', data=''): - json = json or {} - response = MagicMock() - response.status_code = status - response.json.return_value = json - response.url = url - return response - - -class TestDeviceApi(unittest.TestCase): - - @patch('ovos_backend_client.identity.IdentityManager.get') - @patch('ovos_backend_client.backends.base.requests.request') - def test_init(self, mock_request, mock_identity_get): - mock_request.return_value = create_response(200) - mock_identity_get.return_value = create_identity('1234') - - device = ovos_backend_client.api.DeviceApi(url="https://api-test.mycroft.ai", - backend_type=BackendType.PERSONAL) - self.assertEqual(device.identity.uuid, '1234') - self.assertTrue(device.url.endswith("/device")) - - @patch('ovos_backend_client.identity.IdentityManager.get') - @patch('ovos_backend_client.backends.base.requests.post') - def test_device_activate(self, mock_request, mock_identity_get): - mock_request.return_value = create_response(200) - mock_identity_get.return_value = create_identity('1234') - # Test activate - device = ovos_backend_client.api.DeviceApi(url="https://api-test.mycroft.ai", - backend_type=BackendType.PERSONAL) - device.activate('state', 'token') - json = mock_request.call_args[1]['json'] - self.assertEqual(json['state'], 'state') - self.assertEqual(json['token'], 'token') - - @patch('ovos_backend_client.identity.IdentityManager.get') - @patch('ovos_backend_client.backends.base.requests.get') - def test_device_get(self, mock_request, mock_identity_get): - mock_request.return_value = create_response(200) - mock_identity_get.return_value = create_identity('1234') - # Test get - device = ovos_backend_client.api.DeviceApi(url="https://api-test.mycroft.ai", - backend_type=BackendType.PERSONAL) - device.get() - url = mock_request.call_args[0][0] - self.assertEqual(url, 'https://api-test.mycroft.ai/v1/device/1234') - - @patch('ovos_backend_client.identity.IdentityManager.update') - @patch('ovos_backend_client.identity.IdentityManager.get') - @patch('ovos_backend_client.backends.base.requests.get') - def test_device_get_code(self, mock_request, mock_identity_get, - mock_identit_update): - mock_request.return_value = create_response(200, '123ABC') - mock_identity_get.return_value = create_identity('1234') - device = ovos_backend_client.api.DeviceApi(url="https://api-test.mycroft.ai", - backend_type=BackendType.PERSONAL) - ret = device.get_code('state') - self.assertEqual(ret, '123ABC') - url = mock_request.call_args[0][0] - params = mock_request.call_args[1] - self.assertEqual(url, 'https://api-test.mycroft.ai/v1/device/code') - self.assertEqual(params["params"], {"state": "state"}) - - @patch('ovos_backend_client.identity.IdentityManager.get') - @patch('ovos_backend_client.backends.base.requests.get') - def test_device_get_settings(self, mock_request, mock_identity_get): - mock_request.return_value = create_response(200, {}) - mock_identity_get.return_value = create_identity('1234') - device = ovos_backend_client.api.DeviceApi(url="https://api-test.mycroft.ai", - backend_type=BackendType.PERSONAL) - device.get_settings() - url = mock_request.call_args[0][0] - self.assertEqual( - url, 'https://api-test.mycroft.ai/v1/device/1234/setting') - - @patch('ovos_backend_client.identity.IdentityManager.get') - @patch('ovos_backend_client.backends.base.requests.post') - def test_device_report_metric(self, mock_request, mock_identity_get): - mock_request.return_value = create_response(200, {}) - mock_identity_get.return_value = create_identity('1234') - device = ovos_backend_client.api.DeviceApi(url="https://api-test.mycroft.ai", - backend_type=BackendType.PERSONAL) - device.report_metric('mymetric', {'data': 'mydata'}) - url = mock_request.call_args[0][0] - params = mock_request.call_args[1] - - content_type = params['headers']['Content-Type'] - correct_json = {'data': 'mydata'} - self.assertEqual(content_type, 'application/json') - self.assertEqual(params['json'], correct_json) - self.assertEqual( - url, 'https://api-test.mycroft.ai/v1/device/1234/metric/mymetric') - - @patch('ovos_backend_client.identity.IdentityManager.get') - @patch('ovos_backend_client.backends.base.requests.put') - def test_device_send_email(self, mock_request, mock_identity_get): - mock_request.return_value = create_response(200, {}) - mock_identity_get.return_value = create_identity('1234') - device = ovos_backend_client.api.DeviceApi(url="https://api-test.mycroft.ai", - backend_type=BackendType.PERSONAL) - device.send_email('title', 'body', 'sender') - url = mock_request.call_args[0][0] - params = mock_request.call_args[1] - - content_type = params['headers']['Content-Type'] - correct_json = {'body': 'body', 'sender': 'sender', 'title': 'title'} - self.assertEqual(content_type, 'application/json') - self.assertEqual(params['json'], correct_json) - self.assertEqual( - url, 'https://api-test.mycroft.ai/v1/device/1234/message') - - @patch('ovos_backend_client.identity.IdentityManager.get') - @patch('ovos_backend_client.backends.base.requests.get') - def test_device_get_oauth_token(self, mock_request, mock_identity_get): - mock_request.return_value = create_response(200, {}) - mock_identity_get.return_value = create_identity('1234') - device = ovos_backend_client.api.DeviceApi(url="https://api-test.mycroft.ai", - backend_type=BackendType.PERSONAL) - device.get_oauth_token(1) - url = mock_request.call_args[0][0] - - self.assertEqual( - url, 'https://api-test.mycroft.ai/v1/device/1234/token/1') - - @patch('ovos_backend_client.identity.IdentityManager.get') - @patch('ovos_backend_client.backends.base.requests.get') - def test_device_get_location(self, mock_request, mock_identity_get): - mock_request.return_value = create_response(200, {}) - mock_identity_get.return_value = create_identity('1234') - device = ovos_backend_client.api.DeviceApi(url="https://api-test.mycroft.ai", - backend_type=BackendType.PERSONAL) - device.get_location() - url = mock_request.call_args[0][0] - self.assertEqual( - url, 'https://api-test.mycroft.ai/v1/device/1234/location') - - @patch('ovos_backend_client.identity.IdentityManager.get') - @patch('ovos_backend_client.backends.base.requests.get') - def test_device_get_subscription(self, mock_request, mock_identity_get): - mock_request.return_value = create_response(200, {}) - mock_identity_get.return_value = create_identity('1234') - device = ovos_backend_client.api.DeviceApi(url="https://api-test.mycroft.ai", - backend_type=BackendType.PERSONAL) - device.get_subscription() - url = mock_request.call_args[0][0] - self.assertEqual( - url, 'https://api-test.mycroft.ai/v1/device/1234/subscription') - - mock_request.return_value = create_response(200, {'@type': 'free'}) - self.assertFalse(device.is_subscriber) - - mock_request.return_value = create_response(200, {'@type': 'monthly'}) - self.assertTrue(device.is_subscriber) - - mock_request.return_value = create_response(200, {'@type': 'yearly'}) - self.assertTrue(device.is_subscriber) - - @patch('ovos_backend_client.identity.IdentityManager.get') - @patch('ovos_backend_client.backends.base.requests.put') - def test_device_upload_skills_data(self, mock_request, mock_identity_get): - mock_request.return_value = create_response(200) - mock_identity_get.return_value = create_identity('1234') - device = ovos_backend_client.api.DeviceApi(url="https://api-test.mycroft.ai", - backend_type=BackendType.PERSONAL) - device.upload_skills_data({}) - url = mock_request.call_args[0][0] - data = mock_request.call_args[1]['json'] - - # Check that the correct url is called - self.assertEqual( - url, 'https://api-test.mycroft.ai/v1/device/1234/skillJson') - - # Check that the correct data is sent as json - self.assertTrue('blacklist' in data) - self.assertTrue('skills' in data) - - with self.assertRaises(ValueError): - device.upload_skills_data('This isn\'t right at all') - - @patch('ovos_backend_client.identity.IdentityManager.get') - @patch('ovos_backend_client.backends.base.requests.get') - def test_stt(self, mock_request, mock_identity_get): - mock_request.return_value = create_response(200, {}) - mock_identity_get.return_value = create_identity('1234') - stt = ovos_backend_client.api.STTApi('stt', backend_type=BackendType.PERSONAL) - self.assertTrue(stt.url.endswith('stt')) - - @patch('ovos_backend_client.identity.IdentityManager.get') - @patch('ovos_backend_client.backends.base.requests.post') - def test_stt_stt(self, mock_request, mock_identity_get): - mock_request.return_value = create_response(200, {}) - mock_identity_get.return_value = create_identity('1234') - stt = ovos_backend_client.api.STTApi('https://api-test.mycroft.ai', backend_type=BackendType.PERSONAL) - stt.stt('La la la', 'en-US', 1) - url = mock_request.call_args[0][0] - self.assertEqual(url, 'https://api-test.mycroft.ai/v1/stt') - data = mock_request.call_args[1].get('data') - self.assertEqual(data, 'La la la') - params = mock_request.call_args[1].get('params') - self.assertEqual(params['lang'], 'en-US') - - @patch('ovos_backend_client.identity.IdentityManager.load') - def test_has_been_paired(self, mock_identity_load): - # reset pairing cache - mock_identity = MagicMock() - mock_identity_load.return_value = mock_identity - # Test None - mock_identity.uuid = None - self.assertFalse(ovos_backend_client.pairing.has_been_paired()) - # Test empty string - mock_identity.uuid = "" - self.assertFalse(ovos_backend_client.pairing.has_been_paired()) - # Test actual id number - mock_identity.uuid = "1234" - self.assertTrue(ovos_backend_client.pairing.has_been_paired()) - - -class TestSettingsMeta(unittest.TestCase): - - @patch('ovos_backend_client.identity.IdentityManager.get') - @patch('ovos_backend_client.backends.base.requests.put') - def test_upload_meta(self, mock_request, mock_identity_get): - mock_request.return_value = create_response(200, {}) - mock_identity_get.return_value = create_identity('1234') - device = ovos_backend_client.api.DeviceApi(url="https://api-test.mycroft.ai", - backend_type=BackendType.PERSONAL) - - settings_meta = { - 'name': 'TestMeta', - "skill_gid": 'test_skill|19.02', - 'skillMetadata': { - 'sections': [ - { - 'name': 'Settings', - 'fields': [ - { - 'name': 'Set me', - 'type': 'number', - 'value': 4 - } - ] - } - ] - } - } - device.upload_skill_metadata(settings_meta) - url = mock_request.call_args[0][0] - params = mock_request.call_args[1] - - content_type = params['headers']['Content-Type'] - self.assertEqual(content_type, 'application/json') - self.assertEqual(params['json'], settings_meta) - self.assertEqual( - url, 'https://api-test.mycroft.ai/v1/device/1234/settingsMeta') - - @patch('ovos_backend_client.identity.IdentityManager.get') - @patch('ovos_backend_client.backends.base.requests.get') - def test_get_skill_settings(self, mock_request, mock_identity_get): - mock_request.return_value = create_response(200, {}) - mock_identity_get.return_value = create_identity('1234') - device = ovos_backend_client.api.DeviceApi(url="https://api-test.mycroft.ai", - backend_type=BackendType.PERSONAL) - device.get_skill_settings() - url = mock_request.call_args[0][0] - params = mock_request.call_args[1] - - self.assertEqual( - url, 'https://api-test.mycroft.ai/v1/device/1234/skill/settings') - - -class TestIsPaired(unittest.TestCase): - @patch('ovos_backend_client.identity.IdentityManager.get') - @patch('ovos_backend_client.pairing.is_backend_disabled') - def test_is_paired_offline_true(self, mock_backend_status, mock_identity_get): - mock_backend_status.return_value = False - mock_identity = MagicMock() - mock_identity.uuid = '1234' - mock_identity_get.return_value = mock_identity - self.assertTrue(ovos_backend_client.pairing.is_paired(backend_type=BackendType.OFFLINE)) - - @patch('ovos_backend_client.identity.IdentityManager.get') - @patch('ovos_backend_client.pairing.is_backend_disabled') - def test_is_paired_offline_false(self, mock_backend_status, mock_identity_get): - mock_backend_status.return_value = False - mock_identity = MagicMock() - mock_identity.uuid = '' - mock_identity_get.return_value = mock_identity - self.assertFalse(ovos_backend_client.pairing.is_paired(backend_type=BackendType.OFFLINE)) - - @patch('ovos_backend_client.identity.IdentityManager.get') - @patch('ovos_backend_client.backends.personal.PersonalBackend.device_get') - @patch('ovos_backend_client.pairing.is_backend_disabled') - def test_is_paired_selene_true(self, mock_backend_status, mock_request, mock_identity_get): - mock_backend_status.return_value = False - mock_request.return_value = {"uuid": "1234"} - mock_identity = MagicMock() - mock_identity.is_expired.return_value = False - mock_identity.uuid = '1234' - mock_identity_get.return_value = mock_identity - num_calls = mock_identity_get.num_calls - self.assertTrue(ovos_backend_client.pairing.is_paired(backend_type=BackendType.PERSONAL)) - self.assertEqual(num_calls, mock_identity_get.num_calls) - - @patch('ovos_backend_client.identity.IdentityManager.get') - @patch('ovos_backend_client.backends.base.requests.get') - @patch('ovos_backend_client.pairing.is_backend_disabled') - def test_is_paired_selene_false_local(self, mock_backend_status, mock_request, mock_identity_get): - mock_backend_status.return_value = False - mock_request.return_value = create_response(200) - mock_identity = MagicMock() - mock_identity.is_expired.return_value = False - mock_identity.uuid = '' - mock_identity_get.return_value = mock_identity - self.assertFalse(ovos_backend_client.pairing.is_paired(backend_type=BackendType.PERSONAL)) - mock_identity.uuid = None - self.assertFalse(ovos_backend_client.pairing.is_paired(backend_type=BackendType.PERSONAL)) - - @patch('ovos_backend_client.identity.IdentityManager.get') - @patch('ovos_backend_client.backends.base.requests.get') - @patch('ovos_backend_client.pairing.is_backend_disabled') - def test_is_paired_selene_false_remote(self, mock_backend_status, mock_request, mock_identity_get): - mock_backend_status.return_value = False - mock_request.return_value = create_response(401) - mock_identity = MagicMock() - mock_identity.is_expired.return_value = False - mock_identity.uuid = '1234' - mock_identity_get.return_value = mock_identity - self.assertFalse(ovos_backend_client.pairing.is_paired(backend_type=BackendType.PERSONAL)) - - @patch('ovos_backend_client.identity.IdentityManager.get') - @patch('ovos_backend_client.backends.base.requests.get') - @patch('ovos_backend_client.pairing.is_backend_disabled') - def test_is_paired_selene_error_remote(self, mock_backend_status, mock_request, mock_identity_get): - mock_backend_status.return_value = False - mock_request.return_value = create_response(500) - mock_identity = MagicMock() - mock_identity.is_expired.return_value = False - mock_identity.uuid = '1234' - mock_identity_get.return_value = mock_identity - self.assertFalse(ovos_backend_client.pairing.is_paired(backend_type=BackendType.PERSONAL)) - - @patch('ovos_backend_client.identity.IdentityManager.get') - @patch('ovos_backend_client.backends.base.requests.get') - @patch('ovos_backend_client.pairing.is_backend_disabled') - def test_is_paired_selene_false_disabled(self, mock_backend_status, mock_request, mock_identity_get): - mock_backend_status.return_value = True - mock_request.return_value = create_response(500) - mock_identity = MagicMock() - mock_identity.is_expired.return_value = False - mock_identity.uuid = '1234' - mock_identity_get.return_value = mock_identity - self.assertTrue(ovos_backend_client.pairing.is_paired(backend_type=BackendType.PERSONAL)) diff --git a/test/integrationtests/test_workshop.py b/test/integrationtests/test_workshop.py deleted file mode 100644 index fc5e469497aa..000000000000 --- a/test/integrationtests/test_workshop.py +++ /dev/null @@ -1,277 +0,0 @@ -import json -import unittest -from os.path import dirname -from time import sleep -from mycroft.skills.skill_loader import SkillLoader -from mycroft.skills.mycroft_skill.mycroft_skill import MycroftSkill -from ovos_workshop.skills.ovos import OVOSSkill -from ovos_utils.messagebus import FakeBus, Message - -# tests taken from ovos_workshop - - -class TestSkill(unittest.TestCase): - def setUp(self): - self.bus = FakeBus() - self.bus.emitted_msgs = [] - - def get_msg(msg): - msg = json.loads(msg) - self.bus.emitted_msgs.append(msg) - - self.bus.on("message", get_msg) - - self.skill = SkillLoader(self.bus, f"{dirname(__file__)}/ovos_tskill_abort") - self.skill.skill_id = "abort.test" - self.bus.emitted_msgs = [] - - self.skill.load() - - def test_skill_id(self): - self.assertTrue(isinstance(self.skill.instance, OVOSSkill)) - self.assertTrue(isinstance(self.skill.instance, MycroftSkill)) - - self.assertEqual(self.skill.skill_id, "abort.test") - # if running in ovos-core every message will have the skill_id in context - for msg in self.bus.emitted_msgs: - if msg["type"] == 'mycroft.skills.loaded': # emitted by SkillLoader, not by skill - continue - self.assertEqual(msg["context"]["skill_id"], "abort.test") - - def test_intent_register(self): - padatious_intents = ["abort.test:test.intent", - "abort.test:test2.intent", - "abort.test:test3.intent"] - for msg in self.bus.emitted_msgs: - if msg["type"] == "padatious:register_intent": - self.assertTrue(msg["data"]["name"] in padatious_intents) - - def test_registered_events(self): - registered_events = [e[0] for e in self.skill.instance.events] - - # intent events - intent_triggers = [f"{self.skill.skill_id}:test.intent", - f"{self.skill.skill_id}:test2.intent", - f"{self.skill.skill_id}:test3.intent" - ] - for event in intent_triggers: - self.assertTrue(event in registered_events) - - # base skill class events shared with mycroft-core - default_skill = ["mycroft.skill.enable_intent", - "mycroft.skill.disable_intent", - "mycroft.skill.set_cross_context", - "mycroft.skill.remove_cross_context", - "mycroft.skills.settings.changed"] - for event in default_skill: - self.assertTrue(event in registered_events) - - # base skill class events exclusive to ovos-core - default_ovos = [f"{self.skill.skill_id}.converse.ping", - f"{self.skill.skill_id}.converse.request", - "intent.service.skills.activated", - "intent.service.skills.deactivated", - f"{self.skill.skill_id}.activate", - f"{self.skill.skill_id}.deactivate"] - for event in default_ovos: - self.assertTrue(event in registered_events) - - def tearDown(self) -> None: - self.skill.unload() - - -class TestKillableIntents(unittest.TestCase): - def setUp(self): - self.bus = FakeBus() - self.bus.emitted_msgs = [] - - def get_msg(msg): - m = json.loads(msg) - m.pop("context") - self.bus.emitted_msgs.append(m) - - self.bus.on("message", get_msg) - - self.skill = SkillLoader(self.bus, f"{dirname(__file__)}/ovos_tskill_abort") - self.skill.skill_id = "abort.test" - self.skill.load() - - def test_skills_abort_event(self): - self.bus.emitted_msgs = [] - # skill will enter a infinite loop unless aborted - self.assertTrue(self.skill.instance.my_special_var == "default") - self.bus.emit(Message(f"{self.skill.skill_id}:test.intent")) - sleep(2) - # check that intent triggered - start_msg = {'type': 'mycroft.skill.handler.start', - 'data': {'name': 'TestAbortSkill.handle_test_abort_intent'}} - speak_msg = {'type': 'speak', - 'data': {'utterance': 'still here', 'expect_response': False, - 'meta': {'skill': 'abort.test'}, - 'lang': 'en-us'}} - self.assertIn(start_msg, self.bus.emitted_msgs) - self.assertIn(speak_msg, self.bus.emitted_msgs) - self.assertTrue(self.skill.instance.my_special_var == "changed") - - # check that intent reacts to mycroft.skills.abort_execution - # eg, gui can emit this event if some option was selected - # on screen to abort the current voice interaction - self.bus.emitted_msgs = [] - self.bus.emit(Message(f"mycroft.skills.abort_execution")) - sleep(2) - - # check that stop method was called - self.assertTrue(self.skill.instance.stop_called) - - # check that TTS stop message was emmited - tts_stop = {'type': 'mycroft.audio.speech.stop', 'data': {}} - self.assertIn(tts_stop, self.bus.emitted_msgs) - - # check that cleanup callback was called - speak_msg = {'type': 'speak', - 'data': {'utterance': 'I am dead', 'expect_response': False, - 'meta': {'skill': 'abort.test'}, - 'lang': 'en-us'}} - self.assertIn(speak_msg, self.bus.emitted_msgs) - self.assertTrue(self.skill.instance.my_special_var == "default") - - # check that we are not getting speak messages anymore - self.bus.emitted_msgs = [] - sleep(2) - self.assertTrue(self.bus.emitted_msgs == []) - - def test_skill_stop(self): - self.bus.emitted_msgs = [] - # skill will enter a infinite loop unless aborted - self.assertTrue(self.skill.instance.my_special_var == "default") - self.bus.emit(Message(f"{self.skill.skill_id}:test.intent")) - sleep(2) - # check that intent triggered - start_msg = {'type': 'mycroft.skill.handler.start', - 'data': {'name': 'TestAbortSkill.handle_test_abort_intent'}} - speak_msg = {'type': 'speak', - 'data': {'utterance': 'still here', 'expect_response': False, - 'meta': {'skill': 'abort.test'}, 'lang': 'en-us'}} - self.assertIn(start_msg, self.bus.emitted_msgs) - self.assertIn(speak_msg, self.bus.emitted_msgs) - self.assertTrue(self.skill.instance.my_special_var == "changed") - - # check that intent reacts to skill specific stop message - # this is also emitted on mycroft.stop if using OvosSkill class - self.bus.emitted_msgs = [] - self.bus.emit(Message(f"{self.skill.skill_id}.stop")) - sleep(2) - - # check that stop method was called - self.assertTrue(self.skill.instance.stop_called) - - # check that TTS stop message was emmited - tts_stop = {'type': 'mycroft.audio.speech.stop', 'data': {}} - self.assertIn(tts_stop, self.bus.emitted_msgs) - - # check that cleanup callback was called - speak_msg = {'type': 'speak', - 'data': {'utterance': 'I am dead', 'expect_response': False, - 'meta': {'skill': 'abort.test'}, - 'lang': 'en-us'}} - - self.assertIn(speak_msg, self.bus.emitted_msgs) - self.assertTrue(self.skill.instance.my_special_var == "default") - - # check that we are not getting speak messages anymore - self.bus.emitted_msgs = [] - sleep(2) - self.assertTrue(self.bus.emitted_msgs == []) - - def test_get_response(self): - """ send "mycroft.skills.abort_question" and - confirm only get_response is aborted, speech after is still spoken""" - self.bus.emitted_msgs = [] - # skill will enter a infinite loop unless aborted - self.bus.emit(Message(f"{self.skill.skill_id}:test2.intent")) - sleep(1) # mock wait=True in speak_dialog - self.bus.emit(Message("recognizer_loop:audio_output_end")) - sleep(1) - - # check that intent triggered - start_msg = {'type': 'mycroft.skill.handler.start', - 'data': {'name': 'TestAbortSkill.handle_test_get_response_intent'}} - speak_msg = {'type': 'speak', - 'data': {'utterance': 'this is a question', - 'expect_response': True, - 'meta': {'dialog': 'question', 'data': {}, 'skill': 'abort.test'}, - 'lang': 'en-us'}} - activate_msg = {'type': 'intent.service.skills.activate', 'data': {'skill_id': 'abort.test'}} - - self.assertIn(start_msg, self.bus.emitted_msgs) - self.assertIn(speak_msg, self.bus.emitted_msgs) - #self.assertIn(activate_msg, self.bus.emitted_msgs) - - # check that get_response loop is aborted - # but intent continues executing - self.bus.emitted_msgs = [] - self.bus.emit(Message(f"mycroft.skills.abort_question")) - sleep(1) - - # check that stop method was NOT called - self.assertFalse(self.skill.instance.stop_called) - - # check that speak message after get_response loop was spoken - speak_msg = {'type': 'speak', - 'data': {'utterance': 'question aborted', - 'expect_response': False, - 'meta': {'skill': 'abort.test'}, - 'lang': 'en-us'}} - self.assertIn(speak_msg, self.bus.emitted_msgs) - - def test_developer_stop_msg(self): - """ send "my.own.abort.msg" and confirm intent3 is aborted - send "mycroft.skills.abort_execution" and confirm intent3 ignores it""" - self.bus.emitted_msgs = [] - # skill will enter a infinite loop unless aborted - self.bus.emit(Message(f"{self.skill.skill_id}:test3.intent")) - sleep(2) - # check that intent triggered - start_msg = {'type': 'mycroft.skill.handler.start', - 'data': {'name': 'TestAbortSkill.handle_test_msg_intent'}} - speak_msg = {'type': 'speak', - 'data': {'utterance': "you can't abort me", - 'expect_response': False, - 'meta': {'skill': 'abort.test'}, - 'lang': 'en-us'}} - self.assertIn(start_msg, self.bus.emitted_msgs) - self.assertIn(speak_msg, self.bus.emitted_msgs) - - # check that intent does NOT react to mycroft.skills.abort_execution - # developer requested a dedicated abort message - self.bus.emitted_msgs = [] - self.bus.emit(Message(f"mycroft.skills.abort_execution")) - sleep(1) - - # check that stop method was NOT called - self.assertFalse(self.skill.instance.stop_called) - - # check that intent reacts to my.own.abort.msg - self.bus.emitted_msgs = [] - self.bus.emit(Message(f"my.own.abort.msg")) - sleep(2) - - # check that stop method was called - self.assertTrue(self.skill.instance.stop_called) - - # check that TTS stop message was emmited - tts_stop = {'type': 'mycroft.audio.speech.stop', 'data': {}} - self.assertIn(tts_stop, self.bus.emitted_msgs) - - # check that cleanup callback was called - speak_msg = {'type': 'speak', - 'data': {'utterance': 'I am dead', 'expect_response': False, - 'meta': {'skill': 'abort.test'}, - 'lang': 'en-us'}} - self.assertIn(speak_msg, self.bus.emitted_msgs) - self.assertTrue(self.skill.instance.my_special_var == "default") - - # check that we are not getting speak messages anymore - self.bus.emitted_msgs = [] - sleep(2) - self.assertTrue(self.bus.emitted_msgs == []) diff --git a/test/integrationtests/util/__init__.py b/test/integrationtests/util/__init__.py deleted file mode 100644 index 051afedb75cd..000000000000 --- a/test/integrationtests/util/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# TODO - move to ovos-utils diff --git a/test/integrationtests/util/commented.json b/test/integrationtests/util/commented.json deleted file mode 100644 index 00a581f6df47..000000000000 --- a/test/integrationtests/util/commented.json +++ /dev/null @@ -1,168 +0,0 @@ -// Leading comment - -{ -// C-style comment - "lang": "en-us", - - // Comment spaced out - "system_unit": "metric", - - // Comment tabbed out - - "time_format": "half", - - // comment and // another inside - "date_format": "MDY", - - // Comment with " inside it - "confirm_listening": true, - - # Python-style comment - "sounds": { -# Commment with no space - "start_listening": "snd/start_listening.wav", - # Comment inside with a tab - # and multiple lines - "end_listening": "snd/end_listening.wav" - // and a final thought - }, - "play_wav_cmdline": "aplay %1", - "play_mp3_cmdline": "mpg123 %1", - "play_ogg_cmdline": "ogg123 %1", - "location": { - "city": { - "code": "Lawrence", - "name": "Lawrence", - "state": { - "code": "KS", - "name": "Kansas", - "country": { - "code": "US", - "name": "United States" - } - } - }, - "coordinate": { - "latitude": 38.971669, - "longitude": -95.23525 - }, - "timezone": { - "code": "America/Chicago", - "name": "Central Standard Time", - "dstOffset": 3600000, - "offset": -21600000 - } - }, - "skills": { - "directory": "~/.local/share/mycroft/skills" - }, - "server": { - "url": "https://api.mycroft.ai", - "version": "v1", - "update": true, - "metrics": false - }, - "websocket": { - "host": "0.0.0.0", - "port": 8181, - "route": "/core", - "ssl": false - }, - "listener": { - "sample_rate": 16000, - "channels": 1, - "wake_word": "hey mycroft", - "phonemes": "HH EY . M AY K R AO F T", - "threshold": 1e-90, - "multiplier": 1.0, - "energy_ratio": 1.5 - }, - "enclosure": { - "port": "/dev/ttyAMA0", - "rate": 9600, - "timeout": 5.0, - "update": true, - "test": false - }, - "log_level": "DEBUG", - "ignore_logs": ["enclosure.mouth.viseme"], - "session": { - "ttl": 180 - }, - "stt": { - "module": "mycroft" - }, - "tts": { - "module": "mimic", - "mimic": { - "voice": "ap" - }, - "espeak": { - "lang": "english-us", - "voice": "m1" - } - }, - - // Mixture - # of types - // of comments - - - "wifi": { - "setup": false - }, - "ConfigurationSkill": { - "max_delay": 60 - }, - "WikipediaSkill": { - "max_results": 5, - "max_phrases": 2 - }, - "WolframAlphaSkill": { - "api_key": "", - "proxy": true - }, - "WeatherSkill": { - "api_key": "", - "proxy": true, - "temperature": "fahrenheit" - }, - "NPRNewsSkill": { - "url_rss": "http://www.npr.org/rss/podcast.php?id=500005" - }, - "AlarmSkill": { - "filename": "alarm.mp3", - "max_delay": 600, - "repeat_time": 20, - "extended_delay": 60 - }, - "ReminderSkill": { - "max_delay": 600, - "repeat_time": 60, - "extended_delay": 60 - }, - "VolumeSkill": { - "default_level": 6, - "min_volume": 0, - "max_volume": 100 - }, - "AudioRecordSkill": { - "filename": "/tmp/mycroft-recording.wav", - "free_disk": 100, - "max_time": 600, - "notify_delay": 5, - "rate": 16000, - "channels": 1 - }, - "SkillInstallerSkill": { - } -} - - - - - -# Trailing comments -# These go on -# and on - // and on diff --git a/test/integrationtests/util/muppets.dict b/test/integrationtests/util/muppets.dict deleted file mode 100644 index dc736bc4c9e2..000000000000 --- a/test/integrationtests/util/muppets.dict +++ /dev/null @@ -1,2 +0,0 @@ -muppet = miss piggy -fraggle = gobo diff --git a/test/integrationtests/util/plain.json b/test/integrationtests/util/plain.json deleted file mode 100644 index eec84631d886..000000000000 --- a/test/integrationtests/util/plain.json +++ /dev/null @@ -1,135 +0,0 @@ -{ - "lang": "en-us", - "system_unit": "metric", - "time_format": "half", - "date_format": "MDY", - "confirm_listening": true, - "sounds": { - "start_listening": "snd/start_listening.wav", - "end_listening": "snd/end_listening.wav" - }, - "play_wav_cmdline": "aplay %1", - "play_mp3_cmdline": "mpg123 %1", - "play_ogg_cmdline": "ogg123 %1", - "location": { - "city": { - "code": "Lawrence", - "name": "Lawrence", - "state": { - "code": "KS", - "name": "Kansas", - "country": { - "code": "US", - "name": "United States" - } - } - }, - "coordinate": { - "latitude": 38.971669, - "longitude": -95.23525 - }, - "timezone": { - "code": "America/Chicago", - "name": "Central Standard Time", - "dstOffset": 3600000, - "offset": -21600000 - } - }, - "skills": { - "directory": "~/.local/share/mycroft/skills" - }, - "server": { - "url": "https://api.mycroft.ai", - "version": "v1", - "update": true, - "metrics": false - }, - "websocket": { - "host": "0.0.0.0", - "port": 8181, - "route": "/core", - "ssl": false - }, - "listener": { - "sample_rate": 16000, - "channels": 1, - "wake_word": "hey mycroft", - "phonemes": "HH EY . M AY K R AO F T", - "threshold": 1e-90, - "multiplier": 1.0, - "energy_ratio": 1.5 - }, - "enclosure": { - "port": "/dev/ttyAMA0", - "rate": 9600, - "timeout": 5.0, - "update": true, - "test": false - }, - "log_level": "DEBUG", - "ignore_logs": ["enclosure.mouth.viseme"], - "session": { - "ttl": 180 - }, - "stt": { - "module": "mycroft" - }, - "tts": { - "module": "mimic", - "mimic": { - "voice": "ap" - }, - "espeak": { - "lang": "english-us", - "voice": "m1" - } - }, - "wifi": { - "setup": false - }, - "ConfigurationSkill": { - "max_delay": 60 - }, - "WikipediaSkill": { - "max_results": 5, - "max_phrases": 2 - }, - "WolframAlphaSkill": { - "api_key": "", - "proxy": true - }, - "WeatherSkill": { - "api_key": "", - "proxy": true, - "temperature": "fahrenheit" - }, - "NPRNewsSkill": { - "url_rss": "http://www.npr.org/rss/podcast.php?id=500005" - }, - "AlarmSkill": { - "filename": "alarm.mp3", - "max_delay": 600, - "repeat_time": 20, - "extended_delay": 60 - }, - "ReminderSkill": { - "max_delay": 600, - "repeat_time": 60, - "extended_delay": 60 - }, - "VolumeSkill": { - "default_level": 6, - "min_volume": 0, - "max_volume": 100 - }, - "AudioRecordSkill": { - "filename": "/tmp/mycroft-recording.wav", - "free_disk": 100, - "max_time": 600, - "notify_delay": 5, - "rate": 16000, - "channels": 1 - }, - "SkillInstallerSkill": { - } -} diff --git a/test/integrationtests/util/test_audio_utils.py b/test/integrationtests/util/test_audio_utils.py deleted file mode 100644 index 458b7a65ee48..000000000000 --- a/test/integrationtests/util/test_audio_utils.py +++ /dev/null @@ -1,131 +0,0 @@ - -from unittest import TestCase, mock - -from test.util import Anything -from mycroft.util import (play_ogg, play_mp3, play_wav, play_audio_file) -from mycroft.util.file_utils import get_temp_path - -test_config = { - 'play_wav_cmdline': 'mock_wav %1', - 'play_mp3_cmdline': 'mock_mp3 %1', - 'play_ogg_cmdline': 'mock_ogg %1' -} - - -@mock.patch('ovos_utils.sound.read_mycroft_config') -@mock.patch('ovos_utils.sound.subprocess') -class TestPlaySounds(TestCase): - def test_play_ogg(self, mock_subprocess, mock_conf): - mock_conf.return_value = test_config - play_ogg('insult.ogg') - mock_subprocess.Popen.assert_called_once_with(['mock_ogg', - 'insult.ogg'], - env=Anything()) - - @mock.patch('ovos_utils.sound.LOG') - def test_play_ogg_file_not_found(self, mock_log, - mock_subprocess, mock_conf): - """Test that simple log is raised when subprocess can't find command. - """ - def raise_filenotfound(*arg, **kwarg): - raise FileNotFoundError('TEST FILE NOT FOUND') - - mock_subprocess.Popen.side_effect = raise_filenotfound - mock_conf.return_value = test_config - self.assertEqual(play_ogg('insult.ogg'), None) - mock_log.error.called_once_with(Anything()) - - @mock.patch('ovos_utils.sound.LOG') - def test_play_ogg_exception(self, mock_log, - mock_subprocess, mock_conf): - """Test that stack trace is provided when unknown excpetion occurs""" - def raise_exception(*arg, **kwarg): - raise Exception - - mock_subprocess.Popen.side_effect = raise_exception - mock_conf.return_value = test_config - self.assertEqual(play_ogg('insult.ogg'), None) - mock_log.exception.called_once_with(Anything()) - - def test_play_mp3(self, mock_subprocess, mock_conf): - mock_conf.return_value = test_config - play_mp3('praise.mp3') - mock_subprocess.Popen.assert_called_once_with(['mock_mp3', - 'praise.mp3'], - env=Anything()) - - @mock.patch('ovos_utils.sound.LOG') - def test_play_mp3_file_not_found(self, mock_log, - mock_subprocess, mock_conf): - """Test that simple log is raised when subprocess can't find command. - """ - def raise_filenotfound(*arg, **kwarg): - raise FileNotFoundError('TEST FILE NOT FOUND') - - mock_subprocess.Popen.side_effect = raise_filenotfound - mock_conf.return_value = test_config - self.assertEqual(play_mp3('praise.mp3'), None) - mock_log.error.called_once_with(Anything()) - - @mock.patch('ovos_utils.sound.LOG') - def test_play_mp3_exception(self, mock_log, - mock_subprocess, mock_conf): - """Test that stack trace is provided when unknown excpetion occurs""" - def raise_exception(*arg, **kwarg): - raise Exception - - mock_subprocess.Popen.side_effect = raise_exception - mock_conf.return_value = test_config - self.assertEqual(play_mp3('praise.mp3'), None) - mock_log.exception.called_once_with(Anything()) - - def test_play_wav(self, mock_subprocess, mock_conf): - mock_conf.return_value = test_config - play_wav('indifference.wav') - mock_subprocess.Popen.assert_called_once_with(['mock_wav', - 'indifference.wav'], - env=Anything()) - - @mock.patch('ovos_utils.sound.LOG') - def test_play_wav_file_not_found(self, mock_log, - mock_subprocess, mock_conf): - """Test that simple log is raised when subprocess can't find command. - """ - def raise_filenotfound(*arg, **kwarg): - raise FileNotFoundError('TEST FILE NOT FOUND') - - mock_subprocess.Popen.side_effect = raise_filenotfound - mock_conf.return_value = test_config - self.assertEqual(play_wav('indifference.wav'), None) - mock_log.error.called_once_with(Anything()) - - @mock.patch('ovos_utils.sound.LOG') - def test_play_wav_exception(self, mock_log, - mock_subprocess, mock_conf): - """Test that stack trace is provided when unknown excpetion occurs""" - def raise_exception(*arg, **kwarg): - raise Exception - - mock_subprocess.Popen.side_effect = raise_exception - mock_conf.return_value = test_config - self.assertEqual(play_wav('indifference.wav'), None) - mock_log.exception.called_once_with(Anything()) - - def test_play_audio_file(self, mock_subprocess, mock_conf): - mock_conf.return_value = test_config - play_audio_file('indifference.wav') - mock_subprocess.Popen.assert_called_once_with(['mock_wav', - 'indifference.wav'], - env=Anything()) - mock_subprocess.Popen.reset_mock() - - play_audio_file('praise.mp3') - mock_subprocess.Popen.assert_called_once_with(['mock_mp3', - 'praise.mp3'], - env=Anything()) - mock_subprocess.Popen.reset_mock() - mock_conf.return_value = test_config - play_audio_file('insult.ogg') - mock_subprocess.Popen.assert_called_once_with(['mock_ogg', - 'insult.ogg'], - env=Anything()) diff --git a/test/integrationtests/util/test_download.py b/test/integrationtests/util/test_download.py deleted file mode 100644 index 7b11dbb5d455..000000000000 --- a/test/integrationtests/util/test_download.py +++ /dev/null @@ -1,109 +0,0 @@ - -from threading import Event -from unittest import TestCase, mock - -from mycroft.util.download import (download, _running_downloads, - _get_download_tmp) -from mycroft.util.file_utils import get_temp_path - -TEST_URL = 'http://example.com/mycroft-test.tar.gz' -TEST_DEST = get_temp_path('file.tar.gz') - - -@mock.patch('mycroft.util.download.subprocess') -@mock.patch('mycroft.util.download.os') -class TestDownload(TestCase): - def setUp(self): - """Remove any cached instance.""" - for key in list(_running_downloads.keys()): - _running_downloads.pop(key) - - def test_download_basic(self, mock_os, mock_subprocess): - """Test the basic download call.""" - mock_subprocess.call.return_value = 0 - - downloader = download(url=TEST_URL, - dest=TEST_DEST) - downloader.join() - mock_subprocess.call.assert_called_once_with(['wget', '-c', TEST_URL, - '-O', - TEST_DEST + '.part', - '--tries=20', - '--read-timeout=5']) - self.assertTrue(downloader.done) - - def test_download_with_header(self, mock_os, mock_subprocess): - """Test download with specific header.""" - mock_subprocess.call.return_value = 0 - - test_hdr = 'TEST_HEADER' - downloader = download(url=TEST_URL, - dest=TEST_DEST, - header=test_hdr) - downloader.join() - - self.assertTrue(downloader.done) - mock_subprocess.call.assert_called_once_with(['wget', '-c', TEST_URL, - '-O', - TEST_DEST + '.part', - '--tries=20', - '--read-timeout=5', - '--header=' + test_hdr]) - - def test_download_callback(self, mock_os, mock_subprocess): - """Check that callback function is called with correct destination.""" - mock_subprocess.call.return_value = 0 - action_called_with = None - - def action(dest): - nonlocal action_called_with - action_called_with = dest - - downloader = download(url=TEST_URL, - dest=TEST_DEST, - complete_action=action) - downloader.join() - - self.assertTrue(downloader.done) - self.assertEqual(action_called_with, TEST_DEST) - - def test_download_cache(self, mock_os, mock_subprocess): - """Make sure that a cached download is used if exists.""" - - transfer_done = Event() - - def wget_call(*args, **kwargs): - nonlocal transfer_done - transfer_done.wait() - return 0 - - downloader = download(url=TEST_URL, - dest=TEST_DEST) - downloader2 = download(url=TEST_URL, - dest=TEST_DEST) - # When called with the same args a cached download in progress should - # be returned instead of a new one. - self.assertTrue(downloader is downloader2) - transfer_done.set() - downloader.join() - - -@mock.patch('mycroft.util.download.glob') -class TestGetTemp(TestCase): - def test_no_existing(self, mock_glob): - mock_glob.return_value = [] - dest = get_temp_path('test') - self.assertEqual(_get_download_tmp(dest), dest + '.part') - - def test_existing(self, mock_glob): - mock_glob.return_value = [get_temp_path('test.part')] - dest = get_temp_path('test') - self.assertEqual(_get_download_tmp(dest), dest + '.part.1') - - def test_multiple_existing(self, mock_glob): - mock_glob.return_value = [get_temp_path('test.part'), - get_temp_path('test.part.1'), - get_temp_path('test.part.2')] - - dest = get_temp_path('test') - self.assertEqual(_get_download_tmp(dest), dest + '.part.3') diff --git a/test/integrationtests/util/test_json_helper.py b/test/integrationtests/util/test_json_helper.py deleted file mode 100644 index 76b31e28eead..000000000000 --- a/test/integrationtests/util/test_json_helper.py +++ /dev/null @@ -1,41 +0,0 @@ -# Copyright 2017 Mycroft AI Inc. -# -# 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. -# -import json -import unittest - -from os.path import dirname, join - -from mycroft.util.json_helper import load_commented_json - - -class TestFileLoad(unittest.TestCase): - - def test_load(self): - root_dir = dirname(__file__) - # Load normal JSON file - plainfile = join(root_dir, 'plain.json') - with open(plainfile, 'r') as f: - data_from_plain = json.load(f) - - # Load commented JSON file - commentedfile = join(root_dir, 'commented.json') - data_from_commented = load_commented_json(commentedfile) - - # Should be the same... - self.assertEqual(data_from_commented, data_from_plain) - - -if __name__ == "__main__": - unittest.main() diff --git a/test/integrationtests/util/test_log.py b/test/integrationtests/util/test_log.py deleted file mode 100644 index 42390f965ebc..000000000000 --- a/test/integrationtests/util/test_log.py +++ /dev/null @@ -1,71 +0,0 @@ -# Copyright 2017 Mycroft AI Inc. -# -# 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. -# -import unittest -import sys -from io import StringIO -from threading import Thread -from mycroft.util.log import LOG - - -class CaptureLogs(list): - def __init__(self): - list.__init__(self) - self._stdout = None - self._stringio = None - - def __enter__(self): - self._stdout = sys.stdout - sys.stdout = self._stringio = StringIO() - LOG.init() - return self - - def __exit__(self, *args): - self.extend(self._stringio.getvalue().splitlines()) - del self._stringio # free up some memory - sys.stdout = self._stdout - LOG.init() - - -class TestLog(unittest.TestCase): - def test_threads(self): - with CaptureLogs() as output: - def test_logging(): - LOG.debug('testing debug') - LOG.info('testing info') - LOG.warning('testing warning') - LOG.error('testing error') - LOG('testing custom').debug('test') - - threads = [] - for _ in range(100): - t = Thread(target=test_logging) - t.start() - threads.append(t) - - for t in threads: - t.join() - - assert len(output) > 0 - - for line in output: - found_msg = False - for msg in ['debug', 'info', 'warning', 'error', 'custom']: - if 'testing ' + msg in line: - found_msg = True - assert found_msg - - -if __name__ == "__main__": - unittest.main() diff --git a/test/integrationtests/util/test_monotonic_event.py b/test/integrationtests/util/test_monotonic_event.py deleted file mode 100644 index 9c7d27770e01..000000000000 --- a/test/integrationtests/util/test_monotonic_event.py +++ /dev/null @@ -1,32 +0,0 @@ -from threading import Thread -from time import sleep -from unittest import TestCase, mock - -from mycroft.util.monotonic_event import MonotonicEvent - - -class MonotonicEventTest(TestCase): - def test_wait_set(self): - event = MonotonicEvent() - event.set() - self.assertTrue(event.wait()) - - def test_wait_timeout(self): - event = MonotonicEvent() - self.assertFalse(event.wait(0.1)) - - def test_wait_set_with_timeout(self): - wait_result = False - event = MonotonicEvent() - - def wait_event(): - nonlocal wait_result - wait_result = event.wait(30) - - wait_thread = Thread(target=wait_event) - wait_thread.start() - - sleep(0.1) - event.set() - wait_thread.join() - self.assertTrue(wait_result) diff --git a/test/integrationtests/util/test_network_utils.py b/test/integrationtests/util/test_network_utils.py deleted file mode 100644 index ed7dcc1653be..000000000000 --- a/test/integrationtests/util/test_network_utils.py +++ /dev/null @@ -1,52 +0,0 @@ -from unittest import TestCase, mock - -from mycroft.util.network_utils import connected - - -class TestNetworkConnected(TestCase): - def test_default_config_succeeds(self): - """Check that happy path succeeds""" - self.assertTrue(connected()) - - -@mock.patch('ovos_config.config.Configuration') -class TestNetworkFailure(TestCase): - - def test_dns_and_ncsi_fail(self, mock_conf): - """Check that DNS and NCSI failure results in False response""" - mock_conf.return_value = { - "network_tests": { - "dns_primary": "127.0.0.1", - "dns_secondary": "127.0.0.1", - "web_url": "https://www.google.com", - "ncsi_endpoint": "http://www.msftncsi.com/ncsi.txt", - "ncsi_expected_text": "Unexpected text" - } - } - self.assertFalse(connected()) - - def test_secondary_dns_succeeds(self, mock_conf): - """Check that only primary DNS failing still succeeds""" - mock_conf.return_value = { - "network_tests": { - "dns_primary": "127.0.0.1", - "dns_secondary": "8.8.4.4", - "web_url": "https://www.google.com", - "ncsi_endpoint": "http://www.msftncsi.com/ncsi.txt", - "ncsi_expected_text": "Microsoft NCSI" - } - } - self.assertTrue(connected()) - - def test_dns_success_url_fail(self, mock_conf): - """Check that URL connection failure results in False response""" - mock_conf.return_value = { - "network_tests": { - "dns_primary": "8.8.8.8", - "dns_secondary": "8.8.4.4", - "web_url": "https://test.invalid", - "ncsi_endpoint": "http://www.msftncsi.com/ncsi.txt", - "ncsi_expected_text": "Microsoft NCSI" - } - } - self.assertFalse(connected()) diff --git a/test/integrationtests/util/test_parse.py b/test/integrationtests/util/test_parse.py deleted file mode 100644 index 6711a42120db..000000000000 --- a/test/integrationtests/util/test_parse.py +++ /dev/null @@ -1,263 +0,0 @@ -# -# Copyright 2017 Mycroft AI Inc. -# -# 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. -# -import unittest -from datetime import datetime, timedelta - -from mycroft.configuration.locale import load_language, get_default_tz -from lingua_franca.internal import FunctionNotLocalizedError - -from mycroft.util.parse import ( - extract_datetime, - extract_duration, - extract_number, - extract_numbers, - fuzzy_match, - get_gender, - match_one, - normalize -) -from mycroft.util.time import default_timezone - - -load_language("en-us") - - -class TestFuzzyMatch(unittest.TestCase): - def test_matches(self): - self.assertTrue(fuzzy_match("you and me", "you and me") >= 1.0) - self.assertTrue(fuzzy_match("you and me", "you") < 0.5) - self.assertTrue(fuzzy_match("You", "you") > 0.5) - self.assertTrue(fuzzy_match("you and me", "you") == - fuzzy_match("you", "you and me")) - self.assertTrue(fuzzy_match("you and me", "he or they") < 0.2) - - def test_match_one(self): - # test list of choices - choices = ['frank', 'kate', 'harry', 'henry'] - self.assertEqual(match_one('frank', choices)[0], 'frank') - self.assertEqual(match_one('fran', choices)[0], 'frank') - self.assertEqual(match_one('enry', choices)[0], 'henry') - self.assertEqual(match_one('katt', choices)[0], 'kate') - # test dictionary of choices - choices = {'frank': 1, 'kate': 2, 'harry': 3, 'henry': 4} - self.assertEqual(match_one('frank', choices)[0], 1) - self.assertEqual(match_one('enry', choices)[0], 4) - - -class TestNormalize(unittest.TestCase): - def test_articles(self): - self.assertEqual(normalize("this is a test", remove_articles=True), - "this is test") - self.assertEqual(normalize("this is the test", remove_articles=True), - "this is test") - self.assertEqual(normalize("and another test", remove_articles=True), - "and another test") - self.assertEqual(normalize("this is an extra test", - remove_articles=False), - "this is an extra test") - - def test_spaces(self): - self.assertEqual(normalize(" this is a test"), - "this is test") - self.assertEqual(normalize(" this is a test "), - "this is test") - self.assertEqual(normalize(" this is one test"), - "this is 1 test") - - def test_numbers(self): - self.assertEqual(normalize("this is a one two three test"), - "this is 1 2 3 test") - self.assertEqual(normalize(" it's a four five six test"), - "it is 4 5 6 test") - self.assertEqual(normalize("it's a seven eight nine test"), - "it is 7 8 9 test") - self.assertEqual(normalize("it's a seven eight nine test"), - "it is 7 8 9 test") - self.assertEqual(normalize("that's a ten eleven twelve test"), - "that is 10 11 12 test") - self.assertEqual(normalize("that's a thirteen fourteen test"), - "that is 13 14 test") - self.assertEqual(normalize("that's fifteen sixteen seventeen"), - "that is 15 16 17") - self.assertEqual(normalize("that's eighteen nineteen twenty"), - "that is 18 19 20") - self.assertEqual(normalize("that's one nineteen twenty two"), - "that is 1 19 22") - self.assertEqual(normalize("that's one hundred"), - "that is 100") - self.assertEqual(normalize("that's one two twenty two"), - "that is 1 2 22") - self.assertEqual(normalize("that's one and a half"), - "that is 1 and half") - self.assertEqual(normalize("that's one and a half and five six"), - "that is 1 and half and 5 6") - - def test_contractions(self): - self.assertEqual(normalize("ain't"), "is not") - self.assertEqual(normalize("aren't"), "are not") - self.assertEqual(normalize("can't"), "can not") - self.assertEqual(normalize("could've"), "could have") - self.assertEqual(normalize("couldn't"), "could not") - self.assertEqual(normalize("didn't"), "did not") - self.assertEqual(normalize("doesn't"), "does not") - self.assertEqual(normalize("don't"), "do not") - self.assertEqual(normalize("gonna"), "going to") - self.assertEqual(normalize("gotta"), "got to") - self.assertEqual(normalize("hadn't"), "had not") - self.assertEqual(normalize("hadn't have"), "had not have") - self.assertEqual(normalize("hasn't"), "has not") - self.assertEqual(normalize("haven't"), "have not") - # TODO: Ambiguous with "he had" - self.assertEqual(normalize("he'd"), "he would") - self.assertEqual(normalize("he'll"), "he will") - # TODO: Ambiguous with "he has" - self.assertEqual(normalize("he's"), "he is") - # TODO: Ambiguous with "how would" - self.assertEqual(normalize("how'd"), "how did") - self.assertEqual(normalize("how'll"), "how will") - # TODO: Ambiguous with "how has" and "how does" - self.assertEqual(normalize("how's"), "how is") - # TODO: Ambiguous with "I had" - self.assertEqual(normalize("I'd"), "I would") - self.assertEqual(normalize("I'll"), "I will") - self.assertEqual(normalize("I'm"), "I am") - self.assertEqual(normalize("I've"), "I have") - self.assertEqual(normalize("I haven't"), "I have not") - self.assertEqual(normalize("isn't"), "is not") - self.assertEqual(normalize("it'd"), "it would") - self.assertEqual(normalize("it'll"), "it will") - # TODO: Ambiguous with "it has" - self.assertEqual(normalize("it's"), "it is") - self.assertEqual(normalize("it isn't"), "it is not") - self.assertEqual(normalize("mightn't"), "might not") - self.assertEqual(normalize("might've"), "might have") - self.assertEqual(normalize("mustn't"), "must not") - self.assertEqual(normalize("mustn't have"), "must not have") - self.assertEqual(normalize("must've"), "must have") - self.assertEqual(normalize("needn't"), "need not") - self.assertEqual(normalize("oughtn't"), "ought not") - self.assertEqual(normalize("shan't"), "shall not") - # TODO: Ambiguous wiht "she had" - self.assertEqual(normalize("she'd"), "she would") - self.assertEqual(normalize("she hadn't"), "she had not") - self.assertEqual(normalize("she'll"), "she will") - self.assertEqual(normalize("she's"), "she is") - self.assertEqual(normalize("she isn't"), "she is not") - self.assertEqual(normalize("should've"), "should have") - self.assertEqual(normalize("shouldn't"), "should not") - self.assertEqual(normalize("shouldn't have"), "should not have") - self.assertEqual(normalize("somebody's"), "somebody is") - # TODO: Ambiguous with "someone had" - self.assertEqual(normalize("someone'd"), "someone would") - self.assertEqual(normalize("someone hadn't"), "someone had not") - self.assertEqual(normalize("someone'll"), "someone will") - # TODO: Ambiguous with "someone has" - self.assertEqual(normalize("someone's"), "someone is") - self.assertEqual(normalize("that'll"), "that will") - # TODO: Ambiguous with "that has" - self.assertEqual(normalize("that's"), "that is") - # TODO: Ambiguous with "that had" - self.assertEqual(normalize("that'd"), "that would") - # TODO: Ambiguous with "there had" - self.assertEqual(normalize("there'd"), "there would") - self.assertEqual(normalize("there're"), "there are") - # TODO: Ambiguous with "there has" - self.assertEqual(normalize("there's"), "there is") - # TODO: Ambiguous with "they had" - self.assertEqual(normalize("they'd"), "they would") - self.assertEqual(normalize("they'll"), "they will") - self.assertEqual(normalize("they won't have"), "they will not have") - self.assertEqual(normalize("they're"), "they are") - self.assertEqual(normalize("they've"), "they have") - self.assertEqual(normalize("they haven't"), "they have not") - self.assertEqual(normalize("wasn't"), "was not") - # TODO: Ambiguous wiht "we had" - self.assertEqual(normalize("we'd"), "we would") - self.assertEqual(normalize("we would've"), "we would have") - self.assertEqual(normalize("we wouldn't"), "we would not") - self.assertEqual(normalize("we wouldn't have"), "we would not have") - self.assertEqual(normalize("we'll"), "we will") - self.assertEqual(normalize("we won't have"), "we will not have") - self.assertEqual(normalize("we're"), "we are") - self.assertEqual(normalize("we've"), "we have") - self.assertEqual(normalize("weren't"), "were not") - self.assertEqual(normalize("what'd"), "what did") - self.assertEqual(normalize("what'll"), "what will") - self.assertEqual(normalize("what're"), "what are") - # TODO: Ambiguous with "what has" / "what does") - self.assertEqual(normalize("whats"), "what is") - self.assertEqual(normalize("what's"), "what is") - self.assertEqual(normalize("what've"), "what have") - # TODO: Ambiguous with "when has" - self.assertEqual(normalize("when's"), "when is") - self.assertEqual(normalize("where'd"), "where did") - # TODO: Ambiguous with "where has" / where does" - self.assertEqual(normalize("where's"), "where is") - self.assertEqual(normalize("where've"), "where have") - # TODO: Ambiguous with "who had" "who did") - self.assertEqual(normalize("who'd"), "who would") - self.assertEqual(normalize("who'd've"), "who would have") - self.assertEqual(normalize("who'll"), "who will") - self.assertEqual(normalize("who're"), "who are") - # TODO: Ambiguous with "who has" / "who does" - self.assertEqual(normalize("who's"), "who is") - self.assertEqual(normalize("who've"), "who have") - self.assertEqual(normalize("why'd"), "why did") - self.assertEqual(normalize("why're"), "why are") - # TODO: Ambiguous with "why has" / "why does" - self.assertEqual(normalize("why's"), "why is") - self.assertEqual(normalize("won't"), "will not") - self.assertEqual(normalize("won't've"), "will not have") - self.assertEqual(normalize("would've"), "would have") - self.assertEqual(normalize("wouldn't"), "would not") - self.assertEqual(normalize("wouldn't've"), "would not have") - self.assertEqual(normalize("ya'll"), "you all") - self.assertEqual(normalize("y'all"), "you all") - self.assertEqual(normalize("y'ain't"), "you are not") - # TODO: Ambiguous with "you had" - self.assertEqual(normalize("you'd"), "you would") - self.assertEqual(normalize("you'd've"), "you would have") - self.assertEqual(normalize("you'll"), "you will") - self.assertEqual(normalize("you're"), "you are") - self.assertEqual(normalize("you aren't"), "you are not") - self.assertEqual(normalize("you've"), "you have") - self.assertEqual(normalize("you haven't"), "you have not") - - def test_combinations(self): - self.assertEqual(normalize("I couldn't have guessed there'd be two"), - "I could not have guessed there would be 2") - self.assertEqual(normalize("I wouldn't have"), "I would not have") - self.assertEqual(normalize("I hadn't been there"), - "I had not been there") - self.assertEqual(normalize("I would've"), "I would have") - self.assertEqual(normalize("it hadn't"), "it had not") - self.assertEqual(normalize("it hadn't have"), "it had not have") - self.assertEqual(normalize("it would've"), "it would have") - self.assertEqual(normalize("she wouldn't have"), "she would not have") - self.assertEqual(normalize("she would've"), "she would have") - self.assertEqual(normalize("someone wouldn't have"), - "someone would not have") - self.assertEqual(normalize("someone would've"), "someone would have") - self.assertEqual(normalize("what's the weather like"), - "what is weather like") - self.assertEqual(normalize("that's what I told you"), - "that is what I told you") - - self.assertEqual(normalize("whats 8 + 4"), "what is 8 + 4") - - -if __name__ == "__main__": - unittest.main() diff --git a/test/integrationtests/util/test_platform.py b/test/integrationtests/util/test_platform.py deleted file mode 100644 index 431d14438a93..000000000000 --- a/test/integrationtests/util/test_platform.py +++ /dev/null @@ -1,11 +0,0 @@ -from unittest import TestCase, mock - -from mycroft.util import get_arch - - -class TestPlatform(TestCase): - @mock.patch('os.uname') - def test_get_arch(self, mock_uname): - mock_uname.return_value = ('Linux', 'Woodstock', '4.15.0-39-generic', - 'Awesome test system Mark 7', 'x86_64') - self.assertEqual(get_arch(), 'x86_64') diff --git a/test/integrationtests/util/test_plugins.py b/test/integrationtests/util/test_plugins.py deleted file mode 100644 index de6e8a059634..000000000000 --- a/test/integrationtests/util/test_plugins.py +++ /dev/null @@ -1,56 +0,0 @@ -# Copyright 2020 Mycroft AI Inc. -# -# 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. -# -from unittest import TestCase, mock - -import mycroft.util.plugins as mycroft_plugins - - -def get_plug_mock(name): - load_mock = mock.Mock(name=name) - load_mock.name = name - plug_mock = mock.Mock(name=name) - plug_mock.name = name - plug_mock.load.return_value = load_mock - return plug_mock - - -def mock_iter_entry_points(plug_type): - """Function to return mocked plugins.""" - plugs = { - 'mycroft.plugins.tts': [get_plug_mock('dummy'), - get_plug_mock('remote')], - 'mycroft.plugins.stt': [get_plug_mock('dummy'), - get_plug_mock('deepspeech')] - } - return plugs.get(plug_type, []) - - -@mock.patch('mycroft.util.plugins.pkg_resources') -class TestPlugins(TestCase): - def test_load_existing(self, mock_pkg_res): - """Ensure that plugin objects are returned if found.""" - mock_pkg_res.iter_entry_points.side_effect = mock_iter_entry_points - - # Load a couple of existing modules and verify that they're Ok - plug = mycroft_plugins.load_plugin('mycroft.plugins.tts', 'dummy') - self.assertEqual(plug.name, 'dummy') - plug = mycroft_plugins.load_plugin('mycroft.plugins.stt', 'deepspeech') - self.assertEqual(plug.name, 'deepspeech') - - def test_load_nonexisting(self, mock_pkg_res): - """Ensure that the return value is None when no plugin is found.""" - mock_pkg_res.iter_entry_points.side_effect = mock_iter_entry_points - plug = mycroft_plugins.load_plugin('mycroft.plugins.tts', 'blah') - self.assertEqual(plug, None) diff --git a/test/integrationtests/util/test_process_utils.py b/test/integrationtests/util/test_process_utils.py deleted file mode 100644 index d0f329dad173..000000000000 --- a/test/integrationtests/util/test_process_utils.py +++ /dev/null @@ -1,205 +0,0 @@ -from unittest import TestCase, mock - -from mycroft.util.process_utils import (_update_log_level, bus_logging_status, - create_daemon, ProcessStatus, - StatusCallbackMap) - - -class TestCreateDaemon(TestCase): - def test_create(self): - """Make sure deamon thread is created, and runs the expected function. - """ - thread_ran = False - - def thread_func(): - nonlocal thread_ran - thread_ran = True - - thread = create_daemon(thread_func) - self.assertTrue(thread.daemon) - self.assertTrue(thread_ran) - thread.join() - - def test_create_with_args(self): - """Check that the args and kwargs is passed to the thread function.""" - test_args = (1, 2, 3) - test_kwargs = {'meaning': 42, 'borg': '7 of 9'} - passed_args = None - passed_kwargs = None - - def thread_func(*args, **kwargs): - nonlocal passed_args - nonlocal passed_kwargs - passed_args = args - passed_kwargs = kwargs - - thread = create_daemon(thread_func, test_args, test_kwargs) - thread.join() - self.assertEqual(test_args, passed_args) - self.assertEqual(test_kwargs, passed_kwargs) - - -@mock.patch('mycroft.util.process_utils.LOG') -class TestUpdateLogLevel(TestCase): - def test_no_data(self, mock_log): - mock_log.level = 'UNSET' - log_msg = {'msg_type': 'mycroft.debug.log', - 'data': {}} - _update_log_level(log_msg, 'Test') - self.assertEqual(mock_log.level, 'UNSET') - - def test_set_debug(self, mock_log): - mock_log.level = 'UNSET' - log_msg = {'type': 'mycroft.debug.log', - 'data': {'level': 'DEBUG'}} - _update_log_level(log_msg, 'Test') - self.assertEqual(mock_log.level, 'DEBUG') - - def test_set_lowecase_debug(self, mock_log): - mock_log.level = 'UNSET' - log_msg = {'type': 'mycroft.debug.log', - 'data': {'level': 'debug'}} - _update_log_level(log_msg, 'Test') - self.assertEqual(mock_log.level, 'DEBUG') - - def test_set_invalid_level(self, mock_log): - mock_log.level = 'UNSET' - log_msg = {'type': 'mycroft.debug.log', - 'data': {'level': 'snowcrash'}} - _update_log_level(log_msg, 'Test') - self.assertEqual(mock_log.level, 'UNSET') - - def test_set_bus_logging(self, mock_log): - mock_log.level = 'UNSET' - log_msg = {'type': 'mycroft.debug.log', - 'data': {'bus': True}} - self.assertFalse(bus_logging_status()) - _update_log_level(log_msg, 'Test') - self.assertTrue(bus_logging_status()) - - -def create_mock_message(msg_type): - """Creates a mock with members matching a messagebus Message.""" - m = mock.Mock() - m.msg_type = msg_type - m.data = {} - m.context = {} - return m - - -class TestProcessStatus(TestCase): - def test_callbacks(self): - """Assert that callbacks are called as expected.""" - started = False - alive = False - ready = False - stopping = False - error = False - - def started_hook(): - nonlocal started - started = True - - def alive_hook(): - nonlocal alive - alive = True - - def ready_hook(): - nonlocal ready - ready = True - - def stopping_hook(): - nonlocal stopping - stopping = True - - def error_hook(err): - nonlocal error - error = err - - callbacks = StatusCallbackMap(on_started=started_hook, - on_alive=alive_hook, on_ready=ready_hook, - on_stopping=stopping_hook, - on_error=error_hook) - status = ProcessStatus('test', mock.Mock(), callbacks) - - status.set_started() - self.assertTrue(started) - - status.set_alive() - self.assertTrue(alive) - - status.set_ready() - self.assertTrue(ready) - - status.set_stopping() - self.assertTrue(stopping) - - err_msg = 'Test error' - status.set_error(err_msg) - self.assertEqual(err_msg, error) - - def test_init_status(self): - """Check that the status is neither alive nor ready after init.""" - status = ProcessStatus('test', mock.Mock()) - self.assertFalse(status.check_alive()) - self.assertFalse(status.check_ready()) - - def test_alive_status(self): - status = ProcessStatus('test', mock.Mock()) - status.set_alive() - self.assertTrue(status.check_alive()) - self.assertFalse(status.check_ready()) - - def test_ready_status(self): - """Check that alive and ready reports correctly.""" - status = ProcessStatus('test', mock.Mock()) - status.set_alive() - status.set_ready() - self.assertTrue(status.check_alive()) - self.assertTrue(status.check_ready()) - - def test_direct_to_ready_status(self): - """Ensure that process status indicates alive if only ready is set.""" - status = ProcessStatus('test', mock.Mock()) - status.set_ready() - self.assertTrue(status.check_alive()) - self.assertTrue(status.check_ready()) - - def test_error_status(self): - """Ensure that error resets the status and to not alive or ready.""" - status = ProcessStatus('test', mock.Mock()) - status.set_ready() - status.set_error() - self.assertFalse(status.check_alive()) - self.assertFalse(status.check_ready()) - - def test_ready_message(self): - """Assert that ready message contains the correct status.""" - status = ProcessStatus('test', mock.Mock()) - - # Check status when not ready - msg = create_mock_message('mycroft.test.all_loaded') - status.check_ready(msg) - msg.response.assert_called_with(data={'status': False}) - - # Check status when ready - status.set_ready() - msg = create_mock_message('mycroft.test.all_loaded') - status.check_ready(msg) - msg.response.assert_called_with(data={'status': True}) - - def test_is_alive__message(self): - """Assert that is_alive message contains the correct status.""" - status = ProcessStatus('test', mock.Mock()) - status.set_started() - - # Check status when not alive - msg = create_mock_message('mycroft.test.is_alive') - status.check_alive(msg) - msg.response.assert_called_with(data={'status': False}) - - # Check status when ready which should also indicate alive - status.set_ready() - msg = create_mock_message('mycroft.test.is_isalive') - status.check_alive(msg) - msg.response.assert_called_with(data={'status': True}) diff --git a/test/integrationtests/util/test_signal.py b/test/integrationtests/util/test_signal.py deleted file mode 100644 index 93a142ee7dab..000000000000 --- a/test/integrationtests/util/test_signal.py +++ /dev/null @@ -1,49 +0,0 @@ -# Copyright 2017 Mycroft AI Inc. -# -# 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. -# -import unittest -from shutil import rmtree - -from os.path import exists, isfile, join -from tempfile import gettempdir - -from mycroft.util import create_signal, check_for_signal - - -class TestSignals(unittest.TestCase): - def setUp(self): - if exists(join(gettempdir(), 'mycroft')): - rmtree(join(gettempdir(), 'mycroft')) - - def test_create_signal(self): - create_signal('test_signal') - self.assertTrue(isfile(join(gettempdir(), - 'mycroft/ipc/signal/test_signal'))) - - def test_check_signal(self): - if exists(join(gettempdir(), 'mycroft')): - rmtree(join(gettempdir(), 'mycroft')) - # check that signal is not found if file does not exist - self.assertFalse(check_for_signal('test_signal')) - - # Check that the signal is found when created - create_signal('test_signal') - self.assertTrue(check_for_signal('test_signal')) - # Check that the signal is removed after use - self.assertFalse(isfile(join(gettempdir(), - 'mycroft/ipc/signal/test_signal'))) - - -if __name__ == "__main__": - unittest.main() diff --git a/test/integrationtests/util/test_string_utils.py b/test/integrationtests/util/test_string_utils.py deleted file mode 100644 index fd65bd16df06..000000000000 --- a/test/integrationtests/util/test_string_utils.py +++ /dev/null @@ -1,9 +0,0 @@ -from unittest import TestCase -from mycroft.util import camel_case_split - - -class TestStringFunctions(TestCase): - def test_camel_case_split(self): - """Check that camel case string is split properly.""" - self.assertEqual(camel_case_split('MyCoolSkill'), 'My Cool Skill') - self.assertEqual(camel_case_split('MyCOOLSkill'), 'My COOL Skill') diff --git a/test/integrationtests/util/test_time.py b/test/integrationtests/util/test_time.py deleted file mode 100644 index 04ad97e86742..000000000000 --- a/test/integrationtests/util/test_time.py +++ /dev/null @@ -1,91 +0,0 @@ -from datetime import datetime -from dateutil.tz import tzfile, tzlocal, gettz -from unittest import TestCase, mock -from mycroft.configuration import setup_locale, set_default_tz -from mycroft.util.time import (default_timezone, now_local, now_utc, to_utc, - to_local, to_system) - -test_config = { - 'location': { - 'timezone': { - 'code': 'America/Chicago', - 'name': 'Central Standard Time', - 'dstOffset': 3600000, # Daylight saving offset in milliseconds - 'offset': -21600000 # Timezone offset in milliseconds - } - } -} - - -@mock.patch('mycroft.configuration.Configuration') -class TestTimeFuncs(TestCase): - def test_default_timezone(self, mock_conf): - # Test missing tz-info - # TODO how to ensure setup_locale() not called by a previous test? - # mock_conf.get.return_value = {} - # self.assertEqual(default_timezone(), tzlocal()) - - # Test tz from config - mock_conf.return_value = test_config - setup_locale() # will load (test) tz from config - self.assertEqual(default_timezone(), - tzfile('/usr/share/zoneinfo/America/Chicago')) - - # Test changing tz - set_default_tz(tzlocal()) - self.assertEqual(default_timezone(), tzlocal()) - - @mock.patch('mycroft.util.time.datetime') - def test_now_local(self, mock_dt, mock_conf): - mock_conf.return_value = test_config - setup_locale() - - dt_test = datetime(year=1985, month=10, day=25, hour=8, minute=18, - tzinfo=default_timezone()) - mock_dt.now.return_value = dt_test - self.assertEqual(now_local(), dt_test) - - expected_timezone = tzfile('/usr/share/zoneinfo/America/Chicago') - mock_dt.now.assert_called_with(expected_timezone) - - now_local(tzfile('/usr/share/zoneinfo/Europe/Stockholm')) - expected_timezone = tzfile('/usr/share/zoneinfo/Europe/Stockholm') - mock_dt.now.assert_called_with(expected_timezone) - - @mock.patch('mycroft.util.time.datetime') - def test_now_utc(self, mock_dt, mock_conf): - mock_conf.return_value = test_config - setup_locale() - - dt_test = datetime(year=1985, month=10, day=25, hour=8, minute=18) - mock_dt.utcnow.return_value = dt_test - - self.assertEqual(now_utc().tzinfo, gettz('UTC')) - - self.assertEqual(now_utc(), dt_test.astimezone(gettz('UTC'))) - mock_dt.utcnow.assert_called_with() - - def test_to_utc(self, mock_conf): - mock_conf.return_value = test_config - dt = datetime(year=2000, month=1, day=1, - hour=0, minute=0, second=0, - tzinfo=gettz('Europe/Stockholm')) - self.assertEqual(to_utc(dt), dt) - self.assertEqual(to_utc(dt).tzinfo, gettz('UTC')) - - def test_to_local(self, mock_conf): - mock_conf.return_value = test_config - dt = datetime(year=2000, month=1, day=1, - hour=0, minute=0, second=0, - tzinfo=gettz('Europe/Stockholm')) - self.assertEqual(to_local(dt), - dt.astimezone(default_timezone())) - self.assertEqual(to_local(dt).tzinfo, default_timezone()) - - def test_to_system(self, mock_conf): - mock_conf.return_value = test_config - dt = datetime(year=2000, month=1, day=1, - hour=0, minute=0, second=0, - tzinfo=gettz('Europe/Stockholm')) - self.assertEqual(to_system(dt), dt) - self.assertEqual(to_system(dt).tzinfo, tzlocal()) diff --git a/test/integrationtests/util/test_xdg.py b/test/integrationtests/util/test_xdg.py deleted file mode 100644 index 56fdd8267682..000000000000 --- a/test/integrationtests/util/test_xdg.py +++ /dev/null @@ -1,27 +0,0 @@ -from unittest import TestCase, mock - -from ovos_config.locations import get_xdg_config_save_path, get_xdg_data_save_path, get_xdg_cache_save_path -from ovos_backend_client.identity import IdentityManager -from mycroft.filesystem import FileSystemAccess -from mycroft.skills.settings import REMOTE_CACHE - - -class TestXdg(TestCase): - - @mock.patch('ovos_config.meta.get_xdg_base') - def test_base_folder(self, mock_folder): - mock_folder.return_value = "testcroft" - self.assertTrue(get_xdg_config_save_path().endswith("/testcroft")) - self.assertTrue(get_xdg_data_save_path().endswith("/testcroft")) - self.assertTrue(get_xdg_cache_save_path().endswith("/testcroft")) - - def test_identity(self): - self.assertTrue(IdentityManager.IDENTITY_FILE.startswith(get_xdg_config_save_path())) - self.assertTrue(IdentityManager.IDENTITY_FILE.endswith("/identity/identity2.json")) - self.assertTrue(IdentityManager.OLD_IDENTITY_FILE not in IdentityManager.IDENTITY_FILE) - - def test_filesystem(self): - self.assertTrue(FileSystemAccess("test").path.startswith(get_xdg_data_save_path())) - - def test_remote_config(self): - self.assertTrue(str(REMOTE_CACHE).startswith(get_xdg_cache_save_path())) diff --git a/test/integrationtests/util/unstripped_lines.txt b/test/integrationtests/util/unstripped_lines.txt deleted file mode 100644 index d8dee8ccdfea..000000000000 --- a/test/integrationtests/util/unstripped_lines.txt +++ /dev/null @@ -1,5 +0,0 @@ - Once upon a time -there was a great Dragon -It was red and cute - - The end diff --git a/test/unittests/common_query/ovos_tskill_fakewiki/__init__.py b/test/unittests/common_query/ovos_tskill_fakewiki/__init__.py index ed3f4b7ffb0f..8851c6bdd128 100644 --- a/test/unittests/common_query/ovos_tskill_fakewiki/__init__.py +++ b/test/unittests/common_query/ovos_tskill_fakewiki/__init__.py @@ -1,7 +1,7 @@ from adapt.intent import IntentBuilder from ovos_workshop.skills.common_query_skill import CommonQuerySkill, CQSMatchLevel -from mycroft.skills.core import intent_handler +from ovos_workshop.decorators import intent_handler class FakeWikiSkill(CommonQuerySkill):