mock_tk.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. """Classes that replace tkinter gui objects used by an object being tested.
  2. A gui object is anything with a master or parent parameter, which is
  3. typically required in spite of what the doc strings say.
  4. """
  5. import re
  6. from _tkinter import TclError
  7. class Event:
  8. '''Minimal mock with attributes for testing event handlers.
  9. This is not a gui object, but is used as an argument for callbacks
  10. that access attributes of the event passed. If a callback ignores
  11. the event, other than the fact that is happened, pass 'event'.
  12. Keyboard, mouse, window, and other sources generate Event instances.
  13. Event instances have the following attributes: serial (number of
  14. event), time (of event), type (of event as number), widget (in which
  15. event occurred), and x,y (position of mouse). There are other
  16. attributes for specific events, such as keycode for key events.
  17. tkinter.Event.__doc__ has more but is still not complete.
  18. '''
  19. def __init__(self, **kwds):
  20. "Create event with attributes needed for test"
  21. self.__dict__.update(kwds)
  22. class Var:
  23. "Use for String/Int/BooleanVar: incomplete"
  24. def __init__(self, master=None, value=None, name=None):
  25. self.master = master
  26. self.value = value
  27. self.name = name
  28. def set(self, value):
  29. self.value = value
  30. def get(self):
  31. return self.value
  32. class Mbox_func:
  33. """Generic mock for messagebox functions, which all have the same signature.
  34. Instead of displaying a message box, the mock's call method saves the
  35. arguments as instance attributes, which test functions can then examine.
  36. The test can set the result returned to ask function
  37. """
  38. def __init__(self, result=None):
  39. self.result = result # Return None for all show funcs
  40. def __call__(self, title, message, *args, **kwds):
  41. # Save all args for possible examination by tester
  42. self.title = title
  43. self.message = message
  44. self.args = args
  45. self.kwds = kwds
  46. return self.result # Set by tester for ask functions
  47. class Mbox:
  48. """Mock for tkinter.messagebox with an Mbox_func for each function.
  49. Example usage in test_module.py for testing functions in module.py:
  50. ---
  51. from idlelib.idle_test.mock_tk import Mbox
  52. import module
  53. orig_mbox = module.messagebox
  54. showerror = Mbox.showerror # example, for attribute access in test methods
  55. class Test(unittest.TestCase):
  56. @classmethod
  57. def setUpClass(cls):
  58. module.messagebox = Mbox
  59. @classmethod
  60. def tearDownClass(cls):
  61. module.messagebox = orig_mbox
  62. ---
  63. For 'ask' functions, set func.result return value before calling the method
  64. that uses the message function. When messagebox functions are the
  65. only GUI calls in a method, this replacement makes the method GUI-free,
  66. """
  67. askokcancel = Mbox_func() # True or False
  68. askquestion = Mbox_func() # 'yes' or 'no'
  69. askretrycancel = Mbox_func() # True or False
  70. askyesno = Mbox_func() # True or False
  71. askyesnocancel = Mbox_func() # True, False, or None
  72. showerror = Mbox_func() # None
  73. showinfo = Mbox_func() # None
  74. showwarning = Mbox_func() # None
  75. class Text:
  76. """A semi-functional non-gui replacement for tkinter.Text text editors.
  77. The mock's data model is that a text is a list of \n-terminated lines.
  78. The mock adds an empty string at the beginning of the list so that the
  79. index of actual lines start at 1, as with Tk. The methods never see this.
  80. Tk initializes files with a terminal \n that cannot be deleted. It is
  81. invisible in the sense that one cannot move the cursor beyond it.
  82. This class is only tested (and valid) with strings of ascii chars.
  83. For testing, we are not concerned with Tk Text's treatment of,
  84. for instance, 0-width characters or character + accent.
  85. """
  86. def __init__(self, master=None, cnf={}, **kw):
  87. '''Initialize mock, non-gui, text-only Text widget.
  88. At present, all args are ignored. Almost all affect visual behavior.
  89. There are just a few Text-only options that affect text behavior.
  90. '''
  91. self.data = ['', '\n']
  92. def index(self, index):
  93. "Return string version of index decoded according to current text."
  94. return "%s.%s" % self._decode(index, endflag=1)
  95. def _decode(self, index, endflag=0):
  96. """Return a (line, char) tuple of int indexes into self.data.
  97. This implements .index without converting the result back to a string.
  98. The result is constrained by the number of lines and linelengths of
  99. self.data. For many indexes, the result is initially (1, 0).
  100. The input index may have any of several possible forms:
  101. * line.char float: converted to 'line.char' string;
  102. * 'line.char' string, where line and char are decimal integers;
  103. * 'line.char lineend', where lineend='lineend' (and char is ignored);
  104. * 'line.end', where end='end' (same as above);
  105. * 'insert', the positions before terminal \n;
  106. * 'end', whose meaning depends on the endflag passed to ._endex.
  107. * 'sel.first' or 'sel.last', where sel is a tag -- not implemented.
  108. """
  109. if isinstance(index, (float, bytes)):
  110. index = str(index)
  111. try:
  112. index=index.lower()
  113. except AttributeError:
  114. raise TclError('bad text index "%s"' % index) from None
  115. lastline = len(self.data) - 1 # same as number of text lines
  116. if index == 'insert':
  117. return lastline, len(self.data[lastline]) - 1
  118. elif index == 'end':
  119. return self._endex(endflag)
  120. line, char = index.split('.')
  121. line = int(line)
  122. # Out of bounds line becomes first or last ('end') index
  123. if line < 1:
  124. return 1, 0
  125. elif line > lastline:
  126. return self._endex(endflag)
  127. linelength = len(self.data[line]) -1 # position before/at \n
  128. if char.endswith(' lineend') or char == 'end':
  129. return line, linelength
  130. # Tk requires that ignored chars before ' lineend' be valid int
  131. if m := re.fullmatch(r'end-(\d*)c', char, re.A): # Used by hyperparser.
  132. return line, linelength - int(m.group(1))
  133. # Out of bounds char becomes first or last index of line
  134. char = int(char)
  135. if char < 0:
  136. char = 0
  137. elif char > linelength:
  138. char = linelength
  139. return line, char
  140. def _endex(self, endflag):
  141. '''Return position for 'end' or line overflow corresponding to endflag.
  142. -1: position before terminal \n; for .insert(), .delete
  143. 0: position after terminal \n; for .get, .delete index 1
  144. 1: same viewed as beginning of non-existent next line (for .index)
  145. '''
  146. n = len(self.data)
  147. if endflag == 1:
  148. return n, 0
  149. else:
  150. n -= 1
  151. return n, len(self.data[n]) + endflag
  152. def insert(self, index, chars):
  153. "Insert chars before the character at index."
  154. if not chars: # ''.splitlines() is [], not ['']
  155. return
  156. chars = chars.splitlines(True)
  157. if chars[-1][-1] == '\n':
  158. chars.append('')
  159. line, char = self._decode(index, -1)
  160. before = self.data[line][:char]
  161. after = self.data[line][char:]
  162. self.data[line] = before + chars[0]
  163. self.data[line+1:line+1] = chars[1:]
  164. self.data[line+len(chars)-1] += after
  165. def get(self, index1, index2=None):
  166. "Return slice from index1 to index2 (default is 'index1+1')."
  167. startline, startchar = self._decode(index1)
  168. if index2 is None:
  169. endline, endchar = startline, startchar+1
  170. else:
  171. endline, endchar = self._decode(index2)
  172. if startline == endline:
  173. return self.data[startline][startchar:endchar]
  174. else:
  175. lines = [self.data[startline][startchar:]]
  176. for i in range(startline+1, endline):
  177. lines.append(self.data[i])
  178. lines.append(self.data[endline][:endchar])
  179. return ''.join(lines)
  180. def delete(self, index1, index2=None):
  181. '''Delete slice from index1 to index2 (default is 'index1+1').
  182. Adjust default index2 ('index+1) for line ends.
  183. Do not delete the terminal \n at the very end of self.data ([-1][-1]).
  184. '''
  185. startline, startchar = self._decode(index1, -1)
  186. if index2 is None:
  187. if startchar < len(self.data[startline])-1:
  188. # not deleting \n
  189. endline, endchar = startline, startchar+1
  190. elif startline < len(self.data) - 1:
  191. # deleting non-terminal \n, convert 'index1+1 to start of next line
  192. endline, endchar = startline+1, 0
  193. else:
  194. # do not delete terminal \n if index1 == 'insert'
  195. return
  196. else:
  197. endline, endchar = self._decode(index2, -1)
  198. # restricting end position to insert position excludes terminal \n
  199. if startline == endline and startchar < endchar:
  200. self.data[startline] = self.data[startline][:startchar] + \
  201. self.data[startline][endchar:]
  202. elif startline < endline:
  203. self.data[startline] = self.data[startline][:startchar] + \
  204. self.data[endline][endchar:]
  205. startline += 1
  206. for i in range(startline, endline+1):
  207. del self.data[startline]
  208. def compare(self, index1, op, index2):
  209. line1, char1 = self._decode(index1)
  210. line2, char2 = self._decode(index2)
  211. if op == '<':
  212. return line1 < line2 or line1 == line2 and char1 < char2
  213. elif op == '<=':
  214. return line1 < line2 or line1 == line2 and char1 <= char2
  215. elif op == '>':
  216. return line1 > line2 or line1 == line2 and char1 > char2
  217. elif op == '>=':
  218. return line1 > line2 or line1 == line2 and char1 >= char2
  219. elif op == '==':
  220. return line1 == line2 and char1 == char2
  221. elif op == '!=':
  222. return line1 != line2 or char1 != char2
  223. else:
  224. raise TclError('''bad comparison operator "%s": '''
  225. '''must be <, <=, ==, >=, >, or !=''' % op)
  226. # The following Text methods normally do something and return None.
  227. # Whether doing nothing is sufficient for a test will depend on the test.
  228. def mark_set(self, name, index):
  229. "Set mark *name* before the character at index."
  230. pass
  231. def mark_unset(self, *markNames):
  232. "Delete all marks in markNames."
  233. def tag_remove(self, tagName, index1, index2=None):
  234. "Remove tag tagName from all characters between index1 and index2."
  235. pass
  236. # The following Text methods affect the graphics screen and return None.
  237. # Doing nothing should always be sufficient for tests.
  238. def scan_dragto(self, x, y):
  239. "Adjust the view of the text according to scan_mark"
  240. def scan_mark(self, x, y):
  241. "Remember the current X, Y coordinates."
  242. def see(self, index):
  243. "Scroll screen to make the character at INDEX is visible."
  244. pass
  245. # The following is a Misc method inherited by Text.
  246. # It should properly go in a Misc mock, but is included here for now.
  247. def bind(sequence=None, func=None, add=None):
  248. "Bind to this widget at event sequence a call to function func."
  249. pass
  250. class Entry:
  251. "Mock for tkinter.Entry."
  252. def focus_set(self):
  253. pass