mock_tk.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. class Event:
  6. '''Minimal mock with attributes for testing event handlers.
  7. This is not a gui object, but is used as an argument for callbacks
  8. that access attributes of the event passed. If a callback ignores
  9. the event, other than the fact that is happened, pass 'event'.
  10. Keyboard, mouse, window, and other sources generate Event instances.
  11. Event instances have the following attributes: serial (number of
  12. event), time (of event), type (of event as number), widget (in which
  13. event occurred), and x,y (position of mouse). There are other
  14. attributes for specific events, such as keycode for key events.
  15. tkinter.Event.__doc__ has more but is still not complete.
  16. '''
  17. def __init__(self, **kwds):
  18. "Create event with attributes needed for test"
  19. self.__dict__.update(kwds)
  20. class Var:
  21. "Use for String/Int/BooleanVar: incomplete"
  22. def __init__(self, master=None, value=None, name=None):
  23. self.master = master
  24. self.value = value
  25. self.name = name
  26. def set(self, value):
  27. self.value = value
  28. def get(self):
  29. return self.value
  30. class Mbox_func:
  31. """Generic mock for messagebox functions, which all have the same signature.
  32. Instead of displaying a message box, the mock's call method saves the
  33. arguments as instance attributes, which test functions can then examine.
  34. The test can set the result returned to ask function
  35. """
  36. def __init__(self, result=None):
  37. self.result = result # Return None for all show funcs
  38. def __call__(self, title, message, *args, **kwds):
  39. # Save all args for possible examination by tester
  40. self.title = title
  41. self.message = message
  42. self.args = args
  43. self.kwds = kwds
  44. return self.result # Set by tester for ask functions
  45. class Mbox:
  46. """Mock for tkinter.messagebox with an Mbox_func for each function.
  47. This module was 'tkMessageBox' in 2.x; hence the 'import as' in 3.x.
  48. Example usage in test_module.py for testing functions in module.py:
  49. ---
  50. from idlelib.idle_test.mock_tk import Mbox
  51. import module
  52. orig_mbox = module.tkMessageBox
  53. showerror = Mbox.showerror # example, for attribute access in test methods
  54. class Test(unittest.TestCase):
  55. @classmethod
  56. def setUpClass(cls):
  57. module.tkMessageBox = Mbox
  58. @classmethod
  59. def tearDownClass(cls):
  60. module.tkMessageBox = orig_mbox
  61. ---
  62. For 'ask' functions, set func.result return value before calling the method
  63. that uses the message function. When tkMessageBox functions are the
  64. only gui alls in a method, this replacement makes the method gui-free,
  65. """
  66. askokcancel = Mbox_func() # True or False
  67. askquestion = Mbox_func() # 'yes' or 'no'
  68. askretrycancel = Mbox_func() # True or False
  69. askyesno = Mbox_func() # True or False
  70. askyesnocancel = Mbox_func() # True, False, or None
  71. showerror = Mbox_func() # None
  72. showinfo = Mbox_func() # None
  73. showwarning = Mbox_func() # None
  74. from _tkinter import TclError
  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. # Out of bounds char becomes first or last index of line
  132. char = int(char)
  133. if char < 0:
  134. char = 0
  135. elif char > linelength:
  136. char = linelength
  137. return line, char
  138. def _endex(self, endflag):
  139. '''Return position for 'end' or line overflow corresponding to endflag.
  140. -1: position before terminal \n; for .insert(), .delete
  141. 0: position after terminal \n; for .get, .delete index 1
  142. 1: same viewed as beginning of non-existent next line (for .index)
  143. '''
  144. n = len(self.data)
  145. if endflag == 1:
  146. return n, 0
  147. else:
  148. n -= 1
  149. return n, len(self.data[n]) + endflag
  150. def insert(self, index, chars):
  151. "Insert chars before the character at index."
  152. if not chars: # ''.splitlines() is [], not ['']
  153. return
  154. chars = chars.splitlines(True)
  155. if chars[-1][-1] == '\n':
  156. chars.append('')
  157. line, char = self._decode(index, -1)
  158. before = self.data[line][:char]
  159. after = self.data[line][char:]
  160. self.data[line] = before + chars[0]
  161. self.data[line+1:line+1] = chars[1:]
  162. self.data[line+len(chars)-1] += after
  163. def get(self, index1, index2=None):
  164. "Return slice from index1 to index2 (default is 'index1+1')."
  165. startline, startchar = self._decode(index1)
  166. if index2 is None:
  167. endline, endchar = startline, startchar+1
  168. else:
  169. endline, endchar = self._decode(index2)
  170. if startline == endline:
  171. return self.data[startline][startchar:endchar]
  172. else:
  173. lines = [self.data[startline][startchar:]]
  174. for i in range(startline+1, endline):
  175. lines.append(self.data[i])
  176. lines.append(self.data[endline][:endchar])
  177. return ''.join(lines)
  178. def delete(self, index1, index2=None):
  179. '''Delete slice from index1 to index2 (default is 'index1+1').
  180. Adjust default index2 ('index+1) for line ends.
  181. Do not delete the terminal \n at the very end of self.data ([-1][-1]).
  182. '''
  183. startline, startchar = self._decode(index1, -1)
  184. if index2 is None:
  185. if startchar < len(self.data[startline])-1:
  186. # not deleting \n
  187. endline, endchar = startline, startchar+1
  188. elif startline < len(self.data) - 1:
  189. # deleting non-terminal \n, convert 'index1+1 to start of next line
  190. endline, endchar = startline+1, 0
  191. else:
  192. # do not delete terminal \n if index1 == 'insert'
  193. return
  194. else:
  195. endline, endchar = self._decode(index2, -1)
  196. # restricting end position to insert position excludes terminal \n
  197. if startline == endline and startchar < endchar:
  198. self.data[startline] = self.data[startline][:startchar] + \
  199. self.data[startline][endchar:]
  200. elif startline < endline:
  201. self.data[startline] = self.data[startline][:startchar] + \
  202. self.data[endline][endchar:]
  203. startline += 1
  204. for i in range(startline, endline+1):
  205. del self.data[startline]
  206. def compare(self, index1, op, index2):
  207. line1, char1 = self._decode(index1)
  208. line2, char2 = self._decode(index2)
  209. if op == '<':
  210. return line1 < line2 or line1 == line2 and char1 < char2
  211. elif 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 and char1 == char2
  219. elif op == '!=':
  220. return line1 != line2 or char1 != char2
  221. else:
  222. raise TclError('''bad comparison operator "%s": '''
  223. '''must be <, <=, ==, >=, >, or !=''' % op)
  224. # The following Text methods normally do something and return None.
  225. # Whether doing nothing is sufficient for a test will depend on the test.
  226. def mark_set(self, name, index):
  227. "Set mark *name* before the character at index."
  228. pass
  229. def mark_unset(self, *markNames):
  230. "Delete all marks in markNames."
  231. def tag_remove(self, tagName, index1, index2=None):
  232. "Remove tag tagName from all characters between index1 and index2."
  233. pass
  234. # The following Text methods affect the graphics screen and return None.
  235. # Doing nothing should always be sufficient for tests.
  236. def scan_dragto(self, x, y):
  237. "Adjust the view of the text according to scan_mark"
  238. def scan_mark(self, x, y):
  239. "Remember the current X, Y coordinates."
  240. def see(self, index):
  241. "Scroll screen to make the character at INDEX is visible."
  242. pass
  243. # The following is a Misc method inherited by Text.
  244. # It should properly go in a Misc mock, but is included here for now.
  245. def bind(sequence=None, func=None, add=None):
  246. "Bind to this widget at event sequence a call to function func."
  247. pass
  248. class Entry:
  249. "Mock for tkinter.Entry."
  250. def focus_set(self):
  251. pass