Source

thg-qt-mq / backdoor.diff

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
# HG changeset patch
# User Yuya Nishihara <yuya@tcha.org>
# Date 1336279389 -32400
# Branch stable
# Node ID 39604ec2b6c2244e64441a58060357bfa1ca5947
# Parent 0574cf7d7941cee6a1a09fe765f890eca674177d
tests: add helper extension and client to control running thg process

It inclues tests/functional/thgbackdoor_test.py as a usage example.

diff --git a/contrib/thgbackdoor.py b/contrib/thgbackdoor.py
new file mode 100644
--- /dev/null
+++ b/contrib/thgbackdoor.py
@@ -0,0 +1,234 @@
+# thgbackdoor.py - server to execute arbitrary code on TortoiseHg
+#
+# Copyright 2012 Yuya Nishihara <yuya@tcha.org>
+#
+# This software may be used and distributed according to the terms of the
+# GNU General Public License version 2 or any later version.
+"""execute arbitrary code on TortoiseHg
+
+This extension allows to execute arbitrary Python code on running TortoiseHg
+process. This extension might be usable for automated test.
+
+To start the backdoor server, you must specify the server address by
+`THGBACKDOOR` environment variable. It must be a tcp address:port.
+
+Example::
+
+    % THGBACKDOOR=localhost:12345 thg --nofork -v
+    thgbackdoor: listening at 127.0.0.1:12345
+
+Messages are serialized as pickle stream.
+
+Request Messages:
+
+``('eval', expression)``
+    Evaluate the given expression.
+``('exec', code [, delay])``
+    Executes the given code. If delay [sec] is specified, the code will be
+    executed asynchronously after the given time interval.
+``('quit',)``
+    Quit the application.
+
+Response Messages:
+
+``('R', object)``
+    Return the result of `eval`. None for `exec` request.
+    If the object is unpicklable, `repr(object)` will be returned.
+``('E', type, value, tracebacklist)``
+    Exception and traceback information if error raised.
+
+Context of eval or exec:
+
+It imitates global/local contexts of `tortoisehg.run.qtrun`. So you can
+access to the current widget via `dlg` variable.
+
+But you should be careful about the scope of lambda or inner function:
+http://stackoverflow.com/questions/2749655/
+"""
+import os, traceback
+from PyQt4.QtCore import QByteArray, QObject, QTimer
+from PyQt4.QtCore import Qt, pyqtSignal, pyqtSlot
+from PyQt4.QtGui import QApplication
+from PyQt4.QtNetwork import QHostAddress, QTcpServer
+from mercurial import demandimport
+
+demandimport.disable()
+try:
+    import cPickle as pickle
+except ImportError:
+    import pickle
+try:
+    import cStringIO as StringIO
+except ImportError:
+    import StringIO
+try:
+    from tortoisehg.hgqt import run
+    _runavail = True
+except ImportError:
+    _runavail = False
+demandimport.enable()
+
+class BackDoorSession(QObject):
+    """Established backdoor session"""
+
+    def __init__(self, context, io, parent=None):
+        super(BackDoorSession, self).__init__(parent)
+        self._io = io
+        self._io.readyRead.connect(self._handleread)
+        self._readq = QByteArray()
+        self._msgq = []
+        self._context = context.copy()
+
+    @pyqtSlot()
+    def _handleread(self):
+        self._readq.append(self._io.readAll())
+        f = StringIO.StringIO(self._readq.data())
+        readp = 0
+        try:
+            while True:
+                try:
+                    self._msgq.append(pickle.load(f))
+                    readp = f.tell()
+                except (EOFError, ValueError):  # partial data received
+                    break
+        finally:
+            self._readq.remove(0, readp)
+            # not do much things at readyRead slot
+            QTimer.singleShot(0, self._processmsgs)
+
+    @pyqtSlot()
+    def _processmsgs(self):
+        while self._msgq:
+            args = list(self._msgq.pop(0))
+            try:
+                req = args.pop(0)
+                r = self._reqtable[req](self, *args)
+                self._dumpresult(r)
+            except Exception:
+                QTimer.singleShot(0, self._processmsgs)
+                raise
+
+    def _processeval(self, expression):
+        return eval(expression, self._context)
+
+    def _processexec(self, code, delay=None):
+        if delay is None:
+            exec code in self._context
+        else:
+            def runcode():
+                exec code in self._context
+            QTimer.singleShot(int(delay * 1000), runcode)
+
+    def _processquit(self):
+        # postpone to next event loop so that response message can be sent
+        def quitgracefully():
+            QApplication.closeAllWindows()
+            QApplication.quit()  # in case quitOnLastWindowClosed is False
+        QTimer.singleShot(0, quitgracefully)
+
+    _reqtable = {
+        'eval': _processeval,
+        'exec': _processexec,
+        'quit': _processquit,
+        }
+
+    def _dumpresult(self, r):
+        try:
+            dr = pickle.dumps(('R', r))
+        except (pickle.PicklingError, TypeError):  # fail-safe
+            dr = pickle.dumps(('R', repr(r)))
+        self._io.write(dr)
+
+    @pyqtSlot(object, object, object)
+    def dumpexcinfo(self, et, ev, tb):
+        try:
+            # traceback object cannot be pickled
+            pickle.dump(('E', et, ev, traceback.extract_tb(tb)), self._io)
+        except Exception:  # avoid multiple exception
+            pass
+
+class BackDoorServer(QObject):
+    """Manages TCP server and established session"""
+    _excinfogot = pyqtSignal(object, object, object)
+
+    def __init__(self, ui, parent=None):
+        super(BackDoorServer, self).__init__(parent)
+        self._ui = ui
+        self._context = {}
+        self._sock = None  # should be assigned later
+
+    def updatecontext(self, context):
+        self._context.update(context)
+
+    def listen(self, address):
+        """Start listening at the specified address"""
+        if self._sock:
+            raise ValueError('already listening')
+        host, port = address.split(':', 1)
+        if host == 'localhost':
+            host = '127.0.0.1'
+        port = int(port)
+        # Why not unix domain socket? Because Windows never support it.
+        self._sock = sock = QTcpServer(self)
+        sock.newConnection.connect(self._handleconnection)
+        if sock.listen(QHostAddress(host), port):
+            self._ui.note('thgbackdoor: listening at %s:%d\n'
+                          % (sock.serverAddress().toString(),
+                             sock.serverPort()))
+        else:
+            self._ui.warn('thgbackdoor: failed to listen at %s:%d\n'
+                          % (host, port))
+
+    @pyqtSlot()
+    def _handleconnection(self):
+        while self._sock.hasPendingConnections():
+            self._ui.note('thgbackdoor: new connection\n')
+            conn = self._sock.nextPendingConnection()
+            session = BackDoorSession(self._context, conn, parent=self)
+            self._excinfogot.connect(session.dumpexcinfo)
+            conn.disconnected.connect(session.deleteLater)
+
+    def close(self):
+        self._context.clear()
+        if self._sock:
+            self._sock.close()
+            self._sock.deleteLater()
+            self._sock = None
+
+    @pyqtSlot(object, object, object)
+    def notifyexcinfo(self, etype, evalue, traceback):
+        self._excinfogot.emit(etype, evalue, traceback)
+
+def wrapqtrun(ui, qtrun):
+    class BackDoorQtRunner(qtrun.__class__):
+        def __call__(self, dlgfunc, ui, *args, **opts):
+            self._backdoorserver.updatecontext(vars(run))
+            self._backdoorserver.updatecontext(locals())
+
+            def xdlgfunc(ui, *args, **opts):
+                dlg = dlgfunc(ui, *args, **opts)
+                self._backdoorserver.updatecontext({'dlg': dlg})
+                # TODO use command-line option instead?
+                address = os.environ.get('THGBACKDOOR') or ''
+                self._backdoorserver.listen(address)
+                return dlg
+            xdlgfunc.func_name = dlgfunc.func_name
+
+            try:
+                return super(BackDoorQtRunner, self).__call__(
+                    xdlgfunc, ui, *args, **opts)
+            finally:
+                self._backdoorserver.close()
+
+    qtrun.__class__ = BackDoorQtRunner
+
+    # work around thg's stderr hack
+    lui = ui.copy()
+    lui.ferr = os.fdopen(2, 'w')
+    qtrun._backdoorserver = server = BackDoorServer(lui, parent=qtrun)
+    qtrun._exceptionOccured.connect(server.notifyexcinfo, Qt.QueuedConnection)
+
+def uisetup(ui):
+    if not _runavail:
+        return  # not a thg
+    wrapqtrun(ui, run.qtrun)
diff --git a/tests/functional/__init__.py b/tests/functional/__init__.py
new file mode 100644
--- /dev/null
+++ b/tests/functional/__init__.py
@@ -0,0 +1,7 @@
+"""Test functionality of the application by actually running it"""
+from nose.plugins.skip import SkipTest
+from PyQt4.QtGui import QApplication
+
+def setup():
+    if QApplication.type() != QApplication.GuiClient:
+        raise SkipTest
diff --git a/tests/functional/thgbackdoor_test.py b/tests/functional/thgbackdoor_test.py
new file mode 100644
--- /dev/null
+++ b/tests/functional/thgbackdoor_test.py
@@ -0,0 +1,62 @@
+"""Test basic functionality of thgbackdoor extension and ThgClient"""
+import os, socket, time, unittest
+from nose.tools import *
+
+import helpers
+
+class ThgBackDoorTest(unittest.TestCase):
+    def setUp(self):
+        self.thg = helpers.openthg()
+
+    def tearDown(self):
+        self.thg.close()
+
+    def test_run_workbench(self):
+        self.assertTrue(
+            'tortoisehg.hgqt.workbench' in self.thg.eval('repr(dlg)'))
+
+    def test_control_by_qtest(self):
+        # This opens modal dialog. Without delay=0, the execution blocks
+        # response until the dialog closed.
+        self.thg.exec_('''
+        QTest.qWaitForWindowShown(dlg)
+        QTest.keyClick(dlg, "N", Qt.ControlModifier)
+        ''', delay=0)
+        # introduce a helper function?
+        for _i in xrange(5):
+            time.sleep(0.1)
+            aw = self.thg.eval('QApplication.activeModalWidget()'
+                               '.__class__.__name__')
+            if aw == 'InitDialog':
+                break
+        else:
+            self.fail('failed to open InitDialog by Ctrl+N')
+
+    def test_raise_exception(self):
+        self.assertRaises(helpers.ThgRemoteError,
+                          lambda: self.thg.exec_('raise Exception("oops")'))
+
+    def test_raise_delayed_exception(self):
+        self.thg.exec_('raise Exception("oops")', delay=0)
+        self.assertRaises(helpers.ThgRemoteError, lambda: self.thg.wait())
+
+    def test_timeout(self):
+        self.thg.settimeout(1)
+        self.assertRaises(socket.timeout, lambda: self.thg.wait())
+
+def test_openaboutdialog():
+    thg = helpers.openthg(['about'])
+    try:
+        thg.exec_('QTest.qWaitForWindowShown(dlg)')
+        assert_equals('About', thg.eval('dlg.windowTitle()'))
+    finally:
+        thg.close()
+
+def test_homedir():
+    homedir = helpers.mktmpdir(__name__)
+    thg = helpers.openthg(homedir=homedir)
+    try:
+        assert_equals(homedir, thg.homedir)
+        assert os.path.exists(os.path.join(homedir, '.hgrc'))
+    finally:
+        thg.close()
diff --git a/tests/helpers.py b/tests/helpers.py
--- a/tests/helpers.py
+++ b/tests/helpers.py
@@ -1,5 +1,9 @@
 """Helper functions or classes imported from test case"""
-import os, tempfile
+import errno, os, shutil, socket, subprocess, sys, tempfile, time
+try:
+    import cPickle as pickle
+except ImportError:
+    import pickle
 try:
     import cStringIO as StringIO
 except ImportError:
@@ -151,3 +155,219 @@ class HgClient(object):
         if path.startswith('/'):
             raise ValueError('not a relative path: %s' % path)
         return os.path.join(self.path, path)
+
+def _cleancode(code):
+    r"""Clean up indentation of multi-line code text
+
+    >>> _cleancode('')
+    ''
+    >>> _cleancode('''
+    ...            while True:
+    ...                do_something()
+    ...            ''')
+    '\nwhile True:\n    do_something()\n'
+    """
+    if not isinstance(code, basestring) or not code:
+        return code
+    # simplified version of inspect.cleandoc() which requires Python>=2.6
+    lines = code.splitlines()
+    margin = sys.maxint
+    for l in lines[1:]:
+        n = len(l.lstrip())
+        if n:
+            margin = min(margin, len(l) - n)
+    if margin == sys.maxint:
+        return code
+    return lines[0] + '\n' + '\n'.join(l[margin:] for l in lines[1:])
+
+class ThgRemoteError(Exception):
+    """Raised if got exception from remote thg process"""
+
+    def __init__(self, etype, evalue, tracebacklist):
+        super(ThgRemoteError, self).__init__(etype, evalue, tracebacklist)
+        self.etype = etype
+        self.evalue = evalue
+        self.tracebacklist = tracebacklist
+
+class ThgController(object):
+    """Control thg window via channel opened by thgbackdoor extension
+
+    For details, see contrib/thgbackdoor.py.
+    """
+
+    def __init__(self, address, timeout=None):
+        self._address = address
+        self._timeout = timeout
+        self._sock = None
+
+    def open(self):
+        if self._sock:
+            raise ValueError('already open')
+        self._sock = socket.socket()
+        self._sock.settimeout(self._timeout)
+        self._recvq = ''
+
+        # dirty hack to wait server wake up
+        endtime = time.clock() + (self._timeout or 60.)
+        while True:
+            time.sleep(0.1)
+            try:
+                self._sock.connect(self._address)
+                break
+            except socket.error, err:
+                if (err.errno not in (errno.ECONNREFUSED, errno.ECONNABORTED)
+                    or time.clock() >= endtime):
+                    raise
+
+    def close(self):
+        if not self._sock:
+            return
+        self._sock.close()
+        self._sock = None
+
+    def eval(self, expression):
+        self._sendmsg(('eval', _cleancode(expression)))
+        return self.wait()
+
+    def exec_(self, code, delay=None):
+        self._sendmsg(('exec', _cleancode(code), delay))
+        return self.wait()
+
+    def quit(self):
+        self._sendmsg(('quit',))
+        self.wait()
+
+    def _sendmsg(self, msg):
+        if not self._sock:
+            raise ValueError('not open')
+        self._sock.sendall(pickle.dumps(msg))
+
+    def wait(self):
+        """Wait some response"""
+        if not self._sock:
+            raise ValueError('not open')
+        while True:
+            msg = self._popmsg()
+            if msg:
+                return self._processmsg(msg)
+            self._recvone()
+
+    def _popmsg(self):
+        f = StringIO.StringIO(self._recvq)
+        try:
+            msg = pickle.load(f)
+            self._recvq = self._recvq[f.tell():]
+            return msg
+        except (EOFError, ValueError):  # partial data received
+            return None
+
+    def _recvone(self):
+        data = self._sock.recv(4096)
+        if not data:
+            raise EOFError
+        self._recvq += data
+
+    def _processmsg(self, msg):
+        args = list(msg)
+        resp = args.pop(0)
+        if resp == 'R':
+            if len(args) != 1:
+                raise ValueError('unexpected message: %r' % msg)
+            return args[0]
+        elif resp == 'E':
+            etype, evalue, tracebacklist = args
+            raise ThgRemoteError(etype, evalue, tracebacklist)
+        else:
+            raise ValueError('unexpected message: %r' % msg)
+
+    def gettimeout(self):
+        return self._timeout
+
+    def settimeout(self, sec):
+        self._timeout = sec
+        if self._sock:
+            self._sock.settimeout(self._timeout)
+
+class ThgClient(object):
+    """Start thg process with backdoor channel"""
+
+    def __init__(self, address, homedir=None, cmdargs=None, timeout=None):
+        self._address = address
+        self._cmdargs = cmdargs
+        self._homedir = homedir
+        self._proc = None
+        self._controller = ThgController(address, timeout=timeout)
+
+    @property
+    def homedir(self):
+        return self._homedir
+
+    @property
+    def configdir(self):
+        return os.path.join(self._homedir, '.config')
+
+    def open(self):
+        if self._proc:
+            raise ValueError('already open')
+
+        if not self._homedir:
+            self._homedir = mktmpdir('thgclient-')
+        newhgrc = os.path.join(self._homedir, '.hgrc')
+        if (os.path.exists(os.environ['HGRCPATH'])
+            and not os.path.exists(newhgrc)):
+            shutil.copy(os.environ['HGRCPATH'], newhgrc)
+
+        # TODO: use --config=extensions.thgbackdoor=... once implemented
+        f = open(newhgrc, 'a')
+        try:
+            f.write('\n[extensions]\n')
+            f.write('thgbackdoor = %s\n'
+                    % os.path.join(os.environ['THGPATH'], 'contrib',
+                                   'thgbackdoor.py').replace(os.sep, '/'))
+        finally:
+            f.close()
+
+        if not os.path.exists(self.configdir):
+            os.mkdir(self.configdir)
+
+        env = os.environ.copy()
+        env['HOME'] = self._homedir
+        env['HGRCPATH'] = newhgrc
+        env['APPDATA'] = env['XDG_CONFIG_HOME'] = self.configdir
+        env['THGBACKDOOR'] = '%s:%d' % self._address
+        env['QT4_IM_MODULE'] = env['QT_IM_MODULE'] = ''  # suppress warning
+
+        fullargs = [os.path.join(os.environ['THGPATH'], 'thg'), '--nofork']
+        if os.name == 'nt':
+            fullargs.insert(0, sys.executable)
+        if self._cmdargs:
+            fullargs.extend(self._cmdargs)
+        self._proc = subprocess.Popen(fullargs, cwd=self._homedir, env=env)
+        self._controller.open()
+
+    def close(self):
+        if not self._proc:
+            return
+        self._controller.quit()
+        self._controller.close()
+        self._proc.wait()
+        self._proc = None
+
+    def __getattr__(self, name):
+        if name in ('eval', 'exec_', 'wait', 'settimeout'):
+            return getattr(self._controller, name)
+        else:
+            raise AttributeError('%r object has no attribute %r'
+                                 % (self.__class__.__name__, name))
+
+def openthg(cmdargs=None, homedir=None, timeout=60, port=20059):
+    """Start thg process and return object to control it
+
+    :cmdargs: extra arguments to be passed to thg
+    :homedir: switch HOME (default: fresh temporary directory)
+    """
+    thg = ThgClient(('localhost', port), cmdargs=cmdargs, homedir=homedir,
+                    timeout=timeout)
+    thg.open()
+    thg.exec_('from PyQt4.QtTest import QTest')  # for convenience
+    return thg
diff --git a/tests/run-tests.py b/tests/run-tests.py
--- a/tests/run-tests.py
+++ b/tests/run-tests.py
@@ -5,6 +5,19 @@ To run all tests::
 
     % HGPATH=path/to/mercurial ./run-tests.py
 
+To run all tests except for time-consuming functional tests::
+
+    % HGPATH=path/to/mercurial ./run-tests.py -e functional
+
+To run without X display::
+
+    % HGPATH=path/to/mercurial xvfb-run ./run-tests.py
+
+or on separate X display::
+
+    % Xephyr :3 &
+    % DISPLAY=:3 HGPATH=path/to/mercurial xvfb-run ./run-tests.py
+
 For details, please see:
 
 - `./run-tests.py --help`