Esempio n. 1
0
def main():
    import os
    import sys
    from ptvsd.visualstudio_py_debugger import DONT_DEBUG, DEBUG_ENTRYPOINTS, get_code
    from ptvsd.attach_server import DEFAULT_PORT, enable_attach, wait_for_attach
    
    sys.path[0] = os.getcwd()
    os.chdir(sys.argv[1])
    secret = sys.argv[2]
    port = int(sys.argv[3])
    testFx = sys.argv[4]
    args = sys.argv[5:]    

    DONT_DEBUG.append(os.path.normcase(__file__))
    DEBUG_ENTRYPOINTS.add(get_code(main))

    enable_attach(secret, ('127.0.0.1', port), redirect_output = False)
    sys.stdout.flush()
    print('READY')
    sys.stdout.flush()
    wait_for_attach()

    try:
        if testFx == 'pytest':
            import pytest
            pytest.main(args)
        else:
            import nose
            nose.run(argv=args)
        sys.exit()
    finally:
        pass
Esempio n. 2
0
def main():
    import os
    import sys
    import unittest
    from optparse import OptionParser
    
    parser = OptionParser(prog = 'visualstudio_py_testlauncher', usage = 'Usage: %prog [<option>] <test names>... ')
    parser.add_option('-s', '--secret', metavar='<secret>', help='restrict server to only allow clients that specify <secret> when connecting')
    parser.add_option('-p', '--port', type='int', metavar='<port>', help='listen for debugger connections on <port>')
    parser.add_option('-x', '--mixed-mode', action='store_true', help='wait for mixed-mode debugger to attach')
    parser.add_option('-t', '--test', type='str', dest='tests', action='append', help='specifies a test to run')
    parser.add_option('-m', '--module', type='str', help='name of the module to import the tests from')
    
    (opts, _) = parser.parse_args()
    
    sys.path[0] = os.getcwd()
    
    if opts.secret and opts.port:
        from ptvsd.visualstudio_py_debugger import DONT_DEBUG, DEBUG_ENTRYPOINTS, get_code
        from ptvsd.attach_server import DEFAULT_PORT, enable_attach, wait_for_attach

        DONT_DEBUG.append(os.path.normcase(__file__))
        DEBUG_ENTRYPOINTS.add(get_code(main))

        enable_attach(opts.secret, ('127.0.0.1', getattr(opts, 'port', DEFAULT_PORT)), redirect_output = True)
        wait_for_attach()
    elif opts.mixed_mode:
        # For mixed-mode attach, there's no ptvsd and hence no wait_for_attach(), 
        # so we have to use Win32 API in a loop to do the same thing.
        from time import sleep
        from ctypes import windll, c_char
        while True:
            if windll.kernel32.IsDebuggerPresent() != 0:
                break
            sleep(0.1)
        try:
            debugger_helper = windll['Microsoft.PythonTools.Debugger.Helper.x86.dll']
        except WinError:
            debugger_helper = windll['Microsoft.PythonTools.Debugger.Helper.x64.dll']
        isTracing = c_char.in_dll(debugger_helper, "isTracing")
        while True:
            if isTracing.value != 0:
                break
            sleep(0.1)
                
    __import__(opts.module)
    module = sys.modules[opts.module]
    test = unittest.defaultTestLoader.loadTestsFromNames(opts.tests, module)
    runner = unittest.TextTestRunner(verbosity=0)
    
    result = runner.run(test)
    sys.exit(not result.wasSuccessful())
def main():
    import os
    import sys
    import unittest
    from optparse import OptionParser
    global _channel

    parser = OptionParser(prog = 'visualstudio_py_testlauncher', usage = 'Usage: %prog [<option>] <test names>... ')
    parser.add_option('-s', '--secret', metavar='<secret>', help='restrict server to only allow clients that specify <secret> when connecting')
    parser.add_option('-p', '--port', type='int', metavar='<port>', help='listen for debugger connections on <port>')
    parser.add_option('-x', '--mixed-mode', action='store_true', help='wait for mixed-mode debugger to attach')
    parser.add_option('-t', '--test', type='str', dest='tests', action='append', help='specifies a test to run')
    parser.add_option('--testFile', type='str', help='Fully qualitified path to file name')
    parser.add_option('-c', '--coverage', type='str', help='enable code coverage and specify filename')
    parser.add_option('-r', '--result-port', type='int', help='connect to port on localhost and send test results')
    parser.add_option('--us', type='str', help='Directory to start discovery')
    parser.add_option('--up', type='str', help='Pattern to match test files (''test*.py'' default)')
    parser.add_option('--ut', type='str', help='Top level directory of project (default to start directory)')
    parser.add_option('--uvInt', '--verboseInt', type='int', help='Verbose output (0 none, 1 (no -v) simple, 2 (-v) full)')
    parser.add_option('--uf', '--failfast', type='str', help='Stop on first failure')
    parser.add_option('--uc', '--catch', type='str', help='Catch control-C and display results')
    (opts, _) = parser.parse_args()

    if opts.secret and opts.port:
        from ptvsd.visualstudio_py_debugger import DONT_DEBUG, DEBUG_ENTRYPOINTS, get_code
        from ptvsd.attach_server import DEFAULT_PORT, enable_attach, wait_for_attach
    
    sys.path[0] = os.getcwd()
    if opts.result_port:
        try:
            signal.signal(signal.SIGUSR1, signal_handler)
        except:
            try:
                signal.signal(signal.SIGTERM, signal_handler)
            except:
                pass
        _channel = _IpcChannel(socket.create_connection(('127.0.0.1', opts.result_port)), stopTests)
        sys.stdout = _TestOutput(sys.stdout, is_stdout = True)
        sys.stderr = _TestOutput(sys.stderr, is_stdout = False)

    if opts.secret and opts.port:
        DONT_DEBUG.append(os.path.normcase(__file__))
        DEBUG_ENTRYPOINTS.add(get_code(main))

        enable_attach(opts.secret, ('127.0.0.1', getattr(opts, 'port', DEFAULT_PORT)), redirect_output = True)
        sys.stdout.flush()
        print('READY')
        sys.stdout.flush()
        wait_for_attach()
    elif opts.mixed_mode:
        # For mixed-mode attach, there's no ptvsd and hence no wait_for_attach(), 
        # so we have to use Win32 API in a loop to do the same thing.
        from time import sleep
        from ctypes import windll, c_char
        while True:
            if windll.kernel32.IsDebuggerPresent() != 0:
                break
            sleep(0.1)
        try:
            debugger_helper = windll['Microsoft.PythonTools.Debugger.Helper.x86.dll']
        except WindowsError:
            debugger_helper = windll['Microsoft.PythonTools.Debugger.Helper.x64.dll']
        isTracing = c_char.in_dll(debugger_helper, "isTracing")
        while True:
            if isTracing.value != 0:
                break
            sleep(0.1)

    cov = None
    try:
        if opts.coverage:
            try:
                import coverage
                cov = coverage.coverage(opts.coverage)
                cov.load()
                cov.start()
            except:
                pass
        if opts.tests is None and opts.testFile is None:
            if opts.us is None:
                opts.us = '.'
            if opts.up is None:
                opts.up = 'test*.py'
            tests = unittest.defaultTestLoader.discover(opts.us, opts.up)
        else:
            # loadTestsFromNames doesn't work well (with duplicate file names or class names) 
            # Easier approach is find the test suite and use that for running
            loader = unittest.TestLoader()
            # opts.us will be passed in
            suites = loader.discover(opts.us, pattern=os.path.basename(opts.testFile))
            suite = None
            tests = None            
            if opts.tests is None:
                # Run everything in the test file
                tests = suites
            else:
                # Run a specific test class or test method
                for suite in suites._tests:
                    for cls in suite._tests:                        
                        try:
                            for m in cls._tests:
                                testId = m.id()
                                if testId.startswith(opts.tests[0]):
                                    suite = cls
                                if testId == opts.tests[0]:
                                    tests = m
                                    break
                        except Exception as err:
                            errorMessage = traceback.format_exception()                            
                            pass
                if tests is None:
                    tests = suite
            if tests is None and suite is None:
                _channel.send_event(
                    name='error', 
                    outcome='',
                    traceback = '',
                    message = 'Failed to identify the test',
                    test = ''
                )
        if opts.uvInt is None:
            opts.uvInt = 0        
        if opts.uf is not None:
            runner = unittest.TextTestRunner(verbosity=opts.uvInt, resultclass=VsTestResult, failfast=True)
        else:
            runner = unittest.TextTestRunner(verbosity=opts.uvInt, resultclass=VsTestResult)
        result = runner.run(tests)
        sys.exit(not result.wasSuccessful())
    finally:
        if cov is not None:
            cov.stop()
            cov.save()
            cov.xml_report(outfile = opts.coverage + '.xml', omit=__file__)
        if _channel is not None:
            _channel.send_event(
                name='done'
            )
            _channel.socket.close()
        # prevent generation of the error 'Error in sys.exitfunc:'
        try:
            sys.stdout.close()
        except:
            pass
        try:
            sys.stderr.close()
        except:
            pass
Esempio n. 4
0
def main():
    import os
    import sys
    import unittest
    from optparse import OptionParser
    global _channel

    parser = OptionParser(prog='visualstudio_py_testlauncher',
                          usage='Usage: %prog [<option>] <test names>... ')
    parser.add_option(
        '-s',
        '--secret',
        metavar='<secret>',
        help=
        'restrict server to only allow clients that specify <secret> when connecting'
    )
    parser.add_option('-p',
                      '--port',
                      type='int',
                      metavar='<port>',
                      help='listen for debugger connections on <port>')
    parser.add_option('-x',
                      '--mixed-mode',
                      action='store_true',
                      help='wait for mixed-mode debugger to attach')
    parser.add_option('-t',
                      '--test',
                      type='str',
                      dest='tests',
                      action='append',
                      help='specifies a test to run')
    parser.add_option('-c',
                      '--coverage',
                      type='str',
                      help='enable code coverage and specify filename')
    parser.add_option(
        '-r',
        '--result-port',
        type='int',
        help='connect to port on localhost and send test results')
    (opts, _) = parser.parse_args()

    sys.path[0] = os.getcwd()

    if opts.result_port:
        _channel = _IpcChannel(
            socket.create_connection(('127.0.0.1', opts.result_port)))
        sys.stdout = _TestOutput(sys.stdout, is_stdout=True)
        sys.stderr = _TestOutput(sys.stderr, is_stdout=False)

    if opts.secret and opts.port:
        from ptvsd.visualstudio_py_debugger import DONT_DEBUG, DEBUG_ENTRYPOINTS, get_code
        from ptvsd.attach_server import DEFAULT_PORT, enable_attach, wait_for_attach

        DONT_DEBUG.append(os.path.normcase(__file__))
        DEBUG_ENTRYPOINTS.add(get_code(main))

        enable_attach(opts.secret,
                      ('127.0.0.1', getattr(opts, 'port', DEFAULT_PORT)),
                      redirect_output=True)
        wait_for_attach()
    elif opts.mixed_mode:
        # For mixed-mode attach, there's no ptvsd and hence no wait_for_attach(),
        # so we have to use Win32 API in a loop to do the same thing.
        from time import sleep
        from ctypes import windll, c_char
        while True:
            if windll.kernel32.IsDebuggerPresent() != 0:
                break
            sleep(0.1)
        try:
            debugger_helper = windll[
                'Microsoft.PythonTools.Debugger.Helper.x86.dll']
        except WindowsError:
            debugger_helper = windll[
                'Microsoft.PythonTools.Debugger.Helper.x64.dll']
        isTracing = c_char.in_dll(debugger_helper, "isTracing")
        while True:
            if isTracing.value != 0:
                break
            sleep(0.1)

    cov = None
    try:
        if opts.coverage:
            try:
                import coverage
                cov = coverage.coverage(opts.coverage)
                cov.load()
                cov.start()
            except:
                pass
        tests = unittest.defaultTestLoader.loadTestsFromNames(opts.tests)
        runner = unittest.TextTestRunner(verbosity=0, resultclass=VsTestResult)

        result = runner.run(tests)

        sys.exit(not result.wasSuccessful())
    finally:
        if cov is not None:
            cov.stop()
            cov.save()
            cov.xml_report(outfile=opts.coverage + '.xml', omit=__file__)
        if _channel is not None:
            _channel.send_event(name='done')
            _channel.socket.close()
Esempio n. 5
0
                  help='do not redirect stdout and stderr to debugger')
parser.add_option('--wait',
                  dest='wait',
                  action='store_true',
                  default=False,
                  help='wait for a debugger to attach before executing')

argv = sys.argv[1:]
script_argv = []
if '-' in argv:
    script_argv = argv[argv.index('-') + 1:]
    del argv[argv.index('-'):]

(opts, args) = parser.parse_args(argv)
if not args and not script_argv:
    parser.error('<file> not specified')
if args:
    script_argv.insert(0, args[0])
if opts.keyfile and not opts.certfile:
    parser.error('--keyfile requires --certfile')

enable_attach(opts.secret, (opts.interface, opts.port), opts.certfile,
              opts.keyfile, opts.redirect_output)
if opts.wait:
    wait_for_attach()

DONT_DEBUG.append(os.path.normcase(__file__))

sys.argv = script_argv
exec_file(script_argv[0], {'__name__': '__main__'})
Esempio n. 6
0
def main():
    import os
    import sys
    import unittest
    from optparse import OptionParser
    global _channel

    parser = OptionParser(prog='visualstudio_py_testlauncher',
                          usage='Usage: %prog [<option>] <test names>... ')
    parser.add_option(
        '-s',
        '--secret',
        metavar='<secret>',
        help=
        'restrict server to only allow clients that specify <secret> when connecting'
    )
    parser.add_option('-p',
                      '--port',
                      type='int',
                      metavar='<port>',
                      help='listen for debugger connections on <port>')
    parser.add_option('-x',
                      '--mixed-mode',
                      action='store_true',
                      help='wait for mixed-mode debugger to attach')
    parser.add_option('-t',
                      '--test',
                      type='str',
                      dest='tests',
                      action='append',
                      help='specifies a test to run')
    parser.add_option('--testFile',
                      type='str',
                      help='Fully qualitified path to file name')
    parser.add_option('-c',
                      '--coverage',
                      type='str',
                      help='enable code coverage and specify filename')
    parser.add_option(
        '-r',
        '--result-port',
        type='int',
        help='connect to port on localhost and send test results')
    parser.add_option('--us', type='str', help='Directory to start discovery')
    parser.add_option('--up',
                      type='str',
                      help='Pattern to match test files ('
                      'test*.py'
                      ' default)')
    parser.add_option(
        '--ut',
        type='str',
        help='Top level directory of project (default to start directory)')
    parser.add_option(
        '--uvInt',
        '--verboseInt',
        type='int',
        help='Verbose output (0 none, 1 (no -v) simple, 2 (-v) full)')
    parser.add_option('--uf',
                      '--failfast',
                      type='str',
                      help='Stop on first failure')
    parser.add_option('--uc',
                      '--catch',
                      type='str',
                      help='Catch control-C and display results')
    (opts, _) = parser.parse_args()

    if opts.secret and opts.port:
        from ptvsd.visualstudio_py_debugger import DONT_DEBUG, DEBUG_ENTRYPOINTS, get_code
        from ptvsd.attach_server import DEFAULT_PORT, enable_attach, wait_for_attach

    sys.path[0] = os.getcwd()
    if opts.result_port:
        try:
            signal.signal(signal.SIGUSR1, signal_handler)
        except:
            try:
                signal.signal(signal.SIGTERM, signal_handler)
            except:
                pass
        _channel = _IpcChannel(
            socket.create_connection(('127.0.0.1', opts.result_port)),
            stopTests)
        sys.stdout = _TestOutput(sys.stdout, is_stdout=True)
        sys.stderr = _TestOutput(sys.stderr, is_stdout=False)

    if opts.secret and opts.port:
        DONT_DEBUG.append(os.path.normcase(__file__))
        DEBUG_ENTRYPOINTS.add(get_code(main))

        enable_attach(opts.secret,
                      ('127.0.0.1', getattr(opts, 'port', DEFAULT_PORT)),
                      redirect_output=True)
        sys.stdout.flush()
        print('READY')
        sys.stdout.flush()
        wait_for_attach()
    elif opts.mixed_mode:
        # For mixed-mode attach, there's no ptvsd and hence no wait_for_attach(),
        # so we have to use Win32 API in a loop to do the same thing.
        from time import sleep
        from ctypes import windll, c_char
        while True:
            if windll.kernel32.IsDebuggerPresent() != 0:
                break
            sleep(0.1)
        try:
            debugger_helper = windll[
                'Microsoft.PythonTools.Debugger.Helper.x86.dll']
        except WindowsError:
            debugger_helper = windll[
                'Microsoft.PythonTools.Debugger.Helper.x64.dll']
        isTracing = c_char.in_dll(debugger_helper, "isTracing")
        while True:
            if isTracing.value != 0:
                break
            sleep(0.1)

    cov = None
    try:
        if opts.coverage:
            try:
                import coverage
                cov = coverage.coverage(opts.coverage)
                cov.load()
                cov.start()
            except:
                pass
        if opts.tests is None and opts.testFile is None:
            if opts.us is None:
                opts.us = '.'
            if opts.up is None:
                opts.up = 'test*.py'
            tests = unittest.defaultTestLoader.discover(opts.us, opts.up)
        else:
            # loadTestsFromNames doesn't work well (with duplicate file names or class names)
            # Easier approach is find the test suite and use that for running
            loader = unittest.TestLoader()
            # opts.us will be passed in
            suites = loader.discover(opts.us,
                                     pattern=os.path.basename(opts.testFile))
            suite = None
            tests = None
            if opts.tests is None:
                # Run everything in the test file
                tests = suites
            else:
                # Run a specific test class or test method
                for suite in suites._tests:
                    for cls in suite._tests:
                        try:
                            for m in cls._tests:
                                testId = m.id()
                                if testId.startswith(opts.tests[0]):
                                    suite = cls
                                if testId == opts.tests[0]:
                                    tests = m
                                    break
                        except Exception as err:
                            errorMessage = traceback.format_exception()
                            pass
                if tests is None:
                    tests = suite
            if tests is None and suite is None:
                _channel.send_event(name='error',
                                    outcome='',
                                    traceback='',
                                    message='Failed to identify the test',
                                    test='')
        if opts.uvInt is None:
            opts.uvInt = 0
        if opts.uf is not None:
            runner = unittest.TextTestRunner(verbosity=opts.uvInt,
                                             resultclass=VsTestResult,
                                             failfast=True)
        else:
            runner = unittest.TextTestRunner(verbosity=opts.uvInt,
                                             resultclass=VsTestResult)
        result = runner.run(tests)
        sys.exit(not result.wasSuccessful())
    finally:
        if cov is not None:
            cov.stop()
            cov.save()
            cov.xml_report(outfile=opts.coverage + '.xml', omit=__file__)
        if _channel is not None:
            _channel.send_event(name='done')
            _channel.socket.close()
        # prevent generation of the error 'Error in sys.exitfunc:'
        try:
            sys.stdout.close()
        except:
            pass
        try:
            sys.stderr.close()
        except:
            pass
def main():
    import os
    import sys
    import unittest
    from optparse import OptionParser
    global _channel

    parser = OptionParser(prog = 'visualstudio_py_testlauncher', usage = 'Usage: %prog [<option>] <test names>... ')
    parser.add_option('-s', '--secret', metavar='<secret>', help='restrict server to only allow clients that specify <secret> when connecting')
    parser.add_option('-p', '--port', type='int', metavar='<port>', help='listen for debugger connections on <port>')
    parser.add_option('-x', '--mixed-mode', action='store_true', help='wait for mixed-mode debugger to attach')
    parser.add_option('-t', '--test', type='str', dest='tests', action='append', help='specifies a test to run')
    parser.add_option('-c', '--coverage', type='str', help='enable code coverage and specify filename')
    parser.add_option('-r', '--result-port', type='int', help='connect to port on localhost and send test results')
    (opts, _) = parser.parse_args()
    
    sys.path[0] = os.getcwd()
    
    if opts.result_port:
        _channel = _IpcChannel(socket.create_connection(('127.0.0.1', opts.result_port)))
        sys.stdout = _TestOutput(sys.stdout, is_stdout = True)
        sys.stderr = _TestOutput(sys.stderr, is_stdout = False)

    if opts.secret and opts.port:
        from ptvsd.visualstudio_py_debugger import DONT_DEBUG, DEBUG_ENTRYPOINTS, get_code
        from ptvsd.attach_server import DEFAULT_PORT, enable_attach, wait_for_attach

        DONT_DEBUG.append(os.path.normcase(__file__))
        DEBUG_ENTRYPOINTS.add(get_code(main))

        enable_attach(opts.secret, ('127.0.0.1', getattr(opts, 'port', DEFAULT_PORT)), redirect_output = True)
        wait_for_attach()
    elif opts.mixed_mode:
        # For mixed-mode attach, there's no ptvsd and hence no wait_for_attach(), 
        # so we have to use Win32 API in a loop to do the same thing.
        from time import sleep
        from ctypes import windll, c_char
        while True:
            if windll.kernel32.IsDebuggerPresent() != 0:
                break
            sleep(0.1)
        try:
            debugger_helper = windll['Microsoft.PythonTools.Debugger.Helper.x86.dll']
        except WindowsError:
            debugger_helper = windll['Microsoft.PythonTools.Debugger.Helper.x64.dll']
        isTracing = c_char.in_dll(debugger_helper, "isTracing")
        while True:
            if isTracing.value != 0:
                break
            sleep(0.1)

    cov = None
    try:
        if opts.coverage:
            try:
                import coverage
                cov = coverage.coverage(opts.coverage)
                cov.load()
                cov.start()
            except:
                pass

        tests = []
        for test in opts.tests:
            try:
                tests.extend(unittest.defaultTestLoader.loadTestsFromName(test))
            except Exception as err:
                traceback.print_exc()
                formatted = traceback.format_exc().splitlines()
                # Remove the 'Traceback (most recent call last)'
                formatted = formatted[1:]
                tb = '\n'.join(formatted)
                message = str(err)

                if _channel is not None:
                    _channel.send_event(
                        name='start', 
                        test = test
                    )
                    _channel.send_event(
                        name='result', 
                        outcome='failed',
                        traceback = tb,
                        message = message,
                        test = test
                    )

        runner = unittest.TextTestRunner(verbosity=0, resultclass=VsTestResult)
        
        result = runner.run(unittest.defaultTestLoader.suiteClass(tests))

        sys.exit(not result.wasSuccessful())
    finally:
        if cov is not None:
            cov.stop()
            cov.save()
            cov.xml_report(outfile = opts.coverage + '.xml', omit=__file__)
        if _channel is not None:
            _channel.send_event(
                name='done'
            )
            _channel.socket.close()
Esempio n. 8
0
def main():
    import os
    import sys
    import unittest
    from optparse import OptionParser

    parser = OptionParser(prog='visualstudio_py_testlauncher',
                          usage='Usage: %prog [<option>] <test names>... ')
    parser.add_option(
        '-s',
        '--secret',
        metavar='<secret>',
        help=
        'restrict server to only allow clients that specify <secret> when connecting'
    )
    parser.add_option('-p',
                      '--port',
                      type='int',
                      metavar='<port>',
                      help='listen for debugger connections on <port>')
    parser.add_option('-x',
                      '--mixed-mode',
                      action='store_true',
                      help='wait for mixed-mode debugger to attach')
    parser.add_option('-t',
                      '--test',
                      type='str',
                      dest='tests',
                      action='append',
                      help='specifies a test to run')
    parser.add_option('-m',
                      '--module',
                      type='str',
                      help='name of the module to import the tests from')

    (opts, _) = parser.parse_args()

    sys.path[0] = os.getcwd()

    if opts.secret and opts.port:
        from ptvsd.visualstudio_py_debugger import DONT_DEBUG, DEBUG_ENTRYPOINTS, get_code
        from ptvsd.attach_server import DEFAULT_PORT, enable_attach, wait_for_attach

        DONT_DEBUG.append(os.path.normcase(__file__))
        DEBUG_ENTRYPOINTS.add(get_code(main))

        enable_attach(opts.secret,
                      ('127.0.0.1', getattr(opts, 'port', DEFAULT_PORT)),
                      redirect_output=True)
        wait_for_attach()
    elif opts.mixed_mode:
        # For mixed-mode attach, there's no ptvsd and hence no wait_for_attach(),
        # so we have to use Win32 API in a loop to do the same thing.
        from time import sleep
        from ctypes import windll, c_char
        while True:
            if windll.kernel32.IsDebuggerPresent() != 0:
                break
            sleep(0.1)
        try:
            debugger_helper = windll[
                'Microsoft.PythonTools.Debugger.Helper.x86.dll']
        except WinError:
            debugger_helper = windll[
                'Microsoft.PythonTools.Debugger.Helper.x64.dll']
        isTracing = c_char.in_dll(debugger_helper, "isTracing")
        while True:
            if isTracing.value != 0:
                break
            sleep(0.1)

    __import__(opts.module)
    module = sys.modules[opts.module]
    test = unittest.defaultTestLoader.loadTestsFromNames(opts.tests, module)
    runner = unittest.TextTestRunner(verbosity=0)

    result = runner.run(test)
    sys.exit(not result.wasSuccessful())
def main():
    import os
    import sys
    import unittest
    from optparse import OptionParser
    global _channel

    parser = OptionParser(prog='visualstudio_py_testlauncher',
                          usage='Usage: %prog [<option>] <test names>... ')
    parser.add_option(
        '-s',
        '--secret',
        metavar='<secret>',
        help=
        'restrict server to only allow clients that specify <secret> when connecting'
    )
    parser.add_option('-p',
                      '--port',
                      type='int',
                      metavar='<port>',
                      help='listen for debugger connections on <port>')
    parser.add_option('-x',
                      '--mixed-mode',
                      action='store_true',
                      help='wait for mixed-mode debugger to attach')
    parser.add_option('-t',
                      '--test',
                      type='str',
                      dest='tests',
                      action='append',
                      help='specifies a test to run')
    parser.add_option('-c',
                      '--coverage',
                      type='str',
                      help='enable code coverage and specify filename')
    parser.add_option(
        '-r',
        '--result-port',
        type='int',
        help='connect to port on localhost and send test results')
    parser.add_option('--test-list',
                      metavar='<file>',
                      type='str',
                      help='read tests from this file')
    parser.add_option('--dry-run',
                      action='store_true',
                      help='prints a list of tests without executing them')
    (opts, _) = parser.parse_args()

    sys.path[0] = os.getcwd()

    if opts.result_port:
        _channel = _IpcChannel(
            socket.create_connection(('127.0.0.1', opts.result_port)))
        sys.stdout = _TestOutput(sys.stdout, is_stdout=True)
        sys.stderr = _TestOutput(sys.stderr, is_stdout=False)

    if opts.secret and opts.port:
        from ptvsd.debugger import DONT_DEBUG, DEBUG_ENTRYPOINTS, get_code
        from ptvsd.attach_server import DEFAULT_PORT, enable_attach, wait_for_attach

        DONT_DEBUG.append(os.path.normcase(__file__))
        DEBUG_ENTRYPOINTS.add(get_code(main))

        enable_attach(opts.secret,
                      ('127.0.0.1', getattr(opts, 'port', DEFAULT_PORT)),
                      redirect_output=True)
        wait_for_attach()
    elif opts.mixed_mode:
        # For mixed-mode attach, there's no ptvsd and hence no wait_for_attach(),
        # so we have to use Win32 API in a loop to do the same thing.
        from time import sleep
        from ctypes import windll, c_char
        while True:
            if windll.kernel32.IsDebuggerPresent() != 0:
                break
            sleep(0.1)
        try:
            debugger_helper = windll[
                'Microsoft.PythonTools.Debugger.Helper.x86.dll']
        except WindowsError:
            debugger_helper = windll[
                'Microsoft.PythonTools.Debugger.Helper.x64.dll']
        isTracing = c_char.in_dll(debugger_helper, "isTracing")
        while True:
            if isTracing.value != 0:
                break
            sleep(0.1)

    all_tests = list(opts.tests or [])
    if opts.test_list:
        with open(opts.test_list, 'r', encoding='utf-8') as test_list:
            all_tests.extend(t.strip() for t in test_list)

    if opts.dry_run:
        if _channel:
            for test in all_tests:
                print(test)
                _channel.send_event(name='start', test=test)
                _channel.send_event(name='result', outcome='passed', test=test)
        else:
            for test in all_tests:
                print(test)
        sys.exit(0)

    cov = None
    try:
        if opts.coverage:
            try:
                import coverage
                cov = coverage.coverage(opts.coverage)
                cov.load()
                cov.start()
            except:
                pass

        tests = []
        for test in all_tests:
            if not test:
                continue
            try:
                for loaded_test in unittest.defaultTestLoader.loadTestsFromName(
                        test):
                    # Starting with Python 3.5, rather than letting any import error
                    # exception propagate out of loadTestsFromName, unittest catches it and
                    # creates instance(s) of unittest.loader._FailedTest.
                    # Those have an unexpected test.id(), ex: 'unittest.loader._FailedTest.test1'
                    # Store the test id passed in as an additional attribute and
                    # VsTestResult will use that instead of test.id().
                    loaded_test.test_id = test
                    tests.append(loaded_test)
            except Exception as err:
                traceback.print_exc()
                formatted = traceback.format_exc().splitlines()
                # Remove the 'Traceback (most recent call last)'
                formatted = formatted[1:]
                tb = '\n'.join(formatted)
                message = str(err)

                if _channel is not None:
                    _channel.send_event(name='start', test=test)
                    _channel.send_event(name='result',
                                        outcome='failed',
                                        traceback=tb,
                                        message=message,
                                        test=test)

        runner = unittest.TextTestRunner(verbosity=0, resultclass=VsTestResult)

        result = runner.run(unittest.defaultTestLoader.suiteClass(tests))

        sys.exit(not result.wasSuccessful())
    finally:
        if cov is not None:
            cov.stop()
            cov.save()
            cov.xml_report(outfile=opts.coverage + '.xml', omit=__file__)
        if _channel is not None:
            _channel.send_event(name='done')
            _channel.close()
Esempio n. 10
0
parser.add_option('-s', '--secret', metavar = '<secret>', help = 'restrict server to only allow clients that specify <secret> when connecting')
parser.add_option('-i', '--interface', default = '0.0.0.0', metavar = '<ip-address>', help = 'listen for debugger connections on interface <ip-address>')
parser.add_option('-p', '--port', type='int', default = DEFAULT_PORT, metavar = '<port>', help = 'listen for debugger connections on <port>')
parser.add_option('--certfile', metavar = '<file>', help = 'Enable SSL and use PEM certificate from <file> to secure connection')
parser.add_option('--keyfile', metavar = '<file>', help = 'Use private key from <file> to secure connection (requires --certfile)')
parser.add_option('--no-output-redirection', dest = 'redirect_output', action = 'store_false', default = True, help = 'do not redirect stdout and stderr to debugger')
parser.add_option('--wait', dest = 'wait', action = 'store_true', default = False, help = 'wait for a debugger to attach before executing')

argv = sys.argv[1:]
script_argv = []
if '-' in argv:
    script_argv = argv[argv.index('-') + 1:]
    del argv[argv.index('-'):]

(opts, args) = parser.parse_args(argv)
if not args and not script_argv:
    parser.error('<file> not specified')
if args:
    script_argv.insert(0, args[0])
if opts.keyfile and not opts.certfile:
    parser.error('--keyfile requires --certfile')

enable_attach(opts.secret, (opts.interface, opts.port), opts.certfile, opts.keyfile, opts.redirect_output)
if opts.wait:
    wait_for_attach()

DONT_DEBUG.append(os.path.normcase(__file__))

sys.argv = script_argv
exec_file(script_argv[0], {'__name__': '__main__'})