1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
|
import sys
import types
import pytest
from pluggy import (PluginManager, varnames, PluginValidationError,
HookCallError, HookimplMarker, HookspecMarker)
from pluggy import (_MultiCall, _TagTracer, HookImpl, _formatdef)
hookspec = HookspecMarker("example")
hookimpl = HookimplMarker("example")
@pytest.fixture
def pm():
return PluginManager("example")
@pytest.fixture
def he_pm(pm):
class Hooks:
@hookspec
def he_method1(self, arg):
return arg + 1
pm.add_hookspecs(Hooks)
return pm
class TestPluginManager:
def test_plugin_double_register(self, pm):
pm.register(42, name="abc")
with pytest.raises(ValueError):
pm.register(42, name="abc")
with pytest.raises(ValueError):
pm.register(42, name="def")
def test_pm(self, pm):
class A:
pass
a1, a2 = A(), A()
pm.register(a1)
assert pm.is_registered(a1)
pm.register(a2, "hello")
assert pm.is_registered(a2)
l = pm.get_plugins()
assert a1 in l
assert a2 in l
assert pm.get_plugin('hello') == a2
assert pm.unregister(a1) == a1
assert not pm.is_registered(a1)
l = pm.list_name_plugin()
assert len(l) == 1
assert l == [("hello", a2)]
def test_has_plugin(self, pm):
class A:
pass
a1 = A()
pm.register(a1, 'hello')
assert pm.is_registered(a1)
assert pm.has_plugin('hello')
def test_register_dynamic_attr(self, he_pm):
class A:
def __getattr__(self, name):
if name[0] != "_":
return 42
raise AttributeError()
a = A()
he_pm.register(a)
assert not he_pm.get_hookcallers(a)
def test_pm_name(self, pm):
class A:
pass
a1 = A()
name = pm.register(a1, name="hello")
assert name == "hello"
pm.unregister(a1)
assert pm.get_plugin(a1) is None
assert not pm.is_registered(a1)
assert not pm.get_plugins()
name2 = pm.register(a1, name="hello")
assert name2 == name
pm.unregister(name="hello")
assert pm.get_plugin(a1) is None
assert not pm.is_registered(a1)
assert not pm.get_plugins()
def test_set_blocked(self, pm):
class A:
pass
a1 = A()
name = pm.register(a1)
assert pm.is_registered(a1)
assert not pm.is_blocked(name)
pm.set_blocked(name)
assert pm.is_blocked(name)
assert not pm.is_registered(a1)
pm.set_blocked("somename")
assert pm.is_blocked("somename")
assert not pm.register(A(), "somename")
pm.unregister(name="somename")
assert pm.is_blocked("somename")
def test_register_mismatch_method(self, he_pm):
class hello:
@hookimpl
def he_method_notexists(self):
pass
he_pm.register(hello())
with pytest.raises(PluginValidationError):
he_pm.check_pending()
def test_register_mismatch_arg(self, he_pm):
class hello:
@hookimpl
def he_method1(self, qlwkje):
pass
with pytest.raises(PluginValidationError):
he_pm.register(hello())
def test_register(self, pm):
class MyPlugin:
pass
my = MyPlugin()
pm.register(my)
assert my in pm.get_plugins()
my2 = MyPlugin()
pm.register(my2)
assert set([my, my2]).issubset(pm.get_plugins())
assert pm.is_registered(my)
assert pm.is_registered(my2)
pm.unregister(my)
assert not pm.is_registered(my)
assert my not in pm.get_plugins()
def test_register_unknown_hooks(self, pm):
class Plugin1:
@hookimpl
def he_method1(self, arg):
return arg + 1
pname = pm.register(Plugin1())
class Hooks:
@hookspec
def he_method1(self, arg):
pass
pm.add_hookspecs(Hooks)
# assert not pm._unverified_hooks
assert pm.hook.he_method1(arg=1) == [2]
assert len(pm.get_hookcallers(pm.get_plugin(pname))) == 1
def test_register_historic(self, pm):
class Hooks:
@hookspec(historic=True)
def he_method1(self, arg):
pass
pm.add_hookspecs(Hooks)
pm.hook.he_method1.call_historic(kwargs=dict(arg=1))
l = []
class Plugin:
@hookimpl
def he_method1(self, arg):
l.append(arg)
pm.register(Plugin())
assert l == [1]
class Plugin2:
@hookimpl
def he_method1(self, arg):
l.append(arg * 10)
pm.register(Plugin2())
assert l == [1, 10]
pm.hook.he_method1.call_historic(kwargs=dict(arg=12))
assert l == [1, 10, 120, 12]
def test_with_result_memorized(self, pm):
class Hooks:
@hookspec(historic=True)
def he_method1(self, arg):
pass
pm.add_hookspecs(Hooks)
he_method1 = pm.hook.he_method1
he_method1.call_historic(lambda res: l.append(res), dict(arg=1))
l = []
class Plugin:
@hookimpl
def he_method1(self, arg):
return arg * 10
pm.register(Plugin())
assert l == [10]
def test_register_historic_incompat_hookwrapper(self, pm):
class Hooks:
@hookspec(historic=True)
def he_method1(self, arg):
pass
pm.add_hookspecs(Hooks)
l = []
class Plugin:
@hookimpl(hookwrapper=True)
def he_method1(self, arg):
l.append(arg)
with pytest.raises(PluginValidationError):
pm.register(Plugin())
def test_call_extra(self, pm):
class Hooks:
@hookspec
def he_method1(self, arg):
pass
pm.add_hookspecs(Hooks)
def he_method1(arg):
return arg * 10
l = pm.hook.he_method1.call_extra([he_method1], dict(arg=1))
assert l == [10]
def test_call_with_too_few_args(self, pm):
class Hooks:
@hookspec
def he_method1(self, arg):
pass
pm.add_hookspecs(Hooks)
class Plugin1:
@hookimpl
def he_method1(self, arg):
0 / 0
pm.register(Plugin1())
with pytest.raises(HookCallError):
pm.hook.he_method1()
def test_subset_hook_caller(self, pm):
class Hooks:
@hookspec
def he_method1(self, arg):
pass
pm.add_hookspecs(Hooks)
l = []
class Plugin1:
@hookimpl
def he_method1(self, arg):
l.append(arg)
class Plugin2:
@hookimpl
def he_method1(self, arg):
l.append(arg * 10)
class PluginNo:
pass
plugin1, plugin2, plugin3 = Plugin1(), Plugin2(), PluginNo()
pm.register(plugin1)
pm.register(plugin2)
pm.register(plugin3)
pm.hook.he_method1(arg=1)
assert l == [10, 1]
l[:] = []
hc = pm.subset_hook_caller("he_method1", [plugin1])
hc(arg=2)
assert l == [20]
l[:] = []
hc = pm.subset_hook_caller("he_method1", [plugin2])
hc(arg=2)
assert l == [2]
l[:] = []
pm.unregister(plugin1)
hc(arg=2)
assert l == []
l[:] = []
pm.hook.he_method1(arg=1)
assert l == [10]
def test_add_hookspecs_nohooks(self, pm):
with pytest.raises(ValueError):
pm.add_hookspecs(10)
class TestAddMethodOrdering:
@pytest.fixture
def hc(self, pm):
class Hooks:
@hookspec
def he_method1(self, arg):
pass
pm.add_hookspecs(Hooks)
return pm.hook.he_method1
@pytest.fixture
def addmeth(self, hc):
def addmeth(tryfirst=False, trylast=False, hookwrapper=False):
def wrap(func):
hookimpl(tryfirst=tryfirst, trylast=trylast,
hookwrapper=hookwrapper)(func)
hc._add_hookimpl(HookImpl(None, "<temp>", func, func.example_impl))
return func
return wrap
return addmeth
def funcs(self, hookmethods):
return [hookmethod.function for hookmethod in hookmethods]
def test_adding_nonwrappers(self, hc, addmeth):
@addmeth()
def he_method1():
pass
@addmeth()
def he_method2():
pass
@addmeth()
def he_method3():
pass
assert self.funcs(hc._nonwrappers) == [he_method1, he_method2, he_method3]
def test_adding_nonwrappers_trylast(self, hc, addmeth):
@addmeth()
def he_method1_middle():
pass
@addmeth(trylast=True)
def he_method1():
pass
@addmeth()
def he_method1_b():
pass
assert self.funcs(hc._nonwrappers) == \
[he_method1, he_method1_middle, he_method1_b]
def test_adding_nonwrappers_trylast3(self, hc, addmeth):
@addmeth()
def he_method1_a():
pass
@addmeth(trylast=True)
def he_method1_b():
pass
@addmeth()
def he_method1_c():
pass
@addmeth(trylast=True)
def he_method1_d():
pass
assert self.funcs(hc._nonwrappers) == \
[he_method1_d, he_method1_b, he_method1_a, he_method1_c]
def test_adding_nonwrappers_trylast2(self, hc, addmeth):
@addmeth()
def he_method1_middle():
pass
@addmeth()
def he_method1_b():
pass
@addmeth(trylast=True)
def he_method1():
pass
assert self.funcs(hc._nonwrappers) == \
[he_method1, he_method1_middle, he_method1_b]
def test_adding_nonwrappers_tryfirst(self, hc, addmeth):
@addmeth(tryfirst=True)
def he_method1():
pass
@addmeth()
def he_method1_middle():
pass
@addmeth()
def he_method1_b():
pass
assert self.funcs(hc._nonwrappers) == \
[he_method1_middle, he_method1_b, he_method1]
def test_adding_wrappers_ordering(self, hc, addmeth):
@addmeth(hookwrapper=True)
def he_method1():
pass
@addmeth()
def he_method1_middle():
pass
@addmeth(hookwrapper=True)
def he_method3():
pass
assert self.funcs(hc._nonwrappers) == [he_method1_middle]
assert self.funcs(hc._wrappers) == [he_method1, he_method3]
def test_adding_wrappers_ordering_tryfirst(self, hc, addmeth):
@addmeth(hookwrapper=True, tryfirst=True)
def he_method1():
pass
@addmeth(hookwrapper=True)
def he_method2():
pass
assert hc._nonwrappers == []
assert self.funcs(hc._wrappers) == [he_method2, he_method1]
def test_hookspec(self, pm):
class HookSpec:
@hookspec()
def he_myhook1(self, arg1):
pass
@hookspec(firstresult=True)
def he_myhook2(self, arg1):
pass
@hookspec(firstresult=False)
def he_myhook3(self, arg1):
pass
pm.add_hookspecs(HookSpec)
assert not pm.hook.he_myhook1.spec_opts["firstresult"]
assert pm.hook.he_myhook2.spec_opts["firstresult"]
assert not pm.hook.he_myhook3.spec_opts["firstresult"]
def test_hookimpl(self):
for name in ["hookwrapper", "optionalhook", "tryfirst", "trylast"]:
for val in [True, False]:
@hookimpl(**{name: val})
def he_myhook1(self, arg1):
pass
if val:
assert he_myhook1.example_impl.get(name)
else:
assert not hasattr(he_myhook1, name)
def test_decorator_functional(self, pm):
class HookSpec:
@hookspec(firstresult=True)
def he_myhook(self, arg1):
""" add to arg1 """
pm.add_hookspecs(HookSpec)
class Plugin:
@hookimpl()
def he_myhook(self, arg1):
return arg1 + 1
pm.register(Plugin())
results = pm.hook.he_myhook(arg1=17)
assert results == 18
def test_load_setuptools_instantiation(self, monkeypatch, pm):
pkg_resources = pytest.importorskip("pkg_resources")
def my_iter(name):
assert name == "hello"
class EntryPoint:
name = "myname"
dist = None
def load(self):
class PseudoPlugin:
x = 42
return PseudoPlugin()
return iter([EntryPoint()])
monkeypatch.setattr(pkg_resources, 'iter_entry_points', my_iter)
num = pm.load_setuptools_entrypoints("hello")
assert num == 1
plugin = pm.get_plugin("myname")
assert plugin.x == 42
assert pm.list_plugin_distinfo() == [(plugin, None)]
def test_load_setuptools_not_installed(self, monkeypatch, pm):
monkeypatch.setitem(sys.modules, 'pkg_resources',
types.ModuleType("pkg_resources"))
with pytest.raises(ImportError):
pm.load_setuptools_entrypoints("qwe")
def test_add_tracefuncs(self, he_pm):
l = []
class api1:
@hookimpl
def he_method1(self):
l.append("he_method1-api1")
class api2:
@hookimpl
def he_method1(self):
l.append("he_method1-api2")
he_pm.register(api1())
he_pm.register(api2())
def before(hook_name, hook_impls, kwargs):
l.append((hook_name, list(hook_impls), kwargs))
def after(outcome, hook_name, hook_impls, kwargs):
l.append((outcome, hook_name, list(hook_impls), kwargs))
undo = he_pm.add_hookcall_monitoring(before, after)
he_pm.hook.he_method1()
assert len(l) == 4
assert l[0][0] == "he_method1"
assert len(l[0][1]) == 2
assert isinstance(l[0][2], dict)
assert l[1] == "he_method1-api2"
assert l[2] == "he_method1-api1"
assert len(l[3]) == 4
assert l[3][1] == l[0][0]
undo()
he_pm.hook.he_method1()
assert len(l) == 4 + 2
def test_hook_tracing(self, he_pm):
saveindent = []
class api1:
@hookimpl
def he_method1(self):
saveindent.append(he_pm.trace.root.indent)
class api2:
@hookimpl
def he_method1(self):
saveindent.append(he_pm.trace.root.indent)
raise ValueError()
he_pm.register(api1())
l = []
he_pm.trace.root.setwriter(l.append)
undo = he_pm.enable_tracing()
try:
indent = he_pm.trace.root.indent
he_pm.hook.he_method1(arg=1)
assert indent == he_pm.trace.root.indent
assert len(l) == 2
assert 'he_method1' in l[0]
assert 'finish' in l[1]
l[:] = []
he_pm.register(api2())
with pytest.raises(ValueError):
he_pm.hook.he_method1(arg=1)
assert he_pm.trace.root.indent == indent
assert saveindent[0] > indent
finally:
undo()
def test_prefix_hookimpl(self):
pm = PluginManager(hookspec.project_name, "hello_")
class HookSpec:
@hookspec
def hello_myhook(self, arg1):
""" add to arg1 """
pm.add_hookspecs(HookSpec)
class Plugin:
def hello_myhook(self, arg1):
return arg1 + 1
pm.register(Plugin())
pm.register(Plugin())
results = pm.hook.hello_myhook(arg1=17)
assert results == [18, 18]
def test_parse_hookimpl_override():
class MyPluginManager(PluginManager):
def parse_hookimpl_opts(self, module_or_class, name):
opts = PluginManager.parse_hookimpl_opts(self, module_or_class, name)
if opts is None:
if name.startswith("x1"):
opts = {}
return opts
class Plugin:
def x1meth(self):
pass
@hookimpl(hookwrapper=True, tryfirst=True)
def x1meth2(self):
pass
class Spec:
@hookspec
def x1meth(self):
pass
@hookspec
def x1meth2(self):
pass
pm = MyPluginManager(hookspec.project_name)
pm.register(Plugin())
pm.add_hookspecs(Spec)
assert not pm.hook.x1meth._nonwrappers[0].hookwrapper
assert not pm.hook.x1meth._nonwrappers[0].tryfirst
assert not pm.hook.x1meth._nonwrappers[0].trylast
assert not pm.hook.x1meth._nonwrappers[0].optionalhook
assert pm.hook.x1meth2._wrappers[0].tryfirst
assert pm.hook.x1meth2._wrappers[0].hookwrapper
def test_plugin_getattr_raises_errors():
"""Pluggy must be able to handle plugins which raise weird exceptions
when getattr() gets called (#11).
"""
class DontTouchMe:
def __getattr__(self, x):
raise Exception('cant touch me')
class Module:
pass
module = Module()
module.x = DontTouchMe()
pm = PluginManager(hookspec.project_name)
# register() would raise an error
pm.register(module, 'donttouch')
assert pm.get_plugin('donttouch') is module
def test_varnames():
def f(x):
i = 3 # noqa
class A:
def f(self, y):
pass
class B(object):
def __call__(self, z):
pass
assert varnames(f) == ("x",)
assert varnames(A().f) == ('y',)
assert varnames(B()) == ('z',)
def test_varnames_default():
def f(x, y=3):
pass
assert varnames(f) == ("x",)
def test_varnames_class():
class C:
def __init__(self, x):
pass
class D:
pass
assert varnames(C) == ("x",)
assert varnames(D) == ()
def test_formatdef():
def function1():
pass
assert _formatdef(function1) == 'function1()'
def function2(arg1):
pass
assert _formatdef(function2) == "function2(arg1)"
def function3(arg1, arg2="qwe"):
pass
assert _formatdef(function3) == "function3(arg1, arg2='qwe')"
def function4(arg1, *args, **kwargs):
pass
assert _formatdef(function4) == "function4(arg1, *args, **kwargs)"
class Test_MultiCall:
def test_uses_copy_of_methods(self):
l = [lambda: 42]
mc = _MultiCall(l, {})
repr(mc)
l[:] = []
res = mc.execute()
return res == 42
def MC(self, methods, kwargs, firstresult=False):
hookfuncs = []
for method in methods:
f = HookImpl(None, "<temp>", method, method.example_impl)
hookfuncs.append(f)
return _MultiCall(hookfuncs, kwargs, {"firstresult": firstresult})
def test_call_passing(self):
class P1:
@hookimpl
def m(self, __multicall__, x):
assert len(__multicall__.results) == 1
assert not __multicall__.hook_impls
return 17
class P2:
@hookimpl
def m(self, __multicall__, x):
assert __multicall__.results == []
assert __multicall__.hook_impls
return 23
p1 = P1()
p2 = P2()
multicall = self.MC([p1.m, p2.m], {"x": 23})
assert "23" in repr(multicall)
reslist = multicall.execute()
assert len(reslist) == 2
# ensure reversed order
assert reslist == [23, 17]
def test_keyword_args(self):
@hookimpl
def f(x):
return x + 1
class A:
@hookimpl
def f(self, x, y):
return x + y
multicall = self.MC([f, A().f], dict(x=23, y=24))
assert "'x': 23" in repr(multicall)
assert "'y': 24" in repr(multicall)
reslist = multicall.execute()
assert reslist == [24 + 23, 24]
assert "2 results" in repr(multicall)
def test_keyword_args_with_defaultargs(self):
@hookimpl
def f(x, z=1):
return x + z
reslist = self.MC([f], dict(x=23, y=24)).execute()
assert reslist == [24]
def test_tags_call_error(self):
@hookimpl
def f(x):
return x
multicall = self.MC([f], {})
pytest.raises(HookCallError, multicall.execute)
def test_call_subexecute(self):
@hookimpl
def m(__multicall__):
subresult = __multicall__.execute()
return subresult + 1
@hookimpl
def n():
return 1
call = self.MC([n, m], {}, firstresult=True)
res = call.execute()
assert res == 2
def test_call_none_is_no_result(self):
@hookimpl
def m1():
return 1
@hookimpl
def m2():
return None
res = self.MC([m1, m2], {}, {"firstresult": True}).execute()
assert res == 1
res = self.MC([m1, m2], {}, {}).execute()
assert res == [1]
def test_hookwrapper(self):
l = []
@hookimpl(hookwrapper=True)
def m1():
l.append("m1 init")
yield None
l.append("m1 finish")
@hookimpl
def m2():
l.append("m2")
return 2
res = self.MC([m2, m1], {}).execute()
assert res == [2]
assert l == ["m1 init", "m2", "m1 finish"]
l[:] = []
res = self.MC([m2, m1], {}, {"firstresult": True}).execute()
assert res == 2
assert l == ["m1 init", "m2", "m1 finish"]
def test_hookwrapper_order(self):
l = []
@hookimpl(hookwrapper=True)
def m1():
l.append("m1 init")
yield 1
l.append("m1 finish")
@hookimpl(hookwrapper=True)
def m2():
l.append("m2 init")
yield 2
l.append("m2 finish")
res = self.MC([m2, m1], {}).execute()
assert res == []
assert l == ["m1 init", "m2 init", "m2 finish", "m1 finish"]
def test_hookwrapper_not_yield(self):
@hookimpl(hookwrapper=True)
def m1():
pass
mc = self.MC([m1], {})
with pytest.raises(TypeError):
mc.execute()
def test_hookwrapper_too_many_yield(self):
@hookimpl(hookwrapper=True)
def m1():
yield 1
yield 2
mc = self.MC([m1], {})
with pytest.raises(RuntimeError) as ex:
mc.execute()
assert "m1" in str(ex.value)
assert "test_pluggy.py:" in str(ex.value)
@pytest.mark.parametrize("exc", [ValueError, SystemExit])
def test_hookwrapper_exception(self, exc):
l = []
@hookimpl(hookwrapper=True)
def m1():
l.append("m1 init")
yield None
l.append("m1 finish")
@hookimpl
def m2():
raise exc
with pytest.raises(exc):
self.MC([m2, m1], {}).execute()
assert l == ["m1 init", "m1 finish"]
class TestHookRelay:
def test_happypath(self, pm):
class Api:
@hookspec
def hello(self, arg):
"api hook 1"
pm.add_hookspecs(Api)
hook = pm.hook
assert hasattr(hook, 'hello')
assert repr(hook.hello).find("hello") != -1
class Plugin:
@hookimpl
def hello(self, arg):
return arg + 1
plugin = Plugin()
pm.register(plugin)
l = hook.hello(arg=3)
assert l == [4]
assert not hasattr(hook, 'world')
pm.unregister(plugin)
assert hook.hello(arg=3) == []
def test_argmismatch(self, pm):
class Api:
@hookspec
def hello(self, arg):
"api hook 1"
pm.add_hookspecs(Api)
class Plugin:
@hookimpl
def hello(self, argwrong):
pass
with pytest.raises(PluginValidationError) as exc:
pm.register(Plugin())
assert "argwrong" in str(exc.value)
def test_only_kwargs(self, pm):
class Api:
@hookspec
def hello(self, arg):
"api hook 1"
pm.add_hookspecs(Api)
pytest.raises(TypeError, lambda: pm.hook.hello(3))
def test_firstresult_definition(self, pm):
class Api:
@hookspec(firstresult=True)
def hello(self, arg):
"api hook 1"
pm.add_hookspecs(Api)
class Plugin:
@hookimpl
def hello(self, arg):
return arg + 1
pm.register(Plugin())
res = pm.hook.hello(arg=3)
assert res == 4
class TestTracer:
def test_simple(self):
rootlogger = _TagTracer()
log = rootlogger.get("pytest")
log("hello")
l = []
rootlogger.setwriter(l.append)
log("world")
assert len(l) == 1
assert l[0] == "world [pytest]\n"
sublog = log.get("collection")
sublog("hello")
assert l[1] == "hello [pytest:collection]\n"
def test_indent(self):
rootlogger = _TagTracer()
log = rootlogger.get("1")
l = []
log.root.setwriter(lambda arg: l.append(arg))
log("hello")
log.root.indent += 1
log("line1")
log("line2")
log.root.indent += 1
log("line3")
log("line4")
log.root.indent -= 1
log("line5")
log.root.indent -= 1
log("last")
assert len(l) == 7
names = [x[:x.rfind(' [')] for x in l]
assert names == ['hello', ' line1', ' line2',
' line3', ' line4', ' line5', 'last']
def test_readable_output_dictargs(self):
rootlogger = _TagTracer()
out = rootlogger.format_message(['test'], [1])
assert out == ['1 [test]\n']
out2 = rootlogger.format_message(['test'], ['test', {'a': 1}])
assert out2 == [
'test [test]\n',
' a: 1\n'
]
def test_setprocessor(self):
rootlogger = _TagTracer()
log = rootlogger.get("1")
log2 = log.get("2")
assert log2.tags == tuple("12")
l = []
rootlogger.setprocessor(tuple("12"), lambda *args: l.append(args))
log("not seen")
log2("seen")
assert len(l) == 1
tags, args = l[0]
assert "1" in tags
assert "2" in tags
assert args == ("seen",)
l2 = []
rootlogger.setprocessor("1:2", lambda *args: l2.append(args))
log2("seen")
tags, args = l2[0]
assert args == ("seen",)
def test_setmyprocessor(self):
rootlogger = _TagTracer()
log = rootlogger.get("1")
log2 = log.get("2")
l = []
log2.setmyprocessor(lambda *args: l.append(args))
log("not seen")
assert not l
log2(42)
assert len(l) == 1
tags, args = l[0]
assert "1" in tags
assert "2" in tags
assert args == (42,)
|