test_calltip.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. "Test calltip, coverage 60%"
  2. from idlelib import calltip
  3. import unittest
  4. import textwrap
  5. import types
  6. import re
  7. # Test Class TC is used in multiple get_argspec test methods
  8. class TC():
  9. 'doc'
  10. tip = "(ai=None, *b)"
  11. def __init__(self, ai=None, *b): 'doc'
  12. __init__.tip = "(self, ai=None, *b)"
  13. def t1(self): 'doc'
  14. t1.tip = "(self)"
  15. def t2(self, ai, b=None): 'doc'
  16. t2.tip = "(self, ai, b=None)"
  17. def t3(self, ai, *args): 'doc'
  18. t3.tip = "(self, ai, *args)"
  19. def t4(self, *args): 'doc'
  20. t4.tip = "(self, *args)"
  21. def t5(self, ai, b=None, *args, **kw): 'doc'
  22. t5.tip = "(self, ai, b=None, *args, **kw)"
  23. def t6(no, self): 'doc'
  24. t6.tip = "(no, self)"
  25. def __call__(self, ci): 'doc'
  26. __call__.tip = "(self, ci)"
  27. def nd(self): pass # No doc.
  28. # attaching .tip to wrapped methods does not work
  29. @classmethod
  30. def cm(cls, a): 'doc'
  31. @staticmethod
  32. def sm(b): 'doc'
  33. tc = TC()
  34. default_tip = calltip._default_callable_argspec
  35. get_spec = calltip.get_argspec
  36. class Get_argspecTest(unittest.TestCase):
  37. # The get_spec function must return a string, even if blank.
  38. # Test a variety of objects to be sure that none cause it to raise
  39. # (quite aside from getting as correct an answer as possible).
  40. # The tests of builtins may break if inspect or the docstrings change,
  41. # but a red buildbot is better than a user crash (as has happened).
  42. # For a simple mismatch, change the expected output to the actual.
  43. def test_builtins(self):
  44. def tiptest(obj, out):
  45. self.assertEqual(get_spec(obj), out)
  46. # Python class that inherits builtin methods
  47. class List(list): "List() doc"
  48. # Simulate builtin with no docstring for default tip test
  49. class SB: __call__ = None
  50. if List.__doc__ is not None:
  51. tiptest(List,
  52. f'(iterable=(), /){calltip._argument_positional}'
  53. f'\n{List.__doc__}')
  54. tiptest(list.__new__,
  55. '(*args, **kwargs)\n'
  56. 'Create and return a new object. '
  57. 'See help(type) for accurate signature.')
  58. tiptest(list.__init__,
  59. '(self, /, *args, **kwargs)'
  60. + calltip._argument_positional + '\n' +
  61. 'Initialize self. See help(type(self)) for accurate signature.')
  62. append_doc = (calltip._argument_positional
  63. + "\nAppend object to the end of the list.")
  64. tiptest(list.append, '(self, object, /)' + append_doc)
  65. tiptest(List.append, '(self, object, /)' + append_doc)
  66. tiptest([].append, '(object, /)' + append_doc)
  67. tiptest(types.MethodType, "method(function, instance)")
  68. tiptest(SB(), default_tip)
  69. p = re.compile('')
  70. tiptest(re.sub, '''\
  71. (pattern, repl, string, count=0, flags=0)
  72. Return the string obtained by replacing the leftmost
  73. non-overlapping occurrences of the pattern in string by the
  74. replacement repl. repl can be either a string or a callable;
  75. if a string, backslash escapes in it are processed. If it is
  76. a callable, it's passed the Match object and must return''')
  77. tiptest(p.sub, '''\
  78. (repl, string, count=0)
  79. Return the string obtained by replacing the leftmost \
  80. non-overlapping occurrences o...''')
  81. def test_signature_wrap(self):
  82. if textwrap.TextWrapper.__doc__ is not None:
  83. self.assertEqual(get_spec(textwrap.TextWrapper), '''\
  84. (width=70, initial_indent='', subsequent_indent='', expand_tabs=True,
  85. replace_whitespace=True, fix_sentence_endings=False, break_long_words=True,
  86. drop_whitespace=True, break_on_hyphens=True, tabsize=8, *, max_lines=None,
  87. placeholder=' [...]')''')
  88. def test_properly_formated(self):
  89. def foo(s='a'*100):
  90. pass
  91. def bar(s='a'*100):
  92. """Hello Guido"""
  93. pass
  94. def baz(s='a'*100, z='b'*100):
  95. pass
  96. indent = calltip._INDENT
  97. sfoo = "(s='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"\
  98. "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + indent + "aaaaaaaaa"\
  99. "aaaaaaaaaa')"
  100. sbar = "(s='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"\
  101. "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + indent + "aaaaaaaaa"\
  102. "aaaaaaaaaa')\nHello Guido"
  103. sbaz = "(s='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"\
  104. "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + indent + "aaaaaaaaa"\
  105. "aaaaaaaaaa', z='bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"\
  106. "bbbbbbbbbbbbbbbbb\n" + indent + "bbbbbbbbbbbbbbbbbbbbbb"\
  107. "bbbbbbbbbbbbbbbbbbbbbb')"
  108. for func,doc in [(foo, sfoo), (bar, sbar), (baz, sbaz)]:
  109. with self.subTest(func=func, doc=doc):
  110. self.assertEqual(get_spec(func), doc)
  111. def test_docline_truncation(self):
  112. def f(): pass
  113. f.__doc__ = 'a'*300
  114. self.assertEqual(get_spec(f), f"()\n{'a'*(calltip._MAX_COLS-3) + '...'}")
  115. def test_multiline_docstring(self):
  116. # Test fewer lines than max.
  117. self.assertEqual(get_spec(range),
  118. "range(stop) -> range object\n"
  119. "range(start, stop[, step]) -> range object")
  120. # Test max lines
  121. self.assertEqual(get_spec(bytes), '''\
  122. bytes(iterable_of_ints) -> bytes
  123. bytes(string, encoding[, errors]) -> bytes
  124. bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
  125. bytes(int) -> bytes object of size given by the parameter initialized with null bytes
  126. bytes() -> empty bytes object''')
  127. # Test more than max lines
  128. def f(): pass
  129. f.__doc__ = 'a\n' * 15
  130. self.assertEqual(get_spec(f), '()' + '\na' * calltip._MAX_LINES)
  131. def test_functions(self):
  132. def t1(): 'doc'
  133. t1.tip = "()"
  134. def t2(a, b=None): 'doc'
  135. t2.tip = "(a, b=None)"
  136. def t3(a, *args): 'doc'
  137. t3.tip = "(a, *args)"
  138. def t4(*args): 'doc'
  139. t4.tip = "(*args)"
  140. def t5(a, b=None, *args, **kw): 'doc'
  141. t5.tip = "(a, b=None, *args, **kw)"
  142. doc = '\ndoc' if t1.__doc__ is not None else ''
  143. for func in (t1, t2, t3, t4, t5, TC):
  144. with self.subTest(func=func):
  145. self.assertEqual(get_spec(func), func.tip + doc)
  146. def test_methods(self):
  147. doc = '\ndoc' if TC.__doc__ is not None else ''
  148. for meth in (TC.t1, TC.t2, TC.t3, TC.t4, TC.t5, TC.t6, TC.__call__):
  149. with self.subTest(meth=meth):
  150. self.assertEqual(get_spec(meth), meth.tip + doc)
  151. self.assertEqual(get_spec(TC.cm), "(a)" + doc)
  152. self.assertEqual(get_spec(TC.sm), "(b)" + doc)
  153. def test_bound_methods(self):
  154. # test that first parameter is correctly removed from argspec
  155. doc = '\ndoc' if TC.__doc__ is not None else ''
  156. for meth, mtip in ((tc.t1, "()"), (tc.t4, "(*args)"),
  157. (tc.t6, "(self)"), (tc.__call__, '(ci)'),
  158. (tc, '(ci)'), (TC.cm, "(a)"),):
  159. with self.subTest(meth=meth, mtip=mtip):
  160. self.assertEqual(get_spec(meth), mtip + doc)
  161. def test_starred_parameter(self):
  162. # test that starred first parameter is *not* removed from argspec
  163. class C:
  164. def m1(*args): pass
  165. c = C()
  166. for meth, mtip in ((C.m1, '(*args)'), (c.m1, "(*args)"),):
  167. with self.subTest(meth=meth, mtip=mtip):
  168. self.assertEqual(get_spec(meth), mtip)
  169. def test_invalid_method_get_spec(self):
  170. class C:
  171. def m2(**kwargs): pass
  172. class Test:
  173. def __call__(*, a): pass
  174. mtip = calltip._invalid_method
  175. self.assertEqual(get_spec(C().m2), mtip)
  176. self.assertEqual(get_spec(Test()), mtip)
  177. def test_non_ascii_name(self):
  178. # test that re works to delete a first parameter name that
  179. # includes non-ascii chars, such as various forms of A.
  180. uni = "(A\u0391\u0410\u05d0\u0627\u0905\u1e00\u3042, a)"
  181. assert calltip._first_param.sub('', uni) == '(a)'
  182. def test_no_docstring(self):
  183. for meth, mtip in ((TC.nd, "(self)"), (tc.nd, "()")):
  184. with self.subTest(meth=meth, mtip=mtip):
  185. self.assertEqual(get_spec(meth), mtip)
  186. def test_attribute_exception(self):
  187. class NoCall:
  188. def __getattr__(self, name):
  189. raise BaseException
  190. class CallA(NoCall):
  191. def __call__(oui, a, b, c):
  192. pass
  193. class CallB(NoCall):
  194. def __call__(self, ci):
  195. pass
  196. for meth, mtip in ((NoCall, default_tip), (CallA, default_tip),
  197. (NoCall(), ''), (CallA(), '(a, b, c)'),
  198. (CallB(), '(ci)')):
  199. with self.subTest(meth=meth, mtip=mtip):
  200. self.assertEqual(get_spec(meth), mtip)
  201. def test_non_callables(self):
  202. for obj in (0, 0.0, '0', b'0', [], {}):
  203. with self.subTest(obj=obj):
  204. self.assertEqual(get_spec(obj), '')
  205. class Get_entityTest(unittest.TestCase):
  206. def test_bad_entity(self):
  207. self.assertIsNone(calltip.get_entity('1/0'))
  208. def test_good_entity(self):
  209. self.assertIs(calltip.get_entity('int'), int)
  210. if __name__ == '__main__':
  211. unittest.main(verbosity=2)