From 45faa4cba77b8b7740bd8a34830abddfe5d8423e Mon Sep 17 00:00:00 2001 From: schneefux Date: Sat, 24 May 2014 19:30:36 -0700 Subject: Unit tests for brain using mocks --- client/test.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) (limited to 'client/test.py') diff --git a/client/test.py b/client/test.py index 461ceba..06c67fe 100644 --- a/client/test.py +++ b/client/test.py @@ -1,8 +1,10 @@ import unittest +from mock import Mock, patch from urllib2 import URLError, urlopen import yaml from test_mic import Mic from modules import * +import brain def activeInternet(): @@ -94,5 +96,40 @@ class TestModules(unittest.TestCase): or "Tomorrow" in outputs[0]) +class TestBrain(unittest.TestCase): + + @staticmethod + def _emptyBrain(): + mic = Mic([]) + profile = yaml.safe_load(open("profile.yml", "r")) + return brain.Brain(mic, profile) + + @patch.object(brain, 'logError') + def testLog(self, logError): + """Does Brain correctly log errors when raised by modules?""" + my_brain = TestBrain._emptyBrain() + unclear = my_brain.modules[-1] + with patch.object(unclear, 'handle') as mocked_handle: + mocked_handle.side_effect = KeyError('foo') + my_brain.query("zzz gibberish zzz") + logError.assert_called_with() + + def testSortByPriority(self): + """Does Brain sort modules by priority?""" + my_brain = TestBrain._emptyBrain() + with_priority = filter(lambda m: hasattr(m, 'PRIORITY'), my_brain.modules) + self.assertEqual(sorted(with_priority, key=lambda m: m.PRIORITY), with_priority) + + def testPriority(self): + """Does Brain correctly send query to higher-priority module?""" + my_brain = TestBrain._emptyBrain() + hn_module = 'modules.HN' + hn = filter(lambda m: m.__name__ == hn_module, my_brain.modules)[0] + + with patch.object(hn, 'handle') as mocked_handle: + my_brain.query("hacker news") + self.assertTrue(mocked_handle.called) + + if __name__ == '__main__': unittest.main() -- cgit v1.3.1