コード例 #1
0
def test_str_or_sqlrepr():
    select = Select(['id', 'name'], staticTables=['employees'],
                    where='value>0', orderBy='id')
    assert sqlrepr(select, 'sqlite') == \
        'SELECT id, name FROM employees WHERE value>0 ORDER BY id'

    select = Select(['id', 'name'], staticTables=['employees'],
                    where='value>0', orderBy='id', lazyColumns=True)
    assert sqlrepr(select, 'sqlite') == \
        'SELECT id FROM employees WHERE value>0 ORDER BY id'

    insert = Insert('employees', values={'id': 1, 'name': 'test'})
    assert sqlrepr(insert, 'sqlite') == \
        "INSERT INTO employees (id, name) VALUES (1, 'test')"

    update = Update('employees', {'name': 'test'}, where='id=1')
    assert sqlrepr(update, 'sqlite') == \
        "UPDATE employees SET name='test' WHERE id=1"

    update = Update('employees', {'name': 'test', 'age': 42}, where='id=1')
    assert sqlrepr(update, 'sqlite') == \
        "UPDATE employees SET age=42, name='test' WHERE id=1"

    delete = Delete('employees', where='id=1')
    assert sqlrepr(delete, 'sqlite') == \
        "DELETE FROM employees WHERE id=1"

    raises(TypeError, Delete, 'employees')

    delete = Delete('employees', where=None)
    assert sqlrepr(delete, 'sqlite') == \
        "DELETE FROM employees"
コード例 #2
0
def test3():
    setupClass([SOTestPerson3, SOTestMessageCascadeNull])

    john = SOTestPerson3(name='john')
    emily = SOTestPerson3(name='emily')
    message = SOTestMessageCascadeNull(sender=emily,
                                       recipient=john,
                                       body='test3')

    SOTestPerson3.delete(emily.id)
    john.expire()
    message.expire()

    john.sync()
    message.sync()
    raises(SQLObjectNotFound, emily.sync)

    assert message.sender is None
    assert message.recipient == john

    SOTestPerson3.delete(john.id)
    john.expire()
    message.expire()

    message.sync()
    raises(SQLObjectNotFound, john.sync)

    assert message.recipient is None
コード例 #3
0
 def test_wrapType(self):
     t = SOValidation(name3=1)
     raises(validators.Invalid, setattr, t, 'name3', 'x')
     t.name3 = long(1)
     assert t.name3 == 1
     t.name3 = 0
     assert t.name3 == 0
コード例 #4
0
 def test_wrapType(self):
     t = SOValidation(name3=1)
     raises(validators.Invalid, setattr, t, 'name3', 'x')
     t.name3 = long(1)
     assert t.name3 == 1
     t.name3 = 0
     assert t.name3 == 0
コード例 #5
0
def testBad():
    setupClass(Enum1)
    for _l in ['a', 'bcd', 'a', 'e']:
        Enum1(cl=_l)
    raises((Enum1._connection.module.IntegrityError,
            Enum1._connection.module.ProgrammingError, validators.Invalid),
           Enum1,
           cl='b')
コード例 #6
0
ファイル: test_enum.py プロジェクト: LutzSteinborn/sqlobject
def testBad():
    setupClass(Enum1)
    for l in ['a', 'bcd', 'a', 'e']:
        Enum1(l=l)
    raises(
        (Enum1._connection.module.IntegrityError,
         Enum1._connection.module.ProgrammingError,
         validators.Invalid),
        Enum1, l='b')
コード例 #7
0
def test_aggregates():
    setupClass([SOTestAggregate1, SOTestAggregate2])

    SOTestAggregate1(value1=1)
    SOTestAggregate2(value1=2, value2=12)

    assert SOTestAggregate1.select().max("value1") == 2
    assert SOTestAggregate2.select().max("value1") == 2
    raises(Exception, SOTestAggregate2.select().max, "value2")
    assert SOTestAggregate2.select().max(SOTestAggregate2.q.value2) == 12
コード例 #8
0
ファイル: test_indexes.py プロジェクト: ware111/untitled
def test_indexes_1():
    setupClass(SOIndex1)
    n = 0
    for name in 'blah blech boring yep yort snort'.split():
        n += 1
        SOIndex1(name=name, number=n)
    mod = SOIndex1._connection.module
    raises(
        (mod.ProgrammingError, mod.IntegrityError,
         mod.OperationalError, mod.DatabaseError,
         ProgrammingError, IntegrityError, OperationalError, DatabaseError),
        SOIndex1, name='blah', number=0)
コード例 #9
0
def test4():
    setupClass([SOTestPerson4, SOTestMessageCascadeMixed])

    john = SOTestPerson4(name='john')
    emily = SOTestPerson4(name='emily')
    message = SOTestMessageCascadeMixed(sender=emily,
                                        recipient=john,
                                        body='test4')

    SOTestPerson4.delete(emily.id)
    john.expire()
    message.expire()

    john.sync()
    raises(SQLObjectNotFound, message.sync)
コード例 #10
0
def test1():
    setupClass([SOTestPerson1, SOTestMessageCascadeTrue])

    john = SOTestPerson1(name='john')
    emily = SOTestPerson1(name='emily')
    message = SOTestMessageCascadeTrue(sender=emily,
                                       recipient=john,
                                       body='test1')

    SOTestPerson1.delete(emily.id)
    john.expire()
    message.expire()

    john.sync()
    raises(SQLObjectNotFound, emily.sync)
    raises(SQLObjectNotFound, message.sync)
コード例 #11
0
ファイル: test_exceptions.py プロジェクト: ware111/untitled
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"
コード例 #12
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"
コード例 #13
0
def test_foreignkey_validation():
    setupCyclicClasses(SOTestFKValidationA, SOTestFKValidationB,
                       SOTestFKValidationC)
    a = SOTestFKValidationA(name="testa", bfk=None)
    b = SOTestFKValidationB(name="testb", afk=a)
    c = SOTestFKValidationC(id='testc', name="testc")
    a.bfk = b
    a.cfk = c
    assert a.bfk == b
    assert a.cfk == c
    assert b.afk == a

    raises(validators.Invalid,
           SOTestFKValidationA, name="testa", bfk='testb', cfk='testc')

    a = SOTestFKValidationA(name="testa", bfk=1, cfk='testc')
    assert a.bfkID == 1
    assert a.cfkID == 'testc'
コード例 #14
0
    def test_confirmType(self):
        t = SOValidation(name2='hey')
        raises(validators.Invalid, setattr, t, 'name2', 1)
        raises(validators.Invalid, setattr, t, 'name3', '1')
        raises(validators.Invalid, setattr, t, 'name4', '1')
        raises(validators.Invalid, setattr, t, 'name6', '1')
        raises(validators.Invalid, setattr, t, 'name7', 1)
        t.name2 = 'you'
        assert t.name2 == 'you'

        for name, cls, value in (('name4', SOValidationTestFloat,
                                  1.1), ('name6', SOValidationTestBool, True),
                                 ('name8', SOValidationTestInt, 1)):
            setattr(t, name, cls(value))
            assert getattr(t, name) == value
        if PY2:
            for name, cls, value in (('name7', SOValidationTestUnicode,
                                      u'test'), ):
                setattr(t, name, cls(value))
                assert getattr(t, name) == value
コード例 #15
0
def test2():
    setupClass([SOTestPerson2, SOTestMessageCascadeFalse])

    john = SOTestPerson2(name='john')
    emily = SOTestPerson2(name='emily')
    message = SOTestMessageCascadeFalse(sender=emily,
                                        recipient=john,
                                        body='test2')

    raises(SQLObjectIntegrityError, SOTestPerson2.delete, emily.id)
    john.expire()
    emily.expire()
    message.expire()

    john.sync()
    emily.sync()
    message.sync()

    assert message.sender == emily
    assert message.recipient == john
コード例 #16
0
    def test_confirmType(self):
        t = SOValidation(name2='hey')
        raises(validators.Invalid, setattr, t, 'name2', 1)
        raises(validators.Invalid, setattr, t, 'name3', '1')
        raises(validators.Invalid, setattr, t, 'name4', '1')
        raises(validators.Invalid, setattr, t, 'name6', '1')
        raises(validators.Invalid, setattr, t, 'name7', 1)
        t.name2 = 'you'
        assert t.name2 == 'you'

        for name, cls, value in (
                ('name4', SOValidationTestFloat, 1.1),
                ('name6', SOValidationTestBool, True),
                ('name8', SOValidationTestInt, 1)):
            setattr(t, name, cls(value))
            assert getattr(t, name) == value
        if PY2:
            for name, cls, value in (
                    ('name7', SOValidationTestUnicode, u'test'),):
                setattr(t, name, cls(value))
                assert getattr(t, name) == value
コード例 #17
0
ファイル: test_basic.py プロジェクト: LutzSteinborn/sqlobject
def testForeignKeyDestroySelfRestrict():
    setupClass([SOTestSO9, SOTestSO8])

    tc8a = SOTestSO8(name='a')
    tc9a = SOTestSO9(name='1')
    tc8a.other = tc9a
    tc8b = SOTestSO8(name='b')
    tc9b = SOTestSO9(name='2')
    assert tc8a.other == tc9a
    assert tc8a.otherID == tc9a.id
    assert SOTestSO8.select().count() == 2
    assert SOTestSO9.select().count() == 2
    raises(Exception, tc9a.destroySelf)
    tc9b.destroySelf()
    assert SOTestSO8.select().count() == 2
    assert SOTestSO9.select().count() == 1
    tc8a.destroySelf()
    tc8b.destroySelf()
    tc9a.destroySelf()
    assert SOTestSO8.select().count() == 0
    assert SOTestSO9.select().count() == 0
コード例 #18
0
ファイル: test_basic.py プロジェクト: ware111/untitled
def testForeignKeyDestroySelfRestrict():
    setupClass([SOTestSO9, SOTestSO8])

    tc8a = SOTestSO8(name='a')
    tc9a = SOTestSO9(name='1')
    tc8a.other = tc9a
    tc8b = SOTestSO8(name='b')
    tc9b = SOTestSO9(name='2')
    assert tc8a.other == tc9a
    assert tc8a.otherID == tc9a.id
    assert SOTestSO8.select().count() == 2
    assert SOTestSO9.select().count() == 2
    raises(Exception, tc9a.destroySelf)
    tc9b.destroySelf()
    assert SOTestSO8.select().count() == 2
    assert SOTestSO9.select().count() == 1
    tc8a.destroySelf()
    tc8b.destroySelf()
    tc9a.destroySelf()
    assert SOTestSO8.select().count() == 0
    assert SOTestSO9.select().count() == 0
コード例 #19
0
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)
コード例 #20
0
def test_transaction_delete(close=False):
    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()
コード例 #21
0
ファイル: test_pickle.py プロジェクト: ware111/untitled
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)
コード例 #22
0
    def test_confirmType(self):
        t = SOValidation(name2='hey')
        raises(validators.Invalid, setattr, t, 'name2', 1)
        raises(validators.Invalid, setattr, t, 'name3', '1')
        raises(validators.Invalid, setattr, t, 'name4', '1')
        if t._connection.dbName != 'postgres' or \
                t._connection.driver not in ('odbc', 'pyodbc', 'pypyodbc'):
            raises(validators.Invalid, setattr, t, 'name6', '1')
        raises(validators.Invalid, setattr, t, 'name7', 1)
        t.name2 = 'you'
        assert t.name2 == 'you'

        for name, cls, value in (
                ('name4', SOValidationTestFloat, 1.1),
                ('name6', SOValidationTestBool, True),
                ('name8', SOValidationTestInt, 1)):
            setattr(t, name, cls(value))
            assert getattr(t, name) == value
        if PY2:
            for name, cls, value in (
                    ('name7', SOValidationTestUnicode, u'test'),):
                setattr(t, name, cls(value))
                assert getattr(t, name) == value
コード例 #23
0
def test_str_or_sqlrepr():
    select = Select(['id', 'name'],
                    staticTables=['employees'],
                    where='value>0',
                    orderBy='id')
    assert sqlrepr(select, 'sqlite') == \
        'SELECT id, name FROM employees WHERE value>0 ORDER BY id'

    select = Select(['id', 'name'],
                    staticTables=['employees'],
                    where='value>0',
                    orderBy='id',
                    lazyColumns=True)
    assert sqlrepr(select, 'sqlite') == \
        'SELECT id FROM employees WHERE value>0 ORDER BY id'

    insert = Insert('employees', values={'id': 1, 'name': 'test'})
    assert sqlrepr(insert, 'sqlite') == \
        "INSERT INTO employees (id, name) VALUES (1, 'test')"

    update = Update('employees', {'name': 'test'}, where='id=1')
    assert sqlrepr(update, 'sqlite') == \
        "UPDATE employees SET name='test' WHERE id=1"

    update = Update('employees', {'name': 'test', 'age': 42}, where='id=1')
    assert sqlrepr(update, 'sqlite') == \
        "UPDATE employees SET age=42, name='test' WHERE id=1"

    delete = Delete('employees', where='id=1')
    assert sqlrepr(delete, 'sqlite') == \
        "DELETE FROM employees WHERE id=1"

    raises(TypeError, Delete, 'employees')

    delete = Delete('employees', where=None)
    assert sqlrepr(delete, 'sqlite') == \
        "DELETE FROM employees"
コード例 #24
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()
コード例 #25
0
ファイル: test_indexes.py プロジェクト: ware111/untitled
def test_index_get_1():
    setupClass(PersonIndexGet, force=True)

    PersonIndexGet(firstName='Eric', lastName='Idle', age=62)
    PersonIndexGet(firstName='Terry', lastName='Gilliam', age=65)
    PersonIndexGet(firstName='John', lastName='Cleese', age=66)

    PersonIndexGet.get(1)
    PersonIndexGet.nameIndex.get('Terry', 'Gilliam')
    PersonIndexGet.nameIndex.get(firstName='John', lastName='Cleese')

    raises(Exception, PersonIndexGet.nameIndex.get,
           firstName='Graham', lastName='Chapman')

    raises(Exception, PersonIndexGet.nameIndex.get,
           'Terry', lastName='Gilliam')

    raises(Exception, PersonIndexGet.nameIndex.get, 'Terry', 'Gilliam', 65)

    raises(Exception, PersonIndexGet.nameIndex.get, 'Terry')
コード例 #26
0
def test_dbEncoding():
    if not PY2:
        # Python 3 mostly ignores dbEncoding
        pytest.skip("This test is for python 2")
    setup()
    SOTestUnicode.sqlmeta.dbEncoding = 'utf-8'
    _test_select()
    SOTestUnicode.sqlmeta.dbEncoding = 'latin-1'
    raises(AssertionError, _test_select)
    SOTestUnicode.sqlmeta.dbEncoding = 'ascii'
    raises(UnicodeEncodeError, _test_select)
    SOTestUnicode.sqlmeta.dbEncoding = None

    SOTestUnicode._connection.dbEncoding = 'utf-8'
    _test_select()
    SOTestUnicode._connection.dbEncoding = 'latin-1'
    raises(AssertionError, _test_select)
    SOTestUnicode._connection.dbEncoding = 'ascii'
    raises(UnicodeEncodeError, _test_select)
    del SOTestUnicode.sqlmeta.dbEncoding
    SOTestUnicode._connection.dbEncoding = 'utf-8'
コード例 #27
0
 def test_validate(self):
     t = SOValidation(name='hey')
     raises(validators.Invalid, setattr, t, 'name', '!!!')
     t.name = 'you'
     assert t.name == 'you'
コード例 #28
0
ファイル: test_basic.py プロジェクト: LutzSteinborn/sqlobject
def test_nonexisting_attr():
    setupClass(Student)
    raises(AttributeError, getattr, Student.q, 'nonexisting')
コード例 #29
0
def test_constraints():
    obj = 'Test object'
    col = Dummy(name='col')
    isString(obj, col, 'blah')
    raises(BadValue, isString, obj, col, 1)
    if PY2:
        # @@: Should this really be an error?
        raises(BadValue, isString, obj, col, u'test!')
    else:
        raises(BadValue, isString, obj, col, b'test!')
    # isString(obj, col, u'test!')

    raises(BadValue, notNull, obj, col, None)
    raises(BadValue, isInt, obj, col, 1.1)
    isInt(obj, col, 1)
    isInt(obj, col, long(1))
    isFloat(obj, col, 1)
    isFloat(obj, col, long(1))
    isFloat(obj, col, 1.2)
    raises(BadValue, isFloat, obj, col, '1.0')

    # @@: Should test isBool, but I don't think isBool is right

    lst = InList(('a', 'b', 'c'))
    lst(obj, col, 'a')
    raises(BadValue, lst, obj, col, ('a', 'b', 'c'))
    raises(BadValue, lst, obj, col, 'A')

    maxlen = MaxLength(2)
    raises(BadValue, maxlen, obj, col, '123')
    maxlen(obj, col, '12')
    maxlen(obj, col, (1, ))
    raises(BadValue, maxlen, obj, col, 1)
コード例 #30
0
ファイル: test_basic.py プロジェクト: ware111/untitled
def test_nonexisting_attr():
    setupClass(Student)
    raises(AttributeError, getattr, Student.q, 'nonexisting')
コード例 #31
0
 def test_validate(self):
     t = SOValidation(name='hey')
     raises(validators.Invalid, setattr, t, 'name', '!!!')
     t.name = 'you'
     assert t.name == 'you'