def run(self):
     class HandleRequestInput:
         def RequestInput(self):
             return 'RequestInput: OK'
     
     handle_request_input = HandleRequestInput()
     
     import pydev_localhost
     print('Starting client with:', pydev_localhost.get_localhost(), self.client_port)
     client_server = SimpleXMLRPCServer((pydev_localhost.get_localhost(), self.client_port), logRequests=False)
     client_server.register_function(handle_request_input.RequestInput)
     client_server.serve_forever()
    def testServer(self):
        client_port, server_port = self.getFreeAddresses()

        class ServerThread(threading.Thread):
            def __init__(self, client_port, server_port):
                threading.Thread.__init__(self)
                self.client_port = client_port
                self.server_port = server_port

            def run(self):
                import pydev_localhost

                print('Starting server with:', pydev_localhost.get_localhost(), self.server_port, self.client_port)
                pydevconsole.StartServer(pydev_localhost.get_localhost(), self.server_port, self.client_port)

        server_thread = ServerThread(client_port, server_port)
        server_thread.setDaemon(True)
        server_thread.start()

        client_thread = self.startClientThread(client_port)  #@UnusedVariable

        import time

        time.sleep(.3)  #let's give it some time to start the threads

        import pydev_localhost

        server = xmlrpclib.Server('http://%s:%s' % (pydev_localhost.get_localhost(), server_port))
        server.addExec("import sys; print('Running with: %s %s' % (sys.executable or sys.platform, sys.version))")
        server.addExec('class Foo:')
        server.addExec('    pass')
        server.addExec('')
        server.addExec('foo = Foo()')
        server.addExec('a = %s()' % raw_input_name)
        server.addExec('print (a)')
    def __init__(self, tests_queue):
        threading.Thread.__init__(self)
        self.setDaemon(True)
        self.queue = tests_queue
        self.finished = False
        from pydev_imports import SimpleXMLRPCServer
        
        
        # This is a hack to patch slow socket.getfqdn calls that
        # BaseHTTPServer (and its subclasses) make.
        # See: http://bugs.python.org/issue6085
        # See: http://www.answermysearches.com/xmlrpc-server-slow-in-python-how-to-fix/2140/
        try:
            import BaseHTTPServer
            def _bare_address_string(self):
                host, port = self.client_address[:2]
                return '%s' % host
            BaseHTTPServer.BaseHTTPRequestHandler.address_string = _bare_address_string
            
        except:
            pass
        # End hack.


        # Create server
        
        import pydev_localhost
        server = SimpleXMLRPCServer((pydev_localhost.get_localhost(), 0), logRequests=False)
        server.register_function(self.GetTestsToRun)
        server.register_function(self.notifyStartTest)
        server.register_function(self.notifyTest)
        server.register_function(self.notifyCommands)
        self.port = server.socket.getsockname()[1]
        self.server = server
Esempio n. 4
0
        def do_connect_to_debugger():
            try:
                # Try to import the packages needed to attach the debugger
                import pydevd
                import _pydev_threading as threading

            except:
                # This happens on Jython embedded in host eclipse
                traceback.print_exc()
                sys.stderr.write('pydevd is not available, cannot connect\n',)

            import pydev_localhost
            threading.currentThread().__pydevd_id__ = "console_main"

            self.orig_findFrame = pydevd_vars.findFrame
            pydevd_vars.findFrame = self._findFrame

            self.debugger = pydevd.PyDB()
            try:
                self.debugger.connect(pydev_localhost.get_localhost(), debuggerPort)
                self.debugger.prepareToRun()
                import pydevd_tracing
                pydevd_tracing.SetTrace(None)
            except:
                traceback.print_exc()
                sys.stderr.write('Failed to connect to target debugger.\n')

            # Register to process commands when idle
            self.debugrunning = False
            try:
                import pydevconsole
                pydevconsole.set_debug_hook(self.debugger.processInternalCommands)
            except:
                traceback.print_exc()
                sys.stderr.write('Version of Python does not support debuggable Interactive Console.\n')
    def connectToDebugger(self, debuggerPort):
        """
        Used to show console with variables connection.
        Mainly, monkey-patches things in the debugger structure so that the debugger protocol works.
        """
        try:
            # Try to import the packages needed to attach the debugger
            import pydevd
            import pydevd_vars
            import threading
        except:
            # This happens on Jython embedded in host eclipse
            import traceback

            traceback.print_exc()
            return ("pydevd is not available, cannot connect",)

        import pydev_localhost

        threading.currentThread().__pydevd_id__ = "console_main"

        pydevd_vars.findFrame = self._findFrame

        self.debugger = pydevd.PyDB()
        try:
            self.debugger.connect(pydev_localhost.get_localhost(), debuggerPort)
        except:
            import traceback

            traceback.print_exc()
            return "Failed to connect to target debugger."
        return ("connect complete",)
    def __init__(self, notifications_queue, port, daemon=False):
        threading.Thread.__init__(self)
        self.setDaemon(daemon) # If False, wait for all the notifications to be passed before exiting!
        self.finished = False
        self.notifications_queue = notifications_queue

        import pydev_localhost

        # It is necessary to specify an encoding, that matches
        # the encoding of all bytes-strings passed into an
        # XMLRPC call: "All 8-bit strings in the data structure are assumed to use the
        # packet encoding.  Unicode strings are automatically converted,
        # where necessary."
        # Byte strings most likely come from file names.
        encoding = file_system_encoding
        if encoding == "mbcs":
            # Windos symbolic name for the system encoding CP_ACP.
            # We need to convert it into a encoding that is recognized by Java.
            # Unfortunately this is not always possible. You could use
            # GetCPInfoEx and get a name similar to "windows-1251". Then
            # you need a table to translate on a best effort basis. Much to complicated.
            # ISO-8859-1 is good enough.
            encoding = "ISO-8859-1"

        self.server = xmlrpclib.Server('http://%s:%s' % (pydev_localhost.get_localhost(), port),
                                       encoding=encoding)
Esempio n. 7
0
    def testServer(self):
        client_port, server_port = self.getFreeAddresses()
        class ServerThread(threading.Thread):
            def __init__(self, client_port, server_port):
                threading.Thread.__init__(self)
                self.client_port = client_port
                self.server_port = server_port
                
            def run(self):
                import pydev_localhost
                pydevconsole.StartServer(pydev_localhost.get_localhost(), self.server_port, self.client_port)
        server_thread = ServerThread(client_port, server_port)
        server_thread.setDaemon(True)
        server_thread.start()

        client_thread = self.startClientThread(client_port) #@UnusedVariable
        
        import time
        time.sleep(.3) #let's give it some time to start the threads
        
        import pydev_localhost
        server = xmlrpclib.Server('http://%s:%s' % (pydev_localhost.get_localhost(), server_port))
        server.addExec('class Foo:')
        server.addExec('    pass')
        server.addExec('')
        server.addExec('foo = Foo()')
        server.addExec('a = %s()' % (raw_input_name,))
        server.addExec('print (a)')
        self.assertEqual(['input_request'], sys.stdout.getvalue().split())
    def testServer(self):
        # Just making sure that the singleton is created in this thread.
        try:
            from pydev_ipython_console_011 import get_pydev_frontend
        except:
            sys.stderr.write('Skipped test because IPython could not be imported.')
            return
        get_pydev_frontend(get_localhost(), 0)

        client_port, server_port = self.getFreeAddresses()
        class ServerThread(threading.Thread):
            def __init__(self, client_port, server_port):
                threading.Thread.__init__(self)
                self.client_port = client_port
                self.server_port = server_port

            def run(self):
                import pydev_localhost
                print('Starting server with:', pydev_localhost.get_localhost(), self.server_port, self.client_port)
                pydevconsole.StartServer(pydev_localhost.get_localhost(), self.server_port, self.client_port)
        server_thread = ServerThread(client_port, server_port)
        server_thread.setDaemon(True)
        server_thread.start()

        client_thread = self.startClientThread(client_port) #@UnusedVariable

        try:
            import time
            time.sleep(.3) #let's give it some time to start the threads

            import pydev_localhost
            server = xmlrpclib.Server('http://%s:%s' % (pydev_localhost.get_localhost(), server_port))
            server.execLine("import sys; print('Running with: %s %s' % (sys.executable or sys.platform, sys.version))")
            server.execLine('class Foo:')
            server.execLine('    pass')
            server.execLine('')
            server.execLine('foo = Foo()')
            server.execLine('a = %s()' % raw_input_name)
            initial = time.time()
            while not client_thread.requested_input:
                if time.time() - initial > 2:
                    raise AssertionError('Did not get the return asked before the timeout.')
                time.sleep(.1)
            frame_xml = server.getFrame()
            self.assert_('RequestInput' in frame_xml, 'Did not fid RequestInput in:\n%s' % (frame_xml,))
        finally:
            client_thread.shutdown()
Esempio n. 9
0
 def __init__(self, notifications_queue, port):
     threading.Thread.__init__(self)
     self.setDaemon(False) #Wait for all the notifications to be passed before exiting!
     self.finished = False
     self.notifications_queue = notifications_queue
     
     import pydev_localhost
     self.server = xmlrpclib.Server('http://%s:%s' % (pydev_localhost.get_localhost(), port))
 def setUp(self):
     # PyDevFrontEnd depends on singleton in IPython, so you
     # can't make multiple versions. So we reuse self.front_end for
     # all the tests
     self.front_end = get_pydev_frontend(get_localhost(), 0)
     
     from pydev_ipython.inputhook import set_return_control_callback
     set_return_control_callback(lambda:True)
     self.front_end.clearBuffer()
def run_client(job_id, port, verbosity, coverage_output_file, coverage_include):
    job_id = int(job_id)
    
    import pydev_localhost
    server = xmlrpclib.Server('http://%s:%s' % (pydev_localhost.get_localhost(), port))
    server.lock = threading.Lock()

    
    server_comm = ServerComm(job_id, server)
    server_comm.start()
    
    try:
        server_facade = ServerFacade(server_comm.notifications_queue)
        import pydev_runfiles
        import pydev_runfiles_xml_rpc
        pydev_runfiles_xml_rpc.SetServer(server_facade)
        
        tests_to_run = [1]
        while tests_to_run:
            #Investigate: is it dangerous to use the same xmlrpclib server from different threads?
            #It seems it should be, as it creates a new connection for each request...
            server.lock.acquire()
            try:
                tests_to_run = server.GetTestsToRun(job_id)
            finally:
                server.lock.release()
            
            if not tests_to_run:
                break
            
            files_to_tests = {}
            for test in tests_to_run:
                filename_and_test = test.split('|')
                if len(filename_and_test) == 2:
                    files_to_tests.setdefault(filename_and_test[0], []).append(filename_and_test[1])
    
            configuration = pydev_runfiles.Configuration(
                '', 
                verbosity, 
                None, 
                None, 
                None, 
                files_to_tests, 
                1, 
                None, 
                coverage_output_file=coverage_output_file, 
                coverage_include=coverage_include, 
            )
            test_runner = pydev_runfiles.PydevTestRunner(configuration)
            sys.stdout.flush()
            test_runner.run_tests()
        
    except:
        traceback.print_exc()
    server_comm.notifications_queue.put_nowait(KillServer())
Esempio n. 12
0
    def testConsoleHello(self):
        client_port, _server_port = self.getFreeAddresses()
        client_thread = self.startClientThread(client_port) #@UnusedVariable
        import time
        time.sleep(.3) #let's give it some time to start the threads
        
        import pydev_localhost
        interpreter = pydevconsole.InterpreterInterface(pydev_localhost.get_localhost(), client_port)

        (result,) = interpreter.hello("Hello pydevconsole")
        self.assertEqual(result, "Hello eclipse")      
                def run(self):
                    class HandleRequestInput:
                        def RequestInput(self):
                            called_RequestInput[0] = True
                            return '\n'
                        def OpenEditor(self, name, line):
                            called_OpenEditor[0] = (name, line)
                            return True

                    handle_request_input = HandleRequestInput()

                    import pydev_localhost
                    client_server = SimpleXMLRPCServer((pydev_localhost.get_localhost(), self.client_port), logRequests=False)
                    client_server.register_function(handle_request_input.RequestInput)
                    client_server.register_function(handle_request_input.OpenEditor)
                    client_server.serve_forever()
 def testConsoleHello(self):
     self.original_stdout = sys.stdout
     sys.stdout = StringIO()
     
     try:
         client_port, _server_port = self.getFreeAddresses()
         client_thread = self.startClientThread(client_port)  #@UnusedVariable
         import time
         time.sleep(.3)  #let's give it some time to start the threads
 
         import pydev_localhost
         interpreter = pydevconsole.InterpreterInterface(pydev_localhost.get_localhost(), client_port, threading.currentThread())
 
         (result,) = interpreter.hello("Hello pydevconsole")
         self.assertEqual(result, "Hello eclipse")
     finally:
         sys.stdout = self.original_stdout
 def run(self):
     class HandleRequestInput:
         def RequestInput(self):
             client_thread.requested_input = True
             return 'RequestInput: OK'
         
         def NotifyFinished(self, *args, **kwargs):
             client_thread.notified_finished += 1
             return 1
     
     handle_request_input = HandleRequestInput()
     
     import pydev_localhost
     self.client_server = client_server = SimpleXMLRPCServer((pydev_localhost.get_localhost(), self.client_port), logRequests=False)
     client_server.register_function(handle_request_input.RequestInput)
     client_server.register_function(handle_request_input.NotifyFinished)
     client_server.serve_forever()
 def testServer(self):
     self.original_stdout = sys.stdout
     sys.stdout = StringIO()
     try:
         client_port, server_port = self.getFreeAddresses()
         class ServerThread(threading.Thread):
             def __init__(self, client_port, server_port):
                 threading.Thread.__init__(self)
                 self.client_port = client_port
                 self.server_port = server_port
 
             def run(self):
                 import pydev_localhost
                 pydevconsole.StartServer(pydev_localhost.get_localhost(), self.server_port, self.client_port)
         server_thread = ServerThread(client_port, server_port)
         server_thread.setDaemon(True)
         server_thread.start()
 
         client_thread = self.startClientThread(client_port)  #@UnusedVariable
 
         import time
         time.sleep(.3)  #let's give it some time to start the threads
         sys.stdout = StringIO()
 
         import pydev_localhost
         server = xmlrpclib.Server('http://%s:%s' % (pydev_localhost.get_localhost(), server_port))
         server.execLine('class Foo:')
         server.execLine('    pass')
         server.execLine('')
         server.execLine('foo = Foo()')
         server.execLine('a = %s()' % (raw_input_name,))
         server.execLine('print (a)')
         initial = time.time()
         while not client_thread.requested_input:
             if time.time() - initial > 2:
                 raise AssertionError('Did not get the return asked before the timeout.')
             time.sleep(.1)
             
         while ['input_request'] != sys.stdout.getvalue().split():
             if time.time() - initial > 2:
                 break
             time.sleep(.1)
         self.assertEqual(['input_request'], sys.stdout.getvalue().split())
     finally:
         sys.stdout = self.original_stdout
    def testEdit(self):
        ''' Make sure we can issue an edit command '''
        called_RequestInput = [False]
        called_OpenEditor = [False]
        def startClientThread(client_port):
            class ClientThread(threading.Thread):
                def __init__(self, client_port):
                    threading.Thread.__init__(self)
                    self.client_port = client_port
                def run(self):
                    class HandleRequestInput:
                        def RequestInput(self):
                            called_RequestInput[0] = True
                            return '\n'
                        def OpenEditor(self, name, line):
                            called_OpenEditor[0] = (name, line)
                            return True

                    handle_request_input = HandleRequestInput()

                    import pydev_localhost
                    client_server = SimpleXMLRPCServer((pydev_localhost.get_localhost(), self.client_port), logRequests=False)
                    client_server.register_function(handle_request_input.RequestInput)
                    client_server.register_function(handle_request_input.OpenEditor)
                    client_server.serve_forever()

            client_thread = ClientThread(client_port)
            client_thread.setDaemon(True)
            client_thread.start()
            return client_thread

        startClientThread(client_port)
        orig_stdin = sys.stdin
        sys.stdin = StdIn(self, get_localhost(), client_port)
        try:
            filename = 'made_up_file.py'
            addExec('%edit ' + filename)
            eq_(called_OpenEditor[0], (os.path.abspath(filename), 0))
            assert called_RequestInput[0], "Make sure the 'wait' parameter has been respected"
        finally:
            sys.stdin = orig_stdin
    def connectToDebugger(self, debuggerPort):
        '''
        Used to show console with variables connection.
        Mainly, monkey-patches things in the debugger structure so that the debugger protocol works.
        '''
        try:
            # Try to import the packages needed to attach the debugger
            import pydevd
            import pydevd_vars
            import threading
        except:
            # This happens on Jython embedded in host eclipse
            import traceback;traceback.print_exc()
            return ('pydevd is not available, cannot connect',)

        import pydev_localhost
        threading.currentThread().__pydevd_id__ = "console_main"

        self.orig_findFrame = pydevd_vars.findFrame
        pydevd_vars.findFrame = self._findFrame

        self.debugger = pydevd.PyDB()
        try:
            self.debugger.connect(pydev_localhost.get_localhost(), debuggerPort)
            self.debugger.prepareToRun()
            import pydevd_tracing
            pydevd_tracing.SetTrace(None)
        except:
            import traceback;traceback.print_exc()
            return ('Failed to connect to target debugger.')

        # Register to process commands when idle
        self.debugrunning = False
        try:
            self.server.setDebugHook(self.debugger.processInternalCommands)
        except:
            import traceback;traceback.print_exc()
            return ('Version of Python does not support debuggable Interactive Console.')

        return ('connect complete',)
 def run(self):
     import pydev_localhost
     print('Starting server with:', pydev_localhost.get_localhost(), self.server_port, self.client_port)
     pydevconsole.StartServer(pydev_localhost.get_localhost(), self.server_port, self.client_port)
Esempio n. 20
0
 def run(self):
     import pydev_localhost
     pydevconsole.StartServer(pydev_localhost.get_localhost(), self.server_port, self.client_port)
Esempio n. 21
0
            % (host, port, client_port))
        raise

    # Tell UMD the proper default namespace
    _set_globals_function(interpreter.getNamespace)

    # Functions for basic protocol
    server.register_function(interpreter.addExec)
    server.register_function(interpreter.getCompletions)
    server.register_function(interpreter.getDescription)
    server.register_function(interpreter.close)

    # Functions so that the console can work as a debugger (i.e.: variables view, expressions...)
    server.register_function(interpreter.connectToDebugger)
    server.register_function(interpreter.hello)

    # Functions for GUI main loop integration
    server.register_function(interpreter.enableGui)

    server.serve_forever()


#=======================================================================================================================
# main
#=======================================================================================================================
if __name__ == '__main__':
    sys.stdin = BaseStdIn()
    port, client_port = sys.argv[1:3]
    import pydev_localhost
    StartServer(pydev_localhost.get_localhost(), int(port), int(client_port))
Esempio n. 22
0
def _locked_settrace(host, stdoutToServer, stderrToServer, port, suspend,
                     trace_only_current_thread):
    if host is None:
        import pydev_localhost
        host = pydev_localhost.get_localhost()

    global connected
    global bufferStdOutToServer
    global bufferStdErrToServer

    if not connected:
        connected = True
        bufferStdOutToServer = stdoutToServer
        bufferStdErrToServer = stderrToServer

        pydevd_vm_type.SetupType()

        debugger = PyDB()
        debugger.connect(host, port)

        net = NetCommand(str(CMD_THREAD_CREATE), 0,
                         '<xml><thread name="pydevd.reader" id="-1"/></xml>')
        debugger.writer.addCommand(net)
        net = NetCommand(str(CMD_THREAD_CREATE), 0,
                         '<xml><thread name="pydevd.writer" id="-1"/></xml>')
        debugger.writer.addCommand(net)

        if bufferStdOutToServer:
            sys.stdoutBuf = pydevd_io.IOBuf()
            sys.stdout = pydevd_io.IORedirector(
                sys.stdout, sys.stdoutBuf)  #@UndefinedVariable

        if bufferStdErrToServer:
            sys.stderrBuf = pydevd_io.IOBuf()
            sys.stderr = pydevd_io.IORedirector(
                sys.stderr, sys.stderrBuf)  #@UndefinedVariable

        SetTraceForParents(GetFrame(), debugger.trace_dispatch)

        t = threadingCurrentThread()
        try:
            additionalInfo = t.additionalInfo
        except AttributeError:
            additionalInfo = PyDBAdditionalThreadInfo()
            t.additionalInfo = additionalInfo

        while not debugger.readyToRun:
            time.sleep(0.1)  # busy wait until we receive run command

        if suspend:
            debugger.setSuspend(t, CMD_SET_BREAK)

        #note that we do that through pydevd_tracing.SetTrace so that the tracing
        #is not warned to the user!
        pydevd_tracing.SetTrace(debugger.trace_dispatch)

        if not trace_only_current_thread:
            #Trace future threads?
            try:
                #not available in jython!
                threading.settrace(
                    debugger.trace_dispatch)  # for all future threads
            except:
                pass

            try:
                thread.start_new_thread = pydev_start_new_thread
                thread.start_new = pydev_start_new_thread
            except:
                pass

        PyDBCommandThread(debugger).start()

    else:
        #ok, we're already in debug mode, with all set, so, let's just set the break
        debugger = GetGlobalDebugger()

        SetTraceForParents(GetFrame(), debugger.trace_dispatch)

        t = threadingCurrentThread()
        try:
            additionalInfo = t.additionalInfo
        except AttributeError:
            additionalInfo = PyDBAdditionalThreadInfo()
            t.additionalInfo = additionalInfo

        pydevd_tracing.SetTrace(debugger.trace_dispatch)

        if not trace_only_current_thread:
            #Trace future threads?
            try:
                #not available in jython!
                threading.settrace(
                    debugger.trace_dispatch)  # for all future threads
            except:
                pass

            try:
                thread.start_new_thread = pydev_start_new_thread
                thread.start_new = pydev_start_new_thread
            except:
                pass

        if suspend:
            debugger.setSuspend(t, CMD_SET_BREAK)
Esempio n. 23
0
    def testEdit(self):
        ''' Make sure we can issue an edit command'''
        called_RequestInput = [False]
        called_IPythonEditor = [False]

        def startClientThread(client_port):
            class ClientThread(threading.Thread):
                def __init__(self, client_port):
                    threading.Thread.__init__(self)
                    self.client_port = client_port

                def run(self):
                    class HandleRequestInput:
                        def RequestInput(self):
                            called_RequestInput[0] = True
                            return '\n'

                        def IPythonEditor(self, name, line):
                            called_IPythonEditor[0] = (name, line)
                            return True

                    handle_request_input = HandleRequestInput()

                    import pydev_localhost
                    self.client_server = client_server = SimpleXMLRPCServer(
                        (pydev_localhost.get_localhost(), self.client_port),
                        logRequests=False)
                    client_server.register_function(
                        handle_request_input.RequestInput)
                    client_server.register_function(
                        handle_request_input.IPythonEditor)
                    client_server.serve_forever()

                def shutdown(self):
                    return
                    self.client_server.shutdown()

            client_thread = ClientThread(client_port)
            client_thread.setDaemon(True)
            client_thread.start()
            return client_thread

        # PyDevFrontEnd depends on singleton in IPython, so you
        # can't make multiple versions. So we reuse self.front_end for
        # all the tests
        s = socket.socket()
        s.bind(('', 0))
        self.client_port = client_port = s.getsockname()[1]
        s.close()
        self.front_end = get_pydev_frontend(get_localhost(), client_port)

        client_thread = startClientThread(self.client_port)
        orig_stdin = sys.stdin
        sys.stdin = StdIn(self, get_localhost(), self.client_port)
        try:
            filename = 'made_up_file.py'
            self.addExec('%edit ' + filename)

            for i in xrange(10):
                if called_IPythonEditor[0] == (os.path.abspath(filename), '0'):
                    break
                time.sleep(.1)

            if not called_IPythonEditor[0]:
                #   File "/home/travis/miniconda/lib/python3.3/site-packages/IPython/core/interactiveshell.py", line 2883, in run_code
                #     exec(code_obj, self.user_global_ns, self.user_ns)
                #   File "<ipython-input-15-09583ca3bce1>", line 1, in <module>
                #     get_ipython().magic('edit made_up_file.py')
                #   File "/home/travis/miniconda/lib/python3.3/site-packages/IPython/core/interactiveshell.py", line 2205, in magic
                #     return self.run_line_magic(magic_name, magic_arg_s)
                #   File "/home/travis/miniconda/lib/python3.3/site-packages/IPython/core/interactiveshell.py", line 2126, in run_line_magic
                #     result = fn(*args,**kwargs)
                #   File "<string>", line 2, in edit
                #   File "/home/travis/miniconda/lib/python3.3/site-packages/IPython/core/magic.py", line 193, in <lambda>
                #     call = lambda f, *a, **k: f(*a, **k)
                #   File "/home/travis/miniconda/lib/python3.3/site-packages/IPython/core/magics/code.py", line 662, in edit
                #     self.shell.hooks.editor(filename,lineno)
                #   File "/home/travis/build/fabioz/PyDev.Debugger/pydev_ipython_console_011.py", line 70, in call_editor
                #     server.IPythonEditor(filename, str(line))
                #   File "/home/travis/miniconda/lib/python3.3/xmlrpc/client.py", line 1090, in __call__
                #     return self.__send(self.__name, args)
                #   File "/home/travis/miniconda/lib/python3.3/xmlrpc/client.py", line 1419, in __request
                #     verbose=self.__verbose
                #   File "/home/travis/miniconda/lib/python3.3/xmlrpc/client.py", line 1132, in request
                #     return self.single_request(host, handler, request_body, verbose)
                #   File "/home/travis/miniconda/lib/python3.3/xmlrpc/client.py", line 1143, in single_request
                #     http_conn = self.send_request(host, handler, request_body, verbose)
                #   File "/home/travis/miniconda/lib/python3.3/xmlrpc/client.py", line 1255, in send_request
                #     self.send_content(connection, request_body)
                #   File "/home/travis/miniconda/lib/python3.3/xmlrpc/client.py", line 1285, in send_content
                #     connection.endheaders(request_body)
                #   File "/home/travis/miniconda/lib/python3.3/http/client.py", line 1061, in endheaders
                #     self._send_output(message_body)
                #   File "/home/travis/miniconda/lib/python3.3/http/client.py", line 906, in _send_output
                #     self.send(msg)
                #   File "/home/travis/miniconda/lib/python3.3/http/client.py", line 844, in send
                #     self.connect()
                #   File "/home/travis/miniconda/lib/python3.3/http/client.py", line 822, in connect
                #     self.timeout, self.source_address)
                #   File "/home/travis/miniconda/lib/python3.3/socket.py", line 435, in create_connection
                #     raise err
                #   File "/home/travis/miniconda/lib/python3.3/socket.py", line 426, in create_connection
                #     sock.connect(sa)
                # ConnectionRefusedError: [Errno 111] Connection refused

                # I.e.: just warn that the test failing, don't actually fail.
                sys.stderr.write(
                    'Test failed: this test is brittle in travis because sometimes the connection is refused (as above) and we do not have a callback.\n'
                )
                return

            eq_(called_IPythonEditor[0], (os.path.abspath(filename), '0'))
            assert called_RequestInput[
                0], "Make sure the 'wait' parameter has been respected"
        finally:
            sys.stdin = orig_stdin
            client_thread.shutdown()
Esempio n. 24
0
    def testEdit(self):
        """ Make sure we can issue an edit command"""
        called_RequestInput = [False]
        called_IPythonEditor = [False]

        def startClientThread(client_port):
            class ClientThread(threading.Thread):
                def __init__(self, client_port):
                    threading.Thread.__init__(self)
                    self.client_port = client_port

                def run(self):
                    class HandleRequestInput:
                        def RequestInput(self):
                            called_RequestInput[0] = True
                            return "\n"

                        def IPythonEditor(self, name, line):
                            called_IPythonEditor[0] = (name, line)
                            return True

                    handle_request_input = HandleRequestInput()

                    import pydev_localhost

                    self.client_server = client_server = SimpleXMLRPCServer(
                        (pydev_localhost.get_localhost(), self.client_port), logRequests=False
                    )
                    client_server.register_function(handle_request_input.RequestInput)
                    client_server.register_function(handle_request_input.IPythonEditor)
                    client_server.serve_forever()

                def shutdown(self):
                    return
                    self.client_server.shutdown()

            client_thread = ClientThread(client_port)
            client_thread.setDaemon(True)
            client_thread.start()
            return client_thread

        # PyDevFrontEnd depends on singleton in IPython, so you
        # can't make multiple versions. So we reuse self.front_end for
        # all the tests
        s = socket.socket()
        s.bind(("", 0))
        self.client_port = client_port = s.getsockname()[1]
        s.close()
        self.front_end = get_pydev_frontend(get_localhost(), client_port)

        client_thread = startClientThread(self.client_port)
        orig_stdin = sys.stdin
        sys.stdin = StdIn(self, get_localhost(), self.client_port)
        try:
            filename = "made_up_file.py"
            self.addExec("%edit " + filename)

            for i in xrange(10):
                if called_IPythonEditor[0] == (os.path.abspath(filename), "0"):
                    break
                time.sleep(0.1)

            if not called_IPythonEditor[0]:
                #   File "/home/travis/miniconda/lib/python3.3/site-packages/IPython/core/interactiveshell.py", line 2883, in run_code
                #     exec(code_obj, self.user_global_ns, self.user_ns)
                #   File "<ipython-input-15-09583ca3bce1>", line 1, in <module>
                #     get_ipython().magic('edit made_up_file.py')
                #   File "/home/travis/miniconda/lib/python3.3/site-packages/IPython/core/interactiveshell.py", line 2205, in magic
                #     return self.run_line_magic(magic_name, magic_arg_s)
                #   File "/home/travis/miniconda/lib/python3.3/site-packages/IPython/core/interactiveshell.py", line 2126, in run_line_magic
                #     result = fn(*args,**kwargs)
                #   File "<string>", line 2, in edit
                #   File "/home/travis/miniconda/lib/python3.3/site-packages/IPython/core/magic.py", line 193, in <lambda>
                #     call = lambda f, *a, **k: f(*a, **k)
                #   File "/home/travis/miniconda/lib/python3.3/site-packages/IPython/core/magics/code.py", line 662, in edit
                #     self.shell.hooks.editor(filename,lineno)
                #   File "/home/travis/build/fabioz/PyDev.Debugger/pydev_ipython_console_011.py", line 70, in call_editor
                #     server.IPythonEditor(filename, str(line))
                #   File "/home/travis/miniconda/lib/python3.3/xmlrpc/client.py", line 1090, in __call__
                #     return self.__send(self.__name, args)
                #   File "/home/travis/miniconda/lib/python3.3/xmlrpc/client.py", line 1419, in __request
                #     verbose=self.__verbose
                #   File "/home/travis/miniconda/lib/python3.3/xmlrpc/client.py", line 1132, in request
                #     return self.single_request(host, handler, request_body, verbose)
                #   File "/home/travis/miniconda/lib/python3.3/xmlrpc/client.py", line 1143, in single_request
                #     http_conn = self.send_request(host, handler, request_body, verbose)
                #   File "/home/travis/miniconda/lib/python3.3/xmlrpc/client.py", line 1255, in send_request
                #     self.send_content(connection, request_body)
                #   File "/home/travis/miniconda/lib/python3.3/xmlrpc/client.py", line 1285, in send_content
                #     connection.endheaders(request_body)
                #   File "/home/travis/miniconda/lib/python3.3/http/client.py", line 1061, in endheaders
                #     self._send_output(message_body)
                #   File "/home/travis/miniconda/lib/python3.3/http/client.py", line 906, in _send_output
                #     self.send(msg)
                #   File "/home/travis/miniconda/lib/python3.3/http/client.py", line 844, in send
                #     self.connect()
                #   File "/home/travis/miniconda/lib/python3.3/http/client.py", line 822, in connect
                #     self.timeout, self.source_address)
                #   File "/home/travis/miniconda/lib/python3.3/socket.py", line 435, in create_connection
                #     raise err
                #   File "/home/travis/miniconda/lib/python3.3/socket.py", line 426, in create_connection
                #     sock.connect(sa)
                # ConnectionRefusedError: [Errno 111] Connection refused

                # I.e.: just warn that the test failing, don't actually fail.
                sys.stderr.write(
                    "Test failed: this test is brittle in travis because sometimes the connection is refused (as above) and we do not have a callback.\n"
                )
                return

            eq_(called_IPythonEditor[0], (os.path.abspath(filename), "0"))
            assert called_RequestInput[0], "Make sure the 'wait' parameter has been respected"
        finally:
            sys.stdin = orig_stdin
            client_thread.shutdown()
DEBUG = INFO1 | ERROR


def dbg(s, prior):
    if prior & DEBUG != 0:
        sys.stdout.write("%s\n" % (s,))


#        f = open('c:/temp/test.txt', 'a')
#        print_ >> f, s
#        f.close()

import pydev_localhost

HOST = pydev_localhost.get_localhost()  # Symbolic name meaning the local host

MSG_KILL_SERVER = "@@KILL_SERVER_END@@"
MSG_COMPLETIONS = "@@COMPLETIONS"
MSG_END = "END@@"
MSG_INVALID_REQUEST = "@@INVALID_REQUEST"
MSG_JYTHON_INVALID_REQUEST = "@@JYTHON_INVALID_REQUEST"
MSG_CHANGE_DIR = "@@CHANGE_DIR:"
MSG_OK = "@@MSG_OK_END@@"
MSG_IMPORTS = "@@IMPORTS:"
MSG_PYTHONPATH = "@@PYTHONPATH_END@@"
MSG_CHANGE_PYTHONPATH = "@@CHANGE_PYTHONPATH:"
MSG_JEDI = "@@MSG_JEDI:"
MSG_SEARCH = "@@SEARCH"

BUFFER_SIZE = 1024
Esempio n. 26
0
        # Case 2
        return True

    #Case 3

    try:
        Exec(code, updated_globals, frame.f_locals)

    except SystemExit:
        raise
    except:
        interpreter.showtraceback()

    return False

#=======================================================================================================================
# main
#=======================================================================================================================


if __name__ == '__main__':
    port, client_port = sys.argv[1:3]
    import pydev_localhost

    if int(port) == 0 and int(client_port) == 0:
        (h, p) = pydev_localhost.get_socket_name()

        client_port = p

    StartServer(pydev_localhost.get_localhost(), int(port), int(client_port))
Esempio n. 27
0
def UpdatePort():
    global port
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((pydev_localhost.get_localhost(), 0))
    _, port = s.getsockname()
    s.close()
    del sys.argv[1]
    del sys.argv[1]

    file = sys.argv[1]

    del sys.argv[0]

    import pydev_localhost

    if int(port) == 0 and int(client_port) == 0:
        (h, p) = pydev_localhost.get_socket_name()

        client_port = p

    host = pydev_localhost.get_localhost()


    #replace exit (see comments on method)
    #note that this does not work in jython!!! (sys method can't be replaced).
    sys.exit = DoExit

    interpreter = InterpreterInterface(host, int(client_port), threading.currentThread())

    server_thread = threading.Thread(target=start_server,
                                     name='ServerThread',
                                     args=(host, int(port), interpreter))
    server_thread.setDaemon(True)
    server_thread.start()

    globals = run_file(file, None, None)
Esempio n. 29
0
 def testConsoleRequests(self):
     client_port, _server_port = self.getFreeAddresses()
     client_thread = self.startClientThread(client_port) #@UnusedVariable
     import time
     time.sleep(.3) #let's give it some time to start the threads
     
     import pydev_localhost
     interpreter = pydevconsole.InterpreterInterface(pydev_localhost.get_localhost(), client_port)
     interpreter.addExec('class Foo:')
     interpreter.addExec('   CONSTANT=1')
     interpreter.addExec('')
     interpreter.addExec('foo=Foo()')
     interpreter.addExec('foo.__doc__=None')
     interpreter.addExec('val = %s()' % (raw_input_name,))
     interpreter.addExec('50')
     interpreter.addExec('print (val)')
     self.assertEqual(['50', 'input_request'], sys.stdout.getvalue().split())
     
     comps = interpreter.getCompletions('foo.')
     self.assert_(('CONSTANT', '', '', '3') in comps or ('CONSTANT', '', '', '4') in comps)
     
     comps = interpreter.getCompletions('"".')
     self.assert_(
         ('__add__', 'x.__add__(y) <==> x+y', '', '3') in comps or 
         ('__add__', '', '', '4') in comps or 
         ('__add__', 'x.__add__(y) <==> x+y\r\nx.__add__(y) <==> x+y', '()', '2') in comps,
         'Did not find __add__ in : %s' % (comps,)
     )
     
     
     completions = interpreter.getCompletions('')
     for c in completions:
         if c[0] == 'AssertionError':
             break
     else:
         self.fail('Could not find AssertionError')
         
     completions = interpreter.getCompletions('Assert')
     for c in completions:
         if c[0] == 'RuntimeError':
             self.fail('Did not expect to find RuntimeError there')
     
     self.assert_(('__doc__', None, '', '3') not in interpreter.getCompletions('foo.CO'))
     
     comps = interpreter.getCompletions('va')
     self.assert_(('val', '', '', '3') in comps or ('val', '', '', '4') in comps)
     
     interpreter.addExec('s = "mystring"')
     
     desc = interpreter.getDescription('val')
     self.assert_(desc.find('str(object) -> string') >= 0 or 
                  desc == "'input_request'" or 
                  desc.find('str(string[, encoding[, errors]]) -> str') >= 0 or
                  desc.find('str(Char* value)') >= 0, 
                  'Could not find what was needed in %s' % desc)
     
     desc = interpreter.getDescription('val.join')
     self.assert_(desc.find('S.join(sequence) -> string') >= 0 or 
                  desc.find('S.join(sequence) -> str') >= 0 or 
                  desc.find('S.join(iterable) -> string') >= 0 or 
                  desc == "<builtin method 'join'>"  or 
                  desc == "<built-in method join of str object>" or
                  desc.find('str join(str self, list sequence)') >= 0 or
                  desc.find('S.join(iterable) -> str') >= 0,
                  "Could not recognize: %s" % (desc,))
    def testEdit(self):
        ''' Make sure we can issue an edit command'''
        called_RequestInput = [False]
        called_IPythonEditor = [False]
        def startClientThread(client_port):
            class ClientThread(threading.Thread):
                def __init__(self, client_port):
                    threading.Thread.__init__(self)
                    self.client_port = client_port
                def run(self):
                    class HandleRequestInput:
                        def RequestInput(self):
                            called_RequestInput[0] = True
                            return '\n'
                        def IPythonEditor(self, name, line):
                            called_IPythonEditor[0] = (name, line)
                            return True

                    handle_request_input = HandleRequestInput()

                    import pydev_localhost
                    self.client_server = client_server = SimpleXMLRPCServer(
                        (pydev_localhost.get_localhost(), self.client_port), logRequests=False)
                    client_server.register_function(handle_request_input.RequestInput)
                    client_server.register_function(handle_request_input.IPythonEditor)
                    client_server.serve_forever()
                    
                def shutdown(self):
                    return
                    self.client_server.shutdown()

            client_thread = ClientThread(client_port)
            client_thread.setDaemon(True)
            client_thread.start()
            return client_thread

        # PyDevFrontEnd depends on singleton in IPython, so you
        # can't make multiple versions. So we reuse self.front_end for
        # all the tests
        s = socket.socket()
        s.bind(('', 0))
        self.client_port = client_port = s.getsockname()[1]
        s.close()
        self.front_end = get_pydev_frontend(get_localhost(), client_port)

        client_thread = startClientThread(self.client_port)
        orig_stdin = sys.stdin
        sys.stdin = StdIn(self, get_localhost(), self.client_port)
        try:
            filename = 'made_up_file.py'
            self.addExec('%edit ' + filename)
            
            for i in xrange(10):
                if called_IPythonEditor[0] == (os.path.abspath(filename), '0'):
                    break
                time.sleep(.1)
                
            eq_(called_IPythonEditor[0], (os.path.abspath(filename), '0'))
            assert called_RequestInput[0], "Make sure the 'wait' parameter has been respected"
        finally:
            sys.stdin = orig_stdin
            client_thread.shutdown()
Esempio n. 31
0
 def run(self):
     import pydev_localhost
     pydevconsole.StartServer(pydev_localhost.get_localhost(),
                              self.server_port,
                              self.client_port)
 def run(self):
     import pydev_localhost
     print('Starting server with:', pydev_localhost.get_localhost(),
           self.server_port, self.client_port)
     pydevconsole.StartServer(pydev_localhost.get_localhost(),
                              self.server_port, self.client_port)
def run_client(job_id, port, verbosity, coverage_output_file,
               coverage_include):
    job_id = int(job_id)

    import pydev_localhost
    server = xmlrpclib.Server('http://%s:%s' %
                              (pydev_localhost.get_localhost(), port))
    server.lock = threading.Lock()

    server_comm = ServerComm(job_id, server)
    server_comm.start()

    try:
        server_facade = ServerFacade(server_comm.notifications_queue)
        import pydev_runfiles
        import pydev_runfiles_xml_rpc
        pydev_runfiles_xml_rpc.SetServer(server_facade)

        #Starts None and when the 1st test is gotten, it's started (because a server may be initiated and terminated
        #before receiving any test -- which would mean a different process got all the tests to run).
        coverage = None

        try:
            tests_to_run = [1]
            while tests_to_run:
                #Investigate: is it dangerous to use the same xmlrpclib server from different threads?
                #It seems it should be, as it creates a new connection for each request...
                server.lock.acquire()
                try:
                    tests_to_run = server.GetTestsToRun(job_id)
                finally:
                    server.lock.release()

                if not tests_to_run:
                    break

                if coverage is None:
                    _coverage_files, coverage = StartCoverageSupportFromParams(
                        None, coverage_output_file, 1, coverage_include)

                files_to_tests = {}
                for test in tests_to_run:
                    filename_and_test = test.split('|')
                    if len(filename_and_test) == 2:
                        files_to_tests.setdefault(filename_and_test[0],
                                                  []).append(
                                                      filename_and_test[1])

                configuration = pydev_runfiles.Configuration(
                    '',
                    verbosity,
                    None,
                    None,
                    None,
                    files_to_tests,
                    1,  #Always single job here
                    None,

                    #The coverage is handled in this loop.
                    coverage_output_file=None,
                    coverage_include=None,
                )
                test_runner = pydev_runfiles.PydevTestRunner(configuration)
                sys.stdout.flush()
                test_runner.run_tests(handle_coverage=False)
        finally:
            if coverage is not None:
                coverage.stop()
                coverage.save()

    except:
        traceback.print_exc()
    server_comm.notifications_queue.put_nowait(KillServer())
Esempio n. 34
0
    def CheckCase(self, writerThreadClass, run_as_python=True):
	UpdatePort()
	writerThread = writerThreadClass()
	writerThread.start()

	import pydev_localhost
	localhost = pydev_localhost.get_localhost()
	if run_as_python:
	    args = [
		'python',
		PYDEVD_FILE,
		'--DEBUG_RECORD_SOCKET_READS',
		'--client',
		localhost,
		'--port',
		str(port),
		'--file',
		writerThread.TEST_FILE,
	    ]
	
	else:
	    #run as jython
	    args = [
		JAVA_LOCATION,
		'-classpath',
		JYTHON_JAR_LOCATION,
		'org.python.util.jython',
		PYDEVD_FILE,
		'--DEBUG_RECORD_SOCKET_READS',
		'--client',
`               localhost,
		'--port',
		str(port),
		'--file',
		writerThread.TEST_FILE,
	    ]

	if SHOW_OTHER_DEBUG_INFO:
	    print 'executing', ' '.join(args)
	
	process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=os.path.dirname(PYDEVD_FILE))
	class ProcessReadThread(threading.Thread):
	    def run(self):
		self.resultStr = None
		self.resultStr = process.stdout.read()
		process.stdout.close()
	
	    def DoKill(self):
		process.stdout.close()
	
	processReadThread = ProcessReadThread()
	processReadThread.setDaemon(True)
	processReadThread.start()
	if SHOW_OTHER_DEBUG_INFO:
	    print 'Both processes started'

	#polls can fail (because the process may finish and the thread still not -- so, we give it some more chances to
	#finish successfully).
	pools_failed = 0
	while writerThread.isAlive():
	    if process.poll() is not None:
		pools_failed += 1
	    time.sleep(.2)
	    if pools_failed == 10:
		break

	if process.poll() is None:
	    for i in range(10):
		if processReadThread.resultStr is None:
		    time.sleep(.5)
		else:
		    break
	    else:
		writerThread.DoKill()

	else:
	    if process.poll() < 0:
		self.fail("The other process exited with error code: " + str(process.poll()) + " result:" + processReadThread.resultStr)
		

	if SHOW_RESULT_STR:
	    print processReadThread.resultStr
	
	if processReadThread.resultStr is None:
	    self.fail("The other process may still be running -- and didn't give any output")
	
	if 'TEST SUCEEDED' not in processReadThread.resultStr:
	    self.fail(processReadThread.resultStr)
	
	if not writerThread.finishedOk:
	    self.fail("The thread that was doing the tests didn't finish successfully. Output: %s" % processReadThread.resultStr)
Esempio n. 35
0
ERROR = 8

DEBUG = INFO1 | ERROR


def dbg(s, prior):
    if prior & DEBUG != 0:
        sys.stdout.write('%s\n' % (s, ))


#        f = open('c:/temp/test.txt', 'a')
#        print_ >> f, s
#        f.close()

import pydev_localhost
HOST = pydev_localhost.get_localhost()  # Symbolic name meaning the local host

MSG_KILL_SERVER = '@@KILL_SERVER_END@@'
MSG_COMPLETIONS = '@@COMPLETIONS'
MSG_END = 'END@@'
MSG_INVALID_REQUEST = '@@INVALID_REQUEST'
MSG_JYTHON_INVALID_REQUEST = '@@JYTHON_INVALID_REQUEST'
MSG_CHANGE_DIR = '@@CHANGE_DIR:'
MSG_OK = '@@MSG_OK_END@@'
MSG_BIKE = '@@BIKE'
MSG_PROCESSING = '@@PROCESSING_END@@'
MSG_PROCESSING_PROGRESS = '@@PROCESSING:%sEND@@'
MSG_IMPORTS = '@@IMPORTS:'
MSG_PYTHONPATH = '@@PYTHONPATH_END@@'
MSG_CHANGE_PYTHONPATH = '@@CHANGE_PYTHONPATH:'
MSG_SEARCH = '@@SEARCH'
Esempio n. 36
0
def settrace(host=None, stdoutToServer=False, stderrToServer=False, port=5678, suspend=True, trace_only_current_thread=True):
    '''Sets the tracing function with the pydev debug function and initializes needed facilities.
    
    @param host: the user may specify another host, if the debug server is not in the same machine (default is the local host)
    @param stdoutToServer: when this is true, the stdout is passed to the debug server
    @param stderrToServer: when this is true, the stderr is passed to the debug server
        so that they are printed in its console and not in this process console.
    @param port: specifies which port to use for communicating with the server (note that the server must be started 
        in the same port). @note: currently it's hard-coded at 5678 in the client
    @param suspend: whether a breakpoint should be emulated as soon as this function is called. 
    @param trace_only_current_thread: determines if only the current thread will be traced or all future threads will also have the tracing enabled.
    '''
    if host is None:
        import pydev_localhost
        host = pydev_localhost.get_localhost()
    
    global connected
    global bufferStdOutToServer
    global bufferStdErrToServer
    
    if not connected :
        connected = True  
        bufferStdOutToServer = stdoutToServer
        bufferStdErrToServer = stderrToServer
        
        pydevd_vm_type.SetupType()
        
        debugger = PyDB()
        debugger.connect(host, port)
        
        net = NetCommand(str(CMD_THREAD_CREATE), 0, '<xml><thread name="pydevd.reader" id="-1"/></xml>')
        debugger.writer.addCommand(net)
        net = NetCommand(str(CMD_THREAD_CREATE), 0, '<xml><thread name="pydevd.writer" id="-1"/></xml>')
        debugger.writer.addCommand(net)
        
        if bufferStdOutToServer:
            sys.stdoutBuf = pydevd_io.IOBuf()
            sys.stdout = pydevd_io.IORedirector(sys.stdout, sys.stdoutBuf) #@UndefinedVariable
            
        if bufferStdErrToServer:
            sys.stderrBuf = pydevd_io.IOBuf()
            sys.stderr = pydevd_io.IORedirector(sys.stderr, sys.stderrBuf) #@UndefinedVariable
            
        SetTraceForParents(GetFrame(), debugger.trace_dispatch)
        
        t = threadingCurrentThread()      
        try:
            additionalInfo = t.additionalInfo
        except AttributeError:
            additionalInfo = PyDBAdditionalThreadInfo()
            t.additionalInfo = additionalInfo
  
        while not debugger.readyToRun: 
            time.sleep(0.1) # busy wait until we receive run command

        if suspend:
            debugger.setSuspend(t, CMD_SET_BREAK)
        
        #note that we do that through pydevd_tracing.SetTrace so that the tracing
        #is not warned to the user!
        pydevd_tracing.SetTrace(debugger.trace_dispatch)
        
        if not trace_only_current_thread:
            #Trace future threads?
            try:                   
                #not available in jython!  
                threading.settrace(debugger.trace_dispatch) # for all future threads
            except:
                pass
            
            try:
                thread.start_new_thread = pydev_start_new_thread
                thread.start_new = pydev_start_new_thread
            except:
                pass
        
        PyDBCommandThread(debugger).start()
        
    else:
        #ok, we're already in debug mode, with all set, so, let's just set the break
        debugger = GetGlobalDebugger()
        
        SetTraceForParents(GetFrame(), debugger.trace_dispatch)
        
        t = threadingCurrentThread()      
        try:
            additionalInfo = t.additionalInfo
        except AttributeError:
            additionalInfo = PyDBAdditionalThreadInfo()
            t.additionalInfo = additionalInfo
            
        pydevd_tracing.SetTrace(debugger.trace_dispatch)
        
        if not trace_only_current_thread:
            #Trace future threads?
            try:                   
                #not available in jython!  
                threading.settrace(debugger.trace_dispatch) # for all future threads
            except:
                pass
            
            try:
                thread.start_new_thread = pydev_start_new_thread
                thread.start_new = pydev_start_new_thread
            except:
                pass
        
        if suspend:
            debugger.setSuspend(t, CMD_SET_BREAK)
def run_client(job_id, port, verbosity, coverage_output_file, coverage_include):
    job_id = int(job_id)

    import pydev_localhost
    server = xmlrpclib.Server('http://%s:%s' % (pydev_localhost.get_localhost(), port))
    server.lock = threading.Lock()


    server_comm = ServerComm(job_id, server)
    server_comm.start()

    try:
        server_facade = ServerFacade(server_comm.notifications_queue)
        import pydev_runfiles
        import pydev_runfiles_xml_rpc
        pydev_runfiles_xml_rpc.SetServer(server_facade)

        #Starts None and when the 1st test is gotten, it's started (because a server may be initiated and terminated
        #before receiving any test -- which would mean a different process got all the tests to run).
        coverage = None

        try:
            tests_to_run = [1]
            while tests_to_run:
                #Investigate: is it dangerous to use the same xmlrpclib server from different threads?
                #It seems it should be, as it creates a new connection for each request...
                server.lock.acquire()
                try:
                    tests_to_run = server.GetTestsToRun(job_id)
                finally:
                    server.lock.release()

                if not tests_to_run:
                    break

                if coverage is None:
                    _coverage_files, coverage = StartCoverageSupportFromParams(
                        None, coverage_output_file, 1, coverage_include)


                files_to_tests = {}
                for test in tests_to_run:
                    filename_and_test = test.split('|')
                    if len(filename_and_test) == 2:
                        files_to_tests.setdefault(filename_and_test[0], []).append(filename_and_test[1])

                configuration = pydev_runfiles.Configuration(
                    '',
                    verbosity,
                    None,
                    None,
                    None,
                    files_to_tests,
                    1, #Always single job here
                    None,

                    #The coverage is handled in this loop.
                    coverage_output_file=None,
                    coverage_include=None,
                )
                test_runner = pydev_runfiles.PydevTestRunner(configuration)
                sys.stdout.flush()
                test_runner.run_tests(handle_coverage=False)
        finally:
            if coverage is not None:
                coverage.stop()
                coverage.save()


    except:
        traceback.print_exc()
    server_comm.notifications_queue.put_nowait(KillServer())
Esempio n. 38
0
 def CheckCase(self, writerThreadClass, run_as_python=True):
     UpdatePort()
     writerThread = writerThreadClass()
     writerThread.start()
     
     import pydev_localhost
     localhost = pydev_localhost.get_localhost()
     if run_as_python:
         args = [
             'python',
             PYDEVD_FILE,
             '--DEBUG_RECORD_SOCKET_READS',
             '--client',
             localhost,
             '--port',
             str(port),
             '--file',
             writerThread.TEST_FILE,
         ]
         
     else:
         #run as jython
         args = [
             JAVA_LOCATION,
             '-classpath',
             JYTHON_JAR_LOCATION,
             'org.python.util.jython',
             PYDEVD_FILE,
             '--DEBUG_RECORD_SOCKET_READS',
             '--client',
             localhost,
             '--port',
             str(port),
             '--file',
             writerThread.TEST_FILE,
         ]
     
     if SHOW_OTHER_DEBUG_INFO:
         print 'executing', ' '.join(args)
         
     process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=os.path.dirname(PYDEVD_FILE))
     class ProcessReadThread(threading.Thread):
         def run(self):
             self.resultStr = None
             self.resultStr = process.stdout.read()
             process.stdout.close()
             
         def DoKill(self):
             process.stdout.close()
             
     processReadThread = ProcessReadThread()
     processReadThread.setDaemon(True)
     processReadThread.start()
     if SHOW_OTHER_DEBUG_INFO:
         print 'Both processes started'
     
     #polls can fail (because the process may finish and the thread still not -- so, we give it some more chances to
     #finish successfully).
     pools_failed = 0
     while writerThread.isAlive():
         if process.poll() is not None:
             pools_failed += 1
         time.sleep(.2)
         if pools_failed == 10:
             break
     
     if process.poll() is None:
         for i in range(10):
             if processReadThread.resultStr is None:
                 time.sleep(.5)
             else:
                 break
         else:
             writerThread.DoKill()
     
     else:
         if process.poll() < 0:
             self.fail("The other process exited with error code: " + str(process.poll()) + " result:" + processReadThread.resultStr)
                 
     
     if SHOW_RESULT_STR:
         print processReadThread.resultStr
         
     if processReadThread.resultStr is None:
         self.fail("The other process may still be running -- and didn't give any output")
         
     if 'TEST SUCEEDED' not in processReadThread.resultStr:
         self.fail(processReadThread.resultStr)
         
     if not writerThread.finishedOk:
         self.fail("The thread that was doing the tests didn't finish successfully. Output: %s" % processReadThread.resultStr)
Esempio n. 39
0
    except SystemExit:
        raise
    except:
        interpreter.showtraceback()

    return False


#=======================================================================================================================
# main
#=======================================================================================================================
if __name__ == '__main__':
    #Important: don't use this module directly as the __main__ module, rather, import itself as pydevconsole
    #so that we don't get multiple pydevconsole modules if it's executed directly (otherwise we'd have multiple
    #representations of its classes).
    #See: https://sw-brainwy.rhcloud.com/tracker/PyDev/446:
    #'Variables' and 'Expressions' views stopped working when debugging interactive console
    import pydevconsole
    sys.stdin = pydevconsole.BaseStdIn()
    port, client_port = sys.argv[1:3]
    import pydev_localhost

    if int(port) == 0 and int(client_port) == 0:
        (h, p) = pydev_localhost.get_socket_name()

        client_port = p

    pydevconsole.StartServer(pydev_localhost.get_localhost(), int(port),
                             int(client_port))
Esempio n. 40
0
def UpdatePort():
    global port
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((pydev_localhost.get_localhost(), 0))
    _, port = s.getsockname()
    s.close()
Esempio n. 41
0
# PyDevFrontEnd depends on singleton in IPython, so you
# can't make multiple versions. So we reuse front_end for
# all the tests

orig_stdout = sys.stdout
orig_stderr = sys.stderr

stdout = sys.stdout = StringIO()
stderr = sys.stderr = StringIO()

from pydev_ipython_console_011 import PyDevFrontEnd
s = socket.socket()
s.bind(('', 0))
client_port = s.getsockname()[1]
s.close()
front_end = PyDevFrontEnd(get_localhost(), client_port)


def addExec(code, expected_more=False):
    more = front_end.addExec(code)
    eq_(expected_more, more)


class TestBase(unittest.TestCase):
    def setUp(self):
        front_end.input_splitter.reset()
        stdout.truncate(0)
        stdout.seek(0)
        stderr.truncate(0)
        stderr.seek(0)
Esempio n. 42
0
 def testConsoleRequests(self):
     client_port, _server_port = self.getFreeAddresses()
     client_thread = self.startClientThread(client_port) #@UnusedVariable
     import time
     time.sleep(.3) #let's give it some time to start the threads
     
     import pydev_localhost
     interpreter = pydevconsole.InterpreterInterface(pydev_localhost.get_localhost(), client_port)
     interpreter.addExec('class Foo:')
     interpreter.addExec('   CONSTANT=1')
     interpreter.addExec('')
     interpreter.addExec('foo=Foo()')
     interpreter.addExec('foo.__doc__=None')
     interpreter.addExec('val = %s()' % (raw_input_name,))
     interpreter.addExec('50')
     interpreter.addExec('print (val)')
     found = sys.stdout.getvalue().split()
     try:
         self.assertEqual(['50', 'input_request'], found)
     except:
         self.assertEqual(['input_request'], found) #IPython
     
     comps = interpreter.getCompletions('foo.', 'foo.')
     self.assert_(
         ('CONSTANT', '', '', '3') in comps or ('CONSTANT', '', '', '4') in comps,\
         'Found: %s' % comps
     )
     
     comps = interpreter.getCompletions('"".', '"".')
     self.assert_(
         ('__add__', 'x.__add__(y) <==> x+y', '', '3') in comps or 
         ('__add__', '', '', '4') in comps or 
         ('__add__', 'x.__add__(y) <==> x+y\r\nx.__add__(y) <==> x+y', '()', '2') in comps or
         ('__add__', 'x.\n__add__(y) <==> x+yx.\n__add__(y) <==> x+y', '()', '2'),
         'Did not find __add__ in : %s' % (comps,)
     )
     
     
     completions = interpreter.getCompletions('', '')
     for c in completions:
         if c[0] == 'AssertionError':
             break
     else:
         self.fail('Could not find AssertionError')
         
     completions = interpreter.getCompletions('Assert', 'Assert')
     for c in completions:
         if c[0] == 'RuntimeError':
             self.fail('Did not expect to find RuntimeError there')
     
     self.assert_(('__doc__', None, '', '3') not in interpreter.getCompletions('foo.CO', 'foo.'))
     
     comps = interpreter.getCompletions('va', 'va')
     self.assert_(('val', '', '', '3') in comps or ('val', '', '', '4') in comps)
     
     interpreter.addExec('s = "mystring"')
     
     desc = interpreter.getDescription('val')
     self.assert_(desc.find('str(object) -> string') >= 0 or 
                  desc == "'input_request'" or 
                  desc.find('str(string[, encoding[, errors]]) -> str') >= 0 or
                  desc.find('str(Char* value)') >= 0 or 
                  desc.find('str(value: Char*)') >= 0, 
                  'Could not find what was needed in %s' % desc)
     
     desc = interpreter.getDescription('val.join')
     self.assert_(desc.find('S.join(sequence) -> string') >= 0 or 
                  desc.find('S.join(sequence) -> str') >= 0 or 
                  desc.find('S.join(iterable) -> string') >= 0 or 
                  desc == "<builtin method 'join'>"  or 
                  desc == "<built-in method join of str object>" or
                  desc.find('str join(str self, list sequence)') >= 0 or
                  desc.find('S.join(iterable) -> str') >= 0 or
                  desc.find('join(self: str, sequence: list) -> str') >= 0,
                  "Could not recognize: %s" % (desc,))
Esempio n. 43
0
    del sys.argv[1]
    del sys.argv[1]

    file = sys.argv[1]

    del sys.argv[0]

    import pydev_localhost

    if int(port) == 0 and int(client_port) == 0:
        (h, p) = pydev_localhost.get_socket_name()

        client_port = p

    host = pydev_localhost.get_localhost()

    #replace exit (see comments on method)
    #note that this does not work in jython!!! (sys method can't be replaced).
    sys.exit = DoExit

    interpreter = InterpreterInterface(host, int(client_port),
                                       threading.currentThread())

    server_thread = threading.Thread(target=start_server,
                                     name='ServerThread',
                                     args=(host, int(port), interpreter))
    server_thread.setDaemon(True)
    server_thread.start()

    globals = run_file(file, None, None)