Beispiel #1
0
 def test_connect_with_invalid_user_or_password(self):
     with self.assertRaises(connector.DatabaseError):
         conx = connector.connect(user='******',
                                  password='******',
                                  host=config['host'],
                                  port=config['port'])
         cnx1 = connector.connect(user='******',
                                  password='******',
                                  host=config['host'],
                                  port=config['port'])
Beispiel #2
0
 def test_wrong_charset(self):
     cnx = connector.connect(**config)
     print(cnx.property.charset)
     cnx.close()
     with self.assertRaises(connector.ProgrammingError):
         conx1 = connector.connect(
             host=config['host'],
             user=config['user'],
             password=config['password'],
             port=config['port'],
             database='python_testsch1',
             charset='not_exist',
         )
         cursor = conx1.cursor()
Beispiel #3
0
 def test_connect_host_user_password_port_database(self):
     conx = connector.connect(**config)
     cursor = conx.cursor()
     cursor.execute('create schema if not exists python_testsch1')
     cursor.execute('set schema python_testsch1')
     cursor.execute('create table if not EXISTS python_testtb(i int)')
     cursor.close()
     conx1 = connector.connect(host=config['host'],
                               user=config['user'],
                               password=config['password'],
                               port=config['port'],
                               schema='python_testsch1')
     cursor = conx1.cursor()
     cursor.execute('get tables')
     self.assertTrue(('PYTHON_TESTTB', ) in cursor)
    def test_dml_syntax_err_1(self):
        try:
            cnx = None
            if not self.log_file_name:
                print("log file's name is not configured in logger handler")
                return

            with open(self.log_file_name, 'w') as f:
                f.truncate()

            cnx = connector.connect(**config)
            cursor = cnx.cursor()

            cursor.execute(
                'create table if not exists tb_test_logmodule(c1 int)')
            cursor.execute("insert into tb_test_logmodule values('abc')")
        except Exception as e:
            if not cnx:
                raise e

            with open(self.log_file_name, 'r') as f:
                expect_str = '*** ERROR[8413] The string argument contains characters that cannot be converted.'

                log_content = f.read()
                print(log_content)
                print(expect_str)

                if log_content.find(expect_str) == -1:
                    self.fail(
                        'test_dml_syntax_err_1 fail, expect log not found in log file, case Fail!!!'
                    )
        finally:
            if cnx:
                cnx.close()
    def test_ddl_err_1(self):
        try:
            cnx = None
            if not self.log_file_name:
                print("log file's name is not configured in logger handler")
                return

            with open(self.log_file_name, 'w') as f:
                f.truncate()

            cnx = connector.connect(**config)
            cursor = cnx.cursor()
            cursor.execute('drop table tb_not_exist')
        except Exception as e:
            if not cnx:
                raise e

            with open(self.log_file_name, 'r') as f:
                expect_str = 'TB_NOT_EXIST does not exist in Trafodion'

                log_content = f.read()
                print(log_content)
                print(expect_str)

                if log_content.find(expect_str) == -1:
                    self.fail(
                        'test_ddl_err_0 fail, expect log not found in log file, case Fail!!!'
                    )
        finally:
            if cnx:
                cnx.close()
    def test_ddl_err_0(self):
        try:
            cnx = None
            if not self.log_file_name:
                print("log file's name is not configured in logger handler")
                return

            with open(self.log_file_name, 'w') as f:
                f.truncate()

            cnx = connector.connect(**config)
            cursor = cnx.cursor()
            cursor.execute(
                'create table if not exists tb_test_logmodule(c1 int)')
            cursor.execute('create table tb_test_logmodule(c1 int)')

        except Exception as e:
            if not cnx:
                raise e

            with open(self.log_file_name, 'r') as f:
                expect_str = 'TB_TEST_LOGMODULE already exists in Trafodion'

                log_content = f.read()
                print(log_content)
                print(expect_str)

                if log_content.find(expect_str) == -1:
                    self.fail(
                        'test_ddl_err_0 fail, expect log not found in log file, case Fail!!!'
                    )
        finally:
            if cnx:
                cnx.close()
 def test_normal_close(self):
     try:
         cnx = connector.connect(**config)
         cursor = cnx.cursor()
         cnx.close()
     except Exception:
         self.fail('test_normal_close() raise Exception unexpectedly')
Beispiel #8
0
    def __init__(self, auto_commit=True, log_prefix=""):
        super(QueryTerminal, self).__init__()
        try:
            self.connection = connector.connect(**config)
            self.connection.set_auto_commit(auto_commit)
            self.cursor = self.connection.cursor()
            self.stored_result_dict = {}
            self.log_prefix = log_prefix
        except Warning as w:
            print("Connection Warning: ", w)
        except Exception as e:
            print("Connection Exception: ", e.args)
            raise FatalError(e.args)

        # item of queue is a list
        # list idx 0: task type [0 close, 1 execute query, 2 fetch result]
        # list idx 1: task text
        # list idx 2: additional control info [0 nothing]
        self.task_queue = queue.Queue(20)

        # 0 not start, 1 waiting input, 2 executing, 3 down,  4 fatal error
        self.status = 0

        # idx 0: last execution return code, 0 success, 1 warning, 2 error
        # idx 1: last error or warning message if exists
        self.last_execution_result = [0, "", -1]
Beispiel #9
0
 def test_connect_with_invalid_parameter(self):
     with self.assertRaises(connector.Error):
         conx = connector.connect(host=config['host'],
                                  user=config['user'],
                                  password=config['password'],
                                  port=config['port'],
                                  invalid_param="invalid_param")
Beispiel #10
0
 def test_tenant_name(self):
     conx1 = connector.connect(host=config['host'],
                               port=config['port'],
                               user=config['user'],
                               password=config['password'],
                               tenant_name="ESGYNDB")
     conx1.close()
Beispiel #11
0
 def test_commit(self):
     """
     read committed level check.
     """
     cnx2 = connector.connect(user=config['user'],
                              password=config['password'])
     cnx2.close()
Beispiel #12
0
 def test_no_user(self):
     try:
         conx1 = connector.connect(host=config['host'],
                                   port=config['port'],
                                   password=config['password'])
     except Exception as expect_info:
         pass
    def test_dml_syntax_err_0(self):
        try:
            cnx = None
            if not self.log_file_name:
                print("log file's name is not configured in logger handler")
                return

            with open(self.log_file_name, 'w') as f:
                f.truncate()

            cnx = connector.connect(**config)
            cursor = cnx.cursor()

            cursor.execute(
                'create table if not exists tb_test_logmodule(c1 int)')
            cursor.execute('inserrrrrt into tb_test_logmodule values(1)')
        except Exception as e:
            if not cnx:
                raise e

            with open(self.log_file_name, 'r') as f:
                expect_str = '*** ERROR[15001] A syntax error occurred at or before: \n\
inserrrrrt into tb_test_logmodule values(1);'

                log_content = f.read()
                print(log_content)
                print(expect_str)

                if log_content.find(expect_str) == -1:
                    self.fail(
                        'test_dml_syntax_err_0 fail, expect log not found in log file, case Fail!!!'
                    )
        finally:
            if cnx:
                cnx.close()
    def test_ddl_success(self):
        try:
            cnx = None
            if not self.log_file_name:
                print("log file's name is not configured in logger handler")
                return

            with open(self.log_file_name, 'w') as f:
                f.truncate()

            cnx = connector.connect(**config)
            cursor = cnx.cursor()
            cursor.execute(
                'create table if not exists tb_test_logmodule(c1 int)')
            cursor.execute('drop table if exists tb_test_logmodule')

            with open(self.log_file_name, 'r') as f:
                log_content = f.read()
                print(log_content)

                expect_str = "EXECUTE SUCCESS\n\
Execute Type: SQLEXECDIRECT\n\
Query: b'create table if not exists tb_test_logmodule(c1 int)'"

                print(expect_str)

                if self.log_level == logging._checkLevel("DEBUG"):
                    if log_content.find(expect_str) == -1:
                        self.fail(
                            'log about create table, debug info should be logged, case Fail!!!'
                        )
                else:
                    if log_content.find(expect_str) != -1:
                        self.fail(
                            'log about create table, debug info should not be logged, case Fail!!!'
                        )

                expect_str = "EXECUTE SUCCESS\n\
Execute Type: SQLEXECDIRECT\n\
Query: b'drop table if exists tb_test_logmodule'"

                print(expect_str)

                if self.log_level == logging._checkLevel("DEBUG"):
                    if log_content.find(expect_str) == -1:
                        self.fail(
                            'log about drop table, debug info should be logged, case Fail!!!'
                        )
                else:
                    if log_content.find(expect_str) != -1:
                        self.fail(
                            'log about drop table, debug info should not be logged, case Fail!!!'
                        )

        except Exception as e:
            raise e
        finally:
            if cnx:
                cnx.close()
Beispiel #15
0
 def setUp(self):
     self.cnx = connector.connect(host=config['host'],
                                  user=config['user'],
                                  password=config['password'],
                                  database=config['database'])
     self.cursor = self.cnx.cursor()
     self.cursor.execute('drop table if EXISTS bank_account cascade')
     self.cursor.execute('create table bank_account(id int, money float)')
Beispiel #16
0
 def test_rowcount_after_execute(self):
     # table 'employee' has 5 records
     cnx = connector.connect(**config)
     cursor = cnx.cursor()
     cursor.execute('select * from employee')
     self.assertEqual(cursor.rowcount, -1)
     cursor.close()
     cnx.close()
 def test_connect_keyvalue_args_1(self):
     config = {
         'host':'10.10.23.54',
         'user':'******',
         'password':'******'
     }
     conx = connector.connect(config)
     self.assertTrue(isinstance(conx, connector.TrafConnection))
Beispiel #18
0
 def test_no_password(self):
     try:
         conx1 = connector.connect(
             host=config['host'],
             port=config['port'],
             user=config['user'],
         )
     except Exception as expect_info:
         pass
 def test_ddl_err_tmp(self):
     try:
         cnx = None
         cnx = connector.connect(**config)
         cursor = cnx.cursor()
         cursor.execute('drop table tb_not_exist')
     finally:
         if cnx:
             cnx.close()
 def test_connect_with_invalid_kevalue_args(self):
     wrongconfig = {
         'host':config['host'],
         'port':config['port'],
         'user':'******',
         'password':'******'
     }
     with self.assertRaises(Exception):
         conx = connector.connect(wrongconfig)
 def test_close_connection_with_opened_cursor(self):
     try:
         cnx = connector.connect(**config)
         cursor = cnx.cursor()
         cursor.execute('get tables')
         cnx.close()
     except Exception:
         self.fail(
             'test_close_connection_with_opened_cursor() raise exception unexpectedly'
         )
 def test_close_after_execute(self):
     try:
         cnx = connector.connect(**config)
         cursor = cnx.cursor()
         cursor.execute('insert into bank_account values(?, ?)',
                        (self.getId(), 123.456))
         cnx.close()
     except Exception:
         self.fail(
             'test_close_after_execute() raised Exception unexpectedly!')
    def test_commit_on_closed_connection(self):
        row1 = (self.getId(), 789.12345)

        cnx = connector.connect(**config)
        cnx.set_auto_commit(False)
        cursor = cnx.cursor()
        cursor.execute('insert into bank_account values(?, ?)', row1)
        cnx.close()
        with self.assertRaises(connector.Error):
            cnx.commit()
    def test_auto_commit_true(self):
        row1 = (self.getId(), 2345.678)

        cnx = connector.connect(**config)
        cnx.set_auto_commit(True)
        cursor = cnx.cursor()
        cursor.execute('insert into bank_account values(?, ?)', row1)
        cnx.close()
        self.cursor.execute('select * from bank_account where id = ?',
                            (row1[0], ))
        res = self.cursor.fetchall()
        self.assertTrue(row1 in res)
    def test_normal_rollback(self):
        row1 = (self.getId(), 1.23456)

        cnx = connector.connect(**config)
        cnx.set_auto_commit(False)
        cursor = cnx.cursor()
        cursor.execute('insert into bank_account values(?, ?)', row1)
        cnx.rollback()
        cnx.close()
        self.cursor.execute('select * from bank_account where id = ?',
                            (row1[0], ))
        resultset = self.cursor.fetchall()
        # result set should empty
        self.assertTrue(len(resultset) is 0)
Beispiel #26
0
 def setUpClass(cls):
     cls.testdata = [(1, 'Manager A', 2.0, datetime.date(2008, 7, 16)),
                     (2, 'Manager B', 2.1, datetime.date(2008, 7, 16)),
                     (3, 'Dev A', 1.9, datetime.date(2018, 7, 16)),
                     (4, 'Dev B', 1.8, datetime.date(2018, 7, 16)),
                     (5, 'Dev C', 1.7, datetime.date(2018, 7, 16))]
     cls.cnx = connector.connect(**config)
     cursor = cls.cnx.cursor()
     cursor.execute("DROP TABLE IF EXISTS employee CASCADE")
     cursor.execute(
         "CREATE TABLE employee (id INT, name CHAR(20), salary DOUBLE PRECISION , hire_date DATE)"
     )
     query = "INSERT INTO employee VALUES (?, ?, ?, ?)"
     cursor.executemany(query, cls.testdata)
     cursor.close()
Beispiel #27
0
    def test_insert_not_list_and_tuple(self):
        cnx = connector.connect(**config)
        cursor = cnx.cursor()
        cursor.execute("DROP TABLE IF EXISTS employee1 CASCADE")
        cursor.execute(
            "CREATE TABLE employee1 (id INT, name CHAR(20), salary DOUBLE PRECISION , hire_date DATE)"
        )
        query = "INSERT INTO employee1 VALUES (?, ?, ?, ?)"
        with self.assertRaises(connector.DataError):
            cursor.execute(query, 100)

        with self.assertRaises(connector.DataError):
            cursor.executemany(query, 100)
        cursor.close()
        cnx.close()
    def test_commit_after_commit(self):
        row1 = (self.getId(), 789.12345)
        row2 = (self.getId(), 89123.456)

        cnx = connector.connect(**config)
        cnx.set_auto_commit(False)
        cursor = cnx.cursor()
        cursor.execute('insert into bank_account values(?, ?)', row1)
        cnx.commit()
        cursor.execute('insert into bank_account values(?, ?)', row2)
        cnx.commit()
        cnx.close()
        self.cursor.execute('select * from bank_account')
        results = self.cursor.fetchall()
        self.assertTrue(row1 in results)
        self.assertTrue(row2 in results)
    def test_normal_commit(self):
        """
        read committed level check.
        """
        id = self.getId()
        money = 2345.678
        row = (id, money)

        cnx = connector.connect(**config)
        cnx.set_auto_commit(False)
        cursor = cnx.cursor()
        cursor.execute('insert into bank_account values(?,?)', (id, money))
        cnx.commit()
        cnx.close()
        self.cursor.execute('select * from bank_account where id=?', (id, ))
        res = self.cursor.fetchone()
        self.assertEqual(res, row)
Beispiel #30
0
    def test_description_of_all_support_type(self):
        # col_name | col_def | expect_col_name | expect_type_code |
        #             expected_internal_size | expected_precision | scale | null_ok
        table_name = 'test_all_datatype'
        matrix = [('c_char', 'char(10)'), ('c_nchar', 'nchar(10)'),
                  ('c_varchar', 'varchar(10)'),
                  ('c_nvarchar', 'nchar varying(10)'), ('c_date', 'date'),
                  ('c_time', 'time'), ('c_time_with_precision', 'time(2)'),
                  ('c_timestamp', 'timestamp'),
                  ('c_timestamp_with_precision', 'timestamp(3)'),
                  ('c_interval_year', 'interval year'),
                  ('c_interval_year_month', 'interval year to month'),
                  ('c_interval_day', 'interval day'),
                  ('c_interval_hour', 'interval hour'),
                  ('c_interval_minute', 'interval minute'),
                  ('c_interval_second', 'interval second'), ('c_blob', 'blob'),
                  ('c_clob', 'clob'), ('c_numeric', 'numeric(19, 0)'),
                  ('c_numeric_precision', 'numeric(128)'),
                  ('c_float', 'float'), ('c_real', 'real'),
                  ('c_double', 'double precision'),
                  ('c_decimal', 'decimal(18, 2)')]

        ddlstr = f'create table {table_name}('
        for i, co in enumerate(matrix):
            ddlstr += co[0] + ' ' + co[1]
            if (i != len(matrix) - 1):
                ddlstr += ', '
        ddlstr += ')'

        cnx = connector.connect(**config)
        cursor = cnx.cursor()
        cursor.execute(f'drop table if exists {table_name} cascade')
        cursor.execute(ddlstr)
        cursor.execute(f'select * from {table_name}')
        desc = cursor.description
        # print('\n')
        # print('Name                    | TypeCode | DisplaySize | InternalSize | Precision | Scale | Null_ok\n')
        # for d in desc:
        #     print('%-30s, %10d, %10d, %12d, %10d, %8d, %s'% (d[0], d[1], d[2], d[3], d[4], d[5], d[6]))

        cursor.close()
        cnx.close()