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