예제 #1
0
def _add_options(p):
    p.add_option('-t','--test', dest='testcase', metavar='NAME',
        help='Tests to execute, one of %s' % tests.get_test_names())
    p.add_option('-l','--log', dest='logfile', metavar='NAME',
        default=None,
        help='Log file location (if not given, logging is disabled)')
    p.add_option('','--force', dest='force', action="store_true",
        default=False,
        help='Remove previous MySQL test installation.')
    p.add_option('','--keep', dest='keep', action="store_true",
        default=False,
        help='Keep MySQL installation (i.e. for debugging)')
    p.add_option('','--debug', dest='debug', action="store_true",
        default=False,
        help='Show/Log debugging messages')
    p.add_option('','--verbosity', dest='verbosity', metavar='NUMBER',
        default='0', type="int",
        help='Verbosity of unittests (default 0)')
    
    p.add_option('','--mysql-basedir', dest='mysql_basedir',
        metavar='NAME', default='/usr/local/mysql',
        help='Where MySQL is installed. This is used to bootstrap and '\
         'run a MySQL server which is used for unittesting only.')
    p.add_option('','--mysql-topdir', dest='mysql_topdir',
        metavar='NAME',
        default=os.path.join(os.path.dirname(os.path.abspath(__file__)),
            'mysql_myconnpy'),
        help='Where to bootstrap the new MySQL instance for testing. '\
         'Defaults to current ./mysql_myconnpy')
    p.add_option('','--bind-address', dest='bind_address', metavar='NAME',
        default='127.0.0.1',
        help='IP address to bind to')
    p.add_option('-P','--port', dest='port', metavar='NUMBER',
        default='33770', type="int",
        help='Port to use for TCP/IP connections.')
예제 #2
0
def _add_options(p):
    default_topdir = os.path.join(os.path.dirname(
        os.path.abspath(__file__)), 'mysql_myconnpy')
    p.add_option('-t','--test', dest='testcase', metavar='NAME',
        help='Tests to execute, one of %s' % tests.get_test_names())
    p.add_option('-T','--one-test', dest='onetest', metavar='NAME',
        help='Particular test to execute, format: '\
             '<module>[.<class>[.<method>]]. '\
             'For example, to run a particular '\
             'test BugOra13392739.test_reconnect() from the tests.test_bugs '\
             'module, use following value for the -T option: '\
             ' tests.test_bugs.BugOra13392739.test_reconnect')
    p.add_option('-l','--log', dest='logfile', metavar='NAME',
        default=None,
        help='Log file location (if not given, logging is disabled)')
    p.add_option('','--force', dest='force', action="store_true",
        default=False,
        help='Remove previous MySQL test installation.')
    p.add_option('','--keep', dest='keep', action="store_true",
        default=False,
        help='Keep MySQL installation (i.e. for debugging)')
    p.add_option('','--debug', dest='debug', action="store_true",
        default=False,
        help='Show/Log debugging messages')
    p.add_option('','--verbosity', dest='verbosity', metavar='NUMBER',
        default='0', type="int",
        help='Verbosity of unittests (default 0)')
    
    p.add_option('','--mysql-basedir', dest='mysql_basedir',
        metavar='NAME', default='/usr/local/mysql',
        help='Where MySQL is installed. This is used to bootstrap and '\
         'run a MySQL server which is used for unittesting only.')
    p.add_option('','--mysql-topdir', dest='mysql_topdir',
        metavar='NAME',
        default=default_topdir,
        help='Where to bootstrap the new MySQL instance for testing. '\
         'Defaults to current ./mysql_myconnpy')
    p.add_option('','--bind-address', dest='bind_address', metavar='NAME',
        default='127.0.0.1',
        help='IP address to bind to')

    p.add_option('-H', '--host', dest='host', metavar='NAME',
        default='127.0.0.1',
        help='Hostname or IP address for TCP/IP connections.')
    p.add_option('-P', '--port', dest='port', metavar='NUMBER',
        default=33770, type="int",
        help='Port to use for TCP/IP connections.')
    p.add_option('', '--unix-socket', dest='unix_socket', metavar='NAME',
        default=os.path.join(default_topdir, 'myconnpy_mysql.sock'),
        help='Unix socket location.')
예제 #3
0
def _add_options(p):
    default_topdir = os.path.join(os.path.dirname(
        os.path.abspath(__file__)), 'mysql_myconnpy')
    p.add_option('-t','--test', dest='testcase', metavar='NAME',
        help='Tests to execute, one of %s' % tests.get_test_names())
    p.add_option('-T','--one-test', dest='onetest', metavar='NAME',
        help='Particular test to execute, format: '\
             '<module>[.<class>[.<method>]]. '\
             'For example, to run a particular '\
             'test BugOra13392739.test_reconnect() from the tests.test_bugs '\
             'module, use following value for the -T option: '\
             ' tests.test_bugs.BugOra13392739.test_reconnect')
    p.add_option('-l','--log', dest='logfile', metavar='NAME',
        default=None,
        help='Log file location (if not given, logging is disabled)')
    p.add_option('','--force', dest='force', action="store_true",
        default=False,
        help='Remove previous MySQL test installation.')
    p.add_option('','--keep', dest='keep', action="store_true",
        default=False,
        help='Keep MySQL installation (i.e. for debugging)')
    p.add_option('','--debug', dest='debug', action="store_true",
        default=False,
        help='Show/Log debugging messages')
    p.add_option('','--verbosity', dest='verbosity', metavar='NUMBER',
        default='0', type="int",
        help='Verbosity of unittests (default 0)')
    
    p.add_option('','--mysql-basedir', dest='mysql_basedir',
        metavar='NAME', default='/usr/local/mysql',
        help='Where MySQL is installed. This is used to bootstrap and '\
         'run a MySQL server which is used for unittesting only.')
    p.add_option('','--mysql-topdir', dest='mysql_topdir',
        metavar='NAME',
        default=default_topdir,
        help='Where to bootstrap the new MySQL instance for testing. '\
         'Defaults to current ./mysql_myconnpy')
    p.add_option('','--bind-address', dest='bind_address', metavar='NAME',
        default='127.0.0.1',
        help='IP address to bind to')

    p.add_option('-H', '--host', dest='host', metavar='NAME',
        default='127.0.0.1',
        help='Hostname or IP address for TCP/IP connections.')
    p.add_option('-P', '--port', dest='port', metavar='NUMBER',
        default=33770, type="int",
        help='Port to use for TCP/IP connections.')
    p.add_option('', '--unix-socket', dest='unix_socket', metavar='NAME',
        default=os.path.join(default_topdir, 'myconnpy_mysql.sock'),
        help='Unix socket location.')
예제 #4
0
def main():
    usage = 'usage: %prog [options]'
    parser = OptionParser()
    _add_options(parser)

    # Set options
    (options, args) = parser.parse_args()
    option_file = os.path.join(options.mysql_topdir,'myconnpy_my.cnf')
    _set_config(options)
    
    # Init the MySQL Server object
    mysql_server = mysqld.MySQLInit(
        options.mysql_basedir,
        options.mysql_topdir,
        MY_CNF,
        option_file,
        options.bind_address,
        options.port,
        options.unix_socket,
        os.path.abspath(tests.SSL_DIR))
    mysql_server._debug = options.debug
    tests.MYSQL_VERSION = mysql_server.version

    # Check if we can test IPv6
    if options.bind_address.strip() != '::':
        tests.IPV6_AVAILABLE = False
    
    # Force removal of previous test data
    if options.force is True:
        mysql_server.remove()

    # Which tests cases to run
    if options.testcase is not None:
        if options.testcase in tests.get_test_names():
            testcases = [ 'tests.test_%s' % options.testcase ]
        else:
            msg = "Test case is not one of %s" % tests.get_test_names()
            _show_help(msg=msg,parser=parser,exit=1)
        testsuite = unittest.TestLoader().loadTestsFromNames(testcases)
    elif options.onetest is not None:
        testsuite = unittest.TestLoader().loadTestsFromName(options.onetest)
    else:
        testcases = tests.active_testcases
        testsuite = unittest.TestLoader().loadTestsFromNames(testcases)
    
    # Enabling logging
    formatter = logging.Formatter("%(asctime)s [%(name)s:%(levelname)s] %(message)s")
    myconnpy_logger = logging.getLogger('myconnpy')
    fh = None
    if options.logfile is not None:
        fh = logging.FileHandler(options.logfile)
    else:
        fh = logging.StreamHandler()
    fh.setFormatter(formatter)
    logger.addHandler(fh)
    if options.debug is True:
        logger.setLevel(logging.DEBUG)
        myconnpy_logger.setLevel(logging.DEBUG)
    else:
        myconnpy_logger.setLevel(logging.INFO)
    myconnpy_logger.addHandler(fh)
    myconnpy_logger.info(
        "MySQL Connector/Python unittest started: "
        "Python v%s ; MySQL v%s" % (
            '.'.join([ str(v) for v in sys.version_info[0:3]]),
            '.'.join([ str(v) for v in mysql_server.version[0:3]])))
    
    # Bootstrap and start a MySQL server
    myconnpy_logger.info("Bootstrapping a MySQL server")
    mysql_server.bootstrap()
    myconnpy_logger.info("Starting a MySQL server")
    mysql_server.start()
    
    myconnpy_logger.info("Starting unit tests")
    was_successful = False
    try:
        # Run test cases
        result = unittest.TextTestRunner(verbosity=options.verbosity).run(
            testsuite)
        was_successful = result.wasSuccessful()
    except KeyboardInterrupt:
        logger.info("Unittesting was interrupted")
        was_successful = False

    # Log messages added by test cases
    for msg in tests.MESSAGES['WARNINGS']:
        myconnpy_logger.warning(msg)
    for msg in tests.MESSAGES['INFO']:
        myconnpy_logger.info(msg)

    # Clean up
    if not options.keep:
        mysql_server.stop()
        mysql_server.remove()
        myconnpy_logger.info("MySQL server stopped and cleaned up")
    else:
        myconnpy_logger.info("MySQL server kept running on %s:%d" %
                             (options.bind_address, options.port))

    txt = ""
    if not was_successful:
        txt = "not "
    logger.info("MySQL Connector/Python unittests were %ssuccessful" % txt)

    # Return result of tests as exit code
    sys.exit(not was_successful)
예제 #5
0
def main():
    usage = 'usage: %prog [options]'
    parser = OptionParser()
    _add_options(parser)

    # Set options
    (options, args) = parser.parse_args()
    option_file = os.path.join(options.mysql_topdir,'myconnpy_my.cnf')
    unix_socket = os.path.join(options.mysql_topdir,'myconnpy_mysql.sock')
    _set_config(options, unix_socket=unix_socket)
    
    # Init the MySQL Server object
    mysql_server = mysqld.MySQLInit(options.mysql_basedir,
        options.mysql_topdir,
        MY_CNF,
        option_file,
        options.bind_address,
        options.port,
        unix_socket)
    mysql_server._debug = options.debug
    
    # Force removal of previous test data
    if options.force is True:
        mysql_server.remove()

    # Which tests cases to run
    if options.testcase is not None:
        if options.testcase in tests.get_test_names():
            testcases = [ 'tests.test_%s' % options.testcase ]
        else:
            msg = "Test case is not one of %s" % tests.get_test_names()
            _show_help(msg=msg,parser=parser,exit=1)
    else:
        testcases = tests.active_testcases
    
    # Enabling logging
    formatter = logging.Formatter("%(asctime)s [%(name)s:%(levelname)s] %(message)s")
    myconnpy_logger = logging.getLogger('myconnpy')
    fh = None
    if options.logfile is not None:
        fh = logging.FileHandler(options.logfile)
    else:
        fh = logging.StreamHandler()
    fh.setFormatter(formatter)
    logger.addHandler(fh)
    if options.debug is True:
        logger.setLevel(logging.DEBUG)
        myconnpy_logger.setLevel(logging.DEBUG)
    else:
        myconnpy_logger.setLevel(logging.INFO)
    myconnpy_logger.addHandler(fh)
    logger.info("MySQL Connector/Python unittest started")
    
    # Bootstrap and start a MySQL server
    mysql_server.bootstrap()
    mysql_server.start()
    
    # Run test cases
    suite = unittest.TestLoader().loadTestsFromNames(testcases)
    result = unittest.TextTestRunner(verbosity=options.verbosity).run(suite)
    txt = ""
    if not result.wasSuccessful():
        txt = "not "
    logger.info("MySQL Connector/Python unittests were %ssuccessful" % txt)
    
    # Clean up
    mysql_server.stop()
    if options.keep is not True:
        mysql_server.remove()
    
    # Return result of tests as exit code
    sys.exit(not result.wasSuccessful())
예제 #6
0
def main():
    parser = _get_arg_parser()
    options = parser.parse_args()
    tests.OPTIONS_INIT = True

    if isinstance(options, tuple):
        # Fallback to old optparse
        options = options[0]

    tests.setup_logger(LOGGER, debug=options.debug, logfile=options.logfile)
    LOGGER.info("MySQL Connector/Python unittest using Python v{0}".format(
        '.'.join([str(v) for v in sys.version_info[0:3]])))

    # Check if we can test IPv6
    if options.ipv6:
        if not tests.IPV6_AVAILABLE:
            LOGGER.error("Can not test IPv6: not available on your system")
            sys.exit(1)
        options.bind_address = '::'
        options.host = '::1'
        LOGGER.info("Testing using IPv6. Binding to :: and using host ::1")
    else:
        tests.IPV6_AVAILABLE = False

    if not options.mysql_sharedir:
        options.mysql_sharedir = os.path.join(options.mysql_basedir, 'share')
        LOGGER.debug("Setting default sharedir: %s", options.mysql_sharedir)
    if options.mysql_topdir != MYSQL_DEFAULT_TOPDIR:
        # Make sure the topdir is absolute
        if not os.path.isabs(options.mysql_topdir):
            options.mysql_topdir = os.path.join(
                os.path.dirname(os.path.realpath(__file__)),
                options.mysql_topdir)

    # If Django was supplied, add Django to PYTHONPATH
    if options.django_path:
        sys.path.insert(0, options.django_path)
        try:
            import django

            tests.DJANGO_VERSION = django.VERSION[0:3]
        except ImportError:
            msg = "Could not find django package at {0}".format(
                options.django_path)
            LOGGER.error(msg)
            sys.exit(1)

        if sys.version_info[0] == 3 and tests.DJANGO_VERSION < (1, 5):
            LOGGER.error("Django older than v1.5 will not work with Python 3")
            sys.exit(1)

    if options.fabric_config:
        # URL example: fabric://user:[email protected]:32274
        fab = urlsplit(options.fabric_config)
        tests.FABRIC_CONFIG = {
            'host': fab.hostname,
            'port': fab.port or 32274,
            'user': fab.username,
            'password': fab.password,
        }

    # Start Dummy MySQL Server
    #tests.MYSQL_DUMMY = mysqld.DummyMySQLServer(('127.0.0.1', options.port - 1),
    #                                            mysqld.DummyMySQLRequestHandler)
    #tests.MYSQL_DUMMY_THREAD = threading.Thread(
    #    target=tests.MYSQL_DUMMY.serve_forever)
    #tests.MYSQL_DUMMY_THREAD.setDaemon(True)

    # We have to at least run 1 MySQL server
    init_mysql_server(port=(options.port), options=options)

    # Which tests cases to run
    testcases = []
    testsuite = None

    if options.testcase:
        if options.testcase in tests.get_test_names():
            for module in tests.get_test_modules():
                if module.endswith('test_' + options.testcase):
                    testcases = [module]
                    break
            testsuite = unittest.TestLoader().loadTestsFromNames(testcases)
        else:
            msg = "Test case is not one of {0}".format(', '.join(
                tests.get_test_names()))
            _show_help(msg=msg, parser=parser, exit_code=1)
    elif options.onetest:
        testsuite = unittest.TestLoader().loadTestsFromName(options.onetest)
    else:
        testcases = tests.get_test_modules()
        testsuite = unittest.TestLoader().loadTestsFromNames(testcases)

    # Initialize the other MySQL Servers
    for i in range(1, tests.MYSQL_SERVERS_NEEDED):
        init_mysql_server(port=(options.port + i), options=options)

    LOGGER.info("Using MySQL server version %s",
                '.'.join([str(v) for v in tests.MYSQL_VERSION[0:3]]))

    LOGGER.info("Starting unit tests")
    was_successful = False
    try:
        # Run test cases
        if options.stats:
            if options.stats_host:
                stats_db_info = {
                    'host': options.stats_host,
                    'port': options.stats_port,
                    'user': options.stats_user,
                    'password': options.stats_password,
                    'database': options.stats_db,
                }
                cnxstats = mysql.connector.connect(**stats_db_info)
                setup_stats_db(cnxstats)
            else:
                cnxstats = None
            result = StatsTestRunner(verbosity=options.verbosity,
                                     dbcnx=cnxstats).run(testsuite)
        elif sys.version_info[0:2] == (2, 6):
            result = Python26TestRunner(
                verbosity=options.verbosity).run(testsuite)
        else:
            result = BasicTestRunner(
                verbosity=options.verbosity).run(testsuite)
        was_successful = result.wasSuccessful()
    except KeyboardInterrupt:
        LOGGER.info("Unittesting was interrupted")
        was_successful = False

    # Log messages added by test cases
    for msg in tests.MESSAGES['WARNINGS']:
        LOGGER.warning(msg)
    for msg in tests.MESSAGES['INFO']:
        LOGGER.info(msg)

    # Show skipped tests
    if len(tests.MESSAGES['SKIPPED']):
        LOGGER.info("Skipped tests: %d", len(tests.MESSAGES['SKIPPED']))
        for msg in tests.MESSAGES['SKIPPED']:
            LOGGER.info("Skipped: " + msg)

    # Clean up
    try:
        tests.MYSQL_DUMMY_THREAD.join()
        tests.MYSQL_DUMMY.shutdown()
        tests.MYSQL_DUMMY.server_close()
    except:
        # Is OK when failed
        pass
    for mysql_server in tests.MYSQL_SERVERS:
        name = mysql_server.name
        if not options.keep:
            mysql_server.stop()
            if not mysql_server.wait_down():
                LOGGER.error("Failed stopping MySQL server '%s'", name)
            else:
                mysql_server.remove()
                LOGGER.info("MySQL server '%s' stopped and cleaned up", name)
        elif not mysql_server.check_running():
            mysql_server.start()
            if not mysql_server.wait_up():
                LOGGER.error("MySQL could not be kept running; "
                             "failed to restart")
        else:
            LOGGER.info("MySQL server kept running on %s:%d",
                        mysql_server.bind_address, mysql_server.port)

    # Make sure the DEVNULL file is closed
    try:
        mysqld.DEVNULL.close()
    except:
        pass

    txt = ""
    if not was_successful:
        txt = "not "
    LOGGER.info("MySQL Connector/Python unittests were %ssuccessful", txt)

    # Return result of tests as exit code
    sys.exit(not was_successful)
예제 #7
0
     'metavar':
     'NAME',
     'help':
     ('Particular test to execute, format: '
      '<module>[.<class>[.<method>]]. For example, to run a particular '
      'test BugOra13392739.test_reconnect() from the tests.test_bugs '
      'module, use following value for the -T option: '
      ' tests.test_bugs.BugOra13392739.test_reconnect')
 },
 ('-t', '--test'): {
     'dest':
     'testcase',
     'metavar':
     'NAME',
     'help':
     'Tests to execute, one of {names}'.format(names=tests.get_test_names())
 },
 ('-l', '--log'): {
     'dest': 'logfile',
     'metavar': 'NAME',
     'default': None,
     'help': 'Log file location (if not given, logging is disabled)'
 },
 ('', '--force'): {
     'dest': 'force',
     'action': 'store_true',
     'default': False,
     'help': 'Remove previous MySQL test installation.'
 },
 ('', '--keep'): {
     'dest': 'keep',
예제 #8
0
def main():
    usage = 'usage: %prog [options]'
    parser = OptionParser()
    _add_options(parser)

    # Set options
    (options, args) = parser.parse_args()
    option_file = os.path.join(options.mysql_topdir,'myconnpy_my.cnf')
    unix_socket = os.path.join(options.mysql_topdir,'myconnpy_mysql.sock')
    _set_config(options, unix_socket=unix_socket)
    
    # Init the MySQL Server object
    mysql_server = mysqld.MySQLInit(
        options.mysql_basedir,
        options.mysql_topdir,
        MY_CNF,
        option_file,
        options.bind_address,
        options.port,
        unix_socket,
        os.path.abspath(tests.SSL_DIR))
    mysql_server._debug = options.debug
    tests.MYSQL_VERSION = mysql_server.version
    
    # Force removal of previous test data
    if options.force is True:
        mysql_server.remove()

    # Which tests cases to run
    if options.testcase is not None:
        if options.testcase in tests.get_test_names():
            testcases = [ 'tests.test_%s' % options.testcase ]
        else:
            msg = "Test case is not one of %s" % tests.get_test_names()
            _show_help(msg=msg,parser=parser,exit=1)
        testsuite = unittest.TestLoader().loadTestsFromNames(testcases)
    elif options.onetest is not None:
        testsuite = unittest.TestLoader().loadTestsFromName(options.onetest)
    else:
        testcases = tests.active_testcases
        testsuite = unittest.TestLoader().loadTestsFromNames(testcases)
    
    # Enabling logging
    formatter = logging.Formatter("%(asctime)s [%(name)s:%(levelname)s] %(message)s")
    myconnpy_logger = logging.getLogger('myconnpy')
    fh = None
    if options.logfile is not None:
        fh = logging.FileHandler(options.logfile)
    else:
        fh = logging.StreamHandler()
    fh.setFormatter(formatter)
    logger.addHandler(fh)
    if options.debug is True:
        logger.setLevel(logging.DEBUG)
        myconnpy_logger.setLevel(logging.DEBUG)
    else:
        myconnpy_logger.setLevel(logging.INFO)
    myconnpy_logger.addHandler(fh)
    myconnpy_logger.info(
        "MySQL Connector/Python unittest started: "
        "Python v%s ; MySQL v%s" % (
            '.'.join([ str(v) for v in sys.version_info[0:3]]),
            '.'.join([ str(v) for v in mysql_server.version[0:3]])))
    
    # Bootstrap and start a MySQL server
    myconnpy_logger.info("Bootstrapping a MySQL server")
    mysql_server.bootstrap()
    myconnpy_logger.info("Starting a MySQL server")
    mysql_server.start()
    
    myconnpy_logger.info("Starting unit tests")
    was_successful = False
    try:
        # Run test cases
        result = unittest.TextTestRunner(verbosity=options.verbosity).run(
            testsuite)
        was_successful = result.wasSuccessful()
    except KeyboardInterrupt:
        logger.info("Unittesting was interrupted")
        was_successful = False

    # Clean up
    if not options.keep:
        mysql_server.stop()
        mysql_server.remove()
        myconnpy_logger.info("MySQL server stopped and cleaned up")
    else:
        myconnpy_logger.info("MySQL server kept running on %s:%d" %
                             (options.bind_address, options.port))

    txt = ""
    if not was_successful:
        txt = "not "
    logger.info("MySQL Connector/Python unittests were %ssuccessful" % txt)

    # Return result of tests as exit code
    sys.exit(not was_successful)
예제 #9
0
def main():
    parser = _get_arg_parser()
    options = parser.parse_args()
    tests.OPTIONS_INIT = True

    if isinstance(options, tuple):
        # Fallback to old optparse
        options = options[0]

    tests.setup_logger(LOGGER, debug=options.debug, logfile=options.logfile)
    LOGGER.info(
        "MySQL Connector/Python unittest using Python v{0}".format(
            '.'.join([str(v) for v in sys.version_info[0:3]])))

    # Check if we can test IPv6
    if options.ipv6:
        if not tests.IPV6_AVAILABLE:
            LOGGER.error("Can not test IPv6: not available on your system")
            sys.exit(1)
        options.bind_address = '::'
        options.host = '::1'
        LOGGER.info("Testing using IPv6. Binding to :: and using host ::1")
    else:
        tests.IPV6_AVAILABLE = False

    if not options.mysql_sharedir:
        options.mysql_sharedir = os.path.join(options.mysql_basedir, 'share')
        LOGGER.debug("Setting default sharedir: %s", options.mysql_sharedir)
    if options.mysql_topdir != MYSQL_DEFAULT_TOPDIR:
        # Make sure the topdir is absolute
        if not os.path.isabs(options.mysql_topdir):
            options.mysql_topdir = os.path.join(
                os.path.dirname(os.path.realpath(__file__)),
                options.mysql_topdir
            )

    # If Django was supplied, add Django to PYTHONPATH
    if options.django_path:
        sys.path.insert(0, options.django_path)
        try:
            import django

            tests.DJANGO_VERSION = django.VERSION[0:3]
        except ImportError:
            msg = "Could not find django package at {0}".format(
                options.django_path)
            LOGGER.error(msg)
            sys.exit(1)

        if sys.version_info[0] == 3 and tests.DJANGO_VERSION < (1, 5):
            LOGGER.error("Django older than v1.5 will not work with Python 3")
            sys.exit(1)

    if options.fabric_config:
        # URL example: fabric://user:[email protected]:32274
        fab = urlsplit(options.fabric_config)
        tests.FABRIC_CONFIG = {
            'host': fab.hostname,
            'port': fab.port or 32274,
            'user': fab.username,
            'password': fab.password,
        }

    # Start Dummy MySQL Server
    #tests.MYSQL_DUMMY = mysqld.DummyMySQLServer(('127.0.0.1', options.port - 1),
    #                                            mysqld.DummyMySQLRequestHandler)
    #tests.MYSQL_DUMMY_THREAD = threading.Thread(
    #    target=tests.MYSQL_DUMMY.serve_forever)
    #tests.MYSQL_DUMMY_THREAD.setDaemon(True)

    # We have to at least run 1 MySQL server
    init_mysql_server(port=(options.port), options=options)

    # Which tests cases to run
    testcases = []
    testsuite = None

    if options.testcase:
        if options.testcase in tests.get_test_names():
            for module in tests.get_test_modules():
                if module.endswith('test_' + options.testcase):
                    testcases = [module]
                    break
            testsuite = unittest.TestLoader().loadTestsFromNames(testcases)
        else:
            msg = "Test case is not one of {0}".format(
                ', '.join(tests.get_test_names()))
            _show_help(msg=msg, parser=parser, exit_code=1)
    elif options.onetest:
        testsuite = unittest.TestLoader().loadTestsFromName(options.onetest)
    else:
        testcases = tests.get_test_modules()
        testsuite = unittest.TestLoader().loadTestsFromNames(testcases)

    # Initialize the other MySQL Servers
    for i in range(1, tests.MYSQL_SERVERS_NEEDED):
        init_mysql_server(port=(options.port + i), options=options)

    LOGGER.info("Using MySQL server version %s",
                '.'.join([str(v) for v in tests.MYSQL_VERSION[0:3]]))

    LOGGER.info("Starting unit tests")
    was_successful = False
    try:
        # Run test cases
        if options.stats:
            if options.stats_host:
                stats_db_info = {
                    'host': options.stats_host,
                    'port': options.stats_port,
                    'user': options.stats_user,
                    'password': options.stats_password,
                    'database': options.stats_db,
                }
                cnxstats = mysql.connector.connect(**stats_db_info)
                setup_stats_db(cnxstats)
            else:
                cnxstats = None
            result = StatsTestRunner(
                verbosity=options.verbosity, dbcnx=cnxstats).run(testsuite)
        elif sys.version_info[0:2] == (2, 6):
            result = Python26TestRunner(verbosity=options.verbosity).run(
                testsuite)
        else:
            result = BasicTestRunner(verbosity=options.verbosity).run(testsuite)
        was_successful = result.wasSuccessful()
    except KeyboardInterrupt:
        LOGGER.info("Unittesting was interrupted")
        was_successful = False

    # Log messages added by test cases
    for msg in tests.MESSAGES['WARNINGS']:
        LOGGER.warning(msg)
    for msg in tests.MESSAGES['INFO']:
        LOGGER.info(msg)

    # Show skipped tests
    if len(tests.MESSAGES['SKIPPED']):
        LOGGER.info("Skipped tests: %d", len(tests.MESSAGES['SKIPPED']))
        for msg in tests.MESSAGES['SKIPPED']:
            LOGGER.info("Skipped: " + msg)

    # Clean up
    try:
        tests.MYSQL_DUMMY_THREAD.join()
        tests.MYSQL_DUMMY.shutdown()
        tests.MYSQL_DUMMY.server_close()
    except:
        # Is OK when failed
        pass
    for mysql_server in tests.MYSQL_SERVERS:
        name = mysql_server.name
        if not options.keep:
            mysql_server.stop()
            if not mysql_server.wait_down():
                LOGGER.error("Failed stopping MySQL server '%s'", name)
            else:
                mysql_server.remove()
                LOGGER.info("MySQL server '%s' stopped and cleaned up", name)
        elif not mysql_server.check_running():
            mysql_server.start()
            if not mysql_server.wait_up():
                LOGGER.error("MySQL could not be kept running; "
                             "failed to restart")
        else:
            LOGGER.info("MySQL server kept running on %s:%d",
                        mysql_server.bind_address,
                        mysql_server.port
            )

    # Make sure the DEVNULL file is closed
    try:
        mysqld.DEVNULL.close()
    except:
        pass

    txt = ""
    if not was_successful:
        txt = "not "
    LOGGER.info("MySQL Connector/Python unittests were %ssuccessful", txt)

    # Return result of tests as exit code
    sys.exit(not was_successful)
예제 #10
0
_UNITTESTS_CMD_ARGS = {
    ('-T', '--one-test'): {
        'dest': 'onetest', 'metavar': 'NAME',
        'help': (
            'Particular test to execute, format: '
            '<module>[.<class>[.<method>]]. For example, to run a particular '
            'test BugOra13392739.test_reconnect() from the tests.test_bugs '
            'module, use following value for the -T option: '
            ' tests.test_bugs.BugOra13392739.test_reconnect')
    },

    ('-t', '--test'): {
        'dest': 'testcase', 'metavar': 'NAME',
        'help': 'Tests to execute, one of {names}'.format(
            names=tests.get_test_names())
    },

    ('-l', '--log'): {
        'dest': 'logfile', 'metavar': 'NAME', 'default': None,
        'help': 'Log file location (if not given, logging is disabled)'
    },

    ('', '--force'): {
        'dest': 'force', 'action': 'store_true', 'default': False,
        'help': 'Remove previous MySQL test installation.'
    },

    ('', '--keep'): {
        'dest': 'keep', 'action': "store_true", 'default': False,
        'help': 'Keep MySQL installation (i.e. for debugging)'
예제 #11
0
def main():
    parser = _get_arg_parser()
    options = parser.parse_args()

    if isinstance(options, tuple):
        # Fallback to old optparse
        options = options[0]

    setup_logger(LOGGER, debug=options.debug, logfile=options.logfile)
    LOGGER.info(
        "MySQL Connector/Python unittest "
        "started using Python v{0}".format(
            '.'.join([str(v) for v in sys.version_info[0:3]])))

    # Check if we can test IPv6
    if options.ipv6:
        if not tests.IPV6_AVAILABLE:
            LOGGER.error("Can not test IPv6: not available on your system")
            sys.exit(1)
        options.bind_address = '::'
        options.host = '::1'
        LOGGER.info("Testing using IPv6. Binding to :: and using host ::1")
    else:
        tests.IPV6_AVAILABLE = False

    # Which tests cases to run
    if options.testcase:
        if options.testcase in tests.get_test_names():
            for module in tests.get_test_modules():
                if module.endswith('test_' + options.testcase):
                    testcases = [module]
                    break
            testsuite = unittest.TestLoader().loadTestsFromNames(testcases)
        else:
            msg = "Test case is not one of {0}".format(
                ', '.join(tests.get_test_names()))
            _show_help(msg=msg, parser=parser, exit_code=1)
    elif options.onetest:
        testsuite = unittest.TestLoader().loadTestsFromName(options.onetest)
    else:
        testcases = tests.get_test_modules()
        testsuite = unittest.TestLoader().loadTestsFromNames(testcases)

    # Initialize the MySQL Servers
    for i in range(0, tests.MYSQL_SERVERS_NEEDED):
        init_mysql_server(port=(options.port + i), options=options)

    LOGGER.info(
        "Using MySQL server version {0}".format(
            '.'.join([str(v) for v in tests.MYSQL_VERSION[0:3]])))

    LOGGER.info("Starting unit tests")
    was_successful = False
    try:
        # Run test cases
        if options.stats:
            if options.stats_host:
                stats_db_info = {
                    'host': options.stats_host,
                    'port': options.stats_port,
                    'user': options.stats_user,
                    'password': options.stats_password,
                    'database': options.stats_db,
                }
                cnxstats = mysql.connector.connect(**stats_db_info)
                setup_stats_db(cnxstats)
            else:
                cnxstats = None
            result = StatsTestRunner(
                verbosity=options.verbosity, dbcnx=cnxstats).run(
                testsuite)
        elif sys.version_info[0:2] == (2, 6):
            result = Python26TestRunner(verbosity=options.verbosity).run(
                testsuite)
        else:
            result = BasicTestRunner(verbosity=options.verbosity).run(
                testsuite)
        was_successful = result.wasSuccessful()
    except KeyboardInterrupt:
        LOGGER.info("Unittesting was interrupted")
        was_successful = False

    # Log messages added by test cases
    for msg in tests.MESSAGES['WARNINGS']:
        LOGGER.warning(msg)
    for msg in tests.MESSAGES['INFO']:
        LOGGER.info(msg)

    # Show skipped tests
    if len(tests.MESSAGES['SKIPPED']):
        LOGGER.info(
            "Skipped tests: {0}".format(
                len(tests.MESSAGES['SKIPPED'])))
        if options.verbosity >= 1 or options.debug:
            for msg in tests.MESSAGES['SKIPPED']:
                LOGGER.info(msg)

    # Clean up
    for mysql_server in tests.MYSQL_SERVERS:
        name = mysql_server.name
        if not options.keep:
            mysql_server.stop()
            if not mysql_server.wait_down():
                LOGGER.error("Failed stopping MySQL server '{name}'".format(
                    name=name))
            else:
                mysql_server.remove()
                LOGGER.info(
                    "MySQL server '{name}' stopped and cleaned up".format(
                        name=name))
        elif not mysql_server.check_running():
            mysql_server.start()
            if not mysql_server.wait_up():
                LOGGER.error("MySQL could not be kept running; "
                             "failed to restart")
        else:
            LOGGER.info("MySQL server kept running on {addr}:{port}".format(
                addr=mysql_server.bind_address,
                port=mysql_server.port)
            )

    txt = ""
    if not was_successful:
        txt = "not "
    LOGGER.info(
        "MySQL Connector/Python unittests were {result}successful".format(
            result=txt))

    # Return result of tests as exit code
    sys.exit(not was_successful)
예제 #12
0
_UNITTESTS_CMD_ARGS = {
    ('-T', '--one-test'): {
        'dest': 'onetest', 'metavar': 'NAME',
        'help': (
            'Particular test to execute, format: '
            '<module>[.<class>[.<method>]]. For example, to run a particular '
            'test BugOra13392739.test_reconnect() from the tests.test_bugs '
            'module, use following value for the -T option: '
            ' tests.test_bugs.BugOra13392739.test_reconnect')
    },

    ('-t', '--test'): {
        'dest': 'testcase', 'metavar': 'NAME',
        'help': 'Tests to execute, one of {names}'.format(
            names=tests.get_test_names())
    },

    ('-l', '--log'): {
        'dest': 'logfile', 'metavar': 'NAME', 'default': None,
        'help': 'Log file location (if not given, logging is disabled)'
    },

    ('', '--force'): {
        'dest': 'force', 'action': 'store_true', 'default': False,
        'help': 'Remove previous MySQL test installation.'
    },

    ('', '--keep'): {
        'dest': 'keep', 'action': "store_true", 'default': False,
        'help': 'Keep MySQL installation (i.e. for debugging)'
예제 #13
0
def main():
    options = _get_arg_options()

    tests.setup_logger(LOGGER, debug=options.debug, logfile=options.logfile)
    LOGGER.info("MySQL Connector/Python unittest "
                "started using Python v{0}".format('.'.join(
                    [str(v) for v in sys.version_info[0:3]])))

    # Check if we can test IPv6
    if options.ipv6:
        if not tests.IPV6_AVAILABLE:
            LOGGER.error("Can not test IPv6: not available on your system")
            sys.exit(1)
        options.bind_address = '::'
        options.host = '::1'
        LOGGER.info("Testing using IPv6. Binding to :: and using host ::1")
    else:
        tests.IPV6_AVAILABLE = False

    # Which tests cases to run
    if options.testcase:
        if options.testcase in tests.get_test_names():
            for module in tests.get_test_modules():
                if module.endswith('test_' + options.testcase):
                    testcases = [module]
                    break
            testsuite = unittest.TestLoader().loadTestsFromNames(testcases)
        else:
            msg = "Test case is not one of {0}".format(', '.join(
                tests.get_test_names()))
            _show_help(msg=msg, parser=parser, exit_code=1)
    elif options.onetest:
        testsuite = unittest.TestLoader().loadTestsFromName(options.onetest)
    else:
        testcases = tests.get_test_modules()
        testsuite = unittest.TestLoader().loadTestsFromNames(testcases)

    # Initialize the MySQL Servers
    for i in range(0, tests.MYSQL_SERVERS_NEEDED):
        init_mysql_server(port=(options.port + i), options=options)

    LOGGER.info("Using MySQL server version {0}".format('.'.join(
        [str(v) for v in tests.MYSQL_VERSION[0:3]])))

    LOGGER.info("Starting unit tests")
    was_successful = False
    try:
        # Run test cases
        if options.stats:
            if options.stats_host:
                stats_db_info = {
                    'host': options.stats_host,
                    'port': options.stats_port,
                    'user': options.stats_user,
                    'password': options.stats_password,
                    'database': options.stats_db,
                }
                cnxstats = mysql.connector.connect(**stats_db_info)
                setup_stats_db(cnxstats)
            else:
                cnxstats = None
            result = StatsTestRunner(verbosity=options.verbosity,
                                     dbcnx=cnxstats).run(testsuite)
        elif sys.version_info[0:2] == (2, 6):
            result = Python26TestRunner(
                verbosity=options.verbosity).run(testsuite)
        else:
            result = BasicTestRunner(
                verbosity=options.verbosity).run(testsuite)
        was_successful = result.wasSuccessful()
    except KeyboardInterrupt:
        LOGGER.info("Unittesting was interrupted")
        was_successful = False

    # Log messages added by test cases
    for msg in tests.MESSAGES['WARNINGS']:
        LOGGER.warning(msg)
    for msg in tests.MESSAGES['INFO']:
        LOGGER.info(msg)

    # Show skipped tests
    if len(tests.MESSAGES['SKIPPED']):
        LOGGER.info("Skipped tests: {0}".format(len(
            tests.MESSAGES['SKIPPED'])))
        if options.verbosity >= 1 or options.debug:
            for msg in tests.MESSAGES['SKIPPED']:
                LOGGER.info(msg)

    # Clean up
    for mysql_server in tests.MYSQL_SERVERS:
        name = mysql_server.name
        if not options.keep:
            mysql_server.stop()
            if not mysql_server.wait_down():
                LOGGER.error(
                    "Failed stopping MySQL server '{name}'".format(name=name))
            else:
                mysql_server.remove()
                LOGGER.info(
                    "MySQL server '{name}' stopped and cleaned up".format(
                        name=name))
        elif not mysql_server.check_running():
            mysql_server.start()
            if not mysql_server.wait_up():
                LOGGER.error("MySQL could not be kept running; "
                             "failed to restart")
        else:
            LOGGER.info("MySQL server kept running on {addr}:{port}".format(
                addr=mysql_server.bind_address, port=mysql_server.port))

    txt = ""
    if not was_successful:
        txt = "not "
    LOGGER.info(
        "MySQL Connector/Python unittests were {result}successful".format(
            result=txt))

    # Return result of tests as exit code
    sys.exit(not was_successful)
예제 #14
0
def _add_options(p):
    p.add_option('-t',
                 '--test',
                 dest='testcase',
                 metavar='NAME',
                 help='Tests to execute, one of %s' % tests.get_test_names())
    p.add_option('-l',
                 '--log',
                 dest='logfile',
                 metavar='NAME',
                 default=None,
                 help='Log file location (if not given, logging is disabled)')
    p.add_option('',
                 '--force',
                 dest='force',
                 action="store_true",
                 default=False,
                 help='Remove previous MySQL test installation.')
    p.add_option('',
                 '--keep',
                 dest='keep',
                 action="store_true",
                 default=False,
                 help='Keep MySQL installation (i.e. for debugging)')
    p.add_option('',
                 '--debug',
                 dest='debug',
                 action="store_true",
                 default=False,
                 help='Show/Log debugging messages')
    p.add_option('',
                 '--verbosity',
                 dest='verbosity',
                 metavar='NUMBER',
                 default='0',
                 type="int",
                 help='Verbosity of unittests (default 0)')

    p.add_option('','--mysql-basedir', dest='mysql_basedir',
        metavar='NAME', default='/usr/local/mysql',
        help='Where MySQL is installed. This is used to bootstrap and '\
         'run a MySQL server which is used for unittesting only.')
    p.add_option('','--mysql-topdir', dest='mysql_topdir',
        metavar='NAME',
        default=os.path.join(os.path.dirname(os.path.abspath(__file__)),
            'mysql_myconnpy'),
        help='Where to bootstrap the new MySQL instance for testing. '\
         'Defaults to current ./mysql_myconnpy')
    p.add_option('',
                 '--bind-address',
                 dest='bind_address',
                 metavar='NAME',
                 default='127.0.0.1',
                 help='IP address to bind to')
    p.add_option('-P',
                 '--port',
                 dest='port',
                 metavar='NUMBER',
                 default='33770',
                 type="int",
                 help='Port to use for TCP/IP connections.')
예제 #15
0
def main():
    usage = 'usage: %prog [options]'
    parser = OptionParser()
    _add_options(parser)

    # Set options
    (options, args) = parser.parse_args()
    option_file = os.path.join(options.mysql_topdir, 'myconnpy_my.cnf')
    unix_socket = os.path.join(options.mysql_topdir, 'myconnpy_mysql.sock')
    _set_config(options, unix_socket=unix_socket)

    # Init the MySQL Server object
    mysql_server = mysqld.MySQLInit(options.mysql_basedir,
                                    options.mysql_topdir, MY_CNF, option_file,
                                    options.bind_address, options.port,
                                    unix_socket)
    mysql_server._debug = options.debug

    # Force removal of previous test data
    if options.force is True:
        mysql_server.remove()

    # Which tests cases to run
    if options.testcase is not None:
        if options.testcase in tests.get_test_names():
            testcases = ['tests.test_%s' % options.testcase]
        else:
            msg = "Test case is not one of %s" % tests.get_test_names()
            _show_help(msg=msg, parser=parser, exit=1)
    else:
        testcases = tests.active_testcases

    # Enabling logging
    formatter = logging.Formatter(
        "%(asctime)s [%(name)s:%(levelname)s] %(message)s")
    myconnpy_logger = logging.getLogger('myconnpy')
    fh = None
    if options.logfile is not None:
        fh = logging.FileHandler(options.logfile)
    else:
        fh = logging.StreamHandler()
    fh.setFormatter(formatter)
    logger.addHandler(fh)
    if options.debug is True:
        logger.setLevel(logging.DEBUG)
        myconnpy_logger.setLevel(logging.DEBUG)
    else:
        myconnpy_logger.setLevel(logging.INFO)
    myconnpy_logger.addHandler(fh)
    logger.info("MySQL Connector/Python unittest started")

    # Bootstrap and start a MySQL server
    mysql_server.bootstrap()
    mysql_server.start()

    # Run test cases
    suite = unittest.TestLoader().loadTestsFromNames(testcases)
    result = unittest.TextTestRunner(verbosity=options.verbosity).run(suite)
    txt = ""
    if not result.wasSuccessful():
        txt = "not "
    logger.info("MySQL Connector/Python unittests were %ssuccessful" % txt)

    # Clean up
    mysql_server.stop()
    if options.keep is not True:
        mysql_server.remove()

    # Return result of tests as exit code
    sys.exit(not result.wasSuccessful())