test_helpers.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. from functools import wraps
  2. from typing import Any
  3. from typing import Callable
  4. from typing import cast
  5. from typing import TypeVar
  6. from pluggy._hooks import varnames
  7. from pluggy._manager import _formatdef
  8. def test_varnames() -> None:
  9. def f(x) -> None:
  10. i = 3 # noqa
  11. class A:
  12. def f(self, y) -> None:
  13. pass
  14. class B:
  15. def __call__(self, z) -> None:
  16. pass
  17. assert varnames(f) == (("x",), ())
  18. assert varnames(A().f) == (("y",), ())
  19. assert varnames(B()) == (("z",), ())
  20. def test_varnames_default() -> None:
  21. def f(x, y=3) -> None:
  22. pass
  23. assert varnames(f) == (("x",), ("y",))
  24. def test_varnames_class() -> None:
  25. class C:
  26. def __init__(self, x) -> None:
  27. pass
  28. class D:
  29. pass
  30. class E:
  31. def __init__(self, x) -> None:
  32. pass
  33. class F:
  34. pass
  35. assert varnames(C) == (("x",), ())
  36. assert varnames(D) == ((), ())
  37. assert varnames(E) == (("x",), ())
  38. assert varnames(F) == ((), ())
  39. def test_varnames_keyword_only() -> None:
  40. def f1(x, *, y) -> None:
  41. pass
  42. def f2(x, *, y=3) -> None:
  43. pass
  44. def f3(x=1, *, y=3) -> None:
  45. pass
  46. assert varnames(f1) == (("x",), ())
  47. assert varnames(f2) == (("x",), ())
  48. assert varnames(f3) == ((), ("x",))
  49. def test_formatdef() -> None:
  50. def function1():
  51. pass
  52. assert _formatdef(function1) == "function1()"
  53. def function2(arg1):
  54. pass
  55. assert _formatdef(function2) == "function2(arg1)"
  56. def function3(arg1, arg2="qwe"):
  57. pass
  58. assert _formatdef(function3) == "function3(arg1, arg2='qwe')"
  59. def function4(arg1, *args, **kwargs):
  60. pass
  61. assert _formatdef(function4) == "function4(arg1, *args, **kwargs)"
  62. def test_varnames_decorator() -> None:
  63. F = TypeVar("F", bound=Callable[..., Any])
  64. def my_decorator(func: F) -> F:
  65. @wraps(func)
  66. def wrapper(*args, **kwargs):
  67. return func(*args, **kwargs)
  68. return cast(F, wrapper)
  69. @my_decorator
  70. def example(a, b=123) -> None:
  71. pass
  72. class Example:
  73. @my_decorator
  74. def example_method(self, x, y=1) -> None:
  75. pass
  76. ex_inst = Example()
  77. assert varnames(example) == (("a",), ("b",))
  78. assert varnames(Example.example_method) == (("x",), ("y",))
  79. assert varnames(ex_inst.example_method) == (("x",), ("y",))