Rework test suite further to use PEP 8 style guidelines.

This commit is contained in:
Anthony Tuininga 2020-11-02 15:25:51 -07:00
parent ef3d84318e
commit 229f9f5533
27 changed files with 3070 additions and 2932 deletions

View File

@ -44,7 +44,8 @@
# user for on premises databases is SYSTEM. # user for on premises databases is SYSTEM.
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle as oracledb
import getpass import getpass
import os import os
import sys import sys
@ -60,136 +61,137 @@ DEFAULT_CONNECT_STRING = "localhost/orclpdb1"
# directly) and then stored so that a value is not requested more than once # directly) and then stored so that a value is not requested more than once
PARAMETERS = {} PARAMETERS = {}
def GetValue(name, label, defaultValue=""): def get_value(name, label, default_value=""):
value = PARAMETERS.get(name) value = PARAMETERS.get(name)
if value is not None: if value is not None:
return value return value
envName = "CX_ORACLE_TEST_" + name env_name = "CX_ORACLE_TEST_" + name
value = os.environ.get(envName) value = os.environ.get(env_name)
if value is None: if value is None:
if defaultValue: if default_value:
label += " [%s]" % defaultValue label += " [%s]" % default_value
label += ": " label += ": "
if defaultValue: if default_value:
value = input(label).strip() value = input(label).strip()
else: else:
value = getpass.getpass(label) value = getpass.getpass(label)
if not value: if not value:
value = defaultValue value = default_value
PARAMETERS[name] = value PARAMETERS[name] = value
return value return value
def GetMainUser(): def get_admin_connect_string():
return GetValue("MAIN_USER", "Main User Name", DEFAULT_MAIN_USER) admin_user = get_value("ADMIN_USER", "Administrative user", "admin")
admin_password = get_value("ADMIN_PASSWORD",
"Password for %s" % admin_user)
return "%s/%s@%s" % (admin_user, admin_password, get_connect_string())
def GetMainPassword(): def get_charset_ratio():
return GetValue("MAIN_PASSWORD", "Password for %s" % GetMainUser())
def GetProxyUser():
return GetValue("PROXY_USER", "Proxy User Name", DEFAULT_PROXY_USER)
def GetProxyPassword():
return GetValue("PROXY_PASSWORD", "Password for %s" % GetProxyUser())
def GetConnectString():
return GetValue("CONNECT_STRING", "Connect String", DEFAULT_CONNECT_STRING)
def GetCharSetRatio():
value = PARAMETERS.get("CS_RATIO") value = PARAMETERS.get("CS_RATIO")
if value is None: if value is None:
connection = GetConnection() connection = get_connection()
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute("select 'X' from dual") cursor.execute("select 'X' from dual")
col, = cursor.description column_info, = cursor.description
value = col[3] value = PARAMETERS["CS_RATIO"] = column_info[3]
PARAMETERS["CS_RATIO"] = value
return value return value
def GetAdminConnectString(): def get_client_version():
adminUser = GetValue("ADMIN_USER", "Administrative user", "admin") name = "CLIENT_VERSION"
adminPassword = GetValue("ADMIN_PASSWORD", "Password for %s" % adminUser) value = PARAMETERS.get(name)
return "%s/%s@%s" % (adminUser, adminPassword, GetConnectString()) if value is None:
value = oracledb.clientversion()[:2]
PARAMETERS[name] = value
return value
def RunSqlScript(conn, scriptName, **kwargs): def get_connection(**kwargs):
statementParts = [] return oracledb.connect(dsn=get_connect_string(), user=get_main_user(),
password=get_main_password(), **kwargs)
def get_connect_string():
return get_value("CONNECT_STRING", "Connect String",
DEFAULT_CONNECT_STRING)
def get_main_password():
return get_value("MAIN_PASSWORD", "Password for %s" % get_main_user())
def get_main_user():
return get_value("MAIN_USER", "Main User Name", DEFAULT_MAIN_USER)
def get_pool(user=None, password=None, **kwargs):
if user is None:
user = get_main_user()
if password is None:
password = get_main_password()
return oracledb.SessionPool(user, password, get_connect_string(),
**kwargs)
def get_proxy_password():
return get_value("PROXY_PASSWORD", "Password for %s" % get_proxy_user())
def get_proxy_user():
return get_value("PROXY_USER", "Proxy User Name", DEFAULT_PROXY_USER)
def get_server_version():
name = "SERVER_VERSION"
value = PARAMETERS.get(name)
if value is None:
conn = get_connection()
value = tuple(int(s) for s in conn.version.split("."))[:2]
PARAMETERS[name] = value
return value
def run_sql_script(conn, script_name, **kwargs):
statement_parts = []
cursor = conn.cursor() cursor = conn.cursor()
replaceValues = [("&" + k + ".", v) for k, v in kwargs.items()] + \ replace_values = [("&" + k + ".", v) for k, v in kwargs.items()] + \
[("&" + k, v) for k, v in kwargs.items()] [("&" + k, v) for k, v in kwargs.items()]
scriptDir = os.path.dirname(os.path.abspath(sys.argv[0])) script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
fileName = os.path.join(scriptDir, "sql", scriptName + "Exec.sql") file_name = os.path.join(script_dir, "sql", script_name + "Exec.sql")
for line in open(fileName): for line in open(file_name):
if line.strip() == "/": if line.strip() == "/":
statement = "".join(statementParts).strip() statement = "".join(statement_parts).strip()
if statement: if statement:
for searchValue, replaceValue in replaceValues: for search_value, replace_value in replace_values:
statement = statement.replace(searchValue, replaceValue) statement = statement.replace(search_value, replace_value)
try: try:
cursor.execute(statement) cursor.execute(statement)
except: except:
print("Failed to execute SQL:", statement) print("Failed to execute SQL:", statement)
raise raise
statementParts = [] statement_parts = []
else: else:
statementParts.append(line) statement_parts.append(line)
cursor.execute(""" cursor.execute("""
select name, type, line, position, text select name, type, line, position, text
from dba_errors from dba_errors
where owner = upper(:owner) where owner = upper(:owner)
order by name, type, line, position""", order by name, type, line, position""",
owner = GetMainUser()) owner = get_main_user())
prevName = prevObjType = None prev_name = prev_obj_type = None
for name, objType, lineNum, position, text in cursor: for name, obj_type, line_num, position, text in cursor:
if name != prevName or objType != prevObjType: if name != prev_name or obj_type != prev_obj_type:
print("%s (%s)" % (name, objType)) print("%s (%s)" % (name, obj_type))
prevName = name prev_name = name
prevObjType = objType prev_obj_type = obj_type
print(" %s/%s %s" % (lineNum, position, text)) print(" %s/%s %s" % (line_num, position, text))
def RunTestCases(): def run_test_cases():
print("Running tests for cx_Oracle version", cx_Oracle.version, print("Running tests for cx_Oracle version", oracledb.version,
"built at", cx_Oracle.buildtime) "built at", oracledb.buildtime)
print("File:", cx_Oracle.__file__) print("File:", oracledb.__file__)
print("Client Version:", print("Client Version:",
".".join(str(i) for i in cx_Oracle.clientversion())) ".".join(str(i) for i in oracledb.clientversion()))
with GetConnection() as connection: with get_connection() as connection:
print("Server Version:", connection.version) print("Server Version:", connection.version)
print() print()
unittest.main(testRunner=unittest.TextTestRunner(verbosity=2)) unittest.main(testRunner=unittest.TextTestRunner(verbosity=2))
def GetConnection(**kwargs): def skip_soda_tests():
return cx_Oracle.connect(GetMainUser(), GetMainPassword(), client = get_client_version()
GetConnectString(), encoding="UTF-8", nencoding="UTF-8", **kwargs)
def GetPool(user=None, password=None, **kwargs):
if user is None:
user = GetMainUser()
if password is None:
password = GetMainPassword()
return cx_Oracle.SessionPool(user, password, GetConnectString(),
encoding="UTF-8", nencoding="UTF-8", **kwargs)
def GetClientVersion():
name = "CLIENT_VERSION"
value = PARAMETERS.get(name)
if value is None:
value = cx_Oracle.clientversion()[:2]
PARAMETERS[name] = value
return value
def GetServerVersion():
name = "SERVER_VERSION"
value = PARAMETERS.get(name)
if value is None:
conn = GetConnection()
value = tuple(int(s) for s in conn.version.split("."))[:2]
PARAMETERS[name] = value
return value
def SkipSodaTests():
client = GetClientVersion()
if client < (18, 3): if client < (18, 3):
return True return True
server = GetServerVersion() server = get_server_version()
if server < (18, 0): if server < (18, 0):
return True return True
if server > (20, 1) and client < (20, 1): if server > (20, 1) and client < (20, 1):
@ -199,68 +201,65 @@ def SkipSodaTests():
class RoundTripInfo: class RoundTripInfo:
def __init__(self, connection): def __init__(self, connection):
self.prevRoundTrips = 0 self.prev_round_trips = 0
self.adminConn = cx_Oracle.connect(GetAdminConnectString()) self.admin_conn = oracledb.connect(get_admin_connect_string())
with connection.cursor() as cursor: with connection.cursor() as cursor:
cursor.execute("select sys_context('userenv', 'sid') from dual") cursor.execute("select sys_context('userenv', 'sid') from dual")
self.sid, = cursor.fetchone() self.sid, = cursor.fetchone()
self.getRoundTrips() self.get_round_trips()
def getRoundTrips(self): def get_round_trips(self):
with self.adminConn.cursor() as cursor: with self.admin_conn.cursor() as cursor:
cursor.execute(""" cursor.execute("""
select ss.value select ss.value
from v$sesstat ss, v$statname sn from v$sesstat ss, v$statname sn
where ss.sid = :sid where ss.sid = :sid
and ss.statistic# = sn.statistic# and ss.statistic# = sn.statistic#
and sn.name like '%roundtrip%client%'""", sid=self.sid) and sn.name like '%roundtrip%client%'""", sid=self.sid)
currentRoundTrips, = cursor.fetchone() current_round_trips, = cursor.fetchone()
diffRoundTrips = currentRoundTrips - self.prevRoundTrips diff_round_trips = current_round_trips - self.prev_round_trips
self.prevRoundTrips = currentRoundTrips self.prev_round_trips = current_round_trips
return diffRoundTrips return diff_round_trips
class BaseTestCase(unittest.TestCase): class BaseTestCase(unittest.TestCase):
requires_connection = True
def assertRoundTrips(self, n): def assertRoundTrips(self, n):
self.assertEqual(self.roundTripInfo.getRoundTrips(), n) self.assertEqual(self.round_trip_info.get_round_trips(), n)
def getSodaDatabase(self, minclient=(18, 3), minserver=(18, 0), def get_soda_database(self, minclient=(18, 3), minserver=(18, 0),
message="not supported with this client/server combination"): message="not supported with this client/server " \
client = cx_Oracle.clientversion()[:2] "combination"):
client = get_client_version()
if client < minclient: if client < minclient:
self.skipTest(message) self.skipTest(message)
server = tuple(int(s) for s in self.connection.version.split("."))[:2] server = get_server_version()
if server < minserver: if server < minserver:
self.skipTest(message) self.skipTest(message)
if server > (20, 1) and client < (20, 1): if server > (20, 1) and client < (20, 1):
self.skipTest(message) self.skipTest(message)
return self.connection.getSodaDatabase() return self.connection.getSodaDatabase()
def isOnOracleCloud(self, connection=None): def is_on_oracle_cloud(self, connection=None):
if connection is None: if connection is None:
connection = self.connection connection = self.connection
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute(""" cursor.execute("""
select sys_context('userenv', 'service_name') select sys_context('userenv', 'service_name')
from dual""") from dual""")
serviceName, = cursor.fetchone() service_name, = cursor.fetchone()
return serviceName.endswith("oraclecloud.com") return service_name.endswith("oraclecloud.com")
def setUp(self): def setUp(self):
self.connection = GetConnection() if self.requires_connection:
self.connection = get_connection()
self.cursor = self.connection.cursor() self.cursor = self.connection.cursor()
def setUpRoundTripChecker(self): def setup_round_trip_checker(self):
self.roundTripInfo = RoundTripInfo(self.connection) self.round_trip_info = RoundTripInfo(self.connection)
def tearDown(self): def tearDown(self):
if self.requires_connection:
self.connection.close() self.connection.close()
del self.cursor del self.cursor
del self.connection del self.connection
def load_tests(loader, standard_tests, pattern):
return loader.discover(os.path.dirname(__file__))
if __name__ == "__main__":
RunTestCases()

View File

@ -6,40 +6,40 @@
1000 - Module for testing top-level module methods 1000 - Module for testing top-level module methods
""" """
import TestEnv import base
import cx_Oracle import cx_Oracle as oracledb
import datetime import datetime
import time import time
class TestCase(TestEnv.BaseTestCase): class TestCase(base.BaseTestCase):
requires_connection = False
def test_1000_DateFromTicks(self): def test_1000_date_from_ticks(self):
"1000 - test DateFromTicks()" "1000 - test DateFromTicks()"
today = datetime.datetime.today() today = datetime.datetime.today()
timestamp = time.mktime(today.timetuple()) timestamp = time.mktime(today.timetuple())
date = cx_Oracle.DateFromTicks(timestamp) date = oracledb.DateFromTicks(timestamp)
self.assertEqual(date, today.date()) self.assertEqual(date, today.date())
def test_1001_FutureObj(self): def test_1001_future_obj(self):
"1001 - test management of __future__ object" "1001 - test management of __future__ object"
self.assertEqual(cx_Oracle.__future__.dummy, None) self.assertEqual(oracledb.__future__.dummy, None)
cx_Oracle.__future__.dummy = "Unimportant" oracledb.__future__.dummy = "Unimportant"
self.assertEqual(cx_Oracle.__future__.dummy, None) self.assertEqual(oracledb.__future__.dummy, None)
def test_1002_TimestampFromTicks(self): def test_1002_timestamp_from_ticks(self):
"1002 - test TimestampFromTicks()" "1002 - test TimestampFromTicks()"
timestamp = time.mktime(datetime.datetime.today().timetuple()) timestamp = time.mktime(datetime.datetime.today().timetuple())
today = datetime.datetime.fromtimestamp(timestamp) today = datetime.datetime.fromtimestamp(timestamp)
date = cx_Oracle.TimestampFromTicks(timestamp) date = oracledb.TimestampFromTicks(timestamp)
self.assertEqual(date, today) self.assertEqual(date, today)
def test_1003_UnsupportedFunctions(self): def test_1003_unsupported_functions(self):
"1003 - test unsupported time functions" "1003 - test unsupported time functions"
self.assertRaises(cx_Oracle.NotSupportedError, cx_Oracle.Time, self.assertRaises(oracledb.NotSupportedError, oracledb.Time, 12, 0, 0)
12, 0, 0) self.assertRaises(oracledb.NotSupportedError, oracledb.TimeFromTicks,
self.assertRaises(cx_Oracle.NotSupportedError, cx_Oracle.TimeFromTicks,
100) 100)
if __name__ == "__main__": if __name__ == "__main__":
TestEnv.RunTestCases() base.run_test_cases()

View File

@ -11,314 +11,317 @@
1100 - Module for testing connections 1100 - Module for testing connections
""" """
import TestEnv import base
import cx_Oracle import cx_Oracle as oracledb
import random import random
import string import string
import threading import threading
class TestCase(TestEnv.BaseTestCase): class TestCase(base.BaseTestCase):
requires_connection = False
def __ConnectAndDrop(self): def __connect_and_drop(self):
"""Connect to the database, perform a query and drop the connection.""" """Connect to the database, perform a query and drop the connection."""
connection = TestEnv.GetConnection(threaded=True) connection = base.get_connection(threaded=True)
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute("select count(*) from TestNumbers") cursor.execute("select count(*) from TestNumbers")
count, = cursor.fetchone() count, = cursor.fetchone()
self.assertEqual(count, 10) self.assertEqual(count, 10)
def __VerifyAttributes(self, connection, attrName, value, sql): def __verify_args(self, connection):
self.assertEqual(connection.username, base.get_main_user(),
"user name differs")
self.assertEqual(connection.tnsentry, base.get_connect_string(),
"tnsentry differs")
self.assertEqual(connection.dsn, base.get_connect_string(),
"dsn differs")
def __verify_attributes(self, connection, attrName, value, sql):
setattr(connection, attrName, value) setattr(connection, attrName, value)
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute(sql) cursor.execute(sql)
result, = cursor.fetchone() result, = cursor.fetchone()
self.assertEqual(result, value, "%s value mismatch" % attrName) self.assertEqual(result, value, "%s value mismatch" % attrName)
def setUp(self): def test_1100_all_args(self):
pass
def tearDown(self):
pass
def verifyArgs(self, connection):
self.assertEqual(connection.username, TestEnv.GetMainUser(),
"user name differs")
self.assertEqual(connection.tnsentry, TestEnv.GetConnectString(),
"tnsentry differs")
self.assertEqual(connection.dsn, TestEnv.GetConnectString(),
"dsn differs")
def test_1100_AllArgs(self):
"1100 - connection to database with user, password, TNS separate" "1100 - connection to database with user, password, TNS separate"
connection = TestEnv.GetConnection() connection = base.get_connection()
self.verifyArgs(connection) self.__verify_args(connection)
def test_1101_AppContext(self): def test_1101_app_context(self):
"1101 - test use of application context" "1101 - test use of application context"
namespace = "CLIENTCONTEXT" namespace = "CLIENTCONTEXT"
appContextEntries = [ app_context_entries = [
( namespace, "ATTR1", "VALUE1" ), ( namespace, "ATTR1", "VALUE1" ),
( namespace, "ATTR2", "VALUE2" ), ( namespace, "ATTR2", "VALUE2" ),
( namespace, "ATTR3", "VALUE3" ) ( namespace, "ATTR3", "VALUE3" )
] ]
connection = TestEnv.GetConnection(appcontext=appContextEntries) connection = base.get_connection(appcontext=app_context_entries)
cursor = connection.cursor() cursor = connection.cursor()
for namespace, name, value in appContextEntries: for namespace, name, value in app_context_entries:
cursor.execute("select sys_context(:1, :2) from dual", cursor.execute("select sys_context(:1, :2) from dual",
(namespace, name)) (namespace, name))
actualValue, = cursor.fetchone() actual_value, = cursor.fetchone()
self.assertEqual(actualValue, value) self.assertEqual(actual_value, value)
def test_1102_AppContextNegative(self): def test_1102_app_context_negative(self):
"1102 - test invalid use of application context" "1102 - test invalid use of application context"
self.assertRaises(TypeError, cx_Oracle.connect, TestEnv.GetMainUser(), self.assertRaises(TypeError, oracledb.connect, base.get_main_user(),
TestEnv.GetMainPassword(), TestEnv.GetConnectString(), base.get_main_password(), base.get_connect_string(),
appcontext=[('userenv', 'action')]) appcontext=[('userenv', 'action')])
def test_1103_Attributes(self): def test_1103_attributes(self):
"1103 - test connection end-to-end tracing attributes" "1103 - test connection end-to-end tracing attributes"
connection = TestEnv.GetConnection() connection = base.get_connection()
if TestEnv.GetClientVersion() >= (12, 1) \ if base.get_client_version() >= (12, 1) \
and not self.isOnOracleCloud(connection): and not self.is_on_oracle_cloud(connection):
self.__VerifyAttributes(connection, "dbop", "cx_OracleTest_DBOP", sql = "select dbop_name from v$sql_monitor " \
"select dbop_name from v$sql_monitor " "where sid = sys_context('userenv', 'sid')" \
"where sid = sys_context('userenv', 'sid')" "and status = 'EXECUTING'"
"and status = 'EXECUTING'") self.__verify_attributes(connection, "dbop", "oracledb_dbop", sql)
self.__VerifyAttributes(connection, "action", "cx_OracleTest_Action", sql = "select sys_context('userenv', 'action') from dual"
"select sys_context('userenv', 'action') from dual") self.__verify_attributes(connection, "action", "oracledb_Action", sql)
self.__VerifyAttributes(connection, "module", "cx_OracleTest_Module", sql = "select sys_context('userenv', 'module') from dual"
"select sys_context('userenv', 'module') from dual") self.__verify_attributes(connection, "module", "oracledb_Module", sql)
self.__VerifyAttributes(connection, "clientinfo", sql = "select sys_context('userenv', 'client_info') from dual"
"cx_OracleTest_CInfo", self.__verify_attributes(connection, "clientinfo", "oracledb_cinfo",
"select sys_context('userenv', 'client_info') from dual") sql)
self.__VerifyAttributes(connection, "client_identifier", sql = "select sys_context('userenv', 'client_identifier') from dual"
"cx_OracleTest_CID", self.__verify_attributes(connection, "client_identifier",
"select sys_context('userenv', 'client_identifier') from dual") "oracledb_cid", sql)
def test_1104_AutoCommit(self): def test_1104_autocommit(self):
"1104 - test use of autocommit" "1104 - test use of autocommit"
connection = TestEnv.GetConnection() connection = base.get_connection()
cursor = connection.cursor() cursor = connection.cursor()
otherConnection = TestEnv.GetConnection() other_connection = base.get_connection()
otherCursor = otherConnection.cursor() other_cursor = other_connection.cursor()
cursor.execute("truncate table TestTempTable") cursor.execute("truncate table TestTempTable")
cursor.execute("insert into TestTempTable (IntCol) values (1)") cursor.execute("insert into TestTempTable (IntCol) values (1)")
otherCursor.execute("select IntCol from TestTempTable") other_cursor.execute("select IntCol from TestTempTable")
rows = otherCursor.fetchall() rows = other_cursor.fetchall()
self.assertEqual(rows, []) self.assertEqual(rows, [])
connection.autocommit = True connection.autocommit = True
cursor.execute("insert into TestTempTable (IntCol) values (2)") cursor.execute("insert into TestTempTable (IntCol) values (2)")
otherCursor.execute("select IntCol from TestTempTable order by IntCol") other_cursor.execute("select IntCol from TestTempTable order by IntCol")
rows = otherCursor.fetchall() rows = other_cursor.fetchall()
self.assertEqual(rows, [(1,), (2,)]) self.assertEqual(rows, [(1,), (2,)])
def test_1105_BadConnectString(self): def test_1105_bad_connect_string(self):
"1105 - connection to database with bad connect string" "1105 - connection to database with bad connect string"
self.assertRaises(cx_Oracle.DatabaseError, cx_Oracle.connect, self.assertRaises(oracledb.DatabaseError, oracledb.connect,
TestEnv.GetMainUser()) base.get_main_user())
self.assertRaises(cx_Oracle.DatabaseError, cx_Oracle.connect, self.assertRaises(oracledb.DatabaseError, oracledb.connect,
TestEnv.GetMainUser() + "@" + TestEnv.GetConnectString()) base.get_main_user() + "@" + \
self.assertRaises(cx_Oracle.DatabaseError, cx_Oracle.connect, base.get_connect_string())
TestEnv.GetMainUser() + "@" + \ self.assertRaises(oracledb.DatabaseError, oracledb.connect,
TestEnv.GetConnectString() + "/" + TestEnv.GetMainPassword()) base.get_main_user() + "@" + \
base.get_connect_string() + "/" + \
base.get_main_password())
def test_1106_BadPassword(self): def test_1106_bad_password(self):
"1106 - connection to database with bad password" "1106 - connection to database with bad password"
self.assertRaises(cx_Oracle.DatabaseError, cx_Oracle.connect, self.assertRaises(oracledb.DatabaseError, oracledb.connect,
TestEnv.GetMainUser(), TestEnv.GetMainPassword() + "X", base.get_main_user(), base.get_main_password() + "X",
TestEnv.GetConnectString()) base.get_connect_string())
def test_1107_ChangePassword(self): def test_1107_change_password(self):
"1107 - test changing password" "1107 - test changing password"
connection = TestEnv.GetConnection() connection = base.get_connection()
if self.isOnOracleCloud(connection): if self.is_on_oracle_cloud(connection):
self.skipTest("passwords on Oracle Cloud are strictly controlled") self.skipTest("passwords on Oracle Cloud are strictly controlled")
sysRandom = random.SystemRandom() sys_random = random.SystemRandom()
newPassword = "".join(sysRandom.choice(string.ascii_letters) \ new_password = "".join(sys_random.choice(string.ascii_letters) \
for i in range(20)) for i in range(20))
connection.changepassword(TestEnv.GetMainPassword(), newPassword) connection.changepassword(base.get_main_password(), new_password)
cconnection = cx_Oracle.connect(TestEnv.GetMainUser(), newPassword, cconnection = oracledb.connect(base.get_main_user(), new_password,
TestEnv.GetConnectString()) base.get_connect_string())
connection.changepassword(newPassword, TestEnv.GetMainPassword()) connection.changepassword(new_password, base.get_main_password())
def test_1108_ChangePasswordNegative(self): def test_1108_change_password_negative(self):
"1108 - test changing password to an invalid value" "1108 - test changing password to an invalid value"
connection = TestEnv.GetConnection() connection = base.get_connection()
if self.isOnOracleCloud(connection): if self.is_on_oracle_cloud(connection):
self.skipTest("passwords on Oracle Cloud are strictly controlled") self.skipTest("passwords on Oracle Cloud are strictly controlled")
newPassword = "1" * 150 new_password = "1" * 150
self.assertRaises(cx_Oracle.DatabaseError, connection.changepassword, self.assertRaises(oracledb.DatabaseError, connection.changepassword,
TestEnv.GetMainPassword(), newPassword) base.get_main_password(), new_password)
def test_1109_ParsePassword(self): def test_1109_parse_password(self):
"1109 - test connecting with password containing / and @ symbols" "1109 - test connecting with password containing / and @ symbols"
connection = TestEnv.GetConnection() connection = base.get_connection()
if self.isOnOracleCloud(connection): if self.is_on_oracle_cloud(connection):
self.skipTest("passwords on Oracle Cloud are strictly controlled") self.skipTest("passwords on Oracle Cloud are strictly controlled")
sysRandom = random.SystemRandom() sys_random = random.SystemRandom()
chars = list(sysRandom.choice(string.ascii_letters) for i in range(20)) chars = list(sys_random.choice(string.ascii_letters) for i in range(20))
chars[4] = "/" chars[4] = "/"
chars[8] = "@" chars[8] = "@"
newPassword = "".join(chars) new_password = "".join(chars)
connection.changepassword(TestEnv.GetMainPassword(), newPassword) connection.changepassword(base.get_main_password(), new_password)
try: try:
arg = "%s/%s@%s" % (TestEnv.GetMainUser(), newPassword, arg = "%s/%s@%s" % (base.get_main_user(), new_password,
TestEnv.GetConnectString()) base.get_connect_string())
cx_Oracle.connect(arg) oracledb.connect(arg)
finally: finally:
connection.changepassword(newPassword, TestEnv.GetMainPassword()) connection.changepassword(new_password, base.get_main_password())
def test_1110_Encodings(self): def test_1110_encodings(self):
"1110 - connection with only encoding/nencoding specified should work" "1110 - connection with only encoding/nencoding specified should work"
connection = cx_Oracle.connect(TestEnv.GetMainUser(), connection = oracledb.connect(base.get_main_user(),
TestEnv.GetMainPassword(), TestEnv.GetConnectString()) base.get_main_password(),
base.get_connect_string())
encoding = connection.encoding encoding = connection.encoding
nencoding = connection.nencoding nencoding = connection.nencoding
altEncoding = "ISO-8859-1" alt_encoding = "ISO-8859-1"
connection = cx_Oracle.connect(TestEnv.GetMainUser(), connection = oracledb.connect(base.get_main_user(),
TestEnv.GetMainPassword(), TestEnv.GetConnectString(), base.get_main_password(),
encoding=altEncoding) base.get_connect_string(),
self.assertEqual(connection.encoding, altEncoding) encoding=alt_encoding)
self.assertEqual(connection.encoding, alt_encoding)
self.assertEqual(connection.nencoding, nencoding) self.assertEqual(connection.nencoding, nencoding)
connection = cx_Oracle.connect(TestEnv.GetMainUser(), connection = oracledb.connect(base.get_main_user(),
TestEnv.GetMainPassword(), TestEnv.GetConnectString(), base.get_main_password(),
nencoding=altEncoding) base.get_connect_string(),
nencoding=alt_encoding)
self.assertEqual(connection.encoding, encoding) self.assertEqual(connection.encoding, encoding)
self.assertEqual(connection.nencoding, altEncoding) self.assertEqual(connection.nencoding, alt_encoding)
def test_1111_DifferentEncodings(self): def test_1111_different_encodings(self):
"1111 - different encodings can be specified for encoding/nencoding" "1111 - different encodings can be specified for encoding/nencoding"
connection = cx_Oracle.connect(TestEnv.GetMainUser(), connection = oracledb.connect(base.get_main_user(),
TestEnv.GetMainPassword(), TestEnv.GetConnectString(), base.get_main_password(),
base.get_connect_string(),
encoding="UTF-8", nencoding="UTF-16") encoding="UTF-8", nencoding="UTF-16")
value = "\u03b4\u4e2a" value = "\u03b4\u4e2a"
cursor = connection.cursor() cursor = connection.cursor()
ncharVar = cursor.var(cx_Oracle.DB_TYPE_NVARCHAR, 100) nchar_var = cursor.var(oracledb.DB_TYPE_NVARCHAR, 100)
ncharVar.setvalue(0, value) nchar_var.setvalue(0, value)
cursor.execute("select :value from dual", value = ncharVar) cursor.execute("select :value from dual", value=nchar_var)
result, = cursor.fetchone() result, = cursor.fetchone()
self.assertEqual(result, value) self.assertEqual(result, value)
def test_1112_ExceptionOnClose(self): def test_1112_exception_on_close(self):
"1112 - confirm an exception is raised after closing a connection" "1112 - confirm an exception is raised after closing a connection"
connection = TestEnv.GetConnection() connection = base.get_connection()
connection.close() connection.close()
self.assertRaises(cx_Oracle.InterfaceError, connection.rollback) self.assertRaises(oracledb.InterfaceError, connection.rollback)
def test_1113_ConnectWithHandle(self): def test_1113_connect_with_handle(self):
"1113 - test creating a connection using a handle" "1113 - test creating a connection using a handle"
connection = TestEnv.GetConnection() connection = base.get_connection()
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute("truncate table TestTempTable") cursor.execute("truncate table TestTempTable")
intValue = random.randint(1, 32768) int_value = random.randint(1, 32768)
cursor.execute(""" cursor.execute("""
insert into TestTempTable (IntCol, StringCol) insert into TestTempTable (IntCol, StringCol)
values (:val, null)""", val = intValue) values (:val, null)""", val=int_value)
connection2 = cx_Oracle.connect(handle = connection.handle) connection2 = oracledb.connect(handle = connection.handle)
cursor = connection2.cursor() cursor = connection2.cursor()
cursor.execute("select IntCol from TestTempTable") cursor.execute("select IntCol from TestTempTable")
fetchedIntValue, = cursor.fetchone() fetched_int_value, = cursor.fetchone()
self.assertEqual(fetchedIntValue, intValue) self.assertEqual(fetched_int_value, int_value)
cursor.close() cursor.close()
self.assertRaises(cx_Oracle.DatabaseError, connection2.close) self.assertRaises(oracledb.DatabaseError, connection2.close)
connection.close() connection.close()
cursor = connection2.cursor() cursor = connection2.cursor()
self.assertRaises(cx_Oracle.DatabaseError, cursor.execute, self.assertRaises(oracledb.DatabaseError, cursor.execute,
"select count(*) from TestTempTable") "select count(*) from TestTempTable")
def test_1114_MakeDSN(self): def test_1114_make_dsn(self):
"1114 - test making a data source name from host, port and sid" "1114 - test making a data source name from host, port and sid"
formatString = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)" + \ format_string = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)" + \
"(HOST=%s)(PORT=%d))(CONNECT_DATA=(SID=%s)))" "(HOST=%s)(PORT=%d))(CONNECT_DATA=(SID=%s)))"
args = ("hostname", 1521, "TEST") args = ("hostname", 1521, "TEST")
result = cx_Oracle.makedsn(*args) result = oracledb.makedsn(*args)
self.assertEqual(result, formatString % args) self.assertEqual(result, format_string % args)
def test_1115_SingleArg(self): def test_1115_single_arg(self):
"1115 - connection to database with user, password, DSN together" "1115 - connection to database with user, password, DSN together"
connection = cx_Oracle.connect("%s/%s@%s" % \ arg = "%s/%s@%s" % (base.get_main_user(), base.get_main_password(),
(TestEnv.GetMainUser(), TestEnv.GetMainPassword(), base.get_connect_string())
TestEnv.GetConnectString())) connection = oracledb.connect(arg)
self.verifyArgs(connection) self.__verify_args(connection)
def test_1116_Version(self): def test_1116_version(self):
"1116 - connection version is a string" "1116 - connection version is a string"
connection = TestEnv.GetConnection() connection = base.get_connection()
self.assertTrue(isinstance(connection.version, str)) self.assertTrue(isinstance(connection.version, str))
def test_1117_RollbackOnClose(self): def test_1117_rollback_on_close(self):
"1117 - connection rolls back before close" "1117 - connection rolls back before close"
connection = TestEnv.GetConnection() connection = base.get_connection()
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute("truncate table TestTempTable") cursor.execute("truncate table TestTempTable")
otherConnection = TestEnv.GetConnection() other_connection = base.get_connection()
otherCursor = otherConnection.cursor() other_cursor = other_connection.cursor()
otherCursor.execute("insert into TestTempTable (IntCol) values (1)") other_cursor.execute("insert into TestTempTable (IntCol) values (1)")
otherCursor.close() other_cursor.close()
otherConnection.close() other_connection.close()
cursor.execute("select count(*) from TestTempTable") cursor.execute("select count(*) from TestTempTable")
count, = cursor.fetchone() count, = cursor.fetchone()
self.assertEqual(count, 0) self.assertEqual(count, 0)
def test_1118_RollbackOnDel(self): def test_1118_rollback_on_del(self):
"1118 - connection rolls back before destruction" "1118 - connection rolls back before destruction"
connection = TestEnv.GetConnection() connection = base.get_connection()
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute("truncate table TestTempTable") cursor.execute("truncate table TestTempTable")
otherConnection = TestEnv.GetConnection() other_connection = base.get_connection()
otherCursor = otherConnection.cursor() other_cursor = other_connection.cursor()
otherCursor.execute("insert into TestTempTable (IntCol) values (1)") other_cursor.execute("insert into TestTempTable (IntCol) values (1)")
del otherCursor del other_cursor
del otherConnection del other_connection
cursor.execute("select count(*) from TestTempTable") cursor.execute("select count(*) from TestTempTable")
count, = cursor.fetchone() count, = cursor.fetchone()
self.assertEqual(count, 0) self.assertEqual(count, 0)
def test_1119_Threading(self): def test_1119_threading(self):
"1119 - connection to database with multiple threads" "1119 - connection to database with multiple threads"
threads = [] threads = []
for i in range(20): for i in range(20):
thread = threading.Thread(None, self.__ConnectAndDrop) thread = threading.Thread(None, self.__connect_and_drop)
threads.append(thread) threads.append(thread)
thread.start() thread.start()
for thread in threads: for thread in threads:
thread.join() thread.join()
def test_1120_StringFormat(self): def test_1120_string_format(self):
"1120 - test string format of connection" "1120 - test string format of connection"
connection = TestEnv.GetConnection() connection = base.get_connection()
expectedValue = "<cx_Oracle.Connection to %s@%s>" % \ expected_value = "<cx_Oracle.Connection to %s@%s>" % \
(TestEnv.GetMainUser(), TestEnv.GetConnectString()) (base.get_main_user(), base.get_connect_string())
self.assertEqual(str(connection), expectedValue) self.assertEqual(str(connection), expected_value)
def test_1121_CtxMgrClose(self): def test_1121_ctx_mgr_close(self):
"1121 - test context manager - close" "1121 - test context manager - close"
connection = TestEnv.GetConnection() connection = base.get_connection()
with connection: with connection:
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute("truncate table TestTempTable") cursor.execute("truncate table TestTempTable")
cursor.execute("insert into TestTempTable (IntCol) values (1)") cursor.execute("insert into TestTempTable (IntCol) values (1)")
connection.commit() connection.commit()
cursor.execute("insert into TestTempTable (IntCol) values (2)") cursor.execute("insert into TestTempTable (IntCol) values (2)")
self.assertRaises(cx_Oracle.InterfaceError, connection.ping) self.assertRaises(oracledb.InterfaceError, connection.ping)
connection = TestEnv.GetConnection() connection = base.get_connection()
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute("select count(*) from TestTempTable") cursor.execute("select count(*) from TestTempTable")
count, = cursor.fetchone() count, = cursor.fetchone()
self.assertEqual(count, 1) self.assertEqual(count, 1)
def test_1122_ConnectionAttributes(self): def test_1122_connection_attributes(self):
"1122 - test connection attribute values" "1122 - test connection attribute values"
connection = cx_Oracle.connect(TestEnv.GetMainUser(), connection = oracledb.connect(base.get_main_user(),
TestEnv.GetMainPassword(), TestEnv.GetConnectString(), base.get_main_password(),
base.get_connect_string(),
encoding="ASCII") encoding="ASCII")
self.assertEqual(connection.maxBytesPerCharacter, 1) self.assertEqual(connection.maxBytesPerCharacter, 1)
connection = cx_Oracle.connect(TestEnv.GetMainUser(), connection = oracledb.connect(base.get_main_user(),
TestEnv.GetMainPassword(), TestEnv.GetConnectString(), base.get_main_password(),
base.get_connect_string(),
encoding="UTF-8") encoding="UTF-8")
self.assertEqual(connection.maxBytesPerCharacter, 4) self.assertEqual(connection.maxBytesPerCharacter, 4)
if TestEnv.GetClientVersion() >= (12, 1): if base.get_client_version() >= (12, 1):
self.assertEqual(connection.ltxid, b'') self.assertEqual(connection.ltxid, b'')
self.assertEqual(connection.current_schema, None) self.assertEqual(connection.current_schema, None)
connection.current_schema = "test_schema" connection.current_schema = "test_schema"
@ -333,26 +336,26 @@ class TestCase(TestEnv.BaseTestCase):
self.assertRaises(TypeError, connection.stmtcachesize, 20.5) self.assertRaises(TypeError, connection.stmtcachesize, 20.5)
self.assertRaises(TypeError, connection.stmtcachesize, "value") self.assertRaises(TypeError, connection.stmtcachesize, "value")
def test_1123_ClosedConnectionAttributes(self): def test_1123_closed_connection_attributes(self):
"1123 - test closed connection attribute values" "1123 - test closed connection attribute values"
connection = TestEnv.GetConnection() connection = base.get_connection()
connection.close() connection.close()
attrNames = ["current_schema", "edition", "external_name", attr_names = ["current_schema", "edition", "external_name",
"internal_name", "stmtcachesize"] "internal_name", "stmtcachesize"]
if TestEnv.GetClientVersion() >= (12, 1): if base.get_client_version() >= (12, 1):
attrNames.append("ltxid") attr_names.append("ltxid")
for name in attrNames: for name in attr_names:
self.assertRaises(cx_Oracle.InterfaceError, getattr, connection, self.assertRaises(oracledb.InterfaceError, getattr, connection,
name) name)
def test_1124_Ping(self): def test_1124_ping(self):
"1124 - test connection ping" "1124 - test connection ping"
connection = TestEnv.GetConnection() connection = base.get_connection()
connection.ping() connection.ping()
def test_1125_TransactionBegin(self): def test_1125_transaction_begin(self):
"1125 - test begin, prepare, cancel transaction" "1125 - test begin, prepare, cancel transaction"
connection = TestEnv.GetConnection() connection = base.get_connection()
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute("truncate table TestTempTable") cursor.execute("truncate table TestTempTable")
connection.begin(10, 'trxnId', 'branchId') connection.begin(10, 'trxnId', 'branchId')
@ -369,4 +372,4 @@ class TestCase(TestEnv.BaseTestCase):
self.assertEqual(count, 0) self.assertEqual(count, 0)
if __name__ == "__main__": if __name__ == "__main__":
TestEnv.RunTestCases() base.run_test_cases()

View File

@ -11,15 +11,13 @@
1200 - Module for testing cursors 1200 - Module for testing cursors
""" """
import TestEnv import base
import cx_Oracle as oracledb
import cx_Oracle
import decimal import decimal
import sys
class TestCase(TestEnv.BaseTestCase): class TestCase(base.BaseTestCase):
def test_1200_CreateScrollableCursor(self): def test_1200_create_scrollable_cursor(self):
"1200 - test creating a scrollable cursor" "1200 - test creating a scrollable cursor"
cursor = self.connection.cursor() cursor = self.connection.cursor()
self.assertEqual(cursor.scrollable, False) self.assertEqual(cursor.scrollable, False)
@ -30,117 +28,120 @@ class TestCase(TestEnv.BaseTestCase):
cursor.scrollable = False cursor.scrollable = False
self.assertEqual(cursor.scrollable, False) self.assertEqual(cursor.scrollable, False)
def test_1201_ExecuteNoArgs(self): def test_1201_execute_no_args(self):
"1201 - test executing a statement without any arguments" "1201 - test executing a statement without any arguments"
result = self.cursor.execute("begin null; end;") result = self.cursor.execute("begin null; end;")
self.assertEqual(result, None) self.assertEqual(result, None)
def test_1202_ExecuteNoStatementWithArgs(self): def test_1202_execute_no_statement_with_args(self):
"1202 - test executing a None statement with bind variables" "1202 - test executing a None statement with bind variables"
self.assertRaises(cx_Oracle.ProgrammingError, self.cursor.execute, self.assertRaises(oracledb.ProgrammingError, self.cursor.execute, None,
None, x = 5) x=5)
def test_1203_ExecuteEmptyKeywordArgs(self): def test_1203_execute_empty_keyword_args(self):
"1203 - test executing a statement with args and empty keyword args" "1203 - test executing a statement with args and empty keyword args"
simpleVar = self.cursor.var(cx_Oracle.NUMBER) simple_var = self.cursor.var(oracledb.NUMBER)
args = [simpleVar] args = [simple_var]
kwArgs = {} kwargs = {}
result = self.cursor.execute("begin :1 := 25; end;", args, **kwArgs) result = self.cursor.execute("begin :1 := 25; end;", args, **kwargs)
self.assertEqual(result, None) self.assertEqual(result, None)
self.assertEqual(simpleVar.getvalue(), 25) self.assertEqual(simple_var.getvalue(), 25)
def test_1204_ExecuteKeywordArgs(self): def test_1204_execute_keyword_args(self):
"1204 - test executing a statement with keyword arguments" "1204 - test executing a statement with keyword arguments"
simpleVar = self.cursor.var(cx_Oracle.NUMBER) simple_var = self.cursor.var(oracledb.NUMBER)
result = self.cursor.execute("begin :value := 5; end;", result = self.cursor.execute("begin :value := 5; end;",
value = simpleVar) value=simple_var)
self.assertEqual(result, None) self.assertEqual(result, None)
self.assertEqual(simpleVar.getvalue(), 5) self.assertEqual(simple_var.getvalue(), 5)
def test_1205_ExecuteDictionaryArg(self): def test_1205_execute_dictionary_arg(self):
"1205 - test executing a statement with a dictionary argument" "1205 - test executing a statement with a dictionary argument"
simpleVar = self.cursor.var(cx_Oracle.NUMBER) simple_var = self.cursor.var(oracledb.NUMBER)
dictArg = { "value" : simpleVar } dict_arg = dict(value=simple_var)
result = self.cursor.execute("begin :value := 10; end;", dictArg) result = self.cursor.execute("begin :value := 10; end;", dict_arg)
self.assertEqual(result, None) self.assertEqual(result, None)
self.assertEqual(simpleVar.getvalue(), 10) self.assertEqual(simple_var.getvalue(), 10)
def test_1206_ExecuteMultipleMethod(self): def test_1206_execute_multiple_arg_types(self):
"1206 - test executing a statement with both a dict and keyword args" "1206 - test executing a statement with both a dict and keyword args"
simpleVar = self.cursor.var(cx_Oracle.NUMBER) simple_var = self.cursor.var(oracledb.NUMBER)
dictArg = { "value" : simpleVar } dict_arg = dict(value=simple_var)
self.assertRaises(cx_Oracle.InterfaceError, self.cursor.execute, self.assertRaises(oracledb.InterfaceError, self.cursor.execute,
"begin :value := 15; end;", dictArg, value = simpleVar) "begin :value := 15; end;", dict_arg,
value=simple_var)
def test_1207_ExecuteAndModifyArraySize(self): def test_1207_execute_and_modify_array_size(self):
"1207 - test executing a statement and then changing the array size" "1207 - test executing a statement and then changing the array size"
self.cursor.execute("select IntCol from TestNumbers") self.cursor.execute("select IntCol from TestNumbers")
self.cursor.arraysize = 20 self.cursor.arraysize = 20
self.assertEqual(len(self.cursor.fetchall()), 10) self.assertEqual(len(self.cursor.fetchall()), 10)
def test_1208_CallProc(self): def test_1208_callproc(self):
"1208 - test executing a stored procedure" "1208 - test executing a stored procedure"
var = self.cursor.var(cx_Oracle.NUMBER) var = self.cursor.var(oracledb.NUMBER)
results = self.cursor.callproc("proc_Test", ("hi", 5, var)) results = self.cursor.callproc("proc_Test", ("hi", 5, var))
self.assertEqual(results, ["hi", 10, 2.0]) self.assertEqual(results, ["hi", 10, 2.0])
def test_1209_CallProcAllKeywords(self): def test_1209_callproc_all_keywords(self):
"1209 - test executing a stored procedure with keyword args" "1209 - test executing a stored procedure with all args keyword args"
kwargs = dict(a_InOutValue=self.cursor.var(cx_Oracle.NUMBER), inout_value = self.cursor.var(oracledb.NUMBER)
a_InValue="hi", a_OutValue=self.cursor.var(cx_Oracle.NUMBER)) inout_value.setvalue(0, 5)
kwargs['a_InOutValue'].setvalue(0, 5) out_value = self.cursor.var(oracledb.NUMBER)
results = self.cursor.callproc("proc_Test", keywordParameters=kwargs) kwargs = dict(a_InOutValue=inout_value, a_InValue="hi",
a_OutValue=out_value)
results = self.cursor.callproc("proc_Test", [], kwargs)
self.assertEqual(results, []) self.assertEqual(results, [])
self.assertEqual(kwargs['a_InOutValue'].getvalue(), 10) self.assertEqual(inout_value.getvalue(), 10)
self.assertEqual(kwargs['a_OutValue'].getvalue(), 2.0) self.assertEqual(out_value.getvalue(), 2.0)
def test_1210_CallProcOnlyLastKeyword(self): def test_1210_callproc_only_last_keyword(self):
"1210 - test executing a stored procedure with last arg as keyword arg" "1210 - test executing a stored procedure with last arg as keyword arg"
kwargs = dict(a_OutValue = self.cursor.var(cx_Oracle.NUMBER)) out_value = self.cursor.var(oracledb.NUMBER)
kwargs = dict(a_OutValue=out_value)
results = self.cursor.callproc("proc_Test", ("hi", 5), kwargs) results = self.cursor.callproc("proc_Test", ("hi", 5), kwargs)
self.assertEqual(results, ["hi", 10]) self.assertEqual(results, ["hi", 10])
self.assertEqual(kwargs['a_OutValue'].getvalue(), 2.0) self.assertEqual(out_value.getvalue(), 2.0)
def test_1211_CallProcRepeatedKeywordParameters(self): def test_1211_callproc_repeated_keyword_parameters(self):
"1211 - test executing a stored procedure, repeated keyword arg" "1211 - test executing a stored procedure, repeated keyword arg"
kwargs = dict(a_InValue="hi", kwargs = dict(a_InValue="hi",
a_OutValue=self.cursor.var(cx_Oracle.NUMBER)) a_OutValue=self.cursor.var(oracledb.NUMBER))
self.assertRaises(cx_Oracle.DatabaseError, self.cursor.callproc, self.assertRaises(oracledb.DatabaseError, self.cursor.callproc,
"proc_Test", parameters=("hi", 5), keywordParameters=kwargs) "proc_Test", ("hi", 5), kwargs)
def test_1212_CallProcNoArgs(self): def test_1212_callproc_no_args(self):
"1212 - test executing a stored procedure without any arguments" "1212 - test executing a stored procedure without any arguments"
results = self.cursor.callproc("proc_TestNoArgs") results = self.cursor.callproc("proc_TestNoArgs")
self.assertEqual(results, []) self.assertEqual(results, [])
def test_1213_CallFunc(self): def test_1213_callfunc(self):
"1213 - test executing a stored function" "1213 - test executing a stored function"
results = self.cursor.callfunc("func_Test", cx_Oracle.NUMBER, results = self.cursor.callfunc("func_Test", oracledb.NUMBER, ("hi", 5))
("hi", 5))
self.assertEqual(results, 7) self.assertEqual(results, 7)
def test_1214_CallFuncNoArgs(self): def test_1214_callfunc_no_args(self):
"1214 - test executing a stored function without any arguments" "1214 - test executing a stored function without any arguments"
results = self.cursor.callfunc("func_TestNoArgs", cx_Oracle.NUMBER) results = self.cursor.callfunc("func_TestNoArgs", oracledb.NUMBER)
self.assertEqual(results, 712) self.assertEqual(results, 712)
def test_1215_CallFuncNegative(self): def test_1215_callfunc_negative(self):
"1215 - test executing a stored function with wrong parameters" "1215 - test executing a stored function with wrong parameters"
funcName = "func_Test" func_name = "func_Test"
self.assertRaises(TypeError, self.cursor.callfunc, cx_Oracle.NUMBER, self.assertRaises(TypeError, self.cursor.callfunc, oracledb.NUMBER,
funcName, ("hi", 5)) func_name, ("hi", 5))
self.assertRaises(cx_Oracle.DatabaseError, self.cursor.callfunc, self.assertRaises(oracledb.DatabaseError, self.cursor.callfunc,
funcName, cx_Oracle.NUMBER, ("hi", 5, 7)) func_name, oracledb.NUMBER, ("hi", 5, 7))
self.assertRaises(TypeError, self.cursor.callfunc, funcName, self.assertRaises(TypeError, self.cursor.callfunc, func_name,
cx_Oracle.NUMBER, "hi", 7) oracledb.NUMBER, "hi", 7)
self.assertRaises(cx_Oracle.DatabaseError, self.cursor.callfunc, self.assertRaises(oracledb.DatabaseError, self.cursor.callfunc,
funcName, cx_Oracle.NUMBER, [5, "hi"]) func_name, oracledb.NUMBER, [5, "hi"])
self.assertRaises(cx_Oracle.DatabaseError, self.cursor.callfunc, self.assertRaises(oracledb.DatabaseError, self.cursor.callfunc,
funcName, cx_Oracle.NUMBER) func_name, oracledb.NUMBER)
self.assertRaises(TypeError, self.cursor.callfunc, funcName, self.assertRaises(TypeError, self.cursor.callfunc, func_name,
cx_Oracle.NUMBER, 5) oracledb.NUMBER, 5)
def test_1216_ExecuteManyByName(self): def test_1216_executemany_by_name(self):
"1216 - test executing a statement multiple times (named args)" "1216 - test executing a statement multiple times (named args)"
self.cursor.execute("truncate table TestTempTable") self.cursor.execute("truncate table TestTempTable")
rows = [{"value": n} for n in range(250)] rows = [{"value": n} for n in range(250)]
@ -152,7 +153,7 @@ class TestCase(TestEnv.BaseTestCase):
count, = self.cursor.fetchone() count, = self.cursor.fetchone()
self.assertEqual(count, len(rows)) self.assertEqual(count, len(rows))
def test_1217_ExecuteManyByPosition(self): def test_1217_executemany_by_position(self):
"1217 - test executing a statement multiple times (positional args)" "1217 - test executing a statement multiple times (positional args)"
self.cursor.execute("truncate table TestTempTable") self.cursor.execute("truncate table TestTempTable")
rows = [[n] for n in range(230)] rows = [[n] for n in range(230)]
@ -164,7 +165,7 @@ class TestCase(TestEnv.BaseTestCase):
count, = self.cursor.fetchone() count, = self.cursor.fetchone()
self.assertEqual(count, len(rows)) self.assertEqual(count, len(rows))
def test_1218_ExecuteManyWithPrepare(self): def test_1218_executemany_with_prepare(self):
"1218 - test executing a statement multiple times (with prepare)" "1218 - test executing a statement multiple times (with prepare)"
self.cursor.execute("truncate table TestTempTable") self.cursor.execute("truncate table TestTempTable")
rows = [[n] for n in range(225)] rows = [[n] for n in range(225)]
@ -177,7 +178,7 @@ class TestCase(TestEnv.BaseTestCase):
count, = self.cursor.fetchone() count, = self.cursor.fetchone()
self.assertEqual(count, len(rows)) self.assertEqual(count, len(rows))
def test_1219_ExecuteManyWithRebind(self): def test_1219_executemany_with_rebind(self):
"1219 - test executing a statement multiple times (with rebind)" "1219 - test executing a statement multiple times (with rebind)"
self.cursor.execute("truncate table TestTempTable") self.cursor.execute("truncate table TestTempTable")
rows = [[n] for n in range(235)] rows = [[n] for n in range(235)]
@ -190,25 +191,30 @@ class TestCase(TestEnv.BaseTestCase):
count, = self.cursor.fetchone() count, = self.cursor.fetchone()
self.assertEqual(count, len(rows)) self.assertEqual(count, len(rows))
def test_1220_ExecuteManyWithInputSizesWrong(self): def test_1220_executemany_with_input_sizes_wrong(self):
"1220 - test executing multiple times (with input sizes wrong)" "1220 - test executing multiple times (with input sizes wrong)"
cursor = self.connection.cursor() cursor = self.connection.cursor()
cursor.setinputsizes(cx_Oracle.NUMBER) cursor.setinputsizes(oracledb.NUMBER)
data = [[decimal.Decimal("25.8")], [decimal.Decimal("30.0")]] data = [[decimal.Decimal("25.8")], [decimal.Decimal("30.0")]]
cursor.executemany("declare t number; begin t := :1; end;", data) cursor.executemany("declare t number; begin t := :1; end;", data)
def test_1221_ExecuteManyMultipleBatches(self): def test_1221_executemany_with_multiple_batches(self):
"1221 - test executing multiple times (with multiple batches)" "1221 - test executing multiple times (with multiple batches)"
self.cursor.execute("truncate table TestTempTable") self.cursor.execute("truncate table TestTempTable")
sql = "insert into TestTempTable (IntCol, StringCol) values (:1, :2)" sql = "insert into TestTempTable (IntCol, StringCol) values (:1, :2)"
self.cursor.executemany(sql, [(1, None), (2, None)]) self.cursor.executemany(sql, [(1, None), (2, None)])
self.cursor.executemany(sql, [(3, None), (4, "Testing")]) self.cursor.executemany(sql, [(3, None), (4, "Testing")])
def test_1222_ExecuteManyNumeric(self): def test_1222_executemany_numeric(self):
"1222 - test executemany() with various numeric types" "1222 - test executemany() with various numeric types"
self.cursor.execute("truncate table TestTempTable") self.cursor.execute("truncate table TestTempTable")
data = [(1, 5), (2, 7.0), (3, 6.5), (4, 2 ** 65), data = [
(5, decimal.Decimal("24.5"))] (1, 5),
(2, 7.0),
(3, 6.5),
(4, 2 ** 65),
(5, decimal.Decimal("24.5"))
]
sql = "insert into TestTempTable (IntCol, NumberCol) values (:1, :2)" sql = "insert into TestTempTable (IntCol, NumberCol) values (:1, :2)"
self.cursor.executemany(sql, data) self.cursor.executemany(sql, data)
self.cursor.execute(""" self.cursor.execute("""
@ -217,43 +223,45 @@ class TestCase(TestEnv.BaseTestCase):
order by IntCol""") order by IntCol""")
self.assertEqual(self.cursor.fetchall(), data) self.assertEqual(self.cursor.fetchall(), data)
def test_1223_ExecuteManyWithResize(self): def test_1223_executemany_with_resize(self):
"1223 - test executing a statement multiple times (with resize)" "1223 - test executing a statement multiple times (with resize)"
self.cursor.execute("truncate table TestTempTable") self.cursor.execute("truncate table TestTempTable")
rows = [ ( 1, "First" ), rows = [
(1, "First"),
(2, "Second"), (2, "Second"),
(3, "Third"), (3, "Third"),
(4, "Fourth"), (4, "Fourth"),
(5, "Fifth"), (5, "Fifth"),
(6, "Sixth"), (6, "Sixth"),
( 7, "Seventh and the longest one" ) ] (7, "Seventh and the longest one")
]
sql = "insert into TestTempTable (IntCol, StringCol) values (:1, :2)" sql = "insert into TestTempTable (IntCol, StringCol) values (:1, :2)"
self.cursor.executemany(sql, rows) self.cursor.executemany(sql, rows)
self.cursor.execute(""" self.cursor.execute("""
select IntCol, StringCol select IntCol, StringCol
from TestTempTable from TestTempTable
order by IntCol""") order by IntCol""")
fetchedRows = self.cursor.fetchall() fetched_rows = self.cursor.fetchall()
self.assertEqual(fetchedRows, rows) self.assertEqual(fetched_rows, rows)
def test_1224_ExecuteManyWithExecption(self): def test_1224_executemany_with_exception(self):
"1224 - test executing a statement multiple times (with exception)" "1224 - test executing a statement multiple times (with exception)"
self.cursor.execute("truncate table TestTempTable") self.cursor.execute("truncate table TestTempTable")
rows = [{"value": n} for n in (1, 2, 3, 2, 5)] rows = [{"value": n} for n in (1, 2, 3, 2, 5)]
statement = "insert into TestTempTable (IntCol) values (:value)" statement = "insert into TestTempTable (IntCol) values (:value)"
self.assertRaises(cx_Oracle.DatabaseError, self.cursor.executemany, self.assertRaises(oracledb.DatabaseError, self.cursor.executemany,
statement, rows) statement, rows)
self.assertEqual(self.cursor.rowcount, 3) self.assertEqual(self.cursor.rowcount, 3)
def test_1225_ExecuteManyWithInvalidParameters(self): def test_1225_executemany_with_invalid_parameters(self):
"1225 - test calling executemany() with invalid parameters" "1225 - test calling executemany() with invalid parameters"
self.assertRaises(TypeError, self.cursor.executemany, sql = "insert into TestTempTable (IntCol, StringCol) values (:1, :2)"
"insert into TestTempTable (IntCol, StringCol) values (:1, :2)", self.assertRaises(TypeError, self.cursor.executemany, sql,
"These are not valid parameters") "These are not valid parameters")
def test_1226_ExecuteManyNoParameters(self): def test_1226_executemany_no_parameters(self):
"1226 - test calling executemany() without any bind parameters" "1226 - test calling executemany() without any bind parameters"
numRows = 5 num_rows = 5
self.cursor.execute("truncate table TestTempTable") self.cursor.execute("truncate table TestTempTable")
self.cursor.executemany(""" self.cursor.executemany("""
declare declare
@ -264,17 +272,17 @@ class TestCase(TestEnv.BaseTestCase):
insert into TestTempTable (IntCol, StringCol) insert into TestTempTable (IntCol, StringCol)
values (t_Id, 'Test String ' || t_Id); values (t_Id, 'Test String ' || t_Id);
end;""", numRows) end;""", num_rows)
self.assertEqual(self.cursor.rowcount, numRows) self.assertEqual(self.cursor.rowcount, num_rows)
self.cursor.execute("select count(*) from TestTempTable") self.cursor.execute("select count(*) from TestTempTable")
count, = self.cursor.fetchone() count, = self.cursor.fetchone()
self.assertEqual(count, numRows) self.assertEqual(count, num_rows)
def test_1227_ExecuteManyBoundEarlier(self): def test_1227_executemany_bound_earlier(self):
"1227 - test calling executemany() with binds performed earlier" "1227 - test calling executemany() with binds performed earlier"
numRows = 9 num_rows = 9
self.cursor.execute("truncate table TestTempTable") self.cursor.execute("truncate table TestTempTable")
var = self.cursor.var(int, arraysize = numRows) var = self.cursor.var(int, arraysize=num_rows)
self.cursor.setinputsizes(var) self.cursor.setinputsizes(var)
self.cursor.executemany(""" self.cursor.executemany("""
declare declare
@ -288,17 +296,17 @@ class TestCase(TestEnv.BaseTestCase):
select sum(IntCol) into :1 select sum(IntCol) into :1
from TestTempTable; from TestTempTable;
end;""", numRows) end;""", num_rows)
self.assertEqual(self.cursor.rowcount, numRows) self.assertEqual(self.cursor.rowcount, num_rows)
expectedData = [1, 3, 6, 10, 15, 21, 28, 36, 45] expected_data = [1, 3, 6, 10, 15, 21, 28, 36, 45]
self.assertEqual(var.values, expectedData) self.assertEqual(var.values, expected_data)
def test_1228_Prepare(self): def test_1228_prepare(self):
"1228 - test preparing a statement and executing it multiple times" "1228 - test preparing a statement and executing it multiple times"
self.assertEqual(self.cursor.statement, None) self.assertEqual(self.cursor.statement, None)
statement = "begin :value := :value + 5; end;" statement = "begin :value := :value + 5; end;"
self.cursor.prepare(statement) self.cursor.prepare(statement)
var = self.cursor.var(cx_Oracle.NUMBER) var = self.cursor.var(oracledb.NUMBER)
self.assertEqual(self.cursor.statement, statement) self.assertEqual(self.cursor.statement, statement)
var.setvalue(0, 2) var.setvalue(0, 2)
self.cursor.execute(None, value = var) self.cursor.execute(None, value = var)
@ -308,25 +316,23 @@ class TestCase(TestEnv.BaseTestCase):
self.cursor.execute("begin :value2 := 3; end;", value2 = var) self.cursor.execute("begin :value2 := 3; end;", value2 = var)
self.assertEqual(var.getvalue(), 3) self.assertEqual(var.getvalue(), 3)
def test_1229_ExceptionOnClose(self): def test_1229_exception_on_close(self):
"1229 - confirm an exception is raised after closing a cursor" "1229 - confirm an exception is raised after closing a cursor"
self.cursor.close() self.cursor.close()
self.assertRaises(cx_Oracle.InterfaceError, self.cursor.execute, self.assertRaises(oracledb.InterfaceError, self.cursor.execute,
"select 1 from dual") "select 1 from dual")
def test_1230_Iterators(self): def test_1230_iterators(self):
"1230 - test iterators" "1230 - test iterators"
self.cursor.execute(""" self.cursor.execute("""
select IntCol select IntCol
from TestNumbers from TestNumbers
where IntCol between 1 and 3 where IntCol between 1 and 3
order by IntCol""") order by IntCol""")
rows = [] rows = [v for v, in self.cursor]
for row in self.cursor:
rows.append(row[0])
self.assertEqual(rows, [1, 2, 3]) self.assertEqual(rows, [1, 2, 3])
def test_1231_IteratorsInterrupted(self): def test_1231_iterators_interrupted(self):
"1231 - test iterators (with intermediate execute)" "1231 - test iterators (with intermediate execute)"
self.cursor.execute("truncate table TestTempTable") self.cursor.execute("truncate table TestTempTable")
self.cursor.execute(""" self.cursor.execute("""
@ -334,20 +340,14 @@ class TestCase(TestEnv.BaseTestCase):
from TestNumbers from TestNumbers
where IntCol between 1 and 3 where IntCol between 1 and 3
order by IntCol""") order by IntCol""")
testIter = iter(self.cursor) test_iter = iter(self.cursor)
if sys.version_info[0] >= 3: value, = next(test_iter)
value, = next(testIter)
else:
value, = testIter.next()
self.cursor.execute("insert into TestTempTable (IntCol) values (1)") self.cursor.execute("insert into TestTempTable (IntCol) values (1)")
if sys.version_info[0] >= 3: self.assertRaises(oracledb.InterfaceError, next, test_iter)
self.assertRaises(cx_Oracle.InterfaceError, next, testIter)
else:
self.assertRaises(cx_Oracle.InterfaceError, testIter.next)
def test_1232_BindNames(self): def test_1232_bind_names(self):
"1232 - test that bindnames() works correctly." "1232 - test that bindnames() works correctly."
self.assertRaises(cx_Oracle.ProgrammingError, self.cursor.bindnames) self.assertRaises(oracledb.ProgrammingError, self.cursor.bindnames)
self.cursor.prepare("begin null; end;") self.cursor.prepare("begin null; end;")
self.assertEqual(self.cursor.bindnames(), []) self.assertEqual(self.cursor.bindnames(), [])
self.cursor.prepare("begin :retval := :inval + 5; end;") self.cursor.prepare("begin :retval := :inval + 5; end;")
@ -356,26 +356,25 @@ class TestCase(TestEnv.BaseTestCase):
self.assertEqual(self.cursor.bindnames(), ["RETVAL", "A", "B"]) self.assertEqual(self.cursor.bindnames(), ["RETVAL", "A", "B"])
self.cursor.prepare("begin :a := :b + :c + :d + :e + :f + :g + " + \ self.cursor.prepare("begin :a := :b + :c + :d + :e + :f + :g + " + \
":h + :i + :j + :k + :l; end;") ":h + :i + :j + :k + :l; end;")
self.assertEqual(self.cursor.bindnames(), names = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]
["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]) self.assertEqual(self.cursor.bindnames(), names)
self.cursor.prepare("select :a * :a + :b * :b from dual") self.cursor.prepare("select :a * :a + :b * :b from dual")
self.assertEqual(self.cursor.bindnames(), ["A", "B"]) self.assertEqual(self.cursor.bindnames(), ["A", "B"])
def test_1233_BadPrepare(self): def test_1233_bad_execute(self):
"1233 - test that subsequent executes succeed after bad prepare" "1233 - test that subsequent executes succeed after bad execute"
self.assertRaises(cx_Oracle.DatabaseError, self.assertRaises(oracledb.DatabaseError,
self.cursor.execute, self.cursor.execute,
"begin raise_application_error(-20000, 'this); end;") "begin raise_application_error(-20000, 'this); end;")
self.cursor.execute("begin null; end;") self.cursor.execute("begin null; end;")
def test_1234_BadExecute(self): def test_1234_fetch_after_bad_execute(self):
"1234 - test that subsequent fetches fail after bad execute" "1234 - test that subsequent fetches fail after bad execute"
self.assertRaises(cx_Oracle.DatabaseError, self.assertRaises(oracledb.DatabaseError,
self.cursor.execute, "select y from dual") self.cursor.execute, "select y from dual")
self.assertRaises(cx_Oracle.InterfaceError, self.assertRaises(oracledb.InterfaceError, self.cursor.fetchall)
self.cursor.fetchall)
def test_1235_ScrollAbsoluteExceptionAfter(self): def test_1235_scroll_absolute_exception_after(self):
"1235 - test scrolling absolute yields an exception (after result set)" "1235 - test scrolling absolute yields an exception (after result set)"
cursor = self.connection.cursor(scrollable=True) cursor = self.connection.cursor(scrollable=True)
cursor.arraysize = self.cursor.arraysize cursor.arraysize = self.cursor.arraysize
@ -383,10 +382,10 @@ class TestCase(TestEnv.BaseTestCase):
select NumberCol select NumberCol
from TestNumbers from TestNumbers
order by IntCol""") order by IntCol""")
self.assertRaises(cx_Oracle.DatabaseError, cursor.scroll, 12, self.assertRaises(oracledb.DatabaseError, cursor.scroll, 12,
"absolute") "absolute")
def test_1236_ScrollAbsoluteInBuffer(self): def test_1236_scroll_absolute_in_buffer(self):
"1236 - test scrolling absolute (when in buffers)" "1236 - test scrolling absolute (when in buffers)"
cursor = self.connection.cursor(scrollable=True) cursor = self.connection.cursor(scrollable=True)
cursor.arraysize = self.cursor.arraysize cursor.arraysize = self.cursor.arraysize
@ -402,7 +401,7 @@ class TestCase(TestEnv.BaseTestCase):
self.assertEqual(row[0], 1.25) self.assertEqual(row[0], 1.25)
self.assertEqual(cursor.rowcount, 1) self.assertEqual(cursor.rowcount, 1)
def test_1237_ScrollAbsoluteNotInBuffer(self): def test_1237_scroll_absolute_not_in_buffer(self):
"1237 - test scrolling absolute (when not in buffers)" "1237 - test scrolling absolute (when not in buffers)"
cursor = self.connection.cursor(scrollable=True) cursor = self.connection.cursor(scrollable=True)
cursor.arraysize = self.cursor.arraysize cursor.arraysize = self.cursor.arraysize
@ -415,7 +414,7 @@ class TestCase(TestEnv.BaseTestCase):
self.assertEqual(row[0], 7.5) self.assertEqual(row[0], 7.5)
self.assertEqual(cursor.rowcount, 6) self.assertEqual(cursor.rowcount, 6)
def test_1238_ScrollFirstInBuffer(self): def test_1238_scroll_first_in_buffer(self):
"1238 - test scrolling to first row in result set (in buffers)" "1238 - test scrolling to first row in result set (in buffers)"
cursor = self.connection.cursor(scrollable=True) cursor = self.connection.cursor(scrollable=True)
cursor.arraysize = self.cursor.arraysize cursor.arraysize = self.cursor.arraysize
@ -429,7 +428,7 @@ class TestCase(TestEnv.BaseTestCase):
self.assertEqual(row[0], 1.25) self.assertEqual(row[0], 1.25)
self.assertEqual(cursor.rowcount, 1) self.assertEqual(cursor.rowcount, 1)
def test_1239_ScrollFirstNotInBuffer(self): def test_1239_scroll_first_not_in_buffer(self):
"1239 - test scrolling to first row in result set (not in buffers)" "1239 - test scrolling to first row in result set (not in buffers)"
cursor = self.connection.cursor(scrollable=True) cursor = self.connection.cursor(scrollable=True)
cursor.arraysize = self.cursor.arraysize cursor.arraysize = self.cursor.arraysize
@ -444,7 +443,7 @@ class TestCase(TestEnv.BaseTestCase):
self.assertEqual(row[0], 1.25) self.assertEqual(row[0], 1.25)
self.assertEqual(cursor.rowcount, 1) self.assertEqual(cursor.rowcount, 1)
def test_1240_ScrollLast(self): def test_1240_scroll_last(self):
"1240 - test scrolling to last row in result set" "1240 - test scrolling to last row in result set"
cursor = self.connection.cursor(scrollable=True) cursor = self.connection.cursor(scrollable=True)
cursor.arraysize = self.cursor.arraysize cursor.arraysize = self.cursor.arraysize
@ -457,7 +456,7 @@ class TestCase(TestEnv.BaseTestCase):
self.assertEqual(row[0], 12.5) self.assertEqual(row[0], 12.5)
self.assertEqual(cursor.rowcount, 10) self.assertEqual(cursor.rowcount, 10)
def test_1241_ScrollRelativeExceptionAfter(self): def test_1241_scroll_relative_exception_after(self):
"1241 - test scrolling relative yields an exception (after result set)" "1241 - test scrolling relative yields an exception (after result set)"
cursor = self.connection.cursor(scrollable=True) cursor = self.connection.cursor(scrollable=True)
cursor.arraysize = self.cursor.arraysize cursor.arraysize = self.cursor.arraysize
@ -465,9 +464,9 @@ class TestCase(TestEnv.BaseTestCase):
select NumberCol select NumberCol
from TestNumbers from TestNumbers
order by IntCol""") order by IntCol""")
self.assertRaises(cx_Oracle.DatabaseError, cursor.scroll, 15) self.assertRaises(oracledb.DatabaseError, cursor.scroll, 15)
def test_1242_ScrollRelativeExceptionBefore(self): def test_1242_scroll_relative_exception_before(self):
"1242 - test scrolling relative yields exception (before result set)" "1242 - test scrolling relative yields exception (before result set)"
cursor = self.connection.cursor(scrollable=True) cursor = self.connection.cursor(scrollable=True)
cursor.arraysize = self.cursor.arraysize cursor.arraysize = self.cursor.arraysize
@ -475,9 +474,9 @@ class TestCase(TestEnv.BaseTestCase):
select NumberCol select NumberCol
from TestNumbers from TestNumbers
order by IntCol""") order by IntCol""")
self.assertRaises(cx_Oracle.DatabaseError, cursor.scroll, -5) self.assertRaises(oracledb.DatabaseError, cursor.scroll, -5)
def test_1243_ScrollRelativeInBuffer(self): def test_1243_scroll_relative_in_buffer(self):
"1243 - test scrolling relative (when in buffers)" "1243 - test scrolling relative (when in buffers)"
cursor = self.connection.cursor(scrollable=True) cursor = self.connection.cursor(scrollable=True)
cursor.arraysize = self.cursor.arraysize cursor.arraysize = self.cursor.arraysize
@ -486,14 +485,14 @@ class TestCase(TestEnv.BaseTestCase):
from TestNumbers from TestNumbers
order by IntCol""") order by IntCol""")
cursor.fetchmany() cursor.fetchmany()
self.assertTrue(cursor.arraysize > 1, message = "array size must exceed 1 for this test to work correctly"
"array size must exceed 1 for this test to work correctly") self.assertTrue(cursor.arraysize > 1, message)
cursor.scroll(2 - cursor.rowcount) cursor.scroll(2 - cursor.rowcount)
row = cursor.fetchone() row = cursor.fetchone()
self.assertEqual(row[0], 2.5) self.assertEqual(row[0], 2.5)
self.assertEqual(cursor.rowcount, 2) self.assertEqual(cursor.rowcount, 2)
def test_1244_ScrollRelativeNotInBuffer(self): def test_1244_scroll_relative_not_in_buffer(self):
"1244 - test scrolling relative (when not in buffers)" "1244 - test scrolling relative (when not in buffers)"
cursor = self.connection.cursor(scrollable=True) cursor = self.connection.cursor(scrollable=True)
cursor.arraysize = self.cursor.arraysize cursor.arraysize = self.cursor.arraysize
@ -503,14 +502,14 @@ class TestCase(TestEnv.BaseTestCase):
order by IntCol""") order by IntCol""")
cursor.fetchmany() cursor.fetchmany()
cursor.fetchmany() cursor.fetchmany()
self.assertTrue(cursor.arraysize > 1, message = "array size must exceed 1 for this test to work correctly"
"array size must exceed 2 for this test to work correctly") self.assertTrue(cursor.arraysize > 1, message)
cursor.scroll(3 - cursor.rowcount) cursor.scroll(3 - cursor.rowcount)
row = cursor.fetchone() row = cursor.fetchone()
self.assertEqual(row[0], 3.75) self.assertEqual(row[0], 3.75)
self.assertEqual(cursor.rowcount, 3) self.assertEqual(cursor.rowcount, 3)
def test_1245_ScrollNoRows(self): def test_1245_scroll_no_rows(self):
"1245 - test scrolling when there are no rows" "1245 - test scrolling when there are no rows"
self.cursor.execute("truncate table TestTempTable") self.cursor.execute("truncate table TestTempTable")
cursor = self.connection.cursor(scrollable=True) cursor = self.connection.cursor(scrollable=True)
@ -519,10 +518,10 @@ class TestCase(TestEnv.BaseTestCase):
self.assertEqual(cursor.fetchall(), []) self.assertEqual(cursor.fetchall(), [])
cursor.scroll(mode = "first") cursor.scroll(mode = "first")
self.assertEqual(cursor.fetchall(), []) self.assertEqual(cursor.fetchall(), [])
self.assertRaises(cx_Oracle.DatabaseError, cursor.scroll, 1, self.assertRaises(oracledb.DatabaseError, cursor.scroll, 1,
mode="absolute") mode="absolute")
def test_1246_ScrollDifferingArrayAndFetchSizes(self): def test_1246_scroll_differing_array_and_fetch_sizes(self):
"1246 - test scrolling with differing array and fetch array sizes" "1246 - test scrolling with differing array and fetch array sizes"
self.cursor.execute("truncate table TestTempTable") self.cursor.execute("truncate table TestTempTable")
for i in range(30): for i in range(30):
@ -530,74 +529,75 @@ class TestCase(TestEnv.BaseTestCase):
insert into TestTempTable (IntCol, StringCol) insert into TestTempTable (IntCol, StringCol)
values (:1, null)""", values (:1, null)""",
(i + 1,)) (i + 1,))
for arraySize in range(1, 6): for arraysize in range(1, 6):
cursor = self.connection.cursor(scrollable = True) cursor = self.connection.cursor(scrollable = True)
cursor.arraysize = arraySize cursor.arraysize = arraysize
cursor.execute("select IntCol from TestTempTable order by IntCol") cursor.execute("select IntCol from TestTempTable order by IntCol")
for numRows in range(1, arraySize + 1): for num_rows in range(1, arraysize + 1):
cursor.scroll(15, "absolute") cursor.scroll(15, "absolute")
rows = cursor.fetchmany(numRows) rows = cursor.fetchmany(num_rows)
self.assertEqual(rows[0][0], 15) self.assertEqual(rows[0][0], 15)
self.assertEqual(cursor.rowcount, 15 + numRows - 1) self.assertEqual(cursor.rowcount, 15 + num_rows - 1)
cursor.scroll(9) cursor.scroll(9)
rows = cursor.fetchmany(numRows) rows = cursor.fetchmany(num_rows)
numRowsFetched = len(rows) num_rows_fetched = len(rows)
self.assertEqual(rows[0][0], 15 + numRows + 8) self.assertEqual(rows[0][0], 15 + num_rows + 8)
self.assertEqual(cursor.rowcount, self.assertEqual(cursor.rowcount,
15 + numRows + numRowsFetched + 7) 15 + num_rows + num_rows_fetched + 7)
cursor.scroll(-12) cursor.scroll(-12)
rows = cursor.fetchmany(numRows) rows = cursor.fetchmany(num_rows)
self.assertEqual(rows[0][0], 15 + numRows + numRowsFetched - 5) count = 15 + num_rows + num_rows_fetched - 5
self.assertEqual(cursor.rowcount, self.assertEqual(rows[0][0], count)
15 + numRows + numRowsFetched + numRows - 6) count = 15 + num_rows + num_rows_fetched + num_rows - 6
self.assertEqual(cursor.rowcount, count)
def test_1247_SetInputSizesNegative(self): def test_1247_set_input_sizes_negative(self):
"1247 - test cursor.setinputsizes() with invalid parameters" "1247 - test cursor.setinputsizes() with invalid parameters"
val = decimal.Decimal(5) val = decimal.Decimal(5)
self.assertRaises(cx_Oracle.InterfaceError, self.assertRaises(oracledb.InterfaceError,
self.cursor.setinputsizes, val, x=val) self.cursor.setinputsizes, val, x=val)
self.assertRaises(TypeError, self.cursor.setinputsizes, val) self.assertRaises(TypeError, self.cursor.setinputsizes, val)
def test_1248_SetInputSizesNoParameters(self): def test_1248_set_input_sizes_no_parameters(self):
"1248 - test setting input sizes without any parameters" "1248 - test setting input sizes without any parameters"
self.cursor.setinputsizes() self.cursor.setinputsizes()
self.cursor.execute("select :val from dual", val="Test Value") self.cursor.execute("select :val from dual", val="Test Value")
self.assertEqual(self.cursor.fetchall(), [("Test Value",)]) self.assertEqual(self.cursor.fetchall(), [("Test Value",)])
def test_1249_SetInputSizesEmptyDict(self): def test_1249_set_input_sizes_empty_dict(self):
"1249 - test setting input sizes with an empty dictionary" "1249 - test setting input sizes with an empty dictionary"
emptyDict = {} empty_dict = {}
self.cursor.prepare("select 236 from dual") self.cursor.prepare("select 236 from dual")
self.cursor.setinputsizes(**emptyDict) self.cursor.setinputsizes(**empty_dict)
self.cursor.execute(None, emptyDict) self.cursor.execute(None, empty_dict)
self.assertEqual(self.cursor.fetchall(), [(236,)]) self.assertEqual(self.cursor.fetchall(), [(236,)])
def test_1250_SetInputSizesEmptyList(self): def test_1250_set_input_sizes_empty_list(self):
"1250 - test setting input sizes with an empty list" "1250 - test setting input sizes with an empty list"
emptyList = {} empty_list = {}
self.cursor.prepare("select 239 from dual") self.cursor.prepare("select 239 from dual")
self.cursor.setinputsizes(*emptyList) self.cursor.setinputsizes(*empty_list)
self.cursor.execute(None, emptyList) self.cursor.execute(None, empty_list)
self.assertEqual(self.cursor.fetchall(), [(239,)]) self.assertEqual(self.cursor.fetchall(), [(239,)])
def test_1251_SetInputSizesByPosition(self): def test_1251_set_input_sizes_by_position(self):
"1251 - test setting input sizes with positional args" "1251 - test setting input sizes with positional args"
var = self.cursor.var(cx_Oracle.STRING, 100) var = self.cursor.var(oracledb.STRING, 100)
self.cursor.setinputsizes(None, 5, None, 10, None, cx_Oracle.NUMBER) self.cursor.setinputsizes(None, 5, None, 10, None, oracledb.NUMBER)
self.cursor.execute(""" self.cursor.execute("""
begin begin
:1 := :2 || to_char(:3) || :4 || to_char(:5) || to_char(:6); :1 := :2 || to_char(:3) || :4 || to_char(:5) || to_char(:6);
end;""", [var, 'test_', 5, '_second_', 3, 7]) end;""", [var, 'test_', 5, '_second_', 3, 7])
self.assertEqual(var.getvalue(), "test_5_second_37") self.assertEqual(var.getvalue(), "test_5_second_37")
def test_1252_StringFormat(self): def test_1252_string_format(self):
"1252 - test string format of cursor" "1252 - test string format of cursor"
formatString = "<cx_Oracle.Cursor on <cx_Oracle.Connection to %s@%s>>" format_string = "<cx_Oracle.Cursor on <cx_Oracle.Connection to %s@%s>>"
expectedValue = formatString % \ expected_value = format_string % \
(TestEnv.GetMainUser(), TestEnv.GetConnectString()) (base.get_main_user(), base.get_connect_string())
self.assertEqual(str(self.cursor), expectedValue) self.assertEqual(str(self.cursor), expected_value)
def test_1253_CursorFetchRaw(self): def test_1253_cursor_fetch_raw(self):
"1253 - test cursor.fetchraw()" "1253 - test cursor.fetchraw()"
cursor = self.connection.cursor() cursor = self.connection.cursor()
cursor.arraysize = 25 cursor.arraysize = 25
@ -605,28 +605,28 @@ class TestCase(TestEnv.BaseTestCase):
self.assertEqual(cursor.fetchraw(), 10) self.assertEqual(cursor.fetchraw(), 10)
self.assertEqual(cursor.fetchvars[0].getvalue(), 38) self.assertEqual(cursor.fetchvars[0].getvalue(), 38)
def test_1254_Parse(self): def test_1254_parse(self):
"1254 - test parsing statements" "1254 - test parsing statements"
sql = "select LongIntCol from TestNumbers where IntCol = :val" sql = "select LongIntCol from TestNumbers where IntCol = :val"
self.cursor.parse(sql) self.cursor.parse(sql)
self.assertEqual(self.cursor.statement, sql) self.assertEqual(self.cursor.statement, sql)
self.assertEqual(self.cursor.description, self.assertEqual(self.cursor.description,
[ ('LONGINTCOL', cx_Oracle.DB_TYPE_NUMBER, 17, None, 16, 0, [('LONGINTCOL', oracledb.DB_TYPE_NUMBER, 17, None,
0) ]) 16, 0, 0)])
def test_1255_SetOutputSize(self): def test_1255_set_output_size(self):
"1255 - test cursor.setoutputsize() does not fail (but does nothing)" "1255 - test cursor.setoutputsize() does not fail (but does nothing)"
self.cursor.setoutputsize(100, 2) self.cursor.setoutputsize(100, 2)
def test_1256_VarNegative(self): def test_1256_var_negative(self):
"1256 - test cursor.var() with invalid parameters" "1256 - test cursor.var() with invalid parameters"
self.assertRaises(TypeError, self.cursor.var, 5) self.assertRaises(TypeError, self.cursor.var, 5)
def test_1257_ArrayVarNegative(self): def test_1257_arrayvar_negative(self):
"1257 - test cursor.arrayvar() with invalid parameters" "1257 - test cursor.arrayvar() with invalid parameters"
self.assertRaises(TypeError, self.cursor.arrayvar, 5, 1) self.assertRaises(TypeError, self.cursor.arrayvar, 5, 1)
def test_1258_BooleanWithoutPlsql(self): def test_1258_boolean_without_plsql(self):
"1258 - test binding boolean data without the use of PL/SQL" "1258 - test binding boolean data without the use of PL/SQL"
self.cursor.execute("truncate table TestTempTable") self.cursor.execute("truncate table TestTempTable")
sql = "insert into TestTempTable (IntCol, StringCol) values (:1, :2)" sql = "insert into TestTempTable (IntCol, StringCol) values (:1, :2)"
@ -639,16 +639,16 @@ class TestCase(TestEnv.BaseTestCase):
self.assertEqual(self.cursor.fetchall(), self.assertEqual(self.cursor.fetchall(),
[(0, "Value should be 0"), (1, "Value should be 1")]) [(0, "Value should be 0"), (1, "Value should be 1")])
def test_1259_AsContextManager(self): def test_1259_as_context_manager(self):
"1259 - test using a cursor as a context manager" "1259 - test using a cursor as a context manager"
with self.cursor as cursor: with self.cursor as cursor:
cursor.execute("truncate table TestTempTable") cursor.execute("truncate table TestTempTable")
cursor.execute("select count(*) from TestTempTable") cursor.execute("select count(*) from TestTempTable")
count, = cursor.fetchone() count, = cursor.fetchone()
self.assertEqual(count, 0) self.assertEqual(count, 0)
self.assertRaises(cx_Oracle.InterfaceError, self.cursor.close) self.assertRaises(oracledb.InterfaceError, self.cursor.close)
def test_1260_QueryRowCount(self): def test_1260_query_row_count(self):
"1260 - test that rowcount attribute is reset to zero on query execute" "1260 - test that rowcount attribute is reset to zero on query execute"
sql = "select * from dual where 1 = :s" sql = "select * from dual where 1 = :s"
self.cursor.execute(sql, [0]) self.cursor.execute(sql, [0])
@ -664,39 +664,39 @@ class TestCase(TestEnv.BaseTestCase):
self.cursor.fetchone() self.cursor.fetchone()
self.assertEqual(self.cursor.rowcount, 0) self.assertEqual(self.cursor.rowcount, 0)
def test_1261_VarTypeNameNone(self): def test_1261_var_type_name_none(self):
"1261 - test that the typename attribute can be passed a value of None" "1261 - test that the typename attribute can be passed a value of None"
valueToSet = 5 value_to_set = 5
var = self.cursor.var(int, typename=None) var = self.cursor.var(int, typename=None)
var.setvalue(0, valueToSet) var.setvalue(0, value_to_set)
self.assertEqual(var.getvalue(), valueToSet) self.assertEqual(var.getvalue(), value_to_set)
def test_1262_VarTypeWithObjectType(self): def test_1262_var_type_with_object_type(self):
"1262 - test that an object type can be used as type in cursor.var()" "1262 - test that an object type can be used as type in cursor.var()"
objType = self.connection.gettype("UDT_OBJECT") obj_type = self.connection.gettype("UDT_OBJECT")
var = self.cursor.var(objType) var = self.cursor.var(obj_type)
self.cursor.callproc("pkg_TestBindObject.BindObjectOut", self.cursor.callproc("pkg_TestBindObject.BindObjectOut",
(28, "Bind obj out", var)) (28, "Bind obj out", var))
obj = var.getvalue() obj = var.getvalue()
result = self.cursor.callfunc("pkg_TestBindObject.GetStringRep", str, result = self.cursor.callfunc("pkg_TestBindObject.GetStringRep", str,
(obj,)) (obj,))
self.assertEqual(result, exp = "udt_Object(28, 'Bind obj out', null, null, null, null, null)"
"udt_Object(28, 'Bind obj out', null, null, null, null, null)") self.assertEqual(result, exp)
def test_1263_FetchXMLType(self): def test_1263_fetch_xmltype(self):
"1263 - test that fetching an XMLType returns a string" "1263 - test that fetching an XMLType returns a string"
intVal = 5 int_val = 5
label = "IntCol" label = "IntCol"
expectedResult = "<%s>%s</%s>" % (label, intVal, label) expected_result = "<%s>%s</%s>" % (label, int_val, label)
self.cursor.execute(""" self.cursor.execute("""
select XMLElement("%s", IntCol) select XMLElement("%s", IntCol)
from TestStrings from TestStrings
where IntCol = :intVal""" % label, where IntCol = :int_val""" % label,
intVal = intVal) int_val=int_val)
result, = self.cursor.fetchone() result, = self.cursor.fetchone()
self.assertEqual(result, expectedResult) self.assertEqual(result, expected_result)
def test_1264_LastRowid(self): def test_1264_lastrowid(self):
"1264 - test last rowid" "1264 - test last rowid"
# no statement executed: no rowid # no statement executed: no rowid
@ -748,9 +748,9 @@ class TestCase(TestEnv.BaseTestCase):
where rowid = :1""", [rowid]) where rowid = :1""", [rowid])
self.assertEqual("Row %s" % rows[-3], self.cursor.fetchone()[0]) self.assertEqual("Row %s" % rows[-3], self.cursor.fetchone()[0])
def test_1265_PrefetchRows(self): def test_1265_prefetchrows(self):
"1265 - test prefetch rows" "1265 - test prefetch rows"
self.setUpRoundTripChecker() self.setup_round_trip_checker()
# perform simple query and verify only one round trip is needed # perform simple query and verify only one round trip is needed
with self.connection.cursor() as cursor: with self.connection.cursor() as cursor:
@ -769,10 +769,10 @@ class TestCase(TestEnv.BaseTestCase):
self.assertRoundTrips(1) self.assertRoundTrips(1)
# array execution only requires a single round trip # array execution only requires a single round trip
numRows = 590 num_rows = 590
with self.connection.cursor() as cursor: with self.connection.cursor() as cursor:
sql = "insert into TestTempTable (IntCol) values (:1)" sql = "insert into TestTempTable (IntCol) values (:1)"
data = [(n + 1,) for n in range(numRows)] data = [(n + 1,) for n in range(num_rows)]
cursor.executemany(sql, data) cursor.executemany(sql, data)
self.assertRoundTrips(1) self.assertRoundTrips(1)
@ -782,7 +782,7 @@ class TestCase(TestEnv.BaseTestCase):
cursor.prefetchrows = 1 cursor.prefetchrows = 1
cursor.arraysize = 1 cursor.arraysize = 1
cursor.execute("select IntCol from TestTempTable").fetchall() cursor.execute("select IntCol from TestTempTable").fetchall()
self.assertRoundTrips(numRows + 1) self.assertRoundTrips(num_rows + 1)
# setting prefetch and array size to 300 requires 2 round-trips # setting prefetch and array size to 300 requires 2 round-trips
with self.connection.cursor() as cursor: with self.connection.cursor() as cursor:
@ -792,4 +792,4 @@ class TestCase(TestEnv.BaseTestCase):
self.assertRoundTrips(2) self.assertRoundTrips(2)
if __name__ == "__main__": if __name__ == "__main__":
TestEnv.RunTestCases() base.run_test_cases()

View File

@ -11,14 +11,14 @@
1300 - Module for testing cursor variables 1300 - Module for testing cursor variables
""" """
import TestEnv import base
import cx_Oracle import cx_Oracle as oracledb
import sys import sys
class TestCase(TestEnv.BaseTestCase): class TestCase(base.BaseTestCase):
def test_1300_BindCursor(self): def test_1300_bind_cursor(self):
"1300 - test binding in a cursor" "1300 - test binding in a cursor"
cursor = self.connection.cursor() cursor = self.connection.cursor()
self.assertEqual(cursor.description, None) self.assertEqual(cursor.description, None)
@ -27,24 +27,27 @@ class TestCase(TestEnv.BaseTestCase):
open :cursor for select 'X' StringValue from dual; open :cursor for select 'X' StringValue from dual;
end;""", end;""",
cursor=cursor) cursor=cursor)
self.assertEqual(cursor.description, expected_value = [
[ ('STRINGVALUE', cx_Oracle.DB_TYPE_CHAR, 1, ('STRINGVALUE', oracledb.DB_TYPE_CHAR, 1,
TestEnv.GetCharSetRatio(), None, None, 1) ]) base.get_charset_ratio(), None, None, 1)
]
self.assertEqual(cursor.description, expected_value)
self.assertEqual(cursor.fetchall(), [('X',)]) self.assertEqual(cursor.fetchall(), [('X',)])
def test_1301_BindCursorInPackage(self): def test_1301_bind_cursor_in_package(self):
"1301 - test binding in a cursor from a package" "1301 - test binding in a cursor from a package"
cursor = self.connection.cursor() cursor = self.connection.cursor()
self.assertEqual(cursor.description, None) self.assertEqual(cursor.description, None)
self.cursor.callproc("pkg_TestRefCursors.TestOutCursor", (2, cursor)) self.cursor.callproc("pkg_TestRefCursors.TestOutCursor", (2, cursor))
self.assertEqual(cursor.description, expected_value = [
[ ('INTCOL', cx_Oracle.DB_TYPE_NUMBER, 10, None, 9, 0, 0), ('INTCOL', oracledb.DB_TYPE_NUMBER, 10, None, 9, 0, 0),
('STRINGCOL', cx_Oracle.DB_TYPE_VARCHAR, 20, 20 * ('STRINGCOL', oracledb.DB_TYPE_VARCHAR, 20,
TestEnv.GetCharSetRatio(), None, None, 0) ]) 20 * base.get_charset_ratio(), None, None, 0)
self.assertEqual(cursor.fetchall(), ]
[ (1, 'String 1'), (2, 'String 2') ]) self.assertEqual(cursor.description, expected_value)
self.assertEqual(cursor.fetchall(), [(1, 'String 1'), (2, 'String 2')])
def test_1302_BindSelf(self): def test_1302_bind_self(self):
"1302 - test that binding the cursor itself is not supported" "1302 - test that binding the cursor itself is not supported"
cursor = self.connection.cursor() cursor = self.connection.cursor()
sql = """ sql = """
@ -52,12 +55,12 @@ class TestCase(TestEnv.BaseTestCase):
open :pcursor for open :pcursor for
select 1 from dual; select 1 from dual;
end;""" end;"""
self.assertRaises(cx_Oracle.DatabaseError, cursor.execute, sql, self.assertRaises(oracledb.DatabaseError, cursor.execute, sql,
pcursor=cursor) pcursor=cursor)
def test_1303_ExecuteAfterClose(self): def test_1303_execute_after_close(self):
"1303 - test returning a ref cursor after closing it" "1303 - test returning a ref cursor after closing it"
outCursor = self.connection.cursor() out_cursor = self.connection.cursor()
sql = """ sql = """
begin begin
open :pcursor for open :pcursor for
@ -65,15 +68,15 @@ class TestCase(TestEnv.BaseTestCase):
from TestNumbers from TestNumbers
order by IntCol; order by IntCol;
end;""" end;"""
self.cursor.execute(sql, pcursor = outCursor) self.cursor.execute(sql, pcursor=out_cursor)
rows = outCursor.fetchall() rows = out_cursor.fetchall()
outCursor.close() out_cursor.close()
outCursor = self.connection.cursor() out_cursor = self.connection.cursor()
self.cursor.execute(sql, pcursor = outCursor) self.cursor.execute(sql, pcursor=out_cursor)
rows2 = outCursor.fetchall() rows2 = out_cursor.fetchall()
self.assertEqual(rows, rows2) self.assertEqual(rows, rows2)
def test_1304_FetchCursor(self): def test_1304_fetch_cursor(self):
"1304 - test fetching a cursor" "1304 - test fetching a cursor"
self.cursor.execute(""" self.cursor.execute("""
select select
@ -81,14 +84,15 @@ class TestCase(TestEnv.BaseTestCase):
cursor(select IntCol + 1 from dual) CursorValue cursor(select IntCol + 1 from dual) CursorValue
from TestNumbers from TestNumbers
order by IntCol""") order by IntCol""")
self.assertEqual(self.cursor.description, expected_value = [
[ ('INTCOL', cx_Oracle.DB_TYPE_NUMBER, 10, None, 9, 0, 0), ('INTCOL', oracledb.DB_TYPE_NUMBER, 10, None, 9, 0, 0),
('CURSORVALUE', cx_Oracle.DB_TYPE_CURSOR, None, None, None, ('CURSORVALUE', oracledb.DB_TYPE_CURSOR, None, None, None, None, 1)
None, 1) ]) ]
self.assertEqual(self.cursor.description, expected_value)
for i in range(1, 11): for i in range(1, 11):
number, cursor = self.cursor.fetchone() number, cursor = self.cursor.fetchone()
self.assertEqual(number, i) self.assertEqual(number, i)
self.assertEqual(cursor.fetchall(), [(i + 1,)]) self.assertEqual(cursor.fetchall(), [(i + 1,)])
if __name__ == "__main__": if __name__ == "__main__":
TestEnv.RunTestCases() base.run_test_cases()

View File

@ -11,187 +11,183 @@
1400 - Module for testing date/time variables 1400 - Module for testing date/time variables
""" """
import TestEnv import base
import cx_Oracle import cx_Oracle as oracledb
import datetime import datetime
import time import time
class TestCase(TestEnv.BaseTestCase): class TestCase(base.BaseTestCase):
def setUp(self): def setUp(self):
TestEnv.BaseTestCase.setUp(self) super().setUp()
self.rawData = [] self.raw_data = []
self.dataByKey = {} self.data_by_key = {}
for i in range(1, 11): for i in range(1, 11):
timeTuple = (2002, 12, 9, 0, 0, 0, 0, 0, -1) time_tuple = (2002, 12, 9, 0, 0, 0, 0, 0, -1)
timeInTicks = time.mktime(timeTuple) + i * 86400 + i * 8640 time_in_ticks = time.mktime(time_tuple) + i * 86400 + i * 8640
dateCol = cx_Oracle.TimestampFromTicks(int(timeInTicks)) date_col = oracledb.TimestampFromTicks(int(time_in_ticks))
if i % 2: if i % 2:
timeInTicks = time.mktime(timeTuple) + i * 86400 * 2 + \ time_in_ticks = time.mktime(time_tuple) + i * 86400 * 2 + \
i * 12960 i * 12960
nullableCol = cx_Oracle.TimestampFromTicks(int(timeInTicks)) nullable_col = oracledb.TimestampFromTicks(int(time_in_ticks))
else: else:
nullableCol = None nullable_col = None
tuple = (i, dateCol, nullableCol) tuple = (i, date_col, nullable_col)
self.rawData.append(tuple) self.raw_data.append(tuple)
self.dataByKey[i] = tuple self.data_by_key[i] = tuple
def test_1400_BindDate(self): def test_1400_bind_date(self):
"1400 - test binding in a date" "1400 - test binding in a date"
self.cursor.execute(""" self.cursor.execute("""
select * from TestDates select * from TestDates
where DateCol = :value""", where DateCol = :value""",
value = cx_Oracle.Timestamp(2002, 12, 13, 9, 36, 0)) value = oracledb.Timestamp(2002, 12, 13, 9, 36, 0))
self.assertEqual(self.cursor.fetchall(), [self.dataByKey[4]]) self.assertEqual(self.cursor.fetchall(), [self.data_by_key[4]])
def test_1401_BindDateTime(self): def test_1401_bind_datetime(self):
"1401 - test binding in a datetime.datetime value" "1401 - test binding in a datetime.datetime value"
self.cursor.execute(""" self.cursor.execute("""
select * from TestDates select * from TestDates
where DateCol = :value""", where DateCol = :value""",
value=datetime.datetime(2002, 12, 13, 9, 36, 0)) value=datetime.datetime(2002, 12, 13, 9, 36, 0))
self.assertEqual(self.cursor.fetchall(), [self.dataByKey[4]]) self.assertEqual(self.cursor.fetchall(), [self.data_by_key[4]])
def test_1402_BindDateInDateTimeVar(self): def test_1402_bind_date_in_datetime_var(self):
"1402 - test binding date in a datetime variable" "1402 - test binding date in a datetime variable"
var = self.cursor.var(cx_Oracle.DATETIME) var = self.cursor.var(oracledb.DATETIME)
dateVal = datetime.date.today() dateVal = datetime.date.today()
var.setvalue(0, dateVal) var.setvalue(0, dateVal)
self.assertEqual(var.getvalue().date(), dateVal) self.assertEqual(var.getvalue().date(), dateVal)
def test_1403_BindDateAfterString(self): def test_1403_bind_date_after_string(self):
"1403 - test binding in a date after setting input sizes to a string" "1403 - test binding in a date after setting input sizes to a string"
self.cursor.setinputsizes(value=15) self.cursor.setinputsizes(value=15)
self.cursor.execute(""" self.cursor.execute("""
select * from TestDates select * from TestDates
where DateCol = :value""", where DateCol = :value""",
value = cx_Oracle.Timestamp(2002, 12, 14, 12, 0, 0)) value = oracledb.Timestamp(2002, 12, 14, 12, 0, 0))
self.assertEqual(self.cursor.fetchall(), [self.dataByKey[5]]) self.assertEqual(self.cursor.fetchall(), [self.data_by_key[5]])
def test_1404_BindNull(self): def test_1404_bind_null(self):
"1404 - test binding in a null" "1404 - test binding in a null"
self.cursor.setinputsizes(value = cx_Oracle.DATETIME) self.cursor.setinputsizes(value=oracledb.DATETIME)
self.cursor.execute(""" self.cursor.execute("""
select * from TestDates select * from TestDates
where DateCol = :value""", where DateCol = :value""",
value = None) value = None)
self.assertEqual(self.cursor.fetchall(), []) self.assertEqual(self.cursor.fetchall(), [])
def test_1405_BindDateArrayDirect(self): def test_1405_bind_date_array_direct(self):
"1405 - test binding in a date array" "1405 - test binding in a date array"
returnValue = self.cursor.var(cx_Oracle.NUMBER) return_value = self.cursor.var(oracledb.NUMBER)
array = [r[1] for r in self.rawData] array = [r[1] for r in self.raw_data]
statement = """ statement = """
begin begin
:returnValue := pkg_TestDateArrays.TestInArrays( :return_value := pkg_TestDateArrays.TestInArrays(
:startValue, :baseDate, :array); :start_value, :base_date, :array);
end;""" end;"""
self.cursor.execute(statement, self.cursor.execute(statement, return_value=return_value,
returnValue = returnValue, start_value=5,
startValue = 5, base_date=oracledb.Date(2002, 12, 12), array=array)
baseDate = cx_Oracle.Date(2002, 12, 12), self.assertEqual(return_value.getvalue(), 35.5)
array = array)
self.assertEqual(returnValue.getvalue(), 35.5)
array = array + array[:5] array = array + array[:5]
self.cursor.execute(statement, self.cursor.execute(statement, start_value=7,
startValue = 7, base_date=oracledb.Date(2002, 12, 13), array=array)
baseDate = cx_Oracle.Date(2002, 12, 13), self.assertEqual(return_value.getvalue(), 24.0)
array = array)
self.assertEqual(returnValue.getvalue(), 24.0)
def test_1406_BindDateArrayBySizes(self): def test_1406_bind_date_array_by_sizes(self):
"1406 - test binding in a date array (with setinputsizes)" "1406 - test binding in a date array (with setinputsizes)"
returnValue = self.cursor.var(cx_Oracle.NUMBER) return_value = self.cursor.var(oracledb.NUMBER)
self.cursor.setinputsizes(array = [cx_Oracle.DATETIME, 10]) self.cursor.setinputsizes(array=[oracledb.DATETIME, 10])
array = [r[1] for r in self.rawData] array = [r[1] for r in self.raw_data]
self.cursor.execute(""" self.cursor.execute("""
begin begin
:returnValue := pkg_TestDateArrays.TestInArrays( :return_value := pkg_TestDateArrays.TestInArrays(
:startValue, :baseDate, :array); :start_value, :base_date, :array);
end;""", end;""",
returnValue = returnValue, return_value=return_value,
startValue = 6, start_value=6,
baseDate = cx_Oracle.Date(2002, 12, 13), base_date=oracledb.Date(2002, 12, 13),
array=array) array=array)
self.assertEqual(returnValue.getvalue(), 26.5) self.assertEqual(return_value.getvalue(), 26.5)
def test_1407_BindDateArrayByVar(self): def test_1407_bind_date_array_by_var(self):
"1407 - test binding in a date array (with arrayvar)" "1407 - test binding in a date array (with arrayvar)"
returnValue = self.cursor.var(cx_Oracle.NUMBER) return_value = self.cursor.var(oracledb.NUMBER)
array = self.cursor.arrayvar(cx_Oracle.DATETIME, 10, 20) array = self.cursor.arrayvar(oracledb.DATETIME, 10, 20)
array.setvalue(0, [r[1] for r in self.rawData]) array.setvalue(0, [r[1] for r in self.raw_data])
self.cursor.execute(""" self.cursor.execute("""
begin begin
:returnValue := pkg_TestDateArrays.TestInArrays( :return_value := pkg_TestDateArrays.TestInArrays(
:startValue, :baseDate, :array); :start_value, :base_date, :array);
end;""", end;""",
returnValue = returnValue, return_value=return_value,
startValue = 7, start_value=7,
baseDate = cx_Oracle.Date(2002, 12, 14), base_date=oracledb.Date(2002, 12, 14),
array=array) array=array)
self.assertEqual(returnValue.getvalue(), 17.5) self.assertEqual(return_value.getvalue(), 17.5)
def test_1408_BindInOutDateArrayByVar(self): def test_1408_bind_in_out_date_array_by_var(self):
"1408 - test binding in/out a date array (with arrayvar)" "1408 - test binding in/out a date array (with arrayvar)"
array = self.cursor.arrayvar(cx_Oracle.DATETIME, 10, 100) array = self.cursor.arrayvar(oracledb.DATETIME, 10, 100)
originalData = [r[1] for r in self.rawData] original_data = [r[1] for r in self.raw_data]
array.setvalue(0, originalData) array.setvalue(0, original_data)
self.cursor.execute(""" self.cursor.execute("""
begin begin
pkg_TestDateArrays.TestInOutArrays(:numElems, :array); pkg_TestDateArrays.TestInOutArrays(:num_elems, :array);
end;""", end;""",
numElems = 5, num_elems=5,
array=array) array=array)
self.assertEqual(array.getvalue(), self.assertEqual(array.getvalue(),
[ cx_Oracle.Timestamp(2002, 12, 17, 2, 24, 0), [ oracledb.Timestamp(2002, 12, 17, 2, 24, 0),
cx_Oracle.Timestamp(2002, 12, 18, 4, 48, 0), oracledb.Timestamp(2002, 12, 18, 4, 48, 0),
cx_Oracle.Timestamp(2002, 12, 19, 7, 12, 0), oracledb.Timestamp(2002, 12, 19, 7, 12, 0),
cx_Oracle.Timestamp(2002, 12, 20, 9, 36, 0), oracledb.Timestamp(2002, 12, 20, 9, 36, 0),
cx_Oracle.Timestamp(2002, 12, 21, 12, 0, 0) ] + \ oracledb.Timestamp(2002, 12, 21, 12, 0, 0) ] + \
originalData[5:]) original_data[5:])
def test_1409_BindOutDateArrayByVar(self): def test_1409_bind_out_date_array_by_var(self):
"1409 - test binding out a date array (with arrayvar)" "1409 - test binding out a date array (with arrayvar)"
array = self.cursor.arrayvar(cx_Oracle.DATETIME, 6, 100) array = self.cursor.arrayvar(oracledb.DATETIME, 6, 100)
self.cursor.execute(""" self.cursor.execute("""
begin begin
pkg_TestDateArrays.TestOutArrays(:numElems, :array); pkg_TestDateArrays.TestOutArrays(:num_elems, :array);
end;""", end;""",
numElems = 6, num_elems=6,
array=array) array=array)
self.assertEqual(array.getvalue(), self.assertEqual(array.getvalue(),
[ cx_Oracle.Timestamp(2002, 12, 13, 4, 48, 0), [ oracledb.Timestamp(2002, 12, 13, 4, 48, 0),
cx_Oracle.Timestamp(2002, 12, 14, 9, 36, 0), oracledb.Timestamp(2002, 12, 14, 9, 36, 0),
cx_Oracle.Timestamp(2002, 12, 15, 14, 24, 0), oracledb.Timestamp(2002, 12, 15, 14, 24, 0),
cx_Oracle.Timestamp(2002, 12, 16, 19, 12, 0), oracledb.Timestamp(2002, 12, 16, 19, 12, 0),
cx_Oracle.Timestamp(2002, 12, 18, 0, 0, 0), oracledb.Timestamp(2002, 12, 18, 0, 0, 0),
cx_Oracle.Timestamp(2002, 12, 19, 4, 48, 0) ]) oracledb.Timestamp(2002, 12, 19, 4, 48, 0) ])
def test_1410_BindOutSetInputSizes(self): def test_1410_bind_out_set_input_sizes(self):
"1410 - test binding out with set input sizes defined" "1410 - test binding out with set input sizes defined"
vars = self.cursor.setinputsizes(value = cx_Oracle.DATETIME) bind_vars = self.cursor.setinputsizes(value=oracledb.DATETIME)
self.cursor.execute(""" self.cursor.execute("""
begin begin
:value := to_date(20021209, 'YYYYMMDD'); :value := to_date(20021209, 'YYYYMMDD');
end;""") end;""")
self.assertEqual(vars["value"].getvalue(), self.assertEqual(bind_vars["value"].getvalue(),
cx_Oracle.Timestamp(2002, 12, 9)) oracledb.Timestamp(2002, 12, 9))
def test_1411_BindInOutSetInputSizes(self): def test_1411_bind_in_out_set_input_sizes(self):
"1411 - test binding in/out with set input sizes defined" "1411 - test binding in/out with set input sizes defined"
vars = self.cursor.setinputsizes(value = cx_Oracle.DATETIME) bind_vars = self.cursor.setinputsizes(value=oracledb.DATETIME)
self.cursor.execute(""" self.cursor.execute("""
begin begin
:value := :value + 5.25; :value := :value + 5.25;
end;""", end;""",
value = cx_Oracle.Timestamp(2002, 12, 12, 10, 0, 0)) value=oracledb.Timestamp(2002, 12, 12, 10, 0, 0))
self.assertEqual(vars["value"].getvalue(), self.assertEqual(bind_vars["value"].getvalue(),
cx_Oracle.Timestamp(2002, 12, 17, 16, 0, 0)) oracledb.Timestamp(2002, 12, 17, 16, 0, 0))
def test_1412_BindOutVar(self): def test_1412_bind_out_var(self):
"1412 - test binding out with cursor.var() method" "1412 - test binding out with cursor.var() method"
var = self.cursor.var(cx_Oracle.DATETIME) var = self.cursor.var(oracledb.DATETIME)
self.cursor.execute(""" self.cursor.execute("""
begin begin
:value := to_date('20021231 12:31:00', :value := to_date('20021231 12:31:00',
@ -199,54 +195,55 @@ class TestCase(TestEnv.BaseTestCase):
end;""", end;""",
value=var) value=var)
self.assertEqual(var.getvalue(), self.assertEqual(var.getvalue(),
cx_Oracle.Timestamp(2002, 12, 31, 12, 31, 0)) oracledb.Timestamp(2002, 12, 31, 12, 31, 0))
def test_1413_BindInOutVarDirectSet(self): def test_1413_bind_in_out_var_direct_set(self):
"1413 - test binding in/out with cursor.var() method" "1413 - test binding in/out with cursor.var() method"
var = self.cursor.var(cx_Oracle.DATETIME) var = self.cursor.var(oracledb.DATETIME)
var.setvalue(0, cx_Oracle.Timestamp(2002, 12, 9, 6, 0, 0)) var.setvalue(0, oracledb.Timestamp(2002, 12, 9, 6, 0, 0))
self.cursor.execute(""" self.cursor.execute("""
begin begin
:value := :value + 5.25; :value := :value + 5.25;
end;""", end;""",
value=var) value=var)
self.assertEqual(var.getvalue(), self.assertEqual(var.getvalue(),
cx_Oracle.Timestamp(2002, 12, 14, 12, 0, 0)) oracledb.Timestamp(2002, 12, 14, 12, 0, 0))
def test_1414_CursorDescription(self): def test_1414_cursor_description(self):
"1414 - test cursor description is accurate" "1414 - test cursor description is accurate"
self.cursor.execute("select * from TestDates") self.cursor.execute("select * from TestDates")
self.assertEqual(self.cursor.description, expected_value = [
[ ('INTCOL', cx_Oracle.DB_TYPE_NUMBER, 10, None, 9, 0, 0), ('INTCOL', oracledb.DB_TYPE_NUMBER, 10, None, 9, 0, 0),
('DATECOL', cx_Oracle.DB_TYPE_DATE, 23, None, None, None, 0), ('DATECOL', oracledb.DB_TYPE_DATE, 23, None, None, None, 0),
('NULLABLECOL', cx_Oracle.DB_TYPE_DATE, 23, None, None, None, ('NULLABLECOL', oracledb.DB_TYPE_DATE, 23, None, None, None, 1)
1) ]) ]
self.assertEqual(self.cursor.description, expected_value)
def test_1415_FetchAll(self): def test_1415_fetchall(self):
"1415 - test that fetching all of the data returns the correct results" "1415 - test that fetching all of the data returns the correct results"
self.cursor.execute("select * From TestDates order by IntCol") self.cursor.execute("select * From TestDates order by IntCol")
self.assertEqual(self.cursor.fetchall(), self.rawData) self.assertEqual(self.cursor.fetchall(), self.raw_data)
self.assertEqual(self.cursor.fetchall(), []) self.assertEqual(self.cursor.fetchall(), [])
def test_1416_FetchMany(self): def test_1416_fetchmany(self):
"1416 - test that fetching data in chunks returns the correct results" "1416 - test that fetching data in chunks returns the correct results"
self.cursor.execute("select * From TestDates order by IntCol") self.cursor.execute("select * From TestDates order by IntCol")
self.assertEqual(self.cursor.fetchmany(3), self.rawData[0:3]) self.assertEqual(self.cursor.fetchmany(3), self.raw_data[0:3])
self.assertEqual(self.cursor.fetchmany(2), self.rawData[3:5]) self.assertEqual(self.cursor.fetchmany(2), self.raw_data[3:5])
self.assertEqual(self.cursor.fetchmany(4), self.rawData[5:9]) self.assertEqual(self.cursor.fetchmany(4), self.raw_data[5:9])
self.assertEqual(self.cursor.fetchmany(3), self.rawData[9:]) self.assertEqual(self.cursor.fetchmany(3), self.raw_data[9:])
self.assertEqual(self.cursor.fetchmany(3), []) self.assertEqual(self.cursor.fetchmany(3), [])
def test_1417_FetchOne(self): def test_1417_fetchone(self):
"1417 - test that fetching a single row returns the correct results" "1417 - test that fetching a single row returns the correct results"
self.cursor.execute(""" self.cursor.execute("""
select * select *
from TestDates from TestDates
where IntCol in (3, 4) where IntCol in (3, 4)
order by IntCol""") order by IntCol""")
self.assertEqual(self.cursor.fetchone(), self.dataByKey[3]) self.assertEqual(self.cursor.fetchone(), self.data_by_key[3])
self.assertEqual(self.cursor.fetchone(), self.dataByKey[4]) self.assertEqual(self.cursor.fetchone(), self.data_by_key[4])
self.assertEqual(self.cursor.fetchone(), None) self.assertEqual(self.cursor.fetchone(), None)
if __name__ == "__main__": if __name__ == "__main__":
TestEnv.RunTestCases() base.run_test_cases()

View File

@ -8,172 +8,173 @@ including the synonyms retained for backwards compatibility. This module also
tests for pickling/unpickling of database types and API types. tests for pickling/unpickling of database types and API types.
""" """
import TestEnv import base
import cx_Oracle import cx_Oracle as oracledb
import pickle import pickle
class TestCase(TestEnv.BaseTestCase): class TestCase(base.BaseTestCase):
requires_connection = False
def __testCompare(self, dbType, apiType): def __test_compare(self, db_type, api_type):
self.assertEqual(dbType, dbType) self.assertEqual(db_type, db_type)
self.assertEqual(dbType, apiType) self.assertEqual(db_type, api_type)
self.assertEqual(apiType, dbType) self.assertEqual(api_type, db_type)
self.assertNotEqual(dbType, 5) self.assertNotEqual(db_type, 5)
self.assertNotEqual(dbType, cx_Oracle.DB_TYPE_OBJECT) self.assertNotEqual(db_type, oracledb.DB_TYPE_OBJECT)
def __testPickle(self, typ): def __test_pickle(self, typ):
self.assertIs(typ, pickle.loads(pickle.dumps(typ))) self.assertIs(typ, pickle.loads(pickle.dumps(typ)))
def test_1500_DB_TYPE_BFILE(self): def test_1500_DB_TYPE_BFILE(self):
"1500 - test cx_Oracle.DB_TYPE_BFILE comparisons and pickling" "1500 - test oracledb.DB_TYPE_BFILE comparisons and pickling"
self.assertEqual(cx_Oracle.DB_TYPE_BFILE, cx_Oracle.BFILE) self.assertEqual(oracledb.DB_TYPE_BFILE, oracledb.BFILE)
self.__testPickle(cx_Oracle.DB_TYPE_BFILE) self.__test_pickle(oracledb.DB_TYPE_BFILE)
def test_1501_DB_TYPE_BINARY_DOUBLE(self): def test_1501_DB_TYPE_BINARY_DOUBLE(self):
"1501 - test cx_Oracle.DB_TYPE_BINARY_DOUBLE comparisons and pickling" "1501 - test oracledb.DB_TYPE_BINARY_DOUBLE comparisons and pickling"
self.__testCompare(cx_Oracle.DB_TYPE_BINARY_DOUBLE, cx_Oracle.NUMBER) self.__test_compare(oracledb.DB_TYPE_BINARY_DOUBLE, oracledb.NUMBER)
self.assertEqual(cx_Oracle.DB_TYPE_BINARY_DOUBLE, self.assertEqual(oracledb.DB_TYPE_BINARY_DOUBLE,
cx_Oracle.NATIVE_FLOAT) oracledb.NATIVE_FLOAT)
self.__testPickle(cx_Oracle.DB_TYPE_BINARY_DOUBLE) self.__test_pickle(oracledb.DB_TYPE_BINARY_DOUBLE)
def test_1502_DB_TYPE_BINARY_FLOAT(self): def test_1502_DB_TYPE_BINARY_FLOAT(self):
"1502 - test cx_Oracle.DB_TYPE_BINARY_FLOAT comparisons and pickling" "1502 - test oracledb.DB_TYPE_BINARY_FLOAT comparisons and pickling"
self.__testCompare(cx_Oracle.DB_TYPE_BINARY_FLOAT, cx_Oracle.NUMBER) self.__test_compare(oracledb.DB_TYPE_BINARY_FLOAT, oracledb.NUMBER)
self.__testPickle(cx_Oracle.DB_TYPE_BINARY_FLOAT) self.__test_pickle(oracledb.DB_TYPE_BINARY_FLOAT)
def test_1503_DB_TYPE_BINARY_INTEGER(self): def test_1503_DB_TYPE_BINARY_INTEGER(self):
"1503 - test cx_Oracle.DB_TYPE_BINARY_INTEGER comparisons and pickling" "1503 - test oracledb.DB_TYPE_BINARY_INTEGER comparisons and pickling"
self.__testCompare(cx_Oracle.DB_TYPE_BINARY_INTEGER, cx_Oracle.NUMBER) self.__test_compare(oracledb.DB_TYPE_BINARY_INTEGER, oracledb.NUMBER)
self.assertEqual(cx_Oracle.DB_TYPE_BINARY_INTEGER, self.assertEqual(oracledb.DB_TYPE_BINARY_INTEGER,
cx_Oracle.NATIVE_INT) oracledb.NATIVE_INT)
self.__testPickle(cx_Oracle.DB_TYPE_BINARY_INTEGER) self.__test_pickle(oracledb.DB_TYPE_BINARY_INTEGER)
def test_1504_DB_TYPE_BLOB(self): def test_1504_DB_TYPE_BLOB(self):
"1504 - test cx_Oracle.DB_TYPE_BLOB comparisons and pickling" "1504 - test oracledb.DB_TYPE_BLOB comparisons and pickling"
self.assertEqual(cx_Oracle.DB_TYPE_BLOB, cx_Oracle.BLOB) self.assertEqual(oracledb.DB_TYPE_BLOB, oracledb.BLOB)
self.__testPickle(cx_Oracle.DB_TYPE_BLOB) self.__test_pickle(oracledb.DB_TYPE_BLOB)
def test_1505_DB_TYPE_BOOLEAN(self): def test_1505_DB_TYPE_BOOLEAN(self):
"1505 - test cx_Oracle.DB_TYPE_BOOLEAN comparisons and pickling" "1505 - test oracledb.DB_TYPE_BOOLEAN comparisons and pickling"
self.assertEqual(cx_Oracle.DB_TYPE_BOOLEAN, cx_Oracle.BOOLEAN) self.assertEqual(oracledb.DB_TYPE_BOOLEAN, oracledb.BOOLEAN)
self.__testPickle(cx_Oracle.DB_TYPE_BOOLEAN) self.__test_pickle(oracledb.DB_TYPE_BOOLEAN)
def test_1506_DB_TYPE_CHAR(self): def test_1506_DB_TYPE_CHAR(self):
"1506 - test cx_Oracle.DB_TYPE_CHAR comparisons and pickling" "1506 - test oracledb.DB_TYPE_CHAR comparisons and pickling"
self.__testCompare(cx_Oracle.DB_TYPE_CHAR, cx_Oracle.STRING) self.__test_compare(oracledb.DB_TYPE_CHAR, oracledb.STRING)
self.assertEqual(cx_Oracle.DB_TYPE_CHAR, cx_Oracle.FIXED_CHAR) self.assertEqual(oracledb.DB_TYPE_CHAR, oracledb.FIXED_CHAR)
self.__testPickle(cx_Oracle.DB_TYPE_CHAR) self.__test_pickle(oracledb.DB_TYPE_CHAR)
def test_1507_DB_TYPE_CLOB(self): def test_1507_DB_TYPE_CLOB(self):
"1507 - test cx_Oracle.DB_TYPE_CLOB comparisons and pickling" "1507 - test oracledb.DB_TYPE_CLOB comparisons and pickling"
self.assertEqual(cx_Oracle.DB_TYPE_CLOB, cx_Oracle.CLOB) self.assertEqual(oracledb.DB_TYPE_CLOB, oracledb.CLOB)
self.__testPickle(cx_Oracle.DB_TYPE_CLOB) self.__test_pickle(oracledb.DB_TYPE_CLOB)
def test_1508_DB_TYPE_CURSOR(self): def test_1508_DB_TYPE_CURSOR(self):
"1508 - test cx_Oracle.DB_TYPE_CURSOR comparisons and pickling" "1508 - test oracledb.DB_TYPE_CURSOR comparisons and pickling"
self.assertEqual(cx_Oracle.DB_TYPE_CURSOR, cx_Oracle.CURSOR) self.assertEqual(oracledb.DB_TYPE_CURSOR, oracledb.CURSOR)
self.__testPickle(cx_Oracle.DB_TYPE_CURSOR) self.__test_pickle(oracledb.DB_TYPE_CURSOR)
def test_1509_DB_TYPE_DATE(self): def test_1509_DB_TYPE_DATE(self):
"1509 - test cx_Oracle.DB_TYPE_DATE comparisons and pickling" "1509 - test oracledb.DB_TYPE_DATE comparisons and pickling"
self.__testCompare(cx_Oracle.DB_TYPE_DATE, cx_Oracle.DATETIME) self.__test_compare(oracledb.DB_TYPE_DATE, oracledb.DATETIME)
self.__testPickle(cx_Oracle.DB_TYPE_DATE) self.__test_pickle(oracledb.DB_TYPE_DATE)
def test_1510_DB_TYPE_INTERVAL_DS(self): def test_1510_DB_TYPE_INTERVAL_DS(self):
"1510 - test cx_Oracle.DB_TYPE_INTERVAL_DS comparisons and pickling" "1510 - test oracledb.DB_TYPE_INTERVAL_DS comparisons and pickling"
self.assertEqual(cx_Oracle.DB_TYPE_INTERVAL_DS, cx_Oracle.INTERVAL) self.assertEqual(oracledb.DB_TYPE_INTERVAL_DS, oracledb.INTERVAL)
self.__testPickle(cx_Oracle.DB_TYPE_INTERVAL_DS) self.__test_pickle(oracledb.DB_TYPE_INTERVAL_DS)
def test_1511_DB_TYPE_LONG(self): def test_1511_DB_TYPE_LONG(self):
"1511 - test cx_Oracle.DB_TYPE_LONG comparisons and pickling" "1511 - test oracledb.DB_TYPE_LONG comparisons and pickling"
self.__testCompare(cx_Oracle.DB_TYPE_LONG, cx_Oracle.STRING) self.__test_compare(oracledb.DB_TYPE_LONG, oracledb.STRING)
self.assertEqual(cx_Oracle.DB_TYPE_LONG, cx_Oracle.LONG_STRING) self.assertEqual(oracledb.DB_TYPE_LONG, oracledb.LONG_STRING)
self.__testPickle(cx_Oracle.DB_TYPE_LONG) self.__test_pickle(oracledb.DB_TYPE_LONG)
def test_1512_DB_TYPE_LONG_RAW(self): def test_1512_DB_TYPE_LONG_RAW(self):
"1512 - test cx_Oracle.DB_TYPE_LONG_RAW comparisons and pickling" "1512 - test oracledb.DB_TYPE_LONG_RAW comparisons and pickling"
self.__testCompare(cx_Oracle.DB_TYPE_LONG_RAW, cx_Oracle.BINARY) self.__test_compare(oracledb.DB_TYPE_LONG_RAW, oracledb.BINARY)
self.assertEqual(cx_Oracle.DB_TYPE_LONG_RAW, cx_Oracle.LONG_BINARY) self.assertEqual(oracledb.DB_TYPE_LONG_RAW, oracledb.LONG_BINARY)
self.__testPickle(cx_Oracle.DB_TYPE_LONG_RAW) self.__test_pickle(oracledb.DB_TYPE_LONG_RAW)
def test_1513_DB_TYPE_NCHAR(self): def test_1513_DB_TYPE_NCHAR(self):
"1513 - test cx_Oracle.DB_TYPE_NCHAR comparisons and pickling" "1513 - test oracledb.DB_TYPE_NCHAR comparisons and pickling"
self.__testCompare(cx_Oracle.DB_TYPE_NCHAR, cx_Oracle.STRING) self.__test_compare(oracledb.DB_TYPE_NCHAR, oracledb.STRING)
self.assertEqual(cx_Oracle.DB_TYPE_NCHAR, cx_Oracle.FIXED_NCHAR) self.assertEqual(oracledb.DB_TYPE_NCHAR, oracledb.FIXED_NCHAR)
self.__testPickle(cx_Oracle.DB_TYPE_NCHAR) self.__test_pickle(oracledb.DB_TYPE_NCHAR)
def test_1514_DB_TYPE_NCLOB(self): def test_1514_DB_TYPE_NCLOB(self):
"1514 - test cx_Oracle.DB_TYPE_NCLOB comparisons and pickling" "1514 - test oracledb.DB_TYPE_NCLOB comparisons and pickling"
self.assertEqual(cx_Oracle.DB_TYPE_NCLOB, cx_Oracle.NCLOB) self.assertEqual(oracledb.DB_TYPE_NCLOB, oracledb.NCLOB)
self.__testPickle(cx_Oracle.DB_TYPE_NCLOB) self.__test_pickle(oracledb.DB_TYPE_NCLOB)
def test_1515_DB_TYPE_NUMBER(self): def test_1515_DB_TYPE_NUMBER(self):
"1515 - test cx_Oracle.DB_TYPE_NUMBER comparisons and pickling" "1515 - test oracledb.DB_TYPE_NUMBER comparisons and pickling"
self.__testCompare(cx_Oracle.DB_TYPE_NUMBER, cx_Oracle.NUMBER) self.__test_compare(oracledb.DB_TYPE_NUMBER, oracledb.NUMBER)
self.__testPickle(cx_Oracle.DB_TYPE_NUMBER) self.__test_pickle(oracledb.DB_TYPE_NUMBER)
def test_1516_DB_TYPE_NVARCHAR(self): def test_1516_DB_TYPE_NVARCHAR(self):
"1516 - test cx_Oracle.DB_TYPE_NVARCHAR comparisons and pickling" "1516 - test oracledb.DB_TYPE_NVARCHAR comparisons and pickling"
self.__testCompare(cx_Oracle.DB_TYPE_NVARCHAR, cx_Oracle.STRING) self.__test_compare(oracledb.DB_TYPE_NVARCHAR, oracledb.STRING)
self.assertEqual(cx_Oracle.DB_TYPE_NVARCHAR, cx_Oracle.NCHAR) self.assertEqual(oracledb.DB_TYPE_NVARCHAR, oracledb.NCHAR)
self.__testPickle(cx_Oracle.DB_TYPE_NVARCHAR) self.__test_pickle(oracledb.DB_TYPE_NVARCHAR)
def test_1517_DB_TYPE_OBJECT(self): def test_1517_DB_TYPE_OBJECT(self):
"1517 - test cx_Oracle.DB_TYPE_OBJECT comparisons and pickling" "1517 - test oracledb.DB_TYPE_OBJECT comparisons and pickling"
self.assertEqual(cx_Oracle.DB_TYPE_OBJECT, cx_Oracle.OBJECT) self.assertEqual(oracledb.DB_TYPE_OBJECT, oracledb.OBJECT)
self.__testPickle(cx_Oracle.DB_TYPE_OBJECT) self.__test_pickle(oracledb.DB_TYPE_OBJECT)
def test_1518_DB_TYPE_RAW(self): def test_1518_DB_TYPE_RAW(self):
"1518 - test cx_Oracle.DB_TYPE_RAW comparisons and pickling" "1518 - test oracledb.DB_TYPE_RAW comparisons and pickling"
self.__testCompare(cx_Oracle.DB_TYPE_RAW, cx_Oracle.BINARY) self.__test_compare(oracledb.DB_TYPE_RAW, oracledb.BINARY)
self.__testPickle(cx_Oracle.DB_TYPE_RAW) self.__test_pickle(oracledb.DB_TYPE_RAW)
def test_1519_DB_TYPE_ROWID(self): def test_1519_DB_TYPE_ROWID(self):
"1519 - test cx_Oracle.DB_TYPE_ROWID comparisons and pickling" "1519 - test oracledb.DB_TYPE_ROWID comparisons and pickling"
self.__testCompare(cx_Oracle.DB_TYPE_ROWID, cx_Oracle.ROWID) self.__test_compare(oracledb.DB_TYPE_ROWID, oracledb.ROWID)
self.__testPickle(cx_Oracle.DB_TYPE_ROWID) self.__test_pickle(oracledb.DB_TYPE_ROWID)
def test_1520_DB_TYPE_TIMESTAMP(self): def test_1520_DB_TYPE_TIMESTAMP(self):
"1520 - test cx_Oracle.DB_TYPE_TIMESTAMP comparisons and pickling" "1520 - test oracledb.DB_TYPE_TIMESTAMP comparisons and pickling"
self.__testCompare(cx_Oracle.DB_TYPE_TIMESTAMP, cx_Oracle.DATETIME) self.__test_compare(oracledb.DB_TYPE_TIMESTAMP, oracledb.DATETIME)
self.assertEqual(cx_Oracle.DB_TYPE_TIMESTAMP, cx_Oracle.TIMESTAMP) self.assertEqual(oracledb.DB_TYPE_TIMESTAMP, oracledb.TIMESTAMP)
self.__testPickle(cx_Oracle.DB_TYPE_TIMESTAMP) self.__test_pickle(oracledb.DB_TYPE_TIMESTAMP)
def test_1521_DB_TYPE_TIMESTAMP_LTZ(self): def test_1521_DB_TYPE_TIMESTAMP_LTZ(self):
"1521 - test cx_Oracle.DB_TYPE_TIMESTAMP_LTZ comparisons and pickling" "1521 - test oracledb.DB_TYPE_TIMESTAMP_LTZ comparisons and pickling"
self.__testCompare(cx_Oracle.DB_TYPE_TIMESTAMP_LTZ, cx_Oracle.DATETIME) self.__test_compare(oracledb.DB_TYPE_TIMESTAMP_LTZ, oracledb.DATETIME)
self.__testPickle(cx_Oracle.DB_TYPE_TIMESTAMP_LTZ) self.__test_pickle(oracledb.DB_TYPE_TIMESTAMP_LTZ)
def test_1522_DB_TYPE_TIMESTAMP_TZ(self): def test_1522_DB_TYPE_TIMESTAMP_TZ(self):
"1522 - test cx_Oracle.DB_TYPE_TIMESTAMP_TZ comparisons and pickling" "1522 - test oracledb.DB_TYPE_TIMESTAMP_TZ comparisons and pickling"
self.__testCompare(cx_Oracle.DB_TYPE_TIMESTAMP_TZ, cx_Oracle.DATETIME) self.__test_compare(oracledb.DB_TYPE_TIMESTAMP_TZ, oracledb.DATETIME)
self.__testPickle(cx_Oracle.DB_TYPE_TIMESTAMP_TZ) self.__test_pickle(oracledb.DB_TYPE_TIMESTAMP_TZ)
def test_1523_DB_TYPE_VARCHAR(self): def test_1523_DB_TYPE_VARCHAR(self):
"1523 - test cx_Oracle.DB_TYPE_VARCHAR comparisons and pickling" "1523 - test oracledb.DB_TYPE_VARCHAR comparisons and pickling"
self.__testCompare(cx_Oracle.DB_TYPE_VARCHAR, cx_Oracle.STRING) self.__test_compare(oracledb.DB_TYPE_VARCHAR, oracledb.STRING)
self.__testPickle(cx_Oracle.DB_TYPE_VARCHAR) self.__test_pickle(oracledb.DB_TYPE_VARCHAR)
def test_1524_NUMBER(self): def test_1524_NUMBER(self):
"1524 - test cx_Oracle.NUMBER pickling" "1524 - test oracledb.NUMBER pickling"
self.__testPickle(cx_Oracle.NUMBER) self.__test_pickle(oracledb.NUMBER)
def test_1525_STRING(self): def test_1525_STRING(self):
"1525 - test cx_Oracle.STRING pickling" "1525 - test oracledb.STRING pickling"
self.__testPickle(cx_Oracle.STRING) self.__test_pickle(oracledb.STRING)
def test_1526_DATETIME(self): def test_1526_DATETIME(self):
"1526 - test cx_Oracle.DATETIME pickling" "1526 - test oracledb.DATETIME pickling"
self.__testPickle(cx_Oracle.DATETIME) self.__test_pickle(oracledb.DATETIME)
def test_1527_BINARY(self): def test_1527_BINARY(self):
"1527 - test cx_Oracle.BINARY pickling" "1527 - test oracledb.BINARY pickling"
self.__testPickle(cx_Oracle.BINARY) self.__test_pickle(oracledb.BINARY)
def test_1528_ROWID(self): def test_1528_ROWID(self):
"1528 - test cx_Oracle.ROWID pickling" "1528 - test oracledb.ROWID pickling"
self.__testPickle(cx_Oracle.ROWID) self.__test_pickle(oracledb.ROWID)
if __name__ == "__main__": if __name__ == "__main__":
TestEnv.RunTestCases() base.run_test_cases()

View File

@ -6,110 +6,110 @@
1600 - Module for testing DML returning clauses 1600 - Module for testing DML returning clauses
""" """
import TestEnv import base
import cx_Oracle import cx_Oracle as oracledb
class TestCase(TestEnv.BaseTestCase): class TestCase(base.BaseTestCase):
def test_1600_Insert(self): def test_1600_insert(self):
"1600 - test insert (single row) with DML returning" "1600 - test insert (single row) with DML returning"
self.cursor.execute("truncate table TestTempTable") self.cursor.execute("truncate table TestTempTable")
intVal = 5 int_val = 5
strVal = "A test string" str_val = "A test string"
intVar = self.cursor.var(cx_Oracle.NUMBER) int_var = self.cursor.var(oracledb.NUMBER)
strVar = self.cursor.var(str) str_var = self.cursor.var(str)
self.cursor.execute(""" self.cursor.execute("""
insert into TestTempTable (IntCol, StringCol) insert into TestTempTable (IntCol, StringCol)
values (:intVal, :strVal) values (:int_val, :str_val)
returning IntCol, StringCol into :intVar, :strVar""", returning IntCol, StringCol into :int_var, :str_var""",
intVal = intVal, int_val=int_val,
strVal = strVal, str_val=str_val,
intVar = intVar, int_var=int_var,
strVar = strVar) str_var=str_var)
self.assertEqual(intVar.values, [[intVal]]) self.assertEqual(int_var.values, [[int_val]])
self.assertEqual(strVar.values, [[strVal]]) self.assertEqual(str_var.values, [[str_val]])
def test_1601_InsertMany(self): def test_1601_insert_many(self):
"1601 - test insert (multiple rows) with DML returning" "1601 - test insert (multiple rows) with DML returning"
self.cursor.execute("truncate table TestTempTable") self.cursor.execute("truncate table TestTempTable")
intValues = [5, 8, 17, 24, 6] int_values = [5, 8, 17, 24, 6]
strValues = ["Test 5", "Test 8", "Test 17", "Test 24", "Test 6"] str_values = ["Test 5", "Test 8", "Test 17", "Test 24", "Test 6"]
intVar = self.cursor.var(cx_Oracle.NUMBER, arraysize = len(intValues)) int_var = self.cursor.var(oracledb.NUMBER, arraysize=len(int_values))
strVar = self.cursor.var(str, arraysize = len(intValues)) str_var = self.cursor.var(str, arraysize=len(int_values))
self.cursor.setinputsizes(None, None, intVar, strVar) self.cursor.setinputsizes(None, None, int_var, str_var)
data = list(zip(intValues, strValues)) data = list(zip(int_values, str_values))
self.cursor.executemany(""" self.cursor.executemany("""
insert into TestTempTable (IntCol, StringCol) insert into TestTempTable (IntCol, StringCol)
values (:intVal, :strVal) values (:int_val, :str_val)
returning IntCol, StringCol into :intVar, :strVar""", data) returning IntCol, StringCol into :int_var, :str_var""", data)
self.assertEqual(intVar.values, [[v] for v in intValues]) self.assertEqual(int_var.values, [[v] for v in int_values])
self.assertEqual(strVar.values, [[v] for v in strValues]) self.assertEqual(str_var.values, [[v] for v in str_values])
def test_1602_InsertWithSmallSize(self): def test_1602_insert_with_small_size(self):
"1602 - test insert with DML returning into too small a variable" "1602 - test insert with DML returning into too small a variable"
self.cursor.execute("truncate table TestTempTable") self.cursor.execute("truncate table TestTempTable")
intVal = 6 int_val = 6
strVal = "A different test string" str_val = "A different test string"
intVar = self.cursor.var(cx_Oracle.NUMBER) int_var = self.cursor.var(oracledb.NUMBER)
strVar = self.cursor.var(str, 2) str_var = self.cursor.var(str, 2)
parameters = dict(intVal = intVal, strVal = strVal, intVar = intVar, parameters = dict(int_val=int_val, str_val=str_val, int_var=int_var,
strVar = strVar) str_var=str_var)
self.assertRaises(cx_Oracle.DatabaseError, self.cursor.execute, """ self.assertRaises(oracledb.DatabaseError, self.cursor.execute, """
insert into TestTempTable (IntCol, StringCol) insert into TestTempTable (IntCol, StringCol)
values (:intVal, :strVal) values (:int_val, :str_val)
returning IntCol, StringCol into :intVar, :strVar""", returning IntCol, StringCol into :int_var, :str_var""",
parameters) parameters)
def test_1603_UpdateSingleRow(self): def test_1603_update_single_row(self):
"1603 - test update single row with DML returning" "1603 - test update single row with DML returning"
intVal = 7 int_val = 7
strVal = "The updated value of the string" str_val = "The updated value of the string"
self.cursor.execute("truncate table TestTempTable") self.cursor.execute("truncate table TestTempTable")
self.cursor.execute(""" self.cursor.execute("""
insert into TestTempTable (IntCol, StringCol) insert into TestTempTable (IntCol, StringCol)
values (:1, :2)""", values (:1, :2)""",
(intVal, "The initial value of the string")) (int_val, "The initial value of the string"))
intVar = self.cursor.var(cx_Oracle.NUMBER) int_var = self.cursor.var(oracledb.NUMBER)
strVar = self.cursor.var(str) str_var = self.cursor.var(str)
self.cursor.execute(""" self.cursor.execute("""
update TestTempTable set update TestTempTable set
StringCol = :strVal StringCol = :str_val
where IntCol = :intVal where IntCol = :int_val
returning IntCol, StringCol into :intVar, :strVar""", returning IntCol, StringCol into :int_var, :str_var""",
intVal = intVal, int_val=int_val,
strVal = strVal, str_val=str_val,
intVar = intVar, int_var=int_var,
strVar = strVar) str_var=str_var)
self.assertEqual(intVar.values, [[intVal]]) self.assertEqual(int_var.values, [[int_val]])
self.assertEqual(strVar.values, [[strVal]]) self.assertEqual(str_var.values, [[str_val]])
def test_1604_UpdateNoRows(self): def test_1604_update_no_rows(self):
"1604 - test update no rows with DML returning" "1604 - test update no rows with DML returning"
intVal = 8 int_val = 8
strVal = "The updated value of the string" str_val = "The updated value of the string"
self.cursor.execute("truncate table TestTempTable") self.cursor.execute("truncate table TestTempTable")
self.cursor.execute(""" self.cursor.execute("""
insert into TestTempTable (IntCol, StringCol) insert into TestTempTable (IntCol, StringCol)
values (:1, :2)""", values (:1, :2)""",
(intVal, "The initial value of the string")) (int_val, "The initial value of the string"))
intVar = self.cursor.var(cx_Oracle.NUMBER) int_var = self.cursor.var(oracledb.NUMBER)
strVar = self.cursor.var(str) str_var = self.cursor.var(str)
self.cursor.execute(""" self.cursor.execute("""
update TestTempTable set update TestTempTable set
StringCol = :strVal StringCol = :str_val
where IntCol = :intVal where IntCol = :int_val
returning IntCol, StringCol into :intVar, :strVar""", returning IntCol, StringCol into :int_var, :str_var""",
intVal = intVal + 1, int_val=int_val + 1,
strVal = strVal, str_val=str_val,
intVar = intVar, int_var=int_var,
strVar = strVar) str_var=str_var)
self.assertEqual(intVar.values, [[]]) self.assertEqual(int_var.values, [[]])
self.assertEqual(strVar.values, [[]]) self.assertEqual(str_var.values, [[]])
self.assertEqual(intVar.getvalue(), []) self.assertEqual(int_var.getvalue(), [])
self.assertEqual(strVar.getvalue(), []) self.assertEqual(str_var.getvalue(), [])
def test_1605_UpdateMultipleRows(self): def test_1605_update_multiple_rows(self):
"1605 - test update multiple rows with DML returning" "1605 - test update multiple rows with DML returning"
self.cursor.execute("truncate table TestTempTable") self.cursor.execute("truncate table TestTempTable")
for i in (8, 9, 10): for i in (8, 9, 10):
@ -117,24 +117,25 @@ class TestCase(TestEnv.BaseTestCase):
insert into TestTempTable (IntCol, StringCol) insert into TestTempTable (IntCol, StringCol)
values (:1, :2)""", values (:1, :2)""",
(i, "The initial value of string %d" % i)) (i, "The initial value of string %d" % i))
intVar = self.cursor.var(cx_Oracle.NUMBER) int_var = self.cursor.var(oracledb.NUMBER)
strVar = self.cursor.var(str) str_var = self.cursor.var(str)
self.cursor.execute(""" self.cursor.execute("""
update TestTempTable set update TestTempTable set
IntCol = IntCol + 15, IntCol = IntCol + 15,
StringCol = 'The final value of string ' || to_char(IntCol) StringCol = 'The final value of string ' || to_char(IntCol)
returning IntCol, StringCol into :intVar, :strVar""", returning IntCol, StringCol into :int_var, :str_var""",
intVar = intVar, int_var=int_var,
strVar = strVar) str_var=str_var)
self.assertEqual(self.cursor.rowcount, 3) self.assertEqual(self.cursor.rowcount, 3)
self.assertEqual(intVar.values, [[23, 24, 25]]) self.assertEqual(int_var.values, [[23, 24, 25]])
self.assertEqual(strVar.values, [[ expected_values = [[
"The final value of string 8", "The final value of string 8",
"The final value of string 9", "The final value of string 9",
"The final value of string 10" "The final value of string 10"
]]) ]]
self.assertEqual(str_var.values, expected_values)
def test_1606_UpdateMultipleRowsExecuteMany(self): def test_1606_update_multiple_rows_executemany(self):
"1606 - test update multiple rows with DML returning (executeMany)" "1606 - test update multiple rows with DML returning (executeMany)"
data = [(i, "The initial value of string %d" % i) \ data = [(i, "The initial value of string %d" % i) \
for i in range(1, 11)] for i in range(1, 11)]
@ -142,55 +143,63 @@ class TestCase(TestEnv.BaseTestCase):
self.cursor.executemany(""" self.cursor.executemany("""
insert into TestTempTable (IntCol, StringCol) insert into TestTempTable (IntCol, StringCol)
values (:1, :2)""", data) values (:1, :2)""", data)
intVar = self.cursor.var(cx_Oracle.NUMBER, arraysize = 3) int_var = self.cursor.var(oracledb.NUMBER, arraysize=3)
strVar = self.cursor.var(str, arraysize = 3) str_var = self.cursor.var(str, arraysize=3)
self.cursor.setinputsizes(None, intVar, strVar) self.cursor.setinputsizes(None, int_var, str_var)
self.cursor.executemany(""" self.cursor.executemany("""
update TestTempTable set update TestTempTable set
IntCol = IntCol + 25, IntCol = IntCol + 25,
StringCol = 'Updated value of string ' || to_char(IntCol) StringCol = 'Updated value of string ' || to_char(IntCol)
where IntCol < :inVal where IntCol < :inVal
returning IntCol, StringCol into :intVar, :strVar""", returning IntCol, StringCol into :int_var, :str_var""",
[[3], [8], [11]]) [[3], [8], [11]])
self.assertEqual(intVar.values, [ expected_values = [
[26, 27], [26, 27],
[28, 29, 30, 31, 32], [28, 29, 30, 31, 32],
[33, 34, 35] [33, 34, 35]
]) ]
self.assertEqual(strVar.values, [ self.assertEqual(int_var.values, expected_values)
[ "Updated value of string 1", expected_values = [
"Updated value of string 2" ], [
[ "Updated value of string 3", "Updated value of string 1",
"Updated value of string 2"
],
[
"Updated value of string 3",
"Updated value of string 4", "Updated value of string 4",
"Updated value of string 5", "Updated value of string 5",
"Updated value of string 6", "Updated value of string 6",
"Updated value of string 7" ], "Updated value of string 7"
[ "Updated value of string 8", ],
[
"Updated value of string 8",
"Updated value of string 9", "Updated value of string 9",
"Updated value of string 10" ] "Updated value of string 10"
]) ]
]
self.assertEqual(str_var.values, expected_values)
def test_1607_InsertAndReturnObject(self): def test_1607_insert_and_return_object(self):
"1607 - test inserting an object with DML returning" "1607 - test inserting an object with DML returning"
typeObj = self.connection.gettype("UDT_OBJECT") type_obj = self.connection.gettype("UDT_OBJECT")
stringValue = "The string that will be verified" string_value = "The string that will be verified"
obj = typeObj.newobject() obj = type_obj.newobject()
obj.STRINGVALUE = stringValue obj.STRINGVALUE = string_value
outVar = self.cursor.var(cx_Oracle.DB_TYPE_OBJECT, out_var = self.cursor.var(oracledb.DB_TYPE_OBJECT,
typename="UDT_OBJECT") typename="UDT_OBJECT")
self.cursor.execute(""" self.cursor.execute("""
insert into TestObjects (IntCol, ObjectCol) insert into TestObjects (IntCol, ObjectCol)
values (4, :obj) values (4, :obj)
returning ObjectCol into :outObj""", returning ObjectCol into :outObj""",
obj = obj, outObj = outVar) obj=obj, outObj=out_var)
result, = outVar.getvalue() result, = out_var.getvalue()
self.assertEqual(result.STRINGVALUE, stringValue) self.assertEqual(result.STRINGVALUE, string_value)
self.connection.rollback() self.connection.rollback()
def test_1608_InsertAndReturnRowid(self): def test_1608_insert_and_return_rowid(self):
"1608 - test inserting a row and returning a rowid" "1608 - test inserting a row and returning a rowid"
self.cursor.execute("truncate table TestTempTable") self.cursor.execute("truncate table TestTempTable")
var = self.cursor.var(cx_Oracle.ROWID) var = self.cursor.var(oracledb.ROWID)
self.cursor.execute(""" self.cursor.execute("""
insert into TestTempTable (IntCol, StringCol) insert into TestTempTable (IntCol, StringCol)
values (278, 'String 278') values (278, 'String 278')
@ -203,12 +212,12 @@ class TestCase(TestEnv.BaseTestCase):
(rowid,)) (rowid,))
self.assertEqual(self.cursor.fetchall(), [(278, 'String 278')]) self.assertEqual(self.cursor.fetchall(), [(278, 'String 278')])
def test_1609_InsertWithRefCursor(self): def test_1609_insert_with_ref_cursor(self):
"1609 - test inserting with a REF cursor and returning a rowid" "1609 - test inserting with a REF cursor and returning a rowid"
self.cursor.execute("truncate table TestTempTable") self.cursor.execute("truncate table TestTempTable")
var = self.cursor.var(cx_Oracle.ROWID) var = self.cursor.var(oracledb.ROWID)
inCursor = self.connection.cursor() in_cursor = self.connection.cursor()
inCursor.execute(""" in_cursor.execute("""
select StringCol select StringCol
from TestStrings from TestStrings
where IntCol >= 5 where IntCol >= 5
@ -216,7 +225,7 @@ class TestCase(TestEnv.BaseTestCase):
self.cursor.execute(""" self.cursor.execute("""
insert into TestTempTable (IntCol, StringCol) insert into TestTempTable (IntCol, StringCol)
values (187, pkg_TestRefCursors.TestInCursor(:1)) values (187, pkg_TestRefCursors.TestInCursor(:1))
returning rowid into :2""", (inCursor, var)) returning rowid into :2""", (in_cursor, var))
rowid, = var.getvalue() rowid, = var.getvalue()
self.cursor.execute(""" self.cursor.execute("""
select IntCol, StringCol select IntCol, StringCol
@ -226,7 +235,7 @@ class TestCase(TestEnv.BaseTestCase):
self.assertEqual(self.cursor.fetchall(), self.assertEqual(self.cursor.fetchall(),
[(187, 'String 7 (Modified)')]) [(187, 'String 7 (Modified)')])
def test_1610_DeleteReturningDecreasingRowsReturned(self): def test_1610_delete_returning_decreasing_rows_returned(self):
"1610 - test delete returning decreasing number of rows" "1610 - test delete returning decreasing number of rows"
data = [(i, "Test String %d" % i) for i in range(1, 11)] data = [(i, "Test String %d" % i) for i in range(1, 11)]
self.cursor.execute("truncate table TestTempTable") self.cursor.execute("truncate table TestTempTable")
@ -234,31 +243,31 @@ class TestCase(TestEnv.BaseTestCase):
insert into TestTempTable (IntCol, StringCol) insert into TestTempTable (IntCol, StringCol)
values (:1, :2)""", data) values (:1, :2)""", data)
results = [] results = []
intVar = self.cursor.var(int) int_var = self.cursor.var(int)
self.cursor.setinputsizes(None, intVar) self.cursor.setinputsizes(None, int_var)
for intVal in (5, 8, 10): for int_val in (5, 8, 10):
self.cursor.execute(""" self.cursor.execute("""
delete from TestTempTable delete from TestTempTable
where IntCol < :1 where IntCol < :1
returning IntCol into :2""", [intVal]) returning IntCol into :2""", [int_val])
results.append(intVar.getvalue()) results.append(int_var.getvalue())
self.assertEqual(results, [[1, 2, 3, 4], [5, 6, 7], [8, 9]]) self.assertEqual(results, [[1, 2, 3, 4], [5, 6, 7], [8, 9]])
def test_1611_DeleteReturningNoRowsAfterManyRows(self): def test_1611_delete_returning_no_rows_after_many_rows(self):
"1611 - test delete returning no rows after returning many rows" "1611 - test delete returning no rows after returning many rows"
data = [(i, "Test String %d" % i) for i in range(1, 11)] data = [(i, "Test String %d" % i) for i in range(1, 11)]
self.cursor.execute("truncate table TestTempTable") self.cursor.execute("truncate table TestTempTable")
self.cursor.executemany(""" self.cursor.executemany("""
insert into TestTempTable (IntCol, StringCol) insert into TestTempTable (IntCol, StringCol)
values (:1, :2)""", data) values (:1, :2)""", data)
intVar = self.cursor.var(int) int_var = self.cursor.var(int)
self.cursor.execute(""" self.cursor.execute("""
delete from TestTempTable delete from TestTempTable
where IntCol < :1 where IntCol < :1
returning IntCol into :2""", [5, intVar]) returning IntCol into :2""", [5, int_var])
self.assertEqual(intVar.getvalue(), [1, 2, 3, 4]) self.assertEqual(int_var.getvalue(), [1, 2, 3, 4])
self.cursor.execute(None, [4, intVar]) self.cursor.execute(None, [4, int_var])
self.assertEqual(intVar.getvalue(), []) self.assertEqual(int_var.getvalue(), [])
if __name__ == "__main__": if __name__ == "__main__":
TestEnv.RunTestCases() base.run_test_cases()

View File

@ -11,41 +11,40 @@
1700 - Module for testing error objects 1700 - Module for testing error objects
""" """
import TestEnv import base
import cx_Oracle import cx_Oracle as oracledb
import pickle import pickle
class TestCase(TestEnv.BaseTestCase): class TestCase(base.BaseTestCase):
def test_1700_ParseError(self): def test_1700_parse_error(self):
"1700 - test parse error returns offset correctly" "1700 - test parse error returns offset correctly"
with self.assertRaises(cx_Oracle.Error) as cm: with self.assertRaises(oracledb.Error) as cm:
self.cursor.execute("begin t_Missing := 5; end;") self.cursor.execute("begin t_Missing := 5; end;")
errorObj, = cm.exception.args error_obj, = cm.exception.args
self.assertEqual(errorObj.offset, 6) self.assertEqual(error_obj.offset, 6)
def test_1701_PickleError(self): def test_1701_pickle_error(self):
"1701 - test picking/unpickling an error object" "1701 - test picking/unpickling an error object"
with self.assertRaises(cx_Oracle.Error) as cm: with self.assertRaises(oracledb.Error) as cm:
self.cursor.execute(""" self.cursor.execute("""
begin begin
raise_application_error(-20101, 'Test!'); raise_application_error(-20101, 'Test!');
end;""") end;""")
errorObj, = cm.exception.args error_obj, = cm.exception.args
self.assertEqual(type(errorObj), cx_Oracle._Error) self.assertEqual(type(error_obj), oracledb._Error)
self.assertTrue("Test!" in errorObj.message) self.assertTrue("Test!" in error_obj.message)
self.assertEqual(errorObj.code, 20101) self.assertEqual(error_obj.code, 20101)
self.assertEqual(errorObj.offset, 0) self.assertEqual(error_obj.offset, 0)
self.assertTrue(isinstance(errorObj.isrecoverable, bool)) self.assertTrue(isinstance(error_obj.isrecoverable, bool))
pickledData = pickle.dumps(errorObj) new_error_obj = pickle.loads(pickle.dumps(error_obj))
newErrorObj = pickle.loads(pickledData) self.assertEqual(type(new_error_obj), oracledb._Error)
self.assertEqual(type(newErrorObj), cx_Oracle._Error) self.assertTrue(new_error_obj.message == error_obj.message)
self.assertTrue(newErrorObj.message == errorObj.message) self.assertTrue(new_error_obj.code == error_obj.code)
self.assertTrue(newErrorObj.code == errorObj.code) self.assertTrue(new_error_obj.offset == error_obj.offset)
self.assertTrue(newErrorObj.offset == errorObj.offset) self.assertTrue(new_error_obj.context == error_obj.context)
self.assertTrue(newErrorObj.context == errorObj.context) self.assertTrue(new_error_obj.isrecoverable == error_obj.isrecoverable)
self.assertTrue(newErrorObj.isrecoverable == errorObj.isrecoverable)
if __name__ == "__main__": if __name__ == "__main__":
TestEnv.RunTestCases() base.run_test_cases()

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# #
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved. # Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
# #
@ -11,141 +11,145 @@
1800 - Module for testing interval variables 1800 - Module for testing interval variables
""" """
import TestEnv import base
import cx_Oracle import cx_Oracle as oracledb
import datetime import datetime
class TestCase(TestEnv.BaseTestCase): class TestCase(base.BaseTestCase):
def setUp(self): def setUp(self):
TestEnv.BaseTestCase.setUp(self) super().setUp()
self.rawData = [] self.raw_data = []
self.dataByKey = {} self.data_by_key = {}
for i in range(1, 11): for i in range(1, 11):
delta = datetime.timedelta(days=i, hours=i, minutes=i * 2, delta = datetime.timedelta(days=i, hours=i, minutes=i * 2,
seconds=i * 3) seconds=i * 3)
if i % 2 == 0: if i % 2 == 0:
nullableDelta = None nullable_delta = None
else: else:
nullableDelta = datetime.timedelta(days = i + 5, hours = i + 2, nullable_delta = datetime.timedelta(days=i + 5, hours=i + 2,
minutes = i * 2 + 5, seconds = i * 3 + 5) minutes=i * 2 + 5,
tuple = (i, delta, nullableDelta) seconds=i * 3 + 5)
self.rawData.append(tuple) data_tuple = (i, delta, nullable_delta)
self.dataByKey[i] = tuple self.raw_data.append(data_tuple)
self.data_by_key[i] = data_tuple
def test_1800_BindInterval(self): def test_1800_bind_interval(self):
"1800 - test binding in an interval" "1800 - test binding in an interval"
self.cursor.setinputsizes(value = cx_Oracle.DB_TYPE_INTERVAL_DS) self.cursor.setinputsizes(value=oracledb.DB_TYPE_INTERVAL_DS)
value = datetime.timedelta(days=5, hours=5, minutes=10, seconds=15)
self.cursor.execute(""" self.cursor.execute("""
select * from TestIntervals select * from TestIntervals
where IntervalCol = :value""", where IntervalCol = :value""",
value = datetime.timedelta(days = 5, hours = 5, minutes = 10, value=value)
seconds = 15)) self.assertEqual(self.cursor.fetchall(), [self.data_by_key[5]])
self.assertEqual(self.cursor.fetchall(), [self.dataByKey[5]])
def test_1801_BindNull(self): def test_1801_bind_null(self):
"1801 - test binding in a null" "1801 - test binding in a null"
self.cursor.setinputsizes(value = cx_Oracle.DB_TYPE_INTERVAL_DS) self.cursor.setinputsizes(value=oracledb.DB_TYPE_INTERVAL_DS)
self.cursor.execute(""" self.cursor.execute("""
select * from TestIntervals select * from TestIntervals
where IntervalCol = :value""", where IntervalCol = :value""",
value=None) value=None)
self.assertEqual(self.cursor.fetchall(), []) self.assertEqual(self.cursor.fetchall(), [])
def test_1802_BindOutSetInputSizes(self): def test_1802_bind_out_set_input_sizes(self):
"1802 - test binding out with set input sizes defined" "1802 - test binding out with set input sizes defined"
vars = self.cursor.setinputsizes(value = cx_Oracle.DB_TYPE_INTERVAL_DS) bind_vars = \
self.cursor.setinputsizes(value=oracledb.DB_TYPE_INTERVAL_DS)
self.cursor.execute(""" self.cursor.execute("""
begin begin
:value := to_dsinterval('8 09:24:18.123789'); :value := to_dsinterval('8 09:24:18.123789');
end;""") end;""")
self.assertEqual(vars["value"].getvalue(), expected_value = datetime.timedelta(days=8, hours=9, minutes=24,
datetime.timedelta(days = 8, hours = 9, minutes = 24, seconds=18, microseconds=123789)
seconds = 18, microseconds = 123789)) self.assertEqual(bind_vars["value"].getvalue(), expected_value)
def test_1803_BindInOutSetInputSizes(self): def test_1803_bind_in_out_set_input_sizes(self):
"1803 - test binding in/out with set input sizes defined" "1803 - test binding in/out with set input sizes defined"
vars = self.cursor.setinputsizes(value = cx_Oracle.DB_TYPE_INTERVAL_DS) bind_vars = \
self.cursor.setinputsizes(value=oracledb.DB_TYPE_INTERVAL_DS)
self.cursor.execute(""" self.cursor.execute("""
begin begin
:value := :value + to_dsinterval('5 08:30:00'); :value := :value + to_dsinterval('5 08:30:00');
end;""", end;""",
value=datetime.timedelta(days=5, hours=2, minutes=15)) value=datetime.timedelta(days=5, hours=2, minutes=15))
self.assertEqual(vars["value"].getvalue(), expected_value = datetime.timedelta(days=10, hours=10, minutes=45)
datetime.timedelta(days = 10, hours = 10, minutes = 45)) self.assertEqual(bind_vars["value"].getvalue(), expected_value)
def test_1804_BindInOutFractionalSecond(self): def test_1804_bind_in_out_fractional_second(self):
"1804 - test binding in/out with set input sizes defined" "1804 - test binding in/out with set input sizes defined"
vars = self.cursor.setinputsizes(value = cx_Oracle.DB_TYPE_INTERVAL_DS) bind_vars = \
self.cursor.setinputsizes(value=oracledb.DB_TYPE_INTERVAL_DS)
self.cursor.execute(""" self.cursor.execute("""
begin begin
:value := :value + to_dsinterval('5 08:30:00'); :value := :value + to_dsinterval('5 08:30:00');
end;""", end;""",
value=datetime.timedelta(days=5, seconds=12.123789)) value=datetime.timedelta(days=5, seconds=12.123789))
self.assertEqual(vars["value"].getvalue(), expected_value = datetime.timedelta(days=10, hours=8, minutes=30,
datetime.timedelta(days = 10, hours = 8, minutes = 30, seconds=12, microseconds=123789)
seconds=12, microseconds=123789)) self.assertEqual(bind_vars["value"].getvalue(), expected_value)
def test_1805_BindOutVar(self): def test_1805_bind_out_var(self):
"1805 - test binding out with cursor.var() method" "1805 - test binding out with cursor.var() method"
var = self.cursor.var(cx_Oracle.DB_TYPE_INTERVAL_DS) var = self.cursor.var(oracledb.DB_TYPE_INTERVAL_DS)
self.cursor.execute(""" self.cursor.execute("""
begin begin
:value := to_dsinterval('15 18:35:45.586'); :value := to_dsinterval('15 18:35:45.586');
end;""", end;""",
value=var) value=var)
self.assertEqual(var.getvalue(), expected_value = datetime.timedelta(days=15, hours=18, minutes=35,
datetime.timedelta(days = 15, hours = 18, minutes = 35, seconds=45, milliseconds=586)
seconds = 45, milliseconds = 586)) self.assertEqual(var.getvalue(), expected_value)
def test_1806_BindInOutVarDirectSet(self): def test_1806_bind_in_out_var_direct_set(self):
"1806 - test binding in/out with cursor.var() method" "1806 - test binding in/out with cursor.var() method"
var = self.cursor.var(cx_Oracle.DB_TYPE_INTERVAL_DS) var = self.cursor.var(oracledb.DB_TYPE_INTERVAL_DS)
var.setvalue(0, datetime.timedelta(days=1, minutes=50)) var.setvalue(0, datetime.timedelta(days=1, minutes=50))
self.cursor.execute(""" self.cursor.execute("""
begin begin
:value := :value + to_dsinterval('8 05:15:00'); :value := :value + to_dsinterval('8 05:15:00');
end;""", end;""",
value=var) value=var)
self.assertEqual(var.getvalue(), expected_value = datetime.timedelta(days=9, hours=6, minutes=5)
datetime.timedelta(days = 9, hours = 6, minutes = 5)) self.assertEqual(var.getvalue(), expected_value)
def test_1807_CursorDescription(self): def test_1807_cursor_description(self):
"1807 - test cursor description is accurate" "1807 - test cursor description is accurate"
self.cursor.execute("select * from TestIntervals") self.cursor.execute("select * from TestIntervals")
self.assertEqual(self.cursor.description, expected_value = [
[ ('INTCOL', cx_Oracle.DB_TYPE_NUMBER, 10, None, 9, 0, 0), ('INTCOL', oracledb.DB_TYPE_NUMBER, 10, None, 9, 0, 0),
('INTERVALCOL', cx_Oracle.DB_TYPE_INTERVAL_DS, None, None, 2, ('INTERVALCOL', oracledb.DB_TYPE_INTERVAL_DS, None, None, 2, 6, 0),
6, 0), ('NULLABLECOL', oracledb.DB_TYPE_INTERVAL_DS, None, None, 2, 6, 1)
('NULLABLECOL', cx_Oracle.DB_TYPE_INTERVAL_DS, None, None, 2, ]
6, 1) ]) self.assertEqual(self.cursor.description, expected_value)
def test_1808_FetchAll(self): def test_1808_fetchall(self):
"1808 - test that fetching all of the data returns the correct results" "1808 - test that fetching all of the data returns the correct results"
self.cursor.execute("select * From TestIntervals order by IntCol") self.cursor.execute("select * From TestIntervals order by IntCol")
self.assertEqual(self.cursor.fetchall(), self.rawData) self.assertEqual(self.cursor.fetchall(), self.raw_data)
self.assertEqual(self.cursor.fetchall(), []) self.assertEqual(self.cursor.fetchall(), [])
def test_1809_FetchMany(self): def test_1809_fetchmany(self):
"1809 - test that fetching data in chunks returns the correct results" "1809 - test that fetching data in chunks returns the correct results"
self.cursor.execute("select * From TestIntervals order by IntCol") self.cursor.execute("select * From TestIntervals order by IntCol")
self.assertEqual(self.cursor.fetchmany(3), self.rawData[0:3]) self.assertEqual(self.cursor.fetchmany(3), self.raw_data[0:3])
self.assertEqual(self.cursor.fetchmany(2), self.rawData[3:5]) self.assertEqual(self.cursor.fetchmany(2), self.raw_data[3:5])
self.assertEqual(self.cursor.fetchmany(4), self.rawData[5:9]) self.assertEqual(self.cursor.fetchmany(4), self.raw_data[5:9])
self.assertEqual(self.cursor.fetchmany(3), self.rawData[9:]) self.assertEqual(self.cursor.fetchmany(3), self.raw_data[9:])
self.assertEqual(self.cursor.fetchmany(3), []) self.assertEqual(self.cursor.fetchmany(3), [])
def test_1810_FetchOne(self): def test_1810_fetchone(self):
"1810 - test that fetching a single row returns the correct results" "1810 - test that fetching a single row returns the correct results"
self.cursor.execute(""" self.cursor.execute("""
select * select *
from TestIntervals from TestIntervals
where IntCol in (3, 4) where IntCol in (3, 4)
order by IntCol""") order by IntCol""")
self.assertEqual(self.cursor.fetchone(), self.dataByKey[3]) self.assertEqual(self.cursor.fetchone(), self.data_by_key[3])
self.assertEqual(self.cursor.fetchone(), self.dataByKey[4]) self.assertEqual(self.cursor.fetchone(), self.data_by_key[4])
self.assertEqual(self.cursor.fetchone(), None) self.assertEqual(self.cursor.fetchone(), None)
if __name__ == "__main__": if __name__ == "__main__":
TestEnv.RunTestCases() base.run_test_cases()

View File

@ -11,14 +11,13 @@
1900 - Module for testing LOB (CLOB and BLOB) variables 1900 - Module for testing LOB (CLOB and BLOB) variables
""" """
import TestEnv import base
import cx_Oracle import cx_Oracle as oracledb
import sys
class TestCase(TestEnv.BaseTestCase): class TestCase(base.BaseTestCase):
def __GetTempLobs(self, sid): def __get_temp_lobs(self, sid):
cursor = self.connection.cursor() cursor = self.connection.cursor()
cursor.execute(""" cursor.execute("""
select abstract_lobs select abstract_lobs
@ -29,60 +28,60 @@ class TestCase(TestEnv.BaseTestCase):
return 0 return 0
return int(row[0]) return int(row[0])
def __PerformTest(self, lobType, inputType): def __perform_test(self, lob_type, input_type):
longString = "" long_string = ""
directType = getattr(cx_Oracle, lobType) db_type = getattr(oracledb, "DB_TYPE_" + lob_type)
self.cursor.execute("truncate table Test%ss" % lobType) self.cursor.execute("truncate table Test%ss" % lob_type)
for i in range(0, 11): for i in range(0, 11):
if i > 0: if i > 0:
char = chr(ord('A') + i - 1) char = chr(ord('A') + i - 1)
longString += char * 25000 long_string += char * 25000
elif inputType != directType: elif input_type is not db_type:
continue continue
self.cursor.setinputsizes(longString = inputType) self.cursor.setinputsizes(long_string = input_type)
if lobType == "BLOB" and sys.version_info[0] >= 3: if lob_type == "BLOB":
bindValue = longString.encode("ascii") bind_value = long_string.encode()
else: else:
bindValue = longString bind_value = long_string
self.cursor.execute(""" self.cursor.execute("""
insert into Test%ss ( insert into Test%ss (
IntCol, IntCol,
%sCol %sCol
) values ( ) values (
:integerValue, :integer_value,
:longString :long_string
)""" % (lobType, lobType), )""" % (lob_type, lob_type),
integerValue = i, integer_value=i,
longString = bindValue) long_string=bind_value)
self.connection.commit() self.connection.commit()
self.cursor.execute(""" self.cursor.execute("""
select * select *
from Test%ss from Test%ss
order by IntCol""" % lobType) order by IntCol""" % lob_type)
self.__ValidateQuery(self.cursor, lobType) self.__validate_query(self.cursor, lob_type)
def __TestLobOperations(self, lobType): def __test_lob_operations(self, lob_type):
self.cursor.execute("truncate table Test%ss" % lobType) self.cursor.execute("truncate table Test%ss" % lob_type)
self.cursor.setinputsizes(longString = getattr(cx_Oracle, lobType)) self.cursor.setinputsizes(long_string=getattr(oracledb, lob_type))
longString = "X" * 75000 long_string = "X" * 75000
writeValue = "TEST" write_value = "TEST"
if lobType == "BLOB" and sys.version_info[0] >= 3: if lob_type == "BLOB":
longString = longString.encode("ascii") long_string = long_string.encode("ascii")
writeValue = writeValue.encode("ascii") write_value = write_value.encode("ascii")
self.cursor.execute(""" self.cursor.execute("""
insert into Test%ss ( insert into Test%ss (
IntCol, IntCol,
%sCol %sCol
) values ( ) values (
:integerValue, :integer_value,
:longString :long_string
)""" % (lobType, lobType), )""" % (lob_type, lob_type),
integerValue = 1, integer_value=1,
longString = longString) long_string=long_string)
self.cursor.execute(""" self.cursor.execute("""
select %sCol select %sCol
from Test%ss from Test%ss
where IntCol = 1""" % (lobType, lobType)) where IntCol = 1""" % (lob_type, lob_type))
lob, = self.cursor.fetchone() lob, = self.cursor.fetchone()
self.assertEqual(lob.isopen(), False) self.assertEqual(lob.isopen(), False)
lob.open() lob.open()
@ -90,66 +89,67 @@ class TestCase(TestEnv.BaseTestCase):
lob.close() lob.close()
self.assertEqual(lob.isopen(), False) self.assertEqual(lob.isopen(), False)
self.assertEqual(lob.size(), 75000) self.assertEqual(lob.size(), 75000)
lob.write(writeValue, 75001) lob.write(write_value, 75001)
self.assertEqual(lob.size(), 75000 + len(writeValue)) self.assertEqual(lob.size(), 75000 + len(write_value))
self.assertEqual(lob.read(), longString + writeValue) self.assertEqual(lob.read(), long_string + write_value)
lob.write(writeValue, 1) lob.write(write_value, 1)
self.assertEqual(lob.read(), writeValue + longString[4:] + writeValue) self.assertEqual(lob.read(),
write_value + long_string[4:] + write_value)
lob.trim(25000) lob.trim(25000)
self.assertEqual(lob.size(), 25000) self.assertEqual(lob.size(), 25000)
lob.trim() lob.trim()
self.assertEqual(lob.size(), 0) self.assertEqual(lob.size(), 0)
def __TestTemporaryLOB(self, lobType): def __test_temporary_lob(self, lob_type):
self.cursor.execute("truncate table Test%ss" % lobType) self.cursor.execute("truncate table Test%ss" % lob_type)
value = "A test string value" value = "A test string value"
if lobType == "BLOB" and sys.version_info[0] >= 3: if lob_type == "BLOB":
value = value.encode("ascii") value = value.encode("ascii")
lobTypeObj = getattr(cx_Oracle, lobType) db_type = getattr(oracledb, "DB_TYPE_" + lob_type)
lob = self.connection.createlob(lobTypeObj) lob = self.connection.createlob(db_type)
lob.write(value) lob.write(value)
self.cursor.execute(""" self.cursor.execute("""
insert into Test%ss (IntCol, %sCol) insert into Test%ss (IntCol, %sCol)
values (:intVal, :lobVal)""" % (lobType, lobType), values (:int_val, :lob_val)""" % (lob_type, lob_type),
intVal = 1, int_val=1,
lobVal = lob) lob_val=lob)
self.cursor.execute("select %sCol from Test%ss" % (lobType, lobType)) self.cursor.execute("select %sCol from Test%ss" % (lob_type, lob_type))
lob, = self.cursor.fetchone() lob, = self.cursor.fetchone()
self.assertEqual(lob.read(), value) self.assertEqual(lob.read(), value)
def __ValidateQuery(self, rows, lobType): def __validate_query(self, rows, lob_type):
longString = "" long_string = ""
dbType = getattr(cx_Oracle, "DB_TYPE_" + lobType) db_type = getattr(oracledb, "DB_TYPE_" + lob_type)
for row in rows: for row in rows:
integerValue, lob = row integer_value, lob = row
self.assertEqual(lob.type, dbType) self.assertEqual(lob.type, db_type)
if integerValue == 0: if integer_value == 0:
self.assertEqual(lob.size(), 0) self.assertEqual(lob.size(), 0)
expectedValue = "" expected_value = ""
if lobType == "BLOB" and sys.version_info[0] >= 3: if lob_type == "BLOB":
expectedValue = expectedValue.encode("ascii") expected_value = expected_value.encode()
self.assertEqual(lob.read(), expectedValue) self.assertEqual(lob.read(), expected_value)
else: else:
char = chr(ord('A') + integerValue - 1) char = chr(ord('A') + integer_value - 1)
prevChar = chr(ord('A') + integerValue - 2) prev_char = chr(ord('A') + integer_value - 2)
longString += char * 25000 long_string += char * 25000
if lobType == "BLOB" and sys.version_info[0] >= 3: if lob_type == "BLOB":
actualValue = longString.encode("ascii") actualValue = long_string.encode("ascii")
char = char.encode("ascii") char = char.encode("ascii")
prevChar = prevChar.encode("ascii") prev_char = prev_char.encode("ascii")
else: else:
actualValue = longString actualValue = long_string
self.assertEqual(lob.size(), len(actualValue)) self.assertEqual(lob.size(), len(actualValue))
self.assertEqual(lob.read(), actualValue) self.assertEqual(lob.read(), actualValue)
if lobType == "CLOB": if lob_type == "CLOB":
self.assertEqual(str(lob), actualValue) self.assertEqual(str(lob), actualValue)
self.assertEqual(lob.read(len(actualValue)), char) self.assertEqual(lob.read(len(actualValue)), char)
if integerValue > 1: if integer_value > 1:
offset = (integerValue - 1) * 25000 - 4 offset = (integer_value - 1) * 25000 - 4
string = prevChar * 5 + char * 5 string = prev_char * 5 + char * 5
self.assertEqual(lob.read(offset, 10), string) self.assertEqual(lob.read(offset, 10), string)
def test_1900_BindLobValue(self): def test_1900_bind_lob_value(self):
"1900 - test binding a LOB value directly" "1900 - test binding a LOB value directly"
self.cursor.execute("truncate table TestCLOBs") self.cursor.execute("truncate table TestCLOBs")
self.cursor.execute("insert into TestCLOBs values (1, 'Short value')") self.cursor.execute("insert into TestCLOBs values (1, 'Short value')")
@ -158,105 +158,109 @@ class TestCase(TestEnv.BaseTestCase):
self.cursor.execute("insert into TestCLOBs values (2, :value)", self.cursor.execute("insert into TestCLOBs values (2, :value)",
value=lob) value=lob)
def test_1901_BLOBCursorDescription(self): def test_1901_blob_cursor_description(self):
"1901 - test cursor description is accurate for BLOBs" "1901 - test cursor description is accurate for BLOBs"
self.cursor.execute("select * from TestBLOBs") self.cursor.execute("select * from TestBLOBs")
self.assertEqual(self.cursor.description, expected_value = [
[ ('INTCOL', cx_Oracle.DB_TYPE_NUMBER, 10, None, 9, 0, 0), ('INTCOL', oracledb.DB_TYPE_NUMBER, 10, None, 9, 0, 0),
('BLOBCOL', cx_Oracle.DB_TYPE_BLOB, None, None, None, None, ('BLOBCOL', oracledb.DB_TYPE_BLOB, None, None, None, None, 0)
0) ]) ]
self.assertEqual(self.cursor.description, expected_value)
def test_1902_BLOBsDirect(self): def test_1902_blob_direct(self):
"1902 - test binding and fetching BLOB data (directly)" "1902 - test binding and fetching BLOB data (directly)"
self.__PerformTest("BLOB", cx_Oracle.DB_TYPE_BLOB) self.__perform_test("BLOB", oracledb.DB_TYPE_BLOB)
def test_1903_BLOBsIndirect(self): def test_1903_blob_indirect(self):
"1903 - test binding and fetching BLOB data (indirectly)" "1903 - test binding and fetching BLOB data (indirectly)"
self.__PerformTest("BLOB", cx_Oracle.DB_TYPE_LONG_RAW) self.__perform_test("BLOB", oracledb.DB_TYPE_LONG_RAW)
def test_1904_BLOBOperations(self): def test_1904_blob_operations(self):
"1904 - test operations on BLOBs" "1904 - test operations on BLOBs"
self.__TestLobOperations("BLOB") self.__test_lob_operations("BLOB")
def test_1905_CLOBCursorDescription(self): def test_1905_clob_cursor_description(self):
"1905 - test cursor description is accurate for CLOBs" "1905 - test cursor description is accurate for CLOBs"
self.cursor.execute("select * from TestCLOBs") self.cursor.execute("select * from TestCLOBs")
self.assertEqual(self.cursor.description, expected_value = [
[ ('INTCOL', cx_Oracle.DB_TYPE_NUMBER, 10, None, 9, 0, 0), ('INTCOL', oracledb.DB_TYPE_NUMBER, 10, None, 9, 0, 0),
('CLOBCOL', cx_Oracle.DB_TYPE_CLOB, None, None, None, None, ('CLOBCOL', oracledb.DB_TYPE_CLOB, None, None, None, None, 0)
0) ]) ]
self.assertEqual(self.cursor.description, expected_value)
def test_1906_CLOBsDirect(self): def test_1906_clob_direct(self):
"1906 - test binding and fetching CLOB data (directly)" "1906 - test binding and fetching CLOB data (directly)"
self.__PerformTest("CLOB", cx_Oracle.DB_TYPE_CLOB) self.__perform_test("CLOB", oracledb.DB_TYPE_CLOB)
def test_1907_CLOBsIndirect(self): def test_1907_clob_indirect(self):
"1907 - test binding and fetching CLOB data (indirectly)" "1907 - test binding and fetching CLOB data (indirectly)"
self.__PerformTest("CLOB", cx_Oracle.DB_TYPE_LONG) self.__perform_test("CLOB", oracledb.DB_TYPE_LONG)
def test_1908_CLOBOperations(self): def test_1908_clob_operations(self):
"1908 - test operations on CLOBs" "1908 - test operations on CLOBs"
self.__TestLobOperations("CLOB") self.__test_lob_operations("CLOB")
def test_1909_CreateBlob(self): def test_1909_create_temp_blob(self):
"1909 - test creating a temporary BLOB" "1909 - test creating a temporary BLOB"
self.__TestTemporaryLOB("BLOB") self.__test_temporary_lob("BLOB")
def test_1910_CreateClob(self): def test_1910_create_temp_clob(self):
"1910 - test creating a temporary CLOB" "1910 - test creating a temporary CLOB"
self.__TestTemporaryLOB("CLOB") self.__test_temporary_lob("CLOB")
def test_1911_CreateNclob(self): def test_1911_create_temp_nclob(self):
"1911 - test creating a temporary NCLOB" "1911 - test creating a temporary NCLOB"
self.__TestTemporaryLOB("NCLOB") self.__test_temporary_lob("NCLOB")
def test_1912_MultipleFetch(self): def test_1912_multiple_fetch(self):
"1912 - test retrieving data from a CLOB after multiple fetches" "1912 - test retrieving data from a CLOB after multiple fetches"
self.cursor.arraysize = 1 self.cursor.arraysize = 1
self.cursor.execute("select * from TestCLOBS") self.cursor.execute("select * from TestCLOBS")
rows = self.cursor.fetchall() rows = self.cursor.fetchall()
self.__ValidateQuery(rows, "CLOB") self.__validate_query(rows, "CLOB")
def test_1913_NCLOBCursorDescription(self): def test_1913_nclob_cursor_description(self):
"1913 - test cursor description is accurate for NCLOBs" "1913 - test cursor description is accurate for NCLOBs"
self.cursor.execute("select * from TestNCLOBs") self.cursor.execute("select * from TestNCLOBs")
self.assertEqual(self.cursor.description, expected_value = [
[ ('INTCOL', cx_Oracle.DB_TYPE_NUMBER, 10, None, 9, 0, 0), ('INTCOL', oracledb.DB_TYPE_NUMBER, 10, None, 9, 0, 0),
('NCLOBCOL', cx_Oracle.DB_TYPE_NCLOB, None, None, None, None, ('NCLOBCOL', oracledb.DB_TYPE_NCLOB, None, None, None, None, 0)
0) ]) ]
self.assertEqual(self.cursor.description, expected_value)
def test_1914_NCLOBsDirect(self): def test_1914_nclob_direct(self):
"1914 - test binding and fetching NCLOB data (directly)" "1914 - test binding and fetching NCLOB data (directly)"
self.__PerformTest("NCLOB", cx_Oracle.DB_TYPE_NCLOB) self.__perform_test("NCLOB", oracledb.DB_TYPE_NCLOB)
def test_1915_NCLOBDifferentEncodings(self): def test_1915_nclob_different_encodings(self):
"1915 - test binding and fetching NCLOB data (different encodings)" "1915 - test binding and fetching NCLOB data (different encodings)"
connection = cx_Oracle.connect(TestEnv.GetMainUser(), connection = oracledb.connect(base.get_main_user(),
TestEnv.GetMainPassword(), TestEnv.GetConnectString(), base.get_main_password(),
base.get_connect_string(),
encoding="UTF-8", nencoding="UTF-16") encoding="UTF-8", nencoding="UTF-16")
value = "\u03b4\u4e2a" value = "\u03b4\u4e2a"
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute("truncate table TestNCLOBs") cursor.execute("truncate table TestNCLOBs")
cursor.setinputsizes(val = cx_Oracle.DB_TYPE_NVARCHAR) cursor.setinputsizes(val=oracledb.DB_TYPE_NVARCHAR)
cursor.execute("insert into TestNCLOBs values (1, :val)", val=value) cursor.execute("insert into TestNCLOBs values (1, :val)", val=value)
cursor.execute("select NCLOBCol from TestNCLOBs") cursor.execute("select NCLOBCol from TestNCLOBs")
nclob, = cursor.fetchone() nclob, = cursor.fetchone()
cursor.setinputsizes(val = cx_Oracle.DB_TYPE_NVARCHAR) cursor.setinputsizes(val=oracledb.DB_TYPE_NVARCHAR)
cursor.execute("update TestNCLOBs set NCLOBCol = :val", cursor.execute("update TestNCLOBs set NCLOBCol = :val",
val=nclob.read() + value) val=nclob.read() + value)
cursor.execute("select NCLOBCol from TestNCLOBs") cursor.execute("select NCLOBCol from TestNCLOBs")
nclob, = cursor.fetchone() nclob, = cursor.fetchone()
self.assertEqual(nclob.read(), value + value) self.assertEqual(nclob.read(), value + value)
def test_1916_NCLOBsIndirect(self): def test_1916_nclob_indirect(self):
"1916 - test binding and fetching NCLOB data (indirectly)" "1916 - test binding and fetching NCLOB data (indirectly)"
self.__PerformTest("NCLOB", cx_Oracle.DB_TYPE_LONG) self.__perform_test("NCLOB", oracledb.DB_TYPE_LONG)
def test_1917_NCLOBOperations(self): def test_1917_nclob_operations(self):
"1917 - test operations on NCLOBs" "1917 - test operations on NCLOBs"
self.__TestLobOperations("NCLOB") self.__test_lob_operations("NCLOB")
def test_1918_TemporaryLobs(self): def test_1918_temporary_lobs(self):
"1918 - test temporary LOBs" "1918 - test temporary LOBs"
cursor = self.connection.cursor() cursor = self.connection.cursor()
cursor.arraysize = self.cursor.arraysize cursor.arraysize = self.cursor.arraysize
@ -264,8 +268,8 @@ class TestCase(TestEnv.BaseTestCase):
select sys_context('USERENV', 'SID') select sys_context('USERENV', 'SID')
from dual""") from dual""")
sid, = cursor.fetchone() sid, = cursor.fetchone()
tempLobs = self.__GetTempLobs(sid) temp_lobs = self.__get_temp_lobs(sid)
self.assertEqual(tempLobs, 0) self.assertEqual(temp_lobs, 0)
cursor.execute(""" cursor.execute("""
select extract(xmlcol, '/').getclobval() select extract(xmlcol, '/').getclobval()
from TestXML""") from TestXML""")
@ -273,13 +277,13 @@ class TestCase(TestEnv.BaseTestCase):
value = lob.read() value = lob.read()
del lob del lob
cursor.close() cursor.close()
tempLobs = self.__GetTempLobs(sid) temp_lobs = self.__get_temp_lobs(sid)
self.assertEqual(tempLobs, 0) self.assertEqual(temp_lobs, 0)
def test_1919_AssignStringBeyondArraySize(self): def test_1919_AssignStringBeyondArraySize(self):
"1919 - test assign string to NCLOB beyond array size" "1919 - test assign string to NCLOB beyond array size"
nclobVar = self.cursor.var(cx_Oracle.DB_TYPE_NCLOB) nclobVar = self.cursor.var(oracledb.DB_TYPE_NCLOB)
self.assertRaises(IndexError, nclobVar.setvalue, 1, "test char") self.assertRaises(IndexError, nclobVar.setvalue, 1, "test char")
if __name__ == "__main__": if __name__ == "__main__":
TestEnv.RunTestCases() base.run_test_cases()

View File

@ -11,97 +11,95 @@
2000 - Module for testing long and long raw variables 2000 - Module for testing long and long raw variables
""" """
import TestEnv import base
import cx_Oracle import cx_Oracle as oracledb
import sys
class TestCase(TestEnv.BaseTestCase): class TestCase(base.BaseTestCase):
def __PerformTest(self, a_Type, a_InputType): def __perform_test(self, typ):
self.cursor.execute("truncate table Test%ss" % a_Type) name_part = "Long" if typ is oracledb.DB_TYPE_LONG else "LongRaw"
longString = ""
self.cursor.execute("truncate table Test%ss" % name_part)
long_string = ""
for i in range(1, 11): for i in range(1, 11):
char = chr(ord('A') + i - 1) char = chr(ord('A') + i - 1)
longString += char * 25000 long_string += char * 25000
self.cursor.setinputsizes(longString = a_InputType) self.cursor.setinputsizes(long_string=typ)
if a_Type == "LongRaw" and sys.version_info[0] >= 3: if typ is oracledb.DB_TYPE_LONG_RAW:
bindValue = longString.encode("ascii") bind_value = long_string.encode()
else: else:
bindValue = longString bind_value = long_string
self.cursor.execute(""" self.cursor.execute("""
insert into Test%ss ( insert into Test%ss (
IntCol, IntCol,
%sCol %sCol
) values ( ) values (
:integerValue, :integer_value,
:longString :long_string
)""" % (a_Type, a_Type), )""" % (name_part, name_part),
integerValue = i, integer_value=i,
longString = bindValue) long_string=bind_value)
self.connection.commit() self.connection.commit()
self.cursor.execute(""" self.cursor.execute("""
select * select *
from Test%ss from Test%ss
order by IntCol""" % a_Type) order by IntCol""" % name_part)
longString = "" long_string = ""
while 1: for integer_value, fetched_value in self.cursor:
row = self.cursor.fetchone() char = chr(ord('A') + integer_value - 1)
if row is None: long_string += char * 25000
break if typ is oracledb.DB_TYPE_LONG_RAW:
integerValue, fetchedValue = row actual_value = long_string.encode()
char = chr(ord('A') + integerValue - 1)
longString += char * 25000
if a_Type == "LongRaw" and sys.version_info[0] >= 3:
actualValue = longString.encode("ascii")
else: else:
actualValue = longString actual_value = long_string
self.assertEqual(len(fetchedValue), integerValue * 25000) self.assertEqual(len(fetched_value), integer_value * 25000)
self.assertEqual(fetchedValue, actualValue) self.assertEqual(fetched_value, actual_value)
def test_2000_Longs(self): def test_2000_longs(self):
"2000 - test binding and fetching long data" "2000 - test binding and fetching long data"
self.__PerformTest("Long", cx_Oracle.DB_TYPE_LONG) self.__perform_test(oracledb.DB_TYPE_LONG)
def test_2001_LongWithExecuteMany(self): def test_2001_long_with_execute_many(self):
"2001 - test binding long data with executemany()" "2001 - test binding long data with executemany()"
data = [] data = []
self.cursor.execute("truncate table TestLongs") self.cursor.execute("truncate table TestLongs")
for i in range(5): for i in range(5):
char = chr(ord('A') + i) char = chr(ord('A') + i)
longStr = char * (32768 * (i + 1)) long_str = char * (32768 * (i + 1))
data.append((i + 1, longStr)) data.append((i + 1, long_str))
self.cursor.executemany("insert into TestLongs values (:1, :2)", data) self.cursor.executemany("insert into TestLongs values (:1, :2)", data)
self.connection.commit() self.connection.commit()
self.cursor.execute("select * from TestLongs order by IntCol") self.cursor.execute("select * from TestLongs order by IntCol")
fetchedData = self.cursor.fetchall() fetched_data = self.cursor.fetchall()
self.assertEqual(fetchedData, data) self.assertEqual(fetched_data, data)
def test_2002_LongRaws(self): def test_2002_long_raws(self):
"2002 - test binding and fetching long raw data" "2002 - test binding and fetching long raw data"
self.__PerformTest("LongRaw", cx_Oracle.DB_TYPE_LONG_RAW) self.__perform_test(oracledb.DB_TYPE_LONG_RAW)
def test_2003_LongCursorDescription(self): def test_2003_long_cursor_description(self):
"2003 - test cursor description is accurate for longs" "2003 - test cursor description is accurate for longs"
self.cursor.execute("select * from TestLongs") self.cursor.execute("select * from TestLongs")
self.assertEqual(self.cursor.description, expected_value = [
[ ('INTCOL', cx_Oracle.DB_TYPE_NUMBER, 10, None, 9, 0, 0), ('INTCOL', oracledb.DB_TYPE_NUMBER, 10, None, 9, 0, 0),
('LONGCOL', cx_Oracle.DB_TYPE_LONG, None, None, None, None, ('LONGCOL', oracledb.DB_TYPE_LONG, None, None, None, None, 0)
0) ]) ]
self.assertEqual(self.cursor.description, expected_value)
def test_2004_LongRawCursorDescription(self): def test_2004_long_raw_cursor_description(self):
"2004 - test cursor description is accurate for long raws" "2004 - test cursor description is accurate for long raws"
self.cursor.execute("select * from TestLongRaws") self.cursor.execute("select * from TestLongRaws")
self.assertEqual(self.cursor.description, self.assertEqual(self.cursor.description,
[ ('INTCOL', cx_Oracle.DB_TYPE_NUMBER, 10, None, 9, 0, 0), [ ('INTCOL', oracledb.DB_TYPE_NUMBER, 10, None, 9, 0, 0),
('LONGRAWCOL', cx_Oracle.DB_TYPE_LONG_RAW, None, None, None, ('LONGRAWCOL', oracledb.DB_TYPE_LONG_RAW, None, None, None,
None, 0) ]) None, 0) ])
def test_2005_ArraySizeTooLarge(self): def test_2005_array_size_too_large(self):
"2005 - test array size too large generates an exception" "2005 - test array size too large generates an exception"
self.cursor.arraysize = 268435456 self.cursor.arraysize = 268435456
self.assertRaises(cx_Oracle.DatabaseError, self.cursor.execute, self.assertRaises(oracledb.DatabaseError, self.cursor.execute,
"select * from TestLongRaws") "select * from TestLongRaws")
if __name__ == "__main__": if __name__ == "__main__":
TestEnv.RunTestCases() base.run_test_cases()

View File

@ -11,151 +11,146 @@
2100 - Module for testing NCHAR variables 2100 - Module for testing NCHAR variables
""" """
import TestEnv import base
import cx_Oracle import cx_Oracle as oracledb
class TestCase(TestEnv.BaseTestCase): class TestCase(base.BaseTestCase):
def setUp(self): def setUp(self):
TestEnv.BaseTestCase.setUp(self) super().setUp()
self.rawData = [] self.raw_data = []
self.dataByKey = {} self.data_by_key = {}
for i in range(1, 11): for i in range(1, 11):
unicodeCol = "Unicode \u3042 %d" % i unicode_col = "Unicode \u3042 %d" % i
fixedCharCol = ("Fixed Unicode %d" % i).ljust(40) fixed_char_col = ("Fixed Unicode %d" % i).ljust(40)
if i % 2: if i % 2:
nullableCol = "Nullable %d" % i nullable_col = "Nullable %d" % i
else: else:
nullableCol = None nullable_col = None
dataTuple = (i, unicodeCol, fixedCharCol, nullableCol) data_tuple = (i, unicode_col, fixed_char_col, nullable_col)
self.rawData.append(dataTuple) self.raw_data.append(data_tuple)
self.dataByKey[i] = dataTuple self.data_by_key[i] = data_tuple
def test_2100_UnicodeLength(self): def test_2100_unicode_length(self):
"2100 - test value length" "2100 - test value length"
returnValue = self.cursor.var(int) return_value = self.cursor.var(int)
self.cursor.execute(""" self.cursor.execute("""
begin begin
:retval := LENGTH(:value); :retval := LENGTH(:value);
end;""", end;""",
value="InVal \u3042", value="InVal \u3042",
retval = returnValue) retval=return_value)
self.assertEqual(returnValue.getvalue(), 7) self.assertEqual(return_value.getvalue(), 7)
def test_2101_BindUnicode(self): def test_2101_bind_unicode(self):
"2101 - test binding in a unicode" "2101 - test binding in a unicode"
self.cursor.setinputsizes(value = cx_Oracle.DB_TYPE_NVARCHAR) self.cursor.setinputsizes(value=oracledb.DB_TYPE_NVARCHAR)
self.cursor.execute(""" self.cursor.execute("""
select * from TestUnicodes select * from TestUnicodes
where UnicodeCol = :value""", where UnicodeCol = :value""",
value="Unicode \u3042 5") value="Unicode \u3042 5")
self.assertEqual(self.cursor.fetchall(), [self.dataByKey[5]]) self.assertEqual(self.cursor.fetchall(), [self.data_by_key[5]])
def test_2102_BindDifferentVar(self): def test_2102_bind_different_var(self):
"2102 - test binding a different variable on second execution" "2102 - test binding a different variable on second execution"
retval_1 = self.cursor.var(cx_Oracle.DB_TYPE_NVARCHAR, 30) retval_1 = self.cursor.var(oracledb.DB_TYPE_NVARCHAR, 30)
retval_2 = self.cursor.var(cx_Oracle.DB_TYPE_NVARCHAR, 30) retval_2 = self.cursor.var(oracledb.DB_TYPE_NVARCHAR, 30)
self.cursor.execute(r"begin :retval := unistr('Called \3042'); end;", self.cursor.execute(r"begin :retval := unistr('Called \3042'); end;",
retval=retval_1) retval=retval_1)
self.assertEqual(retval_1.getvalue(), "Called \u3042") self.assertEqual(retval_1.getvalue(), "Called \u3042")
self.cursor.execute("begin :retval := 'Called'; end;", self.cursor.execute("begin :retval := 'Called'; end;", retval=retval_2)
retval = retval_2)
self.assertEqual(retval_2.getvalue(), "Called") self.assertEqual(retval_2.getvalue(), "Called")
def test_2103_BindUnicodeAfterNumber(self): def test_2103_bind_unicode_after_number(self):
"2103 - test binding in a string after setting input sizes to a number" "2103 - test binding in a string after setting input sizes to a number"
unicodeVal = self.cursor.var(cx_Oracle.DB_TYPE_NVARCHAR) unicode_val = self.cursor.var(oracledb.DB_TYPE_NVARCHAR)
unicodeVal.setvalue(0, "Unicode \u3042 6") unicode_val.setvalue(0, "Unicode \u3042 6")
self.cursor.setinputsizes(value = cx_Oracle.NUMBER) self.cursor.setinputsizes(value=oracledb.NUMBER)
self.cursor.execute(""" self.cursor.execute("""
select * from TestUnicodes select * from TestUnicodes
where UnicodeCol = :value""", where UnicodeCol = :value""",
value = unicodeVal) value=unicode_val)
self.assertEqual(self.cursor.fetchall(), [self.dataByKey[6]]) self.assertEqual(self.cursor.fetchall(), [self.data_by_key[6]])
def test_2104_BindUnicodeArrayDirect(self): def test_2104_bind_unicode_array_direct(self):
"2104 - test binding in a unicode array" "2104 - test binding in a unicode array"
returnValue = self.cursor.var(cx_Oracle.NUMBER) return_value = self.cursor.var(oracledb.NUMBER)
array = [r[1] for r in self.rawData] array = [r[1] for r in self.raw_data]
arrayVar = self.cursor.arrayvar(cx_Oracle.DB_TYPE_NVARCHAR, array) array_var = self.cursor.arrayvar(oracledb.DB_TYPE_NVARCHAR, array)
statement = """ statement = """
begin begin
:retval := pkg_TestUnicodeArrays.TestInArrays( :retval := pkg_TestUnicodeArrays.TestInArrays(
:integerValue, :array); :integer_value, :array);
end;""" end;"""
self.cursor.execute(statement, self.cursor.execute(statement, retval=return_value, integer_value=5,
retval = returnValue, array=array_var)
integerValue = 5, self.assertEqual(return_value.getvalue(), 116)
array = arrayVar)
self.assertEqual(returnValue.getvalue(), 116)
array = ["Unicode - \u3042 %d" % i for i in range(15)] array = ["Unicode - \u3042 %d" % i for i in range(15)]
arrayVar = self.cursor.arrayvar(cx_Oracle.DB_TYPE_NVARCHAR, array) array_var = self.cursor.arrayvar(oracledb.DB_TYPE_NVARCHAR, array)
self.cursor.execute(statement, self.cursor.execute(statement, integer_value=8, array=array_var)
integerValue = 8, self.assertEqual(return_value.getvalue(), 208)
array = arrayVar)
self.assertEqual(returnValue.getvalue(), 208)
def test_2105_BindUnicodeArrayBySizes(self): def test_2105_bind_unicode_array_by_sizes(self):
"2105 - test binding in a unicode array (with setinputsizes)" "2105 - test binding in a unicode array (with setinputsizes)"
returnValue = self.cursor.var(cx_Oracle.NUMBER) return_value = self.cursor.var(oracledb.NUMBER)
self.cursor.setinputsizes(array = [cx_Oracle.DB_TYPE_NVARCHAR, 10]) self.cursor.setinputsizes(array = [oracledb.DB_TYPE_NVARCHAR, 10])
array = [r[1] for r in self.rawData] array = [r[1] for r in self.raw_data]
self.cursor.execute(""" self.cursor.execute("""
begin begin
:retval := pkg_TestUnicodeArrays.TestInArrays(:integerValue, :retval := pkg_TestUnicodeArrays.TestInArrays(:integer_value,
:array); :array);
end;""", end;""",
retval = returnValue, retval=return_value,
integerValue = 6, integer_value=6,
array=array) array=array)
self.assertEqual(returnValue.getvalue(), 117) self.assertEqual(return_value.getvalue(), 117)
def test_2106_BindUnicodeArrayByVar(self): def test_2106_bind_unicode_array_by_var(self):
"2106 - test binding in a unicode array (with arrayvar)" "2106 - test binding in a unicode array (with arrayvar)"
returnValue = self.cursor.var(cx_Oracle.NUMBER) return_value = self.cursor.var(oracledb.NUMBER)
array = self.cursor.arrayvar(cx_Oracle.DB_TYPE_NVARCHAR, 10, 20) array = self.cursor.arrayvar(oracledb.DB_TYPE_NVARCHAR, 10, 20)
array.setvalue(0, [r[1] for r in self.rawData]) array.setvalue(0, [r[1] for r in self.raw_data])
self.cursor.execute(""" self.cursor.execute("""
begin begin
:retval := pkg_TestUnicodeArrays.TestInArrays(:integerValue, :retval := pkg_TestUnicodeArrays.TestInArrays(:integer_value,
:array); :array);
end;""", end;""",
retval = returnValue, retval=return_value,
integerValue = 7, integer_value=7,
array=array) array=array)
self.assertEqual(returnValue.getvalue(), 118) self.assertEqual(return_value.getvalue(), 118)
def test_2107_BindInOutUnicodeArrayByVar(self): def test_2107_bind_in_out_unicode_array_by_var(self):
"2107 - test binding in/out a unicode array (with arrayvar)" "2107 - test binding in/out a unicode array (with arrayvar)"
array = self.cursor.arrayvar(cx_Oracle.DB_TYPE_NVARCHAR, 10, 100) array = self.cursor.arrayvar(oracledb.DB_TYPE_NVARCHAR, 10, 100)
originalData = [r[1] for r in self.rawData] original_data = [r[1] for r in self.raw_data]
format = "Converted element \u3042 # %d originally had length %d" fmt = "Converted element \u3042 # %d originally had length %d"
expectedData = [format % (i, len(originalData[i - 1])) \ expected_data = [fmt % (i, len(original_data[i - 1])) \
for i in range(1, 6)] + originalData[5:] for i in range(1, 6)] + original_data[5:]
array.setvalue(0, originalData) array.setvalue(0, original_data)
self.cursor.execute(""" self.cursor.execute("""
begin begin
pkg_TestUnicodeArrays.TestInOutArrays(:numElems, :array); pkg_TestUnicodeArrays.TestInOutArrays(:numElems, :array);
end;""", end;""",
numElems = 5, numElems = 5,
array = array) array = array)
self.assertEqual(array.getvalue(), expectedData) self.assertEqual(array.getvalue(), expected_data)
def test_2108_BindOutUnicodeArrayByVar(self): def test_2108_bind_out_unicode_array_by_var(self):
"2108 - test binding out a unicode array (with arrayvar)" "2108 - test binding out a unicode array (with arrayvar)"
array = self.cursor.arrayvar(cx_Oracle.DB_TYPE_NVARCHAR, 6, 100) array = self.cursor.arrayvar(oracledb.DB_TYPE_NVARCHAR, 6, 100)
format = "Test out element \u3042 # %d" fmt = "Test out element \u3042 # %d"
expectedData = [format % i for i in range(1, 7)] expected_data = [fmt % i for i in range(1, 7)]
self.cursor.execute(""" self.cursor.execute("""
begin begin
pkg_TestUnicodeArrays.TestOutArrays(:numElems, :array); pkg_TestUnicodeArrays.TestOutArrays(:numElems, :array);
end;""", end;""",
numElems = 6, numElems = 6,
array = array) array = array)
self.assertEqual(array.getvalue(), expectedData) self.assertEqual(array.getvalue(), expected_data)
def test_2109_BindNull(self): def test_2109_bind_null(self):
"2109 - test binding in a null" "2109 - test binding in a null"
self.cursor.execute(""" self.cursor.execute("""
select * from TestUnicodes select * from TestUnicodes
@ -163,29 +158,29 @@ class TestCase(TestEnv.BaseTestCase):
value = None) value = None)
self.assertEqual(self.cursor.fetchall(), []) self.assertEqual(self.cursor.fetchall(), [])
def test_2110_BindOutSetInputSizesByType(self): def test_2110_bind_out_set_input_sizes_by_type(self):
"2110 - test binding out with set input sizes defined (by type)" "2110 - test binding out with set input sizes defined (by type)"
vars = self.cursor.setinputsizes(value = cx_Oracle.DB_TYPE_NVARCHAR) bind_vars = self.cursor.setinputsizes(value=oracledb.DB_TYPE_NVARCHAR)
self.cursor.execute(r""" self.cursor.execute(r"""
begin begin
:value := unistr('TSI \3042'); :value := unistr('TSI \3042');
end;""") end;""")
self.assertEqual(vars["value"].getvalue(), "TSI \u3042") self.assertEqual(bind_vars["value"].getvalue(), "TSI \u3042")
def test_2111_BindInOutSetInputSizesByType(self): def test_2111_bind_in_out_set_input_sizes_by_type(self):
"2111 - test binding in/out with set input sizes defined (by type)" "2111 - test binding in/out with set input sizes defined (by type)"
vars = self.cursor.setinputsizes(value = cx_Oracle.DB_TYPE_NVARCHAR) bind_vars = self.cursor.setinputsizes(value=oracledb.DB_TYPE_NVARCHAR)
self.cursor.execute(r""" self.cursor.execute(r"""
begin begin
:value := :value || unistr(' TSI \3042'); :value := :value || unistr(' TSI \3042');
end;""", end;""",
value = "InVal \u3041") value = "InVal \u3041")
self.assertEqual(vars["value"].getvalue(), self.assertEqual(bind_vars["value"].getvalue(),
"InVal \u3041 TSI \u3042") "InVal \u3041 TSI \u3042")
def test_2112_BindOutVar(self): def test_2112_bind_out_var(self):
"2112 - test binding out with cursor.var() method" "2112 - test binding out with cursor.var() method"
var = self.cursor.var(cx_Oracle.DB_TYPE_NVARCHAR) var = self.cursor.var(oracledb.DB_TYPE_NVARCHAR)
self.cursor.execute(r""" self.cursor.execute(r"""
begin begin
:value := unistr('TSI (VAR) \3042'); :value := unistr('TSI (VAR) \3042');
@ -193,9 +188,9 @@ class TestCase(TestEnv.BaseTestCase):
value=var) value=var)
self.assertEqual(var.getvalue(), "TSI (VAR) \u3042") self.assertEqual(var.getvalue(), "TSI (VAR) \u3042")
def test_2113_BindInOutVarDirectSet(self): def test_2113_bind_in_out_var_direct_set(self):
"2113 - test binding in/out with cursor.var() method" "2113 - test binding in/out with cursor.var() method"
var = self.cursor.var(cx_Oracle.DB_TYPE_NVARCHAR) var = self.cursor.var(oracledb.DB_TYPE_NVARCHAR)
var.setvalue(0, "InVal \u3041") var.setvalue(0, "InVal \u3041")
self.cursor.execute(r""" self.cursor.execute(r"""
begin begin
@ -204,43 +199,42 @@ class TestCase(TestEnv.BaseTestCase):
value = var) value = var)
self.assertEqual(var.getvalue(), "InVal \u3041 TSI (VAR) \u3042") self.assertEqual(var.getvalue(), "InVal \u3041 TSI (VAR) \u3042")
def test_2114_CursorDescription(self): def test_2114_cursor_description(self):
"2114 - test cursor description is accurate" "2114 - test cursor description is accurate"
self.cursor.execute("select * from TestUnicodes") self.cursor.execute("select * from TestUnicodes")
self.assertEqual(self.cursor.description, expected_value = [
[ ('INTCOL', cx_Oracle.DB_TYPE_NUMBER, 10, None, 9, 0, 0), ('INTCOL', oracledb.DB_TYPE_NUMBER, 10, None, 9, 0, 0),
('UNICODECOL', cx_Oracle.DB_TYPE_NVARCHAR, 20, 80, None, ('UNICODECOL', oracledb.DB_TYPE_NVARCHAR, 20, 80, None, None, 0),
None, 0), ('FIXEDUNICODECOL', oracledb.DB_TYPE_NCHAR, 40, 160, None, None, 0),
('FIXEDUNICODECOL', cx_Oracle.DB_TYPE_NCHAR, 40, 160, None, ('NULLABLECOL', oracledb.DB_TYPE_NVARCHAR, 50, 200, None, None, 1)
None, 0), ]
('NULLABLECOL', cx_Oracle.DB_TYPE_NVARCHAR, 50, 200, None, self.assertEqual(self.cursor.description, expected_value)
None, 1) ])
def test_2115_FetchAll(self): def test_2115_fetchall(self):
"2115 - test that fetching all of the data returns the correct results" "2115 - test that fetching all of the data returns the correct results"
self.cursor.execute("select * From TestUnicodes order by IntCol") self.cursor.execute("select * From TestUnicodes order by IntCol")
self.assertEqual(self.cursor.fetchall(), self.rawData) self.assertEqual(self.cursor.fetchall(), self.raw_data)
self.assertEqual(self.cursor.fetchall(), []) self.assertEqual(self.cursor.fetchall(), [])
def test_2116_FetchMany(self): def test_2116_fetchmany(self):
"2116 - test that fetching data in chunks returns the correct results" "2116 - test that fetching data in chunks returns the correct results"
self.cursor.execute("select * From TestUnicodes order by IntCol") self.cursor.execute("select * From TestUnicodes order by IntCol")
self.assertEqual(self.cursor.fetchmany(3), self.rawData[0:3]) self.assertEqual(self.cursor.fetchmany(3), self.raw_data[0:3])
self.assertEqual(self.cursor.fetchmany(2), self.rawData[3:5]) self.assertEqual(self.cursor.fetchmany(2), self.raw_data[3:5])
self.assertEqual(self.cursor.fetchmany(4), self.rawData[5:9]) self.assertEqual(self.cursor.fetchmany(4), self.raw_data[5:9])
self.assertEqual(self.cursor.fetchmany(3), self.rawData[9:]) self.assertEqual(self.cursor.fetchmany(3), self.raw_data[9:])
self.assertEqual(self.cursor.fetchmany(3), []) self.assertEqual(self.cursor.fetchmany(3), [])
def test_2117_FetchOne(self): def test_2117_fetchone(self):
"2117 - test that fetching a single row returns the correct results" "2117 - test that fetching a single row returns the correct results"
self.cursor.execute(""" self.cursor.execute("""
select * select *
from TestUnicodes from TestUnicodes
where IntCol in (3, 4) where IntCol in (3, 4)
order by IntCol""") order by IntCol""")
self.assertEqual(self.cursor.fetchone(), self.dataByKey[3]) self.assertEqual(self.cursor.fetchone(), self.data_by_key[3])
self.assertEqual(self.cursor.fetchone(), self.dataByKey[4]) self.assertEqual(self.cursor.fetchone(), self.data_by_key[4])
self.assertEqual(self.cursor.fetchone(), None) self.assertEqual(self.cursor.fetchone(), None)
if __name__ == "__main__": if __name__ == "__main__":
TestEnv.RunTestCases() base.run_test_cases()

View File

@ -11,51 +11,51 @@
2200 - Module for testing number variables 2200 - Module for testing number variables
""" """
import TestEnv import base
import cx_Oracle import cx_Oracle as oracledb
import decimal import decimal
import sys import sys
class TestCase(TestEnv.BaseTestCase): class TestCase(base.BaseTestCase):
def outputTypeHandlerNativeInt(self, cursor, name, defaultType, size, def output_type_handler_binary_int(self, cursor, name, default_type, size,
precision, scale): precision, scale):
return cursor.var(cx_Oracle.DB_TYPE_BINARY_INTEGER, return cursor.var(oracledb.DB_TYPE_BINARY_INTEGER,
arraysize=cursor.arraysize) arraysize=cursor.arraysize)
def outputTypeHandlerDecimal(self, cursor, name, defaultType, size, def output_type_handler_decimal(self, cursor, name, default_type, size,
precision, scale): precision, scale):
if defaultType == cx_Oracle.NUMBER: if default_type == oracledb.NUMBER:
return cursor.var(str, 255, outconverter=decimal.Decimal, return cursor.var(str, 255, outconverter=decimal.Decimal,
arraysize=cursor.arraysize) arraysize=cursor.arraysize)
def setUp(self): def setUp(self):
TestEnv.BaseTestCase.setUp(self) super().setUp()
self.rawData = [] self.raw_data = []
self.dataByKey = {} self.data_by_key = {}
for i in range(1, 11): for i in range(1, 11):
numberCol = i + i * 0.25 number_col = i + i * 0.25
floatCol = i + i * 0.75 float_col = i + i * 0.75
unconstrainedCol = i ** 3 + i * 0.5 unconstrained_col = i ** 3 + i * 0.5
if i % 2: if i % 2:
nullableCol = 143 ** i nullable_col = 143 ** i
else: else:
nullableCol = None nullable_col = None
dataTuple = (i, 38 ** i, numberCol, floatCol, data_tuple = (i, 38 ** i, number_col, float_col,
unconstrainedCol, nullableCol) unconstrained_col, nullable_col)
self.rawData.append(dataTuple) self.raw_data.append(data_tuple)
self.dataByKey[i] = dataTuple self.data_by_key[i] = data_tuple
def test_2200_BindBoolean(self): def test_2200_bind_boolean(self):
"2200 - test binding in a boolean" "2200 - test binding in a boolean"
result = self.cursor.callfunc("pkg_TestBooleans.GetStringRep", str, result = self.cursor.callfunc("pkg_TestBooleans.GetStringRep", str,
(True,)) (True,))
self.assertEqual(result, "TRUE") self.assertEqual(result, "TRUE")
def test_2201_BindBooleanAsNumber(self): def test_2201_bind_boolean_as_number(self):
"2201 - test binding in a boolean as a number" "2201 - test binding in a boolean as a number"
var = self.cursor.var(cx_Oracle.NUMBER) var = self.cursor.var(oracledb.NUMBER)
var.setvalue(0, True) var.setvalue(0, True)
self.cursor.execute("select :1 from dual", [var]) self.cursor.execute("select :1 from dual", [var])
result, = self.cursor.fetchone() result, = self.cursor.fetchone()
@ -65,73 +65,75 @@ class TestCase(TestEnv.BaseTestCase):
result, = self.cursor.fetchone() result, = self.cursor.fetchone()
self.assertEqual(result, 0) self.assertEqual(result, 0)
def test_2202_BindDecimal(self): def test_2202_bind_decimal(self):
"2202 - test binding in a decimal.Decimal" "2202 - test binding in a decimal.Decimal"
self.cursor.execute(""" self.cursor.execute("""
select * from TestNumbers select * from TestNumbers
where NumberCol - :value1 - :value2 = trunc(NumberCol)""", where NumberCol - :value1 - :value2 = trunc(NumberCol)""",
value1=decimal.Decimal("0.20"), value1=decimal.Decimal("0.20"),
value2=decimal.Decimal("0.05")) value2=decimal.Decimal("0.05"))
self.assertEqual(self.cursor.fetchall(), expected_data = [self.data_by_key[1], self.data_by_key[5],
[self.dataByKey[1], self.dataByKey[5], self.dataByKey[9]]) self.data_by_key[9]]
self.assertEqual(self.cursor.fetchall(), expected_data)
def test_2203_BindFloat(self): def test_2203_bind_float(self):
"2203 - test binding in a float" "2203 - test binding in a float"
self.cursor.execute(""" self.cursor.execute("""
select * from TestNumbers select * from TestNumbers
where NumberCol - :value = trunc(NumberCol)""", where NumberCol - :value = trunc(NumberCol)""",
value=0.25) value=0.25)
self.assertEqual(self.cursor.fetchall(), expected_data = [self.data_by_key[1], self.data_by_key[5],
[self.dataByKey[1], self.dataByKey[5], self.dataByKey[9]]) self.data_by_key[9]]
self.assertEqual(self.cursor.fetchall(), expected_data)
def test_2204_BindInteger(self): def test_2204_bind_integer(self):
"2204 - test binding in an integer" "2204 - test binding in an integer"
self.cursor.execute(""" self.cursor.execute("""
select * from TestNumbers select * from TestNumbers
where IntCol = :value""", where IntCol = :value""",
value = 2) value = 2)
self.assertEqual(self.cursor.fetchall(), [self.dataByKey[2]]) self.assertEqual(self.cursor.fetchall(), [self.data_by_key[2]])
def test_2205_BindLargeLongAsOracleNumber(self): def test_2205_bind_large_long_as_oracle_number(self):
"2205 - test binding in a large long integer as Oracle number" "2205 - test binding in a large long integer as Oracle number"
valueVar = self.cursor.var(cx_Oracle.NUMBER) in_val = 6088343244
valueVar.setvalue(0, 6088343244) value_var = self.cursor.var(oracledb.NUMBER)
value_var.setvalue(0, in_val)
self.cursor.execute(""" self.cursor.execute("""
begin begin
:value := :value + 5; :value := :value + 5;
end;""", end;""",
value = valueVar) value=value_var)
value = valueVar.getvalue() value = value_var.getvalue()
self.assertEqual(value, 6088343249) self.assertEqual(value, in_val + 5)
def test_2206_BindLargeLongAsInteger(self): def test_2206_bind_large_long_as_integer(self):
"2206 - test binding in a large long integer as Python integer" "2206 - test binding in a large long integer as Python integer"
longValue = -9999999999999999999 long_value = -9999999999999999999
self.cursor.execute("select :value from dual", value = longValue) self.cursor.execute("select :value from dual", value=long_value)
result, = self.cursor.fetchone() result, = self.cursor.fetchone()
self.assertEqual(result, longValue) self.assertEqual(result, long_value)
def test_2207_BindIntegerAfterString(self): def test_2207_bind_integer_after_string(self):
"2207 - test binding in an integer after setting input sizes to string" "2207 - test binding in an integer after setting input sizes to string"
self.cursor.setinputsizes(value=15) self.cursor.setinputsizes(value=15)
self.cursor.execute(""" self.cursor.execute("""
select * from TestNumbers select * from TestNumbers
where IntCol = :value""", where IntCol = :value""",
value=3) value=3)
self.assertEqual(self.cursor.fetchall(), [self.dataByKey[3]]) self.assertEqual(self.cursor.fetchall(), [self.data_by_key[3]])
def test_2208_BindDecimalAfterNumber(self): def test_2208_bind_decimal_after_number(self):
"2208 - test binding in a decimal after setting input sizes to number" "2208 - test binding in a decimal after setting input sizes to number"
cursor = self.connection.cursor() cursor = self.connection.cursor()
value = decimal.Decimal("319438950232418390.273596") value = decimal.Decimal("319438950232418390.273596")
cursor.setinputsizes(value = cx_Oracle.NUMBER) cursor.setinputsizes(value=oracledb.NUMBER)
cursor.outputtypehandler = self.outputTypeHandlerDecimal cursor.outputtypehandler = self.output_type_handler_decimal
cursor.execute("select :value from dual", cursor.execute("select :value from dual", value=value)
value = value) out_value, = cursor.fetchone()
outValue, = cursor.fetchone() self.assertEqual(out_value, value)
self.assertEqual(outValue, value)
def test_2209_BindNull(self): def test_2209_bind_null(self):
"2209 - test binding in a null" "2209 - test binding in a null"
self.cursor.execute(""" self.cursor.execute("""
select * from TestNumbers select * from TestNumbers
@ -139,120 +141,116 @@ class TestCase(TestEnv.BaseTestCase):
value=None) value=None)
self.assertEqual(self.cursor.fetchall(), []) self.assertEqual(self.cursor.fetchall(), [])
def test_2210_BindNumberArrayDirect(self): def test_2210_bind_number_array_direct(self):
"2210 - test binding in a number array" "2210 - test binding in a number array"
returnValue = self.cursor.var(cx_Oracle.NUMBER) return_value = self.cursor.var(oracledb.NUMBER)
array = [r[2] for r in self.rawData] array = [r[2] for r in self.raw_data]
statement = """ statement = """
begin begin
:returnValue := pkg_TestNumberArrays.TestInArrays( :return_value := pkg_TestNumberArrays.TestInArrays(
:startValue, :array); :start_value, :array);
end;""" end;"""
self.cursor.execute(statement, self.cursor.execute(statement, return_value=return_value,
returnValue = returnValue, start_value=5, array=array)
startValue = 5, self.assertEqual(return_value.getvalue(), 73.75)
array = array)
self.assertEqual(returnValue.getvalue(), 73.75)
array = list(range(15)) array = list(range(15))
self.cursor.execute(statement, self.cursor.execute(statement, start_value=10, array=array)
startValue = 10, self.assertEqual(return_value.getvalue(), 115.0)
array = array)
self.assertEqual(returnValue.getvalue(), 115.0)
def test_2211_BindNumberArrayBySizes(self): def test_2211_bind_number_array_by_sizes(self):
"2211 - test binding in a number array (with setinputsizes)" "2211 - test binding in a number array (with setinputsizes)"
returnValue = self.cursor.var(cx_Oracle.NUMBER) return_value = self.cursor.var(oracledb.NUMBER)
self.cursor.setinputsizes(array = [cx_Oracle.NUMBER, 10]) self.cursor.setinputsizes(array = [oracledb.NUMBER, 10])
array = [r[2] for r in self.rawData] array = [r[2] for r in self.raw_data]
self.cursor.execute(""" self.cursor.execute("""
begin begin
:returnValue := pkg_TestNumberArrays.TestInArrays( :return_value := pkg_TestNumberArrays.TestInArrays(
:startValue, :array); :start_value, :array);
end;""", end;""",
returnValue = returnValue, return_value=return_value,
startValue = 6, start_value=6,
array=array) array=array)
self.assertEqual(returnValue.getvalue(), 74.75) self.assertEqual(return_value.getvalue(), 74.75)
def test_2212_BindNumberArrayByVar(self): def test_2212_bind_number_array_by_var(self):
"2212 - test binding in a number array (with arrayvar)" "2212 - test binding in a number array (with arrayvar)"
returnValue = self.cursor.var(cx_Oracle.NUMBER) return_value = self.cursor.var(oracledb.NUMBER)
array = self.cursor.arrayvar(cx_Oracle.NUMBER, array = self.cursor.arrayvar(oracledb.NUMBER,
[r[2] for r in self.rawData]) [r[2] for r in self.raw_data])
self.cursor.execute(""" self.cursor.execute("""
begin begin
:returnValue := pkg_TestNumberArrays.TestInArrays( :return_value := pkg_TestNumberArrays.TestInArrays(
:integerValue, :array); :integer_value, :array);
end;""", end;""",
returnValue = returnValue, return_value = return_value,
integerValue = 7, integer_value = 7,
array = array) array = array)
self.assertEqual(returnValue.getvalue(), 75.75) self.assertEqual(return_value.getvalue(), 75.75)
def test_2213_BindZeroLengthNumberArrayByVar(self): def test_2213_bind_zero_length_number_array_by_var(self):
"2213 - test binding in a zero length number array (with arrayvar)" "2213 - test binding in a zero length number array (with arrayvar)"
returnValue = self.cursor.var(cx_Oracle.NUMBER) return_value = self.cursor.var(oracledb.NUMBER)
array = self.cursor.arrayvar(cx_Oracle.NUMBER, 0) array = self.cursor.arrayvar(oracledb.NUMBER, 0)
self.cursor.execute(""" self.cursor.execute("""
begin begin
:returnValue := pkg_TestNumberArrays.TestInArrays( :return_value := pkg_TestNumberArrays.TestInArrays(
:integerValue, :array); :integer_value, :array);
end;""", end;""",
returnValue = returnValue, return_value=return_value,
integerValue = 8, integer_value=8,
array=array) array=array)
self.assertEqual(returnValue.getvalue(), 8.0) self.assertEqual(return_value.getvalue(), 8.0)
self.assertEqual(array.getvalue(), []) self.assertEqual(array.getvalue(), [])
def test_2214_BindInOutNumberArrayByVar(self): def test_2214_bind_in_out_number_array_by_var(self):
"2214 - test binding in/out a number array (with arrayvar)" "2214 - test binding in/out a number array (with arrayvar)"
array = self.cursor.arrayvar(cx_Oracle.NUMBER, 10) array = self.cursor.arrayvar(oracledb.NUMBER, 10)
originalData = [r[2] for r in self.rawData] original_data = [r[2] for r in self.raw_data]
expectedData = [originalData[i - 1] * 10 for i in range(1, 6)] + \ expected_data = [original_data[i - 1] * 10 for i in range(1, 6)] + \
originalData[5:] original_data[5:]
array.setvalue(0, originalData) array.setvalue(0, original_data)
self.cursor.execute(""" self.cursor.execute("""
begin begin
pkg_TestNumberArrays.TestInOutArrays(:numElems, :array); pkg_TestNumberArrays.TestInOutArrays(:num_elems, :array);
end;""", end;""",
numElems = 5, num_elems=5,
array=array) array=array)
self.assertEqual(array.getvalue(), expectedData) self.assertEqual(array.getvalue(), expected_data)
def test_2215_BindOutNumberArrayByVar(self): def test_2215_bind_out_number_array_by_var(self):
"2215 - test binding out a Number array (with arrayvar)" "2215 - test binding out a Number array (with arrayvar)"
array = self.cursor.arrayvar(cx_Oracle.NUMBER, 6) array = self.cursor.arrayvar(oracledb.NUMBER, 6)
expectedData = [i * 100 for i in range(1, 7)] expected_data = [i * 100 for i in range(1, 7)]
self.cursor.execute(""" self.cursor.execute("""
begin begin
pkg_TestNumberArrays.TestOutArrays(:numElems, :array); pkg_TestNumberArrays.TestOutArrays(:num_elems, :array);
end;""", end;""",
numElems = 6, num_elems=6,
array=array) array=array)
self.assertEqual(array.getvalue(), expectedData) self.assertEqual(array.getvalue(), expected_data)
def test_2216_BindOutSetInputSizes(self): def test_2216_bind_out_set_input_sizes(self):
"2216 - test binding out with set input sizes defined" "2216 - test binding out with set input sizes defined"
vars = self.cursor.setinputsizes(value = cx_Oracle.NUMBER) bind_vars = self.cursor.setinputsizes(value = oracledb.NUMBER)
self.cursor.execute(""" self.cursor.execute("""
begin begin
:value := 5; :value := 5;
end;""") end;""")
self.assertEqual(vars["value"].getvalue(), 5) self.assertEqual(bind_vars["value"].getvalue(), 5)
def test_2217_BindInOutSetInputSizes(self): def test_2217_bind_in_out_set_input_sizes(self):
"2217 - test binding in/out with set input sizes defined" "2217 - test binding in/out with set input sizes defined"
vars = self.cursor.setinputsizes(value = cx_Oracle.NUMBER) bind_vars = self.cursor.setinputsizes(value = oracledb.NUMBER)
self.cursor.execute(""" self.cursor.execute("""
begin begin
:value := :value + 5; :value := :value + 5;
end;""", end;""",
value = 1.25) value = 1.25)
self.assertEqual(vars["value"].getvalue(), 6.25) self.assertEqual(bind_vars["value"].getvalue(), 6.25)
def test_2218_BindOutVar(self): def test_2218_bind_out_var(self):
"2218 - test binding out with cursor.var() method" "2218 - test binding out with cursor.var() method"
var = self.cursor.var(cx_Oracle.NUMBER) var = self.cursor.var(oracledb.NUMBER)
self.cursor.execute(""" self.cursor.execute("""
begin begin
:value := 5; :value := 5;
@ -260,9 +258,9 @@ class TestCase(TestEnv.BaseTestCase):
value = var) value = var)
self.assertEqual(var.getvalue(), 5) self.assertEqual(var.getvalue(), 5)
def test_2219_BindInOutVarDirectSet(self): def test_2219_bind_in_out_var_direct_set(self):
"2219 - test binding in/out with cursor.var() method" "2219 - test binding in/out with cursor.var() method"
var = self.cursor.var(cx_Oracle.NUMBER) var = self.cursor.var(oracledb.NUMBER)
var.setvalue(0, 2.25) var.setvalue(0, 2.25)
self.cursor.execute(""" self.cursor.execute("""
begin begin
@ -271,47 +269,47 @@ class TestCase(TestEnv.BaseTestCase):
value = var) value = var)
self.assertEqual(var.getvalue(), 7.25) self.assertEqual(var.getvalue(), 7.25)
def test_2220_CursorDescription(self): def test_2220_cursor_description(self):
"2220 - test cursor description is accurate" "2220 - test cursor description is accurate"
self.cursor.execute("select * from TestNumbers") self.cursor.execute("select * from TestNumbers")
self.assertEqual(self.cursor.description, expected_value = [
[ ('INTCOL', cx_Oracle.DB_TYPE_NUMBER, 10, None, 9, 0, 0), ('INTCOL', oracledb.DB_TYPE_NUMBER, 10, None, 9, 0, 0),
('LONGINTCOL', cx_Oracle.DB_TYPE_NUMBER, 17, None, 16, 0, 0), ('LONGINTCOL', oracledb.DB_TYPE_NUMBER, 17, None, 16, 0, 0),
('NUMBERCOL', cx_Oracle.DB_TYPE_NUMBER, 13, None, 9, 2, 0), ('NUMBERCOL', oracledb.DB_TYPE_NUMBER, 13, None, 9, 2, 0),
('FLOATCOL', cx_Oracle.DB_TYPE_NUMBER, 127, None, 126, -127, ('FLOATCOL', oracledb.DB_TYPE_NUMBER, 127, None, 126, -127, 0),
('UNCONSTRAINEDCOL', oracledb.DB_TYPE_NUMBER, 127, None, 0, -127,
0), 0),
('UNCONSTRAINEDCOL', cx_Oracle.DB_TYPE_NUMBER, 127, None, 0, ('NULLABLECOL', oracledb.DB_TYPE_NUMBER, 39, None, 38, 0, 1)
-127, 0), ]
('NULLABLECOL', cx_Oracle.DB_TYPE_NUMBER, 39, None, 38, 0, self.assertEqual(self.cursor.description, expected_value)
1) ])
def test_2221_FetchAll(self): def test_2221_fetchall(self):
"2221 - test that fetching all of the data returns the correct results" "2221 - test that fetching all of the data returns the correct results"
self.cursor.execute("select * From TestNumbers order by IntCol") self.cursor.execute("select * From TestNumbers order by IntCol")
self.assertEqual(self.cursor.fetchall(), self.rawData) self.assertEqual(self.cursor.fetchall(), self.raw_data)
self.assertEqual(self.cursor.fetchall(), []) self.assertEqual(self.cursor.fetchall(), [])
def test_2222_FetchMany(self): def test_2222_fetchmany(self):
"2222 - test that fetching data in chunks returns the correct results" "2222 - test that fetching data in chunks returns the correct results"
self.cursor.execute("select * From TestNumbers order by IntCol") self.cursor.execute("select * From TestNumbers order by IntCol")
self.assertEqual(self.cursor.fetchmany(3), self.rawData[0:3]) self.assertEqual(self.cursor.fetchmany(3), self.raw_data[0:3])
self.assertEqual(self.cursor.fetchmany(2), self.rawData[3:5]) self.assertEqual(self.cursor.fetchmany(2), self.raw_data[3:5])
self.assertEqual(self.cursor.fetchmany(4), self.rawData[5:9]) self.assertEqual(self.cursor.fetchmany(4), self.raw_data[5:9])
self.assertEqual(self.cursor.fetchmany(3), self.rawData[9:]) self.assertEqual(self.cursor.fetchmany(3), self.raw_data[9:])
self.assertEqual(self.cursor.fetchmany(3), []) self.assertEqual(self.cursor.fetchmany(3), [])
def test_2223_FetchOne(self): def test_2223_fetchone(self):
"2223 - test that fetching a single row returns the correct results" "2223 - test that fetching a single row returns the correct results"
self.cursor.execute(""" self.cursor.execute("""
select * select *
from TestNumbers from TestNumbers
where IntCol in (3, 4) where IntCol in (3, 4)
order by IntCol""") order by IntCol""")
self.assertEqual(self.cursor.fetchone(), self.dataByKey[3]) self.assertEqual(self.cursor.fetchone(), self.data_by_key[3])
self.assertEqual(self.cursor.fetchone(), self.dataByKey[4]) self.assertEqual(self.cursor.fetchone(), self.data_by_key[4])
self.assertEqual(self.cursor.fetchone(), None) self.assertEqual(self.cursor.fetchone(), None)
def test_2224_ReturnAsLong(self): def test_2224_return_as_long(self):
"2224 - test that fetching a long integer returns such in Python" "2224 - test that fetching a long integer returns such in Python"
self.cursor.execute(""" self.cursor.execute("""
select NullableCol select NullableCol
@ -320,49 +318,48 @@ class TestCase(TestEnv.BaseTestCase):
col, = self.cursor.fetchone() col, = self.cursor.fetchone()
self.assertEqual(col, 25004854810776297743) self.assertEqual(col, 25004854810776297743)
def test_2225_ReturnConstantFloat(self): def test_2225_return_constant_float(self):
"2225 - test fetching a floating point number returns such in Python" "2225 - test fetching a floating point number returns such in Python"
self.cursor.execute("select 1.25 from dual") self.cursor.execute("select 1.25 from dual")
result, = self.cursor.fetchone() result, = self.cursor.fetchone()
self.assertEqual(result, 1.25) self.assertEqual(result, 1.25)
def test_2226_ReturnConstantInteger(self): def test_2226_return_constant_integer(self):
"2226 - test that fetching an integer returns such in Python" "2226 - test that fetching an integer returns such in Python"
self.cursor.execute("select 148 from dual") self.cursor.execute("select 148 from dual")
result, = self.cursor.fetchone() result, = self.cursor.fetchone()
self.assertEqual(result, 148) self.assertEqual(result, 148)
self.assertTrue(isinstance(result, int), "integer not returned") self.assertTrue(isinstance(result, int), "integer not returned")
def test_2227_AcceptableBoundaryNumbers(self): def test_2227_acceptable_boundary_numbers(self):
"2227 - test that acceptable boundary numbers are handled properly" "2227 - test that acceptable boundary numbers are handled properly"
inValues = [decimal.Decimal("9.99999999999999e+125"), in_values = [decimal.Decimal("9.99999999999999e+125"),
decimal.Decimal("-9.99999999999999e+125"), 0.0, 1e-130, decimal.Decimal("-9.99999999999999e+125"), 0.0, 1e-130,
-1e-130] -1e-130]
outValues = [int("9" * 15 + "0" * 111), -int("9" * 15 + "0" * 111), out_values = [int("9" * 15 + "0" * 111), -int("9" * 15 + "0" * 111),
0, 1e-130, -1e-130] 0, 1e-130, -1e-130]
for inValue, outValue in zip(inValues, outValues): for in_value, out_value in zip(in_values, out_values):
self.cursor.execute("select :1 from dual", (inValue,)) self.cursor.execute("select :1 from dual", (in_value,))
result, = self.cursor.fetchone() result, = self.cursor.fetchone()
self.assertEqual(result, outValue) self.assertEqual(result, out_value)
def test_2228_UnacceptableBoundaryNumbers(self): def test_2228_unacceptable_boundary_numbers(self):
"2228 - test that unacceptable boundary numbers are rejected" "2228 - test that unacceptable boundary numbers are rejected"
inValues = [1e126, -1e126, float("inf"), float("-inf"), in_values = [1e126, -1e126, float("inf"), float("-inf"),
float("NaN"), decimal.Decimal("1e126"), float("NaN"), decimal.Decimal("1e126"),
decimal.Decimal("-1e126"), decimal.Decimal("inf"), decimal.Decimal("-1e126"), decimal.Decimal("inf"),
decimal.Decimal("-inf"), decimal.Decimal("NaN")] decimal.Decimal("-inf"), decimal.Decimal("NaN")]
noRepErr = "DPI-1044: value cannot be represented as an Oracle number" no_rep_err = "value cannot be represented as an Oracle number"
invalidErr = "" invalid_err = "invalid number"
expectedErrors = [noRepErr, noRepErr, invalidErr, invalidErr, expected_errors = [no_rep_err, no_rep_err, invalid_err, invalid_err,
invalidErr, noRepErr, noRepErr, invalidErr, invalidErr, invalid_err, no_rep_err, no_rep_err, invalid_err,
invalidErr] invalid_err, invalid_err]
for inValue, error in zip(inValues, expectedErrors): for in_value, error in zip(in_values, expected_errors):
method = self.assertRaisesRegex if sys.version_info[0] == 3 \ self.assertRaisesRegex(oracledb.DatabaseError, error,
else self.assertRaisesRegexp self.cursor.execute, "select :1 from dual",
method(cx_Oracle.DatabaseError, error, self.cursor.execute, (in_value,))
"select :1 from dual", (inValue,))
def test_2229_ReturnFloatFromDivision(self): def test_2229_return_float_from_division(self):
"2229 - test that fetching the result of division returns a float" "2229 - test that fetching the result of division returns a float"
self.cursor.execute(""" self.cursor.execute("""
select IntCol / 7 select IntCol / 7
@ -372,41 +369,42 @@ class TestCase(TestEnv.BaseTestCase):
self.assertEqual(result, 1.0 / 7.0) self.assertEqual(result, 1.0 / 7.0)
self.assertTrue(isinstance(result, float), "float not returned") self.assertTrue(isinstance(result, float), "float not returned")
def test_2230_StringFormat(self): def test_2230_string_format(self):
"2230 - test that string format is returned properly" "2230 - test that string format is returned properly"
var = self.cursor.var(cx_Oracle.NUMBER) var = self.cursor.var(oracledb.NUMBER)
self.assertEqual(str(var), self.assertEqual(str(var),
"<cx_Oracle.Var of type DB_TYPE_NUMBER with value None>") "<cx_Oracle.Var of type DB_TYPE_NUMBER with value None>")
var.setvalue(0, 4) var.setvalue(0, 4)
self.assertEqual(str(var), self.assertEqual(str(var),
"<cx_Oracle.Var of type DB_TYPE_NUMBER with value 4.0>") "<cx_Oracle.Var of type DB_TYPE_NUMBER with value 4.0>")
def test_2231_BindNativeFloat(self): def test_2231_bind_binary_double(self):
"2231 - test that binding native float is possible" "2231 - test that binding binary double is possible"
self.cursor.setinputsizes(cx_Oracle.DB_TYPE_BINARY_DOUBLE) statement = "select :1 from dual"
self.cursor.execute("select :1 from dual", (5,)) self.cursor.setinputsizes(oracledb.DB_TYPE_BINARY_DOUBLE)
self.cursor.execute(statement, (5,))
self.assertEqual(self.cursor.bindvars[0].type, self.assertEqual(self.cursor.bindvars[0].type,
cx_Oracle.DB_TYPE_BINARY_DOUBLE) oracledb.DB_TYPE_BINARY_DOUBLE)
value, = self.cursor.fetchone() value, = self.cursor.fetchone()
self.assertEqual(value, 5) self.assertEqual(value, 5)
self.cursor.execute("select :1 from dual", (1.5,)) self.cursor.execute(statement, (1.5,))
self.assertEqual(self.cursor.bindvars[0].type, self.assertEqual(self.cursor.bindvars[0].type,
cx_Oracle.DB_TYPE_BINARY_DOUBLE) oracledb.DB_TYPE_BINARY_DOUBLE)
value, = self.cursor.fetchone() value, = self.cursor.fetchone()
self.assertEqual(value, 1.5) self.assertEqual(value, 1.5)
self.cursor.execute("select :1 from dual", (decimal.Decimal("NaN"),)) self.cursor.execute(statement, (decimal.Decimal("NaN"),))
self.assertEqual(self.cursor.bindvars[0].type, self.assertEqual(self.cursor.bindvars[0].type,
cx_Oracle.DB_TYPE_BINARY_DOUBLE) oracledb.DB_TYPE_BINARY_DOUBLE)
value, = self.cursor.fetchone() value, = self.cursor.fetchone()
self.assertEqual(str(value), str(float("NaN"))) self.assertEqual(str(value), str(float("NaN")))
def test_2232_FetchNativeInt(self): def test_2232_fetch_binary_int(self):
"2232 - test fetching numbers as native integers" "2232 - test fetching numbers as binary integers"
self.cursor.outputtypehandler = self.outputTypeHandlerNativeInt self.cursor.outputtypehandler = self.output_type_handler_binary_int
for value in (1, 2 ** 31, 2 ** 63 - 1, -1, -2 ** 31, -2 ** 63 + 1): for value in (1, 2 ** 31, 2 ** 63 - 1, -1, -2 ** 31, -2 ** 63 + 1):
self.cursor.execute("select :1 from dual", [str(value)]) self.cursor.execute("select :1 from dual", [str(value)])
fetchedValue, = self.cursor.fetchone() fetched_value, = self.cursor.fetchone()
self.assertEqual(value, fetchedValue) self.assertEqual(value, fetched_value)
if __name__ == "__main__": if __name__ == "__main__":
TestEnv.RunTestCases() base.run_test_cases()

View File

@ -11,63 +11,62 @@
2300 - Module for testing object variables 2300 - Module for testing object variables
""" """
import TestEnv import base
import cx_Oracle import cx_Oracle as oracledb
import datetime import datetime
import decimal import decimal
class TestCase(TestEnv.BaseTestCase): class TestCase(base.BaseTestCase):
def __GetObjectAsTuple(self, obj): def __get_object_as_tuple(self, obj):
if obj.type.iscollection: if obj.type.iscollection:
value = [] value = []
for v in obj.aslist(): for v in obj.aslist():
if isinstance(v, cx_Oracle.Object): if isinstance(v, oracledb.Object):
v = self.__GetObjectAsTuple(v) v = self.__get_object_as_tuple(v)
elif isinstance(value, cx_Oracle.LOB): elif isinstance(value, oracledb.LOB):
v = v.read() v = v.read()
value.append(v) value.append(v)
return value return value
attributeValues = [] attribute_values = []
for attribute in obj.type.attributes: for attribute in obj.type.attributes:
value = getattr(obj, attribute.name) value = getattr(obj, attribute.name)
if isinstance(value, cx_Oracle.Object): if isinstance(value, oracledb.Object):
value = self.__GetObjectAsTuple(value) value = self.__get_object_as_tuple(value)
elif isinstance(value, cx_Oracle.LOB): elif isinstance(value, oracledb.LOB):
value = value.read() value = value.read()
attributeValues.append(value) attribute_values.append(value)
return tuple(attributeValues) return tuple(attribute_values)
def __TestData(self, expectedIntValue, expectedObjectValue, def __test_data(self, expected_int_value, expected_obj_value,
expectedArrayValue): expected_array_value):
intValue, objectValue, arrayValue = self.cursor.fetchone() int_value, object_value, array_value = self.cursor.fetchone()
if objectValue is not None: if object_value is not None:
objectValue = self.__GetObjectAsTuple(objectValue) object_value = self.__get_object_as_tuple(object_value)
if arrayValue is not None: if array_value is not None:
arrayValue = arrayValue.aslist() array_value = array_value.aslist()
self.assertEqual(intValue, expectedIntValue) self.assertEqual(int_value, expected_int_value)
self.assertEqual(objectValue, expectedObjectValue) self.assertEqual(object_value, expected_obj_value)
self.assertEqual(arrayValue, expectedArrayValue) self.assertEqual(array_value, expected_array_value)
def test_2300_BindNullIn(self): def test_2300_bind_null_in(self):
"2300 - test binding a null value (IN)" "2300 - test binding a null value (IN)"
var = self.cursor.var(cx_Oracle.DB_TYPE_OBJECT, var = self.cursor.var(oracledb.DB_TYPE_OBJECT, typename="UDT_OBJECT")
typename = "UDT_OBJECT")
result = self.cursor.callfunc("pkg_TestBindObject.GetStringRep", str, result = self.cursor.callfunc("pkg_TestBindObject.GetStringRep", str,
(var,)) (var,))
self.assertEqual(result, "null") self.assertEqual(result, "null")
def test_2301_BindObjectIn(self): def test_2301_bind_object_in(self):
"2301 - test binding an object (IN)" "2301 - test binding an object (IN)"
typeObj = self.connection.gettype("UDT_OBJECT") type_obj = self.connection.gettype("UDT_OBJECT")
obj = typeObj.newobject() obj = type_obj.newobject()
obj.NUMBERVALUE = 13 obj.NUMBERVALUE = 13
obj.STRINGVALUE = "Test String" obj.STRINGVALUE = "Test String"
result = self.cursor.callfunc("pkg_TestBindObject.GetStringRep", str, result = self.cursor.callfunc("pkg_TestBindObject.GetStringRep", str,
(obj,)) (obj,))
self.assertEqual(result, exp = "udt_Object(13, 'Test String', null, null, null, null, null)"
"udt_Object(13, 'Test String', null, null, null, null, null)") self.assertEqual(result, exp)
obj.NUMBERVALUE = None obj.NUMBERVALUE = None
obj.STRINGVALUE = "Test With Dates" obj.STRINGVALUE = "Test With Dates"
obj.DATEVALUE = datetime.datetime(2016, 2, 10) obj.DATEVALUE = datetime.datetime(2016, 2, 10)
@ -82,39 +81,38 @@ class TestCase(TestEnv.BaseTestCase):
"null, null)") "null, null)")
obj.DATEVALUE = None obj.DATEVALUE = None
obj.TIMESTAMPVALUE = None obj.TIMESTAMPVALUE = None
subTypeObj = self.connection.gettype("UDT_SUBOBJECT") sub_type_obj = self.connection.gettype("UDT_SUBOBJECT")
subObj = subTypeObj.newobject() sub_obj = sub_type_obj.newobject()
subObj.SUBNUMBERVALUE = decimal.Decimal("18.25") sub_obj.SUBNUMBERVALUE = decimal.Decimal("18.25")
subObj.SUBSTRINGVALUE = "Sub String" sub_obj.SUBSTRINGVALUE = "Sub String"
obj.SUBOBJECTVALUE = subObj obj.SUBOBJECTVALUE = sub_obj
result = self.cursor.callfunc("pkg_TestBindObject.GetStringRep", str, result = self.cursor.callfunc("pkg_TestBindObject.GetStringRep", str,
(obj,)) (obj,))
self.assertEqual(result, self.assertEqual(result,
"udt_Object(null, 'Test With Dates', null, null, null, " \ "udt_Object(null, 'Test With Dates', null, null, " \
"udt_SubObject(18.25, 'Sub String'), null)") "null, udt_SubObject(18.25, 'Sub String'), null)")
def test_2302_CopyObject(self): def test_2302_copy_object(self):
"2302 - test copying an object" "2302 - test copying an object"
typeObj = self.connection.gettype("UDT_OBJECT") type_obj = self.connection.gettype("UDT_OBJECT")
obj = typeObj() obj = type_obj()
obj.NUMBERVALUE = 5124 obj.NUMBERVALUE = 5124
obj.STRINGVALUE = "A test string" obj.STRINGVALUE = "A test string"
obj.DATEVALUE = datetime.datetime(2016, 2, 24) obj.DATEVALUE = datetime.datetime(2016, 2, 24)
obj.TIMESTAMPVALUE = datetime.datetime(2016, 2, 24, 13, 39, 10) obj.TIMESTAMPVALUE = datetime.datetime(2016, 2, 24, 13, 39, 10)
copiedObj = obj.copy() copied_obj = obj.copy()
self.assertEqual(obj.NUMBERVALUE, copiedObj.NUMBERVALUE) self.assertEqual(obj.NUMBERVALUE, copied_obj.NUMBERVALUE)
self.assertEqual(obj.STRINGVALUE, copiedObj.STRINGVALUE) self.assertEqual(obj.STRINGVALUE, copied_obj.STRINGVALUE)
self.assertEqual(obj.DATEVALUE, copiedObj.DATEVALUE) self.assertEqual(obj.DATEVALUE, copied_obj.DATEVALUE)
self.assertEqual(obj.TIMESTAMPVALUE, copiedObj.TIMESTAMPVALUE) self.assertEqual(obj.TIMESTAMPVALUE, copied_obj.TIMESTAMPVALUE)
def test_2303_EmptyCollectionAsList(self): def test_2303_empty_collection_as_list(self):
"2303 - test getting an empty collection as a list" "2303 - test getting an empty collection as a list"
typeName = "UDT_ARRAY" type_obj = self.connection.gettype("UDT_ARRAY")
typeObj = self.connection.gettype(typeName) obj = type_obj.newobject()
obj = typeObj.newobject()
self.assertEqual(obj.aslist(), []) self.assertEqual(obj.aslist(), [])
def test_2304_FetchData(self): def test_2304_fetch_data(self):
"2304 - test fetching objects" "2304 - test fetching objects"
self.cursor.execute("alter session set time_zone = 'UTC'") self.cursor.execute("alter session set time_zone = 'UTC'")
self.cursor.execute(""" self.cursor.execute("""
@ -124,84 +122,145 @@ class TestCase(TestEnv.BaseTestCase):
ArrayCol ArrayCol
from TestObjects from TestObjects
order by IntCol""") order by IntCol""")
self.assertEqual(self.cursor.description, expected_value = [
[ ('INTCOL', cx_Oracle.DB_TYPE_NUMBER, 10, None, 9, 0, 0), ('INTCOL', oracledb.DB_TYPE_NUMBER, 10, None, 9, 0, 0),
('OBJECTCOL', cx_Oracle.DB_TYPE_OBJECT, None, None, None, ('OBJECTCOL', oracledb.DB_TYPE_OBJECT, None, None, None, None, 1),
None, 1), ('ARRAYCOL', oracledb.DB_TYPE_OBJECT, None, None, None, None, 1)
('ARRAYCOL', cx_Oracle.DB_TYPE_OBJECT, None, None, None, ]
None, 1) ]) self.assertEqual(self.cursor.description, expected_value)
self.__TestData(1, (1, 'First row', 'First ', 'N First Row', expected_value = (
'N First ', b'Raw Data 1', 2, 5, 12.125, 0.5, 12.5, 25.25, 1,
50.125, cx_Oracle.Timestamp(2007, 3, 6, 0, 0, 0), 'First row',
cx_Oracle.Timestamp(2008, 9, 12, 16, 40), 'First ',
cx_Oracle.Timestamp(2009, 10, 13, 17, 50), 'N First Row',
cx_Oracle.Timestamp(2010, 11, 14, 18, 55), 'N First ',
'Short CLOB value', 'Short NCLOB Value', b'Short BLOB value', b'Raw Data 1',
2,
5,
12.125,
0.5,
12.5,
25.25,
50.125,
oracledb.Timestamp(2007, 3, 6, 0, 0, 0),
oracledb.Timestamp(2008, 9, 12, 16, 40),
oracledb.Timestamp(2009, 10, 13, 17, 50),
oracledb.Timestamp(2010, 11, 14, 18, 55),
'Short CLOB value',
'Short NCLOB Value',
b'Short BLOB value',
(11, 'Sub object 1'), (11, 'Sub object 1'),
[(5, 'first element'), (6, 'second element')]), [(5, 'first element'), (6, 'second element')]
[5, 10, None, 20]) )
self.__TestData(2, None, [3, None, 9, 12, 15]) self.__test_data(1, expected_value, [5, 10, None, 20])
self.__TestData(3, (3, 'Third row', 'Third ', 'N Third Row', self.__test_data(2, None, [3, None, 9, 12, 15])
'N Third ', b'Raw Data 3', 4, 10, 6.5, 0.75, 43.25, 86.5, expected_value = (
192.125, cx_Oracle.Timestamp(2007, 6, 21, 0, 0, 0), 3,
cx_Oracle.Timestamp(2007, 12, 13, 7, 30, 45), 'Third row',
cx_Oracle.Timestamp(2017, 6, 21, 23, 18, 45), 'Third ',
cx_Oracle.Timestamp(2017, 7, 21, 8, 27, 13), 'N Third Row',
'Another short CLOB value', 'Another short NCLOB Value', 'N Third ',
b'Raw Data 3',
4,
10,
6.5,
0.75,
43.25,
86.5,
192.125,
oracledb.Timestamp(2007, 6, 21, 0, 0, 0),
oracledb.Timestamp(2007, 12, 13, 7, 30, 45),
oracledb.Timestamp(2017, 6, 21, 23, 18, 45),
oracledb.Timestamp(2017, 7, 21, 8, 27, 13),
'Another short CLOB value',
'Another short NCLOB Value',
b'Yet another short BLOB value', b'Yet another short BLOB value',
(13, 'Sub object 3'), (13, 'Sub object 3'),
[(10, 'element #1'), (20, 'element #2'), [
(30, 'element #3'), (40, 'element #4')]), None) (10, 'element #1'),
(20, 'element #2'),
(30, 'element #3'),
(40, 'element #4')
]
)
self.__test_data(3, expected_value, None)
def test_2305_GetObjectType(self): def test_2305_get_object_type(self):
"2305 - test getting object type" "2305 - test getting object type"
typeObj = self.connection.gettype("UDT_OBJECT") type_obj = self.connection.gettype("UDT_OBJECT")
self.assertEqual(typeObj.iscollection, False) self.assertEqual(type_obj.iscollection, False)
self.assertEqual(typeObj.schema, self.connection.username.upper()) self.assertEqual(type_obj.schema, self.connection.username.upper())
self.assertEqual(typeObj.name, "UDT_OBJECT") self.assertEqual(type_obj.name, "UDT_OBJECT")
subObjectValueType = self.connection.gettype("UDT_SUBOBJECT") sub_object_value_type = self.connection.gettype("UDT_SUBOBJECT")
subObjectArrayType = self.connection.gettype("UDT_OBJECTARRAY") sub_object_array_type = self.connection.gettype("UDT_OBJECTARRAY")
expectedAttributeNames = ["NUMBERVALUE", "STRINGVALUE", expected_attr_names = [
"FIXEDCHARVALUE", "NSTRINGVALUE", "NFIXEDCHARVALUE", "NUMBERVALUE",
"RAWVALUE", "INTVALUE", "SMALLINTVALUE", "REALVALUE", "STRINGVALUE",
"DOUBLEPRECISIONVALUE", "FLOATVALUE", "BINARYFLOATVALUE", "FIXEDCHARVALUE",
"BINARYDOUBLEVALUE", "DATEVALUE", "TIMESTAMPVALUE", "NSTRINGVALUE",
"TIMESTAMPTZVALUE", "TIMESTAMPLTZVALUE", "CLOBVALUE", "NFIXEDCHARVALUE",
"NCLOBVALUE", "BLOBVALUE", "SUBOBJECTVALUE", "SUBOBJECTARRAY"] "RAWVALUE",
actualAttributeNames = [a.name for a in typeObj.attributes] "INTVALUE",
self.assertEqual(actualAttributeNames, expectedAttributeNames) "SMALLINTVALUE",
expectedAttributeTypes = [cx_Oracle.DB_TYPE_NUMBER, "REALVALUE",
cx_Oracle.DB_TYPE_VARCHAR, cx_Oracle.DB_TYPE_CHAR, "DOUBLEPRECISIONVALUE",
cx_Oracle.DB_TYPE_NVARCHAR, cx_Oracle.DB_TYPE_NCHAR, "FLOATVALUE",
cx_Oracle.DB_TYPE_RAW, cx_Oracle.DB_TYPE_NUMBER, "BINARYFLOATVALUE",
cx_Oracle.DB_TYPE_NUMBER, cx_Oracle.DB_TYPE_NUMBER, "BINARYDOUBLEVALUE",
cx_Oracle.DB_TYPE_NUMBER, cx_Oracle.DB_TYPE_NUMBER, "DATEVALUE",
cx_Oracle.DB_TYPE_BINARY_FLOAT, "TIMESTAMPVALUE",
cx_Oracle.DB_TYPE_BINARY_DOUBLE, "TIMESTAMPTZVALUE",
cx_Oracle.DB_TYPE_DATE, cx_Oracle.DB_TYPE_TIMESTAMP, "TIMESTAMPLTZVALUE",
cx_Oracle.DB_TYPE_TIMESTAMP_TZ, "CLOBVALUE",
cx_Oracle.DB_TYPE_TIMESTAMP_LTZ, cx_Oracle.DB_TYPE_CLOB, "NCLOBVALUE",
cx_Oracle.DB_TYPE_NCLOB, cx_Oracle.DB_TYPE_BLOB, "BLOBVALUE",
subObjectValueType, subObjectArrayType] "SUBOBJECTVALUE",
actualAttributeTypes = [a.type for a in typeObj.attributes] "SUBOBJECTARRAY"
self.assertEqual(actualAttributeTypes, expectedAttributeTypes) ]
self.assertEqual(subObjectArrayType.iscollection, True) actual_attr_names = [a.name for a in type_obj.attributes]
self.assertEqual(subObjectArrayType.attributes, []) self.assertEqual(actual_attr_names, expected_attr_names)
expected_attr_types = [
oracledb.DB_TYPE_NUMBER,
oracledb.DB_TYPE_VARCHAR,
oracledb.DB_TYPE_CHAR,
oracledb.DB_TYPE_NVARCHAR,
oracledb.DB_TYPE_NCHAR,
oracledb.DB_TYPE_RAW,
oracledb.DB_TYPE_NUMBER,
oracledb.DB_TYPE_NUMBER,
oracledb.DB_TYPE_NUMBER,
oracledb.DB_TYPE_NUMBER,
oracledb.DB_TYPE_NUMBER,
oracledb.DB_TYPE_BINARY_FLOAT,
oracledb.DB_TYPE_BINARY_DOUBLE,
oracledb.DB_TYPE_DATE,
oracledb.DB_TYPE_TIMESTAMP,
oracledb.DB_TYPE_TIMESTAMP_TZ,
oracledb.DB_TYPE_TIMESTAMP_LTZ,
oracledb.DB_TYPE_CLOB,
oracledb.DB_TYPE_NCLOB,
oracledb.DB_TYPE_BLOB,
sub_object_value_type,
sub_object_array_type
]
actual_attr_types = [a.type for a in type_obj.attributes]
self.assertEqual(actual_attr_types, expected_attr_types)
self.assertEqual(sub_object_array_type.iscollection, True)
self.assertEqual(sub_object_array_type.attributes, [])
def test_2306_ObjectType(self): def test_2306_object_type(self):
"2306 - test object type data" "2306 - test object type data"
self.cursor.execute(""" self.cursor.execute("""
select ObjectCol select ObjectCol
from TestObjects from TestObjects
where ObjectCol is not null where ObjectCol is not null
and rownum <= 1""") and rownum <= 1""")
objValue, = self.cursor.fetchone() obj, = self.cursor.fetchone()
self.assertEqual(objValue.type.schema, self.assertEqual(obj.type.schema, self.connection.username.upper())
self.connection.username.upper()) self.assertEqual(obj.type.name, "UDT_OBJECT")
self.assertEqual(objValue.type.name, "UDT_OBJECT") self.assertEqual(obj.type.attributes[0].name, "NUMBERVALUE")
self.assertEqual(objValue.type.attributes[0].name, "NUMBERVALUE")
def test_2307_RoundTripObject(self): def test_2307_round_trip_object(self):
"2307 - test inserting and then querying object with all data types" "2307 - test inserting and then querying object with all data types"
self.cursor.execute("alter session set time_zone = 'UTC'") self.cursor.execute("alter session set time_zone = 'UTC'")
self.cursor.execute("truncate table TestClobs") self.cursor.execute("truncate table TestClobs")
@ -220,8 +279,8 @@ class TestCase(TestEnv.BaseTestCase):
nclob, = self.cursor.fetchone() nclob, = self.cursor.fetchone()
self.cursor.execute("select BLOBCol from TestBlobs") self.cursor.execute("select BLOBCol from TestBlobs")
blob, = self.cursor.fetchone() blob, = self.cursor.fetchone()
typeObj = self.connection.gettype("UDT_OBJECT") type_obj = self.connection.gettype("UDT_OBJECT")
obj = typeObj.newobject() obj = type_obj.newobject()
obj.NUMBERVALUE = 5 obj.NUMBERVALUE = 5
obj.STRINGVALUE = "A string" obj.STRINGVALUE = "A string"
obj.FIXEDCHARVALUE = "Fixed str" obj.FIXEDCHARVALUE = "Fixed str"
@ -242,25 +301,42 @@ class TestCase(TestEnv.BaseTestCase):
obj.CLOBVALUE = clob obj.CLOBVALUE = clob
obj.NCLOBVALUE = nclob obj.NCLOBVALUE = nclob
obj.BLOBVALUE = blob obj.BLOBVALUE = blob
subTypeObj = self.connection.gettype("UDT_SUBOBJECT") sub_type_obj = self.connection.gettype("UDT_SUBOBJECT")
subObj = subTypeObj.newobject() sub_obj = sub_type_obj.newobject()
subObj.SUBNUMBERVALUE = 23 sub_obj.SUBNUMBERVALUE = 23
subObj.SUBSTRINGVALUE = "Substring value" sub_obj.SUBSTRINGVALUE = "Substring value"
obj.SUBOBJECTVALUE = subObj obj.SUBOBJECTVALUE = sub_obj
self.cursor.execute("insert into TestObjects (IntCol, ObjectCol) " \ self.cursor.execute("insert into TestObjects (IntCol, ObjectCol) " \
"values (4, :obj)", obj = obj) "values (4, :obj)", obj = obj)
self.cursor.execute(""" self.cursor.execute("""
select IntCol, ObjectCol, ArrayCol select IntCol, ObjectCol, ArrayCol
from TestObjects from TestObjects
where IntCol = 4""") where IntCol = 4""")
self.__TestData(4, (5, 'A string', 'Fixed str ', 'A NCHAR string', expected_value = (
'Fixed N ', b'Raw Value', 27, 13, 184.875, 1.375, 23.75, 5,
14.25, 29.1625, cx_Oracle.Timestamp(2017, 5, 9, 0, 0, 0), 'A string',
cx_Oracle.Timestamp(2017, 5, 9, 9, 41, 13), 'Fixed str ',
cx_Oracle.Timestamp(1986, 8, 2, 15, 27, 38), 'A NCHAR string',
cx_Oracle.Timestamp(1999, 11, 12, 23, 5, 2), 'Fixed N ',
'A short CLOB', 'A short NCLOB', b'A short BLOB', b'Raw Value',
(23, 'Substring value'), None), None) 27,
13,
184.875,
1.375,
23.75,
14.25,
29.1625,
oracledb.Timestamp(2017, 5, 9, 0, 0, 0),
oracledb.Timestamp(2017, 5, 9, 9, 41, 13),
oracledb.Timestamp(1986, 8, 2, 15, 27, 38),
oracledb.Timestamp(1999, 11, 12, 23, 5, 2),
'A short CLOB',
'A short NCLOB',
b'A short BLOB',
(23, 'Substring value'),
None
)
self.__test_data(4, expected_value, None)
obj.CLOBVALUE = "A short CLOB (modified)" obj.CLOBVALUE = "A short CLOB (modified)"
obj.NCLOBVALUE = "A short NCLOB (modified)" obj.NCLOBVALUE = "A short NCLOB (modified)"
obj.BLOBVALUE = "A short BLOB (modified)" obj.BLOBVALUE = "A short BLOB (modified)"
@ -270,106 +346,121 @@ class TestCase(TestEnv.BaseTestCase):
select IntCol, ObjectCol, ArrayCol select IntCol, ObjectCol, ArrayCol
from TestObjects from TestObjects
where IntCol = 5""") where IntCol = 5""")
self.__TestData(5, (5, 'A string', 'Fixed str ', 'A NCHAR string', expected_value = (
'Fixed N ', b'Raw Value', 27, 13, 184.875, 1.375, 23.75, 5,
14.25, 29.1625, cx_Oracle.Timestamp(2017, 5, 9, 0, 0, 0), 'A string',
cx_Oracle.Timestamp(2017, 5, 9, 9, 41, 13), 'Fixed str ',
cx_Oracle.Timestamp(1986, 8, 2, 15, 27, 38), 'A NCHAR string',
cx_Oracle.Timestamp(1999, 11, 12, 23, 5, 2), 'Fixed N ',
'A short CLOB (modified)', 'A short NCLOB (modified)', b'Raw Value',
27,
13,
184.875,
1.375,
23.75,
14.25,
29.1625,
oracledb.Timestamp(2017, 5, 9, 0, 0, 0),
oracledb.Timestamp(2017, 5, 9, 9, 41, 13),
oracledb.Timestamp(1986, 8, 2, 15, 27, 38),
oracledb.Timestamp(1999, 11, 12, 23, 5, 2),
'A short CLOB (modified)',
'A short NCLOB (modified)',
b'A short BLOB (modified)', b'A short BLOB (modified)',
(23, 'Substring value'), None), None) (23, 'Substring value'),
None
)
self.__test_data(5, expected_value, None)
self.connection.rollback() self.connection.rollback()
def test_2308_InvalidTypeObject(self): def test_2308_invalid_type_object(self):
"2308 - test trying to find an object type that does not exist" "2308 - test trying to find an object type that does not exist"
self.assertRaises(cx_Oracle.DatabaseError, self.connection.gettype, self.assertRaises(oracledb.DatabaseError, self.connection.gettype,
"A TYPE THAT DOES NOT EXIST") "A TYPE THAT DOES NOT EXIST")
def test_2309_AppendingWrongObjectType(self): def test_2309_appending_wrong_object_type(self):
"2309 - test appending an object of the wrong type to a collection" "2309 - test appending an object of the wrong type to a collection"
collectionObjType = self.connection.gettype("UDT_OBJECTARRAY") collection_obj_type = self.connection.gettype("UDT_OBJECTARRAY")
collectionObj = collectionObjType.newobject() collection_obj = collection_obj_type.newobject()
arrayObjType = self.connection.gettype("UDT_ARRAY") array_obj_type = self.connection.gettype("UDT_ARRAY")
arrayObj = arrayObjType.newobject() array_obj = array_obj_type.newobject()
self.assertRaises(cx_Oracle.DatabaseError, collectionObj.append, self.assertRaises(oracledb.DatabaseError, collection_obj.append,
arrayObj) array_obj)
def test_2310_ReferencingSubObj(self): def test_2310_referencing_sub_obj(self):
"2310 - test that referencing a sub object affects the parent object" "2310 - test that referencing a sub object affects the parent object"
objType = self.connection.gettype("UDT_OBJECT") obj_type = self.connection.gettype("UDT_OBJECT")
subObjType = self.connection.gettype("UDT_SUBOBJECT") sub_obj_type = self.connection.gettype("UDT_SUBOBJECT")
obj = objType.newobject() obj = obj_type.newobject()
obj.SUBOBJECTVALUE = subObjType.newobject() obj.SUBOBJECTVALUE = sub_obj_type.newobject()
obj.SUBOBJECTVALUE.SUBNUMBERVALUE = 5 obj.SUBOBJECTVALUE.SUBNUMBERVALUE = 5
obj.SUBOBJECTVALUE.SUBSTRINGVALUE = "Substring" obj.SUBOBJECTVALUE.SUBSTRINGVALUE = "Substring"
self.assertEqual(obj.SUBOBJECTVALUE.SUBNUMBERVALUE, 5) self.assertEqual(obj.SUBOBJECTVALUE.SUBNUMBERVALUE, 5)
self.assertEqual(obj.SUBOBJECTVALUE.SUBSTRINGVALUE, "Substring") self.assertEqual(obj.SUBOBJECTVALUE.SUBSTRINGVALUE, "Substring")
def test_2311_AccessSubObjectParentObjectDestroyed(self): def test_2311_access_sub_object_parent_object_destroyed(self):
"2311 - test accessing sub object after parent object destroyed" "2311 - test accessing sub object after parent object destroyed"
objType = self.connection.gettype("UDT_OBJECT") obj_type = self.connection.gettype("UDT_OBJECT")
subObjType = self.connection.gettype("UDT_SUBOBJECT") sub_obj_type = self.connection.gettype("UDT_SUBOBJECT")
arrayType = self.connection.gettype("UDT_OBJECTARRAY") array_type = self.connection.gettype("UDT_OBJECTARRAY")
subObj1 = subObjType.newobject() sub_obj1 = sub_obj_type.newobject()
subObj1.SUBNUMBERVALUE = 2 sub_obj1.SUBNUMBERVALUE = 2
subObj1.SUBSTRINGVALUE = "AB" sub_obj1.SUBSTRINGVALUE = "AB"
subObj2 = subObjType.newobject() sub_obj2 = sub_obj_type.newobject()
subObj2.SUBNUMBERVALUE = 3 sub_obj2.SUBNUMBERVALUE = 3
subObj2.SUBSTRINGVALUE = "CDE" sub_obj2.SUBSTRINGVALUE = "CDE"
obj = objType.newobject() obj = obj_type.newobject()
obj.SUBOBJECTARRAY = arrayType.newobject([subObj1, subObj2]) obj.SUBOBJECTARRAY = array_type.newobject([sub_obj1, sub_obj2])
subObjArray = obj.SUBOBJECTARRAY sub_obj_array = obj.SUBOBJECTARRAY
del obj del obj
self.assertEqual(self.__GetObjectAsTuple(subObjArray), self.assertEqual(self.__get_object_as_tuple(sub_obj_array),
[(2, "AB"), (3, "CDE")]) [(2, "AB"), (3, "CDE")])
def test_2312_SettingAttrWrongObjectType(self): def test_2312_setting_attr_wrong_object_type(self):
"2312 - test assigning an object of wrong type to an object attribute" "2312 - test assigning an object of wrong type to an object attribute"
objType = self.connection.gettype("UDT_OBJECT") obj_type = self.connection.gettype("UDT_OBJECT")
obj = objType.newobject() obj = obj_type.newobject()
wrongObjType = self.connection.gettype("UDT_OBJECTARRAY") wrong_obj_type = self.connection.gettype("UDT_OBJECTARRAY")
wrongObj = wrongObjType.newobject() wrong_obj = wrong_obj_type.newobject()
self.assertRaises(cx_Oracle.DatabaseError, setattr, obj, self.assertRaises(oracledb.DatabaseError, setattr, obj,
"SUBOBJECTVALUE", wrongObj) "SUBOBJECTVALUE", wrong_obj)
def test_2313_SettingVarWrongObjectType(self): def test_2313_setting_var_wrong_object_type(self):
"2313 - test setting value of object variable to wrong object type" "2313 - test setting value of object variable to wrong object type"
wrongObjType = self.connection.gettype("UDT_OBJECTARRAY") wrong_obj_type = self.connection.gettype("UDT_OBJECTARRAY")
wrongObj = wrongObjType.newobject() wrong_obj = wrong_obj_type.newobject()
var = self.cursor.var(cx_Oracle.DB_TYPE_OBJECT, var = self.cursor.var(oracledb.DB_TYPE_OBJECT, typename="UDT_OBJECT")
typename = "UDT_OBJECT") self.assertRaises(oracledb.DatabaseError, var.setvalue, 0, wrong_obj)
self.assertRaises(cx_Oracle.DatabaseError, var.setvalue, 0, wrongObj)
def test_2314_StringFormat(self): def test_2314_string_format(self):
"2314 - test object string format" "2314 - test object string format"
objType = self.connection.gettype("UDT_OBJECT") obj_type = self.connection.gettype("UDT_OBJECT")
user = TestEnv.GetMainUser() user = base.get_main_user()
self.assertEqual(str(objType), self.assertEqual(str(obj_type),
"<cx_Oracle.ObjectType %s.UDT_OBJECT>" % user.upper()) "<cx_Oracle.ObjectType %s.UDT_OBJECT>" % user.upper())
self.assertEqual(str(objType.attributes[0]), self.assertEqual(str(obj_type.attributes[0]),
"<cx_Oracle.ObjectAttribute NUMBERVALUE>") "<cx_Oracle.ObjectAttribute NUMBERVALUE>")
def test_2315_TrimCollectionList(self): def test_2315_trim_collection_list(self):
"2315 - test Trim number of elements from collection" "2315 - test Trim number of elements from collection"
subObjType = self.connection.gettype("UDT_SUBOBJECT") sub_obj_type = self.connection.gettype("UDT_SUBOBJECT")
arrayType = self.connection.gettype("UDT_OBJECTARRAY") array_type = self.connection.gettype("UDT_OBJECTARRAY")
data = [(1, "AB"), (2, "CDE"), (3, "FGH"), (4, "IJK")] data = [(1, "AB"), (2, "CDE"), (3, "FGH"), (4, "IJK")]
arrayObj = arrayType() array_obj = array_type()
for numVal, strVal in data: for num_val, str_val in data:
subObj = subObjType() subObj = sub_obj_type()
subObj.SUBNUMBERVALUE = numVal subObj.SUBNUMBERVALUE = num_val
subObj.SUBSTRINGVALUE = strVal subObj.SUBSTRINGVALUE = str_val
arrayObj.append(subObj) array_obj.append(subObj)
self.assertEqual(self.__GetObjectAsTuple(arrayObj), data) self.assertEqual(self.__get_object_as_tuple(array_obj), data)
arrayObj.trim(2) array_obj.trim(2)
self.assertEqual(self.__GetObjectAsTuple(arrayObj), data[:2]) self.assertEqual(self.__get_object_as_tuple(array_obj), data[:2])
arrayObj.trim(1) array_obj.trim(1)
self.assertEqual(self.__GetObjectAsTuple(arrayObj), data[:1]) self.assertEqual(self.__get_object_as_tuple(array_obj), data[:1])
arrayObj.trim(0) array_obj.trim(0)
self.assertEqual(self.__GetObjectAsTuple(arrayObj), data[:1]) self.assertEqual(self.__get_object_as_tuple(array_obj), data[:1])
arrayObj.trim(1) array_obj.trim(1)
self.assertEqual(self.__GetObjectAsTuple(arrayObj), []) self.assertEqual(self.__get_object_as_tuple(array_obj), [])
if __name__ == "__main__": if __name__ == "__main__":
TestEnv.RunTestCases() base.run_test_cases()

View File

@ -11,56 +11,49 @@
2400 - Module for testing session pools 2400 - Module for testing session pools
""" """
import TestEnv import base
import cx_Oracle import cx_Oracle as oracledb
import threading import threading
class TestCase(TestEnv.BaseTestCase): class TestCase(base.BaseTestCase):
require_connection = False
def __ConnectAndDrop(self): def __connect_and_drop(self):
"""Connect to the database, perform a query and drop the connection."""
connection = self.pool.acquire() connection = self.pool.acquire()
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute("select count(*) from TestNumbers") cursor.execute("select count(*) from TestNumbers")
count, = cursor.fetchone() count, = cursor.fetchone()
self.assertEqual(count, 10) self.assertEqual(count, 10)
def __ConnectAndGenerateError(self): def __connect_and_generate_error(self):
"""Connect to the database, perform a query which raises an error"""
connection = self.pool.acquire() connection = self.pool.acquire()
cursor = connection.cursor() cursor = connection.cursor()
self.assertRaises(cx_Oracle.DatabaseError, cursor.execute, self.assertRaises(oracledb.DatabaseError, cursor.execute,
"select 1 / 0 from dual") "select 1 / 0 from dual")
def __VerifyConnection(self, connection, expectedUser, def __verify_connection(self, connection, expected_user,
expectedProxyUser = None): expected_proxy_user=None):
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute(""" cursor.execute("""
select select
sys_context('userenv', 'session_user'), sys_context('userenv', 'session_user'),
sys_context('userenv', 'proxy_user') sys_context('userenv', 'proxy_user')
from dual""") from dual""")
actualUser, actualProxyUser = cursor.fetchone() actual_user, actual_proxy_user = cursor.fetchone()
self.assertEqual(actualUser, expectedUser.upper()) self.assertEqual(actual_user, expected_user.upper())
self.assertEqual(actualProxyUser, self.assertEqual(actual_proxy_user,
expectedProxyUser and expectedProxyUser.upper()) expected_proxy_user and expected_proxy_user.upper())
def setUp(self): def test_2400_pool(self):
pass
def tearDown(self):
pass
def test_2400_Pool(self):
"2400 - test that the pool is created and has the right attributes" "2400 - test that the pool is created and has the right attributes"
pool = TestEnv.GetPool(min=2, max=8, increment=3, pool = base.get_pool(min=2, max=8, increment=3,
getmode=cx_Oracle.SPOOL_ATTRVAL_WAIT) getmode=oracledb.SPOOL_ATTRVAL_WAIT)
self.assertEqual(pool.username, TestEnv.GetMainUser(), self.assertEqual(pool.username, base.get_main_user(),
"user name differs") "user name differs")
self.assertEqual(pool.tnsentry, TestEnv.GetConnectString(), self.assertEqual(pool.tnsentry, base.get_connect_string(),
"tnsentry differs") "tnsentry differs")
self.assertEqual(pool.dsn, TestEnv.GetConnectString(), "dsn differs") self.assertEqual(pool.dsn, base.get_connect_string(), "dsn differs")
self.assertEqual(pool.max, 8, "max differs") self.assertEqual(pool.max, 8, "max differs")
self.assertEqual(pool.min, 2, "min differs") self.assertEqual(pool.min, 2, "min differs")
self.assertEqual(pool.increment, 3, "increment differs") self.assertEqual(pool.increment, 3, "increment differs")
@ -79,98 +72,99 @@ class TestCase(TestEnv.BaseTestCase):
self.assertEqual(pool.busy, 2, "busy not 2 after release") self.assertEqual(pool.busy, 2, "busy not 2 after release")
del connection_2 del connection_2
self.assertEqual(pool.busy, 1, "busy not 1 after del") self.assertEqual(pool.busy, 1, "busy not 1 after del")
pool.getmode = cx_Oracle.SPOOL_ATTRVAL_NOWAIT pool.getmode = oracledb.SPOOL_ATTRVAL_NOWAIT
self.assertEqual(pool.getmode, cx_Oracle.SPOOL_ATTRVAL_NOWAIT) self.assertEqual(pool.getmode, oracledb.SPOOL_ATTRVAL_NOWAIT)
if TestEnv.GetClientVersion() >= (12, 2): if base.get_client_version() >= (12, 2):
pool.getmode = cx_Oracle.SPOOL_ATTRVAL_TIMEDWAIT pool.getmode = oracledb.SPOOL_ATTRVAL_TIMEDWAIT
self.assertEqual(pool.getmode, cx_Oracle.SPOOL_ATTRVAL_TIMEDWAIT) self.assertEqual(pool.getmode, oracledb.SPOOL_ATTRVAL_TIMEDWAIT)
pool.stmtcachesize = 50 pool.stmtcachesize = 50
self.assertEqual(pool.stmtcachesize, 50) self.assertEqual(pool.stmtcachesize, 50)
pool.timeout = 10 pool.timeout = 10
self.assertEqual(pool.timeout, 10) self.assertEqual(pool.timeout, 10)
if TestEnv.GetClientVersion() >= (12, 1): if base.get_client_version() >= (12, 1):
pool.max_lifetime_session = 10 pool.max_lifetime_session = 10
self.assertEqual(pool.max_lifetime_session, 10) self.assertEqual(pool.max_lifetime_session, 10)
def test_2401_ProxyAuth(self): def test_2401_proxy_auth(self):
"2401 - test that proxy authentication is possible" "2401 - test that proxy authentication is possible"
pool = TestEnv.GetPool(min=2, max=8, increment=3, pool = base.get_pool(min=2, max=8, increment=3,
getmode=cx_Oracle.SPOOL_ATTRVAL_WAIT) getmode=oracledb.SPOOL_ATTRVAL_WAIT)
self.assertEqual(pool.homogeneous, 1, self.assertEqual(pool.homogeneous, True,
"homogeneous should be 1 by default") "homogeneous should be True by default")
self.assertRaises(cx_Oracle.DatabaseError, pool.acquire, self.assertRaises(oracledb.DatabaseError, pool.acquire,
user="missing_proxyuser") user="missing_proxyuser")
pool = TestEnv.GetPool(min=2, max=8, increment=3, pool = base.get_pool(min=2, max=8, increment=3,
getmode=cx_Oracle.SPOOL_ATTRVAL_WAIT, homogeneous=False) getmode=oracledb.SPOOL_ATTRVAL_WAIT,
self.assertEqual(pool.homogeneous, 0, homogeneous=False)
"homogeneous should be 0 after setting it in the constructor") msg = "homogeneous should be False after setting it in the constructor"
connection = pool.acquire(user = TestEnv.GetProxyUser()) self.assertEqual(pool.homogeneous, False, msg)
connection = pool.acquire(user=base.get_proxy_user())
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute('select user from dual') cursor.execute('select user from dual')
result, = cursor.fetchone() result, = cursor.fetchone()
self.assertEqual(result, TestEnv.GetProxyUser().upper()) self.assertEqual(result, base.get_proxy_user().upper())
def test_2402_RollbackOnDel(self): def test_2402_rollback_on_del(self):
"2402 - connection rolls back before being destroyed" "2402 - connection rolls back before being destroyed"
pool = TestEnv.GetPool() pool = base.get_pool()
connection = pool.acquire() connection = pool.acquire()
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute("truncate table TestTempTable") cursor.execute("truncate table TestTempTable")
cursor.execute("insert into TestTempTable (IntCol) values (1)") cursor.execute("insert into TestTempTable (IntCol) values (1)")
pool = TestEnv.GetPool() pool = base.get_pool()
connection = pool.acquire() connection = pool.acquire()
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute("select count(*) from TestTempTable") cursor.execute("select count(*) from TestTempTable")
count, = cursor.fetchone() count, = cursor.fetchone()
self.assertEqual(count, 0) self.assertEqual(count, 0)
def test_2403_RollbackOnRelease(self): def test_2403_rollback_on_release(self):
"2403 - connection rolls back before released back to the pool" "2403 - connection rolls back before released back to the pool"
pool = TestEnv.GetPool() pool = base.get_pool()
connection = pool.acquire() connection = pool.acquire()
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute("truncate table TestTempTable") cursor.execute("truncate table TestTempTable")
cursor.execute("insert into TestTempTable (IntCol) values (1)") cursor.execute("insert into TestTempTable (IntCol) values (1)")
cursor.close() cursor.close()
pool.release(connection) pool.release(connection)
pool = TestEnv.GetPool() pool = base.get_pool()
connection = pool.acquire() connection = pool.acquire()
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute("select count(*) from TestTempTable") cursor.execute("select count(*) from TestTempTable")
count, = cursor.fetchone() count, = cursor.fetchone()
self.assertEqual(count, 0) self.assertEqual(count, 0)
def test_2404_Threading(self): def test_2404_threading(self):
"2404 - test session pool with multiple threads" "2404 - test session pool with multiple threads"
self.pool = TestEnv.GetPool(min=5, max=20, increment=2, threaded=True, self.pool = base.get_pool(min=5, max=20, increment=2, threaded=True,
getmode=cx_Oracle.SPOOL_ATTRVAL_WAIT) getmode=oracledb.SPOOL_ATTRVAL_WAIT)
threads = [] threads = []
for i in range(20): for i in range(20):
thread = threading.Thread(None, self.__ConnectAndDrop) thread = threading.Thread(None, self.__connect_and_drop)
threads.append(thread) threads.append(thread)
thread.start() thread.start()
for thread in threads: for thread in threads:
thread.join() thread.join()
def test_2405_ThreadingWithErrors(self): def test_2405_threading_with_errors(self):
"2405 - test session pool with multiple threads (with errors)" "2405 - test session pool with multiple threads (with errors)"
self.pool = TestEnv.GetPool(min=5, max=20, increment=2, threaded=True, self.pool = base.get_pool(min=5, max=20, increment=2, threaded=True,
getmode=cx_Oracle.SPOOL_ATTRVAL_WAIT) getmode=oracledb.SPOOL_ATTRVAL_WAIT)
threads = [] threads = []
for i in range(20): for i in range(20):
thread = threading.Thread(None, self.__ConnectAndGenerateError) thread = threading.Thread(None, self.__connect_and_generate_error)
threads.append(thread) threads.append(thread)
thread.start() thread.start()
for thread in threads: for thread in threads:
thread.join() thread.join()
def test_2406_Purity(self): def test_2406_purity(self):
"2406 - test session pool with various types of purity" "2406 - test session pool with various types of purity"
action = "TEST_ACTION" pool = base.get_pool(min=1, max=8, increment=1,
pool = TestEnv.GetPool(min=1, max=8, increment=1, getmode=oracledb.SPOOL_ATTRVAL_WAIT)
getmode=cx_Oracle.SPOOL_ATTRVAL_WAIT)
# get connection and set the action # get connection and set the action
action = "TEST_ACTION"
connection = pool.acquire() connection = pool.acquire()
connection.action = action connection.action = action
cursor = connection.cursor() cursor = connection.cursor()
@ -190,7 +184,7 @@ class TestCase(TestEnv.BaseTestCase):
self.assertEqual(pool.opened, 1, "opened (2)") self.assertEqual(pool.opened, 1, "opened (2)")
# get a new connection with new purity (should not have state) # get a new connection with new purity (should not have state)
connection = pool.acquire(purity = cx_Oracle.ATTR_PURITY_NEW) connection = pool.acquire(purity=oracledb.ATTR_PURITY_NEW)
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute("select sys_context('userenv', 'action') from dual") cursor.execute("select sys_context('userenv', 'action') from dual")
result, = cursor.fetchone() result, = cursor.fetchone()
@ -200,77 +194,85 @@ class TestCase(TestEnv.BaseTestCase):
pool.drop(connection) pool.drop(connection)
self.assertEqual(pool.opened, 1, "opened (4)") self.assertEqual(pool.opened, 1, "opened (4)")
def test_2407_Heterogeneous(self): def test_2407_heterogeneous(self):
"2407 - test heterogeneous pool with user and password specified" "2407 - test heterogeneous pool with user and password specified"
pool = TestEnv.GetPool(min=2, max=8, increment=3, homogeneous=False, pool = base.get_pool(min=2, max=8, increment=3, homogeneous=False,
getmode=cx_Oracle.SPOOL_ATTRVAL_WAIT) getmode=oracledb.SPOOL_ATTRVAL_WAIT)
self.assertEqual(pool.homogeneous, 0) self.assertEqual(pool.homogeneous, 0)
self.__VerifyConnection(pool.acquire(), TestEnv.GetMainUser()) self.__verify_connection(pool.acquire(), base.get_main_user())
self.__VerifyConnection(pool.acquire(TestEnv.GetMainUser(), self.__verify_connection(pool.acquire(base.get_main_user(),
TestEnv.GetMainPassword()), TestEnv.GetMainUser()) base.get_main_password()),
self.__VerifyConnection(pool.acquire(TestEnv.GetProxyUser(), base.get_main_user())
TestEnv.GetProxyPassword()), TestEnv.GetProxyUser()) self.__verify_connection(pool.acquire(base.get_proxy_user(),
userStr = "%s[%s]" % (TestEnv.GetMainUser(), TestEnv.GetProxyUser()) base.get_proxy_password()),
self.__VerifyConnection(pool.acquire(userStr, base.get_proxy_user())
TestEnv.GetMainPassword()), TestEnv.GetProxyUser(), user_str = "%s[%s]" % (base.get_main_user(), base.get_proxy_user())
TestEnv.GetMainUser()) self.__verify_connection(pool.acquire(user_str,
base.get_main_password()),
base.get_proxy_user(), base.get_main_user())
def test_2408_HeterogenousWithoutUser(self): def test_2408_heterogenous_without_user(self):
"2408 - test heterogeneous pool without user and password specified" "2408 - test heterogeneous pool without user and password specified"
pool = TestEnv.GetPool(user="", password="", min=2, max=8, increment=3, pool = base.get_pool(user="", password="", min=2, max=8, increment=3,
getmode=cx_Oracle.SPOOL_ATTRVAL_WAIT, homogeneous=False) getmode=oracledb.SPOOL_ATTRVAL_WAIT,
self.__VerifyConnection(pool.acquire(TestEnv.GetMainUser(), homogeneous=False)
TestEnv.GetMainPassword()), TestEnv.GetMainUser()) self.__verify_connection(pool.acquire(base.get_main_user(),
self.__VerifyConnection(pool.acquire(TestEnv.GetProxyUser(), base.get_main_password()),
TestEnv.GetProxyPassword()), TestEnv.GetProxyUser()) base.get_main_user())
userStr = "%s[%s]" % (TestEnv.GetMainUser(), TestEnv.GetProxyUser()) self.__verify_connection(pool.acquire(base.get_proxy_user(),
self.__VerifyConnection(pool.acquire(userStr, base.get_proxy_password()),
TestEnv.GetMainPassword()), TestEnv.GetProxyUser(), base.get_proxy_user())
TestEnv.GetMainUser()) user_str = "%s[%s]" % (base.get_main_user(), base.get_proxy_user())
self.__verify_connection(pool.acquire(user_str,
base.get_main_password()),
base.get_proxy_user(), base.get_main_user())
def test_2409_HeterogeneousWrongPassword(self): def test_2409_heterogeneous_wrong_password(self):
"2409 - test heterogeneous pool with wrong password specified" "2409 - test heterogeneous pool with wrong password specified"
pool = TestEnv.GetPool(min=2, max=8, increment=3, pool = base.get_pool(min=2, max=8, increment=3,
getmode=cx_Oracle.SPOOL_ATTRVAL_WAIT, homogeneous=False) getmode=oracledb.SPOOL_ATTRVAL_WAIT,
self.assertRaises(cx_Oracle.DatabaseError, pool.acquire, homogeneous=False)
TestEnv.GetProxyUser(), "this is the wrong password") self.assertRaises(oracledb.DatabaseError, pool.acquire,
base.get_proxy_user(), "this is the wrong password")
def test_2410_TaggingSession(self): def test_2410_tagging_session(self):
"2410 - test tagging a session" "2410 - test tagging a session"
pool = TestEnv.GetPool(min=2, max=8, increment=3, pool = base.get_pool(min=2, max=8, increment=3,
getmode=cx_Oracle.SPOOL_ATTRVAL_NOWAIT) getmode=oracledb.SPOOL_ATTRVAL_NOWAIT)
tagMST = "TIME_ZONE=MST" tag_mst = "TIME_ZONE=MST"
tagUTC = "TIME_ZONE=UTC" tag_utc = "TIME_ZONE=UTC"
conn = pool.acquire() conn = pool.acquire()
self.assertEqual(conn.tag, None) self.assertEqual(conn.tag, None)
pool.release(conn, tag=tagMST) pool.release(conn, tag=tag_mst)
conn = pool.acquire() conn = pool.acquire()
self.assertEqual(conn.tag, None) self.assertEqual(conn.tag, None)
conn.tag = tagUTC conn.tag = tag_utc
conn.close() conn.close()
conn = pool.acquire(tag=tagMST) conn = pool.acquire(tag=tag_mst)
self.assertEqual(conn.tag, tagMST) self.assertEqual(conn.tag, tag_mst)
conn.close() conn.close()
conn = pool.acquire(tag=tagUTC) conn = pool.acquire(tag=tag_utc)
self.assertEqual(conn.tag, tagUTC) self.assertEqual(conn.tag, tag_utc)
conn.close() conn.close()
def test_2411_PLSQLSessionCallbacks(self): def test_2411_plsql_session_callbacks(self):
"2411 - test PL/SQL session callbacks" "2411 - test PL/SQL session callbacks"
clientVersion = cx_Oracle.clientversion() if base.get_client_version() < (12, 2):
if clientVersion < (12, 2):
self.skipTest("PL/SQL session callbacks not supported before 12.2") self.skipTest("PL/SQL session callbacks not supported before 12.2")
pool = TestEnv.GetPool(min=2, max=8, increment=3, pool = base.get_pool(min=2, max=8, increment=3,
getmode=cx_Oracle.SPOOL_ATTRVAL_NOWAIT, getmode=oracledb.SPOOL_ATTRVAL_NOWAIT,
sessionCallback="pkg_SessionCallback.TheCallback") sessionCallback="pkg_SessionCallback.TheCallback")
tags = ["NLS_DATE_FORMAT=SIMPLE", "NLS_DATE_FORMAT=FULL;TIME_ZONE=UTC", tags = [
"NLS_DATE_FORMAT=FULL;TIME_ZONE=MST"] "NLS_DATE_FORMAT=SIMPLE",
actualTags = [None, None, "NLS_DATE_FORMAT=FULL;TIME_ZONE=UTC"] "NLS_DATE_FORMAT=FULL;TIME_ZONE=UTC",
"NLS_DATE_FORMAT=FULL;TIME_ZONE=MST"
]
actual_tags = [None, None, "NLS_DATE_FORMAT=FULL;TIME_ZONE=UTC"]
# truncate PL/SQL session callback log # truncate PL/SQL session callback log
conn = pool.acquire() conn = pool.acquire()
@ -295,18 +297,17 @@ class TestCase(TestEnv.BaseTestCase):
from PLSQLSessionCallbacks from PLSQLSessionCallbacks
order by FixupTimestamp""") order by FixupTimestamp""")
results = cursor.fetchall() results = cursor.fetchall()
expectedResults = list(zip(tags, actualTags)) expected_results = list(zip(tags, actual_tags))
self.assertEqual(results, expectedResults) self.assertEqual(results, expected_results)
def test_2412_TaggingInvalidKey(self): def test_2412_tagging_invalid_key(self):
"2412 - testTagging with Invalid key" "2412 - testTagging with Invalid key"
pool = TestEnv.GetPool(getmode=cx_Oracle.SPOOL_ATTRVAL_NOWAIT) pool = base.get_pool(getmode=oracledb.SPOOL_ATTRVAL_NOWAIT)
conn = pool.acquire() conn = pool.acquire()
self.assertRaises(TypeError, pool.release, conn, tag=12345) self.assertRaises(TypeError, pool.release, conn, tag=12345)
clientVersion = cx_Oracle.clientversion() if base.get_client_version() >= (12, 2):
if clientVersion >= (12, 2): self.assertRaises(oracledb.DatabaseError, pool.release, conn,
self.assertRaises(cx_Oracle.DatabaseError, pool.release, conn,
tag="INVALID_TAG") tag="INVALID_TAG")
if __name__ == "__main__": if __name__ == "__main__":
TestEnv.RunTestCases() base.run_test_cases()

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# #
@ -12,50 +11,50 @@
2500 - Module for testing string variables 2500 - Module for testing string variables
""" """
import TestEnv import base
import cx_Oracle import cx_Oracle as oracledb
import datetime import datetime
import string import string
import random import random
class TestCase(TestEnv.BaseTestCase): class TestCase(base.BaseTestCase):
def setUp(self): def setUp(self):
TestEnv.BaseTestCase.setUp(self) super().setUp()
self.rawData = [] self.raw_data = []
self.dataByKey = {} self.data_by_key = {}
for i in range(1, 11): for i in range(1, 11):
stringCol = "String %d" % i string_col = "String %d" % i
fixedCharCol = ("Fixed Char %d" % i).ljust(40) fixed_char_col = ("Fixed Char %d" % i).ljust(40)
rawCol = ("Raw %d" % i).encode("ascii") raw_col = ("Raw %d" % i).encode("ascii")
if i % 2: if i % 2:
nullableCol = "Nullable %d" % i nullable_col = "Nullable %d" % i
else: else:
nullableCol = None nullable_col = None
dataTuple = (i, stringCol, rawCol, fixedCharCol, nullableCol) data_tuple = (i, string_col, raw_col, fixed_char_col, nullable_col)
self.rawData.append(dataTuple) self.raw_data.append(data_tuple)
self.dataByKey[i] = dataTuple self.data_by_key[i] = data_tuple
def test_2500_ArrayWithIncreasedSize(self): def test_2500_array_with_increased_size(self):
"2500 - test creating array var and then increasing the internal size" "2500 - test creating array var and then increasing the internal size"
val = ["12345678901234567890"] * 3 val = ["12345678901234567890"] * 3
arrayVar = self.cursor.arrayvar(str, len(val), 4) var = self.cursor.arrayvar(str, len(val), 4)
arrayVar.setvalue(0, val) var.setvalue(0, val)
self.assertEqual(arrayVar.getvalue(), val) self.assertEqual(var.getvalue(), val)
def test_2501_BindString(self): def test_2501_bind_string(self):
"2501 - test binding in a string" "2501 - test binding in a string"
self.cursor.execute(""" self.cursor.execute("""
select * from TestStrings select * from TestStrings
where StringCol = :value""", where StringCol = :value""",
value="String 5") value="String 5")
self.assertEqual(self.cursor.fetchall(), [self.dataByKey[5]]) self.assertEqual(self.cursor.fetchall(), [self.data_by_key[5]])
def test_2502_BindDifferentVar(self): def test_2502_bind_different_var(self):
"2502 - test binding a different variable on second execution" "2502 - test binding a different variable on second execution"
retval_1 = self.cursor.var(cx_Oracle.STRING, 30) retval_1 = self.cursor.var(oracledb.STRING, 30)
retval_2 = self.cursor.var(cx_Oracle.STRING, 30) retval_2 = self.cursor.var(oracledb.STRING, 30)
self.cursor.execute("begin :retval := 'Called'; end;", self.cursor.execute("begin :retval := 'Called'; end;",
retval=retval_1) retval=retval_1)
self.assertEqual(retval_1.getvalue(), "Called") self.assertEqual(retval_1.getvalue(), "Called")
@ -63,108 +62,104 @@ class TestCase(TestEnv.BaseTestCase):
retval=retval_2) retval=retval_2)
self.assertEqual(retval_2.getvalue(), "Called") self.assertEqual(retval_2.getvalue(), "Called")
def test_2503_ExceedsNumElements(self): def test_2503_exceeds_num_elements(self):
"2503 - test exceeding the number of elements returns IndexError" "2503 - test exceeding the number of elements returns IndexError"
var = self.cursor.var(str) var = self.cursor.var(str)
self.assertRaises(IndexError, var.getvalue, 1) self.assertRaises(IndexError, var.getvalue, 1)
def test_2504_BindStringAfterNumber(self): def test_2504_bind_string_after_number(self):
"2504 - test binding in a string after setting input sizes to a number" "2504 - test binding in a string after setting input sizes to a number"
self.cursor.setinputsizes(value = cx_Oracle.NUMBER) self.cursor.setinputsizes(value = oracledb.NUMBER)
self.cursor.execute(""" self.cursor.execute("""
select * from TestStrings select * from TestStrings
where StringCol = :value""", where StringCol = :value""",
value="String 6") value="String 6")
self.assertEqual(self.cursor.fetchall(), [self.dataByKey[6]]) self.assertEqual(self.cursor.fetchall(), [self.data_by_key[6]])
def test_2505_BindStringArrayDirect(self): def test_2505_bind_string_array_direct(self):
"2505 - test binding in a string array" "2505 - test binding in a string array"
returnValue = self.cursor.var(cx_Oracle.NUMBER) return_value = self.cursor.var(oracledb.NUMBER)
array = [r[1] for r in self.rawData] array = [r[1] for r in self.raw_data]
statement = """ statement = """
begin begin
:returnValue := pkg_TestStringArrays.TestInArrays( :return_value := pkg_TestStringArrays.TestInArrays(
:integerValue, :array); :integer_value, :array);
end;""" end;"""
self.cursor.execute(statement, self.cursor.execute(statement, return_value=return_value,
returnValue = returnValue, integer_value=5, array=array)
integerValue = 5, self.assertEqual(return_value.getvalue(), 86)
array = array)
self.assertEqual(returnValue.getvalue(), 86)
array = [ "String - %d" % i for i in range(15) ] array = [ "String - %d" % i for i in range(15) ]
self.cursor.execute(statement, self.cursor.execute(statement, integer_value=8, array=array)
integerValue = 8, self.assertEqual(return_value.getvalue(), 163)
array = array)
self.assertEqual(returnValue.getvalue(), 163)
def test_2506_BindStringArrayBySizes(self): def test_2506_bind_string_array_by_sizes(self):
"2506 - test binding in a string array (with setinputsizes)" "2506 - test binding in a string array (with setinputsizes)"
returnValue = self.cursor.var(cx_Oracle.NUMBER) return_value = self.cursor.var(oracledb.NUMBER)
self.cursor.setinputsizes(array = [cx_Oracle.STRING, 10]) self.cursor.setinputsizes(array=[oracledb.STRING, 10])
array = [r[1] for r in self.rawData] array = [r[1] for r in self.raw_data]
self.cursor.execute(""" self.cursor.execute("""
begin begin
:returnValue := pkg_TestStringArrays.TestInArrays( :return_value := pkg_TestStringArrays.TestInArrays(
:integerValue, :array); :integer_value, :array);
end;""", end;""",
returnValue = returnValue, return_value=return_value,
integerValue = 6, integer_value=6,
array=array) array=array)
self.assertEqual(returnValue.getvalue(), 87) self.assertEqual(return_value.getvalue(), 87)
def test_2507_BindStringArrayByVar(self): def test_2507_bind_string_array_by_var(self):
"2507 - test binding in a string array (with arrayvar)" "2507 - test binding in a string array (with arrayvar)"
returnValue = self.cursor.var(cx_Oracle.NUMBER) return_value = self.cursor.var(oracledb.NUMBER)
array = self.cursor.arrayvar(cx_Oracle.STRING, 10, 20) array = self.cursor.arrayvar(oracledb.STRING, 10, 20)
array.setvalue(0, [r[1] for r in self.rawData]) array.setvalue(0, [r[1] for r in self.raw_data])
self.cursor.execute(""" self.cursor.execute("""
begin begin
:returnValue := pkg_TestStringArrays.TestInArrays( :return_value := pkg_TestStringArrays.TestInArrays(
:integerValue, :array); :integer_value, :array);
end;""", end;""",
returnValue = returnValue, return_value=return_value,
integerValue = 7, integer_value=7,
array=array) array=array)
self.assertEqual(returnValue.getvalue(), 88) self.assertEqual(return_value.getvalue(), 88)
def test_2508_BindInOutStringArrayByVar(self): def test_2508_bind_in_out_string_array_by_var(self):
"2508 - test binding in/out a string array (with arrayvar)" "2508 - test binding in/out a string array (with arrayvar)"
array = self.cursor.arrayvar(cx_Oracle.STRING, 10, 100) array = self.cursor.arrayvar(oracledb.STRING, 10, 100)
originalData = [r[1] for r in self.rawData] original_data = [r[1] for r in self.raw_data]
expectedData = ["Converted element # %d originally had length %d" % \ expected_data = ["Converted element # %d originally had length %d" % \
(i, len(originalData[i - 1])) for i in range(1, 6)] + \ (i, len(original_data[i - 1])) \
originalData[5:] for i in range(1, 6)] + original_data[5:]
array.setvalue(0, originalData) array.setvalue(0, original_data)
self.cursor.execute(""" self.cursor.execute("""
begin begin
pkg_TestStringArrays.TestInOutArrays(:numElems, :array); pkg_TestStringArrays.TestInOutArrays(:num_elems, :array);
end;""", end;""",
numElems = 5, num_elems=5,
array=array) array=array)
self.assertEqual(array.getvalue(), expectedData) self.assertEqual(array.getvalue(), expected_data)
def test_2509_BindOutStringArrayByVar(self): def test_2509_bind_out_string_array_by_var(self):
"2509 - test binding out a string array (with arrayvar)" "2509 - test binding out a string array (with arrayvar)"
array = self.cursor.arrayvar(cx_Oracle.STRING, 6, 100) array = self.cursor.arrayvar(oracledb.STRING, 6, 100)
expectedData = ["Test out element # %d" % i for i in range(1, 7)] expected_data = ["Test out element # %d" % i for i in range(1, 7)]
self.cursor.execute(""" self.cursor.execute("""
begin begin
pkg_TestStringArrays.TestOutArrays(:numElems, :array); pkg_TestStringArrays.TestOutArrays(:num_elems, :array);
end;""", end;""",
numElems = 6, num_elems=6,
array=array) array=array)
self.assertEqual(array.getvalue(), expectedData) self.assertEqual(array.getvalue(), expected_data)
def test_2510_BindRaw(self): def test_2510_bind_raw(self):
"2510 - test binding in a raw" "2510 - test binding in a raw"
self.cursor.setinputsizes(value = cx_Oracle.BINARY) self.cursor.setinputsizes(value = oracledb.BINARY)
self.cursor.execute(""" self.cursor.execute("""
select * from TestStrings select * from TestStrings
where RawCol = :value""", where RawCol = :value""",
value = "Raw 4".encode("ascii")) value="Raw 4".encode())
self.assertEqual(self.cursor.fetchall(), [self.dataByKey[4]]) self.assertEqual(self.cursor.fetchall(), [self.data_by_key[4]])
def test_2511_BindAndFetchRowid(self): def test_2511_bind_and_fetch_rowid(self):
"2511 - test binding (and fetching) a rowid" "2511 - test binding (and fetching) a rowid"
self.cursor.execute(""" self.cursor.execute("""
select rowid select rowid
@ -176,9 +171,9 @@ class TestCase(TestEnv.BaseTestCase):
from TestStrings from TestStrings
where rowid = :value""", where rowid = :value""",
value=rowid) value=rowid)
self.assertEqual(self.cursor.fetchall(), [self.dataByKey[3]]) self.assertEqual(self.cursor.fetchall(), [self.data_by_key[3]])
def test_2512_BindAndFetchUniversalRowids(self): def test_2512_bind_and_fetch_universal_rowids(self):
"2512 - test binding (and fetching) universal rowids" "2512 - test binding (and fetching) universal rowids"
self.cursor.execute("truncate table TestUniversalRowids") self.cursor.execute("truncate table TestUniversalRowids")
data = [ data = [
@ -195,17 +190,17 @@ class TestCase(TestEnv.BaseTestCase):
from TestUniversalRowIds from TestUniversalRowIds
order by IntCol""") order by IntCol""")
rowids = [r for r, in self.cursor] rowids = [r for r, in self.cursor]
fetchedData = [] fetched_data = []
for rowid in rowids: for rowid in rowids:
self.cursor.execute(""" self.cursor.execute("""
select * select *
from TestUniversalRowids from TestUniversalRowids
where rowid = :rid""", where rowid = :rid""",
rid=rowid) rid=rowid)
fetchedData.extend(self.cursor.fetchall()) fetched_data.extend(self.cursor.fetchall())
self.assertEqual(fetchedData, data) self.assertEqual(fetched_data, data)
def test_2513_BindNull(self): def test_2513_bind_null(self):
"2513 - test binding in a null" "2513 - test binding in a null"
self.cursor.execute(""" self.cursor.execute("""
select * from TestStrings select * from TestStrings
@ -213,47 +208,47 @@ class TestCase(TestEnv.BaseTestCase):
value=None) value=None)
self.assertEqual(self.cursor.fetchall(), []) self.assertEqual(self.cursor.fetchall(), [])
def test_2514_BindOutSetInputSizesByType(self): def test_2514_bind_out_set_input_sizes_by_type(self):
"2514 - test binding out with set input sizes defined (by type)" "2514 - test binding out with set input sizes defined (by type)"
vars = self.cursor.setinputsizes(value = cx_Oracle.STRING) bind_vars = self.cursor.setinputsizes(value=oracledb.STRING)
self.cursor.execute(""" self.cursor.execute("""
begin begin
:value := 'TSI'; :value := 'TSI';
end;""") end;""")
self.assertEqual(vars["value"].getvalue(), "TSI") self.assertEqual(bind_vars["value"].getvalue(), "TSI")
def test_2515_BindOutSetInputSizesByInteger(self): def test_2515_bind_out_set_input_sizes_by_integer(self):
"2515 - test binding out with set input sizes defined (by integer)" "2515 - test binding out with set input sizes defined (by integer)"
vars = self.cursor.setinputsizes(value = 30) bind_vars = self.cursor.setinputsizes(value=30)
self.cursor.execute(""" self.cursor.execute("""
begin begin
:value := 'TSI (I)'; :value := 'TSI (I)';
end;""") end;""")
self.assertEqual(vars["value"].getvalue(), "TSI (I)") self.assertEqual(bind_vars["value"].getvalue(), "TSI (I)")
def test_2516_BindInOutSetInputSizesByType(self): def test_2516_bind_in_out_set_input_sizes_by_type(self):
"2516 - test binding in/out with set input sizes defined (by type)" "2516 - test binding in/out with set input sizes defined (by type)"
vars = self.cursor.setinputsizes(value = cx_Oracle.STRING) bind_vars = self.cursor.setinputsizes(value=oracledb.STRING)
self.cursor.execute(""" self.cursor.execute("""
begin begin
:value := :value || ' TSI'; :value := :value || ' TSI';
end;""", end;""",
value="InVal") value="InVal")
self.assertEqual(vars["value"].getvalue(), "InVal TSI") self.assertEqual(bind_vars["value"].getvalue(), "InVal TSI")
def test_2517_BindInOutSetInputSizesByInteger(self): def test_2517_bind_in_out_set_input_sizes_by_integer(self):
"2517 - test binding in/out with set input sizes defined (by integer)" "2517 - test binding in/out with set input sizes defined (by integer)"
vars = self.cursor.setinputsizes(value = 30) bind_vars = self.cursor.setinputsizes(value=30)
self.cursor.execute(""" self.cursor.execute("""
begin begin
:value := :value || ' TSI (I)'; :value := :value || ' TSI (I)';
end;""", end;""",
value="InVal") value="InVal")
self.assertEqual(vars["value"].getvalue(), "InVal TSI (I)") self.assertEqual(bind_vars["value"].getvalue(), "InVal TSI (I)")
def test_2518_BindOutVar(self): def test_2518_bind_out_var(self):
"2518 - test binding out with cursor.var() method" "2518 - test binding out with cursor.var() method"
var = self.cursor.var(cx_Oracle.STRING) var = self.cursor.var(oracledb.STRING)
self.cursor.execute(""" self.cursor.execute("""
begin begin
:value := 'TSI (VAR)'; :value := 'TSI (VAR)';
@ -261,9 +256,9 @@ class TestCase(TestEnv.BaseTestCase):
value=var) value=var)
self.assertEqual(var.getvalue(), "TSI (VAR)") self.assertEqual(var.getvalue(), "TSI (VAR)")
def test_2519_BindInOutVarDirectSet(self): def test_2519_bind_in_out_var_direct_set(self):
"2519 - test binding in/out with cursor.var() method" "2519 - test binding in/out with cursor.var() method"
var = self.cursor.var(cx_Oracle.STRING) var = self.cursor.var(oracledb.STRING)
var.setvalue(0, "InVal") var.setvalue(0, "InVal")
self.cursor.execute(""" self.cursor.execute("""
begin begin
@ -272,70 +267,69 @@ class TestCase(TestEnv.BaseTestCase):
value=var) value=var)
self.assertEqual(var.getvalue(), "InVal TSI (VAR)") self.assertEqual(var.getvalue(), "InVal TSI (VAR)")
def test_2520_BindLongString(self): def test_2520_bind_long_string(self):
"2520 - test that binding a long string succeeds" "2520 - test that binding a long string succeeds"
self.cursor.setinputsizes(bigString = cx_Oracle.DB_TYPE_LONG) self.cursor.setinputsizes(big_string=oracledb.DB_TYPE_LONG)
self.cursor.execute(""" self.cursor.execute("""
declare declare
t_Temp varchar2(20000); t_Temp varchar2(20000);
begin begin
t_Temp := :bigString; t_Temp := :big_string;
end;""", end;""",
bigString = "X" * 10000) big_string="X" * 10000)
def test_2521_BindLongStringAfterSettingSize(self): def test_2521_bind_long_string_after_setting_size(self):
"2521 - test that setinputsizes() returns a long variable" "2521 - test that setinputsizes() returns a long variable"
var = self.cursor.setinputsizes(test=90000)["test"] var = self.cursor.setinputsizes(test=90000)["test"]
inString = "1234567890" * 9000 in_string = "1234567890" * 9000
var.setvalue(0, inString) var.setvalue(0, in_string)
outString = var.getvalue() out_string = var.getvalue()
self.assertEqual(inString, outString, msg = f"output does not match: in was {len(in_string)}, " \
"output does not match: in was %d, out was %d" % \ f"out was {len(out_string)}"
(len(inString), len(outString))) self.assertEqual(in_string, out_string, msg)
def test_2522_CursorDescription(self): def test_2522_cursor_description(self):
"2522 - test cursor description is accurate" "2522 - test cursor description is accurate"
self.cursor.execute("select * from TestStrings") self.cursor.execute("select * from TestStrings")
self.assertEqual(self.cursor.description, expected_value = [
[ ('INTCOL', cx_Oracle.DB_TYPE_NUMBER, 10, None, 9, 0, 0), ('INTCOL', oracledb.DB_TYPE_NUMBER, 10, None, 9, 0, 0),
('STRINGCOL', cx_Oracle.DB_TYPE_VARCHAR, 20, ('STRINGCOL', oracledb.DB_TYPE_VARCHAR, 20,
20 * TestEnv.GetCharSetRatio(), None, 20 * base.get_charset_ratio(), None, None, 0),
None, 0), ('RAWCOL', oracledb.DB_TYPE_RAW, 30, 30, None, None, 0),
('RAWCOL', cx_Oracle.DB_TYPE_RAW, 30, 30, None, None, 0), ('FIXEDCHARCOL', oracledb.DB_TYPE_CHAR, 40,
('FIXEDCHARCOL', cx_Oracle.DB_TYPE_CHAR, 40, 40 * base.get_charset_ratio(), None, None, 0),
40 * TestEnv.GetCharSetRatio(), ('NULLABLECOL', oracledb.DB_TYPE_VARCHAR, 50,
None, None, 0), 50 * base.get_charset_ratio(), None, None, 1)
('NULLABLECOL', cx_Oracle.DB_TYPE_VARCHAR, 50, ]
50 * TestEnv.GetCharSetRatio(), None, self.assertEqual(self.cursor.description, expected_value)
None, 1) ])
def test_2523_FetchAll(self): def test_2523_fetchall(self):
"2523 - test that fetching all of the data returns the correct results" "2523 - test that fetching all of the data returns the correct results"
self.cursor.execute("select * From TestStrings order by IntCol") self.cursor.execute("select * From TestStrings order by IntCol")
self.assertEqual(self.cursor.fetchall(), self.rawData) self.assertEqual(self.cursor.fetchall(), self.raw_data)
self.assertEqual(self.cursor.fetchall(), []) self.assertEqual(self.cursor.fetchall(), [])
def test_2524_FetchMany(self): def test_2524_fetchmany(self):
"2524 - test that fetching data in chunks returns the correct results" "2524 - test that fetching data in chunks returns the correct results"
self.cursor.execute("select * From TestStrings order by IntCol") self.cursor.execute("select * From TestStrings order by IntCol")
self.assertEqual(self.cursor.fetchmany(3), self.rawData[0:3]) self.assertEqual(self.cursor.fetchmany(3), self.raw_data[0:3])
self.assertEqual(self.cursor.fetchmany(2), self.rawData[3:5]) self.assertEqual(self.cursor.fetchmany(2), self.raw_data[3:5])
self.assertEqual(self.cursor.fetchmany(4), self.rawData[5:9]) self.assertEqual(self.cursor.fetchmany(4), self.raw_data[5:9])
self.assertEqual(self.cursor.fetchmany(3), self.rawData[9:]) self.assertEqual(self.cursor.fetchmany(3), self.raw_data[9:])
self.assertEqual(self.cursor.fetchmany(3), []) self.assertEqual(self.cursor.fetchmany(3), [])
def test_2525_FetchOne(self): def test_2525_fetchone(self):
"2525 - test that fetching a single row returns the correct results" "2525 - test that fetching a single row returns the correct results"
self.cursor.execute(""" self.cursor.execute("""
select * select *
from TestStrings from TestStrings
where IntCol in (3, 4) where IntCol in (3, 4)
order by IntCol""") order by IntCol""")
self.assertEqual(self.cursor.fetchone(), self.dataByKey[3]) self.assertEqual(self.cursor.fetchone(), self.data_by_key[3])
self.assertEqual(self.cursor.fetchone(), self.dataByKey[4]) self.assertEqual(self.cursor.fetchone(), self.data_by_key[4])
self.assertEqual(self.cursor.fetchone(), None) self.assertEqual(self.cursor.fetchone(), None)
def test_2526_SupplementalCharacters(self): def test_2526_supplemental_characters(self):
"2526 - test binding and fetching supplemental charcters" "2526 - test binding and fetching supplemental charcters"
self.cursor.execute(""" self.cursor.execute("""
select value select value
@ -344,7 +338,7 @@ class TestCase(TestEnv.BaseTestCase):
charset, = self.cursor.fetchone() charset, = self.cursor.fetchone()
if charset != "AL32UTF8": if charset != "AL32UTF8":
self.skipTest("Database character set must be AL32UTF8") self.skipTest("Database character set must be AL32UTF8")
supplementalChars = "𠜎 𠜱 𠝹 𠱓 𠱸 𠲖 𠳏 𠳕 𠴕 𠵼 𠵿 𠸎 𠸏 𠹷 𠺝 " \ supplemental_chars = "𠜎 𠜱 𠝹 𠱓 𠱸 𠲖 𠳏 𠳕 𠴕 𠵼 𠵿 𠸎 𠸏 𠹷 𠺝 " \
"𠺢 𠻗 𠻹 𠻺 𠼭 𠼮 𠽌 𠾴 𠾼 𠿪 𡁜 𡁯 𡁵 𡁶 𡁻 𡃁 𡃉 𡇙 𢃇 " \ "𠺢 𠻗 𠻹 𠻺 𠼭 𠼮 𠽌 𠾴 𠾼 𠿪 𡁜 𡁯 𡁵 𡁶 𡁻 𡃁 𡃉 𡇙 𢃇 " \
"𢞵 𢫕 𢭃 𢯊 𢱑 𢱕 𢳂 𢴈 𢵌 𢵧 𢺳 𣲷 𤓓 𤶸 𤷪 𥄫 𦉘 𦟌 𦧲 " \ "𢞵 𢫕 𢭃 𢯊 𢱑 𢱕 𢳂 𢴈 𢵌 𢵧 𢺳 𣲷 𤓓 𤶸 𤷪 𥄫 𦉘 𦟌 𦧲 " \
"𦧺 𧨾 𨅝 𨈇 𨋢 𨳊 𨳍 𨳒 𩶘" "𦧺 𧨾 𨅝 𨈇 𨋢 𨳊 𨳍 𨳒 𩶘"
@ -352,34 +346,34 @@ class TestCase(TestEnv.BaseTestCase):
self.cursor.execute(""" self.cursor.execute("""
insert into TestTempTable (IntCol, StringCol) insert into TestTempTable (IntCol, StringCol)
values (:1, :2)""", values (:1, :2)""",
(1, supplementalChars)) (1, supplemental_chars))
self.connection.commit() self.connection.commit()
self.cursor.execute("select StringCol from TestTempTable") self.cursor.execute("select StringCol from TestTempTable")
value, = self.cursor.fetchone() value, = self.cursor.fetchone()
self.assertEqual(value, supplementalChars) self.assertEqual(value, supplemental_chars)
def test_2527_BindTwiceWithLargeStringSecond(self): def test_2527_bind_twice_with_large_string_second(self):
"2527 - test binding twice with a larger string the second time" "2527 - test binding twice with a larger string the second time"
self.cursor.execute("truncate table TestTempTable") self.cursor.execute("truncate table TestTempTable")
sql = "insert into TestTempTable (IntCol, StringCol) values (:1, :2)" sql = "insert into TestTempTable (IntCol, StringCol) values (:1, :2)"
shortString = "short string" short_string = "short string"
longString = "long string " * 30 long_string = "long string " * 30
self.cursor.execute(sql, (1, shortString)) self.cursor.execute(sql, (1, short_string))
self.cursor.execute(sql, (2, longString)) self.cursor.execute(sql, (2, long_string))
self.connection.commit() self.connection.commit()
self.cursor.execute(""" self.cursor.execute("""
select IntCol, StringCol select IntCol, StringCol
from TestTempTable from TestTempTable
order by IntCol""") order by IntCol""")
self.assertEqual(self.cursor.fetchall(), self.assertEqual(self.cursor.fetchall(),
[(1, shortString), (2, longString)]) [(1, short_string), (2, long_string)])
def test_2528_Issue50(self): def test_2528_issue_50(self):
"2528 - test issue 50 - avoid error ORA-24816" "2528 - test issue 50 - avoid error ORA-24816"
cursor = self.connection.cursor() cursor = self.connection.cursor()
try: try:
cursor.execute("drop table issue_50 purge") cursor.execute("drop table issue_50 purge")
except cx_Oracle.DatabaseError: except oracledb.DatabaseError:
pass pass
cursor.execute(""" cursor.execute("""
create table issue_50 ( create table issue_50 (
@ -390,49 +384,49 @@ class TestCase(TestEnv.BaseTestCase):
NClob1 nclob, NClob1 nclob,
NClob2 nclob NClob2 nclob
)""") )""")
idVar = cursor.var(cx_Oracle.NUMBER) id_var = cursor.var(oracledb.NUMBER)
cursor.execute(""" cursor.execute("""
insert into issue_50 (Id, Str2, Str3, NClob1, NClob2, Str1) insert into issue_50 (Id, Str2, Str3, NClob1, NClob2, Str1)
values (:arg0, :arg1, :arg2, :arg3, :arg4, :arg5) values (:arg0, :arg1, :arg2, :arg3, :arg4, :arg5)
returning id into :arg6""", returning id into :arg6""",
[1, '555a4c78', 'f319ef0e', '23009914', '', '', idVar]) [1, '555a4c78', 'f319ef0e', '23009914', '', '', id_var])
cursor = self.connection.cursor() cursor = self.connection.cursor()
cursor.execute(""" cursor.execute("""
insert into issue_50 (Id, Str2, Str3, NClob1, NClob2, Str1) insert into issue_50 (Id, Str2, Str3, NClob1, NClob2, Str1)
values (:arg0, :arg1, :arg2, :arg3, :arg4, :arg5) values (:arg0, :arg1, :arg2, :arg3, :arg4, :arg5)
returning id into :arg6""", returning id into :arg6""",
[2, u'd5ff845a', u'94275767', u'bf161ff6', u'', u'', idVar]) [2, u'd5ff845a', u'94275767', u'bf161ff6', u'', u'', id_var])
cursor.execute("drop table issue_50 purge") cursor.execute("drop table issue_50 purge")
def test_2529_SetRowidToString(self): def test_2529_set_rowid_to_string(self):
"2529 - test assigning a string to rowid" "2529 - test assigning a string to rowid"
var = self.cursor.var(cx_Oracle.ROWID) var = self.cursor.var(oracledb.ROWID)
self.assertRaises(cx_Oracle.NotSupportedError, var.setvalue, 0, self.assertRaises(oracledb.NotSupportedError, var.setvalue, 0,
"ABDHRYTHFJGKDKKDH") "ABDHRYTHFJGKDKKDH")
def test_2530_ShortXMLAsString(self): def test_2530_short_xml_as_string(self):
"2530 - test fetching XMLType object as a string" "2530 - test fetching XMLType object as a string"
self.cursor.execute(""" self.cursor.execute("""
select XMLElement("string", stringCol) select XMLElement("string", stringCol)
from TestStrings from TestStrings
where intCol = 1""") where intCol = 1""")
actualValue, = self.cursor.fetchone() actual_value, = self.cursor.fetchone()
expectedValue = "<string>String 1</string>" expected_value = "<string>String 1</string>"
self.assertEqual(actualValue, expectedValue) self.assertEqual(actual_value, expected_value)
def test_2531_LongXMLAsString(self): def test_2531_long_xml_as_string(self):
"2531 - test inserting and fetching an XMLType object (1K) as a string" "2531 - test inserting and fetching an XMLType object (1K) as a string"
chars = string.ascii_uppercase + string.ascii_lowercase chars = string.ascii_uppercase + string.ascii_lowercase
randomString = ''.join(random.choice(chars) for _ in range(1024)) random_string = ''.join(random.choice(chars) for _ in range(1024))
intVal = 200 int_val = 200
xmlString = '<data>' + randomString + '</data>' xml_string = '<data>' + random_string + '</data>'
self.cursor.execute(""" self.cursor.execute("""
insert into TestXML (IntCol, XMLCol) insert into TestXML (IntCol, XMLCol)
values (:1, :2)""", (intVal, xmlString)) values (:1, :2)""", (int_val, xml_string))
self.cursor.execute("select XMLCol from TestXML where intCol = :1", self.cursor.execute("select XMLCol from TestXML where intCol = :1",
(intVal,)) (int_val,))
actualValue, = self.cursor.fetchone() actual_value, = self.cursor.fetchone()
self.assertEqual(actualValue.strip(), xmlString) self.assertEqual(actual_value.strip(), xml_string)
if __name__ == "__main__": if __name__ == "__main__":
TestEnv.RunTestCases() base.run_test_cases()

View File

@ -11,82 +11,85 @@
2600 - Module for testing timestamp variables 2600 - Module for testing timestamp variables
""" """
import TestEnv import base
import cx_Oracle import cx_Oracle as oracledb
import time import time
class TestCase(TestEnv.BaseTestCase): class TestCase(base.BaseTestCase):
def setUp(self): def setUp(self):
TestEnv.BaseTestCase.setUp(self) super().setUp()
self.rawData = [] self.raw_data = []
self.dataByKey = {} self.data_by_key = {}
for i in range(1, 11): for i in range(1, 11):
timeTuple = (2002, 12, 9, 0, 0, 0, 0, 0, -1) time_tuple = (2002, 12, 9, 0, 0, 0, 0, 0, -1)
timeInTicks = time.mktime(timeTuple) + i * 86400 time_in_ticks = time.mktime(time_tuple) + i * 86400
dateValue = cx_Oracle.TimestampFromTicks(int(timeInTicks)) date_value = oracledb.TimestampFromTicks(int(time_in_ticks))
strValue = str(i * 50) str_value = str(i * 50)
fsecond = int(strValue + "0" * (6 - len(strValue))) fsecond = int(str_value + "0" * (6 - len(str_value)))
dateCol = cx_Oracle.Timestamp(dateValue.year, dateValue.month, date_col = oracledb.Timestamp(date_value.year, date_value.month,
dateValue.day, dateValue.hour, dateValue.minute, date_value.day, date_value.hour,
i * 2, fsecond) date_value.minute, i * 2, fsecond)
if i % 2: if i % 2:
timeInTicks = time.mktime(timeTuple) + i * 86400 + 86400 time_in_ticks = time.mktime(time_tuple) + i * 86400 + 86400
dateValue = cx_Oracle.TimestampFromTicks(int(timeInTicks)) date_value = oracledb.TimestampFromTicks(int(time_in_ticks))
strValue = str(i * 125) str_value = str(i * 125)
fsecond = int(strValue + "0" * (6 - len(strValue))) fsecond = int(str_value + "0" * (6 - len(str_value)))
nullableCol = cx_Oracle.Timestamp(dateValue.year, nullable_col = oracledb.Timestamp(date_value.year,
dateValue.month, dateValue.day, dateValue.hour, date_value.month,
dateValue.minute, i * 3, fsecond) date_value.day,
date_value.hour,
date_value.minute, i * 3,
fsecond)
else: else:
nullableCol = None nullable_col = None
tuple = (i, dateCol, nullableCol) data_tuple = (i, date_col, nullable_col)
self.rawData.append(tuple) self.raw_data.append(data_tuple)
self.dataByKey[i] = tuple self.data_by_key[i] = data_tuple
def test_2600_BindTimestamp(self): def test_2600_bind_timestamp(self):
"2600 - test binding in a timestamp" "2600 - test binding in a timestamp"
self.cursor.setinputsizes(value = cx_Oracle.DB_TYPE_TIMESTAMP) self.cursor.setinputsizes(value=oracledb.DB_TYPE_TIMESTAMP)
self.cursor.execute(""" self.cursor.execute("""
select * from TestTimestamps select * from TestTimestamps
where TimestampCol = :value""", where TimestampCol = :value""",
value = cx_Oracle.Timestamp(2002, 12, 14, 0, 0, 10, 250000)) value=oracledb.Timestamp(2002, 12, 14, 0, 0, 10, 250000))
self.assertEqual(self.cursor.fetchall(), [self.dataByKey[5]]) self.assertEqual(self.cursor.fetchall(), [self.data_by_key[5]])
def test_2601_BindNull(self): def test_2601_bind_null(self):
"2601 - test binding in a null" "2601 - test binding in a null"
self.cursor.setinputsizes(value = cx_Oracle.DB_TYPE_TIMESTAMP) self.cursor.setinputsizes(value=oracledb.DB_TYPE_TIMESTAMP)
self.cursor.execute(""" self.cursor.execute("""
select * from TestTimestamps select * from TestTimestamps
where TimestampCol = :value""", where TimestampCol = :value""",
value=None) value=None)
self.assertEqual(self.cursor.fetchall(), []) self.assertEqual(self.cursor.fetchall(), [])
def test_2602_BindOutSetInputSizes(self): def test_2602_bind_out_set_input_sizes(self):
"2602 - test binding out with set input sizes defined" "2602 - test binding out with set input sizes defined"
vars = self.cursor.setinputsizes(value = cx_Oracle.DB_TYPE_TIMESTAMP) bind_vars = self.cursor.setinputsizes(value=oracledb.DB_TYPE_TIMESTAMP)
self.cursor.execute(""" self.cursor.execute("""
begin begin
:value := to_timestamp('20021209', 'YYYYMMDD'); :value := to_timestamp('20021209', 'YYYYMMDD');
end;""") end;""")
self.assertEqual(vars["value"].getvalue(), self.assertEqual(bind_vars["value"].getvalue(),
cx_Oracle.Timestamp(2002, 12, 9)) oracledb.Timestamp(2002, 12, 9))
def test_2603_BindInOutSetInputSizes(self): def test_2603_bind_in_out_set_input_sizes(self):
"2603 - test binding in/out with set input sizes defined" "2603 - test binding in/out with set input sizes defined"
vars = self.cursor.setinputsizes(value = cx_Oracle.DB_TYPE_TIMESTAMP) bind_vars = self.cursor.setinputsizes(value=oracledb.DB_TYPE_TIMESTAMP)
self.cursor.execute(""" self.cursor.execute("""
begin begin
:value := :value + 5.25; :value := :value + 5.25;
end;""", end;""",
value = cx_Oracle.Timestamp(2002, 12, 12, 10, 0, 0)) value = oracledb.Timestamp(2002, 12, 12, 10, 0, 0))
self.assertEqual(vars["value"].getvalue(), self.assertEqual(bind_vars["value"].getvalue(),
cx_Oracle.Timestamp(2002, 12, 17, 16, 0, 0)) oracledb.Timestamp(2002, 12, 17, 16, 0, 0))
def test_2604_BindOutVar(self): def test_2604_bind_out_var(self):
"2604 - test binding out with cursor.var() method" "2604 - test binding out with cursor.var() method"
var = self.cursor.var(cx_Oracle.DB_TYPE_TIMESTAMP) var = self.cursor.var(oracledb.DB_TYPE_TIMESTAMP)
self.cursor.execute(""" self.cursor.execute("""
begin begin
:value := to_date('20021231 12:31:00', :value := to_date('20021231 12:31:00',
@ -94,55 +97,55 @@ class TestCase(TestEnv.BaseTestCase):
end;""", end;""",
value=var) value=var)
self.assertEqual(var.getvalue(), self.assertEqual(var.getvalue(),
cx_Oracle.Timestamp(2002, 12, 31, 12, 31, 0)) oracledb.Timestamp(2002, 12, 31, 12, 31, 0))
def test_2605_BindInOutVarDirectSet(self): def test_2605_bind_in_out_var_direct_set(self):
"2605 - test binding in/out with cursor.var() method" "2605 - test binding in/out with cursor.var() method"
var = self.cursor.var(cx_Oracle.DB_TYPE_TIMESTAMP) var = self.cursor.var(oracledb.DB_TYPE_TIMESTAMP)
var.setvalue(0, cx_Oracle.Timestamp(2002, 12, 9, 6, 0, 0)) var.setvalue(0, oracledb.Timestamp(2002, 12, 9, 6, 0, 0))
self.cursor.execute(""" self.cursor.execute("""
begin begin
:value := :value + 5.25; :value := :value + 5.25;
end;""", end;""",
value = var) value = var)
self.assertEqual(var.getvalue(), self.assertEqual(var.getvalue(),
cx_Oracle.Timestamp(2002, 12, 14, 12, 0, 0)) oracledb.Timestamp(2002, 12, 14, 12, 0, 0))
def test_2606_CursorDescription(self): def test_2606_cursor_description(self):
"2606 - test cursor description is accurate" "2606 - test cursor description is accurate"
self.cursor.execute("select * from TestTimestamps") self.cursor.execute("select * from TestTimestamps")
self.assertEqual(self.cursor.description, expected_value = [
[ ('INTCOL', cx_Oracle.DB_TYPE_NUMBER, 10, None, 9, 0, 0), ('INTCOL', oracledb.DB_TYPE_NUMBER, 10, None, 9, 0, 0),
('TIMESTAMPCOL', cx_Oracle.DB_TYPE_TIMESTAMP, 23, None, 0, 6, ('TIMESTAMPCOL', oracledb.DB_TYPE_TIMESTAMP, 23, None, 0, 6, 0),
0), ('NULLABLECOL', oracledb.DB_TYPE_TIMESTAMP, 23, None, 0, 6, 1)
('NULLABLECOL', cx_Oracle.DB_TYPE_TIMESTAMP, 23, None, 0, 6, ]
1) ]) self.assertEqual(self.cursor.description, expected_value)
def test_2607_FetchAll(self): def test_2607_fetchall(self):
"2607 - test that fetching all of the data returns the correct results" "2607 - test that fetching all of the data returns the correct results"
self.cursor.execute("select * From TestTimestamps order by IntCol") self.cursor.execute("select * From TestTimestamps order by IntCol")
self.assertEqual(self.cursor.fetchall(), self.rawData) self.assertEqual(self.cursor.fetchall(), self.raw_data)
self.assertEqual(self.cursor.fetchall(), []) self.assertEqual(self.cursor.fetchall(), [])
def test_2608_FetchMany(self): def test_2608_fetchmany(self):
"2608 - test that fetching data in chunks returns the correct results" "2608 - test that fetching data in chunks returns the correct results"
self.cursor.execute("select * From TestTimestamps order by IntCol") self.cursor.execute("select * From TestTimestamps order by IntCol")
self.assertEqual(self.cursor.fetchmany(3), self.rawData[0:3]) self.assertEqual(self.cursor.fetchmany(3), self.raw_data[0:3])
self.assertEqual(self.cursor.fetchmany(2), self.rawData[3:5]) self.assertEqual(self.cursor.fetchmany(2), self.raw_data[3:5])
self.assertEqual(self.cursor.fetchmany(4), self.rawData[5:9]) self.assertEqual(self.cursor.fetchmany(4), self.raw_data[5:9])
self.assertEqual(self.cursor.fetchmany(3), self.rawData[9:]) self.assertEqual(self.cursor.fetchmany(3), self.raw_data[9:])
self.assertEqual(self.cursor.fetchmany(3), []) self.assertEqual(self.cursor.fetchmany(3), [])
def test_2609_FetchOne(self): def test_2609_fetchone(self):
"2609 - test that fetching a single row returns the correct results" "2609 - test that fetching a single row returns the correct results"
self.cursor.execute(""" self.cursor.execute("""
select * select *
from TestTimestamps from TestTimestamps
where IntCol in (3, 4) where IntCol in (3, 4)
order by IntCol""") order by IntCol""")
self.assertEqual(self.cursor.fetchone(), self.dataByKey[3]) self.assertEqual(self.cursor.fetchone(), self.data_by_key[3])
self.assertEqual(self.cursor.fetchone(), self.dataByKey[4]) self.assertEqual(self.cursor.fetchone(), self.data_by_key[4])
self.assertEqual(self.cursor.fetchone(), None) self.assertEqual(self.cursor.fetchone(), None)
if __name__ == "__main__": if __name__ == "__main__":
TestEnv.RunTestCases() base.run_test_cases()

View File

@ -6,373 +6,370 @@
2700 - Module for testing AQ 2700 - Module for testing AQ
""" """
import TestEnv import base
import cx_Oracle import cx_Oracle as oracledb
import decimal import decimal
import threading import threading
class TestCase(TestEnv.BaseTestCase): class TestCase(base.BaseTestCase):
bookQueueName = "TEST_BOOK_QUEUE" book_type_name = "UDT_BOOK"
bookData = [ book_queue_name = "TEST_BOOK_QUEUE"
("Wings of Fire", "A.P.J. Abdul Kalam", book_data = [
decimal.Decimal("15.75")), ("Wings of Fire", "A.P.J. Abdul Kalam", decimal.Decimal("15.75")),
("The Story of My Life", "Hellen Keller", ("The Story of My Life", "Hellen Keller", decimal.Decimal("10.50")),
decimal.Decimal("10.50")), ("The Chronicles of Narnia", "C.S. Lewis", decimal.Decimal("25.25"))
("The Chronicles of Narnia", "C.S. Lewis",
decimal.Decimal("25.25"))
] ]
def __clearBooksQueue(self): def __clear_books_queue(self):
booksType = self.connection.gettype("UDT_BOOK") books_type = self.connection.gettype(self.book_type_name)
book = booksType.newobject() book = books_type.newobject()
options = self.connection.deqoptions() options = self.connection.deqoptions()
options.wait = cx_Oracle.DEQ_NO_WAIT options.wait = oracledb.DEQ_NO_WAIT
options.deliverymode = cx_Oracle.MSG_PERSISTENT_OR_BUFFERED options.deliverymode = oracledb.MSG_PERSISTENT_OR_BUFFERED
options.visibility = cx_Oracle.ENQ_IMMEDIATE options.visibility = oracledb.ENQ_IMMEDIATE
props = self.connection.msgproperties() props = self.connection.msgproperties()
while self.connection.deq(self.bookQueueName, options, props, book): while self.connection.deq(self.book_queue_name, options, props, book):
pass pass
def __deqInThread(self, results): def __deq_in_thread(self, results):
connection = TestEnv.GetConnection() connection = base.get_connection()
booksType = connection.gettype("UDT_BOOK") books_type = connection.gettype(self.book_type_name)
book = booksType.newobject() book = books_type.newobject()
options = connection.deqoptions() options = connection.deqoptions()
options.wait = 10 options.wait = 10
props = connection.msgproperties() props = connection.msgproperties()
if connection.deq(self.bookQueueName, options, props, book): if connection.deq(self.book_queue_name, options, props, book):
results.append((book.TITLE, book.AUTHORS, book.PRICE)) results.append((book.TITLE, book.AUTHORS, book.PRICE))
connection.commit() connection.commit()
def __verifyAttribute(self, obj, attrName, value): def __verify_attr(self, obj, attrName, value):
setattr(obj, attrName, value) setattr(obj, attrName, value)
self.assertEqual(getattr(obj, attrName), value) self.assertEqual(getattr(obj, attrName), value)
def test_2700_DeqEmpty(self): def test_2700_deq_empty(self):
"2700 - test dequeuing an empty queue" "2700 - test dequeuing an empty queue"
self.__clearBooksQueue() self.__clear_books_queue()
booksType = self.connection.gettype("UDT_BOOK") books_type = self.connection.gettype(self.book_type_name)
book = booksType.newobject() book = books_type.newobject()
options = self.connection.deqoptions() options = self.connection.deqoptions()
options.wait = cx_Oracle.DEQ_NO_WAIT options.wait = oracledb.DEQ_NO_WAIT
props = self.connection.msgproperties() props = self.connection.msgproperties()
messageId = self.connection.deq(self.bookQueueName, options, props, message_id = self.connection.deq(self.book_queue_name, options, props,
book) book)
self.assertTrue(messageId is None) self.assertTrue(message_id is None)
def test_2701_DeqEnq(self): def test_2701_deq_enq(self):
"2701 - test enqueuing and dequeuing multiple messages" "2701 - test enqueuing and dequeuing multiple messages"
self.__clearBooksQueue() self.__clear_books_queue()
booksType = self.connection.gettype("UDT_BOOK") books_type = self.connection.gettype(self.book_type_name)
options = self.connection.enqoptions() options = self.connection.enqoptions()
props = self.connection.msgproperties() props = self.connection.msgproperties()
for title, authors, price in self.bookData: for title, authors, price in self.book_data:
book = booksType.newobject() book = books_type.newobject()
book.TITLE = title book.TITLE = title
book.AUTHORS = authors book.AUTHORS = authors
book.PRICE = price book.PRICE = price
self.connection.enq(self.bookQueueName, options, props, book) self.connection.enq(self.book_queue_name, options, props, book)
options = self.connection.deqoptions() options = self.connection.deqoptions()
options.navigation = cx_Oracle.DEQ_FIRST_MSG options.navigation = oracledb.DEQ_FIRST_MSG
options.wait = cx_Oracle.DEQ_NO_WAIT options.wait = oracledb.DEQ_NO_WAIT
results = [] results = []
while self.connection.deq(self.bookQueueName, options, props, book): while self.connection.deq(self.book_queue_name, options, props, book):
row = (book.TITLE, book.AUTHORS, book.PRICE) row = (book.TITLE, book.AUTHORS, book.PRICE)
results.append(row) results.append(row)
self.connection.commit() self.connection.commit()
self.assertEqual(results, self.bookData) self.assertEqual(results, self.book_data)
def test_2702_DeqModeRemoveNoData(self): def test_2702_deq_mode_remove_no_data(self):
"2702 - test dequeuing with DEQ_REMOVE_NODATA option" "2702 - test dequeuing with DEQ_REMOVE_NODATA option"
self.__clearBooksQueue() self.__clear_books_queue()
booksType = self.connection.gettype("UDT_BOOK") books_type = self.connection.gettype(self.book_type_name)
book = booksType.newobject() book = books_type.newobject()
title, authors, price = self.bookData[1] title, authors, price = self.book_data[1]
book.TITLE = title book.TITLE = title
book.AUTHORS = authors book.AUTHORS = authors
book.PRICE = price book.PRICE = price
options = self.connection.enqoptions() options = self.connection.enqoptions()
props = self.connection.msgproperties() props = self.connection.msgproperties()
self.connection.enq(self.bookQueueName, options, props, book) self.connection.enq(self.book_queue_name, options, props, book)
options = self.connection.deqoptions() options = self.connection.deqoptions()
options.navigation = cx_Oracle.DEQ_FIRST_MSG options.navigation = oracledb.DEQ_FIRST_MSG
options.wait = cx_Oracle.DEQ_NO_WAIT options.wait = oracledb.DEQ_NO_WAIT
options.mode = cx_Oracle.DEQ_REMOVE_NODATA options.mode = oracledb.DEQ_REMOVE_NODATA
book = booksType.newobject() book = books_type.newobject()
messageId = self.connection.deq(self.bookQueueName, options, props, message_id = self.connection.deq(self.book_queue_name, options, props,
book) book)
self.connection.commit() self.connection.commit()
self.assertTrue(messageId is not None) self.assertTrue(message_id is not None)
self.assertEqual(book.TITLE, "") self.assertEqual(book.TITLE, "")
def test_2703_DeqOptions(self): def test_2703_deq_options(self):
"2703 - test getting/setting dequeue options attributes" "2703 - test getting/setting dequeue options attributes"
options = self.connection.deqoptions() options = self.connection.deqoptions()
self.__verifyAttribute(options, "condition", "TEST_CONDITION") self.__verify_attr(options, "condition", "TEST_CONDITION")
self.__verifyAttribute(options, "consumername", "TEST_CONSUMERNAME") self.__verify_attr(options, "consumername", "TEST_CONSUMERNAME")
self.__verifyAttribute(options, "correlation", "TEST_CORRELATION") self.__verify_attr(options, "correlation", "TEST_CORRELATION")
self.__verifyAttribute(options, "mode", cx_Oracle.DEQ_LOCKED) self.__verify_attr(options, "mode", oracledb.DEQ_LOCKED)
self.__verifyAttribute(options, "navigation", self.__verify_attr(options, "navigation",
cx_Oracle.DEQ_NEXT_TRANSACTION) oracledb.DEQ_NEXT_TRANSACTION)
self.__verifyAttribute(options, "transformation", self.__verify_attr(options, "transformation", "TEST_TRANSFORMATION")
"TEST_TRANSFORMATION") self.__verify_attr(options, "visibility", oracledb.ENQ_IMMEDIATE)
self.__verifyAttribute(options, "visibility", cx_Oracle.ENQ_IMMEDIATE) self.__verify_attr(options, "wait", 1287)
self.__verifyAttribute(options, "wait", 1287) self.__verify_attr(options, "msgid", b'mID')
self.__verifyAttribute(options, "msgid", b'mID')
def test_2704_DeqWithWait(self): def test_2704_deq_with_wait(self):
"2704 - test waiting for dequeue" "2704 - test waiting for dequeue"
self.__clearBooksQueue() self.__clear_books_queue()
results = [] results = []
thread = threading.Thread(target = self.__deqInThread, thread = threading.Thread(target = self.__deq_in_thread,
args = (results,)) args = (results,))
thread.start() thread.start()
booksType = self.connection.gettype("UDT_BOOK") books_type = self.connection.gettype(self.book_type_name)
book = booksType.newobject() book = books_type.newobject()
title, authors, price = self.bookData[0] title, authors, price = self.book_data[0]
book.TITLE = title book.TITLE = title
book.AUTHORS = authors book.AUTHORS = authors
book.PRICE = price book.PRICE = price
options = self.connection.enqoptions() options = self.connection.enqoptions()
props = self.connection.msgproperties() props = self.connection.msgproperties()
self.connection.enq(self.bookQueueName, options, props, book) self.connection.enq(self.book_queue_name, options, props, book)
self.connection.commit() self.connection.commit()
thread.join() thread.join()
self.assertEqual(results, [(title, authors, price)]) self.assertEqual(results, [(title, authors, price)])
def test_2705_EnqOptions(self): def test_2705_enq_options(self):
"2705 - test getting/setting enqueue options attributes" "2705 - test getting/setting enqueue options attributes"
options = self.connection.enqoptions() options = self.connection.enqoptions()
self.__verifyAttribute(options, "visibility", cx_Oracle.ENQ_IMMEDIATE) self.__verify_attr(options, "visibility", oracledb.ENQ_IMMEDIATE)
def test_2706_ErrorsForInvalidValues(self): def test_2706_errors_for_invalid_values(self):
"2706 - test errors for invalid values for options" "2706 - test errors for invalid values for options"
booksType = self.connection.gettype("UDT_BOOK") books_type = self.connection.gettype(self.book_type_name)
book = booksType.newobject() book = books_type.newobject()
options = self.connection.enqoptions() options = self.connection.enqoptions()
props = self.connection.msgproperties() props = self.connection.msgproperties()
self.assertRaises(TypeError, self.connection.deq, self.bookQueueName, self.assertRaises(TypeError, self.connection.deq, self.book_queue_name,
options, props, book) options, props, book)
options = self.connection.deqoptions() options = self.connection.deqoptions()
self.assertRaises(TypeError, self.connection.enq, self.bookQueueName, self.assertRaises(TypeError, self.connection.enq, self.book_queue_name,
options, props, book) options, props, book)
def test_2707_MsgProps(self): def test_2707_msg_props(self):
"2707 - test getting/setting message properties attributes" "2707 - test getting/setting message properties attributes"
props = self.connection.msgproperties() props = self.connection.msgproperties()
self.__verifyAttribute(props, "correlation", "TEST_CORRELATION") self.__verify_attr(props, "correlation", "TEST_CORRELATION")
self.__verifyAttribute(props, "delay", 60) self.__verify_attr(props, "delay", 60)
self.__verifyAttribute(props, "exceptionq", "TEST_EXCEPTIONQ") self.__verify_attr(props, "exceptionq", "TEST_EXCEPTIONQ")
self.__verifyAttribute(props, "expiration", 30) self.__verify_attr(props, "expiration", 30)
self.assertEqual(props.attempts, 0) self.assertEqual(props.attempts, 0)
self.__verifyAttribute(props, "priority", 1) self.__verify_attr(props, "priority", 1)
self.__verifyAttribute(props, "msgid", b'mID') self.__verify_attr(props, "msgid", b'mID')
self.assertEqual(props.state, cx_Oracle.MSG_READY) self.assertEqual(props.state, oracledb.MSG_READY)
self.assertEqual(props.deliverymode, 0) self.assertEqual(props.deliverymode, 0)
def test_2708_VisibilityModeCommit(self): def test_2708_visibility_mode_commit(self):
"2708 - test enqueue visibility option - ENQ_ON_COMMIT" "2708 - test enqueue visibility option - ENQ_ON_COMMIT"
self.__clearBooksQueue() self.__clear_books_queue()
booksType = self.connection.gettype("UDT_BOOK") books_type = self.connection.gettype(self.book_type_name)
book = booksType.newobject() book = books_type.newobject()
book.TITLE, book.AUTHORS, book.PRICE = self.bookData[0] book.TITLE, book.AUTHORS, book.PRICE = self.book_data[0]
enqOptions = self.connection.enqoptions() enq_options = self.connection.enqoptions()
enqOptions.visibility = cx_Oracle.ENQ_ON_COMMIT enq_options.visibility = oracledb.ENQ_ON_COMMIT
props = self.connection.msgproperties() props = self.connection.msgproperties()
self.connection.enq(self.bookQueueName, enqOptions, props, book) self.connection.enq(self.book_queue_name, enq_options, props, book)
otherConnection = TestEnv.GetConnection() other_connection = base.get_connection()
deqOptions = otherConnection.deqoptions() deq_options = other_connection.deqoptions()
deqOptions.navigation = cx_Oracle.DEQ_FIRST_MSG deq_options.navigation = oracledb.DEQ_FIRST_MSG
deqOptions.wait = cx_Oracle.DEQ_NO_WAIT deq_options.wait = oracledb.DEQ_NO_WAIT
booksType = otherConnection.gettype("UDT_BOOK") books_type = other_connection.gettype(self.book_type_name)
book = booksType.newobject() book = books_type.newobject()
props = otherConnection.msgproperties() props = other_connection.msgproperties()
messageId = otherConnection.deq(self.bookQueueName, deqOptions, props, message_id = other_connection.deq(self.book_queue_name, deq_options,
book) props, book)
self.assertTrue(messageId is None) self.assertTrue(message_id is None)
self.connection.commit() self.connection.commit()
messageId = otherConnection.deq(self.bookQueueName, deqOptions, props, message_id = other_connection.deq(self.book_queue_name, deq_options,
book) props, book)
self.assertTrue(messageId is not None) self.assertTrue(message_id is not None)
def test_2709_VisibilityModeImmediate(self): def test_2709_visibility_mode_immediate(self):
"2709 - test enqueue visibility option - ENQ_IMMEDIATE" "2709 - test enqueue visibility option - ENQ_IMMEDIATE"
self.__clearBooksQueue() self.__clear_books_queue()
booksType = self.connection.gettype("UDT_BOOK") books_type = self.connection.gettype(self.book_type_name)
book = booksType.newobject() book = books_type.newobject()
book.TITLE, book.AUTHORS, book.PRICE = self.bookData[0] book.TITLE, book.AUTHORS, book.PRICE = self.book_data[0]
enqOptions = self.connection.enqoptions() enq_options = self.connection.enqoptions()
enqOptions.visibility = cx_Oracle.ENQ_IMMEDIATE enq_options.visibility = oracledb.ENQ_IMMEDIATE
props = self.connection.msgproperties() props = self.connection.msgproperties()
self.connection.enq(self.bookQueueName, enqOptions, props, book) self.connection.enq(self.book_queue_name, enq_options, props, book)
otherConnection = TestEnv.GetConnection() other_connection = base.get_connection()
deqOptions = otherConnection.deqoptions() deq_options = other_connection.deqoptions()
deqOptions.navigation = cx_Oracle.DEQ_FIRST_MSG deq_options.navigation = oracledb.DEQ_FIRST_MSG
deqOptions.visibility = cx_Oracle.DEQ_ON_COMMIT deq_options.visibility = oracledb.DEQ_ON_COMMIT
deqOptions.wait = cx_Oracle.DEQ_NO_WAIT deq_options.wait = oracledb.DEQ_NO_WAIT
booksType = otherConnection.gettype("UDT_BOOK") books_type = other_connection.gettype(self.book_type_name)
book = booksType.newobject() book = books_type.newobject()
props = otherConnection.msgproperties() props = other_connection.msgproperties()
otherConnection.deq(self.bookQueueName, deqOptions, props, book) other_connection.deq(self.book_queue_name, deq_options, props, book)
results = (book.TITLE, book.AUTHORS, book.PRICE) results = (book.TITLE, book.AUTHORS, book.PRICE)
otherConnection.commit() other_connection.commit()
self.assertEqual(results, self.bookData[0]) self.assertEqual(results, self.book_data[0])
def test_2710_DeliveryModeSameBuffered(self): def test_2710_delivery_mode_same_buffered(self):
"2710 - test enqueue/dequeue delivery modes identical - buffered" "2710 - test enqueue/dequeue delivery modes identical - buffered"
self.__clearBooksQueue() self.__clear_books_queue()
booksType = self.connection.gettype("UDT_BOOK") books_type = self.connection.gettype(self.book_type_name)
book = booksType.newobject() book = books_type.newobject()
book.TITLE, book.AUTHORS, book.PRICE = self.bookData[0] book.TITLE, book.AUTHORS, book.PRICE = self.book_data[0]
enqOptions = self.connection.enqoptions() enq_options = self.connection.enqoptions()
enqOptions.deliverymode = cx_Oracle.MSG_BUFFERED enq_options.deliverymode = oracledb.MSG_BUFFERED
enqOptions.visibility = cx_Oracle.ENQ_IMMEDIATE enq_options.visibility = oracledb.ENQ_IMMEDIATE
props = self.connection.msgproperties() props = self.connection.msgproperties()
self.connection.enq(self.bookQueueName, enqOptions, props, book) self.connection.enq(self.book_queue_name, enq_options, props, book)
otherConnection = TestEnv.GetConnection() other_connection = base.get_connection()
deqOptions = otherConnection.deqoptions() deq_options = other_connection.deqoptions()
deqOptions.deliverymode = cx_Oracle.MSG_BUFFERED deq_options.deliverymode = oracledb.MSG_BUFFERED
deqOptions.navigation = cx_Oracle.DEQ_FIRST_MSG deq_options.navigation = oracledb.DEQ_FIRST_MSG
deqOptions.visibility = cx_Oracle.DEQ_IMMEDIATE deq_options.visibility = oracledb.DEQ_IMMEDIATE
deqOptions.wait = cx_Oracle.DEQ_NO_WAIT deq_options.wait = oracledb.DEQ_NO_WAIT
booksType = otherConnection.gettype("UDT_BOOK") books_type = other_connection.gettype(self.book_type_name)
book = booksType.newobject() book = books_type.newobject()
props = otherConnection.msgproperties() props = other_connection.msgproperties()
otherConnection.deq(self.bookQueueName, deqOptions, props, book) other_connection.deq(self.book_queue_name, deq_options, props, book)
results = (book.TITLE, book.AUTHORS, book.PRICE) results = (book.TITLE, book.AUTHORS, book.PRICE)
otherConnection.commit() other_connection.commit()
self.assertEqual(results, self.bookData[0]) self.assertEqual(results, self.book_data[0])
def test_2711_DeliveryModeSamePersistent(self): def test_2711_delivery_mode_same_persistent(self):
"2711 - test enqueue/dequeue delivery modes identical - persistent" "2711 - test enqueue/dequeue delivery modes identical - persistent"
self.__clearBooksQueue() self.__clear_books_queue()
booksType = self.connection.gettype("UDT_BOOK") books_type = self.connection.gettype(self.book_type_name)
book = booksType.newobject() book = books_type.newobject()
book.TITLE, book.AUTHORS, book.PRICE = self.bookData[0] book.TITLE, book.AUTHORS, book.PRICE = self.book_data[0]
enqOptions = self.connection.enqoptions() enq_options = self.connection.enqoptions()
enqOptions.deliverymode = cx_Oracle.MSG_PERSISTENT enq_options.deliverymode = oracledb.MSG_PERSISTENT
enqOptions.visibility = cx_Oracle.ENQ_IMMEDIATE enq_options.visibility = oracledb.ENQ_IMMEDIATE
props = self.connection.msgproperties() props = self.connection.msgproperties()
self.connection.enq(self.bookQueueName, enqOptions, props, book) self.connection.enq(self.book_queue_name, enq_options, props, book)
otherConnection = TestEnv.GetConnection() other_connection = base.get_connection()
deqOptions = otherConnection.deqoptions() deq_options = other_connection.deqoptions()
deqOptions.deliverymode = cx_Oracle.MSG_PERSISTENT deq_options.deliverymode = oracledb.MSG_PERSISTENT
deqOptions.navigation = cx_Oracle.DEQ_FIRST_MSG deq_options.navigation = oracledb.DEQ_FIRST_MSG
deqOptions.visibility = cx_Oracle.DEQ_IMMEDIATE deq_options.visibility = oracledb.DEQ_IMMEDIATE
deqOptions.wait = cx_Oracle.DEQ_NO_WAIT deq_options.wait = oracledb.DEQ_NO_WAIT
booksType = otherConnection.gettype("UDT_BOOK") books_type = other_connection.gettype(self.book_type_name)
book = booksType.newobject() book = books_type.newobject()
props = otherConnection.msgproperties() props = other_connection.msgproperties()
otherConnection.deq(self.bookQueueName, deqOptions, props, book) other_connection.deq(self.book_queue_name, deq_options, props, book)
results = (book.TITLE, book.AUTHORS, book.PRICE) results = (book.TITLE, book.AUTHORS, book.PRICE)
otherConnection.commit() other_connection.commit()
self.assertEqual(results, self.bookData[0]) self.assertEqual(results, self.book_data[0])
def test_2712_DeliveryModeSamePersistentBuffered(self): def test_2712_delivery_mode_same_persistent_buffered(self):
"2712 - test enqueue/dequeue delivery modes the same" "2712 - test enqueue/dequeue delivery modes the same"
self.__clearBooksQueue() self.__clear_books_queue()
booksType = self.connection.gettype("UDT_BOOK") books_type = self.connection.gettype(self.book_type_name)
book = booksType.newobject() book = books_type.newobject()
book.TITLE, book.AUTHORS, book.PRICE = self.bookData[0] book.TITLE, book.AUTHORS, book.PRICE = self.book_data[0]
enqOptions = self.connection.enqoptions() enq_options = self.connection.enqoptions()
enqOptions.deliverymode = cx_Oracle.MSG_PERSISTENT_OR_BUFFERED enq_options.deliverymode = oracledb.MSG_PERSISTENT_OR_BUFFERED
enqOptions.visibility = cx_Oracle.ENQ_IMMEDIATE enq_options.visibility = oracledb.ENQ_IMMEDIATE
props = self.connection.msgproperties() props = self.connection.msgproperties()
self.connection.enq(self.bookQueueName, enqOptions, props, book) self.connection.enq(self.book_queue_name, enq_options, props, book)
otherConnection = TestEnv.GetConnection() other_connection = base.get_connection()
deqOptions = otherConnection.deqoptions() deq_options = other_connection.deqoptions()
deqOptions.deliverymode = cx_Oracle.MSG_PERSISTENT_OR_BUFFERED deq_options.deliverymode = oracledb.MSG_PERSISTENT_OR_BUFFERED
deqOptions.navigation = cx_Oracle.DEQ_FIRST_MSG deq_options.navigation = oracledb.DEQ_FIRST_MSG
deqOptions.visibility = cx_Oracle.DEQ_IMMEDIATE deq_options.visibility = oracledb.DEQ_IMMEDIATE
deqOptions.wait = cx_Oracle.DEQ_NO_WAIT deq_options.wait = oracledb.DEQ_NO_WAIT
booksType = otherConnection.gettype("UDT_BOOK") books_type = other_connection.gettype(self.book_type_name)
book = booksType.newobject() book = books_type.newobject()
props = otherConnection.msgproperties() props = other_connection.msgproperties()
otherConnection.deq(self.bookQueueName, deqOptions, props, book) other_connection.deq(self.book_queue_name, deq_options, props, book)
results = (book.TITLE, book.AUTHORS, book.PRICE) results = (book.TITLE, book.AUTHORS, book.PRICE)
otherConnection.commit() other_connection.commit()
self.assertEqual(results, self.bookData[0]) self.assertEqual(results, self.book_data[0])
def test_2713_DeliveryModeDifferent(self): def test_2713_delivery_mode_different(self):
"2713 - test enqueue/dequeue delivery modes different" "2713 - test enqueue/dequeue delivery modes different"
self.__clearBooksQueue() self.__clear_books_queue()
booksType = self.connection.gettype("UDT_BOOK") books_type = self.connection.gettype(self.book_type_name)
book = booksType.newobject() book = books_type.newobject()
book.TITLE, book.AUTHORS, book.PRICE = self.bookData[0] book.TITLE, book.AUTHORS, book.PRICE = self.book_data[0]
enqOptions = self.connection.enqoptions() enq_options = self.connection.enqoptions()
enqOptions.deliverymode = cx_Oracle.MSG_BUFFERED enq_options.deliverymode = oracledb.MSG_BUFFERED
enqOptions.visibility = cx_Oracle.ENQ_IMMEDIATE enq_options.visibility = oracledb.ENQ_IMMEDIATE
props = self.connection.msgproperties() props = self.connection.msgproperties()
self.connection.enq(self.bookQueueName, enqOptions, props, book) self.connection.enq(self.book_queue_name, enq_options, props, book)
otherConnection = TestEnv.GetConnection() other_connection = base.get_connection()
deqOptions = otherConnection.deqoptions() deq_options = other_connection.deqoptions()
deqOptions.deliverymode = cx_Oracle.MSG_PERSISTENT deq_options.deliverymode = oracledb.MSG_PERSISTENT
deqOptions.navigation = cx_Oracle.DEQ_FIRST_MSG deq_options.navigation = oracledb.DEQ_FIRST_MSG
deqOptions.visibility = cx_Oracle.DEQ_IMMEDIATE deq_options.visibility = oracledb.DEQ_IMMEDIATE
deqOptions.wait = cx_Oracle.DEQ_NO_WAIT deq_options.wait = oracledb.DEQ_NO_WAIT
booksType = otherConnection.gettype("UDT_BOOK") books_type = other_connection.gettype(self.book_type_name)
book = booksType.newobject() book = books_type.newobject()
props = otherConnection.msgproperties() props = other_connection.msgproperties()
messageId = otherConnection.deq(self.bookQueueName, deqOptions, props, message_id = other_connection.deq(self.book_queue_name, deq_options,
book) props, book)
self.assertTrue(messageId is None) self.assertTrue(message_id is None)
def test_2714_DequeueTransformation(self): def test_2714_dequeue_transformation(self):
"2714 - test dequeue transformation" "2714 - test dequeue transformation"
self.__clearBooksQueue() self.__clear_books_queue()
booksType = self.connection.gettype("UDT_BOOK") books_type = self.connection.gettype(self.book_type_name)
book = booksType.newobject() book = books_type.newobject()
book.TITLE, book.AUTHORS, book.PRICE = self.bookData[0] book.TITLE, book.AUTHORS, book.PRICE = self.book_data[0]
expectedPrice = book.PRICE + 10 expectedPrice = book.PRICE + 10
enqOptions = self.connection.enqoptions() enq_options = self.connection.enqoptions()
props = self.connection.msgproperties() props = self.connection.msgproperties()
self.connection.enq(self.bookQueueName, enqOptions, props, book) self.connection.enq(self.book_queue_name, enq_options, props, book)
self.connection.commit() self.connection.commit()
otherConnection = TestEnv.GetConnection() other_connection = base.get_connection()
deqOptions = otherConnection.deqoptions() deq_options = other_connection.deqoptions()
deqOptions.navigation = cx_Oracle.DEQ_FIRST_MSG deq_options.navigation = oracledb.DEQ_FIRST_MSG
deqOptions.visibility = cx_Oracle.DEQ_IMMEDIATE deq_options.visibility = oracledb.DEQ_IMMEDIATE
deqOptions.transformation = "%s.transform2" % self.connection.username deq_options.transformation = "%s.transform2" % self.connection.username
deqOptions.wait = cx_Oracle.DEQ_NO_WAIT deq_options.wait = oracledb.DEQ_NO_WAIT
booksType = otherConnection.gettype("UDT_BOOK") books_type = other_connection.gettype(self.book_type_name)
book = booksType.newobject() book = books_type.newobject()
props = otherConnection.msgproperties() props = other_connection.msgproperties()
otherConnection.deq(self.bookQueueName, deqOptions, props, book) other_connection.deq(self.book_queue_name, deq_options, props, book)
otherPrice = book.PRICE otherPrice = book.PRICE
self.assertEqual(otherPrice, expectedPrice) self.assertEqual(otherPrice, expectedPrice)
def test_2715_EnqueueTransformation(self): def test_2715_enqueue_transformation(self):
"2715 - test enqueue transformation" "2715 - test enqueue transformation"
self.__clearBooksQueue() self.__clear_books_queue()
booksType = self.connection.gettype("UDT_BOOK") books_type = self.connection.gettype(self.book_type_name)
book = booksType.newobject() book = books_type.newobject()
book.TITLE, book.AUTHORS, book.PRICE = self.bookData[0] book.TITLE, book.AUTHORS, book.PRICE = self.book_data[0]
expectedPrice = book.PRICE + 5 expectedPrice = book.PRICE + 5
enqOptions = self.connection.enqoptions() enq_options = self.connection.enqoptions()
enqOptions.transformation = "%s.transform1" % self.connection.username enq_options.transformation = "%s.transform1" % self.connection.username
props = self.connection.msgproperties() props = self.connection.msgproperties()
self.connection.enq(self.bookQueueName, enqOptions, props, book) self.connection.enq(self.book_queue_name, enq_options, props, book)
self.connection.commit() self.connection.commit()
otherConnection = TestEnv.GetConnection() other_connection = base.get_connection()
deqOptions = otherConnection.deqoptions() deq_options = other_connection.deqoptions()
deqOptions.navigation = cx_Oracle.DEQ_FIRST_MSG deq_options.navigation = oracledb.DEQ_FIRST_MSG
deqOptions.visibility = cx_Oracle.DEQ_IMMEDIATE deq_options.visibility = oracledb.DEQ_IMMEDIATE
deqOptions.wait = cx_Oracle.DEQ_NO_WAIT deq_options.wait = oracledb.DEQ_NO_WAIT
booksType = otherConnection.gettype("UDT_BOOK") books_type = other_connection.gettype(self.book_type_name)
book = booksType.newobject() book = books_type.newobject()
props = otherConnection.msgproperties() props = other_connection.msgproperties()
otherConnection.deq(self.bookQueueName, deqOptions, props, book) other_connection.deq(self.book_queue_name, deq_options, props, book)
otherPrice = book.PRICE otherPrice = book.PRICE
self.assertEqual(otherPrice, expectedPrice) self.assertEqual(otherPrice, expectedPrice)
if __name__ == "__main__": if __name__ == "__main__":
TestEnv.RunTestCases() base.run_test_cases()

View File

@ -6,9 +6,9 @@
2800 - Module for testing AQ Bulk enqueue/dequeue 2800 - Module for testing AQ Bulk enqueue/dequeue
""" """
import TestEnv import base
import cx_Oracle import cx_Oracle as oracledb
import decimal import decimal
import threading import threading
@ -28,13 +28,13 @@ RAW_PAYLOAD_DATA = [
"The twelfth and final message" "The twelfth and final message"
] ]
class TestCase(TestEnv.BaseTestCase): class TestCase(base.BaseTestCase):
def __deqInThread(self, results): def __deq_in_thread(self, results):
connection = TestEnv.GetConnection(threaded=True) connection = base.get_connection(threaded=True)
queue = connection.queue(RAW_QUEUE_NAME) queue = connection.queue(RAW_QUEUE_NAME)
queue.deqOptions.wait = 10 queue.deqOptions.wait = 10
queue.deqOptions.navigation = cx_Oracle.DEQ_FIRST_MSG queue.deqOptions.navigation = oracledb.DEQ_FIRST_MSG
while len(results) < len(RAW_PAYLOAD_DATA): while len(results) < len(RAW_PAYLOAD_DATA):
messages = queue.deqMany(5) messages = queue.deqMany(5)
if not messages: if not messages:
@ -43,18 +43,18 @@ class TestCase(TestEnv.BaseTestCase):
results.append(m.payload.decode(connection.encoding)) results.append(m.payload.decode(connection.encoding))
connection.commit() connection.commit()
def __getAndClearRawQueue(self): def __get_and_clear_raw_queue(self):
queue = self.connection.queue(RAW_QUEUE_NAME) queue = self.connection.queue(RAW_QUEUE_NAME)
queue.deqOptions.wait = cx_Oracle.DEQ_NO_WAIT queue.deqOptions.wait = oracledb.DEQ_NO_WAIT
queue.deqOptions.navigation = cx_Oracle.DEQ_FIRST_MSG queue.deqOptions.navigation = oracledb.DEQ_FIRST_MSG
while queue.deqOne(): while queue.deqOne():
pass pass
self.connection.commit() self.connection.commit()
return queue return queue
def test_2800_EnqAndDeq(self): def test_2800_enq_and_deq(self):
"2800 - test bulk enqueue and dequeue" "2800 - test bulk enqueue and dequeue"
queue = self.__getAndClearRawQueue() queue = self.__get_and_clear_raw_queue()
messages = [self.connection.msgproperties(payload=d) \ messages = [self.connection.msgproperties(payload=d) \
for d in RAW_PAYLOAD_DATA] for d in RAW_PAYLOAD_DATA]
queue.enqMany(messages) queue.enqMany(messages)
@ -63,73 +63,73 @@ class TestCase(TestEnv.BaseTestCase):
self.connection.commit() self.connection.commit()
self.assertEqual(data, RAW_PAYLOAD_DATA) self.assertEqual(data, RAW_PAYLOAD_DATA)
def test_2801_DequeueEmpty(self): def test_2801_dequeue_empty(self):
"2801 - test empty bulk dequeue" "2801 - test empty bulk dequeue"
queue = self.__getAndClearRawQueue() queue = self.__get_and_clear_raw_queue()
messages = queue.deqMany(5) messages = queue.deqMany(5)
self.connection.commit() self.connection.commit()
self.assertEqual(messages, []) self.assertEqual(messages, [])
def test_2802_DeqWithWait(self): def test_2802_deq_with_wait(self):
"2802 - test bulk dequeue with wait" "2802 - test bulk dequeue with wait"
queue = self.__getAndClearRawQueue() queue = self.__get_and_clear_raw_queue()
results = [] results = []
thread = threading.Thread(target=self.__deqInThread, args=(results,)) thread = threading.Thread(target=self.__deq_in_thread, args=(results,))
thread.start() thread.start()
messages = [self.connection.msgproperties(payload=d) \ messages = [self.connection.msgproperties(payload=d) \
for d in RAW_PAYLOAD_DATA] for d in RAW_PAYLOAD_DATA]
queue.enqOptions.visibility = cx_Oracle.ENQ_IMMEDIATE queue.enqOptions.visibility = oracledb.ENQ_IMMEDIATE
queue.enqMany(messages) queue.enqMany(messages)
thread.join() thread.join()
self.assertEqual(results, RAW_PAYLOAD_DATA) self.assertEqual(results, RAW_PAYLOAD_DATA)
def test_2803_EnqAndDeqMultipleTimes(self): def test_2803_enq_and_deq_multiple_times(self):
"2803 - test enqueue and dequeue multiple times" "2803 - test enqueue and dequeue multiple times"
queue = self.__getAndClearRawQueue() queue = self.__get_and_clear_raw_queue()
dataToEnqueue = RAW_PAYLOAD_DATA data_to_enqueue = RAW_PAYLOAD_DATA
for num in (2, 6, 4): for num in (2, 6, 4):
messages = [self.connection.msgproperties(payload=d) \ messages = [self.connection.msgproperties(payload=d) \
for d in dataToEnqueue[:num]] for d in data_to_enqueue[:num]]
dataToEnqueue = dataToEnqueue[num:] data_to_enqueue = data_to_enqueue[num:]
queue.enqMany(messages) queue.enqMany(messages)
self.connection.commit() self.connection.commit()
allData = [] all_data = []
for num in (3, 5, 10): for num in (3, 5, 10):
messages = queue.deqMany(num) messages = queue.deqMany(num)
allData.extend(m.payload.decode(self.connection.encoding) \ all_data.extend(m.payload.decode(self.connection.encoding) \
for m in messages) for m in messages)
self.connection.commit() self.connection.commit()
self.assertEqual(allData, RAW_PAYLOAD_DATA) self.assertEqual(all_data, RAW_PAYLOAD_DATA)
def test_2804_EnqAndDeqVisibility(self): def test_2804_enq_and_deq_visibility(self):
"2804 - test visibility option for enqueue and dequeue" "2804 - test visibility option for enqueue and dequeue"
queue = self.__getAndClearRawQueue() queue = self.__get_and_clear_raw_queue()
# first test with ENQ_ON_COMMIT (commit required) # first test with ENQ_ON_COMMIT (commit required)
queue.enqOptions.visibility = cx_Oracle.ENQ_ON_COMMIT queue.enqOptions.visibility = oracledb.ENQ_ON_COMMIT
props1 = self.connection.msgproperties(payload="A first message") props1 = self.connection.msgproperties(payload="A first message")
props2 = self.connection.msgproperties(payload="A second message") props2 = self.connection.msgproperties(payload="A second message")
queue.enqMany([props1, props2]) queue.enqMany([props1, props2])
otherConnection = TestEnv.GetConnection() other_connection = base.get_connection()
otherQueue = otherConnection.queue(RAW_QUEUE_NAME) other_queue = other_connection.queue(RAW_QUEUE_NAME)
otherQueue.deqOptions.wait = cx_Oracle.DEQ_NO_WAIT other_queue.deqOptions.wait = oracledb.DEQ_NO_WAIT
otherQueue.deqOptions.visibility = cx_Oracle.DEQ_ON_COMMIT other_queue.deqOptions.visibility = oracledb.DEQ_ON_COMMIT
messages = otherQueue.deqMany(5) messages = other_queue.deqMany(5)
self.assertEqual(len(messages), 0) self.assertEqual(len(messages), 0)
self.connection.commit() self.connection.commit()
messages = otherQueue.deqMany(5) messages = other_queue.deqMany(5)
self.assertEqual(len(messages), 2) self.assertEqual(len(messages), 2)
otherConnection.rollback() other_connection.rollback()
# second test with ENQ_IMMEDIATE (no commit required) # second test with ENQ_IMMEDIATE (no commit required)
queue.enqOptions.visibility = cx_Oracle.ENQ_IMMEDIATE queue.enqOptions.visibility = oracledb.ENQ_IMMEDIATE
otherQueue.deqOptions.visibility = cx_Oracle.DEQ_IMMEDIATE other_queue.deqOptions.visibility = oracledb.DEQ_IMMEDIATE
queue.enqMany([props1, props2]) queue.enqMany([props1, props2])
messages = otherQueue.deqMany(5) messages = other_queue.deqMany(5)
self.assertEqual(len(messages), 4) self.assertEqual(len(messages), 4)
otherConnection.rollback() other_connection.rollback()
messages = otherQueue.deqMany(5) messages = other_queue.deqMany(5)
self.assertEqual(len(messages), 0) self.assertEqual(len(messages), 0)
if __name__ == "__main__": if __name__ == "__main__":
TestEnv.RunTestCases() base.run_test_cases()

View File

@ -6,40 +6,39 @@
2900 - Module for testing Rowids 2900 - Module for testing Rowids
""" """
import TestEnv import base
import cx_Oracle import cx_Oracle as oracledb
class TestCase(TestEnv.BaseTestCase): class TestCase(base.BaseTestCase):
def __TestSelectRowids(self, tableName): def __test_select_rowids(self, table_name):
self.cursor.execute("select rowid, IntCol from %s""" % tableName) self.cursor.execute("select rowid, IntCol from %s""" % table_name)
rowidDict = dict(self.cursor) rowid_dict = dict(self.cursor)
sql = "select IntCol from %s where rowid = :val" % tableName sql = "select IntCol from %s where rowid = :val" % table_name
for rowid, intVal in rowidDict.items(): for rowid, int_val in rowid_dict.items():
self.cursor.execute(sql, val = rowid) self.cursor.execute(sql, val = rowid)
rows = self.cursor.fetchall() rows = self.cursor.fetchall()
self.assertEqual(len(rows), 1) self.assertEqual(len(rows), 1)
self.assertEqual(rows[0][0], intVal) self.assertEqual(rows[0][0], int_val)
def test_2900_SelectRowidsRegular(self): def test_2900_select_rowids_regular(self):
"2900 - test selecting all rowids from a regular table" "2900 - test selecting all rowids from a regular table"
self.__TestSelectRowids("TestNumbers") self.__test_select_rowids("TestNumbers")
def test_2901_SelectRowidsIndexOrganised(self): def test_2901_select_rowids_index_organised(self):
"2901 - test selecting all rowids from an index organised table" "2901 - test selecting all rowids from an index organised table"
self.__TestSelectRowids("TestUniversalRowids") self.__test_select_rowids("TestUniversalRowids")
def test_2902_InsertInvalidRowid(self): def test_2902_insert_invalid_rowid(self):
"2902 - test inserting an invalid rowid" "2902 - test inserting an invalid rowid"
self.assertRaises(cx_Oracle.DatabaseError, self.cursor.execute, sql = "insert into TestRowids (IntCol, RowidCol) values (1, :rid)"
"insert into TestRowids (IntCol, RowidCol) values (1, :rid)", self.assertRaises(oracledb.DatabaseError, self.cursor.execute, sql,
rid=12345) rid=12345)
self.assertRaises(cx_Oracle.DatabaseError, self.cursor.execute, self.assertRaises(oracledb.DatabaseError, self.cursor.execute, sql,
"insert into TestRowids (IntCol, RowidCol) values (1, :rid)",
rid="523lkhlf") rid="523lkhlf")
def test_2903_InsertRowids(self): def test_2903_insert_rowids(self):
"2903 - test inserting rowids and verify they are inserted correctly" "2903 - test inserting rowids and verify they are inserted correctly"
self.cursor.execute("select IntCol, rowid from TestNumbers") self.cursor.execute("select IntCol, rowid from TestNumbers")
rows = self.cursor.fetchall() rows = self.cursor.fetchall()
@ -52,11 +51,11 @@ class TestCase(TestEnv.BaseTestCase):
self.cursor.execute("select IntCol, RowidCol from TestRowids") self.cursor.execute("select IntCol, RowidCol from TestRowids")
rows = self.cursor.fetchall() rows = self.cursor.fetchall()
sql = "select IntCol from TestNumbers where rowid = :val" sql = "select IntCol from TestNumbers where rowid = :val"
for intVal, rowid in rows: for int_val, rowid in rows:
self.cursor.execute(sql, val = rowid) self.cursor.execute(sql, val = rowid)
rows = self.cursor.fetchall() rows = self.cursor.fetchall()
self.assertEqual(len(rows), 1) self.assertEqual(len(rows), 1)
self.assertEqual(rows[0][0], intVal) self.assertEqual(rows[0][0], int_val)
if __name__ == "__main__": if __name__ == "__main__":
TestEnv.RunTestCases() base.run_test_cases()

View File

@ -6,63 +6,71 @@
3000 - Module for testing subscriptions 3000 - Module for testing subscriptions
""" """
import TestEnv import base
import cx_Oracle import cx_Oracle as oracledb
import threading import threading
class SubscriptionData(object): class SubscriptionData(object):
def __init__(self, numMessagesExpected): def __init__(self, num_messages_expected):
self.condition = threading.Condition() self.condition = threading.Condition()
self.numMessagesExpected = numMessagesExpected self.num_messages_expected = num_messages_expected
self.numMessagesReceived = 0 self.num_messages_received = 0
self.tableOperations = [] self.table_operations = []
self.rowOperations = [] self.row_operations = []
self.rowids = [] self.rowids = []
def CallbackHandler(self, message): def CallbackHandler(self, message):
if message.type != cx_Oracle.EVENT_DEREG: if message.type != oracledb.EVENT_DEREG:
table, = message.tables table, = message.tables
self.tableOperations.append(table.operation) self.table_operations.append(table.operation)
for row in table.rows: for row in table.rows:
self.rowOperations.append(row.operation) self.row_operations.append(row.operation)
self.rowids.append(row.rowid) self.rowids.append(row.rowid)
self.numMessagesReceived += 1 self.num_messages_received += 1
if message.type == cx_Oracle.EVENT_DEREG or \ if message.type == oracledb.EVENT_DEREG or \
self.numMessagesReceived == self.numMessagesExpected: self.num_messages_received == self.num_messages_expected:
self.condition.acquire() self.condition.acquire()
self.condition.notify() self.condition.notify()
self.condition.release() self.condition.release()
class TestCase(TestEnv.BaseTestCase): class TestCase(base.BaseTestCase):
def test_3000_Subscription(self): def test_3000_subscription(self):
"3000 - test Subscription for insert, update, delete and truncate" "3000 - test Subscription for insert, update, delete and truncate"
# skip if running on the Oracle Cloud, which does not support # skip if running on the Oracle Cloud, which does not support
# subscriptions currently # subscriptions currently
if self.isOnOracleCloud(): if self.is_on_oracle_cloud():
self.skipTest("Oracle Cloud does not support subscriptions " \ message = "Oracle Cloud does not support subscriptions currently"
"currently") self.skipTest(message)
# truncate table in order to run test in known state # truncate table in order to run test in known state
self.cursor.execute("truncate table TestTempTable") self.cursor.execute("truncate table TestTempTable")
# expected values # expected values
tableOperations = [ cx_Oracle.OPCODE_INSERT, cx_Oracle.OPCODE_UPDATE, table_operations = [
cx_Oracle.OPCODE_INSERT, cx_Oracle.OPCODE_DELETE, oracledb.OPCODE_INSERT,
cx_Oracle.OPCODE_ALTER | cx_Oracle.OPCODE_ALLROWS ] oracledb.OPCODE_UPDATE,
rowOperations = [ cx_Oracle.OPCODE_INSERT, cx_Oracle.OPCODE_UPDATE, oracledb.OPCODE_INSERT,
cx_Oracle.OPCODE_INSERT, cx_Oracle.OPCODE_DELETE ] oracledb.OPCODE_DELETE,
oracledb.OPCODE_ALTER | oracledb.OPCODE_ALLROWS
]
row_operations = [
oracledb.OPCODE_INSERT,
oracledb.OPCODE_UPDATE,
oracledb.OPCODE_INSERT,
oracledb.OPCODE_DELETE
]
rowids = [] rowids = []
# set up subscription # set up subscription
data = SubscriptionData(5) data = SubscriptionData(5)
connection = TestEnv.GetConnection(threaded=True, events=True) connection = base.get_connection(threaded=True, events=True)
sub = connection.subscribe(callback=data.CallbackHandler, sub = connection.subscribe(callback=data.CallbackHandler,
timeout = 10, qos = cx_Oracle.SUBSCR_QOS_ROWIDS) timeout=10, qos=oracledb.SUBSCR_QOS_ROWIDS)
sub.registerquery("select * from TestTempTable") sub.registerquery("select * from TestTempTable")
connection.autocommit = True connection.autocommit = True
cursor = connection.cursor() cursor = connection.cursor()
@ -101,15 +109,14 @@ class TestCase(TestEnv.BaseTestCase):
data.condition.wait(10) data.condition.wait(10)
# verify the correct messages were sent # verify the correct messages were sent
self.assertEqual(data.tableOperations, tableOperations) self.assertEqual(data.table_operations, table_operations)
self.assertEqual(data.rowOperations, rowOperations) self.assertEqual(data.row_operations, row_operations)
self.assertEqual(data.rowids, rowids) self.assertEqual(data.rowids, rowids)
# test string format of subscription object is as expected # test string format of subscription object is as expected
fmt = "<cx_Oracle.Subscription on <cx_Oracle.Connection to %s@%s>>" fmt = "<cx_Oracle.Subscription on <cx_Oracle.Connection to %s@%s>>"
expectedValue = fmt % \ expected = fmt % (base.get_main_user(), base.get_connect_string())
(TestEnv.GetMainUser(), TestEnv.GetConnectString()) self.assertEqual(str(sub), expected)
self.assertEqual(str(sub), expectedValue)
if __name__ == "__main__": if __name__ == "__main__":
TestEnv.RunTestCases() base.run_test_cases()

View File

@ -12,67 +12,67 @@
""" """
import unittest import unittest
import TestEnv import base
import cx_Oracle import cx_Oracle as oracledb
@unittest.skipUnless(TestEnv.GetClientVersion() >= (12, 1), @unittest.skipUnless(base.get_client_version() >= (12, 1),
"unsupported client") "unsupported client")
class TestCase(TestEnv.BaseTestCase): class TestCase(base.BaseTestCase):
def __testBindValueAsBoolean(self, value): def __test_bind_value_as_boolean(self, value):
expectedResult = str(bool(value)).upper() expected_result = str(bool(value)).upper()
var = self.cursor.var(bool) var = self.cursor.var(bool)
var.setvalue(0, value) var.setvalue(0, value)
result = self.cursor.callfunc("pkg_TestBooleans.GetStringRep", str, result = self.cursor.callfunc("pkg_TestBooleans.GetStringRep", str,
(var,)) (var,))
self.assertEqual(result, expectedResult) self.assertEqual(result, expected_result)
def test_3100_BindFalse(self): def test_3100_bind_false(self):
"3100 - test binding in a False value" "3100 - test binding in a False value"
result = self.cursor.callfunc("pkg_TestBooleans.GetStringRep", str, result = self.cursor.callfunc("pkg_TestBooleans.GetStringRep", str,
(False,)) (False,))
self.assertEqual(result, "FALSE") self.assertEqual(result, "FALSE")
def test_3101_BindFloatAsBoolean(self): def test_3101_bind_float_as_boolean(self):
"3101 - test binding in a float as a boolean" "3101 - test binding in a float as a boolean"
self.__testBindValueAsBoolean(0.0) self.__test_bind_value_as_boolean(0.0)
self.__testBindValueAsBoolean(1.0) self.__test_bind_value_as_boolean(1.0)
def test_3102_BindIntegerAsBoolean(self): def test_3102_bind_integer_as_boolean(self):
"3102 - test binding in an integer as a boolean" "3102 - test binding in an integer as a boolean"
self.__testBindValueAsBoolean(0) self.__test_bind_value_as_boolean(0)
self.__testBindValueAsBoolean(1) self.__test_bind_value_as_boolean(1)
def test_3103_BindNull(self): def test_3103_bind_null(self):
"3103 - test binding in a null value" "3103 - test binding in a null value"
self.cursor.setinputsizes(None, bool) self.cursor.setinputsizes(None, bool)
result = self.cursor.callfunc("pkg_TestBooleans.GetStringRep", str, result = self.cursor.callfunc("pkg_TestBooleans.GetStringRep", str,
(None,)) (None,))
self.assertEqual(result, "NULL") self.assertEqual(result, "NULL")
def test_3104_BindOutFalse(self): def test_3104_bind_out_false(self):
"3104 - test binding out a boolean value (False)" "3104 - test binding out a boolean value (False)"
result = self.cursor.callfunc("pkg_TestBooleans.IsLessThan10", result = self.cursor.callfunc("pkg_TestBooleans.IsLessThan10",
cx_Oracle.DB_TYPE_BOOLEAN, (15,)) oracledb.DB_TYPE_BOOLEAN, (15,))
self.assertEqual(result, False) self.assertEqual(result, False)
def test_3105_BindOutTrue(self): def test_3105_bind_out_true(self):
"3105 - test binding out a boolean value (True)" "3105 - test binding out a boolean value (True)"
result = self.cursor.callfunc("pkg_TestBooleans.IsLessThan10", bool, result = self.cursor.callfunc("pkg_TestBooleans.IsLessThan10", bool,
(5,)) (5,))
self.assertEqual(result, True) self.assertEqual(result, True)
def test_3106_BindStringAsBoolean(self): def test_3106_bind_string_as_boolean(self):
"3106 - test binding in a string as a boolean" "3106 - test binding in a string as a boolean"
self.__testBindValueAsBoolean("") self.__test_bind_value_as_boolean("")
self.__testBindValueAsBoolean("0") self.__test_bind_value_as_boolean("0")
def test_3107_BindTrue(self): def test_3107_bind_true(self):
"3107 - test binding in a True value" "3107 - test binding in a True value"
result = self.cursor.callfunc("pkg_TestBooleans.GetStringRep", str, result = self.cursor.callfunc("pkg_TestBooleans.GetStringRep", str,
(True,)) (True,))
self.assertEqual(result, "TRUE") self.assertEqual(result, "TRUE")
if __name__ == "__main__": if __name__ == "__main__":
TestEnv.RunTestCases() base.run_test_cases()

View File

@ -11,39 +11,39 @@
3200 - Module for testing features introduced in 12.1 3200 - Module for testing features introduced in 12.1
""" """
import TestEnv import base
import cx_Oracle import cx_Oracle as oracledb
import datetime import datetime
import unittest import unittest
@unittest.skipUnless(TestEnv.GetClientVersion() >= (12, 1), @unittest.skipUnless(base.get_client_version() >= (12, 1),
"unsupported client") "unsupported client")
class TestCase(TestEnv.BaseTestCase): class TestCase(base.BaseTestCase):
def test_3200_ArrayDMLRowCountsOff(self): def test_3200_array_dml_row_counts_off(self):
"3200 - test executing with arraydmlrowcounts mode disabled" "3200 - test executing with arraydmlrowcounts mode disabled"
self.cursor.execute("truncate table TestArrayDML") self.cursor.execute("truncate table TestArrayDML")
rows = [ (1, "First"), rows = [(1, "First"), (2, "Second")]
(2, "Second") ]
sql = "insert into TestArrayDML (IntCol,StringCol) values (:1,:2)" sql = "insert into TestArrayDML (IntCol,StringCol) values (:1,:2)"
self.cursor.executemany(sql, rows, arraydmlrowcounts=False) self.cursor.executemany(sql, rows, arraydmlrowcounts=False)
self.assertRaises(cx_Oracle.DatabaseError, self.assertRaises(oracledb.DatabaseError,
self.cursor.getarraydmlrowcounts) self.cursor.getarraydmlrowcounts)
rows = [ (3, "Third"), rows = [(3, "Third"), (4, "Fourth")]
(4, "Fourth") ]
self.cursor.executemany(sql, rows) self.cursor.executemany(sql, rows)
self.assertRaises(cx_Oracle.DatabaseError, self.assertRaises(oracledb.DatabaseError,
self.cursor.getarraydmlrowcounts) self.cursor.getarraydmlrowcounts)
def test_3201_ArrayDMLRowCountsOn(self): def test_3201_array_dml_row_counts_on(self):
"3201 - test executing with arraydmlrowcounts mode enabled" "3201 - test executing with arraydmlrowcounts mode enabled"
self.cursor.execute("truncate table TestArrayDML") self.cursor.execute("truncate table TestArrayDML")
rows = [ ( 1, "First", 100), rows = [
(1, "First", 100),
(2, "Second", 200), (2, "Second", 200),
(3, "Third", 300), (3, "Third", 300),
(4, "Fourth", 300), (4, "Fourth", 300),
( 5, "Fifth", 300) ] (5, "Fifth", 300)
]
sql = "insert into TestArrayDML (IntCol,StringCol,IntCol2) " \ sql = "insert into TestArrayDML (IntCol,StringCol,IntCol2) " \
"values (:1,:2,:3)" "values (:1,:2,:3)"
self.cursor.executemany(sql, rows, arraydmlrowcounts=True) self.cursor.executemany(sql, rows, arraydmlrowcounts=True)
@ -53,92 +53,100 @@ class TestCase(TestEnv.BaseTestCase):
count, = self.cursor.fetchone() count, = self.cursor.fetchone()
self.assertEqual(count, len(rows)) self.assertEqual(count, len(rows))
def test_3202_BindPLSQLBooleanCollectionIn(self): def test_3202_bind_plsql_boolean_collection_in(self):
"3202 - test binding a boolean collection (in)" "3202 - test binding a boolean collection (in)"
typeObj = self.connection.gettype("PKG_TESTBOOLEANS.UDT_BOOLEANLIST") type_obj = self.connection.gettype("PKG_TESTBOOLEANS.UDT_BOOLEANLIST")
obj = typeObj.newobject() obj = type_obj.newobject()
obj.setelement(1, True) obj.setelement(1, True)
obj.extend([True, False, True, True, False, True]) obj.extend([True, False, True, True, False, True])
result = self.cursor.callfunc("pkg_TestBooleans.TestInArrays", int, result = self.cursor.callfunc("pkg_TestBooleans.TestInArrays", int,
(obj,)) (obj,))
self.assertEqual(result, 5) self.assertEqual(result, 5)
def test_3203_BindPLSQLBooleanCollectionOut(self): def test_3203_bind_plsql_boolean_collection_out(self):
"3203 - test binding a boolean collection (out)" "3203 - test binding a boolean collection (out)"
typeObj = self.connection.gettype("PKG_TESTBOOLEANS.UDT_BOOLEANLIST") type_obj = self.connection.gettype("PKG_TESTBOOLEANS.UDT_BOOLEANLIST")
obj = typeObj.newobject() obj = type_obj.newobject()
self.cursor.callproc("pkg_TestBooleans.TestOutArrays", (6, obj)) self.cursor.callproc("pkg_TestBooleans.TestOutArrays", (6, obj))
self.assertEqual(obj.aslist(), [True, False, True, False, True, False]) self.assertEqual(obj.aslist(), [True, False, True, False, True, False])
def test_3204_BindPLSQLDateCollectionIn(self): def test_3204_bind_plql_date_collection_in(self):
"3204 - test binding a PL/SQL date collection (in)" "3204 - test binding a PL/SQL date collection (in)"
typeObj = self.connection.gettype("PKG_TESTDATEARRAYS.UDT_DATELIST") type_obj = self.connection.gettype("PKG_TESTDATEARRAYS.UDT_DATELIST")
obj = typeObj.newobject() obj = type_obj.newobject()
obj.setelement(1, datetime.datetime(2016, 2, 5)) obj.setelement(1, datetime.datetime(2016, 2, 5))
obj.append(datetime.datetime(2016, 2, 8, 12, 15, 30)) obj.append(datetime.datetime(2016, 2, 8, 12, 15, 30))
obj.append(datetime.datetime(2016, 2, 12, 5, 44, 30)) obj.append(datetime.datetime(2016, 2, 12, 5, 44, 30))
result = self.cursor.callfunc("pkg_TestDateArrays.TestInArrays", result = self.cursor.callfunc("pkg_TestDateArrays.TestInArrays",
cx_Oracle.NUMBER, (2, datetime.datetime(2016, 2, 1), obj)) oracledb.NUMBER,
(2, datetime.datetime(2016, 2, 1), obj))
self.assertEqual(result, 24.75) self.assertEqual(result, 24.75)
def test_3205_BindPLSQLDateCollectionInOut(self): def test_3205_bind_plqsl_date_collection_in_out(self):
"3205 - test binding a PL/SQL date collection (in/out)" "3205 - test binding a PL/SQL date collection (in/out)"
typeObj = self.connection.gettype("PKG_TESTDATEARRAYS.UDT_DATELIST") type_obj = self.connection.gettype("PKG_TESTDATEARRAYS.UDT_DATELIST")
obj = typeObj.newobject() obj = type_obj.newobject()
obj.setelement(1, datetime.datetime(2016, 1, 1)) obj.setelement(1, datetime.datetime(2016, 1, 1))
obj.append(datetime.datetime(2016, 1, 7)) obj.append(datetime.datetime(2016, 1, 7))
obj.append(datetime.datetime(2016, 1, 13)) obj.append(datetime.datetime(2016, 1, 13))
obj.append(datetime.datetime(2016, 1, 19)) obj.append(datetime.datetime(2016, 1, 19))
self.cursor.callproc("pkg_TestDateArrays.TestInOutArrays", (4, obj)) self.cursor.callproc("pkg_TestDateArrays.TestInOutArrays", (4, obj))
self.assertEqual(obj.aslist(), expected_values = [
[datetime.datetime(2016, 1, 8), datetime.datetime(2016, 1, 8),
datetime.datetime(2016, 1, 14), datetime.datetime(2016, 1, 14),
datetime.datetime(2016, 1, 20), datetime.datetime(2016, 1, 20),
datetime.datetime(2016, 1, 26)]) datetime.datetime(2016, 1, 26)
]
self.assertEqual(obj.aslist(), expected_values)
def test_3206_BindPLSQLDateCollectionOut(self): def test_3206_bind_plsql_date_collection_out(self):
"3206 - test binding a PL/SQL date collection (out)" "3206 - test binding a PL/SQL date collection (out)"
typeObj = self.connection.gettype("PKG_TESTDATEARRAYS.UDT_DATELIST") type_obj = self.connection.gettype("PKG_TESTDATEARRAYS.UDT_DATELIST")
obj = typeObj.newobject() obj = type_obj.newobject()
self.cursor.callproc("pkg_TestDateArrays.TestOutArrays", (3, obj)) self.cursor.callproc("pkg_TestDateArrays.TestOutArrays", (3, obj))
self.assertEqual(obj.aslist(), expected_values = [
[datetime.datetime(2002, 12, 13, 4, 48), datetime.datetime(2002, 12, 13, 4, 48),
datetime.datetime(2002, 12, 14, 9, 36), datetime.datetime(2002, 12, 14, 9, 36),
datetime.datetime(2002, 12, 15, 14, 24)]) datetime.datetime(2002, 12, 15, 14, 24)
]
self.assertEqual(obj.aslist(), expected_values)
def test_3207_BindPLSQLNumberCollectionIn(self): def test_3207_bind_plsql_number_collection_in(self):
"3207 - test binding a PL/SQL number collection (in)" "3207 - test binding a PL/SQL number collection (in)"
typeObj = self.connection.gettype("PKG_TESTNUMBERARRAYS.UDT_NUMBERLIST") type_name = "PKG_TESTNUMBERARRAYS.UDT_NUMBERLIST"
obj = typeObj.newobject() type_obj = self.connection.gettype(type_name)
obj = type_obj.newobject()
obj.setelement(1, 10) obj.setelement(1, 10)
obj.extend([20, 30, 40, 50]) obj.extend([20, 30, 40, 50])
result = self.cursor.callfunc("pkg_TestNumberArrays.TestInArrays", int, result = self.cursor.callfunc("pkg_TestNumberArrays.TestInArrays", int,
(5, obj)) (5, obj))
self.assertEqual(result, 155) self.assertEqual(result, 155)
def test_3208_BindPLSQLNumberCollectionInOut(self): def test_3208_bind_plsql_number_collection_in_out(self):
"3208 - test binding a PL/SQL number collection (in/out)" "3208 - test binding a PL/SQL number collection (in/out)"
typeObj = self.connection.gettype("PKG_TESTNUMBERARRAYS.UDT_NUMBERLIST") type_name = "PKG_TESTNUMBERARRAYS.UDT_NUMBERLIST"
obj = typeObj.newobject() type_obj = self.connection.gettype(type_name)
obj = type_obj.newobject()
obj.setelement(1, 5) obj.setelement(1, 5)
obj.extend([8, 3, 2]) obj.extend([8, 3, 2])
self.cursor.callproc("pkg_TestNumberArrays.TestInOutArrays", (4, obj)) self.cursor.callproc("pkg_TestNumberArrays.TestInOutArrays", (4, obj))
self.assertEqual(obj.aslist(), [50, 80, 30, 20]) self.assertEqual(obj.aslist(), [50, 80, 30, 20])
def test_3209_BindPLSQLNumberCollectionOut(self): def test_3209_bind_plsql_number_collection_out(self):
"3209 - test binding a PL/SQL number collection (out)" "3209 - test binding a PL/SQL number collection (out)"
typeObj = self.connection.gettype("PKG_TESTNUMBERARRAYS.UDT_NUMBERLIST") type_name = "PKG_TESTNUMBERARRAYS.UDT_NUMBERLIST"
obj = typeObj.newobject() type_obj = self.connection.gettype(type_name)
obj = type_obj.newobject()
self.cursor.callproc("pkg_TestNumberArrays.TestOutArrays", (3, obj)) self.cursor.callproc("pkg_TestNumberArrays.TestOutArrays", (3, obj))
self.assertEqual(obj.aslist(), [100, 200, 300]) self.assertEqual(obj.aslist(), [100, 200, 300])
def test_3210_BindPLSQLRecordArray(self): def test_3210_bind_plsql_record_array(self):
"3210 - test binding an array of PL/SQL records (in)" "3210 - test binding an array of PL/SQL records (in)"
recType = self.connection.gettype("PKG_TESTRECORDS.UDT_RECORD") rec_type = self.connection.gettype("PKG_TESTRECORDS.UDT_RECORD")
arrayType = self.connection.gettype("PKG_TESTRECORDS.UDT_RECORDARRAY") array_type = self.connection.gettype("PKG_TESTRECORDS.UDT_RECORDARRAY")
arrayObj = arrayType.newobject() array_obj = array_type.newobject()
for i in range(3): for i in range(3):
obj = recType.newobject() obj = rec_type.newobject()
obj.NUMBERVALUE = i + 1 obj.NUMBERVALUE = i + 1
obj.STRINGVALUE = "String in record #%d" % (i + 1) obj.STRINGVALUE = "String in record #%d" % (i + 1)
obj.DATEVALUE = datetime.datetime(2017, i + 1, 1) obj.DATEVALUE = datetime.datetime(2017, i + 1, 1)
@ -146,9 +154,9 @@ class TestCase(TestEnv.BaseTestCase):
obj.BOOLEANVALUE = (i % 2) == 1 obj.BOOLEANVALUE = (i % 2) == 1
obj.PLSINTEGERVALUE = i * 5 obj.PLSINTEGERVALUE = i * 5
obj.BINARYINTEGERVALUE = i * 2 obj.BINARYINTEGERVALUE = i * 2
arrayObj.append(obj) array_obj.append(obj)
result = self.cursor.callfunc("pkg_TestRecords.TestInArrays", str, result = self.cursor.callfunc("pkg_TestRecords.TestInArrays", str,
(arrayObj,)) (array_obj,))
self.assertEqual(result, self.assertEqual(result,
"udt_Record(1, 'String in record #1', " \ "udt_Record(1, 'String in record #1', " \
"to_date('2017-01-01', 'YYYY-MM-DD'), " \ "to_date('2017-01-01', 'YYYY-MM-DD'), " \
@ -163,10 +171,10 @@ class TestCase(TestEnv.BaseTestCase):
"to_timestamp('2017-01-03 00:00:00', " \ "to_timestamp('2017-01-03 00:00:00', " \
"'YYYY-MM-DD HH24:MI:SS'), false, 10, 4)") "'YYYY-MM-DD HH24:MI:SS'), false, 10, 4)")
def test_3211_BindPLSQLRecordIn(self): def test_3211_bind_plsql_record_in(self):
"3211 - test binding a PL/SQL record (in)" "3211 - test binding a PL/SQL record (in)"
typeObj = self.connection.gettype("PKG_TESTRECORDS.UDT_RECORD") type_obj = self.connection.gettype("PKG_TESTRECORDS.UDT_RECORD")
obj = typeObj.newobject() obj = type_obj.newobject()
obj.NUMBERVALUE = 18 obj.NUMBERVALUE = 18
obj.STRINGVALUE = "A string in a record" obj.STRINGVALUE = "A string in a record"
obj.DATEVALUE = datetime.datetime(2016, 2, 15) obj.DATEVALUE = datetime.datetime(2016, 2, 15)
@ -182,10 +190,10 @@ class TestCase(TestEnv.BaseTestCase):
"to_timestamp('2016-02-12 14:25:36', " \ "to_timestamp('2016-02-12 14:25:36', " \
"'YYYY-MM-DD HH24:MI:SS'), false, 21, 5)") "'YYYY-MM-DD HH24:MI:SS'), false, 21, 5)")
def test_3212_BindPLSQLRecordOut(self): def test_3212_bind_plsql_record_out(self):
"3212 - test binding a PL/SQL record (out)" "3212 - test binding a PL/SQL record (out)"
typeObj = self.connection.gettype("PKG_TESTRECORDS.UDT_RECORD") type_obj = self.connection.gettype("PKG_TESTRECORDS.UDT_RECORD")
obj = typeObj.newobject() obj = type_obj.newobject()
obj.NUMBERVALUE = 5 obj.NUMBERVALUE = 5
obj.STRINGVALUE = "Test value" obj.STRINGVALUE = "Test value"
obj.DATEVALUE = datetime.datetime.today() obj.DATEVALUE = datetime.datetime.today()
@ -203,10 +211,11 @@ class TestCase(TestEnv.BaseTestCase):
self.assertEqual(obj.PLSINTEGERVALUE, 45) self.assertEqual(obj.PLSINTEGERVALUE, 45)
self.assertEqual(obj.BINARYINTEGERVALUE, 10) self.assertEqual(obj.BINARYINTEGERVALUE, 10)
def test_3213_BindPLSQLStringCollectionIn(self): def test_3213_bind_plsql_string_collection_in(self):
"3213 - test binding a PL/SQL string collection (in)" "3213 - test binding a PL/SQL string collection (in)"
typeObj = self.connection.gettype("PKG_TESTSTRINGARRAYS.UDT_STRINGLIST") type_name = "PKG_TESTSTRINGARRAYS.UDT_STRINGLIST"
obj = typeObj.newobject() type_obj = self.connection.gettype(type_name)
obj = type_obj.newobject()
obj.setelement(1, "First element") obj.setelement(1, "First element")
obj.setelement(2, "Second element") obj.setelement(2, "Second element")
obj.setelement(3, "Third element") obj.setelement(3, "Third element")
@ -214,34 +223,41 @@ class TestCase(TestEnv.BaseTestCase):
(5, obj)) (5, obj))
self.assertEqual(result, 45) self.assertEqual(result, 45)
def test_3214_BindPLSQLStringCollectionInOut(self): def test_3214_bind_plsql_string_collection_in_out(self):
"3214 - test binding a PL/SQL string collection (in/out)" "3214 - test binding a PL/SQL string collection (in/out)"
typeObj = self.connection.gettype("PKG_TESTSTRINGARRAYS.UDT_STRINGLIST") type_name = "PKG_TESTSTRINGARRAYS.UDT_STRINGLIST"
obj = typeObj.newobject() type_obj = self.connection.gettype(type_name)
obj = type_obj.newobject()
obj.setelement(1, "The first element") obj.setelement(1, "The first element")
obj.append("The second element") obj.append("The second element")
obj.append("The third and final element") obj.append("The third and final element")
self.cursor.callproc("pkg_TestStringArrays.TestInOutArrays", (3, obj)) self.cursor.callproc("pkg_TestStringArrays.TestInOutArrays", (3, obj))
self.assertEqual(obj.aslist(), expected_values = [
['Converted element # 1 originally had length 17', 'Converted element # 1 originally had length 17',
'Converted element # 2 originally had length 18', 'Converted element # 2 originally had length 18',
'Converted element # 3 originally had length 27']) 'Converted element # 3 originally had length 27'
]
self.assertEqual(obj.aslist(), expected_values)
def test_3215_BindPLSQLStringCollectionOut(self): def test_3215_bind_plsql_string_collection_out(self):
"3215 - test binding a PL/SQL string collection (out)" "3215 - test binding a PL/SQL string collection (out)"
typeObj = self.connection.gettype("PKG_TESTSTRINGARRAYS.UDT_STRINGLIST") type_name = "PKG_TESTSTRINGARRAYS.UDT_STRINGLIST"
obj = typeObj.newobject() type_obj = self.connection.gettype(type_name)
obj = type_obj.newobject()
self.cursor.callproc("pkg_TestStringArrays.TestOutArrays", (4, obj)) self.cursor.callproc("pkg_TestStringArrays.TestOutArrays", (4, obj))
self.assertEqual(obj.aslist(), expected_values = [
['Test out element # 1', 'Test out element # 1',
'Test out element # 2', 'Test out element # 2',
'Test out element # 3', 'Test out element # 3',
'Test out element # 4']) 'Test out element # 4'
]
self.assertEqual(obj.aslist(), expected_values)
def test_3216_BindPLSQLStringCollectionOutWithHoles(self): def test_3216_bind_plsql_string_collection_out_with_holes(self):
"3216 - test binding a PL/SQL string collection (out with holes)" "3216 - test binding a PL/SQL string collection (out with holes)"
typeObj = self.connection.gettype("PKG_TESTSTRINGARRAYS.UDT_STRINGLIST") type_name = "PKG_TESTSTRINGARRAYS.UDT_STRINGLIST"
obj = typeObj.newobject() type_obj = self.connection.gettype(type_name)
obj = type_obj.newobject()
self.cursor.callproc("pkg_TestStringArrays.TestIndexBy", (obj,)) self.cursor.callproc("pkg_TestStringArrays.TestIndexBy", (obj,))
self.assertEqual(obj.first(), -1048576) self.assertEqual(obj.first(), -1048576)
self.assertEqual(obj.last(), 8388608) self.assertEqual(obj.last(), 8388608)
@ -251,44 +267,56 @@ class TestCase(TestEnv.BaseTestCase):
self.assertEqual(obj.exists(-576), True) self.assertEqual(obj.exists(-576), True)
self.assertEqual(obj.exists(-577), False) self.assertEqual(obj.exists(-577), False)
self.assertEqual(obj.getelement(284), 'Third element') self.assertEqual(obj.getelement(284), 'Third element')
self.assertEqual(obj.aslist(), expected_list = [
["First element", "Second element", "Third element", "First element",
"Fourth element"]) "Second element",
self.assertEqual(obj.asdict(), "Third element",
{ -1048576 : 'First element', "Fourth element"
]
self.assertEqual(obj.aslist(), expected_list)
expected_dict = {
-1048576: 'First element',
-576: 'Second element', -576: 'Second element',
284: 'Third element', 284: 'Third element',
8388608: 'Fourth element' }) 8388608: 'Fourth element'
}
self.assertEqual(obj.asdict(), expected_dict)
obj.delete(-576) obj.delete(-576)
obj.delete(284) obj.delete(284)
self.assertEqual(obj.aslist(), ["First element", "Fourth element"]) expected_list.pop(2)
self.assertEqual(obj.asdict(), expected_list.pop(1)
{ -1048576 : 'First element', self.assertEqual(obj.aslist(), expected_list)
8388608: 'Fourth element' }) expected_dict.pop(-576)
expected_dict.pop(284)
self.assertEqual(obj.asdict(), expected_dict)
def test_3217_ExceptionInIteration(self): def test_3217_exception_in_iteration(self):
"3217 - test executing with arraydmlrowcounts with exception" "3217 - test executing with arraydmlrowcounts with exception"
self.cursor.execute("truncate table TestArrayDML") self.cursor.execute("truncate table TestArrayDML")
rows = [ (1, "First"), rows = [
(1, "First"),
(2, "Second"), (2, "Second"),
(2, "Third"), (2, "Third"),
(4, "Fourth") ] (4, "Fourth")
]
sql = "insert into TestArrayDML (IntCol,StringCol) values (:1,:2)" sql = "insert into TestArrayDML (IntCol,StringCol) values (:1,:2)"
self.assertRaises(cx_Oracle.DatabaseError, self.cursor.executemany, self.assertRaises(oracledb.DatabaseError, self.cursor.executemany,
sql, rows, arraydmlrowcounts=True) sql, rows, arraydmlrowcounts=True)
self.assertEqual(self.cursor.getarraydmlrowcounts(), [1, 1]) self.assertEqual(self.cursor.getarraydmlrowcounts(), [1, 1])
def test_3218_ExecutingDelete(self): def test_3218_executing_delete(self):
"3218 - test executing delete statement with arraydmlrowcount mode" "3218 - test executing delete statement with arraydmlrowcount mode"
self.cursor.execute("truncate table TestArrayDML") self.cursor.execute("truncate table TestArrayDML")
rows = [ (1, "First", 100), rows = [
(1, "First", 100),
(2, "Second", 200), (2, "Second", 200),
(3, "Third", 300), (3, "Third", 300),
(4, "Fourth", 300), (4, "Fourth", 300),
(5, "Fifth", 300), (5, "Fifth", 300),
(6, "Sixth", 400), (6, "Sixth", 400),
(7, "Seventh", 400), (7, "Seventh", 400),
(8, "Eighth", 500) ] (8, "Eighth", 500)
]
sql = "insert into TestArrayDML (IntCol,StringCol,IntCol2) " \ sql = "insert into TestArrayDML (IntCol,StringCol,IntCol2) " \
"values (:1, :2, :3)" "values (:1, :2, :3)"
self.cursor.executemany(sql, rows) self.cursor.executemany(sql, rows)
@ -298,30 +326,34 @@ class TestCase(TestEnv.BaseTestCase):
self.assertEqual(self.cursor.getarraydmlrowcounts(), [1, 3, 2]) self.assertEqual(self.cursor.getarraydmlrowcounts(), [1, 3, 2])
self.assertEqual(self.cursor.rowcount, 6) self.assertEqual(self.cursor.rowcount, 6)
def test_3219_ExecutingUpdate(self): def test_3219_executing_update(self):
"3219 - test executing update statement with arraydmlrowcount mode" "3219 - test executing update statement with arraydmlrowcount mode"
self.cursor.execute("truncate table TestArrayDML") self.cursor.execute("truncate table TestArrayDML")
rows = [ (1, "First",100), rows = [
(1, "First",100),
(2, "Second",200), (2, "Second",200),
(3, "Third",300), (3, "Third",300),
(4, "Fourth",300), (4, "Fourth",300),
(5, "Fifth",300), (5, "Fifth",300),
(6, "Sixth",400), (6, "Sixth",400),
(7, "Seventh",400), (7, "Seventh",400),
(8, "Eighth",500) ] (8, "Eighth",500)
]
sql = "insert into TestArrayDML (IntCol,StringCol,IntCol2) " \ sql = "insert into TestArrayDML (IntCol,StringCol,IntCol2) " \
"values (:1, :2, :3)" "values (:1, :2, :3)"
self.cursor.executemany(sql, rows) self.cursor.executemany(sql, rows)
rows = [ ("One", 100), rows = [
("One", 100),
("Two", 200), ("Two", 200),
("Three", 300), ("Three", 300),
("Four", 400) ] ("Four", 400)
]
sql = "update TestArrayDML set StringCol = :1 where IntCol2 = :2" sql = "update TestArrayDML set StringCol = :1 where IntCol2 = :2"
self.cursor.executemany(sql, rows, arraydmlrowcounts=True) self.cursor.executemany(sql, rows, arraydmlrowcounts=True)
self.assertEqual(self.cursor.getarraydmlrowcounts(), [1, 1, 3, 2]) self.assertEqual(self.cursor.getarraydmlrowcounts(), [1, 1, 3, 2])
self.assertEqual(self.cursor.rowcount, 7) self.assertEqual(self.cursor.rowcount, 7)
def test_3220_ImplicitResults(self): def test_3220_implicit_results(self):
"3220 - test getimplicitresults() returns the correct data" "3220 - test getimplicitresults() returns the correct data"
self.cursor.execute(""" self.cursor.execute("""
declare declare
@ -349,86 +381,93 @@ class TestCase(TestEnv.BaseTestCase):
self.assertEqual([n for n, in results[0]], [3.75, 5, 6.25]) self.assertEqual([n for n, in results[0]], [3.75, 5, 6.25])
self.assertEqual([n for n, in results[1]], [8.75, 10, 11.25, 12.5]) self.assertEqual([n for n, in results[1]], [8.75, 10, 11.25, 12.5])
def test_3221_ImplicitResultsNoStatement(self): def test_3221_implicit_results_no_statement(self):
"3221 - test getimplicitresults() without executing a statement" "3221 - test getimplicitresults() without executing a statement"
self.assertRaises(cx_Oracle.InterfaceError, self.assertRaises(oracledb.InterfaceError,
self.cursor.getimplicitresults) self.cursor.getimplicitresults)
def test_3222_InsertWithBatchError(self): def test_3222_insert_with_batch_error(self):
"3222 - test executing insert with multiple distinct batch errors" "3222 - test executing insert with multiple distinct batch errors"
self.cursor.execute("truncate table TestArrayDML") self.cursor.execute("truncate table TestArrayDML")
rows = [ (1, "First", 100), rows = [
(1, "First", 100),
(2, "Second", 200), (2, "Second", 200),
(2, "Third", 300), (2, "Third", 300),
(4, "Fourth", 400), (4, "Fourth", 400),
(5, "Fourth", 1000)] (5, "Fourth", 1000)
]
sql = "insert into TestArrayDML (IntCol, StringCol, IntCol2) " \ sql = "insert into TestArrayDML (IntCol, StringCol, IntCol2) " \
"values (:1, :2, :3)" "values (:1, :2, :3)"
self.cursor.executemany(sql, rows, batcherrors=True, self.cursor.executemany(sql, rows, batcherrors=True,
arraydmlrowcounts=True) arraydmlrowcounts=True)
user = TestEnv.GetMainUser() user = base.get_main_user()
expectedErrors = [ expected_errors = [
( 4, 1438, "ORA-01438: value larger than specified " \ ( 4, 1438, "ORA-01438: value larger than specified " \
"precision allowed for this column" ), "precision allowed for this column" ),
( 2, 1, "ORA-00001: unique constraint " \ ( 2, 1, "ORA-00001: unique constraint " \
"(%s.TESTARRAYDML_PK) violated" % user.upper()) "(%s.TESTARRAYDML_PK) violated" % user.upper())
] ]
actualErrors = [(e.offset, e.code, e.message) \ actual_errors = [(e.offset, e.code, e.message) \
for e in self.cursor.getbatcherrors()] for e in self.cursor.getbatcherrors()]
self.assertEqual(actualErrors, expectedErrors) self.assertEqual(actual_errors, expected_errors)
self.assertEqual(self.cursor.getarraydmlrowcounts(), [1, 1, 0, 1, 0]) self.assertEqual(self.cursor.getarraydmlrowcounts(), [1, 1, 0, 1, 0])
def test_3223_BatchErrorFalse(self): def test_3223_batch_error_false(self):
"3223 - test batcherrors mode set to False" "3223 - test batcherrors mode set to False"
self.cursor.execute("truncate table TestArrayDML") self.cursor.execute("truncate table TestArrayDML")
rows = [ (1, "First", 100), rows = [
(1, "First", 100),
(2, "Second", 200), (2, "Second", 200),
(2, "Third", 300) ] (2, "Third", 300)
]
sql = "insert into TestArrayDML (IntCol, StringCol, IntCol2) " \ sql = "insert into TestArrayDML (IntCol, StringCol, IntCol2) " \
"values (:1, :2, :3)" "values (:1, :2, :3)"
self.assertRaises(cx_Oracle.IntegrityError, self.assertRaises(oracledb.IntegrityError, self.cursor.executemany,
self.cursor.executemany, sql, rows, batcherrors = False) sql, rows, batcherrors=False)
def test_3224_UpdatewithBatchError(self): def test_3224_update_with_batch_error(self):
"3224 - test executing in succession with batch error" "3224 - test executing in succession with batch error"
self.cursor.execute("truncate table TestArrayDML") self.cursor.execute("truncate table TestArrayDML")
rows = [ (1, "First", 100), rows = [
(1, "First", 100),
(2, "Second", 200), (2, "Second", 200),
(3, "Third", 300), (3, "Third", 300),
(4, "Second", 300), (4, "Second", 300),
(5, "Fifth", 300), (5, "Fifth", 300),
(6, "Sixth", 400), (6, "Sixth", 400),
(6, "Seventh", 400), (6, "Seventh", 400),
(8, "Eighth", 100) ] (8, "Eighth", 100)
]
sql = "insert into TestArrayDML (IntCol, StringCol, IntCol2) " \ sql = "insert into TestArrayDML (IntCol, StringCol, IntCol2) " \
"values (:1, :2, :3)" "values (:1, :2, :3)"
self.cursor.executemany(sql, rows, batcherrors=True) self.cursor.executemany(sql, rows, batcherrors=True)
user = TestEnv.GetMainUser() user = base.get_main_user()
expectedErrors = [ expected_errors = [
( 6, 1, "ORA-00001: unique constraint " \ ( 6, 1, "ORA-00001: unique constraint " \
"(%s.TESTARRAYDML_PK) violated" % user.upper()) "(%s.TESTARRAYDML_PK) violated" % user.upper())
] ]
actualErrors = [(e.offset, e.code, e.message) \ actual_errors = [(e.offset, e.code, e.message) \
for e in self.cursor.getbatcherrors()] for e in self.cursor.getbatcherrors()]
self.assertEqual(actualErrors, expectedErrors) self.assertEqual(actual_errors, expected_errors)
rows = [ (101, "First"), rows = [
(101, "First"),
(201, "Second"), (201, "Second"),
(3000, "Third"), (3000, "Third"),
(900, "Ninth"), (900, "Ninth"),
(301, "Third") ] (301, "Third")
]
sql = "update TestArrayDML set IntCol2 = :1 where StringCol = :2" sql = "update TestArrayDML set IntCol2 = :1 where StringCol = :2"
self.cursor.executemany(sql, rows, arraydmlrowcounts=True, self.cursor.executemany(sql, rows, arraydmlrowcounts=True,
batcherrors=True) batcherrors=True)
expectedErrors = [ expected_errors = [
(2, 1438, "ORA-01438: value larger than specified " \ (2, 1438, "ORA-01438: value larger than specified " \
"precision allowed for this column") "precision allowed for this column")
] ]
actualErrors = [(e.offset, e.code, e.message) \ actual_errors = [(e.offset, e.code, e.message) \
for e in self.cursor.getbatcherrors()] for e in self.cursor.getbatcherrors()]
self.assertEqual(actualErrors, expectedErrors) self.assertEqual(actual_errors, expected_errors)
self.assertEqual(self.cursor.getarraydmlrowcounts(), self.assertEqual(self.cursor.getarraydmlrowcounts(), [1, 2, 0, 0, 1])
[1, 2, 0, 0, 1])
self.assertEqual(self.cursor.rowcount, 4) self.assertEqual(self.cursor.rowcount, 4)
if __name__ == "__main__": if __name__ == "__main__":
TestEnv.RunTestCases() base.run_test_cases()

View File

@ -6,106 +6,104 @@
3300 - Module for testing Simple Oracle Document Access (SODA) Database 3300 - Module for testing Simple Oracle Document Access (SODA) Database
""" """
import TestEnv import base
import cx_Oracle import cx_Oracle as oracledb
import json import json
import unittest import unittest
@unittest.skipIf(TestEnv.SkipSodaTests(), @unittest.skipIf(base.skip_soda_tests(),
"unsupported client/server combination") "unsupported client/server combination")
class TestCase(TestEnv.BaseTestCase): class TestCase(base.BaseTestCase):
def __dropExistingCollections(self, sodaDatabase): def __drop_existing_collections(self, soda_db):
for name in sodaDatabase.getCollectionNames(): for name in soda_db.getCollectionNames():
sodaDatabase.openCollection(name).drop() soda_db.openCollection(name).drop()
def __verifyDocument(self, doc, rawContent, strContent=None, content=None, def __verify_doc(self, doc, raw_content, str_content=None, content=None,
key=None, mediaType='application/json'): key=None, media_type='application/json'):
self.assertEqual(doc.getContentAsBytes(), rawContent) self.assertEqual(doc.getContentAsBytes(), raw_content)
if strContent is not None: if str_content is not None:
self.assertEqual(doc.getContentAsString(), strContent) self.assertEqual(doc.getContentAsString(), str_content)
if content is not None: if content is not None:
self.assertEqual(doc.getContent(), content) self.assertEqual(doc.getContent(), content)
self.assertEqual(doc.key, key) self.assertEqual(doc.key, key)
self.assertEqual(doc.mediaType, mediaType) self.assertEqual(doc.mediaType, media_type)
def test_3300_CreateDocumentWithJson(self): def test_3300_create_document_with_json(self):
"3300 - test creating documents with JSON data" "3300 - test creating documents with JSON data"
sodaDatabase = self.connection.getSodaDatabase() soda_db = self.connection.getSodaDatabase()
val = {"testKey1": "testValue1", "testKey2": "testValue2"} val = {"testKey1": "testValue1", "testKey2": "testValue2"}
strVal = json.dumps(val) str_val = json.dumps(val)
bytesVal = strVal.encode("UTF-8") bytes_val = str_val.encode()
key = "MyKey" key = "MyKey"
mediaType = "text/plain" media_type = "text/plain"
doc = sodaDatabase.createDocument(val) doc = soda_db.createDocument(val)
self.__verifyDocument(doc, bytesVal, strVal, val) self.__verify_doc(doc, bytes_val, str_val, val)
doc = sodaDatabase.createDocument(strVal, key) doc = soda_db.createDocument(str_val, key)
self.__verifyDocument(doc, bytesVal, strVal, val, key) self.__verify_doc(doc, bytes_val, str_val, val, key)
doc = sodaDatabase.createDocument(bytesVal, key, mediaType) doc = soda_db.createDocument(bytes_val, key, media_type)
self.__verifyDocument(doc, bytesVal, strVal, val, key, mediaType) self.__verify_doc(doc, bytes_val, str_val, val, key, media_type)
def test_3301_CreateDocumentWithRaw(self): def test_3301_create_document_with_raw(self):
"3301 - test creating documents with raw data" "3301 - test creating documents with raw data"
sodaDatabase = self.connection.getSodaDatabase() soda_db = self.connection.getSodaDatabase()
val = b"<html/>" val = b"<html/>"
key = "MyRawKey" key = "MyRawKey"
mediaType = "text/html" media_type = "text/html"
doc = sodaDatabase.createDocument(val) doc = soda_db.createDocument(val)
self.__verifyDocument(doc, val) self.__verify_doc(doc, val)
doc = sodaDatabase.createDocument(val, key) doc = soda_db.createDocument(val, key)
self.__verifyDocument(doc, val, key=key) self.__verify_doc(doc, val, key=key)
doc = sodaDatabase.createDocument(val, key, mediaType) doc = soda_db.createDocument(val, key, media_type)
self.__verifyDocument(doc, val, key=key, mediaType=mediaType) self.__verify_doc(doc, val, key=key, media_type=media_type)
def test_3302_GetCollectionNames(self): def test_3302_get_collection_names(self):
"3302 - test getting collection names from the database" "3302 - test getting collection names from the database"
sodaDatabase = self.connection.getSodaDatabase() soda_db = self.connection.getSodaDatabase()
self.__dropExistingCollections(sodaDatabase) self.__drop_existing_collections(soda_db)
self.assertEqual(sodaDatabase.getCollectionNames(), []) self.assertEqual(soda_db.getCollectionNames(), [])
names = ["zCol", "dCol", "sCol", "aCol", "gCol"] names = ["zCol", "dCol", "sCol", "aCol", "gCol"]
sortedNames = list(sorted(names)) sorted_names = list(sorted(names))
for name in names: for name in names:
sodaDatabase.createCollection(name) soda_db.createCollection(name)
self.assertEqual(sodaDatabase.getCollectionNames(), sortedNames) self.assertEqual(soda_db.getCollectionNames(), sorted_names)
self.assertEqual(sodaDatabase.getCollectionNames(limit=2), self.assertEqual(soda_db.getCollectionNames(limit=2), sorted_names[:2])
sortedNames[:2]) self.assertEqual(soda_db.getCollectionNames("a"), sorted_names)
self.assertEqual(sodaDatabase.getCollectionNames("a"), sortedNames) self.assertEqual(soda_db.getCollectionNames("C"), sorted_names)
self.assertEqual(sodaDatabase.getCollectionNames("C"), sortedNames) self.assertEqual(soda_db.getCollectionNames("b", limit=3),
self.assertEqual(sodaDatabase.getCollectionNames("b", limit=3), sorted_names[1:4])
sortedNames[1:4]) self.assertEqual(soda_db.getCollectionNames("z"), sorted_names[-1:])
self.assertEqual(sodaDatabase.getCollectionNames("z"),
sortedNames[-1:])
def test_3303_OpenCollection(self): def test_3303_open_collection(self):
"3303 - test opening a collection" "3303 - test opening a collection"
sodaDatabase = self.connection.getSodaDatabase() soda_db = self.connection.getSodaDatabase()
self.__dropExistingCollections(sodaDatabase) self.__drop_existing_collections(soda_db)
coll = sodaDatabase.openCollection("CollectionThatDoesNotExist") coll = soda_db.openCollection("CollectionThatDoesNotExist")
self.assertEqual(coll, None) self.assertEqual(coll, None)
createdColl = sodaDatabase.createCollection("cxoTestOpenCollection") created_coll = soda_db.createCollection("TestOpenCollection")
coll = sodaDatabase.openCollection(createdColl.name) coll = soda_db.openCollection(created_coll.name)
self.assertEqual(coll.name, createdColl.name) self.assertEqual(coll.name, created_coll.name)
coll.drop() coll.drop()
def test_3304_Repr(self): def test_3304_repr(self):
"3304 - test SodaDatabase representation" "3304 - test SodaDatabase representation"
con1 = self.connection con1 = self.connection
con2 = TestEnv.GetConnection() con2 = base.get_connection()
sodaDatabase1 = self.connection.getSodaDatabase() soda_db1 = self.connection.getSodaDatabase()
sodaDatabase2 = con1.getSodaDatabase() soda_db2 = con1.getSodaDatabase()
sodaDatabase3 = con2.getSodaDatabase() soda_db3 = con2.getSodaDatabase()
self.assertEqual(str(sodaDatabase1), str(sodaDatabase2)) self.assertEqual(str(soda_db1), str(soda_db2))
self.assertEqual(str(sodaDatabase2), str(sodaDatabase3)) self.assertEqual(str(soda_db2), str(soda_db3))
def test_3305_Negative(self): def test_3305_negative(self):
"3305 - test negative cases for SODA database methods" "3305 - test negative cases for SODA database methods"
sodaDatabase = self.connection.getSodaDatabase() soda_db = self.connection.getSodaDatabase()
self.assertRaises(TypeError, sodaDatabase.createCollection) self.assertRaises(TypeError, soda_db.createCollection)
self.assertRaises(TypeError, sodaDatabase.createCollection, 1) self.assertRaises(TypeError, soda_db.createCollection, 1)
self.assertRaises(cx_Oracle.DatabaseError, self.assertRaises(oracledb.DatabaseError, soda_db.createCollection,
sodaDatabase.createCollection, None) None)
self.assertRaises(TypeError, sodaDatabase.getCollectionNames, 1) self.assertRaises(TypeError, soda_db.getCollectionNames, 1)
if __name__ == "__main__": if __name__ == "__main__":
TestEnv.RunTestCases() base.run_test_cases()

View File

@ -6,90 +6,90 @@
3400 - Module for testing Simple Oracle Document Access (SODA) Collections 3400 - Module for testing Simple Oracle Document Access (SODA) Collections
""" """
import TestEnv import base
import cx_Oracle import cx_Oracle as oracledb
import unittest import unittest
@unittest.skipIf(TestEnv.SkipSodaTests(), @unittest.skipIf(base.skip_soda_tests(),
"unsupported client/server combination") "unsupported client/server combination")
class TestCase(TestEnv.BaseTestCase): class TestCase(base.BaseTestCase):
def __testSkip(self, coll, numToSkip, expectedContent): def __test_skip(self, coll, num_to_skip, expected_content):
filterSpec = {'$orderby': [{'path': 'name', 'order': 'desc'}]} filter_spec = {'$orderby': [{'path': 'name', 'order': 'desc'}]}
doc = coll.find().filter(filterSpec).skip(numToSkip).getOne() doc = coll.find().filter(filter_spec).skip(num_to_skip).getOne()
content = doc.getContent() if doc is not None else None content = doc.getContent() if doc is not None else None
self.assertEqual(content, expectedContent) self.assertEqual(content, expected_content)
def test_3400_InvalidJson(self): def test_3400_invalid_json(self):
"3400 - test inserting invalid JSON value into SODA collection" "3400 - test inserting invalid JSON value into SODA collection"
invalidJson = "{testKey:testValue}" invalid_json = "{testKey:testValue}"
sodaDatabase = self.connection.getSodaDatabase() soda_db = self.connection.getSodaDatabase()
coll = sodaDatabase.createCollection("cxoInvalidJSON") coll = soda_db.createCollection("InvalidJSON")
doc = sodaDatabase.createDocument(invalidJson) doc = soda_db.createDocument(invalid_json)
self.assertRaises(cx_Oracle.IntegrityError, coll.insertOne, doc) self.assertRaises(oracledb.DatabaseError, coll.insertOne, doc)
coll.drop() coll.drop()
def test_3401_InsertDocuments(self): def test_3401_insert_documents(self):
"3401 - test inserting documents into a SODA collection" "3401 - test inserting documents into a SODA collection"
sodaDatabase = self.connection.getSodaDatabase() soda_db = self.connection.getSodaDatabase()
coll = sodaDatabase.createCollection("cxoInsertDocs") coll = soda_db.createCollection("cxoInsertDocs")
coll.find().remove() coll.find().remove()
valuesToInsert = [ values_to_insert = [
{"name": "George", "age": 47}, {"name": "George", "age": 47},
{"name": "Susan", "age": 39}, {"name": "Susan", "age": 39},
{"name": "John", "age": 50}, {"name": "John", "age": 50},
{"name": "Jill", "age": 54} {"name": "Jill", "age": 54}
] ]
insertedKeys = [] inserted_keys = []
for value in valuesToInsert: for value in values_to_insert:
doc = coll.insertOneAndGet(value) doc = coll.insertOneAndGet(value)
insertedKeys.append(doc.key) inserted_keys.append(doc.key)
self.connection.commit() self.connection.commit()
self.assertEqual(coll.find().count(), len(valuesToInsert)) self.assertEqual(coll.find().count(), len(values_to_insert))
for key, value in zip(insertedKeys, valuesToInsert): for key, value in zip(inserted_keys, values_to_insert):
doc = coll.find().key(key).getOne() doc = coll.find().key(key).getOne()
self.assertEqual(doc.getContent(), value) self.assertEqual(doc.getContent(), value)
coll.drop() coll.drop()
def test_3402_SkipDocuments(self): def test_3402_skip_documents(self):
"3402 - test skipping documents in a SODA collection" "3402 - test skipping documents in a SODA collection"
sodaDatabase = self.connection.getSodaDatabase() soda_db = self.connection.getSodaDatabase()
coll = sodaDatabase.createCollection("cxoSkipDocs") coll = soda_db.createCollection("cxoSkipDocs")
coll.find().remove() coll.find().remove()
valuesToInsert = [ values_to_insert = [
{"name": "Anna", "age": 62}, {"name": "Anna", "age": 62},
{"name": "Mark", "age": 37}, {"name": "Mark", "age": 37},
{"name": "Martha", "age": 43}, {"name": "Martha", "age": 43},
{"name": "Matthew", "age": 28} {"name": "Matthew", "age": 28}
] ]
for value in valuesToInsert: for value in values_to_insert:
coll.insertOne(value) coll.insertOne(value)
self.connection.commit() self.connection.commit()
self.__testSkip(coll, 0, valuesToInsert[3]) self.__test_skip(coll, 0, values_to_insert[3])
self.__testSkip(coll, 1, valuesToInsert[2]) self.__test_skip(coll, 1, values_to_insert[2])
self.__testSkip(coll, 3, valuesToInsert[0]) self.__test_skip(coll, 3, values_to_insert[0])
self.__testSkip(coll, 4, None) self.__test_skip(coll, 4, None)
self.__testSkip(coll, 125, None) self.__test_skip(coll, 125, None)
def test_3403_ReplaceDocument(self): def test_3403_replace_document(self):
"3403 - test replace documents in SODA collection" "3403 - test replace documents in SODA collection"
sodaDatabase = self.connection.getSodaDatabase() soda_db = self.connection.getSodaDatabase()
coll = sodaDatabase.createCollection("cxoReplaceDoc") coll = soda_db.createCollection("cxoReplaceDoc")
coll.find().remove() coll.find().remove()
content = {'name': 'John', 'address': {'city': 'Sydney'}} content = {'name': 'John', 'address': {'city': 'Sydney'}}
doc = coll.insertOneAndGet(content) doc = coll.insertOneAndGet(content)
newContent = {'name': 'John', 'address': {'city':'Melbourne'}} new_content = {'name': 'John', 'address': {'city':'Melbourne'}}
coll.find().key(doc.key).replaceOne(newContent) coll.find().key(doc.key).replaceOne(new_content)
self.connection.commit() self.connection.commit()
self.assertEqual(coll.find().key(doc.key).getOne().getContent(), self.assertEqual(coll.find().key(doc.key).getOne().getContent(),
newContent) new_content)
coll.drop() coll.drop()
def test_3404_SearchDocumentsWithContent(self): def test_3404_search_documents_with_content(self):
"3404 - test search documents with content using $like and $regex" "3404 - test search documents with content using $like and $regex"
sodaDatabase = self.connection.getSodaDatabase() soda_db = self.connection.getSodaDatabase()
coll = sodaDatabase.createCollection("cxoSearchDocContent") coll = soda_db.createCollection("cxoSearchDocContent")
coll.find().remove() coll.find().remove()
data = [ data = [
{'name': 'John', 'address': {'city': 'Bangalore'}}, {'name': 'John', 'address': {'city': 'Bangalore'}},
@ -102,7 +102,7 @@ class TestCase(TestEnv.BaseTestCase):
for value in data: for value in data:
coll.insertOne(value) coll.insertOne(value)
self.connection.commit() self.connection.commit()
filterSpecs = [ filter_specs = [
({'name': {'$like': 'And%'}}, 1), ({'name': {'$like': 'And%'}}, 1),
({'name': {'$like': 'J%n'}}, 3), ({'name': {'$like': 'J%n'}}, 3),
({'name': {'$like': '%hn%'}}, 2), ({'name': {'$like': '%hn%'}}, 2),
@ -118,15 +118,15 @@ class TestCase(TestEnv.BaseTestCase):
({'address.city': {'$regex': 'Hyderabad'}}, 1), ({'address.city': {'$regex': 'Hyderabad'}}, 1),
({'name': {'$regex': 'Js.*n'}}, 0) ({'name': {'$regex': 'Js.*n'}}, 0)
] ]
for filterSpec, expectedCount in filterSpecs: for filter_spec, expected_count in filter_specs:
self.assertEqual(coll.find().filter(filterSpec).count(), self.assertEqual(coll.find().filter(filter_spec).count(),
expectedCount, filterSpec) expected_count, filter_spec)
coll.drop() coll.drop()
def test_3405_DocumentRemove(self): def test_3405_document_remove(self):
"3405 - test removing documents" "3405 - test removing documents"
sodaDatabase = self.connection.getSodaDatabase() soda_db = self.connection.getSodaDatabase()
coll = sodaDatabase.createCollection("cxoRemoveDocs") coll = soda_db.createCollection("cxoRemoveDocs")
coll.find().remove() coll.find().remove()
data = [ data = [
{'name': 'John', 'address': {'city': 'Bangalore'}}, {'name': 'John', 'address': {'city': 'Bangalore'}},
@ -150,9 +150,9 @@ class TestCase(TestEnv.BaseTestCase):
def test_3406_CreateAndDropIndex(self): def test_3406_CreateAndDropIndex(self):
"3406 - test create and drop Index" "3406 - test create and drop Index"
indexName = "cxoTestIndexes_ix_1" index_name = "cxoTestIndexes_ix_1"
indexSpec = { index_spec = {
'name': indexName, 'name': index_name,
'fields': [ 'fields': [
{ {
'path': 'address.city', 'path': 'address.city',
@ -161,22 +161,22 @@ class TestCase(TestEnv.BaseTestCase):
} }
] ]
} }
sodaDatabase = self.connection.getSodaDatabase() soda_db = self.connection.getSodaDatabase()
coll = sodaDatabase.createCollection("cxoTestIndexes") coll = soda_db.createCollection("TestIndexes")
coll.find().remove() coll.find().remove()
self.connection.commit() self.connection.commit()
coll.dropIndex(indexName) coll.dropIndex(index_name)
coll.createIndex(indexSpec) coll.createIndex(index_spec)
self.assertRaises(cx_Oracle.DatabaseError, coll.createIndex, indexSpec) self.assertRaises(oracledb.DatabaseError, coll.createIndex, index_spec)
self.assertEqual(coll.dropIndex(indexName), True) self.assertEqual(coll.dropIndex(index_name), True)
self.assertEqual(coll.dropIndex(indexName), False) self.assertEqual(coll.dropIndex(index_name), False)
coll.drop() coll.drop()
def test_3407_GetDocuments(self): def test_3407_get_documents(self):
"3407 - test getting documents from Collection" "3407 - test getting documents from Collection"
self.connection.autocommit = True self.connection.autocommit = True
sodaDatabase = self.connection.getSodaDatabase() soda_db = self.connection.getSodaDatabase()
coll = sodaDatabase.createCollection("cxoTestGetDocs") coll = soda_db.createCollection("cxoTestGetDocs")
coll.find().remove() coll.find().remove()
data = [ data = [
{'name': 'John', 'address': {'city': 'Bangalore'}}, {'name': 'John', 'address': {'city': 'Bangalore'}},
@ -185,31 +185,31 @@ class TestCase(TestEnv.BaseTestCase):
{'name': 'Jibin', 'address': {'city': 'Secunderabad'}}, {'name': 'Jibin', 'address': {'city': 'Secunderabad'}},
{'name': 'Andrew', 'address': {'city': 'Hyderabad'}} {'name': 'Andrew', 'address': {'city': 'Hyderabad'}}
] ]
insertedKeys = list(sorted(coll.insertOneAndGet(v).key for v in data)) inserted_keys = list(sorted(coll.insertOneAndGet(v).key for v in data))
fetchedKeys = list(sorted(d.key for d in coll.find().getDocuments())) fetched_keys = list(sorted(d.key for d in coll.find().getDocuments()))
self.assertEqual(fetchedKeys, insertedKeys) self.assertEqual(fetched_keys, inserted_keys)
coll.drop() coll.drop()
def test_3408_Cursor(self): def test_3408_cursor(self):
"3408 - test fetching documents from a cursor" "3408 - test fetching documents from a cursor"
self.connection.autocommit = True self.connection.autocommit = True
sodaDatabase = self.connection.getSodaDatabase() soda_db = self.connection.getSodaDatabase()
coll = sodaDatabase.createCollection("cxoFindViaCursor") coll = soda_db.createCollection("cxoFindViaCursor")
coll.find().remove() coll.find().remove()
data = [ data = [
{'name': 'John', 'address': {'city': 'Bangalore'}}, {'name': 'John', 'address': {'city': 'Bangalore'}},
{'name': 'Johnson', 'address': {'city': 'Banaras'}}, {'name': 'Johnson', 'address': {'city': 'Banaras'}},
{'name': 'Joseph', 'address': {'city': 'Mangalore'}}, {'name': 'Joseph', 'address': {'city': 'Mangalore'}},
] ]
insertedKeys = list(sorted(coll.insertOneAndGet(v).key for v in data)) inserted_keys = list(sorted(coll.insertOneAndGet(v).key for v in data))
fetchedKeys = list(sorted(d.key for d in coll.find().getCursor())) fetched_keys = list(sorted(d.key for d in coll.find().getCursor()))
self.assertEqual(fetchedKeys, insertedKeys) self.assertEqual(fetched_keys, inserted_keys)
coll.drop() coll.drop()
def test_3409_MultipleDocumentRemove(self): def test_3409_multiple_document_remove(self):
"3409 - test removing multiple documents using multiple keys" "3409 - test removing multiple documents using multiple keys"
sodaDatabase = self.connection.getSodaDatabase() soda_db = self.connection.getSodaDatabase()
coll = sodaDatabase.createCollection("cxoRemoveMultipleDocs") coll = soda_db.createCollection("cxoRemoveMultipleDocs")
coll.find().remove() coll.find().remove()
data = [ data = [
{'name': 'John', 'address': {'city': 'Bangalore'}}, {'name': 'John', 'address': {'city': 'Bangalore'}},
@ -221,40 +221,40 @@ class TestCase(TestEnv.BaseTestCase):
] ]
docs = [coll.insertOneAndGet(v) for v in data] docs = [coll.insertOneAndGet(v) for v in data]
keys = [docs[i].key for i in (1, 3, 5)] keys = [docs[i].key for i in (1, 3, 5)]
numRemoved = coll.find().keys(keys).remove() num_removed = coll.find().keys(keys).remove()
self.assertEqual(numRemoved, len(keys)) self.assertEqual(num_removed, len(keys))
self.assertEqual(coll.find().count(), len(data) - len(keys)) self.assertEqual(coll.find().count(), len(data) - len(keys))
self.connection.commit() self.connection.commit()
coll.drop() coll.drop()
def test_3410_DocumentVersion(self): def test_3410_document_version(self):
"3410 - test using version to get documents and remove them" "3410 - test using version to get documents and remove them"
sodaDatabase = self.connection.getSodaDatabase() soda_db = self.connection.getSodaDatabase()
coll = sodaDatabase.createCollection("cxoDocumentVersion") coll = soda_db.createCollection("cxoDocumentVersion")
coll.find().remove() coll.find().remove()
content = {'name': 'John', 'address': {'city': 'Bangalore'}} content = {'name': 'John', 'address': {'city': 'Bangalore'}}
insertedDoc = coll.insertOneAndGet(content) inserted_doc = coll.insertOneAndGet(content)
key = insertedDoc.key key = inserted_doc.key
version = insertedDoc.version version = inserted_doc.version
doc = coll.find().key(key).version(version).getOne() doc = coll.find().key(key).version(version).getOne()
self.assertEqual(doc.getContent(), content) self.assertEqual(doc.getContent(), content)
newContent = {'name': 'James', 'address': {'city': 'Delhi'}} new_content = {'name': 'James', 'address': {'city': 'Delhi'}}
replacedDoc = coll.find().key(key).replaceOneAndGet(newContent) replacedDoc = coll.find().key(key).replaceOneAndGet(new_content)
newVersion = replacedDoc.version new_version = replacedDoc.version
doc = coll.find().key(key).version(version).getOne() doc = coll.find().key(key).version(version).getOne()
self.assertEqual(doc, None) self.assertEqual(doc, None)
doc = coll.find().key(key).version(newVersion).getOne() doc = coll.find().key(key).version(new_version).getOne()
self.assertEqual(doc.getContent(), newContent) self.assertEqual(doc.getContent(), new_content)
self.assertEqual(coll.find().key(key).version(version).remove(), 0) self.assertEqual(coll.find().key(key).version(version).remove(), 0)
self.assertEqual(coll.find().key(key).version(newVersion).remove(), 1) self.assertEqual(coll.find().key(key).version(new_version).remove(), 1)
self.assertEqual(coll.find().count(), 0) self.assertEqual(coll.find().count(), 0)
self.connection.commit() self.connection.commit()
coll.drop() coll.drop()
def test_3411_GetCursor(self): def test_3411_get_cursor(self):
"3411 - test keys with GetCursor" "3411 - test keys with GetCursor"
sodaDatabase = self.connection.getSodaDatabase() soda_db = self.connection.getSodaDatabase()
coll = sodaDatabase.createCollection("cxoKeysWithGetCursor") coll = soda_db.createCollection("cxoKeysWithGetCursor")
coll.find().remove() coll.find().remove()
data = [ data = [
{'name': 'John', 'address': {'city': 'Bangalore'}}, {'name': 'John', 'address': {'city': 'Bangalore'}},
@ -266,40 +266,39 @@ class TestCase(TestEnv.BaseTestCase):
] ]
docs = [coll.insertOneAndGet(v) for v in data] docs = [coll.insertOneAndGet(v) for v in data]
keys = [docs[i].key for i in (2, 4, 5)] keys = [docs[i].key for i in (2, 4, 5)]
fetchedKeys = [d.key for d in coll.find().keys(keys).getCursor()] fetched_keys = [d.key for d in coll.find().keys(keys).getCursor()]
self.assertEqual(list(sorted(fetchedKeys)), list(sorted(keys))) self.assertEqual(list(sorted(fetched_keys)), list(sorted(keys)))
self.connection.commit() self.connection.commit()
coll.drop() coll.drop()
def test_3412_CreatedOn(self): def test_3412_created_on(self):
"3412 - test createdOn attribute of Document" "3412 - test createdOn attribute of Document"
sodaDatabase = self.connection.getSodaDatabase() soda_db = self.connection.getSodaDatabase()
coll = sodaDatabase.createCollection("cxoCreatedOn") coll = soda_db.createCollection("CreatedOn")
coll.find().remove() coll.find().remove()
data = {'name': 'John', 'address': {'city': 'Bangalore'}} data = {'name': 'John', 'address': {'city': 'Bangalore'}}
doc = coll.insertOneAndGet(data) doc = coll.insertOneAndGet(data)
self.assertEqual(doc.createdOn, doc.lastModified) self.assertEqual(doc.createdOn, doc.lastModified)
@unittest.skipIf(TestEnv.GetClientVersion() < (20, 1), @unittest.skipIf(base.get_client_version() < (20, 1), "unsupported client")
"unsupported client") def test_3413_soda_truncate(self):
def test_3413_SodaTruncate(self):
"3413 - test Soda truncate" "3413 - test Soda truncate"
sodaDatabase = self.connection.getSodaDatabase() soda_db = self.connection.getSodaDatabase()
coll = sodaDatabase.createCollection("cxoTruncateDocs") coll = soda_db.createCollection("cxoTruncateDocs")
coll.find().remove() coll.find().remove()
valuesToInsert = [ values_to_insert = [
{"name": "George", "age": 47}, {"name": "George", "age": 47},
{"name": "Susan", "age": 39}, {"name": "Susan", "age": 39},
{"name": "John", "age": 50}, {"name": "John", "age": 50},
{"name": "Jill", "age": 54} {"name": "Jill", "age": 54}
] ]
for value in valuesToInsert: for value in values_to_insert:
coll.insertOne(value) coll.insertOne(value)
self.connection.commit() self.connection.commit()
self.assertEqual(coll.find().count(), len(valuesToInsert)) self.assertEqual(coll.find().count(), len(values_to_insert))
coll.truncate() coll.truncate()
self.assertEqual(coll.find().count(), 0) self.assertEqual(coll.find().count(), 0)
coll.drop() coll.drop()
if __name__ == "__main__": if __name__ == "__main__":
TestEnv.RunTestCases() base.run_test_cases()

View File

@ -2,7 +2,7 @@
envlist = py{36,37,38,39} envlist = py{36,37,38,39}
[testenv] [testenv]
commands = {envpython} test/TestEnv.py commands = {envpython} -m unittest discover -v -s test
passenv = passenv =
CX_ORACLE_TEST_MAIN_USER CX_ORACLE_TEST_MAIN_USER
CX_ORACLE_TEST_MAIN_PASSWORD CX_ORACLE_TEST_MAIN_PASSWORD