1 # -*- coding: utf-8 -*- 2 """Tests for CommandChainDispatcher.""" 3 4 5 #----------------------------------------------------------------------------- 6 # Imports 7 #----------------------------------------------------------------------------- 8 9 import pytest 10 from IPython.core.error import TryNext 11 from IPython.core.hooks import CommandChainDispatcher 12 13 #----------------------------------------------------------------------------- 14 # Local utilities 15 #----------------------------------------------------------------------------- 16 17 # Define two classes, one which succeeds and one which raises TryNext. Each 18 # sets the attribute `called` to True when it is called. 19 class Okay(object): 20 def __init__(self, message): 21 self.message = message 22 self.called = False 23 def __call__(self): 24 self.called = True 25 return self.message 26 27 class Fail(object): 28 def __init__(self, message): 29 self.message = message 30 self.called = False 31 def __call__(self): 32 self.called = True 33 raise TryNext(self.message) 34 35 #----------------------------------------------------------------------------- 36 # Test functions 37 #----------------------------------------------------------------------------- 38 39 def test_command_chain_dispatcher_ff(): 40 """Test two failing hooks""" 41 fail1 = Fail("fail1") 42 fail2 = Fail("fail2") 43 dp = CommandChainDispatcher([(0, fail1), (10, fail2)]) 44 45 with pytest.raises(TryNext) as e: 46 dp() 47 assert str(e.value) == "fail2" 48 49 assert fail1.called is True 50 assert fail2.called is True 51 52 def test_command_chain_dispatcher_fofo(): 53 """Test a mixture of failing and succeeding hooks.""" 54 fail1 = Fail("fail1") 55 fail2 = Fail("fail2") 56 okay1 = Okay("okay1") 57 okay2 = Okay("okay2") 58 59 dp = CommandChainDispatcher([(0, fail1), 60 # (5, okay1), # add this later 61 (10, fail2), 62 (15, okay2)]) 63 dp.add(okay1, 5) 64 65 assert dp() == "okay1" 66 67 assert fail1.called is True 68 assert okay1.called is True 69 assert fail2.called is False 70 assert okay2.called is False 71 72 def test_command_chain_dispatcher_eq_priority(): 73 okay1 = Okay(u'okay1') 74 okay2 = Okay(u'okay2') 75 dp = CommandChainDispatcher([(1, okay1)]) 76 dp.add(okay2, 1) 77