| 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 |
|
| 18 |
# Define two classes, one which succeeds and one which raises TryNext. Each |
| 19 |
# sets the attribute `called` to True when it is called. |
| 20 |
class Okay(object): |
| 21 |
def __init__(self, message): |
| 22 |
self.message = message |
| 23 |
self.called = False |
| 24 |
|
| 25 |
def __call__(self): |
| 26 |
self.called = True |
| 27 |
return self.message |
| 28 |
|
| 29 |
|
| 30 |
class Fail(object): |
| 31 |
def __init__(self, message): |
| 32 |
self.message = message |
| 33 |
self.called = False |
| 34 |
|
| 35 |
def __call__(self): |
| 36 |
self.called = True |
| 37 |
raise TryNext(self.message) |
| 38 |
|
| 39 |
|
| 40 |
# ----------------------------------------------------------------------------- |
| 41 |
# Test functions |
| 42 |
# ----------------------------------------------------------------------------- |
| 43 |
|
| 44 |
|
| 45 |
def test_command_chain_dispatcher_ff(): |
| 46 |
"""Test two failing hooks""" |
| 47 |
fail1 = Fail("fail1") |
| 48 |
fail2 = Fail("fail2") |
| 49 |
dp = CommandChainDispatcher([(0, fail1), (10, fail2)]) |
| 50 |
|
| 51 |
with pytest.raises(TryNext) as e: |
| 52 |
dp() |
| 53 |
assert str(e.value) == "fail2" |
| 54 |
|
| 55 |
assert fail1.called is True |
| 56 |
assert fail2.called is True |
| 57 |
|
| 58 |
|
| 59 |
def test_command_chain_dispatcher_fofo(): |
| 60 |
"""Test a mixture of failing and succeeding hooks.""" |
| 61 |
fail1 = Fail("fail1") |
| 62 |
fail2 = Fail("fail2") |
| 63 |
okay1 = Okay("okay1") |
| 64 |
okay2 = Okay("okay2") |
| 65 |
|
| 66 |
dp = CommandChainDispatcher( |
| 67 |
[ |
| 68 |
(0, fail1), |
| 69 |
# (5, okay1), # add this later |
| 70 |
(10, fail2), |
| 71 |
(15, okay2), |
| 72 |
] |
| 73 |
) |
| 74 |
dp.add(okay1, 5) |
| 75 |
|
| 76 |
assert dp() == "okay1" |
| 77 |
|
| 78 |
assert fail1.called is True |
| 79 |
assert okay1.called is True |
| 80 |
assert fail2.called is False |
| 81 |
assert okay2.called is False |
| 82 |
|
| 83 |
|
| 84 |
def test_command_chain_dispatcher_eq_priority(): |
| 85 |
okay1 = Okay("okay1") |
| 86 |
okay2 = Okay("okay2") |
| 87 |
dp = CommandChainDispatcher([(1, okay1)]) |
| 88 |
dp.add(okay2, 1) |