def test_otherColumn(): setupClass([SOTestComposerKey, SOTestOtherColumn]) test_composer1 = SOTestComposerKey(name='Test1') test_composer2 = SOTestComposerKey(name='Test2', id2=2) test_fkey = SOTestOtherColumn(key1=test_composer1) test_other = SOTestOtherColumn(key2=test_composer2.id2) getConnection().cache.clear() assert test_fkey.key1 == test_composer1 assert test_other.key2 == test_composer2
def test_perConnection(): connection = getConnection() SOTestPerConnection.dropTable(connection=connection, ifExists=True) SOTestPerConnection.createTable(connection=connection) SOTestPerConnection(test='test', connection=connection) assert len(list(SOTestPerConnection.select( SOTestPerConnection.q.test == 'test', connection=connection))) == 1
def test_microseconds(): connection = getConnection() if not hasattr(connection, 'can_use_microseconds') or \ not connection.can_use_microseconds(): pytest.skip( "The database doesn't support microseconds; " "microseconds are supported by MariaDB since version 5.3.0, " "by MySQL since version 5.6.4, " "by MSSQL since MS SQL Server 2008.") setupClass(DateTime1) _now = datetime.now() dt1 = DateTime1(col1=_now, col2=_now, col3=_now.time()) assert dt1.col1.microsecond == _now.microsecond assert dt1.col3.microsecond == _now.microsecond use_microseconds(False) setupClass(DateTime1) _now = datetime.now() dt1 = DateTime1(col1=_now, col2=_now, col3=_now.time()) assert dt1.col1.microsecond == 0 assert dt1.col3.microsecond == 0 use_microseconds(True) setupClass(DateTime1) _now = datetime.now() dt1 = DateTime1(col1=_now, col2=_now, col3=_now.time()) assert dt1.col1.microsecond == _now.microsecond assert dt1.col3.microsecond == _now.microsecond
def test_cyclic_reference(): if not supports('dropTableCascade'): pytest.skip("dropTableCascade isn't supported") conn = getConnection() SOTestCyclicRefA.setConnection(conn) SOTestCyclicRefB.setConnection(conn) SOTestCyclicRefA.dropTable(ifExists=True, cascade=True) assert not conn.tableExists(SOTestCyclicRefA.sqlmeta.table) SOTestCyclicRefB.dropTable(ifExists=True, cascade=True) assert not conn.tableExists(SOTestCyclicRefB.sqlmeta.table) constraints = SOTestCyclicRefA.createTable(ifNotExists=True, applyConstraints=False) assert conn.tableExists(SOTestCyclicRefA.sqlmeta.table) constraints += SOTestCyclicRefB.createTable(ifNotExists=True, applyConstraints=False) assert conn.tableExists(SOTestCyclicRefB.sqlmeta.table) for constraint in constraints: conn.query(constraint) SOTestCyclicRefA.dropTable(ifExists=True, cascade=True) assert not conn.tableExists(SOTestCyclicRefA.sqlmeta.table) SOTestCyclicRefB.dropTable(ifExists=True, cascade=True) assert not conn.tableExists(SOTestCyclicRefB.sqlmeta.table)
def test_mxDateTime(): setupClass(DateTime2) _now = now() dt2 = DateTime2(col1=_now, col2=_now, col3=Time(_now.hour, _now.minute, _now.second)) assert isinstance(dt2.col1, col.DateTimeType) assert dt2.col1.year == _now.year assert dt2.col1.month == _now.month assert dt2.col1.day == _now.day assert dt2.col1.hour == _now.hour assert dt2.col1.minute == _now.minute assert dt2.col1.second == int(_now.second) assert isinstance(dt2.col2, col.DateTimeType) assert dt2.col2.year == _now.year assert dt2.col2.month == _now.month assert dt2.col2.day == _now.day if getConnection().dbName == "sqlite": assert dt2.col2.hour == _now.hour assert dt2.col2.minute == _now.minute assert dt2.col2.second == int(_now.second) else: assert dt2.col2.hour == 0 assert dt2.col2.minute == 0 assert dt2.col2.second == 0 assert isinstance(dt2.col3, (col.DateTimeType, col.TimeType)) assert dt2.col3.hour == _now.hour assert dt2.col3.minute == _now.minute assert dt2.col3.second == int(_now.second)
def teardown_module(): connection = getConnection() if connection.dbName == 'sqlite': try: connection.dropDatabase() except OSError: pass
def teardown_method(self, meth): conn = getConnection() dbName = conn.dbName dropper = getattr(self, dbName + 'Drop', None) if dropper: try: conn.query(dropper) except Exception: # Perhaps we don't have DROP permission pass
def test_1syntax(): setup() join = JOIN("table1", "table2") assert str(join) == "table1 JOIN table2" join = LEFTJOIN("table1", "table2") assert str(join) == "table1 LEFT JOIN table2" join = LEFTJOINOn("table1", "table2", "tabl1.col1 = table2.col2") assert getConnection().sqlrepr(join) == \ "table1 LEFT JOIN table2 ON tabl1.col1 = table2.col2"
def setup_module(): connection = getConnection() if connection.dbName == 'sqlite': try: connection.dropDatabase() except OSError: pass open_db(connection.uri()) init_db()
def teardown_method(self, meth): conn = getConnection() dbName = conn.dbName dropper = getattr(self, dbName + 'Drop', None) if dropper: try: conn.query(dropper) except: # Perhaps we don't have DROP permission pass
def test_perConnection(): connection = getConnection() SOTestPerConnection.dropTable(connection=connection, ifExists=True) SOTestPerConnection.createTable(connection=connection) SOTestPerConnection(test='test', connection=connection) assert len( list( SOTestPerConnection.select(SOTestPerConnection.q.test == 'test', connection=connection))) == 1
def test_memorydb(): if not supports("memorydb"): pytest.skip("memorydb isn't supported") connection = getConnection() if connection.dbName != "sqlite": pytest.skip("These tests require SQLite") if not connection._memory: pytest.skip("The connection isn't memorydb") setupClass(SOTestSO1) connection.close() # create a new connection to an in-memory database SOTestSO1.setConnection(connection) SOTestSO1.createTable()
def test_create_drop(): conn = getConnection() SOTestCreateDrop.setConnection(conn) SOTestCreateDrop.dropTable(ifExists=True) assert not conn.tableExists(SOTestCreateDrop.sqlmeta.table) SOTestCreateDrop.createTable(ifNotExists=True) assert conn.tableExists(SOTestCreateDrop.sqlmeta.table) SOTestCreateDrop.createTable(ifNotExists=True) assert conn.tableExists(SOTestCreateDrop.sqlmeta.table) SOTestCreateDrop.dropTable(ifExists=True) assert not conn.tableExists(SOTestCreateDrop.sqlmeta.table) SOTestCreateDrop.dropTable(ifExists=True) assert not conn.tableExists(SOTestCreateDrop.sqlmeta.table)
def test_sslmode(): setupClass(SOTestSSLMode) connection = SOTestSSLMode._connection if (connection.dbName != 'postgres') or \ (not connection.module.__name__.startswith('psycopg')): pytest.skip("The test requires PostgreSQL, psycopg and ssl mode") connection = getConnection(sslmode='require') SOTestSSLMode._connection = connection test = SOTestSSLMode(test='test') # Connect to the DB to test sslmode connection.cache.clear() test = SOTestSSLMode.select()[0] assert test.test == 'test'
def test_groupBy_list(): setupClass(GroupbyTest) GroupbyTest(name='a', so_value=1) GroupbyTest(name='a', so_value=2) GroupbyTest(name='b', so_value=1) connection = getConnection() select = Select( [GroupbyTest.q.name, GroupbyTest.q.so_value], groupBy=[GroupbyTest.q.name, GroupbyTest.q.so_value], orderBy=[GroupbyTest.q.name, GroupbyTest.q.so_value]) sql = connection.sqlrepr(select) rows = list(connection.queryAll(sql)) assert [tuple(t) for t in rows] == [('a', 1), ('a', 2), ('b', 1)]
def test_connection_schema(): if not supports('schema'): pytest.skip("schemas aren't supported") conn = getConnection() conn.schema = None conn.query('CREATE SCHEMA test') conn.schema = 'test' conn.query('SET search_path TO test') setupClass(SOTestSchema) assert SOTestSchema._connection is conn SOTestSchema(foo='bar') assert conn.queryAll("SELECT * FROM test.so_test_schema") conn.schema = None conn.query('SET search_path TO public')
def test_groupBy_list(): setupClass(GroupbyTest) GroupbyTest(name='a', value=1) GroupbyTest(name='a', value=2) GroupbyTest(name='b', value=1) connection = getConnection() select = Select( [GroupbyTest.q.name, GroupbyTest.q.value], groupBy=[GroupbyTest.q.name, GroupbyTest.q.value], orderBy=[GroupbyTest.q.name, GroupbyTest.q.value]) sql = connection.sqlrepr(select) rows = connection.queryAll(sql) assert list(rows) == [('a', 1), ('a', 2), ('b', 1)]
def test_sslmode(): setupClass(SOTestSSLMode) connection = SOTestSSLMode._connection if (not connection.module.__name__.startswith('psycopg')) or \ (os.name == 'nt'): pytest.skip("The test requires PostgreSQL, psycopg and ssl mode; " "also it doesn't work on w32") connection = getConnection(sslmode='require') SOTestSSLMode._connection = connection test = SOTestSSLMode(test='test') # Connect to the DB to test sslmode connection.cache.clear() test = SOTestSSLMode.select()[0] assert test.test == 'test'
def test_identity(): # (re)create table SOTestIdentity.dropTable(connection=getConnection(), ifExists=True) setupClass(SOTestIdentity) # insert without giving identity SOTestIdentity(n=100) # i1 # verify result i1get = SOTestIdentity.get(1) assert (i1get.n == 100) # insert while giving identity SOTestIdentity(id=2, n=200) # i2 # verify result i2get = SOTestIdentity.get(2) assert (i2get.n == 200)
def test_identity(): # (re)create table SOTestIdentity.dropTable(connection=getConnection(), ifExists=True) setupClass(SOTestIdentity) # insert without giving identity SOTestIdentity(n=100) # i1 # verify result i1get = SOTestIdentity.get(1) assert(i1get.n == 100) # insert while giving identity SOTestIdentity(id=2, n=200) # i2 # verify result i2get = SOTestIdentity.get(2) assert(i2get.n == 200)
def test_exceptions(): if not supports("exceptions"): pytest.skip("exceptions aren't supported") setupClass(SOTestException) SOTestException(name="test") raises(DuplicateEntryError, SOTestException, name="test") connection = getConnection() if connection.module.__name__ != 'psycopg2': return SOTestExceptionWithNonexistingTable.setConnection(connection) try: list(SOTestExceptionWithNonexistingTable.select()) except ProgrammingError as e: assert e.args[0].code == '42P01' else: assert False, "DID NOT RAISE"
def test_CONCAT(): setupClass(SOTestSQLBuilder) SOTestSQLBuilder(name='test', value=42) assert sqlrepr(CONCAT('a', 'b'), 'mysql') == "CONCAT('a', 'b')" assert sqlrepr(CONCAT('a', 'b'), 'sqlite') == "'a' || 'b'" assert sqlrepr(CONCAT('prefix', SOTestSQLBuilder.q.name), 'mysql') == \ "CONCAT('prefix', so_test_sql_builder.name)" assert sqlrepr(CONCAT('prefix', SOTestSQLBuilder.q.name), 'sqlite') == \ "'prefix' || so_test_sql_builder.name" select = Select([CONCAT(SOTestSQLBuilder.q.name, '-suffix')], staticTables=['so_test_sql_builder']) connection = getConnection() rows = connection.queryAll(connection.sqlrepr(select)) result = rows[0][0] if not PY2 and not isinstance(result, str): result = result.decode('ascii') assert result == "test-suffix"
def test_CONCAT(): setupClass(SOTestSQLBuilder) SOTestSQLBuilder(name='test', so_value=42) assert sqlrepr(CONCAT('a', 'b'), 'mysql') == "CONCAT('a', 'b')" assert sqlrepr(CONCAT('a', 'b'), 'mssql') == "'a' + 'b'" assert sqlrepr(CONCAT('a', 'b'), 'sqlite') == "'a' || 'b'" assert sqlrepr(CONCAT('prefix', SOTestSQLBuilder.q.name), 'mysql') == \ "CONCAT('prefix', so_test_sql_builder.name)" assert sqlrepr(CONCAT('prefix', SOTestSQLBuilder.q.name), 'sqlite') == \ "'prefix' || so_test_sql_builder.name" select = Select([CONCAT(SOTestSQLBuilder.q.name, '-suffix')], staticTables=['so_test_sql_builder']) connection = getConnection() rows = connection.queryAll(connection.sqlrepr(select)) result = rows[0][0] if not PY2 and not isinstance(result, str): result = result.decode('ascii') assert result == "test-suffix"
def test_jsonbCol(): connection = getConnection() if connection.dbName != "postgres": pytest.skip("These tests require PostgreSQL") setupClass([JsonbContainer], force=True) my_jsonb = JsonbContainer(jsondata=dictdata, jsondata_none=nonedata, jsondata_list=listofdictsdata) iid = my_jsonb.id JsonbContainer._connection.cache.clear() my_jsonb_2 = JsonbContainer.get(iid) assert my_jsonb_2.jsondata['coming_home'] == dictdata['coming_home'] assert my_jsonb_2.jsondata['crew'] == dictdata['crew'] assert my_jsonb_2.jsondata['races'] == ['Borg', 'Kason'] assert my_jsonb_2.jsondata_none is None assert my_jsonb_2.jsondata_list == listofdictsdata
def test_pickleCol(): setupClass(SOTestPickle) connection = SOTestPickle._connection test = SOTestPickle(question=test_question, answer=test_answer) pickle_data = pickle.dumps(test, pickle.HIGHEST_PROTOCOL) connection.cache.clear() test = pickle.loads(pickle_data) test2 = connection.cache.tryGet(test.id, SOTestPickle) assert test2 is test assert test.question == test_question assert test.answer == test_answer if (connection.dbName == 'sqlite') and connection._memory: pytest.skip("The following test requires a different connection") test = SOTestPickle.get( test.id, # make a different DB URI and open another connection connection=getConnection(registry='')) raises(pickle.PicklingError, pickle.dumps, test, pickle.HIGHEST_PROTOCOL)
def test_jsonbCol(): connection = getConnection() if connection.dbName != "postgres": pytest.skip("These tests require PostgreSQL") setupClass([JsonbContainer], force=True) my_jsonb = JsonbContainer( jsondata=dictdata, jsondata_none=nonedata, jsondata_list=listofdictsdata) iid = my_jsonb.id JsonbContainer._connection.cache.clear() my_jsonb_2 = JsonbContainer.get(iid) assert my_jsonb_2.jsondata['coming_home'] == dictdata['coming_home'] assert my_jsonb_2.jsondata['crew'] == dictdata['crew'] assert my_jsonb_2.jsondata['races'] == ['Borg', 'Kason'] assert my_jsonb_2.jsondata_none is None assert my_jsonb_2.jsondata_list == listofdictsdata
def test_deep_inheritance(): setupClass([DIManager, DIEmployee, DIPerson]) manager = DIManager(firstName='Project', lastName='Manager', position='Project Manager') manager_id = manager.id employee_id = DIEmployee(firstName='Project', lastName='Leader', position='Project leader', manager=manager).id DIPerson(firstName='Oneof', lastName='Authors', manager=manager) conn = getConnection() cache = conn.cache cache.clear() managers = list(DIManager.select()) assert len(managers) == 1 cache.clear() employees = list(DIEmployee.select()) assert len(employees) == 2 cache.clear() persons = list(DIPerson.select()) assert len(persons) == 3 cache.clear() person = DIPerson.get(employee_id) assert isinstance(person, DIEmployee) person = DIPerson.get(manager_id) assert isinstance(person, DIEmployee) assert isinstance(person, DIManager) cache.clear() person = DIEmployee.get(manager_id) assert isinstance(person, DIManager) conn.close()
def test_deep_inheritance(): setupClass([DIManager, DIEmployee, DIPerson]) manager = DIManager(firstName='Project', lastName='Manager', so_position='Project Manager') manager_id = manager.id employee_id = DIEmployee(firstName='Project', lastName='Leader', so_position='Project leader', manager=manager).id DIPerson(firstName='Oneof', lastName='Authors', manager=manager) conn = getConnection() cache = conn.cache cache.clear() managers = list(DIManager.select()) assert len(managers) == 1 cache.clear() employees = list(DIEmployee.select()) assert len(employees) == 2 cache.clear() persons = list(DIPerson.select()) assert len(persons) == 3 cache.clear() person = DIPerson.get(employee_id) assert isinstance(person, DIEmployee) person = DIPerson.get(manager_id) assert isinstance(person, DIEmployee) assert isinstance(person, DIManager) cache.clear() person = DIEmployee.get(manager_id) assert isinstance(person, DIManager) conn.close()
def test_list_databases(): connection = getConnection() if connection.dbName != "mysql": pytest.skip("These tests require MySQL") assert connection.db in connection.listDatabases()
def test_list_tables(): connection = getConnection() if connection.dbName != "mysql": pytest.skip("These tests require MySQL") setupClass(SOTestSOListMySQL) assert SOTestSOListMySQL.sqlmeta.table in connection.listTables()
def test2(): SOTestWorkKey._connection = getConnection() InstalledTestDatabase.drop(SOTestWorkKey) setupClass([SOTestComposerKey, SOTestWorkKey2], force=True) SOTestWorkKey2.sqlmeta.addColumn(ForeignKey('SOTestComposerKey'), changeSchema=True)
def test_list_tables(): connection = getConnection() if connection.dbName != "sqlite": pytest.skip("These tests require SQLite") setupClass(SOTestSO1) assert SOTestSO1.sqlmeta.table in connection.listTables()
use_microseconds(True) setupClass(DateTime1) _now = datetime.now() dt1 = DateTime1(col1=_now, col2=_now, col3=_now.time()) assert dt1.col1.microsecond == _now.microsecond assert dt1.col3.microsecond == _now.microsecond if mxdatetime_available: col.default_datetime_implementation = MXDATETIME_IMPLEMENTATION from mx.DateTime import now, Time dateFormat = None # use default try: connection = getConnection() except AttributeError: # The module was imported during documentation building pass else: if connection.dbName == "sqlite": if connection.using_sqlite2: # mxDateTime sends and PySQLite2 returns # full date/time for dates dateFormat = "%Y-%m-%d %H:%M:%S.%f" class DateTime2(SQLObject): col1 = DateTimeCol() col2 = DateCol(dateFormat=dateFormat) col3 = TimeCol()
def test_list_databases(): connection = getConnection() if connection.dbName != "sqlite": pytest.skip("These tests require SQLite") assert connection.listDatabases() == ['main']
def setup_method(self, meth): conn = getConnection() dbName = conn.dbName creator = getattr(self, dbName + 'Create', None) if creator: conn.query(creator)
def teardown_method(self, meth): conn = getConnection() dbName = conn.dbName dropper = getattr(self, dbName + 'Drop', None) if dropper: conn.query(dropper)
class AutoTest(SQLObject): _connection = getConnection() class sqlmeta(sqlmeta): idName = 'auto_id' fromDatabase = True
def test_list_tables(): connection = getConnection() if connection.dbName != "postgres": pytest.skip("These tests require PostgreSQL") setupClass(SOTestSOList) assert SOTestSOList.sqlmeta.table in connection.listTables()
def test_list_databases(): connection = getConnection() if connection.dbName != "postgres": pytest.skip("These tests require PostgreSQL") assert connection.db in connection.listDatabases()