##// END OF EJS Templates
Fixing misc testing related things.
Brian Granger -
Show More
@@ -1,76 +1,77 b''
1 """
1 """
2 Base front end class for all async frontends.
2 Base front end class for all async frontends.
3 """
3 """
4 __docformat__ = "restructuredtext en"
4 __docformat__ = "restructuredtext en"
5
5
6 #-------------------------------------------------------------------------------
6 #-------------------------------------------------------------------------------
7 # Copyright (C) 2008 The IPython Development Team
7 # Copyright (C) 2008 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-------------------------------------------------------------------------------
11 #-------------------------------------------------------------------------------
12
12
13
13
14 #-------------------------------------------------------------------------------
14 #-------------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-------------------------------------------------------------------------------
16 #-------------------------------------------------------------------------------
17 from IPython.external import guid
18
17
18 from IPython.external import guid
19
19
20 from zope.interface import Interface, Attribute, implements, classProvides
20 from zope.interface import Interface, Attribute, implements, classProvides
21 from twisted.python.failure import Failure
21 from twisted.python.failure import Failure
22 from IPython.frontend.frontendbase import FrontEndBase, IFrontEnd, IFrontEndFactory
22 from IPython.frontend.frontendbase import (
23 FrontEndBase, IFrontEnd, IFrontEndFactory)
23 from IPython.kernel.core.history import FrontEndHistory
24 from IPython.kernel.core.history import FrontEndHistory
24 from IPython.kernel.engineservice import IEngineCore
25 from IPython.kernel.engineservice import IEngineCore
25
26
26
27
27 class AsyncFrontEndBase(FrontEndBase):
28 class AsyncFrontEndBase(FrontEndBase):
28 """
29 """
29 Overrides FrontEndBase to wrap execute in a deferred result.
30 Overrides FrontEndBase to wrap execute in a deferred result.
30 All callbacks are made as callbacks on the deferred result.
31 All callbacks are made as callbacks on the deferred result.
31 """
32 """
32
33
33 implements(IFrontEnd)
34 implements(IFrontEnd)
34 classProvides(IFrontEndFactory)
35 classProvides(IFrontEndFactory)
35
36
36 def __init__(self, engine=None, history=None):
37 def __init__(self, engine=None, history=None):
37 assert(engine==None or IEngineCore.providedBy(engine))
38 assert(engine==None or IEngineCore.providedBy(engine))
38 self.engine = IEngineCore(engine)
39 self.engine = IEngineCore(engine)
39 if history is None:
40 if history is None:
40 self.history = FrontEndHistory(input_cache=[''])
41 self.history = FrontEndHistory(input_cache=[''])
41 else:
42 else:
42 self.history = history
43 self.history = history
43
44
44
45
45 def execute(self, block, blockID=None):
46 def execute(self, block, blockID=None):
46 """Execute the block and return the deferred result.
47 """Execute the block and return the deferred result.
47
48
48 Parameters:
49 Parameters:
49 block : {str, AST}
50 block : {str, AST}
50 blockID : any
51 blockID : any
51 Caller may provide an ID to identify this block.
52 Caller may provide an ID to identify this block.
52 result['blockID'] := blockID
53 result['blockID'] := blockID
53
54
54 Result:
55 Result:
55 Deferred result of self.interpreter.execute
56 Deferred result of self.interpreter.execute
56 """
57 """
57
58
58 if(not self.is_complete(block)):
59 if(not self.is_complete(block)):
59 return Failure(Exception("Block is not compilable"))
60 return Failure(Exception("Block is not compilable"))
60
61
61 if(blockID == None):
62 if(blockID == None):
62 blockID = guid.generate()
63 blockID = guid.generate()
63
64
64 d = self.engine.execute(block)
65 d = self.engine.execute(block)
65 d.addCallback(self._add_history, block=block)
66 d.addCallback(self._add_history, block=block)
66 d.addCallbacks(self._add_block_id_for_result,
67 d.addCallbacks(self._add_block_id_for_result,
67 errback=self._add_block_id_for_failure,
68 errback=self._add_block_id_for_failure,
68 callbackArgs=(blockID,),
69 callbackArgs=(blockID,),
69 errbackArgs=(blockID,))
70 errbackArgs=(blockID,))
70 d.addBoth(self.update_cell_prompt, blockID=blockID)
71 d.addBoth(self.update_cell_prompt, blockID=blockID)
71 d.addCallbacks(self.render_result,
72 d.addCallbacks(self.render_result,
72 errback=self.render_error)
73 errback=self.render_error)
73
74
74 return d
75 return d
75
76
76
77
@@ -1,95 +1,100 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """This file contains unittests for the
2 """This file contains unittests for the
3 IPython.frontend.cocoa.cocoa_frontend module.
3 IPython.frontend.cocoa.cocoa_frontend module.
4 """
4 """
5 __docformat__ = "restructuredtext en"
5 __docformat__ = "restructuredtext en"
6
6
7 #---------------------------------------------------------------------------
7 #---------------------------------------------------------------------------
8 # Copyright (C) 2005 The IPython Development Team
8 # Copyright (C) 2005 The IPython Development Team
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #---------------------------------------------------------------------------
12 #---------------------------------------------------------------------------
13
13
14 #---------------------------------------------------------------------------
14 #---------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #---------------------------------------------------------------------------
16 #---------------------------------------------------------------------------
17
17
18 # Tell nose to skip this module
19 __test__ = {}
20
21 from twisted.trial import unittest
22 from twisted.internet.defer import succeed
18
23
19 try:
20 from IPython.kernel.core.interpreter import Interpreter
24 from IPython.kernel.core.interpreter import Interpreter
21 import IPython.kernel.engineservice as es
25 import IPython.kernel.engineservice as es
22 from IPython.testing.util import DeferredTestCase
26
23 from twisted.internet.defer import succeed
27 try:
24 from IPython.frontend.cocoa.cocoa_frontend import IPythonCocoaController
28 from IPython.frontend.cocoa.cocoa_frontend import IPythonCocoaController
25 from Foundation import NSMakeRect
29 from Foundation import NSMakeRect
26 from AppKit import NSTextView, NSScrollView
30 from AppKit import NSTextView, NSScrollView
27 except ImportError:
31 except ImportError:
28 import nose
32 # This tells twisted.trial to skip this module if PyObjC is not found
29 raise nose.SkipTest("This test requires zope.interface, Twisted, Foolscap and PyObjC")
33 skip = True
30
34
31 class TestIPythonCocoaControler(DeferredTestCase):
35 #---------------------------------------------------------------------------
36 # Tests
37 #---------------------------------------------------------------------------
38 class TestIPythonCocoaControler(unittest.TestCase):
32 """Tests for IPythonCocoaController"""
39 """Tests for IPythonCocoaController"""
33
40
34 def setUp(self):
41 def setUp(self):
35 self.controller = IPythonCocoaController.alloc().init()
42 self.controller = IPythonCocoaController.alloc().init()
36 self.engine = es.EngineService()
43 self.engine = es.EngineService()
37 self.engine.startService()
44 self.engine.startService()
38
45
39 def tearDown(self):
46 def tearDown(self):
40 self.controller = None
47 self.controller = None
41 self.engine.stopService()
48 self.engine.stopService()
42
49
43 def testControllerExecutesCode(self):
50 def testControllerExecutesCode(self):
44 code ="""5+5"""
51 code ="""5+5"""
45 expected = Interpreter().execute(code)
52 expected = Interpreter().execute(code)
46 del expected['number']
53 del expected['number']
47 def removeNumberAndID(result):
54 def removeNumberAndID(result):
48 del result['number']
55 del result['number']
49 del result['id']
56 del result['id']
50 return result
57 return result
51 self.assertDeferredEquals(
58 d = self.controller.execute(code)
52 self.controller.execute(code).addCallback(removeNumberAndID),
59 d.addCallback(removeNumberAndID)
53 expected)
60 d.addCallback(lambda r: self.assertEquals(r, expected))
54
61
55 def testControllerMirrorsUserNSWithValuesAsStrings(self):
62 def testControllerMirrorsUserNSWithValuesAsStrings(self):
56 code = """userns1=1;userns2=2"""
63 code = """userns1=1;userns2=2"""
57 def testControllerUserNS(result):
64 def testControllerUserNS(result):
58 self.assertEquals(self.controller.userNS['userns1'], 1)
65 self.assertEquals(self.controller.userNS['userns1'], 1)
59 self.assertEquals(self.controller.userNS['userns2'], 2)
66 self.assertEquals(self.controller.userNS['userns2'], 2)
60
61 self.controller.execute(code).addCallback(testControllerUserNS)
67 self.controller.execute(code).addCallback(testControllerUserNS)
62
68
63
64 def testControllerInstantiatesIEngine(self):
69 def testControllerInstantiatesIEngine(self):
65 self.assert_(es.IEngineBase.providedBy(self.controller.engine))
70 self.assert_(es.IEngineBase.providedBy(self.controller.engine))
66
71
67 def testControllerCompletesToken(self):
72 def testControllerCompletesToken(self):
68 code = """longNameVariable=10"""
73 code = """longNameVariable=10"""
69 def testCompletes(result):
74 def testCompletes(result):
70 self.assert_("longNameVariable" in result)
75 self.assert_("longNameVariable" in result)
71
76
72 def testCompleteToken(result):
77 def testCompleteToken(result):
73 self.controller.complete("longNa").addCallback(testCompletes)
78 self.controller.complete("longNa").addCallback(testCompletes)
74
79
75 self.controller.execute(code).addCallback(testCompletes)
80 self.controller.execute(code).addCallback(testCompletes)
76
81
77
82
78 def testCurrentIndent(self):
83 def testCurrentIndent(self):
79 """test that current_indent_string returns current indent or None.
84 """test that current_indent_string returns current indent or None.
80 Uses _indent_for_block for direct unit testing.
85 Uses _indent_for_block for direct unit testing.
81 """
86 """
82
87
83 self.controller.tabUsesSpaces = True
88 self.controller.tabUsesSpaces = True
84 self.assert_(self.controller._indent_for_block("""a=3""") == None)
89 self.assert_(self.controller._indent_for_block("""a=3""") == None)
85 self.assert_(self.controller._indent_for_block("") == None)
90 self.assert_(self.controller._indent_for_block("") == None)
86 block = """def test():\n a=3"""
91 block = """def test():\n a=3"""
87 self.assert_(self.controller._indent_for_block(block) == \
92 self.assert_(self.controller._indent_for_block(block) == \
88 ' ' * self.controller.tabSpaces)
93 ' ' * self.controller.tabSpaces)
89
94
90 block = """if(True):\n%sif(False):\n%spass""" % \
95 block = """if(True):\n%sif(False):\n%spass""" % \
91 (' '*self.controller.tabSpaces,
96 (' '*self.controller.tabSpaces,
92 2*' '*self.controller.tabSpaces)
97 2*' '*self.controller.tabSpaces)
93 self.assert_(self.controller._indent_for_block(block) == \
98 self.assert_(self.controller._indent_for_block(block) == \
94 2*(' '*self.controller.tabSpaces))
99 2*(' '*self.controller.tabSpaces))
95
100
@@ -1,111 +1,109 b''
1 # encoding: utf-8
1 # encoding: utf-8
2
2
3 """This file contains unittests for the asyncfrontendbase module."""
3 """This file contains unittests for the asyncfrontendbase module."""
4
4
5 __docformat__ = "restructuredtext en"
5 __docformat__ = "restructuredtext en"
6
6
7 #---------------------------------------------------------------------------
7 #---------------------------------------------------------------------------
8 # Copyright (C) 2008 The IPython Development Team
8 # Copyright (C) 2008 The IPython Development Team
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #---------------------------------------------------------------------------
12 #---------------------------------------------------------------------------
13
13
14 #---------------------------------------------------------------------------
14 #---------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #---------------------------------------------------------------------------
16 #---------------------------------------------------------------------------
17
17
18 # Tell nose to skip this module
19 __test__ = {}
18
20
19 try:
20 from twisted.trial import unittest
21 from twisted.trial import unittest
21 from IPython.frontend.asyncfrontendbase import AsyncFrontEndBase
22 from IPython.frontend.asyncfrontendbase import AsyncFrontEndBase
22 from IPython.frontend import frontendbase
23 from IPython.frontend import frontendbase
23 from IPython.kernel.engineservice import EngineService
24 from IPython.kernel.engineservice import EngineService
24 from IPython.testing.parametric import Parametric, parametric
25 from IPython.testing.parametric import Parametric, parametric
25 except ImportError:
26 import nose
27 raise nose.SkipTest("This test requires zope.interface, Twisted and Foolscap")
28
26
29
27
30 class FrontEndCallbackChecker(AsyncFrontEndBase):
28 class FrontEndCallbackChecker(AsyncFrontEndBase):
31 """FrontEndBase subclass for checking callbacks"""
29 """FrontEndBase subclass for checking callbacks"""
32 def __init__(self, engine=None, history=None):
30 def __init__(self, engine=None, history=None):
33 super(FrontEndCallbackChecker, self).__init__(engine=engine,
31 super(FrontEndCallbackChecker, self).__init__(engine=engine,
34 history=history)
32 history=history)
35 self.updateCalled = False
33 self.updateCalled = False
36 self.renderResultCalled = False
34 self.renderResultCalled = False
37 self.renderErrorCalled = False
35 self.renderErrorCalled = False
38
36
39 def update_cell_prompt(self, result, blockID=None):
37 def update_cell_prompt(self, result, blockID=None):
40 self.updateCalled = True
38 self.updateCalled = True
41 return result
39 return result
42
40
43 def render_result(self, result):
41 def render_result(self, result):
44 self.renderResultCalled = True
42 self.renderResultCalled = True
45 return result
43 return result
46
44
47 def render_error(self, failure):
45 def render_error(self, failure):
48 self.renderErrorCalled = True
46 self.renderErrorCalled = True
49 return failure
47 return failure
50
48
51
49
52 class TestAsyncFrontendBase(unittest.TestCase):
50 class TestAsyncFrontendBase(unittest.TestCase):
53 def setUp(self):
51 def setUp(self):
54 """Setup the EngineService and FrontEndBase"""
52 """Setup the EngineService and FrontEndBase"""
55
53
56 self.fb = FrontEndCallbackChecker(engine=EngineService())
54 self.fb = FrontEndCallbackChecker(engine=EngineService())
57
55
58 def test_implements_IFrontEnd(self):
56 def test_implements_IFrontEnd(self):
59 self.assert_(frontendbase.IFrontEnd.implementedBy(
57 self.assert_(frontendbase.IFrontEnd.implementedBy(
60 AsyncFrontEndBase))
58 AsyncFrontEndBase))
61
59
62 def test_is_complete_returns_False_for_incomplete_block(self):
60 def test_is_complete_returns_False_for_incomplete_block(self):
63 block = """def test(a):"""
61 block = """def test(a):"""
64 self.assert_(self.fb.is_complete(block) == False)
62 self.assert_(self.fb.is_complete(block) == False)
65
63
66 def test_is_complete_returns_True_for_complete_block(self):
64 def test_is_complete_returns_True_for_complete_block(self):
67 block = """def test(a): pass"""
65 block = """def test(a): pass"""
68 self.assert_(self.fb.is_complete(block))
66 self.assert_(self.fb.is_complete(block))
69 block = """a=3"""
67 block = """a=3"""
70 self.assert_(self.fb.is_complete(block))
68 self.assert_(self.fb.is_complete(block))
71
69
72 def test_blockID_added_to_result(self):
70 def test_blockID_added_to_result(self):
73 block = """3+3"""
71 block = """3+3"""
74 d = self.fb.execute(block, blockID='TEST_ID')
72 d = self.fb.execute(block, blockID='TEST_ID')
75 d.addCallback(lambda r: self.assert_(r['blockID']=='TEST_ID'))
73 d.addCallback(lambda r: self.assert_(r['blockID']=='TEST_ID'))
76 return d
74 return d
77
75
78 def test_blockID_added_to_failure(self):
76 def test_blockID_added_to_failure(self):
79 block = "raise Exception()"
77 block = "raise Exception()"
80 d = self.fb.execute(block,blockID='TEST_ID')
78 d = self.fb.execute(block,blockID='TEST_ID')
81 d.addErrback(lambda f: self.assert_(f.blockID=='TEST_ID'))
79 d.addErrback(lambda f: self.assert_(f.blockID=='TEST_ID'))
82 return d
80 return d
83
81
84 def test_callbacks_added_to_execute(self):
82 def test_callbacks_added_to_execute(self):
85 d = self.fb.execute("10+10")
83 d = self.fb.execute("10+10")
86 d.addCallback(lambda r: self.assert_(self.fb.updateCalled and self.fb.renderResultCalled))
84 d.addCallback(lambda r: self.assert_(self.fb.updateCalled and self.fb.renderResultCalled))
87 return d
85 return d
88
86
89 def test_error_callback_added_to_execute(self):
87 def test_error_callback_added_to_execute(self):
90 """Test that render_error called on execution error."""
88 """Test that render_error called on execution error."""
91
89
92 d = self.fb.execute("raise Exception()")
90 d = self.fb.execute("raise Exception()")
93 d.addErrback(lambda f: self.assert_(self.fb.renderErrorCalled))
91 d.addErrback(lambda f: self.assert_(self.fb.renderErrorCalled))
94 return d
92 return d
95
93
96 def test_history_returns_expected_block(self):
94 def test_history_returns_expected_block(self):
97 """Make sure history browsing doesn't fail."""
95 """Make sure history browsing doesn't fail."""
98
96
99 blocks = ["a=1","a=2","a=3"]
97 blocks = ["a=1","a=2","a=3"]
100 d = self.fb.execute(blocks[0])
98 d = self.fb.execute(blocks[0])
101 d.addCallback(lambda _: self.fb.execute(blocks[1]))
99 d.addCallback(lambda _: self.fb.execute(blocks[1]))
102 d.addCallback(lambda _: self.fb.execute(blocks[2]))
100 d.addCallback(lambda _: self.fb.execute(blocks[2]))
103 d.addCallback(lambda _: self.assert_(self.fb.get_history_previous("")==blocks[-2]))
101 d.addCallback(lambda _: self.assert_(self.fb.get_history_previous("")==blocks[-2]))
104 d.addCallback(lambda _: self.assert_(self.fb.get_history_previous("")==blocks[-3]))
102 d.addCallback(lambda _: self.assert_(self.fb.get_history_previous("")==blocks[-3]))
105 d.addCallback(lambda _: self.assert_(self.fb.get_history_next()==blocks[-2]))
103 d.addCallback(lambda _: self.assert_(self.fb.get_history_next()==blocks[-2]))
106 return d
104 return d
107
105
108 def test_history_returns_none_at_startup(self):
106 def test_history_returns_none_at_startup(self):
109 self.assert_(self.fb.get_history_previous("")==None)
107 self.assert_(self.fb.get_history_previous("")==None)
110 self.assert_(self.fb.get_history_next()==None)
108 self.assert_(self.fb.get_history_next()==None)
111
109
@@ -1,67 +1,67 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Test process execution and IO redirection.
3 Test process execution and IO redirection.
4 """
4 """
5
5
6 __docformat__ = "restructuredtext en"
6 __docformat__ = "restructuredtext en"
7
7
8 #-------------------------------------------------------------------------------
8 #-----------------------------------------------------------------------------
9 # Copyright (C) 2008 The IPython Development Team
9 # Copyright (C) 2008-2009 The IPython Development Team
10 #
10 #
11 # Distributed under the terms of the BSD License. The full license is
11 # Distributed under the terms of the BSD License. The full license is
12 # in the file COPYING, distributed as part of this software.
12 # in the file COPYING, distributed as part of this software.
13 #-------------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 from cStringIO import StringIO
15 from cStringIO import StringIO
16 from time import sleep
16 from time import sleep
17 import sys
17 import sys
18
18
19 from IPython.frontend.process import PipedProcess
19 from IPython.frontend.process import PipedProcess
20 from IPython.testing import decorators as testdec
20 from IPython.testing import decorators as testdec
21
21
22
22
23 def test_capture_out():
23 def test_capture_out():
24 """ A simple test to see if we can execute a process and get the output.
24 """ A simple test to see if we can execute a process and get the output.
25 """
25 """
26 s = StringIO()
26 s = StringIO()
27 p = PipedProcess('echo 1', out_callback=s.write, )
27 p = PipedProcess('echo 1', out_callback=s.write, )
28 p.start()
28 p.start()
29 p.join()
29 p.join()
30 result = s.getvalue().rstrip()
30 result = s.getvalue().rstrip()
31 assert result == '1'
31 assert result == '1'
32
32
33
33
34 def test_io():
34 def test_io():
35 """ Checks that we can send characters on stdin to the process.
35 """ Checks that we can send characters on stdin to the process.
36 """
36 """
37 s = StringIO()
37 s = StringIO()
38 p = PipedProcess(sys.executable + ' -c "a = raw_input(); print a"',
38 p = PipedProcess(sys.executable + ' -c "a = raw_input(); print a"',
39 out_callback=s.write, )
39 out_callback=s.write, )
40 p.start()
40 p.start()
41 test_string = '12345\n'
41 test_string = '12345\n'
42 while not hasattr(p, 'process'):
42 while not hasattr(p, 'process'):
43 sleep(0.1)
43 sleep(0.1)
44 p.process.stdin.write(test_string)
44 p.process.stdin.write(test_string)
45 p.join()
45 p.join()
46 result = s.getvalue()
46 result = s.getvalue()
47 assert result == test_string
47 assert result == test_string
48
48
49
49
50 def test_kill():
50 def test_kill():
51 """ Check that we can kill a process, and its subprocess.
51 """ Check that we can kill a process, and its subprocess.
52 """
52 """
53 s = StringIO()
53 s = StringIO()
54 p = PipedProcess(sys.executable + ' -c "a = raw_input();"',
54 p = PipedProcess(sys.executable + ' -c "a = raw_input();"',
55 out_callback=s.write, )
55 out_callback=s.write, )
56 p.start()
56 p.start()
57 while not hasattr(p, 'process'):
57 while not hasattr(p, 'process'):
58 sleep(0.1)
58 sleep(0.1)
59 p.process.kill()
59 p.process.kill()
60 assert p.process.poll() is not None
60 assert p.process.poll() is not None
61
61
62
62
63 if __name__ == '__main__':
63 if __name__ == '__main__':
64 test_capture_out()
64 test_capture_out()
65 test_io()
65 test_io()
66 test_kill()
66 test_kill()
67
67
@@ -1,61 +1,64 b''
1 # encoding: utf-8
1 # encoding: utf-8
2
2
3 """This file contains unittests for the interpreter.py module."""
3 """This file contains unittests for the interpreter.py module."""
4
4
5 __docformat__ = "restructuredtext en"
5 __docformat__ = "restructuredtext en"
6
6
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 # Copyright (C) 2008-2009 The IPython Development Team
8 # Copyright (C) 2008-2009 The IPython Development Team
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 import unittest
18 import unittest
19 from IPython.kernel.core.interpreter import Interpreter
19 from IPython.kernel.core.interpreter import Interpreter
20
20
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22 # Tests
22 # Tests
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24
24
25 # Tell nose to skip this module
26 __test__ = {}
27
25 class TestInterpreter(unittest.TestCase):
28 class TestInterpreter(unittest.TestCase):
26
29
27 def test_unicode(self):
30 def test_unicode(self):
28 """ Test unicode handling with the interpreter."""
31 """ Test unicode handling with the interpreter."""
29 i = Interpreter()
32 i = Interpreter()
30 i.execute_python(u'print "ù"')
33 i.execute_python(u'print "ù"')
31 i.execute_python('print "ù"')
34 i.execute_python('print "ù"')
32
35
33 def test_ticket266993(self):
36 def test_ticket266993(self):
34 """ Test for ticket 266993."""
37 """ Test for ticket 266993."""
35 i = Interpreter()
38 i = Interpreter()
36 i.execute('str("""a\nb""")')
39 i.execute('str("""a\nb""")')
37
40
38 def test_ticket364347(self):
41 def test_ticket364347(self):
39 """Test for ticket 364347."""
42 """Test for ticket 364347."""
40 i = Interpreter()
43 i = Interpreter()
41 i.split_commands('str("a\\nb")')
44 i.split_commands('str("a\\nb")')
42
45
43 def test_split_commands(self):
46 def test_split_commands(self):
44 """ Test that commands are indeed individually split."""
47 """ Test that commands are indeed individually split."""
45 i = Interpreter()
48 i = Interpreter()
46 test_atoms = [('(1\n + 1)', ),
49 test_atoms = [('(1\n + 1)', ),
47 ('1', '1', ),
50 ('1', '1', ),
48 ]
51 ]
49 for atoms in test_atoms:
52 for atoms in test_atoms:
50 atoms = [atom.rstrip() + '\n' for atom in atoms]
53 atoms = [atom.rstrip() + '\n' for atom in atoms]
51 self.assertEquals(i.split_commands(''.join(atoms)),atoms)
54 self.assertEquals(i.split_commands(''.join(atoms)),atoms)
52
55
53 def test_long_lines(self):
56 def test_long_lines(self):
54 """ Test for spurious syntax error created by the interpreter."""
57 """ Test for spurious syntax error created by the interpreter."""
55 test_strings = [u'( 1 +\n 1\n )\n\n',
58 test_strings = [u'( 1 +\n 1\n )\n\n',
56 u'(1 \n + 1\n )\n\n',
59 u'(1 \n + 1\n )\n\n',
57 ]
60 ]
58 i = Interpreter()
61 i = Interpreter()
59 for s in test_strings:
62 for s in test_strings:
60 i.execute(s)
63 i.execute(s)
61
64
@@ -1,171 +1,174 b''
1 # encoding: utf-8
1 # encoding: utf-8
2
2
3 """This file contains unittests for the notification.py module."""
3 """This file contains unittests for the notification.py module."""
4
4
5 __docformat__ = "restructuredtext en"
5 __docformat__ = "restructuredtext en"
6
6
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 # Copyright (C) 2008 The IPython Development Team
8 # Copyright (C) 2008 The IPython Development Team
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 # Tell nose to skip this module
19 __test__ = {}
20
18 import unittest
21 import unittest
19 import IPython.kernel.core.notification as notification
22 import IPython.kernel.core.notification as notification
20 from nose.tools import timed
23 from nose.tools import timed
21
24
22 #
25 #
23 # Supporting test classes
26 # Supporting test classes
24 #
27 #
25
28
26 class Observer(object):
29 class Observer(object):
27 """docstring for Observer"""
30 """docstring for Observer"""
28 def __init__(self, expectedType, expectedSender,
31 def __init__(self, expectedType, expectedSender,
29 center=notification.sharedCenter, **kwargs):
32 center=notification.sharedCenter, **kwargs):
30 super(Observer, self).__init__()
33 super(Observer, self).__init__()
31 self.expectedType = expectedType
34 self.expectedType = expectedType
32 self.expectedSender = expectedSender
35 self.expectedSender = expectedSender
33 self.expectedKwArgs = kwargs
36 self.expectedKwArgs = kwargs
34 self.recieved = False
37 self.recieved = False
35 center.add_observer(self.callback,
38 center.add_observer(self.callback,
36 self.expectedType,
39 self.expectedType,
37 self.expectedSender)
40 self.expectedSender)
38
41
39
42
40 def callback(self, theType, sender, args={}):
43 def callback(self, theType, sender, args={}):
41 """callback"""
44 """callback"""
42
45
43 assert(theType == self.expectedType or
46 assert(theType == self.expectedType or
44 self.expectedType == None)
47 self.expectedType == None)
45 assert(sender == self.expectedSender or
48 assert(sender == self.expectedSender or
46 self.expectedSender == None)
49 self.expectedSender == None)
47 assert(args == self.expectedKwArgs)
50 assert(args == self.expectedKwArgs)
48 self.recieved = True
51 self.recieved = True
49
52
50
53
51 def verify(self):
54 def verify(self):
52 """verify"""
55 """verify"""
53
56
54 assert(self.recieved)
57 assert(self.recieved)
55
58
56 def reset(self):
59 def reset(self):
57 """reset"""
60 """reset"""
58
61
59 self.recieved = False
62 self.recieved = False
60
63
61
64
62
65
63 class Notifier(object):
66 class Notifier(object):
64 """docstring for Notifier"""
67 """docstring for Notifier"""
65 def __init__(self, theType, **kwargs):
68 def __init__(self, theType, **kwargs):
66 super(Notifier, self).__init__()
69 super(Notifier, self).__init__()
67 self.theType = theType
70 self.theType = theType
68 self.kwargs = kwargs
71 self.kwargs = kwargs
69
72
70 def post(self, center=notification.sharedCenter):
73 def post(self, center=notification.sharedCenter):
71 """fire"""
74 """fire"""
72
75
73 center.post_notification(self.theType, self,
76 center.post_notification(self.theType, self,
74 **self.kwargs)
77 **self.kwargs)
75
78
76
79
77 #
80 #
78 # Test Cases
81 # Test Cases
79 #
82 #
80
83
81 class NotificationTests(unittest.TestCase):
84 class NotificationTests(unittest.TestCase):
82 """docstring for NotificationTests"""
85 """docstring for NotificationTests"""
83
86
84 def tearDown(self):
87 def tearDown(self):
85 notification.sharedCenter.remove_all_observers()
88 notification.sharedCenter.remove_all_observers()
86
89
87 def test_notification_delivered(self):
90 def test_notification_delivered(self):
88 """Test that notifications are delivered"""
91 """Test that notifications are delivered"""
89 expectedType = 'EXPECTED_TYPE'
92 expectedType = 'EXPECTED_TYPE'
90 sender = Notifier(expectedType)
93 sender = Notifier(expectedType)
91 observer = Observer(expectedType, sender)
94 observer = Observer(expectedType, sender)
92
95
93 sender.post()
96 sender.post()
94
97
95 observer.verify()
98 observer.verify()
96
99
97
100
98 def test_type_specificity(self):
101 def test_type_specificity(self):
99 """Test that observers are registered by type"""
102 """Test that observers are registered by type"""
100
103
101 expectedType = 1
104 expectedType = 1
102 unexpectedType = "UNEXPECTED_TYPE"
105 unexpectedType = "UNEXPECTED_TYPE"
103 sender = Notifier(expectedType)
106 sender = Notifier(expectedType)
104 unexpectedSender = Notifier(unexpectedType)
107 unexpectedSender = Notifier(unexpectedType)
105 observer = Observer(expectedType, sender)
108 observer = Observer(expectedType, sender)
106
109
107 sender.post()
110 sender.post()
108 unexpectedSender.post()
111 unexpectedSender.post()
109
112
110 observer.verify()
113 observer.verify()
111
114
112
115
113 def test_sender_specificity(self):
116 def test_sender_specificity(self):
114 """Test that observers are registered by sender"""
117 """Test that observers are registered by sender"""
115
118
116 expectedType = "EXPECTED_TYPE"
119 expectedType = "EXPECTED_TYPE"
117 sender1 = Notifier(expectedType)
120 sender1 = Notifier(expectedType)
118 sender2 = Notifier(expectedType)
121 sender2 = Notifier(expectedType)
119 observer = Observer(expectedType, sender1)
122 observer = Observer(expectedType, sender1)
120
123
121 sender1.post()
124 sender1.post()
122 sender2.post()
125 sender2.post()
123
126
124 observer.verify()
127 observer.verify()
125
128
126
129
127 def test_remove_all_observers(self):
130 def test_remove_all_observers(self):
128 """White-box test for remove_all_observers"""
131 """White-box test for remove_all_observers"""
129
132
130 for i in xrange(10):
133 for i in xrange(10):
131 Observer('TYPE', None, center=notification.sharedCenter)
134 Observer('TYPE', None, center=notification.sharedCenter)
132
135
133 self.assert_(len(notification.sharedCenter.observers[('TYPE',None)]) >= 10,
136 self.assert_(len(notification.sharedCenter.observers[('TYPE',None)]) >= 10,
134 "observers registered")
137 "observers registered")
135
138
136 notification.sharedCenter.remove_all_observers()
139 notification.sharedCenter.remove_all_observers()
137
140
138 self.assert_(len(notification.sharedCenter.observers) == 0, "observers removed")
141 self.assert_(len(notification.sharedCenter.observers) == 0, "observers removed")
139
142
140
143
141 def test_any_sender(self):
144 def test_any_sender(self):
142 """test_any_sender"""
145 """test_any_sender"""
143
146
144 expectedType = "EXPECTED_TYPE"
147 expectedType = "EXPECTED_TYPE"
145 sender1 = Notifier(expectedType)
148 sender1 = Notifier(expectedType)
146 sender2 = Notifier(expectedType)
149 sender2 = Notifier(expectedType)
147 observer = Observer(expectedType, None)
150 observer = Observer(expectedType, None)
148
151
149
152
150 sender1.post()
153 sender1.post()
151 observer.verify()
154 observer.verify()
152
155
153 observer.reset()
156 observer.reset()
154 sender2.post()
157 sender2.post()
155 observer.verify()
158 observer.verify()
156
159
157
160
158 @timed(.01)
161 @timed(.01)
159 def test_post_performance(self):
162 def test_post_performance(self):
160 """Test that post_notification, even with many registered irrelevant
163 """Test that post_notification, even with many registered irrelevant
161 observers is fast"""
164 observers is fast"""
162
165
163 for i in xrange(10):
166 for i in xrange(10):
164 Observer("UNRELATED_TYPE", None)
167 Observer("UNRELATED_TYPE", None)
165
168
166 o = Observer('EXPECTED_TYPE', None)
169 o = Observer('EXPECTED_TYPE', None)
167
170
168 notification.sharedCenter.post_notification('EXPECTED_TYPE', self)
171 notification.sharedCenter.post_notification('EXPECTED_TYPE', self)
169
172
170 o.verify()
173 o.verify()
171
174
@@ -1,70 +1,70 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Test the output capture at the OS level, using file descriptors.
3 Test the output capture at the OS level, using file descriptors.
4 """
4 """
5
5
6 __docformat__ = "restructuredtext en"
6 __docformat__ = "restructuredtext en"
7
7
8 #-------------------------------------------------------------------------------
8 #-------------------------------------------------------------------------------
9 # Copyright (C) 2008 The IPython Development Team
9 # Copyright (C) 2008 The IPython Development Team
10 #
10 #
11 # Distributed under the terms of the BSD License. The full license is
11 # Distributed under the terms of the BSD License. The full license is
12 # in the file COPYING, distributed as part of this software.
12 # in the file COPYING, distributed as part of this software.
13 #-------------------------------------------------------------------------------
13 #-------------------------------------------------------------------------------
14
14
15 # Tell nose to skip this module
16 __test__ = {}
15
17
16 # Stdlib imports
17 import os
18 import os
18 from cStringIO import StringIO
19 from cStringIO import StringIO
19
20
20 # Our own imports
21 from IPython.testing import decorators as dec
21 from IPython.testing import decorators as dec
22
22
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24 # Test functions
24 # Test functions
25
25
26 @dec.skip_win32
26 @dec.skip_win32
27 def test_redirector():
27 def test_redirector():
28 """ Checks that the redirector can be used to do synchronous capture.
28 """ Checks that the redirector can be used to do synchronous capture.
29 """
29 """
30 from IPython.kernel.core.fd_redirector import FDRedirector
30 from IPython.kernel.core.fd_redirector import FDRedirector
31 r = FDRedirector()
31 r = FDRedirector()
32 out = StringIO()
32 out = StringIO()
33 try:
33 try:
34 r.start()
34 r.start()
35 for i in range(10):
35 for i in range(10):
36 os.system('echo %ic' % i)
36 os.system('echo %ic' % i)
37 print >>out, r.getvalue(),
37 print >>out, r.getvalue(),
38 print >>out, i
38 print >>out, i
39 except:
39 except:
40 r.stop()
40 r.stop()
41 raise
41 raise
42 r.stop()
42 r.stop()
43 result1 = out.getvalue()
43 result1 = out.getvalue()
44 result2 = "".join("%ic\n%i\n" %(i, i) for i in range(10))
44 result2 = "".join("%ic\n%i\n" %(i, i) for i in range(10))
45 assert result1 == result2
45 assert result1 == result2
46
46
47
47
48 @dec.skip_win32
48 @dec.skip_win32
49 def test_redirector_output_trap():
49 def test_redirector_output_trap():
50 """ This test check not only that the redirector_output_trap does
50 """ This test check not only that the redirector_output_trap does
51 trap the output, but also that it does it in a gready way, that
51 trap the output, but also that it does it in a gready way, that
52 is by calling the callback ASAP.
52 is by calling the callback ASAP.
53 """
53 """
54 from IPython.kernel.core.redirector_output_trap import RedirectorOutputTrap
54 from IPython.kernel.core.redirector_output_trap import RedirectorOutputTrap
55 out = StringIO()
55 out = StringIO()
56 trap = RedirectorOutputTrap(out.write, out.write)
56 trap = RedirectorOutputTrap(out.write, out.write)
57 try:
57 try:
58 trap.set()
58 trap.set()
59 for i in range(10):
59 for i in range(10):
60 os.system('echo %ic' % i)
60 os.system('echo %ic' % i)
61 print "%ip" % i
61 print "%ip" % i
62 print >>out, i
62 print >>out, i
63 except:
63 except:
64 trap.unset()
64 trap.unset()
65 raise
65 raise
66 trap.unset()
66 trap.unset()
67 result1 = out.getvalue()
67 result1 = out.getvalue()
68 result2 = "".join("%ic\n%ip\n%i\n" %(i, i, i) for i in range(10))
68 result2 = "".join("%ic\n%ip\n%i\n" %(i, i, i) for i in range(10))
69 assert result1 == result2
69 assert result1 == result2
70
70
@@ -1,43 +1,46 b''
1 # Tell nose to skip this module
2 __test__ = {}
3
1 #from __future__ import with_statement
4 #from __future__ import with_statement
2
5
3 # XXX This file is currently disabled to preserve 2.4 compatibility.
6 # XXX This file is currently disabled to preserve 2.4 compatibility.
4
7
5 #def test_simple():
8 #def test_simple():
6 if 0:
9 if 0:
7
10
8 # XXX - for now, we need a running cluster to be started separately. The
11 # XXX - for now, we need a running cluster to be started separately. The
9 # daemon work is almost finished, and will make much of this unnecessary.
12 # daemon work is almost finished, and will make much of this unnecessary.
10 from IPython.kernel import client
13 from IPython.kernel import client
11 mec = client.MultiEngineClient(('127.0.0.1',10105))
14 mec = client.MultiEngineClient(('127.0.0.1',10105))
12
15
13 try:
16 try:
14 mec.get_ids()
17 mec.get_ids()
15 except ConnectionRefusedError:
18 except ConnectionRefusedError:
16 import os, time
19 import os, time
17 os.system('ipcluster -n 2 &')
20 os.system('ipcluster -n 2 &')
18 time.sleep(2)
21 time.sleep(2)
19 mec = client.MultiEngineClient(('127.0.0.1',10105))
22 mec = client.MultiEngineClient(('127.0.0.1',10105))
20
23
21 mec.block = False
24 mec.block = False
22
25
23 import itertools
26 import itertools
24 c = itertools.count()
27 c = itertools.count()
25
28
26 parallel = RemoteMultiEngine(mec)
29 parallel = RemoteMultiEngine(mec)
27
30
28 mec.pushAll()
31 mec.pushAll()
29
32
30 ## with parallel as pr:
33 ## with parallel as pr:
31 ## # A comment
34 ## # A comment
32 ## remote() # this means the code below only runs remotely
35 ## remote() # this means the code below only runs remotely
33 ## print 'Hello remote world'
36 ## print 'Hello remote world'
34 ## x = range(10)
37 ## x = range(10)
35 ## # Comments are OK
38 ## # Comments are OK
36 ## # Even misindented.
39 ## # Even misindented.
37 ## y = x+1
40 ## y = x+1
38
41
39
42
40 ## with pfor('i',sequence) as pr:
43 ## with pfor('i',sequence) as pr:
41 ## print x[i]
44 ## print x[i]
42
45
43 print pr.x + pr.y
46 print pr.x + pr.y
@@ -1,44 +1,44 b''
1 # encoding: utf-8
1 # encoding: utf-8
2
2
3 """This file contains unittests for the kernel.engineservice.py module.
3 """This file contains unittests for the kernel.engineservice.py module.
4
4
5 Things that should be tested:
5 Things that should be tested:
6
6
7 - Should the EngineService return Deferred objects?
7 - Should the EngineService return Deferred objects?
8 - Run the same tests that are run in shell.py.
8 - Run the same tests that are run in shell.py.
9 - Make sure that the Interface is really implemented.
9 - Make sure that the Interface is really implemented.
10 - The startService and stopService methods.
10 - The startService and stopService methods.
11 """
11 """
12
12
13 __docformat__ = "restructuredtext en"
13 __docformat__ = "restructuredtext en"
14
14
15 #-------------------------------------------------------------------------------
15 #-------------------------------------------------------------------------------
16 # Copyright (C) 2008 The IPython Development Team
16 # Copyright (C) 2008 The IPython Development Team
17 #
17 #
18 # Distributed under the terms of the BSD License. The full license is in
18 # Distributed under the terms of the BSD License. The full license is in
19 # the file COPYING, distributed as part of this software.
19 # the file COPYING, distributed as part of this software.
20 #-------------------------------------------------------------------------------
20 #-------------------------------------------------------------------------------
21
21
22 #-------------------------------------------------------------------------------
22 #-------------------------------------------------------------------------------
23 # Imports
23 # Imports
24 #-------------------------------------------------------------------------------
24 #-------------------------------------------------------------------------------
25
25
26 try:
26 # Tell nose to skip this module
27 __test__ = {}
28
27 from twisted.application.service import IService
29 from twisted.application.service import IService
28 from IPython.kernel.controllerservice import ControllerService
30 from IPython.kernel.controllerservice import ControllerService
29 from IPython.kernel.tests import multienginetest as met
31 from IPython.kernel.tests import multienginetest as met
30 from controllertest import IControllerCoreTestCase
32 from controllertest import IControllerCoreTestCase
31 from IPython.testing.util import DeferredTestCase
33 from IPython.testing.util import DeferredTestCase
32 except ImportError:
34
33 import nose
34 raise nose.SkipTest("This test requires zope.interface, Twisted and Foolscap")
35
35
36 class BasicControllerServiceTest(DeferredTestCase,
36 class BasicControllerServiceTest(DeferredTestCase,
37 IControllerCoreTestCase):
37 IControllerCoreTestCase):
38
38
39 def setUp(self):
39 def setUp(self):
40 self.controller = ControllerService()
40 self.controller = ControllerService()
41 self.controller.startService()
41 self.controller.startService()
42
42
43 def tearDown(self):
43 def tearDown(self):
44 self.controller.stopService()
44 self.controller.stopService()
@@ -1,93 +1,92 b''
1 # encoding: utf-8
1 # encoding: utf-8
2
2
3 """This file contains unittests for the enginepb.py module."""
3 """This file contains unittests for the enginepb.py module."""
4
4
5 __docformat__ = "restructuredtext en"
5 __docformat__ = "restructuredtext en"
6
6
7 #-------------------------------------------------------------------------------
7 #-------------------------------------------------------------------------------
8 # Copyright (C) 2008 The IPython Development Team
8 # Copyright (C) 2008 The IPython Development Team
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-------------------------------------------------------------------------------
12 #-------------------------------------------------------------------------------
13
13
14 #-------------------------------------------------------------------------------
14 #-------------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-------------------------------------------------------------------------------
16 #-------------------------------------------------------------------------------
17
17
18 try:
18 # Tell nose to skip this module
19 __test__ = {}
20
19 from twisted.python import components
21 from twisted.python import components
20 from twisted.internet import reactor, defer
22 from twisted.internet import reactor, defer
21 from twisted.spread import pb
23 from twisted.spread import pb
22 from twisted.internet.base import DelayedCall
24 from twisted.internet.base import DelayedCall
23 DelayedCall.debug = True
25 DelayedCall.debug = True
24
26
25 import zope.interface as zi
27 import zope.interface as zi
26
28
27 from IPython.kernel.fcutil import Tub, UnauthenticatedTub
29 from IPython.kernel.fcutil import Tub, UnauthenticatedTub
28 from IPython.kernel import engineservice as es
30 from IPython.kernel import engineservice as es
29 from IPython.testing.util import DeferredTestCase
31 from IPython.testing.util import DeferredTestCase
30 from IPython.kernel.controllerservice import IControllerBase
32 from IPython.kernel.controllerservice import IControllerBase
31 from IPython.kernel.enginefc import FCRemoteEngineRefFromService, IEngineBase
33 from IPython.kernel.enginefc import FCRemoteEngineRefFromService, IEngineBase
32 from IPython.kernel.engineservice import IEngineQueued
34 from IPython.kernel.engineservice import IEngineQueued
33 from IPython.kernel.engineconnector import EngineConnector
35 from IPython.kernel.engineconnector import EngineConnector
34
36
35 from IPython.kernel.tests.engineservicetest import \
37 from IPython.kernel.tests.engineservicetest import \
36 IEngineCoreTestCase, \
38 IEngineCoreTestCase, \
37 IEngineSerializedTestCase, \
39 IEngineSerializedTestCase, \
38 IEngineQueuedTestCase
40 IEngineQueuedTestCase
39 except ImportError:
40 import nose
41 raise nose.SkipTest("This test requires zope.interface, Twisted and Foolscap")
42
41
43
42
44 class EngineFCTest(DeferredTestCase,
43 class EngineFCTest(DeferredTestCase,
45 IEngineCoreTestCase,
44 IEngineCoreTestCase,
46 IEngineSerializedTestCase,
45 IEngineSerializedTestCase,
47 IEngineQueuedTestCase
46 IEngineQueuedTestCase
48 ):
47 ):
49
48
50 zi.implements(IControllerBase)
49 zi.implements(IControllerBase)
51
50
52 def setUp(self):
51 def setUp(self):
53
52
54 # Start a server and append to self.servers
53 # Start a server and append to self.servers
55 self.controller_reference = FCRemoteEngineRefFromService(self)
54 self.controller_reference = FCRemoteEngineRefFromService(self)
56 self.controller_tub = Tub()
55 self.controller_tub = Tub()
57 self.controller_tub.listenOn('tcp:10105:interface=127.0.0.1')
56 self.controller_tub.listenOn('tcp:10105:interface=127.0.0.1')
58 self.controller_tub.setLocation('127.0.0.1:10105')
57 self.controller_tub.setLocation('127.0.0.1:10105')
59
58
60 furl = self.controller_tub.registerReference(self.controller_reference)
59 furl = self.controller_tub.registerReference(self.controller_reference)
61 self.controller_tub.startService()
60 self.controller_tub.startService()
62
61
63 # Start an EngineService and append to services/client
62 # Start an EngineService and append to services/client
64 self.engine_service = es.EngineService()
63 self.engine_service = es.EngineService()
65 self.engine_service.startService()
64 self.engine_service.startService()
66 self.engine_tub = Tub()
65 self.engine_tub = Tub()
67 self.engine_tub.startService()
66 self.engine_tub.startService()
68 engine_connector = EngineConnector(self.engine_tub)
67 engine_connector = EngineConnector(self.engine_tub)
69 d = engine_connector.connect_to_controller(self.engine_service, furl)
68 d = engine_connector.connect_to_controller(self.engine_service, furl)
70 # This deferred doesn't fire until after register_engine has returned and
69 # This deferred doesn't fire until after register_engine has returned and
71 # thus, self.engine has been defined and the tets can proceed.
70 # thus, self.engine has been defined and the tets can proceed.
72 return d
71 return d
73
72
74 def tearDown(self):
73 def tearDown(self):
75 dlist = []
74 dlist = []
76 # Shut down the engine
75 # Shut down the engine
77 d = self.engine_tub.stopService()
76 d = self.engine_tub.stopService()
78 dlist.append(d)
77 dlist.append(d)
79 # Shut down the controller
78 # Shut down the controller
80 d = self.controller_tub.stopService()
79 d = self.controller_tub.stopService()
81 dlist.append(d)
80 dlist.append(d)
82 return defer.DeferredList(dlist)
81 return defer.DeferredList(dlist)
83
82
84 #---------------------------------------------------------------------------
83 #---------------------------------------------------------------------------
85 # Make me look like a basic controller
84 # Make me look like a basic controller
86 #---------------------------------------------------------------------------
85 #---------------------------------------------------------------------------
87
86
88 def register_engine(self, engine_ref, id=None, ip=None, port=None, pid=None):
87 def register_engine(self, engine_ref, id=None, ip=None, port=None, pid=None):
89 self.engine = IEngineQueued(IEngineBase(engine_ref))
88 self.engine = IEngineQueued(IEngineBase(engine_ref))
90 return {'id':id}
89 return {'id':id}
91
90
92 def unregister_engine(self, id):
91 def unregister_engine(self, id):
93 pass No newline at end of file
92 pass
@@ -1,80 +1,79 b''
1 # encoding: utf-8
1 # encoding: utf-8
2
2
3 """This file contains unittests for the kernel.engineservice.py module.
3 """This file contains unittests for the kernel.engineservice.py module.
4
4
5 Things that should be tested:
5 Things that should be tested:
6
6
7 - Should the EngineService return Deferred objects?
7 - Should the EngineService return Deferred objects?
8 - Run the same tests that are run in shell.py.
8 - Run the same tests that are run in shell.py.
9 - Make sure that the Interface is really implemented.
9 - Make sure that the Interface is really implemented.
10 - The startService and stopService methods.
10 - The startService and stopService methods.
11 """
11 """
12
12
13 __docformat__ = "restructuredtext en"
13 __docformat__ = "restructuredtext en"
14
14
15 #-------------------------------------------------------------------------------
15 #-------------------------------------------------------------------------------
16 # Copyright (C) 2008 The IPython Development Team
16 # Copyright (C) 2008 The IPython Development Team
17 #
17 #
18 # Distributed under the terms of the BSD License. The full license is in
18 # Distributed under the terms of the BSD License. The full license is in
19 # the file COPYING, distributed as part of this software.
19 # the file COPYING, distributed as part of this software.
20 #-------------------------------------------------------------------------------
20 #-------------------------------------------------------------------------------
21
21
22 #-------------------------------------------------------------------------------
22 #-------------------------------------------------------------------------------
23 # Imports
23 # Imports
24 #-------------------------------------------------------------------------------
24 #-------------------------------------------------------------------------------
25
25
26 try:
26 # Tell nose to skip this module
27 __test__ = {}
28
27 from twisted.internet import defer
29 from twisted.internet import defer
28 from twisted.application.service import IService
30 from twisted.application.service import IService
29
31
30 from IPython.kernel import engineservice as es
32 from IPython.kernel import engineservice as es
31 from IPython.testing.util import DeferredTestCase
33 from IPython.testing.util import DeferredTestCase
32 from IPython.kernel.tests.engineservicetest import \
34 from IPython.kernel.tests.engineservicetest import \
33 IEngineCoreTestCase, \
35 IEngineCoreTestCase, \
34 IEngineSerializedTestCase, \
36 IEngineSerializedTestCase, \
35 IEngineQueuedTestCase, \
37 IEngineQueuedTestCase, \
36 IEnginePropertiesTestCase
38 IEnginePropertiesTestCase
37 except ImportError:
38 import nose
39 raise nose.SkipTest("This test requires zope.interface, Twisted and Foolscap")
40
39
41
40
42 class BasicEngineServiceTest(DeferredTestCase,
41 class BasicEngineServiceTest(DeferredTestCase,
43 IEngineCoreTestCase,
42 IEngineCoreTestCase,
44 IEngineSerializedTestCase,
43 IEngineSerializedTestCase,
45 IEnginePropertiesTestCase):
44 IEnginePropertiesTestCase):
46
45
47 def setUp(self):
46 def setUp(self):
48 self.engine = es.EngineService()
47 self.engine = es.EngineService()
49 self.engine.startService()
48 self.engine.startService()
50
49
51 def tearDown(self):
50 def tearDown(self):
52 return self.engine.stopService()
51 return self.engine.stopService()
53
52
54 class ThreadedEngineServiceTest(DeferredTestCase,
53 class ThreadedEngineServiceTest(DeferredTestCase,
55 IEngineCoreTestCase,
54 IEngineCoreTestCase,
56 IEngineSerializedTestCase,
55 IEngineSerializedTestCase,
57 IEnginePropertiesTestCase):
56 IEnginePropertiesTestCase):
58
57
59 def setUp(self):
58 def setUp(self):
60 self.engine = es.ThreadedEngineService()
59 self.engine = es.ThreadedEngineService()
61 self.engine.startService()
60 self.engine.startService()
62
61
63 def tearDown(self):
62 def tearDown(self):
64 return self.engine.stopService()
63 return self.engine.stopService()
65
64
66 class QueuedEngineServiceTest(DeferredTestCase,
65 class QueuedEngineServiceTest(DeferredTestCase,
67 IEngineCoreTestCase,
66 IEngineCoreTestCase,
68 IEngineSerializedTestCase,
67 IEngineSerializedTestCase,
69 IEnginePropertiesTestCase,
68 IEnginePropertiesTestCase,
70 IEngineQueuedTestCase):
69 IEngineQueuedTestCase):
71
70
72 def setUp(self):
71 def setUp(self):
73 self.rawEngine = es.EngineService()
72 self.rawEngine = es.EngineService()
74 self.rawEngine.startService()
73 self.rawEngine.startService()
75 self.engine = es.IEngineQueued(self.rawEngine)
74 self.engine = es.IEngineQueued(self.rawEngine)
76
75
77 def tearDown(self):
76 def tearDown(self):
78 return self.rawEngine.stopService()
77 return self.rawEngine.stopService()
79
78
80
79
@@ -1,56 +1,55 b''
1 # encoding: utf-8
1 # encoding: utf-8
2
2
3 """"""
3 """"""
4
4
5 __docformat__ = "restructuredtext en"
5 __docformat__ = "restructuredtext en"
6
6
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 # Copyright (C) 2008 The IPython Development Team
8 # Copyright (C) 2008 The IPython Development Team
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 try:
18 # Tell nose to skip this module
19 __test__ = {}
20
19 from twisted.internet import defer
21 from twisted.internet import defer
20 from IPython.testing.util import DeferredTestCase
22 from IPython.testing.util import DeferredTestCase
21 from IPython.kernel.controllerservice import ControllerService
23 from IPython.kernel.controllerservice import ControllerService
22 from IPython.kernel import multiengine as me
24 from IPython.kernel import multiengine as me
23 from IPython.kernel.tests.multienginetest import (IMultiEngineTestCase,
25 from IPython.kernel.tests.multienginetest import (IMultiEngineTestCase,
24 ISynchronousMultiEngineTestCase)
26 ISynchronousMultiEngineTestCase)
25 except ImportError:
26 import nose
27 raise nose.SkipTest("This test requires zope.interface, Twisted and Foolscap")
28
27
29
28
30 class BasicMultiEngineTestCase(DeferredTestCase, IMultiEngineTestCase):
29 class BasicMultiEngineTestCase(DeferredTestCase, IMultiEngineTestCase):
31
30
32 def setUp(self):
31 def setUp(self):
33 self.controller = ControllerService()
32 self.controller = ControllerService()
34 self.controller.startService()
33 self.controller.startService()
35 self.multiengine = me.IMultiEngine(self.controller)
34 self.multiengine = me.IMultiEngine(self.controller)
36 self.engines = []
35 self.engines = []
37
36
38 def tearDown(self):
37 def tearDown(self):
39 self.controller.stopService()
38 self.controller.stopService()
40 for e in self.engines:
39 for e in self.engines:
41 e.stopService()
40 e.stopService()
42
41
43
42
44 class SynchronousMultiEngineTestCase(DeferredTestCase, ISynchronousMultiEngineTestCase):
43 class SynchronousMultiEngineTestCase(DeferredTestCase, ISynchronousMultiEngineTestCase):
45
44
46 def setUp(self):
45 def setUp(self):
47 self.controller = ControllerService()
46 self.controller = ControllerService()
48 self.controller.startService()
47 self.controller.startService()
49 self.multiengine = me.ISynchronousMultiEngine(me.IMultiEngine(self.controller))
48 self.multiengine = me.ISynchronousMultiEngine(me.IMultiEngine(self.controller))
50 self.engines = []
49 self.engines = []
51
50
52 def tearDown(self):
51 def tearDown(self):
53 self.controller.stopService()
52 self.controller.stopService()
54 for e in self.engines:
53 for e in self.engines:
55 e.stopService()
54 e.stopService()
56
55
@@ -1,144 +1,144 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3
3
4 __docformat__ = "restructuredtext en"
4 __docformat__ = "restructuredtext en"
5
5
6 #-------------------------------------------------------------------------------
6 #-------------------------------------------------------------------------------
7 # Copyright (C) 2008 The IPython Development Team
7 # Copyright (C) 2008 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-------------------------------------------------------------------------------
11 #-------------------------------------------------------------------------------
12
12
13 #-------------------------------------------------------------------------------
13 #-------------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-------------------------------------------------------------------------------
15 #-------------------------------------------------------------------------------
16
16
17 try:
17 # Tell nose to skip this module
18 __test__ = {}
19
18 from twisted.internet import defer, reactor
20 from twisted.internet import defer, reactor
19
21
20 from IPython.kernel.fcutil import Tub, UnauthenticatedTub
22 from IPython.kernel.fcutil import Tub, UnauthenticatedTub
21
23
22 from IPython.testing.util import DeferredTestCase
24 from IPython.testing.util import DeferredTestCase
23 from IPython.kernel.controllerservice import ControllerService
25 from IPython.kernel.controllerservice import ControllerService
24 from IPython.kernel.multiengine import IMultiEngine
26 from IPython.kernel.multiengine import IMultiEngine
25 from IPython.kernel.tests.multienginetest import IFullSynchronousMultiEngineTestCase
27 from IPython.kernel.tests.multienginetest import IFullSynchronousMultiEngineTestCase
26 from IPython.kernel.multienginefc import IFCSynchronousMultiEngine
28 from IPython.kernel.multienginefc import IFCSynchronousMultiEngine
27 from IPython.kernel import multiengine as me
29 from IPython.kernel import multiengine as me
28 from IPython.kernel.clientconnector import ClientConnector
30 from IPython.kernel.clientconnector import ClientConnector
29 from IPython.kernel.parallelfunction import ParallelFunction
31 from IPython.kernel.parallelfunction import ParallelFunction
30 from IPython.kernel.error import CompositeError
32 from IPython.kernel.error import CompositeError
31 from IPython.kernel.util import printer
33 from IPython.kernel.util import printer
32 except ImportError:
34
33 import nose
34 raise nose.SkipTest("This test requires zope.interface, Twisted and Foolscap")
35
35
36 def _raise_it(f):
36 def _raise_it(f):
37 try:
37 try:
38 f.raiseException()
38 f.raiseException()
39 except CompositeError, e:
39 except CompositeError, e:
40 e.raise_exception()
40 e.raise_exception()
41
41
42
42
43 class FullSynchronousMultiEngineTestCase(DeferredTestCase, IFullSynchronousMultiEngineTestCase):
43 class FullSynchronousMultiEngineTestCase(DeferredTestCase, IFullSynchronousMultiEngineTestCase):
44
44
45 def setUp(self):
45 def setUp(self):
46
46
47 self.engines = []
47 self.engines = []
48
48
49 self.controller = ControllerService()
49 self.controller = ControllerService()
50 self.controller.startService()
50 self.controller.startService()
51 self.imultiengine = IMultiEngine(self.controller)
51 self.imultiengine = IMultiEngine(self.controller)
52 self.mec_referenceable = IFCSynchronousMultiEngine(self.imultiengine)
52 self.mec_referenceable = IFCSynchronousMultiEngine(self.imultiengine)
53
53
54 self.controller_tub = Tub()
54 self.controller_tub = Tub()
55 self.controller_tub.listenOn('tcp:10105:interface=127.0.0.1')
55 self.controller_tub.listenOn('tcp:10105:interface=127.0.0.1')
56 self.controller_tub.setLocation('127.0.0.1:10105')
56 self.controller_tub.setLocation('127.0.0.1:10105')
57
57
58 furl = self.controller_tub.registerReference(self.mec_referenceable)
58 furl = self.controller_tub.registerReference(self.mec_referenceable)
59 self.controller_tub.startService()
59 self.controller_tub.startService()
60
60
61 self.client_tub = ClientConnector()
61 self.client_tub = ClientConnector()
62 d = self.client_tub.get_multiengine_client(furl)
62 d = self.client_tub.get_multiengine_client(furl)
63 d.addCallback(self.handle_got_client)
63 d.addCallback(self.handle_got_client)
64 return d
64 return d
65
65
66 def handle_got_client(self, client):
66 def handle_got_client(self, client):
67 self.multiengine = client
67 self.multiengine = client
68
68
69 def tearDown(self):
69 def tearDown(self):
70 dlist = []
70 dlist = []
71 # Shut down the multiengine client
71 # Shut down the multiengine client
72 d = self.client_tub.tub.stopService()
72 d = self.client_tub.tub.stopService()
73 dlist.append(d)
73 dlist.append(d)
74 # Shut down the engines
74 # Shut down the engines
75 for e in self.engines:
75 for e in self.engines:
76 e.stopService()
76 e.stopService()
77 # Shut down the controller
77 # Shut down the controller
78 d = self.controller_tub.stopService()
78 d = self.controller_tub.stopService()
79 d.addBoth(lambda _: self.controller.stopService())
79 d.addBoth(lambda _: self.controller.stopService())
80 dlist.append(d)
80 dlist.append(d)
81 return defer.DeferredList(dlist)
81 return defer.DeferredList(dlist)
82
82
83 def test_mapper(self):
83 def test_mapper(self):
84 self.addEngine(4)
84 self.addEngine(4)
85 m = self.multiengine.mapper()
85 m = self.multiengine.mapper()
86 self.assertEquals(m.multiengine,self.multiengine)
86 self.assertEquals(m.multiengine,self.multiengine)
87 self.assertEquals(m.dist,'b')
87 self.assertEquals(m.dist,'b')
88 self.assertEquals(m.targets,'all')
88 self.assertEquals(m.targets,'all')
89 self.assertEquals(m.block,True)
89 self.assertEquals(m.block,True)
90
90
91 def test_map_default(self):
91 def test_map_default(self):
92 self.addEngine(4)
92 self.addEngine(4)
93 m = self.multiengine.mapper()
93 m = self.multiengine.mapper()
94 d = m.map(lambda x: 2*x, range(10))
94 d = m.map(lambda x: 2*x, range(10))
95 d.addCallback(lambda r: self.assertEquals(r,[2*x for x in range(10)]))
95 d.addCallback(lambda r: self.assertEquals(r,[2*x for x in range(10)]))
96 d.addCallback(lambda _: self.multiengine.map(lambda x: 2*x, range(10)))
96 d.addCallback(lambda _: self.multiengine.map(lambda x: 2*x, range(10)))
97 d.addCallback(lambda r: self.assertEquals(r,[2*x for x in range(10)]))
97 d.addCallback(lambda r: self.assertEquals(r,[2*x for x in range(10)]))
98 return d
98 return d
99
99
100 def test_map_noblock(self):
100 def test_map_noblock(self):
101 self.addEngine(4)
101 self.addEngine(4)
102 m = self.multiengine.mapper(block=False)
102 m = self.multiengine.mapper(block=False)
103 d = m.map(lambda x: 2*x, range(10))
103 d = m.map(lambda x: 2*x, range(10))
104 d.addCallback(lambda did: self.multiengine.get_pending_deferred(did, True))
104 d.addCallback(lambda did: self.multiengine.get_pending_deferred(did, True))
105 d.addCallback(lambda r: self.assertEquals(r,[2*x for x in range(10)]))
105 d.addCallback(lambda r: self.assertEquals(r,[2*x for x in range(10)]))
106 return d
106 return d
107
107
108 def test_mapper_fail(self):
108 def test_mapper_fail(self):
109 self.addEngine(4)
109 self.addEngine(4)
110 m = self.multiengine.mapper()
110 m = self.multiengine.mapper()
111 d = m.map(lambda x: 1/0, range(10))
111 d = m.map(lambda x: 1/0, range(10))
112 d.addBoth(lambda f: self.assertRaises(ZeroDivisionError, _raise_it, f))
112 d.addBoth(lambda f: self.assertRaises(ZeroDivisionError, _raise_it, f))
113 return d
113 return d
114
114
115 def test_parallel(self):
115 def test_parallel(self):
116 self.addEngine(4)
116 self.addEngine(4)
117 p = self.multiengine.parallel()
117 p = self.multiengine.parallel()
118 self.assert_(isinstance(p, ParallelFunction))
118 self.assert_(isinstance(p, ParallelFunction))
119 @p
119 @p
120 def f(x): return 2*x
120 def f(x): return 2*x
121 d = f(range(10))
121 d = f(range(10))
122 d.addCallback(lambda r: self.assertEquals(r,[2*x for x in range(10)]))
122 d.addCallback(lambda r: self.assertEquals(r,[2*x for x in range(10)]))
123 return d
123 return d
124
124
125 def test_parallel_noblock(self):
125 def test_parallel_noblock(self):
126 self.addEngine(1)
126 self.addEngine(1)
127 p = self.multiengine.parallel(block=False)
127 p = self.multiengine.parallel(block=False)
128 self.assert_(isinstance(p, ParallelFunction))
128 self.assert_(isinstance(p, ParallelFunction))
129 @p
129 @p
130 def f(x): return 2*x
130 def f(x): return 2*x
131 d = f(range(10))
131 d = f(range(10))
132 d.addCallback(lambda did: self.multiengine.get_pending_deferred(did, True))
132 d.addCallback(lambda did: self.multiengine.get_pending_deferred(did, True))
133 d.addCallback(lambda r: self.assertEquals(r,[2*x for x in range(10)]))
133 d.addCallback(lambda r: self.assertEquals(r,[2*x for x in range(10)]))
134 return d
134 return d
135
135
136 def test_parallel_fail(self):
136 def test_parallel_fail(self):
137 self.addEngine(4)
137 self.addEngine(4)
138 p = self.multiengine.parallel()
138 p = self.multiengine.parallel()
139 self.assert_(isinstance(p, ParallelFunction))
139 self.assert_(isinstance(p, ParallelFunction))
140 @p
140 @p
141 def f(x): return 1/0
141 def f(x): return 1/0
142 d = f(range(10))
142 d = f(range(10))
143 d.addBoth(lambda f: self.assertRaises(ZeroDivisionError, _raise_it, f))
143 d.addBoth(lambda f: self.assertRaises(ZeroDivisionError, _raise_it, f))
144 return d No newline at end of file
144 return d
@@ -1,102 +1,102 b''
1 # encoding: utf-8
1 # encoding: utf-8
2
2
3 """This file contains unittests for the shell.py module."""
3 """This file contains unittests for the shell.py module."""
4
4
5 __docformat__ = "restructuredtext en"
5 __docformat__ = "restructuredtext en"
6
6
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 # Copyright (C) 2008 The IPython Development Team
8 # Copyright (C) 2008 The IPython Development Team
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 try:
18 # Tell nose to skip this module
19 __test__ = {}
20
19 import zope.interface as zi
21 import zope.interface as zi
20 from twisted.trial import unittest
22 from twisted.trial import unittest
21 from IPython.testing.util import DeferredTestCase
23 from IPython.testing.util import DeferredTestCase
22
24
23 from IPython.kernel.newserialized import \
25 from IPython.kernel.newserialized import \
24 ISerialized, \
26 ISerialized, \
25 IUnSerialized, \
27 IUnSerialized, \
26 Serialized, \
28 Serialized, \
27 UnSerialized, \
29 UnSerialized, \
28 SerializeIt, \
30 SerializeIt, \
29 UnSerializeIt
31 UnSerializeIt
30 except ImportError:
32
31 import nose
32 raise nose.SkipTest("This test requires zope.interface, Twisted and Foolscap")
33
33
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35 # Tests
35 # Tests
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37
37
38 class SerializedTestCase(unittest.TestCase):
38 class SerializedTestCase(unittest.TestCase):
39
39
40 def setUp(self):
40 def setUp(self):
41 pass
41 pass
42
42
43 def tearDown(self):
43 def tearDown(self):
44 pass
44 pass
45
45
46 def testSerializedInterfaces(self):
46 def testSerializedInterfaces(self):
47
47
48 us = UnSerialized({'a':10, 'b':range(10)})
48 us = UnSerialized({'a':10, 'b':range(10)})
49 s = ISerialized(us)
49 s = ISerialized(us)
50 uss = IUnSerialized(s)
50 uss = IUnSerialized(s)
51 self.assert_(ISerialized.providedBy(s))
51 self.assert_(ISerialized.providedBy(s))
52 self.assert_(IUnSerialized.providedBy(us))
52 self.assert_(IUnSerialized.providedBy(us))
53 self.assert_(IUnSerialized.providedBy(uss))
53 self.assert_(IUnSerialized.providedBy(uss))
54 for m in list(ISerialized):
54 for m in list(ISerialized):
55 self.assert_(hasattr(s, m))
55 self.assert_(hasattr(s, m))
56 for m in list(IUnSerialized):
56 for m in list(IUnSerialized):
57 self.assert_(hasattr(us, m))
57 self.assert_(hasattr(us, m))
58 for m in list(IUnSerialized):
58 for m in list(IUnSerialized):
59 self.assert_(hasattr(uss, m))
59 self.assert_(hasattr(uss, m))
60
60
61 def testPickleSerialized(self):
61 def testPickleSerialized(self):
62 obj = {'a':1.45345, 'b':'asdfsdf', 'c':10000L}
62 obj = {'a':1.45345, 'b':'asdfsdf', 'c':10000L}
63 original = UnSerialized(obj)
63 original = UnSerialized(obj)
64 originalSer = ISerialized(original)
64 originalSer = ISerialized(original)
65 firstData = originalSer.getData()
65 firstData = originalSer.getData()
66 firstTD = originalSer.getTypeDescriptor()
66 firstTD = originalSer.getTypeDescriptor()
67 firstMD = originalSer.getMetadata()
67 firstMD = originalSer.getMetadata()
68 self.assert_(firstTD == 'pickle')
68 self.assert_(firstTD == 'pickle')
69 self.assert_(firstMD == {})
69 self.assert_(firstMD == {})
70 unSerialized = IUnSerialized(originalSer)
70 unSerialized = IUnSerialized(originalSer)
71 secondObj = unSerialized.getObject()
71 secondObj = unSerialized.getObject()
72 for k, v in secondObj.iteritems():
72 for k, v in secondObj.iteritems():
73 self.assert_(obj[k] == v)
73 self.assert_(obj[k] == v)
74 secondSer = ISerialized(UnSerialized(secondObj))
74 secondSer = ISerialized(UnSerialized(secondObj))
75 self.assert_(firstData == secondSer.getData())
75 self.assert_(firstData == secondSer.getData())
76 self.assert_(firstTD == secondSer.getTypeDescriptor() )
76 self.assert_(firstTD == secondSer.getTypeDescriptor() )
77 self.assert_(firstMD == secondSer.getMetadata())
77 self.assert_(firstMD == secondSer.getMetadata())
78
78
79 def testNDArraySerialized(self):
79 def testNDArraySerialized(self):
80 try:
80 try:
81 import numpy
81 import numpy
82 except ImportError:
82 except ImportError:
83 pass
83 pass
84 else:
84 else:
85 a = numpy.linspace(0.0, 1.0, 1000)
85 a = numpy.linspace(0.0, 1.0, 1000)
86 unSer1 = UnSerialized(a)
86 unSer1 = UnSerialized(a)
87 ser1 = ISerialized(unSer1)
87 ser1 = ISerialized(unSer1)
88 td = ser1.getTypeDescriptor()
88 td = ser1.getTypeDescriptor()
89 self.assert_(td == 'ndarray')
89 self.assert_(td == 'ndarray')
90 md = ser1.getMetadata()
90 md = ser1.getMetadata()
91 self.assert_(md['shape'] == a.shape)
91 self.assert_(md['shape'] == a.shape)
92 self.assert_(md['dtype'] == a.dtype.str)
92 self.assert_(md['dtype'] == a.dtype.str)
93 buff = ser1.getData()
93 buff = ser1.getData()
94 self.assert_(buff == numpy.getbuffer(a))
94 self.assert_(buff == numpy.getbuffer(a))
95 s = Serialized(buff, td, md)
95 s = Serialized(buff, td, md)
96 us = IUnSerialized(s)
96 us = IUnSerialized(s)
97 final = us.getObject()
97 final = us.getObject()
98 self.assert_(numpy.getbuffer(a) == numpy.getbuffer(final))
98 self.assert_(numpy.getbuffer(a) == numpy.getbuffer(final))
99 self.assert_(a.dtype.str == final.dtype.str)
99 self.assert_(a.dtype.str == final.dtype.str)
100 self.assert_(a.shape == final.shape)
100 self.assert_(a.shape == final.shape)
101
101
102
102
@@ -1,186 +1,186 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3
3
4 """Tests for pendingdeferred.py"""
4 """Tests for pendingdeferred.py"""
5
5
6 __docformat__ = "restructuredtext en"
6 __docformat__ = "restructuredtext en"
7
7
8 #-------------------------------------------------------------------------------
8 #-------------------------------------------------------------------------------
9 # Copyright (C) 2008 The IPython Development Team
9 # Copyright (C) 2008 The IPython Development Team
10 #
10 #
11 # Distributed under the terms of the BSD License. The full license is in
11 # Distributed under the terms of the BSD License. The full license is in
12 # the file COPYING, distributed as part of this software.
12 # the file COPYING, distributed as part of this software.
13 #-------------------------------------------------------------------------------
13 #-------------------------------------------------------------------------------
14
14
15 #-------------------------------------------------------------------------------
15 #-------------------------------------------------------------------------------
16 # Imports
16 # Imports
17 #-------------------------------------------------------------------------------
17 #-------------------------------------------------------------------------------
18
18
19 try:
19 # Tell nose to skip this module
20 __test__ = {}
21
20 from twisted.internet import defer
22 from twisted.internet import defer
21 from twisted.python import failure
23 from twisted.python import failure
22
24
23 from IPython.testing.util import DeferredTestCase
25 from IPython.testing.util import DeferredTestCase
24 import IPython.kernel.pendingdeferred as pd
26 import IPython.kernel.pendingdeferred as pd
25 from IPython.kernel import error
27 from IPython.kernel import error
26 from IPython.kernel.util import printer
28 from IPython.kernel.util import printer
27 except ImportError:
29
28 import nose
29 raise nose.SkipTest("This test requires zope.interface, Twisted and Foolscap")
30
30
31 class Foo(object):
31 class Foo(object):
32
32
33 def bar(self, bahz):
33 def bar(self, bahz):
34 return defer.succeed('blahblah: %s' % bahz)
34 return defer.succeed('blahblah: %s' % bahz)
35
35
36 class TwoPhaseFoo(pd.PendingDeferredManager):
36 class TwoPhaseFoo(pd.PendingDeferredManager):
37
37
38 def __init__(self, foo):
38 def __init__(self, foo):
39 self.foo = foo
39 self.foo = foo
40 pd.PendingDeferredManager.__init__(self)
40 pd.PendingDeferredManager.__init__(self)
41
41
42 @pd.two_phase
42 @pd.two_phase
43 def bar(self, bahz):
43 def bar(self, bahz):
44 return self.foo.bar(bahz)
44 return self.foo.bar(bahz)
45
45
46 class PendingDeferredManagerTest(DeferredTestCase):
46 class PendingDeferredManagerTest(DeferredTestCase):
47
47
48 def setUp(self):
48 def setUp(self):
49 self.pdm = pd.PendingDeferredManager()
49 self.pdm = pd.PendingDeferredManager()
50
50
51 def tearDown(self):
51 def tearDown(self):
52 pass
52 pass
53
53
54 def testBasic(self):
54 def testBasic(self):
55 dDict = {}
55 dDict = {}
56 # Create 10 deferreds and save them
56 # Create 10 deferreds and save them
57 for i in range(10):
57 for i in range(10):
58 d = defer.Deferred()
58 d = defer.Deferred()
59 did = self.pdm.save_pending_deferred(d)
59 did = self.pdm.save_pending_deferred(d)
60 dDict[did] = d
60 dDict[did] = d
61 # Make sure they are begin saved
61 # Make sure they are begin saved
62 for k in dDict.keys():
62 for k in dDict.keys():
63 self.assert_(self.pdm.quick_has_id(k))
63 self.assert_(self.pdm.quick_has_id(k))
64 # Get the pending deferred (block=True), then callback with 'foo' and compare
64 # Get the pending deferred (block=True), then callback with 'foo' and compare
65 for did in dDict.keys()[0:5]:
65 for did in dDict.keys()[0:5]:
66 d = self.pdm.get_pending_deferred(did,block=True)
66 d = self.pdm.get_pending_deferred(did,block=True)
67 dDict[did].callback('foo')
67 dDict[did].callback('foo')
68 d.addCallback(lambda r: self.assert_(r=='foo'))
68 d.addCallback(lambda r: self.assert_(r=='foo'))
69 # Get the pending deferreds with (block=False) and make sure ResultNotCompleted is raised
69 # Get the pending deferreds with (block=False) and make sure ResultNotCompleted is raised
70 for did in dDict.keys()[5:10]:
70 for did in dDict.keys()[5:10]:
71 d = self.pdm.get_pending_deferred(did,block=False)
71 d = self.pdm.get_pending_deferred(did,block=False)
72 d.addErrback(lambda f: self.assertRaises(error.ResultNotCompleted, f.raiseException))
72 d.addErrback(lambda f: self.assertRaises(error.ResultNotCompleted, f.raiseException))
73 # Now callback the last 5, get them and compare.
73 # Now callback the last 5, get them and compare.
74 for did in dDict.keys()[5:10]:
74 for did in dDict.keys()[5:10]:
75 dDict[did].callback('foo')
75 dDict[did].callback('foo')
76 d = self.pdm.get_pending_deferred(did,block=False)
76 d = self.pdm.get_pending_deferred(did,block=False)
77 d.addCallback(lambda r: self.assert_(r=='foo'))
77 d.addCallback(lambda r: self.assert_(r=='foo'))
78
78
79 def test_save_then_delete(self):
79 def test_save_then_delete(self):
80 d = defer.Deferred()
80 d = defer.Deferred()
81 did = self.pdm.save_pending_deferred(d)
81 did = self.pdm.save_pending_deferred(d)
82 self.assert_(self.pdm.quick_has_id(did))
82 self.assert_(self.pdm.quick_has_id(did))
83 self.pdm.delete_pending_deferred(did)
83 self.pdm.delete_pending_deferred(did)
84 self.assert_(not self.pdm.quick_has_id(did))
84 self.assert_(not self.pdm.quick_has_id(did))
85
85
86 def test_save_get_delete(self):
86 def test_save_get_delete(self):
87 d = defer.Deferred()
87 d = defer.Deferred()
88 did = self.pdm.save_pending_deferred(d)
88 did = self.pdm.save_pending_deferred(d)
89 d2 = self.pdm.get_pending_deferred(did,True)
89 d2 = self.pdm.get_pending_deferred(did,True)
90 d2.addErrback(lambda f: self.assertRaises(error.AbortedPendingDeferredError, f.raiseException))
90 d2.addErrback(lambda f: self.assertRaises(error.AbortedPendingDeferredError, f.raiseException))
91 self.pdm.delete_pending_deferred(did)
91 self.pdm.delete_pending_deferred(did)
92 return d2
92 return d2
93
93
94 def test_double_get(self):
94 def test_double_get(self):
95 d = defer.Deferred()
95 d = defer.Deferred()
96 did = self.pdm.save_pending_deferred(d)
96 did = self.pdm.save_pending_deferred(d)
97 d2 = self.pdm.get_pending_deferred(did,True)
97 d2 = self.pdm.get_pending_deferred(did,True)
98 d3 = self.pdm.get_pending_deferred(did,True)
98 d3 = self.pdm.get_pending_deferred(did,True)
99 d3.addErrback(lambda f: self.assertRaises(error.InvalidDeferredID, f.raiseException))
99 d3.addErrback(lambda f: self.assertRaises(error.InvalidDeferredID, f.raiseException))
100
100
101 def test_get_after_callback(self):
101 def test_get_after_callback(self):
102 d = defer.Deferred()
102 d = defer.Deferred()
103 did = self.pdm.save_pending_deferred(d)
103 did = self.pdm.save_pending_deferred(d)
104 d.callback('foo')
104 d.callback('foo')
105 d2 = self.pdm.get_pending_deferred(did,True)
105 d2 = self.pdm.get_pending_deferred(did,True)
106 d2.addCallback(lambda r: self.assertEquals(r,'foo'))
106 d2.addCallback(lambda r: self.assertEquals(r,'foo'))
107 self.assert_(not self.pdm.quick_has_id(did))
107 self.assert_(not self.pdm.quick_has_id(did))
108
108
109 def test_get_before_callback(self):
109 def test_get_before_callback(self):
110 d = defer.Deferred()
110 d = defer.Deferred()
111 did = self.pdm.save_pending_deferred(d)
111 did = self.pdm.save_pending_deferred(d)
112 d2 = self.pdm.get_pending_deferred(did,True)
112 d2 = self.pdm.get_pending_deferred(did,True)
113 d.callback('foo')
113 d.callback('foo')
114 d2.addCallback(lambda r: self.assertEquals(r,'foo'))
114 d2.addCallback(lambda r: self.assertEquals(r,'foo'))
115 self.assert_(not self.pdm.quick_has_id(did))
115 self.assert_(not self.pdm.quick_has_id(did))
116 d = defer.Deferred()
116 d = defer.Deferred()
117 did = self.pdm.save_pending_deferred(d)
117 did = self.pdm.save_pending_deferred(d)
118 d2 = self.pdm.get_pending_deferred(did,True)
118 d2 = self.pdm.get_pending_deferred(did,True)
119 d2.addCallback(lambda r: self.assertEquals(r,'foo'))
119 d2.addCallback(lambda r: self.assertEquals(r,'foo'))
120 d.callback('foo')
120 d.callback('foo')
121 self.assert_(not self.pdm.quick_has_id(did))
121 self.assert_(not self.pdm.quick_has_id(did))
122
122
123 def test_get_after_errback(self):
123 def test_get_after_errback(self):
124 class MyError(Exception):
124 class MyError(Exception):
125 pass
125 pass
126 d = defer.Deferred()
126 d = defer.Deferred()
127 did = self.pdm.save_pending_deferred(d)
127 did = self.pdm.save_pending_deferred(d)
128 d.errback(failure.Failure(MyError('foo')))
128 d.errback(failure.Failure(MyError('foo')))
129 d2 = self.pdm.get_pending_deferred(did,True)
129 d2 = self.pdm.get_pending_deferred(did,True)
130 d2.addErrback(lambda f: self.assertRaises(MyError, f.raiseException))
130 d2.addErrback(lambda f: self.assertRaises(MyError, f.raiseException))
131 self.assert_(not self.pdm.quick_has_id(did))
131 self.assert_(not self.pdm.quick_has_id(did))
132
132
133 def test_get_before_errback(self):
133 def test_get_before_errback(self):
134 class MyError(Exception):
134 class MyError(Exception):
135 pass
135 pass
136 d = defer.Deferred()
136 d = defer.Deferred()
137 did = self.pdm.save_pending_deferred(d)
137 did = self.pdm.save_pending_deferred(d)
138 d2 = self.pdm.get_pending_deferred(did,True)
138 d2 = self.pdm.get_pending_deferred(did,True)
139 d.errback(failure.Failure(MyError('foo')))
139 d.errback(failure.Failure(MyError('foo')))
140 d2.addErrback(lambda f: self.assertRaises(MyError, f.raiseException))
140 d2.addErrback(lambda f: self.assertRaises(MyError, f.raiseException))
141 self.assert_(not self.pdm.quick_has_id(did))
141 self.assert_(not self.pdm.quick_has_id(did))
142 d = defer.Deferred()
142 d = defer.Deferred()
143 did = self.pdm.save_pending_deferred(d)
143 did = self.pdm.save_pending_deferred(d)
144 d2 = self.pdm.get_pending_deferred(did,True)
144 d2 = self.pdm.get_pending_deferred(did,True)
145 d2.addErrback(lambda f: self.assertRaises(MyError, f.raiseException))
145 d2.addErrback(lambda f: self.assertRaises(MyError, f.raiseException))
146 d.errback(failure.Failure(MyError('foo')))
146 d.errback(failure.Failure(MyError('foo')))
147 self.assert_(not self.pdm.quick_has_id(did))
147 self.assert_(not self.pdm.quick_has_id(did))
148
148
149 def test_noresult_noblock(self):
149 def test_noresult_noblock(self):
150 d = defer.Deferred()
150 d = defer.Deferred()
151 did = self.pdm.save_pending_deferred(d)
151 did = self.pdm.save_pending_deferred(d)
152 d2 = self.pdm.get_pending_deferred(did,False)
152 d2 = self.pdm.get_pending_deferred(did,False)
153 d2.addErrback(lambda f: self.assertRaises(error.ResultNotCompleted, f.raiseException))
153 d2.addErrback(lambda f: self.assertRaises(error.ResultNotCompleted, f.raiseException))
154
154
155 def test_with_callbacks(self):
155 def test_with_callbacks(self):
156 d = defer.Deferred()
156 d = defer.Deferred()
157 d.addCallback(lambda r: r+' foo')
157 d.addCallback(lambda r: r+' foo')
158 d.addCallback(lambda r: r+' bar')
158 d.addCallback(lambda r: r+' bar')
159 did = self.pdm.save_pending_deferred(d)
159 did = self.pdm.save_pending_deferred(d)
160 d2 = self.pdm.get_pending_deferred(did,True)
160 d2 = self.pdm.get_pending_deferred(did,True)
161 d.callback('bam')
161 d.callback('bam')
162 d2.addCallback(lambda r: self.assertEquals(r,'bam foo bar'))
162 d2.addCallback(lambda r: self.assertEquals(r,'bam foo bar'))
163
163
164 def test_with_errbacks(self):
164 def test_with_errbacks(self):
165 class MyError(Exception):
165 class MyError(Exception):
166 pass
166 pass
167 d = defer.Deferred()
167 d = defer.Deferred()
168 d.addCallback(lambda r: 'foo')
168 d.addCallback(lambda r: 'foo')
169 d.addErrback(lambda f: 'caught error')
169 d.addErrback(lambda f: 'caught error')
170 did = self.pdm.save_pending_deferred(d)
170 did = self.pdm.save_pending_deferred(d)
171 d2 = self.pdm.get_pending_deferred(did,True)
171 d2 = self.pdm.get_pending_deferred(did,True)
172 d.errback(failure.Failure(MyError('bam')))
172 d.errback(failure.Failure(MyError('bam')))
173 d2.addErrback(lambda f: self.assertRaises(MyError, f.raiseException))
173 d2.addErrback(lambda f: self.assertRaises(MyError, f.raiseException))
174
174
175 def test_nested_deferreds(self):
175 def test_nested_deferreds(self):
176 d = defer.Deferred()
176 d = defer.Deferred()
177 d2 = defer.Deferred()
177 d2 = defer.Deferred()
178 d.addCallback(lambda r: d2)
178 d.addCallback(lambda r: d2)
179 did = self.pdm.save_pending_deferred(d)
179 did = self.pdm.save_pending_deferred(d)
180 d.callback('foo')
180 d.callback('foo')
181 d3 = self.pdm.get_pending_deferred(did,False)
181 d3 = self.pdm.get_pending_deferred(did,False)
182 d3.addErrback(lambda f: self.assertRaises(error.ResultNotCompleted, f.raiseException))
182 d3.addErrback(lambda f: self.assertRaises(error.ResultNotCompleted, f.raiseException))
183 d2.callback('bar')
183 d2.callback('bar')
184 d3 = self.pdm.get_pending_deferred(did,False)
184 d3 = self.pdm.get_pending_deferred(did,False)
185 d3.addCallback(lambda r: self.assertEquals(r,'bar'))
185 d3.addCallback(lambda r: self.assertEquals(r,'bar'))
186
186
@@ -1,51 +1,51 b''
1 # encoding: utf-8
1 # encoding: utf-8
2
2
3 """This file contains unittests for the kernel.task.py module."""
3 """This file contains unittests for the kernel.task.py module."""
4
4
5 __docformat__ = "restructuredtext en"
5 __docformat__ = "restructuredtext en"
6
6
7 #-------------------------------------------------------------------------------
7 #-------------------------------------------------------------------------------
8 # Copyright (C) 2008 The IPython Development Team
8 # Copyright (C) 2008 The IPython Development Team
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-------------------------------------------------------------------------------
12 #-------------------------------------------------------------------------------
13
13
14 #-------------------------------------------------------------------------------
14 #-------------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-------------------------------------------------------------------------------
16 #-------------------------------------------------------------------------------
17
17
18 try:
18 # Tell nose to skip this module
19 __test__ = {}
20
19 import time
21 import time
20
22
21 from twisted.internet import defer
23 from twisted.internet import defer
22 from twisted.trial import unittest
24 from twisted.trial import unittest
23
25
24 from IPython.kernel import task, controllerservice as cs, engineservice as es
26 from IPython.kernel import task, controllerservice as cs, engineservice as es
25 from IPython.kernel.multiengine import IMultiEngine
27 from IPython.kernel.multiengine import IMultiEngine
26 from IPython.testing.util import DeferredTestCase
28 from IPython.testing.util import DeferredTestCase
27 from IPython.kernel.tests.tasktest import ITaskControllerTestCase
29 from IPython.kernel.tests.tasktest import ITaskControllerTestCase
28 except ImportError:
30
29 import nose
30 raise nose.SkipTest("This test requires zope.interface, Twisted and Foolscap")
31
31
32 #-------------------------------------------------------------------------------
32 #-------------------------------------------------------------------------------
33 # Tests
33 # Tests
34 #-------------------------------------------------------------------------------
34 #-------------------------------------------------------------------------------
35
35
36 class BasicTaskControllerTestCase(DeferredTestCase, ITaskControllerTestCase):
36 class BasicTaskControllerTestCase(DeferredTestCase, ITaskControllerTestCase):
37
37
38 def setUp(self):
38 def setUp(self):
39 self.controller = cs.ControllerService()
39 self.controller = cs.ControllerService()
40 self.controller.startService()
40 self.controller.startService()
41 self.multiengine = IMultiEngine(self.controller)
41 self.multiengine = IMultiEngine(self.controller)
42 self.tc = task.ITaskController(self.controller)
42 self.tc = task.ITaskController(self.controller)
43 self.tc.failurePenalty = 0
43 self.tc.failurePenalty = 0
44 self.engines=[]
44 self.engines=[]
45
45
46 def tearDown(self):
46 def tearDown(self):
47 self.controller.stopService()
47 self.controller.stopService()
48 for e in self.engines:
48 for e in self.engines:
49 e.stopService()
49 e.stopService()
50
50
51
51
@@ -1,162 +1,161 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3
3
4 __docformat__ = "restructuredtext en"
4 __docformat__ = "restructuredtext en"
5
5
6 #-------------------------------------------------------------------------------
6 #-------------------------------------------------------------------------------
7 # Copyright (C) 2008 The IPython Development Team
7 # Copyright (C) 2008 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-------------------------------------------------------------------------------
11 #-------------------------------------------------------------------------------
12
12
13 #-------------------------------------------------------------------------------
13 #-------------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-------------------------------------------------------------------------------
15 #-------------------------------------------------------------------------------
16
16
17 try:
17 # Tell nose to skip this module
18 __test__ = {}
19
18 import time
20 import time
19
21
20 from twisted.internet import defer, reactor
22 from twisted.internet import defer, reactor
21
23
22 from IPython.kernel.fcutil import Tub, UnauthenticatedTub
24 from IPython.kernel.fcutil import Tub, UnauthenticatedTub
23
25
24 from IPython.kernel import task as taskmodule
26 from IPython.kernel import task as taskmodule
25 from IPython.kernel import controllerservice as cs
27 from IPython.kernel import controllerservice as cs
26 import IPython.kernel.multiengine as me
28 import IPython.kernel.multiengine as me
27 from IPython.testing.util import DeferredTestCase
29 from IPython.testing.util import DeferredTestCase
28 from IPython.kernel.multienginefc import IFCSynchronousMultiEngine
30 from IPython.kernel.multienginefc import IFCSynchronousMultiEngine
29 from IPython.kernel.taskfc import IFCTaskController
31 from IPython.kernel.taskfc import IFCTaskController
30 from IPython.kernel.util import printer
32 from IPython.kernel.util import printer
31 from IPython.kernel.tests.tasktest import ITaskControllerTestCase
33 from IPython.kernel.tests.tasktest import ITaskControllerTestCase
32 from IPython.kernel.clientconnector import ClientConnector
34 from IPython.kernel.clientconnector import ClientConnector
33 from IPython.kernel.error import CompositeError
35 from IPython.kernel.error import CompositeError
34 from IPython.kernel.parallelfunction import ParallelFunction
36 from IPython.kernel.parallelfunction import ParallelFunction
35 except ImportError:
36 import nose
37 raise nose.SkipTest("This test requires zope.interface, Twisted and Foolscap")
38
37
39
38
40 #-------------------------------------------------------------------------------
39 #-------------------------------------------------------------------------------
41 # Tests
40 # Tests
42 #-------------------------------------------------------------------------------
41 #-------------------------------------------------------------------------------
43
42
44 def _raise_it(f):
43 def _raise_it(f):
45 try:
44 try:
46 f.raiseException()
45 f.raiseException()
47 except CompositeError, e:
46 except CompositeError, e:
48 e.raise_exception()
47 e.raise_exception()
49
48
50 class TaskTest(DeferredTestCase, ITaskControllerTestCase):
49 class TaskTest(DeferredTestCase, ITaskControllerTestCase):
51
50
52 def setUp(self):
51 def setUp(self):
53
52
54 self.engines = []
53 self.engines = []
55
54
56 self.controller = cs.ControllerService()
55 self.controller = cs.ControllerService()
57 self.controller.startService()
56 self.controller.startService()
58 self.imultiengine = me.IMultiEngine(self.controller)
57 self.imultiengine = me.IMultiEngine(self.controller)
59 self.itc = taskmodule.ITaskController(self.controller)
58 self.itc = taskmodule.ITaskController(self.controller)
60 self.itc.failurePenalty = 0
59 self.itc.failurePenalty = 0
61
60
62 self.mec_referenceable = IFCSynchronousMultiEngine(self.imultiengine)
61 self.mec_referenceable = IFCSynchronousMultiEngine(self.imultiengine)
63 self.tc_referenceable = IFCTaskController(self.itc)
62 self.tc_referenceable = IFCTaskController(self.itc)
64
63
65 self.controller_tub = Tub()
64 self.controller_tub = Tub()
66 self.controller_tub.listenOn('tcp:10105:interface=127.0.0.1')
65 self.controller_tub.listenOn('tcp:10105:interface=127.0.0.1')
67 self.controller_tub.setLocation('127.0.0.1:10105')
66 self.controller_tub.setLocation('127.0.0.1:10105')
68
67
69 mec_furl = self.controller_tub.registerReference(self.mec_referenceable)
68 mec_furl = self.controller_tub.registerReference(self.mec_referenceable)
70 tc_furl = self.controller_tub.registerReference(self.tc_referenceable)
69 tc_furl = self.controller_tub.registerReference(self.tc_referenceable)
71 self.controller_tub.startService()
70 self.controller_tub.startService()
72
71
73 self.client_tub = ClientConnector()
72 self.client_tub = ClientConnector()
74 d = self.client_tub.get_multiengine_client(mec_furl)
73 d = self.client_tub.get_multiengine_client(mec_furl)
75 d.addCallback(self.handle_mec_client)
74 d.addCallback(self.handle_mec_client)
76 d.addCallback(lambda _: self.client_tub.get_task_client(tc_furl))
75 d.addCallback(lambda _: self.client_tub.get_task_client(tc_furl))
77 d.addCallback(self.handle_tc_client)
76 d.addCallback(self.handle_tc_client)
78 return d
77 return d
79
78
80 def handle_mec_client(self, client):
79 def handle_mec_client(self, client):
81 self.multiengine = client
80 self.multiengine = client
82
81
83 def handle_tc_client(self, client):
82 def handle_tc_client(self, client):
84 self.tc = client
83 self.tc = client
85
84
86 def tearDown(self):
85 def tearDown(self):
87 dlist = []
86 dlist = []
88 # Shut down the multiengine client
87 # Shut down the multiengine client
89 d = self.client_tub.tub.stopService()
88 d = self.client_tub.tub.stopService()
90 dlist.append(d)
89 dlist.append(d)
91 # Shut down the engines
90 # Shut down the engines
92 for e in self.engines:
91 for e in self.engines:
93 e.stopService()
92 e.stopService()
94 # Shut down the controller
93 # Shut down the controller
95 d = self.controller_tub.stopService()
94 d = self.controller_tub.stopService()
96 d.addBoth(lambda _: self.controller.stopService())
95 d.addBoth(lambda _: self.controller.stopService())
97 dlist.append(d)
96 dlist.append(d)
98 return defer.DeferredList(dlist)
97 return defer.DeferredList(dlist)
99
98
100 def test_mapper(self):
99 def test_mapper(self):
101 self.addEngine(1)
100 self.addEngine(1)
102 m = self.tc.mapper()
101 m = self.tc.mapper()
103 self.assertEquals(m.task_controller,self.tc)
102 self.assertEquals(m.task_controller,self.tc)
104 self.assertEquals(m.clear_before,False)
103 self.assertEquals(m.clear_before,False)
105 self.assertEquals(m.clear_after,False)
104 self.assertEquals(m.clear_after,False)
106 self.assertEquals(m.retries,0)
105 self.assertEquals(m.retries,0)
107 self.assertEquals(m.recovery_task,None)
106 self.assertEquals(m.recovery_task,None)
108 self.assertEquals(m.depend,None)
107 self.assertEquals(m.depend,None)
109 self.assertEquals(m.block,True)
108 self.assertEquals(m.block,True)
110
109
111 def test_map_default(self):
110 def test_map_default(self):
112 self.addEngine(1)
111 self.addEngine(1)
113 m = self.tc.mapper()
112 m = self.tc.mapper()
114 d = m.map(lambda x: 2*x, range(10))
113 d = m.map(lambda x: 2*x, range(10))
115 d.addCallback(lambda r: self.assertEquals(r,[2*x for x in range(10)]))
114 d.addCallback(lambda r: self.assertEquals(r,[2*x for x in range(10)]))
116 d.addCallback(lambda _: self.tc.map(lambda x: 2*x, range(10)))
115 d.addCallback(lambda _: self.tc.map(lambda x: 2*x, range(10)))
117 d.addCallback(lambda r: self.assertEquals(r,[2*x for x in range(10)]))
116 d.addCallback(lambda r: self.assertEquals(r,[2*x for x in range(10)]))
118 return d
117 return d
119
118
120 def test_map_noblock(self):
119 def test_map_noblock(self):
121 self.addEngine(1)
120 self.addEngine(1)
122 m = self.tc.mapper(block=False)
121 m = self.tc.mapper(block=False)
123 d = m.map(lambda x: 2*x, range(10))
122 d = m.map(lambda x: 2*x, range(10))
124 d.addCallback(lambda r: self.assertEquals(r,[x for x in range(10)]))
123 d.addCallback(lambda r: self.assertEquals(r,[x for x in range(10)]))
125 return d
124 return d
126
125
127 def test_mapper_fail(self):
126 def test_mapper_fail(self):
128 self.addEngine(1)
127 self.addEngine(1)
129 m = self.tc.mapper()
128 m = self.tc.mapper()
130 d = m.map(lambda x: 1/0, range(10))
129 d = m.map(lambda x: 1/0, range(10))
131 d.addBoth(lambda f: self.assertRaises(ZeroDivisionError, _raise_it, f))
130 d.addBoth(lambda f: self.assertRaises(ZeroDivisionError, _raise_it, f))
132 return d
131 return d
133
132
134 def test_parallel(self):
133 def test_parallel(self):
135 self.addEngine(1)
134 self.addEngine(1)
136 p = self.tc.parallel()
135 p = self.tc.parallel()
137 self.assert_(isinstance(p, ParallelFunction))
136 self.assert_(isinstance(p, ParallelFunction))
138 @p
137 @p
139 def f(x): return 2*x
138 def f(x): return 2*x
140 d = f(range(10))
139 d = f(range(10))
141 d.addCallback(lambda r: self.assertEquals(r,[2*x for x in range(10)]))
140 d.addCallback(lambda r: self.assertEquals(r,[2*x for x in range(10)]))
142 return d
141 return d
143
142
144 def test_parallel_noblock(self):
143 def test_parallel_noblock(self):
145 self.addEngine(1)
144 self.addEngine(1)
146 p = self.tc.parallel(block=False)
145 p = self.tc.parallel(block=False)
147 self.assert_(isinstance(p, ParallelFunction))
146 self.assert_(isinstance(p, ParallelFunction))
148 @p
147 @p
149 def f(x): return 2*x
148 def f(x): return 2*x
150 d = f(range(10))
149 d = f(range(10))
151 d.addCallback(lambda r: self.assertEquals(r,[x for x in range(10)]))
150 d.addCallback(lambda r: self.assertEquals(r,[x for x in range(10)]))
152 return d
151 return d
153
152
154 def test_parallel_fail(self):
153 def test_parallel_fail(self):
155 self.addEngine(1)
154 self.addEngine(1)
156 p = self.tc.parallel()
155 p = self.tc.parallel()
157 self.assert_(isinstance(p, ParallelFunction))
156 self.assert_(isinstance(p, ParallelFunction))
158 @p
157 @p
159 def f(x): return 1/0
158 def f(x): return 1/0
160 d = f(range(10))
159 d = f(range(10))
161 d.addBoth(lambda f: self.assertRaises(ZeroDivisionError, _raise_it, f))
160 d.addBoth(lambda f: self.assertRaises(ZeroDivisionError, _raise_it, f))
162 return d No newline at end of file
161 return d
@@ -1,48 +1,51 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2008 The IPython Development Team
5 # Copyright (C) 2008 The IPython Development Team
6 #
6 #
7 # Distributed under the terms of the BSD License. The full license is in
7 # Distributed under the terms of the BSD License. The full license is in
8 # the file COPYING, distributed as part of this software.
8 # the file COPYING, distributed as part of this software.
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 # Tell nose to skip this module
16 __test__ = {}
17
15 import tempfile
18 import tempfile
16 import os, sys
19 import os, sys
17
20
18 from twisted.internet import reactor
21 from twisted.internet import reactor
19 from twisted.trial import unittest
22 from twisted.trial import unittest
20
23
21 from IPython.kernel.error import FileTimeoutError
24 from IPython.kernel.error import FileTimeoutError
22 from IPython.kernel.twistedutil import wait_for_file
25 from IPython.kernel.twistedutil import wait_for_file
23
26
24 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
25 # Tests
28 # Tests
26 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
27
30
28 class TestWaitForFile(unittest.TestCase):
31 class TestWaitForFile(unittest.TestCase):
29
32
30 def test_delay(self):
33 def test_delay(self):
31 filename = tempfile.mktemp()
34 filename = tempfile.mktemp()
32 def _create_file():
35 def _create_file():
33 open(filename,'w').write('####')
36 open(filename,'w').write('####')
34 dcall = reactor.callLater(0.5, _create_file)
37 dcall = reactor.callLater(0.5, _create_file)
35 d = wait_for_file(filename,delay=0.1)
38 d = wait_for_file(filename,delay=0.1)
36 d.addCallback(lambda r: self.assert_(r))
39 d.addCallback(lambda r: self.assert_(r))
37 def _cancel_dcall(r):
40 def _cancel_dcall(r):
38 if dcall.active():
41 if dcall.active():
39 dcall.cancel()
42 dcall.cancel()
40 d.addCallback(_cancel_dcall)
43 d.addCallback(_cancel_dcall)
41 return d
44 return d
42
45
43 def test_timeout(self):
46 def test_timeout(self):
44 filename = tempfile.mktemp()
47 filename = tempfile.mktemp()
45 d = wait_for_file(filename,delay=0.1,max_tries=1)
48 d = wait_for_file(filename,delay=0.1,max_tries=1)
46 d.addErrback(lambda f: self.assertRaises(FileTimeoutError,f.raiseException))
49 d.addErrback(lambda f: self.assertRaises(FileTimeoutError,f.raiseException))
47 return d
50 return d
48 No newline at end of file
51
1 NO CONTENT: modified file
NO CONTENT: modified file
General Comments 0
You need to be logged in to leave comments. Login now