LogoopenSUSE Build Service > Projects
Sign Up | Log In

View File 0005-Fix-test-cases-under-python-3.patch of Package mycroft-core (Project home:alarrosa:packages)

From 5924b6992564d26d0d4074bb3182840f961d37fe Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=C3=85ke=20Forslund?= <ake.forslund@gmail.com>
Date: Thu, 8 Feb 2018 09:56:19 +0100
Subject: [PATCH 05/13] Fix test cases under python 3

Lots of minor fixes including, sorting dicts, making ints of strings,
     MagicMock file spec and some other things

A couple of issues in the mycroft-core code base were identified and
fixed. Most notably the incorrect version check for python three when
adding basestring.

Update .travis.yml
---
 .travis.yml                                   |  4 ++--
 mycroft/configuration/config.py               |  4 +++-
 mycroft/skills/core.py                        |  4 +++-
 mycroft/util/lang/parse_pt.py                 |  2 +-
 mycroft/util/parse.py                         |  2 +-
 test/unittests/client/audio_consumer_test.py  |  6 +++++-
 test/unittests/client/hotword_factory_test.py |  1 -
 test/unittests/skills/core.py                 | 27 ++++++++++++++-------------
 test/unittests/skills/intent_service.py       |  2 --
 test/unittests/skills/test_event_scheduler.py |  8 ++++----
 test/unittests/util/test_json_helper.py       |  2 +-
 test/unittests/util/test_log.py               |  3 ++-
 test/unittests/util/test_parse.py             |  2 +-
 test/unittests/util/test_parse_it.py          |  2 +-
 test/unittests/util/test_parse_pt.py          |  2 +-
 15 files changed, 39 insertions(+), 32 deletions(-)

diff --git a/.travis.yml b/.travis.yml
index 3d642a6..428a34e 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,9 +1,9 @@
 language: python
 before_install:
  - sudo apt-get update -qq
- - sudo apt-get install -qq mpg123 portaudio19-dev libglib2.0-dev swig bison libtool autoconf libglib2.0-dev libicu-dev libfann-dev
+ - sudo apt-get install -qq mpg123 portaudio19-dev libglib2.0-dev swig bison libtool autoconf libglib2.0-dev libicu-dev libfann-dev realpath
 python:
-  - "2.7"
+  - "3.4"
 # don't rebuild pocketsphinx for every build
 cache: pocketsphinx-python
 # command to install dependencies
diff --git a/mycroft/configuration/config.py b/mycroft/configuration/config.py
index 7cfa29f..f299708 100644
--- a/mycroft/configuration/config.py
+++ b/mycroft/configuration/config.py
@@ -24,8 +24,10 @@ from mycroft.util.json_helper import load_commented_json
 from mycroft.util.log import LOG
 
 # Python 2+3 compatibility
+import sys
 from future.utils import iteritems
-from past.builtins import basestring
+if sys.version_info[0] >= 3:
+    basestring = str
 
 
 def merge_dict(base, delta):
diff --git a/mycroft/skills/core.py b/mycroft/skills/core.py
index 2b4a4d1..7278fb6 100644
--- a/mycroft/skills/core.py
+++ b/mycroft/skills/core.py
@@ -39,7 +39,9 @@ from mycroft.skills.settings import SkillSettings
 from mycroft.util import resolve_resource_file
 from mycroft.util.log import LOG
 # python 2+3 compatibility
-from past.builtins import basestring
+import sys
+if sys.version_info[0] >= 3:
+    basestring = str
 
 MainModule = '__init__'
 
diff --git a/mycroft/util/lang/parse_pt.py b/mycroft/util/lang/parse_pt.py
index a7df7ca..9a8cf9a 100644
--- a/mycroft/util/lang/parse_pt.py
+++ b/mycroft/util/lang/parse_pt.py
@@ -1026,7 +1026,7 @@ def extract_datetime_pt(input_str, currentDate=None):
                                 remainder = "am"
                                 used += 1
                             elif wordNextNextNext == "noite":
-                                if 0 > strHH > 6:
+                                if 0 > int(strHH) > 6:
                                     remainder = "am"
                                 else:
                                     remainder = "pm"
diff --git a/mycroft/util/parse.py b/mycroft/util/parse.py
index 88aefb9..d74fc2a 100644
--- a/mycroft/util/parse.py
+++ b/mycroft/util/parse.py
@@ -43,7 +43,7 @@ def match_one(query, choices):
         Returns: tuple with best match, score
     """
     if isinstance(choices, dict):
-        _choices = choices.keys()
+        _choices = list(choices.keys())
     elif isinstance(choices, list):
         _choices = choices
     else:
diff --git a/test/unittests/client/audio_consumer_test.py b/test/unittests/client/audio_consumer_test.py
index f294bd7..18a22e1 100644
--- a/test/unittests/client/audio_consumer_test.py
+++ b/test/unittests/client/audio_consumer_test.py
@@ -13,7 +13,6 @@
 # limitations under the License.
 #
 import unittest
-from Queue import Queue
 
 import speech_recognition
 from os.path import dirname, join
@@ -21,6 +20,11 @@ from speech_recognition import WavFile, AudioData
 
 from mycroft.client.speech.listener import AudioConsumer, RecognizerLoop
 from mycroft.stt import MycroftSTT
+import sys
+if sys.version_info[0] < 3:
+    from Queue import Queue
+else:
+    from queue import Queue
 
 
 class MockRecognizer(object):
diff --git a/test/unittests/client/hotword_factory_test.py b/test/unittests/client/hotword_factory_test.py
index dcf6cdf..e406365 100644
--- a/test/unittests/client/hotword_factory_test.py
+++ b/test/unittests/client/hotword_factory_test.py
@@ -44,7 +44,6 @@ class PocketSphinxTest(unittest.TestCase):
         self.assertEquals(p.key_phrase, 'hey mycroft')
 
     def testVictoria(self):
-        print "VICTORIA!"
         config = {
             'hey victoria': {
                 'module': 'pocketsphinx',
diff --git a/test/unittests/skills/core.py b/test/unittests/skills/core.py
index d6df09d..e9fb06c 100644
--- a/test/unittests/skills/core.py
+++ b/test/unittests/skills/core.py
@@ -27,6 +27,9 @@ from mycroft.skills.core import load_regex_from_file, load_regex, \
 from mycroft.skills.core import MycroftSkill, load_skill, \
     create_skill_descriptor, open_intent_envelope
 
+if sys.version_info[0] >= 3:
+    basestring = str
+
 
 class MockEmitter(object):
     def __init__(self):
@@ -83,8 +86,9 @@ class MycroftSkillTest(unittest.TestCase):
     def check_emitter(self, result_list):
         for type in self.emitter.get_types():
             self.assertEquals(type, 'register_vocab')
-        self.assertEquals(sorted(self.emitter.get_results()),
-                          sorted(result_list))
+        self.assertEquals(sorted(self.emitter.get_results(),
+                                 key=lambda d: sorted(d.items())),
+                          sorted(result_list, key=lambda d: sorted(d.items())))
         self.emitter.reset()
 
     def test_load_regex_from_file_single(self):
@@ -100,17 +104,12 @@ class MycroftSkillTest(unittest.TestCase):
         self.check_regex_from_file('invalid/none.rx')
 
     def test_load_regex_from_file_invalid(self):
-        try:
+        with self.assertRaises(error):
             self.check_regex_from_file('invalid/invalid.rx')
-        except error as e:
-            self.assertEquals(e.__str__(),
-                              'unexpected end of regular expression')
 
     def test_load_regex_from_file_does_not_exist(self):
-        try:
+        with self.assertRaises(IOError):
             self.check_regex_from_file('does_not_exist.rx')
-        except IOError as e:
-            self.assertEquals(e.strerror, 'No such file or directory')
 
     def test_load_regex_full(self):
         self.check_regex(join(self.regex_path, 'valid'),
@@ -241,8 +240,9 @@ class MycroftSkillTest(unittest.TestCase):
     def check_register_object_file(self, types_list, result_list):
         self.assertEquals(sorted(self.emitter.get_types()),
                           sorted(types_list))
-        self.assertEquals(sorted(self.emitter.get_results()),
-                          sorted(result_list))
+        self.assertEquals(sorted(self.emitter.get_results(),
+                                 key=lambda d: sorted(d.items())),
+                          sorted(result_list, key=lambda d: sorted(d.items())))
         self.emitter.reset()
 
     def test_register_intent_file(self):
@@ -272,8 +272,9 @@ class MycroftSkillTest(unittest.TestCase):
         self.check_register_object_file(expected_types, expected_results)
 
     def check_register_decorators(self, result_list):
-        self.assertEquals(sorted(self.emitter.get_results()),
-                          sorted(result_list))
+        self.assertEquals(sorted(self.emitter.get_results(),
+                                 key=lambda d: sorted(d.items())),
+                          sorted(result_list, key=lambda d: sorted(d.items())))
         self.emitter.reset()
 
     def test_register_decorators(self):
diff --git a/test/unittests/skills/intent_service.py b/test/unittests/skills/intent_service.py
index 8153754..78b4af7 100644
--- a/test/unittests/skills/intent_service.py
+++ b/test/unittests/skills/intent_service.py
@@ -46,7 +46,6 @@ class ContextManagerTest(unittest.TestCase):
         entity = {'confidence': 1.0}
         context = 'TestContext'
         word = 'TestWord'
-        print "Adding " + context
         entity['data'] = [(word, context)]
         entity['match'] = word
         entity['key'] = word
@@ -59,7 +58,6 @@ class ContextManagerTest(unittest.TestCase):
         entity = {'confidence': 1.0}
         context = 'TestContext'
         word = 'TestWord'
-        print "Adding " + context
         entity['data'] = [(word, context)]
         entity['match'] = word
         entity['key'] = word
diff --git a/test/unittests/skills/test_event_scheduler.py b/test/unittests/skills/test_event_scheduler.py
index e706b97..7e7784b 100644
--- a/test/unittests/skills/test_event_scheduler.py
+++ b/test/unittests/skills/test_event_scheduler.py
@@ -19,7 +19,7 @@ class TestEventScheduler(unittest.TestCase):
             Test creating and shutting down event_scheduler.
         """
         mock_load.return_value = ''
-        mock_open.return_value = mock.MagicMock(spec=file)
+        mock_open.return_value = mock.MagicMock()
         emitter = mock.MagicMock()
         es = EventScheduler(emitter)
         es.shutdown()
@@ -36,7 +36,7 @@ class TestEventScheduler(unittest.TestCase):
         """
         # Thread start is mocked so will not actually run the thread loop
         mock_load.return_value = ''
-        mock_open.return_value = mock.MagicMock(spec=file)
+        mock_open.return_value = mock.MagicMock()
         emitter = mock.MagicMock()
         es = EventScheduler(emitter)
 
@@ -63,7 +63,7 @@ class TestEventScheduler(unittest.TestCase):
             Test save functionality.
         """
         mock_load.return_value = ''
-        mock_open.return_value = mock.MagicMock(spec=file)
+        mock_open.return_value = mock.MagicMock()
         emitter = mock.MagicMock()
         es = EventScheduler(emitter)
 
@@ -87,7 +87,7 @@ class TestEventScheduler(unittest.TestCase):
             Test save functionality.
         """
         mock_load.return_value = ''
-        mock_open.return_value = mock.MagicMock(spec=file)
+        mock_open.return_value = mock.MagicMock()
         emitter = mock.MagicMock()
         es = EventScheduler(emitter)
 
diff --git a/test/unittests/util/test_json_helper.py b/test/unittests/util/test_json_helper.py
index 7330248..76b31e2 100644
--- a/test/unittests/util/test_json_helper.py
+++ b/test/unittests/util/test_json_helper.py
@@ -26,7 +26,7 @@ class TestFileLoad(unittest.TestCase):
         root_dir = dirname(__file__)
         # Load normal JSON file
         plainfile = join(root_dir, 'plain.json')
-        with open(plainfile, 'rw') as f:
+        with open(plainfile, 'r') as f:
             data_from_plain = json.load(f)
 
         # Load commented JSON file
diff --git a/test/unittests/util/test_log.py b/test/unittests/util/test_log.py
index 4e1731f..42390f9 100644
--- a/test/unittests/util/test_log.py
+++ b/test/unittests/util/test_log.py
@@ -14,7 +14,7 @@
 #
 import unittest
 import sys
-from cStringIO import StringIO
+from io import StringIO
 from threading import Thread
 from mycroft.util.log import LOG
 
@@ -66,5 +66,6 @@ class TestLog(unittest.TestCase):
                     found_msg = True
             assert found_msg
 
+
 if __name__ == "__main__":
     unittest.main()
diff --git a/test/unittests/util/test_parse.py b/test/unittests/util/test_parse.py
index 6355a39..a66b2e3 100644
--- a/test/unittests/util/test_parse.py
+++ b/test/unittests/util/test_parse.py
@@ -83,7 +83,7 @@ class TestNormalize(unittest.TestCase):
 
     def test_extractdatetime_en(self):
         def extractWithFormat(text):
-            date = datetime(2017, 06, 27, 00, 00)
+            date = datetime(2017, 6, 27, 0, 0)
             [extractedDate, leftover] = extract_datetime(text, date)
             extractedDate = extractedDate.strftime("%Y-%m-%d %H:%M:%S")
             return [extractedDate, leftover]
diff --git a/test/unittests/util/test_parse_it.py b/test/unittests/util/test_parse_it.py
index 6057b93..ab1b5d4 100644
--- a/test/unittests/util/test_parse_it.py
+++ b/test/unittests/util/test_parse_it.py
@@ -175,7 +175,7 @@ class TestNormalize(unittest.TestCase):
 
     def test_extractdatetime_it(self):
         def extractWithFormat(text):
-            date = datetime(2018, 01, 13, 00, 00)
+            date = datetime(2018, 1, 13, 0, 0)
             [extractedDate, leftover] = extract_datetime(text, date,
                                                          lang="it")
             extractedDate = extractedDate.strftime("%Y-%m-%d %H:%M:%S")
diff --git a/test/unittests/util/test_parse_pt.py b/test/unittests/util/test_parse_pt.py
index 045d70f..a75c383 100644
--- a/test/unittests/util/test_parse_pt.py
+++ b/test/unittests/util/test_parse_pt.py
@@ -140,7 +140,7 @@ class TestNormalize(unittest.TestCase):
 
     def test_extractdatetime_pt(self):
         def extractWithFormat(text):
-            date = datetime(2017, 06, 27, 00, 00)
+            date = datetime(2017, 6, 27, 0, 0)
             [extractedDate, leftover] = extract_datetime(text, date,
                                                          lang="pt")
             extractedDate = extractedDate.strftime("%Y-%m-%d %H:%M:%S")
-- 
2.16.2