Пример #1
0
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_creation_fail2():
    """
    Try to create two Managers with the same position.
    This should fail without leaving any partial records in
    the database.

    """
    setupClass([DIManager, DIEmployee, DIPerson])

    kwargs = {'firstName': 'John', 'lastName': 'Doe',
              'position': 'Project Manager'}
    DIManager(**kwargs)
    persons = DIEmployee.select(DIPerson.q.firstName == 'John')
    assert persons.count() == 1

    kwargs = {'firstName': 'John', 'lastName': 'Doe II',
              'position': 'Project Manager'}
    raises(Exception, DIManager, **kwargs)
    persons = DIPerson.select(DIPerson.q.firstName == 'John')
    assert persons.count() == 1

    if not supports('transactions'):
        skip("Transactions aren't supported")
    transaction = DIPerson._connection.transaction()
    kwargs = {'firstName': 'John', 'lastName': 'Doe III',
              'position': 'Project Manager'}
    raises(Exception, DIManager, connection=transaction, **kwargs)
    transaction.rollback()
    transaction.begin()
    persons = DIPerson.select(DIPerson.q.firstName == 'John',
                              connection=transaction)
    assert persons.count() == 1
Пример #3
0
def test_creation_fail2():
    """
    Try to create two Managers with the same position.
    This should fail without leaving any partial records in
    the database.

    """
    setupClass([DIManager, DIEmployee, DIPerson])

    kwargs = {'firstName': 'John', 'lastName': 'Doe',
              'so_position': 'Project Manager'}
    DIManager(**kwargs)
    persons = DIEmployee.select(DIPerson.q.firstName == 'John')
    assert persons.count() == 1

    kwargs = {'firstName': 'John', 'lastName': 'Doe II',
              'so_position': 'Project Manager'}
    raises(Exception, DIManager, **kwargs)
    persons = DIPerson.select(DIPerson.q.firstName == 'John')
    assert persons.count() == 1

    if not supports('transactions'):
        skip("Transactions aren't supported")
    transaction = DIPerson._connection.transaction()
    kwargs = {'firstName': 'John', 'lastName': 'Doe III',
              'so_position': 'Project Manager'}
    raises(Exception, DIManager, connection=transaction, **kwargs)
    transaction.rollback()
    transaction.begin()
    persons = DIPerson.select(DIPerson.q.firstName == 'John',
                              connection=transaction)
    assert persons.count() == 1
Пример #4
0
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)
Пример #5
0
def test_memorydb():
    if not supports("memorydb"):
        pytest.skip("memorydb isn't supported")
    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()
Пример #6
0
def test_memorydb():
    if not supports("memorydb"):
        pytest.skip("memorydb isn't supported")
    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()
Пример #7
0
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()
Пример #8
0
def test_empty():
    if not supports('emptyTable'):
        pytest.skip("emptyTable isn't supported")
    setupClass(EmptyClass)
    e1 = EmptyClass()
    e2 = EmptyClass()
    assert e1 != e2
    assert e1.id != e2.id
    assert e1 in list(EmptyClass.select())
    assert e2 in list(EmptyClass.select())
    e1.destroySelf()
    assert list(EmptyClass.select()) == [e2]
Пример #9
0
def test_related_join_transaction():
    if not supports('transactions'):
        pytest.skip("Transactions aren't supported")
    createAllTables()
    trans = Tourtment._connection.transaction()
    try:
        t1 = Tourtment(name='Tourtment #1', connection=trans)
        t1.addFighter(Fighter(name='Jim', connection=trans))
        assert t1.fightersAsSResult.count() == 1
        assert t1.fightersAsSResult[0]._connection == trans
    finally:
        trans.commit(True)
        Tourtment._connection.autoCommit = True
Пример #10
0
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_multiple_join_transaction():
    if not supports('transactions'):
        pytest.skip("Transactions aren't supported")
    createAllTables()
    trans = Race._connection.transaction()
    try:
        namek = Race(name='namekuseijin', connection=trans)
        RFighter(name='Gokou (Kakaruto)', race=namek, power=10,
                 connection=trans)
        assert namek.fightersAsSResult.count() == 1
        assert namek.fightersAsSResult[0]._connection == trans
    finally:
        trans.commit(True)
        Race._connection.autoCommit = True
Пример #12
0
def test_transaction_commit_sync():
    if not supports('transactions'):
        pytest.skip("Transactions aren't supported")
    setupClass(SOTestSOTrans)
    trans = SOTestSOTrans._connection.transaction()
    try:
        SOTestSOTrans(name='bob')
        bOut = SOTestSOTrans.byName('bob')
        bIn = SOTestSOTrans.byName('bob', connection=trans)
        bIn.name = 'robert'
        assert bOut.name == 'bob'
        trans.commit()
        assert bOut.name == 'robert'
    finally:
        SOTestSOTrans._connection.autoCommit = True
Пример #13
0
def test_multiple_join_transaction():
    if not supports('transactions'):
        pytest.skip("Transactions aren't supported")
    createAllTables()
    trans = Race._connection.transaction()
    try:
        namek = Race(name='namekuseijin', connection=trans)
        RFighter(name='Gokou (Kakaruto)',
                 race=namek,
                 power=10,
                 connection=trans)
        assert namek.fightersAsSResult.count() == 1
        assert namek.fightersAsSResult[0]._connection == trans
    finally:
        trans.commit(True)
        Race._connection.autoCommit = True
Пример #14
0
def test_BLOBCol():
    if not supports('blobData'):
        pytest.skip("blobData isn't supported")
    setupClass(ImageData)
    if PY2:
        data = ''.join([chr(x) for x in range(256)])
    else:
        data = bytes(range(256))

    prof = ImageData()
    prof.image = data
    iid = prof.id

    ImageData._connection.cache.clear()

    prof2 = ImageData.get(iid)
    assert prof2.image == data
Пример #15
0
def test_BLOBCol():
    if not supports('blobData'):
        pytest.skip("blobData isn't supported")
    setupClass(ImageData)
    if PY2:
        data = ''.join([chr(x) for x in range(256)])
    else:
        data = bytes(range(256))

    prof = ImageData()
    prof.image = data
    iid = prof.id

    ImageData._connection.cache.clear()

    prof2 = ImageData.get(iid)
    assert prof2.image == data
Пример #16
0
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"
Пример #17
0
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"
Пример #18
0
def test_pickleCol():
    if not supports('blobData'):
        pytest.skip("blobData isn't supported")
    setupClass([PickleContainer], force=True)
    mypickledata = PickleData()

    ctnr = PickleContainer(pickledata=mypickledata)
    iid = ctnr.id

    PickleContainer._connection.cache.clear()

    ctnr2 = PickleContainer.get(iid)
    s2 = ctnr2.pickledata

    assert isinstance(s2, PickleData)
    assert isinstance(s2.pi, float)
    assert isinstance(s2.question, str)
    assert isinstance(s2.answer, int)
    assert s2.pi == mypickledata.pi
    assert s2.question == mypickledata.question
    assert s2.answer == mypickledata.answer
Пример #19
0
def test_pickleCol():
    if not supports('blobData'):
        pytest.skip("blobData isn't supported")
    setupClass([PickleContainer], force=True)
    mypickledata = PickleData()

    ctnr = PickleContainer(pickledata=mypickledata)
    iid = ctnr.id

    PickleContainer._connection.cache.clear()

    ctnr2 = PickleContainer.get(iid)
    s2 = ctnr2.pickledata

    assert isinstance(s2, PickleData)
    assert isinstance(s2.pi, float)
    assert isinstance(s2.question, str)
    assert isinstance(s2.answer, int)
    assert s2.pi == mypickledata.pi
    assert s2.question == mypickledata.question
    assert s2.answer == mypickledata.answer
Пример #20
0
def testForeignKeyDropTableCascade():
    if not supports('dropTableCascade'):
        pytest.skip("dropTableCascade isn't supported")
    setupClass(SOTestSO7)
    setupClass(SOTestSO6)
    setupClass(SOTestSO5)

    tc5a = SOTestSO5(name='a')
    tc6a = SOTestSO6(name='1')
    tc5a.other = tc6a
    tc7a = SOTestSO7(name='2')
    tc6a.other = tc7a
    tc5a.another = tc7a
    tc5b = SOTestSO5(name='b')
    tc5c = SOTestSO5(name='c')
    tc6b = SOTestSO6(name='3')
    tc5c.other = tc6b
    assert SOTestSO5.select().count() == 3
    assert SOTestSO6.select().count() == 2
    assert SOTestSO7.select().count() == 1
    SOTestSO7.dropTable(cascade=True)
    assert SOTestSO5.select().count() == 3
    assert SOTestSO6.select().count() == 2
    tc6a.destroySelf()
    assert SOTestSO5.select().count() == 2
    assert SOTestSO6.select().count() == 1
    tc6b.destroySelf()
    assert SOTestSO5.select().count() == 1
    assert SOTestSO6.select().count() == 0
    assert next(iter(SOTestSO5.select())) == tc5b
    tc6c = SOTestSO6(name='3')
    tc5b.other = tc6c
    assert SOTestSO5.select().count() == 1
    assert SOTestSO6.select().count() == 1
    tc6c.destroySelf()
    assert SOTestSO5.select().count() == 0
    assert SOTestSO6.select().count() == 0
Пример #21
0
def testForeignKeyDropTableCascade():
    if not supports('dropTableCascade'):
        pytest.skip("dropTableCascade isn't supported")
    setupClass(SOTestSO7)
    setupClass(SOTestSO6)
    setupClass(SOTestSO5)

    tc5a = SOTestSO5(name='a')
    tc6a = SOTestSO6(name='1')
    tc5a.other = tc6a
    tc7a = SOTestSO7(name='2')
    tc6a.other = tc7a
    tc5a.another = tc7a
    tc5b = SOTestSO5(name='b')
    tc5c = SOTestSO5(name='c')
    tc6b = SOTestSO6(name='3')
    tc5c.other = tc6b
    assert SOTestSO5.select().count() == 3
    assert SOTestSO6.select().count() == 2
    assert SOTestSO7.select().count() == 1
    SOTestSO7.dropTable(cascade=True)
    assert SOTestSO5.select().count() == 3
    assert SOTestSO6.select().count() == 2
    tc6a.destroySelf()
    assert SOTestSO5.select().count() == 2
    assert SOTestSO6.select().count() == 1
    tc6b.destroySelf()
    assert SOTestSO5.select().count() == 1
    assert SOTestSO6.select().count() == 0
    assert next(iter(SOTestSO5.select())) == tc5b
    tc6c = SOTestSO6(name='3')
    tc5b.other = tc6c
    assert SOTestSO5.select().count() == 1
    assert SOTestSO6.select().count() == 1
    tc6c.destroySelf()
    assert SOTestSO5.select().count() == 0
    assert SOTestSO6.select().count() == 0
Пример #22
0
def test_transaction_delete(close=False):
    if not supports('transactions'):
        pytest.skip("Transactions aren't supported")
    setupClass(SOTestSOTrans)
    connection = SOTestSOTrans._connection
    if (connection.dbName == 'sqlite') and connection._memory:
        pytest.skip("The following test requires a different connection")
    trans = connection.transaction()
    try:
        SOTestSOTrans(name='bob')
        bIn = SOTestSOTrans.byName('bob', connection=trans)
        bIn.destroySelf()
        bOut = SOTestSOTrans.select(SOTestSOTrans.q.name == 'bob')
        assert bOut.count() == 1
        bOutInst = bOut[0]
        bOutID = bOutInst.id  # noqa: bOutID is used in the string code below
        trans.commit(close=close)
        assert bOut.count() == 0
        raises(SQLObjectNotFound, "SOTestSOTrans.get(bOutID)")
        raises(SQLObjectNotFound, "bOutInst.name")
    finally:
        trans.rollback()
        connection.autoCommit = True
        connection.close()
Пример #23
0
def test_transaction():
    if not supports('transactions'):
        pytest.skip("Transactions aren't supported")
    setupClass(SOTestSOTrans)
    SOTestSOTrans(name='bob')
    SOTestSOTrans(name='tim')
    trans = SOTestSOTrans._connection.transaction()
    try:
        SOTestSOTrans._connection.autoCommit = 'exception'
        SOTestSOTrans(name='joe', connection=trans)
        trans.rollback()
        trans.begin()
        assert ([n.name for n in SOTestSOTrans.select(connection=trans)] ==
                ['bob', 'tim'])
        b = SOTestSOTrans.byName('bob', connection=trans)
        b.name = 'robert'
        trans.commit()
        assert b.name == 'robert'
        b.name = 'bob'
        trans.rollback()
        trans.begin()
        assert b.name == 'robert'
    finally:
        SOTestSOTrans._connection.autoCommit = True
Пример #24
0
def test_indexes_2():
    if not supports('expressionIndex'):
        pytest.skip("expressionIndex isn't supported")
    setupClass(SOIndex2)
    SOIndex2(name='')
Пример #25
0
import pytest
from sqlobject import SQLObject, SQLObjectNotFound, StringCol
from sqlobject.tests.dbtest import raises, setupClass, supports

########################################
# Transaction test
########################################

try:
    support_transactions = supports('transactions')
except NameError:
    # The module was imported during documentation building
    pass
else:
    if not support_transactions:
        pytestmark = pytest.mark.skip('')


class SOTestSOTrans(SQLObject):
    class sqlmeta:
        defaultOrder = 'name'

    name = StringCol(length=10, alternateID=True, dbName='name_col')


def test_transaction():
    setupClass(SOTestSOTrans)
    SOTestSOTrans(name='bob')
    SOTestSOTrans(name='tim')
    trans = SOTestSOTrans._connection.transaction()
    try:
Пример #26
0
from decimal import Decimal
import pytest
from sqlobject import DecimalCol, DecimalStringCol, SQLObject, UnicodeCol
from sqlobject.tests.dbtest import setupClass, supports


########################################
# Decimal columns
########################################


try:
    support_decimal_column = supports('decimalColumn')
except NameError:
    # The module was imported during documentation building
    pass
else:
    if not support_decimal_column:
        pytestmark = pytest.mark.skip('')


class DecimalTable(SQLObject):
    name = UnicodeCol(length=255)
    col1 = DecimalCol(size=6, precision=4)
    col2 = DecimalStringCol(size=6, precision=4)
    col3 = DecimalStringCol(size=6, precision=4, quantize=True)


def test_1_decimal():
    setupClass(DecimalTable)
    d = DecimalTable(name='test', col1=21.12, col2='10.01', col3='10.01')
Пример #27
0
 def counterEqual(self, counters, value):
     if not supports('limitSelect'):
         pytest.skip("limitSelect isn't supported")
     assert [c.number for c in counters] == value
Пример #28
0
from decimal import Decimal
import pytest
from sqlobject import DecimalCol, DecimalStringCol, SQLObject, UnicodeCol
from sqlobject.tests.dbtest import setupClass, supports

########################################
# Decimal columns
########################################

try:
    support_decimal_column = supports('decimalColumn')
except NameError:
    # The module was imported during documentation building
    pass
else:
    if not support_decimal_column:
        pytestmark = pytest.mark.skip('')


class DecimalTable(SQLObject):
    name = UnicodeCol(length=255)
    col1 = DecimalCol(size=6, precision=4)
    col2 = DecimalStringCol(size=6, precision=4)
    col3 = DecimalStringCol(size=6, precision=4, quantize=True)


def test_1_decimal():
    setupClass(DecimalTable)
    d = DecimalTable(name='test', col1=21.12, col2='10.01', col3='10.01')
    # psycopg2 returns float as Decimal
    if isinstance(d.col1, Decimal):